Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

28.2 KB
Raw Blame
import { EditorSelection } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Config } from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, waitFor, within } from '@testing-library/react';
import { Activity } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
import {
  OUTLINE_NAV_BREADCRUMB,
  OUTLINE_NAV_EVENT,
  type OutlineNavDetail,
} from '@/components/OutlinePanel';
import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';
import { FULL_PAGE_CM_HOST_SELECTORS } from '@/editor/document-scrollports';
import { getFullPageCmEntryForDoc } from '@/editor/full-page-cm-views';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { evictCmEditor } from './editor-cache';
import type { LandingHandle } from './landing-controller';
import { applyRawMdxNavigation, SourceEditor } from './SourceEditor';
import {
  __resetScrollRestoreCoordination,
  registerLandingScrollOwner,
} from './scroll-restore-coordination';
import {
  clearPendingSourceNavigationsForTest,
  peekPendingSourceNavigation,
  rememberPendingSourceNavigation,
  type SelectionOffsetNavigation,
} from './source-editor-navigation';

const landingOverride = vi.hoisted(() => ({
  start: null as (() => LandingHandle | null) | null,
}));

vi.mock('./mode-switch-landing', async (importOriginal) => {
  const actual = await importOriginal<typeof import('./mode-switch-landing')>();
  return {
    ...actual,
    startSourceLanding: (params: Parameters<typeof actual.startSourceLanding>[0]) =>
      landingOverride.start ? landingOverride.start() : actual.startSourceLanding(params),
  };
});

const appLanguage = vi.hoisted(() => {
  const english = (text: string) => text;
  let translate = english;
  const listeners = new Set<() => void>();
  return {
    current: () => translate,
    subscribe(listener: () => void) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    switchTo(next: (text: string) => string) {
      translate = next;
      for (const listener of listeners) listener();
    },
    reset() {
      translate = english;
    },
  };
});

vi.mock('@lingui/react/macro', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@lingui/react/macro')>();
  const { useSyncExternalStore } = await import('react');
  const { renderLinguiTemplate } = await import('@/test-utils/lingui-mock');
  return {
    ...actual,
    useLingui: () => {
      const translate = useSyncExternalStore(appLanguage.subscribe, appLanguage.current);
      return {
        ...actual.useLingui(),
        t: (...args: Parameters<typeof renderLinguiTemplate>) =>
          translate(renderLinguiTemplate(...args)),
      };
    },
  };
});

const originalFetch = globalThis.fetch;
(globalThis as { Window?: typeof window.Window }).Window = window.Window;
Object.defineProperty(window.Range.prototype, 'getClientRects', {
  configurable: true,
  value: () => [],
});
Object.defineProperty(window.Range.prototype, 'getBoundingClientRect', {
  configurable: true,
  value: () => ({ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }),
});

const mountedDocNames = new Set<string>();

let composerOpenRequests = 0;
let unsubscribeComposer: (() => void) | null = null;

function makeConfigValue(wordWrap: boolean): ConfigContextValue {
  return {
    userBinding: null,
    userSynced: false,
    projectBinding: null,
    projectLocalBinding: null,
    okignoreBinding: null,
    okignoreSynced: false,
    userConfig: null,
    projectConfig: null,
    projectLocalConfig: null,
    projectSynced: false,
    projectLocalSynced: false,
    merged: { editor: { wordWrap } } as Config,
  };
}

function makeProvider(
  docName: string,
  content = '# heading\n\nbody',
): { provider: HocuspocusProvider; ytext: Y.Text } {
  const document = new Y.Doc();
  const ytext = document.getText('source');
  ytext.insert(0, content);
  const awareness = new Awareness(document);
  const provider = {
    document,
    awareness,
    configuration: { name: docName },
    destroy: () => {
      awareness.destroy();
      document.destroy();
    },
  } as unknown as HocuspocusProvider;
  mountedDocNames.add(docName);
  return { provider, ytext };
}

