Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

8.3 KB
Raw Blame
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { DocLinkFindingsState } from '@/editor/validation-audit-client';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
  expectVisualClassTokens,
  expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';

type WindowGlobals = { NodeFilter?: typeof NodeFilter };
type GlobalWithDomShims = typeof globalThis &
  WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
const g = globalThis as GlobalWithDomShims;
if (g.NodeFilter === undefined && g.window?.NodeFilter !== undefined) {
  g.NodeFilter = g.window.NodeFilter;
}
if (g.ResizeObserver === undefined) {
  class NoopResizeObserver {
    observe() {}
    unobserve() {}
    disconnect() {}
  }
  g.ResizeObserver = NoopResizeObserver;
}

import * as actualLinguiMacro from '@lingui/react/macro';

vi.doMock('@lingui/core/macro', () => ({
  ...actualLinguiMacro,
  t: renderLinguiTemplate,
  msg: renderLinguiTemplate,
}));
vi.doMock('@lingui/react/macro', () => ({
  ...actualLinguiMacro,
  Trans: ({ children }: { children: ReactNode }) => children,
  useLingui: () => ({ t: renderLinguiTemplate }),
}));

let singleFileValue = false;
vi.doMock('@/lib/single-file-mode', () => ({ useSingleFileMode: () => singleFileValue }));

let diagnosticsValue: Array<{ severity: string }> = [];
let activeProviderValue: unknown = null;
vi.doMock('@/editor/DocumentContext', () => ({
  useDocumentContext: () => ({ activeProvider: activeProviderValue, activeDocName: 'notes' }),
}));
vi.doMock('@/editor/lint-config-client', () => ({
  useDocLintConfig: () => ({ data: null }),
}));
vi.doMock('@/editor/useDocDiagnostics', () => ({
  useDocDiagnostics: () => diagnosticsValue,
}));
let docLinkFindingsValue: DocLinkFindingsState = { status: 'loaded', findings: [] };
vi.doMock('@/editor/validation-audit-client', () => ({
  AUDIT_SUPERSEDED: 'audit-superseded',
  runValidationAudit: async () => null,
  useDocLinkFindings: () => docLinkFindingsValue,
}));
let terminalLaunchValue: unknown = null;
vi.doMock('@/components/handoff/TerminalLaunchContext', () => ({
  useTerminalLaunch: () => terminalLaunchValue,
}));

vi.doMock('@/components/OutlinePanel', () => ({
  OutlinePanel: () => <div data-testid="outline-panel" />,
}));
vi.doMock('@/components/LinksPanel', () => ({
  LinksPanel: () => <div data-testid="links-panel" />,
}));
vi.doMock('@/components/TimelinePanel', () => ({
  TimelineContent: () => <div data-testid="timeline-panel" />,
}));
let lastProblemsProps: Record<string, unknown> | null = null;
vi.doMock('@/components/ProblemsPanel', () => ({
  ProblemsPanel: (props: Record<string, unknown>) => {
    lastProblemsProps = props;
    return <div data-testid="problems-panel" />;
  },
}));

const { DocPanel } = await import('./DocPanel');

type Tab = 'outline' | 'links' | 'graph' | 'timeline' | 'problems';

function renderPanel(activeTab: Tab) {
  return render(
    <TooltipProvider>
      <DocPanel
        docName="notes"
        isSourceMode={false}
        activeTab={activeTab}
        onActiveTabChange={() => {}}
        mode="doc"
      />
    </TooltipProvider>,
  );
}

afterEach(() => {
  cleanup();
  singleFileValue = false;
  diagnosticsValue = [];
  activeProviderValue = null;
  terminalLaunchValue = null;
  lastProblemsProps = null;
  docLinkFindingsValue = { status: 'loaded', findings: [] };
});

describe('DocPanel — tab gating', () => {
  test('project mode renders the full tab strip (outline + links + graph + timeline + problems + comments)', () => {
    singleFileValue = false;
    renderPanel('outline');
    expect(screen.getAllByRole('tab')).toHaveLength(6);
    expect(screen.getByTestId('outline-panel')).toBeTruthy();
  });

  test('single-file mode keeps Outline + Problems + Comments', () => {
    singleFileValue = true;
    renderPanel('graph');
    expect(screen.getAllByRole('tab')).toHaveLength(3);
    expect(screen.getByRole('tab', { name: /comments/i })).toBeTruthy();
    expect(screen.getByTestId('outline-panel')).toBeTruthy();
  });

  test('renders the Problems panel when its tab is active, against the active doc', () => {
    renderPanel('problems');
    expect(screen.getByTestId('problems-panel')).toBeTruthy();
    expect(lastProblemsProps?.docName).toBe('notes');
    expect(screen.getByRole('tabpanel').getAttribute('id')).toBe('panel-problems');
  });

  test('forwards reserved-log suppression from the document audit to Problems', () => {
    docLinkFindingsValue = {
      status: 'loaded',
      findings: [],
      brokenLinkSuppression: { reason: 'reserved-log-policy', count: 2 },
    };

    renderPanel('problems');

    expect(lastProblemsProps?.brokenLinkSuppression).toEqual({
      reason: 'reserved-log-policy',
      count: 2,
    });
  });
});

