An open source design system that's fully customizable and agent ready
TypeScript
feat(native): Swift theme generator warns on lossy values and falls back for impossible ones (#8422)
Cindy Zhanged24daeb0728
diff --git a/packages/native/apple/README.md b/packages/native/apple/README.mdindex fcd66f9b3e..41cb10506a 100644--- a/packages/native/apple/README.md+++ b/packages/native/apple/README.md@@ -149,11 +149,13 @@ node packages/native/scripts/swift-ios-theme.mjs --theme ./src/acmeTheme.ts#acmeThe generator reads the CSS forms its spec lists(`specs/swift/library/theme-generator.md`, G7): hex and named colors, `rgb()`,`hsl()`, `hwb()`, Lab, LCH, OKLab, OKLCH, `color()` in the listed spaces,-`color-mix()`, and relative colors (wide-gamut colors kept as Display P3;-a color outside Display P3 clips, as browsers draw it, with a warning),-lengths with `calc()`, and `[light, dark]` tuples. A value with no static form,-such as `currentColor` or `50%`, stops the run naming the theme, mode, token,-and value; so does a form the generator does not read yet, saying so.+`color-mix()`, and relative colors (wide-gamut colors kept as Display P3),+lengths with `calc()`, and `[light, dark]` tuples. A value it can only+approximate, such as a color outside Display P3 (clipped, as browsers draw it),+prints a warning after the run; a value with no static form, such as+`currentColor` or `50%`, takes core's default for that token with a warning, or+stops the run when core has none. A form the generator does not read yet stops+the run, saying so. Add `--strict` to fail on any warning.A theme's local tokens are not generated yet; the generator names each one itleaves out.diff --git a/packages/native/scripts/css-values.mjs b/packages/native/scripts/css-values.mjsindex 990ff01ccc..de7b29ed5b 100644--- a/packages/native/scripts/css-values.mjs+++ b/packages/native/scripts/css-values.mjs@@ -8,8 +8,8 @@* shadow layers. A conversion that loses something records a note; a value* with no static form throws CssValueError.* @position The value half of the Swift theme generator spec- * (specs/swift/library/theme-generator.md, G7). It reads CSS only;- * swift-ios-theme.mjs decides what an error does to the run.+ * (specs/swift/library/theme-generator.md, G7 and G15). It reads CSS only;+ * swift-ios-theme.mjs decides what a note or an error does to the run.** SYNC: When modified, update this header and G7 in the theme generator spec.*/diff --git a/packages/native/scripts/swift-ios-theme.d.mts b/packages/native/scripts/swift-ios-theme.d.mtsindex 869be81245..59ad3a144d 100644--- a/packages/native/scripts/swift-ios-theme.d.mts+++ b/packages/native/scripts/swift-ios-theme.d.mts@@ -64,15 +64,26 @@ export declare function defineTheme(input: {tokens: Record<string, string | [string, string]>;localTokens?: Record<string, string | [string, string]>;}): Promise<DefinedTheme>;+export interface RenderOptions {+ source?: string;+ regenerate?: string;+ /** Collects one line per lossy conversion; omitted, each prints to stderr (G15). */+ warnings?: string[];+ /** Fails on any lossy conversion instead (G15). */+ strict?: boolean;+}export declare function renderSwiftTheme(theme: DefinedTheme,- options?: {- source?: string;- regenerate?: string;- warn?: (message: string) => void;- },+ options?: RenderOptions,): Promise<string>;+export declare function strictError(warnings: string[]): Error;+export declare function finishRun(+ warnings: string[],+ strict: boolean,+ write: () => void,+): void;export declare function publishedThemePackages(): PublishedThemePackage[];export declare function renderAll(load: ThemeLoader,+ options?: {warnings?: string[]},): Promise<Record<string, string>>;diff --git a/packages/native/scripts/swift-ios-theme.mjs b/packages/native/scripts/swift-ios-theme.mjsindex 21cf046758..c5feada231 100644--- a/packages/native/scripts/swift-ios-theme.mjs+++ b/packages/native/scripts/swift-ios-theme.mjs@@ -11,8 +11,8 @@* @position Implements the Swift theme generator spec* (specs/swift/library/theme-generator.md). Run by `generate:swift-ios`; the* Swift output is committed and a test fails when any file drifts. CSS- * values convert in css-values.mjs; a value it cannot convert fails the- * run (G7).+ * values convert in css-values.mjs; this file turns its notes into+ * warnings and its errors into a fallback or a failed run (G15).** SYNC: When modified, update this header and the theme generator spec.*/@@ -23,7 +23,6 @@ import {fileURLToPath} from 'node:url';import {checkFamilyIsStatic,CssValueError,- OUTSIDE_P3,toColor,toLeading,toPoints,@@ -248,12 +247,15 @@ function convertToken(token, value, group, typedSoFar, notes) {/*** Every kept token of a theme in one mode, read only from core's resolver:- * `{token: {group, member, value}}` with typed values (G1, G5, G7). A value- * with no static form fails the run with the theme, mode, token, value, and- * reason.+ * `{token: {group, member, value}}` with typed values (G1, G5, G7). Each loss+ * is pushed onto `warnings` (G15). A value with no static form takes core's+ * default for that token with a warning; with no default that converts, the+ * run fails.*/-async function resolveMode(theme, mode, warn) {+async function resolveMode(theme, mode, warnings) {const {resolveThemeTokens} = await core();+ const defaults =+ theme === CORE_DEFAULTS ? {} : resolveThemeTokens(null, {mode});const out = {};const entries = Object.entries(resolveThemeTokens(theme === CORE_DEFAULTS ? null : theme, {mode}),@@ -263,37 +265,67 @@ async function resolveMode(theme, mode, warn) {.sort(([a], [b]) => Number(isLeading(a)) - Number(isLeading(b)));for (const [token, value] of entries) {const {group, member} = swiftMember(token);- let typed;+ const where = `${theme.name} ${mode}: ${token} = ${value}`;const notes = [];+ let typed;try {typed = convertToken(token, valueForMode(value, mode), group, out, notes);} catch (error) {if (!(error instanceof CssValueError)) throw error;+ // Notes from the failed read describe a value that is not emitted.+ notes.length = 0;+ const fallback = error.hasNoStaticForm ? defaults[token] : undefined;const outcome = error.hasNoStaticForm? 'Swift has no static value': 'the Swift theme generator does not read this form';- throw new Error(- `${theme.name} ${mode}: ${token} = ${value}: ${error.message}; ${outcome}`,- );+ try {+ if (fallback === undefined) throw error;+ typed = convertToken(+ token,+ valueForMode(fallback, mode),+ group,+ out,+ [],+ );+ } catch {+ throw new Error(`${where}: ${error.message}; ${outcome}`);+ }+ notes.push(`${error.message}; core's default ${fallback} used instead`);+ }+ const emitted = swiftValue(memberType(group, token), typed);+ for (const note of new Set(notes)) {+ warnings.push(`${where} → ${emitted}: ${note}`);}out[token] = {group, member, value: typed};- // A color outside Display P3 warns (G7).- if (notes.includes(OUTSIDE_P3))- warn(`${theme.name} ${mode}: ${token} = ${value}: ${OUTSIDE_P3}`);}return out;}-/** Light and dark tokens of a theme, checked for matching names (G7). */-export async function resolveTheme(theme, {warn = () => {}} = {}) {- const light = await resolveMode(theme, 'light', warn);- const dark = await resolveMode(theme, 'dark', warn);+/** The error `--strict` raises for a run's warnings (G15). */+export function strictError(warnings) {+ return new Error(+ `${warnings.length} warning(s), which --strict treats as errors:\n${warnings.map(w => `error: ${w}`).join('\n')}`,+ );+}++/**+ * Light and dark tokens of a theme, checked for matching names (G7).+ * `warnings` collects every loss (G15); without a list, each prints to+ * standard error. `strict` fails on the first theme with any.+ */+export async function resolveTheme(theme, {warnings, strict = false} = {}) {+ const own = [];+ const light = await resolveMode(theme, 'light', own);+ const dark = await resolveMode(theme, 'dark', own);for (const token of new Set([...Object.keys(light), ...Object.keys(dark)])) {if (!(token in light) || !(token in dark)) {const missing = token in light ? 'dark' : 'light';throw new Error(`${theme.name} ${missing}: ${token} is missing`);}}+ if (strict && own.length) throw strictError(own);+ if (warnings) warnings.push(...own);+ else for (const warning of own) console.warn(`warning: ${warning}`);return {light, dark};}@@ -616,18 +648,16 @@ export const themeFileName = swiftName => `${capitalize(swiftName)}Theme.swift`;* The generated Swift file for one theme (G3). `source` names where the theme* comes from, such as `@astryxdesign/theme-neutral`. A product theme* (`regenerate` set) lives in the app's own target, so it imports `Astryx` and- * its header names the app's own regenerate command.+ * its header names the app's own regenerate command. Each loss goes onto+ * `warnings` (printed to standard error when no list is passed); `strict`+ * turns a loss into an error (G15).*/export async function renderSwiftTheme(theme,- {- source = 'a product theme',- regenerate,- warn = message => console.warn(`warning: ${message}`),- } = {},+ {source = 'a product theme', regenerate, warnings, strict} = {},) {const swiftName = swiftThemeName(theme.name);- const {light, dark} = await resolveTheme(theme, {warn});+ const {light, dark} = await resolveTheme(theme, {warnings, strict});const surface = tokenSurface(light);const header =regenerate === undefined@@ -708,18 +738,22 @@ export async function generatedThemes(load) {return themes;}-/** Every generated file as `{file: contents}`, keyed by absolute path. */-export async function renderAll(load) {+/**+ * Every generated file as `{file: contents}`, keyed by absolute path. Each+ * loss goes onto `warnings`, or prints to standard error without a list+ * (G15).+ */+export async function renderAll(load, {warnings} = {}) {const themes = await generatedThemes(load);const files = {};- const {light} = await resolveTheme(themes[0].theme);+ const {light} = await resolveTheme(themes[0].theme, {warnings: []});files[SWIFT_TOKENS_FILE] = renderTokenTypes(tokenSurface(light));for (const {theme, source} of themes) {const file = path.join(SWIFT_THEME_DIR,themeFileName(swiftThemeName(theme.name)),);- files[file] = await renderSwiftTheme(theme, {source});+ files[file] = await renderSwiftTheme(theme, {source, warnings});}return files;}@@ -735,10 +769,22 @@ async function viteLoad(file) {return module;}+/**+ * Prints a run's warnings at its end, or with `--strict` fails on them before+ * any file is written (G15).+ */+export function finishRun(warnings, strict, write) {+ if (strict && warnings.length) throw strictError(warnings);+ write();+ for (const warning of warnings) console.warn(`warning: ${warning}`);+}+async function main(argv) {+ const strict = argv.includes('--strict');+ const warnings = [];const at = argv.indexOf('--theme');if (at !== -1) {- // A product's own theme: `--theme <module>#<export> [--out <dir>]`.+ // A product's own theme: `--theme <module>#<export> [--out <dir>] [--strict]`.const [modulePath, exportName] = argv[at + 1].split('#');const module = await viteLoad(path.resolve(modulePath));const theme = module[exportName];@@ -746,36 +792,48 @@ async function main(argv) {const outAt = argv.indexOf('--out');const outDir = outAt === -1 ? process.cwd() : path.resolve(argv[outAt + 1]);const file = path.join(outDir, themeFileName(swiftThemeName(theme.name)));- const regenerate = `node packages/native/scripts/swift-ios-theme.mjs --theme ${argv[at + 1]}${outAt === -1 ? '' : ` --out ${argv[outAt + 1]}`}`;- fs.writeFileSync(- file,- await renderSwiftTheme(theme, {source: modulePath, regenerate}),- );- for (const token of localTokensLeftOut(theme)) {- console.warn(`left out: ${theme.name} local token ${token}`);- }- console.log(`wrote ${file}`);+ const regenerate = `node packages/native/scripts/swift-ios-theme.mjs --theme ${argv[at + 1]}${outAt === -1 ? '' : ` --out ${argv[outAt + 1]}`}${strict ? ' --strict' : ''}`;+ const swift = await renderSwiftTheme(theme, {+ source: modulePath,+ regenerate,+ warnings,+ });+ finishRun(warnings, strict, () => {+ fs.writeFileSync(file, swift);+ for (const token of localTokensLeftOut(theme)) {+ console.warn(`left out: ${theme.name} local token ${token}`);+ }+ console.log(`wrote ${file}`);+ });return;}- const files = await renderAll(viteLoad);- for (const {theme} of await generatedThemes(viteLoad)) {- for (const token of localTokensLeftOut(theme)) {- console.warn(- `left out: ${theme.name} local token ${token} (core's resolver does not return local tokens per mode yet)`,- );+ const files = await renderAll(viteLoad, {warnings});+ const themes = await generatedThemes(viteLoad);+ finishRun(warnings, strict, () => {+ for (const {theme} of themes) {+ for (const token of localTokensLeftOut(theme)) {+ console.warn(+ `left out: ${theme.name} local token ${token} (core's resolver does not return local tokens per mode yet)`,+ );+ }}- }- fs.mkdirSync(SWIFT_THEME_DIR, {recursive: true});- for (const existing of fs.readdirSync(SWIFT_THEME_DIR)) {- const file = path.join(SWIFT_THEME_DIR, existing);- if (existing.endsWith('.swift') && !(file in files)) fs.rmSync(file);- }- for (const [file, contents] of Object.entries(files)) {- fs.writeFileSync(file, contents);- console.log(`wrote ${path.relative(PACKAGE_ROOT, file)}`);- }+ fs.mkdirSync(SWIFT_THEME_DIR, {recursive: true});+ for (const existing of fs.readdirSync(SWIFT_THEME_DIR)) {+ const file = path.join(SWIFT_THEME_DIR, existing);+ if (existing.endsWith('.swift') && !(file in files)) fs.rmSync(file);+ }+ for (const [file, contents] of Object.entries(files)) {+ fs.writeFileSync(file, contents);+ console.log(`wrote ${path.relative(PACKAGE_ROOT, file)}`);+ }+ });}if (process.argv[1] === fileURLToPath(import.meta.url)) {- await main(process.argv.slice(2));+ try {+ await main(process.argv.slice(2));+ } catch (error) {+ console.error(`error: ${error.message}`);+ process.exitCode = 1;+ }}diff --git a/packages/native/specs/swift/library/theme-generator.md b/packages/native/specs/swift/library/theme-generator.mdindex e114730753..47d2ecc777 100644--- a/packages/native/specs/swift/library/theme-generator.md+++ b/packages/native/specs/swift/library/theme-generator.md@@ -138,9 +138,8 @@ re-implements theme logic.own `Color(.sRGB, red:green:blue:opacity:)`. A color outside sRGB andinside Display P3 is `Color(.displayP3, red:green:blue:opacity:)` (D5). Acolor outside Display P3 is a value Swift cannot express exactly: each- channel clips to Display P3, as Chromium draws it, and the run prints a- warning naming the theme, mode, token, and value, ending "outside- Display P3; clipped to match the web". Each channel and alpha rounds to the nearest of 256 steps,+ channel clips to Display P3, as Chromium draws it, and the run warns+ (G15), the warning ending "outside Display P3; clipped to match the web". Each channel and alpha rounds to the nearest of 256 steps,halves up, and is written as `0`, `1`, or the exact decimal of its stepover 255 (the same `Double` as `n / 255`); the package declares no colorinitializer of its own.@@ -148,21 +147,21 @@ re-implements theme logic.`pc` × 16, `in` × 96, and `cm`, `mm`, and `Q` from `in`; `calc()`,`min()`, `max()`, and `clamp()` over those; `thin`, `medium`, and`thick` as 1, 3, and 5 for `border-width` only, with no length elsewhere. A unitless number is points. An `em` is read- against the 16-point root.+ against the 16-point root and warns.- Font weights (`font-weight-*`, `text-*-weight`) are numbers from 1 to1000; `normal` is 400 and `bold` 700. `bolder` (700) and `lighter` (100)- are read against 400.+ are read against 400 and warn.- Line heights (`text-*-leading`) are multipliers of the font size: anumber as is, a percentage ÷ 100, a length ÷ the same style's`text-<style>-size` in the same mode (so an `em` counts against that- size and `1.5em` is 1.5), to 12 significant digits. `normal` is 1.2.+ size and `1.5em` is 1.5), to 12 significant digits. `normal` is 1.2 and warns.- Font families are `[String]`, quotes removed, in the CSS stack's order.- Shadows are `[ShadowLayer]`, one per `box-shadow` layer in order, itscolor and lengths in either order; `none` is no layers. A drop layer is`x y [blur [spread]] color`; SwiftUI draws no drop spread, so a spread is- left out. An inset layer is a ring, `inset 0 0 0 <width> color`, which a+ left out and warns. An inset layer is a ring, `inset 0 0 0 <width> color`, which aview draws inside its border, as CSS draws an inset shadow.- - These have no static form: `currentColor`; system colors such as+ - These have no static form (G15): `currentColor`; system colors such as`Canvas`; percentages outside color channels and line heights; viewportand container units; font-relative units (`ex`, `ch`, `ic`, `cap`,`lh`, and their root forms); a `var()` core's resolver leaves unresolved;@@ -170,11 +169,11 @@ re-implements theme logic.kinds; a `color-mix()` whose percentages add up to 0%; a shadow layerwith no color, which draws in `currentColor`; and an offset or blurredinset shadow. This holds in every token, font families and shadows- included. Such a value fails the run with the theme, mode,- token, value, and reason, ending "Swift has no static value". A value- outside the forms above, valid CSS or not, fails the same way but ends- "the Swift theme generator does not read this form", so a reader gap- is not reported as a value Swift cannot hold. A token present in one mode and missing in the other fails+ included. Such a value takes core's default or fails the run as G15+ says, its reason ending "Swift has no static value". A value outside the+ forms above, valid CSS or not, fails the run ending "the Swift theme+ generator does not read this form", so a reader gap is not reported as a+ value Swift cannot hold. A token present in one mode and missing in the other failsthe run with the theme, mode, and token.- **G8 — Theme-local tokens wait for a per-mode source.** A theme's localtokens (AST-006) are generated only once core's resolver returns them per@@ -218,24 +217,46 @@ re-implements theme logic.files are committed beside the Swift sources until CI publishes generatedSwift to a Swift-only branch or tag, as the package README notes.+- **G15 — Every conversion is exact, warned, or an error.**+ - An exact conversion, including G7's stated rounding, prints nothing.+ - A lossy conversion (a color outside Display P3, clipped as Chromium draws+ it; an `em` read against the root; `bolder` or `lighter` read against 400;+ a `normal` line height read as 1.2; a drop shadow's spread left out) emits+ the value and+ one warning naming the theme, mode, token, CSS value, emitted Swift+ value, and what was lost.+ - A value with no static form stops the run with an error naming the+ theme, mode, token, CSS value, and reason, unless the token is optional.+ A token is optional when core fills a default for it: core's resolver+ returns it with no theme (`resolveThemeTokens(null, {mode})`), as it does+ every G5 token. An optional token takes core's default for that mode,+ converted by G7, and warns, naming the default. A token core has no+ default for, a default with no static form, and every token of core's+ own defaults are required.+ - Warnings print after the run writes its files, one line each, starting+ `warning: `. `--strict` turns every warning into an error: the run prints+ each starting `error: `, writes no file, and exits non-zero. A product+ theme (`--theme`) gets the same treatment, and `renderSwiftTheme` takes `warnings` (a list it appends to) and `strict`; called without a list, it prints each warning to standard error, so a loss is never silent. A token's notes print once per mode, and notes from a value that failed are dropped with it, so a fallback's warning names only the failure and core's default.+## Acceptance checks-| Requirement | Check |-| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| G1 | A theme whose resolved token differs from its raw `theme.tokens` entry (a reference) shows the resolved value in Swift. A `DefinedTheme` with web component overrides generates the same file as the same theme without them. |-| G2 | A source check finds no import of core in `packages/native/` outside the build-time reads AST-082 FR16 lists (the two theme entries, core's component documentation, its built-in icon names, and its locale catalogs; later only the portable entry). Generated Swift imports only SwiftUI. |-| G3 | `swiftc -typecheck` compiles `Tokens.swift` and every theme file together; each theme file declares one `Theme` static named as G3 says; two themes with the same name fail the run. |-| G4 | Generating twice, and on two CI machines, gives byte-identical output. |-| G5 | Every theme's light and dark values fill every member of `Tokens`, equal to core's resolved names filtered by the G5 groups. |-| G6 | Unit tests map every row of the G6 table; two tokens that collide fail with both names; a type style without its leading fails naming the style; `Tokens.swift` declares one `TypeStyleTokens` and every theme fills `font.body`, `font.display1`, and `font.heading1` as one. A Swift fixture referencing `theme.color.textPrimray` fails to compile. |-| G7 | A table test converts every listed syntax to its exact 8-bit value (tolerance 0 of 255): CSS Color 4's examples `lab(29.2345% 39.3825 20.0664)`, `oklab(40.101% 0.1147 0.0453)`, and `oklch(40.101% 0.12332 21.555)` generate `#7D2329` and `lch(52.2345% 72.2 56.2)` generates `#C65D06`; `color(display-p3 1 0 0)` generates `Color(.displayP3, red: 1, green: 0, blue: 0, opacity: 1)`; `color-mix(in srgb, red, blue)` generates `#800080`. A `[light, dark]` tuple and a `color-mix()` with a nested `light-dark()` generate each side in its mode. A `20px` line height with a `16px` size generates 1.25. Neutral's `--shadow-low` generates two drop layers and an inset ring, its ring color taken per mode. `"Figtree", -apple-system, sans-serif` becomes `["Figtree", "-apple-system", "sans-serif"]`. Each G7 form with no static form fails with its reason. Generated colors are `Color(.sRGB, …)`, and a Swift test finds `Theme.default.light.color.accent` equal to `Color(.sRGB, red: 0, green: 100 / 255, blue: 224 / 255, opacity: 1)`. A relative `rgb()` over a Display P3 origin stays Display P3; a `1.5em` line height on a 14px style is 1.5; `medium` outside `border-width` fails; a `none` alpha, a missing blue mixed in Lab, and a 400° hue mix as CSS Color 4 reads them; `color-mix(in lab, hsl(0 50% none), lab(50 20 30))` generates `#8E705E` (HSL lightness carries); `hsl(120, 200%, 40%)` and `hsl(120 200% 40%)` generate `#00CC00`; `calc(4px+2px)`, `calc(1rem-2px)`, and a `"Figtree", inherit` family fail as invalid CSS; `color(rec2020 0.4 0.6 0.2)` generates `#4AA829` and `color(rec2020 0.5 0.5 0.5)` generates `#8B8B8B`, as Chromium draws them; `oklch(0.9 0.4 300)` generates Display P3 `#FB7CFF`, as Chromium draws it, and warns "outside Display P3; clipped to match the web" with its theme, mode, token, and value; `currentColor`, `--font-family-body: inherit`, and a colorless shadow layer fail ending "Swift has no static value", and `color(display-p3-linear 1 0 0)` fails ending "the Swift theme generator does not read this form". |-| G8 | Neutral's local tokens generate nothing today and each is reported; a fixture whose local tokens come back per mode generates its values keyed by their exact custom-property names in that theme's `local` maps, none in `Tokens`. |-| G9 | A source check finds no token lookup by string in any component. |-| G10 | On iOS and macOS, a Swift test with no bundled Figtree resolves `font.family.body` to the system font and with a registered test font resolves to that font; on iOS, both scale between Large and AX5. |-| G11 | `Theme.native` exists, is documented, and holds no values. |-| G12 | A test reads `packages/themes/*/package.json` and finds one generated file per non-private package plus `default`. A fixture product theme renders through `renderSwiftTheme`. |-| G13 | Editing one generated value or member name by hand fails the drift test with the regenerate command in the message. |-| G14 | The README's generated-Swift note lists the generated theme files. |+| Requirement | Check |+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| G1 | A theme whose resolved token differs from its raw `theme.tokens` entry (a reference) shows the resolved value in Swift. A `DefinedTheme` with web component overrides generates the same file as the same theme without them. |+| G2 | A source check finds no import of core in `packages/native/` outside the build-time reads AST-082 FR16 lists (the two theme entries, core's component documentation, its built-in icon names, and its locale catalogs; later only the portable entry). Generated Swift imports only SwiftUI. |+| G3 | `swiftc -typecheck` compiles `Tokens.swift` and every theme file together; each theme file declares one `Theme` static named as G3 says; two themes with the same name fail the run. |+| G4 | Generating twice, and on two CI machines, gives byte-identical output. |+| G5 | Every theme's light and dark values fill every member of `Tokens`, equal to core's resolved names filtered by the G5 groups. |+| G6 | Unit tests map every row of the G6 table; two tokens that collide fail with both names; a type style without its leading fails naming the style; `Tokens.swift` declares one `TypeStyleTokens` and every theme fills `font.body`, `font.display1`, and `font.heading1` as one. A Swift fixture referencing `theme.color.textPrimray` fails to compile. |+| G7 | A table test converts every listed syntax to its exact 8-bit value (tolerance 0 of 255): CSS Color 4's examples `lab(29.2345% 39.3825 20.0664)`, `oklab(40.101% 0.1147 0.0453)`, and `oklch(40.101% 0.12332 21.555)` generate `#7D2329` and `lch(52.2345% 72.2 56.2)` generates `#C65D06`; `color(display-p3 1 0 0)` generates `Color(.displayP3, red: 1, green: 0, blue: 0, opacity: 1)`; `color-mix(in srgb, red, blue)` generates `#800080`. A `[light, dark]` tuple and a `color-mix()` with a nested `light-dark()` generate each side in its mode. A `20px` line height with a `16px` size generates 1.25. Neutral's `--shadow-low` generates two drop layers and an inset ring, its ring color taken per mode. `"Figtree", -apple-system, sans-serif` becomes `["Figtree", "-apple-system", "sans-serif"]`. Each G7 form with no static form is reported with its reason and handled as G15 says. Generated colors are `Color(.sRGB, …)`, and a Swift test finds `Theme.default.light.color.accent` equal to `Color(.sRGB, red: 0, green: 100 / 255, blue: 224 / 255, opacity: 1)`. A relative `rgb()` over a Display P3 origin stays Display P3; a `1.5em` line height on a 14px style is 1.5; `medium` outside `border-width` fails; a `none` alpha, a missing blue mixed in Lab, and a 400° hue mix as CSS Color 4 reads them; `color-mix(in lab, hsl(0 50% none), lab(50 20 30))` generates `#8E705E` (HSL lightness carries); `hsl(120, 200%, 40%)` and `hsl(120 200% 40%)` generate `#00CC00`; `calc(4px+2px)`, `calc(1rem-2px)`, and a `"Figtree", inherit` family fail as invalid CSS; `color(rec2020 0.4 0.6 0.2)` generates `#4AA829` and `color(rec2020 0.5 0.5 0.5)` generates `#8B8B8B`, as Chromium draws them; `oklch(0.9 0.4 300)` generates Display P3 `#FB7CFF`, as Chromium draws it, and warns "outside Display P3; clipped to match the web" with its theme, mode, token, and value; `currentColor`, `--font-family-body: inherit`, and a colorless shadow layer are reported as having no static form (G15: core's default with a warning, or a failed run ending "Swift has no static value" when core has none), and `color(display-p3-linear 1 0 0)` fails ending "the Swift theme generator does not read this form". |+| G8 | Neutral's local tokens generate nothing today and each is reported; a fixture whose local tokens come back per mode generates its values keyed by their exact custom-property names in that theme's `local` maps, none in `Tokens`. |+| G9 | A source check finds no token lookup by string in any component. |+| G10 | On iOS and macOS, a Swift test with no bundled Figtree resolves `font.family.body` to the system font and with a registered test font resolves to that font; on iOS, both scale between Large and AX5. |+| G11 | `Theme.native` exists, is documented, and holds no values. |+| G12 | A test reads `packages/themes/*/package.json` and finds one generated file per non-private package plus `default`. A fixture product theme renders through `renderSwiftTheme`. |+| G13 | Editing one generated value or member name by hand fails the drift test with the regenerate command in the message. |+| G14 | The README's generated-Swift note lists the generated theme files. |+| G15 | `oklch(0.7 0.4 150)` emits `Color(.displayP3, red: 0, green: 0.8196078431372549, blue: 0, opacity: 1)`, clipped as Chromium draws it, and warns in light and dark with theme, mode, token, value, and that Swift value, ending "outside Display P3; clipped to match the web"; `--spacing-4: 2vw` emits core's default and warns; `currentColor` in a token core has no default for fails with theme, mode, token, value, and reason; with `--strict`, a theme that warns fails and no file is written. Without a list, `renderSwiftTheme` prints each warning to standard error; `calc(1em + 2vw)` falls back with one warning that does not mention the `em`; `calc(1em + 1em)` warns once per mode. |## Decisions@@ -276,7 +297,7 @@ re-implements theme logic.Display P3, and a browser on them draws an out-of-sRGB theme color inDisplay P3, so a theme color outside sRGB generates as SwiftUI's own`Color(.displayP3, …)`, with no Astryx initializer around it, and only a- color outside Display P3 is clipped, as browsers draw it, with a warning (G7). Rejected: mapping every color into sRGB, because a brand+ color outside Display P3 is clipped, as browsers draw it, with a warning (G15). Rejected: mapping every color into sRGB, because a brandcolor would then draw duller in Swift than on the web on the same device.## Current state@@ -301,7 +322,8 @@ re-implements theme logic.- Core's resolver substitutes `var()` references between tokens andevaluates `color-mix(in srgb, …)` over the colors it parses; the generatorconverts every other G7 form itself.-- Every color in the published themes is inside sRGB.+- Every published theme generates with no warning, and every color in them is+ inside sRGB.## Open questionsdiff --git a/packages/native/src/theme/swiftIOSTheme.test.ts b/packages/native/src/theme/swiftIOSTheme.test.tsindex 312aa20eee..2f207bfb0a 100644--- a/packages/native/src/theme/swiftIOSTheme.test.ts+++ b/packages/native/src/theme/swiftIOSTheme.test.ts@@ -2,12 +2,13 @@import fs from 'node:fs';import path from 'node:path';-import {describe, expect, it} from 'vitest';+import {describe, expect, it, vi} from 'vitest';import {CORE_DEFAULTS,SWIFT_THEME_DIR,SWIFT_TOKENS_FILE,defineTheme,+ finishRun,localTokensLeftOut,publishedThemePackages,renderAll,@@ -319,34 +320,41 @@ describe('swift theme generator: values (G7)', () => {expect(dark).toContain('s4: 12,');});- it('fails on a value with no static form, naming theme, mode, token, value, and reason', async () => {- const theme = await defineTheme({- name: 'acme-brand',- tokens: {'--color-accent': 'currentColor'},- });- await expect(renderSwiftTheme(theme)).rejects.toThrow(- 'acme-brand light: --color-accent = currentColor: currentColor depends on where the token is used; Swift has no static value',- );- });-- // A value with no static form, and a form the reader does not read, each- // fail with their own ending (G7).- const NONE = 'Swift has no static value';- const READ = 'the Swift theme generator does not read this form';+ // A value with no static form takes core's default and warns (G15).it.each([- ['--font-family-body', 'inherit', 'inherit depends on', NONE],- ['--font-family-body', '"Figtree", env(x)', 'env() is known', NONE],- ['--font-family-body', '"Figtree", inherit', 'cannot be one name', READ],- ['--shadow-low', 'inherit', 'inherit depends on', NONE],- ['--shadow-low', '0 1px 2px', 'draws in currentColor', NONE],- ['--color-accent', 'color(display-p3-linear 1 0 0)', 'not a color', READ],- ])('fails %s: %s, saying why', async (token, value, reason, ending) => {+ ['--font-family-body', 'inherit', 'inherit depends on'],+ ['--font-family-body', '"Figtree", env(x)', 'env() is known'],+ ['--shadow-low', 'inherit', 'inherit depends on'],+ ['--shadow-low', '0 1px 2px', 'draws in currentColor'],+ ])('falls back from %s: %s, warning why', async (token, value, reason) => {const theme = await defineTheme({name: 'acme', tokens: {[token]: value}});- const {message} = await renderSwiftTheme(theme).catch(error => error);- expect(message).toContain(reason);- expect(message.endsWith(`; ${ending}`)).toBe(true);+ const warnings: string[] = [];+ await renderSwiftTheme(theme, {warnings});+ expect(warnings).toHaveLength(2);+ for (const warning of warnings) {+ expect(warning).toContain(reason);+ expect(warning).toContain("core's default");+ }});+ // A form the reader does not read fails, saying so (G7).+ it.each([+ ['--font-family-body', '"Figtree", inherit', 'cannot be one name'],+ ['--color-accent', 'color(display-p3-linear 1 0 0)', 'not a color'],+ ])(+ 'fails %s: %s as a form it does not read',+ async (token, value, reason) => {+ const theme = await defineTheme({name: 'acme', tokens: {[token]: value}});+ const {message} = await renderSwiftTheme(theme, {warnings: []}).catch(+ error => error,+ );+ expect(message).toContain(reason);+ expect(+ message.endsWith('; the Swift theme generator does not read this form'),+ ).toBe(true);+ },+ );+it('reads + and - in calc() only with a space on each side, as CSS does', () => {expect(toPoints('calc(1rem - 2px)')).toBe(14);expect(() => toPoints('calc(4px+2px)')).toThrow(/space on each side of \+/);@@ -363,22 +371,6 @@ describe('swift theme generator: values (G7)', () => {expect(() => toColor(css)).toThrow(reason);});- it('warns, naming theme, mode, token, and value, when it clips a color outside Display P3', async () => {- const theme = await defineTheme({- name: 'acme-brand',- tokens: {'--color-accent': 'oklch(0.9 0.4 300)'},- });- const warnings: string[] = [];- const swift = await renderSwiftTheme(theme, {- warn: message => warnings.push(message),- });- expect(swift).toContain('accent: Color(.displayP3,');- expect(warnings).toEqual([- 'acme-brand light: --color-accent = oklch(0.9 0.4 300): outside Display P3; clipped to match the web',- 'acme-brand dark: --color-accent = oklch(0.9 0.4 300): outside Display P3; clipped to match the web',- ]);- });-it("writes a color outside sRGB as SwiftUI's Display P3 color", async () => {const theme = await defineTheme({name: 'acme-brand',@@ -413,6 +405,115 @@ describe('swift theme generator: values (G7)', () => {});});+describe('swift theme generator: diagnostics (G15)', () => {+ it('warns on a lossy value with theme, mode, token, value, and output', async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--color-accent': 'oklch(0.7 0.4 150)'},+ });+ const warnings: string[] = [];+ const swift = await renderSwiftTheme(theme, {warnings});+ expect(swift).toContain(+ 'accent: Color(.displayP3, red: 0, green: 0.8196078431372549, blue: 0, opacity: 1)',+ );+ expect(warnings).toEqual([+ `acme-brand light: --color-accent = oklch(0.7 0.4 150) → Color(.displayP3, red: 0, green: 0.8196078431372549, blue: 0, opacity: 1): ${P3_CLIPPED}`,+ `acme-brand dark: --color-accent = oklch(0.7 0.4 150) → Color(.displayP3, red: 0, green: 0.8196078431372549, blue: 0, opacity: 1): ${P3_CLIPPED}`,+ ]);+ });++ it("takes core's default for a value with no static form, with a warning", async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--spacing-4': '2vw'},+ });+ const warnings: string[] = [];+ const swift = await renderSwiftTheme(theme, {warnings});+ const core = await renderSwiftTheme(CORE_DEFAULTS);+ const s4 = (text: string) => /s4: [\d.]+/.exec(text)?.[0];+ expect(s4(swift)).toBe(s4(core));+ expect(warnings[0]).toMatch(+ /^acme-brand light: --spacing-4 = 2vw → \d+: viewport units depend on the screen; core's default \S+ used instead$/,+ );+ });++ it('fails when a value has no static form and core has no default', async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--color-acme-only': 'currentColor'},+ });+ await expect(renderSwiftTheme(theme)).rejects.toThrow(+ 'acme-brand light: --color-acme-only = currentColor: currentColor depends on where the token is used; Swift has no static value',+ );+ });++ it('prints warnings to standard error when no list is passed', async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--color-accent': 'oklch(0.7 0.4 150)'},+ });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ await renderSwiftTheme(theme);+ expect(warn).toHaveBeenCalledTimes(2);+ expect(warn.mock.calls[0][0]).toMatch(+ /^warning: acme-brand light: --color-accent = oklch\(0\.7 0\.4 150\) → /,+ );+ } finally {+ warn.mockRestore();+ }+ });++ it("drops a failed value's notes before falling back to core's default", async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--spacing-4': 'calc(1em + 2vw)'},+ });+ const warnings: string[] = [];+ await renderSwiftTheme(theme, {warnings});+ expect(warnings).toHaveLength(2);+ for (const warning of warnings) {+ expect(warning).toMatch(+ /viewport units depend on the screen; core's default/,+ );+ expect(warning).not.toMatch(/em read/);+ }+ });++ it("prints a token's note once per mode", async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--spacing-4': 'calc(1em + 1em)'},+ });+ const warnings: string[] = [];+ await renderSwiftTheme(theme, {warnings});+ expect(warnings).toEqual([+ 'acme-brand light: --spacing-4 = calc(1em + 1em) → 32: em read against the 16px root font size',+ 'acme-brand dark: --spacing-4 = calc(1em + 1em) → 32: em read against the 16px root font size',+ ]);+ });++ it('turns warnings into errors with --strict, before anything is written', async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--color-accent': 'oklch(0.7 0.4 150)'},+ });+ await expect(renderSwiftTheme(theme, {strict: true})).rejects.toThrow(+ /2 warning\(s\), which --strict treats as errors:\nerror: acme-brand light: --color-accent/,+ );+ let wrote = false;+ const write = () => {+ wrote = true;+ };+ expect(() => finishRun(['a warning'], true, write)).toThrow(+ /error: a warning/,+ );+ expect(wrote).toBe(false);+ finishRun([], true, write);+ expect(wrote).toBe(true);+ });+});+describe('swift theme generator: local tokens (G8)', () => {it('generates no local token and reports each one it leaves out', async () => {const theme = await defineTheme({