function Harness({
  provider,
  ytext,
  wordWrap,
}: {
  provider: HocuspocusProvider;
  ytext: Y.Text;
  wordWrap: boolean;
}) {
  return (
    <ConfigContext value={makeConfigValue(wordWrap)}>
      <SourceEditor
        docName={provider.configuration.name ?? 'test-source'}
        ytext={ytext}
        provider={provider}
        isSourceModeActive
      />
    </ConfigContext>
  );
}

async function findCmContent(container: HTMLElement): Promise<HTMLElement> {
  await waitFor(() => {
    expect(container.querySelector('.cm-content')).toBeTruthy();
  });
  return container.querySelector<HTMLElement>('.cm-content');
}

const ORIGINAL_PLATFORM = globalThis.navigator.platform;

function setPlatform(platform: string): void {
  Object.defineProperty(globalThis.navigator, 'platform', {
    value: platform,
    configurable: true,
  });
}

describe('SourceEditor host contract', () => {
  test('names the CodeMirror textbox', async () => {
    const { provider, ytext } = makeProvider('source-editor-accessible-name');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    const content = await findCmContent(container);

    expect(within(container).getByRole('textbox', { name: /\S/ })).toBe(content);
  });

  test('renames the mounted CodeMirror textbox when the app language changes', async () => {
    const { provider, ytext } = makeProvider('source-editor-language-switch');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);
    const content = await findCmContent(container);
    expect(within(container).getByRole('textbox', { name: 'Markdown source' })).toBe(content);

    const french: Record<string, string> = { 'Markdown source': 'Source Markdown' };
    act(() => {
      appLanguage.switchTo((text) => french[text] ?? text);
    });

    expect(within(container).getByRole('textbox', { name: 'Source Markdown' })).toBe(content);
  });

  afterEach(() => {
    cleanup();
    appLanguage.reset();
    for (const docName of mountedDocNames) {
      evictCmEditor(docName);
    }
    mountedDocNames.clear();
  });

  test('renders the host class used by the composer-inset selector', async () => {
    const { provider, ytext } = makeProvider('source-composer-inset-host');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    await findCmContent(container);

    expect(container.querySelector(FULL_PAGE_CM_HOST_SELECTORS.sourceEditor)).not.toBeNull();
  });

  test('registers its CodeMirror under the sourceEditor host while it is mounted', async () => {
    const docName = 'source-full-page-cm-host';
    const { provider, ytext } = makeProvider(docName);
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    await findCmContent(container);
    const entry = getFullPageCmEntryForDoc(docName);

    expect(
      entry?.host,
      'the host this component records is what picks its scrollport, and `sourceEditor` is the ' +
        'only one that resolves through an ANCESTOR. Recording any other host sends the caret ' +
        'reveal at this surface own `.cm-scroller`, which never scrolls, and drops markdown out ' +
        'of `getMarkdownSourceViewForDoc` so the outline and the mode-switch landing anchor go ' +
        'with it',
    ).toBe('sourceEditor');
    expect(
      entry?.view.scrollDOM,
      'the registered view must be the CodeMirror this component mounted',
    ).toBe(container.querySelector(`${FULL_PAGE_CM_HOST_SELECTORS.sourceEditor} .cm-scroller`));
  });
});

