@adminiumjs/skin-kit 0.0.0-stage → 0.3.82

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/css.js ADDED
@@ -0,0 +1,690 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * A SKIN'S CSS, HELD TO ITS SLOTS BY THE BROWSER'S OWN PARSER.
4
+ *
5
+ * The skin's text is parsed by the browser (`CSSStyleSheet.replaceSync`, which
6
+ * drops `@import`), then REBUILT: nothing the parser produced is copied as
7
+ * text. Each rule is kept only when every selector is the skin's own classes
8
+ * (joined by a space or `>`, with a short list of pseudos), and each
9
+ * declaration only when its property is on the list and its value reads,
10
+ * token by token, as numbers, lengths, listed keywords, listed functions and
11
+ * `var()` of listed tokens. The result is built through CSSOM (`insertRule`,
12
+ * `setProperty`) into `@layer skin`, under `@layer kit-guard`, whose
13
+ * `!important` rules keep every slot contained, every host whole, the focus
14
+ * ring and the app's figure faces.
15
+ *
16
+ * Every rule or declaration left out is reported with its reason, so an author
17
+ * (and Studio's preview) can see why.
18
+ *
19
+ * Browser only: it needs `CSSStyleSheet`, `CSS.supports` and a document.
20
+ */
21
+ import { APP_TOKENS, COLOR_TOKENS, DERIVED_TOKENS, FACE_TOKENS, RADIUS_TOKENS, SHADOW_TOKENS } from './tokens.js';
22
+ /** The class prefix for a slot's own classes: `sk-<slot with dots as dashes>-`. */
23
+ export function classPrefix(slot) {
24
+ return `sk-${slot.replace(/\./g, '-')}-`;
25
+ }
26
+ // ── selectors ────────────────────────────────────────────────────────────────
27
+ const CLASS = '\\.[a-z][a-z0-9-]{0,31}';
28
+ const NTH = '(?:odd|even|[+-]?\\d{0,3}n(?:\\s*[+-]\\s*\\d{1,3})?|[+-]?\\d{1,3})';
29
+ const PSEUDO = `(?::(?:hover|active|focus-visible|focus-within|first-child|last-child|only-child|empty)|:(?:nth-child|nth-of-type)\\(\\s*${NTH}\\s*\\))`;
30
+ const COMPOUND = `(?:${CLASS})+${PSEUDO}*`;
31
+ const SELECTOR_RE = new RegExp(`^${COMPOUND}(?:\\s*>\\s*${COMPOUND}|\\s+${COMPOUND})*(?:::(?:before|after))?$`);
32
+ const HOVERISH_RE = /:(hover|active|focus-visible|focus-within)/;
33
+ /** The skin's selector, rewritten into its slot; null when it reaches outside. */
34
+ export function rewriteSelector(slot, selector) {
35
+ const s = selector.trim();
36
+ if (!SELECTOR_RE.test(s))
37
+ return null;
38
+ const prefix = classPrefix(slot);
39
+ return `[data-kit-slot="${slot}"] ${s.replace(/\.([a-z][a-z0-9-]{0,31})/g, (_m, name) => `.${prefix}${name}`)}`;
40
+ }
41
+ /** Split a selector list on its top-level commas (only `nth-*()` holds parentheses). */
42
+ function splitSelectors(text) {
43
+ const out = [];
44
+ let depth = 0;
45
+ let current = '';
46
+ for (const ch of text) {
47
+ if (ch === '(')
48
+ depth++;
49
+ if (ch === ')')
50
+ depth--;
51
+ if (ch === ',' && depth === 0) {
52
+ out.push(current);
53
+ current = '';
54
+ }
55
+ else
56
+ current += ch;
57
+ }
58
+ out.push(current);
59
+ return out;
60
+ }
61
+ // ── conditions ───────────────────────────────────────────────────────────────
62
+ const FEATURE = '\\((?:(?:min|max)-width:\\s*\\d{1,4}px|prefers-reduced-motion:\\s*(?:reduce|no-preference))\\)';
63
+ const CONDITION_RE = new RegExp(`^${FEATURE}(?:\\s+and\\s+${FEATURE})*$`);
64
+ const WIDTH_CONDITION_RE = /^\((?:min|max)-width:\s*\d{1,4}px\)(?:\s+and\s+\((?:min|max)-width:\s*\d{1,4}px\))*$/;
65
+ /** Every property a skin may set, longhand or shorthand, and what its value may hold. */
66
+ const PROPERTIES = {
67
+ display: 'plain',
68
+ position: 'plain',
69
+ 'inset-block-start': 'length',
70
+ 'inset-block-end': 'length',
71
+ 'inset-inline-start': 'length',
72
+ 'inset-inline-end': 'length',
73
+ inset: 'length',
74
+ 'inset-block': 'length',
75
+ 'inset-inline': 'length',
76
+ 'z-index': 'plain',
77
+ 'box-sizing': 'plain',
78
+ width: 'length',
79
+ height: 'length',
80
+ 'min-width': 'length',
81
+ 'min-height': 'length',
82
+ 'max-width': 'length',
83
+ 'max-height': 'length',
84
+ 'inline-size': 'length',
85
+ 'block-size': 'length',
86
+ 'min-inline-size': 'length',
87
+ 'min-block-size': 'length',
88
+ 'max-inline-size': 'length',
89
+ 'max-block-size': 'length',
90
+ 'aspect-ratio': 'plain',
91
+ margin: 'length',
92
+ 'margin-block': 'length',
93
+ 'margin-inline': 'length',
94
+ 'margin-block-start': 'length',
95
+ 'margin-block-end': 'length',
96
+ 'margin-inline-start': 'length',
97
+ 'margin-inline-end': 'length',
98
+ padding: 'length',
99
+ 'padding-block': 'length',
100
+ 'padding-inline': 'length',
101
+ 'padding-block-start': 'length',
102
+ 'padding-block-end': 'length',
103
+ 'padding-inline-start': 'length',
104
+ 'padding-inline-end': 'length',
105
+ gap: 'length',
106
+ 'row-gap': 'length',
107
+ 'column-gap': 'length',
108
+ border: 'color',
109
+ 'border-width': 'length',
110
+ 'border-style': 'plain',
111
+ 'border-color': 'color',
112
+ 'border-block': 'color',
113
+ 'border-inline': 'color',
114
+ 'border-block-start': 'color',
115
+ 'border-block-end': 'color',
116
+ 'border-inline-start': 'color',
117
+ 'border-inline-end': 'color',
118
+ 'border-block-width': 'length',
119
+ 'border-inline-width': 'length',
120
+ 'border-block-style': 'plain',
121
+ 'border-inline-style': 'plain',
122
+ 'border-block-color': 'color',
123
+ 'border-inline-color': 'color',
124
+ 'border-block-start-width': 'length',
125
+ 'border-block-end-width': 'length',
126
+ 'border-inline-start-width': 'length',
127
+ 'border-inline-end-width': 'length',
128
+ 'border-block-start-style': 'plain',
129
+ 'border-block-end-style': 'plain',
130
+ 'border-inline-start-style': 'plain',
131
+ 'border-inline-end-style': 'plain',
132
+ 'border-block-start-color': 'color',
133
+ 'border-block-end-color': 'color',
134
+ 'border-inline-start-color': 'color',
135
+ 'border-inline-end-color': 'color',
136
+ 'border-radius': 'radius',
137
+ 'border-start-start-radius': 'radius',
138
+ 'border-start-end-radius': 'radius',
139
+ 'border-end-start-radius': 'radius',
140
+ 'border-end-end-radius': 'radius',
141
+ outline: 'color',
142
+ 'outline-width': 'length',
143
+ 'outline-style': 'plain',
144
+ 'outline-color': 'color',
145
+ 'outline-offset': 'length',
146
+ color: 'color',
147
+ background: 'color',
148
+ 'background-color': 'color',
149
+ 'background-size': 'length',
150
+ 'background-position': 'length',
151
+ 'background-repeat': 'plain',
152
+ 'background-clip': 'plain',
153
+ 'font-family': 'face',
154
+ 'font-size': 'textSize',
155
+ 'font-weight': 'weight',
156
+ 'font-style': 'plain',
157
+ 'font-variant-numeric': 'plain',
158
+ 'line-height': 'length',
159
+ 'letter-spacing': 'length',
160
+ 'word-spacing': 'length',
161
+ 'text-transform': 'plain',
162
+ 'text-decoration': 'color',
163
+ 'text-decoration-line': 'plain',
164
+ 'text-decoration-style': 'plain',
165
+ 'text-decoration-color': 'color',
166
+ 'text-decoration-thickness': 'length',
167
+ 'text-underline-offset': 'length',
168
+ 'text-align': 'plain',
169
+ 'text-wrap': 'plain',
170
+ 'text-wrap-mode': 'plain',
171
+ 'text-wrap-style': 'plain',
172
+ 'white-space': 'plain',
173
+ 'white-space-collapse': 'plain',
174
+ hyphens: 'plain',
175
+ 'vertical-align': 'length',
176
+ 'overflow-wrap': 'plain',
177
+ 'word-break': 'plain',
178
+ 'text-overflow': 'plain',
179
+ 'text-shadow': 'shadow',
180
+ 'box-shadow': 'shadow',
181
+ flex: 'length',
182
+ 'flex-flow': 'plain',
183
+ 'flex-direction': 'plain',
184
+ 'flex-wrap': 'plain',
185
+ 'flex-grow': 'plain',
186
+ 'flex-shrink': 'plain',
187
+ 'flex-basis': 'length',
188
+ order: 'plain',
189
+ 'align-items': 'plain',
190
+ 'align-self': 'plain',
191
+ 'align-content': 'plain',
192
+ 'justify-content': 'plain',
193
+ 'justify-items': 'plain',
194
+ 'justify-self': 'plain',
195
+ 'place-items': 'plain',
196
+ 'place-content': 'plain',
197
+ 'place-self': 'plain',
198
+ 'grid-template-columns': 'length',
199
+ 'grid-template-rows': 'length',
200
+ 'grid-template-areas': 'grid',
201
+ 'grid-auto-flow': 'plain',
202
+ 'grid-auto-columns': 'length',
203
+ 'grid-auto-rows': 'length',
204
+ 'grid-area': 'grid',
205
+ 'grid-row': 'grid',
206
+ 'grid-column': 'grid',
207
+ 'grid-row-start': 'grid',
208
+ 'grid-row-end': 'grid',
209
+ 'grid-column-start': 'grid',
210
+ 'grid-column-end': 'grid',
211
+ overflow: 'plain',
212
+ 'overflow-x': 'plain',
213
+ 'overflow-y': 'plain',
214
+ 'object-fit': 'plain',
215
+ 'object-position': 'length',
216
+ transform: 'transform',
217
+ translate: 'length',
218
+ scale: 'plain',
219
+ rotate: 'plain',
220
+ 'transform-origin': 'length',
221
+ transition: 'motion',
222
+ 'transition-property': 'motion',
223
+ 'transition-duration': 'motion',
224
+ 'transition-timing-function': 'motion',
225
+ 'transition-delay': 'motion',
226
+ 'transition-behavior': 'motion',
227
+ 'list-style-type': 'plain',
228
+ 'list-style': 'plain',
229
+ cursor: 'plain',
230
+ content: 'content',
231
+ };
232
+ /** Shorthands, biggest first: each is read whole so a `var()` inside it survives. */
233
+ const SHORTHANDS = [
234
+ 'border',
235
+ 'margin',
236
+ 'padding',
237
+ 'inset',
238
+ 'border-width',
239
+ 'border-style',
240
+ 'border-color',
241
+ 'border-radius',
242
+ 'border-block',
243
+ 'border-inline',
244
+ 'border-block-start',
245
+ 'border-block-end',
246
+ 'border-inline-start',
247
+ 'border-inline-end',
248
+ 'border-block-width',
249
+ 'border-inline-width',
250
+ 'border-block-style',
251
+ 'border-inline-style',
252
+ 'border-block-color',
253
+ 'border-inline-color',
254
+ 'margin-block',
255
+ 'margin-inline',
256
+ 'padding-block',
257
+ 'padding-inline',
258
+ 'inset-block',
259
+ 'inset-inline',
260
+ 'gap',
261
+ 'outline',
262
+ 'background',
263
+ 'text-decoration',
264
+ 'flex',
265
+ 'flex-flow',
266
+ 'place-items',
267
+ 'place-content',
268
+ 'place-self',
269
+ 'grid-area',
270
+ 'grid-row',
271
+ 'grid-column',
272
+ 'overflow',
273
+ 'transition',
274
+ 'list-style',
275
+ 'white-space',
276
+ 'text-wrap',
277
+ ];
278
+ /** Shorthands whose four values run top, right, bottom, left: right and left must agree (logical only, CD9). */
279
+ const SIDED = new Set(['margin', 'padding', 'inset', 'border-width', 'border-style', 'border-color']);
280
+ /** Keywords a value may hold. No colour names, no physical sides. */
281
+ const KEYWORDS = new Set(('auto none normal inherit initial unset revert solid dashed dotted double groove ridge inset outset hidden visible clip scroll ' +
282
+ 'center start end self-start self-end flex-start flex-end space-between space-around space-evenly stretch baseline first last safe unsafe ' +
283
+ 'row column row-reverse column-reverse wrap nowrap wrap-reverse dense ' +
284
+ 'block inline inline-block flex inline-flex grid inline-grid contents flow-root list-item ' +
285
+ 'static relative absolute sticky border-box content-box padding-box ' +
286
+ 'ease ease-in ease-out ease-in-out linear step-start step-end jump-start jump-end jump-none jump-both allow-discrete ' +
287
+ 'uppercase lowercase capitalize underline overline line-through from-font wavy ' +
288
+ 'italic oblique bold bolder lighter tabular-nums proportional-nums lining-nums oldstyle-nums slashed-zero ' +
289
+ 'cover contain fill scale-down no-repeat repeat repeat-x repeat-y round space ' +
290
+ 'balance pretty stable break-word break-all keep-all anywhere ellipsis pre pre-line pre-wrap break-spaces collapse preserve preserve-breaks manual ' +
291
+ 'top bottom middle text-top text-bottom sub super ' +
292
+ 'currentcolor transparent min-content max-content fit-content span ' +
293
+ 'disc decimal square circle pointer default justify all').split(' '));
294
+ /** Keywords no skin may write, though a property elsewhere may know them. */
295
+ const FORBIDDEN_VALUES = {
296
+ position: new Set(['fixed']),
297
+ 'text-align': new Set(['left', 'right']),
298
+ };
299
+ const FUNCTIONS = new Set(['var', 'calc', 'min', 'max', 'clamp', 'minmax', 'repeat', 'fit-content', 'cubic-bezier', 'steps', 'translate', 'translatex', 'translatey', 'scale', 'rotate']);
300
+ const NUMBER_RE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?(px|%|em|rem|ch|ex|lh|vw|vh|svh|lvh|dvh|vmin|vmax|cqi|cqb|cqw|cqh|fr|deg|turn|rad|s|ms)?$/i;
301
+ const IDENT_RE = /^-?[a-zA-Z][a-zA-Z0-9-]*$/;
302
+ const AREA_IDENT_RE = /^[a-z][a-z0-9-]{0,23}$/;
303
+ const AREAS_STRING_RE = /^"(?:[a-z][a-z0-9-]{0,23}|\.)(?: (?:[a-z][a-z0-9-]{0,23}|\.))*"$/;
304
+ const COLOR_VARS = new Set([...COLOR_TOKENS, ...DERIVED_TOKENS, '--scrim-photo', '--scrim-fg']);
305
+ const VARS_BY_CATEGORY = {
306
+ radius: new Set(RADIUS_TOKENS),
307
+ shadow: new Set(SHADOW_TOKENS),
308
+ face: new Set(FACE_TOKENS),
309
+ textSize: new Set(APP_TOKENS.filter((t) => t.startsWith('--text-'))),
310
+ weight: new Set(APP_TOKENS.filter((t) => t.startsWith('--weight-'))),
311
+ };
312
+ /** The value's tokens: a crude CSS tokenizer, enough to refuse what isn't listed. */
313
+ function tokens(value) {
314
+ const out = [];
315
+ let i = 0;
316
+ while (i < value.length) {
317
+ const ch = value[i] ?? '';
318
+ if (/\s/.test(ch)) {
319
+ i++;
320
+ continue;
321
+ }
322
+ if ('(),/'.includes(ch)) {
323
+ out.push(ch);
324
+ i++;
325
+ continue;
326
+ }
327
+ if (ch === '"') {
328
+ const end = value.indexOf('"', i + 1);
329
+ if (end < 0)
330
+ return null;
331
+ out.push(value.slice(i, end + 1));
332
+ i = end + 1;
333
+ continue;
334
+ }
335
+ const m = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?[a-zA-Z%]*|^-{0,2}[a-zA-Z][a-zA-Z0-9-]*|^[+*-]/.exec(value.slice(i));
336
+ if (m === null)
337
+ return null; // a `#`, a `\`, a `!`, a `;`, an `@`, a `'`…
338
+ out.push(m[0]);
339
+ i += m[0].length;
340
+ }
341
+ return out;
342
+ }
343
+ /** Why a value can't stand for its property, or null when it reads. */
344
+ export function valueProblem(property, value, context, selector) {
345
+ const category = PROPERTIES[property];
346
+ if (category === undefined)
347
+ return 'is not a property a skin may set';
348
+ const v = value.trim();
349
+ if (v === '')
350
+ return 'is empty';
351
+ if (/[\\;{}!@<>]|url\(|image|attr\(|env\(|src\(|expression|element\(/i.test(v))
352
+ return 'holds something a skin may not load or write';
353
+ if (category === 'content')
354
+ return v === '""' || v === 'none' || v === "''" ? (/::(before|after)$/.test(selector.trim()) ? null : 'content is only for ::before and ::after') : 'content is only ""';
355
+ if (category === 'face')
356
+ return /^var\(--font-(display|heading|text|mono)\)$/.test(v) ? null : 'font-family is var(--font-display|heading|text|mono)';
357
+ if (category === 'shadow')
358
+ return v === 'none' || /^var\(--shadow(-md|-lg)?\)$/.test(v) ? null : `${property} is none or var(--shadow), var(--shadow-md), var(--shadow-lg)`;
359
+ if (property === 'z-index')
360
+ return v === 'auto' || (/^\d{1,2}$/.test(v) && Number(v) <= 10) ? null : 'z-index is 0 to 10';
361
+ const forbidden = FORBIDDEN_VALUES[property];
362
+ if (forbidden !== undefined && forbidden.has(v.toLowerCase()))
363
+ return `${property}: ${v} isn't allowed`;
364
+ if (property === 'background' && !(/^var\(--[a-z0-9-]+\)$/.test(v) || v === 'transparent' || v === 'none'))
365
+ return 'background is one colour token';
366
+ if (category === 'grid' && property === 'grid-template-areas') {
367
+ const strings = v.match(/"[^"]*"/g) ?? [];
368
+ if (v !== 'none' && (strings.length === 0 || strings.join(' ') !== v.replace(/\s+/g, ' ') || strings.some((s) => !AREAS_STRING_RE.test(s))))
369
+ return 'grid-template-areas is rows of area names';
370
+ return null;
371
+ }
372
+ const list = tokens(v);
373
+ if (list === null)
374
+ return 'holds a character no skin value has';
375
+ let depth = 0;
376
+ const callStack = [];
377
+ for (let i = 0; i < list.length; i++) {
378
+ const tok = list[i] ?? '';
379
+ const next = list[i + 1];
380
+ if (tok === '(') {
381
+ depth++;
382
+ continue;
383
+ }
384
+ if (tok === ')') {
385
+ depth--;
386
+ callStack.pop();
387
+ if (depth < 0)
388
+ return 'has an unmatched ")"';
389
+ continue;
390
+ }
391
+ if (tok === ',' || tok === '/' || tok === '+' || tok === '-' || tok === '*')
392
+ continue;
393
+ if (tok.startsWith('"'))
394
+ return 'holds a string';
395
+ if (next === '(') {
396
+ const fn = tok.toLowerCase();
397
+ if (!FUNCTIONS.has(fn))
398
+ return `uses ${tok}(), which a skin may not`;
399
+ if (fn === 'var') {
400
+ const name = list[i + 2] ?? '';
401
+ if (list[i + 3] !== ')')
402
+ return 'var() takes one token and no fallback';
403
+ const allowed = category === 'color' || property === 'color'
404
+ ? COLOR_VARS.has(name) || (context.appColors ?? []).includes(name)
405
+ : (VARS_BY_CATEGORY[category]?.has(name) ?? false) || (category === 'length' && RADIUS_TOKENS.includes(name));
406
+ if (!allowed)
407
+ return `var(${name}) is not a token ${property} may read`;
408
+ i += 3;
409
+ continue;
410
+ }
411
+ if ((fn === 'translate' || fn.startsWith('translate') || fn === 'scale' || fn === 'rotate') && category !== 'transform')
412
+ return `${tok}() belongs in transform`;
413
+ callStack.push(fn);
414
+ continue;
415
+ }
416
+ if (NUMBER_RE.test(tok))
417
+ continue;
418
+ if (IDENT_RE.test(tok)) {
419
+ const word = tok.toLowerCase();
420
+ if (KEYWORDS.has(word))
421
+ continue;
422
+ if (category === 'grid' && AREA_IDENT_RE.test(tok))
423
+ continue;
424
+ if (category === 'motion' && (PROPERTIES[word] !== undefined || word === 'all'))
425
+ continue;
426
+ return `"${tok}" is not a value a skin may write here`;
427
+ }
428
+ return `"${tok}" is not a value a skin may write`;
429
+ }
430
+ if (depth !== 0)
431
+ return 'has an unmatched "("';
432
+ if (SIDED.has(property)) {
433
+ const parts = v.split(/\s+(?![^(]*\))/);
434
+ if (parts.length === 4 && parts[1] !== parts[3])
435
+ return `${property} with four values sets right and left apart; use the logical properties`;
436
+ }
437
+ if (property === 'border-radius' && v.split(/\s+(?![^(]*\))/).length > 1)
438
+ return 'border-radius takes one value; use the logical corners';
439
+ return lineProblem(property, v);
440
+ }
441
+ /** Line widths in px, at most: a skin's outline or border can't become a cover. */
442
+ const LINE_CAPS = {
443
+ outline: 8,
444
+ 'outline-width': 8,
445
+ 'outline-offset': 16,
446
+ border: 16,
447
+ 'border-width': 16,
448
+ 'border-block': 16,
449
+ 'border-inline': 16,
450
+ 'border-block-start': 16,
451
+ 'border-block-end': 16,
452
+ 'border-inline-start': 16,
453
+ 'border-inline-end': 16,
454
+ 'border-block-width': 16,
455
+ 'border-inline-width': 16,
456
+ 'border-block-start-width': 16,
457
+ 'border-block-end-width': 16,
458
+ 'border-inline-start-width': 16,
459
+ 'border-inline-end-width': 16,
460
+ };
461
+ /** Why a line width is too wide, or null. */
462
+ function lineProblem(property, value) {
463
+ const cap = LINE_CAPS[property];
464
+ if (cap === undefined)
465
+ return null;
466
+ for (const word of value.split(/[\s,()]+/)) {
467
+ const m = /^-?(\d+\.?\d*|\.\d+)([a-z%]*)$/i.exec(word);
468
+ if (m === null)
469
+ continue;
470
+ if (m[2] !== '' && m[2]?.toLowerCase() !== 'px')
471
+ return `${property} is written in px`;
472
+ if (Math.abs(Number(m[1])) > cap)
473
+ return `${property} is at most ${String(cap)}px`;
474
+ }
475
+ return null;
476
+ }
477
+ /** Which colour a ground (background) needs on it. */
478
+ const PARTNERS = {
479
+ '--bg': new Set(['--fg', '--fg-muted', '--fg-subtle', '--accent', '--pos', '--warn', '--danger', '--info']),
480
+ '--surface': new Set(['--fg', '--fg-muted', '--fg-subtle', '--accent', '--pos', '--warn', '--danger', '--info']),
481
+ '--surface-2': new Set(['--fg', '--fg-muted', '--fg-subtle', '--accent', '--pos', '--warn', '--danger', '--info']),
482
+ '--surface-3': new Set(['--fg', '--fg-muted', '--fg-subtle', '--accent', '--pos', '--warn', '--danger', '--info']),
483
+ '--accent': new Set(['--accent-fg']),
484
+ '--accent-2': new Set(['--accent-2-fg']),
485
+ '--scrim-photo': new Set(['--scrim-fg']),
486
+ '--pos-soft': new Set(['--pos', '--fg']),
487
+ '--warn-soft': new Set(['--warn', '--fg']),
488
+ '--danger-soft': new Set(['--danger', '--fg']),
489
+ '--info-soft': new Set(['--info', '--fg']),
490
+ };
491
+ const varName = (value) => /^var\((--[a-z0-9-]+)\)$/.exec(value.trim())?.[1] ?? null;
492
+ // ── the browser part ─────────────────────────────────────────────────────────
493
+ /** The longhands the browser expands a shorthand into, asked of the browser itself. */
494
+ const longhandCache = new Map();
495
+ function longhandsOf(shorthand) {
496
+ const cached = longhandCache.get(shorthand);
497
+ if (cached !== undefined)
498
+ return cached;
499
+ const style = document.createElement('div').style;
500
+ style.setProperty(shorthand, 'inherit');
501
+ const out = [];
502
+ for (let i = 0; i < style.length; i++)
503
+ out.push(style.item(i));
504
+ longhandCache.set(shorthand, out);
505
+ return out;
506
+ }
507
+ /** The declarations of one parsed style rule, read through the allow-list. */
508
+ function readDeclarations(style, slot, where, context, dropped, selector, motionWelcome) {
509
+ const kept = [];
510
+ const covered = new Set();
511
+ const take = (property, value) => {
512
+ const problem = valueProblem(property, value, context, selector);
513
+ if (problem !== null) {
514
+ dropped.push({ slot, where, property, reason: problem });
515
+ return false;
516
+ }
517
+ if (['transform', 'translate', 'scale', 'rotate'].includes(property) && HOVERISH_RE.test(selector) && !motionWelcome) {
518
+ dropped.push({ slot, where, property, reason: 'a hover movement goes inside @media (prefers-reduced-motion: no-preference)' });
519
+ return false;
520
+ }
521
+ kept.push([property, value.trim()]);
522
+ return true;
523
+ };
524
+ for (const shorthand of SHORTHANDS) {
525
+ const value = style.getPropertyValue(shorthand);
526
+ if (value === '')
527
+ continue;
528
+ const longhands = longhandsOf(shorthand);
529
+ if (longhands.every((l) => covered.has(l)))
530
+ continue;
531
+ take(shorthand, value);
532
+ for (const l of longhands)
533
+ covered.add(l);
534
+ }
535
+ for (let i = 0; i < style.length; i++) {
536
+ const property = style.item(i);
537
+ if (covered.has(property))
538
+ continue;
539
+ covered.add(property);
540
+ if (property.startsWith('--')) {
541
+ dropped.push({ slot, where, property, reason: 'a skin may not set a custom property' });
542
+ continue;
543
+ }
544
+ if (PROPERTIES[property] === undefined) {
545
+ dropped.push({ slot, where, property, reason: /left|right|top|bottom|float|clear/.test(property) ? 'a physical side: use the logical property' : 'is not a property a skin may set' });
546
+ continue;
547
+ }
548
+ const value = style.getPropertyValue(property);
549
+ if (value === '') {
550
+ dropped.push({ slot, where, property, reason: 'only readable through its shorthand, which this rule mixes' });
551
+ continue;
552
+ }
553
+ take(property, value);
554
+ }
555
+ // A ground needs its partner colour in the same rule.
556
+ const ground = kept.find(([p]) => p === 'background-color' || p === 'background');
557
+ if (ground !== undefined) {
558
+ const name = varName(ground[1]);
559
+ if (name !== null) {
560
+ const color = kept.find(([p]) => p === 'color');
561
+ const partners = PARTNERS[name];
562
+ const ok = partners === undefined ? color !== undefined : color !== undefined && partners.has(varName(color[1]) ?? '');
563
+ if (!ok) {
564
+ dropped.push({ slot, where, property: ground[0], reason: `a ground of ${name} needs its text colour (${[...(partners ?? new Set(['a colour']))].join(' or ')}) in the same rule` });
565
+ return kept.filter((d) => d !== ground);
566
+ }
567
+ }
568
+ }
569
+ return kept;
570
+ }
571
+ /** One slot's CSS, parsed by the browser and read back through the allow-list. */
572
+ export function filterSlotCss(slot, text, context) {
573
+ const dropped = [];
574
+ const rules = [];
575
+ const sheet = new CSSStyleSheet();
576
+ try {
577
+ sheet.replaceSync(text);
578
+ }
579
+ catch {
580
+ return { rules, dropped: [{ slot, where: '(sheet)', reason: 'the browser could not read it' }] };
581
+ }
582
+ const visit = (list, condition, motionWelcome) => {
583
+ for (const rule of Array.from(list)) {
584
+ if (rule instanceof CSSStyleRule) {
585
+ const where = rule.selectorText;
586
+ if (rule.cssRules?.length) {
587
+ dropped.push({ slot, where, reason: 'a nested rule: write each rule on its own' });
588
+ continue;
589
+ }
590
+ const selectors = splitSelectors(rule.selectorText).map((s) => rewriteSelector(slot, s));
591
+ if (selectors.some((s) => s === null)) {
592
+ dropped.push({ slot, where, reason: 'a selector reaches outside the skin\'s own classes' });
593
+ continue;
594
+ }
595
+ const declarations = readDeclarations(rule.style, slot, where, context, dropped, rule.selectorText, motionWelcome);
596
+ if (declarations.length > 0)
597
+ rules.push({ condition, selector: selectors.join(', '), declarations });
598
+ continue;
599
+ }
600
+ if (rule instanceof CSSMediaRule && condition === null) {
601
+ const text = rule.media.mediaText.trim();
602
+ if (!CONDITION_RE.test(text)) {
603
+ dropped.push({ slot, where: `@media ${text}`, reason: 'a media query asks only for width or reduced motion' });
604
+ continue;
605
+ }
606
+ visit(rule.cssRules, { kind: 'media', text }, /prefers-reduced-motion:\s*no-preference/.test(text));
607
+ continue;
608
+ }
609
+ const container = globalThis.CSSContainerRule !== undefined && rule instanceof CSSContainerRule ? rule : null;
610
+ if (container !== null && condition === null) {
611
+ const name = container.containerName;
612
+ const query = container.containerQuery.trim();
613
+ if (name !== context.container || !WIDTH_CONDITION_RE.test(query)) {
614
+ dropped.push({ slot, where: `@container ${container.conditionText}`, reason: `a container query asks ${context.container} for its width only` });
615
+ continue;
616
+ }
617
+ visit(container.cssRules, { kind: "container", text: `${name} ${query}` }, false);
618
+ continue;
619
+ }
620
+ dropped.push({ slot, where: rule.cssText.slice(0, 60), reason: 'only style rules, @media and @container are kept' });
621
+ }
622
+ };
623
+ visit(sheet.cssRules, null, false);
624
+ return { rules, dropped };
625
+ }
626
+ /**
627
+ * The guard: the kit's own rules, above the skin. `!important` in the first
628
+ * layer wins over any skin rule, layered or not.
629
+ */
630
+ export function guardCss() {
631
+ const ring = 'outline: 2px solid var(--focus-ring) !important; outline-offset: 2px !important;';
632
+ return [
633
+ '[data-kit-slot] { contain: paint !important; isolation: isolate !important; position: relative !important; }',
634
+ '[data-kit-hostpath] { opacity: 1 !important; transform: none !important; translate: none !important; scale: none !important; rotate: none !important; filter: none !important; clip-path: none !important; visibility: visible !important; overflow: visible !important; z-index: auto !important; }',
635
+ '.kit-host { display: block !important; position: relative !important; z-index: 20 !important; visibility: visible !important; opacity: 1 !important; font-size: var(--text-md, 14px) !important; font-family: var(--font-text) !important; font-weight: var(--weight-normal, 400) !important; font-style: normal !important; letter-spacing: normal !important; word-spacing: normal !important; text-transform: none !important; text-indent: 0 !important; line-height: normal !important; color: var(--fg) !important; }',
636
+ '[data-kit-on="accent"] .kit-host, .kit-host[data-kit-on="accent"] { color: var(--accent-fg) !important; }',
637
+ '[data-kit-on="accent-2"] .kit-host, .kit-host[data-kit-on="accent-2"] { color: var(--accent-2-fg) !important; }',
638
+ `[data-kit-slot] :focus-visible { ${ring} }`,
639
+ '[data-kit-on="accent"] :focus-visible { outline-color: var(--accent-fg) !important; }',
640
+ '[data-kit-on="accent-2"] :focus-visible { outline-color: var(--accent-2-fg) !important; }',
641
+ '.kit-host { grid-area: var(--kit-area, auto); }',
642
+ '.kit-mono { font-family: var(--font-mono); }',
643
+ '.kit-figure { font-family: var(--app-font-mono) !important; font-variant-numeric: tabular-nums !important; font-weight: 500 !important; }',
644
+ '@media (prefers-reduced-motion: reduce) { [data-kit-slot] *, [data-kit-slot] *::before, [data-kit-slot] *::after { transition: none !important; animation: none !important; } }',
645
+ ].join('\n');
646
+ }
647
+ /**
648
+ * The skin's sheet: `@layer kit-guard, skin;`, the guard, then every kept rule
649
+ * built through CSSOM, so no value can leave its declaration.
650
+ */
651
+ export function buildSheet(kept) {
652
+ const dropped = [];
653
+ const sheet = new CSSStyleSheet();
654
+ sheet.insertRule('@layer kit-guard, skin;', 0);
655
+ sheet.insertRule(`@layer kit-guard { ${guardCss()} }`, sheet.cssRules.length);
656
+ const layerIndex = sheet.insertRule('@layer skin {}', sheet.cssRules.length);
657
+ const layer = sheet.cssRules[layerIndex];
658
+ for (const rule of kept) {
659
+ let target = layer;
660
+ if (rule.condition !== null) {
661
+ const index = layer.insertRule(`@${rule.condition.kind} ${rule.condition.text} {}`, layer.cssRules.length);
662
+ target = layer.cssRules[index];
663
+ }
664
+ const index = target.insertRule(`${rule.selector} {}`, target.cssRules.length);
665
+ const style = target.cssRules[index].style;
666
+ for (const [property, value] of rule.declarations) {
667
+ style.setProperty(property, value);
668
+ if (style.getPropertyValue(property) === '' && !longhandsOf(property).some((l) => style.getPropertyValue(l) !== '')) {
669
+ dropped.push({ slot: '(build)', where: rule.selector, property, reason: 'the browser refused the value' });
670
+ }
671
+ }
672
+ }
673
+ return { sheet, dropped };
674
+ }
675
+ /** Whether this browser has what the filter and the guard rely on; with any missing, the shop draws its own skin. */
676
+ export function browserCanSkin() {
677
+ try {
678
+ return (typeof CSSStyleSheet === 'function' &&
679
+ typeof CSSStyleSheet.prototype.replaceSync === 'function' &&
680
+ typeof globalThis.CSSLayerBlockRule === 'function' &&
681
+ typeof CSS !== 'undefined' &&
682
+ CSS.supports('contain', 'paint') &&
683
+ CSS.supports('isolation', 'isolate') &&
684
+ typeof Element.prototype.checkVisibility === 'function');
685
+ }
686
+ catch {
687
+ return false;
688
+ }
689
+ }
690
+ //# sourceMappingURL=css.js.map