Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

37.7 KB
Raw Blame
import { join } from 'node:path';
import { readFileSync } from 'node:fs';
import {
  darkTheme,
  defaultTheme,
  defaultAppearance,
  highContrastDarkTheme,
  highContrastLightTheme,
} from 'librechat-data-provider';
import type { IThemeAppearance, IThemeRGB } from 'librechat-data-provider';
import { clickHouseDarkTheme, clickHouseLightTheme, clickHouseTheme } from './themes/clickhouse';
import { fieldControl } from '../components/Field';

const sharedComponents = [
  'AnimatedSearchInput.tsx',
  'AlertDialog.tsx',
  'Button.tsx',
  'Chip.tsx',
  'SegmentedMeter.tsx',
  'IconButton.tsx',
  'OGDialogTemplate.tsx',
  'OriginalDialog.tsx',
  'Tag.tsx',
  'Toast.tsx',
];

const sharedDialogComponents = ['AlertDialog.tsx', 'OGDialogTemplate.tsx', 'OriginalDialog.tsx'];

describe('shared component color guardrail', () => {
  it('keeps shared primitives free of direct palette utilities and raw colors', () => {
    const directPalette =
      /(?:bg|text|border|ring|from|via|to|fill|stroke)-(?:(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d|white\b|black\b)/;
    /** Literal colors only: `rgb(var(--token))` reads the theme at paint time,
     *  which is exactly what a shared primitive is supposed to do. */
    const rawColor =
      /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})\b|(?:rgb|hsl)a?\((?!\s*var\()/i;
    /** Only CSS-legal hex lengths (3, 4, 6, 8). `{3,8}` also matched a five-
     *  digit issue reference in a comment — see the PR number in
     *  `OriginalDialog.tsx` — which reads as a color to a regex and to nobody
     *  else. */
    const hexColor = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})\b/i;

    sharedComponents.forEach((component) => {
      const source = readFileSync(join(__dirname, '..', 'components', component), 'utf8');

      expect(source).not.toMatch(directPalette);
      expect(source).not.toMatch(rawColor);
    });

    /** The guardrail still has to catch what it exists for. */
    expect('bg-surface-primary text-[#ff0000]').toMatch(hexColor);
    expect('color: #fff;').toMatch(hexColor);
    expect('#aabbccdd').toMatch(hexColor);
    /** …and leave prose alone: an issue reference is not a color. */
    expect('pinned by #11023').not.toMatch(hexColor);
    expect('closes #15738').not.toMatch(hexColor);
  });

  it('keeps every shared dialog shell on the semantic dialog surface', () => {
    sharedDialogComponents.forEach((component) => {
      const source = readFileSync(join(__dirname, '..', 'components', component), 'utf8');

      expect(source).toMatch(/\bbg-surface-dialog\b/);
    });
  });
});

describe('dark dialog surface', () => {
  it('matches the legacy rendered background in CSS and the runtime theme', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect(stockStyles).toMatch(/--gray-875:\s*18 18 18;/);
    expect(stockStyles).toMatch(/--surface-dialog:\s*var\(--gray-875\);/);
    expect(darkTheme['rgb-surface-dialog']).toBe('18 18 18');
  });
});

describe('dark hover surface', () => {
  it('uses the gray-650 midpoint in both CSS and the runtime theme', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect(stockStyles).toMatch(/--gray-650:\s*57 57 57;/);
    expect(stockStyles).toMatch(/--surface-hover:\s*var\(--gray-650\);/);
    expect(darkTheme['rgb-surface-hover']).toBe('57 57 57');
  });
});

describe('composer hover surface', () => {
  it('keeps light hover unchanged and uses the lighter dark hover surface', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect(stockStyles).toMatch(/--surface-composer-hover:\s*var\(--gray-200\);/);
    expect(stockStyles).toMatch(/--surface-composer-hover:\s*var\(--gray-600\);/);
    expect(defaultTheme['rgb-surface-composer-hover']).toBe('227 227 227');
    expect(darkTheme['rgb-surface-composer-hover']).toBe('66 66 66');
  });
});

describe('dark destructive text', () => {
  it('uses red-400 without changing the status error token', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect(stockStyles).toMatch(/--text-destructive:\s*var\(--red-400\);/);
    expect(darkTheme['rgb-text-destructive']).toBe('248 113 113');
    expect(darkTheme['rgb-status-error']).toBe('252 165 165');
  });
});

describe('light brand text', () => {
  it('uses the contrasting purple foreground in the default theme', () => {
    expect(defaultTheme['rgb-brand-purple']).toBe('126 34 206');
  });
});