describe('SourceEditor word-wrap preference wiring', () => {
  beforeEach(() => {
    composerOpenRequests = 0;
    unsubscribeComposer = subscribeToOpenAskAiComposer(() => {
      composerOpenRequests += 1;
    });
    globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
      const url = String(input);
      if (url === '/api/pages') return Response.json({ pages: [] });
      if (url === '/api/documents') return Response.json({ documents: [] });
      if (url === '/api/tags') return Response.json({ tags: [] });
      return Response.json({}, { status: 404 });
    }) as unknown as typeof fetch;
  });

  afterEach(() => {
    setPlatform(ORIGINAL_PLATFORM);
    unsubscribeComposer?.();
    unsubscribeComposer = null;
    cleanup();
    for (const docName of mountedDocNames) {
      evictCmEditor(docName);
    }
    mountedDocNames.clear();
    globalThis.fetch = originalFetch;
  });

  test('applies editor.wordWrap to the source CodeMirror instance', async () => {
    const { provider, ytext } = makeProvider('source-word-wrap-off');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={false} />);

    const content = await findCmContent(container);

    expect(content.classList.contains('cm-lineWrapping')).toBe(false);
  });

  test('hot-swaps source CodeMirror line wrapping without remounting', async () => {
    const { provider, ytext } = makeProvider('source-word-wrap-hot-swap');
    const { container, rerender } = render(
      <Harness provider={provider} ytext={ytext} wordWrap={true} />,
    );

    const content = await findCmContent(container);
    const cmEditor = container.querySelector('.cm-editor');
    expect(content.classList.contains('cm-lineWrapping')).toBe(true);

    rerender(<Harness provider={provider} ytext={ytext} wordWrap={false} />);

    await waitFor(() => {
      expect(content.classList.contains('cm-lineWrapping')).toBe(false);
    });
    expect(container.querySelector('.cm-editor')).toBe(cmEditor);
  });

  test('Cmd+Shift+I no longer opens the Ask AI composer', async () => {
    setPlatform('MacIntel');
    const { provider, ytext } = makeProvider('source-edit-with-ai-retired');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    const content = await findCmContent(container);
    const view = EditorView.findFromDOM(content);
    expect(view).toBeTruthy();
    view?.dispatch({ selection: EditorSelection.range(2, 9) });

    await act(async () => {
      content.dispatchEvent(
        new KeyboardEvent('keydown', {
          key: 'I',
          code: 'KeyI',
          metaKey: true,
          shiftKey: true,
          bubbles: true,
          cancelable: true,
        }),
      );
    });

    expect(composerOpenRequests).toBe(0);
  });
});

