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.

fix(split-layout): focus Controller instead of Viewer Split on fresh load (#5154)

Peter Chinman41a6ab6ba4a1
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 3ee2c6a91b..4a419602ea 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -1,11 +1,9 @@
-import { activeElement } from '@app/signal/focus';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
import {
isSidebarVisible,
useSidebarCollapse,
} from '@components/app/sidebarVisibility';
import { Resize } from '@core/component/Resize';
-import { splitContainerSelector } from '@core/dom-selectors';
import { isMobile } from '@core/mobile/isMobile';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { tabTitleSignal } from '@core/signal/tabTitle';
@@ -13,7 +11,6 @@ import { useWindowSize } from '@solid-primitives/resize-observer';
import { useLocation, useNavigate } from '@solidjs/router';
import { cn } from '@ui';
import {
- type Accessor,
createEffect,
createMemo,
createSelector,
@@ -30,10 +27,8 @@ import { SplitLayoutContext } from './context';
import {
createSplitLayout,
SplitEvent,
- type SplitEventWithType,
type SplitId,
type SplitManager,
- type SplitState,
} from './layoutManager';
import { createLayoutUrlSync, restorePreviewPairs } from './layoutUrlSync';
import {
@@ -45,204 +40,13 @@ import {
loadRestorablePreviewLayout,
PREVIEW_QUERY_PARAM,
} from './previewPersistence';
+import { createSplitFocusTracker } from './splitFocusTracker';
type SplitLayoutContainerProps = {
pairs: string[];
setManager: Setter<SplitManager | undefined>;
};
-function getParentSplitId(element: Element | null) {
- if (!element || !element.isConnected) return null;
- const splitParent = element.closest(splitContainerSelector);
- if (!splitParent) return null;
- const splitId = splitParent.getAttribute('data-split-id');
- if (!splitId) return null;
- return splitId as SplitId;
-}
-
-/**
- * Manages focus / active between splits
- *
- * When a split is focused, it should become the active split.
- * When a split looses focus to a non-split element, the active split should NOT change.
- * Inserting / Removing splits are explicitly handled:
- * - When a split is inserted, it should be focused and activated
- * - When a split is removed, the next split should be focused
- */
-function createSplitFocusTracker(props: {
- splitManager: SplitManager;
- panelRefs: Map<SplitId, HTMLDivElement>;
- splits: Accessor<ReadonlyArray<SplitState>>;
-}) {
- const DEBOUNCE = 40;
- const activeSplitId = () => props.splitManager.activeSplitId();
-
- const currentSplitsIds = () => new Set(props.splits().map((s) => s.id));
- const lastFocusedChildBySplitId: Map<SplitId, HTMLElement | null> = new Map();
- createEffect(
- on(currentSplitsIds, (ids) => {
- for (const key of lastFocusedChildBySplitId.keys()) {
- if (!ids.has(key)) {
- lastFocusedChildBySplitId.delete(key);
- }
- }
- })
- );
-
- const isElementInPanel = (
- panelId: SplitId,
- element: Element | null
- ): boolean => {
- const panelRef = props.panelRefs.get(panelId);
- if (!panelRef || element === null) return false;
- return panelRef === element || panelRef.contains(element);
- };
-
- const focusSplitById = (id: SplitId) => {
- const splitPanelRef = props.panelRefs.get(id);
- if (!splitPanelRef) {
- console.warn(`Tried to focus split with id ${id} but it doesn't exist`);
- return;
- }
-
- // return if panel has a child already with focus.
- if (
- splitPanelRef.contains(document.activeElement) &&
- splitPanelRef !== document.activeElement
- )
- return;
-
- // look for a child to return focus to.
- const child = lastFocusedChildBySplitId.get(id);
- if (child && child.isConnected) {
- child.focus();
- return;
- }
-
- splitPanelRef.focus();
- };
-
- const activateFocusedSplit = (element: Element) => {
- const splitId = activeSplitId();
- if (!splitId) return;
-
- const doesActiveSplitHaveFocus = isElementInPanel(splitId, element);
-
- if (doesActiveSplitHaveFocus) {
- return;
- }
-
- let splitWithFocus: SplitId | undefined;
- // Only visible splits may claim activation — the mobile background
- // split is excluded and can never become active.
- for (const split of props.splitManager.getVisibleSplits()) {
- if (isElementInPanel(split.id, element)) {
- splitWithFocus = split.id;
- break;
- }
- }
-
- if (splitWithFocus) {
- props.splitManager.activateSplit(splitWithFocus);
- }
- };
-
- const findNextSplitToActivate = (splitIndex: number): SplitId | undefined => {
- const nextSplitId =
- splitIndex === 0
- ? props.splits()[0].id
- : props.splits()[splitIndex - 1].id;
-
- return nextSplitId;
- };
-
- const focusFromEvent = (event: SplitEventWithType) => {
- switch (event.type) {
- case SplitEvent.Insert: {
- if (event.activate === false) break;
- const splitId = event.splitId;
- focusSplitById(splitId);
- break;
- }
- case SplitEvent.Remove: {
- const splitId = findNextSplitToActivate(event.splitIndex);
- if (splitId) {
- focusSplitById(splitId);
- }
- break;
- }
- }
- };
-
- // Both of these effects need to be debounced to prevent race conditions.
- // The button for creating a new split itself is in a SplitPanel. This means that without the debounce,
- // the button in the old split might trigger another focus event and re-active the old split.
- let focusTimeout: ReturnType<typeof setTimeout> | undefined;
- let activateTimeout: ReturnType<typeof setTimeout> | undefined;
- let lastProgrammaticActivation = 0;
-
- /** Listens for explicit events from layoutManager that might trigger focus changes */
- createEffect(
- on(
- () => props.splitManager.events(),
- (newEvent) => {
- if (focusTimeout) {
- clearTimeout(focusTimeout);
- }
- if (newEvent.type === SplitEvent.ReturnFocus) {
- const id = props.splitManager.activeSplitId();
- if (id) {
- focusSplitById(id);
- }
- return;
- }
- focusTimeout = setTimeout(() => {
- focusFromEvent(newEvent);
- }, DEBOUNCE);
- }
- )
- );
-
- /** Track when splits are programmatically activated */
- createEffect(
- on(activeSplitId, () => {
- lastProgrammaticActivation = Date.now();
- })
- );
-
- /** Listens for focus changes on the document */
- createEffect(
- on(activeElement, (element) => {
- if (activateTimeout) {
- clearTimeout(activateTimeout);
- }
- if (!element) return;
-
- const parentId = getParentSplitId(element);
- if (
- parentId &&
- element instanceof HTMLElement &&
- !element.closest('[data-no-focus-restore]')
- ) {
- lastFocusedChildBySplitId.set(parentId, element);
- }
-
- activateTimeout = setTimeout(() => {
- const timeSinceActivation = Date.now() - lastProgrammaticActivation;
-
- // If a split was just programmatically activated, ignore this focus change
- if (timeSinceActivation < DEBOUNCE + 50) {
- return;
- }
-
- activateFocusedSplit(element);
- }, DEBOUNCE);
- })
- );
-
- return { focusSplitById };
-}
-
export function SplitLayoutContainer(props: SplitLayoutContainerProps) {
const location = useLocation();
const navigate = useNavigate();
diff --git a/apps/web/src/components/app/split-layout/splitFocusTracker.ts b/apps/web/src/components/app/split-layout/splitFocusTracker.ts
new file mode 100644
index 0000000000..d0fc0a3530
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/splitFocusTracker.ts
@@ -0,0 +1,215 @@
+import { activeElement } from '@app/signal/focus';
+import { splitContainerSelector } from '@core/dom-selectors';
+import { type Accessor, createEffect, on, onCleanup } from 'solid-js';
+import {
+ SplitEvent,
+ type SplitEventWithType,
+ type SplitId,
+ type SplitManager,
+ type SplitState,
+} from './layoutManager';
+
+function getParentSplitId(element: Element | null) {
+ if (!element || !element.isConnected) return null;
+ const splitParent = element.closest(splitContainerSelector);
+ if (!splitParent) return null;
+ const splitId = splitParent.getAttribute('data-split-id');
+ if (!splitId) return null;
+ return splitId as SplitId;
+}
+
+/**
+ * Manages focus / active between splits
+ *
+ * When a split is focused, it should become the active split.
+ * When a split looses focus to a non-split element, the active split should NOT change.
+ * Inserting / Removing splits are explicitly handled:
+ * - When a split is inserted, it should be focused and activated
+ * - When a split is removed, the next split should be focused
+ */
+export function createSplitFocusTracker(props: {
+ splitManager: SplitManager;
+ panelRefs: Map<SplitId, HTMLDivElement>;
+ splits: Accessor<ReadonlyArray<SplitState>>;
+}) {
+ const DEBOUNCE = 40;
+ const activeSplitId = () => props.splitManager.activeSplitId();
+
+ const currentSplitsIds = () => new Set(props.splits().map((s) => s.id));
+ const lastFocusedChildBySplitId: Map<SplitId, HTMLElement | null> = new Map();
+ createEffect(
+ on(currentSplitsIds, (ids) => {
+ for (const key of lastFocusedChildBySplitId.keys()) {
+ if (!ids.has(key)) {
+ lastFocusedChildBySplitId.delete(key);
+ }
+ }
+ })
+ );
+
+ const isElementInPanel = (
+ panelId: SplitId,
+ element: Element | null
+ ): boolean => {
+ const panelRef = props.panelRefs.get(panelId);
+ if (!panelRef || element === null) return false;
+ return panelRef === element || panelRef.contains(element);
+ };
+
+ const focusSplitById = (id: SplitId) => {
+ const splitPanelRef = props.panelRefs.get(id);
+ if (!splitPanelRef) {
+ console.warn(`Tried to focus split with id ${id} but it doesn't exist`);
+ return;
+ }
+
+ // return if panel has a child already with focus.
+ if (
+ splitPanelRef.contains(document.activeElement) &&
+ splitPanelRef !== document.activeElement
+ )
+ return;
+
+ // look for a child to return focus to.
+ const child = lastFocusedChildBySplitId.get(id);
+ if (child && child.isConnected) {
+ child.focus();
+ return;
+ }
+
+ splitPanelRef.focus();
+ };
+
+ const activateFocusedSplit = (element: Element) => {
+ const splitId = activeSplitId();
+ if (!splitId) return;
+
+ const doesActiveSplitHaveFocus = isElementInPanel(splitId, element);
+
+ if (doesActiveSplitHaveFocus) {
+ return;
+ }
+
+ let splitWithFocus: SplitId | undefined;
+ // Only visible splits may claim activation — the mobile background
+ // split is excluded and can never become active.
+ for (const split of props.splitManager.getVisibleSplits()) {
+ if (isElementInPanel(split.id, element)) {
+ splitWithFocus = split.id;
+ break;
+ }
+ }
+
+ if (splitWithFocus) {
+ props.splitManager.activateSplit(splitWithFocus);
+ }
+ };
+
+ const findNextSplitToActivate = (splitIndex: number): SplitId | undefined => {
+ const nextSplitId =
+ splitIndex === 0
+ ? props.splits()[0].id
+ : props.splits()[splitIndex - 1].id;
+
+ return nextSplitId;
+ };
+
+ const focusFromEvent = (event: SplitEventWithType) => {
+ switch (event.type) {
+ case SplitEvent.Insert: {
+ if (event.activate === false) break;
+ // A fresh load replays its last Insert event once this tracker
+ // mounts, and the last URL split is often a restored Preview Pair's
+ // Viewer. The Viewer displays content passively while its Controller
+ // owns the keyboard (restorePreviewPair already returned activation
+ // to it), so initial focus follows the Controller too.
+ const splitId =
+ props.splitManager.controllerOf(event.splitId) ?? event.splitId;
+ focusSplitById(splitId);
+ break;
+ }
+ case SplitEvent.Remove: {
+ const splitId = findNextSplitToActivate(event.splitIndex);
+ if (splitId) {
+ focusSplitById(splitId);
+ }
+ break;
+ }
+ }
+ };
+
+ // Both of these effects need to be debounced to prevent race conditions.
+ // The button for creating a new split itself is in a SplitPanel. This means that without the debounce,
+ // the button in the old split might trigger another focus event and re-active the old split.
+ let focusTimeout: ReturnType<typeof setTimeout> | undefined;
+ let activateTimeout: ReturnType<typeof setTimeout> | undefined;
+ let lastProgrammaticActivation = 0;
+
+ // Disposal must cancel pending debounced work so it cannot focus stale
+ // panels or activate splits on a torn-down manager after unmount.
+ onCleanup(() => {
+ clearTimeout(focusTimeout);
+ clearTimeout(activateTimeout);
+ });
+
+ /** Listens for explicit events from layoutManager that might trigger focus changes */
+ createEffect(
+ on(
+ () => props.splitManager.events(),
+ (newEvent) => {
+ if (focusTimeout) {
+ clearTimeout(focusTimeout);
+ }
+ if (newEvent.type === SplitEvent.ReturnFocus) {
+ const id = props.splitManager.activeSplitId();
+ if (id) {
+ focusSplitById(id);
+ }
+ return;
+ }
+ focusTimeout = setTimeout(() => {
+ focusFromEvent(newEvent);
+ }, DEBOUNCE);
+ }
+ )
+ );
+
+ /** Track when splits are programmatically activated */
+ createEffect(
+ on(activeSplitId, () => {
+ lastProgrammaticActivation = Date.now();
+ })
+ );
+
+ /** Listens for focus changes on the document */
+ createEffect(
+ on(activeElement, (element) => {
+ if (activateTimeout) {
+ clearTimeout(activateTimeout);
+ }
+ if (!element) return;
+
+ const parentId = getParentSplitId(element);
+ if (
+ parentId &&
+ element instanceof HTMLElement &&
+ !element.closest('[data-no-focus-restore]')
+ ) {
+ lastFocusedChildBySplitId.set(parentId, element);
+ }
+
+ activateTimeout = setTimeout(() => {
+ const timeSinceActivation = Date.now() - lastProgrammaticActivation;
+
+ // If a split was just programmatically activated, ignore this focus change
+ if (timeSinceActivation < DEBOUNCE + 50) {
+ return;
+ }
+
+ activateFocusedSplit(element);
+ }, DEBOUNCE);
+ })
+ );
+
+ return { focusSplitById };
+}
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
new file mode 100644
index 0000000000..4e8613211b
--- /dev/null
+++ b/apps/web/src/components/app/split-layout/tests/splitFocusTracker.test.ts
@@ -0,0 +1,141 @@
+import type { BlockOrchestrator } from '@core/orchestrator';
+import { createRoot } from 'solid-js';
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import { createSplitLayout, type SplitId } from '../layoutManager';
+import { restorePreviewPairs } from '../layoutUrlSync';
+import { createSplitFocusTracker } from '../splitFocusTracker';
+
+vi.mock('../componentRegistry', () => ({
+ resolveComponent: vi.fn((id: string, params: Record<string, string>) => ({
+ type: 'mock-component',
+ id,
+ params,
+ })),
+}));
+
+vi.mock('@core/constant/allBlocks', () => ({
+ isBlockAlias: vi.fn(() => false),
+ resolveBlockAlias: vi.fn((type: string) => type),
+}));
+
+beforeAll(() => {
+ 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 {
+ createBlockInstance: vi.fn((_type, id, _splitId) => ({
+ node: { type: 'mock-node', id },
+ detach: vi.fn(),
+ dispose: vi.fn(),
+ })),
+ } as unknown as BlockOrchestrator;
+}
+
+function createPanel(): HTMLDivElement {
+ const panel = document.createElement('div');
+ panel.tabIndex = -1;
+ document.body.appendChild(panel);
+ return panel;
+}
+
+/** Covers the tracker's Insert focus, debounced by 40ms. */
+const FOCUS_DEBOUNCE_MS = 50;
+
+/**
+ * Reproduce the fresh-load wiring of SplitLayoutContainer: the manager comes
+ * up from URL contents (last split active), Preview Pairs restore, and only
+ * then does the focus tracker mount and process the trailing Insert event.
+ */
+function mountFreshLoad(options: { withPreviewPair: boolean }) {
+ return createRoot((dispose) => {
+ const manager = createSplitLayout(createMockOrchestrator(), [
+ { type: 'component', id: 'inbox' },
+ { type: 'md', id: 'doc-1' },
+ ]);
+ if (options.withPreviewPair) {
+ restorePreviewPairs(manager, [{ controllerIndex: 0 }]);
+ }
+
+ const panelRefs = new Map<SplitId, HTMLDivElement>(
+ manager.splits().map((split) => [split.id, createPanel()])
+ );
+
+ createSplitFocusTracker({
+ splitManager: manager,
+ panelRefs,
+ splits: manager.splits,
+ });
+
+ return { dispose, manager, panelRefs };
+ });
+}
+
+describe('createSplitFocusTracker', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ });
+
+ it('moves fresh-load focus to the Controller when the last URL split is a Preview Pair Viewer', () => {
+ const { dispose, manager, panelRefs } = mountFreshLoad({
+ withPreviewPair: true,
+ });
+ const [controller, viewer] = manager.splits();
+
+ vi.advanceTimersByTime(FOCUS_DEBOUNCE_MS);
+
+ expect(manager.controllerOf(viewer.id)).toBe(controller.id);
+ expect(document.activeElement).toBe(panelRefs.get(controller.id));
+ expect(manager.activeSplitId()).toBe(controller.id);
+
+ dispose();
+ });
+
+ it('cancels pending debounced focus when its owner is disposed', () => {
+ const { dispose } = mountFreshLoad({ withPreviewPair: true });
+
+ dispose();
+ vi.advanceTimersByTime(FOCUS_DEBOUNCE_MS);
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('keeps fresh-load focus on the last split when it is not a Viewer', () => {
+ const { dispose, manager, panelRefs } = mountFreshLoad({
+ withPreviewPair: false,
+ });
+ const [, last] = manager.splits();
+
+ vi.advanceTimersByTime(FOCUS_DEBOUNCE_MS);
+
+ expect(document.activeElement).toBe(panelRefs.get(last.id));
+ expect(manager.activeSplitId()).toBe(last.id);
+
+ dispose();
+ });
+});