describe('shared field and dropdown interaction styles', () => {
  it('keeps pointer focus stable and keyboard focus visible on text fields', () => {
    /** The focus treatment lives in the shared field module, so guard it there and
     *  assert the primitives still compose it rather than restating the classes. */
    const field = readFileSync(join(__dirname, '..', 'components', 'Field.ts'), 'utf8');

    expect(field).toMatch(/\bborder-border-control\b/);
    expect(field).not.toMatch(/\bborder-border-(?:light|medium)\b/);
    expect(field).toMatch(/focus-visible:ring-2/);
    expect(field).toMatch(/focus-visible:ring-focus-control/);
    /** The fill and ink classes the field-fill e2e scenarios probe in the browser. */
    expect(fieldControl.split(' ')).toEqual(
      expect.arrayContaining([
        'lc-field',
        'bg-transparent',
        'text-field-text',
        'theme-field-fill:bg-field-fill',
        'theme-field-fill:disabled:hover:bg-field-fill',
      ]),
    );

    const composers: Array<[string, RegExp]> = [
      ['Input.tsx', /\bfieldControl\b/],
      ['Textarea.tsx', /\bfieldBase\b/],
      ['Dropdown.tsx', /\bfieldControl\b/],
      ['ControlCombobox.tsx', /\bfieldControl\b/],
    ];
    composers.forEach(([component, token]) => {
      const source = readFileSync(join(__dirname, '..', 'components', component), 'utf8');
      expect(source).toMatch(token);
    });

    const secretInput = readFileSync(
      join(__dirname, '..', 'components', 'SecretInput.tsx'),
      'utf8',
    );
    expect(secretInput).not.toMatch(/(?:hover|focus-visible):border-/);

    const appStyles = readFileSync(
      join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),
      'utf8',
    );
    expect(appStyles).toMatch(/html\[data-input-modality='pointer'\]/);
    expect(appStyles).toMatch(/html\[data-input-modality='keyboard'\]/);
    expect(appStyles).toMatch(
      /outline:\s*var\(--theme-focus-ring-width, 2px\) solid rgb\(var\(--focus-control\)\) !important;\s*outline-offset:\s*var\(--theme-focus-ring-offset, 2px\) !important;/,
    );
    /** The global outline, in both its layered and its unlayered dark rule, reads the roles. */
    const roleOutline =
      ':focus-visible \\{\\s*outline: var\\(--theme-focus-ring-width, 2px\\) solid rgb\\(var\\(--focus-outline\\)\\);\\s*outline-offset: var\\(--theme-focus-ring-offset, 2px\\);';
    expect(appStyles).toMatch(new RegExp(`@layer base \\{\\s*${roleOutline}`));
    expect(appStyles).toMatch(
      new RegExp(
        `\\.dark ${roleOutline.replace(':focus-visible ', ":focus-visible:not\\(\\[class\\*='focus-visible:outline-'\\], \\[class\\*='focus:outline-'\\]\\) ")}`,
      ),
    );
    expect(appStyles).not.toMatch(/textarea\s*\n\):hover,/);
  });

  it('keeps shared dropdown triggers transparent at rest and while disabled', () => {
    const source = readFileSync(join(__dirname, '..', 'components', 'Dropdown.tsx'), 'utf8');

    expect(source).toMatch(/\bbg-transparent\b/);
    expect(source).toMatch(/\bdisabled:hover:bg-transparent\b/);
    expect(source).not.toMatch(/\bbg-surface-primary\b/);
  });
});

type Rgb = [number, number, number];

/** Surfaces that carry body copy; `surface-tertiary` is chip/input fill, added per-group below. */
const canvasSurfaces: Array<keyof IThemeRGB> = [
  'rgb-surface-primary',
  'rgb-surface-primary-alt',
  'rgb-surface-sidebar',
  'rgb-surface-secondary',
  'rgb-surface-dialog',
  'rgb-surface-chat',
  'rgb-surface-code',
  'rgb-surface-code-body',
  'rgb-presentation',
];

const neutralTextTokens: Array<keyof IThemeRGB> = [
  'rgb-text-primary',
  'rgb-text-secondary',
  'rgb-text-secondary-alt',
  'rgb-text-tertiary',
];

const statusTextTokens: Array<keyof IThemeRGB> = ['rgb-text-warning', 'rgb-text-destructive'];

/** How Alert/Badge/Tag/Chip paint every status variant: `text-status-x` on `bg-status-x-subtle`. */
const statusHues = ['success', 'info', 'warning', 'error', 'neutral'] as const;

const WCAG_AA_NORMAL = 4.5;

function toRgb(theme: IThemeRGB, token: keyof IThemeRGB): Rgb {
  const parts = theme[token]?.trim().split(/\s+/).map(Number);
  if (parts?.length !== 3 || parts.some(Number.isNaN)) {
    throw new Error(`theme token "${token}" is not an "R G B" triplet`);
  }
  return [parts[0], parts[1], parts[2]];
}

