Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(web): Run the app on the next split router (#7431)

dev-rb43474d4fb108
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 52d902e791..fd174c9ce1 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -1,93 +1,41 @@
-import {
- createRoutesManifest,
- createSolidRouterLocation,
- decodeRouteLayout,
- SplitRouter,
- type SplitRouterMiddleware,
- type SplitRoutes,
- type SplitRoutesManifest,
- useSplitRouter,
-} from '@app/lib/split-router';
+import { setGlobalSplitManager } from '@app/signal/splitLayout';
+import { useSplitRouter } from '@app/split-router';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { Resize } from '@core/component/Resize';
-import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { tabTitleSignal } from '@core/signal/tabTitle';
-import { useLocation, useNavigate } from '@solidjs/router';
import {
createEffect,
createMemo,
createSelector,
For,
onCleanup,
- type Setter,
Show,
Suspense,
} from 'solid-js';
import { PopoverSplitRenderer } from './components/PopoverSplitRenderer';
import { SplitPanel } from './components/SplitPanel';
import { SplitLayoutContext } from './context';
+import { createSplitLayout, type SplitId } from './layoutManager';
import {
- createSplitLayout,
- type SplitId,
- type SplitManager,
-} from './layoutManager';
-import {
- createMobileSwipeLayout,
- type MobileSwipeLayout,
-} from './mobile/createMobileSwipeLayout';
-import { MobileSplitContainer } from './mobile/MobileSplitContainer';
-import { createContentNavigator } from './split-router/content-navigation';
-import { splitContentFromLocation } from './split-router/legacy-route';
+ resolveContentLocation,
+ splitContentFromLocation,
+} from './split-router/legacy-route';
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
import { createSplitFocusTracker } from './splitFocusTracker';
-import { createAppSplitRouterLayout } from './splitRouterLayout';
-
-type SplitLayoutContainerProps = {
- pairs: string[];
- routes: SplitRoutes;
- middleware?: readonly SplitRouterMiddleware[];
- setManager: Setter<SplitManager | undefined>;
-};
-function ContentNavigationBinding(props: {
- manager: SplitManager;
- routes: SplitRoutesManifest;
-}) {
- const router = useSplitRouter<SplitId>();
- props.manager.setContentNavigator(
- createContentNavigator(props.manager, router, props.routes)
- );
- onCleanup(() => props.manager.setContentNavigator(undefined));
- return null;
-}
-
-export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
- const location = useLocation();
- const navigate = useNavigate();
- // Bootstrap the legacy layout with the same local state adopted by the router.
- const routes = createRoutesManifest(props.routes);
- const initialContents = decodeRouteLayout(routes, props.pairs).map((entry) =>
- splitContentFromLocation(entry.location)
- );
+/** The app route's view: the split manager, and one panel per pane. */
+export function SplitLayout() {
+ const router = useSplitRouter();
const blockOrchestrator = useGlobalBlockOrchestrator();
- const splitManager = createSplitLayout(blockOrchestrator, initialContents);
- const routerLayout = createAppSplitRouterLayout(splitManager, routes);
- const externalLocation = createSolidRouterLocation({
- pathname: () => `/${props.pairs.join('/')}`,
- search: () => location.search,
- hash: () => location.hash,
- state: () => location.state,
- navigate,
+
+ const splitManager = createSplitLayout(blockOrchestrator, {
+ router,
+ toLocation: (content) => resolveContentLocation(router.routes, content),
+ toContent: splitContentFromLocation,
});
const [, setTabTitle] = tabTitleSignal;
- // Create the mobile swipe layout once on mobile devices.
- const mobileSwipeLayout: MobileSwipeLayout | undefined =
- isNativeMobilePlatform()
- ? createMobileSwipeLayout(splitManager)
- : undefined;
-
// Store a ref to each panel by id
const panelRefs = new Map<SplitId, HTMLDivElement>();
@@ -114,78 +62,51 @@ export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
const ids = createMemo(() => splits().map(({ id }) => id));
createSplitFocusTracker({ splitManager, panelRefs, splits });
- createEffect(() => props.setManager(splitManager));
- onCleanup(() => props.setManager(undefined));
+ createEffect(() => setGlobalSplitManager(splitManager));
+ onCleanup(() => setGlobalSplitManager(undefined));
return (
- <SplitRouter.Root
- layout={routerLayout}
- routes={routes}
- location={externalLocation}
- middleware={props.middleware}
- >
- <SplitLayoutContext.Provider value={{ manager: splitManager }}>
- <ContentNavigationBinding manager={splitManager} routes={routes} />
- <div
- class="size-full"
- classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}
+ <SplitLayoutContext.Provider value={{ manager: splitManager }}>
+ <div class="size-full" classList={{ 'py-1.5 pr-1.5': useBentoLayout() }}>
+ <Resize.Zone
+ direction="horizontal"
+ gutter={useBentoLayout() ? 6 : 1}
+ showDividers={!useBentoLayout()}
+ captureResizeCtx={splitManager.setResizeContext}
>
- <Show
- when={isNativeMobilePlatform() && mobileSwipeLayout}
- fallback={
- // Desktop: side-by-side resizable splits.
- <Resize.Zone
- direction="horizontal"
- gutter={useBentoLayout() ? 6 : 1}
- showDividers={!useBentoLayout()}
- captureResizeCtx={splitManager.setResizeContext}
- >
- <For each={ids()}>
- {(id, index) => (
- <Show when={splitManager.getSplit(id)}>
- {(handle) => (
- <Suspense>
- <Resize.Panel
- id={id}
- minSize={DEFAULT_SPLIT_MIN_WIDTH}
- index={index()}
- >
- <SplitPanel
- split={splits()[index()]!}
- handle={handle()}
- active={activeSplitSelector(id)}
- setPanelRef={(panelRef) =>
- panelRefs.set(id, panelRef)
- }
- index={index()}
- />
- </Resize.Panel>
- </Suspense>
- )}
- </Show>
- )}
- </For>
- </Resize.Zone>
- }
- >
- {/* Mobile: stacked FG/BG layout with swipe-back gesture. */}
- <MobileSplitContainer
- splitManager={splitManager}
- mobileSwipeLayout={mobileSwipeLayout!}
- splits={splits}
- panelRefs={panelRefs}
- />
- </Show>
- </div>
- <PopoverSplitRenderer
- popovers={splitManager.popovers}
- onClosePopover={(id) => {
- const activePopovers = splitManager.getActivePopovers();
- const popover = activePopovers.find((p) => p.id === id);
- popover?.close();
- }}
- />
- </SplitLayoutContext.Provider>
- </SplitRouter.Root>
+ <For each={ids()}>
+ {(id, index) => (
+ <Show when={splitManager.getSplit(id)}>
+ {(handle) => (
+ <Suspense>
+ <Resize.Panel
+ id={id}
+ minSize={DEFAULT_SPLIT_MIN_WIDTH}
+ index={index()}
+ >
+ <SplitPanel
+ split={splits()[index()]!}
+ handle={handle()}
+ active={activeSplitSelector(id)}
+ setPanelRef={(panelRef) => panelRefs.set(id, panelRef)}
+ index={index()}
+ />
+ </Resize.Panel>
+ </Suspense>
+ )}
+ </Show>
+ )}
+ </For>
+ </Resize.Zone>
+ </div>
+ <PopoverSplitRenderer
+ popovers={splitManager.popovers}
+ onClosePopover={(id) => {
+ const activePopovers = splitManager.getActivePopovers();
+ const popover = activePopovers.find((p) => p.id === id);
+ popover?.close();
+ }}
+ />
+ </SplitLayoutContext.Provider>
);
}
diff --git a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx b/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
deleted file mode 100644
index 20dd7743be..0000000000
--- a/apps/web/src/components/app/split-layout/SplitLayoutRoute.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { setGlobalSplitManager } from '@app/signal/splitLayout';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import type { WithRequired } from '@core/util/withRequired';
-import type { RouteDefinition, RouteSectionProps } from '@solidjs/router';
-import { SplitLayoutContainer } from './SplitLayout';
-import { createAppSplitRouterMiddleware } from './split-router/app-middleware';
-import { appSplitRoutes } from './split-router/app-routes';
-
-function LayoutRoute(props: RouteSectionProps) {
- const middleware = createAppSplitRouterMiddleware({ isTouchDevice });
-
- return (
- <SplitLayoutContainer
- pairs={props.params.splits?.split('/') ?? []}
- routes={appSplitRoutes}
- middleware={middleware}
- setManager={setGlobalSplitManager}
- />
- );
-}
-
-export const LAYOUT_ROUTE: WithRequired<RouteDefinition, 'component'> = {
- path: '/*splits',
- component: LayoutRoute,
-};
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index eb82d042ef..009b2c0041 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -1,23 +1,23 @@
-import { ActivityRouteView } from '@app/features/activity/route';
+import { ActivityRouteView } from '@app/features/activity/route-views';
import { parseAgentsRoute } from '@app/features/agents-view/core/route';
-import { AgentsRouteView } from '@app/features/agents-view/route';
+import { AgentsRouteView } from '@app/features/agents-view/route-views';
import { useSpreadsheetAccess } from '@app/features/block-spreadsheet/primitives/use-spreadsheet-access';
import type { EventEditorInitialValues } from '@app/features/calendar/components/composer/event-form-model';
import type { CalendarEvent } from '@app/features/calendar/types';
-import { CalendarRouteView } from '@app/features/calendar-view/route';
-import { ChannelsRouteView } from '@app/features/channels-view/route';
-import { CompaniesRouteView } from '@app/features/crm/route';
-import { DriveRouteView } from '@app/features/drive-view/route';
+import { CalendarRouteView } from '@app/features/calendar-view/route-views';
+import { ChannelsRouteView } from '@app/features/channels-view/route-views';
+import { CompaniesRouteView } from '@app/features/crm/route-views';
+import { DriveRouteView } from '@app/features/drive-view/route-views';
import { EmailCompose } from '@app/features/email-compose/email-compose';
-import { MailRouteView } from '@app/features/email-view/route';
-import { GettingStartedRouteView } from '@app/features/getting-started/route';
-import { HomeRouteView } from '@app/features/home/route';
+import { MailRouteView } from '@app/features/email-view/route-views';
+import { GettingStartedRouteView } from '@app/features/getting-started/route-views';
+import { HomeRouteView } from '@app/features/home/route-views';
import {
CallsRouteView,
FoldersRouteView,
RecentRouteView,
SearchRouteView,
-} from '@app/features/next-soup/route';
+} from '@app/features/next-soup/route-views';
import { parseProjectRoute } from '@app/features/projects/core/route';
import {
CreateProjectView,
@@ -26,15 +26,17 @@ import {
} from '@app/features/projects/project-view';
import { ReminderEditorSplit } from '@app/features/reminders/ReminderEditorSplit';
import { REMINDER_DETAIL_COMPONENT_ID } from '@app/features/reminders/reminder-navigation';
-import { RemindersRouteView } from '@app/features/reminders/route';
-import { ReviewsRouteView } from '@app/features/reviews-view/route';
-import { SettingsRouteView } from '@app/features/settings/route';
-import { TasksRouteView } from '@app/features/tasks-view/route';
+import { RemindersRouteView } from '@app/features/reminders/route-views';
+import { ReviewsRouteView } from '@app/features/reviews-view/route-views';
+import { SettingsRouteView } from '@app/features/settings/route-views';
+import { TasksRouteView } from '@app/features/tasks-view/route-views';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { NOT_FOUND_ROUTE_ID } from '@app/routes/app-route';
import { EventComposerSplit } from '@block-calendar/components/EventComposerSplit';
import { ChannelCompose } from '@block-channel/component/Compose';
import { ComposeSkill } from '@block-md/component/ComposeSkill';
import { ComposeTask } from '@block-md/component/ComposeTask';
+import NotFound from '@core/component/AccessErrorViews/NotFound';
import { LoadingBlock } from '@core/component/LoadingBlock';
import {
DEV_MODE_ENV,
@@ -220,6 +222,7 @@ registerComponent(
() => composableLayout(true)
);
registerComponent('getting-started', () => <GettingStartedRouteView />);
+registerComponent(NOT_FOUND_ROUTE_ID, () => <NotFound />);
registerComponent('recent', () => <RecentRouteView />);
registerComponent('activity', () => <ActivityRouteView />);
registerComponent('reminders', () => <RemindersRouteView />);
diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
index 9294d5016c..79a89f6a1a 100644
--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx
@@ -7,7 +7,7 @@ import type { DriveState } from '@app/features/drive-view/core/types';
import { useSoup } from '@app/features/next-soup/soup-context';
import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';
import { projectRouteId } from '@app/features/projects/core/route';
-import { useSplitRouter } from '@app/lib/split-router';
+import { type PaneId, useSplitRouter } from '@app/split-router';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { type BlockName, NonDocumentBlockTypes } from '@core/block';
import {
@@ -48,7 +48,7 @@ import { Portal } from 'solid-js/web';
import { match, P } from 'ts-pattern';
import { splitBackInterceptor } from '../back-interceptor';
import { SplitLayoutContext, SplitPanelContext } from '../context';
-import type { SplitContent, SplitId } from '../layoutManager';
+import type { SplitContent } from '../layoutManager';
import {
closeSplitOrReturnToList,
shouldShowSplitCloseButton,
@@ -370,7 +370,7 @@ export function ListNavigationButtons(props: {
function SplitHeaderContextMenu(props: ParentProps) {
const panel = useContext(SplitPanelContext);
const layout = useContext(SplitLayoutContext);
- const router = useSplitRouter<SplitId>();
+ const router = useSplitRouter();
if (!panel || !layout) return props.children;
const splitIndex = createMemo(() =>
@@ -415,7 +415,7 @@ function SplitHeaderContextMenu(props: ParentProps) {
activeSplitId: layout.manager.activeSplitId(),
currentSplitId: panel.handle.id,
currentSplitIndex: splitIndex(),
- currentSplitUrl: router.href(panel.handle.id),
+ currentSplitUrl: router.href(panel.handle.id as string as PaneId),
splits: splits.map((split, index) => ({
index,
id: split.id,
diff --git a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
index 02aa912957..a1f0b3bfc1 100644
--- a/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
+++ b/apps/web/src/components/app/split-layout/components/SplitPanel.tsx
@@ -2,8 +2,8 @@ import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
import { createSoupState } from '@app/features/next-soup/create-soup-state';
import { SoupContextProvider } from '@app/features/next-soup/soup-context';
import { SoupViewContextProvider } from '@app/features/next-soup/soup-view/soup-view-context';
-import { SplitRouter } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { type PaneId, SplitRouter } from '@app/split-router';
import { ContentLoading } from '@components/app/ContentLoading';
import { MobileTopEdgeFade } from '@components/app/mobile/MobileEdgeFade';
import { MobilePageActionRow } from '@components/app/mobile/MobilePageActionRow';
@@ -177,17 +177,15 @@ export function SplitPanel(props: SplitPanelProps) {
fallback={
<SoupViewContextProvider soup={nextSoup}>
<SplitRouter.Outlet
- splitId={props.handle.id}
- fallback={() => (
- <Dynamic component={props.split.mount.element} />
- )}
+ pane={props.handle.id as string as PaneId}
+ fallback={<Dynamic component={props.split.mount.element} />}
/>
</SoupViewContextProvider>
}
>
<SplitRouter.Outlet
- splitId={props.handle.id}
- fallback={() => <Dynamic component={props.split.mount.element} />}
+ pane={props.handle.id as string as PaneId}
+ fallback={<Dynamic component={props.split.mount.element} />}
/>
</Show>
</Suspense>
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.ts
index 02aa5f825d..470ee4412b 100644
--- a/apps/web/src/components/app/split-layout/layoutManager.ts
+++ b/apps/web/src/components/app/split-layout/layoutManager.ts
@@ -1,6 +1,15 @@
import { LIST_VIEW_ID, type ListView } from '@app/constants/list-views';
import { parseAgentsRoute } from '@app/features/agents-view/core/route';
-import type { SplitSearchUpdate } from '@app/lib/split-router';
+import type {
+ Entry,
+ NavigationResult,
+ PaneArrival,
+ PaneId,
+ SplitLocation,
+ SplitNavigateOptions,
+ SplitRouter,
+ SplitSearchUpdate,
+} from '@app/split-router';
import type {
BlockAlias,
BlockAliasContext,
@@ -14,17 +23,18 @@ import type {
BlockOrchestrator,
} from '@core/orchestrator';
import { useFocusLock } from '@core/util/createControlledOpenSignal';
-import deepEqual from 'fast-deep-equal';
import {
type Accessor,
batch,
+ createComputed,
createMemo,
createSignal,
type JSXElement,
+ mapArray,
onCleanup,
untrack,
} from 'solid-js';
-import { createStore, produce, reconcile, type Store } from 'solid-js/store';
+import { createStore, produce, type Store } from 'solid-js/store';
import {
type ComponentMeta,
type ComponentMetaMap,
@@ -34,12 +44,33 @@ import { contentReference } from './content-reference';
import {
type ContentInstance,
createContentInstanceRegistry,
- sameContentIdentity,
} from './contentInstanceRegistry';
-import { createHistory, type History } from './history';
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
-const ENABLE_DEFAULT_ALWAYS_IN_HISTORY = false;
+/** Checked on every route change in a pane, so entry state is captured before the pane moves. */
+const ENTRY_STATE_GUARD_DEPTH = Number.MAX_SAFE_INTEGER;
+
+type MaybePromise<T> = T | Promise<T>;
+
+async function settleNavigation(
+ result: Promise<NavigationResult>,
+ then: (outcome: NavigationResult) => void
+) {
+ then(await result);
+}
+
+/** Runs `then` once a router navigation settles, right away when it already has. */
+function afterNavigation(
+ result: MaybePromise<NavigationResult>,
+ then: (outcome: NavigationResult) => void
+): void {
+ if (result instanceof Promise) {
+ void settleNavigation(result, then);
+ return;
+ }
+
+ then(result);
+}
export type SplitId = string & { readonly SplitId: unique symbol };
type SplitKey = `${BlockName | BlockAlias | 'component'}:${string}`;
@@ -94,8 +125,6 @@ function keyOfSplitContent(s: SplitContent): SplitKey {
return `${s.type}:${s.id}`;
}
-const brandSplitId = (s: string) => s as SplitId;
-
type ElementFn = () => JSXElement;
type BlockMount = {
@@ -148,8 +177,7 @@ export type ReferredFrom =
export type SplitState = {
id: SplitId;
- history: History<SplitContent>;
- content: SplitContent; // mirror of current history entry
+ content: SplitContent; // mirror of the pane's current router entry
mount: SplitMount; // contains pinned element
referredFrom: ReferredFrom;
lastNavigationCause: NavigationCause;
@@ -162,10 +190,7 @@ export type CreateNewSplitOptions = {
allowDuplicate?: boolean;
referredFrom: ReferredFrom;
insertIndex?: number;
- /**
- * Optional prior navigation entries to pre-populate this split's history stack.
- * The `content` field is appended as the final (current) entry.
- */
+ /** Not supported: a new pane starts with only `content`. Kept for the mobile swipe layout. */
initialHistory?: SplitContent[];
};
@@ -210,10 +235,6 @@ export type SplitNavigationInterceptor = (
options: OpenWithSplitOptions
) => OpenSplitResult | undefined;
-function keyOfSplitState(s: SplitState): SplitKey {
- return `${s.content.type}:${s.content.id}`;
-}
-
export enum SplitEvent {
Insert,
Remove,
@@ -275,16 +296,19 @@ export type OpenView = ContentInstance & {
topLevelSplit?: SplitHandle;
};
+export type SplitLayoutOptions = {
+ router: SplitRouter;
+ /** Where content lives in the router's route table. */
+ toLocation: (content: SplitContent) => SplitLocation;
+ /** The content a router location shows. */
+ toContent: (location: SplitLocation) => SplitContent;
+ defaultSplitContent?: SplitContent;
+};
+
export type SplitManager = {
- /** Bound by the app router; keeps imperative callers on the same navigation path. */
- setContentNavigator: (
- navigate:
- | ((content: SplitContent, options: OpenWithSplitOptions) => void)
- | undefined
- ) => void;
- /** Whether the app router is currently bound for route-owned imperative opens. */
+ /** Whether the router has loaded the URL, so route-owned opens can run. */
readonly contentNavigationReady: Accessor<boolean>;
- /** Changes whenever the app router binding is installed, replaced, or removed. */
+ /** Changes when route-owned navigation becomes available. */
readonly contentNavigationVersion: Accessor<number>;
/** Find the view owning this content without activating it. */
findOpenView: (content: SplitContent) => OpenView | undefined;
@@ -331,17 +355,6 @@ export type SplitManager = {
canAppendSplit: () => boolean;
- /**
- * Reconcile the splits with the provided list of splits.
- * Useful when applying externally restored layout state.
- *
- * All [SplitContent] of type `component` will be fully re-created.
- * All [SplitContent] of type `block` will be preserved, and not re-mounted.
- *
- * @param splits The new list of splits
- */
- reconcile: (splits: SplitContent[]) => void;
-
/** Replace all splits with a single split containing the given content. */
replaceAllSplits: (
content: SplitContent,
@@ -517,12 +530,6 @@ export type SplitHandle<TMeta extends ComponentMeta = ComponentMeta> = {
) => void;
};
-function newSplitId(): SplitId {
- return brandSplitId(
- `s_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`
- );
-}
-
function createPinnedMount(
orchestrator: BlockOrchestrator,
content: SplitContent
@@ -574,25 +581,11 @@ function contentIdentity(content: SplitContent) {
: content;
}
-function sameEntityContent(a: SplitContent, b: SplitContent): boolean {
- return sameContentIdentity(contentIdentity(a), contentIdentity(b));
-}
-
-function isDuplicateSplit(
- splits: SplitState[],
- content: SplitContent,
- isExcluded: (split: SplitState) => boolean = () => false
-): boolean {
- return splits
- .filter((s) => !isExcluded(s))
- .some((split) => sameEntityContent(split.content, content));
-}
-
export function createSplitLayout(
orchestrator: BlockOrchestrator,
- initial: SplitContent[],
- defaultSplitContent?: SplitContent
+ options: SplitLayoutOptions
): SplitManager {
+ const { router, toLocation, toContent, defaultSplitContent } = options;
const [state, setState] = createStore<{
splits: SplitState[];
activeSplitId: SplitId | undefined;
@@ -665,11 +658,6 @@ export function createSplitLayout(
let exclusionFilter: ((split: SplitState) => boolean) | undefined;
let splitNavigationInterceptor: SplitNavigationInterceptor | undefined;
- const [contentNavigator, setContentNavigatorBinding] = createSignal<
- ((content: SplitContent, options: OpenWithSplitOptions) => void) | undefined
- >();
- const [contentNavigationVersion, setContentNavigationVersion] =
- createSignal(0);
const isExcluded = (split: SplitState) => exclusionFilter?.(split) ?? false;
const canAppendSplit = createMemo(
@@ -687,57 +675,51 @@ export function createSplitLayout(
/**
* Per-split, per-key captors. A captor returns the current value of a
- * component-owned state slice. Right before navigating away from the current
- * entry, we invoke all captors for that split and write the resulting blob
- * to the entry's `state` field via `history.replaceCurrent`.
+ * component-owned state slice. Right before a pane leaves its current
+ * entry, we invoke all captors for that split and keep the resulting blob
+ * for that router entry, so returning to it restores the slices.
*/
const entryStateCaptors = new Map<SplitId, Map<string, () => unknown>>();
+ const entryStates = new Map<string, EntryState>();
- function captureCurrentEntryState(split: SplitState): void {
- const captors = entryStateCaptors.get(split.id);
+ const paneOf = (id: SplitId) => id as string as PaneId;
+ const splitOf = (pane: PaneId) => pane as string as SplitId;
+
+ function captureEntry(id: SplitId, entry: Entry): EntryState | undefined {
+ const captors = entryStateCaptors.get(id);
if (!captors || captors.size === 0) return;
- const items = split.history.items;
- const idx = split.history.index;
- if (idx < 0 || idx >= items.length) return;
- const currentItem = items[idx];
- const state: EntryState = { ...(currentItem.state ?? {}) };
+ const state: EntryState = { ...entryStates.get(entry.id) };
for (const [key, getter] of captors) {
try {
state[key] = getter();
} catch (err) {
console.error(
- `Entry state captor for split ${split.id} key "${key}" threw`,
+ `Entry state captor for split ${id} key "${key}" threw`,
err
);
}
}
- const next = { ...currentItem, state } as SplitContent;
- split.history.replaceCurrent(next);
+ entryStates.set(entry.id, state);
+
+ return state;
+ }
+
+ function captureCurrentEntryState(split: SplitState): void {
+ const entry = untrack(() => router.entry(paneOf(split.id)));
+ if (!entry) return;
+
+ const state = captureEntry(split.id, entry);
+ if (!state) return;
+
// Mirror onto SplitState.content so live reads see the captured state.
setState('splits', (s) => {
const i = s.findIndex((x) => x.id === split.id);
if (i < 0) return s;
- return s.with(i, { ...s[i], content: next });
+ return s.with(i, { ...s[i], content: { ...s[i].content, state } });
});
}
- function applyEntryMetadata(
- split: SplitState,
- desired: SplitContent
- ): SplitState {
- if (deepEqual(split.content.entryMetadata, desired.entryMetadata)) {
- return split;
- }
-
- const content = {
- ...split.content,
- entryMetadata: desired.entryMetadata,
- } as SplitContent;
- split.history.replaceCurrent(content);
- return { ...split, content };
- }
-
const DEFAULT_SPLIT_CONTENT = defaultSplitContent ?? {
type: 'component',
id: LIST_VIEW_ID.home,
@@ -757,69 +739,60 @@ export function createSplitLayout(
const splitIndexById = (id: SplitId) =>
state.splits.findIndex((s) => s.id === id);
- function buildSplit(options: {
- id?: SplitId;
- initialContent: SplitContent;
- isDefault?: boolean;
- referredFrom?: ReferredFrom;
- initialHistory?: SplitContent[];
- }): SplitState {
- const { initialContent, isDefault, referredFrom, initialHistory } = options;
- const id = options.id ?? newSplitId();
- const history = createHistory<SplitContent>({
- canVisit: (content) => canOpenContent(content, id),
- });
- const content = attachAliasContext(initialContent);
+ /**
+ * The content a router entry shows. A fresh visit or replace delivers the
+ * entry's one-shot props as `params`; history traversal does not, unless the
+ * entry keeps them.
+ */
+ function contentOfEntry(entry: Entry, deliverParams: boolean): SplitContent {
+ const routed = toContent(entry.location);
+ const delivers = deliverParams || entry.keepProps === true;
+ const params = delivers ? entry.props : undefined;
+ const state = entryStates.get(entry.id);
+ const content = {
+ ...routed,
+ ...(params !== undefined && { params }),
+ ...(entry.keepProps && { preserveParams: true }),
+ ...(state && { state }),
+ entryMetadata: entry.location,
+ } as SplitContent;
- if (initialHistory && initialHistory.length > 0) {
- // Pre-populate prior navigation entries so previousContent() is accurate.
- for (const item of initialHistory) {
- history.push(attachAliasContext(item));
- }
- } else {
- // If enabled, we always want to be able to go back to the default split
- if (!isDefault && ENABLE_DEFAULT_ALWAYS_IN_HISTORY) {
- history.push(DEFAULT_SPLIT_CONTENT);
- }
- }
+ return attachAliasContext(content);
+ }
+
+ function contentAt(entry: Entry): SplitContent {
+ return contentOfEntry(entry, false);
+ }
+
+ const causeOf = (arrival: PaneArrival): NavigationCause => {
+ if (arrival === 'back') return 'history-back';
+ if (arrival === 'forward') return 'history-forward';
+ if (arrival === 'replace') return 'replace';
- history.push(content);
- const mount = createPinnedMount(orchestrator, content);
+ return 'fresh';
+ };
+ function newSplitState(
+ id: SplitId,
+ content: SplitContent,
+ referredFrom: ReferredFrom | undefined
+ ): SplitState {
return {
id,
- history,
content,
- mount,
+ mount: createPinnedMount(orchestrator, content),
referredFrom: referredFrom ?? null,
lastNavigationCause: 'fresh',
};
}
- /**
- * `deliverParams` marks a fresh forward navigation, which delivers the
- * one-shot `content.params` to the new mount. History-driven reattaches
- * (back/forward, removeFromHistory, reset) leave it unset so re-visiting an
- * entry doesn't re-fire its params (e.g. re-target a channel message).
- */
+ /** Shows `content`, the pane's new current entry, in `split`; a new identity remounts. */
function reattach(
split: SplitState,
- next: SplitContent,
- referredFrom?: ReferredFrom,
- cause: NavigationCause = 'fresh',
- deliverParams = false
+ content: SplitContent,
+ referredFrom: ReferredFrom | undefined,
+ cause: NavigationCause
) {
- const otherSplits = state.splits.filter((s) => s.id !== split.id);
- let content = attachAliasContext(next);
- if (
- !deliverParams &&
- !content.preserveParams &&
- content.params !== undefined
- ) {
- content = { ...content, params: undefined };
- }
- if (isDuplicateSplit(otherSplits, next)) return;
-
const splitIndex = splitIndexById(split.id);
if (
splitIndex >= 0 &&
@@ -893,23 +866,52 @@ export function createSplitLayout(
});
}
- function back(id: SplitId) {
- const i = splitIndexById(id);
- if (i < 0) return console.error(`Split with id ${id} not found`);
+ /** How the manager reached an entry; kept on the router entry, in memory only. */
+ type EntryMeta = {
+ referredFrom?: ReferredFrom;
+ activate?: boolean;
+ entryState?: EntryState;
+ };
- const split = state.splits[i];
- if (!split.history.canGoBack()) return;
+ const metaOf = (entry: Entry) => (entry.meta ?? {}) as EntryMeta;
- batch(() => {
- captureCurrentEntryState(split);
+ function entryOptionsOf(
+ content: SplitContent,
+ meta: EntryMeta = {}
+ ): SplitNavigateOptions {
+ const entryMeta: EntryMeta = {
+ ...meta,
+ ...(content.state && { entryState: content.state }),
+ };
+
+ return {
+ props: content.params,
+ keepProps: content.preserveParams,
+ meta: entryMeta,
+ };
+ }
- const prev = split.history.back();
- if (!prev) return;
+ /** Splits whose next entry relabels the mount instead of remounting it. */
+ const pendingAdoptions = new Set<SplitId>();
- reattach(split, prev, undefined, 'history-back');
+ function navigateSplit(
+ id: SplitId,
+ content: SplitContent,
+ navigateOptions: { replace?: boolean; referredFrom?: ReferredFrom } = {}
+ ): MaybePromise<NavigationResult> {
+ const { replace, referredFrom } = navigateOptions;
+ const target = { location: toLocation(content) };
+
+ return router.navigate(paneOf(id), target, {
+ ...entryOptionsOf(content, { referredFrom }),
+ replace,
});
}
+ function back(id: SplitId) {
+ void router.navigate(paneOf(id), -1);
+ }
+
/**
* Jump a split back to the nearest earlier history entry matching
* `predicate`, skipping the entries in between (they stay reachable with
@@ -920,62 +922,25 @@ export function createSplitLayout(
id: SplitId,
predicate: (content: SplitContent) => boolean
): boolean {
- const i = splitIndexById(id);
- if (i < 0) {
- console.error(`Split with id ${id} not found`);
- return false;
- }
-
- const split = state.splits[i];
- const result = { moved: false };
-
- batch(() => {
- captureCurrentEntryState(split);
-
- // Entries whose content another split already displays are not
- // candidates: `reattach` refuses them, which would strand the history
- // index on an entry the split never mounted. Skipping them here keeps
- // the index and the mounted content in step, and lets the search carry
- // on to an entry that can actually be shown.
- const prev = split.history.backTo(predicate);
- if (!prev) return;
-
- result.moved = true;
- reattach(split, prev, undefined, 'history-back');
- });
+ const result = router.goBackTo(paneOf(id), (entry) =>
+ predicate(contentAt(entry))
+ );
+ if (result instanceof Promise) return true;
- return result.moved;
+ return result;
}
function forward(id: SplitId) {
- const i = splitIndexById(id);
- if (i < 0) return console.error(`Split with id ${id} not found`);
-
- const split = state.splits[i];
- if (!split.history.canGoForward()) return;
-
- batch(() => {
- captureCurrentEntryState(split);
-
- const next = split.history.forward();
- if (!next) return;
-
- reattach(split, next, undefined, 'history-forward');
- });
+ void router.navigate(paneOf(id), 1);
}
function removeFromHistory(
id: SplitId,
predicate: (content: SplitContent) => boolean
) {
- const i = splitIndexById(id);
- if (i < 0) return console.error(`Split with id ${id} not found`);
-
- const split = state.splits[i];
- const next = split.history.remove(predicate);
- if (!next) return;
-
- reattach(split, next, undefined, 'replace');
+ void router.removeEntries(paneOf(id), (entry) =>
+ predicate(contentAt(entry))
+ );
}
/**
@@ -990,8 +955,8 @@ export function createSplitLayout(
}
) {
const { next, mergeHistory, referredFrom } = options;
- const i = splitIndexById(id);
- if (i < 0) return console.error(`Split with id ${id} not found`);
+ if (!findSplitById(id))
+ return console.error(`Split with id ${id} not found`);
const content = attachAliasContext(next);
if (!canOpenContent(content, id)) {
@@ -999,42 +964,25 @@ export function createSplitLayout(
return;
}
- const split = state.splits[i];
- batch(() => {
- captureCurrentEntryState(split);
- if (mergeHistory) {
- split.history.merge(content);
- } else {
- split.history.push(content);
- }
-
- reattach(
- split,
- content,
- referredFrom,
- mergeHistory ? 'replace' : 'fresh',
- true
- );
- });
+ void navigateSplit(id, content, { replace: mergeHistory, referredFrom });
}
/**
* Move a split onto a new id for the block it is already showing, keeping
* the mount. See `SplitHandle.adoptContentId` for why this exists.
*
- * The history entry is rewritten rather than pushed, and the navigation
- * cause is `replace`, so external state can replace the id instead of adding
- * a back step to a placeholder the user can never return to.
+ * The current entry is rewritten rather than pushed, so external state can
+ * replace the id instead of adding a back step to a placeholder the user can
+ * never return to.
*/
function adoptContentId(
id: SplitId,
type: BlockName | 'component',
nextId: string
) {
- const i = splitIndexById(id);
- if (i < 0) return;
+ const split = findSplitById(id);
+ if (!split) return;
- const split = state.splits[i];
const current = split.content;
if (current.type !== type || current.id === nextId) return;
const next: SplitContent = { ...current, id: nextId, params: undefined };
@@ -1043,28 +991,37 @@ export function createSplitLayout(
return;
}
+ pendingAdoptions.add(id);
+ const result = router.rewriteCurrent(paneOf(id), {
+ location: toLocation(next),
+ });
+ afterNavigation(result, () => pendingAdoptions.delete(id));
+ }
+
+ /** Relabels the mount for an adopted id: the same surface, nothing unmounts. */
+ function adoptMount(split: SplitState, next: SplitContent) {
+ const current = split.content;
+
batch(() => {
- split.history.replaceCurrent(next);
setState('splits', (splits) => {
- const index = splits.findIndex((s) => s.id === id);
+ const index = splits.findIndex((s) => s.id === split.id);
if (index < 0) return splits;
const previous = splits[index];
return splits.with(index, {
...previous,
content: next,
- // The same mount, re-labelled: nothing unmounts here.
mount:
previous.mount.kind === 'block'
- ? { ...previous.mount, id: nextId }
+ ? { ...previous.mount, id: next.id }
: previous.mount,
lastNavigationCause: 'replace',
});
});
- if (type !== 'component') {
+ if (current.type !== 'component') {
orchestrator.rekeyBlockInstance(
- resolveBlockAlias(type),
+ resolveBlockAlias(current.type),
current.id,
- nextId
+ next.id
);
}
});
@@ -1076,46 +1033,98 @@ export function createSplitLayout(
): void {
const split = findSplitById(id);
if (!split) return;
- if (
- split.history.index < 0 ||
- split.history.index >= split.history.items.length
- ) {
- return;
- }
const current = split.content;
const next = updater(current);
- if (
- next === current ||
- keyOfSplitContent(current) !== keyOfSplitContent(next)
- )
+ const sameIdentity = keyOfSplitContent(current) === keyOfSplitContent(next);
+ if (next === current || !sameIdentity) return;
+
+ const entry = untrack(() => router.entry(paneOf(id)));
+ if (entry && next.state) entryStates.set(entry.id, next.state);
+
+ void router.rewriteCurrent(paneOf(id), { location: toLocation(next) });
+ }
+
+ function reset(id: SplitId) {
+ if (!findSplitById(id))
+ return console.error(`Split with id ${id} not found`);
+
+ void navigateSplit(id, DEFAULT_SPLIT_CONTENT);
+ }
+
+ /** Mirrors a pane's new current entry onto its split, creating the split when the pane is new. */
+ function applyEntry(id: SplitId, entry: Entry, arrival: PaneArrival) {
+ const deliversParams = arrival === 'fresh' || arrival === 'replace';
+ const content = contentOfEntry(entry, deliversParams);
+ const meta = metaOf(entry);
+ const referredFrom = deliversParams ? meta.referredFrom : undefined;
+ const split = findSplitById(id);
+
+ if (!split) {
+ addSplit(id, content, referredFrom, meta.activate ?? true);
return;
+ }
+
+ if (pendingAdoptions.has(id)) {
+ pendingAdoptions.delete(id);
+ adoptMount(split, content);
+ return;
+ }
+
+ reattach(split, content, referredFrom, causeOf(arrival));
+ }
+
+ function addSplit(
+ id: SplitId,
+ content: SplitContent,
+ referredFrom: ReferredFrom | undefined,
+ activate: boolean
+ ) {
+ const split = newSplitState(id, content, referredFrom);
batch(() => {
- split.history.replaceCurrent(next);
- setState('splits', (splits) => {
- const index = splits.findIndex((candidate) => candidate.id === id);
- if (index < 0) return splits;
- return splits.with(index, { ...splits[index], content: next });
+ setState('splits', (splits) => [...splits, split]);
+ if (activate) activateSplit(id);
+ dispatchEvent(SplitEvent.Insert, {
+ splitId: id,
+ activate,
+ initial: content,
});
});
}
- function reset(id: SplitId) {
- const i = splitIndexById(id);
- if (i < 0) return console.error(`Split with id ${id} not found`);
+ /** Forgets a split whose pane the router removed. */
+ function dropSplit(id: SplitId) {
+ const index = splitIndexById(id);
+ if (index < 0) return;
+
+ contentChangeListeners.delete(id);
+ entryStateCaptors.delete(id);
- const history = createHistory<SplitContent>({
- canVisit: (content) => canOpenContent(content, id),
- });
- const content = attachAliasContext(DEFAULT_SPLIT_CONTENT);
- history.push(content);
batch(() => {
- setState('splits', (splits) => splits.with(i, { ...splits[i], history }));
- reattach(state.splits[i], content, undefined, 'fresh');
+ setSplitNamesById(
+ produce((map) => {
+ delete map[id];
+ return map;
+ })
+ );
+ setState('splits', (splits) => splits.filter((s) => s.id !== id));
+ dispatchEvent(SplitEvent.Remove, { splitId: id, splitIndex: index });
});
}
+ /** Puts splits in the router's pane order. */
+ function orderSplits(ids: readonly SplitId[]) {
+ const byId = new Map(state.splits.map((split) => [split.id, split]));
+ const ordered = ids.flatMap((id) => byId.get(id) ?? []);
+ const inOrder =
+ ordered.length === state.splits.length &&
+ ordered.every((split, index) => split === state.splits[index]);
+ if (inOrder) return;
+
+ setState('splits', ordered);
+ }
+
function activateSplit(id: SplitId) {
// Invariant: an excluded split (the mobile background split) can never
// become the active split. Promote it out of exclusion first.
@@ -1188,14 +1197,8 @@ export function createSplitLayout(
id: currentSplit.id,
content,
activate: () => activateSplit(currentSplit.id),
- // Re-resolve the split by id rather than reading the captured
- // `currentSplit`. reconcileSplits can replace the SplitState (fresh
- // history, same id) while this handle instance persists, so the captured
- // reference goes stale and the button would report the old history.
- canGoBack: () =>
- (findSplitById(currentSplit.id) ?? currentSplit).history.canGoBack(),
- canGoForward: () =>
- (findSplitById(currentSplit.id) ?? currentSplit).history.canGoForward(),
+ canGoBack: () => router.canGo(paneOf(currentSplit.id), -1),
+ canGoForward: () => router.canGo(paneOf(currentSplit.id), 1),
goBack: () => back(currentSplit.id),
goBackTo: (predicate: (content: SplitContent) => boolean) =>
backTo(currentSplit.id, predicate),
@@ -1209,33 +1212,20 @@ export function createSplitLayout(
removeFromHistory(currentSplit.id, predicate);
},
previousContent: () => {
- const s = findSplitById(currentSplit.id);
- if (!s) return null;
- const idx = s.history.index;
- return idx > 0 ? (s.history.items[idx - 1] ?? null) : null;
+ const snapshot = router.history(paneOf(currentSplit.id));
+ if (!snapshot || snapshot.index <= 0) return null;
+
+ const previous = snapshot.entries[snapshot.index - 1];
+ return previous ? contentAt(previous) : null;
},
history: () => {
- const s = findSplitById(currentSplit.id);
- if (!s) return [];
- return s.history.items.slice(0, s.history.index + 1) as SplitContent[];
+ const snapshot = router.history(paneOf(currentSplit.id));
+ if (!snapshot) return [];
+
+ return snapshot.entries.slice(0, snapshot.index + 1).map(contentAt);
},
close: () => {
- // If there's only one split and it's the default split, then no-op
- if (state.splits.length <= 1) {
- // If it's not the default split, replace it with the default
- if (
- keyOfSplitContent(content()) !==
- keyOfSplitContent(DEFAULT_SPLIT_CONTENT)
- )
- replace(currentSplit.id, {
- next: DEFAULT_SPLIT_CONTENT,
- referredFrom: null,
- });
-
- return;
- }
-
- removeSplit(currentSplit.id);
+ void router.close(paneOf(currentSplit.id));
},
isFirst: () => state.splits.at(0)?.id === id,
isLast: () => state.splits.at(-1)?.id === id,
@@ -1311,15 +1301,36 @@ export function createSplitLayout(
};
};
+ /** Opens `content` in a new pane where the policy places it, after the active split by default. */
+ function openPane(
+ content: SplitContent,
+ openOptions: {
+ insertIndex?: number;
+ referredFrom?: ReferredFrom;
+ activate?: boolean;
+ allowDuplicate?: boolean;
+ }
+ ): MaybePromise<NavigationResult> {
+ const { insertIndex, referredFrom, activate, allowDuplicate } = openOptions;
+ const active = state.activeSplitId;
+ const source = active ? paneOf(active) : undefined;
+
+ return router.open(
+ { location: toLocation(content) },
+ { newPane: true, source, intent: { insertIndex, direct: true } },
+ {
+ ...entryOptionsOf(content, { referredFrom, activate }),
+ allowDuplicate,
+ }
+ );
+ }
+
function createNewSplit(
options: CreateNewSplitOptions
): SplitHandle | undefined {
- const { content, activate, referredFrom, initialHistory, insertIndex } =
+ const { content, activate, referredFrom, insertIndex, allowDuplicate } =
options;
- const initialContent = content ?? DEFAULT_SPLIT_CONTENT;
- const isDefault =
- keyOfSplitContent(initialContent) ===
- keyOfSplitContent(DEFAULT_SPLIT_CONTENT);
+ const initialContent = attachAliasContext(content ?? DEFAULT_SPLIT_CONTENT);
// Direct split creation permits duplicate shells, but never duplicate entities.
const existing = findOpenView(initialContent);
@@ -1327,66 +1338,30 @@ export function createSplitLayout(
if (activate) existing.activate?.();
return existing.topLevelSplit;
}
- const split = buildSplit({
- initialContent,
- isDefault,
- referredFrom,
- initialHistory,
- });
- batch(() => {
- setState('splits', (previousSplits) => {
- if (insertIndex === undefined) return [...previousSplits, split];
-
- const nextSplits = [...previousSplits];
- nextSplits.splice(
- Math.max(0, Math.min(insertIndex, nextSplits.length)),
- 0,
- split
- );
- return nextSplits;
- });
- });
-
- const handle = getSplit(split.id)!;
-
- if (activate) {
- handle.activate();
- }
-
- dispatchEvent(SplitEvent.Insert, {
- splitId: split.id,
- activate,
- initial: initialContent,
+ const result = openPane(initialContent, {
+ insertIndex,
+ referredFrom,
+ activate: activate ?? false,
+ allowDuplicate,
});
+ if (result instanceof Promise) return;
+ if (result.status !== 'committed') return;
- return handle;
+ return getSplit(splitOf(result.pane));
}
+ /** Removes a split; the last one shows the default content instead. */
function removeSplit(id: SplitId, createNewOnEmpty: boolean = true) {
- const idx = splitIndexById(id);
- if (idx < 0) return;
-
- contentChangeListeners.delete(id);
- entryStateCaptors.delete(id);
-
- batch(() => {
- setSplitNamesById(
- produce((map) => {
- delete map[id];
- return map;
- })
- );
+ if (!findSplitById(id)) return;
- const nextSplits = state.splits.filter((s) => s.id !== id);
- setState('splits', reconcile(nextSplits));
-
- dispatchEvent(SplitEvent.Remove, { splitId: id, splitIndex: idx });
+ const isLast = state.splits.length <= 1;
+ if (isLast) {
+ if (createNewOnEmpty) void navigateSplit(id, DEFAULT_SPLIT_CONTENT);
+ return;
+ }
- if (nextSplits.length === 0 && createNewOnEmpty) {
- createNewSplit({ content: DEFAULT_SPLIT_CONTENT, referredFrom: null });
- }
- });
+ void router.remove(paneOf(id));
}
function canSwapSplit(id: SplitId, direction: 'left' | 'right') {
@@ -1402,9 +1377,7 @@ export function createSplitLayout(
const target = state.splits[targetIndex];
batch(() => {
resizeContext()?.swap(id, target.id);
- setState('splits', (splits) =>
- splits.with(index, splits[targetIndex]).with(targetIndex, splits[index])
- );
+ router.move(paneOf(id), targetIndex);
});
}
@@ -1431,153 +1404,42 @@ export function createSplitLayout(
return getSplit(match.id);
}
- function reconcileEntryMetadata(
- visibleSplits: SplitState[],
- newSplits: SplitContent[]
- ) {
- const metadataChanged = visibleSplits.some(
- (split, index) =>
- !deepEqual(split.content.entryMetadata, newSplits[index]?.entryMetadata)
- );
- if (!metadataChanged) return;
-
- setState('splits', (splits) => {
- const nextById = new Map(
- visibleSplits.map((split, index) => [
- split.id,
- applyEntryMetadata(split, newSplits[index]),
- ])
- );
- return splits.map((split) => nextById.get(split.id) ?? split);
- });
- }
-
- function reconcileSplits(newSplits: SplitContent[]) {
- const visibleSplits = state.splits.filter((s) => !isExcluded(s));
- const currentKeys = visibleSplits.map(keyOfSplitState);
- const newKeys = newSplits.map(keyOfSplitContent);
- const changed = newKeys.join(',') !== currentKeys.join(',');
-
- if (!changed) {
- reconcileEntryMetadata(visibleSplits, newSplits);
- return;
- }
-
- // Build the result array by position, preserving excluded splits unchanged.
- const resultSplits: SplitState[] = [];
- const usedIds = new Set<SplitId>();
-
- for (const split of state.splits) {
- if (isExcluded(split)) {
- resultSplits.push(split);
- usedIds.add(split.id);
- }
- }
-
- // Assign existing splits before creating replacements. Matching by content
- // after the same-position fast path lets a split keep its identity (and its
- // history/mount) when inbound state merely moves it to another index.
- const assignments = new Array<SplitState | undefined>(newSplits.length);
-
- for (let i = 0; i < newSplits.length; i++) {
- const newContent = newSplits[i];
- const splitAtSameIndex = visibleSplits[i];
-
- if (
- splitAtSameIndex &&
- !usedIds.has(splitAtSameIndex.id) &&
- keyOfSplitContent(splitAtSameIndex.content) ===
- keyOfSplitContent(newContent)
- ) {
- assignments[i] = splitAtSameIndex;
- usedIds.add(splitAtSameIndex.id);
- }
- }
-
- for (let i = 0; i < newSplits.length; i++) {
- if (assignments[i]) continue;
-
- const existing = visibleSplits.find(
- (split) =>
- !usedIds.has(split.id) &&
- keyOfSplitContent(split.content) === keyOfSplitContent(newSplits[i])
- );
- if (existing) {
- assignments[i] = existing;
- usedIds.add(existing.id);
- }
- }
+ // The router owns each pane's history; splits mirror what its panes show.
+ const paneSplits = mapArray(router.panes, (pane) => {
+ const id = splitOf(pane);
- for (let i = 0; i < newSplits.length; i++) {
- const existing = assignments[i];
- if (existing) {
- resultSplits.push(applyEntryMetadata(existing, newSplits[i]));
- continue;
- }
+ createComputed(() => {
+ const entry = router.entry(pane);
+ const arrival = router.arrival(pane);
+ if (!entry) return;
- if (
- isDuplicateSplit(resultSplits, newSplits[i]) ||
- !canOpenContent(newSplits[i])
- ) {
- const previous = visibleSplits[i];
- if (previous && !usedIds.has(previous.id)) {
- resultSplits.push(previous);
- usedIds.add(previous.id);
- }
- continue;
- }
- const splitAtSameIndex = visibleSplits[i];
- // A true replacement can retain the slot's ID, but never steal an ID
- // already assigned to content that moved elsewhere. Choose it before
- // building the history so its availability rule excludes the right owner.
- const retainedId =
- splitAtSameIndex && !usedIds.has(splitAtSameIndex.id)
- ? splitAtSameIndex.id
- : undefined;
- const newSplit = buildSplit({
- id: retainedId,
- initialContent: newSplits[i],
- referredFrom: null,
- });
+ untrack(() => applyEntry(id, entry, arrival));
+ });
- if (retainedId) {
- setSplitNamesById(
- produce((map) => {
- delete map[retainedId];
- return map;
- })
- );
+ const unregisterGuard = router.registerGuard(
+ pane,
+ ENTRY_STATE_GUARD_DEPTH,
+ ({ from }) => {
+ captureEntry(id, from);
+ return true;
}
+ );
- usedIds.add(newSplit.id);
- resultSplits.push(newSplit);
- }
+ onCleanup(() => {
+ unregisterGuard();
+ untrack(() => dropSplit(id));
+ });
- // Update the layout and clean up removed splits atomically.
- batch(() => {
- for (const split of state.splits) {
- if (!usedIds.has(split.id)) {
- contentChangeListeners.delete(split.id);
- entryStateCaptors.delete(split.id);
- setSplitNamesById(
- produce((map) => {
- delete map[split.id];
- return map;
- })
- );
- }
- }
+ return id;
+ });
- setState('splits', resultSplits);
- });
- }
+ createComputed(() => {
+ const ids = paneSplits();
+ untrack(() => orderSplits(ids));
+ });
const lastEvent = createMemo(() => state.events[state.events.length - 1]);
- for (const split of initial) {
- createNewSplit({ content: split, activate: true, referredFrom: null });
- }
-
const tabTitle = () => {
if (state.activeSplitId === undefined) return undefined;
return splitNamesById[state.activeSplitId] || undefined;
@@ -1673,16 +1535,53 @@ export function createSplitLayout(
}
}
+ /** An open that carries search: the router merges it and checks claims as it lands. */
+ function openThroughRouter(
+ content: SplitContent,
+ options: OpenWithSplitOptions
+ ) {
+ const firstVisible = getVisibleSplits()[0];
+ const source =
+ options.handle ??
+ activeSplit() ??
+ (firstVisible ? getSplit(firstVisible.id) : undefined);
+ const target = { location: toLocation(content) };
+ const navigateOptions = {
+ ...entryOptionsOf(content, {
+ referredFrom: options.referredFrom ?? null,
+ }),
+ replace: options.mergeHistory,
+ search: options.search,
+ allowDuplicate: options.allowDuplicate,
+ };
+ const wantsNewPane = options.preferNewSplit === true && canAppendSplit();
+
+ const result =
+ !source || wantsNewPane
+ ? router.open(
+ target,
+ {
+ newPane: true,
+ source: source && paneOf(source.id),
+ intent: { insertIndex: options.insertIndex, direct: true },
+ },
+ navigateOptions
+ )
+ : router.navigate(paneOf(source.id), target, navigateOptions);
+
+ afterNavigation(result, (outcome) => {
+ const applied = outcome.status !== 'cancelled';
+ if (applied) options.onApplied?.();
+ });
+ }
+
function openWithSplit(
content: SplitContent,
options: OpenWithSplitOptions = {}
): OpenSplitResult {
const sourceOwner = options.handle?.id;
if (options.search) {
- const navigate = contentNavigator();
- if (!navigate)
- throw new Error('Split content navigation requires the app router');
- navigate(content, options);
+ openThroughRouter(content, options);
return { status: 'navigating', sourceOwner };
}
const existing = findOpenView(content);
@@ -1853,7 +1752,6 @@ export function createSplitLayout(
activeSplit,
lastActiveSplitId: () => state.lastActiveSplitId,
events: lastEvent,
- reconcile: reconcileSplits,
replaceAllSplits,
getSplit,
openWithSplit,
@@ -1879,19 +1777,13 @@ export function createSplitLayout(
canAppendSplit,
getVisibleSplits,
getVisibleSplitCount: () => getVisibleSplits().length,
- contentNavigationReady: () => contentNavigator() !== undefined,
- contentNavigationVersion,
+ contentNavigationReady: router.ready,
+ contentNavigationVersion: () => (router.ready() ? 1 : 0),
setExclusionFilter: (fn) => {
exclusionFilter = fn;
},
setSplitNavigationInterceptor: (fn) => {
splitNavigationInterceptor = fn;
},
- setContentNavigator: (navigate) => {
- batch(() => {
- setContentNavigatorBinding(() => navigate);
- setContentNavigationVersion((version) => version + 1);
- });
- },
};
}
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
index 3f39f06561..3c3543e048 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts
@@ -14,20 +14,20 @@ import { driveDocumentBlockType } from '@app/features/drive-view/primitives/driv
import { driveSearch } from '@app/features/drive-view/primitives/drive-search';
import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
import { EMAIL_DETAIL_SEARCH_NAMESPACE } from '@app/features/email-view/email-route';
+import { paneRootMatch } from '@app/routes/app-route';
import {
+ replacePaneSearchParams,
routeParams,
type SerializedSearchParams,
type SplitRouterMiddleware,
type SplitRouterMiddlewareContext,
type SplitRouterMiddlewareResult,
-} from '@app/lib/split-router';
-import { replaceSplitSearchParams } from '@app/lib/split-router/search';
+} from '@app/split-router';
import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
import { match } from 'ts-pattern';
-import { appSplitRoutes } from './app-routes';
import { decodeLegacyPair } from './legacy-route';
type AppMiddlewareState = {
@@ -37,14 +37,15 @@ type AppMiddlewareState = {
/** Upgrade legacy component and block URLs when supported; on touch, keep
* document details in their full-block routes instead of inline Drive views. */
function redirectLegacyRoutes(
- { to, redirect }: SplitRouterMiddlewareContext,
+ { routes, to, redirect }: SplitRouterMiddlewareContext,
options: AppMiddlewareState
-): SplitRouterMiddlewareResult {
+): SplitRouterMiddlewareResult | undefined {
const route = to.location.route;
+ const rootId = paneRootMatch(route)?.id;
const isTouch = options.isTouchDevice();
- if (route.matches[0].id === 'drive' && isTouch) {
+ if (rootId === 'drive' && isTouch) {
const { documentType, documentId } = routeParams(route);
if (typeof documentType === 'string' && typeof documentId === 'string') {
return redirect(
@@ -53,19 +54,19 @@ function redirectLegacyRoutes(
}
}
- if (route.matches[0].id === 'call-detail') {
+ if (rootId === 'call-detail') {
const { callId } = routeParams(route);
if (typeof callId === 'string') {
return redirect(`/drive/call/${encodeURIComponent(callId)}`);
}
}
- if (route.matches[0].id === 'pr-detail') {
+ if (rootId === 'pr-detail') {
const { foreignEntityId } = routeParams(route);
if (typeof foreignEntityId === 'string') {
return redirect(`/reviews/pr/${encodeURIComponent(foreignEntityId)}`);
}
}
- if (route.matches[0].id !== 'legacy-content') return;
+ if (rootId !== 'legacy-content') return;
const { type, id } = routeParams(route);
@@ -81,9 +82,7 @@ function redirectLegacyRoutes(
calendarPath(getPreferredCalendarPeriodView())
)
.with({ type: 'component' }, ({ id }) =>
- appSplitRoutes.definitions.some((route) => route.id === `view-${id}`)
- ? `/${id}`
- : undefined
+ routes.byId.has(`view-${id}`) ? `/${id}` : undefined
)
.when(
() => isTouch,
@@ -98,9 +97,7 @@ function redirectLegacyRoutes(
// Like a task, a project opens in Tasks, under its Projects tab.
.with({ type: 'initiative' }, ({ id }) => {
const query = new URLSearchParams();
- replaceSplitSearchParams(query, [
- { location: { search: { tasks: { tab: ['projects'] } } } },
- ]);
+ replacePaneSearchParams(query, [{ tasks: { tab: ['projects'] } }]);
return `/tasks/projects/${encodeURIComponent(id)}/overview?${query}`;
})
.otherwise((content) => {
@@ -123,7 +120,7 @@ function migrateLegacySearch({
cause,
externalSearch,
redirect,
-}: SplitRouterMiddlewareContext): SplitRouterMiddlewareResult {
+}: SplitRouterMiddlewareContext): SplitRouterMiddlewareResult | undefined {
if (cause !== 'initial' && cause !== 'external') return;
if (!externalSearch) return;
@@ -217,7 +214,7 @@ function migrateLegacySearch({
const query = new URLSearchParams();
// Middleware redirects describe one entry; the router assigns its pane index.
- replaceSplitSearchParams(query, [{ location: { search } }]);
+ replacePaneSearchParams(query, [search]);
return redirect(`${path}?${query}`);
}
diff --git a/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts
new file mode 100644
index 0000000000..05cd8a5b47
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/split-router/app-pane-policy.ts
@@ -0,0 +1,77 @@
+import { parseAgentsRoute } from '@app/features/agents-view/core/route';
+import { paneRootMatch } from '@app/routes/app-route';
+import type { PaneId, SplitLocation, SplitPanePolicy } from '@app/split-router';
+import type { SplitContent, SplitId, SplitManager } from '../layoutManager';
+
+type AppPanePolicyOptions = {
+ manager: () => SplitManager | undefined;
+ toContent: (location: SplitLocation) => SplitContent;
+ defaultLocation: () => SplitLocation;
+ /** One pane at a time, as on native mobile; new-pane opens land in the source pane. */
+ singlePane: () => boolean;
+};
+
+/** A component view other than an agent conversation, which is an entity. */
+function isShellComponent(content: SplitContent): boolean {
+ if (content.type !== 'component') return false;
+
+ return parseAgentsRoute(content.id) === undefined;
+}
+
+const splitOf = (pane: PaneId) => pane as string as SplitId;
+
+/** The app's decisions about panes: where new ones go, what closing one does, and focus. */
+export function createAppPanePolicy(
+ options: AppPanePolicyOptions
+): SplitPanePolicy {
+ const sameRoot = (left: SplitLocation, right: SplitLocation) =>
+ paneRootMatch(left.route)?.id === paneRootMatch(right.route)?.id;
+
+ return {
+ // Entity views are always reused; only shell components may be duplicated.
+ placeNewPane({
+ destination,
+ source,
+ intent,
+ panes,
+ holder,
+ allowDuplicate,
+ }) {
+ const fallback = source ?? panes.at(-1);
+ if (options.singlePane() && fallback) return { pane: holder ?? fallback };
+
+ const content = options.toContent(destination);
+ const duplicatesShell = allowDuplicate && isShellComponent(content);
+ const reuses = holder !== undefined && !duplicatesShell;
+ if (reuses) return { pane: holder };
+
+ // Opens the manager already placed skip the capacity check.
+ const full =
+ intent.direct !== true && !options.manager()?.canAppendSplit();
+ if (full && fallback) return { pane: fallback };
+
+ const { insertIndex } = intent;
+ if (typeof insertIndex === 'number') {
+ return { insertAt: Math.max(0, Math.min(insertIndex, panes.length)) };
+ }
+
+ return { insertAt: panes.length };
+ },
+
+ // The last pane shows the default view instead of closing.
+ closeAction({ pane, panes }) {
+ if (panes.length > 1) return { type: 'remove' };
+
+ const destination = options.defaultLocation();
+ const current = options.manager()?.getSplit(splitOf(pane))?.content();
+ const showsDefault =
+ current?.entryMetadata !== undefined &&
+ sameRoot(current.entryMetadata as SplitLocation, destination);
+ if (showsDefault) return { type: 'keep' };
+
+ return { type: 'navigate', destination };
+ },
+
+ activate: (pane) => options.manager()?.activateSplit(splitOf(pane)),
+ };
+}
diff --git a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
index b00bc27bc8..2cfd1168af 100644
--- a/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
+++ b/apps/web/src/components/app/split-layout/split-router/app-route-shell.tsx
@@ -1,12 +1,10 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useSplitRouter } from '@app/lib/split-router';
-import { parseSearchState } from '@app/lib/split-router/search';
-import { isRecord } from '@app/lib/split-router/utils';
+import { isRecord, type PaneId, useSplitRouter } from '@app/split-router';
import { useIsAuthenticated } from '@core/auth';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { type Component, type JSX, onMount, Show } from 'solid-js';
-import type { SplitContent, SplitId } from '../layoutManager';
+import type { SplitContent } from '../layoutManager';
import { useSplitPanelOrThrow } from '../layoutUtils';
export function usePageViewTracking(pageTitle: string) {
@@ -33,11 +31,13 @@ export function RedirectSplit(props: {
mergeHistory?: boolean;
}) {
const panel = useSplitPanelOrThrow();
- const router = useSplitRouter<SplitId>();
+ const router = useSplitRouter();
onMount(() => {
const metadata = isRecord(props.to.entryMetadata)
? props.to.entryMetadata
: {};
+ const pane = panel.handle.id as string as PaneId;
+ const savedSearch = isRecord(metadata.search) ? metadata.search : {};
panel.handle.replace({
mergeHistory: props.mergeHistory,
next: {
@@ -45,8 +45,8 @@ export function RedirectSplit(props: {
entryMetadata: {
...metadata,
search: {
- ...router.location(panel.handle.id)?.search,
- ...parseSearchState(metadata.search),
+ ...router.entry(pane)?.location.search,
+ ...savedSearch,
},
},
},
diff --git a/apps/web/src/components/app/split-layout/split-router/app-routes.ts b/apps/web/src/components/app/split-layout/split-router/app-routes.ts
deleted file mode 100644
index c4120f8a1d..0000000000
--- a/apps/web/src/components/app/split-layout/split-router/app-routes.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { activityRoute } from '@app/features/activity/route';
-import {
- agentChatsRoute,
- agentsRoute,
- agentsViewRoute,
- codersRoute,
-} from '@app/features/agents-view/route';
-import { callDetailRoute } from '@app/features/block-call/route';
-import { prDetailRoute } from '@app/features/block-pr/route';
-import { calendarSplitRoute } from '@app/features/calendar-view/route';
-import { channelsSplitRoute } from '@app/features/channels-view/route';
-import { companiesRoute } from '@app/features/crm/route';
-import { driveSplitRoute } from '@app/features/drive-view/route';
-import { emailSplitRoute } from '@app/features/email-view/route';
-import { gettingStartedRoute } from '@app/features/getting-started/route';
-import { homeSplitRoute } from '@app/features/home/route';
-import {
- callsRoute,
- foldersRoute,
- recentRoute,
- searchRoute,
-} from '@app/features/next-soup/route';
-import {
- reminderDetailRoute,
- remindersRoute,
-} from '@app/features/reminders/route';
-import { reviewsSplitRoute } from '@app/features/reviews-view/route';
-import { settingsRoute } from '@app/features/settings/route';
-import { tasksSplitRoute } from '@app/features/tasks-view/route';
-import { defineRoutes } from '@app/lib/split-router';
-import { debugRoutes } from './debug-routes';
-import { handleLegacySplitPath, legacySplitRoute } from './legacy-route';
-
-export const appSplitRoutes = defineRoutes({
- definitions: [
- driveSplitRoute,
- settingsRoute,
- agentsRoute,
- codersRoute,
- agentChatsRoute,
- homeSplitRoute,
- gettingStartedRoute,
- recentRoute,
- activityRoute,
- reminderDetailRoute,
- remindersRoute,
- agentsViewRoute,
- emailSplitRoute,
- tasksSplitRoute,
- reviewsSplitRoute,
- calendarSplitRoute,
- channelsSplitRoute,
- callsRoute,
- callDetailRoute,
- companiesRoute,
- foldersRoute,
- searchRoute,
- prDetailRoute,
- ...debugRoutes,
- legacySplitRoute,
- ],
- globalSearch: ['referral_code'],
- unmatchedPathHandlers: [handleLegacySplitPath],
- defaultEntry: () => ({
- location: { route: { matches: [{ id: 'view-home', params: {} }] } },
- }),
-});
diff --git a/apps/web/src/components/app/split-layout/split-router/content-navigation.ts b/apps/web/src/components/app/split-layout/split-router/content-navigation.ts
deleted file mode 100644
index 462201d3ac..0000000000
--- a/apps/web/src/components/app/split-layout/split-router/content-navigation.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { SplitRouter, SplitRoutesManifest } from '@app/lib/split-router';
-import { encodeRoute } from '@app/lib/split-router/routes';
-import { replaceSplitSearchParams } from '@app/lib/split-router/search';
-import type {
- OpenWithSplitOptions,
- SplitContent,
- SplitId,
- SplitManager,
-} from '../layoutManager';
-import { openAppSplitLocation } from '../splitRouterLayout';
-import { resolveContentLocation } from './legacy-route';
-
-export function createContentNavigator(
- manager: SplitManager,
- router: SplitRouter<SplitId>,
- routes: SplitRoutesManifest
-) {
- return (content: SplitContent, options: OpenWithSplitOptions) => {
- const firstVisible = manager.getVisibleSplits()[0];
- const source =
- options.handle ??
- manager.activeSplit() ??
- (firstVisible ? manager.getSplit(firstVisible.id) : undefined);
- if (!source) return;
- const location = resolveContentLocation(routes, content);
- const path = `/${encodeRoute(routes, { location }).map(encodeURIComponent).join('/')}`;
- const query = new URLSearchParams();
- replaceSplitSearchParams(query, [{ location }]);
- let onApplied = options.onApplied;
- const reportApplied = () => {
- const callback = onApplied;
- onApplied = undefined;
- callback?.();
- };
- router.navigate(source.id, query.size ? `${path}?${query}` : path, {
- target:
- options.preferNewSplit && manager.canAppendSplit()
- ? 'new-split'
- : 'current',
- replace: options.mergeHistory,
- search: options.search,
- onApplied: reportApplied,
- open: (request) =>
- openAppSplitLocation(manager, routes, request, content, {
- ...options,
- onApplied: reportApplied,
- }),
- });
- };
-}
diff --git a/apps/web/src/components/app/split-layout/split-router/debug-routes.ts b/apps/web/src/components/app/split-layout/split-router/debug-routes.ts
deleted file mode 100644
index 52580516eb..0000000000
--- a/apps/web/src/components/app/split-layout/split-router/debug-routes.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { defineRoute } from '@app/lib/split-router';
-import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';
-import { lazy } from 'solid-js';
-
-const debugComponentIds = [
- 'ui',
- 'icon-gallery',
- ...(LOCAL_ONLY
- ? [
- 'theme-edit-3',
- 'theme-debug',
- 'core',
- 'md',
- 'data',
- 'chat',
- 'chat-attachment',
- 'chat-tool',
- 'http-stream',
- 'static-markdown-stream',
- 'resize',
- 'notifications-playground',
- 'props-debug',
- 'entity-debug',
- 'quick-access-list',
- 'hotkey-debugger',
- 'user-icon',
- 'dynamic-ui',
- 'agent-ui',
- 'agent-replay',
- 'agent-changes-ui',
- 'diff-view-ui',
- ]
- : []),
- ...(import.meta.env.DEV ? ['spreadsheet-demo'] : []),
- ...(DEV_MODE_ENV
- ? [
- 'document-where-playground',
- 'projection-playground',
- 'md-parse',
- 'md-builder',
- 'collab-surface-demo',
- ]
- : []),
-];
-
-/** Keep debug views behind the registry's lazy imports and environment gates. */
-export const debugRoutes = debugComponentIds.map((id) =>
- defineRoute({
- id: `view-${id}`,
- path: `debug/${id}`,
- aliases: [`component/${id}`],
- component: lazy(async () => {
- const { resolveComponent } = await import('../componentRegistry');
- return { default: () => resolveComponent(id).element() };
- }),
- search: '*' as const,
- externalSearch: id === 'ui' ? ['ui'] : [],
- claim: () => ({ namespace: 'component', id }),
- })
-);
diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
index 5c07018963..6db3512dd1 100644
--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts
@@ -12,7 +12,6 @@ import {
} from '@app/features/calendar-view/calendar-url';
import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
import { channelsSearch } from '@app/features/channels-view/channels-route';
-import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
import {
REMINDER_DETAIL_COMPONENT_ID,
REMINDER_DETAIL_ROUTE_ID,
@@ -20,21 +19,23 @@ import {
reminderIdFromDetailContent,
} from '@app/features/reminders/reminder-navigation';
import {
- defineRoute,
- routeParams,
- type SplitLocation,
- type SplitRouterEntry,
- type UnmatchedSplitPathHandler,
-} from '@app/lib/split-router';
+ NOT_FOUND_ROUTE_ID,
+ paneRootMatch,
+ paneRoute,
+} from '@app/routes/app-route';
import {
- assertRouteState,
- decodeRoute,
- encodeRoute,
+ canonicalRoute,
+ decodePane,
+ decodeSegment,
filterRouteSearch,
+ formatPanePath,
+ isRecord,
+ routeParams,
+ type SplitLocation,
type SplitRoutesManifest,
-} from '@app/lib/split-router/routes';
-import { parseSearchState } from '@app/lib/split-router/search';
-import { isRecord } from '@app/lib/split-router/utils';
+ type SplitSearchState,
+ splitPanePaths,
+} from '@app/split-router';
import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import type { BlockAlias, BlockName } from '@core/block';
@@ -44,10 +45,13 @@ import {
isBlockAlias,
resolveBlockAlias,
} from '@core/constant/allBlocks';
-import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';
-import { z } from 'zod';
import type { SplitContent } from '../layoutManager';
+type LegacySplitPathContext = {
+ segments: string[];
+ matchedRouteId?: string;
+};
+
export function decodeLegacyPair(
type: string,
id: string
@@ -95,60 +99,36 @@ export function decodeLegacyPair(
return { type: resolvedType, id };
}
-function legacyEntry(type: string, id: string): SplitRouterEntry | undefined {
+function legacyLocation(type: string, id: string): SplitLocation | undefined {
const agentsRoute = agentsRouteFromSegments(type, id);
if (agentsRoute) {
- return {
- location: {
- route: { matches: [{ id: type, params: { id } }] },
- },
- };
+ return { route: paneRoute({ id: type, params: { id } }) };
}
if (type === 'settings') {
- return {
- location: {
- route: { matches: [{ id: 'settings', params: { tab: id } }] },
- },
- };
+ return { route: paneRoute({ id: 'settings', params: { tab: id } }) };
}
if (type === 'component' && id === 'settings') {
- return {
- location: {
- route: { matches: [{ id: 'settings', params: { tab: 'account' } }] },
- },
- };
+ return { route: paneRoute({ id: 'settings', params: { tab: 'account' } }) };
}
if (type === 'component' && id === 'documents') {
- return {
- location: { route: { matches: [{ id: 'drive', params: {} }] } },
- };
+ return { route: paneRoute({ id: 'drive', params: {} }) };
}
if (!decodeLegacyPair(type, id)) return;
- return {
- location: {
- route: {
- matches: [{ id: 'legacy-content', params: { type, id } }],
- },
- },
- };
+ return { route: paneRoute({ id: 'legacy-content', params: { type, id } }) };
}
-export const handleLegacySplitPath: UnmatchedSplitPathHandler = (context) => {
+export function handleLegacySplitPath(
+ context: LegacySplitPathContext
+): SplitLocation[] | undefined {
const { segments } = context;
if (segments.length === 1 && ['documents', 'files'].includes(segments[0]!)) {
- return [
- {
- location: {
- route: { matches: [{ id: 'drive', params: {} }] },
- },
- },
- ];
+ return [{ route: paneRoute({ id: 'drive', params: {} }) }];
}
if (
@@ -161,7 +141,7 @@ export const handleLegacySplitPath: UnmatchedSplitPathHandler = (context) => {
}
if (segments.length < 2 || segments.length % 2 !== 0) return;
- const entries = [];
+ const locations = [];
for (let index = 0; index < segments.length; index += 2) {
if (
@@ -170,15 +150,50 @@ export const handleLegacySplitPath: UnmatchedSplitPathHandler = (context) => {
segments[index + 1] === 'non-member-channel')
)
continue;
- const entry = legacyEntry(segments[index]!, segments[index + 1]!);
+ const location = legacyLocation(segments[index]!, segments[index + 1]!);
- if (!entry) return;
+ if (!location) return;
- entries.push(entry);
+ locations.push(location);
}
- return entries;
-};
+ return locations;
+}
+
+/** One pane of an incoming path, as pane paths; old pair paths can expand into several panes. */
+function upgradeLegacyPane(
+ routes: SplitRoutesManifest,
+ raw: readonly string[]
+): string[] {
+ const unchanged = [raw.join('/')];
+ const segments = raw.map(decodeSegment);
+ const route = decodePane(routes, segments);
+ const matched =
+ route !== undefined && route.matches.at(-1)?.id !== NOT_FOUND_ROUTE_ID;
+ if (matched) return unchanged;
+
+ const upgraded = handleLegacySplitPath({ segments });
+ if (!upgraded?.length) return unchanged;
+
+ return upgraded.map((location) =>
+ formatPanePath(routes, location.route).slice(1)
+ );
+}
+
+/** Rewrites panes of an incoming path that no route matches, as the old URL format wrote them. */
+export function upgradeLegacyPath(
+ routes: SplitRoutesManifest,
+ path: string
+): string {
+ const panes = splitPanePaths(path);
+ const upgraded = panes.map((raw) => upgradeLegacyPane(routes, raw));
+ const changed = upgraded.some(
+ (paths, index) => paths.length !== 1 || paths[0] !== panes[index]!.join('/')
+ );
+ if (!changed) return path;
+
+ return `/${upgraded.flat().join('/~/')}`;
+}
export function encodeLegacyContent(content: SplitContent): string[] {
return [
@@ -199,9 +214,10 @@ export function splitLocationFromContent(
: undefined;
if (reminderId) {
return {
- route: {
- matches: [{ id: REMINDER_DETAIL_ROUTE_ID, params: { reminderId } }],
- },
+ route: paneRoute({
+ id: REMINDER_DETAIL_ROUTE_ID,
+ params: { reminderId },
+ }),
};
}
@@ -226,64 +242,51 @@ export function splitLocationFromContent(
})
);
return {
- route: {
- matches: [
- {
- id: CALENDAR_ROUTE_ID,
- params: { period: getPreferredCalendarPeriodView() },
- },
- ],
- },
+ route: paneRoute({
+ id: CALENDAR_ROUTE_ID,
+ params: { period: getPreferredCalendarPeriodView() },
+ }),
...(search ? { search: { [CALENDAR_SEARCH_NAMESPACE]: search } } : {}),
};
}
if (content.type === 'pr') {
return {
- route: {
- matches: [{ id: 'pr-detail', params: { foreignEntityId: content.id } }],
- },
+ route: paneRoute({
+ id: 'pr-detail',
+ params: { foreignEntityId: content.id },
+ }),
};
}
if (content.type === 'call') {
return {
- route: {
- matches: [{ id: 'call-detail', params: { callId: content.id } }],
- },
+ route: paneRoute({ id: 'call-detail', params: { callId: content.id } }),
};
}
if (content.type === 'component' && content.id === 'documents') {
- return { route: { matches: [{ id: 'drive', params: {} }] } };
+ return { route: paneRoute({ id: 'drive', params: {} }) };
}
if (content.type === 'component' && content.id === 'settings') {
- return {
- route: {
- matches: [{ id: 'settings', params: { tab: 'account' } }],
- },
- };
+ return { route: paneRoute({ id: 'settings', params: { tab: 'account' } }) };
}
if (content.type === 'component') {
const viewId = `view-${content.id}`;
if (routes.byId.has(viewId)) {
- return { route: { matches: [{ id: viewId, params: {} }] } };
+ return { route: paneRoute({ id: viewId, params: {} }) };
}
const segments = agentsRouteSegments(content.id);
const [section, id] = segments ?? [];
if (section && id) {
- return { route: { matches: [{ id: section, params: { id } }] } };
+ return { route: paneRoute({ id: section, params: { id } }) };
}
}
const [type, id] = encodeLegacyContent(content);
- return {
- route: {
- matches: [{ id: 'legacy-content', params: { type, id } }],
- },
- };
+ return { route: paneRoute({ id: 'legacy-content', params: { type, id } }) };
}
/** Resolve legacy/persisted metadata before it reaches router state. */
@@ -296,34 +299,26 @@ export function resolveContentLocation(
let metadataLocation = metadata;
if (isRecord(metadata?.location)) metadataLocation = metadata.location;
- const resolve = (route: unknown) => {
- assertRouteState(routes, route);
- // Go through the URL representation, not schema validation of schema outputs.
- const decoded = decodeRoute(
- routes,
- encodeRoute(routes, { location: { route } })
- );
- if (
- !decoded ||
- decoded.location.route.matches.length !== route.matches.length ||
- decoded.location.route.matches.some(
- (match, index) => match.id !== route.matches[index]!.id
- )
- ) {
+ // Go through the URL representation, not schema validation of schema outputs.
+ const resolve = (route: SplitLocation['route']) => {
+ const canonical = canonicalRoute(routes, route);
+ if (!canonical)
throw new Error('Split content did not resolve to its route');
- }
- return decoded.location.route;
+
+ return canonical;
};
let route: SplitLocation['route'] | undefined;
- if (metadataLocation?.route !== undefined) {
+ if (isRecord(metadataLocation?.route)) {
try {
- route = resolve(metadataLocation.route);
+ route = resolve(metadataLocation.route as SplitLocation['route']);
} catch {
// Old or malformed metadata falls back to the content's compatibility route.
}
}
route ??= resolve(splitLocationFromContent(routes, content).route);
- const savedSearch = parseSearchState(metadataLocation?.search);
+ const savedSearch = isRecord(metadataLocation?.search)
+ ? (metadataLocation.search as SplitSearchState)
+ : undefined;
// In-app message opens carry block params, not external URL query keys.
// Preserve the target before middleware upgrades the block to Chat, where
// the legacy block (and its imperative navigation handle) is replaced.
@@ -356,7 +351,11 @@ export function resolveContentLocation(
export function splitContentFromLocation(
location: SplitLocation
): SplitContent {
- const root = location.route.matches[0];
+ const root = paneRootMatch(location.route);
+
+ if (!root || root.id === NOT_FOUND_ROUTE_ID) {
+ return { type: 'component', id: NOT_FOUND_ROUTE_ID };
+ }
if (root.id === REMINDER_DETAIL_ROUTE_ID) {
const { reminderId } = routeParams(location.route);
@@ -406,41 +405,3 @@ export function splitContentFromLocation(
throw new Error(`No split content matched route "${root.id}"`);
}
-
-export const legacySplitRoute = defineRoute({
- id: 'legacy-content',
- path: ':type/:id',
- search: '*',
- params: z
- .object({ type: z.string().min(1), id: z.string().min(1) })
- .refine(({ type, id }) => decodeLegacyPair(type, id) !== undefined),
- externalSearch: (entry) => {
- const { type } = routeParams(entry.location.route);
- if (type === 'email') return Object.values(EMAIL_URL_PARAMS);
- if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);
- if (type === 'company' || type === 'contact') return [COMMENT_LINK_PARAM];
- return [];
- },
- claim: ({ type, id }) => {
- const content = decodeLegacyPair(type, id);
- if (!content) return;
-
- if (content.type === 'agent') return { namespace: 'agent', id };
-
- if (content.type === 'component') {
- const [section, conversationId] = agentsRouteSegments(content.id) ?? [];
- if (section && conversationId) {
- return {
- namespace: section === 'agent-chats' ? 'chat' : 'agent',
- id: conversationId,
- };
- }
- return { namespace: 'component', id: content.id };
- }
-
- return {
- namespace: 'block',
- id: `${content.aliasContext?.baseType ?? content.type}:${id}`,
- };
- },
-});
diff --git a/apps/web/src/components/app/split-layout/split-router/mention-links.ts b/apps/web/src/components/app/split-layout/split-router/mention-links.ts
index 8328cf00e1..8a90890cfe 100644
--- a/apps/web/src/components/app/split-layout/split-router/mention-links.ts
+++ b/apps/web/src/components/app/split-layout/split-router/mention-links.ts
@@ -3,14 +3,15 @@ import {
BlockRegistry,
} from '@app/lib/constants/block-registry';
import {
- decodeRouteLayout,
- getExternalSearchKeys,
- parseRoutePathname,
- SPLIT_PATH_SEPARATOR,
+ decodePane,
+ decodeSegment,
+ type Entry,
+ externalSearchKeys,
type SplitReference,
type SplitRoutesManifest,
+ splitPanePaths,
useOptionalSplitRouter,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import type { BlockAlias, BlockName } from '@core/block';
import { parseInternalAppLink } from '@core/util/macroAppUrl';
import { z } from 'zod';
@@ -55,18 +56,18 @@ export function createMacroMentionLinkResolver(
const link = parseInternalAppLink(url);
if (!link) return;
- const segments = parseRoutePathname(routes, link.path);
- if (!segments) return;
- const entries = decodeRouteLayout(routes, segments);
- const paneCount =
- segments.filter((segment) => segment === SPLIT_PATH_SEPARATOR).length + 1;
- if (entries.length !== paneCount) return;
+ const panes = splitPanePaths(link.path).map((raw) =>
+ decodePane(routes, raw.map(decodeSegment))
+ );
+ const everyPaneMatched = panes.every((route) => route !== undefined);
+ if (!everyPaneMatched) return;
// A copied layout URL lists panes from left to right without an active-pane id.
- const entry = entries.at(-1);
- if (!entry) return;
+ const route = panes.at(-1);
+ if (!route) return;
- const leaf = entry.location.route.matches.at(-1);
+ const leaf = route.matches.at(-1);
if (!leaf) return;
+
const reference = routes.byId
.get(leaf.id)
?.definition.toReference?.(leaf.params);
@@ -76,7 +77,8 @@ export function createMacroMentionLinkResolver(
block: reference.type,
params: {},
};
- const externalKeys = getExternalSearchKeys(routes, [entry]);
+ const entry: Entry = { id: 'mention', location: { route } };
+ const externalKeys = new Set(externalSearchKeys(routes, [entry]));
new URLSearchParams(link.query).forEach((value, key) => {
if (key !== 'referral_code' && externalKeys.has(key)) {
mention.params[key] = value;
diff --git a/apps/web/src/components/app/split-layout/splitRouterLayout.ts b/apps/web/src/components/app/split-layout/splitRouterLayout.ts
deleted file mode 100644
index 318314c3c9..0000000000
--- a/apps/web/src/components/app/split-layout/splitRouterLayout.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import type {
- BrowserHistoryIntent,
- SplitRouterEntry,
- SplitRouterLayout,
- SplitRouterLayoutSnapshot,
- SplitRoutesManifest,
-} from '@app/lib/split-router';
-import deepEqual from 'fast-deep-equal';
-import { createEffect, createRoot, on } from 'solid-js';
-import type {
- OpenWithSplitOptions,
- SplitContent,
- SplitId,
- SplitManager,
-} from './layoutManager';
-import {
- resolveContentLocation,
- splitContentFromLocation,
-} from './split-router/legacy-route';
-
-export type AppSplitRouterLayout = SplitRouterLayout<SplitId>;
-type AppSplitRouterSnapshot = SplitRouterLayoutSnapshot<SplitId>;
-
-function contentForLocation(
- location: SplitRouterEntry['location'],
- current?: SplitContent
-): SplitContent {
- const routed = splitContentFromLocation(location);
- let source = routed;
- if (current?.type === routed.type && current.id === routed.id) {
- source = current;
- }
- const { entryMetadata: _entryMetadata, ...content } = source;
-
- return { ...content, entryMetadata: location };
-}
-
-const sameRouterEntries = (
- previous: AppSplitRouterSnapshot['entries'],
- current: AppSplitRouterSnapshot['entries']
-) =>
- previous.length === current.length &&
- previous.every((entry, index) => {
- const next = current[index];
-
- if (!next) return false;
- if (!Object.is(entry.splitId, next.splitId)) return false;
- return deepEqual(entry.location, next.location);
- });
-
-function changeHistory(
- manager: SplitManager,
- previous: SplitRouterEntry[],
- next: SplitRouterEntry[]
-): BrowserHistoryIntent {
- const index = next.findIndex((entry, entryIndex) => {
- const before = previous[entryIndex];
- return !before || !deepEqual(before.location.route, entry.location.route);
- });
-
- if (index < 0) return 'push';
-
- const changed = manager.getVisibleSplits()[index];
-
- return changed?.lastNavigationCause === 'replace' ? 'replace' : 'push';
-}
-
-export function openAppSplitLocation(
- manager: SplitManager,
- routes: SplitRoutesManifest,
- { location, target, replace }: Parameters<AppSplitRouterLayout['open']>[0],
- source?: SplitContent,
- options: OpenWithSplitOptions = {}
-): ReturnType<AppSplitRouterLayout['open']> {
- let handle: ReturnType<SplitManager['getSplit']>;
- if (target && target !== 'new-split') {
- handle = manager.getSplit(target);
- }
-
- const result = manager.openWithSplit(
- {
- ...contentForLocation(location, source),
- ...(source?.state && { state: source.state }),
- },
- {
- ...options,
- search: undefined,
- handle,
- preferNewSplit: target === 'new-split',
- allowDuplicate: options.allowDuplicate || target === 'new-split',
- mergeHistory: replace,
- referredFrom: options.referredFrom ?? null,
- }
- );
- if (!result.split) return { status: 'unavailable' };
-
- const appliedLocation = resolveContentLocation(
- routes,
- result.split.content()
- );
- if (!deepEqual(appliedLocation, location)) {
- if (!deepEqual(appliedLocation.route, location.route)) {
- result.split.captureEntryState();
- }
- result.split.updateCurrentEntry((content) =>
- contentForLocation(location, content)
- );
- }
- // Native forward animation prepares an excluded pane first. Its eventual
- // promotion publishes the accepted location through the layout subscription.
- if (
- !manager.getVisibleSplits().some((split) => split.id === result.split?.id)
- ) {
- return { status: 'unavailable' };
- }
- return { status: 'applied', splitId: result.split.id };
-}
-
-export function createAppSplitRouterLayout(
- manager: SplitManager,
- routes: SplitRoutesManifest
-): AppSplitRouterLayout {
- const snapshot = (): AppSplitRouterSnapshot => ({
- entries: manager.getVisibleSplits().map((split) => ({
- splitId: split.id,
- location: resolveContentLocation(routes, split.content),
- })),
- });
-
- return {
- snapshot,
-
- updateCurrentLocation(splitId, update, replace) {
- const handle = manager.getSplit(splitId);
-
- if (!handle) return;
-
- const current = resolveContentLocation(routes, handle.content());
- const next = update({ splitId, location: current });
- const content = contentForLocation(next, handle.content());
- const existing = handle.content();
- if (existing.type !== content.type || existing.id !== content.id) {
- handle.replace({ next: content, mergeHistory: replace });
- return;
- }
-
- // Child routes keep the workspace mounted but can dispose its list.
- // Capture list focus/scroll before committing that accepted transition.
- if (!deepEqual(current.route, next.route)) {
- handle.captureEntryState();
- }
- handle.updateCurrentEntry((currentContent) =>
- contentForLocation(next, currentContent)
- );
- },
-
- open: (request) => openAppSplitLocation(manager, routes, request),
-
- reconcile(locations) {
- for (const [index, split] of manager.getVisibleSplits().entries()) {
- if (
- !deepEqual(
- resolveContentLocation(routes, split.content).route,
- locations[index]?.route
- )
- ) {
- manager.getSplit(split.id)?.captureEntryState();
- }
- }
- const visible = manager.getVisibleSplits();
- manager.reconcile(
- locations.map((location, index) =>
- contentForLocation(location, visible[index]?.content)
- )
- );
- },
-
- activate(splitId) {
- manager.getSplit(splitId)?.activate();
- },
-
- subscribe(listener) {
- return createRoot((dispose) => {
- let previous = snapshot().entries;
- createEffect(
- on(
- () => manager.getVisibleSplits(),
- () => {
- const current = snapshot().entries;
- if (sameRouterEntries(previous, current)) return;
-
- listener({
- history: changeHistory(manager, previous, current),
- });
- previous = current;
- },
- { defer: true }
- )
- );
-
- return dispose;
- });
- },
- };
-}
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
index 8005e752a1..b200f49c01 100644
--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
@@ -27,9 +27,9 @@ vi.mock('@service-connection/websocket', () => ({
createConnectionBlockWebsocketEffect: vi.fn(),
createConnectionWebsocketEffect: vi.fn(),
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
- useSplitRouter: () => ({ location: () => undefined }),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
+ useSplitRouter: () => ({ entry: () => undefined }),
}));
vi.mock('@core/auth', () => ({
useIsAuthenticated: () => () => state.authenticated(),
diff --git a/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts
deleted file mode 100644
index c3b232bece..0000000000
--- a/apps/web/src/components/app/split-layout/tests/app-route-isolation.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import {
- createRoutesManifest,
- decodeRoute,
- encodeRoute,
-} from '@app/lib/split-router/routes';
-import { describe, expect, it, vi } from 'vitest';
-import { appSplitRoutes } from '../split-router/app-routes';
-
-vi.mock('@service-storage/websocket', () => ({
- storageWS: { reconnectIfDisconnected: vi.fn() },
- createWebSocketJob: vi.fn(),
-}));
-vi.mock('@service-connection/websocket', () => ({
- ws: { addEventListener: vi.fn(), send: vi.fn() },
- state: () => 'closed',
- createConnectionBlockWebsocketEffect: vi.fn(),
- createConnectionWebsocketEffect: vi.fn(),
-}));
-
-vi.mock('@app/features/activity/views/my-activity-view', () => {
- throw new Error('Route declarations must not eagerly load activity views');
-});
-vi.mock('../componentRegistry', () => {
- throw new Error('Route declarations must not eagerly load the registry');
-});
-vi.mock('@app/features/agents-view/views/AgentsView', () => {
- throw new Error('Route declarations must not eagerly load agent views');
-});
-vi.mock('@app/features/getting-started', () => {
- throw new Error('Route declarations must not eagerly load onboarding views');
-});
-vi.mock('@app/features/next-soup/soup-view/soup-view', () => {
- throw new Error('Route declarations must not eagerly load Soup views');
-});
-vi.mock('@app/features/settings/Settings', () => {
- throw new Error('Route declarations must not eagerly load settings views');
-});
-
-describe('application route import isolation', () => {
- it('routes debug views and canonicalizes their legacy URLs', () => {
- const routes = createRoutesManifest(appSplitRoutes);
- for (const id of ['ui', 'icon-gallery']) {
- const route = decodeRoute(routes, ['debug', id]);
- expect(route?.location.route.matches[0].id).toBe(`view-${id}`);
- const legacy = decodeRoute(routes, ['component', id]);
- expect(legacy).toEqual(route);
- expect(encodeRoute(routes, legacy!)).toEqual(['debug', id]);
- }
- });
-
- it('builds and decodes routes without initializing remaining lazy view modules', () => {
- const routes = createRoutesManifest(appSplitRoutes);
- for (const path of [
- ['mail'],
- ['tasks'],
- ['settings', 'account'],
- ['drive', 'md', 'doc'],
- ['calendar', 'week'],
- ['channels', 'channel-id'],
- ]) {
- expect(decodeRoute(routes, path)).toBeDefined();
- }
- expect(decodeRoute(routes, ['channels', 'channel', 'channel-id'])).toBe(
- undefined
- );
- });
-});
diff --git a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
deleted file mode 100644
index c137c0b064..0000000000
--- a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import {
- createRoutesManifest,
- getRouteClaim,
-} from '@app/lib/split-router/routes';
-import {
- decodeSplitRouterLocation,
- serializeSplitRouterLocation,
-} from '@app/lib/split-router/url';
-import { describe, expect, it, vi } from 'vitest';
-import { appSplitRoutes } from '../split-router/app-routes';
-import { createMacroMentionLinkResolver } from '../split-router/mention-links';
-
-vi.mock('@service-storage/websocket', () => ({
- storageWS: { reconnectIfDisconnected: vi.fn() },
- createWebSocketJob: vi.fn(),
-}));
-vi.mock('@service-connection/websocket', () => ({
- ws: { addEventListener: vi.fn(), send: vi.fn() },
- state: () => 'closed',
- createConnectionBlockWebsocketEffect: vi.fn(),
- createConnectionWebsocketEffect: vi.fn(),
-}));
-
-const routes = createRoutesManifest(appSplitRoutes);
-const viewerState = 's0.changes.pane=split';
-
-function roundTrip(pathname: string, search: string, committed: boolean) {
- const location = { pathname, search: `?${search}`, hash: '' };
- const { entries } = decodeSplitRouterLocation({ routes, location });
- return serializeSplitRouterLocation({
- routes,
- entries,
- previous: location,
- // A layout change commits without the inbound query; only globally owned
- // keys survive it.
- preserveExternalSearch: !committed,
- });
-}
-
-describe('application route search ownership', () => {
- it.each([
- '/drive/spreadsheet/sheet-1',
- '/drive/folder/folder-1/spreadsheet/sheet-1',
- '/drive/recent/spreadsheet/sheet-1',
- ])('preserves spreadsheet comment targets on %s', (pathname) => {
- expect(roundTrip(pathname, 'comment_id=message-1', false)).toContain(
- 'comment_id=message-1'
- );
- });
-
- it.each([
- ['/agents/session-1', 'the agents workspace'],
- ['/coders/session-1', 'a coding session'],
- ['/agent/session-1', 'the agent block'],
- ['/reviews/pr/pr-1', 'a pull request in Reviews'],
- ['/pr/pr-1', 'a standalone pull request'],
- ])('keeps the changes pane state on %s (%s)', (pathname) => {
- expect(roundTrip(pathname, viewerState, false)).toContain(viewerState);
- expect(roundTrip(pathname, viewerState, true)).toContain(viewerState);
- });
-
- it('drops the changes pane state of a split whose route does not own it', () => {
- const result = roundTrip(
- '/agents/session-1/~/reviews',
- 's0.changes.pane=split&s1.changes.pane=full',
- true
- );
- expect(result).toContain('s0.changes.pane=split');
- expect(result).not.toContain('s1.changes');
- });
-
- it('drops search keys no route owns', () => {
- expect(roundTrip('/agents/session-1', 'unowned=1', true)).not.toContain(
- 'unowned'
- );
- });
-});
-
-const mentionId = '019507e8-14a3-7bc1-8610-419f16bd03a8';
-const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';
-const resolveMention = createMacroMentionLinkResolver(routes);
-
-describe('application route mentions', () => {
- it('preserves spreadsheet comment targets in Drive links', () => {
- expect(
- resolveMention(
- `https://dev.macro.com/app/drive/spreadsheet/${mentionId}?comment_id=message-1`
- )
- ).toEqual({
- id: mentionId,
- block: 'spreadsheet',
- params: { comment_id: 'message-1' },
- });
- });
-
- it('preserves task comment targets in both task contexts', () => {
- for (const path of [
- `tasks/${mentionId}`,
- `tasks/projects/${projectId}/tasks/task/${mentionId}`,
- ]) {
- expect(
- resolveMention(
- `https://dev.macro.com/app/${path}?comment_id=comment&referral_code=ignored&unknown=drop`
- )
- ).toEqual({
- id: mentionId,
- block: 'task',
- params: { comment_id: 'comment' },
- });
- }
- });
-
- it('converts Home PR links with foreign entity IDs', () => {
- const id = 'macro-inc/macro/pull/6303';
- expect(
- resolveMention(
- `https://dev.macro.com/app/home/pr/${encodeURIComponent(id)}`
- )
- ).toEqual({ id, block: 'pr', params: {} });
- });
-
- it('converts agent chats and coding sessions', () => {
- expect(
- resolveMention(`https://dev.macro.com/app/agents/chat/${mentionId}`)
- ).toEqual({ id: mentionId, block: 'chat', params: {} });
- expect(
- resolveMention(`https://dev.macro.com/app/coders/${mentionId}`)
- ).toEqual({ id: mentionId, block: 'agent', params: {} });
- });
-
- it('uses the rightmost pane of a copied layout URL', () => {
- expect(
- resolveMention(
- `https://dev.macro.com/app/home/~/drive/md/${mentionId}?comment_id=comment`
- )
- ).toEqual({
- id: mentionId,
- block: 'md',
- params: { comment_id: 'comment' },
- });
- expect(
- resolveMention(
- `https://dev.macro.com/app/md/${mentionId}/~/drive/md/${mentionId}`
- )
- ).toEqual({ id: mentionId, block: 'md', params: {} });
- expect(
- resolveMention(
- `https://dev.macro.com/app/not-a-route/~/drive/md/${mentionId}`
- )
- ).toBeUndefined();
- expect(
- resolveMention(
- `https://dev.macro.com/app/drive/md/${mentionId}/~/reviews`
- )
- ).toBeUndefined();
- });
-
- it('treats a routed project and the initiative block as one entity', () => {
- const claim = (pathname: string) => {
- const { entries } = decodeSplitRouterLocation({
- routes,
- location: { pathname, search: '', hash: '' },
- });
- return getRouteClaim(routes, entries[0]!.location.route);
- };
- expect(claim(`/tasks/projects/${projectId}/overview`)).toEqual(
- claim(`/initiative/${projectId}`)
- );
- expect(
- resolveMention(
- `https://dev.macro.com/app/tasks/projects/${projectId}/overview`
- )
- ).toEqual({ id: projectId, block: 'initiative', params: {} });
- });
-
- it('leaves unsupported and invalid destinations as links', () => {
- expect(resolveMention('https://dev.macro.com/app/reviews')).toBeUndefined();
- expect(
- resolveMention('https://dev.macro.com/app/tasks/not-a-uuid')
- ).toBeUndefined();
- });
-});
diff --git a/apps/web/src/components/app/split-layout/tests/fixtures.ts b/apps/web/src/components/app/split-layout/tests/fixtures.ts
new file mode 100644
index 0000000000..92c1888667
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/fixtures.ts
@@ -0,0 +1,71 @@
+import { paneRoute } from '@app/routes/app-route';
+import {
+ appRoute,
+ channelDetailRoute,
+ channelsSplitRoute,
+ homeSplitRoute,
+ legacyContentRoute,
+ notFoundRoute,
+} from '@app/routes/routes';
+import {
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
+ type Entry,
+ type SplitLocation,
+ type SplitRoutes,
+} from '@app/split-router';
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { createSplitLayout, type SplitManager } from '../layoutManager';
+import { createAppPanePolicy } from '../split-router/app-pane-policy';
+import {
+ resolveContentLocation,
+ splitContentFromLocation,
+} from '../split-router/legacy-route';
+
+const homeLocation: SplitLocation = {
+ route: paneRoute({ id: 'view-home', params: {} }),
+};
+
+const routes: SplitRoutes = {
+ definitions: [
+ {
+ ...appRoute,
+ children: [
+ homeSplitRoute,
+ { ...channelsSplitRoute, children: [channelDetailRoute] },
+ legacyContentRoute,
+ notFoundRoute,
+ ],
+ },
+ ],
+ defaultRoute: () => homeLocation.route,
+};
+
+/**
+ * A split manager over a router with a few of the app's pane routes, loaded
+ * from `url` (panes joined by `/~/`). Call it inside a reactive root.
+ */
+export function createRoutedSplitLayout(
+ orchestrator: BlockOrchestrator,
+ url: string
+): SplitManager {
+ let manager: SplitManager | undefined;
+ const router = createSplitRouter({
+ routes,
+ history: createMemoryHistory(url),
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy: createAppPanePolicy({
+ manager: () => manager,
+ toContent: splitContentFromLocation,
+ defaultLocation: () => homeLocation,
+ singlePane: () => false,
+ }),
+ });
+ manager = createSplitLayout(orchestrator, {
+ router,
+ toLocation: (content) => resolveContentLocation(router.routes, content),
+ toContent: splitContentFromLocation,
+ });
+ return manager;
+}
diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
deleted file mode 100644
index 7b1a9d69a2..0000000000
--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts
+++ /dev/null
@@ -1,3499 +0,0 @@
-import { agentsRouteId } from '@app/features/agents-view/core/route';
-import { CALENDAR_PREFERENCES_KEY } from '@app/features/calendar/calendar-preferences';
-import { driveHostedContent } from '@app/features/drive-view/drive-hosted-content';
-import { driveDestination } from '@app/features/drive-view/drive-route-navigation';
-import { driveSplitRoute } from '@app/features/drive-view/route';
-import {
- emailSplitRoute,
- emailThreadRoute,
-} from '@app/features/email-view/route';
-import { searchLocationUpdates } from '@app/features/next-soup/search-navigation';
-import {
- reminderDetailContent,
- reminderIdFromDetailContent,
-} from '@app/features/reminders/reminder-navigation';
-import { reviewsHostedContent } from '@app/features/reviews-view/reviews-hosted-content';
-import { reviewsSplitRoute } from '@app/features/reviews-view/route';
-import {
- getListNavigationSource,
- listNavigationSourceId,
- registerListNavigationSource,
- withListNavigationSource,
-} from '@app/features/soup/collection/list-navigation-source';
-import {
- taskDetailRoute,
- tasksSplitRoute,
-} from '@app/features/tasks-view/route';
-import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
-import { createSplitRouter } from '@app/lib/split-router/router';
-import { createRoutesManifest } from '@app/lib/split-router/routes';
-import type { ResizeZoneCtx } from '@core/component/Resize/types';
-import { toast } from '@core/component/Toast/Toast';
-import type { BlockOrchestrator } from '@core/orchestrator';
-import type { SearchLocation } from '@entity';
-import { createMemo, createRoot, createSignal } from 'solid-js';
-import { beforeAll, describe, expect, it, vi } from 'vitest';
-import { contentReference } from '../content-reference';
-import {
- createSplitLayout,
- type SplitContent,
- SplitEvent,
-} from '../layoutManager';
-import {
- closeSplitOrReturnToList,
- shouldShowSplitCloseButton,
-} from '../layoutUtils';
-import { createMobileSwipeLayout } from '../mobile/createMobileSwipeLayout';
-import { createAppSplitRouterMiddleware } from '../split-router/app-middleware';
-import { appSplitRoutes } from '../split-router/app-routes';
-import { createContentNavigator } from '../split-router/content-navigation';
-import { decodeLegacyPair } from '../split-router/legacy-route';
-import { createAppSplitRouterLayout } from '../splitRouterLayout';
-
-// Settings UI imports the app route registry and is unrelated to layout behavior.
-vi.mock('@core/constant/SettingsState', () => ({
- useSettingsState: vi.fn(),
-}));
-
-// The route graph imports websocket clients; jsdom cannot open their sockets.
-vi.mock('@service-storage/websocket', () => ({
- storageWS: { reconnectIfDisconnected: vi.fn() },
- createWebSocketJob: vi.fn(),
-}));
-vi.mock('@service-connection/websocket', () => ({
- ws: { addEventListener: vi.fn(), send: vi.fn() },
- state: () => 'closed',
- createConnectionBlockWebsocketEffect: vi.fn(),
- createConnectionWebsocketEffect: vi.fn(),
-}));
-
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { alert: vi.fn() },
-}));
-
-vi.mock('../componentRegistry', () => ({
- resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({
- type: 'mock-component',
- id,
- params,
- })),
-}));
-
-beforeAll(() => {
- // Mock window.matchMedia for tests
- Object.defineProperty(window, 'matchMedia', {
- writable: true,
- value: (query: string) => ({
- matches: false,
- media: query,
- onchange: null,
- addListener: () => {},
- removeListener: () => {},
- addEventListener: () => {},
- removeEventListener: () => {},
- dispatchEvent: () => true,
- }),
- });
-});
-
-function createMockOrchestrator(): BlockOrchestrator {
- return {
- isBlockMounted: vi.fn(() => false),
- createBlockInstance: vi.fn((_type, id, _splitId) => ({
- node: { type: 'mock-node', id },
- detach: vi.fn(),
- dispose: vi.fn(),
- })),
- rekeyBlockInstance: vi.fn(),
- } as unknown as BlockOrchestrator;
-}
-
-describe('layoutManager', () => {
- it('tracks content navigator replacement as a reactive host lifecycle', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- expect(manager.contentNavigationReady()).toBe(false);
- expect(manager.contentNavigationVersion()).toBe(0);
- manager.setContentNavigator(() => {});
- expect(manager.contentNavigationReady()).toBe(true);
- expect(manager.contentNavigationVersion()).toBe(1);
- manager.setContentNavigator(() => {});
- expect(manager.contentNavigationVersion()).toBe(2);
- manager.setContentNavigator(undefined);
-
- expect(manager.contentNavigationReady()).toBe(false);
- expect(manager.contentNavigationVersion()).toBe(3);
- dispose();
- });
- });
-
- describe('header close action', () => {
- it.each([false, true])(
- 'returns the sole visible split to its prior list (excluded background: %s)',
- (withBackground) => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- const list: SplitContent = {
- type: 'component',
- id: 'tasks',
- state: { filter: 'assigned' },
- };
- split.replace({ next: list });
- split.replace({ next: { type: 'md', id: 'doc-1' } });
- split.replace({ next: { type: 'md', id: 'doc-2' } });
- if (withBackground) {
- const background = manager.createNewSplit({
- content: { type: 'md', id: 'background' },
- activate: false,
- referredFrom: null,
- })!;
- manager.setExclusionFilter((entry) => entry.id === background.id);
- }
-
- closeSplitOrReturnToList(manager, split);
-
- expect(manager.getVisibleSplitCount()).toBe(1);
- expect(manager.splits()).toHaveLength(withBackground ? 2 : 1);
- expect(split.content()).toEqual(list);
- expect(split.canGoForward()).toBe(true);
- split.goBack();
- expect(split.content()).toEqual({ type: 'component', id: 'home' });
- dispose();
- });
- }
- );
-
- it('falls back to inbox without keeping the current detail as a Back entry', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'direct-link' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- closeSplitOrReturnToList(manager, split);
- expect(split.content()).toEqual({ type: 'component', id: 'home' });
- expect(split.canGoBack()).toBe(false);
- dispose();
- });
- });
-
- it('closes the panel when another visible split remains', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'detail' },
- { type: 'component', id: 'tasks' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- closeSplitOrReturnToList(manager, split);
- expect(manager.getSplit(split.id)).toBeUndefined();
- expect(manager.splits().map((entry) => entry.content.id)).toEqual([
- 'tasks',
- ]);
- dispose();
- });
- });
-
- it('leaves a sole list unchanged', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'tasks' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- closeSplitOrReturnToList(manager, split);
- expect(split.content()).toEqual({ type: 'component', id: 'tasks' });
- expect(manager.getVisibleSplitCount()).toBe(1);
- dispose();
- });
- });
- });
-
- it.each([true, false, undefined])(
- 'honors activate=%s when direct split creation finds an existing entity',
- (activate) => {
- createRoot((dispose) => {
- const content = { type: 'email', id: 'already-open' } as const;
- const manager = createSplitLayout(createMockOrchestrator(), [
- content,
- { type: 'component', id: 'home' },
- ]);
- const [existing, other] = manager.splits();
- manager.activateSplit(other.id);
- vi.mocked(toast.alert).mockClear();
-
- const result = manager.createNewSplit({
- content,
- activate,
- allowDuplicate: true,
- referredFrom: 'sidebar',
- });
-
- expect(result?.id).toBe(existing.id);
- expect(manager.splits()).toHaveLength(2);
- expect(manager.activeSplitId()).toBe(activate ? existing.id : other.id);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- }
- );
-
- it.each([
- { mode: 'chat', type: 'agent_session', block: 'agent' },
- { mode: 'code', type: 'agent_session', block: 'agent' },
- { mode: 'chat', type: 'chat', block: 'chat' },
- ] as const)(
- 'reuses $mode $type conversations across Agents routes and blocks',
- ({ mode, type, block }) => {
- const route: SplitContent = {
- type: 'component',
- id: agentsRouteId({ mode, conversation: { type, id: 'conversation' } }),
- };
- const entity: SplitContent = { type: block, id: 'conversation' };
- for (const [initial, target] of [
- [route, entity],
- [entity, route],
- ]) {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- initial,
- { type: 'component', id: 'home' },
- ]);
- const [existing, other] = manager.splits();
- const mount = existing.mount;
- expect(manager.getSplitByContent(target.type, target.id)?.id).toBe(
- existing.id
- );
-
- manager.activateSplit(other.id);
- const view = manager.findOpenView(target);
- expect(view?.owner).toBe(existing.id);
- expect(view?.topLevelSplit?.id).toBe(existing.id);
- expect(view?.content).toEqual(entity);
- expect(manager.activeSplitId()).toBe(other.id);
- const direct = manager.createNewSplit({
- content: target,
- activate: true,
- allowDuplicate: true,
- referredFrom: 'sidebar',
- });
- expect(direct?.id).toBe(existing.id);
- expect(manager.activeSplitId()).toBe(existing.id);
-
- manager.activateSplit(other.id);
- vi.mocked(toast.alert).mockClear();
- const opened = manager.openWithSplit(target, {
- activate: true,
- allowDuplicate: true,
- handle: manager.getSplit(other.id),
- });
- expect(opened).toMatchObject({
- status: 'reused',
- owner: existing.id,
- sourceOwner: other.id,
- });
- expect(opened.split?.id).toBe(existing.id);
- expect(manager.activeSplitId()).toBe(existing.id);
- expect(manager.splits()).toHaveLength(2);
- expect(existing.mount).toBe(mount);
- expect(existing.content).toEqual(initial);
- expect(other.content).toEqual({ type: 'component', id: 'home' });
- expect(toast.alert).not.toHaveBeenCalled();
-
- manager.openWithSplit(target);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- }
- }
- );
-
- it('reports reuse even when the owning view has no activation target', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'component', id: 'home' },
- ]);
- const release = manager.registerOpenViews(() => [
- {
- owner: 'preview',
- content: { type: 'channel', id: 'preview-channel' },
- },
- ]);
-
- vi.mocked(toast.alert).mockClear();
- expect(
- manager.openWithSplit(
- { type: 'channel', id: 'preview-channel' },
- { preferNewSplit: true }
- )
- ).toMatchObject({ status: 'reused', owner: 'preview' });
- expect(manager.splits()).toHaveLength(1);
- expect(orchestrator.createBlockInstance).not.toHaveBeenCalled();
- expect(toast.alert).not.toHaveBeenCalled();
-
- manager.openWithSplit(
- { type: 'channel', id: 'preview-channel' },
- { preferNewSplit: true }
- );
- expect(manager.splits()).toHaveLength(1);
- expect(orchestrator.createBlockInstance).not.toHaveBeenCalled();
- expect(toast.alert).not.toHaveBeenCalled();
-
- release();
- manager.openWithSplit(
- { type: 'channel', id: 'preview-channel' },
- { preferNewSplit: true }
- );
- expect(manager.splits()).toHaveLength(2);
- expect(orchestrator.createBlockInstance).toHaveBeenCalledOnce();
- dispose();
- });
- });
-
- it.each([
- {
- name: 'channel',
- content: { type: 'channel', id: 'conversation' },
- target: { type: 'channel', id: 'conversation' },
- },
- ...(
- [
- { mode: 'chat', type: 'agent_session', block: 'agent' },
- { mode: 'code', type: 'agent_session', block: 'agent' },
- { mode: 'chat', type: 'chat', block: 'chat' },
- ] as const
- ).map(({ mode, type, block }) => ({
- name: `${mode} ${type}`,
- content: { type: block, id: 'conversation' },
- target: {
- type: 'component' as const,
- id: agentsRouteId({ mode, conversation: { type, id: 'conversation' } }),
- },
- })),
- ] satisfies { name: string; content: SplitContent; target: SplitContent }[])(
- 'reports inline $name reuse without notifications',
- ({ content, target }) => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'component', id: 'channels' },
- { type: 'component', id: 'home' },
- ]);
- const [chat, inbox] = manager.splits();
- manager.activateSplit(inbox.id);
- const activate = vi.fn(() => manager.activateSplit(chat.id));
- manager.registerOpenViews(() => [
- { owner: 'preview', content, activate },
- ]);
- const intercept = vi.fn(() => ({ status: 'unavailable' as const }));
- manager.setSplitNavigationInterceptor(intercept);
-
- const view = manager.findOpenView(target);
- expect(view?.owner).toBe('preview');
- expect(view?.content).toEqual(content);
- expect(view?.topLevelSplit).toBeUndefined();
- expect(activate).not.toHaveBeenCalled();
-
- vi.mocked(toast.alert).mockClear();
- const result = manager.openWithSplit(target, {
- referredFrom: 'kommand-menu',
- });
- expect(result).toMatchObject({ status: 'reused', owner: 'preview' });
- expect(result.split).toBeUndefined();
- expect(activate).toHaveBeenCalledOnce();
- expect(manager.activeSplitId()).toBe(chat.id);
- expect(toast.alert).not.toHaveBeenCalled();
-
- vi.mocked(toast.alert).mockClear();
- manager.activateSplit(inbox.id);
- manager.openWithSplit(target);
- expect(activate).toHaveBeenCalledTimes(2);
- expect(manager.activeSplitId()).toBe(chat.id);
- expect(manager.splits()).toHaveLength(2);
- expect(orchestrator.createBlockInstance).not.toHaveBeenCalled();
- expect(toast.alert).not.toHaveBeenCalled();
-
- manager.activateSplit(inbox.id);
- manager.openWithSplit(target, { activate: false });
- expect(activate).toHaveBeenCalledTimes(2);
- expect(manager.activeSplitId()).toBe(inbox.id);
- expect(toast.alert).not.toHaveBeenCalled();
- expect(intercept).not.toHaveBeenCalled();
- dispose();
- });
- }
- );
-
- it('reports the owner when reusing a standalone split', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'channel', id: 'channel' },
- { type: 'component', id: 'home' },
- ]);
- const [channel, inbox] = manager.splits();
- manager.activateSplit(inbox.id);
- vi.mocked(toast.alert).mockClear();
- manager.openWithSplit(channel.content);
- expect(manager.activeSplitId()).toBe(channel.id);
- expect(toast.alert).not.toHaveBeenCalled();
- vi.mocked(toast.alert).mockClear();
- manager.activateSplit(inbox.id);
- manager.openWithSplit(channel.content);
- expect(manager.activeSplitId()).toBe(channel.id);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- });
-
- it('finds an existing shell even when an open action allows duplicating it', () => {
- createRoot((dispose) => {
- const content = { type: 'component', id: 'channels' } as const;
- const manager = createSplitLayout(createMockOrchestrator(), [
- content,
- { type: 'component', id: 'home' },
- ]);
- const [channels, inbox] = manager.splits();
- manager.activateSplit(inbox.id);
- vi.mocked(toast.alert).mockClear();
-
- expect(manager.findOpenView(content)?.topLevelSplit?.id).toBe(
- channels.id
- );
- expect(manager.activeSplitId()).toBe(inbox.id);
- expect(toast.alert).not.toHaveBeenCalled();
-
- const duplicate = manager.openWithSplit(content, {
- preferNewSplit: true,
- allowDuplicate: true,
- });
- expect(duplicate.status).toBe('opened');
- expect(duplicate.split?.id).not.toBe(channels.id);
- expect(manager.splits()).toHaveLength(3);
- expect(manager.findOpenView(content)?.topLevelSplit?.id).toBe(
- channels.id
- );
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- });
-
- it('distinguishes opening new content from reusing content in the source split', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- const content = { type: 'email', id: 'selected' } as const;
- vi.mocked(toast.alert).mockClear();
- expect(manager.openWithSplit(content, { handle })).toMatchObject({
- status: 'opened',
- split: { id: handle.id },
- });
- expect(manager.openWithSplit(content, { handle })).toMatchObject({
- status: 'reused',
- owner: handle.id,
- sourceOwner: handle.id,
- split: { id: handle.id },
- });
- expect(handle.content()).toMatchObject(content);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- });
-
- it('restoring occupied content does not focus or notify its owner', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const source = manager.splits()[0];
- const content = { type: 'email', id: 'occupied' } as const;
- const activate = vi.fn();
- manager.registerOpenViews(() => [
- { owner: 'preview', content, activate },
- ]);
- vi.mocked(toast.alert).mockClear();
- manager.reconcile([content]);
- expect(manager.splits()[0].content).toEqual(source.content);
- expect(activate).not.toHaveBeenCalled();
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- });
-
- it('blocks detail-owned email through direct split creation, replacement, and history', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'email', id: 'one' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- handle.replace({ next: { type: 'email', id: 'two' } });
- const release = manager.registerOpenViews(() => [
- { owner: 'detail', content: { type: 'email', id: 'one' } },
- ]);
- expect(
- manager.createNewSplit({
- content: { type: 'email', id: 'one' },
- referredFrom: null,
- allowDuplicate: true,
- })
- ).toBeUndefined();
- handle.replace({ next: { type: 'email', id: 'one' } });
- handle.goBack();
- handle.removeFromHistory((content) => content.id === 'two');
- expect(handle.content().id).toBe('two');
- expect(handle.history()).toHaveLength(2);
- release();
- handle.goBack();
- expect(handle.content().id).toBe('one');
- dispose();
- });
- });
-
- it.each(['replace', 'adopt', 'replaceAll', 'popover'] as const)(
- '%s focuses an inline owner when it refuses duplicate content',
- (action) => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'email', id: 'pending' },
- { type: 'component', id: 'mail' },
- ]);
- const [source, host] = manager.splits();
- const handle = manager.getSplit(source.id)!;
- const target = { type: 'email', id: 'owned' } as const;
- manager.registerOpenViews(() => [
- {
- owner: 'detail',
- content: target,
- activate: () => manager.activateSplit(host.id),
- },
- ]);
- handle.activate();
- vi.mocked(toast.alert).mockClear();
-
- if (action === 'replace') handle.replace({ next: target });
- if (action === 'adopt')
- handle.adoptContentId({ type: 'email', nextId: target.id });
- if (action === 'replaceAll') manager.replaceAllSplits(target);
- if (action === 'popover')
- manager.createPopoverSplit({ content: target });
-
- expect(manager.activeSplitId()).toBe(host.id);
- expect(handle.content().id).toBe('pending');
- expect(handle.history()).toHaveLength(1);
- expect(manager.splits()).toHaveLength(2);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- }
- );
-
- it.each(['replace', 'adopt'] as const)(
- '%s focuses an existing block instead of mounting its Agents route',
- (action) => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'chat', id: 'conversation' },
- { type: 'component', id: 'agents' },
- ]);
- const [owner, source] = manager.splits();
- const handle = manager.getSplit(source.id)!;
- const route = agentsRouteId({
- mode: 'chat',
- conversation: { type: 'chat', id: 'conversation' },
- });
- const mount = source.mount;
- handle.activate();
- if (action === 'replace')
- handle.replace({ next: { type: 'component', id: route } });
- else handle.adoptContentId({ type: 'component', nextId: route });
- expect(manager.activeSplitId()).toBe(owner.id);
- expect(handle.content().id).toBe('agents');
- expect(manager.splits()[1].mount).toBe(mount);
- expect(orchestrator.createBlockInstance).toHaveBeenCalledTimes(1);
- dispose();
- });
- }
- );
-
- it('exposes split ownership before block mount and releases it on close', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'email', id: 'one' },
- ]);
- expect(
- manager.findOpenView({
- type: 'email',
- id: 'one',
- })
- ).toBeDefined();
- manager.removeSplit(manager.splits()[0].id);
- expect(
- manager.findOpenView({
- type: 'email',
- id: 'one',
- })
- ).toBeUndefined();
- dispose();
- });
- });
-
- it('scopes content ownership to the layout even when an orchestrator is shared', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const content = { type: 'channel', id: 'channel' } as const;
- const first = createSplitLayout(orchestrator, [content]);
- const second = createSplitLayout(orchestrator, []);
-
- expect(first.findOpenView(content)).toBeDefined();
- expect(second.findOpenView(content)).toBeUndefined();
-
- dispose();
- expect(first.findOpenView(content)).toBeUndefined();
- });
- });
-
- it('navigates and closes adjacent list and detail splits independently', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'md', id: 'detail' },
- ]);
- const [list, detail] = manager.splits();
- const listHandle = manager.getSplit(list.id)!;
- const detailHandle = manager.getSplit(detail.id)!;
-
- manager.openWithSplit(
- { type: 'email', id: 'thread' },
- { handle: listHandle }
- );
- expect(listHandle.content()).toEqual({ type: 'email', id: 'thread' });
- expect(detailHandle.content()).toEqual({ type: 'md', id: 'detail' });
- expect(manager.splits()).toHaveLength(2);
-
- listHandle.goBack();
- expect(listHandle.content()).toEqual({ type: 'component', id: 'home' });
- expect(detailHandle.content()).toEqual({ type: 'md', id: 'detail' });
- listHandle.close();
- expect(manager.splits().map((split) => split.id)).toEqual([detail.id]);
- dispose();
- });
- });
-
- it('navigates and closes adjacent list and detail splits independently', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'md', id: 'detail' },
- ]);
- const [list, detail] = manager.splits();
- const listHandle = manager.getSplit(list.id)!;
- const detailHandle = manager.getSplit(detail.id)!;
-
- manager.openWithSplit(
- { type: 'email', id: 'thread' },
- { handle: listHandle }
- );
- expect(listHandle.content()).toEqual({ type: 'email', id: 'thread' });
- expect(detailHandle.content()).toEqual({ type: 'md', id: 'detail' });
- expect(manager.splits()).toHaveLength(2);
-
- listHandle.goBack();
- expect(listHandle.content()).toEqual({ type: 'component', id: 'home' });
- expect(detailHandle.content()).toEqual({ type: 'md', id: 'detail' });
- listHandle.close();
- expect(manager.splits().map((split) => split.id)).toEqual([detail.id]);
- dispose();
- });
- });
-
- describe('swapSplit', () => {
- it('swaps adjacent splits and delegates the panel reorder to Resize', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'component', id: 'calendar' },
- ]);
- const [first, second] = manager.splits();
- const swap = vi.fn();
- manager.setResizeContext({
- canFit: () => true,
- swap,
- } as unknown as ResizeZoneCtx);
-
- manager.swapSplit(second!.id, 'left');
-
- expect(manager.splits().map((split) => split.id)).toEqual([
- second!.id,
- first!.id,
- ]);
- expect(swap).toHaveBeenCalledWith(second!.id, first!.id);
-
- dispose();
- });
- });
- });
-
- describe('reconciler', () => {
- it('uses the retained split id for history ownership after reconciliation', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- const content = { type: 'email', id: 'same-entity' } as const;
- manager.reconcile([content]);
- expect(manager.splits()[0].id).toBe(handle.id);
- handle.replace({ next: content });
- expect(handle.canGoBack()).toBe(true);
- handle.goBack();
- expect(handle.history()).toHaveLength(1);
- expect(handle.canGoForward()).toBe(true);
- dispose();
- });
- });
-
- it('keeps history availability configured after reset', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- handle.reset();
- expect(handle.history()).toEqual([{ type: 'component', id: 'home' }]);
- expect(handle.canGoBack()).toBe(false);
- handle.replace({ next: { type: 'email', id: 'occupied' } });
- handle.replace({ next: { type: 'email', id: 'current' } });
- const release = manager.registerOpenViews(() => [
- { owner: 'preview', content: { type: 'email', id: 'occupied' } },
- ]);
- expect(handle.canGoBack()).toBe(true);
- handle.goBack();
- expect(handle.content().id).toBe('home');
- handle.goForward();
- expect(handle.content().id).toBe('current');
- release();
- expect(handle.canGoBack()).toBe(true);
- handle.goBack();
- expect(handle.content().id).toBe('occupied');
- dispose();
- });
- });
-
- it('should reconcile between current state and url changes', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'unified-list' },
- { type: 'md', id: 'test-md' },
- { type: 'component', id: 'unified-list' },
- ]);
-
- expect(manager.splits()).toHaveLength(3);
-
- const markdownSplitIdBefore = manager.splits()[1].id;
-
- manager.reconcile([
- { type: 'md', id: 'test-md' },
- { type: 'component', id: 'unified-list' },
- { type: 'component', id: 'unified-list' },
- ]);
-
- const markdownSplitIdAfter = manager.splits()[0].id;
-
- expect(manager.splits()).toHaveLength(3);
- expect(markdownSplitIdBefore).toBe(markdownSplitIdAfter);
-
- dispose();
- });
- });
-
- it('should reconcile between block -> component', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'test-md' },
- ]);
-
- manager.reconcile([{ type: 'component', id: 'unified-list' }]);
-
- expect(manager.splits()).toHaveLength(1);
- expect(manager.splits()[0].content.type).toBe('component');
-
- dispose();
- });
- });
-
- it('should preserve ordering when reconciling back to previous state (browser back)', () => {
- createRoot((dispose) => {
- const ORIGINAL_SPLITS = [
- { type: 'md', id: 'test-md-0' },
- { type: 'md', id: 'test-md-1' },
- { type: 'md', id: 'test-md-2' },
- ] satisfies SplitContent[];
-
- const NEW_SPLITS = [
- { type: 'md', id: 'test-md-0' },
- { type: 'md', id: 'test-md-3' },
- { type: 'md', id: 'test-md-2' },
- ] satisfies SplitContent[];
-
- const manager = createSplitLayout(
- createMockOrchestrator(),
- ORIGINAL_SPLITS
- );
- expect(manager.splits()).toHaveLength(3);
- expect(manager.splits().map((s) => s.content)).toEqual(ORIGINAL_SPLITS);
-
- manager.reconcile(NEW_SPLITS);
- expect(manager.splits()).toHaveLength(3);
- expect(manager.splits().map((s) => s.content)).toEqual(NEW_SPLITS);
-
- manager.reconcile(ORIGINAL_SPLITS);
-
- expect(manager.splits()).toHaveLength(3);
- expect(manager.splits().map((s) => s.content)).toEqual(ORIGINAL_SPLITS);
-
- dispose();
- });
- });
- });
-
- describe('router layout synchronization', () => {
- function ingressRouter(url: string, options: { touch?: boolean } = {}) {
- return createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- const location = createMemorySplitRouterLocation(url);
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location,
- middleware: createAppSplitRouterMiddleware({
- isTouchDevice: () => options.touch ?? false,
- }),
- });
- manager.setContentNavigator(
- createContentNavigator(manager, router, routes)
- );
- return { manager, location, router, dispose };
- });
- }
-
- it('shares reminder identity across Home and standalone routes', async () => {
- const { manager, router, location, dispose } = ingressRouter(
- '/home/reminder/reminder-a'
- );
- await router.settled();
- const home = manager.activeSplit()!;
- const firstApplied = vi.fn();
-
- manager.openWithSplit(reminderDetailContent('reminder-a'), {
- handle: home,
- preferNewSplit: true,
- search: {},
- onApplied: firstApplied,
- });
- await router.settled();
-
- expect(manager.splits()).toHaveLength(1);
- expect(manager.activeSplitId()).toBe(home.id);
- expect(firstApplied).toHaveBeenCalledOnce();
-
- const secondApplied = vi.fn();
- manager.openWithSplit(reminderDetailContent('reminder-b'), {
- handle: home,
- preferNewSplit: true,
- search: {},
- onApplied: secondApplied,
- });
- await router.settled();
-
- expect(manager.splits()).toHaveLength(2);
- expect(
- reminderIdFromDetailContent(manager.activeSplit()!.content())
- ).toBe('reminder-b');
- expect(location.read().pathname).toContain('/reminder/reminder-b');
- expect(secondApplied).toHaveBeenCalledOnce();
-
- manager.openWithSplit(reminderDetailContent('reminder-a'), {
- handle: manager.activeSplit(),
- preferNewSplit: true,
- search: {},
- });
- await router.settled();
- expect(manager.splits()).toHaveLength(2);
- expect(manager.activeSplitId()).toBe(home.id);
-
- router.dispose();
- dispose();
- });
-
- it('keeps reminder list and detail surfaces native-route only', () => {
- expect(decodeLegacyPair('component', 'reminders')).toBeUndefined();
- expect(decodeLegacyPair('component', 'reminder-detail')).toBeUndefined();
- });
-
- const searchTargets: {
- type: SplitContent['type'];
- target: SearchLocation;
- namespace: string;
- fields: Record<string, string[]>;
- path: string;
- }[] = [
- {
- type: 'channel',
- target: { type: 'channel', messageId: 'reply', threadId: 'parent' },
- namespace: 'channels',
- fields: { messageId: ['reply'], threadId: ['parent'] },
- path: '/channels/entity',
- },
- {
- type: 'email',
- target: { type: 'email', messageId: 'message' },
- namespace: 'email-detail',
- fields: { messageId: ['message'] },
- path: '/mail/entity',
- },
- {
- type: 'md',
- target: { type: 'md', nodeId: 'node' },
- namespace: 'markdown-detail',
- fields: { nodeId: ['node'] },
- path: '/drive/md/entity',
- },
- {
- type: 'pdf',
- target: {
- type: 'pdf',
- searchPage: 3,
- highlightTerms: ['a'],
- searchSnippet: 'snippet',
- searchRawQuery: 'a',
- },
- namespace: 'pdf-detail',
- fields: {
- page: ['3'],
- highlightTerms: ['a'],
- snippet: ['snippet'],
- query: ['a'],
- },
- path: '/drive/pdf/entity',
- },
- {
- type: 'agent',
- target: { type: 'agent', messageTurn: 0, author: 'user' },
- namespace: 'agent-detail',
- fields: {},
- path: '/agent/entity',
- },
- {
- type: 'call',
- target: {
- type: 'call_record',
- callId: 'entity',
- transcriptId: 'segment',
- },
- namespace: 'call-detail',
- fields: { transcriptId: ['segment'] },
- path: '/drive/call/entity',
- },
- ];
-
- it.each(searchTargets)(
- 'routes a $type search target on first open and on reuse',
- async ({ type, target, namespace, fields, path }) => {
- const { manager, router, location, dispose } = ingressRouter('/search');
- await router.settled();
- const onApplied = vi.fn();
- const source = manager.getSplit(manager.splits()[0].id)!;
- const sourceRoute = router.route(source.id);
- manager.openWithSplit(contentReference(type, 'entity'), {
- handle: source,
- preferNewSplit: true,
- search: searchLocationUpdates('entity', target),
- onApplied,
- });
- await router.settled();
- expect(manager.splits()).toHaveLength(2);
- const owner = manager.splits().find((split) => split.id !== source.id)!;
- expect(router.search(owner.id, namespace)).toMatchObject({
- ...fields,
- seek: [expect.any(String)],
- });
- expect(location.read().pathname).toContain(path);
- expect(onApplied).toHaveBeenCalledOnce();
- const firstRequest = router.search(owner.id, namespace)?.seek;
- manager.openWithSplit(contentReference(type, 'entity'), {
- handle: source,
- preferNewSplit: true,
- search: searchLocationUpdates('entity', target),
- onApplied,
- });
- await router.settled();
- expect(manager.splits()).toHaveLength(2);
- expect(router.route(source.id)).toEqual(sourceRoute);
- expect(router.search(source.id, namespace)).toBeUndefined();
- expect(router.search(owner.id, namespace)?.seek).not.toEqual(
- firstRequest
- );
- expect(manager.activeSplitId()).toBe(owner.id);
- expect(onApplied).toHaveBeenCalledTimes(2);
- router.dispose();
- dispose();
- }
- );
-
- it.each([false, true])(
- 'preserves native search navigation and list context (animated: %s)',
- async (animated) => {
- const { manager, router, dispose } = ingressRouter('/search', {
- touch: true,
- });
- await router.settled();
- const source = manager.getSplit(manager.splits()[0].id)!;
- let swipe!: ReturnType<typeof createMobileSwipeLayout>;
- const disposeSwipe = createRoot((cleanup) => {
- swipe = createMobileSwipeLayout(manager);
- return cleanup;
- });
- const animate = vi.fn();
- const onApplied = vi.fn();
- if (animated) swipe.setForwardNavigationTrigger(animate);
- manager.openWithSplit(
- withListNavigationSource({ type: 'channel', id: 'entity' }, source),
- {
- handle: source,
- referredFrom: 'search',
- onApplied,
- search: searchLocationUpdates('entity', {
- type: 'channel',
- messageId: 'message',
- }),
- }
- );
- await router.settled();
- if (animated) {
- expect(animate).toHaveBeenCalledOnce();
- expect(onApplied).not.toHaveBeenCalled();
- expect(manager.activeSplitId()).toBe(source.id);
- swipe.completeNavigateForward();
- await router.settled();
- }
- const detail = manager.activeSplit()!;
- expect(onApplied).toHaveBeenCalledOnce();
- expect(detail.id).not.toBe(source.id);
- expect(detail.referredFrom()).toBe('search');
- expect(listNavigationSourceId(detail)).toBe(source.id);
- expect(router.search(detail.id, 'channels')?.messageId).toEqual([
- 'message',
- ]);
- expect(swipe.canGoBack()).toBe(true);
- swipe.swipeBack();
- await router.settled();
- expect(manager.activeSplitId()).toBe(source.id);
- expect(router.route(source.id)?.matches[0].id).toBe('view-search');
- router.dispose();
- disposeSwipe();
- dispose();
- }
- );
-
- it.each(['same', 'different', 'removed'])(
- 'only reports the promoted native request applied (%s prepared target)',
- async (next) => {
- const { manager, router, dispose } = ingressRouter('/search', {
- touch: true,
- });
- await router.settled();
- const source = manager.activeSplit()!;
- let swipe!: ReturnType<typeof createMobileSwipeLayout>;
- const disposeSwipe = createRoot((cleanup) => {
- swipe = createMobileSwipeLayout(manager);
- swipe.setForwardNavigationTrigger(vi.fn());
- return cleanup;
- });
- const first = vi.fn();
- const second = vi.fn();
- const open = (id: string, onApplied: () => void) =>
- manager.openWithSplit(
- { type: 'channel', id },
- {
- handle: source,
- onApplied,
- search: searchLocationUpdates(id, {
- type: 'channel',
- messageId: 'hit',
- }),
- }
- );
- open('entity', first);
- await router.settled();
- expect(first).not.toHaveBeenCalled();
- if (next === 'removed') {
- manager.removeSplit(swipe.slotBSplitId()!);
- } else {
- open(next === 'same' ? 'entity' : 'other', second);
- }
- await router.settled();
- expect(second).not.toHaveBeenCalled();
- swipe.completeNavigateForward();
- await router.settled();
- expect(first).not.toHaveBeenCalled();
- expect(second).toHaveBeenCalledTimes(next === 'removed' ? 0 : 1);
- router.dispose();
- disposeSwipe();
- dispose();
- }
- );
-
- it('uses a remaining visible pane when the active pane was removed', async () => {
- const { manager, router, dispose } = ingressRouter('/search');
- await router.settled();
- const source = manager.splits()[0];
- const removed = manager.createNewSplit({
- content: { type: 'md', id: 'removed' },
- activate: true,
- referredFrom: null,
- })!;
- await router.settled();
- manager.removeSplit(removed.id);
- await router.settled();
- expect(manager.activeSplit()).toBeUndefined();
- manager.openWithSplit(
- { type: 'channel', id: 'entity' },
- {
- search: searchLocationUpdates('entity', {
- type: 'channel',
- messageId: 'hit',
- }),
- }
- );
- await router.settled();
- expect(router.search(source.id, 'channels')?.messageId).toEqual(['hit']);
- expect(manager.activeSplitId()).toBe(source.id);
- router.dispose();
- dispose();
- });
-
- it.each(['/home/agent/entity', '/agents/entity', '/coders/entity'])(
- 'reuses an agent target inside %s while preserving Changes state',
- async (path) => {
- const { manager, router, dispose } = ingressRouter(
- `${path}/~/search?s0.changes.pane=split&s0.changes.style=split`
- );
- await router.settled();
- const [owner, source] = manager.splits();
- const ownerRoute = router.route(owner.id);
- manager.openWithSplit(
- { type: 'agent', id: 'entity' },
- {
- handle: manager.getSplit(source.id),
- search: searchLocationUpdates('entity', {
- type: 'agent',
- messageTurn: 0,
- author: 'agent',
- }),
- }
- );
- await router.settled();
- expect(manager.splits()).toHaveLength(2);
- expect(router.route(owner.id)).toEqual(ownerRoute);
- expect(router.route(source.id)?.matches[0].id).toBe('view-search');
- expect(router.search(owner.id, 'agent-detail')).toMatchObject({
- messageTurn: ['0'],
- author: ['agent'],
- });
- expect(router.search(owner.id, 'changes')).toEqual({
- pane: ['split'],
- style: ['split'],
- });
- router.dispose();
- dispose();
- }
- );
-
- it('retargets an existing Home channel without replacing Home or its filters', async () => {
- const { manager, router, dispose } = ingressRouter(
- '/home/channel/entity/~/search?s0.channels.tab=recents&s0.channels.messageId=old&s0.channels.threadId=old-parent'
- );
- await router.settled();
- const [owner, source] = manager.splits();
- const ownerRoute = router.route(owner.id);
- manager.openWithSplit(
- { type: 'channel', id: 'entity' },
- {
- handle: manager.getSplit(source.id),
- search: searchLocationUpdates('entity', {
- type: 'channel',
- messageId: 'new-root',
- }),
- }
- );
- await router.settled();
- expect(router.route(owner.id)).toEqual(ownerRoute);
- expect(router.search(owner.id, 'channels')).toEqual({
- tab: ['recents'],
- messageId: ['new-root'],
- seek: [expect.any(String)],
- });
- expect(router.route(source.id)?.matches[0].id).toBe('view-search');
- router.dispose();
- dispose();
- });
-
- it.each([
- { name: 'top-level message', expected: { messageId: ['message-1'] } },
- {
- name: 'thread reply',
- threadId: 'thread-1',
- expected: { messageId: ['message-1'], threadId: ['thread-1'] },
- },
- {
- name: 'saved tab',
- threadId: 'thread-1',
- saved: { tab: ['recents'] },
- expected: {
- messageId: ['message-1'],
- threadId: ['thread-1'],
- tab: ['recents'],
- },
- },
- {
- name: 'top-level message after a saved thread',
- saved: { threadId: ['old-thread'], tab: ['recents'] },
- expected: { messageId: ['message-1'], tab: ['recents'] },
- },
- {
- name: 'reply after a saved thread',
- threadId: 'thread-1',
- saved: { threadId: ['old-thread'] },
- expected: { messageId: ['message-1'], threadId: ['thread-1'] },
- },
- {
- name: 'explicit saved target',
- threadId: 'thread-1',
- saved: { messageId: ['saved-message'], threadId: ['saved-thread'] },
- expected: { messageId: ['saved-message'], threadId: ['saved-thread'] },
- },
- {
- name: 'explicit saved top-level target',
- threadId: 'thread-1',
- saved: { messageId: ['saved-message'] },
- expected: { messageId: ['saved-message'] },
- },
- ])(
- 'preserves an in-app channel target through the Chat redirect: $name',
- async ({ threadId, saved, expected }) => {
- const { manager, location, router, dispose } = ingressRouter('/search');
- await router.settled();
-
- manager.openWithSplit(
- {
- type: 'channel',
- id: 'channel-1',
- params: {
- channel_message_id: 'message-1',
- ...(threadId ? { channel_thread_id: threadId } : {}),
- },
- ...(saved
- ? { entryMetadata: { search: { channels: saved } } }
- : {}),
- },
- { activate: true }
- );
- await router.settled();
-
- expect(location.read().pathname).toBe('/channels/channel-1');
- const search = new URLSearchParams(location.read().search);
- expect(search.get('s0.channels.messageId')).toBe(expected.messageId[0]);
- expect(search.get('s0.channels.threadId')).toBe(
- expected.threadId?.[0] ?? null
- );
- expect(router.search(manager.splits()[0].id, 'channels')).toEqual(
- expected
- );
-
- router.dispose();
- dispose();
- }
- );
-
- it.each([
- ['md', 'md'],
- ['pdf', 'pdf'],
- ['canvas', 'canvas'],
- ['task', 'md'],
- ['snippet', 'md'],
- ['skill', 'md'],
- ['csv', 'code'],
- ['code', 'code'],
- ['image', 'image'],
- ['video', 'video'],
- ['spreadsheet', 'spreadsheet'],
- ['unknown', 'unknown'],
- ])(
- 'preserves legacy %s blocks on touch, including canonical links',
- async (type, blockType) => {
- for (const path of [
- `/${blockType}/doc`,
- `/drive/${type}/doc`,
- `/drive/shared/${type}/doc`,
- `/drive/folder/folder/${type}/doc`,
- ]) {
- const { manager, location, router, dispose } = ingressRouter(path, {
- touch: true,
- });
- await router.settled();
- expect(location.read().pathname).toBe(`/${blockType}/doc`);
- expect(manager.splits()[0].content).toMatchObject({
- type: blockType,
- id: 'doc',
- });
- expect(location.history()).toHaveLength(1);
- router.dispose();
- dispose();
- }
- }
- );
-
- it('opens the Reviews list on its own component route', async () => {
- const { manager, location, router, dispose } = ingressRouter('/reviews');
- await router.settled();
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- expect(manager.splits()[0].mount.kind).toBe('component');
- expect(router.route(manager.splits()[0].id)?.matches[0]?.id).toBe(
- 'view-reviews'
- );
- expect(location.read().pathname).toBe('/reviews');
- router.dispose();
- dispose();
- });
- it('navigates from Tasks to Reviews and back in the same pane', async () => {
- const { manager, location, router, dispose } = ingressRouter('/tasks');
- await router.settled();
- const splitId = manager.splits()[0].id;
-
- router.navigate(splitId, { route: reviewsSplitRoute, params: {} });
- await router.settled();
- expect(manager.splits()[0].id).toBe(splitId);
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- expect(location.read().pathname).toBe('/reviews');
-
- router.navigate(splitId, { route: tasksSplitRoute, params: {} });
- await router.settled();
- expect(manager.splits()[0].id).toBe(splitId);
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'tasks',
- });
- expect(location.read().pathname).toBe('/tasks');
- router.dispose();
- dispose();
- });
- it('opens PR details in Reviews and redirects older PR links', async () => {
- for (const path of ['/pr/pr-1', '/reviews/pr/pr-1']) {
- const { manager, location, router, dispose } = ingressRouter(path);
- await router.settled();
- const split = manager.splits()[0];
- expect(split.content).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- expect(split.mount.kind).toBe('component');
- expect(router.route(split.id)?.matches).toEqual([
- { id: 'view-reviews', params: {} },
- { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } },
- ]);
- expect(location.read().pathname).toBe('/reviews/pr/pr-1');
- router.dispose();
- dispose();
- }
- });
-
- it('opens a Reviews PR in a new split without reusing the Reviews list', async () => {
- const { manager, router, dispose } = ingressRouter('/reviews');
- await router.settled();
- const listSplit = manager.splits()[0];
- const content = reviewsHostedContent({ type: 'pr', id: 'pr-1' });
- if (!content) throw new Error('Expected hosted PR content');
-
- const opened = manager.openWithSplit(content, {
- handle: manager.getSplit(listSplit.id),
- preferNewSplit: true,
- allowDuplicate: true,
- });
- await router.settled();
-
- expect(opened.status).toBe('opened');
- expect(manager.splits()).toHaveLength(2);
- expect(manager.splits()[0].id).toBe(listSplit.id);
- if (opened.status === 'opened') {
- expect(router.route(opened.split.id)?.matches.at(-1)).toEqual({
- id: 'reviews-pr',
- params: { foreignEntityId: 'pr-1' },
- });
- }
- router.dispose();
- dispose();
- });
- it('keeps PR details in Reviews on touch', async () => {
- const { manager, location, router, dispose } = ingressRouter('/pr/pr-1', {
- touch: true,
- });
- await router.settled();
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- expect(manager.splits()[0].mount.kind).toBe('component');
- expect(location.read().pathname).toBe('/reviews/pr/pr-1');
- router.dispose();
- dispose();
- });
-
- it('uses the Reviews PR route for existing split navigation', async () => {
- const { manager, location, router, dispose } = ingressRouter('/home');
- await router.settled();
- manager.getSplit(manager.splits()[0].id)!.replace({
- next: { type: 'pr', id: 'pr-2' },
- });
- await router.settled();
- expect(location.read().pathname).toBe('/reviews/pr/pr-2');
- expect(manager.splits()[0].mount.kind).toBe('component');
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- router.dispose();
- dispose();
- });
-
- it('upgrades stored PR route metadata to Reviews content', async () => {
- const { manager, router, dispose } = ingressRouter('/home');
- await router.settled();
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({
- next: {
- type: 'pr',
- id: 'pr-1',
- entryMetadata: {
- route: {
- matches: [
- { id: 'pr-detail', params: { foreignEntityId: 'pr-1' } },
- ],
- },
- },
- },
- });
- await router.settled();
- expect(split.content()).toMatchObject({
- type: 'component',
- id: 'reviews',
- });
- expect(router.route(split.id)?.matches.at(-1)?.id).toBe('reviews-pr');
- router.dispose();
- dispose();
- });
-
- it.each(['/home/channel', '/not-a-block/example'])(
- 'rejects an invalid legacy pair %s without mounting a block',
- async (path) => {
- const { manager, location, router, dispose } = ingressRouter(path);
- await router.settled();
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'home',
- });
- expect(location.read().pathname).toBe('/home');
- router.dispose();
- dispose();
- }
- );
-
- it('opens calls as Drive components and redirects old links', async () => {
- for (const path of ['/call/call-1', '/drive/call/call-1']) {
- const { manager, location, router, dispose } = ingressRouter(path);
- await router.settled();
- const split = manager.splits()[0];
- expect(split.content).toMatchObject({
- type: 'component',
- id: 'documents',
- });
- expect(split.mount.kind).toBe('component');
- expect(router.route(split.id)?.matches).toEqual([
- { id: 'drive', params: {} },
- { id: 'drive-call', params: { callId: 'call-1' } },
- ]);
- expect(location.read().pathname).toBe('/drive/call/call-1');
- router.dispose();
- dispose();
- }
- });
-
- it('keeps call details in Drive on touch', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/call/call-1',
- { touch: true }
- );
- await router.settled();
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'documents',
- });
- expect(manager.splits()[0].mount.kind).toBe('component');
- expect(location.read().pathname).toBe('/drive/call/call-1');
- router.dispose();
- dispose();
- });
-
- it('upgrades old call route metadata without losing transcript search', async () => {
- const { manager, router, dispose } = ingressRouter('/home');
- await router.settled();
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({
- next: {
- type: 'call',
- id: 'call-1',
- entryMetadata: {
- route: {
- matches: [{ id: 'call-detail', params: { callId: 'call-1' } }],
- },
- search: { 'call-detail': { transcriptId: ['segment-1'] } },
- },
- },
- });
- await router.settled();
- expect(split.content()).toMatchObject({
- type: 'component',
- id: 'documents',
- });
- expect(router.route(split.id)?.matches.at(-1)?.id).toBe('drive-call');
- expect(router.search(split.id, 'call-detail')).toEqual({
- transcriptId: ['segment-1'],
- });
- router.dispose();
- dispose();
- });
-
- it('uses the Drive call detail route for existing split navigation', async () => {
- const { manager, location, router, dispose } = ingressRouter('/home');
- await router.settled();
- manager.getSplit(manager.splits()[0].id)!.replace({
- next: { type: 'call', id: 'call-2' },
- });
- await router.settled();
- expect(location.read().pathname).toBe('/drive/call/call-2');
- expect(manager.splits()[0].mount.kind).toBe('component');
- expect(manager.splits()[0].content).toMatchObject({
- type: 'component',
- id: 'documents',
- });
- router.dispose();
- dispose();
- });
-
- it('retains pane-local transcript targeting during call navigation', async () => {
- const { manager, router, dispose } = ingressRouter('/home');
- await router.settled();
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({
- next: driveHostedContent(
- { type: 'call', id: 'call-2' },
- {
- allowDocuments: true,
- search: { 'call-detail': { transcriptId: ['segment-2'] } },
- }
- )!,
- });
- await router.settled();
- expect(router.search(split.id, 'call-detail')).toEqual({
- transcriptId: ['segment-2'],
- });
- const mount = manager.splits()[0].mount;
- split.replace({
- next: driveHostedContent(
- { type: 'call', id: 'call-2' },
- {
- allowDocuments: true,
- search: {
- 'call-detail': { transcriptId: ['segment-2'], seek: ['again'] },
- },
- }
- )!,
- mergeHistory: true,
- });
- await router.settled();
- expect(router.search(split.id, 'call-detail')).toEqual({
- transcriptId: ['segment-2'],
- seek: ['again'],
- });
- expect(manager.splits()[0].mount).toBe(mount);
- router.dispose();
- dispose();
- });
-
- it('restores a call transcript target from old and Drive links', async () => {
- for (const path of [
- '/call/call-1?call_transcript_id=segment-1',
- '/drive/call/call-1?call_transcript_id=segment-1',
- ]) {
- const { manager, location, router, dispose } = ingressRouter(path);
- await router.settled();
- const split = manager.splits()[0];
- expect(router.search(split.id, 'call-detail')).toEqual({
- transcriptId: ['segment-1'],
- });
- expect(location.read().pathname).toBe('/drive/call/call-1');
- expect(
- new URLSearchParams(location.read().search).get('call_transcript_id')
- ).toBe('segment-1');
- router.dispose();
- dispose();
- }
- });
-
- it('restores a call chat target from old and Drive links', async () => {
- for (const path of [
- '/call/call-1?call_message_id=message-1',
- '/drive/call/call-1?call_message_id=message-1',
- ]) {
- const { manager, location, router, dispose } = ingressRouter(path);
- await router.settled();
- const split = manager.splits()[0];
- expect(router.search(split.id, 'call-detail')).toEqual({
- messageId: ['message-1'],
- });
- expect(location.read().pathname).toBe('/drive/call/call-1');
- router.dispose();
- dispose();
- }
- });
-
- it('preserves canonical transcript search when upgrading an old call link', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/call/call-1?s0.call-detail.transcriptId=segment-3&referral_code=code#focus'
- );
- await router.settled();
- expect(router.search(manager.splits()[0].id, 'call-detail')).toEqual({
- transcriptId: ['segment-3'],
- });
- expect(location.read().pathname).toBe('/drive/call/call-1');
- expect(
- new URLSearchParams(location.read().search).get('referral_code')
- ).toBe('code');
- expect(location.read().hash).toBe('#focus');
- router.dispose();
- dispose();
- });
- it('keeps Drive list routes on touch', async () => {
- const { location, router, dispose } = ingressRouter(
- '/drive/~/drive/shared/~/drive/folder/folder',
- { touch: true }
- );
- await router.settled();
- expect(location.read().pathname).toBe(
- '/drive/~/drive/shared/~/drive/folder/folder'
- );
- router.dispose();
- dispose();
- });
-
- it('renders Calendar as a route-backed component and restores URL state', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/calendar/week?eventId=event-1'
- );
- await router.settled();
- const split = manager.splits()[0];
- const mount = split.mount;
- expect(split.content).toMatchObject({
- type: 'component',
- id: 'calendar',
- });
- expect(mount.kind).toBe('component');
- expect(router.route(split.id)?.matches).toEqual([
- { id: 'view-calendar', params: { period: 'timeGridWeek' } },
- ]);
- expect(router.search(split.id, 'calendar')).toEqual({
- eventId: ['event-1'],
- });
- expect(location.read().pathname).toBe('/calendar/week');
- expect(new URLSearchParams(location.read().search).get('eventId')).toBe(
- 'event-1'
- );
- expect(
- new URLSearchParams(location.read().search).get('s0.calendar.eventId')
- ).toBe('event-1');
-
- location.set('/calendar/day?s0.calendar.eventId=event-2');
- await router.settled();
- expect(manager.splits()[0].mount).toBe(mount);
- expect(router.route(split.id)?.matches).toEqual([
- { id: 'view-calendar', params: { period: 'timeGridDay' } },
- ]);
- expect(router.search(split.id, 'calendar')).toEqual({
- eventId: ['event-2'],
- });
- router.dispose();
- dispose();
- });
-
- it.each([
- ['/component/preview-empty', '/home'],
- ['/component/non-member-channel', '/home'],
- ['/component/home', '/home'],
- ['/component/documents', '/drive'],
- ['/component/settings', '/settings/account'],
- ])('upgrades the legacy component URL %s', async (incoming, expected) => {
- const { location, router, dispose } = ingressRouter(incoming);
- await router.settled();
- expect(location.read().pathname).toBe(expected);
- expect(location.history()).toHaveLength(1);
- router.dispose();
- dispose();
- });
-
- it.each([
- ['/email/thread-1', '/mail/thread-1'],
- ['/channel/channel-1', '/channels/channel-1'],
- ['/task/task-1', '/tasks/task-1'],
- ['/md/document-1', '/drive/md/document-1'],
- ])('upgrades the legacy block URL %s', async (incoming, expected) => {
- const { location, router, dispose } = ingressRouter(incoming);
- await router.settled();
- expect(location.read().pathname).toBe(expected);
- expect(location.history()).toHaveLength(1);
- router.dispose();
- dispose();
- });
-
- it('opens a project like a task: in Tasks, under its Projects tab', async () => {
- const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';
- const { manager, location, router, dispose } = ingressRouter('/search');
- await router.settled();
-
- manager.openWithSplit(
- { type: 'initiative', id: projectId } as SplitContent,
- { activate: true }
- );
- await router.settled();
-
- expect(location.read().pathname).toBe(
- `/tasks/projects/${projectId}/overview`
- );
- expect(router.search(manager.splits()[0].id, 'tasks')).toMatchObject({
- tab: ['projects'],
- });
- router.dispose();
- dispose();
- });
-
- it('keeps a project block on touch, like tasks', async () => {
- const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';
- const { manager, location, router, dispose } = ingressRouter(
- `/initiative/${projectId}`,
- { touch: true }
- );
- await router.settled();
-
- expect(location.read().pathname).toBe(`/initiative/${projectId}`);
- expect(manager.splits()[0].content).toMatchObject({
- type: 'initiative',
- id: projectId,
- });
- router.dispose();
- dispose();
- });
-
- it('upgrades the legacy Calendar block URL to the preferred period route', async () => {
- localStorage.setItem(
- CALENDAR_PREFERENCES_KEY,
- JSON.stringify({ periodView: 'dayGridMonth' })
- );
- const { manager, location, router, dispose } = ingressRouter(
- '/calendar/view?eventId=legacy-event'
- );
- await router.settled();
- const split = manager.splits()[0];
- expect(split.content).toMatchObject({
- type: 'component',
- id: 'calendar',
- });
- expect(location.read().pathname).toBe('/calendar/month');
- expect(router.search(split.id, 'calendar')).toEqual({
- eventId: ['legacy-event'],
- });
- localStorage.removeItem(CALENDAR_PREFERENCES_KEY);
- router.dispose();
- dispose();
- });
-
- it('normalizes legacy search per detail pane without overriding canonical values', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/mail/one/~/channels/c1/~/mail/two/~/mail' +
- '?email_message_id=legacy&channel_message_id=first&channel_message_id=last' +
- '&channel_thread_id=thread&s0.email-detail.messageId=explicit' +
- '&s0.email-detail.extra=keep&s2.email-detail.messageId=&referral_code=code#focus'
- );
- await router.settled();
- const [firstMail, channel, secondMail, mailList] = manager.splits();
- expect(router.search(firstMail.id, 'email-detail')).toEqual({
- messageId: ['explicit'],
- extra: ['keep'],
- });
- expect(router.search(channel.id, 'channels')).toEqual({
- messageId: ['first', 'last'],
- threadId: ['thread'],
- });
- expect(router.search(secondMail.id, 'email-detail')).toEqual({
- messageId: [''],
- });
- expect(router.search(mailList.id, 'email-detail')).toBeUndefined();
- expect(
- new URLSearchParams(location.read().search).get('referral_code')
- ).toBe('code');
- expect(location.read().hash).toBe('#focus');
- expect(location.history()).toHaveLength(1);
- router.dispose();
- dispose();
- });
-
- it('migrates legacy channel targets on Inbox preview routes', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/home/channel/c1?channel_message_id=first&channel_message_id=last&channel_thread_id=thread'
- );
- await router.settled();
- const split = manager.splits()[0];
- expect(router.search(split.id, 'channels')).toEqual({
- messageId: ['first', 'last'],
- threadId: ['thread'],
- });
- expect(
- new URLSearchParams(location.read().search).getAll(
- 's0.channels.messageId'
- )
- ).toEqual(['first', 'last']);
- router.dispose();
- dispose();
- });
-
- it.each([
- ['md', 'comment_id'],
- ['task', 'comment_id'],
- ['pdf', 'pdf_ann_id'],
- ['spreadsheet', 'comment_id'],
- ])(
- 'migrates unprefixed %s comments on Inbox document routes',
- async (type, key) => {
- const { manager, location, router, dispose } = ingressRouter(
- `/home/${type}/document-1?${key}=comment-1`
- );
- await router.settled();
- const split = manager.splits()[0];
- expect(router.search(split.id, 'drive')).toEqual({
- commentId: ['comment-1'],
- });
- expect(
- new URLSearchParams(location.read().search).get('s0.drive.commentId')
- ).toBe('comment-1');
- router.dispose();
- dispose();
- }
- );
-
- it('prefers an explicit Inbox document comment over an unprefixed key', async () => {
- const { manager, router, dispose } = ingressRouter(
- '/home/md/document-1?comment_id=legacy&s0.drive.commentId=explicit'
- );
- await router.settled();
- expect(router.search(manager.splits()[0].id, 'drive')).toEqual({
- commentId: ['explicit'],
- });
- router.dispose();
- dispose();
- });
-
- it('preserves Drive facets during comment link migration', async () => {
- const { manager, router, dispose } = ingressRouter(
- '/home/md/document-1?comment_id=comment-1&s0.drive.tags=first&s0.drive.tags=second'
- );
- await router.settled();
- expect(router.search(manager.splits()[0].id, 'drive')).toEqual({
- commentId: ['comment-1'],
- tags: ['first', 'second'],
- });
- router.dispose();
- dispose();
- });
-
- it('applies a new-split location when an entity pane is reused', async () => {
- const { manager, router, dispose } = ingressRouter('/channel/one', {
- touch: true,
- });
- await router.settled();
- const split = manager.splits()[0];
-
- router.navigate(split.id, '/channel/one', {
- target: 'new-split',
- allowDuplicate: true,
- search: {
- channels: { messageId: ['second'] },
- },
- });
- await router.settled();
-
- expect(manager.splits()).toHaveLength(1);
- expect(manager.splits()[0].content.entryMetadata).toMatchObject({
- search: {
- channels: { messageId: ['second'] },
- },
- });
- router.dispose();
- dispose();
- });
-
- it('normalizes every external URL and restores targets through browser history', async () => {
- const { manager, location, router, dispose } = ingressRouter(
- '/mail/one?email_message_id=first'
- );
- await router.settled();
- const split = manager.splits()[0];
- const mount = split.mount;
- expect(router.search(split.id, 'email-detail')).toEqual({
- messageId: ['first'],
- });
-
- location.set('/mail/one?email_message_id=second');
- await router.settled();
- expect(router.search(split.id, 'email-detail')).toEqual({
- messageId: ['second'],
- });
- expect(location.history()).toHaveLength(2);
- expect(manager.splits()[0].mount).toBe(mount);
-
- expect(location.back()).toBe(true);
- await router.settled();
- expect(router.search(split.id, 'email-detail')).toEqual({
- messageId: ['first'],
- });
- expect(location.forward()).toBe(true);
- await router.settled();
- expect(router.search(split.id, 'email-detail')).toEqual({
- messageId: ['second'],
- });
- expect(location.history()).toHaveLength(2);
- router.dispose();
- dispose();
- });
-
- it('preserves full-block legacy targets on touch', async () => {
- const { location, router, dispose } = ingressRouter(
- '/email/one/~/channel/c1?email_message_id=message&channel_message_id=first' +
- '&channel_message_id=last&channel_thread_id=thread',
- { touch: true }
- );
- await router.settled();
- expect(location.read().pathname).toBe('/email/one/~/channel/c1');
- const query = new URLSearchParams(location.read().search);
- expect(query.getAll('email_message_id')).toEqual(['message']);
- expect(query.getAll('channel_message_id')).toEqual(['first', 'last']);
- expect(query.get('channel_thread_id')).toBe('thread');
- expect(
- [...query.keys()].some(
- (key) => key.startsWith('s0.') || key.startsWith('s1.')
- )
- ).toBe(false);
- router.dispose();
- dispose();
- });
-
- it.each(['company', 'contact'])(
- 'keeps a %s discussion link comment for the record page',
- async (type) => {
- const { location, router, dispose } = ingressRouter(
- `/${type}/record-1?comment_id=message-1`
- );
- await router.settled();
- expect(location.read().pathname).toBe(`/${type}/record-1`);
- expect(
- new URLSearchParams(location.read().search).get('comment_id')
- ).toBe('message-1');
- router.dispose();
- dispose();
- }
- );
-
- it('upgrades renderable legacy details and preserves repeated raw target values', async () => {
- let dispose!: () => void;
- let router!: ReturnType<typeof createSplitRouter<string>>;
- let location!: ReturnType<typeof createMemorySplitRouterLocation>;
- createRoot((rootDispose) => {
- dispose = rootDispose;
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'email', id: 'thread-1' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- location = createMemorySplitRouterLocation(
- '/email/thread-1?email_message_id=first&email_message_id=last'
- );
- router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location,
- middleware: createAppSplitRouterMiddleware({
- isTouchDevice: () => false,
- }),
- });
- });
-
- await router.settled();
- expect(location.read().pathname).toBe('/mail/thread-1');
- const query = new URLSearchParams(location.read().search);
- expect(query.getAll('email_message_id')).toEqual(['first', 'last']);
- expect(query.getAll('s0.email-detail.messageId')).toEqual([
- 'first',
- 'last',
- ]);
- expect(location.history()).toHaveLength(1);
- dispose();
- });
-
- it('keeps legacy task detail on touch', async () => {
- let dispose!: () => void;
- let router!: ReturnType<typeof createSplitRouter<string>>;
- let location!: ReturnType<typeof createMemorySplitRouterLocation>;
- createRoot((rootDispose) => {
- dispose = rootDispose;
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'task', id: 'task-1' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- location = createMemorySplitRouterLocation('/task/task-1');
- router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location,
- middleware: createAppSplitRouterMiddleware({
- isTouchDevice: () => true,
- }),
- });
- });
-
- await router.settled();
- expect(location.read().pathname).toBe('/task/task-1');
- dispose();
- });
-
- it('keeps a migrated workspace mounted across typed detail history', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'mail' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location: createMemorySplitRouterLocation('/mail'),
- });
- const split = manager.splits()[0]!;
- const mount = split.mount;
- const handle = manager.getSplit(split.id)!;
- const stopCapture = handle.registerEntryStateCaptor(
- 'email.listState',
- () => ({
- focusKey: 'one',
- scrollOffset: 420,
- })
- );
-
- router.navigate(split.id, {
- route: emailThreadRoute,
- params: { threadId: 'one' },
- });
- stopCapture(); // The list is disposed when its detail outlet takes over.
- expect(handle.currentEntryState()).toMatchObject({
- 'email.listState': { focusKey: 'one', scrollOffset: 420 },
- });
- router.navigate(split.id, {
- route: emailThreadRoute,
- params: { threadId: 'two' },
- });
-
- expect(manager.splits()[0]?.mount).toBe(mount);
- expect(manager.splits()[0]?.content).toMatchObject({
- type: 'component',
- id: 'mail',
- });
- expect(router.route(split.id)?.matches.at(-1)?.params).toEqual({
- threadId: 'two',
- });
-
- router.navigate(split.id, -1);
- expect(router.route(split.id)?.matches.at(-1)?.params).toEqual({
- threadId: 'one',
- });
- router.navigate(split.id, {
- route: emailSplitRoute,
- params: {},
- });
- expect(router.route(split.id)?.matches).toEqual([
- { id: 'view-mail', params: {} },
- ]);
- expect(manager.splits()[0]?.mount).toBe(mount);
- router.dispose();
- dispose();
- });
- });
-
- it('uses canonical detail claims across routed workspaces and legacy blocks', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'tasks' },
- { type: 'md', id: 'task-1' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location: createMemorySplitRouterLocation('/tasks/~/md/task-1'),
- });
- const [tasks, legacy] = manager.splits();
- const accepted = router.route(tasks.id);
-
- router.navigate(tasks.id, {
- route: taskDetailRoute,
- params: { taskId: 'task-1' },
- });
-
- expect(router.route(tasks.id)).toEqual(accepted);
- expect(manager.activeSplitId()).toBe(legacy.id);
- expect(manager.splits()).toHaveLength(2);
- router.dispose();
- dispose();
- });
- });
-
- it('keeps duplicate list roots independent while reusing claimed email details', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'mail' },
- { type: 'component', id: 'mail' },
- ]);
- const routes = createRoutesManifest(appSplitRoutes);
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location: createMemorySplitRouterLocation('/mail/one/~/mail'),
- });
- const [owner, other] = manager.splits();
- const otherRoute = router.route(other.id);
- manager.activateSplit(other.id);
-
- router.navigate(other.id, {
- route: emailThreadRoute,
- params: { threadId: 'one' },
- });
-
- expect(router.route(other.id)).toEqual(otherRoute);
- expect(manager.activeSplitId()).toBe(owner.id);
- expect(manager.splits()).toHaveLength(2);
- router.dispose();
- dispose();
- });
- });
-
- it.each(['drive', 'drive/md/second-document'])(
- 'navigates a second Drive pane independently from %s, including history',
- (initialPath) => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'documents' },
- { type: 'component', id: 'documents' },
- ]);
- const routes = createRoutesManifest({
- definitions: [driveSplitRoute],
- });
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location: createMemorySplitRouterLocation(
- `/drive/~/${initialPath}`
- ),
- });
- const [first, second] = manager.splits();
- const firstRoute = router.route(first.id);
- manager.activateSplit(second.id);
-
- router.navigate(second.id, '/drive/folder/second-folder');
- const folderRoute = router.route(second.id);
- expect(folderRoute?.matches.at(-1)).toEqual({
- id: 'drive-folder',
- params: { view: 'folder', folderId: 'second-folder' },
- });
- expect(router.route(first.id)).toEqual(firstRoute);
- expect(manager.activeSplitId()).toBe(second.id);
-
- router.navigate(second.id, '/drive/md/another-document');
- expect(router.route(second.id)?.matches.at(-1)?.params).toEqual({
- documentType: 'md',
- documentId: 'another-document',
- });
- router.navigate(second.id, -1);
- expect(router.route(second.id)).toEqual(folderRoute);
- expect(router.route(first.id)).toEqual(firstRoute);
- expect(manager.activeSplitId()).toBe(second.id);
-
- router.navigate(second.id, '/drive/shared');
- expect(router.route(second.id)?.matches.at(-1)).toEqual({
- id: 'drive-tab',
- params: { tab: 'shared' },
- });
- router.navigate(
- second.id,
- driveDestination(
- { kind: 'folder', id: 'another-folder' },
- { type: 'md', id: 'nested-document' }
- )
- );
- expect(router.route(second.id)?.matches).toEqual([
- { id: 'drive', params: {} },
- {
- id: 'drive-folder',
- params: { view: 'folder', folderId: 'another-folder' },
- },
- {
- id: 'drive-folder-document',
- params: { documentType: 'md', documentId: 'nested-document' },
- },
- ]);
- expect(router.route(first.id)).toEqual(firstRoute);
- expect(manager.splits()).toHaveLength(2);
- router.dispose();
- dispose();
- });
- }
- );
-
- it('still activates the owner when another Drive pane opens the same document', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'documents' },
- { type: 'component', id: 'documents' },
- ]);
- const routes = createRoutesManifest({
- definitions: [driveSplitRoute],
- });
- const router = createSplitRouter({
- routes,
- layout: createAppSplitRouterLayout(manager, routes),
- location: createMemorySplitRouterLocation(
- '/drive/md/first-document/~/drive/md/second-document'
- ),
- });
- const [first, second] = manager.splits();
- const secondRoute = router.route(second.id);
- manager.activateSplit(second.id);
-
- router.navigate(second.id, '/drive/md/first-document');
-
- expect(manager.activeSplitId()).toBe(first.id);
- expect(router.route(second.id)).toEqual(secondRoute);
- expect(manager.splits()).toHaveLength(2);
- router.dispose();
- dispose();
- });
- });
-
- it('does not publish manager updates that leave router state unchanged', async () => {
- let dispose!: () => void;
- let updateEntry!: (state: Record<string, unknown>) => void;
- let updateLocation!: (folderId?: string) => void;
- const listener = vi.fn();
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'documents' },
- ]);
- const split = manager.getSplit(manager.splits()[0]!.id)!;
- const layout = createAppSplitRouterLayout(
- manager,
- createRoutesManifest({
- definitions: [
- {
- id: 'drive',
- path: 'drive',
- children: [{ id: 'drive-folder', path: 'folder/:folderId' }],
- },
- ],
- })
- );
- layout.subscribe(listener);
-
- updateEntry = (state) => {
- split.updateCurrentEntry((current) => ({ ...current, state }));
- };
- updateLocation = (folderId) => {
- split.updateCurrentEntry((current) => ({
- ...current,
- entryMetadata: {
- route: {
- matches: folderId
- ? [
- { id: 'drive', params: {} },
- { id: 'drive-folder', params: { folderId } },
- ]
- : [{ id: 'drive', params: {} }],
- },
- },
- }));
- };
- });
- await Promise.resolve();
-
- updateEntry({ scrollOffset: 120 });
- await Promise.resolve();
-
- expect(listener).not.toHaveBeenCalled();
-
- updateLocation();
- await Promise.resolve();
-
- expect(listener).not.toHaveBeenCalled();
-
- updateLocation('folder-1');
- await Promise.resolve();
-
- expect(listener).toHaveBeenCalledOnce();
- dispose();
- });
- });
-
- describe('entry state', () => {
- it('captures registered entry state and merges with existing state', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- {
- type: 'component',
- id: 'unified-list',
- state: { existing: true },
- },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.registerEntryStateCaptor('soup.listState', () => ({
- scrollOffset: 120,
- focus: 'entity-1',
- }));
-
- split.captureEntryState();
-
- expect(split.currentEntryState()).toEqual({
- existing: true,
- 'soup.listState': {
- scrollOffset: 120,
- focus: 'entity-1',
- },
- });
- expect(split.history()[0].state).toEqual(split.currentEntryState());
-
- dispose();
- });
- });
- });
-
- describe('entry metadata', () => {
- it('skips structurally equal metadata during reconciliation', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- {
- type: 'component',
- id: 'documents',
- entryMetadata: {
- route: { matches: [{ id: 'drive', params: {} }] },
- search: { drive: { tags: ['one'] } },
- },
- },
- ]);
- const before = manager.splits()[0]!;
- const metadataBefore = before.content.entryMetadata;
-
- manager.reconcile([
- {
- type: 'component',
- id: 'documents',
- entryMetadata: {
- route: { matches: [{ id: 'drive', params: {} }] },
- search: { drive: { tags: ['one'] } },
- },
- },
- ]);
-
- expect(manager.splits()[0]).toBe(before);
- expect(manager.splits()[0]?.content.entryMetadata).toBe(metadataBefore);
-
- dispose();
- });
- });
-
- it('updates the current entry without remounting or emitting content changes', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- {
- type: 'md',
- id: 'doc-1',
- entryMetadata: { source: 'initial' },
- },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- const initialHistoryLength = split.history().length;
- const listener = vi.fn();
- split.registerContentChangeListener(listener);
-
- split.updateCurrentEntry((current) => ({
- ...current,
- entryMetadata: { source: 'updated' },
- }));
-
- expect(split.history()).toHaveLength(initialHistoryLength);
- expect(split.content().entryMetadata).toEqual({
- source: 'updated',
- });
- expect(split.history().at(-1)?.entryMetadata).toEqual(
- split.content().entryMetadata
- );
- expect(orchestrator.createBlockInstance).toHaveBeenCalledOnce();
- expect(listener).not.toHaveBeenCalled();
-
- dispose();
- });
- });
-
- it('applies inbound metadata to same-identity content only', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- {
- type: 'component',
- id: 'documents',
- params: { privateParam: 'retained' },
- state: { privateState: 'retained' },
- entryMetadata: { source: 'initial' },
- },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- const mountBefore = manager.splits()[0].mount;
- const listener = vi.fn();
- split.registerContentChangeListener(listener);
-
- manager.reconcile([
- {
- type: 'component',
- id: 'documents',
- params: { privateParam: 'ignored' },
- state: { privateState: 'ignored' },
- entryMetadata: { source: 'inbound' },
- },
- ]);
-
- expect(split.content()).toEqual({
- type: 'component',
- id: 'documents',
- params: { privateParam: 'retained' },
- state: { privateState: 'retained' },
- entryMetadata: { source: 'inbound' },
- });
- expect(split.history().at(-1)).toEqual(split.content());
- expect(manager.splits()[0].mount).toBe(mountBefore);
- expect(listener).not.toHaveBeenCalled();
-
- dispose();
- });
- });
-
- it('restores metadata with the containing split-history entry', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'doc-1' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.updateCurrentEntry((current) => ({
- ...current,
- entryMetadata: { source: 'first-entry' },
- }));
-
- split.replace({
- next: {
- type: 'md',
- id: 'doc-2',
- entryMetadata: { source: 'second-entry' },
- },
- });
- split.goBack();
-
- expect(split.content().entryMetadata).toEqual({
- source: 'first-entry',
- });
- dispose();
- });
- });
- });
-
- describe('split history', () => {
- it('marks mergeHistory content changes as replace navigation', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
-
- split.replace({
- next: { type: 'md', id: 'created-doc' },
- mergeHistory: true,
- });
-
- expect(manager.events()).toMatchObject({
- type: SplitEvent.ContentChange,
- cause: 'replace',
- newContent: { type: 'md', id: 'created-doc' },
- previousContent: { type: 'component', id: 'home' },
- });
-
- dispose();
- });
- });
-
- it('refreshes entry state when merging content already open in the target split', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- {
- type: 'md',
- id: 'doc-1',
- state: { retained: true, source: 'first' },
- },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
-
- manager.openWithSplit(
- { type: 'md', id: 'doc-1', state: { source: 'second' } },
- { handle: split, mergeHistory: true, referredFrom: null }
- );
-
- expect(split.history()).toHaveLength(1);
- expect(split.content().state).toEqual({
- retained: true,
- source: 'second',
- });
-
- split.replace({ next: { type: 'md', id: 'doc-2' } });
- split.goBack();
- expect(split.content().state).toEqual({
- retained: true,
- source: 'second',
- });
-
- dispose();
- });
- });
-
- it('jumps back to the nearest earlier entry matching a predicate', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
-
- split.replace({ next: { type: 'md', id: 'doc-1' } });
- split.replace({ next: { type: 'component', id: 'tasks' } });
- split.replace({ next: { type: 'md', id: 'doc-2' } });
- split.replace({ next: { type: 'channel', id: 'ch-1' } });
-
- const moved = split.goBackTo(
- (content) => content.type === 'component' && content.id === 'tasks'
- );
-
- expect(moved).toBe(true);
- expect(split.content()).toMatchObject({
- type: 'component',
- id: 'tasks',
- });
- // The skipped entries stay ahead, so forward still reaches them.
- expect(split.canGoForward()).toBe(true);
-
- dispose();
- });
- });
-
- it.each(['split', 'inline'] as const)(
- 'back and forward skip content owned by another %s without focusing it',
- (owner) => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- const occupied = { type: 'email', id: 'occupied' } as const;
- handle.replace({ next: occupied });
- handle.replace({ next: { type: 'channel', id: 'end' } });
- const activate = vi.fn();
- const release =
- owner === 'inline'
- ? manager.registerOpenViews(() => [
- { owner: 'detail', content: occupied, activate },
- ])
- : (() => {
- const split = manager.createNewSplit({
- content: occupied,
- referredFrom: null,
- })!;
- return () => manager.removeSplit(split.id);
- })();
- handle.activate();
- vi.mocked(toast.alert).mockClear();
-
- expect(handle.canGoBack()).toBe(true);
- handle.goBack();
- expect(handle.content().id).toBe('home');
- expect(handle.canGoBack()).toBe(false);
- expect(handle.canGoForward()).toBe(true);
- handle.goForward();
- expect(handle.content().id).toBe('end');
- expect(handle.canGoForward()).toBe(false);
- expect(handle.history().map((entry) => entry.id)).toEqual([
- 'home',
- 'occupied',
- 'end',
- ]);
- expect(manager.activeSplitId()).toBe(handle.id);
- expect(activate).not.toHaveBeenCalled();
- expect(toast.alert).not.toHaveBeenCalled();
-
- release();
- handle.goBack();
- expect(handle.content().id).toBe('occupied');
- dispose();
- });
- }
- );
-
- it('disables history directions with only occupied entries and restores them when released', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'email', id: 'before' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- handle.replace({ next: { type: 'component', id: 'home' } });
- handle.replace({ next: { type: 'email', id: 'after' } });
- handle.goBack();
- const canGoBack = createMemo(handle.canGoBack);
- const canGoForward = createMemo(handle.canGoForward);
- expect(canGoBack()).toBe(true);
- expect(canGoForward()).toBe(true);
- const [occupied, setOccupied] = createSignal(['before', 'after']);
- const release = manager.registerOpenViews(() =>
- occupied().map((id) => ({
- owner: id,
- content: { type: 'email', id },
- }))
- );
- expect(canGoBack()).toBe(false);
- expect(canGoForward()).toBe(false);
- handle.goBack();
- handle.goForward();
- expect(handle.content().id).toBe('home');
- setOccupied([]);
- expect(canGoBack()).toBe(true);
- expect(canGoForward()).toBe(true);
- setOccupied(['before', 'after']);
- expect(canGoBack()).toBe(false);
- expect(canGoForward()).toBe(false);
- release();
- expect(canGoBack()).toBe(true);
- expect(canGoForward()).toBe(true);
- dispose();
- });
- });
-
- it('skips history entries another split already displays', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'email', id: 'other' },
- ]);
- const [listSplitState, docSplitState] = manager.splits();
- const listSplit = manager.getSplit(listSplitState.id)!;
- const docSplit = manager.getSplit(docSplitState.id)!;
-
- // Visit the email, navigate away, then open it in the other split.
- listSplit.replace({ next: { type: 'email', id: 'doc-1' } });
- listSplit.replace({ next: { type: 'channel', id: 'ch-1' } });
- docSplit.replace({ next: { type: 'email', id: 'doc-1' } });
-
- const moved = listSplit.goBackTo(
- (content) => content.type === 'email' && content.id === 'doc-1'
- );
-
- // doc-1 is unmountable here, so nothing moves: the split keeps showing
- // the channel rather than stranding its history on an entry it never
- // mounted.
- expect(moved).toBe(false);
- expect(listSplit.content()).toMatchObject({
- type: 'channel',
- id: 'ch-1',
- });
- expect(docSplit.content()).toMatchObject({
- type: 'email',
- id: 'doc-1',
- });
-
- dispose();
- });
- });
-
- it('leaves the split put when nothing earlier matches', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const split = manager.getSplit(manager.splits()[0].id)!;
-
- split.replace({ next: { type: 'md', id: 'doc-1' } });
-
- const moved = split.goBackTo(
- (content) => content.type === 'component' && content.id === 'tasks'
- );
-
- expect(moved).toBe(false);
- expect(split.content()).toMatchObject({ type: 'md', id: 'doc-1' });
-
- dispose();
- });
- });
- });
-
- describe('component metadata', () => {
- it('updates the current mount through a retained split handle', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- const inboxMeta = handle.meta()!;
-
- handle.updateMeta?.({ splitPanelLayout: 'legacy' });
- handle.replace({ next: { type: 'component', id: 'tasks' } });
-
- const tasksMeta = handle.meta()!;
- expect(tasksMeta).not.toBe(inboxMeta);
-
- handle.updateMeta?.({ splitPanelLayout: 'composable' });
-
- expect(tasksMeta.splitPanelLayout).toBe('composable');
- expect(inboxMeta.splitPanelLayout).toBe('legacy');
-
- handle.replace({ next: { type: 'md', id: 'document-1' } });
-
- expect(handle.meta()).toBeUndefined();
- expect(handle.updateMeta).toBeUndefined();
-
- dispose();
- });
- });
- });
-
- describe('navigation params', () => {
- const channelWithTarget = {
- type: 'channel',
- id: 'ch-1',
- params: { channel_message_id: 'm-1' },
- } satisfies SplitContent;
-
- it('delivers one-shot params on same-split forward navigation', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({ next: channelWithTarget });
-
- expect(split.content()).toMatchObject(channelWithTarget);
-
- dispose();
- });
- });
-
- it('delivers one-shot params on mergeHistory navigation', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({ next: channelWithTarget, mergeHistory: true });
-
- expect(split.content()).toMatchObject(channelWithTarget);
-
- dispose();
- });
- });
-
- it('strips params when re-visiting an entry via history back/forward', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({ next: channelWithTarget });
-
- split.goBack();
- expect(split.content()).toMatchObject({
- type: 'component',
- id: 'home',
- });
-
- split.goForward();
- expect(split.content().type).toBe('channel');
- expect(split.content().params).toBeUndefined();
-
- dispose();
- });
- });
-
- it('strips params when removeFromHistory reattaches a prior entry', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({ next: channelWithTarget });
- split.replace({ next: { type: 'md', id: 'doc-1' } });
-
- split.removeFromHistory((content) => content.type === 'md');
-
- expect(split.content().type).toBe('channel');
- expect(split.content().params).toBeUndefined();
-
- dispose();
- });
- });
-
- it('keeps params on history navigation when preserveParams is set', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
-
- const split = manager.getSplit(manager.splits()[0].id)!;
- split.replace({
- next: { ...channelWithTarget, preserveParams: true },
- });
-
- split.goBack();
- split.goForward();
-
- expect(split.content()).toMatchObject(channelWithTarget);
-
- dispose();
- });
- });
- });
-
- describe('adoptContentId', () => {
- it('moves the split onto the new id without remounting or pushing history', () => {
- createRoot((dispose) => {
- const orchestrator = createMockOrchestrator();
- const manager = createSplitLayout(orchestrator, [
- { type: 'agent', id: 'pending-1' },
- ]);
- const split = manager.splits()[0]!;
- const handle = manager.getSplit(split.id)!;
- const mountBefore = split.mount;
- const historyLengthBefore = handle.history().length;
- const mountsBefore = (
- orchestrator.createBlockInstance as ReturnType<typeof vi.fn>
- ).mock.calls.length;
-
- handle.adoptContentId({ type: 'agent', nextId: 'session-1' });
-
- const after = manager.splits()[0]!;
- expect(after.content).toEqual({ type: 'agent', id: 'session-1' });
- // The same block instance, re-labelled: nothing was mounted again.
- expect(after.mount.kind).toBe('block');
- expect(
- after.mount.kind === 'block' ? after.mount.handle : undefined
- ).toBe(mountBefore.kind === 'block' ? mountBefore.handle : null);
- expect(
- (orchestrator.createBlockInstance as ReturnType<typeof vi.fn>).mock
- .calls.length
- ).toBe(mountsBefore);
- expect(handle.history()).toHaveLength(historyLengthBefore);
- expect(handle.history().at(-1)).toEqual({
- type: 'agent',
- id: 'session-1',
- });
- expect(orchestrator.rekeyBlockInstance).toHaveBeenCalledWith(
- 'agent',
- 'pending-1',
- 'session-1'
- );
- // `replace` is what the URL sync reads to swap the path in place
- // rather than adding a step back to a placeholder.
- expect(after.lastNavigationCause).toBe('replace');
-
- dispose();
- });
- });
-
- it('ignores a type that is not what the split is showing', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'agent', id: 'pending-1' },
- ]);
- const handle = manager.getSplit(manager.splits()[0]!.id)!;
-
- handle.adoptContentId({ type: 'md', nextId: 'session-1' });
-
- expect(manager.splits()[0]!.content).toEqual({
- type: 'agent',
- id: 'pending-1',
- });
- dispose();
- });
- });
-
- it('refuses an id another split already shows', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'agent', id: 'pending-1' },
- { type: 'agent', id: 'session-1' },
- ]);
- const handle = manager.getSplit(manager.splits()[0]!.id)!;
-
- handle.adoptContentId({ type: 'agent', nextId: 'session-1' });
-
- expect(manager.splits()[0]!.content).toEqual({
- type: 'agent',
- id: 'pending-1',
- });
- dispose();
- });
- });
- });
-
- describe('replaceAllSplits', () => {
- it('keeps the first split that already contains the target content', () => {
- createRoot((dispose) => {
- const target = {
- type: 'component',
- id: 'documents',
- } satisfies SplitContent;
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- target,
- { type: 'component', id: 'documents' },
- { type: 'md', id: 'right' },
- ]);
-
- const keptSplitId = manager.splits()[1].id;
- const keptSplit = manager.getSplit(keptSplitId)!;
- const historyBefore = keptSplit.history();
- const handle = manager.replaceAllSplits(target, {
- referredFrom: 'sidebar',
- });
- if (!handle) throw new Error('Expected content to open');
-
- expect(manager.splits()).toHaveLength(1);
- expect(manager.splits()[0].id).toBe(keptSplitId);
- expect(manager.splits()[0].content).toEqual(target);
- expect(manager.activeSplitId()).toBe(handle.id);
- expect(handle.history()).toEqual(historyBefore);
-
- dispose();
- });
- });
-
- it('keeps the 0th split and replaces it when the target content is not open', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'md', id: 'right' },
- ]);
- const keptSplitId = manager.splits()[0].id;
- manager.spotlightSplit(manager.splits()[1].id);
-
- const target = {
- type: 'component',
- id: 'documents',
- } satisfies SplitContent;
- const handle = manager.replaceAllSplits(target, {
- referredFrom: 'sidebar',
- });
- if (!handle) throw new Error('Expected content to open');
-
- expect(manager.splits()).toHaveLength(1);
- expect(manager.splits()[0].id).toBe(keptSplitId);
- expect(manager.splits()[0].content).toEqual(target);
- expect(manager.activeSplitId()).toBe(handle.id);
- expect(handle.isSpotLight()).toBe(false);
- expect(handle.previousContent()).toEqual({
- type: 'component',
- id: 'home',
- });
-
- dispose();
- });
- });
- });
-
- describe('indexed insertion', () => {
- it('creates a split at the requested index', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'left' },
- { type: 'md', id: 'right' },
- ]);
-
- const inserted = manager.createNewSplit({
- content: { type: 'component', id: 'unified-list' },
- activate: true,
- referredFrom: null,
- insertIndex: 1,
- });
- if (!inserted) throw new Error('Expected content to open');
-
- expect(manager.splits().map((split) => split.content.id)).toEqual([
- 'left',
- 'unified-list',
- 'right',
- ]);
- expect(manager.activeSplitId()).toBe(inserted.id);
-
- dispose();
- });
- });
-
- it('opens duplicate content at the requested index when duplicates are allowed', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'unified-list' },
- { type: 'md', id: 'current' },
- ]);
-
- const inserted = manager.openWithSplit(
- { type: 'component', id: 'unified-list' },
- {
- allowDuplicate: true,
- preferNewSplit: true,
- insertIndex: 1,
- }
- );
-
- expect(manager.splits().map((split) => split.content.id)).toEqual([
- 'unified-list',
- 'unified-list',
- 'current',
- ]);
- expect(manager.activeSplitId()).toBe(inserted.split?.id);
-
- dispose();
- });
- });
- });
-
- describe('activation invariant', () => {
- it('reports direct mobile navigation applied after forward promotion', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const swipe = createMobileSwipeLayout(manager);
- const animate = vi.fn();
- const onApplied = vi.fn();
- swipe.setForwardNavigationTrigger(animate);
-
- const result = manager.openWithSplit(
- { type: 'email', id: 'thread' },
- { onApplied }
- );
-
- expect(result).toMatchObject({ status: 'navigating' });
- expect(animate).toHaveBeenCalledOnce();
- expect(onApplied).not.toHaveBeenCalled();
- swipe.completeNavigateForward();
- expect(onApplied).toHaveBeenCalledOnce();
-
- dispose();
- });
- });
-
- it.each(['foreground', 'background'] as const)(
- 'reuses the mobile %s conversation across Agents routes and blocks',
- (position) => {
- const route: SplitContent = {
- type: 'component',
- id: agentsRouteId({
- mode: 'chat',
- conversation: { type: 'chat', id: 'conversation' },
- }),
- };
- const block: SplitContent = { type: 'chat', id: 'conversation' };
- for (const [initial, target] of [
- [route, block],
- [block, route],
- [block, block],
- ]) {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- position === 'foreground'
- ? { type: 'component', id: 'home' }
- : initial,
- ]);
- const swipe = createMobileSwipeLayout(manager);
- manager.openWithSplit(
- position === 'foreground'
- ? initial
- : { type: 'component', id: 'home' }
- );
- const owner = manager.findOpenView(target)!.topLevelSplit!;
- const mount = manager
- .splits()
- .find((split) => split.id === owner.id)!.mount;
- const ids = manager.splits().map((split) => split.id);
- vi.mocked(toast.alert).mockClear();
-
- manager.openWithSplit(target);
-
- expect(manager.activeSplitId()).toBe(owner.id);
- expect(manager.splits().map((split) => split.id)).toEqual(ids);
- expect(
- manager.splits().find((split) => split.id === owner.id)!.mount
- ).toBe(mount);
- expect(swipe.slotASplitId()).not.toBe(swipe.slotBSplitId());
- expect(swipe.canGoBack()).toBe(true);
- expect(toast.alert).not.toHaveBeenCalled();
- swipe.swipeBack();
- expect(
- manager.getSplit(manager.activeSplitId()!)!.content().id
- ).toBe('home');
- dispose();
- });
- }
- }
- );
-
- it('reports reuse when mobile navigation promotes an existing pane', () => {
- createRoot((dispose) => {
- const content = { type: 'email', id: 'background' } as const;
- const manager = createSplitLayout(createMockOrchestrator(), [content]);
- const owner = manager.splits()[0].id;
- createMobileSwipeLayout(manager);
- manager.openWithSplit({ type: 'email', id: 'foreground' });
- vi.mocked(toast.alert).mockClear();
- const result = manager.openWithSplit(content);
- expect(result).toMatchObject({
- status: 'reused',
- owner,
- split: { id: owner },
- });
- expect(manager.activeSplitId()).toBe(owner);
- expect(manager.splits()).toHaveLength(2);
- expect(toast.alert).not.toHaveBeenCalled();
- dispose();
- });
- });
-
- it.each(['refused', 'reused'] as const)(
- 'preserves mobile slots when creation is %s',
- (result) => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const swipe = createMobileSwipeLayout(manager);
- manager.openWithSplit({ type: 'email', id: 'foreground' });
- const foreground = manager.getSplit(manager.activeSplitId()!)!;
- const ids = manager.splits().map((split) => split.id);
- const slots = [
- swipe.slotASplitId(),
- swipe.slotBSplitId(),
- swipe.fgIsSlotA(),
- ];
- const animate = vi.fn();
- swipe.setForwardNavigationTrigger(animate);
- vi.spyOn(manager, 'createNewSplit').mockReturnValueOnce(
- result === 'reused' ? foreground : undefined
- );
- expect(
- manager.openWithSplit({ type: 'email', id: 'next' })
- ).toMatchObject({ status: 'unavailable' });
- expect(manager.splits().map((split) => split.id)).toEqual(ids);
- expect([
- swipe.slotASplitId(),
- swipe.slotBSplitId(),
- swipe.fgIsSlotA(),
- ]).toEqual(slots);
- expect(manager.activeSplitId()).toBe(foreground.id);
- expect(animate).not.toHaveBeenCalled();
- dispose();
- });
- }
- );
-
- it('promotes an occupied mobile background when direct replacement is refused', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'email', id: 'background' },
- ]);
- const owner = manager.splits()[0].id;
- const swipe = createMobileSwipeLayout(manager);
- manager.openWithSplit({ type: 'email', id: 'foreground' });
- const source = manager.getSplit(manager.activeSplitId()!)!;
- source.replace({ next: { type: 'email', id: 'background' } });
- expect(manager.activeSplitId()).toBe(owner);
- expect(source.content().id).toBe('foreground');
- expect(manager.splits()).toHaveLength(2);
- expect(swipe.slotASplitId()).not.toBe(swipe.slotBSplitId());
- dispose();
- });
- });
-
- it('skips already-mounted history when rebuilding the mobile background', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- ]);
- const handle = manager.getSplit(manager.splits()[0].id)!;
- handle.replace({ next: { type: 'chat', id: 'conversation' } });
- handle.replace({ next: { type: 'chat', id: 'conversation' } });
- const swipe = createMobileSwipeLayout(manager);
- manager.openWithSplit({ type: 'email', id: 'next' });
- vi.mocked(toast.alert).mockClear();
- swipe.swipeBack();
- expect(manager.activeSplitId()).toBe(handle.id);
- expect(swipe.slotASplitId()).not.toBe(swipe.slotBSplitId());
- expect(manager.splits().map((split) => split.content.id)).toEqual([
- 'conversation',
- 'home',
- ]);
- expect(toast.alert).not.toHaveBeenCalled();
- swipe.swipeBack();
- expect(manager.getSplit(manager.activeSplitId()!)!.content().id).toBe(
- 'home'
- );
- dispose();
- });
- });
-
- it('refreshes the list source when reopening an email already mounted in the native background', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'email', id: 'a' },
- ]);
- const detail = manager.getSplit(manager.splits()[0].id)!;
- const swipeLayout = createMobileSwipeLayout(manager);
- manager.openWithSplit({ type: 'component', id: 'mail' });
- const list = manager.getSplit(manager.activeSplitId()!)!;
- manager.openWithSplit(
- withListNavigationSource({ type: 'email', id: 'a' }, list),
- { handle: list, referredFrom: 'mail' }
- );
- expect(manager.activeSplitId()).toBe(detail.id);
- expect(detail.referredFrom()).toBe('mail');
- expect(listNavigationSourceId(detail)).toBe(list.id);
- expect(manager.splits()).toHaveLength(2);
- swipeLayout.swipeBack();
- expect(manager.activeSplitId()).toBe(list.id);
- dispose();
- });
- });
-
- it('preserves the native source list through repeated email steps and swipe back', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'mail', state: { 'mail.tab': 'noise' } },
- ]);
- const list = manager.getSplit(manager.splits()[0].id)!;
- const disposeListSource = createRoot((dispose) => {
- registerListNavigationSource(list, {
- viewId: 'mail',
- entities: () => [],
- hasMore: () => false,
- loadMore: async () => {},
- });
- return dispose;
- });
- const source = getListNavigationSource(list.id);
- const swipeLayout = createMobileSwipeLayout(manager);
- manager.openWithSplit(
- withListNavigationSource({ type: 'email', id: 'a' }, list),
- { handle: list, referredFrom: 'mail' }
- );
- const detail = manager.getSplit(manager.activeSplitId()!)!;
- expect(detail.id).not.toBe(list.id);
- expect(getListNavigationSource(listNavigationSourceId(detail))).toBe(
- source
- );
-
- for (const id of ['b', 'c']) {
- manager.openWithSplit(
- withListNavigationSource({ type: 'email', id }, detail),
- { handle: detail, referredFrom: 'mail', mergeHistory: true }
- );
- expect(manager.activeSplitId()).toBe(detail.id);
- expect(detail.content().id).toBe(id);
- expect(getListNavigationSource(listNavigationSourceId(detail))).toBe(
- source
- );
- expect(manager.splits()).toHaveLength(2);
- expect(list.content().state?.['mail.tab']).toBe('noise');
- }
- // Opening an attachment discards the background list. Its component
- // disposes the source; swipe-back mounts that history entry anew.
- manager.openWithSplit(
- { type: 'md', id: 'attachment' },
- { handle: detail, referredFrom: 'attachment' }
- );
- expect(manager.getSplit(list.id)).toBeUndefined();
- disposeListSource();
- expect(
- getListNavigationSource(listNavigationSourceId(detail))
- ).toBeUndefined();
- swipeLayout.swipeBack();
- expect(manager.activeSplitId()).toBe(detail.id);
- const restoredList = manager.getSplit(
- manager.splits().find((split) => split.content.id === 'mail')!.id
- )!;
- expect(restoredList.id).not.toBe(list.id);
- expect(restoredList.content().state?.['mail.tab']).toBe('noise');
- registerListNavigationSource(restoredList, source!);
- expect(getListNavigationSource(listNavigationSourceId(detail))).toBe(
- source
- );
- manager.openWithSplit(
- withListNavigationSource({ type: 'email', id: 'd' }, detail),
- { handle: detail, referredFrom: 'mail', mergeHistory: true }
- );
- expect(detail.content().id).toBe('d');
- swipeLayout.swipeBack();
- expect(manager.activeSplitId()).toBe(restoredList.id);
- expect(restoredList.content().id).toBe('mail');
- dispose();
- });
- });
-
- it('refuses to activate an excluded split', () => {
- createRoot((dispose) => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'foreground' },
- { type: 'md', id: 'background' },
- ]);
-
- const [fg, bg] = manager.splits();
- expect(shouldShowSplitCloseButton(manager)).toBe(true);
- manager.activateSplit(fg.id);
- manager.setExclusionFilter((split) => split.id === bg.id);
- expect(shouldShowSplitCloseButton(manager)).toBe(false);
-
- manager.activateSplit(bg.id);
- expect(manager.activeSplitId()).toBe(fg.id);
-
- manager.setExclusionFilter(undefined);
- expect(shouldShowSplitCloseButton(manager)).toBe(true);
- manager.activateSplit(bg.id);
- expect(manager.activeSplitId()).toBe(bg.id);
-
- warn.mockRestore();
- dispose();
- });
- });
-
- it('keeps the promoted split active through mobile forward navigation and swipe back', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'md', id: 'list' },
- ]);
- const originalId = manager.splits()[0].id;
- manager.activateSplit(originalId);
-
- const swipeLayout = createMobileSwipeLayout(manager);
-
- // Forward navigation goes through the interceptor; with no animation
- // trigger registered it completes synchronously.
- manager.openWithSplit(
- { type: 'md', id: 'detail' },
- { referredFrom: null }
- );
-
- const detailId = swipeLayout.fgIsSlotA()
- ? swipeLayout.slotASplitId()
- : swipeLayout.slotBSplitId();
- expect(detailId).toBeDefined();
- expect(detailId).not.toBe(originalId);
- expect(manager.activeSplitId()).toBe(detailId);
-
- swipeLayout.swipeBack();
- expect(manager.activeSplitId()).toBe(originalId);
-
- dispose();
- });
- });
- });
-
- describe('popover splits', () => {
- it('lets an onClose handler decide when a popover finishes closing', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), []);
- const onClose = vi.fn();
- const popover = manager.createPopoverSplit({
- content: { type: 'component', id: 'composer' },
- onClose,
- });
- if (!popover) throw new Error('Expected content to open');
-
- popover.close();
-
- expect(onClose).toHaveBeenCalledOnce();
- expect(popover.isOpen()).toBe(true);
-
- const finishClose = onClose.mock.calls[0][0];
- finishClose();
- expect(popover.isOpen()).toBe(false);
-
- dispose();
- });
- });
-
- it('closes immediately when no onClose handler is provided', () => {
- createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), []);
- const popover = manager.createPopoverSplit({
- content: { type: 'component', id: 'composer' },
- });
- if (!popover) throw new Error('Expected content to open');
-
- popover.close();
-
- expect(popover.isOpen()).toBe(false);
- dispose();
- });
- });
- });
-});
diff --git a/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts b/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts
index 21e769dd12..640446ee79 100644
--- a/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts
+++ b/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts
@@ -9,8 +9,9 @@ import {
it,
vi,
} from 'vitest';
-import { createSplitLayout, type SplitId } from '../layoutManager';
+import type { SplitId } from '../layoutManager';
import { createSplitFocusTracker } from '../splitFocusTracker';
+import { createRoutedSplitLayout } from './fixtures';
vi.mock('../componentRegistry', () => ({
resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({
@@ -69,10 +70,10 @@ const FOCUS_DEBOUNCE_MS = 50;
*/
function mountFreshLoad() {
return createRoot((dispose) => {
- const manager = createSplitLayout(createMockOrchestrator(), [
- { type: 'component', id: 'home' },
- { type: 'md', id: 'doc-1' },
- ]);
+ const manager = createRoutedSplitLayout(
+ createMockOrchestrator(),
+ '/home/~/channels'
+ );
const panelRefs = new Map<SplitId, HTMLDivElement>(
manager.splits().map((split) => [split.id, createPanel()])
diff --git a/apps/web/src/features/activity/route.tsx b/apps/web/src/features/activity/route-views.tsx
similarity index 78%
rename from apps/web/src/features/activity/route.tsx
rename to apps/web/src/features/activity/route-views.tsx
index 856fa59976..4f1c1856c5 100644
--- a/apps/web/src/features/activity/route.tsx
+++ b/apps/web/src/features/activity/route-views.tsx
@@ -1,5 +1,4 @@
import { usePosthog } from '@app/lib/analytics/posthog';
-import { defineRoute } from '@app/lib/split-router';
import {
RedirectSplit,
usePageViewTracking,
@@ -34,11 +33,3 @@ export const ActivityRouteView = withAuth(() => {
</Show>
);
});
-
-export const activityRoute = defineRoute({
- id: 'view-activity',
- path: 'activity',
- component: ActivityRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'activity' }),
-});
diff --git a/apps/web/src/features/agent-changes/pane-view-state.ts b/apps/web/src/features/agent-changes/pane-view-state.ts
index 853490f53d..86d0c371ea 100644
--- a/apps/web/src/features/agent-changes/pane-view-state.ts
+++ b/apps/web/src/features/agent-changes/pane-view-state.ts
@@ -1,7 +1,4 @@
-import {
- createSearchParams,
- useOwnsSearchNamespace,
-} from '@app/lib/split-router';
+import { createSearchParams, useOwnsSearchNamespace } from '@app/split-router';
import { createSignal } from 'solid-js';
import { changesSearch } from './changes-search';
import type { PaneViewState } from './context/agent-changes-context';
diff --git a/apps/web/src/features/agents-view/route.test.tsx b/apps/web/src/features/agents-view/route-views.test.tsx
similarity index 94%
rename from apps/web/src/features/agents-view/route.test.tsx
rename to apps/web/src/features/agents-view/route-views.test.tsx
index 26f06f0ee7..bc5f1a2ec6 100644
--- a/apps/web/src/features/agents-view/route.test.tsx
+++ b/apps/web/src/features/agents-view/route-views.test.tsx
@@ -1,7 +1,7 @@
import { cleanup, render } from '@solidjs/testing-library';
import { createSignal, Suspense } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { AgentsRouteView } from './route';
+import { AgentsRouteView } from './route-views';
const state = vi.hoisted(() => ({
flag: (): { enabled: boolean; loading: boolean } => ({
@@ -17,8 +17,8 @@ const state = vi.hoisted(() => ({
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => state.flag,
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
defineRoute: (route: unknown) => route,
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
diff --git a/apps/web/src/features/agents-view/route.tsx b/apps/web/src/features/agents-view/route-views.tsx
similarity index 69%
rename from apps/web/src/features/agents-view/route.tsx
rename to apps/web/src/features/agents-view/route-views.tsx
index ef8c252b5b..bc227f477b 100644
--- a/apps/web/src/features/agents-view/route.tsx
+++ b/apps/web/src/features/agents-view/route-views.tsx
@@ -1,21 +1,16 @@
-import { changesSearch } from '@app/features/agent-changes/changes-search';
-import { agentDetailSearch } from '@app/features/block-agent/agent-route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { defineRoute } from '@app/lib/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import {
RedirectSplit,
usePageViewTracking,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableChatV3Agents } from '@core/constant/featureFlags';
import { useUserContext } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useAutomationEntities } from '@queries/agent-schedule/entities';
import { createRenderEffect, lazy, Show } from 'solid-js';
-import { z } from 'zod';
import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';
import { parseAgentsRoute } from './core/route';
@@ -122,46 +117,3 @@ export const AgentsRouteView = withAuth(() => {
</Show>
);
});
-
-export const agentsRoute = defineRoute({
- id: 'agents',
- path: 'agents/:id',
- params: z.object({ id: z.string() }),
- component: AgentsRouteView,
- remountKey: ({ id }) => id,
- claim: ({ id }) => ({ namespace: 'agent', id }),
- search: [changesSearch.namespace, agentDetailSearch.namespace],
- toReference: ({ id }) => uuidRouteReference(id, 'agent'),
-});
-
-export const codersRoute = defineRoute({
- id: 'coders',
- path: 'coders/:id',
- params: z.object({ id: z.string() }),
- component: AgentsRouteView,
- remountKey: ({ id }) => id,
- claim: ({ id }) => ({ namespace: 'agent', id }),
- search: [changesSearch.namespace, agentDetailSearch.namespace],
- toReference: ({ id }) => uuidRouteReference(id, 'agent'),
-});
-
-export const agentChatsRoute = defineRoute({
- id: 'agent-chats',
- path: 'agents/chat/:id',
- aliases: ['agent-chats/:id'],
- params: z.object({ id: z.string() }),
- component: AgentsRouteView,
- remountKey: ({ id }) => id,
- claim: ({ id }) => ({ namespace: 'chat', id }),
- search: [changesSearch.namespace],
- toReference: ({ id }) => uuidRouteReference(id, 'chat'),
-});
-
-export const agentsViewRoute = defineRoute({
- id: 'view-agents',
- path: 'agents',
- component: AgentsRouteView,
- search: '*' as const,
- externalSearch: ['createAgent'],
- claim: () => ({ namespace: 'component', id: 'agents' }),
-});
diff --git a/apps/web/src/features/block-agent/agent-route.ts b/apps/web/src/features/block-agent/agent-route.ts
index 4ec83c07b3..96de03eb10 100644
--- a/apps/web/src/features/block-agent/agent-route.ts
+++ b/apps/web/src/features/block-agent/agent-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
export const agentDetailSearch = {
diff --git a/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts b/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts
index 7f2d537e40..42de129c40 100644
--- a/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts
+++ b/apps/web/src/features/block-agent/primitives/create-agent-route-target.ts
@@ -1,4 +1,4 @@
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import { createMemo } from 'solid-js';
import { agentDetailSearch } from '../agent-route';
import type { AgentMessageTarget } from '../core/search-location';
diff --git a/apps/web/src/features/block-call/call-route.ts b/apps/web/src/features/block-call/call-route.ts
index c6d6762c98..6b4fef3f15 100644
--- a/apps/web/src/features/block-call/call-route.ts
+++ b/apps/web/src/features/block-call/call-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
export const callDetailSearch = {
diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx
index c222f28d6d..76464e5499 100644
--- a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx
+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx
@@ -9,8 +9,8 @@ const state = vi.hoisted(() => ({
setSearch: vi.fn(),
navigate: (_params: CallBlockProps) => {},
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
createSearchParams: () => [state.search, state.setSearch],
}));
vi.mock('@app/signal/splitLayout', () => ({
diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
index 33254c3f73..e7331ee22f 100644
--- a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx
@@ -1,5 +1,5 @@
-import { createSearchParams } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { createSearchParams } from '@app/split-router';
import {
type CallBlockProps,
type CallTranscriptTarget,
diff --git a/apps/web/src/features/block-call/route.tsx b/apps/web/src/features/block-call/route-views.tsx
similarity index 58%
rename from apps/web/src/features/block-call/route.tsx
rename to apps/web/src/features/block-call/route-views.tsx
index 3f31e791a0..91f6a3f137 100644
--- a/apps/web/src/features/block-call/route.tsx
+++ b/apps/web/src/features/block-call/route-views.tsx
@@ -1,20 +1,15 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import {
- createSearchParams,
- defineRoute,
- useRouteParams,
-} from '@app/lib/split-router';
+import { callDetailRoute } from '@app/routes/routes';
+import { createSearchParams, useRouteParams } from '@app/split-router';
import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
import { lazy, onMount } from 'solid-js';
-import { z } from 'zod';
import { callDetailSearch } from './call-route';
-import { URL_PARAMS } from './constants';
const StandaloneCallDetail = lazy(async () => ({
default: (await import('./views/CallDetailView')).StandaloneCallDetail,
}));
-const CallDetailRouteView = withAuth(() => {
+export const CallDetailRouteView = withAuth(() => {
const params = useRouteParams(callDetailRoute);
const [search] = createSearchParams(callDetailSearch);
const analytics = useAnalytics();
@@ -34,14 +29,3 @@ const CallDetailRouteView = withAuth(() => {
/>
);
});
-
-export const callDetailRoute = defineRoute({
- id: 'call-detail',
- path: 'call/:callId',
- params: z.object({ callId: z.string().min(1) }),
- search: [callDetailSearch.namespace],
- externalSearch: [URL_PARAMS.transcriptId, URL_PARAMS.messageId],
- component: CallDetailRouteView,
- remountKey: ({ callId }) => callId,
- claim: ({ callId }) => ({ namespace: 'block', id: `call:${callId}` }),
-});
diff --git a/apps/web/src/features/block-call/views/CallDetailView.test.tsx b/apps/web/src/features/block-call/views/CallDetailView.test.tsx
index 4d2a7ac0bc..bf9f3da4a3 100644
--- a/apps/web/src/features/block-call/views/CallDetailView.test.tsx
+++ b/apps/web/src/features/block-call/views/CallDetailView.test.tsx
@@ -23,7 +23,7 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/split-router', () => ({
createSearchParams: () => [{}, mocks.setSearch],
}));
vi.mock('../call-route', () => ({
diff --git a/apps/web/src/features/block-call/views/CallDetailView.tsx b/apps/web/src/features/block-call/views/CallDetailView.tsx
index a54bf122ab..f3275095ad 100644
--- a/apps/web/src/features/block-call/views/CallDetailView.tsx
+++ b/apps/web/src/features/block-call/views/CallDetailView.tsx
@@ -1,5 +1,5 @@
import { ViewShell } from '@app/components/view-shell';
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import { SidePanel } from '@components/app/side-panel';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
index b3ed8e7a6d..830dfd6ed9 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
@@ -9,8 +9,8 @@ const state = vi.hoisted(() => ({
navigate: (_params: Record<string, unknown>) => {},
latest: () => {},
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
createSearchParams: () => [state.search],
}));
vi.mock('@app/signal/splitLayout', () => ({
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 02f263b879..dffeb9bfc5 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -8,8 +8,8 @@ import {
makeRenameAction,
useBlockEntityCommands,
} from '@app/features/next-soup/actions';
-import { createSearchParams } from '@app/lib/split-router';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { createSearchParams } from '@app/split-router';
import { URL_PARAMS } from '@block-channel/constants';
import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';
import { useChannelBotManagement } from '@channel/Bots/use-channel-bot-management';
diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx
index 304fb7cd60..a4624a197b 100644
--- a/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx
+++ b/apps/web/src/features/block-email/EmailBlockAdapter.test.tsx
@@ -10,8 +10,8 @@ const state = vi.hoisted(() => ({
navigate: (_params: Record<string, unknown>) => {},
host: undefined as EmailThreadHost | undefined,
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
createSearchParams: () => [state.search],
}));
vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));
diff --git a/apps/web/src/features/block-email/EmailBlockAdapter.tsx b/apps/web/src/features/block-email/EmailBlockAdapter.tsx
index 83b37c866b..555e393e2b 100644
--- a/apps/web/src/features/block-email/EmailBlockAdapter.tsx
+++ b/apps/web/src/features/block-email/EmailBlockAdapter.tsx
@@ -4,7 +4,7 @@ import type {
} from '@app/features/email-thread/context/email-thread-context';
import { URL_PARAMS } from '@app/features/email-thread/core/location';
import { emailDetailSearch } from '@app/features/email-view/email-route';
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import {
useCanAutofocusSplitContent,
useSplitPanel,
diff --git a/apps/web/src/features/block-md/markdown-route.ts b/apps/web/src/features/block-md/markdown-route.ts
index ac8bb0f733..a03d4e4386 100644
--- a/apps/web/src/features/block-md/markdown-route.ts
+++ b/apps/web/src/features/block-md/markdown-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
export const markdownDetailSearch = {
diff --git a/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts
index 90a949923e..ff79a8e444 100644
--- a/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts
+++ b/apps/web/src/features/block-md/primitives/create-markdown-route-navigation.ts
@@ -1,4 +1,4 @@
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import { type Accessor, createEffect, on } from 'solid-js';
import { URL_PARAMS } from '../constants';
import { markdownDetailSearch } from '../markdown-route';
diff --git a/apps/web/src/features/block-pdf/pdf-route.ts b/apps/web/src/features/block-pdf/pdf-route.ts
index 317da88acc..002b41577e 100644
--- a/apps/web/src/features/block-pdf/pdf-route.ts
+++ b/apps/web/src/features/block-pdf/pdf-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
export const pdfDetailSearch = {
diff --git a/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts
index 3c4d25982a..a10cc73863 100644
--- a/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts
+++ b/apps/web/src/features/block-pdf/primitives/create-pdf-route-target.ts
@@ -1,4 +1,4 @@
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import { type Accessor, createMemo } from 'solid-js';
import { URL_PARAMS } from '../constants';
import { pdfDetailSearch } from '../pdf-route';
diff --git a/apps/web/src/features/block-pr/route.tsx b/apps/web/src/features/block-pr/route-views.tsx
similarity index 52%
rename from apps/web/src/features/block-pr/route.tsx
rename to apps/web/src/features/block-pr/route-views.tsx
index f18466fffe..1c0181ade4 100644
--- a/apps/web/src/features/block-pr/route.tsx
+++ b/apps/web/src/features/block-pr/route-views.tsx
@@ -1,15 +1,13 @@
-import { changesSearch } from '@app/features/agent-changes/changes-search';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { defineRoute, useParams } from '@app/lib/split-router';
+import { useParams } from '@app/split-router';
import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
import { lazy, onMount } from 'solid-js';
-import { z } from 'zod';
const StandalonePrDetail = lazy(async () => ({
default: (await import('./views/PrDetail')).StandalonePrDetail,
}));
-const PrDetailRouteView = withAuth(() => {
+export const PrDetailRouteView = withAuth(() => {
const params = useParams<{ foreignEntityId: string }>();
const analytics = useAnalytics();
onMount(() => {
@@ -21,16 +19,3 @@ const PrDetailRouteView = withAuth(() => {
});
return <StandalonePrDetail foreignEntityId={params.foreignEntityId} />;
});
-
-export const prDetailRoute = defineRoute({
- id: 'pr-detail',
- path: 'pr/:foreignEntityId',
- params: z.object({ foreignEntityId: z.string().min(1) }),
- component: PrDetailRouteView,
- remountKey: ({ foreignEntityId }) => foreignEntityId,
- claim: ({ foreignEntityId }) => ({
- namespace: 'block',
- id: `pr:${foreignEntityId}`,
- }),
- search: [changesSearch.namespace],
-});
diff --git a/apps/web/src/features/calendar-view/calendar-navigation.test.ts b/apps/web/src/features/calendar-view/calendar-navigation.test.ts
index ed3cfb5126..28425c1b38 100644
--- a/apps/web/src/features/calendar-view/calendar-navigation.test.ts
+++ b/apps/web/src/features/calendar-view/calendar-navigation.test.ts
@@ -1,3 +1,4 @@
+import { paneRoute } from '@app/routes/app-route';
import type {
SplitHandle,
SplitManager,
@@ -22,14 +23,10 @@ describe('Calendar view navigation', () => {
focusRequestId: expect.any(Number),
},
entryMetadata: {
- route: {
- matches: [
- {
- id: 'view-calendar',
- params: { period: 'dayGridMonth' },
- },
- ],
- },
+ route: paneRoute({
+ id: 'view-calendar',
+ params: { period: 'dayGridMonth' },
+ }),
search: {
calendar: { eventId: ['event-1'], occurrenceKey: ['instance-1'] },
},
diff --git a/apps/web/src/features/calendar-view/calendar-navigation.ts b/apps/web/src/features/calendar-view/calendar-navigation.ts
index 8959c90c2b..a0ecff1881 100644
--- a/apps/web/src/features/calendar-view/calendar-navigation.ts
+++ b/apps/web/src/features/calendar-view/calendar-navigation.ts
@@ -1,5 +1,6 @@
import { getPreferredCalendarPeriodView } from '@app/features/calendar/calendar-preferences';
import type { CalendarPeriodView } from '@app/features/calendar/types';
+import { paneRoute } from '@app/routes/app-route';
import { globalSplitManager } from '@app/signal/splitLayout';
import type {
OpenSplitResult,
@@ -52,9 +53,7 @@ export function calendarViewContent(
id: CALENDAR_VIEW_ID,
...(params ? { params: { ...params } } : {}),
entryMetadata: {
- route: {
- matches: [{ id: CALENDAR_ROUTE_ID, params: { period } }],
- },
+ route: paneRoute({ id: CALENDAR_ROUTE_ID, params: { period } }),
...(search ? { search: { [CALENDAR_SEARCH_NAMESPACE]: search } } : {}),
},
};
diff --git a/apps/web/src/features/calendar-view/calendar-url.ts b/apps/web/src/features/calendar-view/calendar-url.ts
index 8d1d17a792..9cf31845b1 100644
--- a/apps/web/src/features/calendar-view/calendar-url.ts
+++ b/apps/web/src/features/calendar-view/calendar-url.ts
@@ -1,5 +1,5 @@
import type { CalendarPeriodView } from '@app/features/calendar/types';
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import { createCalendarRange } from './calendar-range';
import type { CalendarViewTarget } from './types';
diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsx
index 75132aa3d7..578aeadcba 100644
--- a/apps/web/src/features/calendar-view/calendar-view.tsx
+++ b/apps/web/src/features/calendar-view/calendar-view.tsx
@@ -4,11 +4,7 @@ import type { CalendarPeriodView } from '@app/features/calendar/types';
import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { usePosthog } from '@app/lib/analytics/posthog';
-import {
- createSearchParams,
- useNavigate,
- useParams,
-} from '@app/lib/split-router';
+import { createSearchParams, useNavigate, useParams } from '@app/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { useUserId } from '@core/context/user';
diff --git a/apps/web/src/features/calendar-view/route-views.tsx b/apps/web/src/features/calendar-view/route-views.tsx
new file mode 100644
index 0000000000..2e08ee1625
--- /dev/null
+++ b/apps/web/src/features/calendar-view/route-views.tsx
@@ -0,0 +1,11 @@
+import { calendarSplitRoute } from '@app/routes/routes';
+import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
+import { lazy } from 'solid-js';
+
+const CalendarView = lazy(async () => ({
+ default: (await import('./calendar-view')).CalendarView,
+}));
+
+export const CalendarRouteView = withAuth(() => (
+ <CalendarView route={calendarSplitRoute} />
+));
diff --git a/apps/web/src/features/calendar-view/route.tsx b/apps/web/src/features/calendar-view/route.tsx
deleted file mode 100644
index 4a49fa4f23..0000000000
--- a/apps/web/src/features/calendar-view/route.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { defineRoute } from '@app/lib/split-router';
-import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';
-import { lazy } from 'solid-js';
-import {
- CALENDAR_ROUTE_ID,
- CALENDAR_SEARCH_NAMESPACE,
- calendarPeriodParams,
- calendarPeriodPath,
-} from './calendar-url';
-import { CALENDAR_VIEW_ID } from './types';
-
-const CalendarView = lazy(async () => ({
- default: (await import('./calendar-view')).CalendarView,
-}));
-
-export const CalendarRouteView = withAuth(() => (
- <CalendarView route={calendarSplitRoute} />
-));
-
-export const calendarSplitRoute = defineRoute({
- id: CALENDAR_ROUTE_ID,
- path: 'calendar/:period',
- params: calendarPeriodParams,
- serializeParams: ({ period }) => ({
- period: calendarPeriodPath(period),
- }),
- search: [CALENDAR_SEARCH_NAMESPACE],
- externalSearch: ['eventId'],
- component: CalendarRouteView,
- claim: () => ({ namespace: 'component', id: CALENDAR_VIEW_ID }),
-});
diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.ts
index aae666c972..acaff090a7 100644
--- a/apps/web/src/features/channels-view/channels-route.ts
+++ b/apps/web/src/features/channels-view/channels-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import type { ChannelsQueryScope, ChannelsTab } from './types';
diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsx
index c449387c37..0782809c6a 100644
--- a/apps/web/src/features/channels-view/channels-view-context.tsx
+++ b/apps/web/src/features/channels-view/channels-view-context.tsx
@@ -5,11 +5,12 @@ import {
} from '@app/features/next-soup/utils';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { makePersistedState } from '@app/lib/persistence';
+import { channelDetailRoute, channelsSplitRoute } from '@app/routes/routes';
import {
createSearchParams,
useNavigate,
useRouteParams,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { enableChannelThreadsPreview } from '@core/constant/featureFlags';
@@ -26,7 +27,6 @@ import {
clampChannelsRailWidth,
} from './constants';
import { createChannelsViewPersistence } from './persistence';
-import { channelDetailRoute, channelsSplitRoute } from './route';
import type {
ChannelListSort,
ChannelsQueryScope,
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index 46728f11c9..38e244d1a8 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -42,7 +42,7 @@ vi.mock('@queries/soup/search', () => ({
useSearchSoupQuery: () => ({ isSuccess: false, isLoading: false }),
validateSearchServiceText: (text: string) => text.length >= 3,
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/split-router', () => ({
SplitRouter: {
Outlet: (props: { fallback: () => JSX.Element }) => (
<Show when={mocks.selectedId()} fallback={props.fallback()}>
diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsx
index 5deab72c27..fea0783685 100644
--- a/apps/web/src/features/channels-view/channels-view.tsx
+++ b/apps/web/src/features/channels-view/channels-view.tsx
@@ -5,7 +5,7 @@ import { markChannelNotificationsSeenOnOpen } from '@app/features/next-soup/util
import { MaybeSoupEntityActionDrawerManager } from '@app/features/soup';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { ViewTour } from '@app/features/tours/ViewTour';
-import { SplitRouter } from '@app/lib/split-router';
+import { SplitRouter } from '@app/split-router';
import { DebugSuspense } from '@channel/DebugSuspense';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
index afe9a75f42..9182d67522 100644
--- a/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.test.tsx
@@ -7,8 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
routeSearch: vi.fn((): { seek?: string } => ({})),
}));
-vi.mock('@app/lib/split-router', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/lib/split-router')>()),
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
createSearchParams: () => [mocks.routeSearch()],
}));
vi.mock('@app/features/next-soup/actions', () => ({
diff --git a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
index bdb005d5bd..e524ee75de 100644
--- a/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
+++ b/apps/web/src/features/channels-view/components/ChannelDetailView.tsx
@@ -1,5 +1,5 @@
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
-import { createSearchParams } from '@app/lib/split-router';
+import { createSearchParams } from '@app/split-router';
import {
ChannelDetail,
ChannelDetailTopBar,
diff --git a/apps/web/src/features/channels-view/route.tsx b/apps/web/src/features/channels-view/route-views.tsx
similarity index 58%
rename from apps/web/src/features/channels-view/route.tsx
rename to apps/web/src/features/channels-view/route-views.tsx
index 4d63091cd6..3903a76771 100644
--- a/apps/web/src/features/channels-view/route.tsx
+++ b/apps/web/src/features/channels-view/route-views.tsx
@@ -1,8 +1,4 @@
-import {
- createSearchParams,
- defineRoute,
- useParams,
-} from '@app/lib/split-router';
+import { createSearchParams, useParams } from '@app/split-router';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
import {
@@ -10,11 +6,9 @@ import {
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
import { Show } from 'solid-js';
-import { z } from 'zod';
import { channelsSearch } from './channels-route';
-import { ChannelDetailRouteView, ChannelsView } from './channels-view';
+import { ChannelsView } from './channels-view';
function ChannelsLegacyRouteView() {
const params = useParams<{ channelId?: string }>();
@@ -48,25 +42,3 @@ export const ChannelsRouteView = withAuth(() => {
</AppView>
);
});
-
-export const channelDetailRoute = defineRoute({
- id: 'channels-channel',
- path: ':channelId',
- params: z.object({ channelId: z.string().min(1) }),
- component: ChannelDetailRouteView,
- externalSearch: ['channel_message_id', 'channel_thread_id'],
- remountKey: ({ channelId }) => channelId,
- claim: ({ channelId }) => ({
- namespace: 'block',
- id: `channel:${channelId}`,
- }),
- toReference: ({ channelId }) => uuidRouteReference(channelId, 'channel'),
-});
-
-export const channelsSplitRoute = defineRoute({
- id: 'view-channels',
- path: 'channels',
- component: ChannelsRouteView,
- search: '*' as const,
- children: [channelDetailRoute],
-});
diff --git a/apps/web/src/features/crm/route.tsx b/apps/web/src/features/crm/route-views.tsx
similarity index 72%
rename from apps/web/src/features/crm/route.tsx
rename to apps/web/src/features/crm/route-views.tsx
index 7f1b405147..f1c7747e12 100644
--- a/apps/web/src/features/crm/route.tsx
+++ b/apps/web/src/features/crm/route-views.tsx
@@ -1,4 +1,3 @@
-import { defineRoute } from '@app/lib/split-router';
import {
RedirectSplit,
usePageViewTracking,
@@ -26,12 +25,3 @@ export const CompaniesRouteView = withAuth(() => {
<Crm initialView={crmView ? decodeCrmViewParam(crmView) : undefined} />
);
});
-
-export const companiesRoute = defineRoute({
- id: 'view-companies',
- path: 'companies',
- component: CompaniesRouteView,
- search: '*' as const,
- externalSearch: ['crmView'],
- claim: () => ({ namespace: 'component', id: 'companies' }),
-});
diff --git a/apps/web/src/features/drive-view/drive-detail-navigation.tsx b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
index 61273c27a2..d1a0206b01 100644
--- a/apps/web/src/features/drive-view/drive-detail-navigation.tsx
+++ b/apps/web/src/features/drive-view/drive-detail-navigation.tsx
@@ -4,6 +4,7 @@ import type {
EntityDetailNavigationOptions,
EntityDetailTarget,
} from '@app/components/entity-detail/entity-detail-target';
+import { driveSplitRoute } from '@app/routes/routes';
import { useNavigate, useParams, useRouteState } from '@app/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -30,7 +31,6 @@ import {
driveDocumentFromParams,
driveDocumentRoute,
} from './primitives/drive-route';
-import { driveSplitRoute } from './route';
type DriveDetailRootOptions = EntityDetailNavigationOptions & {
location?: DriveLocation;
diff --git a/apps/web/src/features/drive-view/drive-hosted-content.ts b/apps/web/src/features/drive-view/drive-hosted-content.ts
index 6eef92f668..1081638c65 100644
--- a/apps/web/src/features/drive-view/drive-hosted-content.ts
+++ b/apps/web/src/features/drive-view/drive-hosted-content.ts
@@ -1,4 +1,5 @@
-import type { SplitLocation, SplitRouteMatch } from '@app/lib/split-router';
+import { paneRoute } from '@app/routes/app-route';
+import type { SplitLocation, SplitRouteMatch } from '@app/split-router';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
import type { DriveLocation } from './core/types';
import {
@@ -33,7 +34,7 @@ function driveDocumentContent(
return {
type: 'component',
id: 'documents',
- entryMetadata: { route: { matches } },
+ entryMetadata: { route: paneRoute(...matches) },
};
}
@@ -56,12 +57,10 @@ export function driveHostedContent(
type: 'component',
id: 'documents',
entryMetadata: {
- route: {
- matches: [
- { id: 'drive', params: {} },
- { id: 'drive-call', params: { callId: content.id } },
- ],
- },
+ route: paneRoute(
+ { id: 'drive', params: {} },
+ { id: 'drive-call', params: { callId: content.id } }
+ ),
...(options.search ? { search: options.search } : {}),
},
};
diff --git a/apps/web/src/features/drive-view/drive-location-menu.tsx b/apps/web/src/features/drive-view/drive-location-menu.tsx
index b4d8dc4063..6651e116dc 100644
--- a/apps/web/src/features/drive-view/drive-location-menu.tsx
+++ b/apps/web/src/features/drive-view/drive-location-menu.tsx
@@ -48,7 +48,7 @@ export function DriveLocationMenu(
triggerClass="block h-auto"
onOpenCurrentSplit={() => state.navigate(props.location)}
onOpenNewSplit={() =>
- navigate(driveDestination(props.location), { target: 'new-split' })
+ navigate(driveDestination(props.location), { newPane: true })
}
onOpenFullscreen={openFullscreen}
additionalActions={
diff --git a/apps/web/src/features/drive-view/drive-route-navigation.ts b/apps/web/src/features/drive-view/drive-route-navigation.ts
index f01805bfbc..5bbe5fb760 100644
--- a/apps/web/src/features/drive-view/drive-route-navigation.ts
+++ b/apps/web/src/features/drive-view/drive-route-navigation.ts
@@ -1,6 +1,3 @@
-import { match } from 'ts-pattern';
-import type { DriveLocation } from './core/types';
-import type { DriveDocumentRoute } from './primitives/drive-route';
import {
driveFolderDocumentRoute,
driveFolderRoute,
@@ -8,7 +5,10 @@ import {
driveSplitRoute,
driveTabDocumentRoute,
driveTabRoute,
-} from './route';
+} from '@app/routes/routes';
+import { match } from 'ts-pattern';
+import type { DriveLocation } from './core/types';
+import type { DriveDocumentRoute } from './primitives/drive-route';
/** Maps Drive domain selection to a route, including its folder/tab params. */
export function driveDestination(
diff --git a/apps/web/src/features/drive-view/primitives/drive-route-state.ts b/apps/web/src/features/drive-view/primitives/drive-route-state.ts
index 081fa70976..0fa338c926 100644
--- a/apps/web/src/features/drive-view/primitives/drive-route-state.ts
+++ b/apps/web/src/features/drive-view/primitives/drive-route-state.ts
@@ -25,10 +25,7 @@ import { driveDestination } from '../drive-route-navigation';
import { type DriveRouteParams, driveLocationFromParams } from './drive-route';
import { type DriveSearchParams, driveSearch } from './drive-search';
-type NavigationOptions = Pick<
- SplitNavigateOptions<unknown>,
- 'replace' | 'target'
->;
+type NavigationOptions = Pick<SplitNavigateOptions, 'replace'>;
/** URL-owned Drive selection and the one-time legacy launch-facet handoff. */
export function createDriveRouteState(
diff --git a/apps/web/src/features/drive-view/route-views.tsx b/apps/web/src/features/drive-view/route-views.tsx
new file mode 100644
index 0000000000..8ed32c0ef4
--- /dev/null
+++ b/apps/web/src/features/drive-view/route-views.tsx
@@ -0,0 +1,42 @@
+import { driveCallRoute } from '@app/routes/routes';
+import { createSearchParams, useRouteParams } from '@app/split-router';
+import { callDetailSearch } from '@block-call/call-route';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
+import {
+ AppView,
+ withAuth,
+} from '@components/app/split-layout/split-router/app-route-shell';
+import { lazy } from 'solid-js';
+import { DriveView, type DriveViewProps } from './drive-view';
+
+const DriveCallDetail = lazy(async () => ({
+ default: (await import('./views/DriveCallDetail')).DriveCallDetail,
+}));
+
+export const DriveRouteView = withAuth(() => {
+ const panel = useSplitPanelOrThrow();
+ const props = (): DriveViewProps => {
+ const content = panel.handle.content();
+ return content.type === 'component'
+ ? ((content.params ?? {}) as DriveViewProps)
+ : {};
+ };
+ return (
+ <AppView id="documents">
+ <DriveView initialFacets={props().initialFacets} />
+ </AppView>
+ );
+});
+
+export function DriveCallRouteView() {
+ const params = useRouteParams(driveCallRoute);
+ const [search] = createSearchParams(callDetailSearch);
+ return (
+ <DriveCallDetail
+ callId={params.callId}
+ transcriptId={search.transcriptId}
+ messageId={search.messageId}
+ seek={search.seek}
+ />
+ );
+}
diff --git a/apps/web/src/features/drive-view/route.tsx b/apps/web/src/features/drive-view/route.tsx
deleted file mode 100644
index aad91eb56e..0000000000
--- a/apps/web/src/features/drive-view/route.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import { SPREADSHEET_COMMENT_PARAMS } from '@app/features/block-spreadsheet/core/spreadsheet-comments';
-import {
- createSearchParams,
- defineRoute,
- routeParams,
- type SplitRouterEntry,
- useRouteParams,
-} from '@app/lib/split-router';
-import { callDetailSearch } from '@block-call/call-route';
-import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
-import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
-import { markdownDetailSearch } from '@block-md/markdown-route';
-import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
-import { pdfDetailSearch } from '@block-pdf/pdf-route';
-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import {
- AppView,
- withAuth,
-} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
-import { lazy } from 'solid-js';
-import { z } from 'zod';
-import { DriveDetailView } from './components/DriveDetailView';
-import { DriveView, type DriveViewProps } from './drive-view';
-import { driveDetailTrailSchema } from './primitives/drive-detail-trail';
-import {
- DRIVE_DOCUMENT_TYPES,
- driveDocumentBlockType,
-} from './primitives/drive-route-schema';
-
-const DriveCallDetail = lazy(async () => ({
- default: (await import('./views/DriveCallDetail')).DriveCallDetail,
-}));
-
-export const DriveRouteView = withAuth(() => {
- const panel = useSplitPanelOrThrow();
- const props = (): DriveViewProps => {
- const content = panel.handle.content();
- return content.type === 'component'
- ? ((content.params ?? {}) as DriveViewProps)
- : {};
- };
- return (
- <AppView id="documents">
- <DriveView initialFacets={props().initialFacets} />
- </AppView>
- );
-});
-
-function DriveCallRouteView() {
- const params = useRouteParams(driveCallRoute);
- const [search] = createSearchParams(callDetailSearch);
- return (
- <DriveCallDetail
- callId={params.callId}
- transcriptId={search.transcriptId}
- messageId={search.messageId}
- seek={search.seek}
- />
- );
-}
-
-export const driveCallRoute = defineRoute({
- id: 'drive-call',
- path: 'call/:callId',
- params: z.object({ callId: z.string().min(1) }),
- search: [callDetailSearch.namespace],
- component: DriveCallRouteView,
- remountKey: ({ callId }) => callId,
- claim: ({ callId }) => ({ namespace: 'block', id: `call:${callId}` }),
- toReference: ({ callId }) => uuidRouteReference(callId, 'call'),
-});
-const driveDocumentParams = z.object({
- documentType: z.enum(DRIVE_DOCUMENT_TYPES),
- documentId: z.string().min(1),
-});
-
-const documentRemountKey = ({
- documentType,
- documentId,
-}: z.infer<typeof driveDocumentParams>) =>
- `${driveDocumentBlockType(documentType)}:${documentId}`;
-
-export const driveRootDocumentRoute = defineRoute({
- id: 'drive-document',
- search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
- path: ':documentType/:documentId',
- params: driveDocumentParams,
- state: driveDetailTrailSchema,
- component: DriveDetailView,
- remountKey: documentRemountKey,
- claim: ({ documentType, documentId }) => ({
- namespace: 'block',
- id: `${driveDocumentBlockType(documentType)}:${documentId}`,
- }),
- toReference: ({ documentId, documentType }) =>
- uuidRouteReference(documentId, documentType),
-});
-
-export const driveFolderDocumentRoute = defineRoute({
- id: 'drive-folder-document',
- search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
- path: ':documentType/:documentId',
- params: driveDocumentParams,
- state: driveDetailTrailSchema,
- component: DriveDetailView,
- remountKey: documentRemountKey,
- claim: ({ documentType, documentId }) => ({
- namespace: 'block',
- id: `${driveDocumentBlockType(documentType)}:${documentId}`,
- }),
- toReference: ({ documentId, documentType }) =>
- uuidRouteReference(documentId, documentType),
-});
-
-export const driveTabDocumentRoute = defineRoute({
- id: 'drive-tab-document',
- search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
- path: ':documentType/:documentId',
- params: driveDocumentParams,
- state: driveDetailTrailSchema,
- component: DriveDetailView,
- remountKey: documentRemountKey,
- claim: ({ documentType, documentId }) => ({
- namespace: 'block',
- id: `${driveDocumentBlockType(documentType)}:${documentId}`,
- }),
- toReference: ({ documentId, documentType }) =>
- uuidRouteReference(documentId, documentType),
-});
-
-export const driveFolderRoute = defineRoute({
- id: 'drive-folder',
- path: 'folder/:folderId?',
- params: z
- .object({ folderId: z.string().min(1).optional() })
- .transform(({ folderId }) => ({
- view: 'folder' as const,
- folderId,
- })),
- state: driveDetailTrailSchema,
- children: [driveFolderDocumentRoute],
-});
-
-export const driveTabRoute = defineRoute({
- id: 'drive-tab',
- path: ':tab',
- aliases: ['tab/:tab'],
- params: z.object({ tab: z.enum(['recent', 'shared']) }),
- state: driveDetailTrailSchema,
- children: [driveTabDocumentRoute],
-});
-
-export const driveSplitRoute = defineRoute({
- id: 'drive',
- path: 'drive',
- aliases: ['drive/owned', 'drive/tab/owned'],
- component: DriveRouteView,
- search: ['drive'],
- state: driveDetailTrailSchema,
- externalSearch: (entry: Readonly<SplitRouterEntry>) => {
- const type = routeParams<{ documentType?: string }>(
- entry.location.route
- ).documentType;
- if (
- type === 'md' ||
- type === 'task' ||
- type === 'snippet' ||
- type === 'skill'
- ) {
- return Object.values(MARKDOWN_URL_PARAMS);
- }
- if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
- if (type === 'spreadsheet')
- return Object.values(SPREADSHEET_COMMENT_PARAMS);
- if (
- typeof routeParams<{ callId?: string }>(entry.location.route).callId ===
- 'string'
- )
- return [CALL_URL_PARAMS.transcriptId, CALL_URL_PARAMS.messageId];
- return [];
- },
- children: [
- driveFolderRoute,
- driveTabRoute,
- driveCallRoute,
- driveRootDocumentRoute,
- ],
-});
diff --git a/apps/web/src/features/email-view/components/EmailDetailView.tsx b/apps/web/src/features/email-view/components/EmailDetailView.tsx
index 75e9afa879..be8865a163 100644
--- a/apps/web/src/features/email-view/components/EmailDetailView.tsx
+++ b/apps/web/src/features/email-view/components/EmailDetailView.tsx
@@ -5,7 +5,8 @@ import { displaySubject } from '@app/features/email-compose/core/subject-text';
import type { EmailThreadHost } from '@app/features/email-thread/context/email-thread-context';
import { createEmailThreadSource } from '@app/features/email-thread/queries/thread-source';
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
-import { createSearchParams, useRouteParams } from '@app/lib/split-router';
+import { emailThreadRoute } from '@app/routes/routes';
+import { createSearchParams, useRouteParams } from '@app/split-router';
import { EmailThreadControls } from '@block-email/component/EmailThreadControls';
import { EmailThreadLoadGate } from '@block-email/component/EmailThreadLoadGate';
import {
@@ -41,7 +42,6 @@ import { createMemo, createSignal, Show } from 'solid-js';
import { Portal } from 'solid-js/web';
import { emailDetailSearch } from '../email-route';
import { useEmailView } from '../email-view-context';
-import { emailThreadRoute } from '../route';
import type { EmailThreadTarget } from '../types';
import { useEmailDetailListNavigation } from '../use-email-detail-list-navigation';
diff --git a/apps/web/src/features/email-view/email-route.ts b/apps/web/src/features/email-view/email-route.ts
index 38781dd50b..72a9cd34db 100644
--- a/apps/web/src/features/email-view/email-route.ts
+++ b/apps/web/src/features/email-view/email-route.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import type { EmailTab } from './types';
diff --git a/apps/web/src/features/email-view/email-view-context.test.tsx b/apps/web/src/features/email-view/email-view-context.test.tsx
index 511f20e84d..ceabdee686 100644
--- a/apps/web/src/features/email-view/email-view-context.test.tsx
+++ b/apps/web/src/features/email-view/email-view-context.test.tsx
@@ -33,7 +33,8 @@ vi.mock('@app/features/soup/collection/list-navigation-source', () => ({
vi.mock('@app/lib/persistence', () => ({
makePersistedState: <T,>(store: T) => store,
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
useNavigate: () => mocks.navigate,
useRouteParams: () => mocks.useRouteParams(),
createSearchParams: () => [
@@ -44,6 +45,16 @@ vi.mock('@app/lib/split-router', () => ({
},
],
}));
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
vi.mock('@components/app/createPreviewSelectionGuard', () => ({
createPreviewSelectionGuard: () =>
Object.assign(() => true, { canSelect: () => true }),
diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsx
index c771dbde80..a7d082105d 100644
--- a/apps/web/src/features/email-view/email-view-context.tsx
+++ b/apps/web/src/features/email-view/email-view-context.tsx
@@ -11,11 +11,12 @@ import { normalizeFacetSelection } from '@app/features/soup';
import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { makePersistedState } from '@app/lib/persistence';
+import { emailSplitRoute, emailThreadRoute } from '@app/routes/routes';
import {
createSearchParams,
useNavigate,
useRouteParams,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import {
useSplitPanelOrThrow,
@@ -57,7 +58,6 @@ import {
type EmailDataSourceItem,
useEmailDataSource,
} from './queries/use-email-query';
-import { emailSplitRoute, emailThreadRoute } from './route';
import type {
EmailTab,
EmailThreadTarget,
diff --git a/apps/web/src/features/email-view/email-view.tsx b/apps/web/src/features/email-view/email-view.tsx
index c5d9c4f260..64615f664c 100644
--- a/apps/web/src/features/email-view/email-view.tsx
+++ b/apps/web/src/features/email-view/email-view.tsx
@@ -1,7 +1,7 @@
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { ViewTour } from '@app/features/tours/ViewTour';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { SplitRouter } from '@app/lib/split-router';
+import { SplitRouter } from '@app/split-router';
import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';
import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
diff --git a/apps/web/src/features/email-view/route.tsx b/apps/web/src/features/email-view/route-views.tsx
similarity index 59%
rename from apps/web/src/features/email-view/route.tsx
rename to apps/web/src/features/email-view/route-views.tsx
index 2d699342a1..7f90a99b97 100644
--- a/apps/web/src/features/email-view/route.tsx
+++ b/apps/web/src/features/email-view/route-views.tsx
@@ -1,19 +1,12 @@
-import {
- createSearchParams,
- defineRoute,
- useParams,
-} from '@app/lib/split-router';
+import { createSearchParams, useParams } from '@app/split-router';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
import {
AppView,
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
import { Show } from 'solid-js';
-import { z } from 'zod';
import { URL_PARAMS as EMAIL_URL_PARAMS } from '../email-thread/core/location';
-import { EmailDetailRouteView } from './components/EmailDetailView';
import { emailDetailSearch } from './email-route';
import { EmailView } from './email-view';
@@ -48,25 +41,3 @@ export const MailRouteView = withAuth(() => {
</AppView>
);
});
-
-export const emailThreadRoute = defineRoute({
- id: 'mail-thread',
- path: ':threadId',
- params: z.object({ threadId: z.string().min(1) }),
- component: EmailDetailRouteView,
- externalSearch: ['email_message_id'],
- remountKey: ({ threadId }) => threadId,
- claim: ({ threadId }) => ({
- namespace: 'block',
- id: `email:${threadId}`,
- }),
- toReference: ({ threadId }) => uuidRouteReference(threadId, 'email'),
-});
-
-export const emailSplitRoute = defineRoute({
- id: 'view-mail',
- path: 'mail',
- component: MailRouteView,
- search: '*' as const,
- children: [emailThreadRoute],
-});
diff --git a/apps/web/src/features/getting-started/route.tsx b/apps/web/src/features/getting-started/route-views.tsx
similarity index 55%
rename from apps/web/src/features/getting-started/route.tsx
rename to apps/web/src/features/getting-started/route-views.tsx
index 8e57ba5897..1eccc8d3ff 100644
--- a/apps/web/src/features/getting-started/route.tsx
+++ b/apps/web/src/features/getting-started/route-views.tsx
@@ -1,4 +1,3 @@
-import { defineRoute } from '@app/lib/split-router';
import {
usePageViewTracking,
withAuth,
@@ -13,11 +12,3 @@ export const GettingStartedRouteView = withAuth(() => {
usePageViewTracking('getting-started');
return <GettingStarted />;
});
-
-export const gettingStartedRoute = defineRoute({
- id: 'view-getting-started',
- path: 'getting-started',
- component: GettingStartedRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'getting-started' }),
-});
diff --git a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
index 7f014641a8..7c1e2fdff8 100644
--- a/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
+++ b/apps/web/src/features/home/components/HomeEntityDetailRouteView.tsx
@@ -5,7 +5,7 @@ import {
import type { EntityDetailTarget } from '@app/components/entity-detail/entity-detail-target';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { channelsSearch } from '@app/features/channels-view/channels-route';
-import { createSearchParams, useParams } from '@app/lib/split-router';
+import { createSearchParams, useParams } from '@app/split-router';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { ChannelDetailTopBar } from '@channel/Channel/ChannelDetail';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
diff --git a/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx b/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx
index 1880d56e2a..6e56a982bf 100644
--- a/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx
+++ b/apps/web/src/features/home/components/HomeReminderDetailRouteView.tsx
@@ -1,6 +1,6 @@
import { ReminderDetails } from '@app/features/reminders/ReminderEditorSplit';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { useParams } from '@app/lib/split-router';
+import { useParams } from '@app/split-router';
import { PreviewFrame } from '@components/app/PreviewPanel';
import {
useSplitDisplayName,
diff --git a/apps/web/src/features/home/home-calendar-preview.ts b/apps/web/src/features/home/home-calendar-preview.ts
index 816fab9a42..2fdceac965 100644
--- a/apps/web/src/features/home/home-calendar-preview.ts
+++ b/apps/web/src/features/home/home-calendar-preview.ts
@@ -4,12 +4,13 @@ import {
calendarTargetSearch,
} from '@app/features/calendar-view/calendar-url';
import type { CalendarPreviewSelection } from '@app/features/next-soup/utils';
+import { homeCalendarRoute } from '@app/routes/routes';
import {
createSearchParams,
type SerializedSearchParams,
useNavigate,
useRouteParams,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import { previewCalendarTarget } from '@components/app/previewTarget';
import {
enableCalendarUi,
@@ -18,7 +19,6 @@ import {
import deepEqual from 'fast-deep-equal';
import { createSignal } from 'solid-js';
import { homeCalendarNavigation } from './home-preview-navigation';
-import { homeCalendarRoute } from './route';
type WithTab = (
search: Record<string, SerializedSearchParams | undefined>
diff --git a/apps/web/src/features/home/home-preview-navigation.ts b/apps/web/src/features/home/home-preview-navigation.ts
index fc50b496db..147609585c 100644
--- a/apps/web/src/features/home/home-preview-navigation.ts
+++ b/apps/web/src/features/home/home-preview-navigation.ts
@@ -19,7 +19,7 @@ import {
driveSearchCodec,
} from '@app/features/drive-view/primitives/drive-search';
import { emailDetailSearch } from '@app/features/email-view/email-route';
-import type { SerializedSearchParams } from '@app/lib/split-router';
+import type { SerializedSearchParams } from '@app/split-router';
import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
diff --git a/apps/web/src/features/home/home-tab-search.ts b/apps/web/src/features/home/home-tab-search.ts
index 90040dff30..d098c05f0b 100644
--- a/apps/web/src/features/home/home-tab-search.ts
+++ b/apps/web/src/features/home/home-tab-search.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import type { HomeTab } from './types';
diff --git a/apps/web/src/features/home/home-view-context.tsx b/apps/web/src/features/home/home-view-context.tsx
index 0ad578fa9e..f503138030 100644
--- a/apps/web/src/features/home/home-view-context.tsx
+++ b/apps/web/src/features/home/home-view-context.tsx
@@ -4,12 +4,19 @@ import { driveSearch } from '@app/features/drive-view/primitives/drive-search';
import { reminderSourceContent } from '@app/features/reminders/reminder-source';
import type { FacetSelection } from '@app/features/soup/filters/facets/types';
import { makePersistedState } from '@app/lib/persistence';
+import {
+ homeChannelRoute,
+ homeDocumentRoute,
+ homePreviewRoute,
+ homeReminderRoute,
+ homeSplitRoute,
+} from '@app/routes/routes';
import {
createSearchParams,
type SerializedSearchParams,
useNavigate,
useParams,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import {
type PreviewBlockTarget,
@@ -47,13 +54,6 @@ import { homeDetailParamsFromRoute, homePreviewTarget } from './home-route';
import { isHomeDocumentType } from './home-route-schema';
import { homeTabSearch, homeTabSearchCodec } from './home-tab-search';
import { createHomeViewPersistence, normalizeHomeFacets } from './persistence';
-import {
- homeChannelRoute,
- homeDocumentRoute,
- homePreviewRoute,
- homeReminderRoute,
- homeSplitRoute,
-} from './route';
import type {
HomeGroupBy,
HomeTab,
diff --git a/apps/web/src/features/home/home-view.tsx b/apps/web/src/features/home/home-view.tsx
index 789c114c6f..596e8bd20b 100644
--- a/apps/web/src/features/home/home-view.tsx
+++ b/apps/web/src/features/home/home-view.tsx
@@ -2,7 +2,8 @@ import { useViewShell, ViewShell } from '@app/components/view-shell';
import { calendarSearch } from '@app/features/calendar-view/calendar-url';
import { CalendarView } from '@app/features/calendar-view/calendar-view';
import { ViewTour } from '@app/features/tours/ViewTour';
-import { createSearchParams, SplitRouter } from '@app/lib/split-router';
+import { homeCalendarRoute } from '@app/routes/routes';
+import { createSearchParams, SplitRouter } from '@app/split-router';
import { DebugSuspense } from '@channel/DebugSuspense';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import { PreviewFrame, PreviewPanel } from '@components/app/PreviewPanel';
@@ -20,7 +21,6 @@ import { HomeListSkeleton } from './components/HomeListSkeleton';
import { HomeReturnBreadcrumb } from './components/HomeReturnBreadcrumb';
import { HomeTabs } from './components/HomeTabs';
import { HomeViewProvider, useHomeView } from './home-view-context';
-import { homeCalendarRoute } from './route';
import { homeTour } from './tour';
import type { HomeViewStateOptions } from './types';
diff --git a/apps/web/src/features/home/route-views.tsx b/apps/web/src/features/home/route-views.tsx
new file mode 100644
index 0000000000..29ea2d3e78
--- /dev/null
+++ b/apps/web/src/features/home/route-views.tsx
@@ -0,0 +1,68 @@
+import type { CalendarPeriodView } from '@app/features/calendar/types';
+import { calendarSearch } from '@app/features/calendar-view/calendar-url';
+import { channelsSearch } from '@app/features/channels-view/channels-route';
+import { driveSearch } from '@app/features/drive-view/primitives/drive-search';
+import { createSearchParams, useParams } from '@app/split-router';
+import {
+ AppView,
+ RedirectSplit,
+ withAuth,
+} from '@components/app/split-layout/split-router/app-route-shell';
+import { Show } from 'solid-js';
+import {
+ homeCalendarLegacyTarget,
+ homeDetailParamsFromRoute,
+ homePreviewLegacyTarget,
+} from './home-route';
+import type { HomePreviewRouteParams } from './home-route-schema';
+import { HomeView } from './home-view';
+
+type HomeDetailParams = Partial<HomePreviewRouteParams> & {
+ channelId?: string;
+ documentType?: string;
+ documentId?: string;
+ reminderId?: string;
+ period?: CalendarPeriodView;
+};
+
+function HomeLegacyRouteView() {
+ const params = useParams<HomeDetailParams>();
+ const [channelSearch] = createSearchParams(channelsSearch);
+ const [documentSearch] = createSearchParams(driveSearch);
+ const [eventSearch] = createSearchParams(calendarSearch);
+ const legacyTarget = () => {
+ const { period } = params;
+ if (period) return homeCalendarLegacyTarget(period, eventSearch);
+ const detail = homeDetailParamsFromRoute(params);
+ if (!detail) return;
+ return homePreviewLegacyTarget(detail, {
+ channel: channelSearch,
+ document: documentSearch,
+ });
+ };
+
+ return (
+ <Show when={legacyTarget()}>
+ {(target) => <RedirectSplit to={target()} />}
+ </Show>
+ );
+}
+
+export const HomeRouteView = withAuth(() => {
+ const params = useParams<HomeDetailParams>();
+ const detailRequested = () =>
+ homeDetailParamsFromRoute(params) !== undefined ||
+ typeof params.reminderId === 'string' ||
+ typeof params.period === 'string';
+
+ return (
+ <AppView
+ id="home"
+ detailDesktopOnly
+ detailRequested={detailRequested}
+ detailFallback={<HomeLegacyRouteView />}
+ >
+ <HomeView />
+ </AppView>
+ );
+});
diff --git a/apps/web/src/features/home/route.tsx b/apps/web/src/features/home/route.tsx
deleted file mode 100644
index 4a16d7581d..0000000000
--- a/apps/web/src/features/home/route.tsx
+++ /dev/null
@@ -1,202 +0,0 @@
-import type { CalendarPeriodView } from '@app/features/calendar/types';
-import {
- CALENDAR_SEARCH_NAMESPACE,
- calendarPeriodParams,
- calendarPeriodPath,
- calendarSearch,
-} from '@app/features/calendar-view/calendar-url';
-import { channelsSearch } from '@app/features/channels-view/channels-route';
-import { channelDetailRoute } from '@app/features/channels-view/route';
-import { driveSearch } from '@app/features/drive-view/primitives/drive-search';
-import { driveRootDocumentRoute } from '@app/features/drive-view/route';
-import { HOME_REMINDER_DETAIL_ROUTE_ID } from '@app/features/reminders/reminder-navigation';
-import {
- createSearchParams,
- defineRoute,
- routeParams,
- type SplitRouterEntry,
- useParams,
-} from '@app/lib/split-router';
-import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
-import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
-import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
-import {
- AppView,
- RedirectSplit,
- withAuth,
-} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
-import { Show } from 'solid-js';
-import { z } from 'zod';
-import { URL_PARAMS as EMAIL_URL_PARAMS } from '../email-thread/core/location';
-import { HomeEntityDetailRouteView } from './components/HomeEntityDetailRouteView';
-import { HomeReminderDetailRouteView } from './components/HomeReminderDetailRouteView';
-import {
- homeCalendarLegacyTarget,
- homeDetailParamsFromRoute,
- homePreviewLegacyTarget,
-} from './home-route';
-import {
- HOME_PREVIEW_SEARCH_NAMESPACES,
- type HomePreviewRouteParams,
- homeBaseBlockType,
- homePreviewRouteParams,
-} from './home-route-schema';
-import {
- HomeCalendarRouteView,
- HomeDetailRouteView,
- HomeView,
-} from './home-view';
-
-type HomeDetailParams = Partial<HomePreviewRouteParams> & {
- channelId?: string;
- documentType?: string;
- documentId?: string;
- reminderId?: string;
- period?: CalendarPeriodView;
-};
-
-function HomeLegacyRouteView() {
- const params = useParams<HomeDetailParams>();
- const [channelSearch] = createSearchParams(channelsSearch);
- const [documentSearch] = createSearchParams(driveSearch);
- const [eventSearch] = createSearchParams(calendarSearch);
- const legacyTarget = () => {
- const { period } = params;
- if (period) return homeCalendarLegacyTarget(period, eventSearch);
- const detail = homeDetailParamsFromRoute(params);
- if (!detail) return;
- return homePreviewLegacyTarget(detail, {
- channel: channelSearch,
- document: documentSearch,
- });
- };
-
- return (
- <Show when={legacyTarget()}>
- {(target) => <RedirectSplit to={target()} />}
- </Show>
- );
-}
-
-export const HomeRouteView = withAuth(() => {
- const params = useParams<HomeDetailParams>();
- const detailRequested = () =>
- homeDetailParamsFromRoute(params) !== undefined ||
- typeof params.reminderId === 'string' ||
- typeof params.period === 'string';
-
- return (
- <AppView
- id="home"
- detailDesktopOnly
- detailRequested={detailRequested}
- detailFallback={<HomeLegacyRouteView />}
- >
- <HomeView />
- </AppView>
- );
-});
-
-/** The Calendar view inline in Home, at the Calendar route's own period path and search. */
-export const homeCalendarRoute = defineRoute({
- id: 'home-calendar',
- path: 'calendar/:period',
- params: calendarPeriodParams,
- serializeParams: ({ period }) => ({ period: calendarPeriodPath(period) }),
- component: HomeCalendarRouteView,
- search: [CALENDAR_SEARCH_NAMESPACE],
-});
-
-export const homeChannelRoute = defineRoute({
- ...channelDetailRoute,
- id: 'home-channel',
- path: 'channel/:channelId',
- component: HomeEntityDetailRouteView,
-});
-
-export const homeDocumentRoute = defineRoute({
- ...driveRootDocumentRoute,
- id: 'home-document',
- component: HomeEntityDetailRouteView,
- externalSearch: (entry: Readonly<SplitRouterEntry>) => {
- const type = routeParams<{ documentType?: string }>(
- entry.location.route
- ).documentType;
- if (
- type === 'md' ||
- type === 'task' ||
- type === 'snippet' ||
- type === 'skill'
- ) {
- return Object.values(MARKDOWN_URL_PARAMS);
- }
- if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
- return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];
- },
- remountKey: ({ documentType, documentId }) =>
- `${homeBaseBlockType(documentType)}:${documentId}`,
-});
-
-export const homeReminderRoute = defineRoute({
- id: HOME_REMINDER_DETAIL_ROUTE_ID,
- path: 'reminder/:reminderId',
- params: z.object({ reminderId: z.string().min(1) }),
- component: HomeReminderDetailRouteView,
- remountKey: ({ reminderId }) => reminderId,
- claim: ({ reminderId }) => ({ namespace: 'reminder', id: reminderId }),
-});
-
-export const homePreviewRoute = defineRoute({
- id: 'home-preview',
- path: ':blockType/:previewId',
- params: homePreviewRouteParams,
- component: HomeDetailRouteView,
- search: HOME_PREVIEW_SEARCH_NAMESPACES,
- // Blocks read their own location keys from the URL, as they do in Drive.
- externalSearch: (entry: Readonly<SplitRouterEntry>) => {
- const type = routeParams<{ blockType?: string }>(
- entry.location.route
- ).blockType;
- if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);
- if (type === 'email') return Object.values(EMAIL_URL_PARAMS);
- if (
- type === 'md' ||
- type === 'task' ||
- type === 'snippet' ||
- type === 'skill'
- ) {
- return Object.values(MARKDOWN_URL_PARAMS);
- }
- if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
- return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];
- },
- remountKey: ({ blockType, previewId }) =>
- `${homeBaseBlockType(blockType)}:${previewId}`,
- claim: ({ blockType, previewId }) => ({
- namespace: blockType === 'agent' ? 'agent' : 'block',
- id:
- blockType === 'agent'
- ? previewId
- : `${homeBaseBlockType(blockType)}:${previewId}`,
- }),
- toReference: ({ previewId, blockType }) =>
- blockType === 'pr'
- ? { type: 'pr', id: previewId }
- : uuidRouteReference(previewId, blockType),
-});
-
-export const homeSplitRoute = defineRoute({
- id: 'view-home',
- path: 'home',
- component: HomeRouteView,
- search: '*' as const,
- // The period path is matched before the block pattern can claim `calendar`.
- children: [
- homeCalendarRoute,
- homeChannelRoute,
- homeDocumentRoute,
- homeReminderRoute,
- homePreviewRoute,
- ],
-});
diff --git a/apps/web/src/features/next-soup/route.tsx b/apps/web/src/features/next-soup/route-views.tsx
similarity index 78%
rename from apps/web/src/features/next-soup/route.tsx
rename to apps/web/src/features/next-soup/route-views.tsx
index 88a2265ffa..9bfcf76faf 100644
--- a/apps/web/src/features/next-soup/route.tsx
+++ b/apps/web/src/features/next-soup/route-views.tsx
@@ -1,6 +1,5 @@
import { ViewTour } from '@app/features/tours/ViewTour';
import { usePosthog } from '@app/lib/analytics/posthog';
-import { defineRoute } from '@app/lib/split-router';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import {
RedirectSplit,
@@ -109,35 +108,3 @@ export const SearchRouteView = withAuth(() => {
/>
);
});
-
-export const recentRoute = defineRoute({
- id: 'view-recent',
- path: 'recent',
- component: RecentRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'recent' }),
-});
-
-export const callsRoute = defineRoute({
- id: 'view-calls',
- path: 'calls',
- component: CallsRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'calls' }),
-});
-
-export const foldersRoute = defineRoute({
- id: 'view-folders',
- path: 'folders',
- component: FoldersRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'folders' }),
-});
-
-export const searchRoute = defineRoute({
- id: 'view-search',
- path: 'search',
- component: SearchRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'search' }),
-});
diff --git a/apps/web/src/features/next-soup/search-navigation-readers.test.tsx b/apps/web/src/features/next-soup/search-navigation-readers.test.tsx
index b84054facb..2264b554f2 100644
--- a/apps/web/src/features/next-soup/search-navigation-readers.test.tsx
+++ b/apps/web/src/features/next-soup/search-navigation-readers.test.tsx
@@ -1,21 +1,18 @@
import { createAgentRouteTarget } from '@app/features/block-agent/primitives/create-agent-route-target';
import { createMarkdownRouteNavigation } from '@app/features/block-md/primitives/create-markdown-route-navigation';
import { createPdfRouteTarget } from '@app/features/block-pdf/primitives/create-pdf-route-target';
-import type {
- SplitRouter as Router,
- SplitRouterLayout,
- SplitRouterLayoutEntry,
-} from '@app/lib/split-router';
import {
- createMemorySplitRouterLocation,
+ createMemoryHistory,
+ createMemoryPaneStore,
+ createSplitRouter,
defineRoute,
+ replacePaneSearchParams,
+ type SplitPanePolicy,
SplitRouter,
- useSplitRouter,
-} from '@app/lib/split-router';
-import { replaceSplitSearchParams } from '@app/lib/split-router/search';
+} from '@app/split-router';
import type { SearchLocation } from '@entity';
import { cleanup, render } from '@solidjs/testing-library';
-import { type Accessor, createSignal } from 'solid-js';
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
import {
searchLocationTarget,
@@ -24,55 +21,53 @@ import {
afterEach(cleanup);
+const policy: SplitPanePolicy = {
+ placeNewPane: ({ panes }) => ({ insertAt: panes.length }),
+ closeAction: () => ({ type: 'keep' }),
+ activate: () => {},
+};
+
function setup(location: SearchLocation) {
- let entry: SplitRouterLayoutEntry<string> | undefined;
- const layout: SplitRouterLayout<string> = {
- snapshot: () => ({ entries: entry ? [entry] : [] }),
- reconcile: (locations) => {
- entry = { splitId: 'pane', location: locations[0]! };
- },
- updateCurrentLocation: (_, update) => {
- entry = { ...entry!, location: update(entry!) };
- },
- open: () => ({ status: 'unavailable' }),
- activate: () => {},
- subscribe: () => () => {},
- };
const target = searchLocationTarget('document', location);
const query = new URLSearchParams();
- replaceSplitSearchParams(query, [
- { location: { search: { [target.namespace]: target.params } } },
- ]);
+ replacePaneSearchParams(query, [{ [target.namespace]: target.params }]);
const route = defineRoute({
id: 'detail',
path: 'detail',
search: '*' as const,
});
const navigateMarkdown = vi.fn();
- let router!: Router<string>;
+ let router!: ReturnType<typeof createSplitRouter>;
let pdf!: ReturnType<typeof createPdfRouteTarget>;
let agent!: ReturnType<typeof createAgentRouteTarget>;
let setDocument!: (id: string) => void;
let documentId!: Accessor<string>;
function Reader() {
- router = useSplitRouter<string>();
[documentId, setDocument] = createSignal('document');
createMarkdownRouteNavigation(documentId, navigateMarkdown);
pdf = createPdfRouteTarget(documentId);
agent = createAgentRouteTarget();
return null;
}
- render(() => (
- <SplitRouter.Root
- layout={layout}
- routes={{ definitions: [route] }}
- location={createMemorySplitRouterLocation(`/detail?${query}`)}
- >
- <SplitRouter.Scope splitId="pane">
- <Reader />
- </SplitRouter.Scope>
- </SplitRouter.Root>
- ));
+ render(() => {
+ router = createSplitRouter({
+ routes: {
+ definitions: [route],
+ defaultRoute: () => ({ matches: [{ id: 'detail', params: {} }] }),
+ },
+ history: createMemoryHistory(`/detail?${query}`),
+ paneStore: createMemoryPaneStore(),
+ policy,
+ });
+ onCleanup(() => router.dispose());
+ return (
+ <SplitRouter.Root router={router}>
+ <SplitRouter.Scope pane={router.panes()[0]!}>
+ <Reader />
+ </SplitRouter.Scope>
+ </SplitRouter.Root>
+ );
+ });
return {
navigateMarkdown,
pdf,
@@ -80,9 +75,13 @@ function setup(location: SearchLocation) {
setDocument,
router,
replay: () =>
- router.navigate('pane', route.to(), {
- search: searchLocationUpdates('document', location),
- }),
+ router.navigate(
+ router.panes()[0]!,
+ { route },
+ {
+ search: searchLocationUpdates('document', location),
+ }
+ ),
};
}
diff --git a/apps/web/src/features/next-soup/search-navigation.test.ts b/apps/web/src/features/next-soup/search-navigation.test.ts
index c348d5c213..f0f50f8d60 100644
--- a/apps/web/src/features/next-soup/search-navigation.test.ts
+++ b/apps/web/src/features/next-soup/search-navigation.test.ts
@@ -4,10 +4,8 @@ import { markdownDetailSearchCodec } from '@app/features/block-md/markdown-route
import { pdfDetailSearchCodec } from '@app/features/block-pdf/pdf-route';
import { channelsSearchCodec } from '@app/features/channels-view/channels-route';
import { emailDetailSearchCodec } from '@app/features/email-view/email-route';
-import {
- parseSplitSearch,
- replaceSplitSearchParams,
-} from '@app/lib/split-router/search';
+import { parsePaneSearch } from '@app/lib/split-router/next/routes/search';
+import { replacePaneSearchParams } from '@app/split-router';
import type { SearchLocation } from '@entity';
import { describe, expect, it } from 'vitest';
import {
@@ -36,12 +34,8 @@ describe('search target URLs', () => {
(location) => {
const target = searchLocationTarget('entity', location, 'request');
const query = new URLSearchParams();
- replaceSplitSearchParams(query, [
- { location: { search: { [target.namespace]: target.params } } },
- ]);
- const restored = parseSplitSearch(query.toString()).get(0)?.[
- target.namespace
- ];
+ replacePaneSearchParams(query, [{ [target.namespace]: target.params }]);
+ const restored = parsePaneSearch(query.toString())[0]?.[target.namespace];
const codecs = {
channel: channelsSearchCodec,
email: emailDetailSearchCodec,
diff --git a/apps/web/src/features/next-soup/search-navigation.ts b/apps/web/src/features/next-soup/search-navigation.ts
index 2b7a732778..3eb18af6d9 100644
--- a/apps/web/src/features/next-soup/search-navigation.ts
+++ b/apps/web/src/features/next-soup/search-navigation.ts
@@ -25,7 +25,7 @@ import {
import type {
SerializedSearchParams,
SplitSearchUpdate,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import type { SearchLocation } from '@entity';
import { match } from 'ts-pattern';
diff --git a/apps/web/src/features/next-soup/utils.test.ts b/apps/web/src/features/next-soup/utils.test.ts
index 7c87b26c3c..fec79698bc 100644
--- a/apps/web/src/features/next-soup/utils.test.ts
+++ b/apps/web/src/features/next-soup/utils.test.ts
@@ -151,8 +151,9 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => {
};
});
-import type { SerializedSearchParams } from '@app/lib/split-router';
+import { paneRoute } from '@app/routes/app-route';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
+import type { SerializedSearchParams } from '@app/split-router';
import type {
OpenWithSplitOptions,
SplitManager,
@@ -996,13 +997,7 @@ describe('calendar view navigation', () => {
}),
}),
entryMetadata: expect.objectContaining({
- route: {
- matches: [
- expect.objectContaining({
- id: 'view-calendar',
- }),
- ],
- },
+ route: paneRoute(expect.objectContaining({ id: 'view-calendar' })),
search: {
calendar: expect.objectContaining({
eventId: ['event-1'],
@@ -1084,12 +1079,10 @@ describe('Hosted details and Drive document routing', () => {
type: 'component',
id: 'reviews',
entryMetadata: {
- route: {
- matches: [
- { id: 'view-reviews', params: {} },
- { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } },
- ],
- },
+ route: paneRoute(
+ { id: 'view-reviews', params: {} },
+ { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } }
+ ),
},
},
expect.objectContaining({
@@ -1175,18 +1168,13 @@ describe('Hosted details and Drive document routing', () => {
type: 'component',
id: 'documents',
entryMetadata: {
- route: {
- matches: [
- { id: 'drive', params: {} },
- {
- id: 'drive-document',
- params: {
- documentId: 'doc-1',
- documentType: fileType,
- },
- },
- ],
- },
+ route: paneRoute(
+ { id: 'drive', params: {} },
+ {
+ id: 'drive-document',
+ params: { documentId: 'doc-1', documentType: fileType },
+ }
+ ),
},
},
expect.objectContaining({
@@ -1910,15 +1898,13 @@ describe('getDocumentCommentTarget', () => {
type: 'component',
id: 'documents',
entryMetadata: {
- route: {
- matches: [
- { id: 'drive', params: {} },
- {
- id: 'drive-document',
- params: { documentId: 'doc-1', documentType: 'md' },
- },
- ],
- },
+ route: paneRoute(
+ { id: 'drive', params: {} },
+ {
+ id: 'drive-document',
+ params: { documentId: 'doc-1', documentType: 'md' },
+ }
+ ),
},
},
expect.objectContaining({ activate: true, search: undefined })
@@ -2113,12 +2099,10 @@ describe('call navigation', () => {
type: 'component',
id: 'documents',
entryMetadata: {
- route: {
- matches: [
- { id: 'drive', params: {} },
- { id: 'drive-call', params: { callId: 'call-1' } },
- ],
- },
+ route: paneRoute(
+ { id: 'drive', params: {} },
+ { id: 'drive-call', params: { callId: 'call-1' } }
+ ),
},
},
expect.objectContaining({ allowDuplicate: true })
@@ -2146,12 +2130,10 @@ describe('call navigation', () => {
type: 'component',
id: 'documents',
entryMetadata: {
- route: {
- matches: [
- { id: 'drive', params: {} },
- { id: 'drive-call', params: { callId: 'call-1' } },
- ],
- },
+ route: paneRoute(
+ { id: 'drive', params: {} },
+ { id: 'drive-call', params: { callId: 'call-1' } }
+ ),
},
});
expect(targetSearch(openWithSplit, 'call-detail')).toMatchObject({
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index c6c6f9282b..d889204ff2 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -28,8 +28,8 @@ import {
getEntityNotifications,
scopeChannelNotificationsForEntity,
} from '@app/features/soup/entity-notifications';
-import { replaceSplitSearchParams } from '@app/lib/split-router/search';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { replacePaneSearchParams } from '@app/split-router';
import { CALENDAR_BLOCK_ID } from '@block-calendar/types';
import {
goToChannelLatest,
@@ -330,8 +330,8 @@ export const openEntityInNewTab = ({
getEntitySplitContent(entity).id,
target
);
- replaceSplitSearchParams(entityUrl.searchParams, [
- { location: { search: { [namespace]: params } } },
+ replacePaneSearchParams(entityUrl.searchParams, [
+ { [namespace]: params },
]);
}
}
diff --git a/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts b/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
index bf9d068e4d..23aa645c89 100644
--- a/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
+++ b/apps/web/src/features/notifications/tests/channel-notification-navigation.test.ts
@@ -1,4 +1,4 @@
-import { createSplitLayout } from '@components/app/split-layout/layoutManager';
+import { createRoutedSplitLayout } from '@components/app/split-layout/tests/fixtures';
import { toast } from '@core/component/Toast/Toast';
import type { BlockOrchestrator } from '@core/orchestrator';
import { createRoot } from 'solid-js';
@@ -23,13 +23,15 @@ vi.mock('@app/features/calendar-view/calendar-navigation', () => ({
openCalendarView: vi.fn(),
}));
vi.mock('@core/constant/allBlocks', () => ({
+ blocks: { channel: {} },
isBlockAlias: () => false,
itemToBlockName: (value: { fileType: string }) => value.fileType,
resolveBlockAlias: (type: string) => type,
}));
beforeEach(() => vi.clearAllMocks());
-vi.mock('@core/constant/featureFlags', () => ({
+vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/constant/featureFlags')>()),
enableCalendarUi: false,
enableReminders: false,
isFeatureEnabled: vi.fn(),
@@ -77,12 +79,10 @@ function setup(location: 'preview' | 'split' | 'closed') {
} as unknown as BlockOrchestrator;
const layout = createRoot((dispose) => {
onTestFinished(dispose);
- return createSplitLayout(orchestrator, [
- location === 'split'
- ? { type: 'channel', id: 'channel' }
- : { type: 'component', id: 'channels' },
- { type: 'component', id: 'home' },
- ]);
+ return createRoutedSplitLayout(
+ orchestrator,
+ location === 'split' ? '/channel/channel/~/home' : '/channels/~/home'
+ );
});
const [first, other] = layout.splits();
layout.activateSplit(other.id);
diff --git a/apps/web/src/features/projects/project-detail.tsx b/apps/web/src/features/projects/project-detail.tsx
index ff155b82c9..e3972a5b0d 100644
--- a/apps/web/src/features/projects/project-detail.tsx
+++ b/apps/web/src/features/projects/project-detail.tsx
@@ -4,8 +4,8 @@ import {
projectDetailRoute,
projectTaskRoute,
tasksSplitRoute,
-} from '@app/features/tasks-view/route';
-import { useNavigate } from '@app/lib/split-router';
+} from '@app/routes/routes';
+import { useNavigate } from '@app/split-router';
import type { ComposeTaskProps } from '@block-md/component/ComposeTask';
import { useSplitLayout } from '@components/app/split-layout/layout';
import {
diff --git a/apps/web/src/features/projects/project-view.test.tsx b/apps/web/src/features/projects/project-view.test.tsx
index f3517345b3..66461d7672 100644
--- a/apps/web/src/features/projects/project-view.test.tsx
+++ b/apps/web/src/features/projects/project-view.test.tsx
@@ -30,13 +30,14 @@ vi.mock('@core/mobile/isTouchDevice', () => ({
vi.mock('@core/component/Toast/Toast', () => ({
toast: { success: fixtures.toast },
}));
-vi.mock('@app/features/tasks-view/route', () => ({
+vi.mock('@app/routes/routes', () => ({
projectDetailRoute: {},
tasksProjectsRoute: {},
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/split-router', () => ({
useNavigate: () => fixtures.navigate,
- useSplitHistory: () => () => (fixtures.routed() ? { index: 0 } : undefined),
+ usePaneHistory: () => () =>
+ fixtures.routed() ? { entries: [], index: 0 } : undefined,
}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({
diff --git a/apps/web/src/features/projects/project-view.tsx b/apps/web/src/features/projects/project-view.tsx
index 035aab2cfd..151bfb8552 100644
--- a/apps/web/src/features/projects/project-view.tsx
+++ b/apps/web/src/features/projects/project-view.tsx
@@ -1,8 +1,5 @@
-import {
- projectDetailRoute,
- tasksProjectsRoute,
-} from '@app/features/tasks-view/route';
-import { useNavigate, useSplitHistory } from '@app/lib/split-router';
+import { projectDetailRoute, tasksProjectsRoute } from '@app/routes/routes';
+import { useNavigate, usePaneHistory } from '@app/split-router';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
@@ -22,7 +19,7 @@ import { CreateProject } from './views/create-project';
/** A split opened moments ago joins the router after it mounts; earlier navigation is dropped. */
function useRedirectOnceRouted(redirect: () => void) {
- const routed = useSplitHistory();
+ const routed = usePaneHistory();
let redirected = false;
createEffect(() => {
if (redirected || !routed()) return;
diff --git a/apps/web/src/features/reminders/reminder-navigation.test.ts b/apps/web/src/features/reminders/reminder-navigation.test.ts
index e73d9d0870..2a07f02969 100644
--- a/apps/web/src/features/reminders/reminder-navigation.test.ts
+++ b/apps/web/src/features/reminders/reminder-navigation.test.ts
@@ -1,3 +1,4 @@
+import { paneRoute } from '@app/routes/app-route';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
import type {
SplitHandle,
@@ -39,14 +40,10 @@ describe('reminder detail destination', () => {
id: REMINDER_DETAIL_COMPONENT_ID,
params: { reminderId: 'reminder-1' },
entryMetadata: {
- route: {
- matches: [
- {
- id: REMINDER_DETAIL_ROUTE_ID,
- params: { reminderId: 'reminder-1' },
- },
- ],
- },
+ route: paneRoute({
+ id: REMINDER_DETAIL_ROUTE_ID,
+ params: { reminderId: 'reminder-1' },
+ }),
},
},
});
diff --git a/apps/web/src/features/reminders/reminder-navigation.ts b/apps/web/src/features/reminders/reminder-navigation.ts
index 97f2441c63..4364e9668f 100644
--- a/apps/web/src/features/reminders/reminder-navigation.ts
+++ b/apps/web/src/features/reminders/reminder-navigation.ts
@@ -1,3 +1,4 @@
+import { paneRoute } from '@app/routes/app-route';
import { globalSplitManager } from '@app/signal/splitLayout';
import type {
OpenSplitResult,
@@ -61,9 +62,10 @@ export function reminderDetailContent(reminderId: string): SplitContent {
id: REMINDER_DETAIL_COMPONENT_ID,
params: { reminderId },
entryMetadata: {
- route: {
- matches: [{ id: REMINDER_DETAIL_ROUTE_ID, params: { reminderId } }],
- },
+ route: paneRoute({
+ id: REMINDER_DETAIL_ROUTE_ID,
+ params: { reminderId },
+ }),
},
};
}
diff --git a/apps/web/src/features/reminders/route.tsx b/apps/web/src/features/reminders/route-views.tsx
similarity index 71%
rename from apps/web/src/features/reminders/route.tsx
rename to apps/web/src/features/reminders/route-views.tsx
index 82c550dca2..5f96f1aaea 100644
--- a/apps/web/src/features/reminders/route.tsx
+++ b/apps/web/src/features/reminders/route-views.tsx
@@ -1,5 +1,6 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { defineRoute, useRouteParams } from '@app/lib/split-router';
+import { reminderDetailRoute } from '@app/routes/routes';
+import { useRouteParams } from '@app/split-router';
import {
useSplitDisplayName,
useSplitPanelOrThrow,
@@ -12,10 +13,8 @@ import {
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableReminders } from '@core/constant/featureFlags';
import { lazy, Show } from 'solid-js';
-import { z } from 'zod';
import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';
import { ReminderDetails } from './ReminderEditorSplit';
-import { REMINDER_DETAIL_ROUTE_ID } from './reminder-navigation';
const SoupView = lazy(async () => ({
default: (await import('../next-soup/soup-view/soup-view')).SoupView,
@@ -49,14 +48,6 @@ export const RemindersRouteView = withAuth(() => {
);
});
-export const remindersRoute = defineRoute({
- id: 'view-reminders',
- path: 'reminders',
- component: RemindersRouteView,
- search: '*' as const,
- claim: () => ({ namespace: 'component', id: 'reminders' }),
-});
-
function ReminderDetailView() {
const params = useRouteParams(reminderDetailRoute);
const panel = useSplitPanelOrThrow();
@@ -70,7 +61,7 @@ function ReminderDetailView() {
);
}
-const ReminderDetailRouteView = withAuth(() => {
+export const ReminderDetailRouteView = withAuth(() => {
const reminders = useFeatureFlag(enableReminders);
return (
<Show when={!reminders().loading} fallback={<LoadingBlock />}>
@@ -83,13 +74,3 @@ const ReminderDetailRouteView = withAuth(() => {
</Show>
);
});
-
-/** Lightweight standalone reminder detail at `/app/reminder/:reminderId`. */
-export const reminderDetailRoute = defineRoute({
- id: REMINDER_DETAIL_ROUTE_ID,
- path: 'reminder/:reminderId',
- params: z.object({ reminderId: z.string().min(1) }),
- component: ReminderDetailRouteView,
- remountKey: ({ reminderId }) => reminderId,
- claim: ({ reminderId }) => ({ namespace: 'reminder', id: reminderId }),
-});
diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
index 18cd45b2c4..cba7c6c58d 100644
--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx
@@ -1,6 +1,7 @@
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useRouteParams } from '@app/lib/split-router';
+import { reviewsPrRoute } from '@app/routes/routes';
+import { useRouteParams } from '@app/split-router';
import { PrChangesProvider } from '@block-pr/component/PrChanges';
import { PrStatusIcon } from '@block-pr/component/PrStatus';
import { prDisplayName, prHtmlUrl } from '@block-pr/util/prKey';
@@ -14,7 +15,6 @@ import { SplitFileMenu } from '@components/app/split-layout/components/SplitFile
import { SplitPanel } from '@components/app/split-panel';
import { Permissions } from '@core/component/SharePermissions';
import { onMount } from 'solid-js';
-import { reviewsPrRoute } from '../route';
function ReviewsPrBreadcrumb(props: {
foreignEntityId: string;
diff --git a/apps/web/src/features/reviews-view/reviews-hosted-content.test.ts b/apps/web/src/features/reviews-view/reviews-hosted-content.test.ts
index 20f21582ed..16ccce38a8 100644
--- a/apps/web/src/features/reviews-view/reviews-hosted-content.test.ts
+++ b/apps/web/src/features/reviews-view/reviews-hosted-content.test.ts
@@ -1,3 +1,4 @@
+import { paneRoute } from '@app/routes/app-route';
import { describe, expect, it } from 'vitest';
import { reviewsHostedContent } from './reviews-hosted-content';
import { reviewsTabSearchCodec } from './reviews-tab-search';
@@ -15,12 +16,10 @@ describe('Reviews PR navigation', () => {
id: 'reviews',
entryMetadata: {
search: { reviews: { tab: ['authored'] } },
- route: {
- matches: [
- { id: 'view-reviews', params: {} },
- { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } },
- ],
- },
+ route: paneRoute(
+ { id: 'view-reviews', params: {} },
+ { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } }
+ ),
},
});
});
diff --git a/apps/web/src/features/reviews-view/reviews-hosted-content.ts b/apps/web/src/features/reviews-view/reviews-hosted-content.ts
index f048640f6e..c4febf79e9 100644
--- a/apps/web/src/features/reviews-view/reviews-hosted-content.ts
+++ b/apps/web/src/features/reviews-view/reviews-hosted-content.ts
@@ -1,4 +1,5 @@
-import type { SplitLocation, SplitRouteMatch } from '@app/lib/split-router';
+import { paneRoute } from '@app/routes/app-route';
+import type { SplitLocation, SplitRouteMatch } from '@app/split-router';
import type { SplitContent } from '@components/app/split-layout/layoutManager';
const hostedDetailRoutes = {
@@ -22,7 +23,7 @@ export function reviewsHostedContent(
type: 'component',
id: 'reviews',
entryMetadata: {
- route: { matches: [{ id: 'view-reviews', params: {} }, detail] },
+ route: paneRoute({ id: 'view-reviews', params: {} }, detail),
...(search ? { search } : {}),
},
};
diff --git a/apps/web/src/features/reviews-view/reviews-tab-search.ts b/apps/web/src/features/reviews-view/reviews-tab-search.ts
index 9f8242985d..813f638fa4 100644
--- a/apps/web/src/features/reviews-view/reviews-tab-search.ts
+++ b/apps/web/src/features/reviews-view/reviews-tab-search.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import type { ReviewsScope } from './reviews-types';
diff --git a/apps/web/src/features/reviews-view/reviews-view.tsx b/apps/web/src/features/reviews-view/reviews-view.tsx
index 861f46651a..2d034ece3c 100644
--- a/apps/web/src/features/reviews-view/reviews-view.tsx
+++ b/apps/web/src/features/reviews-view/reviews-view.tsx
@@ -3,12 +3,13 @@ import {
ViewBreadcrumbs,
ViewShell,
} from '@app/components/view-shell';
+import { reviewsPrRoute, reviewsSplitRoute } from '@app/routes/routes';
import {
createSearchParams,
SplitRouter,
useNavigate,
useParams,
-} from '@app/lib/split-router';
+} from '@app/split-router';
import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
@@ -48,7 +49,6 @@ import {
type ReviewsSortId,
scopeMatchesViewerGithubId,
} from './reviews-types';
-import { reviewsPrRoute, reviewsSplitRoute } from './route';
const REVIEW_SCOPE_TITLES: Record<ReviewsScope, string> = {
all: 'Pull requests',
diff --git a/apps/web/src/features/reviews-view/route.tsx b/apps/web/src/features/reviews-view/route-views.tsx
similarity index 55%
rename from apps/web/src/features/reviews-view/route.tsx
rename to apps/web/src/features/reviews-view/route-views.tsx
index 5a92e02906..fd726840ed 100644
--- a/apps/web/src/features/reviews-view/route.tsx
+++ b/apps/web/src/features/reviews-view/route-views.tsx
@@ -1,7 +1,6 @@
-import { changesSearch } from '@app/features/agent-changes/changes-search';
-import { tasksSplitRoute } from '@app/features/tasks-view/route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { defineRoute, useNavigate, useParams } from '@app/lib/split-router';
+import { tasksSplitRoute } from '@app/routes/routes';
+import { useNavigate, useParams } from '@app/split-router';
import {
usePageViewTracking,
withAuth,
@@ -9,13 +8,12 @@ import {
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableTasksReviews } from '@core/constant/featureFlags';
import { lazy, onMount, Show } from 'solid-js';
-import { z } from 'zod';
-import { reviewsTabSearch } from './reviews-tab-search';
const ReviewsView = lazy(async () => ({
default: (await import('./reviews-view')).ReviewsView,
}));
-const ReviewsPrDetailRouteView = lazy(async () => ({
+
+export const ReviewsPrDetailRouteView = lazy(async () => ({
default: (await import('./components/ReviewsPrDetail'))
.ReviewsPrDetailRouteView,
}));
@@ -49,25 +47,3 @@ export const ReviewsRouteView = withAuth(() => {
</Show>
);
});
-
-export const reviewsPrRoute = defineRoute({
- id: 'reviews-pr',
- path: 'pr/:foreignEntityId',
- params: z.object({ foreignEntityId: z.string().min(1) }),
- component: ReviewsPrDetailRouteView,
- remountKey: ({ foreignEntityId }) => foreignEntityId,
- claim: ({ foreignEntityId }) => ({
- namespace: 'block',
- id: `pr:${foreignEntityId}`,
- }),
- search: [changesSearch.namespace],
- toReference: ({ foreignEntityId }) => ({ type: 'pr', id: foreignEntityId }),
-});
-
-export const reviewsSplitRoute = defineRoute({
- id: 'view-reviews',
- path: 'reviews',
- component: ReviewsRouteView,
- search: [reviewsTabSearch.namespace],
- children: [reviewsPrRoute],
-});
diff --git a/apps/web/src/features/scheduling/public-booking.tsx b/apps/web/src/features/scheduling/public-booking.tsx
index 97dbb07349..fdcad80e3c 100644
--- a/apps/web/src/features/scheduling/public-booking.tsx
+++ b/apps/web/src/features/scheduling/public-booking.tsx
@@ -1,6 +1,6 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableCalendarScheduling } from '@core/constant/featureFlags';
-import { useLocation, useNavigate, useParams } from '@solidjs/router';
+import { useLocation, useNavigate } from '@solidjs/router';
import { Show, Suspense } from 'solid-js';
import {
createBookingReceiptSource,
@@ -10,8 +10,9 @@ import {
import { BookingReceiptView } from './views/booking-receipt-view';
import { PublicBookingView } from './views/public-booking-view';
-function BookingPageContent() {
- const params = useParams<{ profile: string; slug?: string }>();
+type BookingPageParams = { profile: string; slug?: string };
+
+function BookingPageContent(params: BookingPageParams) {
const navigate = useNavigate();
const profile = usePublicProfileQuery(() => params.profile);
const source = createPublicBookingSource();
@@ -49,7 +50,7 @@ function BookingPageContent() {
</Show>
);
}
-export function PublicBookingPage() {
+export function PublicBookingPage(props: BookingPageParams) {
const scheduling = useFeatureFlag(enableCalendarScheduling);
return (
<Show
@@ -63,14 +64,13 @@ export function PublicBookingPage() {
}
>
<Suspense fallback={<p class="p-12">Loading…</p>}>
- <BookingPageContent />
+ <BookingPageContent profile={props.profile} slug={props.slug} />
</Suspense>
</Show>
);
}
-function ReceiptContent() {
- const params = useParams<{ id: string }>();
+function ReceiptContent(params: { id: string }) {
const location = useLocation();
const token = () => location.hash.slice(1);
const source = createBookingReceiptSource(() => params.id, token);
@@ -85,7 +85,7 @@ function ReceiptContent() {
);
}
-export function BookingReceiptPage() {
+export function BookingReceiptPage(props: { id: string }) {
const scheduling = useFeatureFlag(enableCalendarScheduling);
return (
<Show
@@ -99,7 +99,7 @@ export function BookingReceiptPage() {
}
>
<Suspense fallback={<p class="p-12">Loading…</p>}>
- <ReceiptContent />
+ <ReceiptContent id={props.id} />
</Suspense>
</Show>
);
diff --git a/apps/web/src/features/settings/route-views.tsx b/apps/web/src/features/settings/route-views.tsx
new file mode 100644
index 0000000000..1dd9dc3f50
--- /dev/null
+++ b/apps/web/src/features/settings/route-views.tsx
@@ -0,0 +1,5 @@
+import { lazy } from 'solid-js';
+
+export const SettingsRouteView = lazy(async () => ({
+ default: (await import('./Settings')).SettingsPanelComponentWrapper,
+}));
diff --git a/apps/web/src/features/settings/route.tsx b/apps/web/src/features/settings/route.tsx
deleted file mode 100644
index e3642dd90e..0000000000
--- a/apps/web/src/features/settings/route.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { defineRoute } from '@app/lib/split-router';
-import {
- settingsSlugToTab,
- settingsTabToSlug,
-} from '@core/constant/settingsTabsConfig';
-import { lazy } from 'solid-js';
-import { z } from 'zod';
-
-export const SettingsRouteView = lazy(async () => ({
- default: (await import('./Settings')).SettingsPanelComponentWrapper,
-}));
-
-export const settingsRoute = defineRoute({
- id: 'settings',
- path: 'settings/:tab?',
- params: z.object({
- tab: z
- .string()
- .refine((tab) => settingsSlugToTab(tab) !== undefined)
- .default(settingsTabToSlug('Account')),
- }),
- component: SettingsRouteView,
- claim: () => ({ namespace: 'component', id: 'settings' }),
- externalSearch: ['pair', 'createAgent'],
-});
diff --git a/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx b/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx
index f786c2481c..59c4ac1ec3 100644
--- a/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksDetailView.test.tsx
@@ -27,7 +27,20 @@ vi.mock('@app/components/view-shell', () => ({
vi.mock('@app/components/entity-detail/EntityDetailBreadcrumbSkeleton', () => ({
EntityDetailBreadcrumbSkeleton: () => null,
}));
-vi.mock('@app/lib/split-router', () => ({ useRouteParams: () => ({}) }));
+vi.mock('@app/split-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@app/split-router')>()),
+ useRouteParams: () => ({}),
+}));
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
+}));
vi.mock('../route', () => ({ taskDetailRoute: {} }));
vi.mock('@block-md/component/MarkdownDetailBreadcrumbItem', () => ({
MarkdownDetailBreadcrumbItem: () => null,
diff --git a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx b/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
index 905079489d..43a2fe1c4f 100644
--- a/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksDetailView.tsx
@@ -3,14 +3,14 @@ import type { EntityDetailTarget } from '@app/components/entity-detail/entity-de
import { useListNavigationHotkeys } from '@app/components/entity-detail/use-list-navigation-hotkeys';
import { useListDetailNavigation } from '@app/components/list';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
-import { useRouteParams } from '@app/lib/split-router';
+import { taskDetailRoute } from '@app/routes/routes';
+import { useRouteParams } from '@app/split-router';
import { MarkdownDetailBreadcrumbItem } from '@block-md/component/MarkdownDetailBreadcrumbItem';
import { SidePanel } from '@components/app/side-panel';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
import { ShareTrigger } from '@core/component/TopBar/ShareButton';
import { useDocumentShareModal } from '@core/component/TopBar/shareModal';
-import { taskDetailRoute } from '../route';
import { useTasksView } from '../tasks-view-context';
import type { TaskDetailTarget } from '../types';
import { TaskDetail } from './TaskDetail';
diff --git a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx
index 90cf0c34e3..cb871c5003 100644
--- a/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksMobileTabs.tsx
@@ -1,6 +1,6 @@
-import { reviewsSplitRoute } from '@app/features/reviews-view/route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { useNavigate } from '@app/lib/split-router';
+import { reviewsSplitRoute } from '@app/routes/routes';
+import { useNavigate } from '@app/split-router';
import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';
import { enableTasksReviews } from '@core/constant/featureFlags';
import { type JSX, Show } from 'solid-js';
diff --git a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx b/apps/web/src/features/tasks-view/components/TasksSidebar.tsx
index 91dac8403d..39bb3246c4 100644
--- a/apps/web/src/features/tasks-view/components/TasksSidebar.tsx
+++ b/apps/web/src/features/tasks-view/components/TasksSidebar.tsx
@@ -6,9 +6,9 @@ import {
import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButton';
import { FavoriteContextMenu } from '@app/features/favorites/FavoriteContextMenu';
import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';
-import { reviewsSplitRoute } from '@app/features/reviews-view/route';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { useNavigate } from '@app/lib/split-router';
+import { reviewsSplitRoute } from '@app/routes/routes';
+import { useNavigate } from '@app/split-router';
import {
favoriteSplitContent,
useFavoriteDisplayName,
diff --git a/apps/web/src/features/tasks-view/project-detail-search.ts b/apps/web/src/features/tasks-view/project-detail-search.ts
new file mode 100644
index 0000000000..8b93bdb872
--- /dev/null
+++ b/apps/web/src/features/tasks-view/project-detail-search.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+export const projectDetailSearch = {
+ namespace: 'project',
+ schema: z.object({ discussionId: z.string().optional() }),
+ defaults: { discussionId: undefined as string | undefined },
+};
diff --git a/apps/web/src/features/tasks-view/route.tsx b/apps/web/src/features/tasks-view/route-views.tsx
similarity index 63%
rename from apps/web/src/features/tasks-view/route.tsx
rename to apps/web/src/features/tasks-view/route-views.tsx
index 44f1b1e703..4ca2c541c2 100644
--- a/apps/web/src/features/tasks-view/route.tsx
+++ b/apps/web/src/features/tasks-view/route-views.tsx
@@ -5,31 +5,30 @@ import {
import { Projects } from '@app/features/projects/projects';
import { ProjectTasksProvider } from '@app/features/projects/views/project-tasks-list';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import {
+ projectDetailRoute,
+ projectTaskRoute,
+ tasksSplitRoute,
+} from '@app/routes/routes';
import {
createSearchParams,
- defineRoute,
SplitRouter,
useNavigate,
useParams,
useRouteParams,
-} from '@app/lib/split-router';
-import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
+} from '@app/split-router';
import { SidePanel } from '@components/app/side-panel';
import {
AppView,
RedirectSplit,
withAuth,
} from '@components/app/split-layout/split-router/app-route-shell';
-import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
import { LoadingBlock } from '@core/component/LoadingBlock';
import { enableProjects } from '@core/constant/featureFlags';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { onMount, Show } from 'solid-js';
-import { z } from 'zod';
-import {
- TasksDetailRouteView,
- TasksDetailView,
-} from './components/TasksDetailView';
+import { TasksDetailView } from './components/TasksDetailView';
+import { projectDetailSearch } from './project-detail-search';
import { TasksView } from './tasks-view';
function TasksLegacyRouteView() {
@@ -57,26 +56,6 @@ export const TasksRouteView = withAuth(() => {
);
});
-export const taskDetailRoute = defineRoute({
- id: 'tasks-task',
- path: ':taskId',
- params: z.object({ taskId: z.string().min(1) }),
- component: TasksDetailRouteView,
- remountKey: ({ taskId }) => taskId,
- claim: ({ taskId }) => ({
- namespace: 'block',
- id: `md:${taskId}`,
- }),
- toReference: ({ taskId }) => uuidRouteReference(taskId, 'task'),
- externalSearch: Object.values(MARKDOWN_URL_PARAMS),
-});
-
-export const projectDetailSearch = {
- namespace: 'project',
- schema: z.object({ discussionId: z.string().optional() }),
- defaults: { discussionId: undefined as string | undefined },
-};
-
function DisabledProjectRoute() {
const navigate = useNavigate();
onMount(() =>
@@ -85,7 +64,7 @@ function DisabledProjectRoute() {
return null;
}
-function ProjectTaskRouteView() {
+export function ProjectTaskRouteView() {
const params = useParams<{
projectId: string;
section: 'overview' | 'tasks';
@@ -132,7 +111,7 @@ function ProjectTaskRouteView() {
);
}
-function ProjectDetailRouteView() {
+export function ProjectDetailRouteView() {
const params = useRouteParams(projectDetailRoute);
const [search] = createSearchParams(projectDetailSearch);
const flag = useFeatureFlag(enableProjects);
@@ -174,45 +153,3 @@ function ProjectDetailRouteView() {
</Show>
);
}
-
-export const projectTaskRoute = defineRoute({
- id: 'tasks-project-task',
- path: 'task/:taskId',
- params: z.object({ taskId: z.string().min(1) }),
- component: ProjectTaskRouteView,
- remountKey: ({ taskId }) => taskId,
- claim: ({ taskId }) => ({ namespace: 'block', id: `md:${taskId}` }),
- toReference: ({ taskId }) => uuidRouteReference(taskId, 'task'),
- externalSearch: Object.values(MARKDOWN_URL_PARAMS),
-});
-
-export const projectDetailRoute = defineRoute({
- id: 'tasks-project',
- path: 'projects/:projectId/:section',
- params: z.object({
- projectId: z.string().uuid(),
- section: z.enum(['overview', 'tasks']),
- }),
- component: ProjectDetailRouteView,
- remountKey: ({ projectId }) => projectId,
- claim: ({ projectId }) => ({
- namespace: 'block',
- id: `initiative:${projectId}`,
- }),
- toReference: ({ projectId }) => uuidRouteReference(projectId, 'initiative'),
- children: [projectTaskRoute],
-});
-
-export const tasksProjectsRoute = defineRoute({
- id: 'tasks-projects',
- path: 'projects',
- params: z.object({}).transform(() => ({ projectsTab: 'projects' as const })),
-});
-
-export const tasksSplitRoute = defineRoute({
- id: 'view-tasks',
- path: 'tasks',
- component: TasksRouteView,
- search: '*' as const,
- children: [projectDetailRoute, tasksProjectsRoute, taskDetailRoute],
-});
diff --git a/apps/web/src/features/tasks-view/route.test.tsx b/apps/web/src/features/tasks-view/route.test.tsx
index d79214a51d..8719733004 100644
--- a/apps/web/src/features/tasks-view/route.test.tsx
+++ b/apps/web/src/features/tasks-view/route.test.tsx
@@ -1,59 +1,62 @@
import {
+ projectDetailRoute,
+ projectTaskRoute,
+ taskDetailRoute,
+ tasksProjectsRoute,
+ tasksSplitRoute,
+} from '@app/routes/routes';
+import {
+ claimOf,
createRoutesManifest,
- decodeRoute,
- encodeRoute,
- getRouteClaim,
+ createSearchParamsCodec,
+ decodePane,
+ formatPanePath,
routeParams,
-} from '@app/lib/split-router/routes';
-import { createSearchParamsCodec } from '@app/lib/split-router/search-params-codec';
+} from '@app/split-router';
import { describe, expect, it, vi } from 'vitest';
-import { projectDetailSearch, tasksSplitRoute } from './route';
+import { projectDetailSearch } from './project-detail-search';
-vi.mock('@app/features/projects/project-detail', () => ({
- ProjectBreadcrumb: () => null,
- ProjectDetail: () => null,
-}));
-vi.mock('@app/features/projects/projects', () => ({ Projects: () => null }));
-vi.mock('@app/features/projects/views/project-tasks-list', () => ({
- ProjectTasksProvider: () => null,
-}));
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => ({ enabled: true }),
-}));
-vi.mock('@components/app/side-panel', () => ({ SidePanel: {} }));
-vi.mock('@components/app/split-layout/split-router/app-route-shell', () => ({
- withAuth: (value: unknown) => value,
- AppView: () => null,
- RedirectSplit: () => null,
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
}));
-vi.mock('@core/component/LoadingBlock', () => ({ LoadingBlock: () => null }));
-vi.mock('./components/TasksDetailView', () => ({
- TasksDetailView: () => null,
- TasksDetailRouteView: () => null,
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect: vi.fn(),
+ createConnectionWebsocketEffect: vi.fn(),
}));
-vi.mock('./tasks-view', () => ({ TasksView: () => null }));
const projectId = '01a0cf92-3101-7e21-9a20-6e21058d20e0';
-const manifest = createRoutesManifest({ definitions: [tasksSplitRoute] });
+const manifest = createRoutesManifest({
+ definitions: [
+ {
+ ...tasksSplitRoute,
+ children: [
+ { ...projectDetailRoute, children: [projectTaskRoute] },
+ tasksProjectsRoute,
+ taskDetailRoute,
+ ],
+ },
+ ],
+ defaultRoute: () => ({ matches: [{ id: tasksSplitRoute.id, params: {} }] }),
+});
describe('project routes in Tasks', () => {
it.each(['overview', 'tasks'])(
'restores the %s section in the Tasks shell and claims the same project',
(section) => {
const segments = ['tasks', 'projects', projectId, section];
- const entry = decodeRoute(manifest, segments)!;
- expect(encodeRoute(manifest, entry)).toEqual(segments);
- expect(entry.location.route.matches.map((match) => match.id)).toEqual([
+ const route = decodePane(manifest, segments)!;
+ expect(formatPanePath(manifest, route)).toBe(`/${segments.join('/')}`);
+ expect(route.matches.map((match) => match.id)).toEqual([
'view-tasks',
'tasks-project',
]);
- expect(routeParams(entry.location.route)).toEqual({ projectId, section });
+ expect(routeParams(route)).toEqual({ projectId, section });
// The same claim as the initiative block, so either view is reused.
- expect(getRouteClaim(manifest, entry.location.route)).toEqual({
- namespace: 'block',
- id: `initiative:${projectId}`,
- });
- const leaf = entry.location.route.matches.at(-1)!;
+ expect(claimOf(manifest, route)).toBe(`block:initiative:${projectId}`);
+ const leaf = route.matches.at(-1)!;
expect(
manifest.byId.get(leaf.id)?.definition.toReference?.(leaf.params)
).toEqual({ type: 'initiative', id: projectId });
@@ -69,30 +72,25 @@ describe('project routes in Tasks', () => {
'task',
'task-1',
];
- const entry = decodeRoute(manifest, segments)!;
- expect(encodeRoute(manifest, entry)).toEqual(segments);
- expect(entry.location.route.matches.map((match) => match.id)).toEqual([
+ const route = decodePane(manifest, segments)!;
+ expect(formatPanePath(manifest, route)).toBe(`/${segments.join('/')}`);
+ expect(route.matches.map((match) => match.id)).toEqual([
'view-tasks',
'tasks-project',
'tasks-project-task',
]);
- expect(routeParams(entry.location.route)).toEqual({
+ expect(routeParams(route)).toEqual({
projectId,
section: 'tasks',
taskId: 'task-1',
});
- expect(getRouteClaim(manifest, entry.location.route)).toEqual({
- namespace: 'block',
- id: 'md:task-1',
- });
+ expect(claimOf(manifest, route)).toBe('block:md:task-1');
});
it('resolves Projects as a collection instead of a task named projects', () => {
- const entry = decodeRoute(manifest, ['tasks', 'projects'])!;
- expect(entry.location.route.matches.at(-1)?.id).toBe('tasks-projects');
- expect(routeParams(entry.location.route)).toEqual({
- projectsTab: 'projects',
- });
+ const route = decodePane(manifest, ['tasks', 'projects'])!;
+ expect(route.matches.at(-1)?.id).toBe('tasks-projects');
+ expect(routeParams(route)).toEqual({ projectsTab: 'projects' });
});
it('restores a discussion target from the project search namespace', () => {
diff --git a/apps/web/src/features/tasks-view/tasks-tab-search.ts b/apps/web/src/features/tasks-view/tasks-tab-search.ts
index 0948ecb502..a478ea3d4f 100644
--- a/apps/web/src/features/tasks-view/tasks-tab-search.ts
+++ b/apps/web/src/features/tasks-view/tasks-tab-search.ts
@@ -1,4 +1,4 @@
-import { createSearchParamsCodec } from '@app/lib/split-router';
+import { createSearchParamsCodec } from '@app/split-router';
import { z } from 'zod';
import type { TasksTab } from './types';
diff --git a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx b/apps/web/src/features/tasks-view/tasks-view-context.test.tsx
index fde2c6f675..33d61c6e89 100644
--- a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view-context.test.tsx
@@ -21,7 +21,7 @@ const mocks = vi.hoisted(() => ({
dockOpen: (): boolean => false,
dockText: (): string => '',
}));
-vi.mock('@app/lib/split-router', () => ({
+vi.mock('@app/split-router', () => ({
useNavigate: () => vi.fn(),
useParams: () => ({}),
createSearchParams: () => [
@@ -36,12 +36,12 @@ vi.mock('./tasks-tab-search', () => ({
tasksTabSearch: {},
tasksTabSearchCodec: { serialize: () => ({}) },
}));
-vi.mock('./route', () => ({
+vi.mock('@app/routes/routes', () => ({
taskDetailRoute: {},
tasksProjectsRoute: {},
tasksSplitRoute: {},
+ reviewsSplitRoute: {},
}));
-vi.mock('@app/features/reviews-view/route', () => ({ reviewsSplitRoute: {} }));
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: mocks.projectsEnabled() }),
}));
diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsx
index 2281a8baa0..43d58dda83 100644
--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx
@@ -12,10 +12,11 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableProjects } from '@app/lib/core/constant/featureFlags';
import { makePersistedState } from '@app/lib/persistence';
import {
- createSearchParams,
- useNavigate,
- useParams,
-} from '@app/lib/split-router';
+ taskDetailRoute,
+ tasksProjectsRoute,
+ tasksSplitRoute,
+} from '@app/routes/routes';
+import { createSearchParams, useNavigate, useParams } from '@app/split-router';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import {
useSplitPanelOrThrow,
@@ -50,7 +51,6 @@ import {
type UseTasksDataSourceOptions,
useTasksDataSource,
} from './queries/use-tasks-query';
-import { taskDetailRoute, tasksProjectsRoute, tasksSplitRoute } from './route';
import { tasksTabSearch, tasksTabSearchCodec } from './tasks-tab-search';
import type {
TaskDetailTarget,
diff --git a/apps/web/src/features/tasks-view/tasks-view.tsx b/apps/web/src/features/tasks-view/tasks-view.tsx
index d0e90bb3e2..680c058553 100644
--- a/apps/web/src/features/tasks-view/tasks-view.tsx
+++ b/apps/web/src/features/tasks-view/tasks-view.tsx
@@ -2,7 +2,8 @@ import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
import { openProject } from '@app/features/projects/open-project';
import { ProjectsTab } from '@app/features/projects/projects';
import { ViewTour, ViewTourAction } from '@app/features/tours/ViewTour';
-import { SplitRouter, useNavigate, useParams } from '@app/lib/split-router';
+import { projectDetailRoute } from '@app/routes/routes';
+import { SplitRouter, useNavigate, useParams } from '@app/split-router';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { SplitPanel } from '@components/app/split-panel';
@@ -23,7 +24,6 @@ import {
import { TasksMobileTabs } from './components/TasksMobileTabs';
import { TasksSidebar } from './components/TasksSidebar';
import { TaskList } from './components/task-list/TaskList';
-import { projectDetailRoute } from './route';
import { TasksViewProvider, useTasksView } from './tasks-view-context';
import { tasksTour } from './tour';
import type { TasksViewStateOptions } from './types';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.test.tsx
index d3933e6534..dfe8a5f5eb 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/BlockLink.test.tsx
@@ -1,8 +1,6 @@
import { openEntityInSplit } from '@app/features/activity/open-entity-in-split';
-import {
- createSplitLayout,
- type SplitManager,
-} from '@components/app/split-layout/layoutManager';
+import type { SplitManager } from '@components/app/split-layout/layoutManager';
+import { createRoutedSplitLayout } from '@components/app/split-layout/tests/fixtures';
import { toast } from '@core/component/Toast/Toast';
import type { BlockOrchestrator } from '@core/orchestrator';
import { createRoot } from 'solid-js';
@@ -22,7 +20,10 @@ vi.mock('@components/app/split-layout/layout', () => ({
vi.mock('@components/app/split-layout/componentRegistry', () => ({
resolveComponent: () => ({ element: undefined }),
}));
-vi.mock('@core/block', () => ({ useMaybeBlockId: () => undefined }));
+vi.mock('@core/block', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/block')>()),
+ useMaybeBlockId: () => undefined,
+}));
vi.mock('@core/constant/allBlocks', () => ({
isBlockAlias: () => false,
resolveBlockAlias: (type: string) => type,
@@ -48,10 +49,7 @@ function setup() {
} as unknown as BlockOrchestrator;
const manager = createRoot((dispose) => {
onTestFinished(dispose);
- return createSplitLayout(orchestrator, [
- { type: 'component', id: 'channels' },
- { type: 'component', id: 'home' },
- ]);
+ return createRoutedSplitLayout(orchestrator, '/channels/~/home');
});
const [chat, inbox] = manager.splits();
manager.activateSplit(inbox.id);
diff --git a/apps/web/src/lib/core/constant/SettingsState.test.tsx b/apps/web/src/lib/core/constant/SettingsState.test.tsx
index 586f937e6a..dedbbe9105 100644
--- a/apps/web/src/lib/core/constant/SettingsState.test.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.test.tsx
@@ -2,11 +2,12 @@ import {
MobileSettingsProvider,
useMobileSettings,
} from '@app/features/settings/context/mobile-settings';
+import { paneRoute } from '@app/routes/app-route';
import {
+ createMemoryHistory,
+ createMemoryPaneStore,
createSplitRouter,
- type SplitRouterLayoutSnapshot,
-} from '@app/lib/split-router';
-import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
+} from '@app/split-router';
import {
setActiveTabId as setSplitActiveTabId,
activeTabId as splitActiveTabId,
@@ -110,43 +111,35 @@ describe('settings entry points', () => {
mocks.mobile = false;
mocks.hasSettingsSplit = true;
const { state } = mountSettings();
- let entries: SplitRouterLayoutSnapshot<string>['entries'] = [];
const router = createSplitRouter({
- routes: { definitions: [{ id: 'settings', path: 'settings/:tab' }] },
- location: createMemorySplitRouterLocation('/settings/account'),
- layout: {
- snapshot: () => ({ entries }),
- reconcile: (next) => {
- entries = next.map((location) => ({
- location,
- splitId: 'settings-split',
- }));
- },
- open: ({ location }) => {
- entries = [{ splitId: 'settings-split', location }];
- return { status: 'applied', splitId: 'settings-split' };
- },
- updateCurrentLocation: (id, update) => {
- entries = entries.map((entry) => {
- if (entry.splitId !== id) return entry;
- return { location: update(entry), splitId: id };
- });
- },
+ routes: {
+ definitions: [{ id: 'settings', path: 'settings/:tab' }],
+ defaultRoute: () => ({
+ matches: [{ id: 'settings', params: { tab: 'account' } }],
+ }),
+ },
+ history: createMemoryHistory('/settings/account'),
+ paneStore: createMemoryPaneStore(),
+ policy: {
+ placeNewPane: () => ({ insertAt: 0 }),
+ closeAction: () => ({ type: 'keep' }),
activate: () => {},
- subscribe: () => () => {},
},
});
+ const pane = router.panes()[0]!;
+ const currentTab = () =>
+ router.entry(pane)?.location.route.matches[0]?.params.tab;
const navigateTab = (tab: string) => {
expect(mocks.updateCurrentEntry).not.toHaveBeenCalled();
- router.navigate('settings-split', `/settings/${tab.toLowerCase()}`);
+ router.navigate(pane, `/settings/${tab.toLowerCase()}`);
};
state.selectTab('Appearance', navigateTab);
state.selectTab('Account', navigateTab);
- expect(router.history('settings-split')?.entries).toHaveLength(3);
- router.navigate('settings-split', -1);
- expect(entries[0].location.route.matches[0].params.tab).toBe('appearance');
- router.navigate('settings-split', -1);
- expect(entries[0].location.route.matches[0].params.tab).toBe('account');
+ expect(router.history(pane)?.entries).toHaveLength(3);
+ router.navigate(pane, -1);
+ expect(currentTab()).toBe('appearance');
+ router.navigate(pane, -1);
+ expect(currentTab()).toBe('account');
router.dispose();
});
@@ -267,9 +260,7 @@ describe('settings entry points', () => {
type: 'component',
id: 'settings',
entryMetadata: {
- route: {
- matches: [{ id: 'settings', params: { tab: 'appearance' } }],
- },
+ route: paneRoute({ id: 'settings', params: { tab: 'appearance' } }),
},
},
expect.objectContaining({ allowDuplicate: false, preferNewSplit: true })
@@ -324,7 +315,7 @@ describe('settings entry points', () => {
expect(mocks.managerOpenWithSplit).toHaveBeenCalledWith(
expect.objectContaining({
entryMetadata: {
- route: { matches: [{ id: 'settings', params: { tab: 'billing' } }] },
+ route: paneRoute({ id: 'settings', params: { tab: 'billing' } }),
},
}),
expect.objectContaining({ allowDuplicate: false, preferNewSplit: true })
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index cb58749e0c..b9c032328e 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -1,12 +1,9 @@
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { toBaseRelative } from '@app/constants/routerBase';
import { useMobileSettings } from '@app/features/settings/context/mobile-settings';
-import {
- rootRouteMatch,
- routeParams,
- type SplitLocation,
-} from '@app/lib/split-router';
+import { paneRootMatch, paneRoute } from '@app/routes/app-route';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { routeParams, type SplitLocation } from '@app/split-router';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { isMobile } from '@core/mobile/isMobile';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -122,14 +119,10 @@ export const useSettingsState = () => {
type: 'component' as const,
id: 'settings' as const,
entryMetadata: {
- route: {
- matches: [
- {
- id: 'settings',
- params: { tab: settingsTabToSlug(tab) },
- },
- ],
- },
+ route: paneRoute({
+ id: 'settings',
+ params: { tab: settingsTabToSlug(tab) },
+ }),
},
});
@@ -141,12 +134,11 @@ export const useSettingsState = () => {
const slug = settingsTabToSlug(tab);
const location = split.content.entryMetadata as SplitLocation | undefined;
- if (
- rootRouteMatch(location?.route)?.id === 'settings' &&
- routeParams(location?.route).tab === slug
- ) {
- return;
- }
+ const showsSettings =
+ location !== undefined &&
+ paneRootMatch(location.route)?.id === 'settings';
+ const showsTab = routeParams(location?.route).tab === slug;
+ if (showsSettings && showsTab) return;
globalSplitManager()
?.getSplit(split.id)
diff --git a/apps/web/src/lib/split-router/next/history/solid-router.ts b/apps/web/src/lib/split-router/next/history/solid-router.ts
index a69e739751..98d4919889 100644
--- a/apps/web/src/lib/split-router/next/history/solid-router.ts
+++ b/apps/web/src/lib/split-router/next/history/solid-router.ts
@@ -37,8 +37,6 @@ export type SolidBeforeLeaveEvent = Pick<
export type SolidRouterHistoryOptions = {
location: SolidRouterLocationLike;
navigate: SolidRouterNavigate;
- /** Whether a mount-relative path belongs to the router rather than another route. */
- owns: (path: string) => boolean;
/** Solid Router's `useBeforeLeave`; enables `intercept`. */
beforeLeave?: (listener: (event: SolidBeforeLeaveEvent) => void) => void;
/** The `base` passed to the Solid Router. */
@@ -85,7 +83,7 @@ function windowPath(mode: SolidRouterHistoryOptions['mode']): string {
export function createSolidRouterHistory(
options: SolidRouterHistoryOptions
): HistoryAdapter {
- const { location, navigate, owns, beforeLeave } = options;
+ const { location, navigate, beforeLeave } = options;
const base = normalizeBase(options.base);
const listeners = createList<(change: ExternalChange) => void>();
let reverting: (() => void)[] = [];
@@ -179,7 +177,6 @@ export function createSolidRouterHistory(
const outsideBase = !toMount(untrack(() => location.pathname));
if (outsideBase) return;
- if (!owns(next.path)) return;
const previous = last;
last = { index: landed?.index ?? previous.index + 1, location: next };
@@ -222,13 +219,6 @@ export function createSolidRouterHistory(
settleReverts();
};
- const ownedMount = (to: string) => {
- const mount = toMount(to);
- const owned = mount !== undefined && owns(mount.path);
-
- return owned ? mount : undefined;
- };
-
const landedPath = options.landedPath ?? (() => windowPath(options.mode));
/** Leaving the router's routes; a write still queued would pull the host back in. */
@@ -252,7 +242,7 @@ export function createSolidRouterHistory(
handler: InterceptHandler,
event: SolidBeforeLeaveEvent
) => {
- const staysInRouter = ownedMount(landedPath()) !== undefined;
+ const staysInRouter = toMount(landedPath()) !== undefined;
if (staysInRouter) return;
leave(handler(undefined), event);
@@ -263,7 +253,7 @@ export function createSolidRouterHistory(
event: SolidBeforeLeaveEvent,
to: string
) => {
- const mount = ownedMount(to);
+ const mount = toMount(to);
if (!mount) {
leave(handler(undefined), event);
return;
diff --git a/apps/web/src/lib/split-router/next/index.ts b/apps/web/src/lib/split-router/next/index.ts
index aa4e0a0435..05ccb52b3b 100644
--- a/apps/web/src/lib/split-router/next/index.ts
+++ b/apps/web/src/lib/split-router/next/index.ts
@@ -21,7 +21,7 @@ export type {
Placement,
} from './panes/types';
export type { ClaimHolder } from './router/claims';
-export { createSplitRouter, type SplitRouter } from './router/create-router';
+export { createSplitRouter } from './router/create-router';
export { PANE_LEVEL } from './router/leave-guards';
export type {
SplitRouterMiddleware,
@@ -41,11 +41,32 @@ export type {
SplitPanePolicy,
SplitRouterOptions,
} from './router/types';
+export {
+ formatLocation,
+ formatPanePath,
+ parseLocation,
+ splitPanePaths,
+} from './routes/codec';
export { defineRoute, defineRoutes } from './routes/define';
+export {
+ canonicalRoute,
+ createRoutesManifest,
+ decodePane,
+ type SplitRoutesManifest,
+} from './routes/manifest';
+export { decodeSegment } from './routes/path';
+export {
+ claimOf,
+ externalSearchKeys,
+ filterRouteSearch,
+ routeParams,
+} from './routes/queries';
+export { replacePaneSearchParams } from './routes/search';
export {
createSearchParamsCodec,
type SearchParamsCodec,
type SearchParamsCodecOptions,
+ takeLast,
} from './routes/search-params';
export type {
DefinedSplitRoute,
@@ -63,6 +84,7 @@ export type {
SerializedSearchParams,
SplitLocation,
SplitNavigationTarget,
+ SplitReference,
SplitRouteClaim,
SplitRouteDefinition,
SplitRouteInfo,
@@ -76,7 +98,7 @@ export type {
SplitSearchUpdate,
WriteMode,
} from './routes/types';
-export { SplitRouterProvider, useSplitRouter } from './solid/context';
+export { useOptionalSplitRouter, useSplitRouter } from './solid/context';
export {
type CreateSearchParamsOptions,
createSearchParams,
@@ -90,13 +112,18 @@ export {
useEntryProps,
useMatches,
useNavigate,
+ useOwnsSearchNamespace,
usePane,
+ usePaneHistory,
useParams,
usePendingNavigation,
useRouteParams,
useRouteState,
} from './solid/hooks';
-export { Outlet, type OutletProps } from './solid/outlet';
-export { PaneScope } from './solid/pane-scope';
+export type { OutletProps } from './solid/outlet';
+export type { RouteProps } from './solid/route';
+export type { RouterProps } from './solid/router';
+export { SplitRouter } from './solid/split-router';
export { useBeforeLeave } from './solid/use-before-leave';
export { useClaim } from './solid/use-claim';
+export { isRecord, isSafeName } from './utils';
diff --git a/apps/web/src/lib/split-router/next/router/create-router.ts b/apps/web/src/lib/split-router/next/router/create-router.ts
index 89332f3562..a34d842872 100644
--- a/apps/web/src/lib/split-router/next/router/create-router.ts
+++ b/apps/web/src/lib/split-router/next/router/create-router.ts
@@ -21,7 +21,10 @@ import { createUrlNavigation } from './url-navigation';
export function createSplitRouter(options: SplitRouterOptions) {
const routes = createRoutesManifest(options.routes);
- const { history } = options;
+ const history =
+ typeof options.history === 'function'
+ ? options.history(routes)
+ : options.history;
const [ready, setReady] = createSignal(false);
let disposed = false;
@@ -57,31 +60,32 @@ export function createSplitRouter(options: SplitRouterOptions) {
paneNavigation.carrySearch(pane, destination, mode),
});
- const paneNavigation = createPaneNavigation({
+ const urlNavigation = createUrlNavigation({
routes,
+ history,
panes,
url,
runner,
- claims,
+ guards,
+ markReady: () => setReady(true),
});
- const paneList = createPaneList({
+ const paneNavigation = createPaneNavigation({
routes,
panes,
url,
runner,
claims,
- navigation: paneNavigation,
+ showAlone: urlNavigation.showAlone,
});
- const urlNavigation = createUrlNavigation({
+ const paneList = createPaneList({
routes,
- history,
panes,
url,
runner,
- guards,
- markReady: () => setReady(true),
+ claims,
+ navigation: paneNavigation,
});
const disconnect = urlNavigation.connect();
@@ -130,8 +134,10 @@ export function createSplitRouter(options: SplitRouterOptions) {
canGo: paneNavigation.canGo,
open: paneList.open,
close: paneList.close,
+ remove: paneList.remove,
move: paneList.move,
entry: panes.current,
+ history: panes.read,
arrival: panes.arrival,
pending: runner.pending,
matches,
diff --git a/apps/web/src/lib/split-router/next/router/middleware.ts b/apps/web/src/lib/split-router/next/router/middleware.ts
index 09ec46bd55..f930636167 100644
--- a/apps/web/src/lib/split-router/next/router/middleware.ts
+++ b/apps/web/src/lib/split-router/next/router/middleware.ts
@@ -19,6 +19,7 @@ export type SplitRouterMiddlewareResult =
| { type: 'cancel' };
export type SplitRouterMiddlewareContext = {
+ routes: SplitRoutesManifest;
/** The entry the pane is leaving, if any. */
from: Readonly<Entry> | undefined;
/** The proposed entry; it has not been applied yet. */
@@ -63,11 +64,14 @@ function recordVisit(visited: string[], path: string, entry: Entry): void {
}
function middlewareContext(
- request: MiddlewareRequest,
+ run: MiddlewareRun,
entry: Entry,
path: string
): SplitRouterMiddlewareContext {
+ const { request } = run;
+
return {
+ routes: run.routes,
from: request.from,
to: entry,
path,
@@ -118,7 +122,7 @@ function runHandler(
const handler = run.handlers[index];
if (!handler) return entry;
- const result = handler(middlewareContext(run.request, entry, path));
+ const result = handler(middlewareContext(run, entry, path));
return andThen(result, (settled): Outcome<Entry> => {
// A handler can settle after the navigation was called off.
diff --git a/apps/web/src/lib/split-router/next/router/pane-list.ts b/apps/web/src/lib/split-router/next/router/pane-list.ts
index 917367c6fc..3ac137ecf9 100644
--- a/apps/web/src/lib/split-router/next/router/pane-list.ts
+++ b/apps/web/src/lib/split-router/next/router/pane-list.ts
@@ -219,6 +219,11 @@ export function createPaneList(options: {
const location = navigation.resolve(base, to, navigateOptions);
if (!location) return CANCELLED_RESULT;
+ const intoPane = 'pane' in target ? target.pane : undefined;
+ if (navigation.leavesSharedRoute(intoPane, location)) {
+ return navigation.showAlone(location, navigateOptions);
+ }
+
const { placement, holder } = placementFor(
location,
target,
@@ -249,6 +254,16 @@ export function createPaneList(options: {
});
},
+ /** Remove a pane without asking the policy; its leave guards still apply. */
+ remove(pane: PaneId): MaybePromise<boolean> {
+ return runner.act(false, () => {
+ const exists = panes.current(pane) !== undefined;
+ if (!exists) return false;
+
+ return removePane(pane);
+ });
+ },
+
move(pane: PaneId, to: number): void {
void runner.act(undefined, () => {
runner.commitNow({
diff --git a/apps/web/src/lib/split-router/next/router/pane-navigation.ts b/apps/web/src/lib/split-router/next/router/pane-navigation.ts
index c7ca904f35..6ddd10363d 100644
--- a/apps/web/src/lib/split-router/next/router/pane-navigation.ts
+++ b/apps/web/src/lib/split-router/next/router/pane-navigation.ts
@@ -1,3 +1,4 @@
+import { untrack } from 'solid-js';
import { match, P } from 'ts-pattern';
import {
currentEntry,
@@ -153,9 +154,40 @@ export function createPaneNavigation(options: {
url: Url;
runner: Runner;
claims: Claims;
+ /** Shows `location` as the only pane, for a destination the other panes can't share the URL with. */
+ showAlone(
+ location: SplitLocation,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult>;
}) {
const { routes, panes, url, runner, claims } = options;
+ /** Panes share one top-level route; `location` under another can't join the panes besides `pane`. */
+ const leavesSharedRoute = (
+ pane: PaneId | undefined,
+ location: SplitLocation
+ ): boolean => {
+ const root = location.route.matches[0].id;
+
+ return untrack(panes.ids).some((other) => {
+ if (other === pane) return false;
+
+ const entry = untrack(() => panes.current(other));
+ if (!entry) return false;
+
+ return entry.location.route.matches[0].id !== root;
+ });
+ };
+
+ /** Back and Forward skip entries shown elsewhere and entries under another top-level route. */
+ const visitableIn =
+ (pane: PaneId, allowDuplicate?: boolean) => (entry: Entry) => {
+ const shownElsewhere = !claims.canVisit(pane, allowDuplicate)(entry);
+ if (shownElsewhere) return false;
+
+ return !leavesSharedRoute(pane, entry.location);
+ };
+
const applyVisit = (
pane: PaneId,
{ history, arrival }: Visit,
@@ -264,6 +296,10 @@ export function createPaneNavigation(options: {
const location = resolve(from, to, navigateOptions);
if (!location) return CANCELLED_RESULT;
+ if (leavesSharedRoute(pane, location)) {
+ return options.showAlone(location, navigateOptions);
+ }
+
return visitLocation(pane, from, location, navigateOptions);
}
@@ -274,7 +310,7 @@ export function createPaneNavigation(options: {
navigateOptions: SplitNavigateOptions
): MaybePromise<NavigationResult> {
const { allowDuplicate } = navigateOptions;
- const visitable = claims.canVisit(pane, allowDuplicate);
+ const visitable = visitableIn(pane, allowDuplicate);
const snapshot = panes.read(pane);
if (!snapshot) return CANCELLED_RESULT;
@@ -298,7 +334,7 @@ export function createPaneNavigation(options: {
const snapshot = panes.read(pane);
if (!snapshot) return;
- return findBack(snapshot, predicate, claims.canVisit(pane));
+ return findBack(snapshot, predicate, visitableIn(pane));
};
/** False when the jump is turned down. */
@@ -443,7 +479,7 @@ export function createPaneNavigation(options: {
const snapshot = panes.read(pane);
if (!snapshot) return false;
- return findStep(snapshot, delta, claims.canVisit(pane)) !== undefined;
+ return findStep(snapshot, delta, visitableIn(pane)) !== undefined;
},
/** Carries the search `destination` asked for to `pane`, which already shows it. */
@@ -465,5 +501,7 @@ export function createPaneNavigation(options: {
visitLocation,
backStep,
jumpBack,
+ leavesSharedRoute,
+ showAlone: options.showAlone,
};
}
diff --git a/apps/web/src/lib/split-router/next/router/preload.ts b/apps/web/src/lib/split-router/next/router/preload.ts
index 95aa8dbbfd..27cf0c4eaf 100644
--- a/apps/web/src/lib/split-router/next/router/preload.ts
+++ b/apps/web/src/lib/split-router/next/router/preload.ts
@@ -3,7 +3,7 @@ import {
type SplitRouteNode,
type SplitRoutesManifest,
} from '../routes/manifest';
-import { mergedParams } from '../routes/queries';
+import { routeParams } from '../routes/queries';
import type { PreloadIntent, SplitLocation } from '../routes/types';
import { isPromise } from '../utils';
@@ -45,7 +45,7 @@ function preloadNode(
warmComponent(definition.component);
const data = definition.preload?.({
- params: mergedParams(location.route, depth + 1),
+ params: routeParams(location.route, depth + 1),
search: location.search,
intent,
signal,
diff --git a/apps/web/src/lib/split-router/next/router/types.ts b/apps/web/src/lib/split-router/next/router/types.ts
index 7cc5de0799..e90fdf17e3 100644
--- a/apps/web/src/lib/split-router/next/router/types.ts
+++ b/apps/web/src/lib/split-router/next/router/types.ts
@@ -1,6 +1,7 @@
import type { HistoryAdapter } from '../history/types';
import type { Panes } from '../panes/panes';
import type { CloseAction, PanePolicy, PaneStore } from '../panes/types';
+import type { SplitRoutesManifest } from '../routes/manifest';
import type {
Entry,
PaneId,
@@ -105,7 +106,8 @@ export type RouteMatchInfo = {
export type SplitRouterOptions = {
routes: SplitRoutes;
- history: HistoryAdapter;
+ /** A function receives the compiled routes, for adapters whose path transforms read them. */
+ history: HistoryAdapter | ((routes: SplitRoutesManifest) => HistoryAdapter);
paneStore: PaneStore<Entry>;
policy: SplitPanePolicy;
middleware?: readonly SplitRouterMiddleware[];
diff --git a/apps/web/src/lib/split-router/next/router/url-navigation.ts b/apps/web/src/lib/split-router/next/router/url-navigation.ts
index a4bbb9de90..78751d255b 100644
--- a/apps/web/src/lib/split-router/next/router/url-navigation.ts
+++ b/apps/web/src/lib/split-router/next/router/url-navigation.ts
@@ -7,9 +7,14 @@ import type {
import { type ChangedPane, changedPanes } from '../panes/diff';
import { decodePanes, sameExternalLocation } from '../routes/codec';
import type { SplitRoutesManifest } from '../routes/manifest';
-import type { Entry, ExternalLocation, WriteMode } from '../routes/types';
+import type {
+ Entry,
+ ExternalLocation,
+ SplitLocation,
+ WriteMode,
+} from '../routes/types';
import { type MaybePromise, UNCANCELLABLE } from '../utils';
-import { sameVisit } from './entries';
+import { createEntry, sameVisit } from './entries';
import {
checksFor,
type LeaveGuards,
@@ -23,6 +28,7 @@ import type {
NavigationResult,
PaneTarget,
RouterPanes,
+ SplitNavigateOptions,
} from './types';
import type { Url } from './url';
@@ -61,7 +67,7 @@ export function createUrlNavigation(options: {
}) {
const { routes, history, panes, url, runner, guards } = options;
- /** Makes every pane show `location`. */
+ /** Makes every pane show `location`; a URL nothing handles is written back as the default route. */
const navigationTo = (
location: ExternalLocation,
{ cause, mode, revert }: UrlNavigationOptions
@@ -89,6 +95,34 @@ export function createUrlNavigation(options: {
};
};
+ /**
+ * Shows `location` as the only pane: a pane navigating under a different
+ * top-level route can't share the URL with the others.
+ */
+ const showAlone = (
+ location: SplitLocation,
+ navigateOptions: SplitNavigateOptions
+ ): MaybePromise<NavigationResult> => {
+ const entry = createEntry(routes, location, undefined, navigateOptions);
+ const diff = panes.diff([{ entry }], { same: sameVisit, adopt });
+
+ const navigation: Navigation = {
+ cause: 'navigate',
+ targets: changedPanes(diff).map(toTarget),
+ removed: diff.removed,
+ apply: (entries) => {
+ panes.applyDiff(diff, entries);
+ url.write('push');
+
+ const [first] = diff.panes;
+
+ return { status: 'committed', pane: first!.pane };
+ },
+ };
+
+ return runner.startUrl(navigation, false);
+ };
+
/** The first load; pane actions wait for it. */
const load = (location: ExternalLocation) => {
const navigation = navigationTo(location, {
@@ -162,6 +196,8 @@ export function createUrlNavigation(options: {
};
return {
+ showAlone,
+
/** Loads the URL and follows the history adapter until the returned stop is called. */
connect(): () => void {
const unsubscribe = history.subscribe(follow);
diff --git a/apps/web/src/lib/split-router/next/routes/codec.ts b/apps/web/src/lib/split-router/next/routes/codec.ts
index 9d5f8e6c50..55f9a688e1 100644
--- a/apps/web/src/lib/split-router/next/routes/codec.ts
+++ b/apps/web/src/lib/split-router/next/routes/codec.ts
@@ -1,6 +1,7 @@
import deepEqual from 'fast-deep-equal';
import { createId, isRecord } from '../utils';
import {
+ decodeFirstPane,
decodePane,
defaultRoute,
formatPane,
@@ -10,6 +11,7 @@ import { decodeSegment, SPLIT_PATH_SEPARATOR, splitSegments } from './path';
import {
externalSearchKeys,
filterRouteSearch,
+ keepsAllExternalSearch,
parseRouteEntryState,
} from './queries';
import {
@@ -76,15 +78,6 @@ function encodeSegment(segment: string): string {
return segment === SPLIT_PATH_SEPARATOR ? '%7E' : encodeURIComponent(segment);
}
-function decodePaneSegments(
- routes: SplitRoutesManifest,
- raw: readonly string[]
-): SplitRouteState {
- const segments = raw.map(decodeSegment);
-
- return decodePane(routes, segments) ?? defaultRoute(routes);
-}
-
function readHistoryPane(value: unknown): SplitHistoryPane | undefined {
if (!isRecord(value)) return;
if (typeof value.pane !== 'string') return;
@@ -155,20 +148,41 @@ function defaultPanes(
}
/**
- * Each pane decodes on its own. A pane that matches nothing lands on the
- * catch-all route (or the default route when there is none); others are unaffected.
+ * The first pane picks the URL's top-level route, and every later pane must
+ * match under the same one. Undefined when nothing handles the URL.
*/
+function paneRoutes(
+ routes: SplitRoutesManifest,
+ parts: readonly (readonly string[])[]
+): SplitRouteState[] | undefined {
+ const [first, ...rest] = parts.map((raw) => raw.map(decodeSegment));
+ if (!first) return [];
+
+ const firstRoute = decodeFirstPane(routes, first);
+ if (!firstRoute) return;
+
+ const root = firstRoute.matches[0].id;
+ const restRoutes = rest.map((segments) => decodePane(routes, segments));
+ const sharesRoot = restRoutes.every((route) => route?.matches[0].id === root);
+ if (!sharesRoot) return;
+
+ return [firstRoute, ...(restRoutes as SplitRouteState[])];
+}
+
+/** The panes a URL shows. A URL nothing handles shows the default route, which the router writes back. */
export function decodePanes(
routes: SplitRoutesManifest,
location: ExternalLocation,
createEntryId: () => string = () => createId('entry')
): DecodedPanes {
const parts = splitPanePaths(location.path);
+ const decoded = paneRoutes(routes, parts);
+ if (!decoded?.length) return defaultPanes(routes, createEntryId);
+
const search = parsePaneSearch(location.search);
const stored = storedPanes(location.state, parts.length);
- const panes = parts.map((raw, position): DecodedPane => {
- const route = decodePaneSegments(routes, raw);
+ const panes = decoded.map((route, position): DecodedPane => {
const pane = stored?.[position];
const entry: Entry = {
id: pane?.entry ?? createEntryId(),
@@ -184,9 +198,7 @@ export function decodePanes(
return pane ? { paneId: pane.pane, entry } : { entry };
});
- if (panes.length > 0) return { panes };
-
- return defaultPanes(routes, createEntryId);
+ return { panes };
}
export function formatPanePath(
@@ -221,10 +233,12 @@ function panesSearch(
previousSearch: string
): string {
const owned = externalSearchKeys(routes, entries);
+ const keepsAll = keepsAllExternalSearch(routes, entries);
const query = new URLSearchParams();
for (const [key, value] of new URLSearchParams(previousSearch)) {
- const keep = !isSplitSearchKey(key) && owned.includes(key);
+ const external = !isSplitSearchKey(key);
+ const keep = external && (keepsAll || owned.includes(key));
if (keep) query.append(key, value);
}
diff --git a/apps/web/src/lib/split-router/next/routes/define.ts b/apps/web/src/lib/split-router/next/routes/define.ts
index e1a0fe80c5..7f0c5af6dd 100644
--- a/apps/web/src/lib/split-router/next/routes/define.ts
+++ b/apps/web/src/lib/split-router/next/routes/define.ts
@@ -5,6 +5,7 @@ import type {
Entry,
InferSplitRouteParams,
InferSplitRoutePathParams,
+ SplitReference,
SplitRouteClaim,
SplitRouteInfo,
SplitRoutePreloadContext,
@@ -15,7 +16,7 @@ import type {
type SplitRouteDefinitionConstraint = {
id: string;
- path: string;
+ path?: string;
aliases?: readonly string[];
component?: unknown;
children?: readonly SplitRouteDefinitionConstraint[];
@@ -23,9 +24,11 @@ type SplitRouteDefinitionConstraint = {
state?: StandardSchemaV1;
serializeParams?: unknown;
claim?: unknown;
- search?: readonly string[];
+ toReference?: unknown;
+ search?: readonly string[] | '*';
externalSearch?:
| readonly string[]
+ | '*'
| ((entry: Readonly<Entry>) => readonly string[]);
remountKey?: unknown;
preload?: unknown;
@@ -35,6 +38,7 @@ type SplitRouteDefinitionConstraint = {
type RouteParamCallbacks<TParams> = {
serializeParams?: (params: TParams) => SplitRouteRawParams;
claim?: (params: TParams) => SplitRouteClaim | undefined;
+ toReference?: (params: TParams) => SplitReference | undefined;
remountKey?: (
params: TParams,
context: SplitRouteRemountContext
@@ -219,6 +223,21 @@ export function defineRoute<
StandardSchemaV1.InferOutput<TParamsSchema>
>
>;
+export function defineRoute<
+ const TDefinition extends SplitRouteDefinitionConstraint,
+>(
+ definition: TDefinition & {
+ path?: undefined;
+ aliases?: undefined;
+ params?: undefined;
+ } & RouteParamCallbacks<{}>
+): DefinedSplitRoute<
+ TDefinition & {
+ path?: undefined;
+ aliases?: undefined;
+ params?: undefined;
+ } & RouteParamCallbacks<{}>
+>;
export function defineRoute(
definition: SplitRouteDefinitionConstraint
): unknown {
diff --git a/apps/web/src/lib/split-router/next/routes/manifest.ts b/apps/web/src/lib/split-router/next/routes/manifest.ts
index 486f64bc99..ced5f08f66 100644
--- a/apps/web/src/lib/split-router/next/routes/manifest.ts
+++ b/apps/web/src/lib/split-router/next/routes/manifest.ts
@@ -102,11 +102,26 @@ function ownNamespaces(search: readonly string[] | undefined): string[] {
return own;
}
+/** A route without a path that lists no namespaces leaves the choice to its children. */
+function searchParent(
+ parent: SplitRouteNode | undefined
+): SplitRouteNode | undefined {
+ let node = parent;
+ while (node && isLayoutRoute(node) && node.definition.search === undefined) {
+ node = node.parent;
+ }
+
+ return node;
+}
+
function branchSearch(
- parent: SplitRouteNode | undefined,
- search: readonly string[] | undefined
+ enclosing: SplitRouteNode | undefined,
+ search: readonly string[] | '*' | undefined
): readonly string[] | 'any' {
+ if (search === '*') return 'any';
+
const own = ownNamespaces(search);
+ const parent = searchParent(enclosing);
if (!parent) return search === undefined ? 'any' : own;
if (parent.search === 'any') return 'any';
@@ -116,6 +131,10 @@ function branchSearch(
return [...inherited, ...added];
}
+/** A route without a path groups its children; only they can be matched. */
+const isLayoutRoute = (node: SplitRouteNode) =>
+ node.definition.path === undefined;
+
function collectBranches<TComponent>(
branches: RouteBranch<TComponent>[],
node: SplitRouteNode<TComponent>,
@@ -126,12 +145,14 @@ function collectBranches<TComponent>(
const branchNodes = [...nodes, node];
const branchPatterns = [...patterns, tokens];
- branches.push({
- nodes: branchNodes,
- patterns: branchPatterns,
- score: specificity(branchPatterns.flat()),
- order: branches.length,
- });
+ if (!isLayoutRoute(node as SplitRouteNode)) {
+ branches.push({
+ nodes: branchNodes,
+ patterns: branchPatterns,
+ score: specificity(branchPatterns.flat()),
+ order: branches.length,
+ });
+ }
for (const child of node.children) {
collectBranches(branches, child, branchNodes, branchPatterns);
@@ -178,11 +199,12 @@ function claimSiblingPaths(
siblingPaths: string[],
definition: Pick<SplitRouteDefinition, 'path' | 'aliases'>
): void {
+ if (definition.path === undefined) return;
+
const paths = [definition.path, ...(definition.aliases ?? [])];
for (const path of paths) {
const key = patternKey(path);
- if (!key) throw new Error(`Invalid split route path "${path}"`);
if (siblingPaths.includes(key)) {
throw new Error(`Duplicate sibling split route path "${key}"`);
@@ -219,21 +241,36 @@ function createNode<TComponent>(
return node;
}
+function assertLayoutHasChildren(definition: SplitRouteDefinition): void {
+ const isLayout = definition.path === undefined;
+ const hasChildren = (definition.children?.length ?? 0) > 0;
+ if (!isLayout || hasChildren) return;
+
+ throw new Error(
+ `Split route "${definition.id}" has no path, so it needs children`
+ );
+}
+
+/** Children of a route without a path sit beside its siblings, so they share sibling paths. */
function compileNodes<TComponent>(
byId: Map<string, SplitRouteNode<TComponent>>,
definitions: readonly SplitRouteDefinition<TComponent>[],
- parent?: SplitRouteNode<TComponent>
+ parent?: SplitRouteNode<TComponent>,
+ siblingPaths: string[] = []
): SplitRouteNode<TComponent>[] {
- const siblingPaths: string[] = [];
-
return definitions.map((definition) => {
assertNewRouteId(byId, definition.id);
+ assertLayoutHasChildren(definition as SplitRouteDefinition);
claimSiblingPaths(siblingPaths, definition);
const children: SplitRouteNode<TComponent>[] = [];
const node = createNode(definition, parent, children);
byId.set(definition.id, node);
- children.push(...compileNodes(byId, definition.children ?? [], node));
+
+ const isLayout = definition.path === undefined;
+ const childSiblings = isLayout ? siblingPaths : [];
+ const childDefinitions = definition.children ?? [];
+ children.push(...compileNodes(byId, childDefinitions, node, childSiblings));
return node;
});
@@ -281,17 +318,43 @@ function matchBranch(
return { matches: matches as [SplitRouteMatch, ...SplitRouteMatch[]] };
}
+function decodeAmong(
+ branches: readonly RouteBranch[],
+ segments: readonly string[]
+): SplitRouteState | undefined {
+ for (const branch of branches) {
+ const route = matchBranch(branch, segments);
+ if (route) return route;
+ }
+}
+
/** The most specific route for one pane's decoded segments. */
export function decodePane(
routes: SplitRoutesManifest,
segments: readonly string[]
): SplitRouteState | undefined {
- if (segments.length === 0) return;
+ return decodeAmong(routes.branches, segments);
+}
- for (const branch of routes.branches) {
- const route = matchBranch(branch, segments);
- if (route) return route;
- }
+/** A splat nested in another route, like an in-pane not-found; it can't pick a URL's top-level route. */
+function isNestedCatchAll(branch: RouteBranch): boolean {
+ if (branch.nodes.length < 2) return false;
+
+ const tokens = branch.patterns.flat();
+
+ return tokens.length === 1 && tokens[0]!.type === 'catchAll';
+}
+
+/** The first pane picks the URL's top-level route. */
+export function decodeFirstPane(
+ routes: SplitRoutesManifest,
+ segments: readonly string[]
+): SplitRouteState | undefined {
+ const deciding = routes.branches.filter(
+ (branch) => !isNestedCatchAll(branch)
+ );
+
+ return decodeAmong(deciding, segments);
}
function isNonemptyBranch(value: unknown): value is { matches: unknown[] } {
@@ -378,6 +441,17 @@ export function leafNode<TComponent>(
return branch[branch.length - 1]!;
}
+/** The first route with a path; a pane's search carries over while it stays the same. */
+export function searchRootId(
+ routes: SplitRoutesManifest,
+ route: SplitRouteState
+): string {
+ const branch = resolveBranch(routes, route);
+ const index = branch.findIndex((node) => !isLayoutRoute(node));
+
+ return route.matches[Math.max(index, 0)]!.id;
+}
+
export function defaultRoute(routes: SplitRoutesManifest): SplitRouteState {
const route = routes.defaultRoute();
assertRouteState(routes, route);
diff --git a/apps/web/src/lib/split-router/next/routes/path.ts b/apps/web/src/lib/split-router/next/routes/path.ts
index 6ef48388e4..3565c183ef 100644
--- a/apps/web/src/lib/split-router/next/routes/path.ts
+++ b/apps/web/src/lib/split-router/next/routes/path.ts
@@ -148,11 +148,12 @@ function expandOptionals(tokens: readonly PathToken[]): PathToken[][] {
return variants;
}
+/** A route without a path, or with `''`, consumes no segments. */
export function compileRoutePattern(options: {
- path: string;
+ path?: string;
aliases?: readonly string[];
}): RoutePattern {
- const canonical = tokenize(options.path);
+ const canonical = options.path ? tokenize(options.path) : [];
const aliases = (options.aliases ?? []).map(tokenize);
const alternatives = [canonical, ...aliases].flatMap(expandOptionals);
diff --git a/apps/web/src/lib/split-router/next/routes/queries.ts b/apps/web/src/lib/split-router/next/routes/queries.ts
index de8ac59dfb..1e59edd2e0 100644
--- a/apps/web/src/lib/split-router/next/routes/queries.ts
+++ b/apps/web/src/lib/split-router/next/routes/queries.ts
@@ -11,13 +11,13 @@ import type {
} from './types';
/** Params of the first `depth` matches, with descendants overriding ancestors. */
-export function mergedParams(
- route: SplitRouteState,
- depth = route.matches.length
-): SplitRouteParams {
- const params = route.matches.slice(0, depth).map((match) => match.params);
+export function routeParams<
+ TParams extends SplitRouteParams = SplitRouteParams,
+>(route: SplitRouteState | undefined, depth = route?.matches.length): TParams {
+ const matches = route?.matches.slice(0, depth) ?? [];
+ const params = matches.map((match) => match.params);
- return Object.assign({}, ...params);
+ return Object.assign({}, ...params) as TParams;
}
function claimKey(claim: SplitRouteClaim): string {
@@ -38,7 +38,7 @@ export function claimOf(
route: SplitRouteState
): string | undefined {
const branch = resolveBranch(routes, route);
- const params = mergedParams(route);
+ const params = routeParams(route);
for (let index = branch.length - 1; index >= 0; index -= 1) {
const claim = branch[index]!.definition.claim?.(params);
@@ -133,10 +133,23 @@ function definitionExternalKeys(
): readonly string[] {
const externalSearch = definition.externalSearch;
if (typeof externalSearch === 'function') return externalSearch(entry);
+ if (externalSearch === '*') return [];
return externalSearch ?? [];
}
+/** Whether a shown route keeps every unprefixed query key, as `externalSearch: '*'` asks. */
+export function keepsAllExternalSearch(
+ routes: SplitRoutesManifest,
+ entries: readonly Entry[]
+): boolean {
+ return entries.some((entry) => {
+ const definitions = leafNode(routes, entry.location.route).externalSearch;
+
+ return definitions.some(({ externalSearch }) => externalSearch === '*');
+ });
+}
+
function appendMissing(keys: string[], additions: readonly string[]): void {
for (const key of additions) {
if (!keys.includes(key)) keys.push(key);
diff --git a/apps/web/src/lib/split-router/next/routes/search-params.ts b/apps/web/src/lib/split-router/next/routes/search-params.ts
index a820ff3dd5..625bffa340 100644
--- a/apps/web/src/lib/split-router/next/routes/search-params.ts
+++ b/apps/web/src/lib/split-router/next/routes/search-params.ts
@@ -36,6 +36,10 @@ export type SearchParamsCodec<T> = {
validate(value: unknown): ValidationResult<T>;
};
+export function takeLast<T>(values: readonly T[] | undefined): T | undefined {
+ return values?.at(-1);
+}
+
function deserializeField(
values: readonly string[],
fallback: unknown
diff --git a/apps/web/src/lib/split-router/next/routes/targets.ts b/apps/web/src/lib/split-router/next/routes/targets.ts
index 8525bc1ed2..d58149905c 100644
--- a/apps/web/src/lib/split-router/next/routes/targets.ts
+++ b/apps/web/src/lib/split-router/next/routes/targets.ts
@@ -4,6 +4,7 @@ import {
decodePane,
formatPane,
type SplitRoutesManifest,
+ searchRootId,
} from './manifest';
import { decodeSegment } from './path';
import { filterRouteSearch } from './queries';
@@ -143,6 +144,24 @@ function resolveRoute(
return canonicalTarget(routes, matches);
}
+/** A location resolved elsewhere, checked against the route table; it carries no search over. */
+function resolveLocation(
+ routes: SplitRoutesManifest,
+ location: SplitLocation
+): ResolvedRoute | undefined {
+ let route: SplitRouteState | undefined;
+
+ try {
+ route = canonicalRoute(routes, location.route);
+ } catch {
+ route = undefined;
+ }
+
+ if (!route) return;
+
+ return { route, search: location.search ?? {} };
+}
+
function resolveDestination(
routes: SplitRoutesManifest,
current: SplitLocation | undefined,
@@ -150,19 +169,23 @@ function resolveDestination(
depth: number | undefined
): ResolvedRoute | undefined {
if (typeof to === 'string') return resolvePath(routes, current, to, depth);
+ if ('location' in to) return resolveLocation(routes, to.location);
if (!('route' in to)) return;
return resolveRoute(routes, current, to);
}
function carriedSearch(
+ routes: SplitRoutesManifest,
current: SplitLocation | undefined,
resolved: ResolvedRoute
): SplitSearchState | undefined {
if (resolved.search !== undefined) return resolved.search;
if (!current) return;
- const sameRoot = current.route.matches[0].id === resolved.route.matches[0].id;
+ const sameRoot =
+ searchRootId(routes, current.route) ===
+ searchRootId(routes, resolved.route);
if (!sameRoot) return;
return current.search;
@@ -181,7 +204,7 @@ export function resolveTarget(
const resolved = resolveDestination(routes, current, to, options.depth);
if (!resolved) return;
- const search = carriedSearch(current, resolved);
+ const search = carriedSearch(routes, current, resolved);
const start = locationOf(resolved.route, search);
const updated = updateSearchState(start, options.search);
const owned = filterRouteSearch(routes, updated.route, updated.search);
diff --git a/apps/web/src/lib/split-router/next/routes/types.ts b/apps/web/src/lib/split-router/next/routes/types.ts
index d222b4ab1b..50d2897a19 100644
--- a/apps/web/src/lib/split-router/next/routes/types.ts
+++ b/apps/web/src/lib/split-router/next/routes/types.ts
@@ -51,6 +51,11 @@ export type SplitRouteClaim = {
id: string;
};
+export type SplitReference = {
+ type: string;
+ id: string;
+};
+
/** Route metadata. Hosts extend this interface through declaration merging. */
export interface SplitRouteInfo {
readonly [key: string]: unknown;
@@ -98,7 +103,11 @@ export type SplitRouteDefinition<
>,
> = {
id: string;
- path: string;
+ /**
+ * Segments this route consumes. `''` matches an empty pane. Without a path
+ * the route only groups its `children`, which match where it would.
+ */
+ path?: string;
aliases?: readonly string[];
component?: TComponent;
children?: readonly SplitRouteDefinition<TComponent>[];
@@ -112,14 +121,21 @@ export type SplitRouteDefinition<
StandardSchemaV1.InferOutput<TParamsSchema>,
SplitRouteClaim | undefined
>;
+ /** The entity this route shows, for hosts that link to it; the router never reads it. */
+ toReference?: SplitRouteParamCallback<
+ StandardSchemaV1.InferOutput<TParamsSchema>,
+ SplitReference | undefined
+ >;
/**
- * Pane search namespaces this route adds. Leaving it undefined adds no
- * restriction; a root route without `search` owns every namespace.
+ * Pane search namespaces this route adds, or `'*'` for every namespace.
+ * Leaving it undefined adds no restriction; a root route without `search`
+ * owns every namespace.
*/
- search?: readonly string[];
- /** Unprefixed query keys kept in the URL while this route is shown. */
+ search?: readonly string[] | '*';
+ /** Unprefixed query keys kept in the URL while this route is shown; `'*'` keeps them all. */
externalSearch?:
| readonly string[]
+ | '*'
| ((entry: Readonly<Entry>) => readonly string[]);
remountKey?: {
bivarianceHack(
@@ -137,6 +153,11 @@ export type SplitRouteDefinition<
/** Static route declarations. Do not mutate them during a router's lifetime. */
export type SplitRoutes<TComponent = unknown> = {
definitions: readonly SplitRouteDefinition<TComponent>[];
+ /**
+ * What an empty URL shows, and where URLs nothing handles redirect. A
+ * top-level route with a splat path handles every other first pane, as a
+ * 404 page would.
+ */
defaultRoute: () => SplitRouteState;
globalSearch?: readonly string[];
};
@@ -219,13 +240,17 @@ export type InferSplitRouteParams<TRoute> = TRoute extends {
: undefined
>
>
- : SplitRouteParams;
+ : TRoute extends { path?: undefined }
+ ? {}
+ : SplitRouteParams;
type LocalNavigationParams<TRoute> = TRoute extends { params: StandardSchemaV1 }
? InferSplitRouteParams<TRoute>
: TRoute extends { path: infer TPath extends string }
? MergeRouteParams<{}, PathParams<TPath>>
- : SplitRouteParams;
+ : TRoute extends { path?: undefined }
+ ? {}
+ : SplitRouteParams;
// Type-only ancestry. Declaration helpers never add properties to supplied objects.
declare const branchParams: unique symbol;
@@ -373,7 +398,8 @@ export type SplitRouteNavigationTarget<
export type SplitNavigationTarget =
| string
- | { route: { id: string }; params?: unknown };
+ | { route: { id: string }; params?: unknown }
+ | { location: SplitLocation };
export type SplitRouterStateUpdate<TInput = unknown, TOutput = TInput> =
| TInput
diff --git a/apps/web/src/lib/split-router/next/solid/context.tsx b/apps/web/src/lib/split-router/next/solid/context.tsx
index 2f3fc34d42..c929345cd9 100644
--- a/apps/web/src/lib/split-router/next/solid/context.tsx
+++ b/apps/web/src/lib/split-router/next/solid/context.tsx
@@ -19,6 +19,11 @@ export function SplitRouterProvider(
);
}
+/** The router, or undefined outside a `<SplitRouterProvider>`. */
+export function useOptionalSplitRouter(): SplitRouter | undefined {
+ return useContext(SplitRouterContext);
+}
+
export function useSplitRouter(): SplitRouter {
const router = useContext(SplitRouterContext);
diff --git a/apps/web/src/lib/split-router/next/solid/hooks.ts b/apps/web/src/lib/split-router/next/solid/hooks.ts
index 872a91ce72..c9ab2aed58 100644
--- a/apps/web/src/lib/split-router/next/solid/hooks.ts
+++ b/apps/web/src/lib/split-router/next/solid/hooks.ts
@@ -1,13 +1,19 @@
import deepEqual from 'fast-deep-equal';
import { type Accessor, createMemo, untrack, useContext } from 'solid-js';
+import type { PaneSnapshot } from '../panes/types';
import type { PendingNavigation } from '../router/runner';
import type {
NavigationResult,
RouteMatchInfo,
SplitNavigateOptions,
} from '../router/types';
-import { getRouteEntryState, mergedParams } from '../routes/queries';
+import {
+ getRouteEntryState,
+ ownsNamespace,
+ routeParams,
+} from '../routes/queries';
import type {
+ Entry,
InferSplitRouteBranchParams,
InferSplitRouteParams,
InferSplitRouteState,
@@ -22,13 +28,24 @@ import type {
SplitRouteState,
} from '../routes/types';
import type { MaybePromise } from '../utils';
-import { PaneContext, usePaneContext, useSplitRouter } from './context';
+import {
+ PaneContext,
+ useOptionalSplitRouter,
+ usePaneContext,
+ useSplitRouter,
+} from './context';
import { createMemoRecord } from './memo-record';
+type NewPaneOption = {
+ /** Open the destination in a new pane, placed by the pane policy, instead of this one. */
+ newPane?: boolean;
+};
+
export type SplitRouteNavigateOptions<TRoute> = Omit<
SplitNavigateOptions,
'state' | 'depth'
> &
+ NewPaneOption &
([InferSplitRouteStateInput<TRoute>] extends [never]
? { state?: never }
: {
@@ -45,7 +62,7 @@ export type SplitNavigate = {
): MaybePromise<NavigationResult>;
(
to: string | number,
- options?: Omit<SplitNavigateOptions, 'depth'>
+ options?: Omit<SplitNavigateOptions, 'depth'> & NewPaneOption
): MaybePromise<NavigationResult>;
};
@@ -76,7 +93,7 @@ export function useParams(through?: { id: string }): SplitRouteParams {
const route = scope.entry()?.location.route;
if (!route) return {};
- return mergedParams(route, depthThrough(route, through));
+ return routeParams(route, depthThrough(route, through));
});
}
@@ -121,8 +138,19 @@ export function useNavigate(): SplitNavigate {
const navigate = (
to: SplitNavigationTarget | number,
- options: SplitNavigateOptions = {}
- ) => router.navigate(scope.pane(), to, { ...options, depth: scope.depth() });
+ options: SplitNavigateOptions & NewPaneOption = {}
+ ) => {
+ const { newPane, ...rest } = options;
+ const navigateOptions = { ...rest, depth: scope.depth() };
+
+ if (newPane && typeof to !== 'number') {
+ const target = { newPane: true as const, source: scope.pane() };
+
+ return router.open(to, target, navigateOptions);
+ }
+
+ return router.navigate(scope.pane(), to, navigateOptions);
+ };
return navigate as SplitNavigate;
}
@@ -168,3 +196,25 @@ export function useArrival(): Accessor<PaneArrival> {
return createMemo(() => router.arrival(scope.pane()));
}
+
+/** The pane's entries and its position in them. */
+export function usePaneHistory(): Accessor<PaneSnapshot<Entry> | undefined> {
+ const router = useSplitRouter();
+ const scope = usePaneContext();
+
+ return () => router.history(scope.pane());
+}
+
+/** Whether the route this pane shows owns `namespace`; false outside a pane. */
+export function useOwnsSearchNamespace(namespace: string): Accessor<boolean> {
+ const router = useOptionalSplitRouter();
+ const scope = useContext(PaneContext);
+ if (!router || !scope) return () => false;
+
+ return () => {
+ const entry = scope.entry();
+ if (!entry) return false;
+
+ return ownsNamespace(router.routes, entry.location.route, namespace);
+ };
+}
diff --git a/apps/web/src/lib/split-router/next/solid/outlet.tsx b/apps/web/src/lib/split-router/next/solid/outlet.tsx
index 3a3d4db1a2..75da94a1b4 100644
--- a/apps/web/src/lib/split-router/next/solid/outlet.tsx
+++ b/apps/web/src/lib/split-router/next/solid/outlet.tsx
@@ -1,4 +1,10 @@
-import { type Component, createMemo, type JSX, Show } from 'solid-js';
+import {
+ type Component,
+ createMemo,
+ type JSX,
+ Show,
+ useContext,
+} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { type OutletMatch, outletAt } from '../routes/queries';
import type { PaneId } from '../routes/types';
@@ -10,17 +16,26 @@ import {
} from './context';
import { PaneScope } from './pane-scope';
+type OutletFallback = JSX.Element | (() => JSX.Element);
+
export type OutletProps = {
- /** Shorthand for wrapping this outlet in `<PaneScope pane={…}>`. */
+ /** Shorthand for wrapping this outlet in `<SplitRouter.Scope pane={…}>`. */
pane?: PaneId;
/** Shown when nothing below this point in the branch has a component. */
- fallback?: JSX.Element;
+ fallback?: OutletFallback;
};
-function RouteOutlet(props: { fallback?: JSX.Element }) {
+function RouteOutlet(props: { fallback?: OutletFallback }) {
const router = useSplitRouter();
const parent = usePaneContext();
+ const fallback = () => {
+ const { fallback } = props;
+ if (typeof fallback === 'function') return fallback();
+
+ return fallback;
+ };
+
const match = createMemo<OutletMatch | undefined>(
() => outletAt(router.routes, parent.entry(), parent.depth()),
undefined,
@@ -34,7 +49,7 @@ function RouteOutlet(props: { fallback?: JSX.Element }) {
};
return (
- <Show keyed when={match()} fallback={props.fallback}>
+ <Show keyed when={match()} fallback={fallback()}>
{(resolved) => (
<PaneContext.Provider value={context}>
<Dynamic component={resolved.component as Component} />
@@ -47,14 +62,22 @@ function RouteOutlet(props: { fallback?: JSX.Element }) {
/**
* Renders the next route component in the enclosing pane's branch. Its view
* stays mounted while its route id and `remountKey` are unchanged; params
- * update in place.
+ * update in place. Outside any pane it renders the first pane's top-level
+ * route, whose component decides how the other panes render.
*/
export function Outlet(props: OutletProps) {
+ const router = useSplitRouter();
+ const enclosing = useContext(PaneContext);
+
+ const pane = () => {
+ if (props.pane) return props.pane;
+ if (enclosing) return;
+
+ return router.panes()[0];
+ };
+
return (
- <Show
- when={props.pane}
- fallback={<RouteOutlet fallback={props.fallback} />}
- >
+ <Show when={pane()} fallback={<RouteOutlet fallback={props.fallback} />}>
{(pane) => (
<PaneScope pane={pane()}>
<RouteOutlet fallback={props.fallback} />
diff --git a/apps/web/src/lib/split-router/next/solid/pane-scope.tsx b/apps/web/src/lib/split-router/next/solid/pane-scope.tsx
index 5ad68ca3cd..191dc59a1c 100644
--- a/apps/web/src/lib/split-router/next/solid/pane-scope.tsx
+++ b/apps/web/src/lib/split-router/next/solid/pane-scope.tsx
@@ -1,18 +1,21 @@
-import type { ParentProps } from 'solid-js';
+import { type ParentProps, useContext } from 'solid-js';
import type { PaneId } from '../routes/types';
import { PaneContext, type PaneContextValue, useSplitRouter } from './context';
/**
* Makes `pane` the one that nested outlets render and hooks act on. A panel
* wraps its chrome and its `<Outlet />` in one so both can use the hooks.
+ * Inside a route, the pane continues below that route's level, so a layout
+ * route can render each of its panes; at the root it starts at the top.
*/
export function PaneScope(props: ParentProps<{ pane: PaneId }>) {
const router = useSplitRouter();
+ const enclosing = useContext(PaneContext);
const context: PaneContextValue = {
pane: () => props.pane,
entry: () => router.entry(props.pane),
- depth: () => 0,
+ depth: () => enclosing?.depth() ?? 0,
};
return (
diff --git a/apps/web/src/lib/split-router/next/solid/route.tsx b/apps/web/src/lib/split-router/next/solid/route.tsx
new file mode 100644
index 0000000000..6b549abeee
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/route.tsx
@@ -0,0 +1,72 @@
+import { type Component, type JSX, untrack } from 'solid-js';
+import type { SplitRouteDefinition } from '../routes/types';
+
+export type RouteProps = {
+ /** Its children and component come from this element, not the definition. */
+ definition: SplitRouteDefinition & {
+ children?: undefined;
+ component?: undefined;
+ };
+ component?: Component<object>;
+ children?: JSX.Element;
+};
+
+const routeElement = Symbol('SplitRouter.Route');
+
+type RouteElement = { [routeElement]: RouteProps };
+
+/** Declares a route and the component it renders; it renders nothing itself. */
+export function Route(props: RouteProps): JSX.Element {
+ const element: RouteElement = { [routeElement]: props };
+
+ return element as unknown as JSX.Element;
+}
+
+function isRouteElement(value: unknown): value is RouteElement {
+ return typeof value === 'object' && value !== null && routeElement in value;
+}
+
+/** Flattens children as Solid does, calling accessors; booleans and nullish values drop out. */
+function resolveChildren(children: unknown): unknown[] {
+ if (typeof children === 'function' && children.length === 0) {
+ return resolveChildren(children());
+ }
+ if (Array.isArray(children)) return children.flatMap(resolveChildren);
+ if (children === undefined || children === null) return [];
+ if (typeof children === 'boolean') return [];
+
+ return [children];
+}
+
+function definitionOf(props: RouteProps): SplitRouteDefinition {
+ const { definition, component } = props;
+
+ if (definition.children || definition.component) {
+ throw new Error(
+ `Split route "${definition.id}" is declared with <SplitRouter.Route>, so its definition must not set children or component`
+ );
+ }
+
+ const children = routeDefinitions(props.children);
+
+ return {
+ ...definition,
+ ...(component ? { component } : {}),
+ ...(children.length ? { children } : {}),
+ };
+}
+
+/** The definitions a tree of `<SplitRouter.Route>` elements declares, read once. */
+export function routeDefinitions(children: unknown): SplitRouteDefinition[] {
+ return untrack(() =>
+ resolveChildren(children).map((child) => {
+ if (!isRouteElement(child)) {
+ throw new Error(
+ 'Children of <SplitRouter.Router> and <SplitRouter.Route> must be <SplitRouter.Route> elements'
+ );
+ }
+
+ return definitionOf(child[routeElement]);
+ })
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/solid/router.tsx b/apps/web/src/lib/split-router/next/solid/router.tsx
new file mode 100644
index 0000000000..703839907e
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/router.tsx
@@ -0,0 +1,43 @@
+import { type JSX, onCleanup, untrack } from 'solid-js';
+import { createSplitRouter } from '../router/create-router';
+import type { SplitRouterOptions } from '../router/types';
+import type { SplitRoutes } from '../routes/types';
+import { SplitRouterProvider } from './context';
+import { Outlet } from './outlet';
+import { routeDefinitions } from './route';
+
+export type RouterProps = Omit<SplitRouterOptions, 'routes'> &
+ Omit<SplitRoutes, 'definitions'> & {
+ /** `<SplitRouter.Route>` elements; they are read once, when the router is created. */
+ children: JSX.Element;
+ };
+
+/**
+ * Creates a router from its `<SplitRouter.Route>` children and renders the
+ * first pane's top-level route. To create the router yourself, pass it to
+ * `<SplitRouter.Root>` instead.
+ */
+export function Router(props: RouterProps): JSX.Element {
+ const router = untrack(() =>
+ createSplitRouter({
+ routes: {
+ definitions: routeDefinitions(props.children),
+ globalSearch: props.globalSearch,
+ defaultRoute: props.defaultRoute,
+ },
+ history: props.history,
+ paneStore: props.paneStore,
+ policy: props.policy,
+ middleware: props.middleware,
+ preloadBudgetMs: props.preloadBudgetMs,
+ createPaneId: props.createPaneId,
+ })
+ );
+ onCleanup(router.dispose);
+
+ return (
+ <SplitRouterProvider router={router}>
+ <Outlet />
+ </SplitRouterProvider>
+ );
+}
diff --git a/apps/web/src/lib/split-router/next/solid/split-router.tsx b/apps/web/src/lib/split-router/next/solid/split-router.tsx
new file mode 100644
index 0000000000..c45e99b3ed
--- /dev/null
+++ b/apps/web/src/lib/split-router/next/solid/split-router.tsx
@@ -0,0 +1,21 @@
+import type { SplitRouter as RouterInstance } from '../router/create-router';
+import { SplitRouterProvider } from './context';
+import { Outlet } from './outlet';
+import { PaneScope } from './pane-scope';
+import { Route } from './route';
+import { Router } from './router';
+
+export type SplitRouter = RouterInstance;
+
+/**
+ * `Router` creates a router from its `Route` children; `Root` provides one
+ * created with `createSplitRouter`. `Scope` binds a subtree to a pane, and
+ * `Outlet` renders the pane's route.
+ */
+export const SplitRouter = {
+ Router,
+ Route,
+ Root: SplitRouterProvider,
+ Scope: PaneScope,
+ Outlet,
+};
diff --git a/apps/web/src/lib/split-router/next/tests/fixtures.ts b/apps/web/src/lib/split-router/next/tests/fixtures.ts
index 702d0f99dc..b01ea402e3 100644
--- a/apps/web/src/lib/split-router/next/tests/fixtures.ts
+++ b/apps/web/src/lib/split-router/next/tests/fixtures.ts
@@ -60,15 +60,41 @@ export const notFoundRoute = defineRoute({
});
/** Declared out of order on purpose: matching must rank by specificity. */
+export const appRoute = defineRoute({
+ id: 'app',
+ children: [notFoundRoute, blockRoute, homeRoute, mailRoute, driveRoute],
+});
+
+export const loginRoute = defineRoute({
+ id: 'login',
+ path: 'login',
+ externalSearch: '*',
+});
+
export const appRoutes = defineRoutes({
- definitions: [notFoundRoute, blockRoute, homeRoute, mailRoute, driveRoute],
+ definitions: [loginRoute, appRoute],
globalSearch: ['referral_code'],
- defaultRoute: () => ({ matches: [{ id: 'home', params: {} }] }),
+ defaultRoute: () => ({
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'home', params: {} },
+ ],
+ }),
});
-export const homeLocation: SplitLocation = {
- route: { matches: [{ id: 'home', params: {} }] },
-};
+/** A location under the app route, whose children are the pane routes. */
+export function appLocation(id: string, params = {}): SplitLocation {
+ return {
+ route: {
+ matches: [
+ { id: 'app', params: {} },
+ { id, params },
+ ],
+ },
+ };
+}
+
+export const homeLocation = appLocation('home');
/**
* Opens new panes after their source, or in the source once `maxPanes` are
diff --git a/apps/web/src/lib/split-router/next/tests/history.test.ts b/apps/web/src/lib/split-router/next/tests/history.test.ts
index 05e67c8172..1d598d4aec 100644
--- a/apps/web/src/lib/split-router/next/tests/history.test.ts
+++ b/apps/web/src/lib/split-router/next/tests/history.test.ts
@@ -150,7 +150,7 @@ describe('browser history', () => {
history.read()
);
expect(
- decoded.panes.map((pane) => pane.entry.location.route.matches[0].params)
+ decoded.panes.map((pane) => pane.entry.location.route.matches[1]!.params)
).toEqual([
{ type: 'md', id: 'a' },
{ type: 'pdf', id: 'b' },
@@ -171,7 +171,6 @@ describe('Solid Router history', () => {
navigate: router.navigate,
beforeLeave: router.beforeLeave,
base: '/app',
- owns: () => true,
...options,
});
@@ -249,18 +248,16 @@ describe('Solid Router history', () => {
dispose();
});
- it('ignores locations outside the split panes', () => {
+ it('reports every location under its base and ignores the rest', () => {
const router = createFakeSolidRouter('/app/home');
const listener = vi.fn();
const dispose = createRoot((dispose) => {
- adapterFor(router, { owns: (path) => path !== '/login' }).subscribe(
- listener
- );
+ adapterFor(router).subscribe(listener);
return dispose;
});
- router.show('/app/login', undefined);
+ router.show('/elsewhere', undefined);
expect(listener).not.toHaveBeenCalled();
- router.show('/app/mail', undefined);
+ router.show('/app/login', undefined);
expect(listener).toHaveBeenCalledOnce();
dispose();
});
@@ -274,12 +271,10 @@ describe('Solid Router history', () => {
];
const seen: (ExternalLocation | undefined)[] = [];
const dispose = createRoot((dispose) => {
- adapterFor(router, { owns: (path) => path !== '/login' }).intercept?.(
- (location) => {
- seen.push(location);
- return verdicts.shift()!;
- }
- );
+ adapterFor(router).intercept?.((location) => {
+ seen.push(location);
+ return verdicts.shift()!;
+ });
return dispose;
});
@@ -287,7 +282,7 @@ describe('Solid Router history', () => {
expect(blocked.preventDefault).toHaveBeenCalled();
expect(seen[0]).toEqual({ path: '/mail/t1', search: '', hash: '' });
- const deferred = router.leave('/app/login');
+ const deferred = router.leave('/elsewhere');
expect(seen[1]).toBeUndefined();
expect(deferred.preventDefault).toHaveBeenCalled();
await Promise.resolve();
diff --git a/apps/web/src/lib/split-router/next/tests/navigation.test.ts b/apps/web/src/lib/split-router/next/tests/navigation.test.ts
index bb951441bd..1dcbc47aa7 100644
--- a/apps/web/src/lib/split-router/next/tests/navigation.test.ts
+++ b/apps/web/src/lib/split-router/next/tests/navigation.test.ts
@@ -292,9 +292,10 @@ describe('middleware', () => {
});
it('follows redirects and keeps the entry identity', () => {
- const middleware: SplitRouterMiddleware = ({ to, redirect }) =>
- to.location.route.matches[0].id === 'block'
- ? redirect('/mail/t1')
+ const middleware: SplitRouterMiddleware = (context) =>
+ context.to.location.route.matches.at(-1)?.id === 'block' &&
+ context.routes.byId.has('mail-thread')
+ ? context.redirect('/mail/t1')
: undefined;
const result = runMiddleware(
routes,
@@ -303,7 +304,11 @@ describe('middleware', () => {
);
expect(result).toMatchObject({
id: 'e1',
- location: { route: { matches: [{ id: 'mail' }, { id: 'mail-thread' }] } },
+ location: {
+ route: {
+ matches: [{ id: 'app' }, { id: 'mail' }, { id: 'mail-thread' }],
+ },
+ },
});
});
@@ -326,7 +331,7 @@ describe('middleware', () => {
navigatingTo(entry('e1', '/home'))
);
await expect(result).resolves.toMatchObject({
- location: { route: { matches: [{ id: 'drive' }] } },
+ location: { route: { matches: [{ id: 'app' }, { id: 'drive' }] } },
});
});
diff --git a/apps/web/src/lib/split-router/next/tests/router.test.ts b/apps/web/src/lib/split-router/next/tests/router.test.ts
index 72be178686..3b859fcadd 100644
--- a/apps/web/src/lib/split-router/next/tests/router.test.ts
+++ b/apps/web/src/lib/split-router/next/tests/router.test.ts
@@ -11,12 +11,19 @@ import { defineRoute } from '../routes/define';
import type {
Entry,
PaneId,
- SplitLocation,
+ SplitRouteDefinition,
SplitRoutes,
} from '../routes/types';
import { isPromise } from '../utils';
import { createFakeSolidRouter } from './fake-solid-router';
-import { appRoutes, createTestPolicy, homeLocation } from './fixtures';
+import {
+ appLocation,
+ appRoute,
+ appRoutes,
+ createTestPolicy,
+ homeLocation,
+ loginRoute,
+} from './fixtures';
function setup(
url: string,
@@ -62,7 +69,6 @@ function setupSolid(url: string, ahead: readonly string[] = []) {
location: solid.location,
navigate: solid.navigate,
base: '/app',
- owns: () => true,
beforeLeave: solid.beforeLeave,
landedPath: solid.landed,
}),
@@ -111,10 +117,20 @@ function slowRevertHistory(url: string) {
return { history, adapter, landAll };
}
+/** The level of a pane's first route, below the app route. */
+const PANE_ROUTE_LEVEL = 1;
+/** The pane route ids below the app route. */
const routeIds = (entry: Entry | undefined) =>
- entry?.location.route.matches.map((match) => match.id);
-const location = (id: string, params = {}): SplitLocation => ({
- route: { matches: [{ id, params }] },
+ entry?.location.route.matches
+ .map((match) => match.id)
+ .filter((id) => id !== 'app');
+const location = appLocation;
+const withPaneRoutes = (...children: SplitRouteDefinition[]): SplitRoutes => ({
+ ...appRoutes,
+ definitions: [
+ loginRoute,
+ { ...appRoute, children: [...appRoute.children, ...children] },
+ ],
});
const never = () => new Promise<boolean>(() => {});
@@ -157,6 +173,45 @@ describe('split router', () => {
]);
});
+ it('replaces a URL whose panes sit under different top-level routes with the default route', () => {
+ const { router, history } = track(setup('/login/~/home'));
+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([
+ ['home'],
+ ]);
+ expect(history.entries().map((entry) => entry.path)).toEqual(['/home']);
+ });
+
+ it('turns a pane navigation outside the shared top-level route into a whole-window one, and Back rebuilds the panes', () => {
+ const { router, history, pane } = track(setup('/home/~/mail'));
+ router.navigate(pane(1), '/login');
+ expect(
+ router.panes().map((id) => router.entry(id)?.location.route.matches)
+ ).toEqual([[{ id: 'login', params: {} }]]);
+ expect(history.entries().map((entry) => entry.path)).toEqual([
+ '/home/~/mail',
+ '/login',
+ ]);
+
+ history.back();
+ expect(router.panes().map((id) => routeIds(router.entry(id)))).toEqual([
+ ['home'],
+ ['mail'],
+ ]);
+ });
+
+ it('skips entries under another top-level route on pane Back while other panes share the app route', () => {
+ const { router, pane } = track(setup('/home'));
+ router.navigate(pane(0), '/login');
+ router.navigate(pane(0), '/mail');
+ router.open('/drive', { newPane: true, source: pane(0) });
+ expect(router.panes()).toHaveLength(2);
+
+ expect(router.canGo(pane(0), -1)).toBe(true);
+ router.navigate(pane(0), -1);
+ expect(routeIds(router.entry(pane(0)))).toEqual(['home']);
+ expect(router.canGo(pane(0), -1)).toBe(false);
+ });
+
it('pane back replaces the browser entry and records how the pane arrived', () => {
const { router, history, pane } = track(setup('/home'));
router.navigate(pane(0), '/mail');
@@ -185,7 +240,7 @@ describe('split router', () => {
it('a leave guard can refuse browser back, and the URL is put back', () => {
const { router, history, pane } = track(setup('/home'));
router.navigate(pane(0), '/mail');
- router.registerGuard(pane(0), 0, () => false);
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, () => false);
history.back();
expect(routeIds(router.entry(pane(0)))).toEqual(['mail']);
expect(history.index()).toBe(1);
@@ -200,7 +255,7 @@ describe('split router', () => {
router.navigate(pane, '/mail');
vi.runAllTimers();
const mail = router.entry(pane);
- router.registerGuard(pane, 0, () => false);
+ router.registerGuard(pane, PANE_ROUTE_LEVEL, () => false);
solid.traverse(-1);
await new Promise<void>((resolve) => queueMicrotask(resolve));
@@ -215,7 +270,7 @@ describe('split router', () => {
let allow: (value: boolean) => void = () => {};
router.registerGuard(
pane(0),
- 0,
+ PANE_ROUTE_LEVEL,
() =>
new Promise<boolean>((resolve) => {
allow = resolve;
@@ -254,7 +309,7 @@ describe('split router', () => {
it('a superseded navigation settles even when its guard never does', async () => {
const { router, pane } = track(setup('/home'));
- const unregister = router.registerGuard(pane(0), 0, never);
+ const unregister = router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);
const first = router.navigate(pane(0), '/mail');
unregister();
const second = router.navigate(pane(0), '/drive');
@@ -267,7 +322,7 @@ describe('split router', () => {
const answers: ((allowed: boolean) => void)[] = [];
router.registerGuard(
pane(0),
- 0,
+ PANE_ROUTE_LEVEL,
() => new Promise<boolean>((resolve) => answers.push(resolve))
);
const first = router.navigate(pane(0), '/mail');
@@ -283,7 +338,7 @@ describe('split router', () => {
const { router, history, pane } = track(setup('/home'));
router.navigate(pane(0), '/mail');
let allow: (allowed: boolean) => void = () => {};
- router.registerGuard(pane(0), 0, ({ cause }) =>
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>
cause === 'external'
? true
: new Promise<boolean>((resolve) => {
@@ -335,7 +390,7 @@ describe('split router', () => {
const pane = router.panes()[0]!;
router.navigate(pane, '/mail');
vi.runAllTimers();
- router.registerGuard(pane, 0, never);
+ router.registerGuard(pane, PANE_ROUTE_LEVEL, never);
solid.traverse(-1);
const rewrite = router.rewriteCurrent(pane, '/drive');
@@ -350,7 +405,7 @@ describe('split router', () => {
const { router, history, pane } = track(setup('/home/~/drive'));
router.navigate(pane(0), '/mail');
let guardSignal: AbortSignal | undefined;
- router.registerGuard(pane(0), 0, ({ signal }) => {
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ signal }) => {
guardSignal = signal;
return never();
});
@@ -378,7 +433,7 @@ describe('split router', () => {
const pane = router.panes()[0]!;
router.navigate(pane, '/mail');
vi.runAllTimers();
- router.registerGuard(pane, 0, ({ cause }) =>
+ router.registerGuard(pane, PANE_ROUTE_LEVEL, ({ cause }) =>
cause === 'external' ? never() : true
);
solid.traverse(-1);
@@ -603,7 +658,7 @@ describe('split router', () => {
)
);
const guard = vi.fn(() => true);
- router.registerGuard('pane-1' as PaneId, 0, guard);
+ router.registerGuard('pane-1' as PaneId, PANE_ROUTE_LEVEL, guard);
expect(router.close('pane-1' as PaneId)).toBe(false);
expect(router.panes()).toEqual(['pane-1', 'pane-2']);
expect(guard).not.toHaveBeenCalled();
@@ -663,7 +718,7 @@ describe('split router', () => {
it('a leave guard can keep a pane open', () => {
const { router } = track(setup('/home/~/mail'));
- router.registerGuard('pane-2' as PaneId, 0, () => false);
+ router.registerGuard('pane-2' as PaneId, PANE_ROUTE_LEVEL, () => false);
expect(router.close('pane-2' as PaneId)).toBe(false);
expect(router.panes()).toHaveLength(2);
});
@@ -686,13 +741,9 @@ describe('split router', () => {
it('commits in the same tick without data preloads and waits for them within a budget', async () => {
const preload = vi.fn(() => new Promise(() => {}));
- const routes: SplitRoutes = {
- ...appRoutes,
- definitions: [
- ...appRoutes.definitions,
- defineRoute({ id: 'slow', path: 'slow', preload }),
- ],
- };
+ const routes = withPaneRoutes(
+ defineRoute({ id: 'slow', path: 'slow', preload })
+ );
const { router, pane } = track(
setup('/home', { routes, preloadBudgetMs: 5 })
);
@@ -709,19 +760,15 @@ describe('split router', () => {
it('logs a preload that throws and still navigates', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
- const routes: SplitRoutes = {
- ...appRoutes,
- definitions: [
- ...appRoutes.definitions,
- defineRoute({
- id: 'broken',
- path: 'broken',
- preload: () => {
- throw new Error('boom');
- },
- }),
- ],
- };
+ const routes = withPaneRoutes(
+ defineRoute({
+ id: 'broken',
+ path: 'broken',
+ preload: () => {
+ throw new Error('boom');
+ },
+ })
+ );
const { router, pane } = track(setup('/home', { routes }));
expect(router.navigate(pane(0), '/broken')).toEqual({
status: 'committed',
@@ -766,7 +813,7 @@ describe('split router', () => {
const { router, pane } = track(setup('/home'));
router.navigate(pane(0), '/mail');
router.navigate(pane(0), '/drive');
- router.registerGuard(pane(0), 0, never);
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, never);
const back = router.navigate(pane(0), -1);
expect(routeIds(router.pending(pane(0))?.to)).toEqual(['mail']);
@@ -861,7 +908,7 @@ describe('split router while other work is in flight', () => {
router.navigate(pane(0), '/mail');
router.navigate(pane(0), '/drive');
const answers: ((allowed: boolean) => void)[] = [];
- router.registerGuard(pane(0), 0, ({ cause }) => {
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {
if (cause !== 'external') return true;
return new Promise<boolean>((resolve) => answers.push(resolve));
@@ -882,7 +929,7 @@ describe('split router while other work is in flight', () => {
let leave: (allowed: boolean) => void = () => {};
router.registerGuard(
pane(0),
- 0,
+ PANE_ROUTE_LEVEL,
() =>
new Promise<boolean>((resolve) => {
leave = resolve;
@@ -1015,7 +1062,11 @@ describe('split router while other work is in flight', () => {
setup('/home', {}, createTestPolicy({ closeLast }))
);
router.navigate(pane(0), '/drive');
- router.registerGuard(pane(0), 0, ({ to }) => routeIds(to)?.[0] !== 'home');
+ router.registerGuard(
+ pane(0),
+ PANE_ROUTE_LEVEL,
+ ({ to }) => routeIds(to)?.[0] !== 'home'
+ );
const isHome = (entry: Entry) => routeIds(entry)?.[0] === 'home';
expect(await router.goBackTo(pane(0), isHome)).toBe(false);
@@ -1128,7 +1179,7 @@ describe('split router while other work is in flight', () => {
const { router, pane } = track(setup('/home', { history: adapter }));
router.navigate(pane(0), '/mail');
router.navigate(pane(0), '/drive');
- router.registerGuard(pane(0), 0, ({ cause }) =>
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) =>
cause === 'external' ? never() : true
);
@@ -1150,7 +1201,7 @@ describe('split router while other work is in flight', () => {
router.navigate(pane(0), '/drive');
router.navigate(pane(0), '/md/d1');
let refuse: () => void = () => {};
- router.registerGuard(pane(0), 0, ({ cause }) => {
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {
if (cause !== 'external') return true;
return new Promise<boolean>((resolve) => {
@@ -1185,7 +1236,7 @@ describe('split router while other work is in flight', () => {
const { router, history, pane, paneStore } = track(setup('/home'));
router.navigate(pane(0), '/mail');
let allow: (allowed: boolean) => void = () => {};
- router.registerGuard(pane(0), 0, ({ cause }) => {
+ router.registerGuard(pane(0), PANE_ROUTE_LEVEL, ({ cause }) => {
if (cause !== 'external') return true;
return new Promise<boolean>((resolve) => {
@@ -1274,7 +1325,7 @@ describe('split router while other work is in flight', () => {
const { router, solid } = track(setupSolid('/app/home', ['/settings']));
vi.runAllTimers();
const guard = vi.fn(() => false);
- router.registerGuard(router.panes()[0]!, 0, guard);
+ router.registerGuard(router.panes()[0]!, PANE_ROUTE_LEVEL, guard);
expect(solid.pop(1).defaultPrevented).toBe(true);
expect(guard).toHaveBeenCalledTimes(1);
diff --git a/apps/web/src/lib/split-router/next/tests/routes.test.ts b/apps/web/src/lib/split-router/next/tests/routes.test.ts
index 33024b7994..82d3f9a99c 100644
--- a/apps/web/src/lib/split-router/next/tests/routes.test.ts
+++ b/apps/web/src/lib/split-router/next/tests/routes.test.ts
@@ -26,8 +26,15 @@ import {
} from './fixtures';
const routes = createRoutesManifest(appRoutes);
-const ids = (route: SplitRouteState | undefined) =>
+const matchIds = (route: SplitRouteState | undefined) =>
route?.matches.map((match) => match.id);
+/** The pane route ids below the app route. */
+const ids = (route: SplitRouteState | undefined) =>
+ matchIds(route)?.filter((id) => id !== 'app');
+const decodeUrl = (path: string, search = '') =>
+ decodePanes(routes, { path, search, hash: '' }).panes.map((pane) =>
+ matchIds(pane.entry.location.route)
+ );
const at = (path: string): SplitLocation => ({
route: decodePane(routes, path.split('/').filter(Boolean))!,
});
@@ -47,7 +54,7 @@ describe('route matching', () => {
'drive',
'drive-folder',
]);
- expect(decodePane(routes, ['drive', 'folder', 'f1'])?.matches[1]).toEqual({
+ expect(decodePane(routes, ['drive', 'folder', 'f1'])?.matches[2]).toEqual({
id: 'drive-folder',
params: { folderId: 'f1' },
});
@@ -82,6 +89,27 @@ describe('route matching', () => {
expect(ids(decodePane(nested, ['elsewhere']))).toEqual(['not-found']);
});
+ it('matches a route without a path only through its children', () => {
+ expect(matchIds(decodePane(routes, ['home']))).toEqual(['app', 'home']);
+ expect(decodePane(routes, [])).toBeUndefined();
+ expect(formatPane(routes, decodePane(routes, ['mail', 't1'])!)).toEqual([
+ 'mail',
+ 't1',
+ ]);
+ });
+
+ it('matches an empty pane with an empty path', () => {
+ const withBase = createRoutesManifest({
+ ...appRoutes,
+ definitions: [
+ defineRoute({ id: 'base', path: '' }),
+ ...appRoutes.definitions,
+ ],
+ });
+ expect(matchIds(decodePane(withBase, []))).toEqual(['base']);
+ expect(formatPanePath(withBase, decodePane(withBase, [])!)).toBe('/');
+ });
+
it('expands adjacent optional params into prefixes only', () => {
const pattern = compileRoutePattern({ path: 'a/:b?/:c?' });
expect(pattern.alternatives.map((tokens) => tokens.length)).toEqual([
@@ -106,6 +134,21 @@ describe('route matching', () => {
definitions: [defineRoute({ id: 'bad', path: '*rest/after' })],
})
).toThrow(/catch-all/);
+ expect(() =>
+ createRoutesManifest({ ...appRoutes, definitions: [{ id: 'empty' }] })
+ ).toThrow(/has no path, so it needs children/);
+ expect(() =>
+ createRoutesManifest({
+ ...appRoutes,
+ definitions: [
+ home,
+ defineRoute({
+ id: 'layout',
+ children: [defineRoute({ id: 'nested-home', path: 'home' })],
+ }),
+ ],
+ })
+ ).toThrow(/Duplicate sibling split route path/);
});
});
@@ -139,7 +182,7 @@ describe('route queries', () => {
});
describe('panes codec', () => {
- it('decodes each pane on its own, so one unmatched pane is not found', () => {
+ it('decodes each pane on its own, so an unmatched app pane is not found', () => {
const decoded = decodePanes(routes, {
path: '/mail/t1/~/no/such/place/~/drive',
search: '',
@@ -148,30 +191,35 @@ describe('panes codec', () => {
expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(
[['mail', 'mail-thread'], ['not-found'], ['drive']]
);
- expect(decoded.panes[1]!.entry.location.route.matches[0].params).toEqual({
+ expect(decoded.panes[1]!.entry.location.route.matches[1]!.params).toEqual({
segments: ['no', 'such', 'place'],
});
});
- it('falls back to the default route for a pane only when nothing matches', () => {
- const strict = createRoutesManifest({
+ it('redirects a URL no top-level route handles to the default route', () => {
+ const home = [['app', 'home']];
+ expect(decodeUrl('/no/such/place')).toEqual(home);
+ expect(decodeUrl('/')).toEqual(home);
+ expect(decodeUrl('/login/~/home')).toEqual(home);
+ expect(decodeUrl('/mail/~/login')).toEqual(home);
+ expect(decodeUrl('/login')).toEqual([['login']]);
+ });
+
+ it('shows a top-level catch-all as the 404 page', () => {
+ const withPage = createRoutesManifest({
...appRoutes,
- definitions: [mailRoute, defineRoute({ id: 'home', path: 'home' })],
- });
- const decoded = decodePanes(strict, {
- path: '/mail/t1/~/unknown',
- search: '',
- hash: '',
+ definitions: [
+ ...appRoutes.definitions,
+ defineRoute({ id: 'page-not-found', path: '*path' }),
+ ],
});
- expect(decoded.panes.map((pane) => ids(pane.entry.location.route))).toEqual(
- [['mail', 'mail-thread'], ['home']]
- );
- expect(
- ids(
- decodePanes(strict, { path: '/', search: '', hash: '' }).panes[0]!.entry
- .location.route
- )
- ).toEqual(['home']);
+ const decode = (path: string) =>
+ decodePanes(withPage, { path, search: '', hash: '' }).panes.map((pane) =>
+ matchIds(pane.entry.location.route)
+ );
+ expect(decode('/no/such/place')).toEqual([['page-not-found']]);
+ expect(decode('/home')).toEqual([['app', 'home']]);
+ expect(decode('/no/such/place/~/home')).toEqual([['app', 'home']]);
});
it('reads pane and entry ids back only when the pane count matches', () => {
@@ -250,16 +298,29 @@ describe('panes codec', () => {
).toBe('');
});
+ it('keeps every unprefixed key while a route with externalSearch "*" shows', () => {
+ const login = { id: 'e1', location: at('/login') };
+ const encoded = encodePanes(
+ routes,
+ [{ paneId: 'p1' as PaneId, entry: login }],
+ { path: '/home', search: '?email=a&next=b&s0.drive.sort=name', hash: '' }
+ );
+ expect(encoded.search).toBe('?email=a&next=b');
+ });
+
it('escapes a literal separator value so it round-trips', () => {
const route = canonicalRoute(routes, {
- matches: [{ id: 'block', params: { type: 'md', id: '~' } }],
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'block', params: { type: 'md', id: '~' } },
+ ],
})!;
const path = formatPanePath(routes, route);
expect(path).toBe('/md/%7E');
expect(splitPanePaths(path)).toEqual([['md', '%7E']]);
expect(
decodePanes(routes, { path, search: '', hash: '' }).panes[0]!.entry
- .location.route.matches[0].params
+ .location.route.matches[1]!.params
).toEqual({ type: 'md', id: '~' });
});
});
@@ -272,10 +333,10 @@ describe('target resolution', () => {
it('resolves relative paths against the calling route', () => {
expect(
- ids(resolveTarget(routes, folder, 'md/d1', { depth: 1 })?.route)
+ ids(resolveTarget(routes, folder, 'md/d1', { depth: 2 })?.route)
).toEqual(['drive', 'drive-document']);
expect(
- resolveTarget(routes, folder, '../f2', { depth: 2 })?.route.matches[1]
+ resolveTarget(routes, folder, '../f2', { depth: 3 })?.route.matches[2]
).toEqual({ id: 'drive-folder', params: { folderId: 'f2' } });
expect(ids(resolveTarget(routes, folder, '/mail/t2')?.route)).toEqual([
'mail',
diff --git a/apps/web/src/lib/split-router/next/tests/solid.test.tsx b/apps/web/src/lib/split-router/next/tests/solid.test.tsx
index 4d08f75ff3..e7617db1ea 100644
--- a/apps/web/src/lib/split-router/next/tests/solid.test.tsx
+++ b/apps/web/src/lib/split-router/next/tests/solid.test.tsx
@@ -6,8 +6,13 @@ import { createMemoryHistory, type MemoryHistory } from '../history/memory';
import { createMemoryPaneStore } from '../panes/memory-store';
import { createSplitRouter, type SplitRouter } from '../router/create-router';
import { defineRoute } from '../routes/define';
-import type { PaneId, SplitRoutes } from '../routes/types';
-import { SplitRouterProvider } from '../solid/context';
+import type {
+ Entry,
+ PaneId,
+ SplitRouteState,
+ SplitRoutes,
+} from '../routes/types';
+import { SplitRouterProvider, useSplitRouter } from '../solid/context';
import { createSearchParams } from '../solid/create-search-params';
import {
useCanGo,
@@ -19,6 +24,8 @@ import {
} from '../solid/hooks';
import { Outlet } from '../solid/outlet';
import { PaneScope } from '../solid/pane-scope';
+import { Route } from '../solid/route';
+import { Router } from '../solid/router';
import { useBeforeLeave } from '../solid/use-before-leave';
import { createTestPolicy } from './fixtures';
@@ -128,30 +135,40 @@ function ProbeView() {
);
}
+const paneRoutes = [
+ defineRoute({
+ id: 'drive',
+ path: 'drive',
+ component: DriveView,
+ children: [documentRoute],
+ }),
+ defineRoute({
+ id: 'probe',
+ path: 'probe',
+ search: ['probe', 'other'],
+ component: ProbeView,
+ }),
+ defineRoute({ id: 'home', path: 'home', component: () => <p>home</p> }),
+ defineRoute({ id: 'guarded', path: 'guarded', component: GuardedView }),
+ defineRoute({
+ id: 'list',
+ path: 'list',
+ search: ['list'],
+ component: ListView,
+ }),
+];
+
const routes: SplitRoutes = {
definitions: [
- defineRoute({
- id: 'drive',
- path: 'drive',
- component: DriveView,
- children: [documentRoute],
- }),
- defineRoute({
- id: 'probe',
- path: 'probe',
- search: ['probe', 'other'],
- component: ProbeView,
- }),
- defineRoute({ id: 'home', path: 'home', component: () => <p>home</p> }),
- defineRoute({ id: 'guarded', path: 'guarded', component: GuardedView }),
- defineRoute({
- id: 'list',
- path: 'list',
- search: ['list'],
- component: ListView,
- }),
+ defineRoute({ id: 'login', path: 'login', component: () => <p>login</p> }),
+ defineRoute({ id: 'app', children: paneRoutes }),
],
- defaultRoute: () => ({ matches: [{ id: 'home', params: {} }] }),
+ defaultRoute: () => ({
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'home', params: {} },
+ ],
+ }),
};
function PanelHeader() {
@@ -181,15 +198,16 @@ function Panel(props: { pane: PaneId }) {
);
}
-function renderPanes(
+function renderRouter(
url: string,
- renderPane: (pane: PaneId) => JSX.Element = (pane) => <Outlet pane={pane} />
+ view: (router: SplitRouter) => JSX.Element,
+ routeTable: SplitRoutes = routes
) {
const history: MemoryHistory = createMemoryHistory(url);
let router: SplitRouter | undefined;
render(() => {
const created = createSplitRouter({
- routes,
+ routes: routeTable,
history,
paneStore: createMemoryPaneStore(),
policy: createTestPolicy().policy,
@@ -198,13 +216,22 @@ function renderPanes(
onCleanup(() => created.dispose());
return (
<SplitRouterProvider router={created}>
- <For each={created.panes()}>{renderPane}</For>
+ {view(created)}
</SplitRouterProvider>
);
});
return { history, router: router! };
}
+function renderPanes(
+ url: string,
+ renderPane: (pane: PaneId) => JSX.Element = (pane) => <Outlet pane={pane} />
+) {
+ return renderRouter(url, (router) => (
+ <For each={router.panes()}>{renderPane}</For>
+ ));
+}
+
beforeEach(() => {
counts.drive = 0;
counts.document = 0;
@@ -242,12 +269,12 @@ describe('split router Solid bindings', () => {
));
const pane = router.panes()[0]!;
expect(screen.getByTestId('header').textContent).toBe(
- 'drive/document back:false'
+ 'app/drive/document back:false'
);
expect(screen.getByTestId('document').textContent).toBe('md:d1');
router.navigate(pane, '/home');
- expect(screen.getByTestId('header').textContent).toBe('home back:true');
+ expect(screen.getByTestId('header').textContent).toBe('app/home back:true');
expect(screen.getByText('home')).toBeTruthy();
});
@@ -271,6 +298,53 @@ describe('split router Solid bindings', () => {
expect(router.panes()).toHaveLength(1);
});
+ it('renders the first pane’s top-level route at the root, and a layout route renders each pane below it', async () => {
+ function PaneLayout() {
+ const router = useSplitRouter();
+ return (
+ <For each={router.panes()}>
+ {(pane) => (
+ <section data-testid="pane">
+ <PaneScope pane={pane}>
+ <GuardedChrome />
+ <Outlet />
+ </PaneScope>
+ </section>
+ )}
+ </For>
+ );
+ }
+ const layoutRoutes: SplitRoutes = {
+ ...routes,
+ definitions: [
+ routes.definitions[0]!,
+ defineRoute({ id: 'app', component: PaneLayout, children: paneRoutes }),
+ ],
+ };
+ const { router, history } = renderRouter(
+ '/home/~/drive',
+ () => <Outlet />,
+ layoutRoutes
+ );
+ expect(screen.getAllByTestId('pane')).toHaveLength(2);
+ expect(screen.getByText('home')).toBeTruthy();
+ expect(counts.drive).toBe(1);
+
+ allowLeave = false;
+ const second = router.panes()[1]!;
+ expect(router.navigate(second, '/home')).toMatchObject({
+ status: 'committed',
+ });
+ expect(screen.getAllByText('home')).toHaveLength(2);
+ expect(await router.close(second)).toBe(false);
+
+ allowLeave = true;
+ await router.navigate(router.panes()[0]!, '/login');
+ expect(screen.getByText('login')).toBeTruthy();
+ expect(screen.queryAllByTestId('pane')).toHaveLength(0);
+ expect(history.read().path).toBe('/login');
+ });
+
it('re-runs only the readers of the search field that changed', () => {
let paneRenders = 0;
const { router } = renderPanes('/probe/~/probe', (pane) => {
@@ -317,3 +391,133 @@ describe('split router Solid bindings', () => {
expect(history.read().search).toBe('?s0.list.sort=date');
});
});
+
+describe('<SplitRouter.Router>', () => {
+ const login = defineRoute({ id: 'login', path: 'login' });
+ const app = defineRoute({ id: 'app' });
+ const home = defineRoute({ id: 'home', path: 'home' });
+ const inbox = defineRoute({ id: 'inbox', path: 'inbox' });
+ const defaultRoute = (): SplitRouteState => ({
+ matches: [
+ { id: 'app', params: {} },
+ { id: 'home', params: {} },
+ ],
+ });
+
+ function AppLayout() {
+ const router = useSplitRouter();
+ return (
+ <For each={router.panes()}>
+ {(pane) => (
+ <section data-testid="pane">
+ <Outlet pane={pane} />
+ </section>
+ )}
+ </For>
+ );
+ }
+
+ it('builds the route tree from its children and renders the first pane’s top-level route', async () => {
+ let router: SplitRouter | undefined;
+ function Layout() {
+ router = useSplitRouter();
+ return <AppLayout />;
+ }
+ const history = createMemoryHistory('/home/~/inbox');
+ render(() => (
+ <Router
+ history={history}
+ paneStore={createMemoryPaneStore()}
+ policy={createTestPolicy().policy}
+ defaultRoute={defaultRoute}
+ >
+ <Route definition={login} component={() => <p>login</p>} />
+ <Route definition={app} component={Layout}>
+ <Route definition={home} component={() => <p>home</p>} />
+ <Route definition={inbox} component={() => <p>inbox</p>} />
+ </Route>
+ </Router>
+ ));
+
+ expect(screen.getAllByTestId('pane')).toHaveLength(2);
+ expect(screen.getByText('inbox')).toBeTruthy();
+ expect(home).not.toHaveProperty('component');
+
+ await router!.navigate(router!.panes()[0]!, '/login');
+ expect(screen.getByText('login')).toBeTruthy();
+ expect(screen.queryAllByTestId('pane')).toHaveLength(0);
+ expect(history.read().path).toBe('/login');
+ });
+
+ it('reads routes from arrays and drops false children', () => {
+ const extra = [inbox].map((definition) => (
+ <Route definition={definition} component={() => <p>inbox</p>} />
+ ));
+ render(() => (
+ <Router
+ history={createMemoryHistory('/inbox')}
+ paneStore={createMemoryPaneStore()}
+ policy={createTestPolicy().policy}
+ defaultRoute={defaultRoute}
+ >
+ {false}
+ <Route definition={app} component={AppLayout}>
+ <Route definition={home} component={() => <p>home</p>} />
+ {extra}
+ </Route>
+ </Router>
+ ));
+ expect(screen.getByText('inbox')).toBeTruthy();
+ });
+
+ it('passes the compiled routes to a history factory', () => {
+ const seen: string[] = [];
+ render(() => (
+ <Router
+ history={(routes) => {
+ seen.push(...routes.byId.keys());
+ return createMemoryHistory('/home');
+ }}
+ paneStore={createMemoryPaneStore()}
+ policy={createTestPolicy().policy}
+ defaultRoute={defaultRoute}
+ >
+ <Route definition={app} component={AppLayout}>
+ <Route definition={home} component={() => <p>home</p>} />
+ </Route>
+ </Router>
+ ));
+ expect(seen).toEqual(['app', 'home']);
+ });
+
+ it('rejects definitions that already set children or a component', () => {
+ const withComponent = defineRoute({
+ id: 'bound',
+ path: 'bound',
+ component: () => null,
+ });
+ const options = {
+ history: createMemoryHistory('/bound'),
+ paneStore: createMemoryPaneStore<Entry>(),
+ policy: createTestPolicy().policy,
+ defaultRoute: (): SplitRouteState => ({
+ matches: [{ id: 'bound', params: {} }],
+ }),
+ };
+ expect(() =>
+ render(() => (
+ <Router {...options}>
+ {/* @ts-expect-error definitions passed to Route carry no component */}
+ <Route definition={withComponent} />
+ </Router>
+ ))
+ ).toThrow(/must not set children or component/);
+ expect(() =>
+ render(() => (
+ <Router {...options}>
+ <p>not a route</p>
+ </Router>
+ ))
+ ).toThrow(/must be <SplitRouter.Route> elements/);
+ });
+});
diff --git a/apps/web/src/lib/utils/favorites.test.ts b/apps/web/src/lib/utils/favorites.test.ts
index 95ee8ba3b2..b8308ff52e 100644
--- a/apps/web/src/lib/utils/favorites.test.ts
+++ b/apps/web/src/lib/utils/favorites.test.ts
@@ -1,3 +1,4 @@
+import { paneRoute } from '@app/routes/app-route';
import type { Favorite } from '@service-storage/generated/schemas/favorite';
import { describe, expect, it, vi } from 'vitest';
import { favoriteBlockName, favoriteSplitContent } from './favorites';
@@ -38,12 +39,10 @@ describe('foreign-entity favorites', () => {
type: 'component',
id: 'reviews',
entryMetadata: {
- route: {
- matches: [
- { id: 'view-reviews', params: {} },
- { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } },
- ],
- },
+ route: paneRoute(
+ { id: 'view-reviews', params: {} },
+ { id: 'reviews-pr', params: { foreignEntityId: 'pr-1' } }
+ ),
},
});
});
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index bfae54afd7..460d5f7a6b 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -1,26 +1,14 @@
-import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
import { ROUTER_BASE, ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
-import { makeEmailAuthComponents } from '@app/features/auth/EmailAuth';
-import { Login } from '@app/features/auth/Login';
-import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAuthWelcome';
-import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnboarding';
import { setCookie } from '@app/features/auth/Shared';
-import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
-import { InviteLinksPortal } from '@app/features/gtm-invite/InviteLinksPortal';
-import { InviteWelcome } from '@app/features/gtm-invite/InviteWelcome';
import { usePendingInviteRedemption } from '@app/features/gtm-invite/usePendingInviteRedemption';
import { HomePreferencesProvider } from '@app/features/home/home-prefs';
import { GlobalShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';
import { IncomingMeetingInvitationsProvider } from '@app/features/meetings/incoming-meeting-invitations';
-import { MeetingRouter } from '@app/features/meetings/meeting-router';
import { MeetingSessionProvider } from '@app/features/meetings/meeting-session-provider';
import { usePendingNotificationNavigationEffect } from '@app/features/notifications/PendingNotificationNavigationEffect';
import { InteractiveOnboardingModal } from '@app/features/onboarding/InteractiveOnboardingModal';
-import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';
-import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';
import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
import { SearchProvider } from '@app/features/soup/search/context';
-import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';
import {
AnalyticsContextProvider,
useAnalytics,
@@ -39,10 +27,7 @@ import { CallKitSync } from '@channel/Call/use-callkit';
import { GlobalAppStateProvider } from '@components/app/GlobalAppState';
import { Layout } from '@components/app/Layout';
import { ReactiveFavicon } from '@components/app/ReactiveFavicon';
-import { LAYOUT_ROUTE } from '@components/app/split-layout/SplitLayoutRoute';
-import { publishLoginSuccess } from '@core/auth/login-events';
import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';
-import { LoadingBlock } from '@core/component/LoadingBlock';
import { ToastRegion } from '@core/component/Toast/ToastRegion';
import { enableOnboardingV4 } from '@core/constant/featureFlags';
import { ChannelsContextProvider } from '@core/context/channels';
@@ -98,7 +83,6 @@ import { ws as connectionGatewayWebsocket } from '@service-connection/websocket'
import { MetaProvider, Title } from '@solidjs/meta';
import {
HashRouter,
- Navigate,
type RouteDefinition,
type RoutePreloadFunc,
Router,
@@ -112,7 +96,6 @@ import {
resolveActiveThemeId,
systemThemeEffect,
} from '@theme/utils/themeUtils';
-import { Button } from '@ui';
import { detect } from 'detect-browser';
import {
createEffect,
@@ -125,12 +108,7 @@ import {
Show,
} from 'solid-js';
import { useReminderAlerts } from '../features/reminders/reminder-alerts';
-import {
- BookingReceiptPage,
- PublicBookingPage,
-} from '../features/scheduling/public-booking';
-import { BasePathComponent } from './BasePath';
-import { TaskRoute } from './TaskRoute';
+import { AppRouterView } from './app-router-view';
/** Syncs login cookie with auth state. Only updates on successful query (not errors/loading). */
function useSyncLoginCookie() {
@@ -186,166 +164,9 @@ const rootPreload: RoutePreloadFunc = async (args) => {
}
};
-function NotFound() {
- if (isNativeMobilePlatform()) return <Navigate href={DEFAULT_ROUTE} />;
- window.location.href = window.location.origin;
- return '';
-}
-
-const { EmailCallback, CALLBACK_PATH, EmailLinkCallback, LINK_CALLBACK_PATH } =
- makeEmailAuthComponents({
- callbackPath: '/email-signup-callback',
- linkCallbackPath: '/inbox-link-callback',
- successPath: '/',
- });
-
-/** The retired /setup path forwards to the onboarding flow, query intact. */
-function SetupRedirect() {
- const location = useLocation();
- return <Navigate href={`/onboarding${location.search}`} />;
-}
-
-/**
- * The old split-screen /setup surface is retired; the onboarding flow lives at
- * /onboarding now. Flag off, /setup must go home — forwarding would land
- * flag-off web users on /login and native users on MobileOnboarding.
- */
-function SetupRoute() {
- const onboardingV4 = useOnboardingV4Flag();
-
- return (
- <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
- <Show when={onboardingV4().enabled} fallback={<Navigate href="/" />}>
- <SetupRedirect />
- </Show>
- </Show>
- );
-}
-
-/**
- * Web/desktop gate for /onboarding. Waits for PostHog to report flags before
- * bouncing: with the flag on but not yet loaded, a direct visit (or a reload
- * mid-flow) would otherwise get kicked to /login and lose its ?next.
- */
-function OnboardingRoute() {
- const onboardingV4 = useOnboardingV4Flag();
-
- return (
- <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
- <Show when={onboardingV4().enabled} fallback={<Navigate href="/login" />}>
- <OnboardingFlow />
- </Show>
- </Show>
- );
-}
-
+/** The split router handles every path; its route tree is in `app-router-view.tsx`. */
const ROUTES: RouteDefinition[] = [
- { path: '/book/:profile/:slug?', component: PublicBookingPage },
- { path: '/booking/:id', component: BookingReceiptPage },
- { path: '/meet/*path', component: MeetingRouter },
- {
- path: '/task-slug/:taskSlug',
- component: TaskRoute,
- },
- LAYOUT_ROUTE,
- {
- path: '/',
- component: BasePathComponent,
- },
- {
- path: '/signup',
- component: () => <Login signupMode />,
- },
- {
- path: CALLBACK_PATH,
- component: EmailCallback,
- },
- {
- path: LINK_CALLBACK_PATH,
- component: EmailLinkCallback,
- },
- {
- path: '/login/popup/success',
- component: () => {
- onMount(() => {
- publishLoginSuccess();
- window.close();
- });
-
- onCleanup(() => {
- window.close();
- });
-
- return (
- <div class="h-full overflow-y-hidden">
- <div class="relative flex flex-row items-center pt-4 h-full">
- <Button
- variant="outline"
- onClick={() => {
- publishLoginSuccess();
- window.close();
- }}
- >
- Close
- </Button>
- </div>
- </div>
- );
- },
- },
- {
- path: '/login',
- component: () => <Login />,
- },
- {
- path: '/welcome',
- component: () =>
- isNativeMobilePlatform() ? <MobileAuthWelcome /> : <Login />,
- },
- {
- // Mobile-web visitors can't sign up on a phone, so instead of pushing them
- // through Google SSO + onboarding we capture their email and email them a
- // link to open on desktop. The marketing site redirects mobile browsers
- // here.
- path: '/mobile-email-signup',
- component: MobileWebSignup,
- },
- {
- path: '/onboarding',
- // Flag-gated at the route, not just the redirect: with the flag off a
- // direct visit must not touch the onboarding backend (reading it
- // creates the flow's row and starts gathers).
- component: () =>
- isNativeMobilePlatform() ? <MobileOnboarding /> : <OnboardingRoute />,
- },
- {
- // Preserve the query (?next deep links) when forwarding to /onboarding.
- path: '/setup',
- component: SetupRoute,
- },
- {
- // A personal GTM invite link (`?token=`): welcome page, then signup.
- path: '/invite',
- component: InviteWelcome,
- },
- {
- // Macro staff only: create and track GTM invite links.
- path: '/internal/invite-links',
- component: InviteLinksPortal,
- },
- {
- path: '/team-invite',
- component: TeamInviteAcceptance,
- },
- {
- path: '/channel-invite',
- component: ChannelInviteAcceptance,
- },
- {
- // This splat route must be last to catch all unmatched routes
- path: '*404',
- component: NotFound,
- },
+ { path: '/*path', component: AppRouterView },
];
function ConfiguredGlobalAppStateProvider(props: ParentProps) {
diff --git a/apps/web/src/routes/TaskRoute.test.tsx b/apps/web/src/routes/TaskRoute.test.tsx
index fb06afe452..239dad17f3 100644
--- a/apps/web/src/routes/TaskRoute.test.tsx
+++ b/apps/web/src/routes/TaskRoute.test.tsx
@@ -38,11 +38,6 @@ vi.mock('@solidjs/router', () => ({
return null;
},
useNavigate: () => mocks.navigate,
- useParams: () => ({
- get taskSlug() {
- return mocks.taskSlug;
- },
- }),
}));
vi.mock('@ui', () => ({
@@ -64,7 +59,7 @@ function renderRoute(): HTMLElement {
const disposeRender = render(
() => (
<QueryClientProvider client={queryClient}>
- <TaskRoute />
+ <TaskRoute taskSlug={mocks.taskSlug} />
</QueryClientProvider>
),
container
diff --git a/apps/web/src/routes/TaskRoute.tsx b/apps/web/src/routes/TaskRoute.tsx
index 35dbd7424a..6e8d5e9be8 100644
--- a/apps/web/src/routes/TaskRoute.tsx
+++ b/apps/web/src/routes/TaskRoute.tsx
@@ -4,20 +4,15 @@ import { LoadingBlock } from '@core/component/LoadingBlock';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { thrownResultErrorHasCode } from '@core/util/result';
import { useTeamTaskQuery } from '@queries/storage/team-task';
-import { Navigate, useNavigate, useParams } from '@solidjs/router';
+import { Navigate, useNavigate } from '@solidjs/router';
import { Button } from '@ui';
import { createEffect, createMemo, Match, on, Show, Switch } from 'solid-js';
-type TaskRouteParams = {
- taskSlug: string;
-};
-
/** Resolves a team-scoped task slug to the existing canonical task route. */
-export function TaskRoute() {
- const params = useParams<TaskRouteParams>();
+export function TaskRoute(props: { taskSlug: string }) {
const navigate = useNavigate();
const isAuthenticated = useIsAuthenticated();
- const taskSlug = () => params.taskSlug;
+ const taskSlug = () => props.taskSlug;
const isValidSlug = () => isValidTeamTaskSlug(taskSlug());
const slugToResolve = createMemo(() =>
isAuthenticated() === true && isValidSlug() ? taskSlug() : undefined
diff --git a/apps/web/src/routes/app-route.ts b/apps/web/src/routes/app-route.ts
new file mode 100644
index 0000000000..30ce61eabf
--- /dev/null
+++ b/apps/web/src/routes/app-route.ts
@@ -0,0 +1,26 @@
+import type { SplitRouteMatch, SplitRouteState } from '@app/split-router';
+
+/** The route without a path whose children are the pane routes. */
+export const APP_ROUTE_ID = 'app';
+
+/** The pane route that catches any pane path no other route matches. */
+export const NOT_FOUND_ROUTE_ID = 'not-found';
+
+const appMatch: SplitRouteMatch = { id: APP_ROUTE_ID, params: {} };
+
+/** A pane route's state: the app route, then the pane route's own matches. */
+export function paneRoute(
+ ...matches: [SplitRouteMatch, ...SplitRouteMatch[]]
+): SplitRouteState {
+ return { matches: [appMatch, ...matches] };
+}
+
+/** The first match below the app route, which names what a pane shows. */
+export function paneRootMatch(
+ route: SplitRouteState
+): SplitRouteMatch | undefined {
+ const [first, root] = route.matches;
+ if (first.id !== APP_ROUTE_ID) return;
+
+ return root;
+}
diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsx
new file mode 100644
index 0000000000..84a8df92e1
--- /dev/null
+++ b/apps/web/src/routes/app-router-view.tsx
@@ -0,0 +1,337 @@
+import { ROUTER_BASE } from '@app/constants/routerBase';
+import { ActivityRouteView } from '@app/features/activity/route-views';
+import { AgentsRouteView } from '@app/features/agents-view/route-views';
+import { CallDetailRouteView } from '@app/features/block-call/route-views';
+import { PrDetailRouteView } from '@app/features/block-pr/route-views';
+import { CalendarRouteView } from '@app/features/calendar-view/route-views';
+import { ChannelInviteAcceptance } from '@app/features/channel-invitations/ChannelInviteAcceptance';
+import { ChannelDetailRouteView } from '@app/features/channels-view/channels-view';
+import { ChannelsRouteView } from '@app/features/channels-view/route-views';
+import { CompaniesRouteView } from '@app/features/crm/route-views';
+import { DriveDetailView } from '@app/features/drive-view/components/DriveDetailView';
+import {
+ DriveCallRouteView,
+ DriveRouteView,
+} from '@app/features/drive-view/route-views';
+import { EmailDetailRouteView } from '@app/features/email-view/components/EmailDetailView';
+import { MailRouteView } from '@app/features/email-view/route-views';
+import { GettingStartedRouteView } from '@app/features/getting-started/route-views';
+import { InviteLinksPortal } from '@app/features/gtm-invite/InviteLinksPortal';
+import { InviteWelcome } from '@app/features/gtm-invite/InviteWelcome';
+import { HomeEntityDetailRouteView } from '@app/features/home/components/HomeEntityDetailRouteView';
+import { HomeReminderDetailRouteView } from '@app/features/home/components/HomeReminderDetailRouteView';
+import {
+ HomeCalendarRouteView,
+ HomeDetailRouteView,
+} from '@app/features/home/home-view';
+import { HomeRouteView } from '@app/features/home/route-views';
+import { MeetingRouter } from '@app/features/meetings/meeting-router';
+import {
+ CallsRouteView,
+ FoldersRouteView,
+ RecentRouteView,
+ SearchRouteView,
+} from '@app/features/next-soup/route-views';
+import MobileWebSignup from '@app/features/onboarding/MobileWebSignup';
+import {
+ ReminderDetailRouteView,
+ RemindersRouteView,
+} from '@app/features/reminders/route-views';
+import {
+ ReviewsPrDetailRouteView,
+ ReviewsRouteView,
+} from '@app/features/reviews-view/route-views';
+import { SettingsRouteView } from '@app/features/settings/route-views';
+import { TasksDetailRouteView } from '@app/features/tasks-view/components/TasksDetailView';
+import {
+ ProjectDetailRouteView,
+ ProjectTaskRouteView,
+ TasksRouteView,
+} from '@app/features/tasks-view/route-views';
+import { TeamInviteAcceptance } from '@app/features/team-invitations/TeamInviteAcceptance';
+import { globalSplitManager } from '@app/signal/splitLayout';
+import {
+ createMemoryPaneStore,
+ SplitRouter,
+ useSolidRouterHistory,
+} from '@app/split-router';
+import { SplitLayout } from '@components/app/split-layout/SplitLayout';
+import { createAppSplitRouterMiddleware } from '@components/app/split-layout/split-router/app-middleware';
+import { createAppPanePolicy } from '@components/app/split-layout/split-router/app-pane-policy';
+import {
+ splitContentFromLocation,
+ upgradeLegacyPath,
+} from '@components/app/split-layout/split-router/legacy-route';
+import NotFound from '@core/component/AccessErrorViews/NotFound';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { isTauri } from '@core/util/platform';
+import { transformShortIdInUrlPathname } from '@core/util/url';
+import { lazy } from 'solid-js';
+import { paneRoute } from './app-route';
+import { BasePathComponent } from './BasePath';
+import {
+ BookingReceiptRoutePage,
+ EmailCallback,
+ EmailLinkCallback,
+ LoginPage,
+ LoginPopupSuccess,
+ OnboardingPage,
+ PublicBookingRoutePage,
+ SetupPage,
+ SignupPage,
+ TaskSlugPage,
+ WelcomePage,
+} from './pages';
+import {
+ activityRoute,
+ agentChatsRoute,
+ agentsRoute,
+ agentsViewRoute,
+ appRoute,
+ baseRoute,
+ bookingReceiptRoute,
+ calendarSplitRoute,
+ callDetailRoute,
+ callsRoute,
+ channelDetailRoute,
+ channelInviteRoute,
+ channelsSplitRoute,
+ codersRoute,
+ companiesRoute,
+ debugRoutes,
+ driveCallRoute,
+ driveFolderDocumentRoute,
+ driveFolderRoute,
+ driveRootDocumentRoute,
+ driveSplitRoute,
+ driveTabDocumentRoute,
+ driveTabRoute,
+ emailSignupCallbackRoute,
+ emailSplitRoute,
+ emailThreadRoute,
+ foldersRoute,
+ gettingStartedRoute,
+ homeCalendarRoute,
+ homeChannelRoute,
+ homeDocumentRoute,
+ homePreviewRoute,
+ homeReminderRoute,
+ homeSplitRoute,
+ inboxLinkCallbackRoute,
+ internalInviteLinksRoute,
+ inviteRoute,
+ legacyContentRoute,
+ loginPopupSuccessRoute,
+ loginRoute,
+ meetRoute,
+ mobileEmailSignupRoute,
+ notFoundRoute,
+ onboardingRoute,
+ prDetailRoute,
+ projectDetailRoute,
+ projectTaskRoute,
+ publicBookingRoute,
+ recentRoute,
+ reminderDetailRoute,
+ remindersRoute,
+ reviewsPrRoute,
+ reviewsSplitRoute,
+ searchRoute,
+ settingsRoute,
+ setupRoute,
+ signupRoute,
+ taskDetailRoute,
+ taskSlugRoute,
+ tasksProjectsRoute,
+ tasksSplitRoute,
+ teamInviteRoute,
+ welcomeRoute,
+} from './routes';
+
+const { Router, Route } = SplitRouter;
+
+/** Debug views stay behind the registry's lazy import. */
+function debugView(componentId: string) {
+ return lazy(async () => {
+ const { resolveComponent } = await import(
+ '@components/app/split-layout/componentRegistry'
+ );
+ return { default: () => resolveComponent(componentId).element() };
+ });
+}
+
+/** The app's router: the first pane's top-level route renders here, and app URLs render the split layout. */
+export function AppRouterView() {
+ const debugRouteElements = debugRoutes.map(({ componentId, route }) => (
+ <Route definition={route} component={debugView(componentId)} />
+ ));
+
+ return (
+ <Router
+ history={(routes) =>
+ useSolidRouterHistory({
+ base: ROUTER_BASE,
+ mode: isTauri() ? 'hash' : 'path',
+ transformPath: (path) =>
+ upgradeLegacyPath(routes, transformShortIdInUrlPathname(path)),
+ })
+ }
+ paneStore={createMemoryPaneStore()}
+ policy={createAppPanePolicy({
+ manager: globalSplitManager,
+ toContent: splitContentFromLocation,
+ defaultLocation: () => ({
+ route: paneRoute({ id: 'view-home', params: {} }),
+ }),
+ singlePane: isNativeMobilePlatform,
+ })}
+ middleware={createAppSplitRouterMiddleware({ isTouchDevice })}
+ globalSearch={['referral_code']}
+ defaultRoute={() => ({ matches: [{ id: baseRoute.id, params: {} }] })}
+ >
+ <Route definition={baseRoute} component={BasePathComponent} />
+ <Route
+ definition={publicBookingRoute}
+ component={PublicBookingRoutePage}
+ />
+ <Route
+ definition={bookingReceiptRoute}
+ component={BookingReceiptRoutePage}
+ />
+ <Route definition={meetRoute} component={MeetingRouter} />
+ <Route definition={taskSlugRoute} component={TaskSlugPage} />
+ <Route definition={signupRoute} component={SignupPage} />
+ <Route definition={emailSignupCallbackRoute} component={EmailCallback} />
+ <Route
+ definition={inboxLinkCallbackRoute}
+ component={EmailLinkCallback}
+ />
+ <Route
+ definition={loginPopupSuccessRoute}
+ component={LoginPopupSuccess}
+ />
+ <Route definition={loginRoute} component={LoginPage} />
+ <Route definition={welcomeRoute} component={WelcomePage} />
+ <Route definition={mobileEmailSignupRoute} component={MobileWebSignup} />
+ <Route definition={onboardingRoute} component={OnboardingPage} />
+ <Route definition={setupRoute} component={SetupPage} />
+ <Route definition={inviteRoute} component={InviteWelcome} />
+ <Route
+ definition={internalInviteLinksRoute}
+ component={InviteLinksPortal}
+ />
+ <Route definition={teamInviteRoute} component={TeamInviteAcceptance} />
+ <Route
+ definition={channelInviteRoute}
+ component={ChannelInviteAcceptance}
+ />
+
+ <Route definition={appRoute} component={SplitLayout}>
+ <Route definition={driveSplitRoute} component={DriveRouteView}>
+ <Route definition={driveFolderRoute}>
+ <Route
+ definition={driveFolderDocumentRoute}
+ component={DriveDetailView}
+ />
+ </Route>
+ <Route definition={driveTabRoute}>
+ <Route
+ definition={driveTabDocumentRoute}
+ component={DriveDetailView}
+ />
+ </Route>
+ <Route definition={driveCallRoute} component={DriveCallRouteView} />
+ <Route
+ definition={driveRootDocumentRoute}
+ component={DriveDetailView}
+ />
+ </Route>
+ <Route definition={settingsRoute} component={SettingsRouteView} />
+ <Route definition={agentsRoute} component={AgentsRouteView} />
+ <Route definition={codersRoute} component={AgentsRouteView} />
+ <Route definition={agentChatsRoute} component={AgentsRouteView} />
+ <Route definition={homeSplitRoute} component={HomeRouteView}>
+ {/* The period path is matched before the block pattern can claim `calendar`. */}
+ <Route
+ definition={homeCalendarRoute}
+ component={HomeCalendarRouteView}
+ />
+ <Route
+ definition={homeChannelRoute}
+ component={HomeEntityDetailRouteView}
+ />
+ <Route
+ definition={homeDocumentRoute}
+ component={HomeEntityDetailRouteView}
+ />
+ <Route
+ definition={homeReminderRoute}
+ component={HomeReminderDetailRouteView}
+ />
+ <Route
+ definition={homePreviewRoute}
+ component={HomeDetailRouteView}
+ />
+ </Route>
+ <Route
+ definition={gettingStartedRoute}
+ component={GettingStartedRouteView}
+ />
+ <Route definition={recentRoute} component={RecentRouteView} />
+ <Route definition={activityRoute} component={ActivityRouteView} />
+ <Route
+ definition={reminderDetailRoute}
+ component={ReminderDetailRouteView}
+ />
+ <Route definition={remindersRoute} component={RemindersRouteView} />
+ <Route definition={agentsViewRoute} component={AgentsRouteView} />
+ <Route definition={emailSplitRoute} component={MailRouteView}>
+ <Route
+ definition={emailThreadRoute}
+ component={EmailDetailRouteView}
+ />
+ </Route>
+ <Route definition={tasksSplitRoute} component={TasksRouteView}>
+ <Route
+ definition={projectDetailRoute}
+ component={ProjectDetailRouteView}
+ >
+ <Route
+ definition={projectTaskRoute}
+ component={ProjectTaskRouteView}
+ />
+ </Route>
+ <Route definition={tasksProjectsRoute} />
+ <Route
+ definition={taskDetailRoute}
+ component={TasksDetailRouteView}
+ />
+ </Route>
+ <Route definition={reviewsSplitRoute} component={ReviewsRouteView}>
+ <Route
+ definition={reviewsPrRoute}
+ component={ReviewsPrDetailRouteView}
+ />
+ </Route>
+ <Route definition={calendarSplitRoute} component={CalendarRouteView} />
+ <Route definition={channelsSplitRoute} component={ChannelsRouteView}>
+ <Route
+ definition={channelDetailRoute}
+ component={ChannelDetailRouteView}
+ />
+ </Route>
+ <Route definition={callsRoute} component={CallsRouteView} />
+ <Route definition={callDetailRoute} component={CallDetailRouteView} />
+ <Route definition={companiesRoute} component={CompaniesRouteView} />
+ <Route definition={foldersRoute} component={FoldersRouteView} />
+ <Route definition={searchRoute} component={SearchRouteView} />
+ <Route definition={prDetailRoute} component={PrDetailRouteView} />
+ {debugRouteElements}
+ {/* Renders the split's legacy mount, so it has no component. */}
+ <Route definition={legacyContentRoute} />
+ <Route definition={notFoundRoute} component={NotFound} />
+ </Route>
+ </Router>
+ );
+}
diff --git a/apps/web/src/routes/pages.tsx b/apps/web/src/routes/pages.tsx
new file mode 100644
index 0000000000..2766493086
--- /dev/null
+++ b/apps/web/src/routes/pages.tsx
@@ -0,0 +1,134 @@
+import { makeEmailAuthComponents } from '@app/features/auth/EmailAuth';
+import { Login } from '@app/features/auth/Login';
+import { MobileAuthWelcome } from '@app/features/auth/mobile-onboarding/MobileAuthWelcome';
+import { MobileOnboarding } from '@app/features/auth/mobile-onboarding/MobileOnboarding';
+import {
+ BookingReceiptPage,
+ PublicBookingPage,
+} from '@app/features/scheduling/public-booking';
+import { OnboardingFlow } from '@app/features/setup/flow/OnboardingFlow';
+import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flag';
+import { useRouteParams } from '@app/split-router';
+import { publishLoginSuccess } from '@core/auth/login-events';
+import { LoadingBlock } from '@core/component/LoadingBlock';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { Navigate, useLocation } from '@solidjs/router';
+import { Button } from '@ui';
+import { onCleanup, onMount, Show } from 'solid-js';
+import {
+ bookingReceiptRoute,
+ EMAIL_SIGNUP_CALLBACK_PATH,
+ INBOX_LINK_CALLBACK_PATH,
+ publicBookingRoute,
+ taskSlugRoute,
+} from './routes';
+import { TaskRoute } from './TaskRoute';
+
+export const { EmailCallback, EmailLinkCallback } = makeEmailAuthComponents({
+ callbackPath: EMAIL_SIGNUP_CALLBACK_PATH,
+ linkCallbackPath: INBOX_LINK_CALLBACK_PATH,
+ successPath: '/',
+});
+
+export function LoginPage() {
+ return <Login />;
+}
+
+export function SignupPage() {
+ return <Login signupMode />;
+}
+
+export function WelcomePage() {
+ return isNativeMobilePlatform() ? <MobileAuthWelcome /> : <Login />;
+}
+
+/** The retired /setup path forwards to the onboarding flow, query intact. */
+function SetupRedirect() {
+ const location = useLocation();
+ return <Navigate href={`/onboarding${location.search}`} />;
+}
+
+/**
+ * The old split-screen /setup surface is retired; the onboarding flow lives at
+ * /onboarding now. Flag off, /setup must go home — forwarding would land
+ * flag-off web users on /login and native users on MobileOnboarding.
+ */
+export function SetupPage() {
+ const onboardingV4 = useOnboardingV4Flag();
+
+ return (
+ <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
+ <Show when={onboardingV4().enabled} fallback={<Navigate href="/" />}>
+ <SetupRedirect />
+ </Show>
+ </Show>
+ );
+}
+
+/**
+ * Web/desktop gate for /onboarding. Waits for PostHog to report flags before
+ * bouncing: with the flag on but not yet loaded, a direct visit (or a reload
+ * mid-flow) would otherwise get kicked to /login and lose its ?next.
+ */
+function OnboardingRoute() {
+ const onboardingV4 = useOnboardingV4Flag();
+
+ return (
+ <Show when={!onboardingV4().loading} fallback={<LoadingBlock />}>
+ <Show when={onboardingV4().enabled} fallback={<Navigate href="/login" />}>
+ <OnboardingFlow />
+ </Show>
+ </Show>
+ );
+}
+
+/**
+ * Flag-gated here, not just at the redirect: with the flag off a direct visit
+ * must not touch the onboarding backend (reading it creates the flow's row
+ * and starts gathers).
+ */
+export function OnboardingPage() {
+ return isNativeMobilePlatform() ? <MobileOnboarding /> : <OnboardingRoute />;
+}
+
+export function LoginPopupSuccess() {
+ onMount(() => {
+ publishLoginSuccess();
+ window.close();
+ });
+
+ onCleanup(() => {
+ window.close();
+ });
+
+ return (
+ <div class="h-full overflow-y-hidden">
+ <div class="relative flex flex-row items-center pt-4 h-full">
+ <Button
+ variant="outline"
+ onClick={() => {
+ publishLoginSuccess();
+ window.close();
+ }}
+ >
+ Close
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+export function TaskSlugPage() {
+ const params = useRouteParams(taskSlugRoute);
+ return <TaskRoute taskSlug={params.taskSlug} />;
+}
+
+export function PublicBookingRoutePage() {
+ const params = useRouteParams(publicBookingRoute);
+ return <PublicBookingPage profile={params.profile} slug={params.slug} />;
+}
+
+export function BookingReceiptRoutePage() {
+ const params = useRouteParams(bookingReceiptRoute);
+ return <BookingReceiptPage id={params.id} />;
+}
diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.ts
new file mode 100644
index 0000000000..0617a22982
--- /dev/null
+++ b/apps/web/src/routes/routes.ts
@@ -0,0 +1,725 @@
+import { changesSearch } from '@app/features/agent-changes/changes-search';
+import { agentsRouteSegments } from '@app/features/agents-view/core/route';
+import { agentDetailSearch } from '@app/features/block-agent/agent-route';
+import { SPREADSHEET_COMMENT_PARAMS } from '@app/features/block-spreadsheet/core/spreadsheet-comments';
+import {
+ CALENDAR_ROUTE_ID,
+ CALENDAR_SEARCH_NAMESPACE,
+ calendarPeriodParams,
+ calendarPeriodPath,
+} from '@app/features/calendar-view/calendar-url';
+import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';
+import { driveDetailTrailSchema } from '@app/features/drive-view/primitives/drive-detail-trail';
+import {
+ DRIVE_DOCUMENT_TYPES,
+ driveDocumentBlockType,
+} from '@app/features/drive-view/primitives/drive-route-schema';
+import { URL_PARAMS as EMAIL_URL_PARAMS } from '@app/features/email-thread/core/location';
+import {
+ HOME_PREVIEW_SEARCH_NAMESPACES,
+ homeBaseBlockType,
+ homePreviewRouteParams,
+} from '@app/features/home/home-route-schema';
+import {
+ HOME_REMINDER_DETAIL_ROUTE_ID,
+ REMINDER_DETAIL_ROUTE_ID,
+} from '@app/features/reminders/reminder-navigation';
+import { reviewsTabSearch } from '@app/features/reviews-view/reviews-tab-search';
+import { defineRoute, type Entry, routeParams } from '@app/split-router';
+import { callDetailSearch } from '@block-call/call-route';
+import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';
+import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';
+import { URL_PARAMS as MARKDOWN_URL_PARAMS } from '@block-md/constants';
+import { markdownDetailSearch } from '@block-md/markdown-route';
+import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';
+import { pdfDetailSearch } from '@block-pdf/pdf-route';
+import { decodeLegacyPair } from '@components/app/split-layout/split-router/legacy-route';
+import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';
+import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';
+import {
+ settingsSlugToTab,
+ settingsTabToSlug,
+} from '@core/constant/settingsTabsConfig';
+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';
+import { z } from 'zod';
+import { APP_ROUTE_ID, NOT_FOUND_ROUTE_ID } from './app-route';
+
+export const EMAIL_SIGNUP_CALLBACK_PATH = '/email-signup-callback';
+export const INBOX_LINK_CALLBACK_PATH = '/inbox-link-callback';
+
+// Pages outside the split layout. They keep the whole query.
+
+export const baseRoute = defineRoute({
+ id: 'base',
+ path: '',
+ externalSearch: '*',
+});
+
+export const publicBookingRoute = defineRoute({
+ id: 'public-booking',
+ path: 'book/:profile/:slug?',
+ externalSearch: '*',
+});
+
+export const bookingReceiptRoute = defineRoute({
+ id: 'booking-receipt',
+ path: 'booking/:id',
+ externalSearch: '*',
+});
+
+export const meetRoute = defineRoute({
+ id: 'meet',
+ path: 'meet/*path',
+ externalSearch: '*',
+});
+
+export const taskSlugRoute = defineRoute({
+ id: 'task-slug',
+ path: 'task-slug/:taskSlug',
+ externalSearch: '*',
+});
+
+export const signupRoute = defineRoute({
+ id: 'signup',
+ path: 'signup',
+ externalSearch: '*',
+});
+
+export const emailSignupCallbackRoute = defineRoute({
+ id: 'email-signup-callback',
+ path: EMAIL_SIGNUP_CALLBACK_PATH,
+ externalSearch: '*',
+});
+
+export const inboxLinkCallbackRoute = defineRoute({
+ id: 'inbox-link-callback',
+ path: INBOX_LINK_CALLBACK_PATH,
+ externalSearch: '*',
+});
+
+export const loginPopupSuccessRoute = defineRoute({
+ id: 'login-popup-success',
+ path: 'login/popup/success',
+ externalSearch: '*',
+});
+
+export const loginRoute = defineRoute({
+ id: 'login',
+ path: 'login',
+ externalSearch: '*',
+});
+
+export const welcomeRoute = defineRoute({
+ id: 'welcome',
+ path: 'welcome',
+ externalSearch: '*',
+});
+
+/**
+ * Mobile-web visitors can't sign up on a phone, so instead of pushing them
+ * through Google SSO + onboarding we capture their email and email them a
+ * link to open on desktop. The marketing site redirects mobile browsers here.
+ */
+export const mobileEmailSignupRoute = defineRoute({
+ id: 'mobile-email-signup',
+ path: 'mobile-email-signup',
+ externalSearch: '*',
+});
+
+export const onboardingRoute = defineRoute({
+ id: 'onboarding',
+ path: 'onboarding',
+ externalSearch: '*',
+});
+
+/** The retired setup path; it forwards to onboarding with its query (?next deep links). */
+export const setupRoute = defineRoute({
+ id: 'setup',
+ path: 'setup',
+ externalSearch: '*',
+});
+
+/** A personal GTM invite link (`?token=`): welcome page, then signup. */
+export const inviteRoute = defineRoute({
+ id: 'invite',
+ path: 'invite',
+ externalSearch: '*',
+});
+
+/** Macro staff only: create and track GTM invite links. */
+export const internalInviteLinksRoute = defineRoute({
+ id: 'internal-invite-links',
+ path: 'internal/invite-links',
+ externalSearch: '*',
+});
+
+export const teamInviteRoute = defineRoute({
+ id: 'team-invite',
+ path: 'team-invite',
+ externalSearch: '*',
+});
+
+export const channelInviteRoute = defineRoute({
+ id: 'channel-invite',
+ path: 'channel-invite',
+ externalSearch: '*',
+});
+
+/** The split layout; its children are the pane routes. */
+export const appRoute = defineRoute({ id: APP_ROUTE_ID });
+
+// Pane routes.
+
+export const driveCallRoute = defineRoute({
+ id: 'drive-call',
+ path: 'call/:callId',
+ params: z.object({ callId: z.string().min(1) }),
+ search: [callDetailSearch.namespace],
+ remountKey: ({ callId }) => callId,
+ claim: ({ callId }) => ({ namespace: 'block', id: `call:${callId}` }),
+ toReference: ({ callId }) => uuidRouteReference(callId, 'call'),
+});
+
+const driveDocumentParams = z.object({
+ documentType: z.enum(DRIVE_DOCUMENT_TYPES),
+ documentId: z.string().min(1),
+});
+
+const documentRemountKey = ({
+ documentType,
+ documentId,
+}: z.infer<typeof driveDocumentParams>) =>
+ `${driveDocumentBlockType(documentType)}:${documentId}`;
+
+export const driveRootDocumentRoute = defineRoute({
+ id: 'drive-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ state: driveDetailTrailSchema,
+ remountKey: documentRemountKey,
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+ toReference: ({ documentId, documentType }) =>
+ uuidRouteReference(documentId, documentType),
+});
+
+export const driveFolderDocumentRoute = defineRoute({
+ id: 'drive-folder-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ state: driveDetailTrailSchema,
+ remountKey: documentRemountKey,
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+ toReference: ({ documentId, documentType }) =>
+ uuidRouteReference(documentId, documentType),
+});
+
+export const driveTabDocumentRoute = defineRoute({
+ id: 'drive-tab-document',
+ search: [markdownDetailSearch.namespace, pdfDetailSearch.namespace],
+ path: ':documentType/:documentId',
+ params: driveDocumentParams,
+ state: driveDetailTrailSchema,
+ remountKey: documentRemountKey,
+ claim: ({ documentType, documentId }) => ({
+ namespace: 'block',
+ id: `${driveDocumentBlockType(documentType)}:${documentId}`,
+ }),
+ toReference: ({ documentId, documentType }) =>
+ uuidRouteReference(documentId, documentType),
+});
+
+export const driveFolderRoute = defineRoute({
+ id: 'drive-folder',
+ path: 'folder/:folderId?',
+ params: z
+ .object({ folderId: z.string().min(1).optional() })
+ .transform(({ folderId }) => ({
+ view: 'folder' as const,
+ folderId,
+ })),
+ state: driveDetailTrailSchema,
+});
+
+export const driveTabRoute = defineRoute({
+ id: 'drive-tab',
+ path: ':tab',
+ aliases: ['tab/:tab'],
+ params: z.object({ tab: z.enum(['recent', 'shared']) }),
+ state: driveDetailTrailSchema,
+});
+
+export const driveSplitRoute = defineRoute({
+ id: 'drive',
+ path: 'drive',
+ aliases: ['drive/owned', 'drive/tab/owned'],
+ search: ['drive'],
+ state: driveDetailTrailSchema,
+ externalSearch: (entry: Readonly<Entry>) => {
+ const type = routeParams(entry.location.route).documentType;
+ if (
+ type === 'md' ||
+ type === 'task' ||
+ type === 'snippet' ||
+ type === 'skill'
+ ) {
+ return Object.values(MARKDOWN_URL_PARAMS);
+ }
+ if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
+ if (type === 'spreadsheet')
+ return Object.values(SPREADSHEET_COMMENT_PARAMS);
+ if (typeof routeParams(entry.location.route).callId === 'string')
+ return [CALL_URL_PARAMS.transcriptId, CALL_URL_PARAMS.messageId];
+ return [];
+ },
+});
+
+export const settingsRoute = defineRoute({
+ id: 'settings',
+ path: 'settings/:tab?',
+ params: z.object({
+ tab: z
+ .string()
+ .refine((tab) => settingsSlugToTab(tab) !== undefined)
+ .default(settingsTabToSlug('Account')),
+ }),
+ claim: () => ({ namespace: 'component', id: 'settings' }),
+ externalSearch: ['pair', 'createAgent'],
+});
+
+export const agentsRoute = defineRoute({
+ id: 'agents',
+ path: 'agents/:id',
+ params: z.object({ id: z.string() }),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'agent', id }),
+ search: [changesSearch.namespace, agentDetailSearch.namespace],
+ toReference: ({ id }) => uuidRouteReference(id, 'agent'),
+});
+
+export const codersRoute = defineRoute({
+ id: 'coders',
+ path: 'coders/:id',
+ params: z.object({ id: z.string() }),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'agent', id }),
+ search: [changesSearch.namespace, agentDetailSearch.namespace],
+ toReference: ({ id }) => uuidRouteReference(id, 'agent'),
+});
+
+export const agentChatsRoute = defineRoute({
+ id: 'agent-chats',
+ path: 'agents/chat/:id',
+ aliases: ['agent-chats/:id'],
+ params: z.object({ id: z.string() }),
+ remountKey: ({ id }) => id,
+ claim: ({ id }) => ({ namespace: 'chat', id }),
+ search: [changesSearch.namespace],
+ toReference: ({ id }) => uuidRouteReference(id, 'chat'),
+});
+
+export const channelDetailRoute = defineRoute({
+ id: 'channels-channel',
+ path: ':channelId',
+ params: z.object({ channelId: z.string().min(1) }),
+ externalSearch: ['channel_message_id', 'channel_thread_id'],
+ remountKey: ({ channelId }) => channelId,
+ claim: ({ channelId }) => ({
+ namespace: 'block',
+ id: `channel:${channelId}`,
+ }),
+ toReference: ({ channelId }) => uuidRouteReference(channelId, 'channel'),
+});
+
+export const channelsSplitRoute = defineRoute({
+ id: 'view-channels',
+ path: 'channels',
+ search: '*' as const,
+});
+
+/** The Calendar view inline in Home, at the Calendar route's own period path and search. */
+export const homeCalendarRoute = defineRoute({
+ id: 'home-calendar',
+ path: 'calendar/:period',
+ params: calendarPeriodParams,
+ serializeParams: ({ period }) => ({ period: calendarPeriodPath(period) }),
+ search: [CALENDAR_SEARCH_NAMESPACE],
+});
+
+export const homeChannelRoute = defineRoute({
+ ...channelDetailRoute,
+ id: 'home-channel',
+ path: 'channel/:channelId',
+});
+
+export const homeDocumentRoute = defineRoute({
+ ...driveRootDocumentRoute,
+ id: 'home-document',
+ externalSearch: (entry: Readonly<Entry>) => {
+ const type = routeParams(entry.location.route).documentType;
+ if (
+ type === 'md' ||
+ type === 'task' ||
+ type === 'snippet' ||
+ type === 'skill'
+ ) {
+ return Object.values(MARKDOWN_URL_PARAMS);
+ }
+ if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
+ return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];
+ },
+ remountKey: ({ documentType, documentId }) =>
+ `${homeBaseBlockType(documentType)}:${documentId}`,
+});
+
+export const homeReminderRoute = defineRoute({
+ id: HOME_REMINDER_DETAIL_ROUTE_ID,
+ path: 'reminder/:reminderId',
+ params: z.object({ reminderId: z.string().min(1) }),
+ remountKey: ({ reminderId }) => reminderId,
+ claim: ({ reminderId }) => ({ namespace: 'reminder', id: reminderId }),
+});
+
+export const homePreviewRoute = defineRoute({
+ id: 'home-preview',
+ path: ':blockType/:previewId',
+ params: homePreviewRouteParams,
+ search: HOME_PREVIEW_SEARCH_NAMESPACES,
+ // Blocks read their own location keys from the URL, as they do in Drive.
+ externalSearch: (entry: Readonly<Entry>) => {
+ const type = routeParams(entry.location.route).blockType;
+ if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);
+ if (type === 'email') return Object.values(EMAIL_URL_PARAMS);
+ if (
+ type === 'md' ||
+ type === 'task' ||
+ type === 'snippet' ||
+ type === 'skill'
+ ) {
+ return Object.values(MARKDOWN_URL_PARAMS);
+ }
+ if (type === 'pdf') return Object.values(PDF_URL_PARAMS);
+ return type === 'spreadsheet' ? [MARKDOWN_URL_PARAMS.commentId] : [];
+ },
+ remountKey: ({ blockType, previewId }) =>
+ `${homeBaseBlockType(blockType)}:${previewId}`,
+ claim: ({ blockType, previewId }) => ({
+ namespace: blockType === 'agent' ? 'agent' : 'block',
+ id:
+ blockType === 'agent'
+ ? previewId
+ : `${homeBaseBlockType(blockType)}:${previewId}`,
+ }),
+ toReference: ({ previewId, blockType }) =>
+ blockType === 'pr'
+ ? { type: 'pr', id: previewId }
+ : uuidRouteReference(previewId, blockType),
+});
+
+export const homeSplitRoute = defineRoute({
+ id: 'view-home',
+ path: 'home',
+ search: '*' as const,
+});
+
+export const gettingStartedRoute = defineRoute({
+ id: 'view-getting-started',
+ path: 'getting-started',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'getting-started' }),
+});
+
+export const recentRoute = defineRoute({
+ id: 'view-recent',
+ path: 'recent',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'recent' }),
+});
+
+export const activityRoute = defineRoute({
+ id: 'view-activity',
+ path: 'activity',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'activity' }),
+});
+
+/** Lightweight standalone reminder detail at `/app/reminder/:reminderId`. */
+export const reminderDetailRoute = defineRoute({
+ id: REMINDER_DETAIL_ROUTE_ID,
+ path: 'reminder/:reminderId',
+ params: z.object({ reminderId: z.string().min(1) }),
+ remountKey: ({ reminderId }) => reminderId,
+ claim: ({ reminderId }) => ({ namespace: 'reminder', id: reminderId }),
+});
+
+export const remindersRoute = defineRoute({
+ id: 'view-reminders',
+ path: 'reminders',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'reminders' }),
+});
+
+export const agentsViewRoute = defineRoute({
+ id: 'view-agents',
+ path: 'agents',
+ search: '*' as const,
+ externalSearch: ['createAgent'],
+ claim: () => ({ namespace: 'component', id: 'agents' }),
+});
+
+export const emailThreadRoute = defineRoute({
+ id: 'mail-thread',
+ path: ':threadId',
+ params: z.object({ threadId: z.string().min(1) }),
+ externalSearch: ['email_message_id'],
+ remountKey: ({ threadId }) => threadId,
+ claim: ({ threadId }) => ({
+ namespace: 'block',
+ id: `email:${threadId}`,
+ }),
+ toReference: ({ threadId }) => uuidRouteReference(threadId, 'email'),
+});
+
+export const emailSplitRoute = defineRoute({
+ id: 'view-mail',
+ path: 'mail',
+ search: '*' as const,
+});
+
+export const taskDetailRoute = defineRoute({
+ id: 'tasks-task',
+ path: ':taskId',
+ params: z.object({ taskId: z.string().min(1) }),
+ remountKey: ({ taskId }) => taskId,
+ claim: ({ taskId }) => ({
+ namespace: 'block',
+ id: `md:${taskId}`,
+ }),
+ toReference: ({ taskId }) => uuidRouteReference(taskId, 'task'),
+ externalSearch: Object.values(MARKDOWN_URL_PARAMS),
+});
+
+export const projectTaskRoute = defineRoute({
+ id: 'tasks-project-task',
+ path: 'task/:taskId',
+ params: z.object({ taskId: z.string().min(1) }),
+ remountKey: ({ taskId }) => taskId,
+ claim: ({ taskId }) => ({ namespace: 'block', id: `md:${taskId}` }),
+ toReference: ({ taskId }) => uuidRouteReference(taskId, 'task'),
+ externalSearch: Object.values(MARKDOWN_URL_PARAMS),
+});
+
+export const projectDetailRoute = defineRoute({
+ id: 'tasks-project',
+ path: 'projects/:projectId/:section',
+ params: z.object({
+ projectId: z.string().uuid(),
+ section: z.enum(['overview', 'tasks']),
+ }),
+ remountKey: ({ projectId }) => projectId,
+ claim: ({ projectId }) => ({
+ namespace: 'block',
+ id: `initiative:${projectId}`,
+ }),
+ toReference: ({ projectId }) => uuidRouteReference(projectId, 'initiative'),
+});
+
+export const tasksProjectsRoute = defineRoute({
+ id: 'tasks-projects',
+ path: 'projects',
+ params: z.object({}).transform(() => ({ projectsTab: 'projects' as const })),
+});
+
+export const tasksSplitRoute = defineRoute({
+ id: 'view-tasks',
+ path: 'tasks',
+ search: '*' as const,
+});
+
+export const reviewsPrRoute = defineRoute({
+ id: 'reviews-pr',
+ path: 'pr/:foreignEntityId',
+ params: z.object({ foreignEntityId: z.string().min(1) }),
+ remountKey: ({ foreignEntityId }) => foreignEntityId,
+ claim: ({ foreignEntityId }) => ({
+ namespace: 'block',
+ id: `pr:${foreignEntityId}`,
+ }),
+ search: [changesSearch.namespace],
+ toReference: ({ foreignEntityId }) => ({ type: 'pr', id: foreignEntityId }),
+});
+
+export const reviewsSplitRoute = defineRoute({
+ id: 'view-reviews',
+ path: 'reviews',
+ search: [reviewsTabSearch.namespace],
+});
+
+export const calendarSplitRoute = defineRoute({
+ id: CALENDAR_ROUTE_ID,
+ path: 'calendar/:period',
+ params: calendarPeriodParams,
+ serializeParams: ({ period }) => ({
+ period: calendarPeriodPath(period),
+ }),
+ search: [CALENDAR_SEARCH_NAMESPACE],
+ externalSearch: ['eventId'],
+ claim: () => ({ namespace: 'component', id: CALENDAR_VIEW_ID }),
+});
+
+export const callsRoute = defineRoute({
+ id: 'view-calls',
+ path: 'calls',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'calls' }),
+});
+
+export const callDetailRoute = defineRoute({
+ id: 'call-detail',
+ path: 'call/:callId',
+ params: z.object({ callId: z.string().min(1) }),
+ search: [callDetailSearch.namespace],
+ externalSearch: [CALL_URL_PARAMS.transcriptId, CALL_URL_PARAMS.messageId],
+ remountKey: ({ callId }) => callId,
+ claim: ({ callId }) => ({ namespace: 'block', id: `call:${callId}` }),
+});
+
+export const companiesRoute = defineRoute({
+ id: 'view-companies',
+ path: 'companies',
+ search: '*' as const,
+ externalSearch: ['crmView'],
+ claim: () => ({ namespace: 'component', id: 'companies' }),
+});
+
+export const foldersRoute = defineRoute({
+ id: 'view-folders',
+ path: 'folders',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'folders' }),
+});
+
+export const searchRoute = defineRoute({
+ id: 'view-search',
+ path: 'search',
+ search: '*' as const,
+ claim: () => ({ namespace: 'component', id: 'search' }),
+});
+
+export const prDetailRoute = defineRoute({
+ id: 'pr-detail',
+ path: 'pr/:foreignEntityId',
+ params: z.object({ foreignEntityId: z.string().min(1) }),
+ remountKey: ({ foreignEntityId }) => foreignEntityId,
+ claim: ({ foreignEntityId }) => ({
+ namespace: 'block',
+ id: `pr:${foreignEntityId}`,
+ }),
+ search: [changesSearch.namespace],
+});
+
+const debugComponentIds = [
+ 'ui',
+ 'icon-gallery',
+ ...(LOCAL_ONLY
+ ? [
+ 'theme-edit-3',
+ 'theme-debug',
+ 'core',
+ 'md',
+ 'data',
+ 'chat',
+ 'chat-attachment',
+ 'chat-tool',
+ 'http-stream',
+ 'static-markdown-stream',
+ 'resize',
+ 'notifications-playground',
+ 'props-debug',
+ 'entity-debug',
+ 'quick-access-list',
+ 'hotkey-debugger',
+ 'user-icon',
+ 'dynamic-ui',
+ 'agent-ui',
+ 'agent-replay',
+ 'agent-changes-ui',
+ 'diff-view-ui',
+ ]
+ : []),
+ ...(import.meta.env.DEV ? ['spreadsheet-demo'] : []),
+ ...(DEV_MODE_ENV
+ ? [
+ 'document-where-playground',
+ 'projection-playground',
+ 'md-parse',
+ 'md-builder',
+ 'collab-surface-demo',
+ ]
+ : []),
+];
+
+/** Registered debug views, behind their environment gates. */
+export const debugRoutes = debugComponentIds.map((componentId) => ({
+ componentId,
+ route: defineRoute({
+ id: `view-${componentId}`,
+ path: `debug/${componentId}`,
+ aliases: [`component/${componentId}`],
+ search: '*' as const,
+ externalSearch: componentId === 'ui' ? ['ui'] : [],
+ claim: () => ({ namespace: 'component', id: componentId }),
+ }),
+}));
+
+/** Pre-router `type/id` URLs; the middleware upgrades the ones that have a route now. */
+export const legacyContentRoute = defineRoute({
+ id: 'legacy-content',
+ path: ':type/:id',
+ search: '*',
+ params: z
+ .object({ type: z.string().min(1), id: z.string().min(1) })
+ .refine(({ type, id }) => decodeLegacyPair(type, id) !== undefined),
+ externalSearch: (entry) => {
+ const { type } = routeParams(entry.location.route);
+ if (type === 'email') return Object.values(EMAIL_URL_PARAMS);
+ if (type === 'channel') return Object.values(CHANNEL_URL_PARAMS);
+ if (type === 'company' || type === 'contact') return [COMMENT_LINK_PARAM];
+ return [];
+ },
+ claim: ({ type, id }) => {
+ const content = decodeLegacyPair(type, id);
+ if (!content) return;
+
+ if (content.type === 'agent') return { namespace: 'agent', id };
+
+ if (content.type === 'component') {
+ const [section, conversationId] = agentsRouteSegments(content.id) ?? [];
+ if (section && conversationId) {
+ return {
+ namespace: section === 'agent-chats' ? 'chat' : 'agent',
+ id: conversationId,
+ };
+ }
+ return { namespace: 'component', id: content.id };
+ }
+
+ return {
+ namespace: 'block',
+ id: `${content.aliasContext?.baseType ?? content.type}:${id}`,
+ };
+ },
+});
+
+/** Catches any pane path no other route matches; listed last. */
+export const notFoundRoute = defineRoute({
+ id: NOT_FOUND_ROUTE_ID,
+ path: '*segments',
+});
diff --git a/apps/web/src/split-router/index.ts b/apps/web/src/split-router/index.ts
index 8de7b4cafe..5c46323c3a 100644
--- a/apps/web/src/split-router/index.ts
+++ b/apps/web/src/split-router/index.ts
@@ -1 +1 @@
-export * from '@app/lib/split-router';
+export * from '@app/lib/split-router/next';
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 5e133b87f0..eed7c4e551 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -98,6 +98,15 @@ successfully rather than hashing the empty JavaScript placeholder.
| `/app/debug/ui?ui=invert-util` | UI gallery, including the inverted Markdown demo on the InvertUtil page |
| `/app/debug/<component>` | Registered debug views (for example `icon-gallery`, `md`, or `agent-ui`); existing environment gates apply. `/app/component/<component>` remains a compatibility alias for these views |
+Each `~`-separated part of an app URL is a split (`/app/home/~/drive`). The
+pages outside the app (`/app/login`, `/app/welcome`, `/app/signup`,
+`/app/onboarding`, `/app/setup`, the invite pages, `/app/meet/...` and
+`/app/task-slug/...`) render without the split layout and take one part only.
+`/app/login/~/home` and URLs nothing matches, such as `/app/garbage`, are
+replaced with `/app`, which goes to Home or to login. An unknown split among app
+splits (`/app/mail/~/garbage`) shows the in-split 404 instead. A split that
+navigates to a page outside the app replaces every split; Back restores them.
+
Search-result locations use pane-local namespaces: `channels` (message/thread),
`email-detail` (message), `markdown-detail` (node), `pdf-detail` (page and highlight
context), `agent-detail` (turn/author), and `call-detail` (transcript segment).