mattermost-mobile-upstream/app/store/navigation_store.test.ts
yasser khan 3acf3bec7a
fix: app bugs surfaced by Detox RF migration (#9789)
* app fixes surfaced by detox RF migration

Carve the app-side bug fixes from the migrate_RF_to_detox branch into
their own PR. Includes:

- NavigationStore.waitUntilScreenIsTop helper + matching switchToChannel /
  notification.test wiring (Screens.CHANNEL_LIST -> Screens.HOME)
- Detox source build + null-guard patch for Android FabricUIManagerIdlingResources
  (android/settings.gradle, android/app/build.gradle, gradle.properties)
- iOS Podfile: Alamofire 5.10 duplicate-allHeaders patch + stdlib embed for extensions
- iOS Server screen: defer push-proxy verification alert past Navigation.push to
  fix iOS 26 race
- Android NetworkClient: null-guard host extraction to prevent NPE on bad cert reports
- ephemeral_store: track recently-unsaved saved posts with 2-min TTL
- post_draft: filter undefined channel observable to prevent archived-banner flicker
- queries/servers/thread: is_following nullish-coalesce to false
- datetime: NaN guard for invalid scheduled-message timestamp (MM-T5720)
- navigation: dismissBottomSheet handles GENERIC_BOTTOM_SHEET fallback
- bottom_sheet: accessibilityViewIsModal for VoiceOver
- calls websocket_client: extend interface for optional sendBinary
- edit_profile: wrap Save Pressable in View to constrain Detox tap bounds (MM-T4989_2/MM-T3250)
- invite/summary: fix retry testID hardcoded to use the dynamic type
- channel_bookmark/bookmark_link: URL resolution timeout + setBookmarkLinkUrl
- categories_list/load_channel_error: missing return statement for error UI
- iOS MattermostShare: TestID-friendly testIDs on Swift share-extension views
- patches/react-native-network-client: Android host null-guard patch
- scripts/build.sh: copy compass-icons.ttf manually when --ignore-scripts is used
- types/modules: WebSocketClientInterface sendBinary extension

Matched detox specs that exercise these bugs land in the rf-split/detox-tests PR.

* address CodeRabbit review on PR #9789

- post_list/index.ts, thread_options/index.ts: track serverUrl in withObservables dependency keys
- post/body/index.tsx: restore React.memo(Body) to avoid per-item re-render regression
- thread.tsx, edit_profile.tsx: add pressed feedback via style callback; move inline typography to stylesheet
- bookmark_link.tsx: include queueFetch in useDidUpdate deps
- ephemeral_store.ts: complete and delete per-post recently-unsaved subjects on expiry/clear to bound growth

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: fix stale mocks and add coverage for recently-unsaved saved posts

Update thread/preference tests for the new NavigationStore and
prepareDestroyPermanently call paths, and add unit tests for the
EphemeralStore recently-unsaved saved-post logic plus the websocket
filterStaleSavedPostPreferences path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: tighten recently-unsaved saved post assertions

Address CodeRabbit nitpicks on #9789:
- preference.test.ts: assert addRecentlyUnsavedSavedPost is called once
  with (serverUrl, postId) so the echoed websocket re-save is filtered.
- ephemeral_store.test.ts: assert the observed Set size (2 after two adds,
  1 after clearing one) so we catch stray/missing entries.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: explain pinned posts descending sort order

The asc->desc change to queryPinnedPostsInChannel surfaced during the
detox RF migration was correct but undocumented. selectOrderedPosts
(reached via observePinnedPostsInChannel) iterates the posts array from
the end backwards expecting oldest->newest, so it requires descending
(newest-first) input, matching queryPostsInChannel. Add a comment so the
sort order isn't questioned in review.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: cover thread/config/bottom-sheet edge cases flagged in review

Add unit tests for coverage gaps identified by CodeRabbit on #9789:
- createThreadFromNewPost: reply where the thread is missing but the root
  post exists (back-fills + auto-follows), and where neither exists (only
  records the participant, no crash)
- processReceivedThreads: thread entry with no post/participants is skipped
  without crashing
- markThreadAsUnread: unread_replies/unread_mentions from the API response
  are persisted to the local thread
- getConfigBooleanValue: 'true' -> true, non-'true' -> false, missing key
  honors the default
- dismissBottomSheet: falls back to GENERIC_BOTTOM_SHEET when only the
  generic variant is in the stack

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(thread_options): use withServerUrl HOC

Replace the hand-rolled `ThreadOptionsWithServerUrl` wrapper (which
called `useServerUrl()` inside a function component and re-created
the element via `React.createElement`) with the existing
`withServerUrl` HOC from `@context/server`.

Composition chain becomes:
  withDatabase(withServerUrl(enhanced(ThreadOptions)))

Addresses larkox's review on app/screens/thread_options/index.ts:41:
"This is not needed. You should be able to use `withServerUrl` function."

Also tightens the Props type — `serverUrl` is now required (the HOC
guarantees it), not optional.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore(deps): bump react-native-network-client to 1.10.2; drop workarounds

1.10.2 upstreams both fixes that were being carried locally:

- iOS: apply_patches.rb is now idempotent
  (mattermost/react-native-network-client#167), so its bundled Alamofire
  diff can no longer double-apply. Removes the need for the Podfile
  post_install workaround that stripped the duplicate `let allHeaders`
  (Swift 6 / Xcode 26 "invalid redeclaration"). Workaround deleted.

- Android: the cert-error host null-fallback in NetworkClient.kt is now
  upstream (and improved — prefers HttpUrl host, then URI, then
  baseUrlString; references #9789). The patch-package patch
  (@mattermost+react-native-network-client+1.10.0.patch) is therefore
  obsolete and deleted. It was also a silent no-op here anyway — named
  1.10.0 while 1.10.1 was installed, so patch-package skipped it.

Addresses @enahum's review on #9789: the fix belongs in network-client,
not patched downstream — and it now is.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore(ios): update Podfile.lock for rnnc 1.10.2

Run `pod install` to sync Podfile.lock with the dependency bump in the
previous commit:
- react-native-network-client 1.10.1 → 1.10.2
- its pod checksum recomputed
- PODFILE CHECKSUM recomputed (the Podfile changed — Alamofire
  duplicate-allHeaders workaround removed)

The previous commit bumped package.json + ran npm install but did not
regenerate Podfile.lock, so the iOS lockfile-consistency check would have
failed (caught in review by @enahum).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* refactor(thread): use shared NavigationButton for header back

Addresses @larkox's review on #9789: the thread route hand-rolled its
header back button with a raw Pressable + CompassIcon + local StyleSheet,
which is inconsistent with the rest of the app.

Switch to the shared NavigationButton component — the same pattern used by
app/screens/code/index.tsx, custom_status_clear_after, channel_bookmark, and
the getModalHeaderOptions/getLoginModalHeaderOptions helpers
(navigation.setOptions → NavigationButton with iconName/iconSize/color/
onPress/testID).

Behavior is unchanged (still navigation.goBack() via handleBack) and the
testID 'thread.navigation.back.button' is preserved for Detox. Net effect in
the app: Android now gets the standard header ripple, a larger hitSlop touch
target, and the arrow aligns like other NavigationButton headers. Removes the
local styles, Pressable, StyleSheet, and CompassIcon imports.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 13:25:42 +05:30

389 lines
14 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Screens} from '@constants';
import {NavigationStore} from './navigation_store';
import type {NavigationState as ExpoNavigationState} from '@react-navigation/native';
// Helper function to create a navigation state
function createNavigationState(routes: Array<{key: string; name: string; state?: ExpoNavigationState}>): ExpoNavigationState {
return {
stale: false,
type: 'stack',
key: 'root',
index: routes.length - 1,
routeNames: routes.map((r) => r.name),
routes,
};
}
// Helper function to create a tab navigation state
function createTabNavigationState(routes: Array<{key: string; name: string; state?: ExpoNavigationState}>, activeIndex: number): ExpoNavigationState {
return {
stale: false,
type: 'tab',
key: 'tabs',
index: activeIndex,
routeNames: routes.map((r) => r.name),
routes,
};
}
describe('NavigationStore', () => {
beforeEach(() => {
NavigationStore.reset();
});
describe('updateFromNavigationState', () => {
it('should extract screen IDs from navigation state', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: 'thread-2', name: 'thread'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getScreensInStack()).toEqual(['channel', 'thread']);
expect(NavigationStore.getVisibleScreen()).toBe('thread');
});
it('should handle nested navigation states', () => {
const navState = createNavigationState([
{
key: 'channel-1',
name: 'channel',
state: createNavigationState([
{key: 'post_options-3', name: 'post_options'},
]),
},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getScreensInStack()).toEqual(['channel', 'post_options']);
expect(NavigationStore.getVisibleScreen()).toBe('post_options');
});
it('should handle tab navigator correctly', () => {
const navState = createTabNavigationState([
{key: 'home-1', name: 'home'},
{key: 'account-2', name: 'account'},
{key: 'search-3', name: 'search'},
], 1);
NavigationStore.updateFromNavigationState(navState);
// Tab navigator should only include the active tab
expect(NavigationStore.getScreensInStack()).toEqual(['account']);
expect(NavigationStore.getVisibleScreen()).toBe('account');
});
it('should handle group route names', () => {
const navState = createNavigationState([
{key: '(modals)/edit_profile-1', name: 'edit_profile'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getScreensInStack()).toEqual(['edit_profile']);
});
it('should handle index routes', () => {
const navState = createNavigationState([
{key: '(channel_info)/index-1', name: 'index'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getScreensInStack()).toEqual(['(channel_info)']);
});
it('should not update if navigation state is unchanged', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
const firstStack = NavigationStore.getScreensInStack();
NavigationStore.updateFromNavigationState(navState);
const secondStack = NavigationStore.getScreensInStack();
expect(secondStack).toEqual(firstStack);
});
});
describe('getVisibleScreen', () => {
it('should return the last screen in the stack', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: 'thread-2', name: 'thread'},
{key: 'post_options-3', name: 'post_options'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getVisibleScreen()).toBe('post_options');
});
it('should return undefined for empty stack', () => {
expect(NavigationStore.getVisibleScreen()).toBeUndefined();
});
});
describe('getScreensInStack', () => {
it('should return all screens in order', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: 'thread-2', name: 'thread'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.getScreensInStack()).toEqual(['channel', 'thread']);
});
it('should return empty array initially', () => {
expect(NavigationStore.getScreensInStack()).toEqual([]);
});
});
describe('isScreenInStack', () => {
it('should return true if screen is in stack', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: 'thread-2', name: 'thread'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.isScreenInStack('channel')).toBe(true);
expect(NavigationStore.isScreenInStack('thread')).toBe(true);
});
it('should return false if screen is not in stack', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.isScreenInStack('thread')).toBe(false);
});
});
describe('isModalOpen', () => {
it('should return true when modals group is in stack', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: '(modals)-2', name: '(modals)'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.isModalOpen()).toBe(true);
});
it('should return false when no modals are open', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(NavigationStore.isModalOpen()).toBe(false);
});
});
describe('reset', () => {
it('should clear all state', () => {
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
NavigationStore.setToSOpen(true);
expect(NavigationStore.getScreensInStack()).toEqual(['channel']);
expect(NavigationStore.isToSOpen()).toBe(true);
NavigationStore.reset();
expect(NavigationStore.getScreensInStack()).toEqual([]);
expect(NavigationStore.getVisibleScreen()).toBeUndefined();
expect(NavigationStore.isToSOpen()).toBe(false);
});
});
describe('ToS management', () => {
it('should manage ToS state correctly', () => {
// ToS state is reset in beforeEach via NavigationStore.reset()
expect(NavigationStore.isToSOpen()).toBe(false);
NavigationStore.setToSOpen(true);
expect(NavigationStore.isToSOpen()).toBe(true);
NavigationStore.setToSOpen(false);
expect(NavigationStore.isToSOpen()).toBe(false);
});
});
describe('observables', () => {
it('should notify subscribers of screen changes via state$', () => {
const mockNext = jest.fn();
const subscription = NavigationStore.state$.subscribe(mockNext);
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
expect(mockNext).toHaveBeenCalledWith({
screenStack: ['channel'],
});
subscription.unsubscribe();
});
it('should notify subscribers of current screen changes via currentScreen$', () => {
const mockNext = jest.fn();
const subscription = NavigationStore.currentScreen$.subscribe(mockNext);
const navState1 = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState1);
const navState2 = createNavigationState([
{key: 'channel-1', name: 'channel'},
{key: 'thread-2', name: 'thread'},
]);
NavigationStore.updateFromNavigationState(navState2);
expect(mockNext).toHaveBeenCalledWith('channel');
expect(mockNext).toHaveBeenCalledWith('thread');
subscription.unsubscribe();
});
it('should not notify currentScreen$ if visible screen did not change', () => {
const mockNext = jest.fn();
const subscription = NavigationStore.currentScreen$.subscribe(mockNext);
const navState = createNavigationState([
{key: 'channel-1', name: 'channel'},
]);
NavigationStore.updateFromNavigationState(navState);
NavigationStore.updateFromNavigationState(navState);
// BehaviorSubject emits initial value (undefined) + new value (channel) = 2 calls
// But should not emit again on second update since screen didn't change
expect(mockNext).toHaveBeenCalledTimes(2);
expect(mockNext).toHaveBeenNthCalledWith(1, undefined);
expect(mockNext).toHaveBeenNthCalledWith(2, 'channel');
subscription.unsubscribe();
});
});
describe('async wait utilities', () => {
beforeEach(() => {
jest.useFakeTimers({doNotFake: ['nextTick', 'setImmediate']});
});
afterEach(() => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
it('should resolve waitUntilScreenHasLoaded when screen is added', async () => {
const promise = NavigationStore.waitUntilScreenHasLoaded(Screens.ABOUT);
const navState = createNavigationState([
{key: `${Screens.ABOUT}-1`, name: Screens.ABOUT},
]);
NavigationStore.updateFromNavigationState(navState);
await promise;
expect(NavigationStore.isScreenInStack(Screens.ABOUT)).toBe(true);
});
it('should resolve immediately if screen is already in stack', async () => {
const navState = createNavigationState([
{key: `${Screens.ABOUT}-1`, name: Screens.ABOUT},
]);
NavigationStore.updateFromNavigationState(navState);
await NavigationStore.waitUntilScreenHasLoaded(Screens.ABOUT);
expect(NavigationStore.isScreenInStack(Screens.ABOUT)).toBe(true);
});
it('should resolve waitUntilScreenIsTop when screen becomes visible', async () => {
const navState1 = createNavigationState([
{key: `${Screens.CHANNEL}-1`, name: Screens.CHANNEL},
]);
NavigationStore.updateFromNavigationState(navState1);
const promise = NavigationStore.waitUntilScreenIsTop(Screens.ABOUT);
const navState2 = createNavigationState([
{key: `${Screens.CHANNEL}-1`, name: Screens.CHANNEL},
{key: `${Screens.ABOUT}-2`, name: Screens.ABOUT},
]);
NavigationStore.updateFromNavigationState(navState2);
await promise;
expect(NavigationStore.getVisibleScreen()).toBe(Screens.ABOUT);
});
it('should resolve immediately if screen is already top', async () => {
const navState = createNavigationState([
{key: `${Screens.ABOUT}-1`, name: Screens.ABOUT},
]);
NavigationStore.updateFromNavigationState(navState);
await NavigationStore.waitUntilScreenIsTop(Screens.ABOUT);
expect(NavigationStore.getVisibleScreen()).toBe(Screens.ABOUT);
});
it('should resolve waitUntilScreensIsRemoved when screen is removed', async () => {
const navState1 = createNavigationState([
{key: `${Screens.ABOUT}-1`, name: Screens.ABOUT},
]);
NavigationStore.updateFromNavigationState(navState1);
const promise = NavigationStore.waitUntilScreensIsRemoved(Screens.ABOUT);
const navState2 = createNavigationState([
{key: `${Screens.CHANNEL}-1`, name: Screens.CHANNEL},
]);
NavigationStore.updateFromNavigationState(navState2);
await promise;
expect(NavigationStore.isScreenInStack(Screens.ABOUT)).toBe(false);
});
it('should resolve immediately if screen is not in stack', async () => {
await NavigationStore.waitUntilScreensIsRemoved(Screens.ABOUT);
expect(NavigationStore.isScreenInStack(Screens.ABOUT)).toBe(false);
});
it('should timeout after 30 seconds', async () => {
const promise = NavigationStore.waitUntilScreenHasLoaded(Screens.ABOUT);
// Fast-forward 30 seconds to trigger setTimeout callback
jest.advanceTimersByTime(30000);
// Wait for the promise to resolve
await promise;
// Should resolve even though screen was never added
expect(NavigationStore.isScreenInStack(Screens.ABOUT)).toBe(false);
});
});
});