describe('SourceEditor outline navigation', () => {
  beforeEach(() => {
    globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
      const url = String(input);
      if (url === '/api/pages') return Response.json({ pages: [] });
      if (url === '/api/documents') return Response.json({ documents: [] });
      if (url === '/api/tags') return Response.json({ tags: [] });
      return Response.json({}, { status: 404 });
    }) as unknown as typeof fetch;
  });

  afterEach(() => {
    cleanup();
    for (const docName of mountedDocNames) {
      evictCmEditor(docName);
    }
    mountedDocNames.clear();
    globalThis.fetch = originalFetch;
  });

  async function dispatchOutlineNav(docName: string, index: number, slug: string): Promise<void> {
    const detail: OutlineNavDetail = { docName, index, slug, mode: 'source' };
    await act(async () => {
      window.dispatchEvent(new CustomEvent(OUTLINE_NAV_EVENT, { detail }));
    });
  }

  test('only the source editor matching the navigation document moves its cursor', async () => {
    const first = makeProvider('source-outline-owner', '# First\n\n## First target');
    const second = makeProvider('source-outline-bystander', '# Second\n\n## Second target');
    const { container } = render(
      <>
        <Harness provider={first.provider} ytext={first.ytext} wordWrap={true} />
        <Harness provider={second.provider} ytext={second.ytext} wordWrap={true} />
      </>,
    );

    await waitFor(() => {
      expect(container.querySelectorAll('.cm-content')).toHaveLength(2);
    });
    const [firstContent, secondContent] = container.querySelectorAll<HTMLElement>('.cm-content');
    const firstView = EditorView.findFromDOM(firstContent);
    const secondView = EditorView.findFromDOM(secondContent);
    expect(firstView).toBeTruthy();
    expect(secondView).toBeTruthy();
    if (!firstView || !secondView) return;

    const secondSelectionBefore = secondView.state.selection.main.head;
    await act(async () => {
      window.dispatchEvent(
        new CustomEvent(OUTLINE_NAV_EVENT, {
          detail: {
            docName: 'source-outline-owner',
            index: 1,
            slug: 'first-target',
            mode: 'source',
          } satisfies OutlineNavDetail,
        }),
      );
    });

    expect(firstView.state.selection.main.head).toBe(firstView.state.doc.line(3).from);
    expect(secondView.state.selection.main.head).toBe(secondSelectionBefore);
  });

  test('skips a frontmatter region whose opening fence carries a trailing space', async () => {
    const content = [
      '--- ',
      'title: Fence hazard',
      '# yaml comment, not a heading',
      '---',
      '',
      '# Real Heading',
      '',
      'body',
    ].join('\n');
    const { provider, ytext } = makeProvider('source-outline-nav-fm-ws', content);
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    const cmContent = await findCmContent(container);
    const view = EditorView.findFromDOM(cmContent);
    expect(view).toBeTruthy();
    if (!view) return;

    await dispatchOutlineNav('source-outline-nav-fm-ws', 0, 'real-heading');

    const headingLine = view.state.doc.line(6);
    expect(headingLine.text).toBe('# Real Heading');
    expect(view.state.selection.main.head).toBe(headingLine.from);
  });

  test('skips a frontmatter region whose closing fence carries a trailing tab', async () => {
    const content = [
      '---',
      'title: Fence hazard',
      '# yaml comment, not a heading',
      '---\t',
      '',
      '# Real Heading',
    ].join('\n');
    const { provider, ytext } = makeProvider('source-outline-nav-fm-close-ws', content);
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    const cmContent = await findCmContent(container);
    const view = EditorView.findFromDOM(cmContent);
    expect(view).toBeTruthy();
    if (!view) return;

    await dispatchOutlineNav('source-outline-nav-fm-close-ws', 0, 'real-heading');

    const headingLine = view.state.doc.line(6);
    expect(headingLine.text).toBe('# Real Heading');
    expect(view.state.selection.main.head).toBe(headingLine.from);
  });

  test('bare fences: jumps to the Nth heading after the FM region (regression control)', async () => {
    const content = [
      '---',
      'title: Fence hazard',
      '# yaml comment, not a heading',
      '---',
      '',
      '# First',
      '',
      '## Second',
    ].join('\n');
    const { provider, ytext } = makeProvider('source-outline-nav-fm-bare', content);
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);

    const cmContent = await findCmContent(container);
    const view = EditorView.findFromDOM(cmContent);
    expect(view).toBeTruthy();
    if (!view) return;

    await dispatchOutlineNav('source-outline-nav-fm-bare', 1, 'second');

    const headingLine = view.state.doc.line(8);
    expect(headingLine.text).toBe('## Second');
    expect(view.state.selection.main.head).toBe(headingLine.from);
  });

  describe('breadcrumb', () => {
    let infoSpy: ReturnType<typeof vi.spyOn>;

    beforeEach(() => {
      __resetScrollRestoreCoordination();
      infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined);
    });

    afterEach(() => {
      __resetScrollRestoreCoordination();
      vi.restoreAllMocks();
    });

    function breadcrumbs(): Array<Record<string, unknown>> {
      return infoSpy.mock.calls.flatMap(([first]) => {
        if (typeof first !== 'string') return [];
        let parsed: Record<string, unknown>;
        try {
          parsed = JSON.parse(first) as Record<string, unknown>;
        } catch {
          return [];
        }
        return parsed.event === OUTLINE_NAV_BREADCRUMB ? [parsed] : [];
      });
    }

    async function mountSource(docName: string, content: string): Promise<void> {
      const { provider, ytext } = makeProvider(docName, content);
      const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);
      await findCmContent(container);
    }

    test('a jump reports the line it landed on', async () => {
      await mountSource('source-outline-crumb', '# First\n\n## Second\n\n## Third');
      await dispatchOutlineNav('source-outline-crumb', 2, 'third');
      expect(breadcrumbs()).toEqual([
        expect.objectContaining({
          docName: 'source-outline-crumb',
          mode: 'source',
          index: 2,
          sourceHeadingCount: 3,
          outcome: 'scrolled',
          targetLine: 5,
        }),
      ]);
    });

    test('a declined claim is recorded rather than read as a completed jump', async () => {
      await mountSource('source-outline-crumb-declined', '# First\n\n## Second');
      registerLandingScrollOwner('source-outline-crumb-declined', {
        yieldsToNavigation: false,
        supersede: () => {},
      });
      await dispatchOutlineNav('source-outline-crumb-declined', 1, 'second');
      expect(breadcrumbs()).toEqual([
        expect.objectContaining({ mode: 'source', index: 1, outcome: 'declined' }),
      ]);
    });

    test('an out-of-range ordinal reports the count that made it out of range', async () => {
      await mountSource('source-outline-crumb-range', '# Only');
      await dispatchOutlineNav('source-outline-crumb-range', 7, 'nowhere');
      expect(breadcrumbs()).toEqual([
        expect.objectContaining({ index: 7, sourceHeadingCount: 1, outcome: 'no-target' }),
      ]);
    });
  });
});

