Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(settings): preserve url params when opening and closing settings (#5167)
Peter Chinman36db5a0650f9
diff --git a/apps/web/src/components/app/split-layout/previewPersistence.ts b/apps/web/src/components/app/split-layout/previewPersistence.tsindex dd617663df..aece79a491 100644--- a/apps/web/src/components/app/split-layout/previewPersistence.ts+++ b/apps/web/src/components/app/split-layout/previewPersistence.ts@@ -50,6 +50,36 @@ export function serializePreviewPairs(return value || undefined;}+/**+ * Remap a preview query value for a layout whose split at `removedSplitIndex`+ * (URL pair order) is being removed. A Preview Pair whose Controller or Viewer+ * was the removed split is dropped; Controller indices past it shift down by+ * one so the remaining pairs keep pointing at the same splits. Returns the+ * serialized value, or `undefined` when no pairs survive.+ */+export function remapPreviewQueryForRemovedSplit(+ previewQuery: PreviewQueryValue,+ removedSplitIndex: number+): string | undefined {+ const remapped = parsePreviewPairs(previewQuery).flatMap(+ (previewPair): PreviewPairUrlEntry[] => {+ const viewerIndex = previewPair.controllerIndex + 1;+ if (+ previewPair.controllerIndex === removedSplitIndex ||+ viewerIndex === removedSplitIndex+ ) {+ return [];+ }+ return [+ previewPair.controllerIndex > removedSplitIndex+ ? { controllerIndex: previewPair.controllerIndex - 1 }+ : previewPair,+ ];+ }+ );+ return serializePreviewPairs(remapped);+}+function isPreviewEmpty(content: SplitContent): boolean {return content.type === 'component' && content.id === 'preview-empty';}diff --git a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.tsindex 8b98cb177c..5051d8b398 100644--- a/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutUrlSync.test.ts@@ -190,6 +190,45 @@ describe('layout URL synchronization', () => {harness.dispose();});+ it('restores a Preview Pair across a settings clobber round trip', async () => {+ const harness = createHarness({+ managerContent: [{ type: 'component', id: 'mail' }],+ urlSegments: ['component', 'mail'],+ });+ await flushUrlSync();++ // Engage preview and give the viewer real content, like opening an item.+ const controllerId = harness.manager.splits()[0].id;+ harness.manager.engagePreviewMode(controllerId);+ const viewerId = harness.manager.viewerOf(controllerId)!;+ harness.manager.getSplit(viewerId)!.replace({+ next: { type: 'md', id: 'doc-1' },+ mergeHistory: true,+ });+ await flushUrlSync();+ harness.setUrl(['component', 'mail', 'md', 'doc-1'], '0', '?preview=0');+ await flushUrlSync();++ // Open settings: clobber down to a lone settings split+ // (collapseToSoloSettings), then apply the URL the sync emitted.+ harness.manager.replaceAllSplits({ type: 'component', id: 'settings' });+ await flushUrlSync();+ harness.setUrl(['settings', 'account'], undefined, '');+ await flushUrlSync();++ // Close settings: navigate back to the captured return URL.+ harness.setUrl(['component', 'mail', 'md', 'doc-1'], '0', '?preview=0');+ await flushUrlSync();++ const [controller, viewer] = harness.manager.splits();+ expect(controller.content).toMatchObject({+ type: 'component',+ id: 'mail',+ });+ expect(viewer.content).toMatchObject({ type: 'md', id: 'doc-1' });+ expect(harness.manager.viewerOf(controller.id)).toBe(viewer.id);+ });+it('uses replace navigation and clears location state for replace-caused path changes', async () => {const harness = createHarness({managerContent: [{ type: 'component', id: 'inbox' }],diff --git a/apps/web/src/components/app/split-layout/tests/previewPersistence.test.ts b/apps/web/src/components/app/split-layout/tests/previewPersistence.test.tsindex e9425706fd..83865eda84 100644--- a/apps/web/src/components/app/split-layout/tests/previewPersistence.test.ts+++ b/apps/web/src/components/app/split-layout/tests/previewPersistence.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest';import {loadRestorablePreviewLayout,+ remapPreviewQueryForRemovedSplit,serializePreviewPairs,} from '../previewPersistence';@@ -162,3 +163,26 @@ describe('Preview Pair URL state', () => {});});});++describe('remapPreviewQueryForRemovedSplit', () => {+ it('keeps pairs before the removed split and shifts pairs after it', () => {+ expect(remapPreviewQueryForRemovedSplit('0_3', 2)).toBe('0_2');+ });++ it('shifts a pair down when an earlier split is removed', () => {+ expect(remapPreviewQueryForRemovedSplit('1', 0)).toBe('0');+ });++ it('drops a pair whose Controller was removed', () => {+ expect(remapPreviewQueryForRemovedSplit('1', 1)).toBeUndefined();+ });++ it('drops a pair whose Viewer was removed', () => {+ expect(remapPreviewQueryForRemovedSplit('1', 2)).toBeUndefined();+ });++ it('ignores absent and malformed values', () => {+ expect(remapPreviewQueryForRemovedSplit(undefined, 0)).toBeUndefined();+ expect(remapPreviewQueryForRemovedSplit('bad', 0)).toBeUndefined();+ });+});diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsxindex 151b8507ca..9a58097e34 100644--- a/apps/web/src/lib/core/constant/SettingsState.tsx+++ b/apps/web/src/lib/core/constant/SettingsState.tsx@@ -7,6 +7,10 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { activeTabId, setActiveTabId } from '@core/signal/settingsTab';import { useLocation, useNavigate } from '@solidjs/router';import { createMemo, createSignal } from 'solid-js';+import {+ appendSettingsSplitToUrl,+ stripSettingsSplitFromUrl,+} from './settingsSplitUrl';import { settingsSlugToTab, settingsTabToSlug } from './settingsTabsConfig';/**@@ -45,36 +49,19 @@ export type SettingsTab =| 'Admin';// Where "Back to app" (and move-to-split) should return to: the layout the user-// was on when they opened settings. Undefined when settings was deep-linked, in-// which case we fall back to DEFAULT_ROUTE.+// was on when they opened settings. A full base-relative URL — path plus query+// and hash — so layout state carried outside the path (notably the `preview`+// param encoding Controller/Viewer Preview Pairs) survives the round trip.+// Undefined when settings was deep-linked, in which case we fall back to+// DEFAULT_ROUTE.const [settingsReturnTo, setSettingsReturnTo] = createSignal<string>();-/**- * Drop a settings split from a split-layout path, if present. Handles both the- * URL encoding (`settings/<tab>`) and the legacy internal form- * (`component/settings`). Only type positions (even indices) are inspected so a- * block id that happens to be "settings" isn't mistaken for one.- */-const stripSettingsSplit = (pathname: string) => {- const segments = pathname.split('/').filter(Boolean);- for (let i = 0; i + 1 < segments.length; i += 2) {- const type = segments[i];- if (- type === 'settings' ||- (type === 'component' && segments[i + 1] === 'settings')- ) {- segments.splice(i, 2);- break;- }- }- return segments.length ? `/${segments.join('/')}` : DEFAULT_ROUTE;-};-/*** Extract the active settings tab from a docked-split path* (`.../settings/<slug>`), or undefined if the path has no settings split.* Scans type positions (even indices, base stripped) so a block id that happens- * to be "settings" isn't mistaken for one — mirrors {@link stripSettingsSplit}.+ * to be "settings" isn't mistaken for one — mirrors+ * {@link stripSettingsSplitFromUrl}.*/export const settingsTabFromSplitPath = (pathname: string@@ -138,9 +125,15 @@ export const useSettingsState = () => {// Capture the current layout (minus any settings split) as where "Back to// app"/"Move to split" should return to, then clobber every other split so// settings becomes the sole one. Shared by opening settings fresh and by- // collapsing a docked-alongside layout back down to solo.+ // collapsing a docked-alongside layout back down to solo. The query and hash+ // are captured too: the `preview` param is what links Controller/Viewer+ // Preview Pairs, so returning to the path alone would sever them.const collapseToSoloSettings = (tab: SettingsTab) => {- setSettingsReturnTo(stripSettingsSplit(toBaseRelative(location.pathname)));+ setSettingsReturnTo(+ stripSettingsSplitFromUrl(+ `${toBaseRelative(location.pathname)}${location.search}${location.hash}`+ )+ );setActiveTabId(tab);replaceAllSplits({ type: 'component', id: 'settings' });};@@ -216,10 +209,15 @@ export const useSettingsState = () => {// Strip any settings split already in the target layout before re-adding// one, so repeatedly toggling fullscreen ⇄ split reuses a single settings// split (on the current tab) instead of stacking a new one each cycle.- const base = stripSettingsSplit(+ // The return layout's query/hash ride along — appending settings at the+ // end keeps `preview` indices valid — so its Preview Pairs re-link when+ // the URL sync rebuilds the layout.+ const returnTo = stripSettingsSplitFromUrl(settingsReturnTo() ?? DEFAULT_ROUTE- ).replace(/\/$/, '');- navigate(`${base}/settings/${settingsTabToSlug(activeTabId())}`);+ );+ navigate(+ appendSettingsSplitToUrl(returnTo, settingsTabToSlug(activeTabId()))+ );};// Collapse a docked-alongside layout back down to a lone settings split.diff --git a/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts b/apps/web/src/lib/core/constant/settingsSplitUrl.test.tsnew file mode 100644index 0000000000..f33377128d--- /dev/null+++ b/apps/web/src/lib/core/constant/settingsSplitUrl.test.ts@@ -0,0 +1,83 @@+import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';+import { describe, expect, it, vi } from 'vitest';+import {+ appendSettingsSplitToUrl,+ stripSettingsSplitFromUrl,+} from './settingsSplitUrl';++// The preview-persistence import chain reaches the block registry, whose+// eager definition glob drags in every block feature; the URL helpers only+// need alias resolution to exist.+vi.mock('@core/constant/allBlocks', () => ({+ isBlockAlias: vi.fn(() => false),+ resolveBlockAlias: vi.fn((type: string) => type),+}));++describe('stripSettingsSplitFromUrl', () => {+ it('returns a URL without a settings split unchanged', () => {+ expect(+ stripSettingsSplitFromUrl('/component/mail/email/e-1?preview=0#sel')+ ).toBe('/component/mail/email/e-1?preview=0#sel');+ });++ it('strips a trailing settings split, preserving query and hash', () => {+ expect(+ stripSettingsSplitFromUrl(+ '/component/mail/email/e-1/settings/account?preview=0#sel'+ )+ ).toBe('/component/mail/email/e-1?preview=0#sel');+ });++ it('remaps Preview Pair indices past a stripped settings split', () => {+ expect(+ stripSettingsSplitFromUrl(+ '/settings/account/component/mail/md/doc-1?preview=1'+ )+ ).toBe('/component/mail/md/doc-1?preview=0');+ });++ it('drops a Preview Pair that referenced the settings split', () => {+ expect(+ stripSettingsSplitFromUrl('/component/mail/settings/account?preview=0')+ ).toBe('/component/mail');+ });++ it('keeps unrelated query params while remapping the preview param', () => {+ expect(+ stripSettingsSplitFromUrl(+ '/settings/account/component/mail/md/doc-1?keep=value&preview=1'+ )+ ).toBe('/component/mail/md/doc-1?keep=value&preview=0');+ });++ it('strips the legacy component/settings form', () => {+ expect(+ stripSettingsSplitFromUrl('/component/inbox/component/settings')+ ).toBe('/component/inbox');+ });++ it('does not mistake a block id named settings for a settings split', () => {+ expect(stripSettingsSplitFromUrl('/md/settings')).toBe('/md/settings');+ });++ it('falls back to the default route when settings was the only split', () => {+ expect(stripSettingsSplitFromUrl('/settings/account')).toBe(DEFAULT_ROUTE);+ });+});++describe('appendSettingsSplitToUrl', () => {+ it('appends the settings split before the query and hash', () => {+ expect(+ appendSettingsSplitToUrl(+ '/component/mail/email/e-1?preview=0#sel',+ 'account'+ )+ ).toBe('/component/mail/email/e-1/settings/account?preview=0#sel');+ });++ it('handles a trailing slash on the base path', () => {+ expect(appendSettingsSplitToUrl('/component/inbox/', 'account')).toBe(+ '/component/inbox/settings/account'+ );+ });+});diff --git a/apps/web/src/lib/core/constant/settingsSplitUrl.ts b/apps/web/src/lib/core/constant/settingsSplitUrl.tsnew file mode 100644index 0000000000..6b74218598--- /dev/null+++ b/apps/web/src/lib/core/constant/settingsSplitUrl.ts@@ -0,0 +1,80 @@+import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';+import {+ PREVIEW_QUERY_PARAM,+ remapPreviewQueryForRemovedSplit,+} from '@components/app/split-layout/previewPersistence';++/**+ * Parse a base-relative app URL. The base only anchors parsing — inputs come+ * from the router's `location`, which is already URL-canonical — and only the+ * pathname/query/hash are ever read back out.+ */+const parseUrl = (url: string) => new URL(url, 'http://localhost');++/** Serialize a parsed URL back to its base-relative string form. */+const toRelativeUrl = (url: URL) => `${url.pathname}${url.search}${url.hash}`;++/**+ * Drop a settings split from a base-relative split-layout URL, if present.+ * Handles both the URL encoding (`settings/<tab>`) and the legacy internal+ * form (`component/settings`). Only type positions (even indices) are+ * inspected so a block id that happens to be "settings" isn't mistaken for+ * one.+ *+ * The query string and hash are preserved. Removing a split shifts the URL+ * pair indices after it, so Preview Pairs declared in the `preview` query+ * param are remapped to keep pointing at the same splits (a pair that+ * referenced the settings split itself is dropped). When settings was the+ * only split there is no layout left to return to, so the default route is+ * returned bare.+ */+export const stripSettingsSplitFromUrl = (urlString: string): string => {+ const url = parseUrl(urlString);+ const segments = url.pathname.split('/').filter(Boolean);++ let removedSplitIndex: number | undefined;+ for (let i = 0; i + 1 < segments.length; i += 2) {+ const type = segments[i];+ if (+ type === 'settings' ||+ (type === 'component' && segments[i + 1] === 'settings')+ ) {+ removedSplitIndex = i / 2;+ segments.splice(i, 2);+ break;+ }+ }++ if (segments.length === 0) return DEFAULT_ROUTE;++ if (removedSplitIndex !== undefined) {+ const remappedPreview = remapPreviewQueryForRemovedSplit(+ url.searchParams.get(PREVIEW_QUERY_PARAM) ?? undefined,+ removedSplitIndex+ );+ if (remappedPreview === undefined) {+ url.searchParams.delete(PREVIEW_QUERY_PARAM);+ } else {+ url.searchParams.set(PREVIEW_QUERY_PARAM, remappedPreview);+ }+ }++ url.pathname = `/${segments.join('/')}`;+ return toRelativeUrl(url);+};++/**+ * Append a docked settings split (`settings/<slug>`) to a base-relative+ * split-layout URL, keeping its query string and hash. Appending at the end+ * leaves existing URL pair indices untouched, so Preview Pairs in the+ * `preview` query param stay valid as-is.+ */+export const appendSettingsSplitToUrl = (+ urlString: string,+ settingsTabSlug: string+): string => {+ const url = parseUrl(urlString);+ const base = url.pathname.replace(/\/$/, '');+ url.pathname = `${base}/settings/${settingsTabSlug}`;+ return toRelativeUrl(url);+};