diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 96fb51625..10d7ed0ed 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -93,6 +93,11 @@ jobs: run: npm run lint working-directory: ui/apps/chat + - name: Check DESIGN.md is current with the tokens + if: ${{ always() && steps.setup.conclusion == 'success' }} + run: npm run check:design + working-directory: ui/apps/chat + - name: Install Playwright browsers id: playwright if: ${{ always() && steps.setup.conclusion == 'success' }} diff --git a/ui/apps/chat/.storybook/docs.css b/ui/apps/chat/.storybook/docs.css deleted file mode 100644 index 4a2f1facc..000000000 --- a/ui/apps/chat/.storybook/docs.css +++ /dev/null @@ -1,91 +0,0 @@ -@reference '../src/app.css'; - -/* - * MDX pages that wrap their content in
drop - * Storybook's docs theme and take colours, font and type roles from the design system. - */ -.sbdocs-wrapper:has(.ds-docs) { - background: var(--surface-page); -} - -.ds-docs { - @apply mx-auto max-w-3xl font-sans text-body text-fg-default; - - & :where(h1) { - @apply mb-4 text-heading; - } - - & :where(h2) { - @apply mt-10 mb-3 border-b border-line-default pb-2 text-title; - } - - & :where(h3) { - @apply mt-6 mb-2 text-body font-semibold; - } - - & :where(h4, h5, h6) { - @apply mt-4 mb-2 text-label; - } - - & :where(p, ul, ol, blockquote, table, pre) { - @apply my-3; - } - - & :where(ul) { - @apply list-disc pl-6; - } - - & :where(ol) { - @apply list-decimal pl-6; - } - - & :where(li) { - @apply my-1; - } - - & :where(strong) { - @apply font-semibold; - } - - & :where(a) { - @apply underline underline-offset-2 hover:text-fg-muted; - } - - & :where(blockquote) { - @apply border-l-2 border-line-default pl-4 text-fg-muted; - } - - /* a note that stands out from the running text: a quiet panel with the accent on its edge */ - & :where(.callout) { - @apply my-6 rounded-panel border-l-2 border-(--art-cinder) bg-surface-muted px-5 py-4; - - & > :where(p) { - @apply my-0; - } - } - - & :where(hr) { - @apply my-8 border-line-default; - } - - /* inline code only, with a selector that outranks the code the Markdown block renders */ - & :not(pre) > code { - @apply rounded-control border-0 bg-surface-code px-1 py-0.5 font-mono text-[0.875em] text-(--fg-code); - } - - & :where(pre) { - @apply overflow-x-auto rounded-panel bg-surface-code p-4 text-body-sm; - } - - & :where(table) { - @apply w-full border-collapse text-body-sm; - } - - & :where(th, td) { - @apply border-b border-line-default px-3 py-2 text-left align-top; - } - - & :where(th) { - @apply text-label; - } -} diff --git a/ui/apps/chat/.storybook/main.ts b/ui/apps/chat/.storybook/main.ts index 076f24481..3e8c1a39d 100644 --- a/ui/apps/chat/.storybook/main.ts +++ b/ui/apps/chat/.storybook/main.ts @@ -6,6 +6,8 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); // Llama UI's stories live with the library (ui/lib/ui/tests/stories), which runs and tests them in its own // Storybook; this one shows them too, under Llama UI, next to Llama Chat's own. The library's front page stays its own. +// Llama Chat's stories take the helpers they share with the library's (the Editorial, the state gallery) from there +// too, as $llama-ui-stories/..., which tsconfig.json maps for TypeScript const LLAMA_UI_STORIES = resolve(__dirname, '../../../lib/ui/tests/stories'); const config: StorybookConfig = { @@ -36,6 +38,15 @@ const config: StorybookConfig = { ]; // the library's stories import Storybook from where they live, where only this app's packages are installed config.resolve = config.resolve || {}; + config.resolve.alias = [ + ...(Array.isArray(config.resolve.alias) + ? config.resolve.alias + : Object.entries(config.resolve.alias || {}).map(([find, replacement]) => ({ + find, + replacement + }))), + { find: '$llama-ui-stories', replacement: LLAMA_UI_STORIES } + ]; config.resolve.dedupe = [ ...(config.resolve.dedupe || []), '@storybook/addon-svelte-csf', diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 671aa2f95..7e7a58d16 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -2,7 +2,8 @@ import '../src/app.css'; import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; import { SurfaceTheme } from '#lib/enums/ui.enums.ts'; import { applySurfaceTheme } from '#lib/utils/css.ts'; -import './docs.css'; +// the docs pages' styles, shared with the library's Storybook +import '../../../lib/ui/.storybook/docs.css'; import { applyColorScheme } from './color-scheme'; import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; @@ -76,9 +77,10 @@ const preview: Preview = { }, a11y: { - // 'todo' - show a11y violations in the test UI only - // 'error' - fail CI on a11y violations - // 'off' - skip a11y checks entirely + // 'todo' shows violations in the Accessibility panel and the test UI without failing a test; 'error' would + // fail CI on them. Not yet 'error': about half the stories fail it, most on colour contrast (the muted + // foreground on the light surfaces, below 4.5:1) and nested interactive controls, which need design changes + // rather than story fixes. Switch once those are settled test: 'todo' } }, diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index c4c0a0f3c..f585ec54f 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -2,8 +2,8 @@ These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. -- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual; when it and the CSS disagree, the CSS wins and DESIGN.md is updated. -- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. +- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. +- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. - **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. ## Content is Markdown, custom pieces are Svelte: .svx diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index 708a656d5..971685e1b 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -5,10 +5,14 @@ description: >- Llama UI, the design system and components of Llama Chat, the chat client llama-server bundles. Neutral and quiet: frosted matte surfaces with faint blue-grey hairlines, near-flat fills, and status colours for success, warning, error and info. Tokens come in - three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs) - and components. Generated from ui/lib/ui/src/lib/styles/tokens/*.css. + three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs and a + "-matte" twin where the Matte light theme does) and components. The colors, typography and + rounded sections are generated from ui/lib/ui/src/lib/styles by `npm run design:tokens` in + ui/apps/chat; spacing, components and the prose are kept in sync with the CSS by hand. colors: primary: '{colors.action-primary}' + brand-ink: '#111111' + brand-light: '#fafafa' neutral-0: 'oklch(1 0 0)' neutral-25: 'oklch(0.988 0 0)' neutral-50: 'oklch(0.985 0 0)' @@ -18,28 +22,30 @@ colors: neutral-300: 'oklch(0.87 0 0)' neutral-400: 'oklch(0.708 0 0)' neutral-500: 'oklch(0.556 0 0)' + neutral-600: 'oklch(0.439 0 0)' + neutral-700: 'oklch(0.371 0 0)' neutral-750: 'oklch(0.29 0 0)' neutral-800: 'oklch(0.269 0 0)' neutral-900: 'oklch(0.205 0 0)' neutral-925: 'oklch(0.16 0 0)' neutral-950: 'oklch(0.145 0 0)' - cool-gray-50: 'oklch(0.958 0.002 250)' - cool-gray-100: 'oklch(0.938 0.004 250)' - cool-gray-200: 'oklch(0.91 0.005 250)' - cool-gray-300: 'oklch(0.86 0.007 250)' - cool-gray-400: 'oklch(0.81 0.01 250)' - art-day-sky: 'oklch(0.78 0.075 245)' - art-night-sky: 'oklch(0.33 0.07 256)' - art-cinder: 'oklch(0.68 0.18 46)' - art-cinder-light: 'oklch(0.85 0.065 46)' sand-50: 'oklch(0.965 0.01 80)' sand-100: 'oklch(0.936 0.015 81)' sand-200: 'oklch(0.89 0.02 80)' sand-400: 'oklch(0.72 0.025 76)' sand-900: 'oklch(0.272 0.013 72)' + art-day-sky: 'oklch(0.78 0.075 245)' + art-night-sky: 'oklch(0.33 0.07 256)' + art-cinder: 'oklch(0.68 0.18 46)' + art-cinder-light: 'oklch(0.85 0.065 46)' + cool-gray-50: 'oklch(0.958 0.002 250)' + cool-gray-100: 'oklch(0.938 0.004 250)' + cool-gray-200: 'oklch(0.91 0.005 250)' + cool-gray-300: 'oklch(0.86 0.007 250)' + cool-gray-400: 'oklch(0.81 0.01 250)' red-400: 'oklch(0.69 0.2 27)' - red-500: 'oklch(0.6 0.235 27)' red-450: 'oklch(0.635 0.229 28)' + red-500: 'oklch(0.6 0.235 27)' red-550: 'oklch(0.588 0.236 28)' red-600: 'oklch(0.55 0.22 27)' red-800: 'oklch(0.43 0.17 27)' @@ -69,19 +75,32 @@ colors: white-a18: 'oklch(1 0 0 / 0.18)' white-a20: 'oklch(1 0 0 / 0.2)' white-a30: 'oklch(1 0 0 / 0.3)' + white-a40: 'oklch(1 0 0 / 0.4)' white-a50: 'oklch(1 0 0 / 0.5)' + white-a85: 'oklch(1 0 0 / 0.85)' + black-a3: 'oklch(0 0 0 / 0.03)' + black-a4: 'oklch(0 0 0 / 0.04)' + black-a5: 'oklch(0 0 0 / 0.05)' black-a6: 'oklch(0 0 0 / 0.06)' + black-a8: 'oklch(0 0 0 / 0.08)' + black-a10: 'oklch(0 0 0 / 0.1)' + black-a12: 'oklch(0 0 0 / 0.12)' + black-a18: 'oklch(0 0 0 / 0.18)' + black-a25: 'oklch(0 0 0 / 0.25)' black-a30: 'oklch(0 0 0 / 0.3)' + black-a35: 'oklch(0 0 0 / 0.35)' black-a40: 'oklch(0 0 0 / 0.4)' - surface-page: '{colors.neutral-0}' + black-a55: 'oklch(0 0 0 / 0.55)' + black-a60: 'oklch(0 0 0 / 0.6)' + surface-page: '{colors.neutral-25}' surface-muted: '{colors.neutral-100}' surface-emphasis: '{colors.neutral-150}' surface-selected: '{colors.neutral-150}' surface-raised: '{colors.neutral-0}' surface-lifted: '{colors.neutral-0}' surface-pressed: '{colors.neutral-0}' - surface-glass: 'oklch(0.97 0 0 / 0.6)' - surface-code: '{colors.neutral-50}' + surface-glass: 'oklch(1 0 0 / 0.8)' + surface-code: '{colors.neutral-100}' surface-overlay: '{colors.black-a40}' fg-default: '{colors.neutral-950}' fg-muted: '{colors.neutral-500}' @@ -124,7 +143,7 @@ colors: action-quiet: 'oklch(0.97 0 0 / 0.3)' action-quiet-hover: '{colors.neutral-100}' action-ghost-hover: 'oklch(0.556 0 0 / 0.1)' - field-background: 'oklch(1 0 0)' + field-background: '{colors.neutral-0}' field-shade: '{colors.black-a6}' status-danger: '{colors.fill-danger}' status-danger-rim: '{colors.red-400}' @@ -142,6 +161,15 @@ colors: highlight-inverse: '{colors.white-a12}' sheen-start: '{colors.white-a20}' sheen-end: 'transparent' + elevation-ring: '{colors.black-a5}' + surface-page-matte: '{colors.neutral-0}' + surface-glass-matte: 'oklch(0.97 0 0 / 0.6)' + surface-code-matte: '{colors.neutral-50}' + surface-success-matte: 'color-mix(in oklab, {colors.fill-success} 11%, {colors.surface-page-matte})' + surface-warning-matte: 'color-mix(in oklab, {colors.fill-warning} 11%, {colors.surface-page-matte})' + surface-danger-matte: 'color-mix(in oklab, {colors.fill-danger} 11%, {colors.surface-page-matte})' + surface-info-matte: 'color-mix(in oklab, {colors.fill-info} 11%, {colors.surface-page-matte})' + field-background-matte: '{colors.surface-page-matte}' surface-page-dark: '{colors.neutral-925}' surface-muted-dark: '{colors.neutral-800}' surface-emphasis-dark: '{colors.neutral-750}' @@ -193,46 +221,51 @@ colors: action-ghost-hover-dark: 'oklch(0.708 0 0 / 0.1)' field-background-dark: '{colors.white-a9}' field-shade-dark: '{colors.black-a30}' + status-danger-dark: '{colors.fill-danger-dark}' + status-warning-dark: '{colors.fill-warning-dark}' + status-success-dark: '{colors.fill-success-dark}' + status-info-dark: '{colors.fill-info-dark}' highlight-inner-dark: '{colors.white-a4}' sheen-start-dark: '{colors.white-a2}' + elevation-ring-dark: '{colors.white-a18}' typography: - heading: - fontFamily: system-ui - fontSize: 1.5rem - fontWeight: 600 - lineHeight: 2rem - title: - fontFamily: system-ui - fontSize: 1.125rem - fontWeight: 600 - lineHeight: 1.75rem body: - fontFamily: system-ui + fontFamily: 'Llama Sans' fontSize: 1rem fontWeight: 400 lineHeight: 1.5rem body-sm: - fontFamily: system-ui + fontFamily: 'Llama Sans' fontSize: 0.875rem fontWeight: 400 lineHeight: 1.25rem label: - fontFamily: system-ui + fontFamily: 'Llama Sans' fontSize: 0.875rem fontWeight: 500 lineHeight: 1.25rem label-sm: - fontFamily: system-ui + fontFamily: 'Llama Sans' fontSize: 0.75rem fontWeight: 500 lineHeight: 1rem caption: - fontFamily: system-ui + fontFamily: 'Llama Sans' fontSize: 0.75rem fontWeight: 400 lineHeight: 1rem + title: + fontFamily: 'Llama Sans' + fontSize: 1.125rem + fontWeight: 600 + lineHeight: 1.75rem + heading: + fontFamily: 'Llama Sans' + fontSize: 1.5rem + fontWeight: 600 + lineHeight: 2rem code: - fontFamily: Llama Mono + fontFamily: 'Llama Mono' fontSize: 0.875rem fontWeight: 400 lineHeight: 1.25rem @@ -336,6 +369,10 @@ components: backgroundColor: '{colors.edge-raised}' floating-panel-edge-dark: backgroundColor: '{colors.edge-raised-dark}' + floating-panel-rim: + backgroundColor: '{colors.highlight-inner}' + floating-panel-rim-dark: + backgroundColor: '{colors.highlight-inner-dark}' dialog: backgroundColor: '#ffffff' textColor: '{colors.fg-default}' @@ -778,12 +815,16 @@ Design tokens come in three tiers, each in its own file under `ui/lib/ui/src/lib `button-secondary-background-hover`. They point at semantic tokens, and components read them as `bg-(--button-primary-background)` and similar. -The front matter of this file mirrors those three files. When they disagree, the CSS wins -and this file should be updated to match. Storybook shows every tier under **Llama UI › -Foundations › Colors**. +The front matter's `colors`, `typography` and `rounded` are generated from the primitives, the +semantic tokens and the font stacks by `npm run design:tokens` in `ui/apps/chat`, and CI fails +when they are out of date (`npm run check:design`): change the CSS and run it, never edit them +here. The `spacing` and `components` sections and the prose are written by hand; when they +disagree with the CSS, the CSS wins and this file is updated to match. Storybook shows every +tier under **Llama UI › Foundations › Colors**. -Light mode is the base. A semantic token whose dark value differs has a `-dark` twin here, -and components list a `-dark` entry wherever their colours change. Translucent component +Paper light mode is the base. A semantic token that resolves differently in dark mode has a +`-dark` twin here, and one that resolves differently in Matte a `-matte` twin; components list +a `-dark` entry wherever their colours change. Translucent component fills are given as they render over the page, so contrast checks see the real colour. ## Colors @@ -935,10 +976,12 @@ matches the role of the surface instead of combining raw shadows. `inset-group-surface` point those slots at one component's tokens, so each component needs a single class. - **`matte-float`** and **`matte-float-modal`:** menus, popovers, select lists, hover cards - and drawers, and dialogs over the page colour. An 86% opaque panel with blur, a faint edge - and a deeper shadow. The edge is a hairline ring baked into the shadow as its last layer, - never a border next to a shadow, which would read as a double edge; the panel's border stays transparent so its size does not change. In light mode dialogs are solid white instead: over the dimmed page a - translucent white turns grey. + and drawers, and dialogs over the page colour. An 86% opaque panel with blur, a faint edge, + a rim and a deeper shadow. The edge is a hairline ring baked into the shadow as its last + layer (`float-panel-edge`). The panel's 1px border is its rim, the inner highlight + (`float-panel-highlight`) right inside the ring; an inset shadow for the rim would sit inside + the border instead, and the 1px between the two would draw a double edge. In light mode + dialogs are solid white instead: over the dimmed page a translucent white turns grey. - **`matte-key`:** buttons, selects, toggles and tabs. The matte finish: on top of the button's own fill it adds a light blur, a fill barely lighter at the top (`--key-sheen`, 12% white in light mode, 2% in dark) and a small drop shadow. It never changes the button colour and draws no rim of its own: every diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index ae3455084..1120f6f87 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -11,6 +11,8 @@ "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "check:design": "node scripts/design-md.js --check", + "design:tokens": "node scripts/design-md.js", "reset": "rm -rf .svelte-kit node_modules", "format": "eslint --fix . && prettier --write .", "format:files": "sh -c 'eslint --fix \"$@\" && prettier --write \"$@\"' sh", diff --git a/ui/apps/chat/scripts/design-md.js b/ui/apps/chat/scripts/design-md.js new file mode 100644 index 000000000..316bf9acd --- /dev/null +++ b/ui/apps/chat/scripts/design-md.js @@ -0,0 +1,301 @@ +#!/usr/bin/env node + +/** + * Writes the token sections of DESIGN.md's front matter (`colors`, `typography` and `rounded`) from the CSS they + * mirror, so the file agents read cannot drift from the code: + * + * - the brand's colours, @ggml-org/llama-brand's css/colors.css, + * - Llama UI's primitives and semantic tokens, ui/lib/ui/src/lib/styles/tokens/{primitives,semantic}.css, + * - Llama UI's font stacks, ui/lib/ui/src/lib/styles/theme.css. + * + * Everything else in DESIGN.md, the `spacing` and `components` sections and the prose, is written by hand. + * + * Usage: node scripts/design-md.js [--check] + * + * --check writes nothing and exits with 1 if DESIGN.md is not current, for CI (`npm run check:design`). + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const app = new URL('../', import.meta.url); +const styles = new URL('../../../lib/ui/src/lib/styles/', import.meta.url); +const DESIGN_MD = fileURLToPath(new URL('DESIGN.md', app)); +const SOURCES = { + brand: fileURLToPath(new URL('node_modules/@ggml-org/llama-brand/css/colors.css', app)), + primitives: fileURLToPath(new URL('tokens/primitives.css', styles)), + semantic: fileURLToPath(new URL('tokens/semantic.css', styles)), + theme: fileURLToPath(new URL('theme.css', styles)) +}; +// the selectors of the themes a semantic token may change in, and the suffix its twin takes here +const THEMES = [ + { selector: '.theme-matte:not(.dark)', suffix: '-matte' }, + { selector: '.dark', suffix: '-dark' } +]; +// the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height +const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/; +// code takes the body-sm role in the mono stack (see `:where(code, pre, kbd, samp)` in theme.css) +const CODE_ROLE = 'body-sm'; +// Tailwind's own `rounded-full`, for lamps, avatars and round buttons; the other corners are roles in semantic.css +const ROUNDED_FULL = '9999px'; +// the sections this script owns, in the order they appear in the front matter; the next one is written by hand +const SECTIONS = ['colors', 'typography', 'rounded']; +const NEXT_SECTION = 'spacing'; + +/** @param {string} css @returns {string} */ +function stripComments(css) { + return css.replace(/\/\*[\s\S]*?\*\//g, ''); +} + +/** + * The custom properties declared in each top-level block, by the block's selector (or at-rule). + * @param {string} css + * @returns {Map>} + */ +function parseBlocks(css) { + /** @type {Map>} */ + const blocks = new Map(); + const source = stripComments(css); + + let depth = 0; + let start = 0; + let selector = ''; + + for (let i = 0; i < source.length; i++) { + const char = source[i]; + + if (char === '{') { + if (depth === 0) { + selector = source.slice(start, i).trim().split(';').pop()?.trim() ?? ''; + start = i + 1; + } + + depth++; + } else if (char === '}') { + depth--; + + if (depth === 0) { + const declarations = blocks.get(selector) ?? new Map(); + + for (const [, name, value] of source + .slice(start, i) + .matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)) { + declarations.set(name, value.replace(/\s+/g, ' ').trim()); + } + + blocks.set(selector, declarations); + start = i + 1; + } + } + } + + return blocks; +} + +/** @param {string} path @returns {Map>} */ +function readBlocks(path) { + return parseBlocks(readFileSync(path, 'utf8')); +} + +/** @param {string} value */ +const isColorLiteral = (value) => + /^#[0-9a-f]{3,8}$/i.test(value) || + value === 'transparent' || + /^(oklch|oklab|rgb|hsl)\([^()]*\)$/.test(value); +/** @param {string} value */ +const isColorMix = (value) => /^color-mix\(.*\)$/.test(value) && !/\)\s*,/.test(value); +/** @param {string} value */ +const varName = (value) => /^var\(--([\w-]+)\)$/.exec(value)?.[1]; + +function build() { + const brand = readBlocks(SOURCES.brand).get(':root') ?? new Map(); + const primitiveBlocks = readBlocks(SOURCES.primitives); + const primitives = new Map([...brand, ...(primitiveBlocks.get(':root') ?? [])]); + const semanticBlocks = readBlocks(SOURCES.semantic); + const semantic = semanticBlocks.get(':root') ?? new Map(); + const inline = semanticBlocks.get('@theme inline') ?? new Map(); + const theme = readBlocks(SOURCES.theme); + /** @type {Map} name (no dashes) to literal colour */ + const primitiveColors = new Map(); + + for (const [name, value] of primitives) { + if (isColorLiteral(value)) primitiveColors.set(name.slice(2), value); + } + + /** @param {string} value @param {Map} scope */ + const isColor = (value, scope) => { + if (isColorLiteral(value) || isColorMix(value)) return true; + + const ref = varName(value); + + if (!ref) return false; + + if (primitiveColors.has(ref)) return true; + + const next = scope.get(`--${ref}`); + + return next !== undefined && isColor(next, scope); + }; + const semanticColors = [...semantic].filter(([, value]) => isColor(value, semantic)); + const semanticNames = new Set(semanticColors.map(([name]) => name.slice(2))); + /** + * A token's value as the front matter writes it: a reference to another token, a literal, or a mix of them. A + * primitive faded with transparent (`color-mix(in oklch, var(--neutral-100) 30%, transparent)`) is written as the + * colour it is, with its alpha (`oklch(0.97 0 0 / 0.3)`). + * @param {string} value + * @param {(name: string) => string} ref the front matter name a token reference points at + */ + const render = (value, ref) => { + const faded = /^color-mix\(in oklch, var\(--([\w-]+)\) (\d+(?:\.\d+)?)%, transparent\)$/.exec( + value + ); + const base = faded && primitiveColors.get(faded[1]); + + if (faded && base && /^oklch\([^/]*\)$/.test(base)) { + return `${base.slice(0, -1)} / ${Number(faded[2]) / 100})`; + } + + return value.replace(/var\(--([\w-]+)\)/g, (_, name) => `{colors.${ref(name)}}`); + }; + /** @type {[string, string][]} */ + const colors = [['primary', '{colors.action-primary}']]; + + for (const [name, value] of primitiveColors) colors.push([name, value]); + + /** @type {Map} */ + const base = new Map(); + + for (const [name, value] of semanticColors) { + const rendered = render(value, (n) => n); + + base.set(name, rendered); + colors.push([name.slice(2), rendered]); + } + + // a twin per theme wherever the token resolves differently there, directly or through a token it points at + for (const { selector, suffix } of THEMES) { + const overrides = semanticBlocks.get(selector) ?? new Map(); + /** @type {Set} */ + const twins = new Set(); + /** @type {Map} */ + const rendered = new Map(); + // twins resolve in dependency order: a reference to a token that has a twin points at the twin + /** @param {string} name */ + const resolve = (name) => { + if (rendered.has(name)) return /** @type {string} */ (rendered.get(name)); + + const value = overrides.get(name) ?? semantic.get(name) ?? ''; + + for (const [, ref] of value.matchAll(/var\(--([\w-]+)\)/g)) { + if (semanticNames.has(ref)) resolve(`--${ref}`); + } + + const result = render(value, (n) => (twins.has(n) ? `${n}${suffix}` : n)); + + rendered.set(name, result); + + if (result !== base.get(name)) twins.add(name.slice(2)); + + return result; + }; + + for (const [name] of semanticColors) resolve(name); + + for (const [name] of semanticColors) { + if (twins.has(name.slice(2))) + colors.push([`${name.slice(2)}${suffix}`, rendered.get(name) ?? '']); + } + } + + const firstFamily = (/** @type {string | undefined} */ stack) => + stack?.split(',')[0].trim().replace(/^'|'$/g, '') ?? 'system-ui'; + const sans = firstFamily(theme.get('@theme inline')?.get('--font-sans')); + const mono = firstFamily(theme.get(':root')?.get('--font-mono')); + /** @param {string | undefined} value */ + const length = (value) => { + const name = value && varName(value); + + return (name && primitives.get(`--${name}`)) ?? value ?? ''; + }; + /** @type {[string, Record][]} */ + const typography = []; + + for (const [name, value] of inline) { + const role = TYPE_ROLE.exec(name)?.[1]; + + if (!role || !inline.has(`${name}--line-height`)) continue; + + typography.push([ + role, + { + fontFamily: sans, + fontSize: length(value), + fontWeight: length(inline.get(`${name}--font-weight`)), + lineHeight: length(inline.get(`${name}--line-height`)) + } + ]); + } + + const code = typography.find(([role]) => role === CODE_ROLE); + + if (code) typography.push(['code', { ...code[1], fontFamily: mono }]); + + /** @type {[string, string][]} */ + const rounded = []; + + for (const [name, value] of inline) { + const role = /^--radius-([a-z-]+)$/.exec(name)?.[1]; + + if (role) rounded.push([role, length(value)]); + } + + rounded.push(['full', ROUNDED_FULL]); + + /** @param {string} value */ + const quote = (value) => (/^[\w.-]+$/.test(value) ? value : `'${value.replace(/'/g, "''")}'`); + const lines = ['colors:']; + + for (const [name, value] of colors) lines.push(` ${name}: '${value.replace(/'/g, "''")}'`); + + lines.push('typography:'); + + for (const [role, style] of typography) { + lines.push(` ${role}:`); + + for (const [key, value] of Object.entries(style)) lines.push(` ${key}: ${quote(value)}`); + } + + lines.push('rounded:'); + + for (const [role, value] of rounded) lines.push(` ${role}: ${value}`); + + return lines.join('\n') + '\n'; +} + +const check = process.argv.includes('--check'); +const current = readFileSync(DESIGN_MD, 'utf8'); +const start = current.indexOf(`\n${SECTIONS[0]}:\n`) + 1; +const end = current.indexOf(`\n${NEXT_SECTION}:\n`) + 1; + +if (!current.startsWith('---\n') || start <= 0 || end <= start) { + console.error(`DESIGN.md: no front matter with ${SECTIONS[0]}: ... ${NEXT_SECTION}: in it`); + process.exit(1); +} + +const next = current.slice(0, start) + build() + current.slice(end); + +if (check) { + if (next !== current) { + console.error( + 'DESIGN.md is out of date with the tokens: run `npm run design:tokens` in ui/apps/chat and commit it.' + ); + process.exit(1); + } + + console.log('DESIGN.md is current.'); +} else if (next !== current) { + writeFileSync(DESIGN_MD, next); + console.log('DESIGN.md updated.'); +} else { + console.log('DESIGN.md is already current.'); +} diff --git a/ui/apps/chat/tests/stories/actions/ActionIconCopyToClipboard.stories.svelte b/ui/apps/chat/tests/stories/actions/ActionIconCopyToClipboard.stories.svelte index b3fecbd7c..93671ad61 100644 --- a/ui/apps/chat/tests/stories/actions/ActionIconCopyToClipboard.stories.svelte +++ b/ui/apps/chat/tests/stories/actions/ActionIconCopyToClipboard.stories.svelte @@ -1,8 +1,8 @@ - -{#if chapters.length} - -{/if} - - diff --git a/ui/apps/chat/tests/stories/editorial/Editorial.svelte b/ui/apps/chat/tests/stories/editorial/Editorial.svelte deleted file mode 100644 index cdc71ad11..000000000 --- a/ui/apps/chat/tests/stories/editorial/Editorial.svelte +++ /dev/null @@ -1,205 +0,0 @@ - - - -
{@render children()}
- - - - diff --git a/ui/apps/chat/tests/stories/forms/HighlightedMatch.stories.svelte b/ui/apps/chat/tests/stories/forms/HighlightedMatch.stories.svelte index 9eb502f47..046acaef2 100644 --- a/ui/apps/chat/tests/stories/forms/HighlightedMatch.stories.svelte +++ b/ui/apps/chat/tests/stories/forms/HighlightedMatch.stories.svelte @@ -1,8 +1,8 @@ - -
- {#if title} -

{title}

- {/if} - - -
- {@render children()} -
-
diff --git a/ui/apps/chat/tests/stories/helpers/StateGalleryItem.svelte b/ui/apps/chat/tests/stories/helpers/StateGalleryItem.svelte deleted file mode 100644 index 005bea001..000000000 --- a/ui/apps/chat/tests/stories/helpers/StateGalleryItem.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - - -
-
- {label} - - {#if note} - {note} - {/if} -
- -
- {@render children()} -
-
diff --git a/ui/apps/chat/tests/stories/introduction/Introduction.stories.svelte b/ui/apps/chat/tests/stories/introduction/Introduction.stories.svelte index a0eb2594a..10921e5ca 100644 --- a/ui/apps/chat/tests/stories/introduction/Introduction.stories.svelte +++ b/ui/apps/chat/tests/stories/introduction/Introduction.stories.svelte @@ -1,7 +1,7 @@
    diff --git a/ui/apps/chat/tests/stories/introduction/Uses.svelte b/ui/apps/chat/tests/stories/introduction/Uses.svelte index 4c10841d7..36f5d2686 100644 --- a/ui/apps/chat/tests/stories/introduction/Uses.svelte +++ b/ui/apps/chat/tests/stories/introduction/Uses.svelte @@ -1,6 +1,7 @@