function channel(value: number): number {
  const c = value / 255;
  return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
}

function luminance([r, g, b]: Rgb): number {
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}

function contrast(a: Rgb, b: Rgb): number {
  const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (lighter + 0.05) / (darker + 0.05);
}

function belowAA(
  theme: IThemeRGB,
  textTokens: Array<keyof IThemeRGB>,
  surfaces: Array<keyof IThemeRGB>,
): string[] {
  return textTokens.flatMap((text) =>
    surfaces.flatMap((surface) => {
      const ratio = contrast(toRgb(theme, text), toRgb(theme, surface));
      return ratio < WCAG_AA_NORMAL ? [`${text} on ${surface}: ${ratio.toFixed(2)}:1`] : [];
    }),
  );
}

describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s theme text contrast', (name, theme: IThemeRGB) => {
  it('keeps neutral text at WCAG AA on every surface it renders on', () => {
    expect(belowAA(theme, neutralTextTokens, [...canvasSurfaces, 'rgb-surface-tertiary'])).toEqual(
      [],
    );
  });

  it('keeps the tooltip label and the error alert text at WCAG AA', () => {
    const tooltip = belowAA(theme, ['rgb-text-tooltip'], ['rgb-surface-tooltip']);
    const alert = belowAA(theme, ['rgb-status-error'], ['rgb-alert-error-fill']);

    expect({ tooltip, alert }).toEqual({ tooltip: [], alert: [] });
  });

  it('keeps warning and destructive text at WCAG AA on canvas surfaces', () => {
    expect(belowAA(theme, statusTextTokens, canvasSurfaces)).toEqual([]);
  });

  it('keeps every status hue at WCAG AA against its own subtle fill', () => {
    const failures = statusHues.flatMap((hue) =>
      belowAA(
        theme,
        [`rgb-status-${hue}` as keyof IThemeRGB],
        [`rgb-status-${hue}-subtle` as keyof IThemeRGB],
      ),
    );
    const held =
      name === 'clickhouse light'
        ? [
            'rgb-status-success on rgb-status-success-subtle: 4.27:1',
            'rgb-status-info on rgb-status-info-subtle: 3.32:1',
          ]
        : [];
    expect(failures.filter((failure) => !held.includes(failure))).toEqual([]);
  });
});

/** The meter paints segments on `surface-tertiary`; the swatch and popover chrome
 *  sit on `surface-secondary`; prompt categories sit on `surface-primary`;
 *  checked capability badges sit on `surface-chat`; dialog option toggles sit
 *  on `surface-dialog`. All have to clear the 3:1 mark-contrast floor. */
const seriesTokens = Array.from(
  { length: 8 },
  (_, index) => `rgb-series-${index + 1}` as keyof IThemeRGB,
);
const seriesSurfaces: Array<keyof IThemeRGB> = [
  'rgb-surface-primary',
  'rgb-surface-tertiary',
  'rgb-surface-secondary',
  'rgb-surface-chat',
  'rgb-surface-dialog',
];
const WCAG_MARK_MIN = 3;

describe('categorical series scale', () => {
  it('defines every slot in both modes as an "R G B" triplet', () => {
    seriesTokens.forEach((token) => {
      expect(() => toRgb(defaultTheme, token)).not.toThrow();
      expect(() => toRgb(darkTheme, token)).not.toThrow();
    });
  });

  it('never reuses a reserved status colour for series identity', () => {
    const reserved = new Set(
      statusHues.flatMap((hue) => [
        defaultTheme[`rgb-status-${hue}` as keyof IThemeRGB],
        darkTheme[`rgb-status-${hue}` as keyof IThemeRGB],
      ]),
    );

    seriesTokens.forEach((token) => {
      expect(reserved.has(defaultTheme[token])).toBe(false);
      expect(reserved.has(darkTheme[token])).toBe(false);
    });
  });

  it('keeps the stock CSS defaults in step with the runtime themes', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    seriesTokens.forEach((token) => {
      const property = token.slice(4);
      const declared = [...stockStyles.matchAll(new RegExp(`--${property}:\\s*([^;]+);`, 'g'))].map(
        (match) => match[1].trim(),
      );

      /** One declaration for `html`, one for `.dark` — and both must match. */
      expect(declared).toEqual([defaultTheme[token], darkTheme[token]]);
    });
  });

  it('exposes each slot as a Tailwind color backed by its CSS variable', () => {
    const tokens = readFileSync(join(__dirname, 'tokens.css'), 'utf8');

    seriesTokens.forEach((token) => {
      const property = token.slice(4);
      expect(tokens).toContain(`--color-${property}: rgb(var(--${property}));`);
    });
  });
});

describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
])('%s series contrast', (_name, theme: IThemeRGB) => {
  it('keeps every series slot at the 3:1 mark floor on its consumer surfaces', () => {
    const failures = seriesTokens.flatMap((token) =>
      seriesSurfaces.flatMap((surface) => {
        const ratio = contrast(toRgb(theme, token), toRgb(theme, surface));
        return ratio < WCAG_MARK_MIN ? [`${token} on ${surface}: ${ratio.toFixed(2)}:1`] : [];
      }),
    );

    expect(failures).toEqual([]);
  });

  /** A series slot is not only a chart mark: the file-source badges fill a chip
   *  with one and drop a glyph on top, so a slot has to carry `text-on-status`
   *  at the same 3:1 floor. */
  it('lets every series slot carry the status label at the 3:1 mark floor', () => {
    const failures = seriesTokens.flatMap((token) => {
      const ratio = contrast(toRgb(theme, token), toRgb(theme, 'rgb-text-on-status'));
      return ratio < WCAG_MARK_MIN ? [`${token} under text-on-status: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });

  /** Identity labels (`SeriesLabel`: action methods, principal types) are small text, so the
   *  series hue never paints the glyphs: the label takes `text-secondary` at AA
   *  and the hue rides on a leading dot at the 3:1 mark floor, both on the rows
   *  and popover options that host them, at rest and while hovered or active. */
  it('keeps identity labels at AA and their hue dots at the 3:1 mark floor', () => {
    const hosts: Array<keyof IThemeRGB> = [
      'rgb-surface-primary',
      'rgb-surface-secondary',
      'rgb-surface-tertiary',
      'rgb-surface-dialog',
    ];
    const dots: Array<keyof IThemeRGB> = [...seriesTokens, 'rgb-status-error'];
    const dotFailures = dots.flatMap((token) =>
      hosts.flatMap((surface) => {
        const ratio = contrast(toRgb(theme, token), toRgb(theme, surface));
        return ratio < WCAG_MARK_MIN ? [`${token} dot on ${surface}: ${ratio.toFixed(2)}:1`] : [];
      }),
    );

    expect([...dotFailures, ...belowAA(theme, ['rgb-text-secondary'], hosts)]).toEqual([]);
  });
});

describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s control focus', (_name, theme: IThemeRGB) => {
  it('keeps the keyboard focus ring at the 3:1 floor on every control canvas', () => {
    const ring = toRgb(theme, 'rgb-focus-control');
    const surfaces: Array<keyof IThemeRGB> = [
      'rgb-surface-primary',
      'rgb-presentation',
      'rgb-surface-secondary',
      'rgb-surface-dialog',
    ];

    const failures = surfaces.flatMap((surface) => {
      const ratio = contrast(ring, toRgb(theme, surface));
      return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });
});

describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s skill indicators', (_name, theme: IThemeRGB) => {
  it('keeps informational marks at the 3:1 floor on every skill surface', () => {
    const indicator = toRgb(theme, 'rgb-status-info');
    const surfaces: Array<keyof IThemeRGB> = [
      'rgb-presentation',
      'rgb-surface-secondary',
      'rgb-surface-active',
    ];

    const failures = surfaces.flatMap((surface) => {
      const ratio = contrast(indicator, toRgb(theme, surface));
      return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });
});

/** `status-success-strong` is the one status fill that also paints bare marks:
 *  the selected-tool check, the version timeline rail and its "current" dot, and
 *  the selected prompt-version chip. It owes two ratios at once, AA under the
 *  `text-on-status` label it carries and the 3:1 mark floor against the panel it
 *  sits on. `surface-secondary` is that panel in every mode. */
describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s success fill', (_name, theme: IThemeRGB) => {
  it('carries its label at WCAG AA', () => {
    const ratio = contrast(
      toRgb(theme, 'rgb-status-success-strong'),
      toRgb(theme, 'rgb-text-on-status'),
    );
    expect(ratio).toBeGreaterThanOrEqual(WCAG_AA_NORMAL);
  });

  it('keeps its silhouette at the 3:1 mark floor on the panel', () => {
    const ratio = contrast(
      toRgb(theme, 'rgb-status-success-strong'),
      toRgb(theme, 'rgb-surface-secondary'),
    );
    expect(ratio).toBeGreaterThanOrEqual(WCAG_MARK_MIN);
  });
});

describe('success fill defaults', () => {
  /** Both copies have to move together: the value is a tuned hex rather than a
   *  palette step, so the stylesheet cannot alias it to a `--green-*` step. */
  it('keeps the stock CSS in step with the runtime themes', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    const declared = [...stockStyles.matchAll(/--status-success-strong:\s*([^;]+);/g)].map(
      (match) => match[1].trim(),
    );

    /** One declaration for `html`, one for `.dark`, and both must match. */
    expect(declared).toEqual([
      defaultTheme['rgb-status-success-strong'],
      darkTheme['rgb-status-success-strong'],
    ]);
  });
});

/** `status-verified` paints one thing: the check a first-party item wears next
 *  to its name. Both of its relationships are graphical objects under WCAG
 *  1.4.11, so both owe 3:1 and neither owes AA: the badge against the card it
 *  sits on, and the `text-on-status` check against the badge. That is where it
 *  parts from the success fill above, which carries a text label and therefore
 *  owes AA. The card is not one surface — `ToolCard` rests on the dialog and
 *  repaints to `surface-tertiary` on hover — so the silhouette is checked
 *  against every background the card can take. Separate from
 *  `status-success-strong` on purpose: green already means selected on the same
 *  card, so provenance needs its own hue. */
describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s verified fill', (_name, theme: IThemeRGB) => {
  it('carries its check at the 3:1 mark floor', () => {
    const ratio = contrast(toRgb(theme, 'rgb-status-verified'), toRgb(theme, 'rgb-text-on-status'));
    expect(ratio).toBeGreaterThanOrEqual(WCAG_MARK_MIN);
  });

  it('keeps its silhouette at the 3:1 mark floor on every card state', () => {
    const mark = toRgb(theme, 'rgb-status-verified');
    /** Resting card, the panel behind the grid, and the hover repaint from
     *  `ToolCard`'s `hover:bg-surface-tertiary`. */
    const surfaces: Array<keyof IThemeRGB> = [
      'rgb-surface-dialog',
      'rgb-surface-secondary',
      'rgb-surface-tertiary',
    ];

    const failures = surfaces.flatMap((surface) => {
      const ratio = contrast(mark, toRgb(theme, surface));
      return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });
});

describe('verified fill defaults', () => {
  /** Tuned values rather than palette steps in either mode, so the stylesheet
   *  cannot alias them to a `--blue-*` step and both copies move together. */
  it('keeps the stock CSS in step with the runtime themes', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    const declared = [...stockStyles.matchAll(/--status-verified:\s*([^;]+);/g)].map((match) =>
      match[1].trim(),
    );

    expect(declared).toEqual([
      defaultTheme['rgb-status-verified'],
      darkTheme['rgb-status-verified'],
    ]);
  });
});

/** The default avatar's glyph is a graphical object under WCAG 1.4.11, so it needs 3:1 on its fill. */
describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s default avatar', (_name, theme: IThemeRGB) => {
  it('keeps the glyph at the 3:1 mark floor against its fill', () => {
    expect(
      contrast(toRgb(theme, 'rgb-avatar-text'), toRgb(theme, 'rgb-avatar-fill')),
    ).toBeGreaterThanOrEqual(WCAG_MARK_MIN);
  });
});

/** The shared `Switch` paints this track, so it travels with the package rather
 *  than the app stylesheet. It is a UI component boundary under WCAG 1.4.11 and
 *  has to stay distinct from the `switch-thumb` knob on it and from the
 *  `surface-inverted` fill it swaps with when checked. */
describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
])('%s switch track', (_name, theme: IThemeRGB) => {
  it('keeps the unchecked track at the 3:1 mark floor against thumb and checked fill', () => {
    const track = toRgb(theme, 'rgb-switch-unchecked');
    (['rgb-switch-thumb', 'rgb-surface-inverted'] as Array<keyof IThemeRGB>).forEach((surface) => {
      expect({ surface, ok: contrast(track, toRgb(theme, surface)) >= WCAG_MARK_MIN }).toEqual({
        surface,
        ok: true,
      });
    });
  });
});

describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s table header', (_name, theme: IThemeRGB) => {
  it('keeps column names readable on the header fill', () => {
    expect(
      contrast(toRgb(theme, 'rgb-table-header-text'), toRgb(theme, 'rgb-surface-secondary')),
    ).toBeGreaterThanOrEqual(4.5);
  });

  it('keeps column names readable on a self-sticking header', () => {
    expect(
      contrast(toRgb(theme, 'rgb-table-header-text'), toRgb(theme, 'rgb-table-header-fill')),
    ).toBeGreaterThanOrEqual(4.5);
  });
});

describe('switch track defaults', () => {
  /** The app stylesheet only restates the registry now: the contrast modes used
   *  to carry their own `html.high-contrast` overrides here, which the published
   *  package never shipped. */
  it('keeps the stock CSS in step with the runtime themes', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    const declared = [...stockStyles.matchAll(/--switch-unchecked:\s*([^;]+);/g)].map((match) =>
      match[1].trim(),
    );

    expect(declared).toEqual([
      defaultTheme['rgb-switch-unchecked'],
      darkTheme['rgb-switch-unchecked'],
    ]);
  });

  it('declares table column names on the secondary text they were before the role', () => {
    const appStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect([...appStyles.matchAll(/--table-header-text:\s*([^;]+);/g)].map((m) => m[1])).toEqual([
      'var(--text-secondary)',
    ]);
    expect(defaultTheme['rgb-table-header-text']).toBe(defaultTheme['rgb-text-secondary']);
    expect(darkTheme['rgb-table-header-text']).toBe(darkTheme['rgb-text-secondary']);
  });

  it('declares the self-sticking header fill on the dialog surface it was before the role', () => {
    const appStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect([...appStyles.matchAll(/--table-header-fill:\s*([^;]+);/g)].map((m) => m[1])).toEqual([
      'var(--surface-dialog)',
    ]);
    [defaultTheme, darkTheme, highContrastLightTheme, highContrastDarkTheme].forEach((theme) =>
      expect(theme['rgb-table-header-fill']).toBe(theme['rgb-surface-dialog']),
    );
  });

  it('ships the no-rule table default with the package', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    expect(stockStyles).toContain(`--theme-table-row-stroke: ${defaultAppearance.tableRowStroke};`);
  });

  it('declares the stock thumb the registry paints', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    const declared = [...stockStyles.matchAll(/--switch-thumb:\s*([^;]+);/g)].map((match) =>
      match[1].trim(),
    );

    expect(declared).toEqual([defaultTheme['rgb-switch-thumb'], darkTheme['rgb-switch-thumb']]);
  });
});

/** The syntax palette used to live as raw hex in `style.css`, which meant a
 *  change had to be made twice and neither copy was checked. It is a registry
 *  token map now, so the stylesheet is only allowed to restate it. */
describe('syntax highlighting palette', () => {
  const syntaxTokens = (
    ['comment', 'meta', 'builtin', 'keyword', 'string', 'attr', 'title'] as const
  ).map((role) => `rgb-syntax-${role}` as keyof IThemeRGB);

  it('is declared in both bundled themes', () => {
    syntaxTokens.forEach((token) => {
      expect(() => toRgb(defaultTheme, token)).not.toThrow();
      expect(() => toRgb(darkTheme, token)).not.toThrow();
    });
  });

  it('keeps the stock CSS defaults in step with the runtime themes', () => {
    const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');

    syntaxTokens.forEach((token) => {
      const property = token.slice(4);
      const declared = [...stockStyles.matchAll(new RegExp(`--${property}:\\s*([^;]+);`, 'g'))].map(
        (match) => match[1].trim(),
      );

      /** `html` may alias a raw palette entry; `.dark` states the triplet. */
      expect(declared).toHaveLength(2);
      expect(declared[1]).toBe(darkTheme[token]);
    });
  });

  it('leaves no hard-coded syntax hex behind in the stylesheet', () => {
    const appStyles = readFileSync(
      join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),
      'utf8',
    );
    const hljsRules = [...appStyles.matchAll(/^\.hljs[^{]*\{([^}]*)\}/gm)].map((match) => match[1]);

    expect(hljsRules.length).toBeGreaterThan(0);
    expect(hljsRules.filter((body) => /#[0-9a-f]{3,8}|hsla?\(/i.test(body))).toEqual([]);
  });
});

/** `border-control` is the only edge a form control has (`Field`, `Select`,
 *  `InputOTP`, the dropdown and combobox triggers). The stock light and dark
 *  palettes keep it at their quiet `border-light` value by design; the high
 *  contrast and ClickHouse palette holds it to the WCAG 1.4.11 3:1 floor. ClickHouse takes Click UI's
 *  `field.color.stroke.default` instead, which sits below it by owner decision. */
const controlCanvases: Array<keyof IThemeRGB> = [...canvasSurfaces, 'rgb-surface-tertiary'];

describe.each([
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
])('%s control border', (_name, theme: IThemeRGB) => {
  it('keeps the form-control outline at the 3:1 floor on every canvas', () => {
    const outline = toRgb(theme, 'rgb-border-control');
    const failures = controlCanvases.flatMap((surface) => {
      const ratio = contrast(outline, toRgb(theme, surface));
      return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });
});

/** WCAG 2.4.13 holds a focus indicator to 3:1 against what it is drawn on. The
 *  global outline and the primitives' ring are theme roles, so every bundled
 *  palette carries both at that floor on its canvases. */
describe.each([
  ['default light', defaultTheme],
  ['default dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s focus roles', (_name, theme: IThemeRGB) => {
  it.each(['rgb-focus-outline', 'rgb-focus-control'] as const)(
    'keeps %s at the 3:1 floor on every canvas',
    (role) => {
      const focus = toRgb(theme, role);
      const failures = canvasSurfaces.flatMap((surface) => {
        const ratio = contrast(focus, toRgb(theme, surface));
        return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
      });

      expect(failures).toEqual([]);
    },
  );
});

describe('focus role defaults', () => {
  /** The default theme's outline was literal black and white and its primitives
   *  drew their ring in the primary ink; the roles reproduce both. */
  it('reproduces the outline and ring the default theme drew before the roles', () => {
    expect([defaultTheme['rgb-focus-outline'], darkTheme['rgb-focus-outline']]).toEqual([
      '0 0 0',
      '255 255 255',
    ]);
    expect([defaultTheme['rgb-focus-control'], darkTheme['rgb-focus-control']]).toEqual([
      defaultTheme['rgb-text-primary'],
      darkTheme['rgb-text-primary'],
    ]);
  });
});

describe('state role defaults', () => {
  /** A pointer press lands on a hovered control, so the default press shows the
   *  hover fill it always did; only a theme that names a pressed fill changes it. */
  it.each([
    ['default light', defaultTheme],
    ['default dark', darkTheme],
    ['high contrast light', highContrastLightTheme],
    ['high contrast dark', highContrastDarkTheme],
  ])('presses %s controls in their hover fills', (_name, theme: IThemeRGB) => {
    expect(theme['rgb-surface-pressed']).toBe(theme['rgb-surface-hover']);
    expect(theme['rgb-surface-inverted-pressed']).toBe(theme['rgb-surface-inverted-hover']);
  });

  it.each([
    ['default light', defaultTheme],
    ['default dark', darkTheme],
    ['high contrast light', highContrastLightTheme],
    ['high contrast dark', highContrastDarkTheme],
  ])('fills %s primary buttons with the inverted surface', (_name, theme: IThemeRGB) => {
    expect(theme['rgb-button-primary']).toBe(theme['rgb-surface-inverted']);
    expect(theme['rgb-button-primary-hover']).toBe(theme['rgb-surface-inverted-hover']);
  });

  it.each([
    ['default light', defaultTheme],
    ['default dark', darkTheme],
    ['high contrast light', highContrastLightTheme],
    ['high contrast dark', highContrastDarkTheme],
  ])('sets %s dialog titles and badge labels in the primary ink', (_name, theme: IThemeRGB) => {
    expect(theme['rgb-dialog-title']).toBe(theme['rgb-text-primary']);
    expect(theme['rgb-badge-label']).toBe(theme['rgb-text-primary']);
  });

  it.each([
    ['default light', defaultTheme],
    ['default dark', darkTheme],
    ['high contrast light', highContrastLightTheme],
    ['high contrast dark', highContrastDarkTheme],
    ['clickhouse light', clickHouseLightTheme],
    ['clickhouse dark', clickHouseDarkTheme],
  ])('keeps %s badge labels at AA on the resting badge fill', (_name, theme: IThemeRGB) => {
    const ink = toRgb(theme, 'rgb-badge-label');
    /** A hovered or selected badge is labeled in the primary ink, so only the resting fill counts. */
    const fills: Array<keyof IThemeRGB> = ['rgb-surface-chat'];

    const failures = fills.flatMap((fill) => {
      const ratio = contrast(ink, toRgb(theme, fill));
      return ratio < 4.5 ? [`${fill}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });

  it.each([
    ['default light', defaultTheme],
    ['default dark', darkTheme],
    ['high contrast light', highContrastLightTheme],
    ['high contrast dark', highContrastDarkTheme],
  ])('edges %s focused fields in the focus ring color', (_name, theme: IThemeRGB) => {
    expect(theme['rgb-border-field-focus']).toBe(theme['rgb-focus-control']);
  });

  it.each([
    ['clickhouse light', clickHouseLightTheme],
    ['clickhouse dark', clickHouseDarkTheme],
  ])('keeps the %s focused field edge at 3:1 on every field canvas', (_name, theme: IThemeRGB) => {
    const edge = toRgb(theme, 'rgb-border-field-focus');
    const canvases: Array<keyof IThemeRGB> = [
      'rgb-surface-primary',
      'rgb-presentation',
      'rgb-surface-secondary',
      'rgb-surface-dialog',
    ];

    const failures = canvases.flatMap((canvas) => {
      const ratio = contrast(edge, toRgb(theme, canvas));
      return ratio < WCAG_MARK_MIN ? [`${canvas}: ${ratio.toFixed(2)}:1`] : [];
    });

    expect(failures).toEqual([]);
  });

  it.each([
    ['clickhouse light', clickHouseLightTheme],
    ['clickhouse dark', clickHouseDarkTheme],
  ])('keeps %s dialog titles at AA on the dialog surface', (_name, theme: IThemeRGB) => {
    expect(
      contrast(toRgb(theme, 'rgb-dialog-title'), toRgb(theme, 'rgb-surface-dialog')),
    ).toBeGreaterThanOrEqual(4.5);
  });
});

/**
 * The dialog scrims are `surface-overlay` at each family's opacity role. A scrim
 * dims the page it covers and never lifts it (Click UI's dark scrim is a lighter
 * gray, which the ClickHouse theme draws anyway, by owner decision), and on a light
 * canvas the dimmed page separates the dialog by the 3:1 a non-text boundary
 * needs. Dark canvases draw that boundary with the dialog's own border instead.
 */
const scrimRoles = ['scrimOpacity', 'alertScrimOpacity', 'modalScrimOpacity'] as const;
const clickHouseAppearance = (mode: 'light' | 'dark'): IThemeAppearance => ({
  ...defaultAppearance,
  ...clickHouseTheme.modes[mode]?.appearance,
});

describe.each([
  ['default light', defaultTheme, defaultAppearance, true],
  ['default dark', darkTheme, defaultAppearance, false],
  ['high contrast light', highContrastLightTheme, defaultAppearance, true],
  ['high contrast dark', highContrastDarkTheme, defaultAppearance, false],
  ['clickhouse light', clickHouseLightTheme, clickHouseAppearance('light'), true],
  ['clickhouse dark', clickHouseDarkTheme, clickHouseAppearance('dark'), false],
])('%s scrims', (name, theme: IThemeRGB, appearance: IThemeAppearance, lightCanvas: boolean) => {
  it.each(scrimRoles)('%s dims the page without lifting it', (role) => {
    const alpha = Number(appearance[role]);
    const overlay = toRgb(theme, 'rgb-surface-overlay');
    const page = toRgb(theme, 'rgb-surface-primary');
    const dimmed = page.map(
      (channel, index) => overlay[index] * alpha + channel * (1 - alpha),
    ) as Rgb;

    if (name !== 'clickhouse dark') {
      expect(luminance(dimmed)).toBeLessThanOrEqual(luminance(page));
    }
    if (lightCanvas) {
      expect(contrast(toRgb(theme, 'rgb-surface-dialog'), dimmed)).toBeGreaterThanOrEqual(
        WCAG_MARK_MIN,
      );
    }
  });
});

describe('scrim defaults', () => {
  it('reproduce the opacities each dialog family drew before the roles', () => {
    expect(scrimRoles.map((role) => defaultAppearance[role])).toEqual(['0.8', '0.9', '0.65']);
  });
});

const categoryIconSlots = ['1', '2', '4', '5', '6', '7'] as const;

/** The stock and high contrast palettes keep each category icon on the series slot it drew in. */
describe.each([
  ['default', defaultTheme],
  ['dark', darkTheme],
  ['high contrast light', highContrastLightTheme],
  ['high contrast dark', highContrastDarkTheme],
])('%s category icons', (_name, theme: IThemeRGB) => {
  it.each(categoryIconSlots)('paint category-icon-%s in its series slot', (slot) => {
    expect(theme[`rgb-category-icon-${slot}`]).toBe(theme[`rgb-series-${slot}`]);
  });
});

/** ClickHouse draws every category icon in its muted ink, apart from the chart slots, and each one
 *  is a graphical object under WCAG 1.4.11, so it owes 3:1 on the panel and on a hovered or
 *  selected row. */
describe.each([
  ['clickhouse light', clickHouseLightTheme],
  ['clickhouse dark', clickHouseDarkTheme],
])('%s category icons', (_name, theme: IThemeRGB) => {
  const surfaces: Array<keyof IThemeRGB> = [
    'rgb-surface-primary',
    'rgb-surface-primary-alt',
    'rgb-surface-nav-hover',
    'rgb-surface-nav-selected',
  ];

  it.each(categoryIconSlots)(
    'clear the 3:1 mark floor for category-icon-%s on every row surface',
    (slot) => {
      const icon = toRgb(theme, `rgb-category-icon-${slot}`);
      const failures = surfaces.flatMap((surface) => {
        const ratio = contrast(icon, toRgb(theme, surface));
        return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];
      });

      expect(failures).toEqual([]);
    },
  );

  it('draw every category in the muted ink without moving the series slots', () => {
    categoryIconSlots.forEach((slot) => {
      expect(theme[`rgb-category-icon-${slot}`]).toBe(theme['rgb-text-secondary']);
      expect(theme[`rgb-series-${slot}`]).not.toBe(theme['rgb-text-secondary']);
    });
  });
});