A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(app): keep back and forward inside the current account
Hampus457c649cb5a1
diff --git a/fluxer_app/src/features/app/components/layout/app_layout/nagbars/ConnectionNagbar.tsx b/fluxer_app/src/features/app/components/layout/app_layout/nagbars/ConnectionNagbar.tsxindex cd51e4b10..1969709d1 100644--- a/fluxer_app/src/features/app/components/layout/app_layout/nagbars/ConnectionNagbar.tsx+++ b/fluxer_app/src/features/app/components/layout/app_layout/nagbars/ConnectionNagbar.tsx@@ -70,7 +70,6 @@ export const ConnectionNagbar = observer(({isMobile, rememberedRows}: ConnectioncloseCurrentAccountOnSelect: true,initialReloginAccount: null,redirectAfterLogin: null,- redirectAfterSwitch: null,switchAccount: switchAccountFromStalledConnection,'data-flx': 'app.app-layout.nagbars.connection-nagbar.handle-switch-account.account-switcher-modal',},diff --git a/fluxer_app/src/features/navigation/hooks/useLastLocationPersistence.ts b/fluxer_app/src/features/navigation/hooks/useLastLocationPersistence.tsindex 56d0d8bd9..5e46482c6 100644--- a/fluxer_app/src/features/navigation/hooks/useLastLocationPersistence.ts+++ b/fluxer_app/src/features/navigation/hooks/useLastLocationPersistence.ts@@ -6,12 +6,12 @@ import Authentication from '@app/features/auth/state/Authentication';import Location from '@app/features/ui/state/Location';import {useEffect} from 'react';-export function useLastLocationPersistence(pathname: string): void {+export function useLastLocationPersistence(pathname: string | null): void {const isAuthenticated = Authentication.isAuthenticated;const currentAccountKey = Accounts.currentAccountKey;const isViewLive = Accounts.isViewLive;useEffect(() => {- if (!isAuthenticated || currentAccountKey === null || !isViewLive) {+ if (pathname === null || !isAuthenticated || currentAccountKey === null || !isViewLive) {return;}if (!Routes.isChannelRoute(pathname) && !Routes.isSpecialPage(pathname)) {diff --git a/fluxer_app/src/features/navigation/state/NavigationSideEffects.ts b/fluxer_app/src/features/navigation/state/NavigationSideEffects.tsindex e2fef7735..665e2be77 100644--- a/fluxer_app/src/features/navigation/state/NavigationSideEffects.ts+++ b/fluxer_app/src/features/navigation/state/NavigationSideEffects.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {ResettableStates} from '@app/features/app/state/ResettableStates';import Channels from '@app/features/channel/state/Channels';import Messages from '@app/features/messaging/state/MessagingMessages';import Navigation from '@app/features/navigation/state/Navigation';@@ -57,6 +58,12 @@ class NavigationSideEffects {Notification.handleChannelSelect({channelId});}+ reset(): void {+ this.lastChannelId = null;+ this.lastMessageId = null;+ this.lastThreadKey = null;+ }+handleGatewayReady(): void {const {guildId, threadId, threadMessageId} = Navigation;if (threadId == null || Channels.getChannel(threadId)) return;@@ -77,4 +84,8 @@ class NavigationSideEffects {}}-export default new NavigationSideEffects();+const navigationSideEffects = new NavigationSideEffects();++ResettableStates.register(navigationSideEffects, () => navigationSideEffects.reset());++export default navigationSideEffects;diff --git a/fluxer_app/src/features/navigation/state/SelectedChannel.ts b/fluxer_app/src/features/navigation/state/SelectedChannel.tsindex aa7432d04..1e600c813 100644--- a/fluxer_app/src/features/navigation/state/SelectedChannel.ts+++ b/fluxer_app/src/features/navigation/state/SelectedChannel.ts@@ -1,8 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {ResettableStates} from '@app/features/app/state/ResettableStates';import Channels from '@app/features/channel/state/Channels';import Favorites from '@app/features/messaging/state/Favorites';import Navigation from '@app/features/navigation/state/Navigation';+import * as RouterUtils from '@app/features/navigation/utils/RouterUtils';import {type AppStorageScopeChangeEvent,UNAUTHENTICATED_APP_STORAGE_SCOPE,@@ -103,6 +105,10 @@ class SelectedChannel {get currentChannelId(): string | null {const guildId = this.getCurrentGuildId();if (guildId == null) return null;+ const routeChannelId = Navigation.channelId;+ if (routeChannelId != null) {+ return this.isStoredChannelNavigable(routeChannelId) ? routeChannelId : null;+ }return this.selectedChannelIds.get(guildId) ?? null;}@@ -272,6 +278,16 @@ class SelectedChannel {this.removeGuildSelection(FAVORITES_GUILD_ID);return null;}++ reset(): void {+ this.viewedChannelHistory = [];+ this.viewedChannelHistoryIndex = -1;+ RouterUtils.getHistory()?.markBoundary();+ }}-export default new SelectedChannel();+const selectedChannel = new SelectedChannel();++ResettableStates.register(selectedChannel, () => selectedChannel.reset());++export default selectedChannel;diff --git a/fluxer_app/src/features/navigation/state/SelectedGuild.ts b/fluxer_app/src/features/navigation/state/SelectedGuild.tsindex a396a04de..d5ef697de 100644--- a/fluxer_app/src/features/navigation/state/SelectedGuild.ts+++ b/fluxer_app/src/features/navigation/state/SelectedGuild.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport Navigation from '@app/features/navigation/state/Navigation';+import {getAppStorageScope} from '@app/features/platform/state/PersistentStorage';import {makePersistent} from '@app/features/platform/utils/MobXPersistence';import {initializeStore} from '@app/features/platform/utils/StoreInitialization';import {ME} from '@fluxer/constants/src/AppConstants';@@ -12,6 +13,7 @@ class SelectedGuild {lastSelectedGuildId: string | null = null;selectedGuildId: string | null = null;selectionNonce: number = 0;+ private selectedGuildScope: string | null = null;private navigationDisposer: (() => void) | null = null;constructor() {@@ -61,8 +63,9 @@ class SelectedGuild {): void {const hasChanged = guildId !== this.selectedGuildId;if (hasChanged) {- this.lastSelectedGuildId = this.selectedGuildId;+ this.rememberSelectedGuild();this.selectedGuildId = guildId;+ this.selectedGuildScope = getAppStorageScope();this.bumpNonce();return;}@@ -75,11 +78,18 @@ class SelectedGuild {if (this.selectedGuildId == null) {return;}- this.lastSelectedGuildId = this.selectedGuildId;+ this.rememberSelectedGuild();this.selectedGuildId = null;+ this.selectedGuildScope = null;this.bumpNonce();}+ private rememberSelectedGuild(): void {+ if (this.selectedGuildScope === getAppStorageScope()) {+ this.lastSelectedGuildId = this.selectedGuildId;+ }+ }+private bumpNonce(): void {this.selectionNonce++;}diff --git a/fluxer_app/src/features/platform/components/router/BrowserNavigation.ts b/fluxer_app/src/features/platform/components/router/BrowserNavigation.tsindex d261d70bf..a41577837 100644--- a/fluxer_app/src/features/platform/components/router/BrowserNavigation.ts+++ b/fluxer_app/src/features/platform/components/router/BrowserNavigation.ts@@ -3,6 +3,7 @@interface BrowserNavigationEntry {id: string;url?: string;+ index?: number;}export interface BrowserNavigation {@@ -15,8 +16,12 @@ export interface BrowserNavigation {function isNavigationEntry(value: unknown): value is BrowserNavigationEntry {if (typeof value !== 'object' || value === null) return false;- const entry = value as {id?: unknown; url?: unknown};- return typeof entry.id === 'string' && (entry.url === undefined || typeof entry.url === 'string');+ const entry = value as {id?: unknown; url?: unknown; index?: unknown};+ return (+ typeof entry.id === 'string' &&+ (entry.url === undefined || typeof entry.url === 'string') &&+ (entry.index === undefined || typeof entry.index === 'number')+ );}function isBrowserNavigation(value: unknown): value is BrowserNavigation {diff --git a/fluxer_app/src/features/platform/components/router/RouterCore.ts b/fluxer_app/src/features/platform/components/router/RouterCore.tsindex 1461fdffd..3e10d7e3b 100644--- a/fluxer_app/src/features/platform/components/router/RouterCore.ts+++ b/fluxer_app/src/features/platform/components/router/RouterCore.ts@@ -18,6 +18,11 @@ import {Logger} from '@app/features/platform/utils/AppLogger';const logger = new Logger('Router');+function sameParams(a: Match['params'], b: Match['params']): boolean {+ const keys = Object.keys(a);+ return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);+}+class RouterImpl implements Router {private readonly routes: Array<Route>;private readonly routeById: Map<string, Route>;@@ -301,7 +306,8 @@ class RouterImpl implements Router {while (i < prevMatches.length &&i < nextMatches.length &&- prevMatches[i].route.id === nextMatches[i].route.id+ prevMatches[i].route.id === nextMatches[i].route.id &&+ sameParams(prevMatches[i].params, nextMatches[i].params)) {i++;}diff --git a/fluxer_app/src/features/platform/components/router/RouterHistory.ts b/fluxer_app/src/features/platform/components/router/RouterHistory.tsindex ea19ed75f..97a4ee786 100644--- a/fluxer_app/src/features/platform/components/router/RouterHistory.ts+++ b/fluxer_app/src/features/platform/components/router/RouterHistory.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {getBrowserNavigation} from '@app/features/platform/components/router/BrowserNavigation';import type {HistoryAdapter, HistoryLocation} from '@app/features/platform/components/router/RouterTypes';const TRAVERSAL_SETTLE_TIMEOUT_MS = 500;@@ -50,8 +51,45 @@ function writeAfterTraversal(write: () => void): void {write();}+function currentEntryIndex(): number | null {+ const index = getBrowserNavigation()?.currentEntry?.index;+ return typeof index === 'number' && index >= 0 ? index : null;+}+export function createBrowserHistory(): HistoryAdapter {const listeners = new Set<(location: HistoryLocation, action: 'pop') => void>();+ let backDepth = 0;+ let forwardDepth = 0;+ let ownTraversals = 0;+ let returnTraversals = 0;+ let range: {floor: number; ceiling: number} | null = null;+ const moveBy = (delta: number) => {+ backDepth = Math.max(0, backDepth + delta);+ forwardDepth = Math.max(0, forwardDepth - delta);+ };+ const returnInsideBoundary = (): boolean => {+ const index = currentEntryIndex();+ if (range === null || index === null) {+ return false;+ }+ const target = Math.min(Math.max(index, range.floor), range.ceiling);+ if (target === index) {+ return false;+ }+ beginTraversal();+ returnTraversals += 1;+ window.history.go(target - index);+ return true;+ };+ const syncDepth = (): boolean => {+ const index = currentEntryIndex();+ if (range === null || index === null) {+ return false;+ }+ backDepth = index - range.floor;+ forwardDepth = range.ceiling - index;+ return true;+ };const getLocation = (): HistoryLocation => ({url: new URL(window.location.href),state: window.history.state ?? null,@@ -60,9 +98,32 @@ export function createBrowserHistory(): HistoryAdapter {const loc = getLocation();for (const l of listeners) l(loc, 'pop');};+ window.addEventListener('popstate', () => {+ if (returnTraversals > 0) {+ returnTraversals -= 1;+ return;+ }+ if (returnInsideBoundary()) {+ return;+ }+ const own = ownTraversals > 0;+ if (own) {+ ownTraversals -= 1;+ }+ if (!syncDepth() && !own) {+ moveBy(-1);+ }+ notify();+ });const push = (url: URL, state?: unknown) => {writeAfterTraversal(() => {window.history.pushState(state ?? null, '', url);+ backDepth += 1;+ forwardDepth = 0;+ const index = currentEntryIndex();+ if (range !== null && index !== null) {+ range.ceiling = index;+ }notify();});};@@ -74,11 +135,8 @@ export function createBrowserHistory(): HistoryAdapter {};const listen = (listener: (location: HistoryLocation, action: 'pop') => void) => {listeners.add(listener);- const handler = () => listener(getLocation(), 'pop');- window.addEventListener('popstate', handler);return () => {listeners.delete(listener);- window.removeEventListener('popstate', handler);};};const go = (delta: number) => {@@ -86,54 +144,18 @@ export function createBrowserHistory(): HistoryAdapter {return;}beginTraversal();+ ownTraversals += 1;+ moveBy(delta);window.history.go(delta);};- const back = () => {- beginTraversal();- window.history.back();- };- return {- getLocation,- push,- replace,- listen,- go,- back,- get location() {- return getLocation().url;- },- };-}--export function createMemoryHistory(initialHref = 'http://localhost/'): HistoryAdapter {- const stack: Array<HistoryLocation> = [{url: new URL(initialHref), state: null}];- let index = 0;- const listeners = new Set<(location: HistoryLocation, action: 'pop') => void>();- const notify = () => {- for (const l of listeners) l(stack[index], 'pop');- };- const getLocation = (): HistoryLocation => stack[index];- const push = (url: URL, state?: unknown) => {- index++;- stack.splice(index, stack.length - index, {url, state: state ?? null});- notify();- };- const replace = (url: URL, state?: unknown) => {- stack[index] = {url, state: state ?? null};- notify();- };- const listen = (listener: (location: HistoryLocation, action: 'pop') => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- };- const go = (delta: number) => {- const newIndex = Math.max(0, Math.min(stack.length - 1, index + delta));- if (newIndex !== index) {- index = newIndex;- notify();- }- };const back = () => go(-1);+ const markBoundary = () => {+ backDepth = 0;+ forwardDepth = 0;+ const index = currentEntryIndex();+ range = index === null ? null : {floor: index, ceiling: index};+ };+ const canGo = (delta: number) => (delta < 0 ? backDepth >= -delta : forwardDepth >= delta);return {getLocation,push,@@ -141,6 +163,8 @@ export function createMemoryHistory(initialHref = 'http://localhost/'): HistoryAlisten,go,back,+ markBoundary,+ canGo,get location() {return getLocation().url;},diff --git a/fluxer_app/src/features/platform/components/router/RouterTypes.ts b/fluxer_app/src/features/platform/components/router/RouterTypes.tsindex 9a57a1e51..cca7af6be 100644--- a/fluxer_app/src/features/platform/components/router/RouterTypes.ts+++ b/fluxer_app/src/features/platform/components/router/RouterTypes.ts@@ -110,6 +110,8 @@ export interface HistoryAdapter {listen(listener: (location: HistoryLocation, action: 'pop') => void): () => void;go(delta: number): void;back(): void;+ markBoundary(): void;+ canGo(delta: number): boolean;readonly location: URL;}