@wix/web5-core 1.63.1 → 1.63.3
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/dist/cjs/client/applyThemeOverrides.js +38 -13
- package/dist/cjs/client/applyThemeOverrides.js.map +1 -1
- package/dist/cjs/client/themeDebug.js +26 -7
- package/dist/cjs/client/themeDebug.js.map +1 -1
- package/dist/cjs/index.js +8 -3
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/theme/colorFormat.js +105 -0
- package/dist/cjs/theme/colorFormat.js.map +1 -0
- package/dist/cjs/theme/tokenContract.js +32 -8
- package/dist/cjs/theme/tokenContract.js.map +1 -1
- package/dist/esm/client/applyThemeOverrides.js +38 -13
- package/dist/esm/client/applyThemeOverrides.js.map +1 -1
- package/dist/esm/client/themeDebug.js +28 -9
- package/dist/esm/client/themeDebug.js.map +1 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/theme/colorFormat.js +99 -0
- package/dist/esm/theme/colorFormat.js.map +1 -0
- package/dist/esm/theme/tokenContract.js +34 -7
- package/dist/esm/theme/tokenContract.js.map +1 -1
- package/dist/types/client/applyThemeOverrides.d.ts +1 -1
- package/dist/types/client/applyThemeOverrides.d.ts.map +1 -1
- package/dist/types/client/themeDebug.d.ts +10 -1
- package/dist/types/client/themeDebug.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/theme/colorFormat.d.ts +35 -0
- package/dist/types/theme/colorFormat.d.ts.map +1 -0
- package/dist/types/theme/tokenContract.d.ts +13 -0
- package/dist/types/theme/tokenContract.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
exports.hexToHslTriplet = hexToHslTriplet;
|
|
5
|
+
exports.hslTripletToHex = hslTripletToHex;
|
|
6
|
+
exports.isHslTriplet = isHslTriplet;
|
|
7
|
+
/**
|
|
8
|
+
* Between the two spellings of a colour: the token's and the colour input's.
|
|
9
|
+
*
|
|
10
|
+
* A theme token is an HSL triplet with no wrapper — `262 83% 58%` — because the
|
|
11
|
+
* core bridge supplies the wrapper (`--color-primary: hsl(var(--primary))`), so
|
|
12
|
+
* a token carrying `hsl(...)` or a hex value produces `hsl(#7c3aed)` and the
|
|
13
|
+
* whole role falls back to nothing. `<input type="color">` speaks only
|
|
14
|
+
* `#rrggbb`. The owner panel therefore has to translate on every read and every
|
|
15
|
+
* write, and getting it wrong is invisible until a merchant's brand colour
|
|
16
|
+
* quietly stops applying.
|
|
17
|
+
*
|
|
18
|
+
* Round-tripping is deliberately NOT exact, and cannot be: 16.7M hex values map
|
|
19
|
+
* onto an HSL space this rounds to one decimal, so `hex → triplet → hex` can
|
|
20
|
+
* land a step away. What IS guaranteed is that the triplet is well-formed and
|
|
21
|
+
* within gamut, which is what the CSS needs; a merchant dragging a picker never
|
|
22
|
+
* sees the difference, and nothing downstream compares two colours for equality.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** `262 83% 58%` — the only spelling a colour token may carry. */
|
|
26
|
+
const TRIPLET = /^(\d{1,3}(?:\.\d+)?)\s+(\d{1,3}(?:\.\d+)?)%\s+(\d{1,3}(?:\.\d+)?)%$/;
|
|
27
|
+
const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
|
|
28
|
+
|
|
29
|
+
/** Trims to one decimal without leaving `58.0` behind. */
|
|
30
|
+
const round = n => String(Math.round(n * 10) / 10);
|
|
31
|
+
|
|
32
|
+
/** Whether a value is a bare HSL triplet — the shape a colour token must carry. */
|
|
33
|
+
function isHslTriplet(value) {
|
|
34
|
+
const parts = TRIPLET.exec(value.trim());
|
|
35
|
+
if (!parts) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
const [, h, s, l] = parts;
|
|
39
|
+
return Number(h) <= 360 && Number(s) <= 100 && Number(l) <= 100;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `#7c3aed` → `262.1 83.3% 57.8%`.
|
|
44
|
+
*
|
|
45
|
+
* Returns null for anything that is not a 3- or 6-digit hex colour, so a caller
|
|
46
|
+
* writing a token can refuse rather than store a value CSS will drop.
|
|
47
|
+
*/
|
|
48
|
+
function hexToHslTriplet(hex) {
|
|
49
|
+
const raw = hex.trim().replace(/^#/, '');
|
|
50
|
+
const full = raw.length === 3 ? raw.split('').map(c => c + c).join('') : raw;
|
|
51
|
+
if (!/^[0-9a-fA-F]{6}$/.test(full)) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const r = parseInt(full.slice(0, 2), 16) / 255;
|
|
55
|
+
const g = parseInt(full.slice(2, 4), 16) / 255;
|
|
56
|
+
const b = parseInt(full.slice(4, 6), 16) / 255;
|
|
57
|
+
const max = Math.max(r, g, b);
|
|
58
|
+
const min = Math.min(r, g, b);
|
|
59
|
+
const l = (max + min) / 2;
|
|
60
|
+
const d = max - min;
|
|
61
|
+
|
|
62
|
+
// Grey: hue and saturation are both meaningless, and any hue would do. Zero
|
|
63
|
+
// is the conventional answer and keeps the value stable across edits.
|
|
64
|
+
if (d === 0) {
|
|
65
|
+
return `0 0% ${round(l * 100)}%`;
|
|
66
|
+
}
|
|
67
|
+
const s = d / (1 - Math.abs(2 * l - 1));
|
|
68
|
+
let h;
|
|
69
|
+
if (max === r) {
|
|
70
|
+
h = (g - b) / d % 6;
|
|
71
|
+
} else if (max === g) {
|
|
72
|
+
h = (b - r) / d + 2;
|
|
73
|
+
} else {
|
|
74
|
+
h = (r - g) / d + 4;
|
|
75
|
+
}
|
|
76
|
+
h *= 60;
|
|
77
|
+
if (h < 0) {
|
|
78
|
+
h += 360;
|
|
79
|
+
}
|
|
80
|
+
return `${round(h)} ${round(s * 100)}% ${round(l * 100)}%`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* `262 83% 58%` → `#7c3aed`, for seeding a colour input.
|
|
85
|
+
*
|
|
86
|
+
* Returns null rather than a guess when the value is not a triplet — a token
|
|
87
|
+
* holding something else is a bug worth seeing as a blank control rather than
|
|
88
|
+
* as an arbitrary colour the merchant did not choose.
|
|
89
|
+
*/
|
|
90
|
+
function hslTripletToHex(triplet) {
|
|
91
|
+
const parts = TRIPLET.exec(triplet.trim());
|
|
92
|
+
if (!parts) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
const h = clamp(Number(parts[1]), 0, 360);
|
|
96
|
+
const s = clamp(Number(parts[2]), 0, 100) / 100;
|
|
97
|
+
const l = clamp(Number(parts[3]), 0, 100) / 100;
|
|
98
|
+
const c = (1 - Math.abs(2 * l - 1)) * s;
|
|
99
|
+
const x = c * (1 - Math.abs(h / 60 % 2 - 1));
|
|
100
|
+
const m = l - c / 2;
|
|
101
|
+
const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
|
|
102
|
+
const channel = v => Math.round((v + m) * 255).toString(16).padStart(2, '0');
|
|
103
|
+
return `#${channel(r)}${channel(g)}${channel(b)}`;
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=colorFormat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["TRIPLET","clamp","n","min","max","Math","round","String","isHslTriplet","value","parts","exec","trim","h","s","l","Number","hexToHslTriplet","hex","raw","replace","full","length","split","map","c","join","test","r","parseInt","slice","g","b","d","abs","hslTripletToHex","triplet","x","m","channel","v","toString","padStart"],"sources":["../../../src/theme/colorFormat.ts"],"sourcesContent":["/**\n * Between the two spellings of a colour: the token's and the colour input's.\n *\n * A theme token is an HSL triplet with no wrapper — `262 83% 58%` — because the\n * core bridge supplies the wrapper (`--color-primary: hsl(var(--primary))`), so\n * a token carrying `hsl(...)` or a hex value produces `hsl(#7c3aed)` and the\n * whole role falls back to nothing. `<input type=\"color\">` speaks only\n * `#rrggbb`. The owner panel therefore has to translate on every read and every\n * write, and getting it wrong is invisible until a merchant's brand colour\n * quietly stops applying.\n *\n * Round-tripping is deliberately NOT exact, and cannot be: 16.7M hex values map\n * onto an HSL space this rounds to one decimal, so `hex → triplet → hex` can\n * land a step away. What IS guaranteed is that the triplet is well-formed and\n * within gamut, which is what the CSS needs; a merchant dragging a picker never\n * sees the difference, and nothing downstream compares two colours for equality.\n */\n\n/** `262 83% 58%` — the only spelling a colour token may carry. */\nconst TRIPLET = /^(\\d{1,3}(?:\\.\\d+)?)\\s+(\\d{1,3}(?:\\.\\d+)?)%\\s+(\\d{1,3}(?:\\.\\d+)?)%$/;\n\nconst clamp = (n: number, min: number, max: number): number =>\n Math.min(max, Math.max(min, n));\n\n/** Trims to one decimal without leaving `58.0` behind. */\nconst round = (n: number): string => String(Math.round(n * 10) / 10);\n\n/** Whether a value is a bare HSL triplet — the shape a colour token must carry. */\nexport function isHslTriplet(value: string): boolean {\n const parts = TRIPLET.exec(value.trim());\n if (!parts) {\n return false;\n }\n const [, h, s, l] = parts;\n return Number(h) <= 360 && Number(s) <= 100 && Number(l) <= 100;\n}\n\n/**\n * `#7c3aed` → `262.1 83.3% 57.8%`.\n *\n * Returns null for anything that is not a 3- or 6-digit hex colour, so a caller\n * writing a token can refuse rather than store a value CSS will drop.\n */\nexport function hexToHslTriplet(hex: string): string | null {\n const raw = hex.trim().replace(/^#/, '');\n const full =\n raw.length === 3\n ? raw\n .split('')\n .map((c) => c + c)\n .join('')\n : raw;\n if (!/^[0-9a-fA-F]{6}$/.test(full)) {\n return null;\n }\n\n const r = parseInt(full.slice(0, 2), 16) / 255;\n const g = parseInt(full.slice(2, 4), 16) / 255;\n const b = parseInt(full.slice(4, 6), 16) / 255;\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n const d = max - min;\n\n // Grey: hue and saturation are both meaningless, and any hue would do. Zero\n // is the conventional answer and keeps the value stable across edits.\n if (d === 0) {\n return `0 0% ${round(l * 100)}%`;\n }\n\n const s = d / (1 - Math.abs(2 * l - 1));\n let h: number;\n if (max === r) {\n h = ((g - b) / d) % 6;\n } else if (max === g) {\n h = (b - r) / d + 2;\n } else {\n h = (r - g) / d + 4;\n }\n h *= 60;\n if (h < 0) {\n h += 360;\n }\n\n return `${round(h)} ${round(s * 100)}% ${round(l * 100)}%`;\n}\n\n/**\n * `262 83% 58%` → `#7c3aed`, for seeding a colour input.\n *\n * Returns null rather than a guess when the value is not a triplet — a token\n * holding something else is a bug worth seeing as a blank control rather than\n * as an arbitrary colour the merchant did not choose.\n */\nexport function hslTripletToHex(triplet: string): string | null {\n const parts = TRIPLET.exec(triplet.trim());\n if (!parts) {\n return null;\n }\n const h = clamp(Number(parts[1]), 0, 360);\n const s = clamp(Number(parts[2]), 0, 100) / 100;\n const l = clamp(Number(parts[3]), 0, 100) / 100;\n\n const c = (1 - Math.abs(2 * l - 1)) * s;\n const x = c * (1 - Math.abs(((h / 60) % 2) - 1));\n const m = l - c / 2;\n\n const [r, g, b] =\n h < 60\n ? [c, x, 0]\n : h < 120\n ? [x, c, 0]\n : h < 180\n ? [0, c, x]\n : h < 240\n ? [0, x, c]\n : h < 300\n ? [x, 0, c]\n : [c, 0, x];\n\n const channel = (v: number): string =>\n Math.round((v + m) * 255)\n .toString(16)\n .padStart(2, '0');\n\n return `#${channel(r)}${channel(g)}${channel(b)}`;\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,MAAMA,OAAO,GAAG,qEAAqE;AAErF,MAAMC,KAAK,GAAGA,CAACC,CAAS,EAAEC,GAAW,EAAEC,GAAW,KAChDC,IAAI,CAACF,GAAG,CAACC,GAAG,EAAEC,IAAI,CAACD,GAAG,CAACD,GAAG,EAAED,CAAC,CAAC,CAAC;;AAEjC;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,CAAC,GACTZ,CAAC,GAAG,GAAG,GACP,CAACwB,CAAC,EAAE,CAAC,EAAEZ,CAAC,CAAC,GACT,CAACA,CAAC,EAAE,CAAC,EAAEY,CAAC,CAAC;EAEf,MAAME,OAAO,GAAIC,CAAS,IACxBnC,IAAI,CAACC,KAAK,CAAC,CAACkC,CAAC,GAAGF,CAAC,IAAI,GAAG,CAAC,CACtBG,QAAQ,CAAC,EAAE,CAAC,CACZC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;EAErB,OAAO,IAAIH,OAAO,CAACX,CAAC,CAAC,GAAGW,OAAO,CAACR,CAAC,CAAC,GAAGQ,OAAO,CAACP,CAAC,CAAC,EAAE;AACnD","ignoreList":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
exports.__esModule = true;
|
|
4
|
-
exports.TOKEN_NAME_PATTERN = exports.THEME_TOKEN_CONTRACT = exports.BRAND_TOKENS = void 0;
|
|
4
|
+
exports.TOKEN_NAME_PATTERN = exports.THEME_TOKEN_CONTRACT = exports.EDITABLE_TOKENS = exports.BRAND_TOKENS = void 0;
|
|
5
5
|
exports.bucketOf = bucketOf;
|
|
6
6
|
exports.hostAliasFor = hostAliasFor;
|
|
7
7
|
/**
|
|
@@ -64,10 +64,23 @@ exports.hostAliasFor = hostAliasFor;
|
|
|
64
64
|
|
|
65
65
|
/** Which layer wins when both a store and a template state this token. */
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* A colour role. Giving one a label is what puts it in the owner's panel.
|
|
69
|
+
*
|
|
70
|
+
* The two travel together on purpose: `editable` without a label is a control
|
|
71
|
+
* with no name, and a label on a token nobody may set is a promise the panel
|
|
72
|
+
* cannot keep. One argument, one decision.
|
|
73
|
+
*
|
|
74
|
+
* Labels are the merchant's words rather than the token's — "Buttons & links",
|
|
75
|
+
* not "primary". Someone choosing their shop's colours is not reading a design
|
|
76
|
+
* system, and `--primary-foreground` is not a colour anyone picks: it is
|
|
77
|
+
* whatever stays legible ON primary, which the theme derives. Exposing the
|
|
78
|
+
* derived half is how a panel produces white text on a white button.
|
|
79
|
+
*/
|
|
67
80
|
const brandColor = label => ({
|
|
68
81
|
bucket: 'brand',
|
|
69
82
|
type: 'color-hsl',
|
|
70
|
-
editable:
|
|
83
|
+
editable: label !== undefined,
|
|
71
84
|
...(label === undefined ? {} : {
|
|
72
85
|
label
|
|
73
86
|
})
|
|
@@ -84,21 +97,21 @@ const brandColor = label => ({
|
|
|
84
97
|
*/
|
|
85
98
|
const THEME_TOKEN_CONTRACT = exports.THEME_TOKEN_CONTRACT = Object.freeze({
|
|
86
99
|
// ── brand · colour roles (18) ────────────────────────────────────────────
|
|
87
|
-
'--background': brandColor(),
|
|
88
|
-
'--foreground': brandColor(),
|
|
100
|
+
'--background': brandColor('Page background'),
|
|
101
|
+
'--foreground': brandColor('Text'),
|
|
89
102
|
'--card': brandColor(),
|
|
90
103
|
'--card-foreground': brandColor(),
|
|
91
104
|
'--popover': brandColor(),
|
|
92
105
|
'--popover-foreground': brandColor(),
|
|
93
|
-
'--primary': brandColor(),
|
|
106
|
+
'--primary': brandColor('Buttons & links'),
|
|
94
107
|
'--primary-foreground': brandColor(),
|
|
95
108
|
'--secondary': brandColor(),
|
|
96
109
|
'--secondary-foreground': brandColor(),
|
|
97
110
|
'--muted': brandColor(),
|
|
98
111
|
'--muted-foreground': brandColor(),
|
|
99
|
-
'--accent': brandColor(),
|
|
112
|
+
'--accent': brandColor('Highlights'),
|
|
100
113
|
'--accent-foreground': brandColor(),
|
|
101
|
-
'--border': brandColor(),
|
|
114
|
+
'--border': brandColor('Lines & borders'),
|
|
102
115
|
'--input': brandColor(),
|
|
103
116
|
'--ring': brandColor(),
|
|
104
117
|
/**
|
|
@@ -108,7 +121,7 @@ const THEME_TOKEN_CONTRACT = exports.THEME_TOKEN_CONTRACT = Object.freeze({
|
|
|
108
121
|
* emits the other twenty. A store that states a distinct heading colour has
|
|
109
122
|
* somewhere for it to go the moment an adapter learns to read one.
|
|
110
123
|
*/
|
|
111
|
-
'--heading': brandColor(),
|
|
124
|
+
'--heading': brandColor('Headings'),
|
|
112
125
|
// ── brand · type (2) ─────────────────────────────────────────────────────
|
|
113
126
|
'--font-sans': {
|
|
114
127
|
bucket: 'brand',
|
|
@@ -150,6 +163,17 @@ const BRAND_TOKENS = exports.BRAND_TOKENS = Object.freeze(new Set(Object.entries
|
|
|
150
163
|
*/
|
|
151
164
|
const TOKEN_NAME_PATTERN = exports.TOKEN_NAME_PATTERN = /^--[a-z0-9-]+$/;
|
|
152
165
|
|
|
166
|
+
/**
|
|
167
|
+
* What the owner's panel offers, in the order it offers it.
|
|
168
|
+
*
|
|
169
|
+
* Derived from the contract rather than listed again beside it, so a token
|
|
170
|
+
* cannot be editable in one place and absent from the other. The order is the
|
|
171
|
+
* declaration order above, which reads outside-in — the page, then its text,
|
|
172
|
+
* then the things drawn on it — and is a better first impression than
|
|
173
|
+
* alphabetical or than the order the tokens happen to be defined for CSS.
|
|
174
|
+
*/
|
|
175
|
+
const EDITABLE_TOKENS = exports.EDITABLE_TOKENS = Object.freeze(Object.entries(THEME_TOKEN_CONTRACT).filter(([, entry]) => entry.editable));
|
|
176
|
+
|
|
153
177
|
/** `--radius` → `--web5-host-radius`. Derived, never stored: one fewer thing to get wrong. */
|
|
154
178
|
function hostAliasFor(token) {
|
|
155
179
|
return `--web5-host-${token.slice(2)}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["brandColor","label","bucket","type","editable","undefined","THEME_TOKEN_CONTRACT","exports","Object","freeze","BRAND_TOKENS","Set","entries","filter","entry","map","token","TOKEN_NAME_PATTERN","hostAliasFor","slice","bucketOf","_THEME_TOKEN_CONTRACT"],"sources":["../../../src/theme/tokenContract.ts"],"sourcesContent":["/**\n * The theme-token contract (DL #193).\n *\n * One home for the answer to \"who is allowed to set this token, and who wins\n * when more than one of them does\". Three things need that answer and must not\n * each keep their own copy:\n *\n * - **`applyThemeOverrides`** decides, per key, whether to write the real\n * token or its `--web5-host-*` alias.\n * - **the seed's `validate-templates`** fails a template that sets a brand\n * token.\n * - **the shop owner's panel** renders a control per `editable` entry.\n *\n * A leaf module beside `hostScope.ts`, and for the same reason: both are data\n * that several packages must agree on, and both have to be readable from plain\n * Node tooling. Requiring this package's ENTRY from Node fails — the CSS import\n * in it is a syntax error to the CJS loader, which is what `scope-css.ts`\n * documents — but a deep import of a leaf like this one works, so the seed's\n * validator can read it without loading a component library.\n *\n * It was briefly its own package. That was justified by `embed-loader` needing\n * the list without taking core's eleven dependencies — and the loader turned\n * out not to need it at all, because `applyThemeOverrides` has owned runtime\n * token injection here since DL #131.\n *\n * ## The two buckets\n *\n * The split is about who WINS, not about what may be imported. A platform\n * adapter is free to read anything the store states; the bucket decides what\n * happens when a template has an opinion about the same token.\n *\n * - `brand` — the store's identity: colour roles and font families. The\n * imported value is written as the real token, last, so it wins\n * unconditionally. A template is not permitted to set these.\n * - `host` — the store's shape: corner radius today. The imported value is\n * written as `--web5-host-<name>` and consumed by core as a `var()`\n * fallback, so a template stating the real token beats it and a template\n * that stays silent inherits the store's.\n *\n * A token absent from this map is treated as `host`. That is deliberate and\n * safe: an alias nothing consumes renders nothing, so an adapter that learns\n * to read a token core has never heard of cannot override a template by\n * accident. The wiring line in core is the real gate for a host token, not the\n * entry here.\n *\n * ## Why all but one are brand\n *\n * This is not a new taxonomy. Twenty of these are the set\n * `web50-shopify-adapter` already emits, with a bucket attached; the\n * twenty-first, `--heading`, has been in core's catalogue since DL #131 and is\n * consumed by the seed, but no adapter fills it yet. Exactly one token changes\n * hands relative to the behaviour before DL #193 — `--radius`, which used to\n * win against the template that had chosen a different one. That single\n * misfiling is the whole of the bug this contract exists to fix.\n */\n\n/** How a value is spelled, which is what makes validation possible. */\nexport type TokenType =\n /** An HSL triplet with no `hsl()` wrapper — `0 0% 9%`. The core bridge wraps it. */\n | 'color-hsl'\n /** A CSS font stack — `'Poppins', ui-sans-serif, sans-serif`. */\n | 'font-stack'\n /** A CSS length. MUST carry a unit: a bare `0` turns `calc(var(--radius) - 4px)`\n * into a type error and takes the derived radius scale out entirely. */\n | 'length';\n\n/** Which layer wins when both a store and a template state this token. */\nexport type TokenBucket = 'brand' | 'host';\n\nexport interface TokenContractEntry {\n bucket: TokenBucket;\n type: TokenType;\n /** May the shop owner set this from the panel? */\n editable: boolean;\n /** Shown in the owner's panel. Absent for entries that are not editable. */\n label?: string;\n}\n\nconst brandColor = (label?: string): TokenContractEntry => ({\n bucket: 'brand',\n type: 'color-hsl',\n editable: false,\n ...(label === undefined ? {} : { label }),\n});\n\n/**\n * Every token a platform adapter may meaningfully emit today.\n *\n * Growth is adapter-driven on purpose: a token joins when an adapter can\n * actually read it, not on spec. `theme_overrides` is capped at 32 entries by\n * its proto, so there are twelve slots left and no reason to spend them on\n * speculation. `--spacing` is the tempting next one and should be resisted —\n * it scales every `p-*`, `m-*` and `gap-*` in the bundle from one number.\n */\nexport const THEME_TOKEN_CONTRACT: Readonly<Record<string, TokenContractEntry>> =\n Object.freeze({\n // ── brand · colour roles (18) ────────────────────────────────────────────\n '--background': brandColor(),\n '--foreground': brandColor(),\n '--card': brandColor(),\n '--card-foreground': brandColor(),\n '--popover': brandColor(),\n '--popover-foreground': brandColor(),\n '--primary': brandColor(),\n '--primary-foreground': brandColor(),\n '--secondary': brandColor(),\n '--secondary-foreground': brandColor(),\n '--muted': brandColor(),\n '--muted-foreground': brandColor(),\n '--accent': brandColor(),\n '--accent-foreground': brandColor(),\n '--border': brandColor(),\n '--input': brandColor(),\n '--ring': brandColor(),\n\n /**\n * Brand-shaped and supported end to end, but no adapter fills it yet: the\n * seed consumes it (`--color-heading-fg: hsl(var(--heading, var(--foreground)))`)\n * and core has catalogued it since DL #131, while `web50-shopify-adapter`\n * emits the other twenty. A store that states a distinct heading colour has\n * somewhere for it to go the moment an adapter learns to read one.\n */\n '--heading': brandColor(),\n\n // ── brand · type (2) ─────────────────────────────────────────────────────\n '--font-sans': { bucket: 'brand', type: 'font-stack', editable: false },\n '--font-display': { bucket: 'brand', type: 'font-stack', editable: false },\n\n // ── host · shape (1) ─────────────────────────────────────────────────────\n /**\n * The one token whose bucket changed, and the reason this contract exists.\n * Editable because it is the one value a store and a template are known to\n * disagree about in a way a merchant can see and wants to settle.\n */\n '--radius': {\n bucket: 'host',\n type: 'length',\n editable: true,\n label: 'Corner rounding',\n },\n });\n\n/**\n * The tokens written directly, which is the only question the loader has to\n * answer per key — everything else takes the alias path.\n */\nexport const BRAND_TOKENS: ReadonlySet<string> = Object.freeze(\n new Set(\n Object.entries(THEME_TOKEN_CONTRACT)\n .filter(([, entry]) => entry.bucket === 'brand')\n .map(([token]) => token),\n ),\n) as ReadonlySet<string>;\n\n/**\n * A token name we are willing to compose into a CSS declaration.\n *\n * The keys reaching the loader came out of a backend map, which came out of an\n * adapter reading a merchant's theme file. A key carrying `:` or `;` would\n * write arbitrary declarations onto the mount, so the shape is checked where\n * the declaration is built rather than trusted from the source.\n */\nexport const TOKEN_NAME_PATTERN = /^--[a-z0-9-]+$/;\n\n/** `--radius` → `--web5-host-radius`. Derived, never stored: one fewer thing to get wrong. */\nexport function hostAliasFor(token: string): string {\n return `--web5-host-${token.slice(2)}`;\n}\n\n/** Whether this token is written directly (brand) or as an alias (host, and anything unknown). */\nexport function bucketOf(token: string): TokenBucket {\n return THEME_TOKEN_CONTRACT[token]?.bucket ?? 'host';\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAUA;;AAYA,MAAMA,UAAU,GAAIC,KAAc,KAA0B;EAC1DC,MA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E1E;EACA;AACJ;AACA;AACA;AACA;EACI,UAAU,EAAE;IACVF,MAAM,EAAE,MAAM;IACdC,IAAI,EAAE,QAAQ;IACdC,QAAQ,EAAE,IAAI;IACdH,KAAK,EAAE;EACT;AACF,CAAC,CAAC;;AAEJ;AACA;AACA;AACA;AACO,MAAMS,YAAiC,GAAAH,OAAA,CAAAG,YAAA,GAAGF,MAAM,CAACC,MAAM,CAC5D,IAAIE,GAAG,CACLH,MAAM,CAACI,OAAO,CAACN,oBAAoB,CAAC,CACjCO,MAAM,CAAC,CAAC,GAAGC,KAAK,CAAC,KAAKA,KAAK,CAACZ,MAAM,KAAK,OAAO,CAAC,CAC/Ca,GAAG,CAAC,CAAC,CAACC,KAAK,CAAC,KAAKA,KAAK,CAC3B,CACF,CAAwB;;AAExB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,kBAAkB,GAAAV,OAAA,CAAAU,kBAAA,GAAG,gBAAgB;;AAElD;AACO,SAASC,YAAYA,CAACF,KAAa,EAAU;EAClD,OAAO,eAAeA,KAAK,CAACG,KAAK,CAAC,CAAC,CAAC,EAAE;AACxC;;AAEA;AACO,SAASC,QAAQA,CAACJ,KAAa,EAAe;EAAA,IAAAK,qBAAA;EACnD,OAAO,EAAAA,qBAAA,GAAAf,oBAAoB,CAACU,KAAK,CAAC,qBAA3BK,qBAAA,CAA6BnB,MAAM,KAAI,MAAM;AACtD","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["brandColor","label","bucket","type","editable","undefined","THEME_TOKEN_CONTRACT","exports","Object","freeze","BRAND_TOKENS","Set","entries","filter","entry","map","token","TOKEN_NAME_PATTERN","EDITABLE_TOKENS","hostAliasFor","slice","bucketOf","_THEME_TOKEN_CONTRACT"],"sources":["../../../src/theme/tokenContract.ts"],"sourcesContent":["/**\n * The theme-token contract (DL #193).\n *\n * One home for the answer to \"who is allowed to set this token, and who wins\n * when more than one of them does\". Three things need that answer and must not\n * each keep their own copy:\n *\n * - **`applyThemeOverrides`** decides, per key, whether to write the real\n * token or its `--web5-host-*` alias.\n * - **the seed's `validate-templates`** fails a template that sets a brand\n * token.\n * - **the shop owner's panel** renders a control per `editable` entry.\n *\n * A leaf module beside `hostScope.ts`, and for the same reason: both are data\n * that several packages must agree on, and both have to be readable from plain\n * Node tooling. Requiring this package's ENTRY from Node fails — the CSS import\n * in it is a syntax error to the CJS loader, which is what `scope-css.ts`\n * documents — but a deep import of a leaf like this one works, so the seed's\n * validator can read it without loading a component library.\n *\n * It was briefly its own package. That was justified by `embed-loader` needing\n * the list without taking core's eleven dependencies — and the loader turned\n * out not to need it at all, because `applyThemeOverrides` has owned runtime\n * token injection here since DL #131.\n *\n * ## The two buckets\n *\n * The split is about who WINS, not about what may be imported. A platform\n * adapter is free to read anything the store states; the bucket decides what\n * happens when a template has an opinion about the same token.\n *\n * - `brand` — the store's identity: colour roles and font families. The\n * imported value is written as the real token, last, so it wins\n * unconditionally. A template is not permitted to set these.\n * - `host` — the store's shape: corner radius today. The imported value is\n * written as `--web5-host-<name>` and consumed by core as a `var()`\n * fallback, so a template stating the real token beats it and a template\n * that stays silent inherits the store's.\n *\n * A token absent from this map is treated as `host`. That is deliberate and\n * safe: an alias nothing consumes renders nothing, so an adapter that learns\n * to read a token core has never heard of cannot override a template by\n * accident. The wiring line in core is the real gate for a host token, not the\n * entry here.\n *\n * ## Why all but one are brand\n *\n * This is not a new taxonomy. Twenty of these are the set\n * `web50-shopify-adapter` already emits, with a bucket attached; the\n * twenty-first, `--heading`, has been in core's catalogue since DL #131 and is\n * consumed by the seed, but no adapter fills it yet. Exactly one token changes\n * hands relative to the behaviour before DL #193 — `--radius`, which used to\n * win against the template that had chosen a different one. That single\n * misfiling is the whole of the bug this contract exists to fix.\n */\n\n/** How a value is spelled, which is what makes validation possible. */\nexport type TokenType =\n /** An HSL triplet with no `hsl()` wrapper — `0 0% 9%`. The core bridge wraps it. */\n | 'color-hsl'\n /** A CSS font stack — `'Poppins', ui-sans-serif, sans-serif`. */\n | 'font-stack'\n /** A CSS length. MUST carry a unit: a bare `0` turns `calc(var(--radius) - 4px)`\n * into a type error and takes the derived radius scale out entirely. */\n | 'length';\n\n/** Which layer wins when both a store and a template state this token. */\nexport type TokenBucket = 'brand' | 'host';\n\nexport interface TokenContractEntry {\n bucket: TokenBucket;\n type: TokenType;\n /** May the shop owner set this from the panel? */\n editable: boolean;\n /** Shown in the owner's panel. Absent for entries that are not editable. */\n label?: string;\n}\n\n/**\n * A colour role. Giving one a label is what puts it in the owner's panel.\n *\n * The two travel together on purpose: `editable` without a label is a control\n * with no name, and a label on a token nobody may set is a promise the panel\n * cannot keep. One argument, one decision.\n *\n * Labels are the merchant's words rather than the token's — \"Buttons & links\",\n * not \"primary\". Someone choosing their shop's colours is not reading a design\n * system, and `--primary-foreground` is not a colour anyone picks: it is\n * whatever stays legible ON primary, which the theme derives. Exposing the\n * derived half is how a panel produces white text on a white button.\n */\nconst brandColor = (label?: string): TokenContractEntry => ({\n bucket: 'brand',\n type: 'color-hsl',\n editable: label !== undefined,\n ...(label === undefined ? {} : { label }),\n});\n\n/**\n * Every token a platform adapter may meaningfully emit today.\n *\n * Growth is adapter-driven on purpose: a token joins when an adapter can\n * actually read it, not on spec. `theme_overrides` is capped at 32 entries by\n * its proto, so there are twelve slots left and no reason to spend them on\n * speculation. `--spacing` is the tempting next one and should be resisted —\n * it scales every `p-*`, `m-*` and `gap-*` in the bundle from one number.\n */\nexport const THEME_TOKEN_CONTRACT: Readonly<Record<string, TokenContractEntry>> =\n Object.freeze({\n // ── brand · colour roles (18) ────────────────────────────────────────────\n '--background': brandColor('Page background'),\n '--foreground': brandColor('Text'),\n '--card': brandColor(),\n '--card-foreground': brandColor(),\n '--popover': brandColor(),\n '--popover-foreground': brandColor(),\n '--primary': brandColor('Buttons & links'),\n '--primary-foreground': brandColor(),\n '--secondary': brandColor(),\n '--secondary-foreground': brandColor(),\n '--muted': brandColor(),\n '--muted-foreground': brandColor(),\n '--accent': brandColor('Highlights'),\n '--accent-foreground': brandColor(),\n '--border': brandColor('Lines & borders'),\n '--input': brandColor(),\n '--ring': brandColor(),\n\n /**\n * Brand-shaped and supported end to end, but no adapter fills it yet: the\n * seed consumes it (`--color-heading-fg: hsl(var(--heading, var(--foreground)))`)\n * and core has catalogued it since DL #131, while `web50-shopify-adapter`\n * emits the other twenty. A store that states a distinct heading colour has\n * somewhere for it to go the moment an adapter learns to read one.\n */\n '--heading': brandColor('Headings'),\n\n // ── brand · type (2) ─────────────────────────────────────────────────────\n '--font-sans': { bucket: 'brand', type: 'font-stack', editable: false },\n '--font-display': { bucket: 'brand', type: 'font-stack', editable: false },\n\n // ── host · shape (1) ─────────────────────────────────────────────────────\n /**\n * The one token whose bucket changed, and the reason this contract exists.\n * Editable because it is the one value a store and a template are known to\n * disagree about in a way a merchant can see and wants to settle.\n */\n '--radius': {\n bucket: 'host',\n type: 'length',\n editable: true,\n label: 'Corner rounding',\n },\n });\n\n/**\n * The tokens written directly, which is the only question the loader has to\n * answer per key — everything else takes the alias path.\n */\nexport const BRAND_TOKENS: ReadonlySet<string> = Object.freeze(\n new Set(\n Object.entries(THEME_TOKEN_CONTRACT)\n .filter(([, entry]) => entry.bucket === 'brand')\n .map(([token]) => token),\n ),\n) as ReadonlySet<string>;\n\n/**\n * A token name we are willing to compose into a CSS declaration.\n *\n * The keys reaching the loader came out of a backend map, which came out of an\n * adapter reading a merchant's theme file. A key carrying `:` or `;` would\n * write arbitrary declarations onto the mount, so the shape is checked where\n * the declaration is built rather than trusted from the source.\n */\nexport const TOKEN_NAME_PATTERN = /^--[a-z0-9-]+$/;\n\n/**\n * What the owner's panel offers, in the order it offers it.\n *\n * Derived from the contract rather than listed again beside it, so a token\n * cannot be editable in one place and absent from the other. The order is the\n * declaration order above, which reads outside-in — the page, then its text,\n * then the things drawn on it — and is a better first impression than\n * alphabetical or than the order the tokens happen to be defined for CSS.\n */\nexport const EDITABLE_TOKENS: readonly (readonly [\n token: string,\n entry: TokenContractEntry,\n])[] = Object.freeze(\n Object.entries(THEME_TOKEN_CONTRACT).filter(([, entry]) => entry.editable),\n) as readonly (readonly [string, TokenContractEntry])[];\n\n/** `--radius` → `--web5-host-radius`. Derived, never stored: one fewer thing to get wrong. */\nexport function hostAliasFor(token: string): string {\n return `--web5-host-${token.slice(2)}`;\n}\n\n/** Whether this token is written directly (brand) or as an alias (host, and anything unknown). */\nexport function bucketOf(token: string): TokenBucket {\n return THEME_TOKEN_CONTRACT[token]?.bucket ?? 'host';\n}\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAUA;;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,UAAU,GAAIC,KAAc,KAA0B;EAC1DC,MAAM,EAAE,OAAO;EACfC,IAAI,EAAE,WAAW;EACjBC,QAAQ,EAAEH,KAAK,KAAKI,SAAS;EAC7B,IAAIJ,KAAK,KAAKI,SAAS,GAAG,CAAC,CAAC,GAAG;IAAEJ;EAAM,CAAC;AAC1C,CAAC,CAAC;;AAEF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMK,oBAAkE,GAAAC,OAAA,CAAAD,oBAAA,GAC7EE,MAAM,CAACC,MAAM,CAAC;EACZ;EACA,cAAc,EAAET,UAAU,CAAC,iBAAiB,CAAC;EAC7C,cAAc,EAAEA,UAAU,CAAC,MAAM,CAAC;EAClC,QAAQ,EAAEA,UAAU,CAAC,CAAC;EACtB,mBAAmB,EAAEA,UAAU,CAAC,CAAC;EACjC,WAAW,EAAEA,UAAU,CAAC,CAAC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C,KAAKA,KAAK,CAC3B,CACF,CAAwB;;AAExB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,kBAAkB,GAAAV,OAAA,CAAAU,kBAAA,GAAG,gBAAgB;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMC,eAGT,GAAAX,OAAA,CAAAW,eAAA,GAAGV,MAAM,CAACC,MAAM,CAClBD,MAAM,CAACI,OAAO,CAACN,oBAAoB,CAAC,CAACO,MAAM,CAAC,CAAC,GAAGC,KAAK,CAAC,KAAKA,KAAK,CAACV,QAAQ,CAC3E,CAAuD;;AAEvD;AACO,SAASe,YAAYA,CAACH,KAAa,EAAU;EAClD,OAAO,eAAeA,KAAK,CAACI,KAAK,CAAC,CAAC,CAAC,EAAE;AACxC;;AAEA;AACO,SAASC,QAAQA,CAACL,KAAa,EAAe;EAAA,IAAAM,qBAAA;EACnD,OAAO,EAAAA,qBAAA,GAAAhB,oBAAoB,CAACU,KAAK,CAAC,qBAA3BM,qBAAA,CAA6BpB,MAAM,KAAI,MAAM;AACtD","ignoreList":[]}
|
|
@@ -31,6 +31,13 @@
|
|
|
31
31
|
* - **Values are inert**: entries are written with
|
|
32
32
|
* `CSSStyleDeclaration.setProperty`, never string-concatenated into CSS, so
|
|
33
33
|
* a hostile value cannot terminate the declaration or open a new rule.
|
|
34
|
+
* - **The shop owner is the last word (DL #193)**: `userOverrides` carries the
|
|
35
|
+
* choices a human made in the owner panel, and every one of them is written
|
|
36
|
+
* as the real token whatever its bucket. Bucketing exists to arbitrate a
|
|
37
|
+
* disagreement between a store and a template; an owner who opened a panel
|
|
38
|
+
* and set a value has already settled that argument, so aliasing theirs would
|
|
39
|
+
* let the template overrule the person who chose. They are written last, so a
|
|
40
|
+
* token both maps carry resolves to the owner's value.
|
|
34
41
|
* - **Idempotent**: one marker element per document, replaced wholesale on
|
|
35
42
|
* re-apply; empty/absent input removes it.
|
|
36
43
|
*/
|
|
@@ -61,12 +68,10 @@ export const THEME_OVERRIDE_TOKENS = new Set(Object.keys(THEME_TOKEN_CONTRACT));
|
|
|
61
68
|
/** Mirrors the server's Consts.ThemeOverrideKeyPattern. */
|
|
62
69
|
const KEY_PATTERN = /^--[a-z][a-z0-9-]{0,62}$/;
|
|
63
70
|
const MARKER_ATTR = 'data-web5-theme-overrides';
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
const existing = document.head.querySelector(`style[${MARKER_ATTR}]`);
|
|
69
|
-
const entries = Object.entries(overrides ?? {}).filter(_ref => {
|
|
71
|
+
|
|
72
|
+
/** Drops keys that are not well-formed custom properties, warning about each. */
|
|
73
|
+
function wellFormedEntries(overrides) {
|
|
74
|
+
return Object.entries(overrides ?? {}).filter(_ref => {
|
|
70
75
|
let [key] = _ref;
|
|
71
76
|
const wellFormed = KEY_PATTERN.test(key);
|
|
72
77
|
if (!wellFormed) {
|
|
@@ -74,7 +79,15 @@ export function applyThemeOverrides(overrides) {
|
|
|
74
79
|
}
|
|
75
80
|
return wellFormed;
|
|
76
81
|
});
|
|
77
|
-
|
|
82
|
+
}
|
|
83
|
+
export function applyThemeOverrides(overrides, userOverrides) {
|
|
84
|
+
if (typeof document === 'undefined') {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const existing = document.head.querySelector(`style[${MARKER_ATTR}]`);
|
|
88
|
+
const entries = wellFormedEntries(overrides);
|
|
89
|
+
const userEntries = wellFormedEntries(userOverrides);
|
|
90
|
+
if (entries.length === 0 && userEntries.length === 0) {
|
|
78
91
|
existing == null || existing.remove();
|
|
79
92
|
// Nothing to apply is itself a traceable answer: it means every token on
|
|
80
93
|
// the page is the template's, which is otherwise indistinguishable from
|
|
@@ -93,18 +106,30 @@ export function applyThemeOverrides(overrides) {
|
|
|
93
106
|
sheet.insertRule(`${WEB5_SCOPE} {}`, 0);
|
|
94
107
|
const rule = sheet.cssRules[0];
|
|
95
108
|
const applied = [];
|
|
96
|
-
|
|
97
|
-
// Brand wins over the template, so it is written as the token the
|
|
98
|
-
// stylesheets actually read. Everything else lands in the host namespace,
|
|
99
|
-
// where core consumes it only as a fallback the template can beat.
|
|
100
|
-
const target = bucketOf(key) === 'brand' ? key : hostAliasFor(key);
|
|
109
|
+
const write = (key, value, target, source) => {
|
|
101
110
|
try {
|
|
102
111
|
rule.style.setProperty(target, value);
|
|
103
|
-
applied.push(
|
|
112
|
+
applied.push({
|
|
113
|
+
token: key,
|
|
114
|
+
value,
|
|
115
|
+
writtenAs: target,
|
|
116
|
+
source
|
|
117
|
+
});
|
|
104
118
|
} catch {
|
|
105
119
|
// An engine that rejects the value leaves the token at its baked
|
|
106
120
|
// default — degraded theming, never broken CSS.
|
|
107
121
|
}
|
|
122
|
+
};
|
|
123
|
+
for (const [key, value] of entries) {
|
|
124
|
+
// Brand wins over the template, so it is written as the token the
|
|
125
|
+
// stylesheets actually read. Everything else lands in the host namespace,
|
|
126
|
+
// where core consumes it only as a fallback the template can beat.
|
|
127
|
+
write(key, value, bucketOf(key) === 'brand' ? key : hostAliasFor(key), 'store');
|
|
128
|
+
}
|
|
129
|
+
// Owner choices last and never aliased: within one declaration block the last
|
|
130
|
+
// write of a property wins, so a token both maps carry ends up the owner's.
|
|
131
|
+
for (const [key, value] of userEntries) {
|
|
132
|
+
write(key, value, key, 'user');
|
|
108
133
|
}
|
|
109
134
|
// Replace-on-reapply: the fresh element is appended (so it stays last in
|
|
110
135
|
// document order) before the stale one is dropped.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["WEB5_SCOPE","traceThemeOverrides","THEME_TOKEN_CONTRACT","bucketOf","hostAliasFor","THEME_OVERRIDE_TOKENS","Set","Object","keys","KEY_PATTERN","MARKER_ATTR","applyThemeOverrides","overrides","document","existing","head","querySelector","entries","filter","_ref","key","wellFormed","test","console","warn","length","remove","style","createElement","setAttribute","appendChild","sheet","insertRule","rule","cssRules","applied","value","target","setProperty","push"],"sources":["../../../src/client/applyThemeOverrides.ts"],"sourcesContent":["/**\n * Runtime theme token injection (DL #131).\n *\n * `Configuration.themeOverrides` carries per-store CSS custom-property\n * overrides (`--primary`, `--radius`, `--heading`, ...) computed from the\n * store's own theme (e.g. the Shopify `settings_data.json` extractor). This\n * applies them to the page so they win over the bundle's baked `theme.css`:\n *\n * - **Scoped, not `:root`**: the rule targets `WEB5_SCOPE`, the same\n * `:is(#root, .w5-root, [data-web5-placement], .debug-view)` selector every\n * compiled bundle stylesheet uses — host-page styling is never touched, and\n * equal specificity + later document order makes the override win. Callers\n * must therefore apply AFTER the client bundle's CSS is in the document.\n * - **Bucketed, since DL #193**: a `brand` token (colour roles, font families)\n * is written as itself, so the store's identity beats the template's. Every\n * other key — `host` tokens and anything the contract has never heard of —\n * is written as its `--web5-host-*` alias, which core's stylesheets consume\n * as a `var()` fallback. A template stating the real token therefore wins on\n * shape, and an unknown key is inert rather than dangerous: a custom property\n * nothing references renders nothing, so an adapter that learns to read a new\n * token cannot silently override a template.\n * - **The token set stays open, but the destination changed.** Before DL #193\n * an unrecognised key was applied verbatim, so a template could consume\n * `var(--foo)` and grow a token with no release. It now arrives as\n * `--web5-host-foo`, so the template consumes `var(--web5-host-foo, <default>)`\n * instead. One line different, and the provenance is explicit — the wiring\n * line is what activates a host token, not the contract entry.\n * - The mandatory `--` prefix means an override can only define custom\n * properties — it can never set a real CSS property inside the scope. The\n * server enforces the same shape (plus value sanitation) at write time.\n * - **Values are inert**: entries are written with\n * `CSSStyleDeclaration.setProperty`, never string-concatenated into CSS, so\n * a hostile value cannot terminate the declaration or open a new rule.\n * - **Idempotent**: one marker element per document, replaced wholesale on\n * re-apply; empty/absent input removes it.\n */\nimport { WEB5_SCOPE } from '../hostScope';\nimport { traceThemeOverrides } from './themeDebug';\nimport {\n THEME_TOKEN_CONTRACT,\n bucketOf,\n hostAliasFor,\n} from '../theme/tokenContract';\n\n/** A themeOverrides key: always a CSS custom property. */\nexport type ThemeOverrideKey = `--${string}`;\n\n/**\n * Writer-side shape for a theme override map. The catalog below documents\n * the tokens the seed consumes today; the type stays open so new tokens\n * flow end-to-end with no release anywhere but the seed.\n */\nexport type ThemeOverrides = Record<ThemeOverrideKey, string>;\n\n/**\n * The known token catalog. GUIDANCE, NOT A GATE — `applyThemeOverrides` still\n * applies any well-formed custom property, so the vocabulary can grow without a\n * release here.\n *\n * Derived from `@wix/web5-token-contract` rather than restated, because two\n * hand-maintained copies of one list is how they drift. The contract also\n * carries what this Set cannot: which bucket each token is in, and therefore\n * who wins when a store and a template disagree.\n */\nexport const THEME_OVERRIDE_TOKENS: ReadonlySet<string> = new Set(\n Object.keys(THEME_TOKEN_CONTRACT),\n);\n\n/** Mirrors the server's Consts.ThemeOverrideKeyPattern. */\nconst KEY_PATTERN = /^--[a-z][a-z0-9-]{0,62}$/;\n\nconst MARKER_ATTR = 'data-web5-theme-overrides';\n\nexport function applyThemeOverrides(\n overrides?: Record<string, string> | null,\n): void {\n if (typeof document === 'undefined') {\n return;\n }\n\n const existing = document.head.querySelector(`style[${MARKER_ATTR}]`);\n const entries = Object.entries(overrides ?? {}).filter(([key]) => {\n const wellFormed = KEY_PATTERN.test(key);\n if (!wellFormed) {\n console.warn(\n `[web5-theme] Skipping malformed theme override key: ${key}`,\n );\n }\n return wellFormed;\n });\n\n if (entries.length === 0) {\n existing?.remove();\n // Nothing to apply is itself a traceable answer: it means every token on\n // the page is the template's, which is otherwise indistinguishable from\n // tracing having failed.\n traceThemeOverrides([]);\n return;\n }\n\n const style = document.createElement('style');\n style.setAttribute(MARKER_ATTR, '');\n document.head.appendChild(style);\n const sheet = style.sheet;\n if (!sheet) {\n style.remove();\n return;\n }\n sheet.insertRule(`${WEB5_SCOPE} {}`, 0);\n const rule = sheet.cssRules[0] as CSSStyleRule;\n const applied: [string, string][] = [];\n for (const [key, value] of entries) {\n // Brand wins over the template, so it is written as the token the\n // stylesheets actually read. Everything else lands in the host namespace,\n // where core consumes it only as a fallback the template can beat.\n const target = bucketOf(key) === 'brand' ? key : hostAliasFor(key);\n try {\n rule.style.setProperty(target, value);\n applied.push([key, value]);\n } catch {\n // An engine that rejects the value leaves the token at its baked\n // default — degraded theming, never broken CSS.\n }\n }\n // Replace-on-reapply: the fresh element is appended (so it stays last in\n // document order) before the stale one is dropped.\n existing?.remove();\n // AFTER the stale element is gone, so the resolved values traced below are\n // the ones the page will actually render. Off unless explicitly enabled.\n traceThemeOverrides(applied);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,cAAc;AACzC,SAASC,mBAAmB,QAAQ,cAAc;AAClD,SACEC,oBAAoB,EACpBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;;AAE/B;;AAGA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,qBAA0C,GAAG,IAAIC,GAAG,CAC/DC,MAAM,CAACC,IAAI,CAACN,oBAAoB,CAClC,CAAC;;AAED;AACA,MAAMO,WAAW,GAAG,0BAA0B;AAE9C,MAAMC,WAAW,GAAG,2BAA2B;AAE/C,OAAO,SAASC,mBAAmBA,CACjCC,SAAyC,EACnC;EACN,IAAI,OAAOC,QAAQ,KAAK,WAAW,EAAE;IACnC;EACF;EAEA,MAAMC,QAAQ,GAAGD,QAAQ,CAACE,IAAI,CAACC,aAAa,CAAC,SAASN,WAAW,GAAG,CAAC;EACrE,MAAMO,OAAO,GAAGV,MAAM,CAACU,OAAO,CAACL,SAAS,IAAI,CAAC,CAAC,CAAC,CAACM,MAAM,CAACC,IAAA,IAAW;IAAA,IAAV,CAACC,GAAG,CAAC,GAAAD,IAAA;IAC3D,MAAME,UAAU,GAAGZ,WAAW,CAACa,IAAI,CAACF,GAAG,CAAC;IACx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ACAzB,mBAAmB,CAACkC,OAAO,CAAC;AAC9B","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["WEB5_SCOPE","traceThemeOverrides","THEME_TOKEN_CONTRACT","bucketOf","hostAliasFor","THEME_OVERRIDE_TOKENS","Set","Object","keys","KEY_PATTERN","MARKER_ATTR","wellFormedEntries","overrides","entries","filter","_ref","key","wellFormed","test","console","warn","applyThemeOverrides","userOverrides","document","existing","head","querySelector","userEntries","length","remove","style","createElement","setAttribute","appendChild","sheet","insertRule","rule","cssRules","applied","write","value","target","source","setProperty","push","token","writtenAs"],"sources":["../../../src/client/applyThemeOverrides.ts"],"sourcesContent":["/**\n * Runtime theme token injection (DL #131).\n *\n * `Configuration.themeOverrides` carries per-store CSS custom-property\n * overrides (`--primary`, `--radius`, `--heading`, ...) computed from the\n * store's own theme (e.g. the Shopify `settings_data.json` extractor). This\n * applies them to the page so they win over the bundle's baked `theme.css`:\n *\n * - **Scoped, not `:root`**: the rule targets `WEB5_SCOPE`, the same\n * `:is(#root, .w5-root, [data-web5-placement], .debug-view)` selector every\n * compiled bundle stylesheet uses — host-page styling is never touched, and\n * equal specificity + later document order makes the override win. Callers\n * must therefore apply AFTER the client bundle's CSS is in the document.\n * - **Bucketed, since DL #193**: a `brand` token (colour roles, font families)\n * is written as itself, so the store's identity beats the template's. Every\n * other key — `host` tokens and anything the contract has never heard of —\n * is written as its `--web5-host-*` alias, which core's stylesheets consume\n * as a `var()` fallback. A template stating the real token therefore wins on\n * shape, and an unknown key is inert rather than dangerous: a custom property\n * nothing references renders nothing, so an adapter that learns to read a new\n * token cannot silently override a template.\n * - **The token set stays open, but the destination changed.** Before DL #193\n * an unrecognised key was applied verbatim, so a template could consume\n * `var(--foo)` and grow a token with no release. It now arrives as\n * `--web5-host-foo`, so the template consumes `var(--web5-host-foo, <default>)`\n * instead. One line different, and the provenance is explicit — the wiring\n * line is what activates a host token, not the contract entry.\n * - The mandatory `--` prefix means an override can only define custom\n * properties — it can never set a real CSS property inside the scope. The\n * server enforces the same shape (plus value sanitation) at write time.\n * - **Values are inert**: entries are written with\n * `CSSStyleDeclaration.setProperty`, never string-concatenated into CSS, so\n * a hostile value cannot terminate the declaration or open a new rule.\n * - **The shop owner is the last word (DL #193)**: `userOverrides` carries the\n * choices a human made in the owner panel, and every one of them is written\n * as the real token whatever its bucket. Bucketing exists to arbitrate a\n * disagreement between a store and a template; an owner who opened a panel\n * and set a value has already settled that argument, so aliasing theirs would\n * let the template overrule the person who chose. They are written last, so a\n * token both maps carry resolves to the owner's value.\n * - **Idempotent**: one marker element per document, replaced wholesale on\n * re-apply; empty/absent input removes it.\n */\nimport { WEB5_SCOPE } from '../hostScope';\nimport {\n traceThemeOverrides,\n type AppliedToken,\n type ThemeOverrideSource,\n} from './themeDebug';\nimport {\n THEME_TOKEN_CONTRACT,\n bucketOf,\n hostAliasFor,\n} from '../theme/tokenContract';\n\n/** A themeOverrides key: always a CSS custom property. */\nexport type ThemeOverrideKey = `--${string}`;\n\n/**\n * Writer-side shape for a theme override map. The catalog below documents\n * the tokens the seed consumes today; the type stays open so new tokens\n * flow end-to-end with no release anywhere but the seed.\n */\nexport type ThemeOverrides = Record<ThemeOverrideKey, string>;\n\n/**\n * The known token catalog. GUIDANCE, NOT A GATE — `applyThemeOverrides` still\n * applies any well-formed custom property, so the vocabulary can grow without a\n * release here.\n *\n * Derived from `@wix/web5-token-contract` rather than restated, because two\n * hand-maintained copies of one list is how they drift. The contract also\n * carries what this Set cannot: which bucket each token is in, and therefore\n * who wins when a store and a template disagree.\n */\nexport const THEME_OVERRIDE_TOKENS: ReadonlySet<string> = new Set(\n Object.keys(THEME_TOKEN_CONTRACT),\n);\n\n/** Mirrors the server's Consts.ThemeOverrideKeyPattern. */\nconst KEY_PATTERN = /^--[a-z][a-z0-9-]{0,62}$/;\n\nconst MARKER_ATTR = 'data-web5-theme-overrides';\n\n/** Drops keys that are not well-formed custom properties, warning about each. */\nfunction wellFormedEntries(\n overrides?: Record<string, string> | null,\n): [string, string][] {\n return Object.entries(overrides ?? {}).filter(([key]) => {\n const wellFormed = KEY_PATTERN.test(key);\n if (!wellFormed) {\n console.warn(\n `[web5-theme] Skipping malformed theme override key: ${key}`,\n );\n }\n return wellFormed;\n });\n}\n\nexport function applyThemeOverrides(\n overrides?: Record<string, string> | null,\n userOverrides?: Record<string, string> | null,\n): void {\n if (typeof document === 'undefined') {\n return;\n }\n\n const existing = document.head.querySelector(`style[${MARKER_ATTR}]`);\n const entries = wellFormedEntries(overrides);\n const userEntries = wellFormedEntries(userOverrides);\n\n if (entries.length === 0 && userEntries.length === 0) {\n existing?.remove();\n // Nothing to apply is itself a traceable answer: it means every token on\n // the page is the template's, which is otherwise indistinguishable from\n // tracing having failed.\n traceThemeOverrides([]);\n return;\n }\n\n const style = document.createElement('style');\n style.setAttribute(MARKER_ATTR, '');\n document.head.appendChild(style);\n const sheet = style.sheet;\n if (!sheet) {\n style.remove();\n return;\n }\n sheet.insertRule(`${WEB5_SCOPE} {}`, 0);\n const rule = sheet.cssRules[0] as CSSStyleRule;\n const applied: AppliedToken[] = [];\n const write = (\n key: string,\n value: string,\n target: string,\n source: ThemeOverrideSource,\n ): void => {\n try {\n rule.style.setProperty(target, value);\n applied.push({ token: key, value, writtenAs: target, source });\n } catch {\n // An engine that rejects the value leaves the token at its baked\n // default — degraded theming, never broken CSS.\n }\n };\n\n for (const [key, value] of entries) {\n // Brand wins over the template, so it is written as the token the\n // stylesheets actually read. Everything else lands in the host namespace,\n // where core consumes it only as a fallback the template can beat.\n write(\n key,\n value,\n bucketOf(key) === 'brand' ? key : hostAliasFor(key),\n 'store',\n );\n }\n // Owner choices last and never aliased: within one declaration block the last\n // write of a property wins, so a token both maps carry ends up the owner's.\n for (const [key, value] of userEntries) {\n write(key, value, key, 'user');\n }\n // Replace-on-reapply: the fresh element is appended (so it stays last in\n // document order) before the stale one is dropped.\n existing?.remove();\n // AFTER the stale element is gone, so the resolved values traced below are\n // the ones the page will actually render. Off unless explicitly enabled.\n traceThemeOverrides(applied);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,UAAU,QAAQ,cAAc;AACzC,SACEC,mBAAmB,QAGd,cAAc;AACrB,SACEC,oBAAoB,EACpBC,QAAQ,EACRC,YAAY,QACP,wBAAwB;;AAE/B;;AAGA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,qBAA0C,GAAG,IAAIC,GAAG,CAC/DC,MAAM,CAACC,IAAI,CAACN,oBAAoB,CAClC,CAAC;;AAED;AACA,MAAMO,WAAW,GAAG,0BAA0B;AAE9C,MAAMC,WAAW,GAAG,2BAA2B;;AAE/C;AACA,SAASC,iBAAiBA,CACxBC,SAAyC,EACrB;EACpB,OAAOL,MAAM,CAACM,OAAO,CAACD,SAAS,IAAI,CAAC,CAAC,CAAC,CAACE,MAAM,CAACC,IAAA,IAAW;IAAA,IAAV,CAACC,GAAG,CAAC,GAAAD,IAAA;IAClD,MAAME,UAAU,GAAGR,WAAW,CAACS,IAAI,CAACF,GAAG,CAAC;IACxC,IAAI,CAACC,UAAU,EAAE;MACfE,OAAO,CAACC,IAAI,CACV,uDAAuDJ,GAAG,EAC5D,CAAC;IACH;IACA,OAAOC,UAAU;EACnB,CAAC,CAAC;AACJ;AAEA,OAAO,SAASI,mBAAmBA,CACjCT,SAAyC,EACzCU,aAA6C,EACvC;EACN,IAAI,OAAOC,QAAQ,KAAK,WAAW,EAAE;IACnC;EACF;EAEA,MAAMC,QAAQ,GAAGD,QAAQ,CAACE,IAAI,CAACC,aAAa,CAAC,SAAShB,WAAW,GAAG,CAAC;EACrE,MAAMG,OAAO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ACLrC,QAAQ,CAACa,GAAG,CAAC,KAAK,OAAO,GAAGA,GAAG,GAAGZ,YAAY,CAACY,GAAG,CAAC,EACnD,OACF,CAAC;EACH;EACA;EACA;EACA,KAAK,MAAM,CAACA,GAAG,EAAEwB,KAAK,CAAC,IAAIb,WAAW,EAAE;IACtCY,KAAK,CAACvB,GAAG,EAAEwB,KAAK,EAAExB,GAAG,EAAE,MAAM,CAAC;EAChC;EACA;EACA;EACAQ,QAAQ,YAARA,QAAQ,CAAEK,MAAM,CAAC,CAAC;EAClB;EACA;EACA5B,mBAAmB,CAACqC,OAAO,CAAC;AAC9B","ignoreList":[]}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
*
|
|
21
21
|
* [web5:theme] --radius host wrote --web5-host-radius=0rem → 1.25rem TEMPLATE
|
|
22
22
|
* [web5:theme] --primary brand wrote --primary=0 0% 9% → 0 0% 9% STORE
|
|
23
|
+
* [web5:theme] --radius owner wrote --radius=2rem → 2rem OWNER
|
|
23
24
|
*
|
|
24
25
|
* Off by default. Enable with `?web5DebugTheme=1` (one-shot, wins over storage)
|
|
25
26
|
* or `localStorage["web5_debug_theme"] = "1"` (sticky) — the same shape as
|
|
@@ -30,7 +31,7 @@
|
|
|
30
31
|
* the whole batch, not one per token.
|
|
31
32
|
*/
|
|
32
33
|
import { WEB5_SCOPES } from '../hostScope.js';
|
|
33
|
-
import { bucketOf
|
|
34
|
+
import { bucketOf } from '../theme/tokenContract.js';
|
|
34
35
|
export const THEME_DEBUG_KEY = 'web5_debug_theme';
|
|
35
36
|
|
|
36
37
|
/** Query param that forces theme tracing on, overriding localStorage. */
|
|
@@ -65,6 +66,11 @@ export const isThemeDebugEnabled = () => {
|
|
|
65
66
|
export const resetThemeDebugCache = () => {
|
|
66
67
|
cached = null;
|
|
67
68
|
};
|
|
69
|
+
|
|
70
|
+
/** Which layer asked for a value: the platform import, or a human. */
|
|
71
|
+
|
|
72
|
+
/** One token as it was actually written to the mount rule. */
|
|
73
|
+
|
|
68
74
|
/**
|
|
69
75
|
* Report what each override did, after the rule is live.
|
|
70
76
|
*
|
|
@@ -100,19 +106,32 @@ export function traceThemeOverrides(applied) {
|
|
|
100
106
|
// One computed-style read for the whole batch: the expensive part is the style
|
|
101
107
|
// recalculation it forces, not the per-property lookups off the result.
|
|
102
108
|
const computed = getComputedStyle(mount);
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
109
|
+
// An owner's write is the last one into the rule, so when both layers name a
|
|
110
|
+
// token the resolved value is theirs — check the owner first or a store value
|
|
111
|
+
// that happens to match would be credited with a win it did not have.
|
|
112
|
+
const byToken = new Map();
|
|
113
|
+
for (const entry of applied) {
|
|
114
|
+
const held = byToken.get(entry.token);
|
|
115
|
+
if (!held || entry.source === 'user') {
|
|
116
|
+
byToken.set(entry.token, entry);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const rows = [...byToken.values()].map(entry => {
|
|
120
|
+
const {
|
|
121
|
+
token,
|
|
122
|
+
value,
|
|
123
|
+
writtenAs,
|
|
124
|
+
source
|
|
125
|
+
} = entry;
|
|
107
126
|
const resolved = computed.getPropertyValue(token).trim();
|
|
108
127
|
const wanted = value.trim();
|
|
109
128
|
return {
|
|
110
129
|
token,
|
|
111
|
-
bucket,
|
|
112
|
-
'written as':
|
|
113
|
-
'
|
|
130
|
+
bucket: source === 'user' ? 'owner' : bucketOf(token),
|
|
131
|
+
'written as': writtenAs,
|
|
132
|
+
'asked for': wanted,
|
|
114
133
|
'resolves to': resolved || '(nothing reads it)',
|
|
115
|
-
winner: !resolved ? 'NOBODY — no stylesheet consumes this token' : resolved
|
|
134
|
+
winner: !resolved ? 'NOBODY — no stylesheet consumes this token' : resolved !== wanted ? 'TEMPLATE' : source === 'user' ? 'OWNER' : 'STORE'
|
|
116
135
|
};
|
|
117
136
|
});
|
|
118
137
|
const overridden = rows.filter(r => r.winner === 'TEMPLATE').length;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["WEB5_SCOPES","bucketOf","hostAliasFor","THEME_DEBUG_KEY","THEME_DEBUG_QUERY_PARAM","LOG_PREFIX","isTruthy","value","cached","isThemeDebugEnabled","URLSearchParams","window","location","search","get","localStorage","getItem","resetThemeDebugCache","traceThemeOverrides","applied","length","console","info","mount","document","querySelector","join","warn","computed","getComputedStyle","rows","map","_ref","token","bucket","target","resolved","getPropertyValue","trim","wanted","winner","overridden","filter","r","inert","startsWith","groupCollapsed","table","groupEnd"],"sources":["../../../src/client/themeDebug.ts"],"sourcesContent":["/**\n * Theme-override tracing (debug-only).\n *\n * Answers the one question the token pipeline cannot otherwise be asked:\n * **which layer actually won?**\n *\n * Since DL #193 a `brand` token is written as itself and everything else as its\n * `--web5-host-*` alias, which core's stylesheets consume as a `var()` fallback\n * a template can beat. That makes the outcome a cascade decision, and a cascade\n * decision is invisible — there is no callback, no return value, and nothing in\n * the DOM to read. Worse, `applyThemeOverrides` writes through the CSSOM\n * (`insertRule` + `setProperty`, never `textContent`) so that a hostile value\n * can never terminate a declaration, which means DevTools renders the marker as\n * `<style data-web5-theme-overrides=\"\">` — an empty tag, with the rules real but\n * nowhere in the DOM tree. Every part of that is deliberate and every part of it\n * looks broken.\n *\n * So this reads the resolved value back off the mount **after** the rule is in,\n * and reports what the browser actually decided:\n *\n * [web5:theme] --radius host wrote --web5-host-radius=0rem → 1.25rem TEMPLATE\n * [web5:theme] --primary brand wrote --primary=0 0% 9% → 0 0% 9% STORE\n *\n * Off by default. Enable with `?web5DebugTheme=1` (one-shot, wins over storage)\n * or `localStorage[\"web5_debug_theme\"] = \"1\"` (sticky) — the same shape as\n * `matchDebug`, so there is one convention to learn rather than two.\n *\n * It is gated rather than always-on because reading a computed value forces a\n * style recalculation, and this runs during page setup. One read is taken for\n * the whole batch, not one per token.\n */\nimport { WEB5_SCOPES } from '../hostScope';\nimport { bucketOf, hostAliasFor } from '../theme/tokenContract';\n\nexport const THEME_DEBUG_KEY = 'web5_debug_theme';\n\n/** Query param that forces theme tracing on, overriding localStorage. */\nexport const THEME_DEBUG_QUERY_PARAM = 'web5DebugTheme';\n\nconst LOG_PREFIX = '[web5:theme]';\n\nconst isTruthy = (value: unknown): boolean => value === '1' || value === 'true';\n\nlet cached: boolean | null = null;\n\n/** Whether theme tracing is enabled. Memoized — resolved once per page load. */\nexport const isThemeDebugEnabled = (): boolean => {\n if (cached !== null) {\n return cached;\n }\n cached = false;\n try {\n if (\n isTruthy(\n new URLSearchParams(window.location.search).get(\n THEME_DEBUG_QUERY_PARAM,\n ),\n )\n ) {\n cached = true;\n return cached;\n }\n } catch {\n // window / URLSearchParams unavailable (SSR, non-DOM environments).\n }\n try {\n cached = isTruthy(localStorage.getItem(THEME_DEBUG_KEY));\n } catch {\n // localStorage can throw in privacy mode / non-DOM environments.\n }\n return cached;\n};\n\n/** Test seam — the flag is memoized for the page, so tests must be able to clear it. */\nexport const resetThemeDebugCache = (): void => {\n cached = null;\n};\n\ninterface TraceRow {\n token: string;\n bucket: string;\n 'written as': string;\n 'store said': string;\n 'resolves to': string;\n winner: string;\n}\n\n/**\n * Report what each override did, after the rule is live.\n *\n * `applied` is what `applyThemeOverrides` actually wrote — already filtered for\n * key shape, so anything malformed has been dropped and warned about before\n * reaching here.\n */\nexport function traceThemeOverrides(applied: [string, string][]): void {\n if (!isThemeDebugEnabled()) {\n return;\n }\n if (applied.length === 0) {\n // Silence here would be indistinguishable from tracing being broken, and\n // \"no overrides reached the page\" is itself the answer often enough — a\n // store with nothing imported means every token is the template's.\n // eslint-disable-next-line no-console\n console.info(\n `${LOG_PREFIX} no overrides applied — nothing usable arrived for this store, so every token is whatever the template and core defaults say`,\n );\n return;\n }\n let mount: Element | null = null;\n try {\n mount = document.querySelector(WEB5_SCOPES.join(','));\n } catch {\n // Malformed selector cannot happen with the constant, but querySelector is\n // the one call here that can throw, and a debug aid must never be the thing\n // that breaks a page.\n }\n if (!mount) {\n console.warn(\n `${LOG_PREFIX} no mount found (${WEB5_SCOPES.join(\n ', ',\n )}) — tokens were written, but their resolved values cannot be read`,\n );\n return;\n }\n\n // One computed-style read for the whole batch: the expensive part is the style\n // recalculation it forces, not the per-property lookups off the result.\n const computed = getComputedStyle(mount);\n const rows: TraceRow[] = applied.map(([token, value]) => {\n const bucket = bucketOf(token);\n const target = bucket === 'brand' ? token : hostAliasFor(token);\n const resolved = computed.getPropertyValue(token).trim();\n const wanted = value.trim();\n return {\n token,\n bucket,\n 'written as': target,\n 'store said': wanted,\n 'resolves to': resolved || '(nothing reads it)',\n winner: !resolved\n ? 'NOBODY — no stylesheet consumes this token'\n : resolved === wanted\n ? 'STORE'\n : 'TEMPLATE',\n };\n });\n\n const overridden = rows.filter((r) => r.winner === 'TEMPLATE').length;\n const inert = rows.filter((r) => r.winner.startsWith('NOBODY')).length;\n\n /* eslint-disable no-console */\n console.groupCollapsed(\n `${LOG_PREFIX} ${rows.length} override(s) applied · ${overridden} kept by the template · ${inert} inert`,\n );\n console.table(rows);\n if (inert > 0) {\n console.info(\n `${LOG_PREFIX} \"inert\" means the value was written but no stylesheet reads that token — ` +\n `for a host token that means core has no \\`var(--web5-host-…)\\` wiring for it yet.`,\n );\n }\n console.info(\n `${LOG_PREFIX} the marker <style data-web5-theme-overrides> looks empty in DevTools on purpose: ` +\n `rules are inserted through the CSSOM, never as text. Read them with ` +\n `document.querySelector('style[data-web5-theme-overrides]').sheet.cssRules[0].cssText`,\n );\n console.groupEnd();\n /* eslint-enable no-console */\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,WAAW,QAAQ,cAAc;AAC1C,SAASC,QAAQ,EAAEC,YAAY,QAAQ,wBAAwB;AAE/D,OAAO,MAAMC,eAAe,GAAG,kBAAkB;;AAEjD;AACA,OAAO,MAAMC,uBAAuB,GAAG,gBAAgB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AAC0B,KAAK,CAACjB,IAAI,CAAC;EACnB,IAAIc,KAAK,GAAG,CAAC,EAAE;IACbvB,OAAO,CAACC,IAAI,CACV,GAAGjB,UAAU,4EAA4E,GACvF,mFACJ,CAAC;EACH;EACAgB,OAAO,CAACC,IAAI,CACV,GAAGjB,UAAU,oFAAoF,GAC/F,sEAAsE,GACtE,sFACJ,CAAC;EACDgB,OAAO,CAAC2B,QAAQ,CAAC,CAAC;EAClB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["WEB5_SCOPES","bucketOf","THEME_DEBUG_KEY","THEME_DEBUG_QUERY_PARAM","LOG_PREFIX","isTruthy","value","cached","isThemeDebugEnabled","URLSearchParams","window","location","search","get","localStorage","getItem","resetThemeDebugCache","traceThemeOverrides","applied","length","console","info","mount","document","querySelector","join","warn","computed","getComputedStyle","byToken","Map","entry","held","token","source","set","rows","values","map","writtenAs","resolved","getPropertyValue","trim","wanted","bucket","winner","overridden","filter","r","inert","startsWith","groupCollapsed","table","groupEnd"],"sources":["../../../src/client/themeDebug.ts"],"sourcesContent":["/**\n * Theme-override tracing (debug-only).\n *\n * Answers the one question the token pipeline cannot otherwise be asked:\n * **which layer actually won?**\n *\n * Since DL #193 a `brand` token is written as itself and everything else as its\n * `--web5-host-*` alias, which core's stylesheets consume as a `var()` fallback\n * a template can beat. That makes the outcome a cascade decision, and a cascade\n * decision is invisible — there is no callback, no return value, and nothing in\n * the DOM to read. Worse, `applyThemeOverrides` writes through the CSSOM\n * (`insertRule` + `setProperty`, never `textContent`) so that a hostile value\n * can never terminate a declaration, which means DevTools renders the marker as\n * `<style data-web5-theme-overrides=\"\">` — an empty tag, with the rules real but\n * nowhere in the DOM tree. Every part of that is deliberate and every part of it\n * looks broken.\n *\n * So this reads the resolved value back off the mount **after** the rule is in,\n * and reports what the browser actually decided:\n *\n * [web5:theme] --radius host wrote --web5-host-radius=0rem → 1.25rem TEMPLATE\n * [web5:theme] --primary brand wrote --primary=0 0% 9% → 0 0% 9% STORE\n * [web5:theme] --radius owner wrote --radius=2rem → 2rem OWNER\n *\n * Off by default. Enable with `?web5DebugTheme=1` (one-shot, wins over storage)\n * or `localStorage[\"web5_debug_theme\"] = \"1\"` (sticky) — the same shape as\n * `matchDebug`, so there is one convention to learn rather than two.\n *\n * It is gated rather than always-on because reading a computed value forces a\n * style recalculation, and this runs during page setup. One read is taken for\n * the whole batch, not one per token.\n */\nimport { WEB5_SCOPES } from '../hostScope';\nimport { bucketOf } from '../theme/tokenContract';\n\nexport const THEME_DEBUG_KEY = 'web5_debug_theme';\n\n/** Query param that forces theme tracing on, overriding localStorage. */\nexport const THEME_DEBUG_QUERY_PARAM = 'web5DebugTheme';\n\nconst LOG_PREFIX = '[web5:theme]';\n\nconst isTruthy = (value: unknown): boolean => value === '1' || value === 'true';\n\nlet cached: boolean | null = null;\n\n/** Whether theme tracing is enabled. Memoized — resolved once per page load. */\nexport const isThemeDebugEnabled = (): boolean => {\n if (cached !== null) {\n return cached;\n }\n cached = false;\n try {\n if (\n isTruthy(\n new URLSearchParams(window.location.search).get(\n THEME_DEBUG_QUERY_PARAM,\n ),\n )\n ) {\n cached = true;\n return cached;\n }\n } catch {\n // window / URLSearchParams unavailable (SSR, non-DOM environments).\n }\n try {\n cached = isTruthy(localStorage.getItem(THEME_DEBUG_KEY));\n } catch {\n // localStorage can throw in privacy mode / non-DOM environments.\n }\n return cached;\n};\n\n/** Test seam — the flag is memoized for the page, so tests must be able to clear it. */\nexport const resetThemeDebugCache = (): void => {\n cached = null;\n};\n\n/** Which layer asked for a value: the platform import, or a human. */\nexport type ThemeOverrideSource = 'store' | 'user';\n\n/** One token as it was actually written to the mount rule. */\nexport interface AppliedToken {\n token: string;\n value: string;\n writtenAs: string;\n source: ThemeOverrideSource;\n}\n\ninterface TraceRow {\n token: string;\n bucket: string;\n 'written as': string;\n 'asked for': string;\n 'resolves to': string;\n winner: string;\n}\n\n/**\n * Report what each override did, after the rule is live.\n *\n * `applied` is what `applyThemeOverrides` actually wrote — already filtered for\n * key shape, so anything malformed has been dropped and warned about before\n * reaching here.\n */\nexport function traceThemeOverrides(applied: AppliedToken[]): void {\n if (!isThemeDebugEnabled()) {\n return;\n }\n if (applied.length === 0) {\n // Silence here would be indistinguishable from tracing being broken, and\n // \"no overrides reached the page\" is itself the answer often enough — a\n // store with nothing imported means every token is the template's.\n // eslint-disable-next-line no-console\n console.info(\n `${LOG_PREFIX} no overrides applied — nothing usable arrived for this store, so every token is whatever the template and core defaults say`,\n );\n return;\n }\n let mount: Element | null = null;\n try {\n mount = document.querySelector(WEB5_SCOPES.join(','));\n } catch {\n // Malformed selector cannot happen with the constant, but querySelector is\n // the one call here that can throw, and a debug aid must never be the thing\n // that breaks a page.\n }\n if (!mount) {\n console.warn(\n `${LOG_PREFIX} no mount found (${WEB5_SCOPES.join(\n ', ',\n )}) — tokens were written, but their resolved values cannot be read`,\n );\n return;\n }\n\n // One computed-style read for the whole batch: the expensive part is the style\n // recalculation it forces, not the per-property lookups off the result.\n const computed = getComputedStyle(mount);\n // An owner's write is the last one into the rule, so when both layers name a\n // token the resolved value is theirs — check the owner first or a store value\n // that happens to match would be credited with a win it did not have.\n const byToken = new Map<string, AppliedToken>();\n for (const entry of applied) {\n const held = byToken.get(entry.token);\n if (!held || entry.source === 'user') {\n byToken.set(entry.token, entry);\n }\n }\n const rows: TraceRow[] = [...byToken.values()].map((entry) => {\n const { token, value, writtenAs, source } = entry;\n const resolved = computed.getPropertyValue(token).trim();\n const wanted = value.trim();\n return {\n token,\n bucket: source === 'user' ? 'owner' : bucketOf(token),\n 'written as': writtenAs,\n 'asked for': wanted,\n 'resolves to': resolved || '(nothing reads it)',\n winner: !resolved\n ? 'NOBODY — no stylesheet consumes this token'\n : resolved !== wanted\n ? 'TEMPLATE'\n : source === 'user'\n ? 'OWNER'\n : 'STORE',\n };\n });\n\n const overridden = rows.filter((r) => r.winner === 'TEMPLATE').length;\n const inert = rows.filter((r) => r.winner.startsWith('NOBODY')).length;\n\n /* eslint-disable no-console */\n console.groupCollapsed(\n `${LOG_PREFIX} ${rows.length} override(s) applied · ${overridden} kept by the template · ${inert} inert`,\n );\n console.table(rows);\n if (inert > 0) {\n console.info(\n `${LOG_PREFIX} \"inert\" means the value was written but no stylesheet reads that token — ` +\n `for a host token that means core has no \\`var(--web5-host-…)\\` wiring for it yet.`,\n );\n }\n console.info(\n `${LOG_PREFIX} the marker <style data-web5-theme-overrides> looks empty in DevTools on purpose: ` +\n `rules are inserted through the CSSOM, never as text. Read them with ` +\n `document.querySelector('style[data-web5-theme-overrides]').sheet.cssRules[0].cssText`,\n );\n console.groupEnd();\n /* eslint-enable no-console */\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,WAAW,QAAQ,cAAc;AAC1C,SAASC,QAAQ,QAAQ,wBAAwB;AAEjD,OAAO,MAAMC,eAAe,GAAG,kBAAkB;;AAEjD;AACA,OAAO,MAAMC,uBAAuB,GAAG,gBAAgB;AAEvD,MAAMC,UAAU,GAAG,cAAc;AAEjC,MAAMC,QAAQ,GAAIC,KAAc,IAAcA,KAAK,KAAK,GAAG,IAAIA,KAAK,KAAK,MAAM;AAE/E,IAAIC,MAAsB,GAAG,IAAI;;AAEjC;AACA,OAAO,MAAMC,mBAAmB,GAAGA,CAAA,KAAe;EAChD,IAAID,MAAM,KAAK,IAAI,EAAE;IACnB,OAAOA,MAAM;EACf;EACAA,MAAM,GAAG,KAAK;EACd,IAAI;IACF,IACEF,QAAQ,CACN,IAAII,eAAe,CAACC,MAAM,CAACC,QAAQ,CAACC,MAAM,CAAC,CAACC,GAAG,CAC7CV,uBACF,CACF,CAAC,EACD;MACAI,MAAM,GAAG,IAAI;MACb,OAAOA,MAAM;IACf;EACF,CAAC,CAAC,MAAM;IACN;EAAA;EAE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,GACvF,mFACJ,CAAC;EACH;EACAgB,OAAO,CAACC,IAAI,CACV,GAAGjB,UAAU,oFAAoF,GAC/F,sEAAsE,GACtE,sFACJ,CAAC;EACDgB,OAAO,CAACiC,QAAQ,CAAC,CAAC;EAClB;AACF","ignoreList":[]}
|
package/dist/esm/index.js
CHANGED
|
@@ -142,8 +142,9 @@ export { getClientBundleOverride, isTrustedBundleHost } from './client/clientBun
|
|
|
142
142
|
export { TEMPLATES_CDN_BASE, TEMPLATES_MANIFEST_URL, getTemplateOverride, isTemplatePickerRequested, isValidTemplateId, resolveClientBundleUrl } from './client/clientBundleUrl.js';
|
|
143
143
|
export { mergeClientConfig } from './client/mergeClientConfig.js';
|
|
144
144
|
export { applyThemeOverrides, THEME_OVERRIDE_TOKENS } from './client/applyThemeOverrides.js';
|
|
145
|
-
export { THEME_TOKEN_CONTRACT, BRAND_TOKENS, TOKEN_NAME_PATTERN, bucketOf, hostAliasFor } from './theme/tokenContract.js';
|
|
145
|
+
export { THEME_TOKEN_CONTRACT, BRAND_TOKENS, EDITABLE_TOKENS, TOKEN_NAME_PATTERN, bucketOf, hostAliasFor } from './theme/tokenContract.js';
|
|
146
146
|
export { isThemeDebugEnabled, THEME_DEBUG_KEY, THEME_DEBUG_QUERY_PARAM } from './client/themeDebug.js';
|
|
147
|
+
export { hexToHslTriplet, hslTripletToHex, isHslTriplet } from './theme/colorFormat.js';
|
|
147
148
|
|
|
148
149
|
// Placement renderer + DI helper (DL #088 D3.2, D3.4)
|
|
149
150
|
export { PlacementResponseRenderer, PlacementSmoothHeight } from './components/placement/PlacementResponseRenderer.js';
|