An open source design system that's fully customizable and agent ready
TypeScript
feat(native): Swift theme generator reads the CSS colors and lengths its spec lists (#8420)
Cindy Zhang1ffa1660c660
diff --git a/packages/native/apple/README.md b/packages/native/apple/README.mdindex 16aad346ca..fcd66f9b3e 100644--- a/packages/native/apple/README.md+++ b/packages/native/apple/README.md@@ -146,6 +146,15 @@ export:node packages/native/scripts/swift-ios-theme.mjs --theme ./src/acmeTheme.ts#acmeTheme --out ./Sources/Theme```+The 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.+A theme's local tokens are not generated yet; the generator names each one itleaves out.diff --git a/packages/native/scripts/css-values.d.mts b/packages/native/scripts/css-values.d.mtsnew file mode 100644index 0000000000..8c710db030--- /dev/null+++ b/packages/native/scripts/css-values.d.mts@@ -0,0 +1,36 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++export declare class CssValueError extends Error {+ constructor(reason: string, options?: {hasNoStaticForm?: boolean});+ readonly hasNoStaticForm: boolean;+}+export declare const ROOT_FONT_SIZE: number;+export declare const OUTSIDE_P3: string;+export declare function checkFamilyIsStatic(value: string): void;+export declare function valueForMode(+ value: string,+ mode: 'light' | 'dark',+): string;+export declare function toColor(value: string, notes?: string[]): string;+export declare function toPoints(+ value: string,+ notes?: string[],+ options?: {borderWidth?: boolean},+): number;+export declare function toWeight(value: string, notes?: string[]): number;+export declare function toLeading(+ value: string,+ fontSize: number | undefined,+ notes?: string[],+): number;+export declare function toShadow(+ value: string,+ notes?: string[],+): {+ x: number;+ y: number;+ blur: number;+ spread: number;+ isInset: boolean;+ color: string;+}[];diff --git a/packages/native/scripts/css-values.mjs b/packages/native/scripts/css-values.mjsnew file mode 100644index 0000000000..990ff01ccc--- /dev/null+++ b/packages/native/scripts/css-values.mjs@@ -0,0 +1,1135 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file scripts/css-values.mjs+ * @input One resolved CSS token value for one mode (core's resolver output)+ * @output A static value Swift can hold: a color as 8-bit sRGB or Display P3+ * channels, a length in points, a font weight, a line-height multiplier, or+ * 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.+ *+ * SYNC: When modified, update this header and G7 in the theme generator spec.+ */++/**+ * A value the generator cannot convert. `reason` says why, in plain words;+ * `hasNoStaticForm` is true when CSS itself gives the value no static form+ * (G7's list), and false when it is a form the generator does not read.+ */+export class CssValueError extends Error {+ constructor(reason, {hasNoStaticForm = false} = {}) {+ super(reason);+ this.hasNoStaticForm = hasNoStaticForm;+ }+}+const fail = reason => {+ throw new CssValueError(reason);+};+const noStaticForm = reason => {+ throw new CssValueError(reason, {hasNoStaticForm: true});+};++export const ROOT_FONT_SIZE = 16;++/** The warning for a color outside Display P3, clipped as browsers draw it. */+export const OUTSIDE_P3 = 'outside Display P3; clipped to match the web';++const REC2020_ALPHA = 1.09929682680944;+const REC2020_BETA = 0.018053968510807;++// ---------------------------------------------------------------------------+// Mode: light-dark() anywhere in a value+// ---------------------------------------------------------------------------++/** Index of the `)` that closes the `(` at `open`, or -1. */+function closing(text, open) {+ let depth = 0;+ for (let i = open; i < text.length; i++) {+ if (text[i] === '(') depth++;+ else if (text[i] === ')' && --depth === 0) return i;+ }+ return -1;+}++/** Splits at top-level commas. */+function splitTopLevel(text) {+ const parts = [];+ let depth = 0;+ let start = 0;+ for (let i = 0; i < text.length; i++) {+ if (text[i] === '(') depth++;+ else if (text[i] === ')') depth--;+ else if (text[i] === ',' && depth === 0) {+ parts.push(text.slice(start, i).trim());+ start = i + 1;+ }+ }+ parts.push(text.slice(start).trim());+ return parts;+}++/**+ * The value in one mode: every `light-dark(a, b)`, at any depth, becomes `a`+ * in light and `b` in dark.+ */+export function valueForMode(value, mode) {+ const re = /light-dark\(/gi;+ let out = '';+ let from = 0;+ let m;+ while ((m = re.exec(value))) {+ const open = m.index + m[0].length - 1;+ const close = closing(value, open);+ if (close === -1) fail('it has an unclosed light-dark()');+ const sides = splitTopLevel(value.slice(open + 1, close));+ if (sides.length !== 2) fail('light-dark() needs exactly two values');+ out +=+ value.slice(from, m.index) ++ valueForMode(sides[mode === 'dark' ? 1 : 0], mode);+ from = close + 1;+ re.lastIndex = from;+ }+ return out + value.slice(from);+}++// ---------------------------------------------------------------------------+// Tokens+// ---------------------------------------------------------------------------++const NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i;+const IDENT = /^-?-?[a-z_][\w-]*/i;++/**+ * A CSS value as tokens: `{t:'num', v, u}`, `{t:'id', v}`, `{t:'hash', v}`,+ * `{t:'fn', name, body}`, and `,` `/` `+` `-` `*` as `{t:'op', v}`.+ */+function tokenize(text) {+ const out = [];+ let i = 0;+ while (i < text.length) {+ const rest = text.slice(i);+ const c = text[i];+ let m;+ if (/\s/.test(c)) {+ i++;+ } else if (+ (m = NUMBER.exec(rest)) &&+ // A sign right after a value is a calc() operator, not part of a number.+ !(+ /^[+-]/.test(c) &&+ out.at(-1)?.t !== 'op' &&+ /\S/.test(text[i - 1] ?? ' ')+ )+ ) {+ i += m[0].length;+ const unit = /^(%|[a-z]+)/i.exec(text.slice(i));+ const u = unit ? unit[1].toLowerCase() : '';+ i += u.length;+ out.push({t: 'num', v: parseFloat(m[0]), u});+ } else if ((m = IDENT.exec(rest))) {+ i += m[0].length;+ if (text[i] === '(') {+ const close = closing(text, i);+ if (close === -1) fail(`it has an unclosed ${m[0]}()`);+ const name = m[0].toLowerCase();+ const inner = text.slice(i + 1, close);+ // Strings inside var(), env() and url() are not values to tokenize.+ const opaque = /^(var|env|attr|url)$/.test(name);+ out.push({t: 'fn', name, body: opaque ? inner : tokenize(inner)});+ i = close + 1;+ } else {+ out.push({t: 'id', v: m[0].toLowerCase()});+ }+ } else if (c === '#') {+ m = /^#([0-9a-z]+)/i.exec(rest) ?? fail(`"${rest}" is not CSS`);+ i += m[0].length;+ out.push({t: 'hash', v: m[1]});+ } else if (c === '(') {+ const close = closing(text, i);+ if (close === -1) fail('it has an unclosed (');+ out.push({t: 'fn', name: '', body: tokenize(text.slice(i + 1, close))});+ i = close + 1;+ } else if (',/+-*'.includes(c)) {+ // calc() reads + and - as operators only with a space on each side.+ const spaced =+ /\s/.test(text[i - 1] ?? ' ') && /\s/.test(text[i + 1] ?? ' ');+ out.push({t: 'op', v: c, spaced});+ i++;+ } else {+ fail(`"${c}" is not part of a value Swift can read`);+ }+ }+ return out;+}++/** Splits tokens at `,`. */+function commas(tokens) {+ const parts = [[]];+ for (const tok of tokens) {+ if (tok.t === 'op' && tok.v === ',') parts.push([]);+ else parts[parts.length - 1].push(tok);+ }+ return parts;+}++// ---------------------------------------------------------------------------+// Numbers and math functions+// ---------------------------------------------------------------------------++const LENGTH_UNITS = {+ px: 1,+ rem: ROOT_FONT_SIZE,+ em: ROOT_FONT_SIZE,+ pt: 4 / 3,+ pc: 16,+ in: 96,+ cm: 96 / 2.54,+ mm: 96 / 25.4,+ q: 96 / 101.6,+};+const ANGLE_UNITS = {deg: 1, grad: 0.9, rad: 180 / Math.PI, turn: 360};+const CONTEXT_UNITS = {+ '%': 'a percentage depends on the box it is used in',+ vh: 'viewport units depend on the screen',+ vw: 'viewport units depend on the screen',+ vmin: 'viewport units depend on the screen',+ vmax: 'viewport units depend on the screen',+ ex: 'font-relative units depend on the font in use',+ ch: 'font-relative units depend on the font in use',+ lh: 'font-relative units depend on the font in use',+};++/**+ * A number with its kind: `number`, `length` (px), `angle` (deg), or+ * `percent`. `vars` names channel keywords in relative colors.+ */+function quantity(tok, vars, notes, em = null) {+ if (tok.t === 'num') {+ if (tok.u === '') return {v: tok.v, k: 'number'};+ if (tok.u === '%') return {v: tok.v, k: 'percent'};+ if (tok.u in LENGTH_UNITS) {+ if (tok.u === 'em') {+ if (em != null) return {v: tok.v * em, k: 'length'};+ if (tok.v !== 0) {+ notes.push(`em read against the ${ROOT_FONT_SIZE}px root font size`);+ }+ }+ return {v: tok.v * LENGTH_UNITS[tok.u], k: 'length'};+ }+ if (tok.u in ANGLE_UNITS)+ return {v: tok.v * ANGLE_UNITS[tok.u], k: 'angle'};+ const context =+ CONTEXT_UNITS[tok.u] ??+ (/^(d|s|l)?v(h|w|i|b|min|max)$|^cq/.test(tok.u)+ ? 'viewport and container units depend on the screen'+ : /^r?(ex|ch|ic|cap|lh)$/.test(tok.u)+ ? 'font-relative units depend on the font in use'+ : null);+ if (context) noStaticForm(context);+ fail(`"${tok.u}" is not a unit Swift can read`);+ }+ if (tok.t === 'id') {+ if (vars && tok.v in vars) {+ const v = vars[tok.v];+ return {v: Number.isNaN(v) ? 0 : v, k: 'number'};+ }+ if (tok.v === 'pi') return {v: Math.PI, k: 'number'};+ if (tok.v === 'e') return {v: Math.E, k: 'number'};+ }+ if (tok.t === 'fn') return dynamic(tok) ?? math(tok, vars, notes, em);+ return dynamic(tok) ?? fail(`"${show(tok)}" is not a number`);+}++/** Evaluates calc(), min(), max(), clamp(), or a bare ( ) group. */+function math(tok, vars, notes, em) {+ const args = commas(tok.body).map(part => sum(part, vars, notes, em));+ const same = () => {+ const kinds = new Set(args.map(a => a.k));+ if (kinds.size > 1) fail(`${tok.name}() mixes ${[...kinds].join(' and ')}`);+ return args[0].k;+ };+ switch (tok.name) {+ case '':+ case 'calc':+ if (args.length !== 1) fail(`${tok.name || '( )'} takes one expression`);+ return args[0];+ case 'min':+ case 'max':+ return {v: Math[tok.name](...args.map(a => a.v)), k: same()};+ case 'clamp':+ if (args.length !== 3) fail('clamp() takes three values');+ return {+ v: Math.max(args[0].v, Math.min(args[1].v, args[2].v)),+ k: same(),+ };+ default:+ return fail(`${tok.name}() is not a function Swift can read`);+ }+}++/** `+ -` over `* /` over quantities, as calc() reads them. */+function sum(tokens, vars, notes, em) {+ if (!tokens.length) fail('an expression is empty');+ let i = 0;+ const product = () => {+ let left = quantity(tokens[i++], vars, notes, em);+ while (tokens[i]?.t === 'op' && '*/'.includes(tokens[i].v)) {+ const op = tokens[i++].v;+ const right = quantity(+ tokens[i++] ?? fail('an expression ends early'),+ vars,+ notes,+ em,+ );+ if (op === '*') {+ if (left.k !== 'number' && right.k !== 'number') {+ fail('calc() multiplies two dimensions');+ }+ left = {v: left.v * right.v, k: left.k === 'number' ? right.k : left.k};+ } else {+ if (right.k !== 'number' || right.v === 0) {+ fail('calc() divides by a dimension or by zero');+ }+ left = {v: left.v / right.v, k: left.k};+ }+ }+ return left;+ };+ let total = product();+ while (i < tokens.length) {+ const op = tokens[i++];+ if (op.t !== 'op' || !'+-'.includes(op.v))+ fail('calc() is missing an operator');+ if (!op.spaced) fail(`calc() needs a space on each side of ${op.v}`);+ const right = product();+ if (right.k !== total.k)+ noStaticForm(`calc() adds ${total.k} and ${right.k}`);+ total = {+ v: op.v === '+' ? total.v + right.v : total.v - right.v,+ k: total.k,+ };+ }+ return total;+}++/**+ * Fails when a font-family value has no static form (G7): a CSS-wide keyword,+ * or `var()`, `env()`, or `attr()` outside a quoted name. A CSS-wide keyword+ * as one name in a list is not valid CSS, so it fails too.+ */+export function checkFamilyIsStatic(value) {+ const bare = value+ .replace(/"[^"]*"|'[^']*'/g, '""')+ .trim()+ .toLowerCase();+ if (/^(inherit|initial|unset|revert|revert-layer)$/.test(bare))+ noStaticForm(`${bare} depends on where the token is used`);+ const page = /\b(env|attr)\(/.exec(bare);+ if (page) noStaticForm(`${page[1]}() is known only on the page`);+ const unresolved = /\bvar\(([^)]*)\)/.exec(bare);+ if (unresolved)+ noStaticForm(`var(${unresolved[1]}) is not a token core's resolver knows`);+ const listed = bare+ .split(',')+ .map(name => name.trim())+ .find(name => /^(inherit|initial|unset|revert|revert-layer)$/.test(name));+ if (listed) fail(`${listed} cannot be one name in a font-family list`);+}++/** The reason a token can only be known where it is used, or null. */+function dynamic(tok) {+ if (tok.t === 'fn' && tok.name === 'var') {+ return noStaticForm(+ `var(${tok.body}) is not a token core's resolver knows`,+ );+ }+ if (tok.t === 'fn' && /^(env|attr)$/.test(tok.name)) {+ return noStaticForm(`${tok.name}() is known only on the page`);+ }+ if (+ tok.t === 'id' &&+ /^(inherit|initial|unset|revert|revert-layer)$/.test(tok.v)+ ) {+ return noStaticForm(`${tok.v} depends on where the token is used`);+ }+ return null;+}++const show = tok =>+ tok.t === 'num'+ ? `${tok.v}${tok.u}`+ : tok.t === 'hash'+ ? `#${tok.v}`+ : tok.t === 'fn'+ ? `${tok.name}()`+ : tok.v;++// ---------------------------------------------------------------------------+// Lengths, weights, line heights+// ---------------------------------------------------------------------------++/** One quantity from a whole value. */+function single(value, notes, em = null) {+ const tokens = tokenize(value);+ if (tokens.length !== 1) fail(`"${value}" is not one value`);+ return quantity(tokens[0], null, notes, em);+}++const BORDER_KEYWORDS = {thin: 1, medium: 3, thick: 5};++/**+ * A length in points: px × 1, rem and em × 16, pt × 4/3, math over them.+ * `thin`, `medium`, and `thick` are lengths only for a border width.+ */+export function toPoints(value, notes = [], {borderWidth = false} = {}) {+ const v = value.trim().toLowerCase();+ if (v in BORDER_KEYWORDS) {+ if (borderWidth) return BORDER_KEYWORDS[v];+ fail(`${v} names a border width; here it has no length`);+ }+ const q = single(value, notes);+ if (q.k === 'percent') noStaticForm(CONTEXT_UNITS['%']);+ if (q.k !== 'length' && q.k !== 'number') fail(`a ${q.k} is not a length`);+ return q.v;+}++/** A font weight from 1 to 1000; `normal` 400, `bold` 700. */+export function toWeight(value, notes = []) {+ const v = value.trim().toLowerCase();+ if (v === 'normal') return 400;+ if (v === 'bold') return 700;+ if (v === 'bolder' || v === 'lighter') {+ notes.push(`${v} read against normal (400), the root's inherited weight`);+ return v === 'bolder' ? 700 : 100;+ }+ const q = single(value, notes);+ if (q.k !== 'number' || q.v < 1 || q.v > 1000) {+ fail('a font weight is a number from 1 to 1000');+ }+ return q.v;+}++/**+ * A line height as a multiplier of the font size: a number as is, a+ * percentage ÷ 100, a length ÷ `fontSize` (points), so an `em` counts+ * against the style's own size. `normal` depends on the font, so it reads as+ * 1.2 with a note.+ */+export function toLeading(value, fontSize, notes = []) {+ if (value.trim().toLowerCase() === 'normal') {+ notes.push('normal depends on the font; read as 1.2');+ return 1.2;+ }+ const q = single(value, notes, fontSize || null);+ if (q.k === 'number') return q.v;+ if (q.k === 'percent') return q.v / 100;+ if (q.k === 'length') {+ if (!fontSize) fail("a length line height needs its style's font size");+ return Number((q.v / fontSize).toPrecision(12));+ }+ return fail(`a ${q.k} is not a line height`);+}++// ---------------------------------------------------------------------------+// Color spaces+// ---------------------------------------------------------------------------++const mul = (m, [a, b, c]) => m.map(r => r[0] * a + r[1] * b + r[2] * c);+const D50_WHITE = [0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585];+const D65_TO_D50 = [+ [1.0479297925449969, 0.022946870601609652, -0.05019226628920524],+ [0.02962780877005599, 0.9904344267538799, -0.017073799063418826],+ [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371],+];+const D50_TO_D65 = [+ [0.955473421488075, -0.02309845494876471, 0.06325924320057072],+ [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323],+ [0.012314014864481998, -0.020507649298898964, 1.330365926242124],+];+const sign = (c, f) => (c < 0 ? -f(-c) : f(c));+const SRGB_TRC = {+ toLinear: c =>+ sign(c, x => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4)),+ fromLinear: c =>+ sign(c, x => (x <= 0.0031308 ? x * 12.92 : 1.055 * x ** (1 / 2.4) - 0.055)),+};+const LINEAR = {toLinear: c => c, fromLinear: c => c};++// RGB spaces: transfer function, linear → XYZ matrix, its inverse, and the+// white point the matrix lands on (CSS Color 4, section 18).+const RGB_SPACES = {+ srgb: {+ trc: SRGB_TRC,+ white: 'd65',+ toXYZ: [+ [0.41239079926595934, 0.357584339383878, 0.1804807884018343],+ [0.21263900587151027, 0.715168678767756, 0.07219231536073371],+ [0.01933081871559182, 0.11919477979462598, 0.9505321522496607],+ ],+ fromXYZ: [+ [3.2409699419045226, -1.537383177570094, -0.4986107602930034],+ [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559],+ [0.05563007969699366, -0.20397695888897652, 1.0569715142428786],+ ],+ },+ 'display-p3': {+ trc: SRGB_TRC,+ white: 'd65',+ toXYZ: [+ [0.4865709486482162, 0.26566769316909306, 0.1982172852343625],+ [0.2289745640697488, 0.6917385218365064, 0.079286914093745],+ [0, 0.04511338185890264, 1.043944368900976],+ ],+ fromXYZ: [+ [2.493496911941425, -0.9313836179191239, -0.40271078445071684],+ [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577],+ [0.03584583024378447, -0.07617238926804182, 0.9568845240076872],+ ],+ },+ 'a98-rgb': {+ trc: {+ toLinear: c => sign(c, x => x ** (563 / 256)),+ fromLinear: c => sign(c, x => x ** (256 / 563)),+ },+ white: 'd65',+ toXYZ: [+ [0.5766690429101305, 0.1855582379065463, 0.1882286462349947],+ [0.29734497525053605, 0.6273635662554661, 0.0752914584939978],+ [0.02703136138641234, 0.07068885253582723, 0.9913375368376388],+ ],+ fromXYZ: [+ [2.0415879038107465, -0.5650069742788596, -0.34473135077832956],+ [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557],+ [0.013444280632031142, -0.11836239223101838, 1.0151749943912054],+ ],+ },+ 'prophoto-rgb': {+ trc: {+ toLinear: c => sign(c, x => (x <= 16 / 512 ? x / 16 : x ** 1.8)),+ fromLinear: c => sign(c, x => (x >= 1 / 512 ? x ** (1 / 1.8) : 16 * x)),+ },+ white: 'd50',+ toXYZ: [+ [0.7977666449006423, 0.13518129740053308, 0.0313477341283922],+ [0.2880748288194013, 0.711835234241873, 0.00008993693872564],+ [0, 0, 0.8251046025104602],+ ],+ fromXYZ: [+ [1.3457868816471583, -0.25557208737979464, -0.05110186497554526],+ [-0.5446307051249019, 1.5082477428451468, 0.02052744743642139],+ [0, 0, 1.2119675456389452],+ ],+ },+ rec2020: {+ // The BT.2020 piecewise curve, as Chromium draws rec2020; CSS Color 4+ // specifies a 2.4 gamma.+ trc: {+ toLinear: c =>+ sign(c, x =>+ x < REC2020_BETA * 4.5+ ? x / 4.5+ : ((x + REC2020_ALPHA - 1) / REC2020_ALPHA) ** (1 / 0.45),+ ),+ fromLinear: c =>+ sign(c, x =>+ x > REC2020_BETA+ ? REC2020_ALPHA * x ** 0.45 - (REC2020_ALPHA - 1)+ : x * 4.5,+ ),+ },+ white: 'd65',+ toXYZ: [+ [0.6369580483012914, 0.14461690358620832, 0.1688809751641721],+ [0.2627002120112671, 0.6779980715188708, 0.05930171646986196],+ [0, 0.028072693049087428, 1.060985057710791],+ ],+ fromXYZ: [+ [1.716651187971268, -0.355670783776392, -0.25336628137366],+ [-0.666684351832489, 1.616481236634939, 0.0157685458139111],+ [0.017639857445311, -0.042770613257809, 0.942103121235474],+ ],+ },+};+RGB_SPACES['srgb-linear'] = {...RGB_SPACES.srgb, trc: LINEAR};+const XYZ_TO_LMS = [+ [0.819022437996703, 0.3619062600528904, -0.1288737815209879],+ [0.0329836539323885, 0.9292868615863434, 0.0361446663506424],+ [0.0481771893596242, 0.2642395317527308, 0.6335478284694309],+];+const LMS_TO_OKLAB = [+ [0.210454268309314, 0.7936177747023054, -0.0040720430116193],+ [1.9779985324311684, -2.42859224204858, 0.450593709617411],+ [0.0259040424655478, 0.7827717124575296, -0.8086757549230774],+];+const LMS_TO_XYZ = [+ [1.2268798758459243, -0.5578149944602171, 0.2813910456659647],+ [-0.0405757452148008, 1.112286803280317, -0.0717110580655164],+ [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816],+];+const OKLAB_TO_LMS = [+ [1, 0.3963377773761749, 0.2158037573099136],+ [1, -0.1055613458156586, -0.0638541728258133],+ [1, -0.0894841775298119, -1.2914855480194092],+];+const KAPPA = 24389 / 27;+const EPSILON = 216 / 24389;++const toPolar = ([l, a, b], powerless) => {+ const c = Math.hypot(a, b);+ const h = ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360;+ return [l, c, c < powerless ? NaN : h];+};+const fromPolar = ([l, c, h]) => {+ const r = ((Number.isNaN(h) ? 0 : h) * Math.PI) / 180;+ return [l, c * Math.cos(r), c * Math.sin(r)];+};++function hslToSrgb([h, s, l]) {+ const hue = Number.isNaN(h) ? 0 : ((h % 360) + 360) % 360;+ s /= 100;+ l /= 100;+ const f = n => {+ const k = (n + hue / 30) % 12;+ return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1));+ };+ return [f(0), f(8), f(4)];+}+function srgbToHsl([r, g, b]) {+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ let h = NaN;+ let s = 0;+ if (d > 1e-7) {+ s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);+ h =+ (max === r+ ? (g - b) / d + (g < b ? 6 : 0)+ : max === g+ ? (b - r) / d + 2+ : (r - g) / d + 4) * 60;+ }+ return [h, s * 100, l * 100];+}+function hwbToSrgb([h, w, b]) {+ w /= 100;+ b /= 100;+ if (w + b >= 1) return [w / (w + b), w / (w + b), w / (w + b)];+ return hslToSrgb([h, 100, 50]).map(c => c * (1 - w - b) + w);+}+function srgbToHwb(rgb) {+ const [h] = srgbToHsl(rgb);+ const w = Math.min(...rgb);+ const b = 1 - Math.max(...rgb);+ return [w + b >= 1 - 1e-7 ? NaN : h, w * 100, b * 100];+}++/** XYZ (D65) from coordinates in `space`; a missing coordinate counts as 0. */+function toXYZ(space, coords) {+ const c = coords.map(v => (Number.isNaN(v) ? 0 : v));+ if (space in RGB_SPACES) {+ const s = RGB_SPACES[space];+ const xyz = mul(s.toXYZ, c.map(s.trc.toLinear));+ return s.white === 'd50' ? mul(D50_TO_D65, xyz) : xyz;+ }+ switch (space) {+ case 'xyz':+ case 'xyz-d65':+ return c;+ case 'xyz-d50':+ return mul(D50_TO_D65, c);+ case 'hsl':+ return toXYZ('srgb', hslToSrgb(c));+ case 'hwb':+ return toXYZ('srgb', hwbToSrgb(c));+ case 'lch':+ return toXYZ('lab', fromPolar(c));+ case 'oklch':+ return toXYZ('oklab', fromPolar(c));+ case 'lab': {+ const [l, a, b] = c;+ const f1 = (l + 16) / 116;+ const f0 = a / 500 + f1;+ const f2 = f1 - b / 200;+ const xyz = [+ f0 ** 3 > EPSILON ? f0 ** 3 : (116 * f0 - 16) / KAPPA,+ l > KAPPA * EPSILON ? f1 ** 3 : l / KAPPA,+ f2 ** 3 > EPSILON ? f2 ** 3 : (116 * f2 - 16) / KAPPA,+ ].map((v, i) => v * D50_WHITE[i]);+ return mul(D50_TO_D65, xyz);+ }+ case 'oklab':+ return mul(+ LMS_TO_XYZ,+ mul(OKLAB_TO_LMS, c).map(v => v ** 3),+ );+ default:+ return fail(`"${space}" is not a color space`);+ }+}++/** Coordinates in `space` from XYZ (D65). */+function fromXYZ(space, xyz) {+ if (space in RGB_SPACES) {+ const s = RGB_SPACES[space];+ const v = s.white === 'd50' ? mul(D65_TO_D50, xyz) : xyz;+ return mul(s.fromXYZ, v).map(s.trc.fromLinear);+ }+ switch (space) {+ case 'xyz':+ case 'xyz-d65':+ return xyz;+ case 'xyz-d50':+ return mul(D65_TO_D50, xyz);+ case 'hsl':+ return srgbToHsl(fromXYZ('srgb', xyz));+ case 'hwb':+ return srgbToHwb(fromXYZ('srgb', xyz));+ case 'lch':+ return toPolar(fromXYZ('lab', xyz), 0.0015);+ case 'oklch':+ return toPolar(fromXYZ('oklab', xyz), 0.000004);+ case 'lab': {+ const f = mul(D65_TO_D50, xyz)+ .map((v, i) => v / D50_WHITE[i])+ .map(v => (v > EPSILON ? Math.cbrt(v) : (KAPPA * v + 16) / 116));+ return [116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2])];+ }+ case 'oklab':+ return mul(LMS_TO_OKLAB, mul(XYZ_TO_LMS, xyz).map(Math.cbrt));+ default:+ return fail(`"${space}" is not a color space`);+ }+}++// Analogous components carry a missing (`none`) value across spaces in+// color-mix(), as CSS Color 4 section 12.2 says.+// Reds, greens, and blues include X, Y, and Z; HSL lightness is a lightness;+// HWB's whiteness and blackness have no analog.+const ANALOGOUS = {+ hsl: ['hue', 'colorfulness', 'lightness'],+ hwb: ['hue', null, null],+ lab: ['lightness', 'opponentA', 'opponentB'],+ oklab: ['lightness', 'opponentA', 'opponentB'],+ lch: ['lightness', 'colorfulness', 'hue'],+ oklch: ['lightness', 'colorfulness', 'hue'],+};+const analog = space => ANALOGOUS[space] ?? ['reds', 'greens', 'blues'];++/** A color `{space, coords, alpha}` converted to `space`. */+function convert(color, space) {+ if (color.space === space) return color;+ const coords = fromXYZ(space, toXYZ(color.space, color.coords));+ const from = analog(color.space);+ const to = analog(space);+ color.coords.forEach((v, i) => {+ const at = from[i] ? to.indexOf(from[i]) : -1;+ if (Number.isNaN(v) && at !== -1) coords[at] = NaN;+ });+ return {space, coords, alpha: color.alpha};+}++// ---------------------------------------------------------------------------+// Color syntax+// ---------------------------------------------------------------------------++// Every CSS named color (CSS Color 4, section 6.1), as 6-digit hex.+const NAMED = Object.fromEntries(+ 'aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc bisque ffe4c4 black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a burlywood deb887 cadetblue 5f9ea0 chartreuse 7fff00 chocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc crimson dc143c cyan 00ffff darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9 darkgreen 006400 darkgrey a9a9a9 darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00 darkorchid 9932cc darkred 8b0000 darksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b darkslategray 2f4f4f darkslategrey 2f4f4f darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493 deepskyblue 00bfff dimgray 696969 dimgrey 696969 dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0 forestgreen 228b22 fuchsia ff00ff gainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080 green 008000 greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4 indianred cd5c5c indigo 4b0082 ivory fffff0 khaki f0e68c lavender e6e6fa lavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd lightblue add8e6 lightcoral f08080 lightcyan e0ffff lightgoldenrodyellow fafad2 lightgray d3d3d3 lightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 lightsalmon ffa07a lightseagreen 20b2aa lightskyblue 87cefa lightslategray 778899 lightslategrey 778899 lightsteelblue b0c4de lightyellow ffffe0 lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 mediumaquamarine 66cdaa mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 mediumslateblue 7b68ee mediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585 midnightblue 191970 mintcream f5fffa mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 oldlace fdf5e6 olive 808000 olivedrab 6b8e23 orange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa palegreen 98fb98 paleturquoise afeeee palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9 peru cd853f pink ffc0cb plum dda0dd powderblue b0e0e6 purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 saddlebrown 8b4513 salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee sienna a0522d silver c0c0c0 skyblue 87ceeb slateblue 6a5acd slategray 708090 slategrey 708090 snow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c teal 008080 thistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3 white ffffff whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32'+ .split(' ')+ .reduce(+ (pairs, word, i, all) => (i % 2 ? pairs : [...pairs, [word, all[i + 1]]]),+ [],+ ),+);+const SYSTEM_COLORS = new Set(+ 'accentcolor accentcolortext activetext buttonborder buttonface buttontext canvas canvastext field fieldtext graytext highlight highlighttext linktext mark marktext selecteditem selecteditemtext visitedtext'.split(+ ' ',+ ),+);++/** sRGB from hex digits. */+function fromHex(digits) {+ let h = digits;+ if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join('');+ if (h.length === 6) h += 'ff';+ if (h.length !== 8 || /[^0-9a-f]/i.test(h))+ fail(`#${digits} is not a hex color`);+ const n = [0, 2, 4, 6].map(i => parseInt(h.slice(i, i + 2), 16) / 255);+ return {space: 'srgb', coords: n.slice(0, 3), alpha: n[3]};+}++// Channels per color function: [keyword, value of 100%, kind]. `hue` reads+// angles; `clamp` holds a channel in range as CSS does at parse time.+const CHANNELS = {+ rgb: {+ space: 'srgb',+ scale: 1 / 255,+ ch: [+ ['r', 255],+ ['g', 255],+ ['b', 255],+ ],+ clamp: [0, 255],+ },+ hsl: {+ space: 'hsl',+ ch: [+ ['h', 0, 'hue'],+ ['s', 100],+ ['l', 100],+ ],+ },+ hwb: {+ space: 'hwb',+ ch: [+ ['h', 0, 'hue'],+ ['w', 100],+ ['b', 100],+ ],+ },+ lab: {+ space: 'lab',+ ch: [+ ['l', 100],+ ['a', 125],+ ['b', 125],+ ],+ },+ lch: {+ space: 'lch',+ ch: [+ ['l', 100],+ ['c', 150],+ ['h', 0, 'hue'],+ ],+ },+ oklab: {+ space: 'oklab',+ ch: [+ ['l', 1],+ ['a', 0.4],+ ['b', 0.4],+ ],+ },+ oklch: {+ space: 'oklch',+ ch: [+ ['l', 1],+ ['c', 0.4],+ ['h', 0, 'hue'],+ ],+ },+};+CHANNELS.rgba = CHANNELS.rgb;+CHANNELS.hsla = CHANNELS.hsl;+const COLOR_FN_SPACES = new Set([+ ...Object.keys(RGB_SPACES),+ 'xyz',+ 'xyz-d50',+ 'xyz-d65',+]);++/** One channel: a number, percentage, angle, `none`, keyword, or math. */+function channel(tok, [, full, kind], vars, notes) {+ if (tok.t === 'id' && tok.v === 'none') return NaN;+ const q = quantity(tok, vars, notes);+ if (q.k === 'percent')+ return kind === 'hue'+ ? fail('a hue is not a percentage')+ : (q.v / 100) * full;+ if (q.k === 'angle')+ return kind === 'hue' ? q.v : fail('only a hue takes an angle');+ if (q.k !== 'number') fail(`a ${q.k} is not a color channel`);+ return q.v;+}++/** Alpha from a token: a number or percentage, held in 0…1. */+function alphaOf(tok, vars, notes) {+ if (tok.t === 'id' && tok.v === 'none') return NaN;+ const v = channel(tok, ['alpha', 1], vars, notes);+ return Math.min(1, Math.max(0, v));+}++/** Channel keyword values of a relative color's origin, in the function's terms. */+function originVars(fn, origin, names) {+ const coords = convert(origin, fn.space).coords.map(v => v / (fn.scale ?? 1));+ return Object.fromEntries([+ ...names.map((n, i) => [n, coords[i]]),+ ['alpha', origin.alpha],+ ]);+}++/** A color function: rgb(), hsl(), hwb(), lab(), lch(), oklab(), oklch(), color(). */+function colorFunction(tok, notes) {+ let body = tok.body;+ let origin = null;+ if (body[0]?.t === 'id' && body[0].v === 'from') {+ origin = parseColor(body[1] ?? fail('from needs a color'), notes);+ body = body.slice(2);+ }+ let fn = CHANNELS[tok.name];+ if (tok.name === 'color') {+ const space = body[0]?.t === 'id' ? body[0].v : null;+ if (!COLOR_FN_SPACES.has(space))+ fail(`color(${space ?? ''}) is not a color space Swift can read`);+ const names = space.startsWith('xyz') ? ['x', 'y', 'z'] : ['r', 'g', 'b'];+ fn = {space, ch: names.map(n => [n, 1])};+ body = body.slice(1);+ }+ const names = fn.ch.map(c => c[0]);+ const vars = origin ? originVars(fn, origin, names) : null;+ let parts = body;+ let alphaTok = null;+ const legacy = !origin && body.some(t => t.t === 'op' && t.v === ',');+ if (legacy) {+ parts = commas(body).map(p =>+ p.length === 1+ ? p[0]+ : fail(`${tok.name}() has an empty or doubled value`),+ );+ checkCommaSyntax(tok.name, parts);+ if (parts.length === 4) alphaTok = parts.pop();+ } else {+ const slash = body.findIndex(t => t.t === 'op' && t.v === '/');+ if (slash !== -1) {+ if (slash !== body.length - 2)+ fail(`${tok.name}() needs one alpha after /`);+ alphaTok = body[slash + 1];+ parts = body.slice(0, slash);+ }+ }+ if (parts.length !== 3) fail(`${tok.name}() needs three channels`);+ let coords = parts.map((p, i) => channel(p, fn.ch[i], vars, notes));+ // A relative color keeps its origin's gamut, so only literal channels clamp.+ if (fn.clamp && !origin)+ coords = coords.map(v =>+ Number.isNaN(v) ? v : Math.min(fn.clamp[1], Math.max(fn.clamp[0], v)),+ );+ if (fn.scale) coords = coords.map(v => v * fn.scale);+ if (!origin && (fn.space === 'hsl' || fn.space === 'hwb')) {+ // hsl() saturation and lightness clamp at 100%, as browsers read them.+ const capped = i => fn.space === 'hsl' && i > 0;+ coords = coords.map((v, i) =>+ i === 0 ? v : Math.max(0, capped(i) ? Math.min(100, v) : v),+ );+ }+ if (!origin && /^(ok)?l(ab|ch)$/.test(fn.space)) {+ coords[0] = Math.min(fn.ch[0][1], Math.max(0, coords[0]));+ if (fn.space.endsWith('ch')) coords[1] = Math.max(0, coords[1]);+ }+ const alpha = alphaTok ? alphaOf(alphaTok, vars, notes) : (vars?.alpha ?? 1);+ return {space: fn.space, coords, alpha};+}++/**+ * Fails comma-syntax channels CSS does not allow: commas only in `rgb()` and+ * `hsl()` (and their `a` forms), no `none`, `rgb()` channels all numbers or+ * all percentages, and `hsl()` saturation and lightness as percentages.+ */+function checkCommaSyntax(name, parts) {+ if (!/^(rgba?|hsla?)$/.test(name)) fail(`${name}() has no comma syntax`);+ if (parts.some(p => p.t === 'id' && p.v === 'none'))+ fail(`${name}() with commas cannot hold none`);+ const percent = p => p.t === 'num' && p.u === '%';+ const plain = p => p.t === 'num' && p.u === '';+ if (name.startsWith('rgb')) {+ const nums = parts.slice(0, 3).filter(p => p.t === 'num');+ if (!(nums.every(percent) || nums.every(plain)))+ fail(`${name}() with commas takes all numbers or all percentages`);+ } else if (parts.slice(1, 3).some(p => p.t === 'num' && !percent(p))) {+ fail(+ `${name}() with commas takes its saturation and lightness as percentages`,+ );+ }+}++/** The interpolation part of color-mix(): `in <space> [<hue> hue]`. */+const HUE_METHODS = new Set(['shorter', 'longer', 'increasing', 'decreasing']);++/** color-mix(), CSS Color 5 section 3: percentages normalized, alpha premultiplied. */+function colorMix(tok, notes) {+ const parts = commas(tok.body);+ let space = 'oklab';+ let hue = 'shorter';+ if (parts[0][0]?.t === 'id' && parts[0][0].v === 'in') {+ const spec = parts.shift();+ space =+ spec[1]?.t === 'id'+ ? spec[1].v+ : fail('color-mix() needs a space after in');+ if (space === 'xyz-d65') space = 'xyz';+ if (!(+ space in RGB_SPACES ||+ space in ANALOGOUS ||+ space.startsWith('xyz')+ )) {+ fail(`color-mix() cannot interpolate in "${space}"`);+ }+ if (spec.length === 4 && HUE_METHODS.has(spec[2].v) && spec[3].v === 'hue')+ hue = spec[2].v;+ else if (spec.length !== 2)+ fail('color-mix() has an unknown interpolation method');+ }+ if (parts.length !== 2) fail('color-mix() mixes two colors');+ const items = parts.map(p => {+ const pct = p.find(t => t.t === 'num' && t.u === '%');+ const rest = p.filter(t => t !== pct);+ if (rest.length !== 1)+ fail('a color-mix() color is one color and an optional percentage');+ if (pct && (pct.v < 0 || pct.v > 100))+ fail('a color-mix() percentage is from 0% to 100%');+ return {+ color: convert(parseColor(rest[0], notes), space),+ p: pct ? pct.v : null,+ };+ });+ let [p1, p2] = items.map(i => i.p);+ if (p1 == null && p2 == null) [p1, p2] = [50, 50];+ else if (p1 == null) p1 = 100 - p2;+ else if (p2 == null) p2 = 100 - p1;+ const total = p1 + p2;+ if (total === 0) noStaticForm('color-mix() percentages add up to 0%');+ const w = p2 / total;+ const [a, b] = items.map(i => i.color);+ const pick = (x, y) => (Number.isNaN(x) ? y : Number.isNaN(y) ? x : null);+ // A missing alpha takes the other color's before premultiplying.+ const alphaA = Number.isNaN(a.alpha) ? b.alpha : a.alpha;+ const alphaB = Number.isNaN(b.alpha) ? a.alpha : b.alpha;+ const alpha = alphaA * (1 - w) + alphaB * w;+ const [pa, pb] = [alphaA, alphaB].map(v => (Number.isNaN(v) ? 1 : v));+ const unpremultiply = Number.isNaN(alpha) ? 1 : alpha;+ const hueAt = analog(space).indexOf('hue');+ const coords = a.coords.map((x, i) => {+ const y = b.coords[i];+ const missing = pick(x, y);+ if (missing !== null) return missing;+ if (i === hueAt) {+ let [h1, h2] = [x, y].map(h => ((h % 360) + 360) % 360);+ const d = h2 - h1;+ if (hue === 'shorter') d > 180 ? (h1 += 360) : d < -180 && (h2 += 360);+ else if (hue === 'longer')+ d > 0 && d < 180 ? (h1 += 360) : d > -180 && d <= 0 && (h2 += 360);+ else if (hue === 'increasing') h2 < h1 && (h2 += 360);+ else h1 < h2 && (h1 += 360);+ return (h1 * (1 - w) + h2 * w) % 360;+ }+ const premixed = x * pa * (1 - w) + y * pb * w;+ return unpremultiply === 0 ? 0 : premixed / unpremultiply;+ });+ return {space, coords, alpha: alpha * (total < 100 ? total / 100 : 1)};+}++/** A color token as `{space, coords, alpha}`. */+function parseColor(tok, notes) {+ if (tok.t === 'hash') return fromHex(tok.v);+ if (tok.t === 'id') {+ if (tok.v === 'transparent')+ return {space: 'srgb', coords: [0, 0, 0], alpha: 0};+ if (tok.v in NAMED) return fromHex(NAMED[tok.v]);+ if (tok.v === 'currentcolor')+ noStaticForm('currentColor depends on where the token is used');+ if (SYSTEM_COLORS.has(tok.v))+ noStaticForm(`${tok.v} is a system color the browser picks`);+ }+ if (tok.t === 'fn') {+ if (tok.name in CHANNELS || tok.name === 'color')+ return colorFunction(tok, notes);+ if (tok.name === 'color-mix') return colorMix(tok, notes);+ }+ return dynamic(tok) ?? fail(`"${show(tok)}" is not a color`);+}++// ---------------------------------------------------------------------------+// Output gamut (G7)+// ---------------------------------------------------------------------------++const GAMUT_EPSILON = 0.000075;+const inGamut = rgb =>+ rgb.every(c => c >= -GAMUT_EPSILON && c <= 1 + GAMUT_EPSILON);+const clip = rgb => rgb.map(c => Math.min(1, Math.max(0, c)));++const byte = c =>+ Math.round(Math.round(c * 255 * 1e6) / 1e6)+ .toString(16)+ .padStart(2, '0')+ .toUpperCase();++/**+ * A CSS color as 8-bit channels: `#RRGGBBAA` in sRGB when the color is inside+ * sRGB, else `display-p3 #RRGGBBAA` (clipped per channel, with a note, when it+ * is outside Display P3 too). Each channel rounds to the nearest of+ * 256 steps, halves up.+ */+export function toColor(value, notes = []) {+ const tokens = tokenize(value);+ if (tokens.length !== 1) fail(`"${value}" is not one color`);+ return outputColor(parseColor(tokens[0], notes), notes);+}++function outputColor(color, notes) {+ const alpha = Number.isNaN(color.alpha) ? 0 : color.alpha;+ const xyz = toXYZ(color.space, color.coords);+ const srgb = fromXYZ('srgb', xyz);+ if (inGamut(srgb)) return `#${clip(srgb).map(byte).join('')}${byte(alpha)}`;+ const p3 = fromXYZ('display-p3', xyz);+ // Outside Display P3, each channel clips, as Chromium draws the color.+ if (!inGamut(p3)) notes.push(OUTSIDE_P3);+ return `display-p3 #${clip(p3).map(byte).join('')}${byte(alpha)}`;+}++// ---------------------------------------------------------------------------+// Shadows+// ---------------------------------------------------------------------------++/**+ * A `box-shadow` list as layers. A drop layer is `x y [blur [spread]] color`;+ * SwiftUI has no drop spread, so a spread is left out with a note. An inset+ * layer is a ring, `inset 0 0 0 <width> color`; an offset or blurred inset+ * has no SwiftUI form. `none` is no layers.+ */+export function toShadow(value, notes = []) {+ if (value.trim().toLowerCase() === 'none') return [];+ return splitTopLevel(value).map(layer => {+ const lengths = [];+ let colorTok = null;+ let isInset = false;+ for (const tok of tokenize(layer)) {+ // CSS-wide keywords, var(), env(), and attr() have no static form.+ dynamic(tok);+ if (tok.t === 'id' && tok.v === 'inset') isInset = true;+ else if (+ tok.t === 'num' ||+ (tok.t === 'fn' && /^(calc|min|max|clamp)?$/.test(tok.name))+ ) {+ const q = quantity(tok, null, notes);+ if (q.k !== 'length' && !(q.k === 'number' && q.v === 0))+ fail(`shadow layer "${layer}" has a ${q.k} where a length goes`);+ lengths.push(q.v);+ } else if (colorTok) fail(`shadow layer "${layer}" has two colors`);+ else colorTok = tok;+ }+ if (lengths.length < 2 || lengths.length > 4)+ fail(`shadow layer "${layer}" needs two to four lengths`);+ if (!colorTok)+ noStaticForm(+ `shadow layer "${layer}" has no color, so it draws in currentColor`,+ );+ const [x, y, blur = 0, spread = 0] = lengths;+ const color = outputColor(parseColor(colorTok, notes), notes);+ if (isInset) {+ if (x !== 0 || y !== 0 || blur !== 0)+ noStaticForm(+ `inset layer "${layer}" is not a ring; SwiftUI draws only inset rings`,+ );+ return {x, y, blur, spread, isInset, color};+ }+ if (spread !== 0)+ notes.push(`drop layer "${layer}" drawn without its spread`);+ return {x, y, blur, spread: 0, isInset, color};+ });+}diff --git a/packages/native/scripts/swift-ios-theme.d.mts b/packages/native/scripts/swift-ios-theme.d.mtsindex 668eab035f..869be81245 100644--- a/packages/native/scripts/swift-ios-theme.d.mts+++ b/packages/native/scripts/swift-ios-theme.d.mts@@ -20,8 +20,19 @@ export declare const SWIFT_TOKENS_FILE: string;export declare function swiftMember(token: string): SwiftMember | null;export declare function swiftThemeName(themeName: string): string;export declare function themeFileName(swiftName: string): string;-export declare function toHexColor(value: string): string | null;-export declare function toPoints(value: string): number | null;+/** `#RRGGBBAA` in sRGB, or `display-p3 #RRGGBBAA` outside sRGB. */+export declare function toColor(value: string, notes?: string[]): string;+export declare function toPoints(+ value: string,+ notes?: string[],+ options?: {borderWidth?: boolean},+): number;+export declare function toWeight(value: string, notes?: string[]): number;+export declare function toLeading(+ value: string,+ fontSize: number | undefined,+ notes?: string[],+): number;export interface ShadowLayer {x: number;y: number;@@ -32,8 +43,8 @@ export interface ShadowLayer {}export declare function toShadow(value: string,- mode: 'light' | 'dark',-): ShadowLayer[] | null;+ notes?: string[],+): ShadowLayer[];export declare function toFamilies(value: string): string[] | null;export declare function valueForMode(value: string,@@ -55,7 +66,11 @@ export declare function defineTheme(input: {}): Promise<DefinedTheme>;export declare function renderSwiftTheme(theme: DefinedTheme,- options?: {source?: string; regenerate?: string},+ options?: {+ source?: string;+ regenerate?: string;+ warn?: (message: string) => void;+ },): Promise<string>;export declare function publishedThemePackages(): PublishedThemePackage[];export declare function renderAll(diff --git a/packages/native/scripts/swift-ios-theme.mjs b/packages/native/scripts/swift-ios-theme.mjsindex e09c39a3ae..21cf046758 100644--- a/packages/native/scripts/swift-ios-theme.mjs+++ b/packages/native/scripts/swift-ios-theme.mjs@@ -10,7 +10,9 @@* Theme.<swiftName>* @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.+ * 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).** SYNC: When modified, update this header and the theme generator spec.*/@@ -18,6 +20,19 @@import fs from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';+import {+ checkFamilyIsStatic,+ CssValueError,+ OUTSIDE_P3,+ toColor,+ toLeading,+ toPoints,+ toShadow,+ toWeight,+ valueForMode,+} from './css-values.mjs';++export {toColor, toLeading, toPoints, toShadow, toWeight, valueForMode};const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)),@@ -41,7 +56,6 @@ const REGENERATE = 'pnpm -F @astryxdesign/native generate:swift-ios';// needs it.const KEEP =/^--(color-|spacing-|radius-|size-element-|border-width$|font-size-|font-weight-|font-family-|text-(heading-\d|display-\d|body|large|label|supporting|code)-|shadow-(low|med|high)$)/;-const REM = 16;// Words Swift reserves as identifiers. A member or theme name that equals one// fails the run (G3, G6).@@ -128,183 +142,13 @@ const swiftIdent = name => (SWIFT_KEYWORDS.has(name) ? `\`${name}\`` : name);// Values (G7)// ----------------------------------------------------------------------------function hex2(n) {- return Math.round(n).toString(16).padStart(2, '0').toUpperCase();-}--// The CSS color keywords core's resolved tokens use.-const NAMED_COLORS = {- black: '#000000FF',- white: '#FFFFFFFF',- transparent: '#00000000',-};--/** A CSS color as `#RRGGBBAA`, or null when it is not a plain color. */-export function toHexColor(value) {- const v = value.trim();- let m = /^#([0-9a-f]{3,8})$/i.exec(v);- if (m) {- let h = m[1];- if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join('');- if (h.length === 6) h += 'FF';- return h.length === 8 ? `#${h.toUpperCase()}` : null;- }- m =- /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)$/i.exec(- v,- );- if (m) {- const alpha =- m[4] === undefined- ? 1- : m[4].endsWith('%')- ? parseFloat(m[4]) / 100- : parseFloat(m[4]);- return `#${hex2(+m[1])}${hex2(+m[2])}${hex2(+m[3])}${hex2(alpha * 255)}`;- }- m =- /^hsla?\(\s*(-?[\d.]+)(?:deg)?[,\s]+([\d.]+)%[,\s]+([\d.]+)%(?:[,\s/]+([\d.]+%?))?\s*\)$/i.exec(- v,- );- if (m) {- // Exact sRGB, then each channel rounded to the nearest of 256 steps,- // halves up (G7).- const h = (((+m[1] % 360) + 360) % 360) / 360;- const sat = +m[2] / 100;- const l = +m[3] / 100;- const q = l < 0.5 ? l * (1 + sat) : l + sat - l * sat;- const p = 2 * l - q;- const channel = t => {- const u = t < 0 ? t + 1 : t > 1 ? t - 1 : t;- if (u < 1 / 6) return p + (q - p) * 6 * u;- if (u < 1 / 2) return q;- if (u < 2 / 3) return p + (q - p) * (2 / 3 - u) * 6;- return p;- };- const alpha =- m[4] === undefined- ? 1- : m[4].endsWith('%')- ? parseFloat(m[4]) / 100- : parseFloat(m[4]);- // Round away float noise first so an exact half rounds up.- const byte = c => hex2(Math.round(c * 255 * 1e6) / 1e6);- return `#${byte(channel(h + 1 / 3))}${byte(channel(h))}${byte(channel(h - 1 / 3))}${byte(alpha)}`;- }- m =- /^oklch\(\s*([\d.]+%?)\s+([\d.]+%?)\s+(-?[\d.]+)(?:deg)?(?:\s*\/\s*([\d.]+%?))?\s*\)$/i.exec(- v,- );- if (m) {- // Exact OKLCH → OKLab → linear sRGB → sRGB, clipped to the sRGB gamut,- // then each channel rounded to the nearest of 256 steps, halves up (G7).- const part = (text, percentOf) =>- text.endsWith('%')- ? (parseFloat(text) / 100) * percentOf- : parseFloat(text);- const L = part(m[1], 1);- const C = part(m[2], 0.4);- const hue = (parseFloat(m[3]) * Math.PI) / 180;- const a = C * Math.cos(hue);- const b = C * Math.sin(hue);- const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;- const mm = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;- const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;- const linear = [- 4.0767416621 * l - 3.3077115913 * mm + 0.2309699292 * s,- -1.2684380046 * l + 2.6097574011 * mm - 0.3413193965 * s,- -0.0041960863 * l - 0.7034186147 * mm + 1.707614701 * s,- ];- const encode = c => {- const x = Math.min(1, Math.max(0, c));- return x <= 0.0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055;- };- const alpha = m[4] === undefined ? 1 : part(m[4], 1);- const byte = c => hex2(Math.round(c * 255 * 1e6) / 1e6);- return `#${linear.map(c => byte(encode(c))).join('')}${byte(alpha)}`;- }- return NAMED_COLORS[v.toLowerCase()] ?? null;-}--/**- * The value of a token in one mode: a whole-value `light-dark(a, b)` is `a` in- * light and `b` in dark (G1); any other value is returned unchanged.- */-export function valueForMode(value, mode) {- const m = /^\s*light-dark\((.*)\)\s*$/s.exec(value);- if (!m) return value;- let depth = 0;- for (let i = 0; i < m[1].length; i++) {- const c = m[1][i];- if (c === '(') depth++;- else if (c === ')') depth--;- else if (c === ',' && depth === 0) {- const part = mode === 'light' ? m[1].slice(0, i) : m[1].slice(i + 1);- return part.trim();- }- }- return value;-}--/** Splits a CSS list at its top-level commas. */-function splitTopLevel(value) {- const parts = [];- let depth = 0;- let start = 0;- for (let i = 0; i < value.length; i++) {- const c = value[i];- if (c === '(') depth++;- else if (c === ')') depth--;- else if (c === ',' && depth === 0) {- parts.push(value.slice(start, i));- start = i + 1;- }- }- parts.push(value.slice(start));- return parts.map(part => part.trim());-}--/**- * A CSS `box-shadow` list as shadow layers in one mode, or null (G7). A drop- * layer is `x y blur color` with no spread; an inset layer is a ring,- * `inset 0 0 0 <width> color`. A `light-dark()` color is taken per mode. Any- * other layer has no exact SwiftUI form, so the list is null.- */-export function toShadow(value, mode) {- const layers = [];- for (const layer of splitTopLevel(value.trim())) {- const m =- /^(inset\s+)?(\S+)\s+(\S+)\s+(\S+)(?:\s+(\S+))?\s+((?:light-dark|rgba?|hsla?|oklch)\(.*\)|#[0-9A-Fa-f]+|[a-z]+)$/s.exec(- layer,- );- if (!m) return null;- const [x, y, blur] = [m[2], m[3], m[4]].map(toPoints);- const spread = m[5] == null ? 0 : toPoints(m[5]);- const color = toHexColor(valueForMode(m[6], mode));- if (x == null || y == null || blur == null || spread == null || !color) {- return null;- }- const isInset = m[1] != null;- if (isInset ? x !== 0 || y !== 0 || blur !== 0 : spread !== 0) return null;- layers.push({x, y, blur, spread, isInset, color});- }- return layers.length ? layers : null;-}--/** A CSS length or unitless number as points, or null. */-export function toPoints(value) {- const m = /^(-?[\d.]+)(rem|px)?$/.exec(value.trim());- if (!m) return null;- return m[2] === 'rem' ? parseFloat(m[1]) * REM : parseFloat(m[1]);-}-/** A CSS font-family stack as family names in order, or null. */export function toFamilies(value) {const families = [];const re = /\s*("([^"]*)"|'([^']*)'|([^,]+?))\s*(,|$)/gy;let m;const v = value.trim();- if (!v || /var\(|calc\(/.test(v)) return null;+ if (!v || /\b(var|calc|env|attr)\(/.test(v)) return null;while (re.lastIndex < v.length && (m = re.exec(v))) {const name = (m[2] ?? m[3] ?? m[4] ?? '').trim();if (!name) return null;@@ -378,39 +222,72 @@ export function localTokensLeftOut(theme) {return Object.keys(theme.localTokens ?? {}).sort();}+const isWeight = token => /^--font-weight-|-weight$/.test(token);+const isLeading = token => token.endsWith('-leading');++/**+ * One token's value in one mode as its Swift value (G7). A loss goes into+ * `notes`; a value with no static form throws CssValueError.+ */+function convertToken(token, value, group, typedSoFar, notes) {+ if (group === 'color') return toColor(value, notes);+ if (group === 'shadow') return toShadow(value, notes);+ if (isFamily(token)) {+ checkFamilyIsStatic(value);+ const families = toFamilies(value);+ if (!families) throw new CssValueError('a font family is a list of names');+ return families;+ }+ if (isWeight(token)) return toWeight(value, notes);+ if (isLeading(token)) {+ const size = typedSoFar[token.replace(/-leading$/, '-size')]?.value;+ return toLeading(value, size, notes);+ }+ return toPoints(value, notes, {borderWidth: token === '--border-width'});+}+/*** 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).+ * `{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.*/-async function resolveMode(theme, mode) {+async function resolveMode(theme, mode, warn) {const {resolveThemeTokens} = await core();const out = {};- for (let [token, value] of Object.entries(+ const entries = Object.entries(resolveThemeTokens(theme === CORE_DEFAULTS ? null : theme, {mode}),- )) {- if (!KEEP.test(token) || typeof value !== 'string') continue;+ )+ .filter(([token, value]) => KEEP.test(token) && typeof value === 'string')+ // A length line height divides by its style's size, so sizes go first.+ .sort(([a], [b]) => Number(isLeading(a)) - Number(isLeading(b)));+ for (const [token, value] of entries) {const {group, member} = swiftMember(token);- if (group !== 'shadow') value = valueForMode(value, mode);- const fail = kind => {+ let typed;+ const notes = [];+ try {+ typed = convertToken(token, valueForMode(value, mode), group, out, notes);+ } catch (error) {+ if (!(error instanceof CssValueError)) throw error;+ 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} is not a ${kind} Swift can read: ${value}`,+ `${theme.name} ${mode}: ${token} = ${value}: ${error.message}; ${outcome}`,);- };- let typed;- if (group === 'color') typed = toHexColor(value) ?? fail('color');- else if (group === 'shadow')- typed = toShadow(value, mode) ?? fail('shadow');- else if (isFamily(token)) typed = toFamilies(value) ?? fail('font family');- else typed = toPoints(value) ?? fail('size');+ }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) {- const light = await resolveMode(theme, 'light');- const dark = await resolveMode(theme, 'dark');+export async function resolveTheme(theme, {warn = () => {}} = {}) {+ const light = await resolveMode(theme, 'light', warn);+ const dark = await resolveMode(theme, 'dark', warn);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';@@ -685,7 +562,8 @@ ${structs}}/**- * SwiftUI's own color for `RRGGBBAA` in a color space (`sRGB`), each 8-bit+ * SwiftUI's own color for `RRGGBBAA` in a color space (`sRGB` or+ * `displayP3`), each 8-bit* channel written as `0`, `1`, or the exact decimal of its step over 255* (G7). A decimal literal, not `n / 255`, keeps Swift's type checker fast on* a theme's hundreds of colors.@@ -699,7 +577,11 @@ function swiftColor(space, hex) {}function swiftValue(type, value) {- if (type === 'Color') return swiftColor('sRGB', value.slice(1));+ if (type === 'Color') {+ return value.startsWith('#')+ ? swiftColor('sRGB', value.slice(1))+ : swiftColor('displayP3', value.split('#')[1]);+ }if (type === '[String]')return `[${value.map(v => JSON.stringify(v)).join(', ')}]`;if (type === '[ShadowLayer]')@@ -738,10 +620,14 @@ export const themeFileName = swiftName => `${capitalize(swiftName)}Theme.swift`;*/export async function renderSwiftTheme(theme,- {source = 'a product theme', regenerate} = {},+ {+ source = 'a product theme',+ regenerate,+ warn = message => console.warn(`warning: ${message}`),+ } = {},) {const swiftName = swiftThemeName(theme.name);- const {light, dark} = await resolveTheme(theme);+ const {light, dark} = await resolveTheme(theme, {warn});const surface = tokenSurface(light);const header =regenerate === undefineddiff --git a/packages/native/specs/swift/library/theme-generator.md b/packages/native/specs/swift/library/theme-generator.mdindex 0ec7191f60..e114730753 100644--- a/packages/native/specs/swift/library/theme-generator.md+++ b/packages/native/specs/swift/library/theme-generator.md@@ -23,10 +23,13 @@ re-implements theme logic.part the generator ignores. Until core ships `PortableTheme`, the input typeis `DefinedTheme`. Values come only from core's`resolveThemeTokens(theme, {mode})`, called once with `mode: 'light'` and- once with `mode: 'dark'`. A token whose whole value is- `light-dark(<light>, <dark>)` takes its first argument in light mode and its- second in dark mode, as the resolver hands them. The generator never reads- `theme.tokens` directly and never evaluates a color or reference itself.+ once with `mode: 'dark'`. A theme's `[light, dark]` tuple reaches the+ generator already split, one side per mode. A `light-dark(<light>, <dark>)`+ at any depth of a value (the whole value, or inside `color-mix()`, a+ relative color, or a shadow layer) takes its first argument in light mode+ and its second in dark mode. The generator never reads `theme.tokens`+ directly and never resolves a reference itself; it converts each resolved+ CSS value to a Swift value (G7).- **G2 — Core is read only at build time.** The generator runs at build time;generated Swift imports only SwiftUI and carries nothing from core at runtime (AST-082 FR16). Until core's portable entry ships, the generator reads@@ -93,32 +96,86 @@ re-implements theme logic.to the same member, or a member part that is a Swift keyword or does notstart with a letter, fail the run with both token names.-- **G7 — Values are typed and exact, or the run fails.**- - Colors are `Color` values in sRGB, from `#RGB`, `#RGBA`, `#RRGGBB`,- `#RRGGBBAA`, `rgb()`/`rgba()` and `hsl()`/`hsla()` (comma or space- separated, hue in degrees or unitless, alpha as a number or a percentage),- `oklch()` (lightness as a number or a percentage, chroma as a number or a- percentage of 0.4, hue in degrees, optional alpha), and the keywords- `black`, `white`, and `transparent`. Every color is stored as 8-bit sRGB- channels: an `hsl()` or `oklch()` value is converted exactly (`oklch()`- through OKLab, clipped to the sRGB gamut), then each channel is rounded to- the nearest of 256 steps, halves up. A color is written as SwiftUI's own- `Color(.sRGB, red:green:blue:opacity:)`, each channel as `0`, `1`, or the- exact decimal of its step over 255 (the same `Double` as `n / 255`); the- package declares no color initializer of its own.- - Lengths are `CGFloat` points: `rem` × 16, `px` × 1. Unitless numbers- (weights, line-height ratios) are `CGFloat`.+- **G7 — Values are typed, and each conversion is exact or stated.** Each+ value is read in one mode after G1's `light-dark()` rule.+ - Colors are `Color` values. The generator reads hex (`#RGB`, `#RGBA`,+ `#RRGGBB`, `#RRGGBBAA`); the 148 CSS named colors and `transparent`;+ `rgb()`/`rgba()` and `hsl()`/`hsla()` in comma or space syntax; `hwb()`;+ `lab()`, `lch()`, `oklab()`, and `oklch()`; `color()` in `srgb`,+ `srgb-linear`, `display-p3`, `a98-rgb`, `prophoto-rgb`, `rec2020`,+ `xyz`, `xyz-d50`, and `xyz-d65`; `color-mix()` in any of those spaces or+ `hsl`, `hwb`, `lab`, `lch`, `oklab` (the default), and `oklch`, with+ `shorter`, `longer`, `increasing`, or `decreasing` hue; and relative+ colors (`rgb(from <color> r g b / alpha)`, the same for every function,+ and `color(from <color> <space> …)`). A channel is a number, a+ percentage of its CSS reference range, `none`, a channel keyword of a+ relative color, or `calc()`, `min()`, `max()`, or `clamp()` over those;+ a hue is a number or an angle in `deg`, `rad`, `grad`, or `turn`; alpha+ follows `/` (or a fourth comma) as a number or a percentage. Commas are+ read only where CSS allows them: in `rgb()` and `hsl()` (and their `a`+ forms), with no `none`, `rgb()` channels all numbers or all+ percentages, and `hsl()` saturation and lightness as percentages.+ - Conversion uses CSS Color 4's equations and matrices through CIE XYZ D65,+ with Bradford adaptation for D50 spaces; `rec2020` uses the BT.2020+ piecewise transfer curve, as Chromium draws it; CSS Color 4 specifies a+ 2.4 gamma.+ In a color written with literal channels, `rgb()` channels clamp to+ 0–255; `hsl()` and `hwb()` saturation, whiteness, and blackness clamp at+ 0, and `hsl()` saturation and lightness at 100%, as browsers read them; Lab and OKLab lightness clamp to their+ range and chroma at 0. A relative color's channels do not clamp, so it+ keeps its origin's gamut. Alpha clamps to 0–1. `color-mix()` follows CSS Color 5: an omitted percentage+ is 100% minus the other (both omitted are 50% each), the pair is scaled+ to sum to 100%, a sum under 100% multiplies the result's alpha by it, a+ sum of 0% has no static form, hues are taken modulo 360° before the hue+ method applies, a `none` alpha takes the other color's alpha before+ premultiplying, channels interpolate premultiplied by alpha, and a+ `none` channel takes the other color's analogous channel (CSS Color 4's+ analogous components: reds, greens, and blues including X, Y, and Z;+ lightness, `hsl()`'s included; colorfulness; hue; and the two opponent+ axes; HWB's whiteness and blackness have none). A channel+ still missing at output is 0.+ - A color inside sRGB (every channel within 0.000075 of 0–1) is SwiftUI's+ own `Color(.sRGB, red:green:blue:opacity:)`. A color outside sRGB and+ inside Display P3 is `Color(.displayP3, red:green:blue:opacity:)` (D5). A+ color 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,+ halves up, and is written as `0`, `1`, or the exact decimal of its step+ over 255 (the same `Double` as `n / 255`); the package declares no color+ initializer of its own.+ - Lengths are `CGFloat` points: `px` × 1, `rem` and `em` × 16, `pt` × 4/3,+ `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.+ - Font weights (`font-weight-*`, `text-*-weight`) are numbers from 1 to+ 1000; `normal` is 400 and `bold` 700. `bolder` (700) and `lighter` (100)+ are read against 400.+ - Line heights (`text-*-leading`) are multipliers of the font size: a+ number 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.- Font families are `[String]`, quotes removed, in the CSS stack's order.- - Shadows are `[ShadowLayer]`, one per `box-shadow` layer in order: a drop- layer `x y blur color` with no spread, or an inset ring- `inset 0 0 0 <width> color`, which a view draws inside its border, as CSS- draws an inset shadow. A `light-dark()` color inside a layer is- taken per mode.- - Any other value in a kept group, such as `color-mix()`,- `calc()`, an unresolved `var()`, a nested `light-dark()` outside a shadow- layer, or a shadow layer with any other shape, fails the run with the- theme, mode, token, and value. A token present in one mode and missing in- the other fails the same way. Nothing is dropped or guessed.+ - Shadows are `[ShadowLayer]`, one per `box-shadow` layer in order, its+ color 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+ view draws inside its border, as CSS draws an inset shadow.+ - These have no static form: `currentColor`; system colors such as+ `Canvas`; percentages outside color channels and line heights; viewport+ and container units; font-relative units (`ex`, `ch`, `ic`, `cap`,+ `lh`, and their root forms); a `var()` core's resolver leaves unresolved;+ `env()` and `attr()`; CSS-wide keywords; `calc()` that adds unlike+ kinds; a `color-mix()` whose percentages add up to 0%; a shadow layer+ with no color, which draws in `currentColor`; and an offset or blurred+ inset 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+ the 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 permode, as it returns shared tokens; until then the generator emits none and@@ -163,22 +220,22 @@ re-implements theme logic.## 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 token written as `light-dark(#000, #fff)` generates black in light and white in dark. `hsl(210 100% 50%)` generates the same color as `#0080FF`. Unit tests convert every listed form; `oklch(0 0 0 / 5%)` generates `#0000000D`; `color-mix(in srgb, red, blue)` in a kept group fails with theme, mode, token, and value in the message; 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"]`. 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)`. |-| 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 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. |## Decisions@@ -215,6 +272,13 @@ re-implements theme logic.(checked by a Swift test that sets `colorSchemeContrast` to increased andreads the border color).+- **D5 — Colors outside sRGB stay wide.** iPhone and Mac displays are+ Display P3, and a browser on them draws an out-of-sRGB theme color in+ Display 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 would then draw duller in Swift than on the web on the same device.+## Current state- `packages/native/apple/` is one Swift package with the `AstryxNative`@@ -234,6 +298,10 @@ re-implements theme logic.(component styles), neutral's shadows use `oklch()` with an inset ring, and`color-mix()` appears inside the groups only in`--color-syntax-added` and `--color-syntax-removed`.+- Core's resolver substitutes `var()` references between tokens and+ evaluates `color-mix(in srgb, …)` over the colors it parses; the generator+ converts every other G7 form itself.+- Every color in the published themes is inside sRGB.## Open questionsdiff --git a/packages/native/src/theme/swiftIOSTheme.test.ts b/packages/native/src/theme/swiftIOSTheme.test.tsindex 9456f0740e..312aa20eee 100644--- a/packages/native/src/theme/swiftIOSTheme.test.ts+++ b/packages/native/src/theme/swiftIOSTheme.test.ts@@ -14,11 +14,13 @@ import {renderSwiftTheme,swiftMember,swiftThemeName,+ toColor,toFamilies,- toHexColor,+ toLeading,toPoints,renderTokenTypes,toShadow,+ toWeight,tokenSurface,valueForMode,} from '../../scripts/swift-ios-theme.mjs';@@ -105,25 +107,128 @@ describe('swift theme generator: names (G6)', () => {});});+// Every row is exact to the 8-bit channel (tolerance 0 of 255). The lab(),+// lch(), oklab(), and oklch() rows are CSS Color 4's own examples of #7D2329+// and #C65D06; the rest agree with an independent CSS Color 4 implementation.+// Outside Display P3, each channel clips, as Chromium 154 draws it.+const P3_CLIPPED = 'outside Display P3; clipped to match the web';+const COLORS: [css: string, swift: string, note?: string][] = [+ ['#0064E0', '#0064E0FF'],+ ['#abc8', '#AABBCC88'],+ ['rebeccapurple', '#663399FF'],+ ['transparent', '#00000000'],+ ['rgba(5, 54, 89, 0.1)', '#0536591A'],+ ['rgb(10% 20% 30% / 50%)', '#1A334D80'],+ ['rgb(none 0 0)', '#000000FF'],+ ['rgb(calc(255 / 2) 0 0)', '#800000FF'],+ ['hsl(210 100% 50%)', '#0080FFFF'],+ ['hsla(120, 100%, 25%, 0.5)', '#00800080'],+ ['hsl(0.5turn 50% 50%)', '#40BFBFFF'],+ ['hsl(200grad 50% 50%)', '#40BFBFFF'],+ ['hsl(3.14159rad 50% 50%)', '#40BFBFFF'],+ ['hwb(194 0% 0% / .5)', '#00C4FF80'],+ ['hwb(0 60% 60%)', '#808080FF'],+ ['lab(29.2345% 39.3825 20.0664)', '#7D2329FF'],+ ['lch(52.2345% 72.2 56.2)', '#C65D06FF'],+ ['oklab(40.101% 0.1147 0.0453)', '#7D2329FF'],+ ['oklch(40.101% 0.12332 21.555)', '#7D2329FF'],+ ['oklch(0 0 0 / 5%)', '#0000000D'],+ ['oklch(50% 0 0)', '#636363FF'],+ ['color(srgb 0.5 0.2 0.1)', '#80331AFF'],+ ['color(srgb-linear 0.5 0.2 0.1)', '#BC7C59FF'],+ ['color(display-p3 0.4 0.6 0.2)', '#559B17FF'],+ ['color(a98-rgb 0.4 0.6 0.2)', '#439A22FF'],+ ['color(prophoto-rgb 0.4 0.6 0.2)', '#52B204FF'],+ // rec2020 decodes with the BT.2020 curve, as Chromium 154 draws it.+ ['color(rec2020 0.4 0.6 0.2)', '#4AA829FF'],+ ['color(rec2020 0.5 0.5 0.5)', '#8B8B8BFF'],+ ['color(xyz-d65 0.2 0.3 0.4)', 'display-p3 #44A4A3FF'],+ ['color(xyz-d50 0.2 0.3 0.4)', 'display-p3 #2CA5BAFF'],+ ['color(display-p3 1 0 0)', 'display-p3 #FF0000FF'],+ ['color-mix(in srgb, red, blue)', '#800080FF'],+ ['color-mix(in srgb, red 30%, blue)', '#4D00B3FF'],+ ['color-mix(in srgb, red 20%, blue 20%)', '#80008066'],+ ['color-mix(in srgb, rgb(255 0 0 / .5), blue)', '#5500AABF'],+ ['color-mix(in srgb, rgb(none 50 0), rgb(10 200 0))', '#0A7D00FF'],+ ['color-mix(in srgb-linear, red, blue)', '#BC00BCFF'],+ ['color-mix(in xyz, red, blue)', '#BC00BCFF'],+ ['color-mix(in display-p3, red, blue)', '#800A91FF'],+ ['color-mix(in oklab, red, blue)', '#8C53A2FF'],+ ['color-mix(red, blue)', '#8C53A2FF'],+ ['color-mix(in lab, red, blue)', 'display-p3 #B01185FF'],+ ['color-mix(in hsl, red, blue)', '#FF00FFFF'],+ ['color-mix(in oklch, red, blue)', 'display-p3 #AA00BBFF', P3_CLIPPED],+ [+ 'color-mix(in oklch longer hue, red, blue)',+ 'display-p3 #009000FF',+ P3_CLIPPED,+ ],+ ['rgb(from #123456 calc(r + 10) g b)', '#1C3456FF'],+ ['rgb(from red r g b / 50%)', '#FF000080'],+ ['hsl(from blue calc(h + 180) s l)', '#FFFF00FF'],+ ['oklch(0.7 0.4 150)', 'display-p3 #00D100FF', P3_CLIPPED],+ ['oklch(0.9 0.4 300)', 'display-p3 #FB7CFFFF', P3_CLIPPED],+ // A relative color keeps its origin's gamut instead of clamping to sRGB.+ ['rgb(from color(display-p3 1 0 0) r g b / 50%)', 'display-p3 #FF000080'],+ ['hwb(from color(display-p3 1 0 0) h w b)', 'display-p3 #FF0000FF'],+ // A missing alpha takes the other color's before premultiplying.+ ['color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / 0.5))', '#80008080'],+ ['color-mix(in srgb, rgb(255 0 0 / none), rgb(0 0 255 / none))', '#80008000'],+ // A missing blue is not Lab's b: only analogous channels carry over.+ ['color-mix(in lab, rgb(0 0 none), lab(50 20 30))', '#4F3525FF'],+ // HSL lightness is analogous to Lab's, so a missing one carries over.+ ['color-mix(in lab, hsl(0 50% none), lab(50 20 30))', '#8E705EFF'],+ // hsl() saturation clamps at 100% in both syntaxes, as browsers read it.+ ['hsl(120, 200%, 40%)', '#00CC00FF'],+ ['hsl(120 200% 40%)', '#00CC00FF'],+ // Hues are taken modulo 360° before interpolating (400° is 40°).+ ['color-mix(in oklch, oklch(0.6 0.1 400), oklch(0.6 0.1 20))', '#B4685CFF'],+];+describe('swift theme generator: values (G7)', () => {- it('reads CSS colors, lengths, and font stacks as Swift values', () => {- expect(toHexColor('#0064E0')).toBe('#0064E0FF');- expect(toHexColor('#fff')).toBe('#FFFFFFFF');- expect(toHexColor('rgba(5, 54, 89, 0.1)')).toBe('#0536591A');- expect(toHexColor('transparent')).toBe('#00000000');- expect(toHexColor('oklch(0 0 0 / 5%)')).toBe('#0000000D');- expect(toHexColor('oklch(1 0 0 / 8%)')).toBe('#FFFFFF14');- expect(toHexColor('oklch(0.5 0 0)')).toBe('#636363FF');- expect(toHexColor('oklch(50% 0 0)')).toBe('#636363FF');- expect(toHexColor('color-mix(in srgb, red, blue)')).toBeNull();- expect(toHexColor('light-dark(#000, #fff)')).toBeNull();- expect(toHexColor('hsl(0 100% 50%)')).toBe('#FF0000FF');- expect(toHexColor('hsl(210 100% 50%)')).toBe('#0080FFFF');- expect(toHexColor('hsla(120, 100%, 25%, 0.5)')).toBe('#00800080');- expect(toPoints('0.875rem')).toBe(14);- expect(toPoints('32px')).toBe(32);- expect(toPoints('600')).toBe(600);- expect(toPoints('calc(1px + 1rem)')).toBeNull();+ it.each(COLORS)('reads the color %s as %s', (css, swift, note) => {+ const notes: string[] = [];+ expect(toColor(css, notes)).toBe(swift);+ expect(notes).toEqual(note ? [note] : []);+ });++ it('reads lengths, weights, and line heights', () => {+ const lengths: [string, number][] = [+ ['0.875rem', 14],+ ['32px', 32],+ ['12pt', 16],+ ['1in', 96],+ ['0', 0],+ ['calc(1rem + 2px)', 18],+ ['calc((1rem - 2px) * 2)', 28],+ ['max(4px, 0.5rem)', 8],+ ['clamp(2px, 1rem, 12px)', 12],+ ];+ for (const [css, points] of lengths) {+ expect(toPoints(css), css).toBe(points);+ }+ // thin, medium, and thick are lengths only for a border width.+ expect(toPoints('thin', [], {borderWidth: true})).toBe(1);+ expect(toPoints('medium', [], {borderWidth: true})).toBe(3);+ expect(() => toPoints('medium')).toThrow(/names a border width/);+ const notes: string[] = [];+ expect(toPoints('1.5em', notes)).toBe(24);+ expect(notes).toEqual(['em read against the 16px root font size']);+ expect(toWeight('bold')).toBe(700);+ expect(toWeight('normal')).toBe(400);+ expect(toWeight('650')).toBe(650);+ expect(toWeight('bolder', notes)).toBe(700);+ expect(toLeading('1.5', 14)).toBe(1.5);+ expect(toLeading('150%', 14)).toBe(1.5);+ expect(toLeading('21px', 14)).toBe(1.5);+ // An em counts against the style's own size, not the 16-point root.+ expect(toLeading('1.5em', 14)).toBe(1.5);+ expect(toLeading('calc(1em + 7px)', 14)).toBe(1.5);+ expect(toLeading('normal', 14, notes)).toBe(1.2);+ expect(notes.slice(1)).toEqual([+ "bolder read against normal (400), the root's inherited weight",+ 'normal depends on the font; read as 1.2',+ ]);expect(toFamilies('"Figtree", -apple-system, sans-serif')).toEqual(['Figtree','-apple-system',@@ -132,50 +237,178 @@ describe('swift theme generator: values (G7)', () => {expect(toFamilies('var(--font-family-body)')).toBeNull();});- it('reads box-shadow lists as drop layers and inset rings (G7)', () => {+ it('fails on a value with no static form, saying why', () => {+ const cases: [() => unknown, RegExp][] = [+ [() => toColor('currentColor'), /currentColor depends on where/],+ [() => toColor('Canvas'), /system color/],+ [() => toColor('var(--brand)'), /var\(--brand\) is not a token/],+ [() => toColor('color(--custom 1 0 0)'), /not a color space/],+ [() => toPoints('50%'), /percentage depends on the box/],+ [() => toPoints('10vh'), /viewport units/],+ [() => toPoints('2ch'), /font-relative units/],+ [() => toPoints('calc(1px + 50%)'), /adds length and percent/],+ [() => toPoints('env(safe-area-inset-top)'), /env\(\) is known only/],+ [() => toWeight('1001'), /from 1 to 1000/],+ [+ () => toShadow('inset 0 1px 2px #000'),+ /SwiftUI draws only inset rings/,+ ],+ ];+ for (const [run, message] of cases) {+ expect(run).toThrow(message);+ }+ });++ it('reads box-shadow lists as drop layers and inset rings', () => {const neutralLow ='0 2px 4px light-dark(oklch(0 0 0 / 5%), oklch(0 0 0 / 25%)), 0 4px 8px light-dark(oklch(0 0 0 / 10%), oklch(0 0 0 / 40%)), inset 0 0 0 1px light-dark(transparent, oklch(1 0 0 / 8%))';- expect(toShadow(neutralLow, 'light')).toEqual([+ expect(toShadow(valueForMode(neutralLow, 'light'))).toEqual([{x: 0, y: 2, blur: 4, spread: 0, isInset: false, color: '#0000000D'},{x: 0, y: 4, blur: 8, spread: 0, isInset: false, color: '#0000001A'},{x: 0, y: 0, blur: 0, spread: 1, isInset: true, color: '#00000000'},]);- expect(toShadow(neutralLow, 'dark')?.[2]?.color).toBe('#FFFFFF14');- expect(toShadow('0 2px 4px #4a35200D', 'light')).toEqual([- {x: 0, y: 2, blur: 4, spread: 0, isInset: false, color: '#4A35200D'},+ expect(toShadow(valueForMode(neutralLow, 'dark'))[2]?.color).toBe(+ '#FFFFFF14',+ );+ expect(toShadow('none')).toEqual([]);+ const notes: string[] = [];+ expect(toShadow('#000 0 calc(1px + 1px) 0.25rem 1px', notes)).toEqual([+ {x: 0, y: 2, blur: 4, spread: 0, isInset: false, color: '#000000FF'},+ ]);+ expect(notes).toEqual([+ 'drop layer "#000 0 calc(1px + 1px) 0.25rem 1px" drawn without its spread',]);- // No exact SwiftUI form: a drop spread, or a blurred or offset inset.- expect(toShadow('0 2px 4px 1px #000', 'light')).toBeNull();- expect(toShadow('inset 0 1px 2px #000', 'light')).toBeNull();});- it('takes light-dark() per mode (G1)', async () => {+ it('takes light-dark() per mode at any depth (G1)', () => {expect(valueForMode('light-dark(#000, #fff)', 'light')).toBe('#000');expect(valueForMode('light-dark(#000, #fff)', 'dark')).toBe('#fff');- expect(- valueForMode('light-dark(rgb(0, 0, 0), rgb(255, 255, 255))', 'dark'),- ).toBe('rgb(255, 255, 255)');+ const mixed = 'color-mix(in srgb, light-dark(red, blue), white)';+ expect(toColor(valueForMode(mixed, 'light'))).toBe('#FF8080FF');+ expect(toColor(valueForMode(mixed, 'dark'))).toBe('#8080FFFF');expect(valueForMode('#123', 'dark')).toBe('#123');+ });++ it('generates a [light, dark] tuple and a light-dark() value per mode', async () => {const theme = await defineTheme({name: 'acme-brand',- tokens: {'--color-accent': 'light-dark(#000, #fff)'},+ tokens: {+ '--color-accent': 'light-dark(#000, #fff)',+ '--color-border': [+ 'oklch(40.101% 0.12332 21.555)',+ 'color-mix(in srgb, light-dark(red, blue) 50%, white)',+ ],+ '--spacing-4': ['4px', '0.75rem'],+ },});const swift = await renderSwiftTheme(theme);- expect(swift).toContain(+ const [light, dark] = swift.split('dark: Tokens(');+ expect(light).toContain('accent: Color(.sRGB, red: 0, green: 0, blue: 0, opacity: 1)',);- expect(swift).toContain(+ expect(dark).toContain('accent: Color(.sRGB, red: 1, green: 1, blue: 1, opacity: 1)',);+ expect(light).toContain(+ 'border: Color(.sRGB, red: 0.49019607843137253, green: 0.13725490196078433, blue: 0.1607843137254902, opacity: 1)',+ );+ expect(dark).toContain(+ 'border: Color(.sRGB, red: 0.5019607843137255, green: 0.5019607843137255, blue: 1, opacity: 1)',+ );+ expect(light).toContain('s4: 4,');+ expect(dark).toContain('s4: 12,');});- it('fails on a value Swift cannot read, naming theme, mode, token, and value', async () => {+ 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': 'color-mix(in srgb, red, blue)'},+ tokens: {'--color-accent': 'currentColor'},});await expect(renderSwiftTheme(theme)).rejects.toThrow(- 'acme-brand light: --color-accent is not a color Swift can read: color-mix(in srgb, red, blue)',+ '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';+ 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) => {+ 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);+ });++ 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 \+/);+ expect(() => toPoints('calc(1rem-2px)')).toThrow(/space on each side of -/);+ });++ it.each([+ ['hwb(0, 0%, 0%)', /no comma syntax/],+ ['rgb(255, none, 0)', /cannot hold none/],+ ['rgba(255, 0, 0, none)', /cannot hold none/],+ ['rgb(255, 50%, 0)', /all numbers or all percentages/],+ ['hsl(120, 50, 40)', /saturation and lightness as percentages/],+ ])('fails the comma syntax CSS does not allow: %s', (css, reason) => {+ 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',+ tokens: {'--color-accent': 'color(display-p3 1 0 0 / 50%)'},+ });+ expect(await renderSwiftTheme(theme)).toContain(+ 'accent: Color(.displayP3, red: 1, green: 0, blue: 0, opacity: 0.5019607843137255)',+ );+ });++ it("keeps a relative color in its origin's gamut through core's var()", async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {+ '--color-accent': 'color(display-p3 1 0 0)',+ '--color-border': 'rgb(from var(--color-accent) r g b / 50%)',+ },+ });+ expect(await renderSwiftTheme(theme)).toContain(+ 'border: Color(.displayP3, red: 1, green: 0, blue: 0, opacity: 0.5019607843137255)',+ );+ });++ it('turns a length line height into a multiplier of its style size', async () => {+ const theme = await defineTheme({+ name: 'acme-brand',+ tokens: {'--text-body-size': '16px', '--text-body-leading': '20px'},+ });+ expect(await renderSwiftTheme(theme)).toMatch(+ /body: TypeStyleTokens\(size: 16, weight: \d+, leading: 1\.25\)/,);});});