@barocss/kit 0.10.3 → 0.11.0

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/index.js CHANGED
@@ -270,249 +270,571 @@ function clearContextCaches(ctx) {
270
270
  state.failures.clear();
271
271
  }
272
272
  //#endregion
273
- //#region src/core/registry.ts
274
- var utilityRegistry = [];
275
- function registerUtility(util, ctx) {
276
- const state = ctx && getContextState(ctx);
277
- if (ctx && !state) throw new Error("Utility registration requires a context from createContext");
278
- (state?.utilities || utilityRegistry).push(util);
279
- if (ctx) clearContextCaches(ctx);
280
- else {
281
- parseResultCache.clear();
282
- utilityCache.clear();
283
- }
284
- }
285
- function getUtility(ctx) {
286
- return ctx && getContextState(ctx)?.utilities || utilityRegistry;
287
- }
288
- var modifierRegistry = [];
273
+ //#region src/core/utils.ts
289
274
  /**
290
- * staticModifier: A helper that registers a modifier name and an array of CSS selectors directly to the registry
291
- *
292
- * @example
293
- * ```
294
- * staticModifier('disabled', ['&:disabled'], { source: 'pseudo' });
295
- * ```
296
- *
297
- * @param name The name of the modifier
298
- * @param selectors The selectors of the modifier
299
- * @param options The options of the modifier
300
- *
301
- * @returns {void}
275
+ * Parses a fraction string (e.g., '1/2') and returns a percentage string (e.g., '50%'), or null if not a valid fraction.
302
276
  */