describe('DocPanel — Problems fix/ask-ai wiring', () => {
  const fakeProvider = { document: { getText: () => ({ toString: () => '' }) } };

  test('web host (no terminal launch context) withholds onAskAi but keeps the fix handlers', () => {
    activeProviderValue = fakeProvider;
    terminalLaunchValue = null;
    renderPanel('problems');
    expect(lastProblemsProps?.onAskAi).toBeUndefined();
    expect(typeof lastProblemsProps?.onFix).toBe('function');
    expect(typeof lastProblemsProps?.onAutoFix).toBe('function');
    expect(lastProblemsProps?.onFixWithAi).toBeUndefined();
  });

  test('desktop host (terminal launch available) passes onAskAi alongside the fix handlers', () => {
    activeProviderValue = fakeProvider;
    terminalLaunchValue = { launchInTerminal: () => {}, installedClis: {} };
    renderPanel('problems');
    expect(typeof lastProblemsProps?.onAskAi).toBe('function');
    expect(typeof lastProblemsProps?.onAutoFix).toBe('function');
    expect(typeof lastProblemsProps?.onFixWithAi).toBe('function');
  });

  test('without a matching provider every fix/ask handler is withheld', () => {
    activeProviderValue = null;
    terminalLaunchValue = { launchInTerminal: () => {}, installedClis: {} };
    renderPanel('problems');
    expect(lastProblemsProps?.onFix).toBeUndefined();
    expect(lastProblemsProps?.onAutoFix).toBeUndefined();
    expect(lastProblemsProps?.onAskAi).toBeUndefined();
    expect(typeof lastProblemsProps?.onFixWithAi).toBe('function');
  });
});

describe('DocPanel — Problems badge', () => {
  test('no badge when there are no diagnostics', () => {
    diagnosticsValue = [];
    renderPanel('outline');
    expect(screen.queryByText('3')).toBeNull();
  });

  test('shows the diagnostic count on the Problems tab', () => {
    diagnosticsValue = [{ severity: 'warning' }, { severity: 'error' }, { severity: 'warning' }];
    renderPanel('outline');
    expect(screen.getByText('3')).toBeTruthy();
  });

  test('caps the badge at 99+', () => {
    diagnosticsValue = Array.from({ length: 150 }, () => ({ severity: 'warning' }));
    renderPanel('outline');
    expect(screen.getByText('99+')).toBeTruthy();
  });
});

describe('DocPanel — card top bar', () => {
  afterEach(() => {
    Reflect.deleteProperty(window, 'okDesktop');
  });

  test('the icon row is a 44px top bar with no hairline under it', () => {
    renderPanel('outline');
    const header = document.querySelector('[data-doc-panel-header]');
    expectVisualClassTokens(header?.getAttribute('class'), ['h-11', 'shrink-0']);
    expectVisualClassTokensAbsent(header?.getAttribute('class'), [
      'pe-9',
      '[-webkit-app-region:drag]',
      'shadow-[inset_0_-1px_0_var(--border)]',
    ]);
    expect(header?.contains(screen.getByRole('tab', { name: 'Outline' }))).toBe(true);
  });

  test('on desktop the empty top bar drags the window while the tab buttons opt out', () => {
    Object.defineProperty(window, 'okDesktop', {
      configurable: true,
      value: { config: { mode: 'editor' } },
    });
    renderPanel('outline');
    const header = document.querySelector('[data-doc-panel-header]');
    expect(header?.getAttribute('data-electron-drag')).toBe('');
    expectVisualClassTokens(header?.getAttribute('class'), ['[-webkit-app-region:drag]']);
    expectVisualClassTokens(
      screen
        .getByRole('tab', { name: 'Outline' })
        .closest('[data-slot="toggle-group"]')
        ?.getAttribute('class'),
      ['[-webkit-app-region:no-drag]'],
    );
  });
});