@tanrei/mcp 0.1.0-next.0 → 0.1.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +4 -5
- package/README.md +21 -6
- package/bin/tanrei-mcp.js +3 -3
- package/dist/server.js +2218 -711
- package/dist/vocabulary/docs/governance/mimicry-gaps.json +95 -21
- package/dist/vocabulary/packages/tokens-build/generated/component-catalog.json +1825 -0
- package/dist/vocabulary/specs/accordion.spec.json +1 -0
- package/dist/vocabulary/specs/app-bar.spec.json +1 -0
- package/dist/vocabulary/specs/app-shell.spec.json +1 -0
- package/dist/vocabulary/specs/avatar.spec.json +1 -0
- package/dist/vocabulary/specs/badge.spec.json +1 -0
- package/dist/vocabulary/specs/bottom-sheet.spec.json +1 -0
- package/dist/vocabulary/specs/breadcrumbs.spec.json +1 -0
- package/dist/vocabulary/specs/button-group.spec.json +1 -0
- package/dist/vocabulary/specs/button-with-menu.spec.json +1 -0
- package/dist/vocabulary/specs/button.spec.json +1 -0
- package/dist/vocabulary/specs/calendar.spec.json +1 -0
- package/dist/vocabulary/specs/callout.spec.json +1 -0
- package/dist/vocabulary/specs/card.spec.json +1 -0
- package/dist/vocabulary/specs/carousel.spec.json +1 -0
- package/dist/vocabulary/specs/chat-composer.spec.json +1 -0
- package/dist/vocabulary/specs/checkbox-group.spec.json +1 -0
- package/dist/vocabulary/specs/checkbox.spec.json +1 -0
- package/dist/vocabulary/specs/chip-field.spec.json +1 -0
- package/dist/vocabulary/specs/chip.spec.json +1 -0
- package/dist/vocabulary/specs/code-block.spec.json +1 -0
- package/dist/vocabulary/specs/color-field.spec.json +1 -0
- package/dist/vocabulary/specs/color-input.spec.json +1 -0
- package/dist/vocabulary/specs/combobox-field.spec.json +1 -0
- package/dist/vocabulary/specs/combobox.spec.json +1 -0
- package/dist/vocabulary/specs/component.schema.json +1 -0
- package/dist/vocabulary/specs/copy-button.spec.json +1 -0
- package/dist/vocabulary/specs/date-time-picker.spec.json +1 -0
- package/dist/vocabulary/specs/description-list.spec.json +1 -0
- package/dist/vocabulary/specs/dialog.spec.json +1 -0
- package/dist/vocabulary/specs/divider.spec.json +1 -0
- package/dist/vocabulary/specs/drop-zone.spec.json +1 -0
- package/dist/vocabulary/specs/embedded-text-input.spec.json +1 -0
- package/dist/vocabulary/specs/empty-state.spec.json +1 -0
- package/dist/vocabulary/specs/fab-menu.spec.json +1 -0
- package/dist/vocabulary/specs/field-group.spec.json +1 -0
- package/dist/vocabulary/specs/field.spec.json +1 -0
- package/dist/vocabulary/specs/figure.spec.json +1 -0
- package/dist/vocabulary/specs/file-item.spec.json +1 -0
- package/dist/vocabulary/specs/file-picker.spec.json +1 -0
- package/dist/vocabulary/specs/file-upload.spec.json +1 -0
- package/dist/vocabulary/specs/handle.spec.json +1 -0
- package/dist/vocabulary/specs/image-preview.spec.json +1 -0
- package/dist/vocabulary/specs/inline-code.spec.json +1 -0
- package/dist/vocabulary/specs/inventory.json +1 -0
- package/dist/vocabulary/specs/keyboard-shortcut.spec.json +1 -0
- package/dist/vocabulary/specs/link-card.spec.json +1 -0
- package/dist/vocabulary/specs/link.spec.json +1 -0
- package/dist/vocabulary/specs/list-row.spec.json +1 -0
- package/dist/vocabulary/specs/list.spec.json +1 -0
- package/dist/vocabulary/specs/loading-indicator.spec.json +1 -0
- package/dist/vocabulary/specs/main-action-button.spec.json +1 -0
- package/dist/vocabulary/specs/marquee-text.spec.json +1 -0
- package/dist/vocabulary/specs/menu.spec.json +1 -0
- package/dist/vocabulary/specs/menubar.spec.json +1 -0
- package/dist/vocabulary/specs/meter.spec.json +1 -0
- package/dist/vocabulary/specs/modal-layer.spec.json +1 -0
- package/dist/vocabulary/specs/navigation-bar.spec.json +1 -0
- package/dist/vocabulary/specs/navigation-drawer.spec.json +1 -0
- package/dist/vocabulary/specs/number-field.spec.json +1 -0
- package/dist/vocabulary/specs/number-input.spec.json +1 -0
- package/dist/vocabulary/specs/number-ticker.spec.json +1 -0
- package/dist/vocabulary/specs/one-time-code-field.spec.json +1 -0
- package/dist/vocabulary/specs/one-time-code-input.spec.json +1 -0
- package/dist/vocabulary/specs/page-header.spec.json +1 -0
- package/dist/vocabulary/specs/pagination.spec.json +1 -0
- package/dist/vocabulary/specs/popover.spec.json +1 -0
- package/dist/vocabulary/specs/previous-next-links.spec.json +1 -0
- package/dist/vocabulary/specs/progress-indicator.spec.json +1 -0
- package/dist/vocabulary/specs/prose.spec.json +1 -0
- package/dist/vocabulary/specs/radio-button.spec.json +1 -0
- package/dist/vocabulary/specs/radio-group.spec.json +1 -0
- package/dist/vocabulary/specs/rating.spec.json +1 -0
- package/dist/vocabulary/specs/resizable-frame.spec.json +1 -0
- package/dist/vocabulary/specs/scroll-area.spec.json +1 -0
- package/dist/vocabulary/specs/search.spec.json +1 -0
- package/dist/vocabulary/specs/segmented-button.spec.json +1 -0
- package/dist/vocabulary/specs/select-field.spec.json +1 -0
- package/dist/vocabulary/specs/select.spec.json +1 -0
- package/dist/vocabulary/specs/side-sheet.spec.json +1 -0
- package/dist/vocabulary/specs/size-transition.spec.json +1 -0
- package/dist/vocabulary/specs/skeleton.spec.json +1 -0
- package/dist/vocabulary/specs/slider-field.spec.json +1 -0
- package/dist/vocabulary/specs/slider.spec.json +1 -0
- package/dist/vocabulary/specs/snackbar.spec.json +1 -0
- package/dist/vocabulary/specs/split-view.spec.json +1 -0
- package/dist/vocabulary/specs/stepper.spec.json +1 -0
- package/dist/vocabulary/specs/steps.spec.json +1 -0
- package/dist/vocabulary/specs/swatch.spec.json +1 -0
- package/dist/vocabulary/specs/switch.spec.json +1 -0
- package/dist/vocabulary/specs/tab-view.spec.json +1 -0
- package/dist/vocabulary/specs/table-of-contents.spec.json +1 -0
- package/dist/vocabulary/specs/table.spec.json +1 -0
- package/dist/vocabulary/specs/tabs.spec.json +1 -0
- package/dist/vocabulary/specs/tag-group.spec.json +1 -0
- package/dist/vocabulary/specs/tag.spec.json +1 -0
- package/dist/vocabulary/specs/text-field.spec.json +1 -0
- package/dist/vocabulary/specs/text-input.spec.json +1 -0
- package/dist/vocabulary/specs/timeline.spec.json +1 -0
- package/dist/vocabulary/specs/toolbar.spec.json +1 -0
- package/dist/vocabulary/specs/tooltip.spec.json +1 -0
- package/dist/vocabulary/specs/tree-view.spec.json +1 -0
- package/dist/vocabulary/tanrei.config.json +2 -1
- package/dist/vocabulary/tokens/comp/accordion.tokens.json +70 -47
- package/dist/vocabulary/tokens/comp/app-bar.tokens.json +99 -2
- package/dist/vocabulary/tokens/comp/app-shell.tokens.json +1 -1
- package/dist/vocabulary/tokens/comp/avatar.tokens.json +17 -5
- package/dist/vocabulary/tokens/comp/badge.tokens.json +2 -1
- package/dist/vocabulary/tokens/comp/bottom-sheet.tokens.json +143 -73
- package/dist/vocabulary/tokens/comp/breadcrumbs.tokens.json +3 -3
- package/dist/vocabulary/tokens/comp/button-group.tokens.json +26 -4
- package/dist/vocabulary/tokens/comp/button-with-menu.tokens.json +256 -28
- package/dist/vocabulary/tokens/comp/button.tokens.json +275 -22
- package/dist/vocabulary/tokens/comp/calendar.tokens.json +28 -18
- package/dist/vocabulary/tokens/comp/callout.tokens.json +55 -299
- package/dist/vocabulary/tokens/comp/card.tokens.json +3 -3
- package/dist/vocabulary/tokens/comp/carousel.tokens.json +70 -10
- package/dist/vocabulary/tokens/comp/chat-composer.tokens.json +37 -3
- package/dist/vocabulary/tokens/comp/checkbox.tokens.json +18 -22
- package/dist/vocabulary/tokens/comp/chip.tokens.json +67 -16
- package/dist/vocabulary/tokens/comp/code-block.tokens.json +15 -1
- package/dist/vocabulary/tokens/comp/combobox.tokens.json +202 -33
- package/dist/vocabulary/tokens/comp/copy-button.tokens.json +19 -2
- package/dist/vocabulary/tokens/comp/date-time-picker.tokens.json +66 -35
- package/dist/vocabulary/tokens/comp/description-list.tokens.json +45 -23
- package/dist/vocabulary/tokens/comp/dialog.tokens.json +95 -35
- package/dist/vocabulary/tokens/comp/drop-zone.tokens.json +151 -0
- package/dist/vocabulary/tokens/comp/embedded-text-input.tokens.json +2 -2
- package/dist/vocabulary/tokens/comp/field-group.tokens.json +21 -1
- package/dist/vocabulary/tokens/comp/field.tokens.json +33 -4
- package/dist/vocabulary/tokens/comp/figure.tokens.json +56 -2
- package/dist/vocabulary/tokens/comp/file-item.tokens.json +4 -4
- package/dist/vocabulary/tokens/comp/file-picker.tokens.json +3 -3
- package/dist/vocabulary/tokens/comp/file-upload.tokens.json +2 -7
- package/dist/vocabulary/tokens/comp/handle.tokens.json +343 -0
- package/dist/vocabulary/tokens/comp/image-preview.tokens.json +53 -23
- package/dist/vocabulary/tokens/comp/input-box.tokens.json +161 -26
- package/dist/vocabulary/tokens/comp/keyboard-shortcut.tokens.json +5 -3
- package/dist/vocabulary/tokens/comp/link-card.tokens.json +24 -4
- package/dist/vocabulary/tokens/comp/link.tokens.json +3 -3
- package/dist/vocabulary/tokens/comp/list-row.tokens.json +249 -0
- package/dist/vocabulary/tokens/comp/list.tokens.json +106 -225
- package/dist/vocabulary/tokens/comp/loading-indicator.tokens.json +13 -3
- package/dist/vocabulary/tokens/comp/main-action-button.tokens.json +96 -23
- package/dist/vocabulary/tokens/comp/marquee-text.tokens.json +110 -0
- package/dist/vocabulary/tokens/comp/menu.tokens.json +248 -43
- package/dist/vocabulary/tokens/comp/menubar.tokens.json +63 -12
- package/dist/vocabulary/tokens/comp/meter.tokens.json +173 -0
- package/dist/vocabulary/tokens/comp/modal-layer.tokens.json +69 -0
- package/dist/vocabulary/tokens/comp/navigation-bar.tokens.json +5 -36
- package/dist/vocabulary/tokens/comp/navigation-drawer.tokens.json +478 -122
- package/dist/vocabulary/tokens/comp/number-input.tokens.json +2 -2
- package/dist/vocabulary/tokens/comp/number-ticker.tokens.json +77 -0
- package/dist/vocabulary/tokens/comp/one-time-code-input.tokens.json +22 -7
- package/dist/vocabulary/tokens/comp/pagination.tokens.json +118 -79
- package/dist/vocabulary/tokens/comp/popover.tokens.json +84 -13
- package/dist/vocabulary/tokens/comp/previous-next-links.tokens.json +194 -0
- package/dist/vocabulary/tokens/comp/progress-indicator.tokens.json +14 -4
- package/dist/vocabulary/tokens/comp/prose.tokens.json +16 -0
- package/dist/vocabulary/tokens/comp/radio-button.tokens.json +16 -20
- package/dist/vocabulary/tokens/comp/rating.tokens.json +230 -0
- package/dist/vocabulary/tokens/comp/resizable-frame.tokens.json +166 -0
- package/dist/vocabulary/tokens/comp/scroll-area.tokens.json +99 -0
- package/dist/vocabulary/tokens/comp/search.tokens.json +144 -58
- package/dist/vocabulary/tokens/comp/segmented-button.tokens.json +75 -21
- package/dist/vocabulary/tokens/comp/select.tokens.json +168 -34
- package/dist/vocabulary/tokens/comp/side-sheet.tokens.json +60 -13
- package/dist/vocabulary/tokens/comp/size-transition.tokens.json +49 -0
- package/dist/vocabulary/tokens/comp/skeleton.tokens.json +5 -2
- package/dist/vocabulary/tokens/comp/slider.tokens.json +11 -10
- package/dist/vocabulary/tokens/comp/snackbar.tokens.json +81 -255
- package/dist/vocabulary/tokens/comp/split-view.tokens.json +52 -0
- package/dist/vocabulary/tokens/comp/stepper.tokens.json +538 -0
- package/dist/vocabulary/tokens/comp/swatch.tokens.json +208 -0
- package/dist/vocabulary/tokens/comp/switch.tokens.json +19 -18
- package/dist/vocabulary/tokens/comp/tab-view.tokens.json +5 -5
- package/dist/vocabulary/tokens/comp/table-of-contents.tokens.json +58 -33
- package/dist/vocabulary/tokens/comp/table.tokens.json +141 -30
- package/dist/vocabulary/tokens/comp/tabs.tokens.json +132 -44
- package/dist/vocabulary/tokens/comp/tag-group.tokens.json +15 -4
- package/dist/vocabulary/tokens/comp/tag.tokens.json +32 -8
- package/dist/vocabulary/tokens/comp/text-input.tokens.json +18 -88
- package/dist/vocabulary/tokens/comp/timeline.tokens.json +15 -19
- package/dist/vocabulary/tokens/comp/toolbar.tokens.json +121 -6
- package/dist/vocabulary/tokens/comp/tooltip.tokens.json +8 -32
- package/dist/vocabulary/tokens/comp/tree-view.tokens.json +136 -51
- package/dist/vocabulary/tokens/dial/dial.tokens.json +23 -3
- package/dist/vocabulary/tokens/fidelity/cupertino.fidelity.json +165 -0
- package/dist/vocabulary/tokens/fidelity/m3-like.fidelity.json +215 -5
- package/dist/vocabulary/tokens/fidelity/reference/androidx-material3.json +144 -0
- package/dist/vocabulary/tokens/fidelity/reference/apple-hig.json +196 -0
- package/dist/vocabulary/tokens/generated/cupertino/components.json +1749 -0
- package/dist/vocabulary/tokens/generated/cupertino/fidelity.json +162 -0
- package/dist/vocabulary/tokens/generated/m3-like/components.json +1761 -0
- package/dist/vocabulary/tokens/generated/m3-like/fidelity.json +182 -12
- package/dist/vocabulary/tokens/generated/tanrei/components.json +1764 -0
- package/dist/vocabulary/tokens/icon-sets/material-symbols.icon-set.json +2 -1
- package/dist/vocabulary/tokens/schema/system.schema.json +324 -35
- package/dist/vocabulary/tokens/sys/behavior.tokens.json +66 -1
- package/dist/vocabulary/tokens/sys/measure.tokens.json +105 -21
- package/dist/vocabulary/tokens/sys/motion.tokens.json +474 -2
- package/dist/vocabulary/tokens/sys/scroll-edge.tokens.json +50 -0
- package/dist/vocabulary/tokens/sys/shape.tokens.json +1 -1
- package/dist/vocabulary/tokens/sys/state.tokens.json +16 -3
- package/dist/vocabulary/tokens/sys/typescale.tokens.json +5 -5
- package/dist/vocabulary/tokens/systems/core.system.json +1889 -0
- package/dist/vocabulary/tokens/systems/cupertino.system.json +298 -79
- package/dist/vocabulary/tokens/{comp → systems/m3-like/comp}/fab-menu.tokens.json +5 -15
- package/dist/vocabulary/tokens/systems/m3-like.system.json +451 -125
- package/dist/vocabulary/tokens/systems/tanrei.system.json +619 -321
- package/dist/vocabulary/tokens/tanrei.resolver.json +48 -6
- package/package.json +22 -6
- package/dist/vocabulary/tokens/AGENTS.md +0 -15
- package/dist/vocabulary/tokens/comp/navigation-rail.tokens.json +0 -254
- package/dist/vocabulary/tokens/fidelity/m3-expressive-like.fidelity.json +0 -68
- package/dist/vocabulary/tokens/fidelity/reference/androidx-material3-buttons.json +0 -67
- package/dist/vocabulary/tokens/generated/m3-expressive-like/fidelity.json +0 -99
- package/dist/vocabulary/tokens/systems/m3-expressive-like.system.json +0 -83
- package/dist/vocabulary/tokens/vocabulary.lock.json +0 -7052
package/dist/server.js
CHANGED
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
// Bundled from the Tanrei monorepo (packages/mcp, packages/tokens-build, packages/token-engine).
|
|
2
2
|
|
|
3
3
|
// src/server.js
|
|
4
|
-
import
|
|
4
|
+
import fs10 from "node:fs";
|
|
5
5
|
import Ajv20202 from "ajv/dist/2020.js";
|
|
6
6
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
7
7
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
8
8
|
import { CallToolRequestSchema, ErrorCode, ListResourceTemplatesRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
9
9
|
|
|
10
10
|
// src/resources.js
|
|
11
|
-
import
|
|
12
|
-
import
|
|
11
|
+
import fs8 from "node:fs";
|
|
12
|
+
import path9 from "node:path";
|
|
13
13
|
|
|
14
|
-
// src/
|
|
15
|
-
import
|
|
16
|
-
import
|
|
14
|
+
// src/components.js
|
|
15
|
+
import fs7 from "node:fs";
|
|
16
|
+
import path8 from "node:path";
|
|
17
|
+
|
|
18
|
+
// ../tokens-build/src/bundle.js
|
|
19
|
+
import fs2 from "node:fs";
|
|
20
|
+
import path3 from "node:path";
|
|
21
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
17
22
|
|
|
18
23
|
// ../token-engine/src/contexts.js
|
|
19
24
|
var SCHEMES = ["light", "light-medium", "light-high", "dark", "dark-medium", "dark-high"];
|
|
@@ -43,6 +48,7 @@ var SystemError = class extends Error {
|
|
|
43
48
|
var DERIVE = "dev.tanrei.derive";
|
|
44
49
|
var VOCABULARY = "dev.tanrei.vocabulary";
|
|
45
50
|
var ENUM = "dev.tanrei.enum";
|
|
51
|
+
var REFERENCE = "dev.tanrei.reference";
|
|
46
52
|
var enumName = (token) => token?.$extensions?.[ENUM]?.values?.[token.$value];
|
|
47
53
|
var ROUND = { dimension: 0.25, duration: 1, number: 1e-4, tracking: 1e-4 };
|
|
48
54
|
function roundTo(value, step) {
|
|
@@ -51,10 +57,36 @@ function roundTo(value, step) {
|
|
|
51
57
|
}
|
|
52
58
|
var isRef = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
53
59
|
var refId = (v) => v.slice(1, -1);
|
|
60
|
+
function roundToStep(value, step) {
|
|
61
|
+
const n = Math.round(Number((value / step).toFixed(9)));
|
|
62
|
+
return Number((n * step).toFixed(9));
|
|
63
|
+
}
|
|
54
64
|
function ruleDependencies(rule) {
|
|
55
65
|
if (!rule || typeof rule !== "object" || "fixed" in rule) return [];
|
|
56
66
|
if (!("fn" in rule)) return Object.values(rule).flatMap(ruleDependencies);
|
|
57
|
-
|
|
67
|
+
const picked = rule.fn === "pick" && rule.values && typeof rule.values === "object" ? Object.values(rule.values) : [];
|
|
68
|
+
return [rule.of, rule.base, rule.exp, rule.by, rule.round, rule.min, rule.height, rule.with, rule.amount, rule.on, ...Array.isArray(rule.from) ? rule.from : [], ...picked].filter(isRef).map(refId);
|
|
69
|
+
}
|
|
70
|
+
var sameUnit = (fn, field, rule, term, of) => {
|
|
71
|
+
if ((term.unit ?? null) !== (of.unit ?? null)) throw new Error(`"${fn}" ${field} ${rule[field]} (${term.unit ?? "no unit"}) is not in the unit of ${rule.of} (${of.unit ?? "no unit"})`);
|
|
72
|
+
};
|
|
73
|
+
function mulTerms(rule, of, lookup, ctx) {
|
|
74
|
+
if ("times" in rule) throw new Error('"mul" has no "times": a height that moves with another is a step of the control height ladder, or an "add"');
|
|
75
|
+
for (const field of ["round", "min"]) if (rule[field] !== void 0 && !isRef(rule[field])) throw new Error(`"mul" ${field} must be a token, as "{id}"`);
|
|
76
|
+
let step;
|
|
77
|
+
if (rule.round !== void 0) {
|
|
78
|
+
const grid = lookup(refId(rule.round));
|
|
79
|
+
sameUnit("mul", "round", rule, grid, of);
|
|
80
|
+
if (!(grid.value > 0)) throw new Error(`"mul" round ${rule.round} must be above zero; it is ${grid.value}`);
|
|
81
|
+
step = grid.value;
|
|
82
|
+
}
|
|
83
|
+
let min;
|
|
84
|
+
if (rule.min !== void 0 && !ctx.unscaling) {
|
|
85
|
+
const floor = lookup(refId(rule.min));
|
|
86
|
+
sameUnit("mul", "min", rule, floor, of);
|
|
87
|
+
min = floor.value;
|
|
88
|
+
}
|
|
89
|
+
return [step, min];
|
|
58
90
|
}
|
|
59
91
|
function evaluateNumeric(rule, lookup, ctx) {
|
|
60
92
|
const num = (v) => isRef(v) ? lookup(refId(v)).value : v;
|
|
@@ -63,7 +95,33 @@ function evaluateNumeric(rule, lookup, ctx) {
|
|
|
63
95
|
const of = lookup(refId(rule.of));
|
|
64
96
|
const exp = rule.exp === void 0 ? 1 : num(rule.exp);
|
|
65
97
|
const coefficient = exp === 1 ? rule.by : rule.by ** exp;
|
|
66
|
-
|
|
98
|
+
const [step, min] = mulTerms(rule, of, lookup, ctx);
|
|
99
|
+
const product = of.value * coefficient;
|
|
100
|
+
const rounded = step === void 0 ? roundTo(product, ROUND[ctx.type] ?? ROUND.number) : roundToStep(product, step);
|
|
101
|
+
return { value: min === void 0 ? rounded : Math.max(min, rounded), unit: of.unit };
|
|
102
|
+
}
|
|
103
|
+
case "add": {
|
|
104
|
+
if (!isRef(rule.of) || !isRef(rule.by)) throw new Error('"add" needs "of" and "by", each a token as "{id}"');
|
|
105
|
+
if (rule.times !== void 0 && !(typeof rule.times === "number" && Number.isFinite(rule.times))) throw new Error(`"add" times must be a number; it is ${JSON.stringify(rule.times)}`);
|
|
106
|
+
if (rule.min !== void 0 && !isRef(rule.min)) throw new Error('"add" min must be a token, as "{id}"');
|
|
107
|
+
const [of, by] = [lookup(refId(rule.of)), lookup(refId(rule.by))];
|
|
108
|
+
sameUnit("add", "by", rule, by, of);
|
|
109
|
+
const sum = roundTo(of.value + by.value * (rule.times ?? 1), ROUND[ctx.type] ?? ROUND.number);
|
|
110
|
+
if (rule.min === void 0 || ctx.unscaling) return { value: sum, unit: of.unit };
|
|
111
|
+
const floor = lookup(refId(rule.min));
|
|
112
|
+
sameUnit("add", "min", rule, floor, of);
|
|
113
|
+
return { value: Math.max(floor.value, sum), unit: of.unit };
|
|
114
|
+
}
|
|
115
|
+
case "pad": {
|
|
116
|
+
if (!isRef(rule.of) || !isRef(rule.height)) throw new Error('"pad" needs "of" and "height", each a token as "{id}"');
|
|
117
|
+
const of = lookup(refId(rule.of));
|
|
118
|
+
if (rule.by !== void 0 && !(typeof rule.by === "number" && rule.by >= 0)) throw new Error(`"pad" by must be a number of zero or more; it is ${JSON.stringify(rule.by)}`);
|
|
119
|
+
const base = rule.by === void 0 ? of.value : roundTo(of.value * rule.by, ROUND[ctx.type] ?? ROUND.number);
|
|
120
|
+
if (ctx.unscaling) return { value: base, unit: of.unit };
|
|
121
|
+
if (typeof ctx.unscaled !== "function") throw new Error('"pad" needs the height its rule gives with no "min" (ctx.unscaled; see unscaledLookup)');
|
|
122
|
+
const [height, height1] = [lookup(refId(rule.height)), ctx.unscaled(refId(rule.height))];
|
|
123
|
+
sameUnit("pad", "height", rule, height, of);
|
|
124
|
+
return { value: Math.max(0, roundTo(base + (height.value - height1.value) / 2, ROUND[ctx.type] ?? ROUND.number)), unit: of.unit };
|
|
67
125
|
}
|
|
68
126
|
case "scale": {
|
|
69
127
|
const base = lookup(refId(rule.base));
|
|
@@ -73,25 +131,64 @@ function evaluateNumeric(rule, lookup, ctx) {
|
|
|
73
131
|
const of = lookup(refId(rule.of));
|
|
74
132
|
return { value: Math.min(rule.max, Math.max(rule.min, of.value)), unit: of.unit };
|
|
75
133
|
}
|
|
134
|
+
case "sub": {
|
|
135
|
+
if (!isRef(rule.of) || !isRef(rule.by)) throw new Error('"sub" needs "of" and "by", each a token as "{id}"');
|
|
136
|
+
const [of, by] = [lookup(refId(rule.of)), lookup(refId(rule.by))];
|
|
137
|
+
if ((of.unit ?? null) !== (by.unit ?? null)) throw new Error(`"sub" takes ${rule.by} (${by.unit ?? "no unit"}) from ${rule.of} (${of.unit ?? "no unit"}): both need one unit`);
|
|
138
|
+
return { value: roundTo(Math.max(0, of.value - by.value), ROUND[ctx.type] ?? ROUND.number), unit: of.unit };
|
|
139
|
+
}
|
|
76
140
|
case "em":
|
|
77
141
|
if (ctx.fontSize === void 0) throw new Error('"em" is only valid for typography.letterSpacing');
|
|
78
142
|
return { value: roundTo(ctx.fontSize * rule.by, ROUND.tracking), unit: "px" };
|
|
143
|
+
case "pick": {
|
|
144
|
+
if (!isRef(rule.by)) throw new Error('"pick" needs "by": the choice of kind it follows, as "{id}"');
|
|
145
|
+
const choice = lookup(refId(rule.by));
|
|
146
|
+
const names = choice.names;
|
|
147
|
+
if (!Array.isArray(names)) throw new Error(`"pick" follows ${rule.by}, which is not a choice of kind (it has no ${ENUM}.values)`);
|
|
148
|
+
const values = rule.values ?? {};
|
|
149
|
+
const missing = names.filter((name) => !(name in values));
|
|
150
|
+
const unknown = Object.keys(values).filter((name) => !names.includes(name));
|
|
151
|
+
if (missing.length || unknown.length) throw new Error(`"pick" must give one value for each name of ${rule.by} (${names.join(", ")})${missing.length ? `; it gives none for ${missing.join(", ")}` : ""}${unknown.length ? `; ${unknown.join(", ")} is not one of them` : ""}`);
|
|
152
|
+
const chosen = values[names[choice.value]];
|
|
153
|
+
if (isRef(chosen)) return lookup(refId(chosen));
|
|
154
|
+
return typeof chosen === "number" ? { value: chosen } : { ...chosen };
|
|
155
|
+
}
|
|
79
156
|
default:
|
|
80
157
|
throw new Error(`unknown rule function "${rule.fn}"`);
|
|
81
158
|
}
|
|
82
159
|
}
|
|
83
|
-
function
|
|
160
|
+
function unscaledLookup(describe) {
|
|
161
|
+
const memo = /* @__PURE__ */ new Map();
|
|
162
|
+
const unscaled = (id) => {
|
|
163
|
+
if (memo.has(id)) {
|
|
164
|
+
if (memo.get(id) === null) throw new Error(`cycle through {${id}}`);
|
|
165
|
+
return memo.get(id);
|
|
166
|
+
}
|
|
167
|
+
memo.set(id, null);
|
|
168
|
+
try {
|
|
169
|
+
const { alias, rule, type, value, reference } = describe(id);
|
|
170
|
+
const result = reference ? value && value.value > reference.value ? value : { ...reference } : alias ? unscaled(alias) : rule && typeof rule.fn === "string" ? evaluateNumeric(rule, unscaled, { type, unscaling: true, unscaled }) : value;
|
|
171
|
+
memo.set(id, result);
|
|
172
|
+
return result;
|
|
173
|
+
} catch (error) {
|
|
174
|
+
memo.delete(id);
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
return unscaled;
|
|
179
|
+
}
|
|
180
|
+
function* walkTokens(node, path11 = [], inherited = {}) {
|
|
84
181
|
const here = {
|
|
85
182
|
type: node.$type ?? inherited.type,
|
|
86
183
|
rationale: node.$extensions?.[VOCABULARY]?.rationale ?? inherited.rationale
|
|
87
184
|
};
|
|
88
185
|
if ("$value" in node) {
|
|
89
|
-
yield { id:
|
|
186
|
+
yield { id: path11.join("."), token: node, type: here.type, rationale: here.rationale };
|
|
90
187
|
return;
|
|
91
188
|
}
|
|
92
189
|
for (const [key, child] of Object.entries(node)) {
|
|
93
190
|
if (key.startsWith("$") || child === null || typeof child !== "object") continue;
|
|
94
|
-
yield* walkTokens(child, [...
|
|
191
|
+
yield* walkTokens(child, [...path11, key], here);
|
|
95
192
|
}
|
|
96
193
|
}
|
|
97
194
|
|
|
@@ -100,14 +197,15 @@ var STATES = "dev.tanrei.states";
|
|
|
100
197
|
var COLOR_RULES = /* @__PURE__ */ new Set(["mix", "alpha", "tone", "contrast-pick"]);
|
|
101
198
|
var isColorRule = (op) => Boolean(op && !("$value" in op) && COLOR_RULES.has(op.derive?.fn));
|
|
102
199
|
var isRef2 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
200
|
+
var hasContextAmount = (rule) => (rule.fn === "mix" || rule.fn === "alpha") && rule.amount !== null && typeof rule.amount === "object";
|
|
103
201
|
var refId2 = (v) => v.slice(1, -1);
|
|
104
202
|
var clone = (v) => JSON.parse(JSON.stringify(v));
|
|
105
203
|
function expandStateVocabulary(compDocuments) {
|
|
106
204
|
const out = [];
|
|
107
|
-
const visit = (node,
|
|
205
|
+
const visit = (node, path11) => {
|
|
108
206
|
const decl = node.$extensions?.[STATES];
|
|
109
207
|
if (decl) {
|
|
110
|
-
const component =
|
|
208
|
+
const component = path11.join(".");
|
|
111
209
|
const rationale = node.$extensions?.[VOCABULARY]?.rationale;
|
|
112
210
|
for (const state of decl.states) {
|
|
113
211
|
for (const variant of decl.variants ?? []) {
|
|
@@ -116,7 +214,7 @@ function expandStateVocabulary(compDocuments) {
|
|
|
116
214
|
for (const [part, type] of Object.entries(decl.perComponent ?? {})) out.push({ id: `${component}.${state}.${part}`, type, component, state, part, rationale });
|
|
117
215
|
}
|
|
118
216
|
}
|
|
119
|
-
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) visit(child, [...
|
|
217
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) visit(child, [...path11, key]);
|
|
120
218
|
};
|
|
121
219
|
for (const doc of compDocuments) visit(doc, []);
|
|
122
220
|
return out;
|
|
@@ -136,28 +234,28 @@ function matchPattern(pattern, id, s = id.split(".")) {
|
|
|
136
234
|
var substitute = (value, captures) => typeof value === "string" ? value.replace(/\$(\d)/g, (_, n) => captures[n - 1] ?? `$${n}`) : Array.isArray(value) ? value.map((v) => substitute(v, captures)) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, captures)])) : value;
|
|
137
235
|
var ruleIndexes = /* @__PURE__ */ new WeakMap();
|
|
138
236
|
function ruleIndex(rules) {
|
|
139
|
-
let
|
|
140
|
-
if (!
|
|
237
|
+
let index2 = ruleIndexes.get(rules);
|
|
238
|
+
if (!index2 || index2.count !== rules.length) {
|
|
141
239
|
const byLength = /* @__PURE__ */ new Map();
|
|
142
240
|
for (const rule of rules) {
|
|
143
241
|
const p = rule.match.split(".");
|
|
144
242
|
if (!byLength.has(p.length)) byLength.set(p.length, []);
|
|
145
243
|
byLength.get(p.length).push({ rule, p });
|
|
146
244
|
}
|
|
147
|
-
|
|
148
|
-
ruleIndexes.set(rules,
|
|
245
|
+
index2 = { count: rules.length, byLength, chosen: /* @__PURE__ */ new Map() };
|
|
246
|
+
ruleIndexes.set(rules, index2);
|
|
149
247
|
}
|
|
150
|
-
return
|
|
248
|
+
return index2;
|
|
151
249
|
}
|
|
152
250
|
function operationFor(id, system) {
|
|
153
251
|
if (system.tokens[id]) return system.tokens[id];
|
|
154
252
|
if (!system.rules?.length) return null;
|
|
155
|
-
const
|
|
156
|
-
let best =
|
|
253
|
+
const index2 = ruleIndex(system.rules);
|
|
254
|
+
let best = index2.chosen.get(id);
|
|
157
255
|
if (best === void 0) {
|
|
158
256
|
best = null;
|
|
159
257
|
const s = id.split(".");
|
|
160
|
-
for (const { rule, p } of
|
|
258
|
+
for (const { rule, p } of index2.byLength.get(s.length) ?? []) {
|
|
161
259
|
const captures = [];
|
|
162
260
|
let hit = true;
|
|
163
261
|
for (let i = 0; i < p.length && hit; i++) {
|
|
@@ -166,7 +264,7 @@ function operationFor(id, system) {
|
|
|
166
264
|
}
|
|
167
265
|
if (hit && (!best || captures.length <= best.captures.length)) best = { rule, captures };
|
|
168
266
|
}
|
|
169
|
-
|
|
267
|
+
index2.chosen.set(id, best);
|
|
170
268
|
}
|
|
171
269
|
if (!best) return null;
|
|
172
270
|
const { match, ...operation } = best.rule;
|
|
@@ -175,9 +273,9 @@ function operationFor(id, system) {
|
|
|
175
273
|
function matchingRules(id, layers) {
|
|
176
274
|
const hits = [];
|
|
177
275
|
for (const layer of layers) {
|
|
178
|
-
(layer.rules ?? []).forEach((rule,
|
|
276
|
+
(layer.rules ?? []).forEach((rule, index2) => {
|
|
179
277
|
const captures = matchPattern(rule.match, id);
|
|
180
|
-
if (captures) hits.push({ layer: layer.id, index, match: rule.match, wildcards: captures.length });
|
|
278
|
+
if (captures) hits.push({ layer: layer.id, index: index2, match: rule.match, wildcards: captures.length });
|
|
181
279
|
});
|
|
182
280
|
}
|
|
183
281
|
const explicit = [...layers].reverse().find((layer) => layer.tokens?.[id]);
|
|
@@ -239,9 +337,9 @@ function statePlan(system, documents, NS3, across) {
|
|
|
239
337
|
const authoredColors = /* @__PURE__ */ new Set();
|
|
240
338
|
for (const doc of Object.values(documents)) for (const entry of walkTokens(doc)) authored.set(entry.id, entry.token), entry.type === "color" && authoredColors.add(entry.id);
|
|
241
339
|
const rationales = new Map(vocabulary.map((v) => [v.component, v.rationale]));
|
|
242
|
-
const declaring = (node,
|
|
243
|
-
if (node.$extensions?.[STATES] && !rationales.has(
|
|
244
|
-
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) declaring(child, [...
|
|
340
|
+
const declaring = (node, path11) => {
|
|
341
|
+
if (node.$extensions?.[STATES] && !rationales.has(path11.join("."))) rationales.set(path11.join("."), node.$extensions[VOCABULARY]?.rationale);
|
|
342
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) declaring(child, [...path11, key]);
|
|
245
343
|
};
|
|
246
344
|
for (const doc of comp) declaring(doc, []);
|
|
247
345
|
const resting = Object.entries(system.tokens).filter(([id, op]) => id.startsWith(`${NS3}.comp.`) && authoredColors.has(id) && isColorRule(op)).map(([id]) => ({ id, type: "color", state: null, rationale: rationales.get(id.split(".").slice(0, 3).join(".")) }));
|
|
@@ -286,7 +384,8 @@ function generateStateDocument({ system, documents, roleColor, toneColor, note,
|
|
|
286
384
|
} catch (error) {
|
|
287
385
|
throw new SystemError(`${id}: the "${rule.fn}" rule's amount cannot be read for scheme "${scheme}": ${error.message}`);
|
|
288
386
|
}
|
|
289
|
-
if (
|
|
387
|
+
if (isMap && isRef2(n)) return resolve(refId2(n), trail);
|
|
388
|
+
if (typeof n !== "number" || !Number.isFinite(n)) throw new SystemError(`${id}: the "${rule.fn}" rule's amount must be a number from 0 to 1, a "{\u2026}" reference to one, or a context map of those ([standard, medium, high] or { "light": [\u2026], "dark": [\u2026] }) \u2014 not ${JSON.stringify(v)}`);
|
|
290
389
|
return n;
|
|
291
390
|
};
|
|
292
391
|
function resolve(id, trail = []) {
|
|
@@ -339,14 +438,15 @@ function generateStateDocument({ system, documents, roleColor, toneColor, note,
|
|
|
339
438
|
let written = plan.written.get(entry.id);
|
|
340
439
|
if (!written) {
|
|
341
440
|
const aliasOnly = op && !op.derive && isRef2(op.$value);
|
|
342
|
-
const $
|
|
343
|
-
if (op?.derive) $
|
|
344
|
-
else if (!aliasOnly) $
|
|
345
|
-
Object.freeze($
|
|
346
|
-
written = aliasOnly ? { token: Object.freeze({ $type: entry.type, $value: op.$value, $extensions }) } : { $extensions };
|
|
441
|
+
const $extensions2 = { [VOCABULARY]: plan.rationale(entry.rationale), ...entry.state ? { "dev.tanrei.state": entry.state } : {} };
|
|
442
|
+
if (op?.derive) $extensions2[DERIVE] = op.derive;
|
|
443
|
+
else if (!aliasOnly) $extensions2[DERIVE] = { fixed: op.reason ?? "Set by the system layer." };
|
|
444
|
+
Object.freeze($extensions2);
|
|
445
|
+
written = aliasOnly ? { token: Object.freeze({ $type: entry.type, $value: op.$value, $extensions: $extensions2 }) } : { $extensions: $extensions2 };
|
|
347
446
|
plan.written.set(entry.id, written);
|
|
348
447
|
}
|
|
349
|
-
|
|
448
|
+
const $extensions = op?.derive && hasContextAmount(op.derive) ? Object.freeze({ ...written.$extensions, [DERIVE]: { ...op.derive, amount: inContext(op.derive.amount, scheme) } }) : written.$extensions;
|
|
449
|
+
node[parts.at(-1)] = written.token ?? { $type: entry.type, $value: picked.has(entry.id) ? picked.get(entry.id) : entry.type === "color" ? toDtcgColor(value) : value, $extensions };
|
|
350
450
|
}
|
|
351
451
|
return root2;
|
|
352
452
|
}
|
|
@@ -372,14 +472,14 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
372
472
|
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
373
473
|
const REF_PALETTE = `${NS3}.ref.palette.`;
|
|
374
474
|
function buildPalette(declaration, name) {
|
|
375
|
-
const
|
|
475
|
+
const source2 = declaration.source ?? {};
|
|
376
476
|
let generated;
|
|
377
|
-
if ("seed" in
|
|
378
|
-
const hct = Hct2.fromInt(hexToArgb(
|
|
477
|
+
if ("seed" in source2) {
|
|
478
|
+
const hct = Hct2.fromInt(hexToArgb(source2.seed));
|
|
379
479
|
generated = TonalPalette2.fromHueAndChroma(hct.hue, hct.chroma);
|
|
380
|
-
} else if ("hue" in
|
|
381
|
-
else throw new Error(`palette "${name}": unsupported source ${JSON.stringify(
|
|
382
|
-
const fixed = new Map(Object.entries(
|
|
480
|
+
} else if ("hue" in source2 && "chroma" in source2) generated = TonalPalette2.fromHueAndChroma(source2.hue, source2.chroma);
|
|
481
|
+
else throw new Error(`palette "${name}": unsupported source ${JSON.stringify(source2)}`);
|
|
482
|
+
const fixed = new Map(Object.entries(source2.tones ?? {}).map(([tone, hex]) => [Number(tone), hexToArgb(hex)]));
|
|
383
483
|
if (!fixed.size) return generated;
|
|
384
484
|
return { tone: (t) => fixed.get(t) ?? generated.tone(t) };
|
|
385
485
|
}
|
|
@@ -389,6 +489,15 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
389
489
|
"{name}-container": { light: [93, 91, 89], dark: [22] },
|
|
390
490
|
"on-{name}-container": { light: [20, 15, 10], dark: [88, 92, 96] }
|
|
391
491
|
};
|
|
492
|
+
const INVERSE_TONES = { light: [80, 85, 90], dark: [40, 30, 20] };
|
|
493
|
+
function roleOperation(system, role, entry) {
|
|
494
|
+
const op = system.tokens[`${SYS_COLOR4}${role}`];
|
|
495
|
+
const palette = entry?.template?.palette;
|
|
496
|
+
if (!palette || op?.derive?.fn !== "tone" || op.derive.palette === palette) return op;
|
|
497
|
+
const chain = system.chain ?? [];
|
|
498
|
+
const declared = chain.indexOf(system.paletteLayers?.[palette]);
|
|
499
|
+
return declared >= 0 && declared > chain.indexOf(op.layer) ? void 0 : op;
|
|
500
|
+
}
|
|
392
501
|
function roleTable(system, vocabulary) {
|
|
393
502
|
const table = /* @__PURE__ */ new Map();
|
|
394
503
|
const pattern = vocabulary.sets.intent.roles;
|
|
@@ -396,7 +505,11 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
396
505
|
for (const p of pattern) table.set(p.replace("{name}", name), { rationale, template: palette ? { palette, tone: INTENT_TONES[p] } : null, declared });
|
|
397
506
|
};
|
|
398
507
|
for (const [name, rationale] of Object.entries(vocabulary.intents)) add(name, name in system.palettes ? name : null, rationale, false);
|
|
399
|
-
|
|
508
|
+
const inverseOf = (role) => Object.keys(vocabulary.intents).find((name) => role === `inverse-${name}` && name in system.palettes);
|
|
509
|
+
for (const [role, rationale] of Object.entries(vocabulary.roles)) {
|
|
510
|
+
const intent = inverseOf(role);
|
|
511
|
+
table.set(role, { rationale, template: intent ? { palette: intent, tone: INVERSE_TONES } : null, declared: false });
|
|
512
|
+
}
|
|
400
513
|
for (const [name, decl] of Object.entries(system.palettes)) {
|
|
401
514
|
if (decl.roles !== "intent") continue;
|
|
402
515
|
if (name in vocabulary.intents) continue;
|
|
@@ -406,12 +519,24 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
406
519
|
for (const [id, decl] of Object.entries(system.vocabulary ?? {})) {
|
|
407
520
|
if (decl.kind !== "token" || !id.startsWith(SYS_COLOR4)) continue;
|
|
408
521
|
const role = id.slice(SYS_COLOR4.length);
|
|
409
|
-
if (table.has(role))
|
|
522
|
+
if (table.has(role)) throw new SystemError(`${id}: "${role}" is a core color role; a layer declares only what the core lacks: delete this declaration, and write its value under "tokens"`);
|
|
410
523
|
if (decl.type !== "color") throw new Error(`${id}: a color role is declared with "$type": "color"`);
|
|
411
524
|
table.set(role, { rationale: decl.rationale, template: null, declared: true, extension: { declaredBy: decl.declaredBy, onRole: decl.onRole } });
|
|
412
525
|
}
|
|
413
526
|
return table;
|
|
414
527
|
}
|
|
528
|
+
function paletteToneColor(palettes, target, where) {
|
|
529
|
+
const [p, t] = target.slice(REF_PALETTE.length).split(".");
|
|
530
|
+
if (!palettes[p]) throw new SystemError(`${where}: {${target}} names the palette "${p}", which this system does not declare`);
|
|
531
|
+
return argbToRgb(palettes[p].tone(Number(t)));
|
|
532
|
+
}
|
|
533
|
+
function valueColor(palettes, def) {
|
|
534
|
+
if (def.alpha) {
|
|
535
|
+
const c = def.alpha === "white" ? 1 : 0;
|
|
536
|
+
return { r: c, g: c, b: c, a: def.a / 100 };
|
|
537
|
+
}
|
|
538
|
+
return argbToRgb(palettes[def.p].tone(def.t));
|
|
539
|
+
}
|
|
415
540
|
function rolesFor(system, scheme, vocabulary, palettes = buildPalettes(system)) {
|
|
416
541
|
const table = roleTable(system, vocabulary);
|
|
417
542
|
for (const id of Object.keys(system.tokens)) {
|
|
@@ -421,9 +546,10 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
421
546
|
}
|
|
422
547
|
const out = {};
|
|
423
548
|
const picks = [];
|
|
424
|
-
for (const [role,
|
|
549
|
+
for (const [role, entry] of table) {
|
|
550
|
+
const { template } = entry;
|
|
425
551
|
const id = `${SYS_COLOR4}${role}`;
|
|
426
|
-
const op = system
|
|
552
|
+
const op = roleOperation(system, role, entry);
|
|
427
553
|
if (op && "$value" in op && typeof op.$value !== "string") {
|
|
428
554
|
throw new Error(`${id}: a color role cannot hold a literal. Alias another role ("{\u2026}"), use a tone or alpha rule, or declare a palette for the color.`);
|
|
429
555
|
}
|
|
@@ -440,11 +566,7 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
440
566
|
const pending = new Map(picks.map((pick2) => [pick2.role, pick2]));
|
|
441
567
|
const colorOf = (ref, trail) => {
|
|
442
568
|
const target = ref.slice(1, -1);
|
|
443
|
-
if (target.startsWith(REF_PALETTE))
|
|
444
|
-
const [p, t] = target.slice(REF_PALETTE.length).split(".");
|
|
445
|
-
if (!palettes[p]) throw new SystemError(`${trail.at(-1)}: {${target}} names the palette "${p}", which this system does not declare`);
|
|
446
|
-
return argbToRgb(palettes[p].tone(Number(t)));
|
|
447
|
-
}
|
|
569
|
+
if (target.startsWith(REF_PALETTE)) return paletteToneColor(palettes, target, trail.at(-1));
|
|
448
570
|
if (!target.startsWith(SYS_COLOR4)) throw new SystemError(`${trail.at(-1)}: "contrast-pick" on a color role chooses among color roles and ${REF_PALETTE}<palette>.<tone> \u2014 {${target}} is neither`);
|
|
449
571
|
const role = target.slice(SYS_COLOR4.length);
|
|
450
572
|
if (trail.includes(target)) throw new SystemError(`cycle: ${[...trail, target].join(" \u2192 ")}`);
|
|
@@ -452,8 +574,7 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
452
574
|
const def = out[role];
|
|
453
575
|
if (!def) throw new SystemError(`${trail.at(-1)}: unknown color role {${target}}`);
|
|
454
576
|
if (def.ref) return colorOf(def.ref, [...trail, target]);
|
|
455
|
-
|
|
456
|
-
return argbToRgb(palettes[def.p].tone(def.t));
|
|
577
|
+
return valueColor(palettes, def);
|
|
457
578
|
};
|
|
458
579
|
function decide({ role, id, rule }, trail = []) {
|
|
459
580
|
checkContrastPick(rule, id);
|
|
@@ -509,9 +630,12 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
509
630
|
const roleColor = (role, trail = []) => {
|
|
510
631
|
const def = resolved[scheme][role];
|
|
511
632
|
if (!def) throw new Error(`unknown color role "${role}"`);
|
|
512
|
-
if (def.ref)
|
|
513
|
-
|
|
514
|
-
|
|
633
|
+
if (def.ref) {
|
|
634
|
+
const target = def.ref.slice(1, -1);
|
|
635
|
+
if (target.startsWith(REF_PALETTE)) return paletteToneColor(palettes, target, `${SYS_COLOR4}${role}`);
|
|
636
|
+
return roleColor(target.slice(SYS_COLOR4.length), [...trail, role]);
|
|
637
|
+
}
|
|
638
|
+
return valueColor(palettes, def);
|
|
515
639
|
};
|
|
516
640
|
const toneColor = (palette2, tone, id = "?") => {
|
|
517
641
|
if (!palettes[palette2]) throw new SystemError(`${id}: unknown palette "${palette2}". Declared: ${Object.keys(palettes).join(", ")}.`);
|
|
@@ -525,7 +649,7 @@ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace
|
|
|
525
649
|
}
|
|
526
650
|
return files;
|
|
527
651
|
}
|
|
528
|
-
return { buildPalette, roleTable, rolesFor, generateColorFiles };
|
|
652
|
+
return { buildPalette, roleTable, roleOperation, rolesFor, generateColorFiles };
|
|
529
653
|
}
|
|
530
654
|
|
|
531
655
|
// ../token-engine/src/operations.js
|
|
@@ -619,9 +743,10 @@ function legalOperations(descriptor, { namespace: NS3 = DEFAULT_NAMESPACE } = {}
|
|
|
619
743
|
operations.push(entry("re-point alias", { $value: `{${alias.split(".").slice(0, -1).join(".")}.<another-step>}` }, `Use a different step of the same scale. It is "{${alias}}" now. The target must exist and be of the same $type.`));
|
|
620
744
|
if (["dimension", "duration", "number"].includes(type)) operations.push(entry("scale", { scale: 2 }, "N \xD7 the inherited alias target, still following its dial."));
|
|
621
745
|
}
|
|
746
|
+
if (kind === "derived" && rule?.fn === "pick") operations.push({ op: "note", effect: `This value follows the choice ${rule.by}: each of its names sets its own value (${Object.entries(rule.values ?? {}).map(([name, v]) => `${name}: ${typeof v === "object" && v !== null ? `${v.value}${v.unit ?? ""}` : v}`).join(", ")}). Choose another name there to change it with the others it sets, or pin this one.` });
|
|
622
747
|
if (kind === "derived" && rule?.fn === "mul") operations.push(entry("scale", { scale: 1.5 }, `N \xD7 the inherited rule (${rule.of} \xD7 ${rule.by}); still follows the dial. Composes with a parent layer's scale.`));
|
|
623
748
|
if (kind === "derived" || kind === "fixed") operations.push(entry("re-point alias", { $value: `{${NS3}.sys.<scale>.<step>}` }, "Make it follow another token instead of its own rule."));
|
|
624
|
-
operations.push(entry("derive", { derive: { fn: "mul", of: `{${NS3}.dial.<family>.unit}`, by: 3 } }, "Replace the rule. Closed language: mul, scale, clamp (
|
|
749
|
+
operations.push(entry("derive", { derive: { fn: "mul", of: `{${NS3}.dial.<family>.unit}`, by: 3 } }, "Replace the rule. Closed language: mul (with optional round and min: max(min, round(of \xD7 by, round))), add (max(min, of + by \xD7 times): a step a number of units from another value), scale, clamp, sub (max(0, of \u2212 by): a corner inside another at an inset), pad (max(0, of \xD7 by + (height \u2212 height\u2081) / 2): a block padding that follows the height of its box), and pick (a value set by a choice of kind) for numbers. No other arithmetic, conditionals or functions of your own."));
|
|
625
750
|
operations.push(entry("pin $value", { $value: literal, reason: REASON }, "A literal that no longer follows any dial. Last resort; the reason is mandatory and is written into the generated tokens."));
|
|
626
751
|
if (kind === "fixed") operations.unshift({ op: "note", effect: `This token is fixed${rule?.fixed ? ` ("${rule.fixed}")` : ""}: "scale" is not legal on it \u2014 pin another $value (with a reason) or give it a rule.` });
|
|
627
752
|
return operations;
|
|
@@ -664,15 +789,48 @@ var AXES = "dev.tanrei.axes";
|
|
|
664
789
|
var KEY = /^[a-z0-9][a-z0-9-]*$/;
|
|
665
790
|
var isRef3 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
666
791
|
var clone2 = (v) => JSON.parse(JSON.stringify(v));
|
|
667
|
-
var kindOf = (entry, id) => !("from" in entry) ? "token" : id.split(".")[1] === "sys" ? "group" : "axis-value";
|
|
668
|
-
|
|
792
|
+
var kindOf = (entry, id) => "document" in entry ? "component" : !("from" in entry) ? "token" : id.split(".")[1] === "sys" ? "group" : "axis-value";
|
|
793
|
+
var heldDocumentPath = (layerId, component) => `systems/${layerId}/comp/${component}.tokens.json`;
|
|
794
|
+
var componentDocumentPath = (component) => `comp/${component}.tokens.json`;
|
|
795
|
+
var isHeldDocument = (name) => name.startsWith("systems/");
|
|
796
|
+
function componentDeclaration(id, entry, layerId, CORE_NS) {
|
|
797
|
+
const segments2 = id.split(".");
|
|
798
|
+
if (segments2[0] !== CORE_NS || segments2[1] !== "comp" || segments2.length !== 3) throw new SystemError(`${id}: a component's whole vocabulary is declared as "${CORE_NS}.comp.<component>", in the core namespace, so that the names a product, a stylesheet and the native types use do not depend on where the component lives`);
|
|
799
|
+
const component = segments2[2];
|
|
800
|
+
if (entry.document !== componentDocumentPath(component)) throw new SystemError(`${id}: "document" is "${componentDocumentPath(component)}" \u2014 the component's document, kept in tokens/systems/${layerId}/`);
|
|
801
|
+
for (const key of ["$type", "from", "scale", "$value", "derive", "onRole"]) if (key in entry) throw new SystemError(`${id}: a component's whole vocabulary is its document; "${key}" belongs to a single token`);
|
|
802
|
+
for (const rule of entry.rules ?? []) {
|
|
803
|
+
if (typeof rule?.match !== "string" || !rule.match.startsWith(`${CORE_NS}.comp.${component}.`)) throw new SystemError(`${id}: its rules value the component's own states \u2014 "match" starts with "${CORE_NS}.comp.${component}.", not ${JSON.stringify(rule?.match)}`);
|
|
804
|
+
}
|
|
805
|
+
return component;
|
|
806
|
+
}
|
|
807
|
+
function borrowed({ name, from }, layer, lend, CORE_NS) {
|
|
808
|
+
const id = `${CORE_NS}.comp.${name}`;
|
|
809
|
+
if (!lend) throw new SystemError(`${layer.id}: components.include takes "${name}" from "${from}"; building it needs that layer \u2014 pass "lend"`);
|
|
810
|
+
const entry = lend(from)?.vocabulary?.[id];
|
|
811
|
+
if (!entry || typeof entry !== "object" || !("document" in entry)) throw new SystemError(`${layer.id}: components.include: "${name}" does not live in "${from}" \u2014 that layer declares no "${id}" with its document`);
|
|
812
|
+
return { id, component: componentDeclaration(id, entry, from, CORE_NS), entry };
|
|
813
|
+
}
|
|
814
|
+
function collectVocabulary(layers, { namespace: CORE_NS = "tanrei", lend } = {}) {
|
|
669
815
|
const out = {};
|
|
816
|
+
const copy = (rules) => JSON.parse(JSON.stringify(rules ?? []));
|
|
670
817
|
for (const layer of layers) {
|
|
818
|
+
for (const include of layer.components?.include ?? []) {
|
|
819
|
+
if (typeof include !== "object" || include === null) continue;
|
|
820
|
+
const { id, component, entry } = borrowed(include, layer, lend, CORE_NS);
|
|
821
|
+
if (out[id]) throw new SystemError(`${layer.id}: components.include: "${component}" is already in this system (declared by layer "${out[id].declaredBy}"); there is nothing to include`);
|
|
822
|
+
out[id] = { kind: "component", component, document: entry.document, rules: copy(entry.rules), rationale: entry.rationale, declaredBy: include.from, includedBy: layer.id, definition: {} };
|
|
823
|
+
}
|
|
671
824
|
for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
|
|
672
825
|
if (out[id]) throw new SystemError(`${id}: already declared by layer "${out[id].declaredBy}". Declare a token once; change its value under "tokens".`);
|
|
673
826
|
if (typeof entry.rationale !== "string" || entry.rationale.length < 8) throw new SystemError(`${id}: an extension needs a "rationale" \u2014 why does this design system or product need it?`);
|
|
674
827
|
const namespace = id.split(".")[0];
|
|
675
828
|
const kind = kindOf(entry, id);
|
|
829
|
+
if (kind === "component") {
|
|
830
|
+
const component = componentDeclaration(id, entry, layer.id, CORE_NS);
|
|
831
|
+
out[id] = { kind, component, document: entry.document, rules: copy(entry.rules), rationale: entry.rationale, description: entry.$description, declaredBy: layer.id, definition: {} };
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
676
834
|
if (namespace !== CORE_NS) {
|
|
677
835
|
if (namespace !== layer.id) throw new SystemError(`${id}: a layer's own tokens live in its own namespace \u2014 "${layer.id}.\u2026", not "${namespace}.\u2026"`);
|
|
678
836
|
if (kind === "group") throw new SystemError(`${id}: a step cloned with "from" belongs to a series of the core vocabulary \u2014 "${CORE_NS}.sys.<series>.\u2026". In your own namespace declare each token with "$type".`);
|
|
@@ -715,15 +873,24 @@ function scaleNode(node, factor, id, type) {
|
|
|
715
873
|
ext[DERIVE] = { fn: "mul", of: node.$value, by: factor };
|
|
716
874
|
node.$value = null;
|
|
717
875
|
} else if (ext[DERIVE]?.fn === "mul") ext[DERIVE] = { ...ext[DERIVE], by: ext[DERIVE].by * factor };
|
|
876
|
+
else if (ext[DERIVE]?.fn === "pad") ext[DERIVE] = { ...ext[DERIVE], by: (ext[DERIVE].by ?? 1) * factor };
|
|
718
877
|
else throw new SystemError(`${id}: cannot scale a fixed value \u2014 give this member a value under "tokens"`);
|
|
719
878
|
}
|
|
720
|
-
function
|
|
879
|
+
function repointPad(node, componentPath, members, from, value) {
|
|
880
|
+
const rule = node.$extensions?.[DERIVE];
|
|
881
|
+
if (rule?.fn !== "pad" || !isRef3(rule.height)) return;
|
|
882
|
+
const prefix = `${componentPath.join(".")}.`;
|
|
883
|
+
const height = rule.height.slice(1, -1);
|
|
884
|
+
const member = members.find((m) => height === `${prefix}${m}.${from}`);
|
|
885
|
+
if (member) node.$extensions[DERIVE] = { ...rule, height: `{${prefix}${member}.${value}}` };
|
|
886
|
+
}
|
|
887
|
+
function* tokensUnder(node, path11 = [], type) {
|
|
721
888
|
const here = node.$type ?? type;
|
|
722
889
|
if (isToken(node)) {
|
|
723
|
-
yield { path:
|
|
890
|
+
yield { path: path11, token: node, type: here };
|
|
724
891
|
return;
|
|
725
892
|
}
|
|
726
|
-
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") yield* tokensUnder(child, [...
|
|
893
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") yield* tokensUnder(child, [...path11, key], here);
|
|
727
894
|
}
|
|
728
895
|
function addAxisValue(docs, id, decl) {
|
|
729
896
|
const segments2 = id.split(".");
|
|
@@ -737,14 +904,14 @@ function addAxisValue(docs, id, decl) {
|
|
|
737
904
|
const states = component.$extensions[STATES];
|
|
738
905
|
const values = declared.from === "states" ? states.variants : declared.values;
|
|
739
906
|
if (!values.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing ${axis} (${values.join(", ")}), not "${decl.from}"`);
|
|
740
|
-
if (values.includes(value))
|
|
907
|
+
if (values.includes(value)) throw new SystemError(`${id}: "${value}" is a core ${axis} of ${componentPath.join(".")}; a layer declares only what the core lacks: delete this declaration (its values under "tokens" stay)`);
|
|
741
908
|
if ((states?.states ?? []).includes(value)) throw new SystemError(`${id}: "${value}" is an interaction state; states are not extensible`);
|
|
742
909
|
if (declared.from === "states") {
|
|
743
910
|
if (component[value]) throw new SystemError(`${id}: "${componentPath.join(".")}.${value}" already exists`);
|
|
744
911
|
const copy = clone2(component[decl.from]);
|
|
745
|
-
const
|
|
912
|
+
const own2 = `{${[...componentPath, decl.from].join(".")}.`;
|
|
746
913
|
for (const { token } of tokensUnder(copy)) {
|
|
747
|
-
if (typeof token.$value === "string" && token.$value.startsWith(
|
|
914
|
+
if (typeof token.$value === "string" && token.$value.startsWith(own2)) token.$value = `{${[...componentPath, value].join(".")}.${token.$value.slice(own2.length)}`;
|
|
748
915
|
stamp(token, decl);
|
|
749
916
|
}
|
|
750
917
|
component[value] = copy;
|
|
@@ -755,6 +922,7 @@ function addAxisValue(docs, id, decl) {
|
|
|
755
922
|
if (!group || !isToken(group[decl.from])) throw new SystemError(`${id}: axis member "${member}" has no "${decl.from}"`);
|
|
756
923
|
const copy = clone2(group[decl.from]);
|
|
757
924
|
const factor = typeof decl.scale === "object" ? decl.scale[member] : decl.scale;
|
|
925
|
+
repointPad(copy, componentPath, declared.members, decl.from, value);
|
|
758
926
|
scaleNode(copy, factor, `${componentPath.join(".")}.${member}.${value}`, copy.$type ?? group.$type);
|
|
759
927
|
stamp(copy, decl);
|
|
760
928
|
group[value] = copy;
|
|
@@ -765,7 +933,16 @@ function addAxisValue(docs, id, decl) {
|
|
|
765
933
|
declared.values = [...declared.values, value];
|
|
766
934
|
}
|
|
767
935
|
(declared.extensions ??= []).push({ value, declaredBy: decl.declaredBy });
|
|
768
|
-
|
|
936
|
+
}
|
|
937
|
+
function addComponent(docs, id, decl, CORE_NS) {
|
|
938
|
+
const held2 = heldDocumentPath(decl.declaredBy, decl.component);
|
|
939
|
+
const name = componentDocumentPath(decl.component);
|
|
940
|
+
if (docs[name]) throw new SystemError(`${id}: the core vocabulary already has ${name}; a component lives in one place \u2014 the core, or the one layer that declares it`);
|
|
941
|
+
const doc = docs[held2];
|
|
942
|
+
if (!doc) throw new SystemError(`${id}: the component's document (tokens/${held2}) is not among the sources \u2014 pass the documents the layers hold along with the core's`);
|
|
943
|
+
const own2 = (node) => Object.keys(node ?? {}).filter((key) => !key.startsWith("$"));
|
|
944
|
+
if (own2(doc).join() !== CORE_NS || own2(doc[CORE_NS]).join() !== "comp" || own2(doc[CORE_NS].comp).join() !== decl.component) throw new SystemError(`${id}: tokens/${held2} holds the group "${CORE_NS}.comp.${decl.component}" and nothing else`);
|
|
945
|
+
docs[name] = doc;
|
|
769
946
|
}
|
|
770
947
|
function addGroup(docs, id, decl) {
|
|
771
948
|
const segments2 = id.split(".");
|
|
@@ -774,7 +951,7 @@ function addGroup(docs, id, decl) {
|
|
|
774
951
|
const series = home && groupAt(home, segments2.slice(0, -1));
|
|
775
952
|
const siblings = series ? Object.keys(series).filter((key) => !key.startsWith("$") && !isToken(series[key])) : [];
|
|
776
953
|
if (!series || !siblings.length) throw new SystemError(`${id}: "${segments2.slice(0, -1).join(".")}" is not a series whose steps are groups of tokens (such as ${segments2[0]}.sys.motion.spring.standard). A single token is declared with "$type", not "from".`);
|
|
777
|
-
if (series[name])
|
|
954
|
+
if (series[name]) throw new SystemError(`${id}: "${name}" is a core step of ${segments2.slice(0, -1).join(".")}; a layer declares only what the core lacks: delete this declaration (its values under "tokens" stay)`);
|
|
778
955
|
if (!siblings.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing step of ${segments2.slice(0, -1).join(".")} (${siblings.join(", ")}), not "${decl.from}"`);
|
|
779
956
|
if (decl.scale !== void 0) throw new SystemError(`${id}: "scale" does not apply to a cloned step; change its fields under "tokens"`);
|
|
780
957
|
if (Object.entries(series[decl.from]).some(([key, child]) => !key.startsWith("$") && !isToken(child))) throw new SystemError(`${id}: "${decl.from}" is not a step but a group of steps. A cloned step is one named set of tokens, e.g. ${segments2.slice(0, -1).join(".")}.${decl.from}.<name>.`);
|
|
@@ -782,17 +959,14 @@ function addGroup(docs, id, decl) {
|
|
|
782
959
|
for (const { token } of tokensUnder(copy)) stamp(token, decl);
|
|
783
960
|
if (decl.description) copy.$description = decl.description;
|
|
784
961
|
series[name] = copy;
|
|
785
|
-
return null;
|
|
786
962
|
}
|
|
787
963
|
function addToken(docs, id, decl, core, system) {
|
|
788
964
|
const CORE_NS = system.namespace ?? "tanrei";
|
|
789
965
|
const segments2 = id.split(".");
|
|
790
966
|
if (core.has(id)) {
|
|
791
967
|
const existing = core.get(id);
|
|
792
|
-
if (existing.type !== decl.type) throw new SystemError(`${id}: core
|
|
793
|
-
|
|
794
|
-
if (!system.tokens[id] && ($value2 !== void 0 || derive2)) system.tokens[id] = { ...$value2 !== void 0 ? { $value: $value2, reason: reason2 ?? decl.rationale } : {}, ...derive2 ? { derive: derive2 } : {}, layer: decl.declaredBy };
|
|
795
|
-
return `${id}: now a core token; this declaration can be deleted (its value still applies).`;
|
|
968
|
+
if (existing.type !== decl.type) throw new SystemError(`${id}: the core has this id as "${existing.type}", not "${decl.type}". Rename the extension.`);
|
|
969
|
+
throw new SystemError(`${id}: a core token; a layer declares only what the core lacks: delete this declaration, and write its value under "tokens"`);
|
|
796
970
|
}
|
|
797
971
|
if (!decl.type) throw new SystemError(`${id}: a declared token needs "$type"`);
|
|
798
972
|
const namespace = segments2[0];
|
|
@@ -818,25 +992,25 @@ function addToken(docs, id, decl, core, system) {
|
|
|
818
992
|
else if ($value !== void 0 && !isRef3($value)) token.$extensions = { [DERIVE]: { fixed: reason ?? decl.rationale } };
|
|
819
993
|
stamp(token, decl);
|
|
820
994
|
node[segments2.at(-1)] = token;
|
|
821
|
-
return null;
|
|
822
995
|
}
|
|
823
996
|
function materializeVocabulary(docs, system) {
|
|
824
997
|
const vocabulary = system.vocabulary ?? {};
|
|
825
998
|
const SYS_COLOR4 = `${system.namespace ?? "tanrei"}.sys.color.`;
|
|
826
|
-
const
|
|
827
|
-
if (!Object.
|
|
999
|
+
for (const [id, decl] of Object.entries(vocabulary)) if (decl.kind === "component") addComponent(docs, id, decl, system.namespace ?? "tanrei");
|
|
1000
|
+
if (!Object.values(vocabulary).some((decl) => decl.kind !== "component")) return;
|
|
828
1001
|
const core = /* @__PURE__ */ new Map();
|
|
829
1002
|
for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) core.set(entry.id, entry);
|
|
830
1003
|
const ordered = Object.entries(vocabulary).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
|
|
831
1004
|
for (const [id, decl] of ordered) {
|
|
1005
|
+
if (decl.kind === "component") continue;
|
|
832
1006
|
if (decl.kind === "token" && id.startsWith(SYS_COLOR4)) continue;
|
|
833
|
-
|
|
834
|
-
if (
|
|
1007
|
+
if (decl.kind === "axis-value") addAxisValue(docs, id, decl);
|
|
1008
|
+
else if (decl.kind === "group") addGroup(docs, id, decl);
|
|
1009
|
+
else addToken(docs, id, decl, core, system);
|
|
835
1010
|
}
|
|
836
|
-
return notices;
|
|
837
1011
|
}
|
|
838
1012
|
function listExtensions(system) {
|
|
839
|
-
return Object.entries(system.vocabulary ?? {}).map(([id, d]) => ({ id, kind: d.kind, ...d.type ? { $type: d.type } : {}, ...d.from ? { from: d.from } : {}, declaredBy: d.declaredBy, rationale: d.rationale }));
|
|
1013
|
+
return Object.entries(system.vocabulary ?? {}).map(([id, d]) => ({ id, kind: d.kind, ...d.type ? { $type: d.type } : {}, ...d.from ? { from: d.from } : {}, ...d.document ? { document: d.document } : {}, declaredBy: d.declaredBy, ...d.includedBy ? { includedBy: d.includedBy } : {}, rationale: d.rationale }));
|
|
840
1014
|
}
|
|
841
1015
|
|
|
842
1016
|
// ../token-engine/src/system.js
|
|
@@ -844,29 +1018,37 @@ var DEFAULT_NAMESPACE2 = "tanrei";
|
|
|
844
1018
|
var isRef4 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
845
1019
|
var refId3 = (v) => v.slice(1, -1);
|
|
846
1020
|
var clone3 = (v) => JSON.parse(JSON.stringify(v));
|
|
847
|
-
function mergeLayers(layers, { namespace = DEFAULT_NAMESPACE2 } = {}) {
|
|
1021
|
+
function mergeLayers(layers, { namespace = DEFAULT_NAMESPACE2, lend } = {}) {
|
|
848
1022
|
const SYS_COLOR4 = `${namespace}.sys.color.`;
|
|
849
|
-
const merged = { id: layers.at(-1).id, namespace, name: layers.at(-1).name, specVersion: layers[0].specVersion, palettes: {}, tokens: {}, rules: [], chain: layers.map((l) => l.id), vocabulary: collectVocabulary(layers, { namespace })
|
|
1023
|
+
const merged = { id: layers.at(-1).id, namespace, name: layers.at(-1).name, specVersion: layers[0].specVersion, palettes: {}, paletteLayers: {}, tokens: {}, rules: [], chain: layers.map((l) => l.id), vocabulary: collectVocabulary(layers, { namespace, lend }) };
|
|
850
1024
|
for (const layer of layers) {
|
|
1025
|
+
for (const decl of Object.values(merged.vocabulary)) {
|
|
1026
|
+
if (decl.kind === "component" && (decl.includedBy ?? decl.declaredBy) === layer.id) merged.rules.push(...clone3(decl.rules));
|
|
1027
|
+
}
|
|
851
1028
|
for (const [id, decl] of Object.entries(merged.vocabulary)) {
|
|
852
1029
|
if (decl.declaredBy === layer.id && decl.kind === "token" && id.startsWith(SYS_COLOR4)) merged.tokens[id] = { ...clone3(decl.definition), layer: layer.id };
|
|
853
1030
|
}
|
|
854
1031
|
if (layer.specVersion) merged.specVersion = layer.specVersion;
|
|
855
1032
|
for (const [name, declaration] of Object.entries(layer.palettes ?? {})) {
|
|
856
|
-
if (declaration === null)
|
|
857
|
-
|
|
1033
|
+
if (declaration === null) {
|
|
1034
|
+
delete merged.palettes[name];
|
|
1035
|
+
delete merged.paletteLayers[name];
|
|
1036
|
+
} else {
|
|
1037
|
+
merged.paletteLayers[name] ??= layer.id;
|
|
1038
|
+
merged.palettes[name] = clone3(declaration);
|
|
1039
|
+
}
|
|
858
1040
|
}
|
|
859
1041
|
merged.rules.push(...clone3(layer.rules ?? []).map((rule) => ({ ...rule, layer: void 0 })));
|
|
860
1042
|
for (const [id, op] of Object.entries(layer.tokens ?? {})) {
|
|
861
1043
|
const previous = merged.tokens[id];
|
|
862
1044
|
const replaces = "$value" in op || "derive" in op;
|
|
863
1045
|
const inherited = replaces ? 1 : previous?.scale ?? 1;
|
|
864
|
-
const
|
|
1046
|
+
const own2 = op.scale ?? 1;
|
|
865
1047
|
let scale;
|
|
866
|
-
if (typeof inherited === "number" && typeof
|
|
1048
|
+
if (typeof inherited === "number" && typeof own2 === "number") scale = inherited * own2;
|
|
867
1049
|
else {
|
|
868
1050
|
const fields = (v) => typeof v === "number" ? { fontSize: v } : v;
|
|
869
|
-
const [x, y] = [fields(inherited), fields(
|
|
1051
|
+
const [x, y] = [fields(inherited), fields(own2)];
|
|
870
1052
|
scale = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(x), ...Object.keys(y)])].map((field) => [field, (x[field] ?? 1) * (y[field] ?? 1)]));
|
|
871
1053
|
}
|
|
872
1054
|
merged.tokens[id] = { ...replaces ? {} : previous, ...clone3(op), ...scale !== 1 ? { scale } : {}, layer: layer.id };
|
|
@@ -878,7 +1060,8 @@ function mergeLayers(layers, { namespace = DEFAULT_NAMESPACE2 } = {}) {
|
|
|
878
1060
|
function scaleRule(rule, factor, id) {
|
|
879
1061
|
if (!rule || "fixed" in rule) throw new SystemError(`${id}: cannot scale a fixed value \u2014 set "$value" instead`);
|
|
880
1062
|
if (rule.fn === "mul") return { ...rule, by: rule.by * factor };
|
|
881
|
-
|
|
1063
|
+
if (rule.fn === "pad") return { ...rule, by: (rule.by ?? 1) * factor };
|
|
1064
|
+
throw new SystemError(`${id}: "scale" is supported on "mul" and "pad" rules and aliases, not on "${rule.fn}"`);
|
|
882
1065
|
}
|
|
883
1066
|
function generatedFrom(id, op, type, { namespace, stateIds }) {
|
|
884
1067
|
if (id.startsWith(`${namespace}.sys.color.`)) return "roles";
|
|
@@ -887,18 +1070,19 @@ function generatedFrom(id, op, type, { namespace, stateIds }) {
|
|
|
887
1070
|
return null;
|
|
888
1071
|
}
|
|
889
1072
|
var stateIdsOf = (documents) => new Set(expandStateVocabulary(Object.entries(documents).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc)).map((v) => v.id));
|
|
890
|
-
function resolveNumericTokens(
|
|
1073
|
+
function resolveNumericTokens(sources2, system) {
|
|
891
1074
|
const NS3 = system.namespace ?? DEFAULT_NAMESPACE2;
|
|
892
1075
|
const SYS_COLOR4 = `${NS3}.sys.color.`;
|
|
893
1076
|
const isColorRef = (id) => id.startsWith(SYS_COLOR4) || id.startsWith(`${NS3}.ref.palette.`) || id.startsWith(`${NS3}.ref.alpha.`);
|
|
894
|
-
const docs = Object.fromEntries(Object.entries(
|
|
1077
|
+
const docs = Object.fromEntries(Object.entries(sources2).map(([name, doc]) => [name, clone3(doc)]));
|
|
895
1078
|
const work = { ...system, tokens: clone3(system.tokens) };
|
|
896
|
-
|
|
897
|
-
const
|
|
898
|
-
|
|
1079
|
+
materializeVocabulary(docs, work);
|
|
1080
|
+
for (const name of Object.keys(docs)) if (isHeldDocument(name)) delete docs[name];
|
|
1081
|
+
const index2 = /* @__PURE__ */ new Map();
|
|
1082
|
+
for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) index2.set(entry.id, entry);
|
|
899
1083
|
const stateIds = stateIdsOf(docs);
|
|
900
1084
|
for (const [id, op] of Object.entries(work.tokens)) {
|
|
901
|
-
const entry =
|
|
1085
|
+
const entry = index2.get(id);
|
|
902
1086
|
const generated = generatedFrom(id, op, entry?.type, { namespace: NS3, stateIds });
|
|
903
1087
|
if (generated === "roles" || generated === "states") continue;
|
|
904
1088
|
if (!entry) throw new SystemError(`${id}: unknown token (layer "${op.layer}"). To add it, declare it under "vocabulary" with a rationale.`);
|
|
@@ -910,14 +1094,14 @@ function resolveNumericTokens(sources, system) {
|
|
|
910
1094
|
if (names) {
|
|
911
1095
|
if ("scale" in op || "derive" in op) throw new SystemError(`${id}: a choice of kind is neither scaled nor derived. Choose one of its names: { "$value": "${names[1] ?? names[0]}", "reason": "\u2026" } (${names.join(" | ")}).`);
|
|
912
1096
|
if ("$value" in op && !isRef4(op.$value)) {
|
|
913
|
-
const
|
|
914
|
-
if (!Number.isInteger(
|
|
915
|
-
op.$value =
|
|
1097
|
+
const index3 = typeof op.$value === "string" ? names.indexOf(op.$value) : op.$value;
|
|
1098
|
+
if (!Number.isInteger(index3) || index3 < 0 || index3 >= names.length) throw new SystemError(`${id}: ${JSON.stringify(op.$value)} is not one of its choices (layer "${op.layer}"). Allowed: ${names.map((name, i) => `"${name}" (${i})`).join(", ")}. The list is part of the vocabulary; a layer chooses among the names, it does not add one.`);
|
|
1099
|
+
op.$value = index3;
|
|
916
1100
|
}
|
|
917
1101
|
}
|
|
918
1102
|
if ("$value" in op) {
|
|
919
1103
|
if (isRef4(op.$value)) {
|
|
920
|
-
if (!
|
|
1104
|
+
if (!index2.has(refId3(op.$value)) && !isColorRef(refId3(op.$value))) throw new SystemError(`${id}: alias target ${op.$value} does not exist`);
|
|
921
1105
|
token.$value = op.$value;
|
|
922
1106
|
delete ext[DERIVE];
|
|
923
1107
|
} else {
|
|
@@ -955,11 +1139,11 @@ function resolveNumericTokens(sources, system) {
|
|
|
955
1139
|
}
|
|
956
1140
|
}
|
|
957
1141
|
}
|
|
958
|
-
for (const [id, { token }] of
|
|
1142
|
+
for (const [id, { token }] of index2) if (token.$value === null && !token.$extensions?.[DERIVE]) throw new SystemError(`${id}: declared under "vocabulary" but never given a value \u2014 add "$value" or "derive" to the declaration, or an entry under "tokens"`);
|
|
959
1143
|
const state = /* @__PURE__ */ new Map();
|
|
960
1144
|
const resolve = (id, trail = []) => {
|
|
961
1145
|
if (isColorRef(id)) return { color: id };
|
|
962
|
-
const entry =
|
|
1146
|
+
const entry = index2.get(id);
|
|
963
1147
|
if (!entry) throw new SystemError(`${trail.at(-1) ?? "?"}: references unknown token {${id}}`);
|
|
964
1148
|
if (trail.length && trail.at(-1).startsWith(`${NS3}.`) && !id.startsWith(`${NS3}.`)) throw new SystemError(`${trail.at(-1)}: a ${NS3}.* token cannot reference {${id}}, a token in a layer's own namespace`);
|
|
965
1149
|
if (state.get(id) === "visiting") throw new SystemError(`cycle: ${[...trail, id].join(" \u2192 ")}`);
|
|
@@ -975,32 +1159,35 @@ function resolveNumericTokens(sources, system) {
|
|
|
975
1159
|
if (rule.fontSize) token.$value.fontSize = evaluateNumeric(rule.fontSize, lookup, { type: "dimension" });
|
|
976
1160
|
if (rule.letterSpacing) token.$value.letterSpacing = evaluateNumeric(rule.letterSpacing, lookup, { type: "dimension", fontSize: token.$value.fontSize.value });
|
|
977
1161
|
} else {
|
|
978
|
-
const result = evaluateNumeric(rule, lookup, { type });
|
|
1162
|
+
const result = evaluateNumeric(rule, lookup, { type, unscaled });
|
|
979
1163
|
token.$value = type === "number" ? result.value : result;
|
|
980
1164
|
}
|
|
981
1165
|
}
|
|
982
1166
|
state.set(id, "done");
|
|
983
1167
|
}
|
|
984
1168
|
const v = isRef4(token.$value) ? resolve(refId3(token.$value), [...trail, id]) : token.$value;
|
|
985
|
-
return typeof v === "number" ? { value: v } : v;
|
|
1169
|
+
return typeof v === "number" ? { value: v, names: token.$extensions?.[ENUM]?.values } : v;
|
|
986
1170
|
};
|
|
987
|
-
|
|
988
|
-
|
|
1171
|
+
const unscaled = unscaledLookup((id) => {
|
|
1172
|
+
const entry = index2.get(id);
|
|
1173
|
+
if (!entry) return { value: resolve(id) };
|
|
1174
|
+
const rule = entry.token.$extensions?.[DERIVE];
|
|
1175
|
+
if (isRef4(entry.token.$value)) return { alias: refId3(entry.token.$value) };
|
|
1176
|
+
return rule && !("fixed" in rule) && entry.type !== "typography" ? { rule, type: entry.type } : { value: resolve(id), reference: entry.token.$extensions?.[REFERENCE] };
|
|
1177
|
+
});
|
|
1178
|
+
for (const id of index2.keys()) resolve(id);
|
|
1179
|
+
for (const [id, { token }] of index2) for (const dep of ruleDependencies(token.$extensions?.[DERIVE])) if (!index2.has(dep) && !isColorRef(dep)) throw new SystemError(`${id}: rule references unknown token {${dep}}`);
|
|
989
1180
|
return docs;
|
|
990
1181
|
}
|
|
991
1182
|
|
|
992
|
-
// ../tokens-build/src/bundle.js
|
|
993
|
-
import fs2 from "node:fs";
|
|
994
|
-
import path3 from "node:path";
|
|
995
|
-
import Ajv2020 from "ajv/dist/2020.js";
|
|
996
|
-
|
|
997
1183
|
// ../../tanrei.config.json
|
|
998
1184
|
var tanrei_config_default = {
|
|
999
1185
|
$comment: "Single source for naming. Every generated artifact derives names from here; never hardcode them elsewhere. Checked by `pnpm validate`.",
|
|
1000
1186
|
name: "Tanrei",
|
|
1001
1187
|
namespace: "tanrei",
|
|
1002
|
-
version: "0.1.0-next.
|
|
1188
|
+
version: "0.1.0-next.1",
|
|
1003
1189
|
license: "Apache-2.0",
|
|
1190
|
+
site: "https://tanrei.chnotchy.com",
|
|
1004
1191
|
repository: {
|
|
1005
1192
|
public: "chnotchy/tanrei"
|
|
1006
1193
|
},
|
|
@@ -1035,6 +1222,71 @@ function rgba(color) {
|
|
|
1035
1222
|
return { r, g, b, a: color.alpha ?? 1 };
|
|
1036
1223
|
}
|
|
1037
1224
|
|
|
1225
|
+
// ../tokens-build/src/layers.js
|
|
1226
|
+
var ROOT_SYSTEM = "core";
|
|
1227
|
+
var DEFAULT_SYSTEM = CONFIG.namespace;
|
|
1228
|
+
function layerChain(id, read) {
|
|
1229
|
+
const chain = [];
|
|
1230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1231
|
+
for (let current = id; current; current = chain[0].extends) {
|
|
1232
|
+
if (chain.length) assertSystemId(current, `${chain[0].id}.system.json "extends"`);
|
|
1233
|
+
if (seen.has(current)) throw new Error(`"extends" cycle: ${[...seen, current].join(" \u2192 ")}`);
|
|
1234
|
+
seen.add(current);
|
|
1235
|
+
chain.unshift(read(current));
|
|
1236
|
+
}
|
|
1237
|
+
if (chain[0].id !== ROOT_SYSTEM) throw new Error(`system "${id}" does not extend "${ROOT_SYSTEM}"`);
|
|
1238
|
+
return chain;
|
|
1239
|
+
}
|
|
1240
|
+
var includedName = (include) => typeof include === "string" ? include : include.name;
|
|
1241
|
+
function heldComponents(ids, read) {
|
|
1242
|
+
const held2 = /* @__PURE__ */ new Map();
|
|
1243
|
+
const prefix = `${CONFIG.namespace}.comp.`;
|
|
1244
|
+
for (const id of ids) {
|
|
1245
|
+
for (const [key, entry] of Object.entries(read(id).vocabulary ?? {})) {
|
|
1246
|
+
if (key.startsWith(prefix) && entry && typeof entry === "object" && "document" in entry) held2.set(key.slice(prefix.length), id);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return held2;
|
|
1250
|
+
}
|
|
1251
|
+
function outsideComponents(chain, held2) {
|
|
1252
|
+
const ids = new Set(chain.map((layer) => layer.id));
|
|
1253
|
+
const included = new Set(chain.flatMap((layer) => (layer.components?.include ?? []).filter((include) => typeof include === "object").map(includedName)));
|
|
1254
|
+
return Object.fromEntries([...held2].filter(([name, layer]) => !ids.has(layer) && !included.has(name)));
|
|
1255
|
+
}
|
|
1256
|
+
function componentChoices(chain) {
|
|
1257
|
+
const components = /* @__PURE__ */ new Map();
|
|
1258
|
+
const variants = /* @__PURE__ */ new Map();
|
|
1259
|
+
const variantsOf2 = (name) => variants.get(name) ?? variants.set(name, /* @__PURE__ */ new Map()).get(name);
|
|
1260
|
+
for (const layer of chain) {
|
|
1261
|
+
const own2 = layer.components ?? {};
|
|
1262
|
+
for (const [name, { reason, insteadUse }] of Object.entries(own2.omit ?? {})) {
|
|
1263
|
+
components.delete(name);
|
|
1264
|
+
components.set(name, { layer: layer.id, reason, ...insteadUse ? { insteadUse: [...insteadUse] } : {} });
|
|
1265
|
+
}
|
|
1266
|
+
for (const include of own2.include ?? []) components.delete(includedName(include));
|
|
1267
|
+
for (const [name, { omit = [], include = [] }] of Object.entries(own2.variants ?? {})) {
|
|
1268
|
+
const values = variantsOf2(name);
|
|
1269
|
+
for (const value of omit) values.delete(value), values.set(value, { layer: layer.id });
|
|
1270
|
+
for (const value of include) values.delete(value);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
for (const [name, values] of variants) if (!values.size) variants.delete(name);
|
|
1274
|
+
return { components, variants };
|
|
1275
|
+
}
|
|
1276
|
+
function omittedOf(chain, held2, standIns = /* @__PURE__ */ new Map()) {
|
|
1277
|
+
const { components: left } = componentChoices(chain);
|
|
1278
|
+
const outside = outsideComponents(chain, held2);
|
|
1279
|
+
const ships = (name) => !left.has(name) && !outside[name];
|
|
1280
|
+
return [
|
|
1281
|
+
...[...left].map(([name, { layer, reason, insteadUse }]) => ({ name, omittedBy: layer, ...reason ? { reason } : {}, ...insteadUse ? { insteadUse } : {} })),
|
|
1282
|
+
...Object.entries(outside).map(([name, layer]) => {
|
|
1283
|
+
const instead = standIns.get(name);
|
|
1284
|
+
const insteadUse = instead?.insteadUse.filter(ships) ?? [];
|
|
1285
|
+
return { name, providedBy: layer, ...instead ? { reason: instead.reason } : {}, ...insteadUse.length ? { insteadUse } : {} };
|
|
1286
|
+
})
|
|
1287
|
+
].sort((a, b) => a.name.localeCompare(b.name));
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1038
1290
|
// ../tokens-build/src/scheme.js
|
|
1039
1291
|
import crypto from "node:crypto";
|
|
1040
1292
|
import fs from "node:fs";
|
|
@@ -1063,7 +1315,7 @@ function colorVocabulary(repoRoot) {
|
|
|
1063
1315
|
}
|
|
1064
1316
|
function generateSchemeFiles(system, repoRoot, documents) {
|
|
1065
1317
|
const merged = system.chain ? system : mergeLayers([system], { namespace: NAMESPACE });
|
|
1066
|
-
const docs = documents ?? resolveNumericTokens(sourceFiles(repoRoot), merged);
|
|
1318
|
+
const docs = documents ?? resolveNumericTokens({ ...sourceFiles(repoRoot), ...heldDocuments(repoRoot, merged) }, merged);
|
|
1067
1319
|
return engine.generateColorFiles(merged, { sourcePath: systemPath(merged.id), vocabulary: colorVocabulary(repoRoot), documents: docs });
|
|
1068
1320
|
}
|
|
1069
1321
|
function sourcePaths(repoRoot) {
|
|
@@ -1077,6 +1329,13 @@ function sourceFiles(repoRoot) {
|
|
|
1077
1329
|
const { dir, refs } = sourcePaths(repoRoot);
|
|
1078
1330
|
return Object.fromEntries(refs.map((ref) => [ref, JSON.parse(fs.readFileSync(path2.join(dir, ref), "utf8"))]));
|
|
1079
1331
|
}
|
|
1332
|
+
function heldDocuments(repoRoot, system) {
|
|
1333
|
+
const relative = system ? Object.values(system.vocabulary ?? {}).filter((decl) => decl.kind === "component").map((decl) => heldDocumentPath(decl.declaredBy, decl.component)) : fs.readdirSync(path2.join(repoRoot, "tokens/systems"), { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => {
|
|
1334
|
+
const dir = path2.join(repoRoot, "tokens/systems", entry.name, "comp");
|
|
1335
|
+
return fs.existsSync(dir) ? fs.readdirSync(dir).filter((file) => file.endsWith(".tokens.json")).map((file) => `systems/${entry.name}/comp/${file}`) : [];
|
|
1336
|
+
});
|
|
1337
|
+
return Object.fromEntries(relative.map((name) => [name, JSON.parse(fs.readFileSync(path2.join(repoRoot, "tokens", name), "utf8"))]));
|
|
1338
|
+
}
|
|
1080
1339
|
function vocabularyDigest(repoRoot) {
|
|
1081
1340
|
const { dir, resolverFile, refs } = sourcePaths(repoRoot);
|
|
1082
1341
|
const files = [resolverFile, ...refs, "sys/color.vocabulary.json"];
|
|
@@ -1092,44 +1351,34 @@ function vocabularyDigest(repoRoot) {
|
|
|
1092
1351
|
}
|
|
1093
1352
|
|
|
1094
1353
|
// ../tokens-build/src/bundle.js
|
|
1095
|
-
var ROOT_SYSTEM = CONFIG.namespace;
|
|
1096
1354
|
var RECIPE = "dev.tanrei.system";
|
|
1097
1355
|
function listSystems(repoRoot) {
|
|
1098
1356
|
return fs2.readdirSync(path3.join(repoRoot, "tokens/systems")).filter((f) => f.endsWith(".system.json")).map((f) => f.replace(".system.json", "")).sort();
|
|
1099
1357
|
}
|
|
1358
|
+
var shippedSystems = (repoRoot) => listSystems(repoRoot).filter((id) => id !== ROOT_SYSTEM);
|
|
1100
1359
|
var validateLayer;
|
|
1101
1360
|
function validateLayerFile(repoRoot, layer, fileId) {
|
|
1102
1361
|
if (!validateLayer) {
|
|
1103
|
-
const
|
|
1104
|
-
validateLayer = new Ajv2020({ allErrors: true, strict: false }).compile(
|
|
1362
|
+
const schema2 = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens/schema/system.schema.json"), "utf8"));
|
|
1363
|
+
validateLayer = new Ajv2020({ allErrors: true, strict: false }).compile(schema2);
|
|
1105
1364
|
}
|
|
1106
1365
|
const problems = validateLayer(layer) ? [] : validateLayer.errors.map((e) => `${fileId}.system.json ${e.instancePath || "/"} ${e.message}`);
|
|
1107
1366
|
if (layer.id !== fileId) problems.push(`${fileId}.system.json: "id" must equal the file name`);
|
|
1108
1367
|
if (fileId === ROOT_SYSTEM ? "extends" in layer : !layer.extends) problems.push(`${fileId}.system.json: only the root layer "${ROOT_SYSTEM}" omits "extends"`);
|
|
1109
1368
|
return problems;
|
|
1110
1369
|
}
|
|
1111
|
-
function
|
|
1112
|
-
const
|
|
1113
|
-
const
|
|
1114
|
-
for (let current = id; current; current = chain[0].extends) {
|
|
1115
|
-
if (chain.length) assertSystemId(current, `${chain[0].id}.system.json "extends"`);
|
|
1116
|
-
if (seen.has(current)) throw new Error(`"extends" cycle: ${[...seen, current].join(" \u2192 ")}`);
|
|
1117
|
-
seen.add(current);
|
|
1118
|
-
chain.unshift(read(current));
|
|
1119
|
-
}
|
|
1120
|
-
if (chain[0].id !== ROOT_SYSTEM) throw new Error(`system "${id}" does not extend "${ROOT_SYSTEM}"`);
|
|
1121
|
-
return chain;
|
|
1122
|
-
}
|
|
1123
|
-
function buildBundle(repoRoot, chain) {
|
|
1124
|
-
const system = mergeLayers(chain, { namespace: CONFIG.namespace });
|
|
1125
|
-
const files = resolveNumericTokens(sourceFiles(repoRoot), system);
|
|
1370
|
+
function buildBundle(repoRoot, chain, { lend = (id) => loadSystem(repoRoot, id) } = {}) {
|
|
1371
|
+
const system = mergeLayers(chain, { namespace: CONFIG.namespace, lend });
|
|
1372
|
+
const files = resolveNumericTokens({ ...sourceFiles(repoRoot), ...heldDocuments(repoRoot, system) }, system);
|
|
1126
1373
|
for (const [name, doc] of Object.entries(generateSchemeFiles(system, repoRoot, files))) files[`generated/${name}`] = doc;
|
|
1127
|
-
const resolver = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens", `${
|
|
1374
|
+
const resolver = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens", `${DEFAULT_SYSTEM}.resolver.json`), "utf8"));
|
|
1375
|
+
const held2 = Object.values(system.vocabulary).filter((decl) => decl.kind === "component").map((decl) => ({ $ref: componentDocumentPath(decl.component) }));
|
|
1376
|
+
resolver.sets.comp.sources.push(...held2);
|
|
1128
1377
|
resolver.name = system.name ?? system.id;
|
|
1129
1378
|
resolver.description = `Design system "${system.id}" (${system.chain.join(" \u2190 ")}), fully valued. Generated by Tanrei; do not edit.`;
|
|
1130
|
-
const
|
|
1131
|
-
if (
|
|
1132
|
-
if (
|
|
1379
|
+
const own2 = Object.keys(files).filter((name) => name.startsWith("ext/")).sort();
|
|
1380
|
+
if (own2.length) resolver.resolutionOrder.push({ $ref: "#/sets/ext" });
|
|
1381
|
+
if (own2.length) resolver.sets.ext = { description: "Tokens that layers of this system declare in their own namespace.", sources: own2.map((name) => ({ $ref: name })) };
|
|
1133
1382
|
files[`${system.id}.resolver.json`] = resolver;
|
|
1134
1383
|
const dial = files["dial/dial.tokens.json"];
|
|
1135
1384
|
const extensions = listExtensions(system);
|
|
@@ -1137,151 +1386,1326 @@ function buildBundle(repoRoot, chain) {
|
|
|
1137
1386
|
return { system, files };
|
|
1138
1387
|
}
|
|
1139
1388
|
|
|
1140
|
-
// ../tokens-build/src/
|
|
1389
|
+
// ../tokens-build/src/components-manifest.js
|
|
1141
1390
|
import fs3 from "node:fs";
|
|
1142
1391
|
import path4 from "node:path";
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
var
|
|
1147
|
-
}
|
|
1148
|
-
var
|
|
1149
|
-
var
|
|
1150
|
-
var
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1392
|
+
var CATALOG_FILE = "packages/tokens-build/generated/component-catalog.json";
|
|
1393
|
+
var manifestFile = (id) => `tokens/generated/${id}/components.json`;
|
|
1394
|
+
var WEB = `${CONFIG.packages.npmScope}/web`;
|
|
1395
|
+
var REACT = `${CONFIG.packages.npmScope}/react`;
|
|
1396
|
+
var REACT_ADVANCED = `${REACT}/advanced`;
|
|
1397
|
+
var REACT_ALL = `${REACT}/all`;
|
|
1398
|
+
var reactEntryOf = (id) => id === DEFAULT_SYSTEM ? REACT : `${REACT}/${id}`;
|
|
1399
|
+
var webEntryOf = (system) => system === DEFAULT_SYSTEM ? WEB : `${WEB}/${system}`;
|
|
1400
|
+
function importOf(component, { registeredBy, system, shipped }) {
|
|
1401
|
+
return {
|
|
1402
|
+
web: registeredBy ? webEntryOf(registeredBy) : component.web?.module,
|
|
1403
|
+
react: component.listing === "advanced" ? REACT_ADVANCED : shipped.has(system) ? reactEntryOf(system) : REACT_ALL
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
function readComponentCatalog(root2) {
|
|
1407
|
+
const file = path4.join(root2, CATALOG_FILE);
|
|
1408
|
+
return fs3.existsSync(file) ? JSON.parse(fs3.readFileSync(file, "utf8")) : null;
|
|
1409
|
+
}
|
|
1410
|
+
function addedValues(chain, axis) {
|
|
1411
|
+
if (!axis) return [];
|
|
1412
|
+
const prefix = `${axis}.`;
|
|
1413
|
+
return chain.flatMap(
|
|
1414
|
+
(layer) => Object.entries(layer.vocabulary ?? {}).filter(([id, entry]) => id.startsWith(prefix) && !id.slice(prefix.length).includes(".") && entry && typeof entry === "object" && "from" in entry && !("document" in entry)).map(([id]) => id.slice(prefix.length))
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
var shipsIn = (chain, catalog, held2) => {
|
|
1418
|
+
const { components: left } = componentChoices(chain);
|
|
1419
|
+
const outside = outsideComponents(chain, held2);
|
|
1420
|
+
return new Set(catalog.components.map((component) => component.name).filter((name) => !left.has(name) && !outside[name]));
|
|
1160
1421
|
};
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1422
|
+
function componentsManifest(chain, catalog, held2, shipped) {
|
|
1423
|
+
if (!shipped) throw new Error("componentsManifest: name the shipped systems, whose entries register their components");
|
|
1424
|
+
const system = chain.at(-1);
|
|
1425
|
+
const { components: left, variants: leftValues } = componentChoices(chain);
|
|
1426
|
+
const outside = outsideComponents(chain, held2);
|
|
1427
|
+
const byName = new Map(catalog.components.map((component) => [component.name, component]));
|
|
1428
|
+
const title = (name) => byName.get(name)?.title ?? name;
|
|
1429
|
+
const ids = new Set(shipped);
|
|
1430
|
+
const entries = chain.map((layer, at) => ids.has(layer.id) ? { id: layer.id, ships: shipsIn(chain.slice(0, at + 1), catalog, held2) } : null).filter(Boolean).reverse();
|
|
1431
|
+
const registeredBy = (name) => entries.find(({ ships }) => ships.has(name))?.id ?? null;
|
|
1432
|
+
const components = [];
|
|
1433
|
+
const omittedVariants = {};
|
|
1434
|
+
for (const component of [...catalog.components].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
1435
|
+
if (left.has(component.name) || outside[component.name]) continue;
|
|
1436
|
+
const entry = { name: component.name, title: component.title, level: component.level, listing: component.listing, layer: component.layer };
|
|
1437
|
+
const imports = importOf(component, { registeredBy: registeredBy(component.name), system: system.id, shipped: ids });
|
|
1438
|
+
if (component.web) entry.web = component.web.tag ? { tag: component.web.tag, import: imports.web, module: component.web.module } : { class: component.web.class, import: component.web.stylesheet };
|
|
1439
|
+
if (component.react) entry.react = { name: component.react.name, import: imports.react };
|
|
1440
|
+
if (component.variant) {
|
|
1441
|
+
const out = /* @__PURE__ */ new Set([...leftValues.get(component.variant.source)?.keys() ?? [], ...leftValues.get(component.name)?.keys() ?? []]);
|
|
1442
|
+
const values = [.../* @__PURE__ */ new Set([...component.variant.values, ...addedValues(chain, component.variant.axis)])];
|
|
1443
|
+
entry.variants = values.filter((value) => !out.has(value));
|
|
1444
|
+
const gone = values.filter((value) => out.has(value));
|
|
1445
|
+
if (gone.length) omittedVariants[component.name] = gone;
|
|
1446
|
+
}
|
|
1447
|
+
components.push(entry);
|
|
1448
|
+
}
|
|
1449
|
+
const standIns = new Map(catalog.components.filter((component) => component.outside).map((component) => [component.name, component.outside]));
|
|
1450
|
+
const omitted = omittedOf(chain, held2, standIns).map(({ name, ...entry }) => ({ name, title: title(name), ...entry }));
|
|
1451
|
+
return {
|
|
1452
|
+
system: system.id,
|
|
1453
|
+
name: system.name ?? system.id,
|
|
1454
|
+
...system.extends ? { extends: system.extends } : {},
|
|
1455
|
+
chain: chain.map((layer) => layer.id),
|
|
1456
|
+
components,
|
|
1457
|
+
omitted,
|
|
1458
|
+
omittedVariants
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// ../tokens-build/src/components-audit.js
|
|
1463
|
+
var PREFIX = `${CONFIG.web.tagPrefix}-`;
|
|
1464
|
+
var WEB2 = `${CONFIG.packages.npmScope}/web`;
|
|
1465
|
+
var REACT2 = `${CONFIG.packages.npmScope}/react`;
|
|
1466
|
+
var TAG = `${PREFIX}[a-z0-9]+(?:-[a-z0-9]+)*`;
|
|
1467
|
+
var pascal = (name) => name.split("-").map((word) => word[0].toUpperCase() + word.slice(1)).join("");
|
|
1468
|
+
function textKind(file) {
|
|
1469
|
+
const ext = /\.([a-z0-9]+)$/i.exec(file ?? "")?.[1]?.toLowerCase();
|
|
1470
|
+
if (["scss", "less"].includes(ext)) return "scss";
|
|
1471
|
+
if (["css", "pcss"].includes(ext)) return "css";
|
|
1472
|
+
if (["html", "htm", "vue", "svelte", "astro"].includes(ext)) return "html";
|
|
1473
|
+
return "script";
|
|
1474
|
+
}
|
|
1475
|
+
var blank = (chars, from, to) => {
|
|
1476
|
+
for (let i = from; i < to; i++) if (chars[i] !== "\n" && chars[i] !== "\r") chars[i] = " ";
|
|
1180
1477
|
};
|
|
1181
|
-
function
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1478
|
+
function blankHtmlComments(chars, text2, from, to) {
|
|
1479
|
+
for (let at = text2.indexOf("<!--", from); at !== -1 && at < to; at = text2.indexOf("<!--", at + 4)) {
|
|
1480
|
+
const end = text2.indexOf("-->", at + 4);
|
|
1481
|
+
const stop = end === -1 || end + 3 > to ? to : end + 3;
|
|
1482
|
+
blank(chars, at, stop);
|
|
1483
|
+
at = stop - 4;
|
|
1484
|
+
}
|
|
1188
1485
|
}
|
|
1189
|
-
var
|
|
1190
|
-
var
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1486
|
+
var BEFORE_REGEX = /* @__PURE__ */ new Set(["", "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", ";", "+", "-", "*", "%", "<", ">", "~", "^"]);
|
|
1487
|
+
var KEYWORDS_BEFORE_REGEX = /* @__PURE__ */ new Set(["return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await"]);
|
|
1488
|
+
function readScript(chars, text2, from = 0, to = text2.length) {
|
|
1489
|
+
const templates = [];
|
|
1490
|
+
const open = [];
|
|
1491
|
+
let depth = 0;
|
|
1492
|
+
let last = "";
|
|
1493
|
+
let i = from;
|
|
1494
|
+
const templateText = (template, at) => {
|
|
1495
|
+
let j = at;
|
|
1496
|
+
while (j < to && text2[j] !== "`" && !(text2[j] === "$" && text2[j + 1] === "{")) j += text2[j] === "\\" ? 2 : 1;
|
|
1497
|
+
blankHtmlComments(chars, text2, at, Math.min(j, to));
|
|
1498
|
+
if (j < to && text2[j] === "$") {
|
|
1499
|
+
open.push({ depth, template });
|
|
1500
|
+
depth++;
|
|
1501
|
+
last = "{";
|
|
1502
|
+
i = j + 2;
|
|
1503
|
+
} else {
|
|
1504
|
+
template.end = Math.min(j, to);
|
|
1505
|
+
last = "`";
|
|
1506
|
+
i = j + 1;
|
|
1507
|
+
}
|
|
1508
|
+
};
|
|
1509
|
+
while (i < to) {
|
|
1510
|
+
const c = text2[i];
|
|
1511
|
+
const next = text2[i + 1];
|
|
1512
|
+
if (c === "/" && next === "/" && text2[i - 1] !== ":" && last !== "<") {
|
|
1513
|
+
const end = text2.indexOf("\n", i);
|
|
1514
|
+
const stop = end === -1 || end > to ? to : end;
|
|
1515
|
+
blank(chars, i, stop);
|
|
1516
|
+
i = stop;
|
|
1517
|
+
} else if (c === "/" && next === "*" && last !== "<") {
|
|
1518
|
+
const end = text2.indexOf("*/", i + 2);
|
|
1519
|
+
const stop = end === -1 || end + 2 > to ? to : end + 2;
|
|
1520
|
+
blank(chars, i, stop);
|
|
1521
|
+
i = stop;
|
|
1522
|
+
} else if (c === '"' || c === "'") {
|
|
1523
|
+
let j = i + 1;
|
|
1524
|
+
while (j < to && text2[j] !== c && text2[j] !== "\n") j += text2[j] === "\\" ? 2 : 1;
|
|
1525
|
+
blankHtmlComments(chars, text2, i + 1, Math.min(j, to));
|
|
1526
|
+
i = j + 1;
|
|
1527
|
+
last = c;
|
|
1528
|
+
} else if (c === "`") {
|
|
1529
|
+
const template = { tag: /([\w$]+)\s*$/.exec(text2.slice(Math.max(from, i - 40), i))?.[1] ?? "", start: i + 1, end: to };
|
|
1530
|
+
templates.push(template);
|
|
1531
|
+
templateText(template, i + 1);
|
|
1532
|
+
} else if (c === "/" && last !== "<" && next !== ">" && (BEFORE_REGEX.has(last) || KEYWORDS_BEFORE_REGEX.has(last))) {
|
|
1533
|
+
let j = i + 1;
|
|
1534
|
+
let inClass = false;
|
|
1535
|
+
while (j < to && text2[j] !== "\n") {
|
|
1536
|
+
if (text2[j] === "\\") j++;
|
|
1537
|
+
else if (text2[j] === "[") inClass = true;
|
|
1538
|
+
else if (text2[j] === "]") inClass = false;
|
|
1539
|
+
else if (text2[j] === "/" && !inClass) break;
|
|
1540
|
+
j++;
|
|
1541
|
+
}
|
|
1542
|
+
i = j + 1;
|
|
1543
|
+
last = "regex";
|
|
1544
|
+
} else if (c === "{") {
|
|
1545
|
+
depth++;
|
|
1546
|
+
last = "{";
|
|
1547
|
+
i++;
|
|
1548
|
+
} else if (c === "}") {
|
|
1549
|
+
depth--;
|
|
1550
|
+
if (open.length && open.at(-1).depth === depth) templateText(open.pop().template, i + 1);
|
|
1551
|
+
else {
|
|
1552
|
+
last = "}";
|
|
1553
|
+
i++;
|
|
1554
|
+
}
|
|
1555
|
+
} else if (/\s/.test(c)) i++;
|
|
1556
|
+
else if (/[\w$]/.test(c)) {
|
|
1557
|
+
let j = i + 1;
|
|
1558
|
+
while (j < to && /[\w$]/.test(text2[j])) j++;
|
|
1559
|
+
last = text2.slice(i, j);
|
|
1560
|
+
i = j;
|
|
1561
|
+
} else {
|
|
1562
|
+
last = c;
|
|
1563
|
+
i++;
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
return templates;
|
|
1196
1567
|
}
|
|
1197
|
-
function
|
|
1198
|
-
let
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1568
|
+
function readCss(chars, text2, from, to, { lineComments = false } = {}) {
|
|
1569
|
+
let i = from;
|
|
1570
|
+
while (i < to) {
|
|
1571
|
+
const c = text2[i];
|
|
1572
|
+
if (c === "/" && text2[i + 1] === "*") {
|
|
1573
|
+
const end = text2.indexOf("*/", i + 2);
|
|
1574
|
+
const stop = end === -1 || end + 2 > to ? to : end + 2;
|
|
1575
|
+
blank(chars, i, stop);
|
|
1576
|
+
i = stop;
|
|
1577
|
+
} else if (lineComments && c === "/" && text2[i + 1] === "/" && text2[i - 1] !== ":" && text2[i - 1] !== "(") {
|
|
1578
|
+
const end = text2.indexOf("\n", i);
|
|
1579
|
+
blank(chars, i, end === -1 || end > to ? to : end);
|
|
1580
|
+
i = end === -1 || end > to ? to : end;
|
|
1581
|
+
} else if (c === '"' || c === "'") {
|
|
1582
|
+
let j = i + 1;
|
|
1583
|
+
while (j < to && text2[j] !== c && text2[j] !== "\n") j += text2[j] === "\\" ? 2 : 1;
|
|
1584
|
+
i = j + 1;
|
|
1585
|
+
} else i++;
|
|
1586
|
+
}
|
|
1202
1587
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1588
|
+
function readText(text2, kind) {
|
|
1589
|
+
const chars = text2.split("");
|
|
1590
|
+
const styles = [];
|
|
1591
|
+
if (kind === "css" || kind === "scss") {
|
|
1592
|
+
readCss(chars, text2, 0, text2.length, { lineComments: kind === "scss" });
|
|
1593
|
+
styles.push([0, text2.length]);
|
|
1594
|
+
} else if (kind === "html") {
|
|
1595
|
+
const blocks = [...text2.matchAll(/<(script|style)\b[^>]*>([\s\S]*?)<\/\1\s*>/gi)].map((match) => {
|
|
1596
|
+
const start = match.index + match[0].indexOf(">") + 1;
|
|
1597
|
+
return { name: match[1].toLowerCase(), start, end: start + match[2].length, outer: [match.index, match.index + match[0].length] };
|
|
1598
|
+
});
|
|
1599
|
+
const frontmatter = /^---\r?\n[\s\S]*?\r?\n---(?=\r?\n|$)/.exec(text2);
|
|
1600
|
+
if (frontmatter) blocks.unshift({ name: "script", start: 3, end: frontmatter[0].length - 3, outer: [0, frontmatter[0].length] });
|
|
1601
|
+
let at = 0;
|
|
1602
|
+
for (const block of blocks) {
|
|
1603
|
+
blankHtmlComments(chars, text2, at, block.outer[0]);
|
|
1604
|
+
at = block.outer[1];
|
|
1605
|
+
if (block.name === "style") {
|
|
1606
|
+
readCss(chars, text2, block.start, block.end);
|
|
1607
|
+
styles.push([block.start, block.end]);
|
|
1608
|
+
} else {
|
|
1609
|
+
for (const template of readScript(chars, text2, block.start, block.end)) {
|
|
1610
|
+
if (template.tag !== "css") continue;
|
|
1611
|
+
readCss(chars, text2, template.start, template.end);
|
|
1612
|
+
styles.push([template.start, template.end]);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
blankHtmlComments(chars, text2, at, text2.length);
|
|
1617
|
+
} else {
|
|
1618
|
+
for (const template of readScript(chars, text2)) {
|
|
1619
|
+
if (template.tag === "css") {
|
|
1620
|
+
readCss(chars, text2, template.start, template.end);
|
|
1621
|
+
styles.push([template.start, template.end]);
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
for (const match of chars.join("").matchAll(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/gi)) {
|
|
1625
|
+
const start = match.index + match[0].indexOf(">") + 1;
|
|
1626
|
+
readCss(chars, text2, start, start + match[1].length);
|
|
1627
|
+
styles.push([start, start + match[1].length]);
|
|
1628
|
+
}
|
|
1211
1629
|
}
|
|
1212
|
-
return
|
|
1630
|
+
return { code: chars.join(""), styles };
|
|
1213
1631
|
}
|
|
1214
|
-
function
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1632
|
+
function selectorTags(code, from, to) {
|
|
1633
|
+
const found = [];
|
|
1634
|
+
let start = from;
|
|
1635
|
+
for (let i = from; i < to; i++) {
|
|
1636
|
+
const c = code[i];
|
|
1637
|
+
if (c === '"' || c === "'") {
|
|
1638
|
+
const end = code.indexOf(c, i + 1);
|
|
1639
|
+
i = end === -1 || end > to ? to : end;
|
|
1640
|
+
} else if (c === ";" || c === "}") start = i + 1;
|
|
1641
|
+
else if (c === "{") {
|
|
1642
|
+
const prelude = code.slice(start, i);
|
|
1643
|
+
if (!/^\s*@/.test(prelude)) {
|
|
1644
|
+
for (const match of prelude.matchAll(new RegExp(`(?<![\\w\\-.#:\\[\\\\@$%'"=])(${TAG})(?![\\w-])`, "g"))) {
|
|
1645
|
+
const before = prelude.slice(0, match.index);
|
|
1646
|
+
if (/::?(?:part|state|lang|dir|nth-[a-z-]+|highlight)\(\s*[^)]*$/.test(before)) continue;
|
|
1647
|
+
found.push({ offset: start + match.index, tag: match[1] });
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
start = i + 1;
|
|
1228
1651
|
}
|
|
1229
|
-
case "gradient":
|
|
1230
|
-
if (!Array.isArray(value)) return value;
|
|
1231
|
-
return normalForm(value, type, () => withFields(value, value.map((stop, i) => [i, isObject(stop) && stop.color ? withFields(stop, [["color", normalColor(stop.color, id)]]) : stop])));
|
|
1232
|
-
case "transition":
|
|
1233
|
-
if (!isObject(value)) return value;
|
|
1234
|
-
return normalForm(value, type, () => withFields(value, [...value.duration ? [] : [["duration", { value: 0, unit: "ms" }]], ...value.delay ? [] : [["delay", { value: 0, unit: "ms" }]], ...value.timingFunction ? [] : [["timingFunction", [0, 0, 1, 1]]]]));
|
|
1235
|
-
case "typography":
|
|
1236
|
-
if (!isObject(value)) return value;
|
|
1237
|
-
return normalForm(value, type, () => withFields(value, [..."fontFamily" in value ? [["fontFamily", fontFamily(value.fontFamily)]] : [], ..."fontWeight" in value ? [["fontWeight", fontWeight(value.fontWeight)]] : []]));
|
|
1238
|
-
default:
|
|
1239
|
-
return value;
|
|
1240
1652
|
}
|
|
1653
|
+
return found;
|
|
1241
1654
|
}
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1655
|
+
function positions(text2) {
|
|
1656
|
+
const starts = [0];
|
|
1657
|
+
for (let i = 0; i < text2.length; i++) if (text2[i] === "\n") starts.push(i + 1);
|
|
1658
|
+
return (at) => {
|
|
1659
|
+
let low = 0;
|
|
1660
|
+
let high = starts.length - 1;
|
|
1661
|
+
while (low < high) {
|
|
1662
|
+
const mid = low + high + 1 >> 1;
|
|
1663
|
+
if (starts[mid] <= at) low = mid;
|
|
1664
|
+
else high = mid - 1;
|
|
1665
|
+
}
|
|
1666
|
+
return { line: low + 1, column: at - starts[low] + 1 };
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
function openingTagEnd(text2, from) {
|
|
1670
|
+
let quote = null;
|
|
1671
|
+
let depth = 0;
|
|
1672
|
+
for (let i = from; i < text2.length; i++) {
|
|
1673
|
+
const c = text2[i];
|
|
1674
|
+
if (quote) {
|
|
1675
|
+
if (c === quote) quote = null;
|
|
1676
|
+
} else if (c === '"' || c === "'" || c === "`") quote = c;
|
|
1677
|
+
else if (c === "{") depth++;
|
|
1678
|
+
else if (c === "}") depth = Math.max(0, depth - 1);
|
|
1679
|
+
else if (c === ">" && depth === 0) return i;
|
|
1250
1680
|
}
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1681
|
+
return text2.length;
|
|
1682
|
+
}
|
|
1683
|
+
var VARIANT = /(?<![\w.:-])variant\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(?:"([^"]*)"|'([^']*)'|`([^`$]*)`)\s*\}|([^\s"'=<>`{}$]+))/g;
|
|
1684
|
+
var IMPORT = /\b(?:import|export)\s*(?:type\s+)?([\w$*\s{},]*?)\s*from\s*(['"])([^'"]+)\2|\bimport\s*\(?\s*(['"])([^'"]+)\4|\brequire\s*\(\s*(['"])([^'"]+)\6/g;
|
|
1685
|
+
var indexes = /* @__PURE__ */ new WeakMap();
|
|
1686
|
+
function elementIndex(catalog) {
|
|
1687
|
+
if (indexes.has(catalog)) return indexes.get(catalog);
|
|
1688
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
1689
|
+
for (const component of catalog.components) if (component.web?.tag) byTag.set(component.web.tag, { components: [component.name], own: true });
|
|
1690
|
+
for (const component of catalog.components) {
|
|
1691
|
+
for (const tag of component.web?.items ?? []) {
|
|
1692
|
+
const at = byTag.get(tag) ?? { components: [], own: false };
|
|
1693
|
+
if (!at.components.includes(component.name)) at.components.push(component.name);
|
|
1694
|
+
byTag.set(tag, at);
|
|
1695
|
+
}
|
|
1255
1696
|
}
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1697
|
+
const byReactName = new Map([...byTag].map(([tag, at]) => [pascal(tag.slice(PREFIX.length)), { ...at, tag }]));
|
|
1698
|
+
indexes.set(catalog, { byTag, byReactName });
|
|
1699
|
+
return indexes.get(catalog);
|
|
1700
|
+
}
|
|
1701
|
+
function auditContext(catalog, manifest, shipped, { product = false } = {}) {
|
|
1702
|
+
const { byTag, byReactName } = elementIndex(catalog);
|
|
1703
|
+
const byWebModule = /* @__PURE__ */ new Map();
|
|
1704
|
+
const webEntries = /* @__PURE__ */ new Map();
|
|
1705
|
+
const register = (specifier, name) => byWebModule.set(specifier, [.../* @__PURE__ */ new Set([...byWebModule.get(specifier) ?? [], name])]);
|
|
1706
|
+
for (const component of catalog.components) {
|
|
1707
|
+
if (component.web?.module) register(component.web.module, component.name);
|
|
1708
|
+
if (component.web?.stylesheet) register(component.web.stylesheet, component.name);
|
|
1709
|
+
if (component.web?.tag) register(`${WEB2}/all`, component.name);
|
|
1259
1710
|
}
|
|
1260
|
-
};
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const name
|
|
1267
|
-
const
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
const
|
|
1277
|
-
|
|
1711
|
+
webEntries.set(`${WEB2}/all`, "*");
|
|
1712
|
+
for (const [id, each] of shipped) {
|
|
1713
|
+
webEntries.set(webEntryOf(id), id);
|
|
1714
|
+
for (const { name, web } of each.components) if (web?.tag) register(webEntryOf(id), name);
|
|
1715
|
+
}
|
|
1716
|
+
const reactEntries = /* @__PURE__ */ new Map();
|
|
1717
|
+
for (const each of shipped.values()) for (const { name, react } of each.components) if (react) reactEntries.set(react.import, (reactEntries.get(react.import) ?? /* @__PURE__ */ new Set()).add(name));
|
|
1718
|
+
const listed = new Map(manifest.components.map((component) => [component.name, component]));
|
|
1719
|
+
const ownEntries = new Set(manifest.components.map((component) => component.web?.import).filter((specifier) => webEntries.has(specifier)));
|
|
1720
|
+
return { catalog, manifest, shipped, product, byTag, byReactName, byWebModule, webEntries, reactEntries, listed, ownEntries };
|
|
1721
|
+
}
|
|
1722
|
+
function briefComponent(entry) {
|
|
1723
|
+
return { name: entry.name, title: entry.title, ...entry.web ? { web: entry.web } : {}, ...entry.react ? { react: entry.react } : {} };
|
|
1724
|
+
}
|
|
1725
|
+
var variantsOf = (manifest, name) => ({ values: manifest.components.find((c) => c.name === name)?.variants, omitted: manifest.omittedVariants[name] ?? [] });
|
|
1726
|
+
function standInsFor({ manifest, shipped, product }, name) {
|
|
1727
|
+
const omitted = manifest.omitted.find((o) => o.name === name);
|
|
1728
|
+
if (!omitted) return null;
|
|
1729
|
+
const listed = new Map(manifest.components.map((c) => [c.name, c]));
|
|
1730
|
+
const { name: _name, title: _title, ...why } = omitted;
|
|
1731
|
+
const take = omitted.providedBy ? { name, from: omitted.providedBy } : name;
|
|
1732
|
+
return {
|
|
1733
|
+
...why,
|
|
1734
|
+
...omitted.insteadUse ? { insteadUse: omitted.insteadUse.filter((other) => listed.has(other)).map((other) => briefComponent(listed.get(other))) } : {},
|
|
1735
|
+
availableIn: [...shipped].filter(([, each]) => each.components.some((c) => c.name === name)).map(([id]) => id),
|
|
1736
|
+
// A layer that left it out itself takes it back by no longer leaving it out; a later layer includes it.
|
|
1737
|
+
howToInclude: product && omitted.omittedBy === manifest.system ? { note: `Remove "${name}" from components.omit in ${manifest.system}.system.json.` } : { ...product ? {} : { note: `A shipped system is not edited: a product layer that extends "${manifest.system}" may take it.` }, write: { components: { include: [take] } } }
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
function distance(a, b) {
|
|
1741
|
+
let row = [...Array(b.length + 1).keys()];
|
|
1742
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1743
|
+
const next = [i];
|
|
1744
|
+
for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
1745
|
+
row = next;
|
|
1746
|
+
}
|
|
1747
|
+
return row[b.length];
|
|
1748
|
+
}
|
|
1749
|
+
var plainName = (name) => name.replace(new RegExp(`^${PREFIX}`), "").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
1750
|
+
function spelledLike({ manifest }, name, limit = 3) {
|
|
1751
|
+
const plain = plainName(name);
|
|
1752
|
+
return manifest.components.map((component) => [component.name, distance(plain, component.name)]).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0])).slice(0, limit).map(([other]) => other);
|
|
1753
|
+
}
|
|
1754
|
+
function auditText(context, text2, { file, kind = textKind(file), near } = {}) {
|
|
1755
|
+
const { manifest, byTag, byReactName, byWebModule, webEntries, reactEntries, listed, ownEntries } = context;
|
|
1756
|
+
const { code, styles } = readText(text2, kind);
|
|
1757
|
+
const at = positions(text2);
|
|
1758
|
+
const findings = [];
|
|
1759
|
+
const add = (offset, finding) => findings.push({ ...file ? { file } : {}, ...at(offset), ...finding });
|
|
1760
|
+
const unavailable = (names) => names.filter((name) => !listed.has(name));
|
|
1761
|
+
const missing = (offset, kind2, found, names) => {
|
|
1762
|
+
for (const name of names) add(offset, { kind: kind2, found, component: name, problem: `"${manifest.system}" does not have ${name}`, ...standInsFor(context, name) });
|
|
1763
|
+
};
|
|
1764
|
+
const unknownTag = (offset, kind2, found, tag) => add(offset, { kind: kind2, found, problem: `Tanrei has no element <${tag}>`, near: (near ?? ((name) => spelledLike(context, name)))(tag) });
|
|
1765
|
+
const inStyle = (offset) => styles.some(([from, to]) => offset >= from && offset < to);
|
|
1766
|
+
const local = /* @__PURE__ */ new Map();
|
|
1767
|
+
for (const match of code.matchAll(IMPORT)) {
|
|
1768
|
+
const specifier = match[3] ?? match[5] ?? match[7];
|
|
1769
|
+
const offset = match.index + match[0].lastIndexOf(specifier);
|
|
1770
|
+
if (specifier === WEB2 || specifier.startsWith(`${WEB2}/`)) {
|
|
1771
|
+
const names = byWebModule.get(specifier);
|
|
1772
|
+
if (!names) continue;
|
|
1773
|
+
if (webEntries.has(specifier) && ownEntries.size && !ownEntries.has(specifier)) {
|
|
1774
|
+
const of = webEntries.get(specifier);
|
|
1775
|
+
const extra = unavailable(names);
|
|
1776
|
+
const use = [...ownEntries][0];
|
|
1777
|
+
add(offset, {
|
|
1778
|
+
kind: "import",
|
|
1779
|
+
found: specifier,
|
|
1780
|
+
problem: `'${specifier}' registers ${of === "*" ? "every component" : `what "${of}" ships`}${extra.length ? `, with ${extra.join(", ")}, which "${manifest.system}" does not have` : ""}: in "${manifest.system}", the components are registered by '${use}'`,
|
|
1781
|
+
...extra.length ? { notInThisSystem: extra } : {},
|
|
1782
|
+
use
|
|
1783
|
+
});
|
|
1784
|
+
} else if (!webEntries.has(specifier) && unavailable(names).length === names.length) missing(offset, "import", specifier, names);
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (specifier !== REACT2 && !specifier.startsWith(`${REACT2}/`)) continue;
|
|
1788
|
+
const named = /\{([^}]*)\}/.exec(match[1] ?? "")?.[1];
|
|
1789
|
+
if (!named) continue;
|
|
1790
|
+
let cursor = match.index + match[0].indexOf("{");
|
|
1791
|
+
for (const part of named.split(",")) {
|
|
1792
|
+
const [, typeOnly, imported, alias] = /^\s*(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?\s*$/.exec(part) ?? [];
|
|
1793
|
+
const partAt = code.indexOf(imported ?? part.trim(), cursor);
|
|
1794
|
+
cursor = partAt + part.length;
|
|
1795
|
+
const wrapper = imported && byReactName.get(imported);
|
|
1796
|
+
if (!wrapper) continue;
|
|
1797
|
+
if (!typeOnly) local.set(alias ?? imported, { components: wrapper.components, imported });
|
|
1798
|
+
const names = unavailable(wrapper.components);
|
|
1799
|
+
if (names.length === wrapper.components.length) missing(partAt, "import", imported, names);
|
|
1800
|
+
else {
|
|
1801
|
+
const owner = listed.get(wrapper.components.find((name) => listed.has(name)));
|
|
1802
|
+
const expected = owner.react?.import;
|
|
1803
|
+
if (!expected || specifier === expected) continue;
|
|
1804
|
+
const holds = specifier === REACT_ALL || reactEntries.get(specifier)?.has(owner.name);
|
|
1805
|
+
const entryOf = [...context.shipped.keys()].find((id) => reactEntryOf(id) === specifier);
|
|
1806
|
+
const typedFor = specifier === REACT_ALL ? "every system" : entryOf ? `"${entryOf}"` : "another system";
|
|
1807
|
+
add(partAt, { kind: "import", found: `${imported} from '${specifier}'`, component: owner.name, problem: holds ? `in "${manifest.system}", ${imported} is imported from '${expected}': '${specifier}' types it for ${typedFor}` : `'${specifier}' does not export ${imported}`, use: expected });
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
const element = (offset, found, components, own2, end) => {
|
|
1812
|
+
const names = unavailable(components);
|
|
1813
|
+
if (names.length === components.length) return missing(offset, "element", found, names);
|
|
1814
|
+
if (!own2) return;
|
|
1815
|
+
const name = components[0];
|
|
1816
|
+
const { values, omitted } = variantsOf(manifest, name);
|
|
1817
|
+
if (!values) return;
|
|
1818
|
+
for (const value of code.slice(offset, end).matchAll(VARIANT)) {
|
|
1819
|
+
const chosen = value.slice(1).find((v) => v !== void 0);
|
|
1820
|
+
if (values.includes(chosen) || chosen.includes("${")) continue;
|
|
1821
|
+
const gone = omitted.includes(chosen);
|
|
1822
|
+
add(offset + value.index, { kind: "variant", found: `variant="${chosen}"`, component: name, problem: gone ? `"${manifest.system}" leaves the ${chosen} ${name} out` : `${name} has no variant "${chosen}"`, values });
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
for (const match of code.matchAll(new RegExp(`<(${TAG})(?![\\w-])`, "g"))) {
|
|
1826
|
+
const tag = match[1];
|
|
1827
|
+
const known = byTag.get(tag);
|
|
1828
|
+
if (known) element(match.index + 1, `<${tag}>`, known.components, known.own, openingTagEnd(code, match.index));
|
|
1829
|
+
else unknownTag(match.index + 1, "element", `<${tag}>`, tag);
|
|
1830
|
+
}
|
|
1831
|
+
for (const match of code.matchAll(new RegExp(`(['"\`])(${TAG})\\1`, "g"))) {
|
|
1832
|
+
const known = byTag.get(match[2]);
|
|
1833
|
+
if (known && !inStyle(match.index)) element(match.index + 1, `'${match[2]}'`, known.components, false, match.index);
|
|
1834
|
+
}
|
|
1835
|
+
if (local.size) {
|
|
1836
|
+
for (const match of code.matchAll(/<([A-Z][\w$]*)(?![\w$])/g)) {
|
|
1837
|
+
const bound = local.get(match[1]);
|
|
1838
|
+
if (bound) element(match.index + 1, `<${match[1]}>`, bound.components, byTag.get(byReactName.get(bound.imported).tag).own, openingTagEnd(code, match.index));
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
for (const [from, to] of styles) {
|
|
1842
|
+
for (const { offset, tag } of selectorTags(code, from, to)) {
|
|
1843
|
+
const known = byTag.get(tag);
|
|
1844
|
+
if (!known) unknownTag(offset, "selector", tag, tag);
|
|
1845
|
+
else if (unavailable(known.components).length === known.components.length) missing(offset, "selector", tag, known.components);
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return findings.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
1849
|
+
}
|
|
1850
|
+
function auditTexts(context, texts, options = {}) {
|
|
1851
|
+
const findings = texts.flatMap(({ file, text: text2, kind }) => auditText(context, text2, { file, kind, ...options }));
|
|
1852
|
+
return {
|
|
1853
|
+
system: context.manifest.system,
|
|
1854
|
+
...context.product ? { product: true } : {},
|
|
1855
|
+
checked: texts.length,
|
|
1856
|
+
clean: findings.length === 0,
|
|
1857
|
+
errors: findings.length,
|
|
1858
|
+
findings,
|
|
1859
|
+
...findings.length ? { next: "Replace each finding with what it names (insteadUse, use, values), or take the component into the product's layer (howToInclude) and run `tanrei build`." } : {}
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// ../tools/src/from.js
|
|
1864
|
+
var source = (from) => {
|
|
1865
|
+
const at = from.indexOf(".");
|
|
1866
|
+
return { component: from.slice(0, at), name: from.slice(at + 1) };
|
|
1867
|
+
};
|
|
1868
|
+
var LISTS = [
|
|
1869
|
+
["props", "prop"],
|
|
1870
|
+
["events", "event"],
|
|
1871
|
+
["slots", "slot"]
|
|
1872
|
+
];
|
|
1873
|
+
var forwards = (spec) => LISTS.some(([list]) => (spec?.[list] ?? []).some((entry) => entry.from)) || (spec?.items ?? []).some((kind) => kind.from);
|
|
1874
|
+
function resolveFrom(spec, byName, seen = /* @__PURE__ */ new Set()) {
|
|
1875
|
+
if (!forwards(spec)) return spec;
|
|
1876
|
+
const resolved = { ...spec };
|
|
1877
|
+
for (const [list] of LISTS) {
|
|
1878
|
+
if (!spec[list]) continue;
|
|
1879
|
+
resolved[list] = spec[list].map((entry) => {
|
|
1880
|
+
if (!entry.from) return entry;
|
|
1881
|
+
const { component, name } = source(entry.from);
|
|
1882
|
+
const member = byName.get(component);
|
|
1883
|
+
if (!member || component === spec.name || seen.has(component)) return entry;
|
|
1884
|
+
const theirs = (resolveFrom(member, byName, /* @__PURE__ */ new Set([...seen, spec.name]))[list] ?? []).find((e) => e.name === name);
|
|
1885
|
+
if (!theirs || !("description" in theirs)) return entry;
|
|
1886
|
+
const { from: _theirFrom, note: _theirNote, ...own2 } = theirs;
|
|
1887
|
+
return { ...own2, name: entry.name, from: entry.from, ...entry.note ? { note: entry.note } : {} };
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
if ((spec.items ?? []).some((kind) => kind.from)) {
|
|
1891
|
+
resolved.items = spec.items.map((kind) => {
|
|
1892
|
+
if (!kind.from) return kind;
|
|
1893
|
+
const { component, name } = source(kind.from);
|
|
1894
|
+
const member = byName.get(component);
|
|
1895
|
+
if (!member || component === spec.name || seen.has(component)) return kind;
|
|
1896
|
+
const theirs = (resolveFrom(member, byName, /* @__PURE__ */ new Set([...seen, spec.name])).items ?? []).find((k) => k.name === name);
|
|
1897
|
+
if (!theirs || !("summary" in theirs)) return kind;
|
|
1898
|
+
const { from: _theirFrom, note: _theirNote, ...own2 } = theirs;
|
|
1899
|
+
return { ...own2, name: kind.name, from: kind.from, ...kind.note ? { note: kind.note } : {} };
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
return resolved;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// src/systems.js
|
|
1906
|
+
import fs6 from "node:fs";
|
|
1907
|
+
import path7 from "node:path";
|
|
1908
|
+
|
|
1909
|
+
// ../tokens-build/src/invariants.js
|
|
1910
|
+
var lin = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
1911
|
+
var luminance2 = ({ r, g, b }) => 0.2126 * lin(r / 255) + 0.7152 * lin(g / 255) + 0.0722 * lin(b / 255);
|
|
1912
|
+
var over = (fg, bg) => ({
|
|
1913
|
+
r: fg.r * fg.a + bg.r * (1 - fg.a),
|
|
1914
|
+
g: fg.g * fg.a + bg.g * (1 - fg.a),
|
|
1915
|
+
b: fg.b * fg.a + bg.b * (1 - fg.a),
|
|
1916
|
+
a: 1
|
|
1917
|
+
});
|
|
1918
|
+
var leadWithStructure = (warnings) => [...warnings.filter((w) => !/^\[[a-z-]+\] /.test(w)), ...warnings.filter((w) => /^\[[a-z-]+\] /.test(w))];
|
|
1919
|
+
var isCriterionFinding = (finding) => /^\[[a-z-]+\] [a-z0-9.-]+ on [a-z0-9.-]+: \d+\.\d+:1 < \d+(\.\d+)?:1 \(/.test(finding) || isTargetSizeFinding(finding);
|
|
1920
|
+
var isTargetSizeFinding = (finding) => finding.startsWith("target size: ");
|
|
1921
|
+
var isRefusedEverywhere = (finding) => finding.startsWith("target floor: ");
|
|
1922
|
+
var TARGET_THRESHOLDS = Object.freeze({ minimum: 24 });
|
|
1923
|
+
function targetFloors(documents) {
|
|
1924
|
+
const MIN = `{${CONFIG.namespace}.sys.target.minimum}`;
|
|
1925
|
+
const floored = /* @__PURE__ */ new Set();
|
|
1926
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1927
|
+
const walk = (node, path11) => {
|
|
1928
|
+
if (!node || typeof node !== "object") return;
|
|
1929
|
+
if ("$value" in node) {
|
|
1930
|
+
const id = path11.join(".");
|
|
1931
|
+
if (node.$extensions?.["dev.tanrei.derive"]?.min === MIN) floored.add(id);
|
|
1932
|
+
else if (typeof node.$value === "string" && /^\{[^{}]+\}$/.test(node.$value)) aliases.set(id, node.$value.slice(1, -1));
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1936
|
+
};
|
|
1937
|
+
for (const doc of documents) walk(doc, []);
|
|
1938
|
+
for (let grew = true; grew; ) {
|
|
1939
|
+
grew = false;
|
|
1940
|
+
for (const [id, target] of aliases) {
|
|
1941
|
+
if (floored.has(target) && !floored.has(id)) {
|
|
1942
|
+
floored.add(id);
|
|
1943
|
+
grew = true;
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
return [...floored].sort();
|
|
1948
|
+
}
|
|
1949
|
+
function ladderReaders(documents) {
|
|
1950
|
+
const STEP = new RegExp(`^\\{${CONFIG.namespace}\\.sys\\.control\\.height\\.([a-z-]+)\\}$`);
|
|
1951
|
+
const steps = /* @__PURE__ */ new Map();
|
|
1952
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1953
|
+
const walk = (node, path11) => {
|
|
1954
|
+
if (!node || typeof node !== "object") return;
|
|
1955
|
+
if ("$value" in node) {
|
|
1956
|
+
const id = path11.join(".");
|
|
1957
|
+
const rule = node.$extensions?.["dev.tanrei.derive"];
|
|
1958
|
+
const step = rule?.fn === "mul" && rule.by === 1 && rule.round === void 0 && typeof rule.of === "string" && rule.of.match(STEP)?.[1] || typeof node.$value === "string" && node.$value.match(STEP)?.[1];
|
|
1959
|
+
if (step) steps.set(id, step);
|
|
1960
|
+
else if (typeof node.$value === "string" && /^\{[^{}]+\}$/.test(node.$value)) aliases.set(id, node.$value.slice(1, -1));
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1964
|
+
};
|
|
1965
|
+
for (const doc of documents) walk(doc, []);
|
|
1966
|
+
for (let grew = true; grew; ) {
|
|
1967
|
+
grew = false;
|
|
1968
|
+
for (const [id, target] of aliases) {
|
|
1969
|
+
if (steps.has(target) && !steps.has(id)) {
|
|
1970
|
+
steps.set(id, steps.get(target));
|
|
1971
|
+
grew = true;
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
return Object.fromEntries([...steps].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
1976
|
+
}
|
|
1977
|
+
var ALIGNED = "dev.tanrei.aligned";
|
|
1978
|
+
function alignedTokens(documents, mark = "control") {
|
|
1979
|
+
const marked = [];
|
|
1980
|
+
const walk = (node, path11) => {
|
|
1981
|
+
if (!node || typeof node !== "object") return;
|
|
1982
|
+
if ("$value" in node) {
|
|
1983
|
+
if (node.$extensions?.[ALIGNED] === mark) marked.push(path11.join("."));
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
for (const [key, child] of Object.entries(node)) if (!key.startsWith("$")) walk(child, [...path11, key]);
|
|
1987
|
+
};
|
|
1988
|
+
for (const doc of documents) walk(doc, []);
|
|
1989
|
+
return marked.sort();
|
|
1990
|
+
}
|
|
1991
|
+
var ownHeights = (documents) => alignedTokens(documents, "own");
|
|
1992
|
+
var PRESET_CRITERIA_NOTE = "An imitation preset is held to fidelity to the system it imitates, not to Tanrei's accessibility criteria, in every contrast scheme. These are measurements against the fixed thresholds, kept as information: they are not warnings and not mimicry gaps.";
|
|
1993
|
+
var SELECTED_ROWS = [
|
|
1994
|
+
["list.selected.container.color", "list.unselected.hovered.container.color", "list.selected.content.color"],
|
|
1995
|
+
["tree-view.selected.container.color", "tree-view.unselected.hovered.container.color", "tree-view.selected.label.color"],
|
|
1996
|
+
["navigation-drawer.selected.item.container.color", "navigation-drawer.unselected.hovered.item.container.color", "navigation-drawer.selected.item.label.color"],
|
|
1997
|
+
["table.row.selected.container.color", "table.row.unselected.hovered.container.color", "table.row.selected.text.color"]
|
|
1998
|
+
];
|
|
1999
|
+
var COMPONENTS_HELD_IN_EVERY_SCHEME = ["radio-button", "menu", "snackbar", "chip", ...new Set(SELECTED_ROWS.map(([selected]) => selected.split(".")[0]))];
|
|
2000
|
+
function contrast(fgColor, bgColor) {
|
|
2001
|
+
const bg = rgba(bgColor);
|
|
2002
|
+
const fg = over(rgba(fgColor), bg);
|
|
2003
|
+
const [hi, lo] = [luminance2(fg), luminance2(bg)].sort((a, b) => b - a);
|
|
2004
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
2005
|
+
}
|
|
2006
|
+
var SURFACES = [
|
|
2007
|
+
"surface",
|
|
2008
|
+
"surface-dim",
|
|
2009
|
+
"surface-bright",
|
|
2010
|
+
"surface-container-lowest",
|
|
2011
|
+
"surface-container-low",
|
|
2012
|
+
"surface-container",
|
|
2013
|
+
"surface-container-high",
|
|
2014
|
+
"surface-container-highest"
|
|
2015
|
+
];
|
|
2016
|
+
var TEXT = 4.5;
|
|
2017
|
+
var NON_TEXT = 3;
|
|
2018
|
+
var STATUSES = ["info", "warning", "error", "success"];
|
|
2019
|
+
function intentsOf(roles) {
|
|
2020
|
+
return Object.keys(roles).filter((r) => [`on-${r}`, `${r}-container`, `on-${r}-container`].every((k) => k in roles));
|
|
2021
|
+
}
|
|
2022
|
+
function pairsFor(roles, focusStyle = "ring") {
|
|
2023
|
+
const intents = intentsOf(roles);
|
|
2024
|
+
const focus = focusStyle === "ring" ? "focus indicator (WCAG 2.4.13)" : `focus indicator, drawn as a ${focusStyle} (WCAG 2.4.13)`;
|
|
2025
|
+
return [
|
|
2026
|
+
...intents.flatMap((r) => [
|
|
2027
|
+
[`on-${r}`, r, TEXT, "content on filled container"],
|
|
2028
|
+
[`on-${r}-container`, `${r}-container`, TEXT, "content on tonal container"]
|
|
2029
|
+
]),
|
|
2030
|
+
...STATUSES.filter((r) => intents.includes(r)).map((r) => [r, `${r}-container`, NON_TEXT, "status mark on its tonal container (WCAG 1.4.11)"]),
|
|
2031
|
+
["inverse-on-surface", "inverse-surface", TEXT, "content on inverse surface"],
|
|
2032
|
+
// inverse-primary on inverse-surface is a snackbar's action label: text.
|
|
2033
|
+
["inverse-primary", "inverse-surface", TEXT, "accent text on inverse surface"],
|
|
2034
|
+
// A link on a surface of the opposite theme: the counterpart of `link` on the surfaces below.
|
|
2035
|
+
["inverse-link", "inverse-surface", TEXT, "inline links on inverse surface"],
|
|
2036
|
+
...SURFACES.flatMap((s) => [
|
|
2037
|
+
["on-surface", s, TEXT, "body text"],
|
|
2038
|
+
["on-surface-variant", s, TEXT, "secondary text"],
|
|
2039
|
+
["link", s, TEXT, "inline links"],
|
|
2040
|
+
...intents.map((r) => [r, s, TEXT, `${r}-colored text`]),
|
|
2041
|
+
["outline", s, NON_TEXT, "functional boundary (WCAG 1.4.11)"],
|
|
2042
|
+
["focus-ring", s, NON_TEXT, focus]
|
|
2043
|
+
])
|
|
2044
|
+
];
|
|
2045
|
+
}
|
|
2046
|
+
var tonalPairs = (roles) => ["secondary", ...STATUSES].filter((r) => `${r}-container` in roles).flatMap((r) => [
|
|
2047
|
+
["link", `${r}-container`, TEXT, "inline link on a tonal container"],
|
|
2048
|
+
["focus-ring", `${r}-container`, NON_TEXT, "focus indicator on a tonal container (WCAG 2.4.13)"]
|
|
2049
|
+
]);
|
|
2050
|
+
var HIGH_CONTRAST_TEXT = 7;
|
|
2051
|
+
var HAIRLINE = { medium: 3, high: 4.5 };
|
|
2052
|
+
var ROW_SELECTION = 1.1;
|
|
2053
|
+
var CONTRAST_THRESHOLDS = Object.freeze({
|
|
2054
|
+
/** Text, and a content color on its container, in the standard and medium contrast schemes. */
|
|
2055
|
+
text: TEXT,
|
|
2056
|
+
/** The same pairs in the high-contrast schemes. */
|
|
2057
|
+
highContrastText: HIGH_CONTRAST_TEXT,
|
|
2058
|
+
/** A boundary that identifies a control, a status's mark, the focus indicator: in every scheme. */
|
|
2059
|
+
nonText: NON_TEXT,
|
|
2060
|
+
/** The hairline (outline-variant) in the default system's raised-contrast schemes. */
|
|
2061
|
+
hairline: Object.freeze({ ...HAIRLINE })
|
|
2062
|
+
});
|
|
2063
|
+
var OTHER_THEME = { light: "dark", "light-medium": "dark-medium", "light-high": "dark-high", dark: "light", "dark-medium": "light-medium", "dark-high": "light-high" };
|
|
2064
|
+
var choiceOf = (model, name) => {
|
|
2065
|
+
const token = model.tokens[`${CONFIG.namespace}.sys.behavior.${name}`];
|
|
2066
|
+
return token?.enum?.values?.[token.value];
|
|
2067
|
+
};
|
|
2068
|
+
var choiceOfToken = (model, token) => {
|
|
2069
|
+
const target = token?.alias ? model.tokens[token.aliasFinal ?? token.alias] : token;
|
|
2070
|
+
return token?.enum?.values?.[target?.value];
|
|
2071
|
+
};
|
|
2072
|
+
var STACKED_ITEMS = [
|
|
2073
|
+
{
|
|
2074
|
+
component: "navigation-bar",
|
|
2075
|
+
what: "destination",
|
|
2076
|
+
height: "container.height",
|
|
2077
|
+
around: [["container.padding"], ["item.container.padding-block"]],
|
|
2078
|
+
glyph: "item.icon-indicator.height",
|
|
2079
|
+
gap: "item.gap",
|
|
2080
|
+
label: "item.label.typescale"
|
|
2081
|
+
},
|
|
2082
|
+
{
|
|
2083
|
+
component: "tabs",
|
|
2084
|
+
what: "primary tab",
|
|
2085
|
+
height: "container.height-with-icon",
|
|
2086
|
+
sizes: (tokens) => Object.keys(tokens).map((id) => id.match(new RegExp(`^${CONFIG.namespace}\\.comp\\.tabs\\.icon\\.size\\.([a-z0-9-]+)$`))?.[1]).filter(Boolean),
|
|
2087
|
+
when: ["icon.placement.<size>", "stacked", "icon.placement.medium"],
|
|
2088
|
+
// The content stands inside the indicator's box, held in by track.padding or by the primary underline's thickness,
|
|
2089
|
+
// whichever is more, and keeps the active indicator's padding-block inside it.
|
|
2090
|
+
around: [["track.padding", "primary.<state>.underline.thickness"], ["active-indicator.padding-block.<size>"]],
|
|
2091
|
+
glyph: "icon.size.<size>",
|
|
2092
|
+
gap: "container.gap",
|
|
2093
|
+
label: "label.typescale"
|
|
2094
|
+
}
|
|
2095
|
+
];
|
|
2096
|
+
var STACK_STATES = ["", "hovered.", "focused.", "pressed.", "disabled."];
|
|
2097
|
+
function auditInvariants(model) {
|
|
2098
|
+
const failures = [];
|
|
2099
|
+
const checked = Object.fromEntries(model.schemes.map((scheme) => [scheme, { rolePairs: 0, componentPairs: 0 }]));
|
|
2100
|
+
const measure = (scheme, kind, fg, bg) => {
|
|
2101
|
+
checked[scheme][kind] += 1;
|
|
2102
|
+
return contrast(fg, bg);
|
|
2103
|
+
};
|
|
2104
|
+
const focusStyle = choiceOf(model, "focus-style");
|
|
2105
|
+
for (const scheme of model.schemes) {
|
|
2106
|
+
const roles = model.colors[scheme];
|
|
2107
|
+
const isHigh = scheme.endsWith("-high");
|
|
2108
|
+
const declared = Object.entries(roles).filter(([, token]) => token.vocabulary?.onRole).map(([role2, token]) => [token.vocabulary.onRole.split(".").at(-1), role2, TEXT, `content on the declared role "${role2}"`]);
|
|
2109
|
+
const tonal = model.system === CONFIG.namespace ? tonalPairs(roles) : [];
|
|
2110
|
+
for (const [fg, bg, min, why] of [...pairsFor(roles, focusStyle), ...tonal, ...declared]) {
|
|
2111
|
+
if (!roles[fg] || !roles[bg]) {
|
|
2112
|
+
failures.push(`[${scheme}] missing role for pair ${fg} / ${bg}`);
|
|
2113
|
+
continue;
|
|
2114
|
+
}
|
|
2115
|
+
const required = isHigh && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2116
|
+
const ratio = measure(scheme, "rolePairs", roles[fg].value, roles[bg].value);
|
|
2117
|
+
if (ratio < required) {
|
|
2118
|
+
failures.push(`[${scheme}] ${fg} on ${bg}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
const level = model.system !== CONFIG.namespace ? null : isHigh ? "high" : scheme.endsWith("-medium") ? "medium" : null;
|
|
2122
|
+
if (level && roles["outline-variant"] && roles.outline) {
|
|
2123
|
+
for (const s of SURFACES.filter((each) => roles[each])) {
|
|
2124
|
+
const hairline = measure(scheme, "rolePairs", roles["outline-variant"].value, roles[s].value);
|
|
2125
|
+
if (hairline < HAIRLINE[level]) failures.push(`[${scheme}] outline-variant on ${s}: ${hairline.toFixed(2)}:1 < ${HAIRLINE[level]}:1 (the hairline in a raised-contrast scheme)`);
|
|
2126
|
+
const edge = measure(scheme, "rolePairs", roles.outline.value, roles[s].value);
|
|
2127
|
+
if (edge < hairline) failures.push(`[${scheme}] outline on ${s}: ${edge.toFixed(2)}:1 < ${hairline.toFixed(2)}:1 (an input's edge stays stronger than the hairline)`);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
if (choiceOf(model, "pressed-feedback") === "dim") {
|
|
2132
|
+
const pressed = Object.values(model.tokens).filter((t) => t.path[0] === "comp" && /(^|\.)pressed\.opacity$/.test(t.path.slice(2).join(".")));
|
|
2133
|
+
if (pressed.length && pressed.every((t) => t.value >= 1)) failures.push(`sys.behavior.pressed-feedback is "dim", but every pressed opacity is 1 (${pressed.map((t) => t.id).join(", ")}): a press would show nothing \u2014 set the pressed opacity below 1, or choose another feedback`);
|
|
2134
|
+
}
|
|
2135
|
+
for (const token of Object.values(model.tokens)) {
|
|
2136
|
+
const tier = token.path[0];
|
|
2137
|
+
if (tier === "sys" && token.path[1] === "color") {
|
|
2138
|
+
if (!token.alias) failures.push(`${token.id}: sys.color roles must alias ref.palette / ref.alpha`);
|
|
2139
|
+
} else if ((tier === "sys" || tier === "comp") && !token.alias && !token.derive) {
|
|
2140
|
+
failures.push(`${token.id}: a literal needs a rule or a stated reason for being fixed; component tokens normally alias a sys token`);
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
for (const token of Object.values(model.tokens)) {
|
|
2144
|
+
if (!token.enum) continue;
|
|
2145
|
+
const names = token.enum.values;
|
|
2146
|
+
const list = (values) => (values ?? []).map((name, i) => `${name} (${i})`).join(", ");
|
|
2147
|
+
let value = token.value;
|
|
2148
|
+
if (token.alias) {
|
|
2149
|
+
const targetId = token.aliasFinal ?? token.alias;
|
|
2150
|
+
const target = model.tokens[targetId];
|
|
2151
|
+
if (!Array.isArray(target?.enum?.values)) {
|
|
2152
|
+
failures.push(`${token.id}: aliases ${targetId}, which is not a choice of kind \u2014 a choice follows another choice or is one of its own names: ${list(names)}`);
|
|
2153
|
+
continue;
|
|
2154
|
+
}
|
|
2155
|
+
if (!Array.isArray(names) || names.length !== target.enum.values.length || names.some((name, i) => name !== target.enum.values[i])) {
|
|
2156
|
+
failures.push(`${token.id}: aliases ${targetId}, whose choices differ \u2014 ${list(names)} here, ${list(target.enum.values)} there`);
|
|
2157
|
+
continue;
|
|
2158
|
+
}
|
|
2159
|
+
value = target.value;
|
|
2160
|
+
}
|
|
2161
|
+
if (!Array.isArray(names) || !Number.isInteger(value) || value < 0 || value >= names.length) failures.push(`${token.id}: ${JSON.stringify(value)} is not one of its choices \u2014 ${list(names)}`);
|
|
2162
|
+
}
|
|
2163
|
+
for (const token of Object.values(model.tokens)) {
|
|
2164
|
+
if (token.type !== "shadow" || token.alias) continue;
|
|
2165
|
+
if (!Array.isArray(token.value)) failures.push(`${token.id}: a shadow is a list of layers (an empty list draws nothing)`);
|
|
2166
|
+
else token.value.forEach((_, i) => {
|
|
2167
|
+
if (!token.partialAlias?.[i]?.color?.startsWith(`${CONFIG.namespace}.sys.color.`)) failures.push(`${token.id}: shadow layer ${i + 1} must take its color from a sys.color role`);
|
|
2168
|
+
});
|
|
2169
|
+
}
|
|
2170
|
+
for (const token of Object.values(model.tokens)) {
|
|
2171
|
+
const [tier, component, part, property, size] = token.path;
|
|
2172
|
+
if (tier !== "comp" || part !== "container" || property !== "height") continue;
|
|
2173
|
+
const at = (...rest) => model.tokens[[CONFIG.namespace, "comp", component, ...rest].join(".")];
|
|
2174
|
+
const padding = at("container", "padding-block", size)?.value?.value;
|
|
2175
|
+
const label = at("label", "typescale", size)?.value;
|
|
2176
|
+
if (padding === void 0 || !label?.fontSize) continue;
|
|
2177
|
+
const inset = at("set", "padding")?.value?.value ?? 0;
|
|
2178
|
+
const needed = 2 * padding + 2 * inset + Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
|
|
2179
|
+
if (token.value.value < needed) failures.push(`${token.id}: ${token.value.value}px cannot hold its content \u2014 2 \xD7 padding-block (${padding}px)${inset ? ` + 2 \xD7 set.padding (${inset}px)` : ""} + one label line = ${needed}px`);
|
|
2180
|
+
}
|
|
2181
|
+
for (const stack of STACKED_ITEMS) {
|
|
2182
|
+
const of = (part) => model.tokens[`${CONFIG.namespace}.comp.${stack.component}.${part}`];
|
|
2183
|
+
const height = of(stack.height)?.value?.value;
|
|
2184
|
+
if (typeof height !== "number") continue;
|
|
2185
|
+
for (const size of stack.sizes ? stack.sizes(model.tokens) : [""]) {
|
|
2186
|
+
const named = (part) => part.replaceAll("<size>", size);
|
|
2187
|
+
if (stack.when && (choiceOfToken(model, of(named(stack.when[0]))) ?? choiceOfToken(model, of(stack.when[2]))) !== stack.when[1]) continue;
|
|
2188
|
+
const label = of(named(stack.label))?.value;
|
|
2189
|
+
if (!label?.fontSize) continue;
|
|
2190
|
+
const around = stack.around.map(
|
|
2191
|
+
(band) => band.flatMap((part) => part.includes("<state>.") ? STACK_STATES.map((state) => named(part).replace("<state>.", state)) : [named(part)]).map((part) => [part, of(part)?.value?.value]).filter(([, value]) => typeof value === "number").reduce((most, each) => each[1] > most[1] ? each : most, [named(band[0]).replace("<state>.", ""), 0])
|
|
2192
|
+
);
|
|
2193
|
+
const [glyph, gap] = [stack.glyph, stack.gap].map((part) => [named(part), of(named(part))?.value?.value ?? 0]);
|
|
2194
|
+
const line = Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
|
|
2195
|
+
const needed = Math.round((around.reduce((sum, [, value]) => sum + 2 * value, 0) + glyph[1] + gap[1] + line) * 100) / 100;
|
|
2196
|
+
if (height >= needed) continue;
|
|
2197
|
+
const terms = [...around.map(([part, value]) => `2 \xD7 ${part} (${value}px)`), `${glyph[0]} (${glyph[1]}px)`, `${gap[0]} (${gap[1]}px)`, `one ${named(stack.label)} line (${line}px)`];
|
|
2198
|
+
failures.push(`${CONFIG.namespace}.comp.${stack.component}.${stack.height}: ${height}px cannot hold its stacked ${stack.what}${size ? ` (${size})` : ""} \u2014 ${terms.join(" + ")} = ${needed}px`);
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
const role = (token) => {
|
|
2202
|
+
for (let at = token, hops = 0; at?.alias && hops < 16; at = model.tokens[at.alias], hops++) {
|
|
2203
|
+
if (at.alias.startsWith(`${CONFIG.namespace}.sys.color.`)) return at.alias.slice(`${CONFIG.namespace}.sys.color.`.length);
|
|
2204
|
+
}
|
|
2205
|
+
return void 0;
|
|
2206
|
+
};
|
|
2207
|
+
const short = (id) => id.slice(CONFIG.namespace.length + 1);
|
|
2208
|
+
for (const ring of Object.values(model.tokens)) {
|
|
2209
|
+
if (ring.path[0] !== "comp" || ring.type !== "color" || ring.path.at(-2) !== "focus-ring" || ring.path.at(-1) !== "color") continue;
|
|
2210
|
+
const barId = [CONFIG.namespace, ...ring.path.slice(0, -2), "container", "color"].join(".");
|
|
2211
|
+
const bar = model.tokens[barId];
|
|
2212
|
+
if (!bar) continue;
|
|
2213
|
+
const [ringRole, barRole] = [role(ring), role(bar)];
|
|
2214
|
+
for (const scheme of model.schemes) {
|
|
2215
|
+
const byRole = ringRole && barRole && model.colors[scheme][ringRole] && model.colors[scheme][barRole];
|
|
2216
|
+
const fg = byRole ? model.colors[scheme][ringRole].value : model.componentColors?.[scheme]?.[ring.id]?.value;
|
|
2217
|
+
const bg = byRole ? model.colors[scheme][barRole].value : model.componentColors?.[scheme]?.[barId]?.value;
|
|
2218
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2219
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2220
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(ring.id)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (focus indicator on the component's own bar, WCAG 2.4.13)`);
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
const snackbar = `${CONFIG.namespace}.comp.snackbar`;
|
|
2224
|
+
const inScheme = (scheme, id) => model.componentColors?.[scheme]?.[id]?.value;
|
|
2225
|
+
const number = (id) => typeof model.tokens[id]?.value === "number" ? model.tokens[id].value : 1;
|
|
2226
|
+
const faded = (color, opacity) => ({ ...color, alpha: (color.alpha ?? 1) * opacity });
|
|
2227
|
+
const flat = (fg, bg) => {
|
|
2228
|
+
const c = over(rgba(fg), rgba(bg));
|
|
2229
|
+
return { colorSpace: "srgb", components: [c.r / 255, c.g / 255, c.b / 255], alpha: 1 };
|
|
2230
|
+
};
|
|
2231
|
+
const sameColor = (x, y) => ["r", "g", "b", "a"].every((k) => rgba(x)[k] === rgba(y)[k]);
|
|
2232
|
+
const hex = (color) => `#${[rgba(color).r, rgba(color).g, rgba(color).b].map((n) => n.toString(16).padStart(2, "0")).join("")}${rgba(color).a < 1 ? ` at ${rgba(color).a}` : ""}`;
|
|
2233
|
+
if (model.system === CONFIG.namespace) {
|
|
2234
|
+
for (const scheme of model.schemes) {
|
|
2235
|
+
const other = OTHER_THEME[scheme];
|
|
2236
|
+
for (const id of Object.keys(model.componentColors?.[scheme] ?? {})) {
|
|
2237
|
+
if (!id.startsWith(`${snackbar}.`) || !STATUSES.some((status) => id.includes(`.inverse-${status}.`))) continue;
|
|
2238
|
+
const twin = id.replace(".inverse-", ".");
|
|
2239
|
+
const [here, there] = [inScheme(scheme, id), inScheme(other, twin)];
|
|
2240
|
+
if (!here || !there || sameColor(here, there)) continue;
|
|
2241
|
+
failures.push(`[${scheme}] ${short(id)} is ${hex(here)}, but ${short(twin)} is ${hex(there)} in ${other}: a status's inverse form is that status's form in the other theme (SNK-30)`);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
const STATES2 = ["", "hovered.", "focused.", "pressed."];
|
|
2246
|
+
for (const status of STATUSES) {
|
|
2247
|
+
const form = `inverse-${status}`;
|
|
2248
|
+
const barId = `${snackbar}.${form}.container.color`;
|
|
2249
|
+
if (!model.tokens[barId]) continue;
|
|
2250
|
+
const pairs = [
|
|
2251
|
+
[`${form}.title.color`, null, 1, TEXT, "title on its bar"],
|
|
2252
|
+
[`${form}.supporting-text.color`, null, 1, TEXT, "message on its bar"],
|
|
2253
|
+
[`${form}.icon.color`, null, number(`${snackbar}.icon.opacity`), NON_TEXT, "status glyph at icon.opacity on its bar"],
|
|
2254
|
+
[`${form}.supporting-text.color`, null, number(`${snackbar}.supporting-text.under-title.opacity`), TEXT, "description at its opacity under a title"]
|
|
2255
|
+
];
|
|
2256
|
+
for (const [fgName, groundName, opacity, min, why] of pairs) {
|
|
2257
|
+
const [fgId, groundId] = [`${snackbar}.${fgName}`, groundName && `${snackbar}.${groundName}`];
|
|
2258
|
+
if (!model.tokens[fgId] || groundId && !model.tokens[groundId]) continue;
|
|
2259
|
+
if (!groundId && opacity === 1 && role(model.tokens[fgId]) && role(model.tokens[barId])) continue;
|
|
2260
|
+
for (const scheme of model.schemes) {
|
|
2261
|
+
const [fg, bar, ground] = [inScheme(scheme, fgId), inScheme(scheme, barId), groundId && inScheme(scheme, groundId)];
|
|
2262
|
+
if (!fg || !bar || rgba(bar).a < 1 || groundId && !ground) continue;
|
|
2263
|
+
const bg = ground ? flat(ground, bar) : bar;
|
|
2264
|
+
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2265
|
+
const ratio = measure(scheme, "componentPairs", faded(fg, opacity), bg);
|
|
2266
|
+
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(groundId ?? barId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
const ns = CONFIG.namespace;
|
|
2271
|
+
const toneOpacity = model.tokens[`${ns}.comp.button.tone.container.opacity`]?.value;
|
|
2272
|
+
const variant = model.tokens[`${snackbar}.close-button.variant`]?.value;
|
|
2273
|
+
const LAYERS = { rest: null, hovered: "hover", focused: "focus", pressed: "pressed" };
|
|
2274
|
+
const layerOpacity = Object.fromEntries(Object.entries(LAYERS).map(([state, name]) => [state, name ? model.tokens[`${ns}.sys.state.${name}-state-layer-opacity`]?.value : 0]));
|
|
2275
|
+
if (["dim", "none"].includes(choiceOf(model, "pressed-feedback"))) delete layerOpacity.pressed;
|
|
2276
|
+
if (typeof toneOpacity === "number" && typeof variant === "number" && Object.values(layerOpacity).every((value) => typeof value === "number")) {
|
|
2277
|
+
const bare = variant === 3 || variant === 4;
|
|
2278
|
+
for (const form of ["", ...STATUSES, "inverse", ...STATUSES.map((status) => `inverse-${status}`)]) {
|
|
2279
|
+
const prefix = form ? `${snackbar}.${form}` : snackbar;
|
|
2280
|
+
const [toneId, barId] = [`${prefix}.supporting-text.color`, `${prefix}.container.color`];
|
|
2281
|
+
if (!model.tokens[toneId] || !model.tokens[barId]) continue;
|
|
2282
|
+
for (const scheme of model.schemes) {
|
|
2283
|
+
const [tone, bar] = [inScheme(scheme, toneId), inScheme(scheme, barId)];
|
|
2284
|
+
if (!tone || !bar || rgba(bar).a < 1) continue;
|
|
2285
|
+
const circle = bare ? bar : flat(faded(tone, toneOpacity), bar);
|
|
2286
|
+
for (const [state, opacity] of Object.entries(layerOpacity)) {
|
|
2287
|
+
if (bare && state === "rest") continue;
|
|
2288
|
+
const ground = opacity ? flat(faded(tone, opacity), circle) : circle;
|
|
2289
|
+
const ratio = measure(scheme, "componentPairs", tone, ground);
|
|
2290
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(toneId)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (expand and close glyph on its circle over the bar, ${state})`);
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
const held2 = /* @__PURE__ */ new Map();
|
|
2296
|
+
for (const scheme of model.schemes) for (const [fg, bg, min] of pairsFor(model.colors[scheme], focusStyle)) held2.set(`${fg} ${bg}`, Math.max(min, held2.get(`${fg} ${bg}`) ?? 0));
|
|
2297
|
+
const codeBlock = `${CONFIG.namespace}.comp.code-block`;
|
|
2298
|
+
const inlineCode = `${CONFIG.namespace}.comp.inline-code`;
|
|
2299
|
+
const SYNTAX = Object.keys(model.tokens).filter((id) => id.startsWith(`${codeBlock}.syntax.color.`)).map((id) => id.slice(codeBlock.length + 1));
|
|
2300
|
+
const CODE_TEXT = ["code.color", "line-number.color", "prompt.color", ...SYNTAX];
|
|
2301
|
+
const CODE_MARKS = ["line.highlighted.mark.color", "line.added.mark.color", "line.removed.mark.color"];
|
|
2302
|
+
const codePairs = [
|
|
2303
|
+
...CODE_TEXT.flatMap((part) => [
|
|
2304
|
+
[`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, TEXT, "code on the block's fill"],
|
|
2305
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.highlighted.container.color`, TEXT, "code on a highlighted line's band"],
|
|
2306
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.added.container.color`, TEXT, "code on an added line's band"],
|
|
2307
|
+
[`${codeBlock}.${part}`, `${codeBlock}.line.removed.container.color`, TEXT, "code on a removed line's band"]
|
|
2308
|
+
]),
|
|
2309
|
+
[`${codeBlock}.line.added.mark.color`, `${codeBlock}.line.added.container.color`, NON_TEXT, "an added line's bar and sign on its band"],
|
|
2310
|
+
[`${codeBlock}.line.removed.mark.color`, `${codeBlock}.line.removed.container.color`, NON_TEXT, "a removed line's bar and sign on its band"],
|
|
2311
|
+
...CODE_MARKS.map((part) => [`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, NON_TEXT, "a marked line's bar on the block's fill"]),
|
|
2312
|
+
// An outlined block has no fill: its code is read on the surface it is placed on, so a syntax color is held on
|
|
2313
|
+
// every surface role. The other text colors of the block are roles the role pairs hold there.
|
|
2314
|
+
...SYNTAX.flatMap((part) => SURFACES.map((surface) => [`${codeBlock}.${part}`, `${CONFIG.namespace}.sys.color.${surface}`, TEXT, "code in an outlined block on a surface"])),
|
|
2315
|
+
[`${inlineCode}.label.color`, `${inlineCode}.container.color`, TEXT, "inline code on its fill"]
|
|
2316
|
+
];
|
|
2317
|
+
const comp = (name) => `${CONFIG.namespace}.comp.${name}`;
|
|
2318
|
+
const match = comp("combobox.option.match");
|
|
2319
|
+
const markPairs = [
|
|
2320
|
+
[comp("search.result.mark.color"), comp("search.result.mark.container.color"), TEXT, "a match on its fill"],
|
|
2321
|
+
[`${match}.color`, `${match}.container.color`, TEXT, "a matched run of an option on its fill"],
|
|
2322
|
+
[`${match}.selected.color`, `${match}.selected.container.color`, TEXT, "a matched run of an option on the fill a selected one takes"]
|
|
2323
|
+
];
|
|
2324
|
+
for (const [fgId, bgId, min, why] of [...codePairs, ...markPairs]) {
|
|
2325
|
+
const [fgToken, bgToken] = [model.tokens[fgId], model.tokens[bgId]];
|
|
2326
|
+
if (!fgToken || !bgToken) continue;
|
|
2327
|
+
const [fgRole, bgRole] = [role(fgToken), bgId.startsWith(`${CONFIG.namespace}.sys.color.`) ? bgId.split(".").at(-1) : role(bgToken)];
|
|
2328
|
+
if (fgRole && bgRole && (held2.get(`${fgRole} ${bgRole}`) ?? 0) >= min) continue;
|
|
2329
|
+
for (const scheme of model.schemes) {
|
|
2330
|
+
const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
|
|
2331
|
+
const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
|
|
2332
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2333
|
+
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
2334
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2335
|
+
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
const meter = `${CONFIG.namespace}.comp.meter`;
|
|
2339
|
+
const meterGrounds = [[`${meter}.track.color`, "its track"], ...SURFACES.map((surface) => [`${CONFIG.namespace}.sys.color.${surface}`, "the surface it stands on"])];
|
|
2340
|
+
for (const part of ["indicator.color", ...STATUSES.map((status) => `${status}.indicator.color`)]) {
|
|
2341
|
+
const fgId = `${meter}.${part}`;
|
|
2342
|
+
if (!model.tokens[fgId]) continue;
|
|
2343
|
+
for (const [bgId, what] of meterGrounds) {
|
|
2344
|
+
const isRole = bgId.startsWith(`${CONFIG.namespace}.sys.color.`);
|
|
2345
|
+
if (!isRole && !model.tokens[bgId]) continue;
|
|
2346
|
+
const [fgRole, bgRole] = [role(model.tokens[fgId]), isRole ? bgId.split(".").at(-1) : role(model.tokens[bgId])];
|
|
2347
|
+
if (fgRole && bgRole && (held2.get(`${fgRole} ${bgRole}`) ?? 0) >= NON_TEXT) continue;
|
|
2348
|
+
for (const scheme of model.schemes) {
|
|
2349
|
+
const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
|
|
2350
|
+
const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
|
|
2351
|
+
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
2352
|
+
const ratio = measure(scheme, "componentPairs", fg, bg);
|
|
2353
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (a meter's indicator against ${what}, where its value is read \u2014 WCAG 1.4.11)`);
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
const RADIO_MARKS = [
|
|
2358
|
+
{
|
|
2359
|
+
component: "radio-button",
|
|
2360
|
+
conditions: ["unselected", "selected", "error-unselected", "error-selected"],
|
|
2361
|
+
ring: "ring",
|
|
2362
|
+
fill: "fill",
|
|
2363
|
+
opacity: "fill.opacity",
|
|
2364
|
+
inset: "fill.inset",
|
|
2365
|
+
grounds: SURFACES.map((surface) => `${CONFIG.namespace}.sys.color.${surface}`)
|
|
2366
|
+
},
|
|
2367
|
+
{
|
|
2368
|
+
// A menu draws the radio look only while its radio items are marked as radios (MNU-40), and fills a checked one.
|
|
2369
|
+
component: "menu",
|
|
2370
|
+
when: ["radio-item.mark", "radio"],
|
|
2371
|
+
conditions: ["selected"],
|
|
2372
|
+
ring: "control",
|
|
2373
|
+
fill: "control",
|
|
2374
|
+
opacity: "control.fill.opacity",
|
|
2375
|
+
inset: "control.fill.inset",
|
|
2376
|
+
grounds: [`${CONFIG.namespace}.comp.menu.surface.color`]
|
|
2377
|
+
}
|
|
2378
|
+
];
|
|
2379
|
+
const colorOf = (scheme, id) => {
|
|
2380
|
+
const colorRole = id.startsWith(`${CONFIG.namespace}.sys.color.`) ? id.split(".").at(-1) : model.tokens[id] && role(model.tokens[id]);
|
|
2381
|
+
return colorRole && model.colors[scheme]?.[colorRole] ? model.colors[scheme][colorRole].value : inScheme(scheme, id);
|
|
2382
|
+
};
|
|
2383
|
+
for (const mark of RADIO_MARKS) {
|
|
2384
|
+
const at = (rest) => `${CONFIG.namespace}.comp.${mark.component}.${rest}`;
|
|
2385
|
+
if (!model.tokens[at(`${mark.conditions[0]}.${mark.ring}.color`)]) continue;
|
|
2386
|
+
if (mark.when) {
|
|
2387
|
+
const choice = model.tokens[at(mark.when[0])];
|
|
2388
|
+
const target = choice?.alias ? model.tokens[choice.aliasFinal ?? choice.alias] : choice;
|
|
2389
|
+
if (choice?.enum?.values?.[target?.value] !== mark.when[1]) continue;
|
|
2390
|
+
}
|
|
2391
|
+
const opacity = number(at(mark.opacity));
|
|
2392
|
+
const gap = (model.tokens[at(mark.inset)]?.value?.value ?? 0) > 0;
|
|
2393
|
+
for (const scheme of model.schemes) {
|
|
2394
|
+
for (const condition of mark.conditions) {
|
|
2395
|
+
for (const state of STATES2) {
|
|
2396
|
+
const part = (name) => inScheme(scheme, at(`${condition}.${state}${name}.color`)) ?? inScheme(scheme, at(`${condition}.${name}.color`));
|
|
2397
|
+
const [ring, fill, layer] = [part(mark.ring), part(mark.fill), part("container")];
|
|
2398
|
+
if (!ring || !fill || rgba(fill).a * opacity === 0) continue;
|
|
2399
|
+
let worst;
|
|
2400
|
+
for (const groundId of mark.grounds) {
|
|
2401
|
+
const surface = colorOf(scheme, groundId);
|
|
2402
|
+
if (!surface || rgba(surface).a < 1) continue;
|
|
2403
|
+
const ground = layer ? flat(layer, surface) : surface;
|
|
2404
|
+
const center = flat(faded(fill, opacity), ground);
|
|
2405
|
+
const ratio = contrast(center, gap ? ground : flat(ring, ground));
|
|
2406
|
+
if (!worst || ratio < worst.ratio) worst = { ratio, groundId };
|
|
2407
|
+
}
|
|
2408
|
+
if (worst) checked[scheme].componentPairs += 1;
|
|
2409
|
+
if (!worst || worst.ratio >= NON_TEXT) continue;
|
|
2410
|
+
const [fillId, besideId] = [at(`${condition}.${state}${mark.fill}.color`), gap ? short(worst.groundId) : short(at(`${condition}.${state}${mark.ring}.color`))];
|
|
2411
|
+
const why = gap ? `the dot of a radio against the gap its fill.inset leaves, which shows ${short(worst.groundId)} through the state layer \u2014 WCAG 1.4.11` : `the fill of a radio against the ring it meets, at ${short(at(mark.opacity))} ${opacity} over ${short(worst.groundId)} and the state layer \u2014 WCAG 1.4.11`;
|
|
2412
|
+
failures.push(`[${scheme}] ${short(fillId)} on ${besideId}: ${worst.ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why})`);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
const chip = `${CONFIG.namespace}.comp.chip`;
|
|
2418
|
+
for (const variant2 of ["outlined", "elevated"]) {
|
|
2419
|
+
const at = (rest) => `${chip}.${variant2}.${rest}`;
|
|
2420
|
+
if (!model.tokens[at("container.color")]) continue;
|
|
2421
|
+
for (const look of ["remove", "destructive-remove"]) {
|
|
2422
|
+
if (!model.tokens[at(`${look}.icon.color`)]) continue;
|
|
2423
|
+
for (const scheme of model.schemes) {
|
|
2424
|
+
for (const state of STATES2) {
|
|
2425
|
+
const part = (name) => colorOf(scheme, at(`${state}${look}.${name}.color`)) ?? colorOf(scheme, at(`${look}.${name}.color`));
|
|
2426
|
+
const [glyph, layer, container] = [part("icon"), part("container"), colorOf(scheme, at("container.color"))];
|
|
2427
|
+
if (!glyph || !container) continue;
|
|
2428
|
+
let worst;
|
|
2429
|
+
for (const surface of SURFACES) {
|
|
2430
|
+
const ground = colorOf(scheme, `${CONFIG.namespace}.sys.color.${surface}`);
|
|
2431
|
+
if (!ground || rgba(ground).a < 1) continue;
|
|
2432
|
+
const chipGround = flat(container, ground);
|
|
2433
|
+
const ratio = contrast(glyph, layer ? flat(layer, chipGround) : chipGround);
|
|
2434
|
+
if (!worst || ratio < worst.ratio) worst = { ratio, surface };
|
|
2435
|
+
if (rgba(container).a >= 1) break;
|
|
2436
|
+
}
|
|
2437
|
+
if (worst) checked[scheme].componentPairs += 1;
|
|
2438
|
+
if (!worst || worst.ratio >= NON_TEXT) continue;
|
|
2439
|
+
const beneath = rgba(container).a >= 1 ? short(at("container.color")) : `sys.color.${worst.surface}`;
|
|
2440
|
+
failures.push(`[${scheme}] ${short(at(`${state}${look}.icon.color`))} on ${short(at(`${state}${look}.container.color`))}: ${worst.ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (the remove glyph of an input chip against its round container over ${beneath} \u2014 WCAG 1.4.11)`);
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
if (model.system === CONFIG.namespace) {
|
|
2446
|
+
for (const [selectedName, hoveredName, textName] of SELECTED_ROWS) {
|
|
2447
|
+
const [selectedId, hoveredId, textId] = [selectedName, hoveredName, textName].map((name) => `${CONFIG.namespace}.comp.${name}`);
|
|
2448
|
+
if (!model.tokens[selectedId] || !model.tokens[hoveredId]) continue;
|
|
2449
|
+
for (const scheme of model.schemes) {
|
|
2450
|
+
const [selected, hovered, text2] = [colorOf(scheme, selectedId), colorOf(scheme, hoveredId), model.tokens[textId] && colorOf(scheme, textId)];
|
|
2451
|
+
if (!selected || !hovered) continue;
|
|
2452
|
+
let apart;
|
|
2453
|
+
let read;
|
|
2454
|
+
for (const surface of SURFACES) {
|
|
2455
|
+
const ground = model.colors[scheme][surface]?.value;
|
|
2456
|
+
if (!ground || rgba(ground).a < 1) continue;
|
|
2457
|
+
const fill = flat(selected, ground);
|
|
2458
|
+
const ratio = contrast(fill, flat(hovered, ground));
|
|
2459
|
+
if (!apart || ratio < apart.ratio) apart = { ratio, surface };
|
|
2460
|
+
if (text2 && !role(model.tokens[selectedId])) {
|
|
2461
|
+
const textRatio = contrast(text2, fill);
|
|
2462
|
+
if (!read || textRatio < read.ratio) read = { ratio: textRatio, surface };
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
if (apart) checked[scheme].componentPairs += 1;
|
|
2466
|
+
if (read) checked[scheme].componentPairs += 1;
|
|
2467
|
+
if (apart && apart.ratio < ROW_SELECTION) failures.push(`[${scheme}] ${short(selectedId)} on ${short(hoveredId)}: ${apart.ratio.toFixed(2)}:1 < ${ROW_SELECTION}:1 (a selected row against a hovered one, each laid over sys.color.${apart.surface}: the two read as one fill \u2014 make the selection a layer of the row's content color, as comp.list.selected.container.color is)`);
|
|
2468
|
+
const required = scheme.endsWith("-high") ? HIGH_CONTRAST_TEXT : TEXT;
|
|
2469
|
+
if (read && read.ratio < required) failures.push(`[${scheme}] ${short(textId)} on ${short(selectedId)}: ${read.ratio.toFixed(2)}:1 < ${required}:1 (a selected row's text on its fill, laid over sys.color.${read.surface})`);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
if (model.system === CONFIG.namespace) {
|
|
2474
|
+
const px2 = (id) => model.tokens[id]?.value?.value;
|
|
2475
|
+
for (const token of Object.values(model.tokens)) {
|
|
2476
|
+
if (!token.concentric) continue;
|
|
2477
|
+
const [outerId, insetId] = [token.concentric.outer, token.concentric.inset].map((ref) => typeof ref === "string" ? ref.replace(/^\{|\}$/g, "") : void 0);
|
|
2478
|
+
const [inner, outer, inset] = [token.value?.value, px2(outerId), px2(insetId)];
|
|
2479
|
+
if (typeof inner !== "number" || typeof outer !== "number" || typeof inset !== "number") {
|
|
2480
|
+
failures.push(`${short(token.id)}: dev.tanrei.concentric names ${JSON.stringify(token.concentric)}, which must be two dimension tokens, { "outer": "{id}", "inset": "{id}" }`);
|
|
2481
|
+
continue;
|
|
2482
|
+
}
|
|
2483
|
+
const expected = Math.max(0, outer - inset);
|
|
2484
|
+
if (inner !== expected) failures.push(`${short(token.id)}: ${inner}px, but an inner corner is its outer corner less the inset, never below zero \u2014 max(0, ${short(outerId)} ${outer}px \u2212 ${short(insetId)} ${inset}px) = ${expected}px; derive it with { "fn": "sub", "of": "{${outerId}}", "by": "{${insetId}}" }`);
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
const px = (id) => model.tokens[`${CONFIG.namespace}.${id}`]?.value?.value;
|
|
2488
|
+
const minimum = px("sys.target.minimum");
|
|
2489
|
+
for (const name of ["minimum", "pointer", "touch"]) {
|
|
2490
|
+
const value = px(`sys.target.${name}`);
|
|
2491
|
+
if (typeof value === "number" && value < TARGET_THRESHOLDS.minimum) failures.push(`target size: sys.target.${name}: ${value}px < ${TARGET_THRESHOLDS.minimum}px (WCAG 2.5.8: the least target a person presses)`);
|
|
2492
|
+
if (name !== "minimum" && typeof value === "number" && typeof minimum === "number" && value < minimum) failures.push(`target floor: sys.target.${name}: ${value}px is under sys.target.minimum (${minimum}px) \u2014 the area a press is taken from is never smaller than what is drawn; set it to the minimum or above`);
|
|
2493
|
+
}
|
|
2494
|
+
if (typeof minimum === "number") {
|
|
2495
|
+
const MIN = `{${CONFIG.namespace}.sys.target.minimum}`;
|
|
2496
|
+
const floored = /* @__PURE__ */ new Set([...model.floored ?? [], ...Object.values(model.tokens).filter((token) => token.derive?.min === MIN).map((token) => token.id)]);
|
|
2497
|
+
for (const id of [...floored].sort()) {
|
|
2498
|
+
const value = model.tokens[id]?.value?.value;
|
|
2499
|
+
if (typeof value === "number" && value < minimum) failures.push(`target size: ${id.slice(CONFIG.namespace.length + 1)}: ${value}px < sys.target.minimum ${minimum}px (a box a person presses is drawn at least the minimum target; derive it with "min": "${MIN}", or lower the minimum)`);
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
const controlHeight = px("dial.control.height");
|
|
2503
|
+
if (typeof minimum === "number" && typeof controlHeight === "number" && minimum > controlHeight) failures.push(`target floor: sys.target.minimum: ${minimum}px is above dial.control.height (${controlHeight}px) \u2014 a control of the default size is drawn at the control height; lower the minimum or raise the control height`);
|
|
2504
|
+
if ((model.system === CONFIG.namespace || model.system === "core") && model.ladder) {
|
|
2505
|
+
for (const id of model.aligned ?? []) {
|
|
2506
|
+
if (model.ladder[id] !== "medium") failures.push(`${short(id)}: marked ${ALIGNED}, but it does not read sys.control.height.medium \u2014 derive it with { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.medium}", "by": 1, "min": "{${CONFIG.namespace}.sys.target.minimum}" }, or alias a token that does`);
|
|
2507
|
+
}
|
|
2508
|
+
const own2 = new Set(model.own ?? []);
|
|
2509
|
+
for (const id of model.floored ?? []) {
|
|
2510
|
+
if (!(id in model.ladder) && !own2.has(id)) failures.push(`${short(id)}: a pressable height that reads no step of the control height ladder \u2014 read the step of its size, { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.<step>}", "by": 1, "min": "{${CONFIG.namespace}.sys.target.minimum}" }, or, where its spec says it keeps a size of its own at every control height, mark it "${ALIGNED}": "own"`);
|
|
2511
|
+
}
|
|
2512
|
+
const floored = new Set(model.floored ?? []);
|
|
2513
|
+
for (const id of own2) {
|
|
2514
|
+
if (id in model.ladder || !floored.has(id)) failures.push(`${short(id)}: marked ${ALIGNED} "own", but it ${id in model.ladder ? "reads a step of the ladder" : "is no pressable height the core floors"} \u2014 take the mark off`);
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
if (model.system === CONFIG.namespace && model.ladder) {
|
|
2518
|
+
const floored = new Set(model.floored ?? []);
|
|
2519
|
+
for (const [id, step] of Object.entries(model.ladder)) {
|
|
2520
|
+
const [value, height] = [model.tokens[id]?.value?.value, px(`sys.control.height.${step}`)];
|
|
2521
|
+
if (typeof value !== "number" || typeof height !== "number") continue;
|
|
2522
|
+
const held3 = floored.has(id) && typeof minimum === "number" && minimum > height;
|
|
2523
|
+
const expected = held3 ? minimum : height;
|
|
2524
|
+
if (value !== expected) failures.push(`${short(id)}: ${value}px, but a control of the ${step} size is as tall as sys.control.height.${step} (${height}px)${held3 ? `, held at sys.target.minimum (${minimum}px)` : ""} \u2014 read the step, { "fn": "mul", "of": "{${CONFIG.namespace}.sys.control.height.${step}}", "by": 1${floored.has(id) ? `, "min": "{${CONFIG.namespace}.sys.target.minimum}"` : ""} }`);
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
const TOLD_APART = [
|
|
2528
|
+
["link", "standard.label.color", "sys.color.on-surface", "a link beside body text"],
|
|
2529
|
+
["link", "inverse.label.color", "sys.color.inverse-on-surface", "a link beside text on an inverse surface"],
|
|
2530
|
+
["breadcrumbs", "item.content.color", "comp.breadcrumbs.label.color", "a level that is a link beside a level that is text"]
|
|
2531
|
+
];
|
|
2532
|
+
for (const [component, fgName, besideName, why] of TOLD_APART) {
|
|
2533
|
+
const choice = model.tokens[`${CONFIG.namespace}.comp.${component}.underline.visibility`];
|
|
2534
|
+
if (!choice?.enum) continue;
|
|
2535
|
+
const target = choice.alias ? model.tokens[choice.aliasFinal ?? choice.alias] : choice;
|
|
2536
|
+
const named = choice.enum.values?.[target?.value];
|
|
2537
|
+
if (!named || named === "always") continue;
|
|
2538
|
+
const [fgId, besideId] = [`${CONFIG.namespace}.comp.${component}.${fgName}`, `${CONFIG.namespace}.${besideName}`];
|
|
2539
|
+
const colorIn = (scheme, id) => {
|
|
2540
|
+
const colorRole = id.startsWith(`${CONFIG.namespace}.sys.color.`) ? id.split(".").at(-1) : model.tokens[id] && role(model.tokens[id]);
|
|
2541
|
+
return colorRole && model.colors[scheme][colorRole] ? model.colors[scheme][colorRole].value : inScheme(scheme, id);
|
|
2542
|
+
};
|
|
2543
|
+
for (const scheme of model.schemes) {
|
|
2544
|
+
const [fg, beside] = [colorIn(scheme, fgId), colorIn(scheme, besideId)];
|
|
2545
|
+
if (!fg || !beside || rgba(fg).a < 1 || rgba(beside).a < 1) continue;
|
|
2546
|
+
const ratio = measure(scheme, "componentPairs", fg, beside);
|
|
2547
|
+
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} against ${short(besideId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why}, while ${short(choice.id)} is "${named}": a link not underlined at rest is told from text by color alone \u2014 WCAG 1.4.1; underline it always, or move the link color)`);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
const drawer = (rest) => model.tokens[`${CONFIG.namespace}.comp.navigation-drawer.${rest}`];
|
|
2551
|
+
const [least, opens, greatest] = ["min-width", "width", "max-width"].map((name) => drawer(`container.${name}`)?.value?.value);
|
|
2552
|
+
if (typeof least === "number" && typeof opens === "number" && typeof greatest === "number") {
|
|
2553
|
+
if (!(least <= opens && opens <= greatest)) failures.push(`navigation drawer widths: comp.navigation-drawer.container.min-width ${least}px \u2264 container.width ${opens}px \u2264 container.max-width ${greatest}px does not hold \u2014 the drawer opens at its width, between the least and the greatest a person can give it`);
|
|
2554
|
+
for (const token of Object.values(model.tokens)) {
|
|
2555
|
+
if (!token.id.startsWith(`${CONFIG.namespace}.comp.navigation-drawer.collapsed.container.width.`)) continue;
|
|
2556
|
+
const column = token.value?.value;
|
|
2557
|
+
if (typeof column === "number" && !(column < least)) failures.push(`navigation drawer widths: ${short(token.id)} ${column}px is not below container.min-width ${least}px \u2014 a drag folds a collapsible drawer halfway between its column and its least width, so the column is the narrower of the two at every size`);
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
return { failures, checked };
|
|
2561
|
+
}
|
|
2562
|
+
var checkInvariants = (model) => auditInvariants(model).failures;
|
|
2563
|
+
|
|
2564
|
+
// ../tokens-build/src/model.js
|
|
2565
|
+
import fs4 from "node:fs";
|
|
2566
|
+
import path5 from "node:path";
|
|
2567
|
+
import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "node:url";
|
|
2568
|
+
|
|
2569
|
+
// ../tokens-build/src/reader.js
|
|
2570
|
+
var TokenReadError = class extends Error {
|
|
2571
|
+
};
|
|
2572
|
+
var collator = new Intl.Collator("en-us", { numeric: true });
|
|
2573
|
+
var ALIAS = /^\{([^}]+)\}$/;
|
|
2574
|
+
var isAlias = (value) => typeof value === "string" && ALIAS.test(value);
|
|
2575
|
+
var isObject = (value) => value !== null && typeof value === "object";
|
|
2576
|
+
var DTCG_TYPES = /* @__PURE__ */ new Set(["color", "dimension", "fontFamily", "fontWeight", "duration", "cubicBezier", "number", "strokeStyle", "border", "transition", "shadow", "gradient", "typography"]);
|
|
2577
|
+
var NESTED = {
|
|
2578
|
+
border: { color: ["color"], stroke: ["strokeStyle"], width: ["dimension"] },
|
|
2579
|
+
gradient: { color: ["color"], position: ["number"] },
|
|
2580
|
+
shadow: { color: ["color"], offsetX: ["dimension"], offsetY: ["dimension"], blur: ["dimension"], spread: ["dimension"], inset: ["boolean"] },
|
|
2581
|
+
strokeStyle: { dashArray: ["dimension"] },
|
|
2582
|
+
transition: { duration: ["duration"], delay: ["duration"], timingFunction: ["cubicBezier"] },
|
|
2583
|
+
typography: { fontFamily: ["fontFamily"], fontWeight: ["fontWeight"], fontSize: ["dimension"], lineHeight: ["dimension", "number"], letterSpacing: ["dimension"], paragraphSpacing: ["dimension", "string"], wordSpacing: ["dimension", "string"] }
|
|
2584
|
+
};
|
|
2585
|
+
var FONT_WEIGHTS = {
|
|
2586
|
+
thin: 100,
|
|
2587
|
+
hairline: 100,
|
|
2588
|
+
"extra-light": 200,
|
|
2589
|
+
"ultra-light": 200,
|
|
2590
|
+
light: 300,
|
|
2591
|
+
normal: 400,
|
|
2592
|
+
regular: 400,
|
|
2593
|
+
book: 400,
|
|
2594
|
+
medium: 500,
|
|
2595
|
+
"semi-bold": 600,
|
|
2596
|
+
"demi-bold": 600,
|
|
2597
|
+
bold: 700,
|
|
2598
|
+
"extra-bold": 800,
|
|
2599
|
+
"ultra-bold": 800,
|
|
2600
|
+
black: 900,
|
|
2601
|
+
heavy: 900,
|
|
2602
|
+
"extra-black": 950,
|
|
2603
|
+
"ultra-black": 950
|
|
2604
|
+
};
|
|
2605
|
+
function merge(under, over2) {
|
|
2606
|
+
if (under === void 0 || !isObject(over2) || Array.isArray(over2)) return over2;
|
|
2607
|
+
if (under === null) return null;
|
|
2608
|
+
if (typeof under !== "object") return over2;
|
|
2609
|
+
const out = Array.isArray(under) ? [...under] : { ...under };
|
|
2610
|
+
for (const key of Object.keys(over2)) out[key] = Object.hasOwn(under, key) ? merge(under[key], over2[key]) : over2[key];
|
|
2611
|
+
return out;
|
|
2612
|
+
}
|
|
2613
|
+
var GROUP_KEYS = /* @__PURE__ */ new Set(["$type", "$description", "$deprecated", "$extensions", "$value", "$schema"]);
|
|
2614
|
+
var resolvedForms = /* @__PURE__ */ new WeakMap();
|
|
2615
|
+
var normalForms = /* @__PURE__ */ new WeakMap();
|
|
2616
|
+
function normalColor(value, id) {
|
|
2617
|
+
if (typeof value === "string" && !isAlias(value)) throw new TokenReadError(`${id}: a color written as a string ("${value}") is not read; write it in the object notation`);
|
|
2618
|
+
if (!isObject(value) || value.alpha !== void 0) return value;
|
|
2619
|
+
return normalForm(value, "color", () => ({ ...value, alpha: 1 }));
|
|
2620
|
+
}
|
|
2621
|
+
function normalForm(value, type, make) {
|
|
2622
|
+
let forms = normalForms.get(value);
|
|
2623
|
+
if (!forms) normalForms.set(value, forms = /* @__PURE__ */ new Map());
|
|
2624
|
+
if (!forms.has(type)) forms.set(type, make());
|
|
2625
|
+
return forms.get(type);
|
|
2626
|
+
}
|
|
2627
|
+
var fontFamily = (value) => typeof value === "string" ? [value] : value;
|
|
2628
|
+
var fontWeight = (value) => typeof value === "string" && FONT_WEIGHTS[value] || value;
|
|
2629
|
+
function withFields(value, changes) {
|
|
2630
|
+
let out = value;
|
|
2631
|
+
for (const [key, next] of changes) {
|
|
2632
|
+
if (next === value[key] && key in value) continue;
|
|
2633
|
+
if (out === value) out = Array.isArray(value) ? [...value] : { ...value };
|
|
2634
|
+
out[key] = next;
|
|
2635
|
+
}
|
|
2636
|
+
return out;
|
|
2637
|
+
}
|
|
2638
|
+
function normalize(value, type, id) {
|
|
2639
|
+
switch (type) {
|
|
2640
|
+
case "color":
|
|
2641
|
+
return normalColor(value, id);
|
|
2642
|
+
case "fontFamily":
|
|
2643
|
+
return fontFamily(value);
|
|
2644
|
+
case "fontWeight":
|
|
2645
|
+
return fontWeight(value);
|
|
2646
|
+
case "border":
|
|
2647
|
+
return isObject(value) && value.color ? normalForm(value, type, () => withFields(value, [["color", normalColor(value.color, id)]])) : value;
|
|
2648
|
+
case "shadow": {
|
|
2649
|
+
const layer = (shadow) => isObject(shadow) ? withFields(shadow, [...shadow.color ? [["color", normalColor(shadow.color, id)]] : [], ..."inset" in shadow ? [] : [["inset", false]]]) : shadow;
|
|
2650
|
+
if (!isObject(value)) return [value];
|
|
2651
|
+
return normalForm(value, type, () => Array.isArray(value) ? withFields(value, value.map((shadow, i) => [i, layer(shadow)])) : [layer(value)]);
|
|
2652
|
+
}
|
|
2653
|
+
case "gradient":
|
|
2654
|
+
if (!Array.isArray(value)) return value;
|
|
2655
|
+
return normalForm(value, type, () => withFields(value, value.map((stop, i) => [i, isObject(stop) && stop.color ? withFields(stop, [["color", normalColor(stop.color, id)]]) : stop])));
|
|
2656
|
+
case "transition":
|
|
2657
|
+
if (!isObject(value)) return value;
|
|
2658
|
+
return normalForm(value, type, () => withFields(value, [...value.duration ? [] : [["duration", { value: 0, unit: "ms" }]], ...value.delay ? [] : [["delay", { value: 0, unit: "ms" }]], ...value.timingFunction ? [] : [["timingFunction", [0, 0, 1, 1]]]]));
|
|
2659
|
+
case "typography":
|
|
2660
|
+
if (!isObject(value)) return value;
|
|
2661
|
+
return normalForm(value, type, () => withFields(value, [..."fontFamily" in value ? [["fontFamily", fontFamily(value.fontFamily)]] : [], ..."fontWeight" in value ? [["fontWeight", fontWeight(value.fontWeight)]] : []]));
|
|
2662
|
+
default:
|
|
2663
|
+
return value;
|
|
2664
|
+
}
|
|
2665
|
+
}
|
|
2666
|
+
var pointerPart = (part) => part.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
2667
|
+
var Name = class _Name {
|
|
2668
|
+
constructor(parent, key) {
|
|
2669
|
+
this.id = parent ? parent.id ? `${parent.id}.${key}` : key : "";
|
|
2670
|
+
this.jsonID = parent ? `${parent.jsonID === "#/" ? "#" : parent.jsonID}/${pointerPart(key)}` : "#/";
|
|
2671
|
+
this.children = void 0;
|
|
2672
|
+
this.reference = void 0;
|
|
2673
|
+
this.rank = void 0;
|
|
2674
|
+
}
|
|
2675
|
+
child(key) {
|
|
2676
|
+
let child = (this.children ??= /* @__PURE__ */ new Map()).get(key);
|
|
2677
|
+
if (!child) this.children.set(key, child = new _Name(this, key));
|
|
2678
|
+
return child;
|
|
2679
|
+
}
|
|
2680
|
+
/** The reference a dependency is written as: the pointer of the token's value. */
|
|
2681
|
+
get ref() {
|
|
2682
|
+
return this.reference ??= `${this.jsonID}/$value`;
|
|
2683
|
+
}
|
|
2684
|
+
};
|
|
2685
|
+
var SCALARS = ["$type", "$description", "$deprecated", "$value", "$extensions", "aliasOf", "originalValue"];
|
|
2686
|
+
var LISTS2 = ["aliasChain", "aliasedBy", "dependencies"];
|
|
2687
|
+
var sameList = (a, b) => a === b || a !== void 0 && b !== void 0 && a.length === b.length && a.every((item, i) => item === b[i]);
|
|
2688
|
+
var sameShape = (a, b) => a === b || isObject(a) && isObject(b) && Array.isArray(a) === Array.isArray(b) && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => key in b && sameShape(a[key], b[key]));
|
|
2689
|
+
function readBundle(files, systemId) {
|
|
2690
|
+
const name = `${systemId}.resolver.json`;
|
|
2691
|
+
const resolver = files[name];
|
|
2692
|
+
if (!resolver) throw new Error(`the bundle has no ${name}`);
|
|
2693
|
+
const documentOf = (source2, where) => {
|
|
2694
|
+
if (typeof source2?.$ref !== "string") return source2;
|
|
2695
|
+
if (source2.$ref.startsWith("#")) throw new TokenReadError(`${name} ${where}: a source that points into the resolver document ("${source2.$ref}") is not read`);
|
|
2696
|
+
const doc = files[source2.$ref];
|
|
2697
|
+
if (!doc) throw new Error(`the bundle has no ${source2.$ref}`);
|
|
2698
|
+
return doc;
|
|
2699
|
+
};
|
|
2700
|
+
const steps = (resolver.resolutionOrder ?? []).map(({ $ref }, i) => {
|
|
2701
|
+
const [, kind, key] = /^#\/(sets|modifiers)\/(.+)$/.exec($ref ?? "") ?? [];
|
|
1278
2702
|
const item = kind && resolver[kind]?.[key];
|
|
1279
2703
|
if (!item) throw new TokenReadError(`${name} resolutionOrder[${i}]: "${$ref}" names no set and no modifier of this document`);
|
|
1280
2704
|
return kind === "sets" ? { set: key, sources: item.sources ?? [] } : { modifier: key, contexts: item.contexts ?? {}, default: typeof item.default === "string" ? item.default : Object.keys(item.contexts ?? {})[0] };
|
|
1281
2705
|
});
|
|
1282
2706
|
const modifiers = steps.filter((step) => step.modifier);
|
|
1283
2707
|
const schemeModifier = modifiers.find((step) => step.modifier === "scheme");
|
|
1284
|
-
const mergeSources = (tree,
|
|
2708
|
+
const mergeSources = (tree, sources2, where) => sources2.reduce((acc, source2) => merge(acc, documentOf(source2, where)), tree);
|
|
1285
2709
|
const firstModifier = steps.findIndex((step) => step.modifier);
|
|
1286
2710
|
const shared = steps.slice(0, firstModifier < 0 ? steps.length : firstModifier);
|
|
1287
2711
|
let common;
|
|
@@ -1337,14 +2761,14 @@ function readBundle(files, systemId) {
|
|
|
1337
2761
|
target.walking = false;
|
|
1338
2762
|
return target.way = { links, end: links.at(-1), ids: links.map((link) => link.name.id), refs: links.map((link) => link.name.ref).sort(collator.compare) };
|
|
1339
2763
|
};
|
|
1340
|
-
const deep = (value, expected,
|
|
2764
|
+
const deep = (value, expected, path11, entry, partials) => {
|
|
1341
2765
|
if (typeof value !== "string") {
|
|
1342
2766
|
if (Array.isArray(value)) {
|
|
1343
2767
|
const inner = expected?.includes("cubicBezier") ? ["number"] : expected;
|
|
1344
|
-
return withFields(value, value.flatMap((item, i) => item ? [[i, deep(item, inner, [...
|
|
2768
|
+
return withFields(value, value.flatMap((item, i) => item ? [[i, deep(item, inner, [...path11, i], entry, partials)]] : []));
|
|
1345
2769
|
}
|
|
1346
2770
|
const fields = isObject(value) && expected?.length ? NESTED[expected[0]] : void 0;
|
|
1347
|
-
return fields ? withFields(value, Object.keys(value).map((key) => [key, deep(value[key], fields[key], [...
|
|
2771
|
+
return fields ? withFields(value, Object.keys(value).map((key) => [key, deep(value[key], fields[key], [...path11, key], entry, partials)])) : value;
|
|
1348
2772
|
}
|
|
1349
2773
|
if (!isAlias(value)) {
|
|
1350
2774
|
if ((!expected?.[0] || DTCG_TYPES.has(expected[0])) && (value.includes("{") || value.includes("}"))) fail(entry, "Invalid alias syntax.");
|
|
@@ -1352,7 +2776,7 @@ function readBundle(files, systemId) {
|
|
|
1352
2776
|
}
|
|
1353
2777
|
const way = chainOf(value, entry);
|
|
1354
2778
|
if (expected?.length && !expected.includes(way.end.type)) fail(entry, `Cannot alias to $type "${way.end.type}" from $type "${expected.join(" / ")}".`);
|
|
1355
|
-
partials.push({ path:
|
|
2779
|
+
partials.push({ path: path11, way });
|
|
1356
2780
|
return literal(way.end).value;
|
|
1357
2781
|
};
|
|
1358
2782
|
const literal = (entry) => {
|
|
@@ -1439,9 +2863,9 @@ function readBundle(files, systemId) {
|
|
|
1439
2863
|
const known = canonical.get(token.id);
|
|
1440
2864
|
if (!known) return canonical.set(token.id, [token]), token;
|
|
1441
2865
|
for (const other of known) {
|
|
1442
|
-
if (SCALARS.every((key) => token[key] === other[key]) &&
|
|
2866
|
+
if (SCALARS.every((key) => token[key] === other[key]) && LISTS2.every((key) => sameList(token[key], other[key])) && sameShape(token.partialAliasOf, other.partialAliasOf)) return other;
|
|
1443
2867
|
}
|
|
1444
|
-
for (const key of
|
|
2868
|
+
for (const key of LISTS2) if (sameList(token[key], known[0][key])) token[key] = known[0][key];
|
|
1445
2869
|
if (sameShape(token.partialAliasOf, known[0].partialAliasOf)) token.partialAliasOf = known[0].partialAliasOf;
|
|
1446
2870
|
known.push(token);
|
|
1447
2871
|
return token;
|
|
@@ -1470,14 +2894,14 @@ function partialAliases(entry) {
|
|
|
1470
2894
|
if (!entry.partials.length || !isObject(value)) return void 0;
|
|
1471
2895
|
const loneShadow = entry.type === "shadow" && !Array.isArray(value);
|
|
1472
2896
|
const out = Array.isArray(value) || entry.type === "shadow" ? [] : {};
|
|
1473
|
-
for (const { path:
|
|
1474
|
-
if (!
|
|
2897
|
+
for (const { path: path11, way } of entry.partials) {
|
|
2898
|
+
if (!path11.length) continue;
|
|
1475
2899
|
if (loneShadow && !out.length) out.push({});
|
|
1476
2900
|
let into = loneShadow ? out[0] : out;
|
|
1477
2901
|
let node = value;
|
|
1478
|
-
|
|
2902
|
+
path11.forEach((key, i) => {
|
|
1479
2903
|
if (isObject(node) && key in node && node[key] !== void 0) node = node[key];
|
|
1480
|
-
if (i ===
|
|
2904
|
+
if (i === path11.length - 1) into[key] = way.ids[0];
|
|
1481
2905
|
if (!(key in into)) into[key] = Array.isArray(node) ? [] : {};
|
|
1482
2906
|
into = into[key];
|
|
1483
2907
|
});
|
|
@@ -1486,11 +2910,11 @@ function partialAliases(entry) {
|
|
|
1486
2910
|
}
|
|
1487
2911
|
|
|
1488
2912
|
// ../tokens-build/src/model.js
|
|
1489
|
-
var REPO_ROOT = process.env.TANREI_VOCABULARY_ROOT ?
|
|
1490
|
-
var TOKENS_DIR =
|
|
2913
|
+
var REPO_ROOT = process.env.TANREI_VOCABULARY_ROOT ? path5.resolve(process.env.TANREI_VOCABULARY_ROOT) : path5.resolve(path5.dirname(fileURLToPath(import.meta.url)), "../../..");
|
|
2914
|
+
var TOKENS_DIR = path5.join(REPO_ROOT, "tokens");
|
|
1491
2915
|
var NS = CONFIG.namespace;
|
|
1492
2916
|
var MEMORY = new URL("file:///tanrei-bundle-in-memory/");
|
|
1493
|
-
function componentDeclarations(bundleDir, systemId, read = (name) => JSON.parse(
|
|
2917
|
+
function componentDeclarations(bundleDir, systemId, read = (name) => JSON.parse(fs4.readFileSync(path5.join(bundleDir, name), "utf8"))) {
|
|
1494
2918
|
const resolver = read(`${systemId}.resolver.json`);
|
|
1495
2919
|
const out = {};
|
|
1496
2920
|
for (const { $ref } of resolver.sets.comp?.sources ?? []) {
|
|
@@ -1510,390 +2934,165 @@ async function lintValues(tokens) {
|
|
|
1510
2934
|
if (typeof partial === "string") return written(partial);
|
|
1511
2935
|
if (!partial || value === null || typeof value !== "object") return value;
|
|
1512
2936
|
if (Array.isArray(partial) && !Array.isArray(value)) return inlined(value, partial[0]);
|
|
1513
|
-
const out = Array.isArray(value) ? [...value] : { ...value };
|
|
1514
|
-
for (const key of Object.keys(partial)) out[key] = inlined(value[key], partial[key]);
|
|
1515
|
-
return out;
|
|
1516
|
-
};
|
|
1517
|
-
const lines = ["{"];
|
|
1518
|
-
const at = [null];
|
|
1519
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1520
|
-
for (const token of Object.values(tokens)) {
|
|
1521
|
-
if (token.aliasOf) continue;
|
|
1522
|
-
const text2 = JSON.stringify({ $type: token.$type, $value: inlined(token.originalValue.$value, token.partialAliasOf) });
|
|
1523
|
-
if (linted.has(text2) || seen.has(text2)) continue;
|
|
1524
|
-
seen.set(text2, token.id);
|
|
1525
|
-
}
|
|
1526
|
-
if (!seen.size) return;
|
|
1527
|
-
[...seen].forEach(([text2, id], i) => {
|
|
1528
|
-
lines.push(`"v${i}": ${text2}${i === seen.size - 1 ? "" : ","}`);
|
|
1529
|
-
at.push(id);
|
|
1530
|
-
});
|
|
1531
|
-
lines.push("}");
|
|
1532
|
-
const { Logger, defineConfig, parse } = await import("@terrazzo/parser");
|
|
1533
|
-
class Problems extends Logger {
|
|
1534
|
-
error(...entries) {
|
|
1535
|
-
const said = entries.filter((entry) => !(entry.group === "lint" && entry.label === "lint"));
|
|
1536
|
-
throw new TokenReadError(said.map((entry) => `${at[entry.node?.loc?.start?.line - 1] ?? "a value"}: ${entry.message}${entry.group === "lint" ? ` (${entry.label})` : ""}`).join("\n"));
|
|
1537
|
-
}
|
|
1538
|
-
}
|
|
1539
|
-
const filename = new URL("values.tokens.json", MEMORY);
|
|
1540
|
-
await parse([{ filename, src: lines.join("\n") }], { config: defineConfig({}, { cwd: MEMORY }), logger: new Problems({ level: "error" }) });
|
|
1541
|
-
if (linted.size + seen.size > LINTED_AT_MOST) linted.clear();
|
|
1542
|
-
for (const text2 of seen.keys()) linted.add(text2);
|
|
1543
|
-
}
|
|
1544
|
-
var segments = (id) => id.split(".").slice(1);
|
|
1545
|
-
function simplify(token, paths) {
|
|
1546
|
-
let tokenPath = paths?.get(token.id);
|
|
1547
|
-
if (!tokenPath) paths?.set(token.id, tokenPath = segments(token.id));
|
|
1548
|
-
return simplified(token, tokenPath ?? segments(token.id));
|
|
1549
|
-
}
|
|
1550
|
-
function simplified(token, tokenPath) {
|
|
1551
|
-
return {
|
|
1552
|
-
id: token.id,
|
|
1553
|
-
path: tokenPath,
|
|
1554
|
-
// `tanrei` for the vocabulary (core and extensions inside its tree); a layer's id for its own tokens.
|
|
1555
|
-
namespace: token.id.split(".")[0],
|
|
1556
|
-
// Set on extensions: { rationale, declaredBy, extension: true, onRole? }.
|
|
1557
|
-
vocabulary: token.$extensions?.["dev.tanrei.vocabulary"],
|
|
1558
|
-
type: token.$type,
|
|
1559
|
-
value: token.$value,
|
|
1560
|
-
description: token.$description,
|
|
1561
|
-
deprecated: token.$deprecated || void 0,
|
|
1562
|
-
// Direct alias target (one hop), so emitters can keep the ref → sys → comp chain visible.
|
|
1563
|
-
alias: token.aliasChain?.[0],
|
|
1564
|
-
// The end of the alias chain (a comp token may alias another comp token that aliases a sys token).
|
|
1565
|
-
aliasFinal: token.aliasOf,
|
|
1566
|
-
partialAlias: token.partialAliasOf,
|
|
1567
|
-
// How the value is decided when it is not an alias: a rule, or { fixed: reason }.
|
|
1568
|
-
derive: token.$extensions?.["dev.tanrei.derive"],
|
|
1569
|
-
// Set on generated per-state component tokens: 'hovered' | 'focused' | 'pressed' | 'disabled'.
|
|
1570
|
-
state: token.$extensions?.["dev.tanrei.state"],
|
|
1571
|
-
// Set on a choice of kind: { values: [...] }; the value is an index into it.
|
|
1572
|
-
enum: token.$extensions?.["dev.tanrei.enum"]
|
|
1573
|
-
};
|
|
1574
|
-
}
|
|
1575
|
-
var SYS_COLOR = `${NS}.sys.color.`;
|
|
1576
|
-
var COMP = `${NS}.comp.`;
|
|
1577
|
-
var WHOLE_ALIAS = /^\{[^{}]+\}$/;
|
|
1578
|
-
function simplifyAll(set, paths) {
|
|
1579
|
-
const tokens = {};
|
|
1580
|
-
for (const [id, token] of Object.entries(set)) tokens[id] = simplify(token, paths);
|
|
1581
|
-
for (const token of Object.values(tokens)) {
|
|
1582
|
-
if (typeof token.value === "string" && WHOLE_ALIAS.test(token.value) && token.aliasFinal && tokens[token.aliasFinal]) token.value = tokens[token.aliasFinal].value;
|
|
1583
|
-
}
|
|
1584
|
-
return tokens;
|
|
1585
|
-
}
|
|
1586
|
-
function assertEveryRole(colors) {
|
|
1587
|
-
const roles = Object.keys(colors.light);
|
|
1588
|
-
for (const scheme of SCHEMES) {
|
|
1589
|
-
const missing = roles.filter((r) => !(r in colors[scheme]));
|
|
1590
|
-
if (missing.length) throw new Error(`Scheme "${scheme}" is missing color roles: ${missing.join(", ")}`);
|
|
1591
|
-
}
|
|
1592
|
-
}
|
|
1593
|
-
function partialModel(base, systemId, components, colors) {
|
|
1594
|
-
const tokens = simplifyAll(base);
|
|
1595
|
-
return { system: systemId, schemes: SCHEMES, tokens, colors, componentColors: { light: Object.fromEntries(Object.entries(tokens).filter(([id, t]) => id.startsWith(COMP) && t.type === "color")) }, components, partial: true };
|
|
1596
|
-
}
|
|
1597
|
-
async function colorsFromBundle(files, systemId = NS, reader = readBundle(files, systemId)) {
|
|
1598
|
-
const colors = {};
|
|
1599
|
-
for (const scheme of SCHEMES) {
|
|
1600
|
-
colors[scheme] = {};
|
|
1601
|
-
for (const [id, token] of Object.entries(reader.apply({ scheme }))) if (id.startsWith(SYS_COLOR)) colors[scheme][id.slice(SYS_COLOR.length)] = simplify(token);
|
|
1602
|
-
}
|
|
1603
|
-
assertEveryRole(colors);
|
|
1604
|
-
return colors;
|
|
1605
|
-
}
|
|
1606
|
-
async function invariantModel(files, systemId, light, reader) {
|
|
1607
|
-
return partialModel(light, systemId, componentDeclarations(null, systemId, (name) => files[name]), await colorsFromBundle(files, systemId, reader));
|
|
1608
|
-
}
|
|
1609
|
-
|
|
1610
|
-
// ../tokens-build/src/resolve.js
|
|
1611
|
-
import crypto2 from "node:crypto";
|
|
1612
|
-
import fs4 from "node:fs";
|
|
1613
|
-
import path5 from "node:path";
|
|
1614
|
-
|
|
1615
|
-
// ../tokens-build/src/invariants.js
|
|
1616
|
-
var lin = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
1617
|
-
var luminance2 = ({ r, g, b }) => 0.2126 * lin(r / 255) + 0.7152 * lin(g / 255) + 0.0722 * lin(b / 255);
|
|
1618
|
-
var over = (fg, bg) => ({
|
|
1619
|
-
r: fg.r * fg.a + bg.r * (1 - fg.a),
|
|
1620
|
-
g: fg.g * fg.a + bg.g * (1 - fg.a),
|
|
1621
|
-
b: fg.b * fg.a + bg.b * (1 - fg.a),
|
|
1622
|
-
a: 1
|
|
1623
|
-
});
|
|
1624
|
-
var leadWithStructure = (warnings) => [...warnings.filter((w) => !/^\[[a-z-]+\] /.test(w)), ...warnings.filter((w) => /^\[[a-z-]+\] /.test(w))];
|
|
1625
|
-
var isCriterionFinding = (finding) => /^\[[a-z-]+\] [a-z0-9-]+ on [a-z0-9-]+: \d+\.\d+:1 < \d+(\.\d+)?:1 \(/.test(finding);
|
|
1626
|
-
var PRESET_CRITERIA_NOTE = "An imitation preset is held to fidelity to the system it imitates, not to Tanrei's accessibility criteria, in every contrast scheme. These are measurements against the fixed thresholds, kept as information: they are not warnings and not mimicry gaps.";
|
|
1627
|
-
function contrast(fgColor, bgColor) {
|
|
1628
|
-
const bg = rgba(bgColor);
|
|
1629
|
-
const fg = over(rgba(fgColor), bg);
|
|
1630
|
-
const [hi, lo] = [luminance2(fg), luminance2(bg)].sort((a, b) => b - a);
|
|
1631
|
-
return (hi + 0.05) / (lo + 0.05);
|
|
1632
|
-
}
|
|
1633
|
-
var SURFACES = [
|
|
1634
|
-
"surface",
|
|
1635
|
-
"surface-dim",
|
|
1636
|
-
"surface-bright",
|
|
1637
|
-
"surface-container-lowest",
|
|
1638
|
-
"surface-container-low",
|
|
1639
|
-
"surface-container",
|
|
1640
|
-
"surface-container-high",
|
|
1641
|
-
"surface-container-highest"
|
|
1642
|
-
];
|
|
1643
|
-
var TEXT = 4.5;
|
|
1644
|
-
var NON_TEXT = 3;
|
|
1645
|
-
var STATUSES = ["info", "warning", "error", "success"];
|
|
1646
|
-
function intentsOf(roles) {
|
|
1647
|
-
return Object.keys(roles).filter((r) => [`on-${r}`, `${r}-container`, `on-${r}-container`].every((k) => k in roles));
|
|
1648
|
-
}
|
|
1649
|
-
function pairsFor(roles, focusStyle = "ring") {
|
|
1650
|
-
const intents = intentsOf(roles);
|
|
1651
|
-
const focus = focusStyle === "ring" ? "focus indicator (WCAG 2.4.13)" : `focus indicator, drawn as a ${focusStyle} (WCAG 2.4.13)`;
|
|
1652
|
-
return [
|
|
1653
|
-
...intents.flatMap((r) => [
|
|
1654
|
-
[`on-${r}`, r, TEXT, "content on filled container"],
|
|
1655
|
-
[`on-${r}-container`, `${r}-container`, TEXT, "content on tonal container"]
|
|
1656
|
-
]),
|
|
1657
|
-
...STATUSES.filter((r) => intents.includes(r)).map((r) => [r, `${r}-container`, NON_TEXT, "status mark on its tonal container (WCAG 1.4.11)"]),
|
|
1658
|
-
["inverse-on-surface", "inverse-surface", TEXT, "content on inverse surface"],
|
|
1659
|
-
// inverse-primary on inverse-surface is a snackbar's action label: text.
|
|
1660
|
-
["inverse-primary", "inverse-surface", TEXT, "accent text on inverse surface"],
|
|
1661
|
-
// A link on a surface of the opposite theme: the counterpart of `link` on the surfaces below.
|
|
1662
|
-
["inverse-link", "inverse-surface", TEXT, "inline links on inverse surface"],
|
|
1663
|
-
...SURFACES.flatMap((s) => [
|
|
1664
|
-
["on-surface", s, TEXT, "body text"],
|
|
1665
|
-
["on-surface-variant", s, TEXT, "secondary text"],
|
|
1666
|
-
["link", s, TEXT, "inline links"],
|
|
1667
|
-
...intents.map((r) => [r, s, TEXT, `${r}-colored text`]),
|
|
1668
|
-
["outline", s, NON_TEXT, "functional boundary (WCAG 1.4.11)"],
|
|
1669
|
-
["focus-ring", s, NON_TEXT, focus]
|
|
1670
|
-
])
|
|
1671
|
-
];
|
|
1672
|
-
}
|
|
1673
|
-
var tonalPairs = (roles) => ["secondary", ...STATUSES].filter((r) => `${r}-container` in roles).flatMap((r) => [
|
|
1674
|
-
["link", `${r}-container`, TEXT, "inline link on a tonal container"],
|
|
1675
|
-
["focus-ring", `${r}-container`, NON_TEXT, "focus indicator on a tonal container (WCAG 2.4.13)"]
|
|
1676
|
-
]);
|
|
1677
|
-
var HIGH_CONTRAST_TEXT = 7;
|
|
1678
|
-
var OTHER_THEME = { light: "dark", "light-medium": "dark-medium", "light-high": "dark-high", dark: "light", "dark-medium": "light-medium", "dark-high": "light-high" };
|
|
1679
|
-
var choiceOf = (model, name) => {
|
|
1680
|
-
const token = model.tokens[`${CONFIG.namespace}.sys.behavior.${name}`];
|
|
1681
|
-
return token?.enum?.values?.[token.value];
|
|
1682
|
-
};
|
|
1683
|
-
function checkInvariants(model) {
|
|
1684
|
-
const failures = [];
|
|
1685
|
-
const focusStyle = choiceOf(model, "focus-style");
|
|
1686
|
-
for (const scheme of model.schemes) {
|
|
1687
|
-
const roles = model.colors[scheme];
|
|
1688
|
-
const isHigh = scheme.endsWith("-high");
|
|
1689
|
-
const declared = Object.entries(roles).filter(([, token]) => token.vocabulary?.onRole).map(([role2, token]) => [token.vocabulary.onRole.split(".").at(-1), role2, TEXT, `content on the declared role "${role2}"`]);
|
|
1690
|
-
const tonal = model.system === CONFIG.namespace ? tonalPairs(roles) : [];
|
|
1691
|
-
for (const [fg, bg, min, why] of [...pairsFor(roles, focusStyle), ...tonal, ...declared]) {
|
|
1692
|
-
if (!roles[fg] || !roles[bg]) {
|
|
1693
|
-
failures.push(`[${scheme}] missing role for pair ${fg} / ${bg}`);
|
|
1694
|
-
continue;
|
|
1695
|
-
}
|
|
1696
|
-
const required = isHigh && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
1697
|
-
const ratio = contrast(roles[fg].value, roles[bg].value);
|
|
1698
|
-
if (ratio < required) {
|
|
1699
|
-
failures.push(`[${scheme}] ${fg} on ${bg}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
1700
|
-
}
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
if (choiceOf(model, "pressed-feedback") === "dim") {
|
|
1704
|
-
const pressed = Object.values(model.tokens).filter((t) => t.path[0] === "comp" && /(^|\.)pressed\.opacity$/.test(t.path.slice(2).join(".")));
|
|
1705
|
-
if (pressed.length && pressed.every((t) => t.value >= 1)) failures.push(`sys.behavior.pressed-feedback is "dim", but every pressed opacity is 1 (${pressed.map((t) => t.id).join(", ")}): a press would show nothing \u2014 set the pressed opacity below 1, or choose another feedback`);
|
|
1706
|
-
}
|
|
1707
|
-
for (const token of Object.values(model.tokens)) {
|
|
1708
|
-
const tier = token.path[0];
|
|
1709
|
-
if (tier === "sys" && token.path[1] === "color") {
|
|
1710
|
-
if (!token.alias) failures.push(`${token.id}: sys.color roles must alias ref.palette / ref.alpha`);
|
|
1711
|
-
} else if ((tier === "sys" || tier === "comp") && !token.alias && !token.derive) {
|
|
1712
|
-
failures.push(`${token.id}: a literal needs a rule or a stated reason for being fixed; component tokens normally alias a sys token`);
|
|
1713
|
-
}
|
|
1714
|
-
}
|
|
1715
|
-
for (const token of Object.values(model.tokens)) {
|
|
1716
|
-
if (!token.enum) continue;
|
|
1717
|
-
const names = token.enum.values;
|
|
1718
|
-
const list = (values) => (values ?? []).map((name, i) => `${name} (${i})`).join(", ");
|
|
1719
|
-
let value = token.value;
|
|
1720
|
-
if (token.alias) {
|
|
1721
|
-
const targetId = token.aliasFinal ?? token.alias;
|
|
1722
|
-
const target = model.tokens[targetId];
|
|
1723
|
-
if (!Array.isArray(target?.enum?.values)) {
|
|
1724
|
-
failures.push(`${token.id}: aliases ${targetId}, which is not a choice of kind \u2014 a choice follows another choice or is one of its own names: ${list(names)}`);
|
|
1725
|
-
continue;
|
|
1726
|
-
}
|
|
1727
|
-
if (!Array.isArray(names) || names.length !== target.enum.values.length || names.some((name, i) => name !== target.enum.values[i])) {
|
|
1728
|
-
failures.push(`${token.id}: aliases ${targetId}, whose choices differ \u2014 ${list(names)} here, ${list(target.enum.values)} there`);
|
|
1729
|
-
continue;
|
|
1730
|
-
}
|
|
1731
|
-
value = target.value;
|
|
1732
|
-
}
|
|
1733
|
-
if (!Array.isArray(names) || !Number.isInteger(value) || value < 0 || value >= names.length) failures.push(`${token.id}: ${JSON.stringify(value)} is not one of its choices \u2014 ${list(names)}`);
|
|
1734
|
-
}
|
|
1735
|
-
for (const token of Object.values(model.tokens)) {
|
|
1736
|
-
if (token.type !== "shadow" || token.alias) continue;
|
|
1737
|
-
if (!Array.isArray(token.value)) failures.push(`${token.id}: a shadow is a list of layers (an empty list draws nothing)`);
|
|
1738
|
-
else token.value.forEach((_, i) => {
|
|
1739
|
-
if (!token.partialAlias?.[i]?.color?.startsWith(`${CONFIG.namespace}.sys.color.`)) failures.push(`${token.id}: shadow layer ${i + 1} must take its color from a sys.color role`);
|
|
1740
|
-
});
|
|
1741
|
-
}
|
|
1742
|
-
for (const token of Object.values(model.tokens)) {
|
|
1743
|
-
const [tier, component, part, property, size] = token.path;
|
|
1744
|
-
if (tier !== "comp" || part !== "container" || property !== "height") continue;
|
|
1745
|
-
const at = (...rest) => model.tokens[[CONFIG.namespace, "comp", component, ...rest].join(".")];
|
|
1746
|
-
const padding = at("container", "padding-block", size)?.value?.value;
|
|
1747
|
-
const label = at("label", "typescale", size)?.value;
|
|
1748
|
-
if (padding === void 0 || !label?.fontSize) continue;
|
|
1749
|
-
const needed = 2 * padding + Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
|
|
1750
|
-
if (token.value.value < needed) failures.push(`${token.id}: ${token.value.value}px cannot hold its content \u2014 2 \xD7 padding-block (${padding}px) + one label line = ${needed}px`);
|
|
1751
|
-
}
|
|
1752
|
-
const role = (token) => {
|
|
1753
|
-
for (let at = token, hops = 0; at?.alias && hops < 16; at = model.tokens[at.alias], hops++) {
|
|
1754
|
-
if (at.alias.startsWith(`${CONFIG.namespace}.sys.color.`)) return at.alias.slice(`${CONFIG.namespace}.sys.color.`.length);
|
|
1755
|
-
}
|
|
1756
|
-
return void 0;
|
|
1757
|
-
};
|
|
1758
|
-
const short = (id) => id.slice(CONFIG.namespace.length + 1);
|
|
1759
|
-
for (const ring of Object.values(model.tokens)) {
|
|
1760
|
-
if (ring.path[0] !== "comp" || ring.type !== "color" || ring.path.at(-2) !== "focus-ring" || ring.path.at(-1) !== "color") continue;
|
|
1761
|
-
const barId = [CONFIG.namespace, ...ring.path.slice(0, -2), "container", "color"].join(".");
|
|
1762
|
-
const bar = model.tokens[barId];
|
|
1763
|
-
if (!bar) continue;
|
|
1764
|
-
const [ringRole, barRole] = [role(ring), role(bar)];
|
|
1765
|
-
for (const scheme of model.schemes) {
|
|
1766
|
-
const byRole = ringRole && barRole && model.colors[scheme][ringRole] && model.colors[scheme][barRole];
|
|
1767
|
-
const fg = byRole ? model.colors[scheme][ringRole].value : model.componentColors?.[scheme]?.[ring.id]?.value;
|
|
1768
|
-
const bg = byRole ? model.colors[scheme][barRole].value : model.componentColors?.[scheme]?.[barId]?.value;
|
|
1769
|
-
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
1770
|
-
const ratio = contrast(fg, bg);
|
|
1771
|
-
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(ring.id)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (focus indicator on the component's own bar, WCAG 2.4.13)`);
|
|
2937
|
+
const out = Array.isArray(value) ? [...value] : { ...value };
|
|
2938
|
+
for (const key of Object.keys(partial)) out[key] = inlined(value[key], partial[key]);
|
|
2939
|
+
return out;
|
|
2940
|
+
};
|
|
2941
|
+
const lines = ["{"];
|
|
2942
|
+
const at = [null];
|
|
2943
|
+
const seen = /* @__PURE__ */ new Map();
|
|
2944
|
+
for (const token of Object.values(tokens)) {
|
|
2945
|
+
if (token.aliasOf) continue;
|
|
2946
|
+
const text2 = JSON.stringify({ $type: token.$type, $value: inlined(token.originalValue.$value, token.partialAliasOf) });
|
|
2947
|
+
if (linted.has(text2) || seen.has(text2)) continue;
|
|
2948
|
+
seen.set(text2, token.id);
|
|
2949
|
+
}
|
|
2950
|
+
if (!seen.size) return;
|
|
2951
|
+
[...seen].forEach(([text2, id], i) => {
|
|
2952
|
+
lines.push(`"v${i}": ${text2}${i === seen.size - 1 ? "" : ","}`);
|
|
2953
|
+
at.push(id);
|
|
2954
|
+
});
|
|
2955
|
+
lines.push("}");
|
|
2956
|
+
const { Logger, defineConfig, parse } = await import("@terrazzo/parser");
|
|
2957
|
+
class Problems extends Logger {
|
|
2958
|
+
error(...entries) {
|
|
2959
|
+
const said = entries.filter((entry) => !(entry.group === "lint" && entry.label === "lint"));
|
|
2960
|
+
throw new TokenReadError(said.map((entry) => `${at[entry.node?.loc?.start?.line - 1] ?? "a value"}: ${entry.message}${entry.group === "lint" ? ` (${entry.label})` : ""}`).join("\n"));
|
|
1772
2961
|
}
|
|
1773
2962
|
}
|
|
1774
|
-
const
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
const
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
2963
|
+
const filename = new URL("values.tokens.json", MEMORY);
|
|
2964
|
+
await parse([{ filename, src: lines.join("\n") }], { config: defineConfig({}, { cwd: MEMORY }), logger: new Problems({ level: "error" }) });
|
|
2965
|
+
if (linted.size + seen.size > LINTED_AT_MOST) linted.clear();
|
|
2966
|
+
for (const text2 of seen.keys()) linted.add(text2);
|
|
2967
|
+
}
|
|
2968
|
+
var segments = (id) => id.split(".").slice(1);
|
|
2969
|
+
function simplify(token, paths) {
|
|
2970
|
+
let tokenPath = paths?.get(token.id);
|
|
2971
|
+
if (!tokenPath) paths?.set(token.id, tokenPath = segments(token.id));
|
|
2972
|
+
return simplified(token, tokenPath ?? segments(token.id));
|
|
2973
|
+
}
|
|
2974
|
+
function simplified(token, tokenPath) {
|
|
2975
|
+
return {
|
|
2976
|
+
id: token.id,
|
|
2977
|
+
path: tokenPath,
|
|
2978
|
+
// `tanrei` for the vocabulary (core and extensions inside its tree); a layer's id for its own tokens.
|
|
2979
|
+
namespace: token.id.split(".")[0],
|
|
2980
|
+
// Set on extensions: { rationale, declaredBy, extension: true, onRole? }.
|
|
2981
|
+
vocabulary: token.$extensions?.["dev.tanrei.vocabulary"],
|
|
2982
|
+
type: token.$type,
|
|
2983
|
+
value: token.$value,
|
|
2984
|
+
description: token.$description,
|
|
2985
|
+
// Direct alias target (one hop), so emitters can keep the ref → sys → comp chain visible.
|
|
2986
|
+
alias: token.aliasChain?.[0],
|
|
2987
|
+
// The end of the alias chain (a comp token may alias another comp token that aliases a sys token).
|
|
2988
|
+
aliasFinal: token.aliasOf,
|
|
2989
|
+
partialAlias: token.partialAliasOf,
|
|
2990
|
+
// How the value is decided when it is not an alias: a rule, or { fixed: reason }.
|
|
2991
|
+
derive: token.$extensions?.["dev.tanrei.derive"],
|
|
2992
|
+
// Set on generated per-state component tokens: 'hovered' | 'focused' | 'pressed' | 'disabled'.
|
|
2993
|
+
state: token.$extensions?.["dev.tanrei.state"],
|
|
2994
|
+
// Set on a choice of kind: { values: [...] }; the value is an index into it.
|
|
2995
|
+
enum: token.$extensions?.["dev.tanrei.enum"],
|
|
2996
|
+
// Set on a dial a padding measures from (the control height): its core default, { value, unit }.
|
|
2997
|
+
reference: token.$extensions?.["dev.tanrei.reference"],
|
|
2998
|
+
// Set on an inner corner: { outer: "{id}", inset: "{id}" }, the corner it stands in and how far inside it.
|
|
2999
|
+
concentric: token.$extensions?.["dev.tanrei.concentric"]
|
|
1781
3000
|
};
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
3001
|
+
}
|
|
3002
|
+
var floors;
|
|
3003
|
+
function coreTargetFloors() {
|
|
3004
|
+
return floors ??= targetFloors(coreComponentDocuments());
|
|
3005
|
+
}
|
|
3006
|
+
var ladder;
|
|
3007
|
+
function coreLadderReaders() {
|
|
3008
|
+
return ladder ??= ladderReaders(coreComponentDocuments());
|
|
3009
|
+
}
|
|
3010
|
+
var aligned;
|
|
3011
|
+
function coreAlignedTokens() {
|
|
3012
|
+
return aligned ??= alignedTokens(coreComponentDocuments());
|
|
3013
|
+
}
|
|
3014
|
+
var own;
|
|
3015
|
+
function coreOwnHeights() {
|
|
3016
|
+
return own ??= ownHeights(coreComponentDocuments());
|
|
3017
|
+
}
|
|
3018
|
+
var componentDocuments;
|
|
3019
|
+
function coreComponentDocuments() {
|
|
3020
|
+
if (componentDocuments) return componentDocuments;
|
|
3021
|
+
const documents = [];
|
|
3022
|
+
const read = (dir) => {
|
|
3023
|
+
if (!fs4.existsSync(dir)) return;
|
|
3024
|
+
for (const name of fs4.readdirSync(dir)) if (name.endsWith(".tokens.json")) documents.push(JSON.parse(fs4.readFileSync(path5.join(dir, name), "utf8")));
|
|
3025
|
+
};
|
|
3026
|
+
read(path5.join(TOKENS_DIR, "comp"));
|
|
3027
|
+
const systems = path5.join(TOKENS_DIR, "systems");
|
|
3028
|
+
if (fs4.existsSync(systems)) {
|
|
3029
|
+
for (const entry of fs4.readdirSync(systems, { withFileTypes: true })) if (entry.isDirectory()) read(path5.join(systems, entry.name, "comp"));
|
|
1795
3030
|
}
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
...STATES2.map((state) => [`close.${state}${form}.content.color`, `close.${state}${form}.container.color`, 1, NON_TEXT, "close glyph on its container over the bar"])
|
|
1807
|
-
];
|
|
1808
|
-
for (const [fgName, groundName, opacity, min, why] of pairs) {
|
|
1809
|
-
const [fgId, groundId] = [`${snackbar}.${fgName}`, groundName && `${snackbar}.${groundName}`];
|
|
1810
|
-
if (!model.tokens[fgId] || groundId && !model.tokens[groundId]) continue;
|
|
1811
|
-
if (!groundId && opacity === 1 && role(model.tokens[fgId]) && role(model.tokens[barId])) continue;
|
|
1812
|
-
for (const scheme of model.schemes) {
|
|
1813
|
-
const [fg, bar, ground] = [inScheme(scheme, fgId), inScheme(scheme, barId), groundId && inScheme(scheme, groundId)];
|
|
1814
|
-
if (!fg || !bar || rgba(bar).a < 1 || groundId && !ground) continue;
|
|
1815
|
-
const bg = ground ? flat(ground, bar) : bar;
|
|
1816
|
-
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
1817
|
-
const ratio = contrast(faded(fg, opacity), bg);
|
|
1818
|
-
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(groundId ?? barId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
1819
|
-
}
|
|
1820
|
-
}
|
|
3031
|
+
return componentDocuments = documents;
|
|
3032
|
+
}
|
|
3033
|
+
var SYS_COLOR = `${NS}.sys.color.`;
|
|
3034
|
+
var COMP = `${NS}.comp.`;
|
|
3035
|
+
var WHOLE_ALIAS = /^\{[^{}]+\}$/;
|
|
3036
|
+
function simplifyAll(set, paths) {
|
|
3037
|
+
const tokens = {};
|
|
3038
|
+
for (const [id, token] of Object.entries(set)) tokens[id] = simplify(token, paths);
|
|
3039
|
+
for (const token of Object.values(tokens)) {
|
|
3040
|
+
if (typeof token.value === "string" && WHOLE_ALIAS.test(token.value) && token.aliasFinal && tokens[token.aliasFinal]) token.value = tokens[token.aliasFinal].value;
|
|
1821
3041
|
}
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
const
|
|
1826
|
-
const
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
const codePairs = [
|
|
1830
|
-
...CODE_TEXT.flatMap((part) => [
|
|
1831
|
-
[`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, TEXT, "code on the block's fill"],
|
|
1832
|
-
[`${codeBlock}.${part}`, `${codeBlock}.line.highlighted.container.color`, TEXT, "code on a highlighted line's band"]
|
|
1833
|
-
]),
|
|
1834
|
-
...CODE_MARKS.map((part) => [`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, NON_TEXT, "a marked line's bar on the block's fill"]),
|
|
1835
|
-
// An outlined block has no fill: its code is read on the surface it is placed on, so a syntax color is held on
|
|
1836
|
-
// every surface role. The other text colors of the block are roles the role pairs hold there.
|
|
1837
|
-
...SYNTAX.flatMap((part) => SURFACES.map((surface) => [`${codeBlock}.${part}`, `${CONFIG.namespace}.sys.color.${surface}`, TEXT, "code in an outlined block on a surface"])),
|
|
1838
|
-
[`${inlineCode}.label.color`, `${inlineCode}.container.color`, TEXT, "inline code on its fill"]
|
|
1839
|
-
];
|
|
1840
|
-
for (const [fgId, bgId, min, why] of codePairs) {
|
|
1841
|
-
const [fgToken, bgToken] = [model.tokens[fgId], model.tokens[bgId]];
|
|
1842
|
-
if (!fgToken || !bgToken) continue;
|
|
1843
|
-
const [fgRole, bgRole] = [role(fgToken), bgId.startsWith(`${CONFIG.namespace}.sys.color.`) ? bgId.split(".").at(-1) : role(bgToken)];
|
|
1844
|
-
if (fgRole && bgRole && (held.get(`${fgRole} ${bgRole}`) ?? 0) >= min) continue;
|
|
1845
|
-
for (const scheme of model.schemes) {
|
|
1846
|
-
const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
|
|
1847
|
-
const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
|
|
1848
|
-
if (!fg || !bg || rgba(bg).a < 1) continue;
|
|
1849
|
-
const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
|
|
1850
|
-
const ratio = contrast(fg, bg);
|
|
1851
|
-
if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
|
|
1852
|
-
}
|
|
3042
|
+
return tokens;
|
|
3043
|
+
}
|
|
3044
|
+
function assertEveryRole(colors) {
|
|
3045
|
+
const roles = Object.keys(colors.light);
|
|
3046
|
+
for (const scheme of SCHEMES) {
|
|
3047
|
+
const missing = roles.filter((r) => !(r in colors[scheme]));
|
|
3048
|
+
if (missing.length) throw new Error(`Scheme "${scheme}" is missing color roles: ${missing.join(", ")}`);
|
|
1853
3049
|
}
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
for (const scheme of model.schemes) {
|
|
1871
|
-
const [fg, beside] = [colorIn(scheme, fgId), colorIn(scheme, besideId)];
|
|
1872
|
-
if (!fg || !beside || rgba(fg).a < 1 || rgba(beside).a < 1) continue;
|
|
1873
|
-
const ratio = contrast(fg, beside);
|
|
1874
|
-
if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} against ${short(besideId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why}, while ${short(choice.id)} is "${named}": a link not underlined at rest is told from text by color alone \u2014 WCAG 1.4.1; underline it always, or move the link color)`);
|
|
3050
|
+
}
|
|
3051
|
+
function partialModel(base, systemId, components, colors, otherSchemes = {}) {
|
|
3052
|
+
const tokens = simplifyAll(base);
|
|
3053
|
+
const light = Object.fromEntries(Object.entries(tokens).filter(([id, t]) => id.startsWith(COMP) && t.type === "color"));
|
|
3054
|
+
return { system: systemId, schemes: SCHEMES, tokens, colors, componentColors: { ...otherSchemes, light }, components, partial: true, floored: coreTargetFloors(), ladder: coreLadderReaders(), aligned: coreAlignedTokens(), own: coreOwnHeights() };
|
|
3055
|
+
}
|
|
3056
|
+
async function schemeColors(reader) {
|
|
3057
|
+
const colors = {};
|
|
3058
|
+
const componentColors = {};
|
|
3059
|
+
const held2 = COMPONENTS_HELD_IN_EVERY_SCHEME.map((component) => `${COMP}${component}.`);
|
|
3060
|
+
for (const scheme of SCHEMES) {
|
|
3061
|
+
colors[scheme] = {};
|
|
3062
|
+
componentColors[scheme] = {};
|
|
3063
|
+
for (const [id, token] of Object.entries(reader.apply({ scheme }))) {
|
|
3064
|
+
if (id.startsWith(SYS_COLOR)) colors[scheme][id.slice(SYS_COLOR.length)] = simplify(token);
|
|
3065
|
+
else if (token.$type === "color" && held2.some((prefix) => id.startsWith(prefix))) componentColors[scheme][id] = simplify(token);
|
|
1875
3066
|
}
|
|
1876
3067
|
}
|
|
1877
|
-
|
|
3068
|
+
assertEveryRole(colors);
|
|
3069
|
+
return { colors, componentColors };
|
|
3070
|
+
}
|
|
3071
|
+
async function invariantModel(files, systemId, light, reader) {
|
|
3072
|
+
const { colors, componentColors } = await schemeColors(reader);
|
|
3073
|
+
return partialModel(light, systemId, componentDeclarations(null, systemId, (name) => files[name]), colors, componentColors);
|
|
1878
3074
|
}
|
|
1879
3075
|
|
|
1880
3076
|
// ../tokens-build/src/resolve.js
|
|
3077
|
+
import crypto2 from "node:crypto";
|
|
3078
|
+
import fs5 from "node:fs";
|
|
3079
|
+
import path6 from "node:path";
|
|
1881
3080
|
var LAYER_SUFFIX = ".system.json";
|
|
1882
|
-
var systemIdOf = (file) =>
|
|
3081
|
+
var systemIdOf = (file) => path6.basename(file, LAYER_SUFFIX);
|
|
1883
3082
|
function localLayerFile(dir, id) {
|
|
1884
3083
|
assertSystemId(id);
|
|
1885
|
-
const file =
|
|
1886
|
-
if (!
|
|
3084
|
+
const file = path6.join(dir, `${id}${LAYER_SUFFIX}`);
|
|
3085
|
+
if (!fs5.lstatSync(file, { throwIfNoEntry: false })) return null;
|
|
1887
3086
|
const name = `${id}${LAYER_SUFFIX}`;
|
|
1888
3087
|
let real;
|
|
1889
3088
|
try {
|
|
1890
|
-
real =
|
|
3089
|
+
real = fs5.realpathSync(file);
|
|
1891
3090
|
} catch {
|
|
1892
3091
|
throw new Error(`${name}: a link that leads nowhere. A parent layer is a regular file in ${dir}`);
|
|
1893
3092
|
}
|
|
1894
|
-
const root2 =
|
|
1895
|
-
if (!real.startsWith(root2 +
|
|
1896
|
-
if (!
|
|
3093
|
+
const root2 = fs5.realpathSync(dir);
|
|
3094
|
+
if (!real.startsWith(root2 + path6.sep)) throw new Error(`${name}: a link that leaves ${dir}. A parent layer is read only from inside the directory of the product's layers`);
|
|
3095
|
+
if (!fs5.statSync(real).isFile()) throw new Error(`${name}: not a regular file`);
|
|
1897
3096
|
return file;
|
|
1898
3097
|
}
|
|
1899
3098
|
function readSystemChain({ system, layerFile, layers, dir } = {}) {
|
|
@@ -1902,17 +3101,17 @@ function readSystemChain({ system, layerFile, layers, dir } = {}) {
|
|
|
1902
3101
|
if (layers && (!Array.isArray(layers) || !layers.length || layers.some((l) => !l || typeof l !== "object" || typeof l.id !== "string" || !l.id))) throw new Error('"layers" is a non-empty list of layer objects, each with an "id"');
|
|
1903
3102
|
const inline = new Map((layers ?? []).map((layer) => [layer.id, layer]));
|
|
1904
3103
|
if (inline.size !== (layers ?? []).length) throw new Error(`"layers" names the same id twice (${(layers ?? []).map((l) => l.id).join(", ")})`);
|
|
1905
|
-
const local = dir ?? (layerFile ?
|
|
3104
|
+
const local = dir ?? (layerFile ? path6.dirname(path6.resolve(layerFile)) : null);
|
|
1906
3105
|
const shipped = new Set(listSystems(REPO_ROOT));
|
|
1907
3106
|
const id = system ?? (layerFile ? systemIdOf(layerFile) : layers.at(-1).id);
|
|
1908
3107
|
const origin = /* @__PURE__ */ new Map();
|
|
1909
3108
|
const read = (wanted) => {
|
|
1910
3109
|
if (inline.has(wanted)) return origin.set(wanted, null), inline.get(wanted);
|
|
1911
|
-
const
|
|
1912
|
-
const file = system !== void 0 ? null :
|
|
1913
|
-
if (file) return origin.set(wanted, file), JSON.parse(
|
|
1914
|
-
if (shipped.has(wanted)) return origin.set(wanted,
|
|
1915
|
-
const where = [...inline.size ? ["not among the layers passed"] : [], ...local ? [`no ${wanted}${LAYER_SUFFIX} in ${layerFile ? `the directory of ${
|
|
3110
|
+
const own2 = layerFile && wanted === id ? path6.resolve(layerFile) : null;
|
|
3111
|
+
const file = system !== void 0 ? null : own2 ? fs5.existsSync(own2) ? own2 : null : local ? localLayerFile(local, wanted) : null;
|
|
3112
|
+
if (file) return origin.set(wanted, file), JSON.parse(fs5.readFileSync(file, "utf8"));
|
|
3113
|
+
if (shipped.has(wanted)) return origin.set(wanted, path6.join(REPO_ROOT, systemPath(wanted))), loadSystem(REPO_ROOT, wanted);
|
|
3114
|
+
const where = [...inline.size ? ["not among the layers passed"] : [], ...local ? [`no ${wanted}${LAYER_SUFFIX} in ${layerFile ? `the directory of ${path6.basename(layerFile)}` : local}`] : []];
|
|
1916
3115
|
throw new Error(`system "${wanted}" not found: ${[...where, `not a shipped system (${[...shipped].join(", ")})`].join(", ")}`);
|
|
1917
3116
|
};
|
|
1918
3117
|
const wantedIds = [];
|
|
@@ -1926,6 +3125,12 @@ function validateSystem(input) {
|
|
|
1926
3125
|
const problems = [];
|
|
1927
3126
|
if (chain.at(-1).id !== id) problems.push(`${id}${LAYER_SUFFIX}: "id" must equal the file name`);
|
|
1928
3127
|
chain.forEach((layer, i) => problems.push(...validateLayerFile(REPO_ROOT, layer, fileIds[i])));
|
|
3128
|
+
const outside = outsideComponents(chain, heldComponents(listSystems(REPO_ROOT), (shipped) => loadSystem(REPO_ROOT, shipped)));
|
|
3129
|
+
chain.forEach((layer, i) => {
|
|
3130
|
+
for (const name of (layer.components?.include ?? []).filter((include) => typeof include === "string" && outside[include])) {
|
|
3131
|
+
problems.push(`${fileIds[i] ?? layer.id}${LAYER_SUFFIX} components.include: "${name}" lives in the layer "${outside[name]}", which this system does not extend \u2014 include it from there: { "name": "${name}", "from": "${outside[name]}" }`);
|
|
3132
|
+
}
|
|
3133
|
+
});
|
|
1929
3134
|
return [...new Set(problems)];
|
|
1930
3135
|
}
|
|
1931
3136
|
var chainDigest = (chain) => crypto2.createHash("sha256").update(JSON.stringify(chain)).digest("hex").slice(0, 32);
|
|
@@ -1953,14 +3158,12 @@ async function resolveChainByScheme(chain) {
|
|
|
1953
3158
|
},
|
|
1954
3159
|
load: load2,
|
|
1955
3160
|
// From the light tokens and the role colors of every scheme: the model's warnings without the model's component colors.
|
|
1956
|
-
warnings: () => warnings ??= invariantModel(files, id, reader.tokens("light"), reader).then(checkInvariants)
|
|
1957
|
-
notices: system.notices ?? []
|
|
3161
|
+
warnings: () => warnings ??= invariantModel(files, id, reader.tokens("light"), reader).then(checkInvariants)
|
|
1958
3162
|
};
|
|
1959
3163
|
}
|
|
1960
3164
|
|
|
1961
3165
|
// src/systems.js
|
|
1962
3166
|
var NS2 = CONFIG.namespace;
|
|
1963
|
-
var ROOT_SYSTEM2 = NS2;
|
|
1964
3167
|
var VOCABULARY2 = "dev.tanrei.vocabulary";
|
|
1965
3168
|
var LLM2 = "dev.tanrei.llm";
|
|
1966
3169
|
var DERIVE2 = "dev.tanrei.derive";
|
|
@@ -1970,7 +3173,7 @@ var SYS_COLOR2 = `${NS2}.sys.color.`;
|
|
|
1970
3173
|
var SEGMENT = /^[a-z0-9][a-z0-9-]*$/;
|
|
1971
3174
|
var isPlaceholder = (text2) => typeof text2 === "string" && /^\s*<[^>]*>\s*$/.test(text2);
|
|
1972
3175
|
var clone4 = (value) => JSON.parse(JSON.stringify(value));
|
|
1973
|
-
var collectVocabulary2 = (layers) => collectVocabulary(layers, { namespace: NS2 });
|
|
3176
|
+
var collectVocabulary2 = (layers, chain = layers) => collectVocabulary(layers, { namespace: NS2, lend: (id) => chain.find((layer) => layer.id === id) ?? (listSystems(REPO_ROOT).includes(id) ? loadSystem(REPO_ROOT, id) : void 0) });
|
|
1974
3177
|
var LAYER_SUFFIX2 = ".system.json";
|
|
1975
3178
|
var ToolError = class extends Error {
|
|
1976
3179
|
constructor(message, details) {
|
|
@@ -1978,7 +3181,8 @@ var ToolError = class extends Error {
|
|
|
1978
3181
|
this.details = details;
|
|
1979
3182
|
}
|
|
1980
3183
|
};
|
|
1981
|
-
var
|
|
3184
|
+
var shippedSystems2 = () => listSystems(REPO_ROOT);
|
|
3185
|
+
var listedSystems = () => shippedSystems(REPO_ROOT);
|
|
1982
3186
|
var shippedLayer = (id) => loadSystem(REPO_ROOT, id);
|
|
1983
3187
|
var isRef5 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
|
|
1984
3188
|
function matchSegments(pattern, id) {
|
|
@@ -1989,24 +3193,24 @@ function matchSegments(pattern, id) {
|
|
|
1989
3193
|
function describeReference({ system, layerFile, layer, parents, dir } = {}) {
|
|
1990
3194
|
if (layer) {
|
|
1991
3195
|
if (parents !== void 0 && (!Array.isArray(parents) || parents.some((p) => !p || typeof p !== "object" || typeof p.id !== "string"))) throw new ToolError('"parents" is a list of layer objects, each with an "id": the layers that exist only in this request and that "layer" (or another parent) extends.');
|
|
1992
|
-
if (dir !== void 0 && (typeof dir !== "string" || !
|
|
1993
|
-
return { kind: "inline", layer, parents: parents ?? [], dir: dir === void 0 ? void 0 :
|
|
3196
|
+
if (dir !== void 0 && (typeof dir !== "string" || !fs6.existsSync(path7.resolve(dir)))) throw new ToolError(`${dir}: no such directory. "dir" is where the product's other <id>${LAYER_SUFFIX2} files live.`);
|
|
3197
|
+
return { kind: "inline", layer, parents: parents ?? [], dir: dir === void 0 ? void 0 : path7.resolve(dir) };
|
|
1994
3198
|
}
|
|
1995
3199
|
if (!layerFile && typeof system === "string" && system.endsWith(LAYER_SUFFIX2)) layerFile = system;
|
|
1996
3200
|
if (layerFile) {
|
|
1997
|
-
const file =
|
|
3201
|
+
const file = path7.resolve(layerFile);
|
|
1998
3202
|
if (!file.endsWith(LAYER_SUFFIX2)) throw new ToolError(`${layerFile}: a layer file is named <id>${LAYER_SUFFIX2}`);
|
|
1999
|
-
if (!
|
|
3203
|
+
if (!fs6.existsSync(file)) throw new ToolError(`${layerFile}: no such file. Pass an absolute path, or one relative to the server's working directory (${process.cwd()}).`);
|
|
2000
3204
|
return { kind: "file", file };
|
|
2001
3205
|
}
|
|
2002
|
-
const id = system ??
|
|
2003
|
-
if (!
|
|
3206
|
+
const id = system ?? DEFAULT_SYSTEM;
|
|
3207
|
+
if (!shippedSystems2().includes(id)) throw new ToolError(`"${id}" is not a shipped system. Shipped: ${shippedSystems2().join(", ")}. For a product's own system pass "layerFile": the path of its <id>${LAYER_SUFFIX2}.`);
|
|
2004
3208
|
return { kind: "shipped", id };
|
|
2005
3209
|
}
|
|
2006
3210
|
function readChain(reference) {
|
|
2007
3211
|
const input = reference.kind === "shipped" ? { system: reference.id } : reference.kind === "file" ? { layerFile: reference.file } : { layers: [...reference.parents.filter((p) => p.id !== reference.layer.id), reference.layer], dir: reference.dir };
|
|
2008
|
-
const { id, chain, sources } = readSystemChain(input);
|
|
2009
|
-
return { id, chain, sources, input };
|
|
3212
|
+
const { id, chain, sources: sources2 } = readSystemChain(input);
|
|
3213
|
+
return { id, chain, sources: sources2, input };
|
|
2010
3214
|
}
|
|
2011
3215
|
function readLayers(input) {
|
|
2012
3216
|
const reference = describeReference(input);
|
|
@@ -2112,6 +3316,18 @@ async function withScheme(context, scheme) {
|
|
|
2112
3316
|
}
|
|
2113
3317
|
return ctx;
|
|
2114
3318
|
}
|
|
3319
|
+
function readValidLayers(input) {
|
|
3320
|
+
const reference = describeReference(input);
|
|
3321
|
+
let read;
|
|
3322
|
+
try {
|
|
3323
|
+
read = readChain(reference);
|
|
3324
|
+
} catch (error) {
|
|
3325
|
+
throw new ToolError(error.message);
|
|
3326
|
+
}
|
|
3327
|
+
const problems = layerProblems(reference, read);
|
|
3328
|
+
if (problems.length) throw new ToolError(`"${read.id}" is not a valid layer. Fix these first (validate_layer reports the same list):`, { problems });
|
|
3329
|
+
return { reference, id: read.id, chain: read.chain };
|
|
3330
|
+
}
|
|
2115
3331
|
function trialBuild(chain) {
|
|
2116
3332
|
const layer = chain.at(-1);
|
|
2117
3333
|
const problems = tidySchemaProblems(validateLayerFile(REPO_ROOT, layer, layer.id), [layer]);
|
|
@@ -2143,8 +3359,10 @@ async function assemble(id, chain) {
|
|
|
2143
3359
|
axisOf: (tokenId) => axisOf(components, tokenId),
|
|
2144
3360
|
/** { declaredBy, rationale, declaredAs? } when a layer added this token; null for core vocabulary. */
|
|
2145
3361
|
extensionOf(token) {
|
|
2146
|
-
const
|
|
2147
|
-
if (
|
|
3362
|
+
const own2 = token.$extensions?.[VOCABULARY2];
|
|
3363
|
+
if (own2?.extension) return { declaredBy: own2.declaredBy, rationale: own2.rationale };
|
|
3364
|
+
const component = extensions.find((e) => e.kind === "component" && token.id.startsWith(`${e.id}.`));
|
|
3365
|
+
if (component) return { declaredBy: component.declaredBy, rationale: component.rationale, declaredAs: component.id };
|
|
2148
3366
|
const axis = axisOf(components, token.id);
|
|
2149
3367
|
const declaration = axis && extensions.find((e) => e.id === `${axis.id}.${axis.key}`);
|
|
2150
3368
|
return declaration ? { declaredBy: declaration.declaredBy, rationale: declaration.rationale, declaredAs: declaration.id } : null;
|
|
@@ -2163,7 +3381,7 @@ async function assemble(id, chain) {
|
|
|
2163
3381
|
}
|
|
2164
3382
|
var rootIds;
|
|
2165
3383
|
async function coreIds() {
|
|
2166
|
-
rootIds ??= loadContext({ system:
|
|
3384
|
+
rootIds ??= loadContext({ system: ROOT_SYSTEM }).then((ctx) => new Map(Object.entries(ctx.tokens("light")).map(([id, token]) => [id, token.$type])));
|
|
2167
3385
|
return rootIds;
|
|
2168
3386
|
}
|
|
2169
3387
|
var INTENT_ROLES = (name) => [name, `on-${name}`, `${name}-container`, `on-${name}-container`].map((role) => `${SYS_COLOR2}${role}`);
|
|
@@ -2207,7 +3425,7 @@ function checkVocabulary(chain, reports) {
|
|
|
2207
3425
|
failed.push(id);
|
|
2208
3426
|
if (reports(layer)) problems.push(`${layer}: vocabulary: ${message}`);
|
|
2209
3427
|
};
|
|
2210
|
-
const accepted = chain.map((layer) => ({ id: layer.id, vocabulary: {} }));
|
|
3428
|
+
const accepted = chain.map((layer) => ({ id: layer.id, ...layer.components ? { components: layer.components } : {}, vocabulary: {} }));
|
|
2211
3429
|
chain.forEach((layer, i) => {
|
|
2212
3430
|
for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
|
|
2213
3431
|
if (isPlaceholder(entry?.rationale)) {
|
|
@@ -2215,16 +3433,22 @@ function checkVocabulary(chain, reports) {
|
|
|
2215
3433
|
continue;
|
|
2216
3434
|
}
|
|
2217
3435
|
try {
|
|
2218
|
-
collectVocabulary2([...accepted.slice(0, i), {
|
|
3436
|
+
collectVocabulary2([...accepted.slice(0, i), { ...accepted[i], vocabulary: { ...accepted[i].vocabulary, [id]: entry } }].map(({ components, ...rest }) => rest));
|
|
2219
3437
|
accepted[i].vocabulary[id] = entry;
|
|
2220
3438
|
} catch (error) {
|
|
2221
3439
|
fail(layer.id, id, error.message);
|
|
2222
3440
|
}
|
|
2223
3441
|
}
|
|
2224
3442
|
});
|
|
2225
|
-
const docs = clone4(sourceFiles(REPO_ROOT));
|
|
3443
|
+
const docs = clone4({ ...sourceFiles(REPO_ROOT), ...heldDocuments(REPO_ROOT) });
|
|
2226
3444
|
const known = /* @__PURE__ */ new Map();
|
|
2227
|
-
|
|
3445
|
+
let collected = {};
|
|
3446
|
+
try {
|
|
3447
|
+
collected = collectVocabulary2(accepted, chain);
|
|
3448
|
+
} catch (error) {
|
|
3449
|
+
fail(chain.at(-1).id, "components.include", error.message);
|
|
3450
|
+
}
|
|
3451
|
+
const declared = Object.entries(collected).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
|
|
2228
3452
|
for (const [id, declaration] of declared) {
|
|
2229
3453
|
if (declaration.kind === "token" && id.startsWith(SYS_COLOR2)) known.set(id, "color");
|
|
2230
3454
|
try {
|
|
@@ -2233,6 +3457,7 @@ function checkVocabulary(chain, reports) {
|
|
|
2233
3457
|
fail(declaration.declaredBy, id, error.message);
|
|
2234
3458
|
}
|
|
2235
3459
|
}
|
|
3460
|
+
for (const name of Object.keys(docs)) if (isHeldDocument(name)) delete docs[name];
|
|
2236
3461
|
for (const doc of Object.values(docs)) for (const { id, type } of walkTokens(doc)) known.set(id, type);
|
|
2237
3462
|
for (const { id, type } of expandStateVocabulary(Object.entries(docs).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc))) known.set(id, type);
|
|
2238
3463
|
return { problems, failed, known };
|
|
@@ -2245,7 +3470,7 @@ function echoesFailure(tokenId, failed) {
|
|
|
2245
3470
|
});
|
|
2246
3471
|
}
|
|
2247
3472
|
async function philosophyProblems(chain) {
|
|
2248
|
-
const shipped = new Set(
|
|
3473
|
+
const shipped = new Set(shippedSystems2());
|
|
2249
3474
|
const reports = (layerId) => !shipped.has(layerId) || layerId === chain.at(-1).id;
|
|
2250
3475
|
const vocabulary = checkVocabulary(chain, reports);
|
|
2251
3476
|
const known = new Map([...await coreIds(), ...vocabulary.known]);
|
|
@@ -2266,8 +3491,8 @@ async function philosophyProblems(chain) {
|
|
|
2266
3491
|
else if (pinsLiteral && (typeof op.reason !== "string" || op.reason.length < 8)) problems.push(`${at}: pinning a literal "$value" needs a "reason" (8+ characters): a pinned token stops following the dials, and the next person must know why.`);
|
|
2267
3492
|
else if (pinsLiteral && isPlaceholder(op.reason)) problems.push(`${at}: the "reason" is still the placeholder. Say why this value is pinned.`);
|
|
2268
3493
|
}
|
|
2269
|
-
for (const [
|
|
2270
|
-
const at = `${layer.id}: rules[${
|
|
3494
|
+
for (const [index2, rule] of (layer.rules ?? []).entries()) {
|
|
3495
|
+
const at = `${layer.id}: rules[${index2}] ${rule.match}`;
|
|
2271
3496
|
if (![...known.keys()].some((id) => matchSegments(rule.match, id)) && !vocabulary.failed.length) problems.push(`${at}: matches no token. Patterns value the per-state component tokens that exist \u2014 core ones, and those of a variant declared under "vocabulary". Interaction states themselves are not extensible.`);
|
|
2272
3497
|
if ("$value" in rule && !isRef5(rule.$value) && (typeof rule.reason !== "string" || rule.reason.length < 8)) problems.push(`${at}: a literal "$value" needs a "reason".`);
|
|
2273
3498
|
}
|
|
@@ -2290,14 +3515,236 @@ async function validateLayer2(input) {
|
|
|
2290
3515
|
if (problems.length) return { id: read.id, chain, valid: false, problems };
|
|
2291
3516
|
try {
|
|
2292
3517
|
const ctx = await loadContext(input);
|
|
2293
|
-
|
|
3518
|
+
const warnings = await ctx.warnings();
|
|
3519
|
+
const refused = warnings.filter(isRefusedEverywhere);
|
|
3520
|
+
if (refused.length) return { id: read.id, chain, valid: false, problems: refused };
|
|
3521
|
+
return { id: read.id, chain, valid: true, problems: [], tokens: Object.keys(ctx.tokens("light")).length, extensions: ctx.extensions.length, warnings };
|
|
2294
3522
|
} catch (error) {
|
|
2295
3523
|
return { id: read.id, chain, valid: false, problems: [error.message, ...error.details?.problems ?? []] };
|
|
2296
3524
|
}
|
|
2297
3525
|
}
|
|
2298
3526
|
|
|
3527
|
+
// src/components.js
|
|
3528
|
+
var PREFIX2 = `${CONFIG.web.tagPrefix}-`;
|
|
3529
|
+
var readJson = (file) => JSON.parse(fs7.readFileSync(file, "utf8"));
|
|
3530
|
+
var schema = readJson(path8.join(REPO_ROOT, "specs/component.schema.json"));
|
|
3531
|
+
var PLATFORMS = Object.keys(schema.properties.platforms.properties);
|
|
3532
|
+
var STATUSES2 = schema.$defs.platform.properties.status.enum;
|
|
3533
|
+
var LEVELS = schema.properties.level.enum;
|
|
3534
|
+
var LISTINGS = schema.properties.listing.enum;
|
|
3535
|
+
var CATEGORIES = [...new Set(readJson(path8.join(REPO_ROOT, "specs/inventory.json")).components.map((row) => row.category))].sort();
|
|
3536
|
+
var sources;
|
|
3537
|
+
function readSources() {
|
|
3538
|
+
if (sources) return sources;
|
|
3539
|
+
const catalog = readComponentCatalog(REPO_ROOT);
|
|
3540
|
+
if (!catalog) throw new ToolError("The component catalog is missing: run `pnpm generate` in the Tanrei repository.");
|
|
3541
|
+
const inventory = readJson(path8.join(REPO_ROOT, "specs/inventory.json")).components;
|
|
3542
|
+
const written = new Map(catalog.components.map(({ name }) => [name, readJson(path8.join(REPO_ROOT, "specs", `${name}.spec.json`))]));
|
|
3543
|
+
const specs = new Map([...written].map(([name, spec]) => [name, resolveFrom(spec, written)]));
|
|
3544
|
+
const categories = new Map(inventory.map((row) => [row.name, row.category]));
|
|
3545
|
+
sources = { catalog, specs, written, categories };
|
|
3546
|
+
return sources;
|
|
3547
|
+
}
|
|
3548
|
+
var shippedManifests = /* @__PURE__ */ new Map();
|
|
3549
|
+
function shippedManifest(id) {
|
|
3550
|
+
if (!shippedManifests.has(id)) {
|
|
3551
|
+
const file = path8.join(REPO_ROOT, manifestFile(id));
|
|
3552
|
+
if (!fs7.existsSync(file)) throw new ToolError(`No components manifest for "${id}" (${manifestFile(id)}): run \`pnpm generate\` in the Tanrei repository.`);
|
|
3553
|
+
const { $comment, ...manifest } = readJson(file);
|
|
3554
|
+
shippedManifests.set(id, manifest);
|
|
3555
|
+
}
|
|
3556
|
+
return shippedManifests.get(id);
|
|
3557
|
+
}
|
|
3558
|
+
var held;
|
|
3559
|
+
function manifestOf({ system, layerFile } = {}) {
|
|
3560
|
+
if (!layerFile && (system === void 0 || !system.endsWith(".system.json"))) {
|
|
3561
|
+
const id = system ?? DEFAULT_SYSTEM;
|
|
3562
|
+
if (id === ROOT_SYSTEM) throw new ToolError(`"${ROOT_SYSTEM}" is the root layer every system extends; it ships no components of its own. Pick a system: ${listedSystems().join(", ")}, or pass "layerFile" (a product's <id>.system.json).`);
|
|
3563
|
+
if (listedSystems().includes(id)) return { product: false, manifest: shippedManifest(id) };
|
|
3564
|
+
}
|
|
3565
|
+
const { reference, chain } = readValidLayers({ system, layerFile });
|
|
3566
|
+
if (reference.kind === "shipped") return { product: false, manifest: shippedManifest(reference.id) };
|
|
3567
|
+
held ??= heldComponents(listSystems(REPO_ROOT), (id) => loadSystem(REPO_ROOT, id));
|
|
3568
|
+
return { product: true, manifest: componentsManifest(chain, readSources().catalog, held, listedSystems()) };
|
|
3569
|
+
}
|
|
3570
|
+
var shippedAll = () => new Map(listedSystems().map((id) => [id, shippedManifest(id)]));
|
|
3571
|
+
var standInsFor2 = (manifest, name, product) => standInsFor({ manifest, shipped: shippedAll(), product }, name);
|
|
3572
|
+
function componentNamed(name) {
|
|
3573
|
+
const { catalog } = readSources();
|
|
3574
|
+
const { byTag, byReactName } = elementIndex(catalog);
|
|
3575
|
+
if (catalog.components.some((c) => c.name === name)) return name;
|
|
3576
|
+
const at = byTag.get(name) ?? byReactName.get(name);
|
|
3577
|
+
return at ? at.components[0] : null;
|
|
3578
|
+
}
|
|
3579
|
+
var STOP = new Set("a an and are as at be by can do for from has have i in into is it its let lets me my need of on one or our people show so some that the their them this to use user users want we what when where which with without you your".split(" "));
|
|
3580
|
+
function stem(word) {
|
|
3581
|
+
for (const ending of ["ings", "ing", "ers", "er", "ies", "es", "ed", "s"]) if (word.length - ending.length >= 3 && word.endsWith(ending)) return ending === "ies" ? `${word.slice(0, -3)}y` : word.slice(0, -ending.length);
|
|
3582
|
+
return word;
|
|
3583
|
+
}
|
|
3584
|
+
var words = (text2) => (String(text2 ?? "").toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((word) => !STOP.has(word)).map(stem);
|
|
3585
|
+
var clip = (text2, max = 200) => typeof text2 === "string" && text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
|
|
3586
|
+
function listComponents({ listing, category, level, platform = "web", status, limit = 100, offset = 0, ...reference }) {
|
|
3587
|
+
const { manifest, product } = manifestOf(reference);
|
|
3588
|
+
const { specs, categories } = readSources();
|
|
3589
|
+
const rows = manifest.components.map((entry) => {
|
|
3590
|
+
const spec = specs.get(entry.name);
|
|
3591
|
+
const variant = spec.props?.find((prop) => prop.name === "variant");
|
|
3592
|
+
return {
|
|
3593
|
+
name: entry.name,
|
|
3594
|
+
title: entry.title,
|
|
3595
|
+
category: categories.get(entry.name),
|
|
3596
|
+
level: entry.level,
|
|
3597
|
+
listing: entry.listing,
|
|
3598
|
+
summary: clip(spec.summary, 140),
|
|
3599
|
+
...entry.web ? { web: entry.web } : {},
|
|
3600
|
+
...entry.react ? { react: entry.react } : {},
|
|
3601
|
+
...entry.variants ? { variants: entry.variants, ...variant?.default !== void 0 ? { defaultVariant: variant.default } : {} } : {},
|
|
3602
|
+
status: spec.platforms?.[platform]?.status,
|
|
3603
|
+
...entry.layer !== ROOT_SYSTEM ? { layer: entry.layer } : {}
|
|
3604
|
+
};
|
|
3605
|
+
}).filter((row) => (!listing || row.listing === listing) && (!category || row.category === category) && (!level || row.level === level) && (!status || row.status === status));
|
|
3606
|
+
const slice = rows.slice(offset, offset + limit);
|
|
3607
|
+
return {
|
|
3608
|
+
system: manifest.system,
|
|
3609
|
+
chain: manifest.chain,
|
|
3610
|
+
...product ? { product: true } : {},
|
|
3611
|
+
rule: `Write UI with these components only. Anything this list does not have is not part of "${manifest.system}" \u2014 omitted names it, with what to use instead.`,
|
|
3612
|
+
total: rows.length,
|
|
3613
|
+
offset,
|
|
3614
|
+
limit,
|
|
3615
|
+
nextOffset: offset + slice.length < rows.length ? offset + slice.length : null,
|
|
3616
|
+
components: slice,
|
|
3617
|
+
omitted: manifest.omitted.map(({ name, title }) => ({ name, title, ...standInsFor2(manifest, name, product) })),
|
|
3618
|
+
omittedVariants: manifest.omittedVariants
|
|
3619
|
+
};
|
|
3620
|
+
}
|
|
3621
|
+
var SECTIONS = ["props", "events", "slots", "items", "states", "behavior", "accessibility", "example", "anatomy", "tokens", "platforms", "fixtures"];
|
|
3622
|
+
var DEFAULT_SECTIONS = ["props", "events", "slots", "items", "states", "behavior", "accessibility", "example"];
|
|
3623
|
+
function shownProp(prop, variants) {
|
|
3624
|
+
const { words: _words, ...rest } = prop;
|
|
3625
|
+
if (prop.name !== "variant" || !variants.values) return rest;
|
|
3626
|
+
return { ...rest, values: variants.values, ...variants.omitted.length ? { notInThisSystem: variants.omitted } : {} };
|
|
3627
|
+
}
|
|
3628
|
+
function exampleOf(spec, variants) {
|
|
3629
|
+
const usable = (fixture2) => !variants.values || fixture2.props?.variant === void 0 || variants.values.includes(fixture2.props.variant);
|
|
3630
|
+
const fixture = (spec.fixtures ?? []).find(usable);
|
|
3631
|
+
if (!fixture) return null;
|
|
3632
|
+
const { twin: _twin, ...shown } = fixture;
|
|
3633
|
+
return shown;
|
|
3634
|
+
}
|
|
3635
|
+
function getComponent({ name, sections = DEFAULT_SECTIONS, ...reference }) {
|
|
3636
|
+
const { manifest, product } = manifestOf(reference);
|
|
3637
|
+
const { specs, categories } = readSources();
|
|
3638
|
+
const found = componentNamed(name);
|
|
3639
|
+
if (!found) throw new ToolError(`"${name}" is not a Tanrei component. Pass a component's name ("text-field"), its element ("${PREFIX2}text-field") or its React name ("TextField"); find_component looks one up by what it is for.`, { near: nearestNames(manifest, name, 5) });
|
|
3640
|
+
const spec = specs.get(found);
|
|
3641
|
+
const entry = manifest.components.find((c) => c.name === found);
|
|
3642
|
+
const head = { name: found, title: spec.title, system: manifest.system, category: categories.get(found), level: spec.level, listing: spec.listing, summary: spec.summary };
|
|
3643
|
+
if (!entry) return { ...head, available: false, ...standInsFor2(manifest, found, product) };
|
|
3644
|
+
const variants = variantsOf(manifest, found);
|
|
3645
|
+
const out = { ...head, available: true, ...entry.web ? { web: entry.web } : {}, ...entry.react ? { react: entry.react } : {}, ...spec.builtFrom ? { builtFrom: spec.builtFrom } : {} };
|
|
3646
|
+
const want = new Set(sections);
|
|
3647
|
+
if (want.has("props")) out.props = (spec.props ?? []).map((prop) => shownProp(prop, variants));
|
|
3648
|
+
if (want.has("events") && spec.events) out.events = spec.events;
|
|
3649
|
+
if (want.has("slots") && spec.slots) out.slots = spec.slots;
|
|
3650
|
+
if (want.has("items") && spec.items) out.items = spec.items;
|
|
3651
|
+
if (want.has("states") && spec.states) out.states = spec.states;
|
|
3652
|
+
if (want.has("behavior")) out.behavior = (spec.behavior ?? []).map(({ id, text: text2 }) => ({ id, text: text2 }));
|
|
3653
|
+
if (want.has("accessibility") && spec.accessibility) out.accessibility = spec.accessibility;
|
|
3654
|
+
if (want.has("anatomy") && spec.anatomy) out.anatomy = spec.anatomy;
|
|
3655
|
+
if (want.has("tokens") && spec.tokens) out.tokens = { group: `${CONFIG.namespace}.${spec.tokens}`, find: `search_tokens { "query": "${CONFIG.namespace}.${spec.tokens}.**" }` };
|
|
3656
|
+
if (want.has("platforms")) out.platforms = spec.platforms;
|
|
3657
|
+
if (want.has("example")) {
|
|
3658
|
+
const example = exampleOf(spec, variants);
|
|
3659
|
+
if (example) out.example = { ...example, note: 'One of the fixtures the spec is tested with: the props, slots, content and items to set. "fixtures" lists them all; "platforms" names each prop on each platform.' };
|
|
3660
|
+
}
|
|
3661
|
+
if (want.has("fixtures") && spec.fixtures) out.fixtures = spec.fixtures.map(({ twin: _twin, ...fixture }) => ({ ...fixture, ...variants.values && fixture.props?.variant !== void 0 && !variants.values.includes(fixture.props.variant) ? { notInThisSystem: true } : {} }));
|
|
3662
|
+
return out;
|
|
3663
|
+
}
|
|
3664
|
+
var index;
|
|
3665
|
+
function wordIndex() {
|
|
3666
|
+
if (index) return index;
|
|
3667
|
+
const { specs, categories } = readSources();
|
|
3668
|
+
index = new Map(
|
|
3669
|
+
[...specs].map(([name, spec]) => [
|
|
3670
|
+
name,
|
|
3671
|
+
{
|
|
3672
|
+
name: /* @__PURE__ */ new Set([...words(name.replace(/-/g, " ")), ...words(spec.title)]),
|
|
3673
|
+
summary: /* @__PURE__ */ new Set([...words(spec.summary), ...words(categories.get(name)), ...words(spec.accessibility?.role)]),
|
|
3674
|
+
props: new Set((spec.props ?? []).flatMap((prop) => [...words(prop.name.replace(/([a-z])([A-Z])/g, "$1 $2")), ...words(prop.description)]))
|
|
3675
|
+
}
|
|
3676
|
+
])
|
|
3677
|
+
);
|
|
3678
|
+
return index;
|
|
3679
|
+
}
|
|
3680
|
+
function nearestNames(manifest, name, limit, { availableOnly = false } = {}) {
|
|
3681
|
+
const plain = plainName(name);
|
|
3682
|
+
const spelled = readSources().catalog.components.map((c) => [c.name, distance(plain, c.name)]).filter(([, d]) => d <= 2).sort((a, b) => a[1] - b[1]).map(([n]) => n);
|
|
3683
|
+
const names = [.../* @__PURE__ */ new Set([...spelled, ...findIn(manifest, plain.replace(/-/g, " "), limit).map((hit) => hit.name)])];
|
|
3684
|
+
return (availableOnly ? names.filter((other) => manifest.components.some((c) => c.name === other)) : names).slice(0, limit);
|
|
3685
|
+
}
|
|
3686
|
+
function findIn(manifest, need, limit) {
|
|
3687
|
+
const asked = [...new Set(words(need))];
|
|
3688
|
+
if (!asked.length) return [];
|
|
3689
|
+
const meets = (set, word) => set.has(word) || word.length >= 4 && [...set].some((other) => other.length >= 4 && (other.startsWith(word) || word.startsWith(other)));
|
|
3690
|
+
const hits = [];
|
|
3691
|
+
for (const [name, fields] of wordIndex()) {
|
|
3692
|
+
let score = 0;
|
|
3693
|
+
const matched = [];
|
|
3694
|
+
for (const word of asked) {
|
|
3695
|
+
const weight = meets(fields.name, word) ? 5 : meets(fields.summary, word) ? 2 : meets(fields.props, word) ? 1 : 0;
|
|
3696
|
+
if (weight) matched.push(word);
|
|
3697
|
+
score += weight;
|
|
3698
|
+
}
|
|
3699
|
+
if (score) hits.push({ name, score, matched, available: manifest.components.some((c) => c.name === name) });
|
|
3700
|
+
}
|
|
3701
|
+
return hits.sort((a, b) => b.score - a.score || b.matched.length - a.matched.length || a.name.localeCompare(b.name)).slice(0, limit);
|
|
3702
|
+
}
|
|
3703
|
+
function findComponent({ need, limit = 5, ...reference }) {
|
|
3704
|
+
const { manifest, product } = manifestOf(reference);
|
|
3705
|
+
const { specs } = readSources();
|
|
3706
|
+
const hits = findIn(manifest, need, 40);
|
|
3707
|
+
const listed = new Map(manifest.components.map((c) => [c.name, c]));
|
|
3708
|
+
const available = hits.filter((hit) => hit.available).slice(0, limit);
|
|
3709
|
+
const elsewhere = hits.filter((hit) => !hit.available && (!available.length || hit.score >= available.at(-1).score));
|
|
3710
|
+
return {
|
|
3711
|
+
system: manifest.system,
|
|
3712
|
+
need,
|
|
3713
|
+
components: available.map(({ name, score, matched }) => ({ ...briefComponent(listed.get(name)), summary: clip(specs.get(name).summary), score, matched })),
|
|
3714
|
+
...elsewhere.length ? { notInThisSystem: elsewhere.map(({ name, score }) => ({ name, title: specs.get(name).title, score, ...standInsFor2(manifest, name, product) })) } : {},
|
|
3715
|
+
...available.length ? { next: "get_component gives the props, events, slots, the EARS rules and an example of one." } : { next: "No component of this system matches these words: try others, or list_components for the whole list." }
|
|
3716
|
+
};
|
|
3717
|
+
}
|
|
3718
|
+
var MAX_FILES = 50;
|
|
3719
|
+
var MAX_BYTES = 1024 * 1024;
|
|
3720
|
+
function checkUsage({ code, files, path: name, ...reference }) {
|
|
3721
|
+
if (code === void 0 === (files === void 0)) throw new ToolError('Pass "code" (the text to check) or "files" (paths of files to read), not both.');
|
|
3722
|
+
const { manifest, product } = manifestOf(reference);
|
|
3723
|
+
const texts = [];
|
|
3724
|
+
if (code !== void 0) texts.push({ file: name, text: code });
|
|
3725
|
+
else {
|
|
3726
|
+
if (files.length > MAX_FILES) throw new ToolError(`At most ${MAX_FILES} files at a time.`);
|
|
3727
|
+
for (const file of files) {
|
|
3728
|
+
const full = path8.resolve(file);
|
|
3729
|
+
let stat;
|
|
3730
|
+
try {
|
|
3731
|
+
stat = fs7.statSync(full);
|
|
3732
|
+
} catch {
|
|
3733
|
+
throw new ToolError(`${file}: no such file. Pass a path absolute, or relative to the server's working directory (${process.cwd()}).`);
|
|
3734
|
+
}
|
|
3735
|
+
if (!stat.isFile()) throw new ToolError(`${file}: not a file.`);
|
|
3736
|
+
if (stat.size > MAX_BYTES) throw new ToolError(`${file}: larger than ${MAX_BYTES / 1024 / 1024} MB.`);
|
|
3737
|
+
texts.push({ file, text: fs7.readFileSync(full, "utf8") });
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
return auditTexts(auditContext(readSources().catalog, manifest, shippedAll(), { product }), texts, { near: (tag) => nearestNames(manifest, tag, 3, { availableOnly: true }) });
|
|
3741
|
+
}
|
|
3742
|
+
var COMPONENTS_URI = /^tanrei:\/\/components\/([a-z0-9-]+)$/;
|
|
3743
|
+
var componentsResource = (id) => listedSystems().includes(id) ? shippedManifest(id) : null;
|
|
3744
|
+
|
|
2299
3745
|
// src/resources.js
|
|
2300
3746
|
var INSTRUCTIONS = `Tanrei is a small, simply named core vocabulary of design tokens shipped to five platforms, which any design system can reproduce exactly: a design system is a layer file (<id>.system.json) that changes VALUES and, where the core has no word for something, EXTENDS the vocabulary.
|
|
3747
|
+
Components: first call list_components to settle the system, and use no component it does not list (omitted says what to use instead); when asked to rebuild a product with Tanrei, use system=${DEFAULT_SYSTEM}. get_component gives a component's props and its EARS rules; check_usage checks code before it is kept.
|
|
2301
3748
|
Hard rules:
|
|
2302
3749
|
- Values first. Find the existing token with search_tokens and change it in the layer, in this order of preference: set a dial, "scale" an inherited rule, re-point an alias, replace "derive", and only then pin a literal "$value" \u2014 a pinned literal needs a "reason" (8+ characters). New color families are declared under "palettes" with "roles": "intent". Never edit generated files.
|
|
2303
3750
|
- If the word really is missing, add it \u2014 in the layer, under "vocabulary", with a "rationale" (8+ characters): a step in a series, a value on a component axis (a size, a variant), or the layer's own token in its own namespace ("<layer id>.comp.\u2026"). propose_extension writes and verifies the declaration. Additive only: never re-declare, remove or retype what exists (change its value under "tokens"); interaction states are not extensible; nothing in tanrei.* may reference a layer's own token.
|
|
@@ -2317,15 +3764,15 @@ a product may want a saturated brand color and a quiet focus ring). It does not
|
|
|
2317
3764
|
nor because a component uses it today. Core changes happen only in the Tanrei repository (tokens/, lock file, review).
|
|
2318
3765
|
|
|
2319
3766
|
## Tiers and kinds
|
|
2320
|
-
Four tiers, one reference order: \`dial < ref < sys < comp\`. Components read \`comp\` tokens only.
|
|
2321
|
-
under everything: type.base 16px, type.contrast 1, space.unit 8px, size.unit 4px,
|
|
2322
|
-
motion.unit 50ms. Color seeds are palette declarations, not dials. Every value is one of three kinds:
|
|
2323
|
-
- **derived** \u2014 a rule in a closed language: \`mul
|
|
2324
|
-
\`contrast-pick\` ({ on, from: [\u2026] } \u2192 the most readable candidate, per scheme) for per-state component colors. No
|
|
3767
|
+
Four tiers, one reference order: \`dial < ref < sys < comp\`. Components read \`comp\` tokens only. Eight numeric dials sit
|
|
3768
|
+
under everything: type.base 16px, type.contrast 1, space.unit 8px, size.unit 4px, control.height 40px, shape.unit 2px,
|
|
3769
|
+
stroke.unit 1px, motion.unit 50ms. \`control.height\` is the height controls and rows are drawn at in their default size: the ladder sys.control.height.* is whole size units from it (small 32, medium 40, large 56), and a pressable height never goes below \`sys.target.minimum\`, which is no dial (36px, the developer's value). Color seeds are palette declarations, not dials. Every value is one of three kinds:
|
|
3770
|
+
- **derived** \u2014 a rule in a closed language: \`mul\` ({ of, by, exp?, round?, min? } \u2192 max(min, round(of \xD7 by^exp, round)): round a step, ties upward, min a floor after rounding), \`add\` ({ of, by, times?, min? } \u2192 max(min, of + by \xD7 times): a step a number of units from another value), \`scale\`, \`clamp\`, \`sub\` ({ of, by } \u2192 max(0, of \u2212 by): a corner inside another at an inset), \`pad\` ({ of, height, by? } \u2192 max(0, of \xD7 by + (height \u2212 height\u2081) / 2), by being 1 unless a scale multiplies it and height\u2081 being the height with no min: a block padding that gives up or takes half of what its box's height lost or gained), \`em\`; \`tone\`, \`alpha\`, \`contrast-pick\` for color roles; \`mix\`, \`alpha\`, \`tone\`,
|
|
3771
|
+
\`contrast-pick\` ({ on, from: [\u2026] } \u2192 the most readable candidate, per scheme) for per-state component colors. No other arithmetic, conditionals or user functions.
|
|
2325
3772
|
- **fixed** \u2014 a literal with a stated reason, exempt from the dials. - **alias** \u2014 a reference that can be re-pointed.
|
|
2326
3773
|
|
|
2327
3774
|
## A design system is a layer
|
|
2328
|
-
\`<id>.system.json\`: \`id\`, \`extends\` (every chain ends at the root \`tanrei\`), \`vocabulary\`, \`palettes\`, \`tokens\`, \`rules\`.
|
|
3775
|
+
\`<id>.system.json\`: \`id\`, \`extends\` (every chain ends at the root \`core\`; the default system \`tanrei\` extends it), \`vocabulary\`, \`palettes\`, \`tokens\`, \`rules\`.
|
|
2329
3776
|
**Values first.** Operations under \`tokens\`, keyed by an existing token id \u2014 prefer the earliest that does the job:
|
|
2330
3777
|
1. set a dial \`"tanrei.dial.type.base": { "$value": { "value": 17, "unit": "px" }, "reason": "\u2026" }\`
|
|
2331
3778
|
2. scale \`{ "scale": 2 }\` \u2014 N \xD7 the inherited rule or alias, still following its dial
|
|
@@ -2355,10 +3802,10 @@ available as $1, $2\u2026. An explicit \`tokens\` entry beats a pattern; fewer w
|
|
|
2355
3802
|
|
|
2356
3803
|
## Accessibility
|
|
2357
3804
|
The ruler never changes, for core and extensions alike: text 4.5:1 (7:1 in high contrast), non-text and focus 3:1, and a
|
|
2358
|
-
control's height must hold its content. These are constants in code. In the
|
|
3805
|
+
control's height must hold its content. \`sys.target.minimum\` (36px; \`sys.target.pointer\` and \`.touch\` alias it, and a layer may set them higher, never lower) and both of those are never under 24px (WCAG 2.5.8), and every pressable height the core floors at the minimum stays at or above it. These are constants in code. In the default system a violation fails the build; in
|
|
2359
3806
|
a product layer it is a warning \u2014 printed, written to a11y-report.json, stamped into every generated file. An imitation
|
|
2360
3807
|
preset is held to fidelity to its original, not to Tanrei's accessibility criteria, in every contrast scheme: its
|
|
2361
|
-
contrast is reported as measurements, not warnings; a structural or functional failure fails its build, as in the
|
|
3808
|
+
contrast is reported as measurements, not warnings; a structural or functional failure fails its build, as in the default system. Two findings fail every build, a product layer's too: \`sys.target.pointer\` or \`.touch\` under \`sys.target.minimum\`, and \`sys.target.minimum\` above \`dial.control.height\`.
|
|
2362
3809
|
|
|
2363
3810
|
## Workflow for a product
|
|
2364
3811
|
search_tokens \u2192 explain_token (\`howToChange\`, \`howToExtend\`) \u2192 propose_extension if a word is missing \u2192 edit the layer \u2192
|
|
@@ -2369,28 +3816,36 @@ function listResources() {
|
|
|
2369
3816
|
return [
|
|
2370
3817
|
{ uri: "tanrei://philosophy", name: "Tanrei philosophy", description: "The two ideals (a small core, exact reproduction), tiers and kinds, the operations a layer may perform and the three ways it may extend the vocabulary. Read once before editing a layer.", mimeType: "text/markdown" },
|
|
2371
3818
|
{ uri: "tanrei://schema/system", name: "Layer JSON Schema", description: "JSON Schema of a design system layer (<id>.system.json).", mimeType: "application/schema+json" },
|
|
2372
|
-
...
|
|
3819
|
+
...shippedSystems2().map((id) => {
|
|
2373
3820
|
const layer = shippedLayer(id);
|
|
2374
3821
|
return { uri: `tanrei://systems/${id}`, name: `System layer: ${id}`, description: `${layer.name ?? id}${layer.extends ? ` (extends ${layer.extends})` : " (root)"} \u2014 the layer file as authored. A worked example of every operation.`, mimeType: "application/json" };
|
|
2375
|
-
})
|
|
3822
|
+
}),
|
|
3823
|
+
...listedSystems().map((id) => ({ uri: `tanrei://components/${id}`, name: `Components: ${id}`, description: `The components manifest of "${id}": every component it ships with the module that registers it, those it does not have with what to use instead, and the variant values it leaves out.`, mimeType: "application/json" }))
|
|
2376
3824
|
];
|
|
2377
3825
|
}
|
|
2378
3826
|
function readResource(uri) {
|
|
2379
3827
|
if (uri === "tanrei://philosophy") return { uri, mimeType: "text/markdown", text: PHILOSOPHY };
|
|
2380
|
-
if (uri === "tanrei://schema/system") return { uri, mimeType: "application/schema+json", text:
|
|
3828
|
+
if (uri === "tanrei://schema/system") return { uri, mimeType: "application/schema+json", text: fs8.readFileSync(path9.join(REPO_ROOT, "tokens/schema/system.schema.json"), "utf8") };
|
|
2381
3829
|
const id = SYSTEM_URI.exec(uri)?.[1];
|
|
2382
|
-
if (id &&
|
|
3830
|
+
if (id && shippedSystems2().includes(id)) return { uri, mimeType: "application/json", text: fs8.readFileSync(path9.join(REPO_ROOT, "tokens/systems", `${id}.system.json`), "utf8") };
|
|
3831
|
+
const manifest = componentsResource(COMPONENTS_URI.exec(uri)?.[1]);
|
|
3832
|
+
if (manifest) return { uri, mimeType: "application/json", text: JSON.stringify(manifest) };
|
|
2383
3833
|
throw new ToolError(`unknown resource ${uri}. Known: ${listResources().map((r) => r.uri).join(", ")}`);
|
|
2384
3834
|
}
|
|
2385
3835
|
|
|
2386
3836
|
// src/tools.js
|
|
2387
|
-
import
|
|
2388
|
-
import
|
|
3837
|
+
import fs9 from "node:fs";
|
|
3838
|
+
import path10 from "node:path";
|
|
2389
3839
|
|
|
2390
3840
|
// ../tokens-build/src/emit/css.js
|
|
2391
|
-
var
|
|
2392
|
-
var varName = (
|
|
2393
|
-
var
|
|
3841
|
+
var PREFIX3 = CONFIG.web.cssPrefix;
|
|
3842
|
+
var varName = (path11) => `${PREFIX3}-${kebab(path11)}`;
|
|
3843
|
+
var VAR_NAMES = /* @__PURE__ */ new Map();
|
|
3844
|
+
var idToVar = (id) => {
|
|
3845
|
+
let name = VAR_NAMES.get(id);
|
|
3846
|
+
if (name === void 0) VAR_NAMES.set(id, name = id.startsWith(`${CONFIG.namespace}.`) ? varName(id.split(".").slice(1)) : `--${kebab(id.split("."))}`);
|
|
3847
|
+
return name;
|
|
3848
|
+
};
|
|
2394
3849
|
var CORNER = `${CONFIG.namespace}.sys.shape.corner.`;
|
|
2395
3850
|
var FULL = `${CORNER}full`;
|
|
2396
3851
|
|
|
@@ -2401,7 +3856,7 @@ var CANNOT2 = cannot(NS2);
|
|
|
2401
3856
|
var TIERS = ["dial", "ref", "sys", "comp"];
|
|
2402
3857
|
var SYS_COLOR3 = `${NS2}.sys.color.`;
|
|
2403
3858
|
var systemProperties = {
|
|
2404
|
-
system: { type: "string", description: `A shipped system id (default "${
|
|
3859
|
+
system: { type: "string", description: `A shipped system id (default "${DEFAULT_SYSTEM}"), or the path of a product's <id>.system.json.` },
|
|
2405
3860
|
layerFile: { type: "string", description: "Path of a product's <id>.system.json (absolute, or relative to the server's working directory). Wins over `system`." }
|
|
2406
3861
|
};
|
|
2407
3862
|
var schemeProperty = { type: "string", enum: SCHEMES, default: "light", description: "Theme \xD7 contrast. Only colors differ between schemes." };
|
|
@@ -2414,7 +3869,7 @@ function page(items, { offset = 0, limit }) {
|
|
|
2414
3869
|
return { total: items.length, offset, limit, nextOffset: offset + slice.length < items.length ? offset + slice.length : null, items: slice };
|
|
2415
3870
|
}
|
|
2416
3871
|
var tierOf2 = (id) => id.split(".")[1];
|
|
2417
|
-
var
|
|
3872
|
+
var clip2 = (text2, max = 140) => typeof text2 === "string" && text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
|
|
2418
3873
|
function formatValue(value) {
|
|
2419
3874
|
if (Array.isArray(value)) return value.map(formatValue);
|
|
2420
3875
|
if (!value || typeof value !== "object") return value;
|
|
@@ -2464,7 +3919,7 @@ function requireToken(ctx, id, scheme = "light") {
|
|
|
2464
3919
|
function descriptorOf(ctx, token, { kind, rule }) {
|
|
2465
3920
|
return { id: token.id, type: token.$type, value: token.$value, alias: kind === "alias" ? token.aliasChain?.[0] ?? null : null, rule: rule ?? null, state: token.$extensions?.[STATE] ?? false, axis: ctx.axisOf(token.id) ?? void 0, choices: token.$extensions?.[ENUM]?.values };
|
|
2466
3921
|
}
|
|
2467
|
-
var editableLayerId = (ctx) =>
|
|
3922
|
+
var editableLayerId = (ctx) => shippedSystems2().includes(ctx.id) ? void 0 : ctx.id;
|
|
2468
3923
|
var extensionFlags = (ctx, token) => {
|
|
2469
3924
|
const extension = ctx.extensionOf(token);
|
|
2470
3925
|
return extension ? { extension: true, declaredBy: extension.declaredBy } : {};
|
|
@@ -2475,10 +3930,10 @@ function summarizeExtensions(extensions, first = 6) {
|
|
|
2475
3930
|
return { total: extensions.length, ...extensions.length ? { byKind } : {}, first: extensions.slice(0, first).map(({ id, kind, declaredBy }) => ({ id, kind, declaredBy })) };
|
|
2476
3931
|
}
|
|
2477
3932
|
function fidelityOf(id) {
|
|
2478
|
-
const file =
|
|
2479
|
-
if (!
|
|
2480
|
-
const { equal, total, covered, different, unmapped, reference } = JSON.parse(
|
|
2481
|
-
return { equal, measured: total - covered, different: different.length, unmapped: unmapped.length, reference: { name:
|
|
3933
|
+
const file = path10.join(REPO_ROOT, "tokens/generated", id, "fidelity.json");
|
|
3934
|
+
if (!fs9.existsSync(file)) return void 0;
|
|
3935
|
+
const { equal, total, covered, different, unmapped, reference } = JSON.parse(fs9.readFileSync(file, "utf8"));
|
|
3936
|
+
return { equal, measured: total - covered, different: different.length, unmapped: unmapped.length, reference: reference.map(({ name, version, source: source2 }) => ({ name, version, source: source2 })) };
|
|
2482
3937
|
}
|
|
2483
3938
|
function summarizeLayer(layer, chain) {
|
|
2484
3939
|
const palettes = Object.entries(layer.palettes ?? {});
|
|
@@ -2498,13 +3953,13 @@ function summarizeLayer(layer, chain) {
|
|
|
2498
3953
|
async function listSystemsTool({ layerFile, warnings = true }) {
|
|
2499
3954
|
const ctx = layerFile ? await loadContext({ layerFile }) : null;
|
|
2500
3955
|
const shipped = [];
|
|
2501
|
-
for (const id of
|
|
3956
|
+
for (const id of listedSystems()) {
|
|
2502
3957
|
const summary = summarizeLayer(shippedLayer(id), readLayers({ system: id }).chain);
|
|
2503
3958
|
const fidelity = fidelityOf(id);
|
|
2504
3959
|
if (fidelity) summary.fidelity = fidelity;
|
|
2505
3960
|
if (warnings) {
|
|
2506
3961
|
const findings = await (await loadContext({ system: id })).warnings();
|
|
2507
|
-
if (id ===
|
|
3962
|
+
if (id === DEFAULT_SYSTEM) summary.accessibilityWarnings = findings.length;
|
|
2508
3963
|
else {
|
|
2509
3964
|
const failures = findings.filter((f) => !isCriterionFinding(f));
|
|
2510
3965
|
summary.accessibility = { criteria: "not-applied", measurements: findings.length - failures.length, because: PRESET_CRITERIA_NOTE, ...failures.length ? { failures } : {} };
|
|
@@ -2512,9 +3967,9 @@ async function listSystemsTool({ layerFile, warnings = true }) {
|
|
|
2512
3967
|
}
|
|
2513
3968
|
shipped.push(summary);
|
|
2514
3969
|
}
|
|
2515
|
-
const result = { root:
|
|
3970
|
+
const result = { root: ROOT_SYSTEM, default: DEFAULT_SYSTEM, schemes: SCHEMES, shipped };
|
|
2516
3971
|
if (ctx) {
|
|
2517
|
-
const known = new Set(
|
|
3972
|
+
const known = new Set(shippedSystems2());
|
|
2518
3973
|
result.product = {
|
|
2519
3974
|
id: ctx.id,
|
|
2520
3975
|
chain: ctx.chain.map((l) => l.id),
|
|
@@ -2532,8 +3987,8 @@ function matcher(query, namespaces = [NS2]) {
|
|
|
2532
3987
|
}
|
|
2533
3988
|
const rooted = namespaces.includes(query.split(".")[0]) || query.startsWith("*") ? query : `${NS2}.${query}`;
|
|
2534
3989
|
const segments2 = rooted.split(".");
|
|
2535
|
-
const
|
|
2536
|
-
const pattern = new RegExp(`^${
|
|
3990
|
+
const source2 = segments2.map((segment, i) => segment === "**" || segment === "*" && i === segments2.length - 1 && i > 0 ? ".+" : segment.replace(/[$()+?[\]^{|}\\]/g, "\\$&").replace(/\*/g, "[^.]*")).join("\\.");
|
|
3991
|
+
const pattern = new RegExp(`^${source2}$`);
|
|
2537
3992
|
return (id) => pattern.test(id);
|
|
2538
3993
|
}
|
|
2539
3994
|
async function searchTokens({ query, tier, type, kind, extensions, limit = 25, offset = 0, ...reference }) {
|
|
@@ -2547,7 +4002,7 @@ async function searchTokens({ query, tier, type, kind, extensions, limit = 25, o
|
|
|
2547
4002
|
if (kind && described !== kind) continue;
|
|
2548
4003
|
const flags = extensionFlags(ctx, token);
|
|
2549
4004
|
if (extensions !== void 0 && extensions !== Boolean(flags.extension)) continue;
|
|
2550
|
-
found.push({ id: token.id, $type: token.$type, kind: described, ...choiceOf2(token) ? { value: choiceOf2(token).value, choices: choiceOf2(token).choice.of } : {}, ...flags, description:
|
|
4005
|
+
found.push({ id: token.id, $type: token.$type, kind: described, ...choiceOf2(token) ? { value: choiceOf2(token).value, choices: choiceOf2(token).choice.of } : {}, ...flags, description: clip2(token.$description ?? ctx.meta.get(token.id)?.vocabulary?.rationale) });
|
|
2551
4006
|
}
|
|
2552
4007
|
found.sort((a, b) => a.id.localeCompare(b.id));
|
|
2553
4008
|
const { items, ...rest } = page(found, { offset, limit });
|
|
@@ -2604,7 +4059,7 @@ async function explainToken({ token: id, scheme = "light", ...reference }) {
|
|
|
2604
4059
|
const touchedBy = [];
|
|
2605
4060
|
for (const layer of ctx.chain) {
|
|
2606
4061
|
const operation = layer.tokens?.[id];
|
|
2607
|
-
const rules = precedence.rules.filter((r) => r.layer === layer.id).map(({ index, wins, because }) => ({ ...layer.rules[
|
|
4062
|
+
const rules = precedence.rules.filter((r) => r.layer === layer.id).map(({ index: index2, wins, because }) => ({ ...layer.rules[index2], index: index2, wins, because }));
|
|
2608
4063
|
const declares = palette && layer.palettes && palette in layer.palettes ? { [palette]: layer.palettes[palette] } : void 0;
|
|
2609
4064
|
if (operation || rules.length || declares) touchedBy.push({ layer: layer.id, ...operation ? { operation } : {}, ...rules.length ? { rules } : {}, ...declares ? { palette: declares } : {} });
|
|
2610
4065
|
}
|
|
@@ -2623,7 +4078,6 @@ async function explainToken({ token: id, scheme = "light", ...reference }) {
|
|
|
2623
4078
|
...rule ? { rule } : {},
|
|
2624
4079
|
cssVar: idToVar(id),
|
|
2625
4080
|
description: token.$description,
|
|
2626
|
-
...token.$deprecated ? { deprecated: token.$deprecated } : {},
|
|
2627
4081
|
// Core vocabulary, or an extension a layer of this system declared — with who declared it and why.
|
|
2628
4082
|
...extension ? { extension: true, ...extension } : {},
|
|
2629
4083
|
vocabulary: meta.vocabulary ?? null,
|
|
@@ -2632,7 +4086,7 @@ async function explainToken({ token: id, scheme = "light", ...reference }) {
|
|
|
2632
4086
|
touchedBy: touchedBy.length ? touchedBy : extension ? `No layer changes ${id} after "${extension.declaredBy}" declared it: it has the value of its declaration.` : `No layer changes ${id}: it has the default the vocabulary gives it.`,
|
|
2633
4087
|
...effective ? { effectiveOperation, ...setBy ? { setBy } : {} } : {},
|
|
2634
4088
|
// For a per-state token: the ONE pattern rule that values it (or the explicit entry that beats them all), and why.
|
|
2635
|
-
...precedence.rules.length ? { winningRule: precedence.explicit ? { explicit: true, layer: precedence.explicit.layer, because: `an explicit entry under "tokens" (layer "${precedence.explicit.layer}") beats every pattern` } : (({ layer, index, match, wildcards, because }) => ({ layer, index, match, wildcards, because }))(precedence.rules.find((r) => r.wins)) } : {},
|
|
4089
|
+
...precedence.rules.length ? { winningRule: precedence.explicit ? { explicit: true, layer: precedence.explicit.layer, because: `an explicit entry under "tokens" (layer "${precedence.explicit.layer}") beats every pattern` } : (({ layer, index: index2, match, wildcards, because }) => ({ layer, index: index2, match, wildcards, because }))(precedence.rules.find((r) => r.wins)) } : {},
|
|
2636
4090
|
usedBy: token.aliasedBy?.length ? { total: token.aliasedBy.length, first: token.aliasedBy.slice(0, 8) } : void 0,
|
|
2637
4091
|
// What follows this token: every token whose value moves when it does, through aliases and rules (transitively).
|
|
2638
4092
|
followers: { total: followers.length, first: followers.slice(0, 8) },
|
|
@@ -2665,7 +4119,7 @@ async function diffSystems({ a, b, scheme = "light", group, limit = 20, offset =
|
|
|
2665
4119
|
for (const [id, token] of Object.entries(ta)) {
|
|
2666
4120
|
if (!(id in tb)) onlyInA.push(id);
|
|
2667
4121
|
else if (JSON.stringify(formatValue(token.$value)) !== JSON.stringify(formatValue(tb[id].$value))) {
|
|
2668
|
-
const direct = [left, right].flatMap((ctx) => ctx.system.tokens[id]?.layer && ctx.system.tokens[id].layer !==
|
|
4122
|
+
const direct = [left, right].flatMap((ctx) => ctx.system.tokens[id]?.layer && ctx.system.tokens[id].layer !== ROOT_SYSTEM ? [ctx.system.tokens[id].layer] : []);
|
|
2669
4123
|
changed.push({ id, a: shownValue(token), b: shownValue(tb[id]), ...direct.length ? { setBy: [...new Set(direct)] } : {} });
|
|
2670
4124
|
}
|
|
2671
4125
|
}
|
|
@@ -2743,7 +4197,7 @@ async function proposeExtension({ kind, near, component, axis, from, value, scal
|
|
|
2743
4197
|
const into = described.kind === "shipped" ? null : chain.at(-1);
|
|
2744
4198
|
if (into && layerId && layerId !== into.id) throw new ToolError(`"layerId" (${layerId}) is not the id of ${reference.layerFile ?? reference.system} (${into.id}). Pass one of them.`);
|
|
2745
4199
|
const layer = into?.id ?? layerId ?? null;
|
|
2746
|
-
if (layer !== null && !into && (
|
|
4200
|
+
if (layer !== null && !into && (shippedSystems2().includes(layer) || !/^[a-z][a-z0-9-]*$/.test(layer))) throw new ToolError(`"${layer}" cannot be a product layer's id: lowercase letters, digits and hyphens, and not a shipped system (${shippedSystems2().join(", ")}).`);
|
|
2747
4201
|
const ctx = await loadContext(reference);
|
|
2748
4202
|
const tokens = ctx.tokens("light");
|
|
2749
4203
|
const nearToken = near ? requireToken(ctx, near) : null;
|
|
@@ -2766,16 +4220,16 @@ async function proposeExtension({ kind, near, component, axis, from, value, scal
|
|
|
2766
4220
|
if (declared.states.includes(value)) throw new ToolError(`"${value}" is an interaction state. States are not extensible: ${declared.states.join(", ")} are bound to platform behaviour, not to values. How a state LOOKS is a value \u2014 see explain_token on ${declared.id}.<variant>.${value}.container.color, or a pattern rule.`);
|
|
2767
4221
|
declaration = `${declared.id}.${axisName}.${value}`;
|
|
2768
4222
|
if (onAxis.values.includes(value)) refuseExisting(ctx, declaration, null, `Value its tokens under "tokens": search_tokens "${onAxis.members ? `${declared.id}.**.${value}` : `${declared.id}.${value}.**`}".`);
|
|
2769
|
-
const
|
|
2770
|
-
if (!onAxis.values.includes(
|
|
4223
|
+
const source2 = from ?? located?.key ?? onAxis.default;
|
|
4224
|
+
if (!onAxis.values.includes(source2)) throw new ToolError(`"from" must be an existing ${axisName} of ${componentName} (${onAxis.values.join(", ")}), not "${source2}".`);
|
|
2771
4225
|
if (scale !== void 0 && !onAxis.members) throw new ToolError(`"scale" applies to a size-like axis, whose members are numeric. A ${axisName} is cloned as it is; give its resting tokens values under "tokens".`);
|
|
2772
|
-
fragment.vocabulary[declaration] = { from:
|
|
2773
|
-
if (onAxis.members) notes.push(`One line values every member of the axis (${onAxis.members.join(", ")}) from "${
|
|
4226
|
+
fragment.vocabulary[declaration] = { from: source2, ...scale !== void 0 ? { scale } : {}, rationale: RATIONALE2 };
|
|
4227
|
+
if (onAxis.members) notes.push(`One line values every member of the axis (${onAxis.members.join(", ")}) from "${source2}"${scale !== void 0 ? ", scaled and still following the dials" : ""}. Override a single member under "tokens", e.g. "${declared.id}.${onAxis.members[0]}.${value}".`);
|
|
2774
4228
|
else {
|
|
2775
|
-
const prefix = `${declared.id}.${
|
|
4229
|
+
const prefix = `${declared.id}.${source2}.`;
|
|
2776
4230
|
const resting = Object.values(tokens).filter((t) => t.id.startsWith(prefix) && !t.$extensions?.[STATE] && t.$type === "color" && t.aliasChain?.length && !t.aliasChain[0].startsWith(prefix));
|
|
2777
4231
|
if (resting.length) fragment.tokens = Object.fromEntries(resting.map((t) => [`${declared.id}.${value}.${t.id.slice(prefix.length)}`, { $value: `{${t.aliasChain[0]}}` }]));
|
|
2778
|
-
notes.push(`"tokens" holds the resting colors of "${value}", as cloned from "${
|
|
4232
|
+
notes.push(`"tokens" holds the resting colors of "${value}", as cloned from "${source2}": re-point the ones that make it a distinct ${axisName} and delete the rest. Its ${declared.states.join(", ")} tokens are valued by the system's pattern rules.`);
|
|
2779
4233
|
}
|
|
2780
4234
|
} else {
|
|
2781
4235
|
declaration = id ?? (nearToken && value ? `${parentOf(near)}.${value}` : null);
|
|
@@ -2815,7 +4269,6 @@ async function proposeExtension({ kind, near, component, axis, from, value, scal
|
|
|
2815
4269
|
built: true,
|
|
2816
4270
|
how: `Built "${ctx.id}" + this fragment with the real pipeline (a stand-in for the rationale). Nothing was written.`,
|
|
2817
4271
|
newTokens: { total: added.length, values: Object.fromEntries(added.slice(0, 40).map((other) => [other, briefValue(after[other])])) },
|
|
2818
|
-
...trial.system.notices?.length ? { notices: trial.system.notices } : {},
|
|
2819
4272
|
// The parent is resolved once per chain digest and kept; the trial's warnings read its light tokens and role colors only.
|
|
2820
4273
|
newWarnings: (await trial.warnings()).filter((warning) => !before.has(warning))
|
|
2821
4274
|
};
|
|
@@ -2838,7 +4291,7 @@ async function proposeExtension({ kind, near, component, axis, from, value, scal
|
|
|
2838
4291
|
}
|
|
2839
4292
|
var registry;
|
|
2840
4293
|
function gapsRegistry() {
|
|
2841
|
-
registry ??= JSON.parse(
|
|
4294
|
+
registry ??= JSON.parse(fs9.readFileSync(path10.join(REPO_ROOT, "docs/governance/mimicry-gaps.json"), "utf8"));
|
|
2842
4295
|
return registry;
|
|
2843
4296
|
}
|
|
2844
4297
|
function mimicryGaps({ status, kind, system, id, limit = 10, offset = 0 }) {
|
|
@@ -2859,13 +4312,64 @@ var object = (properties, required = []) => ({ type: "object", additionalPropert
|
|
|
2859
4312
|
var TOOLS = [
|
|
2860
4313
|
{
|
|
2861
4314
|
name: "list_systems",
|
|
2862
|
-
description: "The design systems that ship with Tanrei (the
|
|
4315
|
+
description: "The design systems that ship with Tanrei (the default `tanrei` and the presets; every chain starts at the root layer `core`, which values the vocabulary and is not listed) and, with `layerFile`, a product's own layer chain. A system is a LAYER: it changes values of a small shared core vocabulary, and may EXTEND it under `vocabulary` \u2014 each system lists its extensions with the layer that declared them, and a preset measured against the published system it reproduces lists its `fidelity` (equal / measured reference tokens, how many differ or have no counterpart, and the reference). Start here.",
|
|
2863
4316
|
inputSchema: object({
|
|
2864
4317
|
layerFile: systemProperties.layerFile,
|
|
2865
4318
|
warnings: { type: "boolean", default: true, description: "Count accessibility/structure warnings per system (builds each system once; cached). For an imitation preset the count is of contrast measurements that do not apply to it, under `accessibility`." }
|
|
2866
4319
|
}),
|
|
2867
4320
|
handler: listSystemsTool
|
|
2868
4321
|
},
|
|
4322
|
+
{
|
|
4323
|
+
name: "list_components",
|
|
4324
|
+
description: `The components a system ships, from its components manifest \u2014 call it first, to settle the system, and write UI with nothing it does not list. Each component: name, title, category, level, listing (\`advanced\` = a building block that a composed component usually wraps), a short summary, the web element with the module that registers it, the React wrapper with the entry to import it from, the \`variant\` values this system offers, and each platform's status. \`omitted\` lists the components the system does not have \u2014 the layer that left each out and why, or the layer it lives in \u2014 with \`insteadUse\` (what this system ships for the same job), the shipped systems that have it and the layer line that takes it; \`omittedVariants\` the variant values it leaves out. Default system "${DEFAULT_SYSTEM}"; with \`layerFile\`, a product's system as \`tanrei build\` works it out.`,
|
|
4325
|
+
inputSchema: object({
|
|
4326
|
+
...systemProperties,
|
|
4327
|
+
listing: { type: "string", enum: LISTINGS, description: "advanced: the building blocks a composed component wraps; a product usually writes the composed one." },
|
|
4328
|
+
category: { type: "string", enum: CATEGORIES },
|
|
4329
|
+
level: { type: "string", enum: LEVELS },
|
|
4330
|
+
platform: { type: "string", enum: PLATFORMS, default: "web", description: "The platform whose status is shown, and filtered on with `status`." },
|
|
4331
|
+
status: { type: "string", enum: STATUSES2 },
|
|
4332
|
+
...pagination(100, 200)
|
|
4333
|
+
}),
|
|
4334
|
+
handler: listComponents
|
|
4335
|
+
},
|
|
4336
|
+
{
|
|
4337
|
+
name: "get_component",
|
|
4338
|
+
description: "One component as its spec describes it, for one system: its props (`variant` narrowed to the values this system offers), events, slots, the elements it holds (`items`), states, its behaviour as EARS rules each with its stable id (`BTN-1` \u2026), accessibility (role, keys, labeling), and one fixture as an example of what to set. `name` may be the component's name, its element or its React wrapper. A component the system does not have answers `available: false` with what to use instead. `sections` narrows the answer, or adds `anatomy`, `tokens`, `platforms` (each platform's names for every prop and event) and `fixtures` (all of them).",
|
|
4339
|
+
inputSchema: object(
|
|
4340
|
+
{
|
|
4341
|
+
name: { type: "string", description: 'e.g. "text-field", "tanrei-text-field" or "TextField".' },
|
|
4342
|
+
...systemProperties,
|
|
4343
|
+
sections: { type: "array", items: { type: "string", enum: SECTIONS }, uniqueItems: true, default: DEFAULT_SECTIONS, description: `Default: ${DEFAULT_SECTIONS.join(", ")}.` }
|
|
4344
|
+
},
|
|
4345
|
+
["name"]
|
|
4346
|
+
),
|
|
4347
|
+
handler: getComponent
|
|
4348
|
+
},
|
|
4349
|
+
{
|
|
4350
|
+
name: "find_component",
|
|
4351
|
+
description: 'Which component does a job: the words of `need` ("pick a date", "confirm before deleting") against each spec\'s name and title, its summary and its props, best first, among the components the system has. A component that matches as well but that the system does not have is listed apart (`notInThisSystem`), with what to use instead.',
|
|
4352
|
+
inputSchema: object(
|
|
4353
|
+
{
|
|
4354
|
+
need: { type: "string", minLength: 2, description: "What the UI has to do, in plain English." },
|
|
4355
|
+
...systemProperties,
|
|
4356
|
+
limit: { type: "integer", minimum: 1, maximum: 20, default: 5 }
|
|
4357
|
+
},
|
|
4358
|
+
["need"]
|
|
4359
|
+
),
|
|
4360
|
+
handler: findComponent
|
|
4361
|
+
},
|
|
4362
|
+
{
|
|
4363
|
+
name: "check_usage",
|
|
4364
|
+
description: "Check code against a system's components manifest \u2014 the check `tanrei audit` runs: every element (`<tanrei-\u2026>`, a tag in a string, an imported React wrapper) and every CSS selector naming an element of a component the system does not have; every import of an entry that does not fit the system (another system's, or the one of every component), of a web module or of a React wrapper it does not have; and every literal `variant` the system leaves out. Each with its file, line and column, why, and what to write instead (`insteadUse` for a component, also the shipped systems that have it and the layer line that takes it into a product; `use` for an import; `values` for a variant). An unknown `tanrei-` element is reported with the nearest components. Comments are skipped. It reads the text, not a syntax tree: a variant set from a variable is not seen. Pass `code` (with `path`, whose extension says how to read it: .html, .css, or script by default) or `files`. Reads, never writes.",
|
|
4365
|
+
inputSchema: object({
|
|
4366
|
+
code: { type: "string", maxLength: 1048576, description: "Source text: HTML, a template, JSX/TSX, Vue, Svelte\u2026" },
|
|
4367
|
+
path: { type: "string", description: "With `code`: the name findings carry as `file`; its extension says how to read the text (.html, .vue, .svelte and .astro as markup, .css, .scss and .less as a stylesheet, anything else as script)." },
|
|
4368
|
+
files: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 50, description: "Paths of files to read (absolute, or relative to the server's working directory)." },
|
|
4369
|
+
...systemProperties
|
|
4370
|
+
}),
|
|
4371
|
+
handler: checkUsage
|
|
4372
|
+
},
|
|
2869
4373
|
{
|
|
2870
4374
|
name: "search_tokens",
|
|
2871
4375
|
description: `Find tokens of the vocabulary by id. \`query\` is a case-insensitive substring, or a glob when it contains \`*\`: \`*\` matches within one segment, \`**\` any number of segments (e.g. \`${NS2}.comp.button.*.hovered.*\`, \`sys.color.on-*\`, \`**.opacity\`). A layer's own tokens are found by their namespace (\`acme.comp.*\`). Returns id, $type, kind (derived | fixed | alias | dial), \`extension: true\` + \`declaredBy\` for vocabulary a layer added, and a short description, paginated. A choice of kind (\`sys.behavior.*\`) shows the NAME it has and the names it may take. Search before concluding a token is missing; if it really is, propose_extension adds it.`,
|
|
@@ -2915,7 +4419,7 @@ var TOOLS = [
|
|
|
2915
4419
|
},
|
|
2916
4420
|
{
|
|
2917
4421
|
name: "validate_layer",
|
|
2918
|
-
description:
|
|
4422
|
+
description: `Check a product layer before it is saved or built: JSON Schema; then every problem at once, with the way out \u2014 \`vocabulary\` declarations as the engine judges them (a rationale, the layer's own namespace, declared once, an existing axis and \`from\`, never an interaction state), ids under \`tokens\`/\`rules\` that are neither core nor declared (declare them, or use the token that exists), a pinned literal without a \`reason\`, a \`$type\` change, leftover placeholders; then the real build, which is the final authority, and what it refuses in every layer: \`${NS2}.sys.target.pointer\` or \`.touch\` under \`${NS2}.sys.target.minimum\` (they alias it; set them higher, never lower), and \`${NS2}.sys.target.minimum\` above \`${NS2}.dial.control.height\`. If valid, returns the accessibility/structure warnings \`tanrei build\` would print \u2014 among them \`sys.target.minimum\`, \`.pointer\` or \`.touch\` under 24px (WCAG 2.5.8) and a pressable height under \`sys.target.minimum\` (no size step draws one lower; derive it with \`"min": "{${NS2}.sys.target.minimum}"\`, or lower the minimum). Writes nothing.`,
|
|
2919
4423
|
inputSchema: object({
|
|
2920
4424
|
layer: { type: "object", description: 'The layer as JSON: { "id", "extends", "vocabulary", "palettes", "tokens", "rules" }. It may extend a shipped system, a layer passed in "parents", or a layer file in "dir".' },
|
|
2921
4425
|
parents: { type: "array", items: { type: "object" }, maxItems: 8, description: 'With "layer": other layers that exist only in this request and that the layer (or another parent) extends \u2014 a product that stacks its own layers. Any order; each needs an "id". They are validated too.' },
|
|
@@ -2962,7 +4466,7 @@ var TOOLS = [
|
|
|
2962
4466
|
];
|
|
2963
4467
|
|
|
2964
4468
|
// src/server.js
|
|
2965
|
-
var VERSION = JSON.parse(
|
|
4469
|
+
var VERSION = JSON.parse(fs10.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
2966
4470
|
var ajv = new Ajv20202({ allErrors: true, strict: false, useDefaults: true });
|
|
2967
4471
|
var tools = new Map(TOOLS.map((tool) => [tool.name, { ...tool, validate: ajv.compile(tool.inputSchema) }]));
|
|
2968
4472
|
var text = (value, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(value) }], ...isError ? { isError: true } : {} });
|
|
@@ -2986,7 +4490,10 @@ function createServer() {
|
|
|
2986
4490
|
server.setRequestHandler(CallToolRequestSchema, async (request) => callTool(request.params.name, request.params.arguments));
|
|
2987
4491
|
server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: listResources() }));
|
|
2988
4492
|
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
|
|
2989
|
-
resourceTemplates: [
|
|
4493
|
+
resourceTemplates: [
|
|
4494
|
+
{ uriTemplate: "tanrei://systems/{id}", name: "System layer", description: "The layer file of a shipped system, as authored.", mimeType: "application/json" },
|
|
4495
|
+
{ uriTemplate: "tanrei://components/{id}", name: "Components manifest", description: "The components a shipped system ships, those it does not have, and the variant values it leaves out.", mimeType: "application/json" }
|
|
4496
|
+
]
|
|
2990
4497
|
}));
|
|
2991
4498
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
2992
4499
|
try {
|