describe('SourceEditor raw-MDX replay mode re-check', () => {
  interface FakeCmView {
    state: { doc: { length: number } };
    dispatch: (spec: unknown) => void;
    focus: () => void;
    dispatched: unknown[];
  }

  function fakeCmView(docLength = 100): FakeCmView {
    const dispatched: unknown[] = [];
    return {
      state: { doc: { length: docLength } },
      dispatch: (spec) => {
        dispatched.push(spec);
      },
      focus: () => {},
      dispatched,
    };
  }

  const nextFrame = () =>
    new Promise<void>((resolve) => {
      requestAnimationFrame(() => resolve());
    });

  const NAV_DOC = 'raw-mdx-doc';

  beforeEach(() => {
    __resetScrollRestoreCoordination();
  });

  afterEach(() => {
    __resetScrollRestoreCoordination();
  });

  test('does not dispatch when the editor left source mode before the frame ran', async () => {
    const view = fakeCmView();
    applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => false, NAV_DOC);
    await nextFrame();
    expect(view.dispatched).toHaveLength(0);
  });

  test('dispatches the navigation when still in source mode', async () => {
    const view = fakeCmView();
    applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);
    await nextFrame();
    expect(view.dispatched).toHaveLength(1);
  });

  test('supersedes a position-preserving landing still holding the scroller', async () => {
    const supersede = vi.fn();
    registerLandingScrollOwner(NAV_DOC, { yieldsToNavigation: true, supersede });
    const view = fakeCmView();

    applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);
    await nextFrame();

    expect(supersede).toHaveBeenCalledTimes(1);
    expect(view.dispatched).toHaveLength(1);
  });

  test('stands down while a landing that is itself a navigation owns the scroller', async () => {
    registerLandingScrollOwner(NAV_DOC, { yieldsToNavigation: false, supersede: vi.fn() });
    const view = fakeCmView();

    applyRawMdxNavigation(view as unknown as EditorView, { offset: 42 }, () => true, NAV_DOC);
    await nextFrame();

    expect(view.dispatched).toHaveLength(0);
  });
});