303
- function staticModifier(name, selectors, options = {}, ctx) {
304
- registerModifier({
305
- name,
306
- match: (mod) => mod === name,
307
- modifySelector: ({ ..._rest }) => {
308
- return selectors.map((sel) => ({
309
- selector: sel,
310
- source: options.source
311
- }));
312
- },
313
- ...options
314
- }, ctx);
315
- }
316
- function functionalModifier(match, modifySelector, wrap, options = {}, ctx) {
317
- registerModifier({
318
- match,
319
- modifySelector,
320
- wrap,
321
- ...options
322
- }, ctx);
323
- }
324
- function registerModifier(modifier, ctx) {
325
- const state = ctx && getContextState(ctx);
326
- if (ctx && !state) throw new Error("Modifier registration requires a context from createContext");
327
- (state?.modifiers || modifierRegistry).push(modifier);
328
- if (ctx) clearContextCaches(ctx);
329
- }
330
- function getModifier(ctx) {
331
- return ctx && getContextState(ctx)?.modifiers || modifierRegistry;
332
- }
333
- var ESCAPE_REGEX = /[^A-Za-z0-9_-]/gu;
334
- var UNSAFE_RAW = /^[\s\p{C}\p{Z}]$/u;
335
- function escapeClassName(className) {
336
- if (className === "-") return "\\-";
337
- const lead = /^-?[0-9]/.exec(className);
338
- if (lead) {
339
- const i = lead[0].length - 1;
340
- return className.slice(0, i) + "\\" + className.charCodeAt(i).toString(16) + " " + escapeRest(className.slice(i + 1));
277
+ function parseFraction(input) {
278
+ if (input.includes("/")) {
279
+ const [num, denom] = input.split("/").map(Number);
280
+ if (!isNaN(num) && !isNaN(denom) && denom !== 0) return `${num / denom * 100}%`;
341
281
  }
342
- return escapeRest(className);
343
- }
344
- function escapeRest(className) {
345
- return className.replace(ESCAPE_REGEX, (c) => {
346
- if (c === " ") return "\\x20 ";
347
- if (c === ".") return "\\.";
348
- if (c === "/") return "\\/";
349
- if (c === ":") return "\\:";
350
- if (c === "[") return "\\[";
351
- if (c === "]") return "\\]";
352
- if (c === "(") return "\\(";
353
- if (c === ")") return "\\)";
354
- if (c === "%") return "\\%";
355
- if (c === "#") return "\\#";
356
- if (c === ",") return "\\,";
357
- if (c === "=") return "\\=";
358
- if (c === "&") return "\\&";
359
- if (c === "~") return "\\~";
360
- if (c === "*") return "\\*";
361
- if (c === "$") return "\\$";
362
- if (c === "^") return "\\^";
363
- if (c === "+") return "\\+";
364
- if (c === "?") return "\\?";
365
- if (c === "!") return "\\!";
366
- if (c === "@") return "\\@";
367
- if (c === "'") return "\\'";
368
- if (c === "\"") return "\\\"";
369
- if (c === "`") return "\\`";
370
- if (c === ";") return "\\;";
371
- if (c === "<") return "\\<";
372
- if (c === ">") return "\\>";
373
- if (c === "{") return "\\{";
374
- if (c === "}") return "\\}";
375
- if (c === "|") return "\\|";
376
- if (c === "\\") return "\\\\";
377
- if (UNSAFE_RAW.test(c)) return "\\" + c.codePointAt(0).toString(16) + " ";
378
- return "\\" + c;
379
- });
282
+ return null;
380
283
  }
381
284
  /**
382
- * staticUtility: A helper that registers a utility name and an array of CSS declaration pairs directly to the registry
383
- *
384
- * @example
385
- * ```
386
- * staticUtility('block', [['display', 'block']]);
387
- * staticUtility('hidden', [['display', 'none']]);
388
- * staticUtility('space-x-px', [
389
- * [
390
- * '& > :not([hidden]) ~ :not([hidden])', // selector
391
- * [
392
- * ['margin-inline-start', '1px'], // [prop, value]
393
- * ['margin-inline-end', '1px'], // [prop, value]
394
- * ],
395
- * ],
396
- * ]);
397
- * ```
398
- *
399
- * @param name The name of the utility
400
- * @param decls The declarations of the utility
401
- * @param opts The options of the utility
285
+ * Returns the input if it is a valid non-negative integer string, else null.
402
286
  *
403
- * @returns {void}
287
+ * @example
288
+ * parseNumber("10") // "10"
289
+ * parseNumber("-10") // "-10"
290
+ * parseNumber("10.5") // "10.5"
404
291
  */
405
- function staticUtility(name, decls, opts, ctx) {
406
- registerUtility({
407
- name,
408
- match: (className) => {
409
- return className === name;
410
- },
411
- handler: (value) => {
412
- return decls.flatMap((params) => {
413
- if (params.type) return [params];
414
- if (typeof params === "function") return [params(value)];
415
- const [a, b] = params;
416
- if (typeof b === "string") return [decl(a, b)];
417
- else if (Array.isArray(b)) return [rule(a, b.map(([prop, value]) => decl(prop, value)))];
418
- return [];
419
- });
420
- },
421
- description: opts?.description,
422
- category: opts?.category,
423
- priority: opts?.priority
424
- }, ctx);
292
+ function parseNumber(input) {
293
+ return /^-?\d+(?:\.\d+)?$/.test(input) ? input : null;
425
294
  }
426
295
  /**
427
- * functionalUtility: A helper that registers dynamic utilities (theme, arbitrary, custom, negative, fraction, etc.) directly
428
- *
429
- * Example:
430
- * functionalUtility({
431
- * name: 'z',
432
- * supportsNegative: true,
433
- * themeKeys: ['--z-index'],
434
- * handleBareValue: ({ value }) => isPositiveInteger(value) ? value : null,
435
- * handle: (value) => [decl('z-index', value)],
436
- * description: 'z-index utility',
437
- * category: 'layout',
438
- * });
296
+ * Returns the input if it is a valid length string, else null.
439
297
  */
298
+ function parseLength(input) {
299
+ return /^\d+(px|em|rem|vh|vw|vmin|vmax|%|in|cm|mm|pt|pc|ex|ch|fr)$/.test(input) ? input : null;
300
+ }
440
301
  /**
441
- * #300: a theme key that no built-in utility names (`theme.extend.borderRadius.card`) still resolves, as in
442
- * Tailwind 4 where `--radius-card` gives `rounded-card`. Only word keys that start with a letter (numbers stay
443
- * bare values), never `DEFAULT`; unknown keys return null so the utility emits nothing (#213).
302
+ * Unified parser for fraction or number, with options for percent or repeat syntax.
303
+ * - percent: if true, returns percentage for fraction (e.g., '1/2' -> '50%')
304
+ * - repeat: if true, returns repeat() for number (e.g., '3' -> 'repeat(3, minmax(0, 1fr))')
444
305
  */
445
- function themeKeyEntry(ctx, namespace, key) {
446
- if (key === "DEFAULT" || !/^[a-zA-Z][\w-]*$/.test(key) || typeof ctx?.theme !== "function") return void 0;
447
- const table = ctx.theme(namespace);
448
- if (!table || typeof table !== "object" || !Object.prototype.hasOwnProperty.call(table, key)) return void 0;
449
- return table[key] ?? void 0;
450
- }
451
- /** #300: the literal value of `theme.<namespace>.<key>` when it is a string, else null. */
452
- function themeKeyValue(ctx, namespace, key) {
453
- const v = themeKeyEntry(ctx, namespace, key);
454
- return typeof v === "string" ? v : null;
455
- }
456
- /** #300: `var(--<varPrefix>-<key>)` when `theme.<namespace>.<key>` exists (the :root var BaroCSS emits for it), else null. */
457
- function themeKeyVar(ctx, namespace, key, varPrefix) {
458
- return themeKeyEntry(ctx, namespace, key) === void 0 ? null : `var(--${varPrefix}-${key})`;
459
- }
460
- /** #261: `var(--spacing-<key>)` for a named (non-numeric) `theme.spacing` key, else null. */
461
- function spacingKeyValue(ctx, key, negative) {
462
- if (key === "px" || !/^[a-zA-Z][\w-]*$/.test(key) || ctx.theme("spacing", key) == null) return null;
463
- const ref = `var(--spacing-${key})`;
464
- return negative ? `calc(${ref} * -1)` : ref;
306
+ function parseFractionOrNumber(value, opts = {}) {
307
+ if (/^\d+$/.test(value)) {
308
+ if (opts.repeat) return `repeat(${value}, minmax(0, 1fr))`;
309
+ return value;
310
+ }
311
+ if (value.includes("/")) {
312
+ const [numerator, denominator] = value.split("/").map(Number);
313
+ if (!isNaN(numerator) && !isNaN(denominator) && denominator !== 0) {
314
+ const result = numerator / denominator;
315
+ if (opts.percent) return `${result * 100}%`;
316
+ return result.toString();
317
+ }
318
+ }
319
+ return null;
465
320
  }
466
- function functionalUtility(opts, ctx) {
467
- registerUtility({
468
- name: opts.name,
469
- match: (className) => className.startsWith(opts.name + "-"),
470
- handler: (value, ctx, token, _options) => {
471
- let finalValue = value;
472
- const parsedUtility = token;
473
- const extra = { opacity: token.opacity };
474
- if (opts.supportsOpacity && !token.arbitrary && !token.customProperty && value.includes("/")) {
475
- const list = value.split("/");
476
- if (list.length >= 2) {
477
- extra.opacity = list.pop();
478
- finalValue = list.join("/");
479
- }
480
- }
481
- if (opts.supportsArbitrary && parsedUtility.arbitrary) {
482
- const processedValue = normalizeMathSpacing(expandThemeFunctions(finalValue.replace(/_/g, " ")));
483
- if (opts.handle) {
484
- const result = opts.handle(processedValue, ctx, token, extra);
485
- if (result) return result;
486
- }
487
- if (opts.prop) return [decl(opts.prop, processedValue)];
488
- return [];
489
- }
490
- if (opts.supportsCustomProperty && parsedUtility.customProperty) {
491
- if (opts.handleCustomProperty) return opts.handleCustomProperty(finalValue, ctx, token, extra);
492
- const customValue = `var(${finalValue})`;
493
- if (opts.handle) {
494
- const result = opts.handle(customValue, ctx, token, extra);
495
- if (result) return result;
496
- }
497
- if (opts.prop) return [decl(opts.prop, customValue)];
498
- return [];
499
- }
500
- let themeValue;
501
- if (opts.themeKey && ctx.theme) themeValue = themeScalar(ctx.theme(opts.themeKey, finalValue));
502
- let namespace = themeValue !== void 0 ? opts.themeKey : void 0;
503
- if (!themeValue && opts.themeKeys && ctx.theme) for (const key of opts.themeKeys) {
504
- themeValue = themeScalar(ctx.theme(key, finalValue));
505
- if (themeValue !== void 0) {
506
- namespace = key;
507
- break;
508
- }
509
- }
510
- if (themeValue !== void 0) {
511
- extra.themeNamespace = namespace;
512
- extra.themeKey = finalValue;
513
- if (namespace === "colors" || !(opts.themeKeys ?? [opts.themeKey]).includes("colors")) extra.realThemeValue = finalValue;
514
- finalValue = themeValue;
515
- if (opts.prop) return [decl(opts.prop, finalValue)];
321
+ var CSS_COLOR_NAMES = /* @__PURE__ */ new Set([
322
+ "aliceblue",
323
+ "antiquewhite",
324
+ "aqua",
325
+ "aquamarine",
326
+ "azure",
327
+ "beige",
328
+ "bisque",
329
+ "black",
330
+ "blanchedalmond",
331
+ "blue",
332
+ "blueviolet",
333
+ "brown",
334
+ "burlywood",
335
+ "cadetblue",
336
+ "chartreuse",
337
+ "chocolate",
338
+ "coral",
339
+ "cornflowerblue",
340
+ "cornsilk",
341
+ "crimson",
342
+ "cyan",
343
+ "darkblue",
344
+ "darkcyan",
345
+ "darkgoldenrod",
346
+ "darkgray",
347
+ "darkgreen",
348
+ "darkgrey",
349
+ "darkkhaki",
350
+ "darkmagenta",
351
+ "darkolivegreen",
352
+ "darkorange",
353
+ "darkorchid",
354
+ "darkred",
355
+ "darksalmon",
356
+ "darkseagreen",
357
+ "darkslateblue",
358
+ "darkslategray",
359
+ "darkslategrey",
360
+ "darkturquoise",
361
+ "darkviolet",
362
+ "deeppink",
363
+ "deepskyblue",
364
+ "dimgray",
365
+ "dimgrey",
366
+ "dodgerblue",
367
+ "firebrick",
368
+ "floralwhite",
369
+ "forestgreen",
370
+ "fuchsia",
371
+ "gainsboro",
372
+ "ghostwhite",
373
+ "gold",
374
+ "goldenrod",
375
+ "gray",
376
+ "grey",
377
+ "green",
378
+ "greenyellow",
379
+ "honeydew",
380
+ "hotpink",
381
+ "indianred",
382
+ "indigo",
383
+ "ivory",
384
+ "khaki",
385
+ "lavender",
386
+ "lavenderblush",
387
+ "lawngreen",
388
+ "lemonchiffon",
389
+ "lightblue",
390
+ "lightcoral",
391
+ "lightcyan",
392
+ "lightgoldenrodyellow",
393
+ "lightgray",
394
+ "lightgreen",
395
+ "lightgrey",
396
+ "lightpink",
397
+ "lightsalmon",
398
+ "lightseagreen",
399
+ "lightskyblue",
400
+ "lightslategray",
401
+ "lightslategrey",
402
+ "lightsteelblue",
403
+ "lightyellow",
404
+ "lime",
405
+ "limegreen",
406
+ "linen",
407
+ "magenta",
408
+ "maroon",
409
+ "mediumaquamarine",
410
+ "mediumblue",
411
+ "mediumorchid",
412
+ "mediumpurple",
413
+ "mediumseagreen",
414
+ "mediumslateblue",
415
+ "mediumspringgreen",
416
+ "mediumturquoise",
417
+ "mediumvioletred",
418
+ "midnightblue",
419
+ "mintcream",
420
+ "mistyrose",
421
+ "moccasin",
422
+ "navajowhite",
423
+ "navy",
424
+ "oldlace",
425
+ "olive",
426
+ "olivedrab",
427
+ "orange",
428
+ "orangered",
429
+ "orchid",
430
+ "palegoldenrod",
431
+ "palegreen",
432
+ "paleturquoise",
433
+ "palevioletred",
434
+ "papayawhip",
435
+ "peachpuff",
436
+ "peru",
437
+ "pink",
438
+ "plum",
439
+ "powderblue",
440
+ "purple",
441
+ "red",
442
+ "rosybrown",
443
+ "royalblue",
444
+ "saddlebrown",
445
+ "salmon",
446
+ "sandybrown",
447
+ "seagreen",
448
+ "seashell",
449
+ "sienna",
450
+ "silver",
451
+ "skyblue",
452
+ "slateblue",
453
+ "slategray",
454
+ "slategrey",
455
+ "snow",
456
+ "springgreen",
457
+ "steelblue",
458
+ "tan",
459
+ "teal",
460
+ "thistle",
461
+ "tomato",
462
+ "turquoise",
463
+ "violet",
464
+ "wheat",
465
+ "white",
466
+ "whitesmoke",
467
+ "yellow",
468
+ "yellowgreen"
469
+ ]);
470
+ /**
471
+ * Returns the input if it is a valid color string, else null.
472
+ *
473
+ * #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(r, g, b), rgb(r, g, b, a), hsl(h, s, l), hsl(h, s, l, a), hwb(h, w, b), hwb(h, w, b, a), lab(l, a, b), lab(l, a, b, a), lch(l, c, h), lch(l, c, h, a), oklab(l, a, b), oklab(l, a, b, a), oklch(l, c, h), oklch(l, c, h, a), color-mix(in oklab, var(--color-blue-500) 60%, transparent)
474
+ */
475
+ function parseColor(input) {
476
+ if (CSS_COLOR_NAMES.has(input.toLowerCase())) return input;
477
+ if (input.startsWith("color:var(")) return input.slice(6);
478
+ if (input.startsWith("color:")) return parseColor(input.slice(6));
479
+ if (input.startsWith("#") && input.length === 4) return `#${input.slice(1)}`;
480
+ if (input.startsWith("#") && input.length === 5) return `#${input.slice(1)}`;
481
+ if (input.startsWith("#") && input.length === 7) return `#${input.slice(1)}`;
482
+ if (input.startsWith("#") && input.length === 9) return `#${input.slice(1)}`;
483
+ if (input.startsWith("rgb(")) return input.slice(4, -1);
484
+ if (input.startsWith("rgba(")) return input.slice(5, -1);
485
+ if (input.startsWith("hsl(")) return input.slice(4, -1);
486
+ if (input.startsWith("hsla(")) return input.slice(5, -1);
487
+ if (input.startsWith("hwb(")) return input.slice(4, -1);
488
+ if (input.startsWith("lab(")) return input.slice(4, -1);
489
+ if (input.startsWith("lch(")) return input.slice(4, -1);
490
+ if (input.startsWith("oklab(")) return input.slice(5, -1);
491
+ if (input.startsWith("oklch(")) return input.slice(6, -1);
492
+ if (input.startsWith("color-mix(")) return input.slice(9, -1);
493
+ return null;
494
+ }
495
+ var COLOR_KEYWORDS = /* @__PURE__ */ new Set([
496
+ "inherit",
497
+ "currentcolor",
498
+ "transparent"
499
+ ]);
500
+ /**
501
+ * Declarations for a theme colour (#228), as Tailwind v4 emits them: `var(--color-<key>)` so runtime theme
502
+ * overrides apply; with an opacity modifier, a literal srgb color-mix fallback plus an oklab color-mix of the var.
503
+ */
504
+ function themeColorDecls(prop, value, extra) {
505
+ const key = String(extra.realThemeValue);
506
+ const ref = COLOR_KEYWORDS.has(value.toLowerCase()) || value.startsWith("var(") || !/^[\w-]+$/.test(key) ? value : `var(--color-${key})`;
507
+ if (!extra.opacity) return [decl(prop, ref)];
508
+ const alpha = normalizeAlpha(String(extra.opacity));
509
+ if (!alpha) return [];
510
+ const supports = (amount) => atRule("supports", "(color:color-mix(in lab, red, red))", [decl(prop, `color-mix(in oklab, ${ref} ${amount}, transparent)`)]);
511
+ if (alpha.isVar) return [decl(prop, value), supports(alpha.amount)];
512
+ return [decl(prop, `color-mix(in srgb, ${value} ${alpha.amount}, transparent)`), supports(alpha.amount)];
513
+ }
514
+ /**
515
+ * Opacity modifier → color-mix amount, as Tailwind v4 does: `50` → `50%`, `[37%]` → `37%`, `[0.5]` / `[.8]` → `50%` /
516
+ * `80%` (a bracketed number ≤ 1 is a fraction), `[var(--a)]` / `(--a)` → `var(--a)`.
517
+ */
518
+ function normalizeAlpha(raw) {
519
+ const v = raw.trim();
520
+ const cp = /^\((--[\w-]+)\)$/.exec(v) ?? /^\[var\((--[\w-]+)\)\]$/.exec(v);
521
+ if (cp) return {
522
+ amount: `var(${cp[1]})`,
523
+ isVar: true
524
+ };
525
+ const m = /^(\[)?(\d+(?:\.\d+)?|\.\d+)(%)?(\])?$/.exec(v);
526
+ if (!m || !!m[1] !== !!m[4] || m[3] && !m[1]) return null;
527
+ const n = Number(m[2]);
528
+ return {
529
+ amount: `${+(m[3] ? n : m[1] && n <= 1 ? n * 100 : n).toFixed(4)}%`,
530
+ isVar: false
531
+ };
532
+ }
533
+ var MIX_SUPPORTS = "(color:color-mix(in lab, red, red))";
534
+ var COLOR_PROP = /(^|-)color$|^(fill|stroke)$|^--baro-gradient-(from|via|to)$/;
535
+ /**
536
+ * #393: an arbitrary or custom-property colour with an opacity modifier, as Tailwind 4.3.3 emits it: a literal
537
+ * colour with a literal alpha mixes directly (`color-mix(in oklab, #f00 50%, transparent)`); a var colour or a var
538
+ * alpha keeps the plain colour and mixes only under `@supports`. Returns null for an alpha it can't express.
539
+ */
540
+ function colorAlphaDecls(prop, color, opacity) {
541
+ const alpha = normalizeAlpha(opacity);
542
+ if (!alpha) return null;
543
+ const mix = `color-mix(in oklab, ${color} ${alpha.amount}, transparent)`;
544
+ if (alpha.isVar || color.startsWith("var(")) return [decl(prop, color), atRule("supports", MIX_SUPPORTS, [decl(prop, mix)])];
545
+ return [decl(prop, mix)];
546
+ }
547
+ /**
548
+ * #393: applies an opacity modifier to every declaration of `nodes` whose value is one of `colors` (the colour an
549
+ * arbitrary / custom-property utility emitted without the modifier). Returns null when none matched or the alpha
550
+ * is invalid, so the caller emits nothing rather than dropping the modifier or writing a malformed value.
551
+ */
552
+ function applyColorAlpha(nodes, colors, opacity) {
553
+ let matched = false;
554
+ let invalid = false;
555
+ const walk = (list) => list.flatMap((n) => {
556
+ if (n.type === "decl" && typeof n.value === "string" && colors.includes(n.value)) {
557
+ matched = true;
558
+ const out = COLOR_PROP.test(n.prop) ? colorAlphaDecls(n.prop, n.value, opacity) : null;
559
+ if (!out) invalid = true;
560
+ return out ?? [];
561
+ }
562
+ if (n.type === "at-rule" || n.type === "rule" || n.type === "style-rule" || n.type === "at-root") return [{
563
+ ...n,
564
+ nodes: walk(n.nodes)
565
+ }];
566
+ if (n.type === "wrap") return [{
567
+ ...n,
568
+ items: walk(n.items)
569
+ }];
570
+ return [n];
571
+ });
572
+ const out = walk(nodes);
573
+ return matched && !invalid ? out : null;
574
+ }
575
+ //#endregion
576
+ //#region src/core/registry.ts
577
+ /** #393: a handler result meaning "this class is invalid": the engine stops trying other registrations. */
578
+ var REJECT_CLASS = Object.freeze([]);
579
+ var utilityRegistry = [];
580
+ function registerUtility(util, ctx) {
581
+ const state = ctx && getContextState(ctx);
582
+ if (ctx && !state) throw new Error("Utility registration requires a context from createContext");
583
+ (state?.utilities || utilityRegistry).push(util);
584
+ if (ctx) clearContextCaches(ctx);
585
+ else {
586
+ parseResultCache.clear();
587
+ utilityCache.clear();
588
+ }
589
+ }
590
+ function getUtility(ctx) {
591
+ return ctx && getContextState(ctx)?.utilities || utilityRegistry;
592
+ }
593
+ var modifierRegistry = [];
594
+ /**
595
+ * staticModifier: A helper that registers a modifier name and an array of CSS selectors directly to the registry
596
+ *
597
+ * @example
598
+ * ```
599
+ * staticModifier('disabled', ['&:disabled'], { source: 'pseudo' });
600
+ * ```
601
+ *
602
+ * @param name The name of the modifier
603
+ * @param selectors The selectors of the modifier
604
+ * @param options The options of the modifier
605
+ *
606
+ * @returns {void}
607
+ */
608
+ function staticModifier(name, selectors, options = {}, ctx) {
609
+ registerModifier({
610
+ name,
611
+ match: (mod) => mod === name,
612
+ modifySelector: ({ ..._rest }) => {
613
+ return selectors.map((sel) => ({
614
+ selector: sel,
615
+ source: options.source
616
+ }));
617
+ },
618
+ ...options
619
+ }, ctx);
620
+ }
621
+ function functionalModifier(match, modifySelector, wrap, options = {}, ctx) {
622
+ registerModifier({
623
+ match,
624
+ modifySelector,
625
+ wrap,
626
+ ...options
627
+ }, ctx);
628
+ }
629
+ function registerModifier(modifier, ctx) {
630
+ const state = ctx && getContextState(ctx);
631
+ if (ctx && !state) throw new Error("Modifier registration requires a context from createContext");
632
+ (state?.modifiers || modifierRegistry).push(modifier);
633
+ if (ctx) clearContextCaches(ctx);
634
+ }
635
+ function getModifier(ctx) {
636
+ return ctx && getContextState(ctx)?.modifiers || modifierRegistry;
637
+ }
638
+ var ESCAPE_REGEX = /[^A-Za-z0-9_-]/gu;
639
+ var UNSAFE_RAW = /^[\s\p{C}\p{Z}]$/u;
640
+ function escapeClassName(className) {
641
+ if (className === "-") return "\\-";
642
+ const lead = /^-?[0-9]/.exec(className);
643
+ if (lead) {
644
+ const i = lead[0].length - 1;
645
+ return className.slice(0, i) + "\\" + className.charCodeAt(i).toString(16) + " " + escapeRest(className.slice(i + 1));
646
+ }
647
+ return escapeRest(className);
648
+ }
649
+ function escapeRest(className) {
650
+ return className.replace(ESCAPE_REGEX, (c) => {
651
+ if (c === " ") return "\\x20 ";
652
+ if (c === ".") return "\\.";
653
+ if (c === "/") return "\\/";
654
+ if (c === ":") return "\\:";
655
+ if (c === "[") return "\\[";
656
+ if (c === "]") return "\\]";
657
+ if (c === "(") return "\\(";
658
+ if (c === ")") return "\\)";
659
+ if (c === "%") return "\\%";
660
+ if (c === "#") return "\\#";
661
+ if (c === ",") return "\\,";
662
+ if (c === "=") return "\\=";
663
+ if (c === "&") return "\\&";
664
+ if (c === "~") return "\\~";
665
+ if (c === "*") return "\\*";
666
+ if (c === "$") return "\\$";
667
+ if (c === "^") return "\\^";
668
+ if (c === "+") return "\\+";
669
+ if (c === "?") return "\\?";
670
+ if (c === "!") return "\\!";
671
+ if (c === "@") return "\\@";
672
+ if (c === "'") return "\\'";
673
+ if (c === "\"") return "\\\"";
674
+ if (c === "`") return "\\`";
675
+ if (c === ";") return "\\;";
676
+ if (c === "<") return "\\<";
677
+ if (c === ">") return "\\>";
678
+ if (c === "{") return "\\{";
679
+ if (c === "}") return "\\}";
680
+ if (c === "|") return "\\|";
681
+ if (c === "\\") return "\\\\";
682
+ if (UNSAFE_RAW.test(c)) return "\\" + c.codePointAt(0).toString(16) + " ";
683
+ return "\\" + c;
684
+ });
685
+ }
686
+ /**
687
+ * staticUtility: A helper that registers a utility name and an array of CSS declaration pairs directly to the registry
688
+ *
689
+ * @example
690
+ * ```
691
+ * staticUtility('block', [['display', 'block']]);
692
+ * staticUtility('hidden', [['display', 'none']]);
693
+ * staticUtility('space-x-px', [
694
+ * [
695
+ * '& > :not([hidden]) ~ :not([hidden])', // selector
696
+ * [
697
+ * ['margin-inline-start', '1px'], // [prop, value]
698
+ * ['margin-inline-end', '1px'], // [prop, value]
699
+ * ],
700
+ * ],
701
+ * ]);
702
+ * ```
703
+ *
704
+ * @param name The name of the utility
705
+ * @param decls The declarations of the utility
706
+ * @param opts The options of the utility
707
+ *
708
+ * @returns {void}
709
+ */
710
+ function staticUtility(name, decls, opts, ctx) {
711
+ registerUtility({
712
+ name,
713
+ match: (className) => {
714
+ return className === name;
715
+ },
716
+ handler: (value) => {
717
+ return decls.flatMap((params) => {
718
+ if (params.type) return [params];
719
+ if (typeof params === "function") return [params(value)];
720
+ const [a, b] = params;
721
+ if (typeof b === "string") return [decl(a, b)];
722
+ else if (Array.isArray(b)) return [rule(a, b.map(([prop, value]) => decl(prop, value)))];
723
+ return [];
724
+ });
725
+ },
726
+ description: opts?.description,
727
+ category: opts?.category,
728
+ priority: opts?.priority
729
+ }, ctx);
730
+ }
731
+ /**
732
+ * functionalUtility: A helper that registers dynamic utilities (theme, arbitrary, custom, negative, fraction, etc.) directly
733
+ *
734
+ * Example:
735
+ * functionalUtility({
736
+ * name: 'z',
737
+ * supportsNegative: true,
738
+ * themeKeys: ['--z-index'],
739
+ * handleBareValue: ({ value }) => isPositiveInteger(value) ? value : null,
740
+ * handle: (value) => [decl('z-index', value)],
741
+ * description: 'z-index utility',
742
+ * category: 'layout',
743
+ * });
744
+ */
745
+ /**
746
+ * #300: a theme key that no built-in utility names (`theme.extend.borderRadius.card`) still resolves, as in
747
+ * Tailwind 4 where `--radius-card` gives `rounded-card`. Only word keys that start with a letter (numbers stay
748
+ * bare values), never `DEFAULT`; unknown keys return null so the utility emits nothing (#213).
749
+ */
750
+ function themeKeyEntry(ctx, namespace, key) {
751
+ if (key === "DEFAULT" || !/^[a-zA-Z][\w-]*$/.test(key) || typeof ctx?.theme !== "function") return void 0;
752
+ const table = ctx.theme(namespace);
753
+ if (!table || typeof table !== "object" || !Object.prototype.hasOwnProperty.call(table, key)) return void 0;
754
+ return table[key] ?? void 0;
755
+ }
756
+ /** #300: the literal value of `theme.<namespace>.<key>` when it is a string, else null. */
757
+ function themeKeyValue(ctx, namespace, key) {
758
+ const v = themeKeyEntry(ctx, namespace, key);
759
+ return typeof v === "string" ? v : null;
760
+ }
761
+ /** #300: `var(--<varPrefix>-<key>)` when `theme.<namespace>.<key>` exists (the :root var BaroCSS emits for it), else null. */
762
+ function themeKeyVar(ctx, namespace, key, varPrefix) {
763
+ return themeKeyEntry(ctx, namespace, key) === void 0 ? null : `var(--${varPrefix}-${key})`;
764
+ }
765
+ /** #261: `var(--spacing-<key>)` for a named (non-numeric) `theme.spacing` key, else null. */
766
+ function spacingKeyValue(ctx, key, negative) {
767
+ if (key === "px" || !/^[a-zA-Z][\w-]*$/.test(key) || ctx.theme("spacing", key) == null) return null;
768
+ const ref = `var(--spacing-${key})`;
769
+ return negative ? `calc(${ref} * -1)` : ref;
770
+ }
771
+ function functionalUtility(opts, ctx) {
772
+ registerUtility({
773
+ name: opts.name,
774
+ match: (className) => className.startsWith(opts.name + "-"),
775
+ handler: (value, ctx, token, _options) => {
776
+ let finalValue = value;
777
+ const parsedUtility = token;
778
+ const extra = { opacity: token.opacity };
779
+ if (opts.supportsOpacity && !token.arbitrary && !token.customProperty && value.includes("/")) {
780
+ const list = value.split("/");
781
+ if (list.length >= 2) {
782
+ extra.opacity = list.pop();
783
+ finalValue = list.join("/");
784
+ }
785
+ }
786
+ const splitModifier = !token.arbitrary && !token.customProperty && value.includes("/");
787
+ if (opts.supportsOpacity && (extra.opacity || splitModifier) && !normalizeAlpha(String(extra.opacity ?? ""))) {
788
+ const v = parsedUtility.arbitrary ? finalValue.replace(/_/g, " ") : finalValue;
789
+ return (parsedUtility.customProperty ? !/^[\w-]+:/.test(v) || v.startsWith("color:") : parsedUtility.arbitrary ? !!parseColor(v) || /^var\(--/.test(v) || v.startsWith("color:") : false) ? REJECT_CLASS : [];
790
+ }
791
+ const direct = (x) => {
792
+ if (opts.supportsArbitrary && parsedUtility.arbitrary) {
793
+ const processedValue = normalizeMathSpacing(expandThemeFunctions(finalValue.replace(/_/g, " ")));
794
+ if (opts.handle) {
795
+ const result = opts.handle(processedValue, ctx, token, x);
796
+ if (result) return result;
797
+ }
798
+ if (opts.prop) return [decl(opts.prop, processedValue)];
799
+ return [];
800
+ }
801
+ if (opts.supportsCustomProperty && parsedUtility.customProperty) {
802
+ if (opts.handleCustomProperty) return opts.handleCustomProperty(finalValue, ctx, token, x) ?? null;
803
+ const customValue = `var(${finalValue})`;
804
+ if (opts.handle) {
805
+ const result = opts.handle(customValue, ctx, token, x);
806
+ if (result) return result;
807
+ }
808
+ if (opts.prop) return [decl(opts.prop, customValue)];
809
+ return [];
810
+ }
811
+ return null;
812
+ };
813
+ if (opts.supportsArbitrary && parsedUtility.arbitrary || opts.supportsCustomProperty && parsedUtility.customProperty) {
814
+ const result = direct(extra);
815
+ if (opts.supportsOpacity && !opts.ownsOpacity && extra.opacity && result?.length) {
816
+ const raw = parsedUtility.arbitrary ? normalizeMathSpacing(expandThemeFunctions(finalValue.replace(/_/g, " "))) : `var(${finalValue})`;
817
+ const hint = parsedUtility.arbitrary ? /^color:(.+)$/.exec(raw)?.[1] : /^color:(--.+)$/.exec(finalValue)?.[1];
818
+ return applyColorAlpha(result, [raw, ...hint ? [hint, `var(${hint})`] : []], String(extra.opacity)) ?? [];
819
+ }
820
+ return result;
821
+ }
822
+ let themeValue;
823
+ if (opts.themeKey && ctx.theme) themeValue = themeScalar(ctx.theme(opts.themeKey, finalValue));
824
+ let namespace = themeValue !== void 0 ? opts.themeKey : void 0;
825
+ if (!themeValue && opts.themeKeys && ctx.theme) for (const key of opts.themeKeys) {
826
+ themeValue = themeScalar(ctx.theme(key, finalValue));
827
+ if (themeValue !== void 0) {
828
+ namespace = key;
829
+ break;
830
+ }
831
+ }
832
+ if (themeValue !== void 0) {
833
+ extra.themeNamespace = namespace;
834
+ extra.themeKey = finalValue;
835
+ if (namespace === "colors" || !(opts.themeKeys ?? [opts.themeKey]).includes("colors")) extra.realThemeValue = finalValue;
836
+ finalValue = themeValue;
837
+ if (opts.prop) return [decl(opts.prop, finalValue)];
516
838
  if (opts.handle) {
517
839
  const result = opts.handle(finalValue, ctx, token, extra);
518
840
  if (result) return result;
@@ -1044,6 +1366,13 @@ function parseModifier(value) {
1044
1366
  function nameSort(a, b) {
1045
1367
  return b.name.length - a.name.length;
1046
1368
  }
1369
+ /** #393: index of the `close` that balances the value opened just before `s` (depth starts at 1), or -1. */
1370
+ function matchingClose(s, open, close) {
1371
+ let depth = 1;
1372
+ for (let i = 0; i < s.length; i++) if (s[i] === open) depth++;
1373
+ else if (s[i] === close && --depth === 0) return i;
1374
+ return -1;
1375
+ }
1047
1376
  /**
1048
1377
  * Parse utility token
1049
1378
  */
@@ -1072,15 +1401,27 @@ function parseUtility(value, ctx) {
1072
1401
  if (value.startsWith("-")) negative = true;
1073
1402
  if (value.includes("-[")) {
1074
1403
  [prefix, utilityValue] = value.split("-[");
1075
- const closeIdx = utilityValue.lastIndexOf("]");
1404
+ const closeIdx = matchingClose(utilityValue, "[", "]");
1076
1405
  if (closeIdx !== -1 && closeIdx < utilityValue.length - 1 && utilityValue[closeIdx + 1] === "/") {
1077
1406
  opacity = utilityValue.slice(closeIdx + 2);
1407
+ if (!opacity) return {
1408
+ prefix: "",
1409
+ value: ""
1410
+ };
1078
1411
  utilityValue = utilityValue.slice(0, closeIdx);
1079
1412
  } else utilityValue = utilityValue.replace(/]$/, "");
1080
1413
  arbitrary = true;
1081
1414
  } else if (value.includes("-(")) {
1082
1415
  [prefix, utilityValue] = value.split("-(");
1083
- utilityValue = utilityValue.replace(/\)$/, "");
1416
+ const closeIdx = matchingClose(utilityValue, "(", ")");
1417
+ if (closeIdx !== -1 && closeIdx < utilityValue.length - 1 && utilityValue[closeIdx + 1] === "/") {
1418
+ opacity = utilityValue.slice(closeIdx + 2);
1419
+ if (!opacity) return {
1420
+ prefix: "",
1421
+ value: ""
1422
+ };
1423
+ utilityValue = utilityValue.slice(0, closeIdx);
1424
+ } else utilityValue = utilityValue.replace(/\)$/, "");
1084
1425
  customProperty = true;
1085
1426
  } else {
1086
1427
  const sortedUtilities = [...getUtility(ctx)].sort(nameSort);
@@ -1132,6 +1473,13 @@ var uniqueDescriptors = (node) => {
1132
1473
  const seen = /* @__PURE__ */ new Set();
1133
1474
  return node.nodes.filter((c) => c.type !== "decl" || !seen.has(c.prop) && !!seen.add(c.prop));
1134
1475
  };
1476
+ var NO_IMPORTANT_AT = /* @__PURE__ */ new Set([
1477
+ "property",
1478
+ "font-face",
1479
+ "keyframes",
1480
+ "-webkit-keyframes",
1481
+ "counter-style"
1482
+ ]);
1135
1483
  var isSafeDecl = (prop, value) => isStructureSafeValue(String(prop)) && isStructureSafeValue(String(value ?? "")) && !hasHtmlEndTagOpener(String(prop)) && !hasHtmlEndTagOpener(String(value ?? ""));
1136
1484
  var importantPrefix = "!important";
1137
1485
  /**
@@ -1202,10 +1550,15 @@ function astToCss(ast, baseSelector, opts, _indent = "") {
1202
1550
  if (!isSafePrelude(node.selector) || !inScope(node.selector)) return "";
1203
1551
  if (minify) return `${indent}${node.selector} {${astToCss(node.nodes, baseSelector, nestedOpts, nextIndent)}}`;
1204
1552
  else return `${indent}${node.selector} {\n${astToCss(node.nodes, baseSelector, nestedOpts, nextIndent)}${indent}}`;
1205
- case "at-rule":
1553
+ case "at-rule": {
1206
1554
  if (!isSafePrelude(node.name) || !isSafePrelude(node.params)) return "";
1207
- if (minify) return `${indent}@${node.name} ${node.params}{${astToCss(node.nodes, baseSelector, opts, nextIndent)}}`;
1208
- else return `${indent}@${node.name} ${node.params} {\n${astToCss(node.nodes, baseSelector, opts, nextIndent)}${indent}}`;
1555
+ const atOpts = opts?.important && NO_IMPORTANT_AT.has(node.name) ? {
1556
+ ...opts,
1557
+ important: false
1558
+ } : opts;
1559
+ if (minify) return `${indent}@${node.name} ${node.params}{${astToCss(node.nodes, baseSelector, atOpts, nextIndent)}}`;
1560
+ else return `${indent}@${node.name} ${node.params} {\n${astToCss(node.nodes, baseSelector, atOpts, nextIndent)}${indent}}`;
1561
+ }
1209
1562
  case "comment": return minify ? "" : `${indent}/* ${node.text} */`;
1210
1563
  case "raw": return `${indent}${node.value}`;
1211
1564
  default:
@@ -1564,6 +1917,552 @@ function applyVarPrefix(ast, ctx) {
1564
1917
  return walk(ast);
1565
1918
  }
1566
1919
  //#endregion
1920
+ //#region src/core/tw-property-order.ts
1921
+ var TW_PROPERTY_ORDER = [
1922
+ "container-type",
1923
+ "pointer-events",
1924
+ "visibility",
1925
+ "position",
1926
+ "inset",
1927
+ "inset-inline",
1928
+ "inset-block",
1929
+ "inset-inline-start",
1930
+ "inset-inline-end",
1931
+ "inset-block-start",
1932
+ "inset-block-end",
1933
+ "top",
1934
+ "right",
1935
+ "bottom",
1936
+ "left",
1937
+ "isolation",
1938
+ "z-index",
1939
+ "order",
1940
+ "grid-column",
1941
+ "grid-column-start",
1942
+ "grid-column-end",
1943
+ "grid-row",
1944
+ "grid-row-start",
1945
+ "grid-row-end",
1946
+ "float",
1947
+ "clear",
1948
+ "--tw-container-component",
1949
+ "margin",
1950
+ "margin-inline",
1951
+ "margin-block",
1952
+ "margin-inline-start",
1953
+ "margin-inline-end",
1954
+ "margin-block-start",
1955
+ "margin-block-end",
1956
+ "margin-top",
1957
+ "margin-right",
1958
+ "margin-bottom",
1959
+ "margin-left",
1960
+ "box-sizing",
1961
+ "display",
1962
+ "field-sizing",
1963
+ "aspect-ratio",
1964
+ "height",
1965
+ "max-height",
1966
+ "min-height",
1967
+ "width",
1968
+ "max-width",
1969
+ "min-width",
1970
+ "flex",
1971
+ "flex-shrink",
1972
+ "flex-grow",
1973
+ "flex-basis",
1974
+ "table-layout",
1975
+ "caption-side",
1976
+ "border-collapse",
1977
+ "border-spacing",
1978
+ "transform-origin",
1979
+ "translate",
1980
+ "--tw-translate-x",
1981
+ "--tw-translate-y",
1982
+ "--tw-translate-z",
1983
+ "scale",
1984
+ "--tw-scale-x",
1985
+ "--tw-scale-y",
1986
+ "--tw-scale-z",
1987
+ "rotate",
1988
+ "--tw-rotate-x",
1989
+ "--tw-rotate-y",
1990
+ "--tw-rotate-z",
1991
+ "--tw-skew-x",
1992
+ "--tw-skew-y",
1993
+ "transform",
1994
+ "zoom",
1995
+ "animation",
1996
+ "cursor",
1997
+ "touch-action",
1998
+ "--tw-pan-x",
1999
+ "--tw-pan-y",
2000
+ "--tw-pinch-zoom",
2001
+ "resize",
2002
+ "scroll-snap-type",
2003
+ "--tw-scroll-snap-strictness",
2004
+ "scroll-snap-align",
2005
+ "scroll-snap-stop",
2006
+ "scroll-margin",
2007
+ "scroll-margin-inline",
2008
+ "scroll-margin-block",
2009
+ "scroll-margin-inline-start",
2010
+ "scroll-margin-inline-end",
2011
+ "scroll-margin-block-start",
2012
+ "scroll-margin-block-end",
2013
+ "scroll-margin-top",
2014
+ "scroll-margin-right",
2015
+ "scroll-margin-bottom",
2016
+ "scroll-margin-left",
2017
+ "scroll-padding",
2018
+ "scroll-padding-inline",
2019
+ "scroll-padding-block",
2020
+ "scroll-padding-inline-start",
2021
+ "scroll-padding-inline-end",
2022
+ "scroll-padding-block-start",
2023
+ "scroll-padding-block-end",
2024
+ "scroll-padding-top",
2025
+ "scroll-padding-right",
2026
+ "scroll-padding-bottom",
2027
+ "scroll-padding-left",
2028
+ "scrollbar-width",
2029
+ "scrollbar-color",
2030
+ "scrollbar-gutter",
2031
+ "list-style-position",
2032
+ "list-style-type",
2033
+ "list-style-image",
2034
+ "appearance",
2035
+ "columns",
2036
+ "break-before",
2037
+ "break-inside",
2038
+ "break-after",
2039
+ "grid-auto-columns",
2040
+ "grid-auto-flow",
2041
+ "grid-auto-rows",
2042
+ "grid-template-columns",
2043
+ "grid-template-rows",
2044
+ "flex-direction",
2045
+ "flex-wrap",
2046
+ "place-content",
2047
+ "place-items",
2048
+ "align-content",
2049
+ "align-items",
2050
+ "justify-content",
2051
+ "justify-items",
2052
+ "gap",
2053
+ "column-gap",
2054
+ "row-gap",
2055
+ "--tw-space-x-reverse",
2056
+ "--tw-space-y-reverse",
2057
+ "divide-x-width",
2058
+ "divide-y-width",
2059
+ "--tw-divide-y-reverse",
2060
+ "divide-style",
2061
+ "divide-color",
2062
+ "place-self",
2063
+ "align-self",
2064
+ "justify-self",
2065
+ "overflow",
2066
+ "overflow-x",
2067
+ "overflow-y",
2068
+ "overscroll-behavior",
2069
+ "overscroll-behavior-x",
2070
+ "overscroll-behavior-y",
2071
+ "scroll-behavior",
2072
+ "border-radius",
2073
+ "border-start-radius",
2074
+ "border-end-radius",
2075
+ "border-top-radius",
2076
+ "border-right-radius",
2077
+ "border-bottom-radius",
2078
+ "border-left-radius",
2079
+ "border-start-start-radius",
2080
+ "border-start-end-radius",
2081
+ "border-end-end-radius",
2082
+ "border-end-start-radius",
2083
+ "border-top-left-radius",
2084
+ "border-top-right-radius",
2085
+ "border-bottom-right-radius",
2086
+ "border-bottom-left-radius",
2087
+ "border-width",
2088
+ "border-inline-width",
2089
+ "border-block-width",
2090
+ "border-inline-start-width",
2091
+ "border-inline-end-width",
2092
+ "border-block-start-width",
2093
+ "border-block-end-width",
2094
+ "border-top-width",
2095
+ "border-right-width",
2096
+ "border-bottom-width",
2097
+ "border-left-width",
2098
+ "border-style",
2099
+ "border-inline-style",
2100
+ "border-block-style",
2101
+ "border-inline-start-style",
2102
+ "border-inline-end-style",
2103
+ "border-block-start-style",
2104
+ "border-block-end-style",
2105
+ "border-top-style",
2106
+ "border-right-style",
2107
+ "border-bottom-style",
2108
+ "border-left-style",
2109
+ "border-color",
2110
+ "border-inline-color",
2111
+ "border-block-color",
2112
+ "border-inline-start-color",
2113
+ "border-inline-end-color",
2114
+ "border-block-start-color",
2115
+ "border-block-end-color",
2116
+ "border-top-color",
2117
+ "border-right-color",
2118
+ "border-bottom-color",
2119
+ "border-left-color",
2120
+ "background-color",
2121
+ "background-image",
2122
+ "--tw-gradient-position",
2123
+ "--tw-gradient-stops",
2124
+ "--tw-gradient-via-stops",
2125
+ "--tw-gradient-from",
2126
+ "--tw-gradient-from-position",
2127
+ "--tw-gradient-via",
2128
+ "--tw-gradient-via-position",
2129
+ "--tw-gradient-to",
2130
+ "--tw-gradient-to-position",
2131
+ "mask-image",
2132
+ "--tw-mask-top",
2133
+ "--tw-mask-top-from-color",
2134
+ "--tw-mask-top-from-position",
2135
+ "--tw-mask-top-to-color",
2136
+ "--tw-mask-top-to-position",
2137
+ "--tw-mask-right",
2138
+ "--tw-mask-right-from-color",
2139
+ "--tw-mask-right-from-position",
2140
+ "--tw-mask-right-to-color",
2141
+ "--tw-mask-right-to-position",
2142
+ "--tw-mask-bottom",
2143
+ "--tw-mask-bottom-from-color",
2144
+ "--tw-mask-bottom-from-position",
2145
+ "--tw-mask-bottom-to-color",
2146
+ "--tw-mask-bottom-to-position",
2147
+ "--tw-mask-left",
2148
+ "--tw-mask-left-from-color",
2149
+ "--tw-mask-left-from-position",
2150
+ "--tw-mask-left-to-color",
2151
+ "--tw-mask-left-to-position",
2152
+ "--tw-mask-linear",
2153
+ "--tw-mask-linear-position",
2154
+ "--tw-mask-linear-from-color",
2155
+ "--tw-mask-linear-from-position",
2156
+ "--tw-mask-linear-to-color",
2157
+ "--tw-mask-linear-to-position",
2158
+ "--tw-mask-radial",
2159
+ "--tw-mask-radial-shape",
2160
+ "--tw-mask-radial-size",
2161
+ "--tw-mask-radial-position",
2162
+ "--tw-mask-radial-from-color",
2163
+ "--tw-mask-radial-from-position",
2164
+ "--tw-mask-radial-to-color",
2165
+ "--tw-mask-radial-to-position",
2166
+ "--tw-mask-conic",
2167
+ "--tw-mask-conic-position",
2168
+ "--tw-mask-conic-from-color",
2169
+ "--tw-mask-conic-from-position",
2170
+ "--tw-mask-conic-to-color",
2171
+ "--tw-mask-conic-to-position",
2172
+ "box-decoration-break",
2173
+ "background-size",
2174
+ "background-attachment",
2175
+ "background-clip",
2176
+ "background-position",
2177
+ "background-repeat",
2178
+ "background-origin",
2179
+ "mask-composite",
2180
+ "mask-mode",
2181
+ "mask-type",
2182
+ "mask-size",
2183
+ "mask-clip",
2184
+ "mask-position",
2185
+ "mask-repeat",
2186
+ "mask-origin",
2187
+ "fill",
2188
+ "stroke",
2189
+ "stroke-width",
2190
+ "object-fit",
2191
+ "object-position",
2192
+ "padding",
2193
+ "padding-inline",
2194
+ "padding-block",
2195
+ "padding-inline-start",
2196
+ "padding-inline-end",
2197
+ "padding-block-start",
2198
+ "padding-block-end",
2199
+ "padding-top",
2200
+ "padding-right",
2201
+ "padding-bottom",
2202
+ "padding-left",
2203
+ "text-align",
2204
+ "text-indent",
2205
+ "vertical-align",
2206
+ "font-family",
2207
+ "font-feature-settings",
2208
+ "font-size",
2209
+ "line-height",
2210
+ "font-weight",
2211
+ "letter-spacing",
2212
+ "text-wrap",
2213
+ "overflow-wrap",
2214
+ "word-break",
2215
+ "text-overflow",
2216
+ "hyphens",
2217
+ "white-space",
2218
+ "tab-size",
2219
+ "color",
2220
+ "text-transform",
2221
+ "font-style",
2222
+ "font-stretch",
2223
+ "font-variant-numeric",
2224
+ "text-decoration-line",
2225
+ "text-decoration-color",
2226
+ "text-decoration-style",
2227
+ "text-decoration-thickness",
2228
+ "text-underline-offset",
2229
+ "-webkit-font-smoothing",
2230
+ "placeholder-color",
2231
+ "caret-color",
2232
+ "accent-color",
2233
+ "color-scheme",
2234
+ "opacity",
2235
+ "background-blend-mode",
2236
+ "mix-blend-mode",
2237
+ "box-shadow",
2238
+ "--tw-shadow",
2239
+ "--tw-shadow-color",
2240
+ "--tw-ring-shadow",
2241
+ "--tw-ring-color",
2242
+ "--tw-inset-shadow",
2243
+ "--tw-inset-shadow-color",
2244
+ "--tw-inset-ring-shadow",
2245
+ "--tw-inset-ring-color",
2246
+ "--tw-ring-offset-width",
2247
+ "--tw-ring-offset-color",
2248
+ "outline",
2249
+ "outline-width",
2250
+ "outline-offset",
2251
+ "outline-color",
2252
+ "--tw-blur",
2253
+ "--tw-brightness",
2254
+ "--tw-contrast",
2255
+ "--tw-drop-shadow",
2256
+ "--tw-grayscale",
2257
+ "--tw-hue-rotate",
2258
+ "--tw-invert",
2259
+ "--tw-saturate",
2260
+ "--tw-sepia",
2261
+ "filter",
2262
+ "--tw-backdrop-blur",
2263
+ "--tw-backdrop-brightness",
2264
+ "--tw-backdrop-contrast",
2265
+ "--tw-backdrop-grayscale",
2266
+ "--tw-backdrop-hue-rotate",
2267
+ "--tw-backdrop-invert",
2268
+ "--tw-backdrop-opacity",
2269
+ "--tw-backdrop-saturate",
2270
+ "--tw-backdrop-sepia",
2271
+ "backdrop-filter",
2272
+ "transition-property",
2273
+ "transition-behavior",
2274
+ "transition-delay",
2275
+ "transition-duration",
2276
+ "transition-timing-function",
2277
+ "will-change",
2278
+ "contain",
2279
+ "content",
2280
+ "forced-color-adjust"
2281
+ ];
2282
+ //#endregion
2283
+ //#region src/core/rule-order.ts
2284
+ /**
2285
+ * Tailwind-compatible cascade order for runtime-inserted rules (#254); shared by @barocss/server (#267).
2286
+ *
2287
+ * The runtime discovers classes in DOM order, so without sorting `lg:px-8`
2288
+ * seen before `sm:px-6` would land earlier and lose at >= 1024px. Each rule
2289
+ * gets a sort key derived from its leading `@media` / `@container` preludes:
2290
+ *
2291
+ * 0 base, negated media (`not-md:` → `@media not (…)`, as Tailwind 4.3.3 orders them, #352),
2292
+ * state media (hover), motion/contrast, unknown
2293
+ * 1 max-* breakpoints (larger width first)
2294
+ * 2 min-* breakpoints (smaller width first)
2295
+ * 3 @max-* container queries (larger width first)
2296
+ * 4 @min-* container queries (smaller width first)
2297
+ * 5 orientation, dark (prefers-color-scheme), print, forced-colors
2298
+ *
2299
+ * Nested at-rules (e.g. `sm:dark:`) contribute one key pair per level, so
2300
+ * `sm:` < `sm:dark:` < `md:`.
2301
+ *
2302
+ * #401: within one variant key, rules follow Tailwind 4's property order (the candidate sort of
2303
+ * Tailwind 4.3.3's `compile()`): compare the sorted TW property indices of each rule's declarations up
2304
+ * to the first difference (a rule that runs out of indices sorts last), then more declarations first,
2305
+ * then the class name (Tailwind's numeric-aware compare). Equal keys keep discovery order.
2306
+ */
2307
+ var LEADING_AT = /^\s*@(media|container)\s+([^{]*)\{/;
2308
+ var LATE_MEDIA = /prefers-color-scheme|\bprint\b|forced-colors|orientation/;
2309
+ var MIN_W = /(?:min-width\s*:\s*|width\s*>=?\s*)([\d.]+)(px|rem|em)?/;
2310
+ var MAX_W = /(?:max-width\s*:\s*|width\s*<=?\s*)([\d.]+)(px|rem|em)?/;
2311
+ /** Separates the variant pairs (whose first slot is >= 0) from the property part of a key. */
2312
+ var PROPERTY_PART = -1;
2313
+ /** A rule that has run out of property indices sorts after every real index (TW: `?? Infinity`). */
2314
+ var NO_MORE = Number.MAX_SAFE_INTEGER;
2315
+ var PROPERTY_INDEX = new Map(TW_PROPERTY_ORDER.map((p, i) => [p, i]));
2316
+ var DECL = /(?:^|[{;])\s*(-{0,2}[a-zA-Z][\w-]*)\s*:[^;{}]*(?=[;}])/g;
2317
+ var AT_PRELUDE = /^\s*@[\w-]+[^{]*\{/;
2318
+ var CLASS = /\.((?:\\.|[\w-])+)/;
2319
+ function toPx(n, unit) {
2320
+ const v = parseFloat(n);
2321
+ return unit === "rem" || unit === "em" ? v * 16 : v;
2322
+ }
2323
+ function preludeKey(kind, prelude) {
2324
+ const container = kind === "container";
2325
+ if (!container && /^\s*not\b/i.test(prelude)) return [0, 0];
2326
+ const min = MIN_W.exec(prelude);
2327
+ if (min) return [container ? 4 : 2, toPx(min[1], min[2])];
2328
+ const max = MAX_W.exec(prelude);
2329
+ if (max) return [container ? 3 : 1, -toPx(max[1], max[2])];
2330
+ if (!container && LATE_MEDIA.test(prelude)) return [5, 0];
2331
+ return [0, 0];
2332
+ }
2333
+ /** The rule text after its leading at-rule preludes, up to its first `{` (the selector). */
2334
+ function ruleSelector(rule) {
2335
+ let rest = rule;
2336
+ let m;
2337
+ while (m = AT_PRELUDE.exec(rest)) rest = rest.slice(m[0].length);
2338
+ const end = rest.indexOf("{");
2339
+ return end === -1 ? "" : rest.slice(0, end);
2340
+ }
2341
+ /**
2342
+ * Tailwind's `--tw-sort` overrides (a utility sorts as one pseudo-property), recognised from BaroCSS's
2343
+ * output for the same utilities: space-x/y, divide-*, placeholder colour, gradient stops, container.
2344
+ * (TW's `size-*` override names no listed property, so Tailwind ignores it, and so does this.)
2345
+ */
2346
+ function sortOverride(selector, props, candidate) {
2347
+ const first = props[0];
2348
+ if (first === "--tw-space-x-reverse") return "row-gap";
2349
+ if (first === "--tw-space-y-reverse") return "column-gap";
2350
+ if (first === "--tw-divide-x-reverse") return "divide-x-width";
2351
+ if (first === "--tw-divide-y-reverse") return "divide-y-width";
2352
+ if (selector.includes(":not(:last-child)")) {
2353
+ if (props.includes("border-color")) return "divide-color";
2354
+ if (props.includes("border-style")) return "divide-style";
2355
+ }
2356
+ if (selector.includes("::placeholder") && props.includes("color")) return "placeholder-color";
2357
+ for (const stop of [
2358
+ "from",
2359
+ "via",
2360
+ "to"
2361
+ ]) if (props.includes(`--tw-gradient-${stop}`)) return `--tw-gradient-${stop}`;
2362
+ if (candidate.slice(candidate.lastIndexOf(":") + 1) === "container") return "--tw-container-component";
2363
+ return null;
2364
+ }
2365
+ /**
2366
+ * Tailwind's per-candidate property sort (#401): the sorted, de-duplicated TW property-order indices of
2367
+ * the rule's declarations (at any depth), and the declaration count. `--baro-*` vars count as `--tw-*`.
2368
+ */
2369
+ /** @internal (#401) */ function rulePropertySort(rule, candidate = ruleCandidate(rule)) {
2370
+ const props = [];
2371
+ for (const d of rule.matchAll(DECL)) props.push(d[1].startsWith("--baro-") ? "--tw-" + d[1].slice(7) : d[1]);
2372
+ const override = sortOverride(ruleSelector(rule), props, candidate);
2373
+ const overrideIndex = override === null ? void 0 : PROPERTY_INDEX.get(override);
2374
+ if (overrideIndex !== void 0) return {
2375
+ order: [overrideIndex],
2376
+ count: props.length + 1
2377
+ };
2378
+ const set = /* @__PURE__ */ new Set();
2379
+ for (const p of props) {
2380
+ const i = PROPERTY_INDEX.get(p);
2381
+ if (i !== void 0) set.add(i);
2382
+ }
2383
+ return {
2384
+ order: Array.from(set).sort((a, b) => a - b),
2385
+ count: props.length
2386
+ };
2387
+ }
2388
+ /** The (unescaped) first class in the rule's selector, e.g. `sm:px-2`. */
2389
+ /** @internal (#401) */ function ruleCandidate(rule) {
2390
+ const c = CLASS.exec(ruleSelector(rule));
2391
+ return c ? c[1].replace(/\\(.)/g, "$1") : "";
2392
+ }
2393
+ /** Tailwind's candidate compare: runs of digits compare by value, other chars by code. */
2394
+ /** @internal (#401) */ function compareCandidates(a, b) {
2395
+ const n = Math.min(a.length, b.length);
2396
+ for (let i = 0; i < n; i++) {
2397
+ let x = a.charCodeAt(i);
2398
+ let y = b.charCodeAt(i);
2399
+ if (x >= 48 && x <= 57 && y >= 48 && y <= 57) {
2400
+ let ae = i + 1;
2401
+ let be = i + 1;
2402
+ for (x = a.charCodeAt(ae); x >= 48 && x <= 57;) x = a.charCodeAt(++ae);
2403
+ for (y = b.charCodeAt(be); y >= 48 && y <= 57;) y = b.charCodeAt(++be);
2404
+ const as = a.slice(i, ae);
2405
+ const bs = b.slice(i, be);
2406
+ const diff = Number(as) - Number(bs);
2407
+ if (diff) return diff;
2408
+ if (as < bs) return -1;
2409
+ if (as > bs) return 1;
2410
+ continue;
2411
+ }
2412
+ if (x !== y) return x - y;
2413
+ }
2414
+ return a.length - b.length;
2415
+ }
2416
+ /** The #254 variant part of the key (leading `@media` / `@container` preludes). */
2417
+ /** @internal (#401) */ function ruleVariantKey(rule) {
2418
+ const key = [];
2419
+ let rest = rule;
2420
+ let m;
2421
+ while (m = LEADING_AT.exec(rest)) {
2422
+ const [g, v] = preludeKey(m[1], m[2]);
2423
+ key.push(g, v);
2424
+ rest = rest.slice(m[0].length);
2425
+ }
2426
+ return key;
2427
+ }
2428
+ /**
2429
+ * Full sort key: the #254 variant pairs, then (#401) Tailwind's property sort and the class name.
2430
+ * `candidate` defaults to the rule's first class.
2431
+ */
2432
+ function ruleSortKey(rule, candidate) {
2433
+ const name = candidate ?? ruleCandidate(rule);
2434
+ const { order, count } = rulePropertySort(rule, name);
2435
+ const key = ruleVariantKey(rule);
2436
+ key.push(PROPERTY_PART, ...order, NO_MORE, -count, name);
2437
+ return key;
2438
+ }
2439
+ function compareKeys(a, b) {
2440
+ const n = Math.min(a.length, b.length);
2441
+ for (let i = 0; i < n; i++) {
2442
+ const x = a[i];
2443
+ const y = b[i];
2444
+ if (x === y) continue;
2445
+ if (typeof x === "string" || typeof y === "string") {
2446
+ const d = compareCandidates(String(x), String(y));
2447
+ if (d) return d;
2448
+ continue;
2449
+ }
2450
+ return x - y;
2451
+ }
2452
+ return a.length - b.length;
2453
+ }
2454
+ /** Index after the last key <= `key` (stable upper bound) in sorted `keys`. */
2455
+ function upperBound(keys, key) {
2456
+ let lo = 0;
2457
+ let hi = keys.length;
2458
+ while (lo < hi) {
2459
+ const mid = lo + hi >> 1;
2460
+ if (compareKeys(keys[mid], key) <= 0) lo = mid + 1;
2461
+ else hi = mid;
2462
+ }
2463
+ return lo;
2464
+ }
2465
+ //#endregion
1567
2466
  //#region src/core/engine.ts
1568
2467
  var failureCache = /* @__PURE__ */ new Set();
1569
2468
  /**
@@ -1762,6 +2661,10 @@ function parseClassToAst(fullClassName, ctx) {
1762
2661
  let ast = [];
1763
2662
  for (const utilReg of utilRegs) {
1764
2663
  ast = utilReg.handler(value, ctx, utility, utilReg) || [];
2664
+ if (ast === REJECT_CLASS) {
2665
+ ast = [];
2666
+ break;
2667
+ }
1765
2668
  if (ast.length > 0) break;
1766
2669
  }
1767
2670
  const wrappers = [];
@@ -1886,7 +2789,7 @@ var CLASS_SEPARATOR = /[ \t\n\f\r]+/;
1886
2789
  function generateCss(classList, ctx, opts) {
1887
2790
  const seen = /* @__PURE__ */ new Set();
1888
2791
  const allAtRootNodes = [];
1889
- const results = classList.split(CLASS_SEPARATOR).filter((cls) => {
2792
+ const generated = classList.split(CLASS_SEPARATOR).filter((cls) => {
1890
2793
  if (!cls) return false;
1891
2794
  if (opts?.dedup) {
1892
2795
  if (seen.has(cls)) return false;
@@ -1895,12 +2798,31 @@ function generateCss(classList, ctx, opts) {
1895
2798
  return true;
1896
2799
  }).map((cls) => {
1897
2800
  try {
1898
- return generateOne(cls);
2801
+ return {
2802
+ cls,
2803
+ css: generateOne(cls)
2804
+ };
1899
2805
  } catch (err) {
1900
2806
  debugWarn("[generateCss] class generation failed:", cls, err);
1901
- return "";
2807
+ return {
2808
+ cls,
2809
+ css: ""
2810
+ };
1902
2811
  }
1903
- }).join(opts?.minify ? "" : "\n");
2812
+ });
2813
+ const slots = generated.flatMap((g, i) => g.css ? [i] : []);
2814
+ const sorted = slots.map((i) => ({
2815
+ i,
2816
+ css: generated[i].css,
2817
+ key: ruleSortKey(generated[i].css, generated[i].cls)
2818
+ })).sort((a, b) => compareKeys(a.key, b.key) || a.i - b.i);
2819
+ slots.forEach((slot, j) => {
2820
+ generated[slot] = {
2821
+ cls: generated[slot].cls,
2822
+ css: sorted[j].css
2823
+ };
2824
+ });
2825
+ const results = generated.map((g) => g.css).join(opts?.minify ? "" : "\n");
1904
2826
  function generateOne(cls) {
1905
2827
  const ast = parseClassToAst(cls, ctx);
1906
2828
  const parsedResult = (getContextState(ctx)?.parseResultCache || parseResultCache).get(cls);
@@ -3049,500 +3971,232 @@ function configGetter(config, ...path) {
3049
3971
  else keys = path;
3050
3972
  return keys.reduce((acc, key) => acc ? acc[key] : void 0, config);
3051
3973
  }
3052
- function hasPreset(themeObj, category, preset) {
3053
- return themeObj[category]?.includes?.(preset);
3054
- }
3055
- function resolveTheme(config) {
3056
- let theme = {};
3057
- if (config.presets) {
3058
- for (const preset of config.presets) if (preset.theme) theme = deepMerge(theme, preset.theme);
3059
- }
3060
- if (config.theme) {
3061
- const { extend, ...overrideTheme } = config.theme;
3062
- theme = deepMerge(theme, overrideTheme);
3063
- if (extend) theme = deepMerge(theme, extend);
3064
- }
3065
- return theme;
3066
- }
3067
- function themeToCssVars(theme) {
3068
- return toCssVarsBlock(themeToCssVarsAll(theme));
3069
- }
3070
- function createContext(configObj) {
3071
- if (configObj.debug !== void 0) setDebug(!!configObj.debug);
3072
- const configWithDefaults = {
3073
- presets: [{ theme: defaultTheme }, ...configObj.presets || []],
3074
- ...configObj
3075
- };
3076
- const themeObj = resolveTheme(configWithDefaults);
3077
- const ctx = {
3078
- hasPreset: (category, preset) => {
3079
- return hasPreset(themeObj, category, preset);
3080
- },
3081
- theme: (...args) => {
3082
- return themeGetter(themeObj, ...args);
3083
- },
3084
- config: (...args) => {
3085
- return configGetter(configWithDefaults, ...args);
3086
- },
3087
- themeToCssVars: () => themeToCssVars(themeObj),
3088
- extendTheme: (category, values) => {
3089
- if (typeof values === "function") {
3090
- const result = values(ctx.theme);
3091
- if (result && typeof result === "object") {
3092
- const existingValues = themeObj[category] || {};
3093
- themeObj[category] = {
3094
- ...existingValues,
3095
- ...result
3096
- };
3097
- }
3098
- } else if (typeof values === "object" && values !== null && !Array.isArray(values)) {
3099
- const existingValues = themeObj[category] || {};
3100
- themeObj[category] = {
3101
- ...existingValues,
3102
- ...values
3103
- };
3104
- }
3105
- clearContextCaches(ctx);
3106
- },
3107
- getPreflightCSS: (level = true) => {
3108
- return getPreflightCSS(level);
3109
- }
3110
- };
3111
- initializeContextState(ctx, getUtility(), getModifier());
3112
- registerCustomUtilities(ctx, configObj.utilities);
3113
- return ctx;
3114
- }
3115
- //#endregion
3116
- //#region src/core/jsonToAst.ts
3117
- /**
3118
- * Converts a single BaroJsonInput object into an AST tree.
3119
- * Bypasses string parsing and directly invokes utility/modifier handlers.
3120
- *
3121
- * @param input BaroJsonInput object
3122
- * @param ctx Context
3123
- * @returns AstNode[]
3124
- */
3125
- function jsonToAst(input, ctx) {
3126
- if ((input.variants || []).some((v) => typeof v === "string" ? !isSafeVariantToken(v) : !isSafeVariantValue(v.name || "") || !isSafeVariantValue(v.value || "") || hasCommentToken(v.name || "") || hasCommentToken(v.value || ""))) return [];
3127
- let utilReg = getUtility(ctx).find((u) => u.name === input.utility.name);
3128
- if (input.utility.value && !input.utility.arbitrary && !input.utility.customProperty) {
3129
- const fullName = `${input.utility.name}-${input.utility.value}`;
3130
- const exactMatch = getUtility(ctx).find((u) => u.name === fullName);
3131
- if (exactMatch) utilReg = exactMatch;
3132
- }
3133
- if (!utilReg) {
3134
- debugWarn(`[jsonToAst] Unknown utility: "${input.utility.name}"`);
3135
- return [];
3136
- }
3137
- const parsedUtility = {
3138
- prefix: input.utility.name,
3139
- value: input.utility.value,
3140
- arbitrary: input.utility.arbitrary,
3141
- negative: input.utility.negative,
3142
- opacity: input.utility.opacity,
3143
- important: input.utility.important,
3144
- customProperty: input.utility.customProperty,
3145
- category: utilReg.category,
3146
- priority: utilReg.priority
3147
- };
3148
- let value = input.utility.value;
3149
- if (input.utility.negative && value) value = "-" + value;
3150
- let ast = utilReg.handler(value || "", ctx, parsedUtility, utilReg) || [];
3151
- if (input.variants && input.variants.length > 0) {
3152
- const wrappers = [];
3153
- const selector = "&";
3154
- for (let i = input.variants.length - 1; i >= 0; i--) {
3155
- const variantInput = input.variants[i];
3156
- const variantName = typeof variantInput === "string" ? variantInput : variantInput.name;
3157
- const variantValue = typeof variantInput === "string" ? void 0 : variantInput.value;
3158
- const variantArbitrary = typeof variantInput === "string" ? false : variantInput.arbitrary;
3159
- const parsedModifier = {
3160
- type: variantName,
3161
- value: variantValue,
3162
- arbitrary: variantArbitrary
3163
- };
3164
- let matchKey = variantName;
3165
- if (variantArbitrary && variantValue) {
3166
- if (variantName) {
3167
- matchKey = `${variantName}-[${variantValue}]`;
3168
- parsedModifier.type = matchKey;
3169
- } else {
3170
- matchKey = `[${variantValue}]`;
3171
- parsedModifier.type = matchKey;
3172
- }
3173
- } else if (variantValue) {
3174
- matchKey = `${variantName}-[${variantValue}]`;
3175
- parsedModifier.type = matchKey;
3176
- }
3177
- const plugin = getModifier(ctx).find((p) => p.match(matchKey, ctx));
3178
- if (!plugin) {
3179
- debugWarn(`[jsonToAst] Unknown variant: "${matchKey}"`);
3180
- continue;
3181
- }
3182
- if (plugin.astHandler) ast = plugin.astHandler(ast, parsedModifier, ctx, [], i);
3183
- if (plugin.modifySelector) {
3184
- const result = plugin.modifySelector({
3185
- selector,
3186
- fullClassName: "JSON_GENERATED",
3187
- mod: parsedModifier,
3188
- context: ctx,
3189
- variantChain: [],
3190
- index: i
3191
- });
3192
- if (result == null) continue;
3193
- if (plugin.wrap && (result === "&" || typeof result === "object" && !Array.isArray(result) && result.selector === "&" || Array.isArray(result) && result.length === 1 && result[0].selector === "&")) {} else if (typeof result === "string" && result.includes("&")) wrappers.push({
3194
- type: "rule",
3195
- selector: result
3196
- });
3197
- else if (typeof result === "object" && !Array.isArray(result) && result.selector) {
3198
- const r = result;
3199
- const wrappingType = r.wrappingType || "rule";
3200
- wrappers.push({
3201
- type: wrappingType,
3202
- selector: r.selector,
3203
- flatten: r.flatten,
3204
- source: r.source
3205
- });
3206
- } else if (Array.isArray(result)) wrappers.push({
3207
- type: "wrap",
3208
- items: result.map((r) => ({
3209
- type: r.wrappingType || "rule",
3210
- selector: r.selector,
3211
- source: r.source,
3212
- nodes: []
3213
- }))
3214
- });
3215
- }
3216
- if (plugin.wrap) wrappers.push({
3217
- type: "wrap",
3218
- items: plugin.wrap(parsedModifier, ctx)
3219
- });
3220
- }
3221
- for (let i = 0; i < wrappers.length; i++) {
3222
- const wrap = wrappers[i];
3223
- if (wrap.type === "wrap") ast = wrap.items.map((item) => item.type === "rule" || item.type === "style-rule" || item.type === "at-rule" || item.type === "at-root" ? {
3224
- ...item,
3225
- nodes: [...item.nodes || [], ...ast]
3226
- } : item);
3227
- else if (wrap.type === "style-rule") ast = [{
3228
- type: "style-rule",
3229
- selector: wrap.selector,
3230
- source: wrap.source,
3231
- nodes: Array.isArray(ast) ? ast : [ast]
3232
- }];
3233
- else if (wrap.type === "at-rule") ast = [{
3234
- type: "at-rule",
3235
- name: wrap.name || "media",
3236
- params: wrap.params,
3237
- source: wrap.source,
3238
- nodes: Array.isArray(ast) ? ast : [ast]
3239
- }];
3240
- else if (wrap.type === "rule") ast = [{
3241
- type: "rule",
3242
- selector: wrap.selector,
3243
- source: wrap.source,
3244
- nodes: Array.isArray(ast) ? ast : [ast]
3245
- }];
3246
- }
3247
- }
3248
- return applyVarPrefix(ast, ctx);
3249
- }
3250
- /**
3251
- * Generates CSS from a list of BaroJsonInput objects.
3252
- *
3253
- * @param inputs Array of BaroJsonInput
3254
- * @param ctx Context
3255
- * @param opts Options (minify, etc.)
3256
- * @returns CSS string
3257
- */
3258
- function generateCssFromJson(inputs, ctx, opts) {
3259
- const allAtRootNodes = [];
3260
- const cssList = [];
3261
- inputs.forEach((input) => {
3262
- const cleanAst = optimizeAst(jsonToAst(input, ctx));
3263
- cleanAst.forEach((node) => {
3264
- if (node.type === "at-root") allAtRootNodes.push(...node.nodes);
3265
- });
3266
- let reconstructedName = input.utility.name;
3267
- if (input.utility.value) reconstructedName += `-${input.utility.value}`;
3268
- if (input.utility.arbitrary) reconstructedName = `${input.utility.name}-[${input.utility.value}]`;
3269
- if (input.variants) reconstructedName = `${input.variants.map((v) => typeof v === "string" ? v : v.name).join(":")}:${reconstructedName}`;
3270
- const css = astToCss(cleanAst, cleanAst.some((node) => node.type === "style-rule") ? void 0 : `.${reconstructedName.replace(/[^a-zA-Z0-9-_]/g, "\\$&")}`, {
3271
- minify: opts?.minify,
3272
- important: input.utility.important ?? false
3273
- });
3274
- if (css) cssList.push(css);
3275
- });
3276
- const rootCss = rootToCss(allAtRootNodes);
3277
- return `${rootCss ? `:root,:host {${rootCss}}` : ""}${cssList.join(opts?.minify ? "" : "\n")}`;
3278
- }
3279
- //#endregion
3280
- //#region src/core/utils.ts
3281
- /**
3282
- * Parses a fraction string (e.g., '1/2') and returns a percentage string (e.g., '50%'), or null if not a valid fraction.
3283
- */
3284
- function parseFraction(input) {
3285
- if (input.includes("/")) {
3286
- const [num, denom] = input.split("/").map(Number);
3287
- if (!isNaN(num) && !isNaN(denom) && denom !== 0) return `${num / denom * 100}%`;
3288
- }
3289
- return null;
3290
- }
3291
- /**
3292
- * Returns the input if it is a valid non-negative integer string, else null.
3293
- *
3294
- * @example
3295
- * parseNumber("10") // "10"
3296
- * parseNumber("-10") // "-10"
3297
- * parseNumber("10.5") // "10.5"
3298
- */
3299
- function parseNumber(input) {
3300
- return /^-?\d+(?:\.\d+)?$/.test(input) ? input : null;
3301
- }
3302
- /**
3303
- * Returns the input if it is a valid length string, else null.
3304
- */
3305
- function parseLength(input) {
3306
- return /^\d+(px|em|rem|vh|vw|vmin|vmax|%|in|cm|mm|pt|pc|ex|ch|fr)$/.test(input) ? input : null;
3307
- }
3308
- /**
3309
- * Unified parser for fraction or number, with options for percent or repeat syntax.
3310
- * - percent: if true, returns percentage for fraction (e.g., '1/2' -> '50%')
3311
- * - repeat: if true, returns repeat() for number (e.g., '3' -> 'repeat(3, minmax(0, 1fr))')
3312
- */
3313
- function parseFractionOrNumber(value, opts = {}) {
3314
- if (/^\d+$/.test(value)) {
3315
- if (opts.repeat) return `repeat(${value}, minmax(0, 1fr))`;
3316
- return value;
3974
+ function hasPreset(themeObj, category, preset) {
3975
+ return themeObj[category]?.includes?.(preset);
3976
+ }
3977
+ function resolveTheme(config) {
3978
+ let theme = {};
3979
+ if (config.presets) {
3980
+ for (const preset of config.presets) if (preset.theme) theme = deepMerge(theme, preset.theme);
3317
3981
  }
3318
- if (value.includes("/")) {
3319
- const [numerator, denominator] = value.split("/").map(Number);
3320
- if (!isNaN(numerator) && !isNaN(denominator) && denominator !== 0) {
3321
- const result = numerator / denominator;
3322
- if (opts.percent) return `${result * 100}%`;
3323
- return result.toString();
3324
- }
3982
+ if (config.theme) {
3983
+ const { extend, ...overrideTheme } = config.theme;
3984
+ theme = deepMerge(theme, overrideTheme);
3985
+ if (extend) theme = deepMerge(theme, extend);
3325
3986
  }
3326
- return null;
3987
+ return theme;
3327
3988
  }
3328
- var CSS_COLOR_NAMES = /* @__PURE__ */ new Set([
3329
- "aliceblue",
3330
- "antiquewhite",
3331
- "aqua",
3332
- "aquamarine",
3333
- "azure",
3334
- "beige",
3335
- "bisque",
3336
- "black",
3337
- "blanchedalmond",
3338
- "blue",
3339
- "blueviolet",
3340
- "brown",
3341
- "burlywood",
3342
- "cadetblue",
3343
- "chartreuse",
3344
- "chocolate",
3345
- "coral",
3346
- "cornflowerblue",
3347
- "cornsilk",
3348
- "crimson",
3349
- "cyan",
3350
- "darkblue",
3351
- "darkcyan",
3352
- "darkgoldenrod",
3353
- "darkgray",
3354
- "darkgreen",
3355
- "darkgrey",
3356
- "darkkhaki",
3357
- "darkmagenta",
3358
- "darkolivegreen",
3359
- "darkorange",
3360
- "darkorchid",
3361
- "darkred",
3362
- "darksalmon",
3363
- "darkseagreen",
3364
- "darkslateblue",
3365
- "darkslategray",
3366
- "darkslategrey",
3367
- "darkturquoise",
3368
- "darkviolet",
3369
- "deeppink",
3370
- "deepskyblue",
3371
- "dimgray",
3372
- "dimgrey",
3373
- "dodgerblue",
3374
- "firebrick",
3375
- "floralwhite",
3376
- "forestgreen",
3377
- "fuchsia",
3378
- "gainsboro",
3379
- "ghostwhite",
3380
- "gold",
3381
- "goldenrod",
3382
- "gray",
3383
- "grey",
3384
- "green",
3385
- "greenyellow",
3386
- "honeydew",
3387
- "hotpink",
3388
- "indianred",
3389
- "indigo",
3390
- "ivory",
3391
- "khaki",
3392
- "lavender",
3393
- "lavenderblush",
3394
- "lawngreen",
3395
- "lemonchiffon",
3396
- "lightblue",
3397
- "lightcoral",
3398
- "lightcyan",
3399
- "lightgoldenrodyellow",
3400
- "lightgray",
3401
- "lightgreen",
3402
- "lightgrey",
3403
- "lightpink",
3404
- "lightsalmon",
3405
- "lightseagreen",
3406
- "lightskyblue",
3407
- "lightslategray",
3408
- "lightslategrey",
3409
- "lightsteelblue",
3410
- "lightyellow",
3411
- "lime",
3412
- "limegreen",
3413
- "linen",
3414
- "magenta",
3415
- "maroon",
3416
- "mediumaquamarine",
3417
- "mediumblue",
3418
- "mediumorchid",
3419
- "mediumpurple",
3420
- "mediumseagreen",
3421
- "mediumslateblue",
3422
- "mediumspringgreen",
3423
- "mediumturquoise",
3424
- "mediumvioletred",
3425
- "midnightblue",
3426
- "mintcream",
3427
- "mistyrose",
3428
- "moccasin",
3429
- "navajowhite",
3430
- "navy",
3431
- "oldlace",
3432
- "olive",
3433
- "olivedrab",
3434
- "orange",
3435
- "orangered",
3436
- "orchid",
3437
- "palegoldenrod",
3438
- "palegreen",
3439
- "paleturquoise",
3440
- "palevioletred",
3441
- "papayawhip",
3442
- "peachpuff",
3443
- "peru",
3444
- "pink",
3445
- "plum",
3446
- "powderblue",
3447
- "purple",
3448
- "red",
3449
- "rosybrown",
3450
- "royalblue",
3451
- "saddlebrown",
3452
- "salmon",
3453
- "sandybrown",
3454
- "seagreen",
3455
- "seashell",
3456
- "sienna",
3457
- "silver",
3458
- "skyblue",
3459
- "slateblue",
3460
- "slategray",
3461
- "slategrey",
3462
- "snow",
3463
- "springgreen",
3464
- "steelblue",
3465
- "tan",
3466
- "teal",
3467
- "thistle",
3468
- "tomato",
3469
- "turquoise",
3470
- "violet",
3471
- "wheat",
3472
- "white",
3473
- "whitesmoke",
3474
- "yellow",
3475
- "yellowgreen"
3476
- ]);
3477
- /**
3478
- * Returns the input if it is a valid color string, else null.
3479
- *
3480
- * #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(r, g, b), rgb(r, g, b, a), hsl(h, s, l), hsl(h, s, l, a), hwb(h, w, b), hwb(h, w, b, a), lab(l, a, b), lab(l, a, b, a), lch(l, c, h), lch(l, c, h, a), oklab(l, a, b), oklab(l, a, b, a), oklch(l, c, h), oklch(l, c, h, a), color-mix(in oklab, var(--color-blue-500) 60%, transparent)
3481
- */
3482
- function parseColor(input) {
3483
- if (CSS_COLOR_NAMES.has(input.toLowerCase())) return input;
3484
- if (input.startsWith("color:var(")) return input.slice(6);
3485
- if (input.startsWith("color:")) return parseColor(input.slice(6));
3486
- if (input.startsWith("#") && input.length === 4) return `#${input.slice(1)}`;
3487
- if (input.startsWith("#") && input.length === 5) return `#${input.slice(1)}`;
3488
- if (input.startsWith("#") && input.length === 7) return `#${input.slice(1)}`;
3489
- if (input.startsWith("#") && input.length === 9) return `#${input.slice(1)}`;
3490
- if (input.startsWith("rgb(")) return input.slice(4, -1);
3491
- if (input.startsWith("rgba(")) return input.slice(5, -1);
3492
- if (input.startsWith("hsl(")) return input.slice(4, -1);
3493
- if (input.startsWith("hsla(")) return input.slice(5, -1);
3494
- if (input.startsWith("hwb(")) return input.slice(4, -1);
3495
- if (input.startsWith("lab(")) return input.slice(4, -1);
3496
- if (input.startsWith("lch(")) return input.slice(4, -1);
3497
- if (input.startsWith("oklab(")) return input.slice(5, -1);
3498
- if (input.startsWith("oklch(")) return input.slice(6, -1);
3499
- if (input.startsWith("color-mix(")) return input.slice(9, -1);
3500
- return null;
3989
+ function themeToCssVars(theme) {
3990
+ return toCssVarsBlock(themeToCssVarsAll(theme));
3501
3991
  }
3502
- var COLOR_KEYWORDS = /* @__PURE__ */ new Set([
3503
- "inherit",
3504
- "currentcolor",
3505
- "transparent"
3506
- ]);
3992
+ function createContext(configObj) {
3993
+ if (configObj.debug !== void 0) setDebug(!!configObj.debug);
3994
+ const configWithDefaults = {
3995
+ presets: [{ theme: defaultTheme }, ...configObj.presets || []],
3996
+ ...configObj
3997
+ };
3998
+ const themeObj = resolveTheme(configWithDefaults);
3999
+ const ctx = {
4000
+ hasPreset: (category, preset) => {
4001
+ return hasPreset(themeObj, category, preset);
4002
+ },
4003
+ theme: (...args) => {
4004
+ return themeGetter(themeObj, ...args);
4005
+ },
4006
+ config: (...args) => {
4007
+ return configGetter(configWithDefaults, ...args);
4008
+ },
4009
+ themeToCssVars: () => themeToCssVars(themeObj),
4010
+ extendTheme: (category, values) => {
4011
+ if (typeof values === "function") {
4012
+ const result = values(ctx.theme);
4013
+ if (result && typeof result === "object") {
4014
+ const existingValues = themeObj[category] || {};
4015
+ themeObj[category] = {
4016
+ ...existingValues,
4017
+ ...result
4018
+ };
4019
+ }
4020
+ } else if (typeof values === "object" && values !== null && !Array.isArray(values)) {
4021
+ const existingValues = themeObj[category] || {};
4022
+ themeObj[category] = {
4023
+ ...existingValues,
4024
+ ...values
4025
+ };
4026
+ }
4027
+ clearContextCaches(ctx);
4028
+ },
4029
+ getPreflightCSS: (level = true) => {
4030
+ return getPreflightCSS(level);
4031
+ }
4032
+ };
4033
+ initializeContextState(ctx, getUtility(), getModifier());
4034
+ registerCustomUtilities(ctx, configObj.utilities);
4035
+ return ctx;
4036
+ }
4037
+ //#endregion
4038
+ //#region src/core/jsonToAst.ts
3507
4039
  /**
3508
- * Declarations for a theme colour (#228), as Tailwind v4 emits them: `var(--color-<key>)` so runtime theme
3509
- * overrides apply; with an opacity modifier, a literal srgb color-mix fallback plus an oklab color-mix of the var.
4040
+ * Converts a single BaroJsonInput object into an AST tree.
4041
+ * Bypasses string parsing and directly invokes utility/modifier handlers.
4042
+ *
4043
+ * @param input BaroJsonInput object
4044
+ * @param ctx Context
4045
+ * @returns AstNode[]
3510
4046
  */
3511
- function themeColorDecls(prop, value, extra) {
3512
- const key = String(extra.realThemeValue);
3513
- const ref = COLOR_KEYWORDS.has(value.toLowerCase()) || value.startsWith("var(") || !/^[\w-]+$/.test(key) ? value : `var(--color-${key})`;
3514
- if (!extra.opacity) return [decl(prop, ref)];
3515
- const alpha = normalizeAlpha(String(extra.opacity));
3516
- const supports = (amount) => atRule("supports", "(color:color-mix(in lab, red, red))", [decl(prop, `color-mix(in oklab, ${ref} ${amount}, transparent)`)]);
3517
- if (alpha.isVar) return [decl(prop, value), supports(alpha.amount)];
3518
- return [decl(prop, `color-mix(in srgb, ${value} ${alpha.amount}, transparent)`), supports(alpha.amount)];
4047
+ function jsonToAst(input, ctx) {
4048
+ if ((input.variants || []).some((v) => typeof v === "string" ? !isSafeVariantToken(v) : !isSafeVariantValue(v.name || "") || !isSafeVariantValue(v.value || "") || hasCommentToken(v.name || "") || hasCommentToken(v.value || ""))) return [];
4049
+ let utilReg = getUtility(ctx).find((u) => u.name === input.utility.name);
4050
+ if (input.utility.value && !input.utility.arbitrary && !input.utility.customProperty) {
4051
+ const fullName = `${input.utility.name}-${input.utility.value}`;
4052
+ const exactMatch = getUtility(ctx).find((u) => u.name === fullName);
4053
+ if (exactMatch) utilReg = exactMatch;
4054
+ }
4055
+ if (!utilReg) {
4056
+ debugWarn(`[jsonToAst] Unknown utility: "${input.utility.name}"`);
4057
+ return [];
4058
+ }
4059
+ const parsedUtility = {
4060
+ prefix: input.utility.name,
4061
+ value: input.utility.value,
4062
+ arbitrary: input.utility.arbitrary,
4063
+ negative: input.utility.negative,
4064
+ opacity: input.utility.opacity,
4065
+ important: input.utility.important,
4066
+ customProperty: input.utility.customProperty,
4067
+ category: utilReg.category,
4068
+ priority: utilReg.priority
4069
+ };
4070
+ let value = input.utility.value;
4071
+ if (input.utility.negative && value) value = "-" + value;
4072
+ let ast = utilReg.handler(value || "", ctx, parsedUtility, utilReg) || [];
4073
+ if (input.variants && input.variants.length > 0) {
4074
+ const wrappers = [];
4075
+ const selector = "&";
4076
+ for (let i = input.variants.length - 1; i >= 0; i--) {
4077
+ const variantInput = input.variants[i];
4078
+ const variantName = typeof variantInput === "string" ? variantInput : variantInput.name;
4079
+ const variantValue = typeof variantInput === "string" ? void 0 : variantInput.value;
4080
+ const variantArbitrary = typeof variantInput === "string" ? false : variantInput.arbitrary;
4081
+ const parsedModifier = {
4082
+ type: variantName,
4083
+ value: variantValue,
4084
+ arbitrary: variantArbitrary
4085
+ };
4086
+ let matchKey = variantName;
4087
+ if (variantArbitrary && variantValue) {
4088
+ if (variantName) {
4089
+ matchKey = `${variantName}-[${variantValue}]`;
4090
+ parsedModifier.type = matchKey;
4091
+ } else {
4092
+ matchKey = `[${variantValue}]`;
4093
+ parsedModifier.type = matchKey;
4094
+ }
4095
+ } else if (variantValue) {
4096
+ matchKey = `${variantName}-[${variantValue}]`;
4097
+ parsedModifier.type = matchKey;
4098
+ }
4099
+ const plugin = getModifier(ctx).find((p) => p.match(matchKey, ctx));
4100
+ if (!plugin) {
4101
+ debugWarn(`[jsonToAst] Unknown variant: "${matchKey}"`);
4102
+ continue;
4103
+ }
4104
+ if (plugin.astHandler) ast = plugin.astHandler(ast, parsedModifier, ctx, [], i);
4105
+ if (plugin.modifySelector) {
4106
+ const result = plugin.modifySelector({
4107
+ selector,
4108
+ fullClassName: "JSON_GENERATED",
4109
+ mod: parsedModifier,
4110
+ context: ctx,
4111
+ variantChain: [],
4112
+ index: i
4113
+ });
4114
+ if (result == null) continue;
4115
+ if (plugin.wrap && (result === "&" || typeof result === "object" && !Array.isArray(result) && result.selector === "&" || Array.isArray(result) && result.length === 1 && result[0].selector === "&")) {} else if (typeof result === "string" && result.includes("&")) wrappers.push({
4116
+ type: "rule",
4117
+ selector: result
4118
+ });
4119
+ else if (typeof result === "object" && !Array.isArray(result) && result.selector) {
4120
+ const r = result;
4121
+ const wrappingType = r.wrappingType || "rule";
4122
+ wrappers.push({
4123
+ type: wrappingType,
4124
+ selector: r.selector,
4125
+ flatten: r.flatten,
4126
+ source: r.source
4127
+ });
4128
+ } else if (Array.isArray(result)) wrappers.push({
4129
+ type: "wrap",
4130
+ items: result.map((r) => ({
4131
+ type: r.wrappingType || "rule",
4132
+ selector: r.selector,
4133
+ source: r.source,
4134
+ nodes: []
4135
+ }))
4136
+ });
4137
+ }
4138
+ if (plugin.wrap) wrappers.push({
4139
+ type: "wrap",
4140
+ items: plugin.wrap(parsedModifier, ctx)
4141
+ });
4142
+ }
4143
+ for (let i = 0; i < wrappers.length; i++) {
4144
+ const wrap = wrappers[i];
4145
+ if (wrap.type === "wrap") ast = wrap.items.map((item) => item.type === "rule" || item.type === "style-rule" || item.type === "at-rule" || item.type === "at-root" ? {
4146
+ ...item,
4147
+ nodes: [...item.nodes || [], ...ast]
4148
+ } : item);
4149
+ else if (wrap.type === "style-rule") ast = [{
4150
+ type: "style-rule",
4151
+ selector: wrap.selector,
4152
+ source: wrap.source,
4153
+ nodes: Array.isArray(ast) ? ast : [ast]
4154
+ }];
4155
+ else if (wrap.type === "at-rule") ast = [{
4156
+ type: "at-rule",
4157
+ name: wrap.name || "media",
4158
+ params: wrap.params,
4159
+ source: wrap.source,
4160
+ nodes: Array.isArray(ast) ? ast : [ast]
4161
+ }];
4162
+ else if (wrap.type === "rule") ast = [{
4163
+ type: "rule",
4164
+ selector: wrap.selector,
4165
+ source: wrap.source,
4166
+ nodes: Array.isArray(ast) ? ast : [ast]
4167
+ }];
4168
+ }
4169
+ }
4170
+ return applyVarPrefix(ast, ctx);
3519
4171
  }
3520
4172
  /**
3521
- * Opacity modifier → color-mix amount, as Tailwind v4 does: `50` → `50%`, `[37%]` → `37%`, `[0.5]` / `[.8]` → `50%` /
3522
- * `80%` (a bracketed number ≤ 1 is a fraction), `[var(--a)]` / `(--a)` → `var(--a)`.
4173
+ * Generates CSS from a list of BaroJsonInput objects.
4174
+ *
4175
+ * @param inputs Array of BaroJsonInput
4176
+ * @param ctx Context
4177
+ * @param opts Options (minify, etc.)
4178
+ * @returns CSS string
3523
4179
  */
3524
- function normalizeAlpha(raw) {
3525
- let v = raw.trim();
3526
- const bracketed = v.startsWith("[") && v.endsWith("]");
3527
- if (bracketed) v = v.slice(1, -1).trim();
3528
- if (v.startsWith("(") && v.endsWith(")")) v = `var(${v.slice(1, -1).trim()})`;
3529
- if (v.startsWith("var(")) return {
3530
- amount: v,
3531
- isVar: true
3532
- };
3533
- if (v.endsWith("%")) return {
3534
- amount: v,
3535
- isVar: false
3536
- };
3537
- const n = Number(v);
3538
- if (v !== "" && Number.isFinite(n)) return {
3539
- amount: `${+(bracketed && n <= 1 ? n * 100 : n).toFixed(4)}%`,
3540
- isVar: false
3541
- };
3542
- return {
3543
- amount: v,
3544
- isVar: false
3545
- };
4180
+ function generateCssFromJson(inputs, ctx, opts) {
4181
+ const allAtRootNodes = [];
4182
+ const cssList = [];
4183
+ inputs.forEach((input) => {
4184
+ const cleanAst = optimizeAst(jsonToAst(input, ctx));
4185
+ cleanAst.forEach((node) => {
4186
+ if (node.type === "at-root") allAtRootNodes.push(...node.nodes);
4187
+ });
4188
+ let reconstructedName = input.utility.name;
4189
+ if (input.utility.value) reconstructedName += `-${input.utility.value}`;
4190
+ if (input.utility.arbitrary) reconstructedName = `${input.utility.name}-[${input.utility.value}]`;
4191
+ if (input.variants) reconstructedName = `${input.variants.map((v) => typeof v === "string" ? v : v.name).join(":")}:${reconstructedName}`;
4192
+ const css = astToCss(cleanAst, cleanAst.some((node) => node.type === "style-rule") ? void 0 : `.${reconstructedName.replace(/[^a-zA-Z0-9-_]/g, "\\$&")}`, {
4193
+ minify: opts?.minify,
4194
+ important: input.utility.important ?? false
4195
+ });
4196
+ if (css) cssList.push(css);
4197
+ });
4198
+ const rootCss = rootToCss(allAtRootNodes);
4199
+ return `${rootCss ? `:root,:host {${rootCss}}` : ""}${cssList.join(opts?.minify ? "" : "\n")}`;
3546
4200
  }
3547
4201
  //#endregion
3548
4202
  //#region src/presets/interactivity.ts
@@ -3556,10 +4210,7 @@ functionalUtility({
3556
4210
  supportsArbitrary: true,
3557
4211
  supportsCustomProperty: true,
3558
4212
  handle: (value, _ctx, _token, extra) => {
3559
- if (extra?.realThemeValue) {
3560
- if (extra.opacity) return [atRule("supports", `(color:color-mix(in lab, red, red))`, [decl("accent-color", `color-mix(in lab, ${value} ${extra.opacity}%, transparent)`)]), decl("accent-color", value)];
3561
- return [decl("accent-color", `var(--color-${extra.realThemeValue})`)];
3562
- }
4213
+ if (extra?.realThemeValue) return themeColorDecls("accent-color", value, extra);
3563
4214
  return [decl("accent-color", value)];
3564
4215
  },
3565
4216
  handleCustomProperty: (value) => [decl("accent-color", `var(${value})`)],
@@ -3578,10 +4229,7 @@ functionalUtility({
3578
4229
  supportsArbitrary: true,
3579
4230
  supportsCustomProperty: true,
3580
4231
  handle: (value, ctx, token, extra) => {
3581
- if (extra?.realThemeValue) {
3582
- if (extra.opacity) return [atRule("supports", `(color:color-mix(in lab, red, red))`, [decl("caret-color", `color-mix(in lab, ${value} ${extra.opacity}%, transparent)`)]), decl("caret-color", value)];
3583
- return [decl("caret-color", `var(--color-${extra.realThemeValue})`)];
3584
- }
4232
+ if (extra?.realThemeValue) return themeColorDecls("caret-color", value, extra);
3585
4233
  return [decl("caret-color", value)];
3586
4234
  },
3587
4235
  handleCustomProperty: (value) => [decl("caret-color", `var(${value})`)],
@@ -3946,22 +4594,11 @@ staticUtility("caption-bottom", [["caption-side", "bottom"]], { category: "table
3946
4594
  //#region src/presets/shadow-color.ts
3947
4595
  /** Opacity modifier to an alpha: `50` → 50%, `[20%]` → 20%, `(--o)` → var(--o); anything else is invalid. */
3948
4596
  function parseAlpha(op) {
3949
- if (!op) return null;
3950
- if (/^\d+(\.\d+)?$/.test(op)) return {
3951
- alpha: `${op}%`,
3952
- isVar: false
3953
- };
3954
- const pct = /^\[(\d+(?:\.\d+)?)%\]$/.exec(op);
3955
- if (pct) return {
3956
- alpha: `${pct[1]}%`,
3957
- isVar: false
3958
- };
3959
- const cp = /^\((--[\w-]+)\)$/.exec(op);
3960
- if (cp) return {
3961
- alpha: `var(${cp[1]})`,
3962
- isVar: true
4597
+ const a = op ? normalizeAlpha(op) : null;
4598
+ return a && {
4599
+ alpha: a.amount,
4600
+ isVar: a.isVar
3963
4601
  };
3964
- return null;
3965
4602
  }
3966
4603
  function splitTop(value, sep) {
3967
4604
  const out = [];
@@ -4470,6 +5107,11 @@ function layerColor(layer, main, opacity, token, realThemeValue) {
4470
5107
  if (main.startsWith("color:")) return shadowColorDecls(layer, `var(${main.slice(6)})`, opacity);
4471
5108
  if (token.arbitrary && parseColor(main)) return shadowColorDecls(layer, main, opacity);
4472
5109
  }
5110
+ function customShadowAlpha(layer, opacity) {
5111
+ if (!opacity) return [];
5112
+ const a = parseAlpha(opacity);
5113
+ return a ? [decl(`--baro-${layer}-alpha`, a.alpha)] : null;
5114
+ }
4473
5115
  for (const layer of ["shadow", "inset-shadow"]) functionalUtility({
4474
5116
  name: layer,
4475
5117
  supportsArbitrary: true,
@@ -4486,11 +5128,17 @@ for (const layer of ["shadow", "inset-shadow"]) functionalUtility({
4486
5128
  if (token.arbitrary) return boxShadowLayer(layer, layer === "inset-shadow" ? insetEach(value) : value, opacity);
4487
5129
  return null;
4488
5130
  },
4489
- handleCustomProperty: (value) => value.startsWith("color:") ? shadowColorDecls(layer, `var(${value.slice(6)})`, void 0) ?? [] : [
4490
- ringShadowProperties(),
4491
- decl(`--baro-${layer}`, layer === "inset-shadow" ? `inset var(${value})` : `var(${value})`),
4492
- decl("box-shadow", SHADOW_COMPOSITE)
4493
- ]
5131
+ ownsOpacity: true,
5132
+ handleCustomProperty: (value, _ctx, _token, extra) => {
5133
+ if (value.startsWith("color:")) return shadowColorDecls(layer, `var(${value.slice(6)})`, extra?.opacity) ?? [];
5134
+ const alpha = customShadowAlpha(layer, extra?.opacity);
5135
+ return alpha ? [
5136
+ ringShadowProperties(),
5137
+ ...alpha,
5138
+ decl(`--baro-${layer}`, layer === "inset-shadow" ? `inset var(${value})` : `var(${value})`),
5139
+ decl("box-shadow", SHADOW_COMPOSITE)
5140
+ ] : [];
5141
+ }
4494
5142
  });
4495
5143
  var textShadowProperties = () => atRoot([property("--baro-text-shadow-color"), property("--baro-text-shadow-alpha", "100%", "<percentage>")]);
4496
5144
  var namedTextShadow = (ctx, name) => {
@@ -4520,7 +5168,19 @@ functionalUtility({
4520
5168
  if (token.arbitrary) return textShadowValue(value, opacity);
4521
5169
  return null;
4522
5170
  },
4523
- handleCustomProperty: (value) => value.startsWith("color:") ? [textShadowProperties(), ...shadowColorDecls("text-shadow", `var(${value.slice(6)})`, void 0) ?? []] : [textShadowProperties(), decl("text-shadow", `var(${value})`)],
5171
+ ownsOpacity: true,
5172
+ handleCustomProperty: (value, _ctx, _token, extra) => {
5173
+ if (value.startsWith("color:")) {
5174
+ const color = shadowColorDecls("text-shadow", `var(${value.slice(6)})`, extra?.opacity);
5175
+ return color ? [textShadowProperties(), ...color] : [];
5176
+ }
5177
+ const alpha = customShadowAlpha("text-shadow", extra?.opacity);
5178
+ return alpha ? [
5179
+ textShadowProperties(),
5180
+ ...alpha,
5181
+ decl("text-shadow", `var(${value})`)
5182
+ ] : [];
5183
+ },
4524
5184
  category: "effects"
4525
5185
  });
4526
5186
  [
@@ -4584,17 +5244,6 @@ functionalUtility({
4584
5244
  ], { category: "effects" });
4585
5245
  });
4586
5246
  staticUtility("ring-inset", [["--baro-ring-inset", "inset"]], { category: "effects" });
4587
- function createRingColorDecls(key, main, opacity, realThemeValue) {
4588
- const colorVar = `var(--color-${realThemeValue})`;
4589
- let colorMix = colorVar;
4590
- let fallback = colorVar;
4591
- if (opacity) {
4592
- colorMix = `color-mix(in oklab, ${colorVar} ${opacity}%, transparent)`;
4593
- if (parseColor(main) && main.startsWith("#")) fallback = `${main}${Math.round(Number(opacity) / 100 * 255).toString(16).padStart(2, "0")}`;
4594
- else fallback = colorMix;
4595
- }
4596
- return [atRule("supports", "(color:color-mix(in lab, red, red))", [decl(key, colorMix)]), decl(key, fallback)];
4597
- }
4598
5247
  functionalUtility({
4599
5248
  name: "ring",
4600
5249
  supportsArbitrary: true,
@@ -4608,28 +5257,9 @@ functionalUtility({
4608
5257
  decl("--baro-ring-shadow", ringShadowValue(value)),
4609
5258
  decl("box-shadow", SHADOW_COMPOSITE)
4610
5259
  ];
4611
- const opacity = extra?.opacity;
4612
- const realThemeValue = extra?.realThemeValue;
4613
- if (realThemeValue) return createRingColorDecls("--baro-ring-color", main, opacity, realThemeValue);
4614
- if (main.startsWith("color:")) {
4615
- const cp = main.replace("color:", "");
4616
- let colorMix = `var(${cp})`;
4617
- let fallback = colorMix;
4618
- if (opacity) {
4619
- colorMix = `color-mix(in oklab, var(${cp}) ${opacity}%, transparent)`;
4620
- fallback = colorMix;
4621
- }
4622
- return [atRule("supports", "(color:color-mix(in lab, red, red))", [decl("--baro-ring-color", colorMix)]), decl("--baro-ring-color", fallback)];
4623
- }
5260
+ if (extra?.realThemeValue) return themeColorDecls("--baro-ring-color", main, extra);
5261
+ if (main.startsWith("color:")) return [decl("--baro-ring-color", `var(${main.slice(6)})`)];
4624
5262
  if (token.arbitrary) {
4625
- let colorMix = main;
4626
- let fallback = main;
4627
- if (opacity) {
4628
- colorMix = `color-mix(in oklab, ${main} ${opacity}%, transparent)`;
4629
- if (parseColor(main) && main.startsWith("#")) fallback = `${main}${Math.round(Number(opacity) / 100 * 255).toString(16).padStart(2, "0")}`;
4630
- else fallback = colorMix;
4631
- return [atRule("supports", "(color:color-mix(in lab, red, red))", [decl("--baro-ring-color", colorMix)]), decl("--baro-ring-color", fallback)];
4632
- }
4633
5263
  if (!parseColor(main) && /^(-?(\d+\.?\d*|\.\d+)(px|rem|em|%|vw|vh|vmin|vmax|ch|ex|pt|cm|mm|in|pc)|0|(length:.+)|calc\(.+\))$/i.test(main)) {
4634
5264
  const width = main.startsWith("length:") ? main.slice(7) : main;
4635
5265
  return [
@@ -4656,30 +5286,9 @@ functionalUtility({
4656
5286
  themeKeys: ["colors", "shadows"],
4657
5287
  handle: (value, ctx, token, extra) => {
4658
5288
  const main = value;
4659
- const opacity = extra?.opacity;
4660
- const realThemeValue = extra?.realThemeValue;
4661
- if (realThemeValue) return createRingColorDecls("--baro-inset-ring-color", main, opacity, realThemeValue);
4662
- if (main.startsWith("color:")) {
4663
- const cp = main.replace("color:", "");
4664
- let colorMix = `var(${cp})`;
4665
- let fallback = colorMix;
4666
- if (opacity) {
4667
- colorMix = `color-mix(in oklab, var(${cp}) ${opacity}%, transparent)`;
4668
- fallback = colorMix;
4669
- }
4670
- return [atRule("supports", "(color:color-mix(in lab, red, red))", [decl("--baro-inset-ring-color", colorMix)]), decl("--baro-inset-ring-color", fallback)];
4671
- }
4672
- if (token.arbitrary) {
4673
- let colorMix = main;
4674
- let fallback = main;
4675
- if (opacity) {
4676
- colorMix = `color-mix(in oklab, ${main} ${opacity}%, transparent)`;
4677
- if (parseColor(main) && main.startsWith("#")) fallback = `${main}${Math.round(Number(opacity) / 100 * 255).toString(16).padStart(2, "0")}`;
4678
- else fallback = colorMix;
4679
- return [atRule("supports", "(color:color-mix(in lab, red, red))", [decl("--baro-inset-ring-color", colorMix)]), decl("--baro-inset-ring-color", fallback)];
4680
- }
4681
- return [decl("box-shadow", `inset ${main}`)];
4682
- }
5289
+ if (extra?.realThemeValue) return themeColorDecls("--baro-inset-ring-color", main, extra);
5290
+ if (main.startsWith("color:")) return [decl("--baro-inset-ring-color", `var(${main.slice(6)})`)];
5291
+ if (token.arbitrary) return [parseColor(main) || /^var\(--[^)]+\)$/.test(main) ? decl("--baro-inset-ring-color", main) : decl("box-shadow", `inset ${main}`)];
4683
5292
  if (main === "inherit" || main === "current" || main === "transparent") return [decl("--baro-inset-ring-color", main === "current" ? "currentColor" : main)];
4684
5293
  return null;
4685
5294
  },
@@ -6504,7 +7113,7 @@ functionalUtility({
6504
7113
  supportsOpacity: true,
6505
7114
  handle: (value, _ctx, _token, extra) => {
6506
7115
  if (extra?.realThemeValue) return [rule("&::placeholder", themeColorDecls("color", value, extra))];
6507
- if (parseColor(value)) return placeholderColor(value);
7116
+ if (parseColor(value) || /^var\(--[\w-]+\)$/.test(value)) return placeholderColor(value);
6508
7117
  return null;
6509
7118
  },
6510
7119
  handleCustomProperty: (value) => placeholderColor(`var(${value})`),
@@ -6710,7 +7319,7 @@ var stopsDecls = (stop, color) => {
6710
7319
  if (parseColor(value)) return stopsDecls(stop, value);
6711
7320
  return null;
6712
7321
  },
6713
- handleCustomProperty: (value) => [decl(`--baro-gradient-${stop}`, `var(${value})`)],
7322
+ handleCustomProperty: (value) => value.startsWith("color:") ? stopsDecls(stop, `var(${value.slice(6)})`) : [decl(`--baro-gradient-${stop}`, `var(${value})`)],
6714
7323
  description: `${stop} gradient stop utility (color, percent, custom property, arbitrary supported)`,
6715
7324
  category: "background"
6716
7325
  });
@@ -6892,11 +7501,11 @@ var withBorderStyle = (props, width) => [
6892
7501
  ...propList.map((prop) => [prop.replace("width", "style"), "var(--baro-border-style)"]),
6893
7502
  ...propList.map((prop) => [prop, width])
6894
7503
  ];
6895
- staticUtility(`${name}-0`, styled("0px"));
6896
- staticUtility(`${name}-2`, styled("2px"));
6897
- staticUtility(`${name}-4`, styled("4px"));
6898
- staticUtility(`${name}-8`, styled("8px"));
6899
- staticUtility(`${name}`, styled("1px"));
7504
+ staticUtility(`${name}-0`, styled("0px"), { category: "borders" });
7505
+ staticUtility(`${name}-2`, styled("2px"), { category: "borders" });
7506
+ staticUtility(`${name}-4`, styled("4px"), { category: "borders" });
7507
+ staticUtility(`${name}-8`, styled("8px"), { category: "borders" });
7508
+ staticUtility(`${name}`, styled("1px"), { category: "borders" });
6900
7509
  functionalUtility({
6901
7510
  name,
6902
7511
  themeKeys: ["colors", "borderWidth"],
@@ -7066,7 +7675,7 @@ functionalUtility({
7066
7675
  return null;
7067
7676
  },
7068
7677
  handleCustomProperty: (value) => {
7069
- if (value.startsWith("color:")) return [decl("outline-color", value.replace("color:", ""))];
7678
+ if (value.startsWith("color:")) return [decl("outline-color", `var(${value.slice(6)})`)];
7070
7679
  if (value.startsWith("length:")) return withOutlineStyle(`var(${value.replace("length:", "")})`);
7071
7680
  return [decl("outline-color", `var(${value})`)];
7072
7681
  },
@@ -7098,7 +7707,7 @@ functionalUtility({
7098
7707
  handle: (value, _ctx, token, extra) => {
7099
7708
  if (token.prefix !== "divide") return null;
7100
7709
  if (extra?.realThemeValue) return [rule(":where(& > :not(:last-child))", themeColorDecls("border-color", value, extra))];
7101
- if (parseColor(value)) return divideColor(value);
7710
+ if (parseColor(value) || /^var\(--[\w-]+\)$/.test(value)) return divideColor(value);
7102
7711
  return null;
7103
7712
  },
7104
7713
  handleCustomProperty: (value, _ctx, token) => token.prefix === "divide" ? divideColor(`var(${value})`) : [],
@@ -7517,8 +8126,9 @@ functionalUtility({
7517
8126
  themeKeys: ["colors"],
7518
8127
  supportsArbitrary: true,
7519
8128
  supportsCustomProperty: true,
8129
+ supportsOpacity: true,
7520
8130
  handle: (value, ctx, token, extra) => {
7521
- if (extra?.realThemeValue) return [decl("fill", `var(--color-${extra.realThemeValue})`)];
8131
+ if (extra?.realThemeValue) return themeColorDecls("fill", value, extra);
7522
8132
  return [decl("fill", value)];
7523
8133
  },
7524
8134
  description: "fill utility (static, theme, arbitrary, custom property supported)",
@@ -7534,6 +8144,7 @@ functionalUtility({
7534
8144
  themeKeys: ["colors", "strokeWidth"],
7535
8145
  supportsArbitrary: true,
7536
8146
  supportsCustomProperty: true,
8147
+ supportsOpacity: true,
7537
8148
  handle: (value, ctx, token, extra) => {
7538
8149
  if (parseNumber(value) || extra?.themeNamespace === "strokeWidth") return [decl("stroke-width", value)];
7539
8150
  if (token.arbitrary) {
@@ -7541,7 +8152,7 @@ functionalUtility({
7541
8152
  if (hint) return [decl("stroke-width", hint[2])];
7542
8153
  if (!parseColor(value) && (STROKE_LENGTH.test(value) || /^calc\(/.test(value))) return [decl("stroke-width", value)];
7543
8154
  }
7544
- if (extra?.realThemeValue) return [decl("stroke", `var(--color-${extra.realThemeValue})`)];
8155
+ if (extra?.realThemeValue) return themeColorDecls("stroke", value, extra);
7545
8156
  return [decl("stroke", value)];
7546
8157
  },
7547
8158
  handleCustomProperty: (value) => {
@@ -8550,53 +9161,6 @@ functionalModifier((mod) => /^child-(.+)$/.test(mod), ({ selector, mod }) => {
8550
9161
  };
8551
9162
  }, void 0);
8552
9163
  //#endregion
8553
- //#region src/core/rule-order.ts
8554
- var LEADING_AT = /^\s*@(media|container)\s+([^{]*)\{/;
8555
- var LATE_MEDIA = /prefers-color-scheme|\bprint\b|forced-colors|orientation/;
8556
- var MIN_W = /(?:min-width\s*:\s*|width\s*>=?\s*)([\d.]+)(px|rem|em)?/;
8557
- var MAX_W = /(?:max-width\s*:\s*|width\s*<=?\s*)([\d.]+)(px|rem|em)?/;
8558
- function toPx(n, unit) {
8559
- const v = parseFloat(n);
8560
- return unit === "rem" || unit === "em" ? v * 16 : v;
8561
- }
8562
- function preludeKey(kind, prelude) {
8563
- const container = kind === "container";
8564
- if (!container && /^\s*not\b/i.test(prelude)) return [0, 0];
8565
- const min = MIN_W.exec(prelude);
8566
- if (min) return [container ? 4 : 2, toPx(min[1], min[2])];
8567
- const max = MAX_W.exec(prelude);
8568
- if (max) return [container ? 3 : 1, -toPx(max[1], max[2])];
8569
- if (!container && LATE_MEDIA.test(prelude)) return [5, 0];
8570
- return [0, 0];
8571
- }
8572
- function ruleSortKey(rule) {
8573
- const key = [];
8574
- let rest = rule;
8575
- let m;
8576
- while (m = LEADING_AT.exec(rest)) {
8577
- const [g, v] = preludeKey(m[1], m[2]);
8578
- key.push(g, v);
8579
- rest = rest.slice(m[0].length);
8580
- }
8581
- return key;
8582
- }
8583
- function compareKeys(a, b) {
8584
- const n = Math.min(a.length, b.length);
8585
- for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];
8586
- return a.length - b.length;
8587
- }
8588
- /** Index after the last key <= `key` (stable upper bound) in sorted `keys`. */
8589
- function upperBound(keys, key) {
8590
- let lo = 0;
8591
- let hi = keys.length;
8592
- while (lo < hi) {
8593
- const mid = lo + hi >> 1;
8594
- if (compareKeys(keys[mid], key) <= 0) lo = mid + 1;
8595
- else hi = mid;
8596
- }
8597
- return lo;
8598
- }
8599
- //#endregion
8600
- export { AstCache, IncrementalParser, ParseResultCache, UtilityCache, WeakCache, arbitraryPropertyRegistration, astCache, astToCss, atRoot, atRule, clearAllCaches, clearAstCache, collectDeclPaths, comment, compareKeys, configGetter, createContext, decl, declPathToAst, deepMerge, defaultConfig, escapeClassName, expandThemeFunctions, functionalModifier, functionalUtility, generateCss, generateCssFromJson, generateCssRules, getAstCacheStats, getModifier, getPreflightCSS, getUtility, hasCommentDelimiter, hasCommentToken, hasHtmlEndTagOpener, hasPreset, isBalancedPrelude, isDebug, isSafeVariantToken, isSafeVariantValue, isScopedSelector, isStructureSafeValue, isWellFormedVariantBrackets, jsonToAst, mergeAstTreeList, modifierRegistry, normalizeMathSpacing, optimizeAst, parseClassName, parseClassToAst, parseResultCache, property, raw, registerModifier, registerUtility, resolveTheme, rootToCss, rule, ruleSortKey, setContextCacheReset, setDebug, staticModifier, staticUtility, styleRule, themeGetter, themeKeyValue, themeKeyVar, themeToCssVars, tokenize, upperBound, utilityCache };
9164
+ export { AstCache, IncrementalParser, ParseResultCache, REJECT_CLASS, UtilityCache, WeakCache, arbitraryPropertyRegistration, astCache, astToCss, atRoot, atRule, clearAllCaches, clearAstCache, collectDeclPaths, comment, compareKeys, configGetter, createContext, decl, declPathToAst, deepMerge, defaultConfig, escapeClassName, expandThemeFunctions, functionalModifier, functionalUtility, generateCss, generateCssFromJson, generateCssRules, getAstCacheStats, getModifier, getPreflightCSS, getUtility, hasCommentDelimiter, hasCommentToken, hasHtmlEndTagOpener, hasPreset, isBalancedPrelude, isDebug, isSafeVariantToken, isSafeVariantValue, isScopedSelector, isStructureSafeValue, isWellFormedVariantBrackets, jsonToAst, mergeAstTreeList, modifierRegistry, normalizeMathSpacing, optimizeAst, parseClassName, parseClassToAst, parseResultCache, property, raw, registerModifier, registerUtility, resolveTheme, rootToCss, rule, ruleSortKey, setContextCacheReset, setDebug, staticModifier, staticUtility, styleRule, themeGetter, themeKeyValue, themeKeyVar, themeToCssVars, tokenize, upperBound, utilityCache };
8601
9165
 
8602
9166
  //# sourceMappingURL=index.js.map