describe('SourceEditor cross-mode landing replay', () => {
  const NAVIGATION: SelectionOffsetNavigation = {
    kind: 'selection-offset',
    intent: 'jump',
    anchor: { blockIndex: 0, kind: 'heading', content: 'heading' },
  };

  beforeEach(() => {
    clearPendingSourceNavigationsForTest();
    globalThis.fetch = vi.fn(async () => Response.json({})) as unknown as typeof fetch;
  });

  afterEach(() => {
    landingOverride.start = null;
    clearPendingSourceNavigationsForTest();
    cleanup();
    for (const docName of mountedDocNames) evictCmEditor(docName);
    mountedDocNames.clear();
    globalThis.fetch = originalFetch;
  });

  async function mountWithQueuedJump(docName: string): Promise<void> {
    const { provider, ytext } = makeProvider(docName);
    rememberPendingSourceNavigation(docName, NAVIGATION);
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);
    await findCmContent(container);
    await act(async () => {});
  }

  test('keeps the jump banked when no landing could start', async () => {
    landingOverride.start = () => null;

    await mountWithQueuedJump('source-landing-declined');

    expect(peekPendingSourceNavigation('source-landing-declined')).toEqual(NAVIGATION);
  });

  test('consumes the jump once a landing owns it', async () => {
    landingOverride.start = () => ({ cancel: () => {} });

    await mountWithQueuedJump('source-landing-started');

    expect(peekPendingSourceNavigation('source-landing-started')).toBeNull();
  });
});

describe('SourceEditor Problems-row navigation', () => {
  const detailFor = (docName: string): LintNavDetail => ({ docName, line: 3, column: 1 });

  beforeEach(() => {
    __resetScrollRestoreCoordination();
    clearPendingSourceNavigationsForTest();
    globalThis.fetch = vi.fn(async () => Response.json({})) as unknown as typeof fetch;
  });

  afterEach(() => {
    __resetScrollRestoreCoordination();
    clearPendingSourceNavigationsForTest();
    cleanup();
    for (const docName of mountedDocNames) evictCmEditor(docName);
    mountedDocNames.clear();
    globalThis.fetch = originalFetch;
  });

  async function clickProblemsRow(docName: string): Promise<void> {
    const { provider, ytext } = makeProvider(docName, '# heading\n\nbody\n\nmore body');
    const { container } = render(<Harness provider={provider} ytext={ytext} wordWrap={true} />);
    await findCmContent(container);
    rememberPendingSourceNavigation(docName, { kind: 'lint', detail: detailFor(docName) });
    await act(async () => {
      window.dispatchEvent(new CustomEvent(LINT_NAV_EVENT, { detail: detailFor(docName) }));
    });
  }

  test('keeps the banked intent when a landing refuses the scroller', async () => {
    const docName = 'source-problems-row-refused';
    registerLandingScrollOwner(docName, { yieldsToNavigation: false, supersede: () => {} });

    await clickProblemsRow(docName);

    expect(peekPendingSourceNavigation(docName)).toEqual({
      kind: 'lint',
      detail: detailFor(docName),
    });
  });

  test('consumes it once the jump has run', async () => {
    const docName = 'source-problems-row-granted';

    await clickProblemsRow(docName);

    expect(peekPendingSourceNavigation(docName)).toBeNull();
  });
});

const FLIP_UNTRACKED_ORIGIN = Object.freeze({ kind: 'source-editor-dom-untracked-rewrite' });
const MOD_KEY: 'metaKey' | 'ctrlKey' = /Mac/.test(ORIGINAL_PLATFORM) ? 'metaKey' : 'ctrlKey';

function ActivityHarness({
  provider,
  ytext,
  visible,
  sourceMode = true,
}: {
  provider: HocuspocusProvider;
  ytext: Y.Text;
  visible: boolean;
  sourceMode?: boolean;
}) {
  return (
    <ConfigContext value={makeConfigValue(true)}>
      <Activity mode={visible ? 'visible' : 'hidden'}>
        <SourceEditor
          docName={provider.configuration.name ?? 'test-source'}
          ytext={ytext}
          provider={provider}
          isSourceModeActive={visible && sourceMode}
        />
      </Activity>
    </ConfigContext>
  );
}

async function pressUndo(content: HTMLElement): Promise<void> {
  await act(async () => {
    fireEvent.keyDown(content, { key: 'z', code: 'KeyZ', keyCode: 90, [MOD_KEY]: true });
  });
}

describe('SourceEditor undo after leaving and returning to source mode', () => {
  beforeEach(() => {
    globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
      const url = String(input);
      if (url === '/api/pages') return Response.json({ pages: [] });
      if (url === '/api/documents') return Response.json({ documents: [] });
      if (url === '/api/tags') return Response.json({ tags: [] });
      return Response.json({}, { status: 404 });
    }) as unknown as typeof fetch;
  });

  afterEach(() => {
    cleanup();
    for (const docName of mountedDocNames) {
      evictCmEditor(docName);
    }
    mountedDocNames.clear();
    globalThis.fetch = originalFetch;
  });

  async function mountAndType(docName: string): Promise<{
    ytext: Y.Text;
    content: HTMLElement;
    rerender: (state: { visible: boolean; sourceMode?: boolean }) => void;
  }> {
    const { provider, ytext } = makeProvider(docName, '');
    const view = render(<ActivityHarness provider={provider} ytext={ytext} visible={true} />);
    const content = await findCmContent(view.container);
    const cm = EditorView.findFromDOM(content);
    expect(cm).toBeTruthy();
    if (!cm) throw new Error('no CodeMirror view');
    await act(async () => {
      cm.dispatch({
        changes: { from: 0, insert: 'hello bug\n\n\nhello bug' },
        userEvent: 'input.type',
      });
    });
    expect(ytext.toString()).toBe('hello bug\n\n\nhello bug');
    return {
      ytext,
      content,
      rerender: ({ visible, sourceMode }: { visible: boolean; sourceMode?: boolean }) =>
        view.rerender(
          <ActivityHarness
            provider={provider}
            ytext={ytext}
            visible={visible}
            sourceMode={sourceMode}
          />,
        ),
    };
  }

  test('Cmd+Z after returning to a tab rewritten while hidden leaves the document unchanged', async () => {
    const { ytext, content, rerender } = await mountAndType('source-flip-activity-rewrite');

    await act(async () => rerender({ visible: false }));
    await act(async () => {
      ytext.doc?.transact(() => ytext.insert(ytext.length, ' oops'), FLIP_UNTRACKED_ORIGIN);
    });
    await act(async () => rerender({ visible: true }));

    const beforeUndo = ytext.toString();
    expect(beforeUndo).toBe('hello bug\n\n\nhello bug oops');

    await pressUndo(content);

    expect(ytext.toString()).toBe(beforeUndo);
  });

  test('Cmd+Z still undoes the pre-hide burst when nothing wrote while the tab was hidden', async () => {
    const { ytext, content, rerender } = await mountAndType('source-flip-activity-quiet');

    await act(async () => rerender({ visible: false }));
    await act(async () => rerender({ visible: true }));

    await pressUndo(content);

    expect(ytext.toString()).toBe('');
  });

  test('Cmd+Z after an in-pane flip to Visual and back over a rewrite leaves the document unchanged', async () => {
    const { ytext, content, rerender } = await mountAndType('source-flip-inpane-rewrite');

    await act(async () => rerender({ visible: true, sourceMode: false }));
    await act(async () => {
      ytext.doc?.transact(() => ytext.insert(ytext.length, ' oops'), FLIP_UNTRACKED_ORIGIN);
    });
    await act(async () => rerender({ visible: true, sourceMode: true }));

    const beforeUndo = ytext.toString();
    expect(beforeUndo).toBe('hello bug\n\n\nhello bug oops');

    await pressUndo(content);

    expect(ytext.toString()).toBe(beforeUndo);
  });

  test('Cmd+Z still undoes the pre-flip burst after an in-pane flip with no rewrite', async () => {
    const { ytext, content, rerender } = await mountAndType('source-flip-inpane-quiet');

    await act(async () => rerender({ visible: true, sourceMode: false }));
    await act(async () => rerender({ visible: true, sourceMode: true }));

    await pressUndo(content);

    expect(ytext.toString()).toBe('');
  });
});