@tenphi/tasty 0.16.1 → 0.17.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/styles/preset.js +2 -2
- package/dist/styles/preset.js.map +1 -1
- package/dist/utils/styles.d.ts +0 -1
- package/dist/utils/styles.js +0 -1
- package/dist/utils/styles.js.map +1 -1
- package/docs/dsl.md +0 -1
- package/package.json +1 -1
package/dist/styles/preset.js
CHANGED
|
@@ -62,10 +62,10 @@ function presetStyle({ preset, fontSize, lineHeight, textTransform, letterSpacin
|
|
|
62
62
|
mods = mods.filter((mod) => mod !== "strong" && mod !== "bold" && mod !== "italic" && mod !== "icon" && mod !== "tight");
|
|
63
63
|
const name = mods[0] || "inherit";
|
|
64
64
|
if (fontSize == null) setCSSValue(styles, "font-size", name, { cssOnly: true });
|
|
65
|
-
if (lineHeight == null) setCSSValue(styles, "line-height", name);
|
|
65
|
+
if (lineHeight == null) setCSSValue(styles, "line-height", name, { cssOnly: true });
|
|
66
66
|
if (letterSpacing == null) setCSSValue(styles, "letter-spacing", name, { cssOnly: true });
|
|
67
67
|
if (fontWeight == null) setCSSValue(styles, "font-weight", name, { cssOnly: true });
|
|
68
|
-
if (fontStyle == null) setCSSValue(styles, "font-style", name);
|
|
68
|
+
if (fontStyle == null) setCSSValue(styles, "font-style", name, { cssOnly: true });
|
|
69
69
|
if (textTransform == null) setCSSValue(styles, "text-transform", name, { cssOnly: true });
|
|
70
70
|
if (fontFamily == null && font == null) setCSSValue(styles, "font-family", name, { cssOnly: true });
|
|
71
71
|
setCSSValue(styles, "bold-font-weight", name, { varOnly: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preset.js","names":[],"sources":["../../src/styles/preset.ts"],"sourcesContent":["import { makeEmptyDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\n\nimport type { Styles } from './types';\n\n/**\n * Convert a value to CSS, handling numbers as pixels for numeric properties\n */\nfunction toCSS(\n value: string | number | undefined,\n isNumeric: boolean,\n): string | null {\n if (value == null) return null;\n if (typeof value === 'number') {\n return isNumeric ? `${value}px` : String(value);\n }\n // Parse through style parser to handle custom units like 1x, 2r, etc.\n const processed = parseStyle(String(value));\n return processed.groups[0]?.values[0] || String(value);\n}\n\nfunction setCSSValue(\n styles: Styles,\n styleName: string,\n presetName: string,\n { varOnly, cssOnly }: { varOnly?: boolean; cssOnly?: boolean } = {},\n) {\n const value = (() => {\n if (presetName === 'inherit') {\n return 'inherit';\n }\n\n const defaultValue = `var(--default-${styleName}${\n styleName === 'font-family'\n ? ', var(--font-sans, var(--font-sans-fallback))'\n : ''\n })`;\n const fontSuffix =\n styleName === 'font-family'\n ? ', var(--font-sans, var(--font-sans-fallback))'\n : '';\n\n if (presetName === 'default') {\n return `${defaultValue}${fontSuffix}`;\n } else {\n return `var(--${presetName}-${styleName}, ${defaultValue})${fontSuffix}`;\n }\n })();\n\n if (!cssOnly) {\n styles[`--${styleName}`] = value;\n }\n\n if (!varOnly) {\n styles[styleName] = value;\n }\n}\n\ninterface PresetStyleProps {\n preset?: string | boolean;\n fontSize?: string | number;\n lineHeight?: string | number;\n textTransform?: string;\n letterSpacing?: string | number;\n fontWeight?: string | number;\n fontStyle?: string | boolean;\n fontFamily?: string;\n /** Alias for fontFamily with special handling for 'monospace' and boolean */\n font?: string | boolean;\n}\n\n/**\n * Resolve font/fontFamily value to CSS font-family string.\n *\n * - `font=\"monospace\"` → var(--font-mono, var(--font-mono-fallback))\n * - `font={true}` → var(--font-sans, var(--font-sans-fallback))\n * - `font=\"CustomFont\"` → CustomFont, var(--font-sans, var(--font-sans-fallback))\n * - `fontFamily=\"Arial\"` → Arial (direct, no fallback)\n */\nfunction resolveFontFamily(\n font: string | boolean | undefined,\n fontFamily: string | undefined,\n): string | null {\n // fontFamily takes precedence as a direct value\n if (fontFamily) {\n return fontFamily;\n }\n\n if (font == null || font === false) {\n return null;\n }\n\n if (font === 'monospace') {\n return 'var(--font-mono, var(--font-mono-fallback))';\n }\n\n if (font === true) {\n return 'var(--font-sans, var(--font-sans-fallback))';\n }\n\n return `${font}, var(--font-sans, var(--font-sans-fallback))`;\n}\n\n/**\n * Handles typography preset and individual font properties.\n *\n * When `preset` is defined, it sets up CSS custom properties for typography.\n * Individual font props can be used with or without `preset`:\n * - With `preset`: overrides the preset value for that property\n * - Without `preset`: outputs the CSS directly\n *\n * Number values are converted to pixels for fontSize, lineHeight, letterSpacing.\n * fontWeight accepts numbers directly (e.g., 400, 700).\n *\n * font vs fontFamily:\n * - `font` is the recommended prop with special handling (monospace, boolean, fallback)\n * - `fontFamily` is a direct value without special handling\n */\nexport function presetStyle({\n preset,\n fontSize,\n lineHeight,\n textTransform,\n letterSpacing,\n fontWeight,\n fontStyle,\n fontFamily,\n font,\n}: PresetStyleProps) {\n const styles: Styles = {};\n const hasPreset = preset != null && preset !== false;\n\n // Handle preset if defined\n if (hasPreset) {\n const presetValue = preset === true ? '' : String(preset);\n\n const processed = parseStyle(presetValue);\n let { mods } = processed.groups[0] ?? makeEmptyDetails();\n\n const isStrong = mods.includes('strong');\n const isItalic = mods.includes('italic');\n const isIcon = mods.includes('icon');\n const isTight = mods.includes('tight');\n\n mods = mods.filter(\n (mod) =>\n mod !== 'strong' &&\n mod !== 'bold' &&\n mod !== 'italic' &&\n mod !== 'icon' &&\n mod !== 'tight',\n );\n\n const name = mods[0] || 'inherit';\n\n // Set preset values for properties not explicitly overridden\n if (fontSize == null) {\n setCSSValue(styles, 'font-size', name, { cssOnly: true });\n }\n if (lineHeight == null) {\n setCSSValue(styles, 'line-height', name);\n }\n if (letterSpacing == null) {\n setCSSValue(styles, 'letter-spacing', name, { cssOnly: true });\n }\n if (fontWeight == null) {\n setCSSValue(styles, 'font-weight', name, { cssOnly: true });\n }\n if (fontStyle == null) {\n setCSSValue(styles, 'font-style', name);\n }\n if (textTransform == null) {\n setCSSValue(styles, 'text-transform', name, { cssOnly: true });\n }\n if (fontFamily == null && font == null) {\n setCSSValue(styles, 'font-family', name, { cssOnly: true });\n }\n\n setCSSValue(styles, 'bold-font-weight', name, { varOnly: true });\n setCSSValue(styles, 'icon-size', name, { varOnly: true });\n\n if (isStrong) {\n styles['font-weight'] = 'var(--bold-font-weight)';\n }\n if (isItalic) {\n styles['font-style'] = 'italic';\n }\n if (isIcon) {\n styles['font-size'] = 'var(--icon-size)';\n styles['line-height'] = 'var(--icon-size)';\n }\n if (isTight) {\n styles['line-height'] = '1em';\n }\n }\n\n // Handle individual font properties (work with or without preset)\n const fontSizeVal = toCSS(fontSize, true);\n if (fontSizeVal) {\n styles['font-size'] = fontSizeVal;\n }\n\n const lineHeightVal = toCSS(lineHeight, true);\n if (lineHeightVal) {\n styles['line-height'] = lineHeightVal;\n }\n\n const letterSpacingVal = toCSS(letterSpacing, true);\n if (letterSpacingVal) {\n styles['letter-spacing'] = letterSpacingVal;\n }\n\n // fontWeight: numbers should NOT get 'px' suffix\n const fontWeightVal = toCSS(fontWeight, false);\n if (fontWeightVal) {\n styles['font-weight'] = fontWeightVal;\n }\n\n // fontStyle: handle boolean (true → italic) and string values\n if (fontStyle != null) {\n if (fontStyle === true) {\n styles['font-style'] = 'italic';\n } else if (fontStyle !== 'inherit') {\n styles['font-style'] = fontStyle ? 'italic' : 'normal';\n } else {\n styles['font-style'] = 'inherit';\n }\n }\n\n if (textTransform) {\n styles['text-transform'] = textTransform;\n }\n\n // Handle font/fontFamily (font has special handling, fontFamily is direct)\n const fontFamily_ = resolveFontFamily(font, fontFamily);\n if (fontFamily_) {\n styles['font-family'] = fontFamily_;\n }\n\n // Return undefined if no styles to apply\n if (Object.keys(styles).length === 0) {\n return;\n }\n\n return styles;\n}\n\npresetStyle.__lookupStyles = [\n 'preset',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textTransform',\n 'fontWeight',\n 'fontStyle',\n 'fontFamily',\n 'font',\n];\n"],"mappings":";;;;;;;AAQA,SAAS,MACP,OACA,WACe;AACf,KAAI,SAAS,KAAM,QAAO;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,KAAK,MAAM;AAGxB,MAAI,YAAY,KACd,aAAY,QAAQ,aAAa,MAAM,EAAE,SAAS,MAAM,CAAC;AAE3D,MAAI,cAAc,KAChB,aAAY,QAAQ,eAAe,
|
|
1
|
+
{"version":3,"file":"preset.js","names":[],"sources":["../../src/styles/preset.ts"],"sourcesContent":["import { makeEmptyDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\n\nimport type { Styles } from './types';\n\n/**\n * Convert a value to CSS, handling numbers as pixels for numeric properties\n */\nfunction toCSS(\n value: string | number | undefined,\n isNumeric: boolean,\n): string | null {\n if (value == null) return null;\n if (typeof value === 'number') {\n return isNumeric ? `${value}px` : String(value);\n }\n // Parse through style parser to handle custom units like 1x, 2r, etc.\n const processed = parseStyle(String(value));\n return processed.groups[0]?.values[0] || String(value);\n}\n\nfunction setCSSValue(\n styles: Styles,\n styleName: string,\n presetName: string,\n { varOnly, cssOnly }: { varOnly?: boolean; cssOnly?: boolean } = {},\n) {\n const value = (() => {\n if (presetName === 'inherit') {\n return 'inherit';\n }\n\n const defaultValue = `var(--default-${styleName}${\n styleName === 'font-family'\n ? ', var(--font-sans, var(--font-sans-fallback))'\n : ''\n })`;\n const fontSuffix =\n styleName === 'font-family'\n ? ', var(--font-sans, var(--font-sans-fallback))'\n : '';\n\n if (presetName === 'default') {\n return `${defaultValue}${fontSuffix}`;\n } else {\n return `var(--${presetName}-${styleName}, ${defaultValue})${fontSuffix}`;\n }\n })();\n\n if (!cssOnly) {\n styles[`--${styleName}`] = value;\n }\n\n if (!varOnly) {\n styles[styleName] = value;\n }\n}\n\ninterface PresetStyleProps {\n preset?: string | boolean;\n fontSize?: string | number;\n lineHeight?: string | number;\n textTransform?: string;\n letterSpacing?: string | number;\n fontWeight?: string | number;\n fontStyle?: string | boolean;\n fontFamily?: string;\n /** Alias for fontFamily with special handling for 'monospace' and boolean */\n font?: string | boolean;\n}\n\n/**\n * Resolve font/fontFamily value to CSS font-family string.\n *\n * - `font=\"monospace\"` → var(--font-mono, var(--font-mono-fallback))\n * - `font={true}` → var(--font-sans, var(--font-sans-fallback))\n * - `font=\"CustomFont\"` → CustomFont, var(--font-sans, var(--font-sans-fallback))\n * - `fontFamily=\"Arial\"` → Arial (direct, no fallback)\n */\nfunction resolveFontFamily(\n font: string | boolean | undefined,\n fontFamily: string | undefined,\n): string | null {\n // fontFamily takes precedence as a direct value\n if (fontFamily) {\n return fontFamily;\n }\n\n if (font == null || font === false) {\n return null;\n }\n\n if (font === 'monospace') {\n return 'var(--font-mono, var(--font-mono-fallback))';\n }\n\n if (font === true) {\n return 'var(--font-sans, var(--font-sans-fallback))';\n }\n\n return `${font}, var(--font-sans, var(--font-sans-fallback))`;\n}\n\n/**\n * Handles typography preset and individual font properties.\n *\n * When `preset` is defined, it sets up CSS custom properties for typography.\n * Individual font props can be used with or without `preset`:\n * - With `preset`: overrides the preset value for that property\n * - Without `preset`: outputs the CSS directly\n *\n * Number values are converted to pixels for fontSize, lineHeight, letterSpacing.\n * fontWeight accepts numbers directly (e.g., 400, 700).\n *\n * font vs fontFamily:\n * - `font` is the recommended prop with special handling (monospace, boolean, fallback)\n * - `fontFamily` is a direct value without special handling\n */\nexport function presetStyle({\n preset,\n fontSize,\n lineHeight,\n textTransform,\n letterSpacing,\n fontWeight,\n fontStyle,\n fontFamily,\n font,\n}: PresetStyleProps) {\n const styles: Styles = {};\n const hasPreset = preset != null && preset !== false;\n\n // Handle preset if defined\n if (hasPreset) {\n const presetValue = preset === true ? '' : String(preset);\n\n const processed = parseStyle(presetValue);\n let { mods } = processed.groups[0] ?? makeEmptyDetails();\n\n const isStrong = mods.includes('strong');\n const isItalic = mods.includes('italic');\n const isIcon = mods.includes('icon');\n const isTight = mods.includes('tight');\n\n mods = mods.filter(\n (mod) =>\n mod !== 'strong' &&\n mod !== 'bold' &&\n mod !== 'italic' &&\n mod !== 'icon' &&\n mod !== 'tight',\n );\n\n const name = mods[0] || 'inherit';\n\n // Set preset values for properties not explicitly overridden\n if (fontSize == null) {\n setCSSValue(styles, 'font-size', name, { cssOnly: true });\n }\n if (lineHeight == null) {\n setCSSValue(styles, 'line-height', name, { cssOnly: true });\n }\n if (letterSpacing == null) {\n setCSSValue(styles, 'letter-spacing', name, { cssOnly: true });\n }\n if (fontWeight == null) {\n setCSSValue(styles, 'font-weight', name, { cssOnly: true });\n }\n if (fontStyle == null) {\n setCSSValue(styles, 'font-style', name, { cssOnly: true });\n }\n if (textTransform == null) {\n setCSSValue(styles, 'text-transform', name, { cssOnly: true });\n }\n if (fontFamily == null && font == null) {\n setCSSValue(styles, 'font-family', name, { cssOnly: true });\n }\n\n setCSSValue(styles, 'bold-font-weight', name, { varOnly: true });\n setCSSValue(styles, 'icon-size', name, { varOnly: true });\n\n if (isStrong) {\n styles['font-weight'] = 'var(--bold-font-weight)';\n }\n if (isItalic) {\n styles['font-style'] = 'italic';\n }\n if (isIcon) {\n styles['font-size'] = 'var(--icon-size)';\n styles['line-height'] = 'var(--icon-size)';\n }\n if (isTight) {\n styles['line-height'] = '1em';\n }\n }\n\n // Handle individual font properties (work with or without preset)\n const fontSizeVal = toCSS(fontSize, true);\n if (fontSizeVal) {\n styles['font-size'] = fontSizeVal;\n }\n\n const lineHeightVal = toCSS(lineHeight, true);\n if (lineHeightVal) {\n styles['line-height'] = lineHeightVal;\n }\n\n const letterSpacingVal = toCSS(letterSpacing, true);\n if (letterSpacingVal) {\n styles['letter-spacing'] = letterSpacingVal;\n }\n\n // fontWeight: numbers should NOT get 'px' suffix\n const fontWeightVal = toCSS(fontWeight, false);\n if (fontWeightVal) {\n styles['font-weight'] = fontWeightVal;\n }\n\n // fontStyle: handle boolean (true → italic) and string values\n if (fontStyle != null) {\n if (fontStyle === true) {\n styles['font-style'] = 'italic';\n } else if (fontStyle !== 'inherit') {\n styles['font-style'] = fontStyle ? 'italic' : 'normal';\n } else {\n styles['font-style'] = 'inherit';\n }\n }\n\n if (textTransform) {\n styles['text-transform'] = textTransform;\n }\n\n // Handle font/fontFamily (font has special handling, fontFamily is direct)\n const fontFamily_ = resolveFontFamily(font, fontFamily);\n if (fontFamily_) {\n styles['font-family'] = fontFamily_;\n }\n\n // Return undefined if no styles to apply\n if (Object.keys(styles).length === 0) {\n return;\n }\n\n return styles;\n}\n\npresetStyle.__lookupStyles = [\n 'preset',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textTransform',\n 'fontWeight',\n 'fontStyle',\n 'fontFamily',\n 'font',\n];\n"],"mappings":";;;;;;;AAQA,SAAS,MACP,OACA,WACe;AACf,KAAI,SAAS,KAAM,QAAO;AAC1B,KAAI,OAAO,UAAU,SACnB,QAAO,YAAY,GAAG,MAAM,MAAM,OAAO,MAAM;AAIjD,QADkB,WAAW,OAAO,MAAM,CAAC,CAC1B,OAAO,IAAI,OAAO,MAAM,OAAO,MAAM;;AAGxD,SAAS,YACP,QACA,WACA,YACA,EAAE,SAAS,YAAsD,EAAE,EACnE;CACA,MAAM,eAAe;AACnB,MAAI,eAAe,UACjB,QAAO;EAGT,MAAM,eAAe,iBAAiB,YACpC,cAAc,gBACV,kDACA,GACL;EACD,MAAM,aACJ,cAAc,gBACV,kDACA;AAEN,MAAI,eAAe,UACjB,QAAO,GAAG,eAAe;MAEzB,QAAO,SAAS,WAAW,GAAG,UAAU,IAAI,aAAa,GAAG;KAE5D;AAEJ,KAAI,CAAC,QACH,QAAO,KAAK,eAAe;AAG7B,KAAI,CAAC,QACH,QAAO,aAAa;;;;;;;;;;AAyBxB,SAAS,kBACP,MACA,YACe;AAEf,KAAI,WACF,QAAO;AAGT,KAAI,QAAQ,QAAQ,SAAS,MAC3B,QAAO;AAGT,KAAI,SAAS,YACX,QAAO;AAGT,KAAI,SAAS,KACX,QAAO;AAGT,QAAO,GAAG,KAAK;;;;;;;;;;;;;;;;;AAkBjB,SAAgB,YAAY,EAC1B,QACA,UACA,YACA,eACA,eACA,YACA,WACA,YACA,QACmB;CACnB,MAAM,SAAiB,EAAE;AAIzB,KAHkB,UAAU,QAAQ,WAAW,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,QAAO,eAAe;CAGxB,MAAM,gBAAgB,MAAM,YAAY,KAAK;AAC7C,KAAI,cACF,QAAO,iBAAiB;CAG1B,MAAM,mBAAmB,MAAM,eAAe,KAAK;AACnD,KAAI,iBACF,QAAO,oBAAoB;CAI7B,MAAM,gBAAgB,MAAM,YAAY,MAAM;AAC9C,KAAI,cACF,QAAO,iBAAiB;AAI1B,KAAI,aAAa,KACf,KAAI,cAAc,KAChB,QAAO,gBAAgB;UACd,cAAc,UACvB,QAAO,gBAAgB,YAAY,WAAW;KAE9C,QAAO,gBAAgB;AAI3B,KAAI,cACF,QAAO,oBAAoB;CAI7B,MAAM,cAAc,kBAAkB,MAAM,WAAW;AACvD,KAAI,YACF,QAAO,iBAAiB;AAI1B,KAAI,OAAO,KAAK,OAAO,CAAC,WAAW,EACjC;AAGF,QAAO;;AAGT,YAAY,iBAAiB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
|
package/dist/utils/styles.d.ts
CHANGED
package/dist/utils/styles.js
CHANGED
package/dist/utils/styles.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"styles.js","names":[],"sources":["../../src/utils/styles.ts"],"sourcesContent":["import { StyleParser } from '../parser/parser';\nimport { okhslFunc } from '../plugins/okhsl-plugin';\n\nimport type { ProcessedStyle, StyleDetails } from '../parser/types';\n\nimport { getNamedColorHex } from './color-math';\n\nexport {\n getNamedColorHex,\n getRgbValuesFromRgbaString,\n hexToRgb,\n strToRgb,\n} from './color-math';\n\nexport type StyleValue<T = string> = T | boolean | number | null | undefined;\n\n/**\n * Normalize a color token value.\n * - Boolean `true` is converted to `'transparent'`\n * - Boolean `false` returns `null` (signals the token should be skipped)\n * - Other values are returned as-is\n *\n * @param value - The raw token value\n * @returns Normalized value or null if the token should be skipped\n */\nexport function normalizeColorTokenValue<T>(\n value: T | boolean,\n): T | 'transparent' | null {\n if (value === true) {\n return 'transparent';\n }\n if (value === false) {\n return null;\n }\n return value as T;\n}\n\nexport type StyleValueStateMap<T = string> = Record<\n string,\n StyleValue<T> | '@inherit'\n>;\n\n/**\n * Combined type for style values that can be either a direct value or a state map.\n * Use this for component props that accept style values.\n */\nexport type StylePropValue<T = string> = StyleValue<T> | StyleValueStateMap<T>;\n\nexport type CSSMap = { $?: string | string[] } & Record<\n string,\n string | string[]\n>;\n\nexport type StyleHandlerResult = CSSMap | CSSMap[] | void;\n\nexport type RawStyleHandler = (value: StyleValueStateMap) => StyleHandlerResult;\n\nexport type StyleHandler = RawStyleHandler & {\n __lookupStyles: string[];\n};\n\n/**\n * Handler definition forms for configure() and plugins.\n * - Function only: lookup styles inferred from key name\n * - Single property tuple: ['styleName', handler]\n * - Multi-property tuple: [['style1', 'style2'], handler]\n */\nexport type StyleHandlerDefinition =\n | RawStyleHandler\n | [string, RawStyleHandler]\n | [string[], RawStyleHandler];\n\nexport interface ParsedColor {\n color?: string;\n name?: string;\n opacity?: number;\n}\n\nexport type StyleMap = Record<string, StyleValue | StyleValueStateMap>;\n\nconst devMode = process.env.NODE_ENV !== 'production';\n\n// Precompiled regex patterns for parseColor optimization\n// Match var(--name-color...) and extract the name, regardless of fallbacks\nconst COLOR_VAR_PATTERN = /var\\(--([a-z0-9-]+)-color/;\nconst COLOR_VAR_COMPONENTS_PATTERN =\n /var\\(--([a-z0-9-]+)-color-(?:rgb|hsl|oklch)/;\nconst RGB_ALPHA_PATTERN = /\\/\\s*([0-9.]+)\\)/;\nconst RE_HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;\nconst RE_VAR_COLOR = /^var\\(--[a-z0-9-]+-color/;\n\nfunction isSimpleColorFast(val: string): boolean {\n const c0 = val.charCodeAt(0);\n\n switch (c0) {\n case 35: // '#'\n return RE_HEX_COLOR.test(val);\n case 114: // 'r'\n return val.charCodeAt(1) === 103 && val.charCodeAt(2) === 98; // 'rgb'\n case 104: // 'h'\n return val.charCodeAt(1) === 115 && val.charCodeAt(2) === 108; // 'hsl'\n case 108: // 'l'\n return val.charCodeAt(1) === 99 && val.charCodeAt(2) === 104; // 'lch'\n case 111: // 'o'\n return val.startsWith('oklch(') || val.startsWith('okhsl(');\n case 118: // 'v'\n return RE_VAR_COLOR.test(val);\n case 99: // 'c'\n return val === 'currentColor' || val === 'currentcolor';\n case 116: // 't'\n return val === 'transparent';\n default:\n return getNamedColorHex().has(val.toLowerCase());\n }\n}\n\n// Rate limiting for dev warnings to avoid spam\nlet colorWarningCount = 0;\nconst MAX_COLOR_WARNINGS = 10;\n\nexport const CUSTOM_UNITS = {\n r: '6px',\n cr: '10px',\n bw: '1px',\n ow: '3px',\n x: '8px',\n lh: 'var(--line-height)',\n sf: function sf(num: number) {\n return `minmax(0, ${num}fr)`;\n },\n};\n\nexport const DIRECTIONS = ['top', 'right', 'bottom', 'left'];\n\n// Lazy-initialized to break the circular dependency:\n// parser.ts → classify.ts → utils/styles.ts → parser.ts\nlet __tastyParser: StyleParser | null = null;\n\nfunction getOrCreateParser(): StyleParser {\n if (!__tastyParser) {\n __tastyParser = new StyleParser({ units: CUSTOM_UNITS });\n __tastyParser.setFuncs(__tastyFuncs);\n }\n return __tastyParser;\n}\n\n// Registry for user-provided custom functions that the parser can call.\n// It is updated through the `customFunc` helper exported below.\n// okhsl is registered as a built-in function so it works regardless of\n// tree-shaking or module initialization order.\nconst __tastyFuncs: Record<string, (groups: StyleDetails[]) => string> = {\n okhsl: okhslFunc,\n};\n\nexport function customFunc(\n name: string,\n fn: (groups: StyleDetails[]) => string,\n) {\n __tastyFuncs[name] = fn;\n getOrCreateParser().setFuncs(__tastyFuncs);\n}\n\n/**\n * Get the global StyleParser instance.\n * Used by configure() to apply parser configuration.\n */\nexport function getGlobalParser(): StyleParser {\n return getOrCreateParser();\n}\n\n/**\n * Get the current custom functions registry.\n * Used by configure() to merge with new functions.\n */\nexport function getGlobalFuncs(): Record<\n string,\n (groups: StyleDetails[]) => string\n> {\n return __tastyFuncs;\n}\n\n// ============================================================================\n// Global Predefined Tokens\n// ============================================================================\n\n/**\n * Storage for predefined tokens that are replaced during style parsing.\n * Keys are token names (with $ or # prefix), values are pre-processed CSS values.\n */\nlet __globalPredefinedTokens: Record<string, string> | null = null;\n\n/**\n * Set global predefined tokens.\n * Called from configure() after processing token values.\n * Merges with existing tokens (new tokens override existing ones with same key).\n * Keys are normalized to lowercase (parser lowercases input before classification).\n * @internal\n */\nexport function setGlobalPredefinedTokens(\n tokens: Record<string, string>,\n): void {\n // Normalize keys to lowercase for case-insensitive matching\n const normalizedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(tokens)) {\n const lowerKey = key.toLowerCase();\n const lowerValue = value.toLowerCase();\n\n // Warn if trying to use bare #current to define other color tokens\n // #current represents currentcolor which cannot be used as a base for recursive token resolution\n // Note: #current.5 (with opacity) is allowed since it resolves to a concrete color-mix value\n if (lowerKey.startsWith('#') && lowerValue === '#current') {\n console.warn(\n `Tasty: Using #current to define color token \"${key}\" is not supported. ` +\n `The #current token represents currentcolor which cannot be used as a base for other tokens.`,\n );\n continue; // Skip this token\n }\n\n normalizedTokens[lowerKey] = value;\n }\n // Merge with existing tokens (consistent with how states, units, funcs are handled)\n __globalPredefinedTokens = __globalPredefinedTokens\n ? { ...__globalPredefinedTokens, ...normalizedTokens }\n : normalizedTokens;\n // Clear parser cache since token values affect parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n * Get the current global predefined tokens.\n * Returns null if no tokens are configured.\n */\nexport function getGlobalPredefinedTokens(): Record<string, string> | null {\n return __globalPredefinedTokens;\n}\n\n/**\n * Reset global predefined tokens.\n * Used for testing.\n * @internal\n */\nexport function resetGlobalPredefinedTokens(): void {\n __globalPredefinedTokens = null;\n // Clear parser cache since token availability affects parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n *\n * @param {String} value\n * @param {Number} mode\n * @returns {Object<String,String|Array>}\n */\nexport function parseStyle(value: StyleValue): ProcessedStyle {\n let str: string;\n\n if (typeof value === 'string') {\n str = value;\n } else if (typeof value === 'number') {\n str = String(value);\n } else {\n // boolean, null, undefined, objects etc. → empty string\n str = '';\n }\n\n return getOrCreateParser().process(str);\n}\n\n/**\n * Parse color. Find it value, name and opacity.\n * Optimized to avoid heavy parseStyle calls for simple color patterns.\n */\nexport function parseColor(val: string, ignoreError = false): ParsedColor {\n // Early return for non-strings or empty values\n if (typeof val !== 'string') {\n val = String(val ?? '');\n }\n\n val = val.trim();\n if (!val) return {};\n\n // Fast path: Check if it's a simple color pattern that doesn't need full parsing\n const isSimpleColor = isSimpleColorFast(val);\n\n let firstColor: string;\n if (isSimpleColor) {\n // For simple colors, use the value directly without parsing\n firstColor = val;\n } else {\n const processed = parseStyle(val);\n const extractedColor = processed.groups.find((g) => g.colors.length)\n ?.colors[0];\n\n if (!extractedColor) {\n // Rate-limited warning to avoid spam\n if (!ignoreError && devMode && colorWarningCount < MAX_COLOR_WARNINGS) {\n console.warn('Tasty: unable to parse color:', val);\n colorWarningCount++;\n if (colorWarningCount === MAX_COLOR_WARNINGS) {\n console.warn(\n 'Tasty: color parsing warnings will be suppressed from now on',\n );\n }\n }\n return {};\n }\n\n firstColor = extractedColor;\n }\n\n // Extract color name (if present) from variable pattern using precompiled regex\n let nameMatch = firstColor.match(COLOR_VAR_PATTERN);\n if (!nameMatch) {\n nameMatch = firstColor.match(COLOR_VAR_COMPONENTS_PATTERN);\n }\n\n let opacity: number | undefined;\n if (\n firstColor.startsWith('rgb') ||\n firstColor.startsWith('hsl') ||\n firstColor.startsWith('lch') ||\n firstColor.startsWith('oklch') ||\n firstColor.startsWith('okhsl')\n ) {\n const alphaMatch = firstColor.match(RGB_ALPHA_PATTERN);\n if (alphaMatch) {\n const v = parseFloat(alphaMatch[1]);\n if (!isNaN(v)) opacity = v * 100;\n }\n }\n\n return {\n color: firstColor,\n name: nameMatch ? nameMatch[1] : undefined,\n opacity,\n };\n}\n\nexport function filterMods(mods: string[], allowedMods: string[]): string[] {\n return mods.filter((mod) => allowedMods.includes(mod));\n}\n\n// ============================================================================\n// Style Stringification\n// ============================================================================\n\nconst _innerCache = new WeakMap();\nconst _topLevelCache = new WeakMap<object, string>();\n\nexport function stringifyStyles(styles: unknown): string {\n if (styles == null || typeof styles !== 'object') return '';\n\n const cached = _topLevelCache.get(styles as object);\n if (cached !== undefined) return cached;\n\n const obj = styles as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = obj[k];\n if (v === undefined || typeof v === 'function' || typeof v === 'symbol')\n continue;\n\n const c0 = k.charCodeAt(0);\n const needsInnerSort =\n ((c0 >= 65 && c0 <= 90) || c0 === 38) &&\n v &&\n typeof v === 'object' &&\n !Array.isArray(v);\n\n let sv: string;\n if (needsInnerSort) {\n sv = _innerCache.get(v);\n if (sv === undefined) {\n const innerObj = v as Record<string, unknown>;\n const innerKeys = Object.keys(innerObj).sort();\n const innerParts: string[] = [];\n for (const ik of innerKeys) {\n const ivs = JSON.stringify(innerObj[ik]);\n if (ivs !== undefined)\n innerParts.push(JSON.stringify(ik) + ':' + ivs);\n }\n sv = '{' + innerParts.join(',') + '}';\n _innerCache.set(v, sv);\n }\n } else {\n sv = JSON.stringify(v);\n }\n parts.push(JSON.stringify(k) + ':' + sv);\n }\n const result = '{' + parts.join(',') + '}';\n _topLevelCache.set(styles as object, result);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAgB,yBACd,OAC0B;AAC1B,KAAI,UAAU,KACZ,QAAO;AAET,KAAI,UAAU,MACZ,QAAO;AAET,QAAO;;AAkDT,MAAM,oBAAoB;AAC1B,MAAM,+BACJ;AACF,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AAErB,SAAS,kBAAkB,KAAsB;AAG/C,SAFW,IAAI,WAAW,EAAE,EAE5B;EACE,KAAK,GACH,QAAO,aAAa,KAAK,IAAI;EAC/B,KAAK,IACH,QAAO,IAAI,WAAW,EAAE,KAAK,OAAO,IAAI,WAAW,EAAE,KAAK;EAC5D,KAAK,IACH,QAAO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AAG;;QAGxB,MAAK,KAAK,UAAU,EAAE;AAExB,QAAM,KAAK,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG;;CAE1C,MAAM,SAAS,MAAM,MAAM,KAAK,IAAI,GAAG;AACvC,gBAAe,IAAI,QAAkB,OAAO;AAC5C,QAAO"}
|
|
1
|
+
{"version":3,"file":"styles.js","names":[],"sources":["../../src/utils/styles.ts"],"sourcesContent":["import { StyleParser } from '../parser/parser';\nimport { okhslFunc } from '../plugins/okhsl-plugin';\n\nimport type { ProcessedStyle, StyleDetails } from '../parser/types';\n\nimport { getNamedColorHex } from './color-math';\n\nexport {\n getNamedColorHex,\n getRgbValuesFromRgbaString,\n hexToRgb,\n strToRgb,\n} from './color-math';\n\nexport type StyleValue<T = string> = T | boolean | number | null | undefined;\n\n/**\n * Normalize a color token value.\n * - Boolean `true` is converted to `'transparent'`\n * - Boolean `false` returns `null` (signals the token should be skipped)\n * - Other values are returned as-is\n *\n * @param value - The raw token value\n * @returns Normalized value or null if the token should be skipped\n */\nexport function normalizeColorTokenValue<T>(\n value: T | boolean,\n): T | 'transparent' | null {\n if (value === true) {\n return 'transparent';\n }\n if (value === false) {\n return null;\n }\n return value as T;\n}\n\nexport type StyleValueStateMap<T = string> = Record<\n string,\n StyleValue<T> | '@inherit'\n>;\n\n/**\n * Combined type for style values that can be either a direct value or a state map.\n * Use this for component props that accept style values.\n */\nexport type StylePropValue<T = string> = StyleValue<T> | StyleValueStateMap<T>;\n\nexport type CSSMap = { $?: string | string[] } & Record<\n string,\n string | string[]\n>;\n\nexport type StyleHandlerResult = CSSMap | CSSMap[] | void;\n\nexport type RawStyleHandler = (value: StyleValueStateMap) => StyleHandlerResult;\n\nexport type StyleHandler = RawStyleHandler & {\n __lookupStyles: string[];\n};\n\n/**\n * Handler definition forms for configure() and plugins.\n * - Function only: lookup styles inferred from key name\n * - Single property tuple: ['styleName', handler]\n * - Multi-property tuple: [['style1', 'style2'], handler]\n */\nexport type StyleHandlerDefinition =\n | RawStyleHandler\n | [string, RawStyleHandler]\n | [string[], RawStyleHandler];\n\nexport interface ParsedColor {\n color?: string;\n name?: string;\n opacity?: number;\n}\n\nexport type StyleMap = Record<string, StyleValue | StyleValueStateMap>;\n\nconst devMode = process.env.NODE_ENV !== 'production';\n\n// Precompiled regex patterns for parseColor optimization\n// Match var(--name-color...) and extract the name, regardless of fallbacks\nconst COLOR_VAR_PATTERN = /var\\(--([a-z0-9-]+)-color/;\nconst COLOR_VAR_COMPONENTS_PATTERN =\n /var\\(--([a-z0-9-]+)-color-(?:rgb|hsl|oklch)/;\nconst RGB_ALPHA_PATTERN = /\\/\\s*([0-9.]+)\\)/;\nconst RE_HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;\nconst RE_VAR_COLOR = /^var\\(--[a-z0-9-]+-color/;\n\nfunction isSimpleColorFast(val: string): boolean {\n const c0 = val.charCodeAt(0);\n\n switch (c0) {\n case 35: // '#'\n return RE_HEX_COLOR.test(val);\n case 114: // 'r'\n return val.charCodeAt(1) === 103 && val.charCodeAt(2) === 98; // 'rgb'\n case 104: // 'h'\n return val.charCodeAt(1) === 115 && val.charCodeAt(2) === 108; // 'hsl'\n case 108: // 'l'\n return val.charCodeAt(1) === 99 && val.charCodeAt(2) === 104; // 'lch'\n case 111: // 'o'\n return val.startsWith('oklch(') || val.startsWith('okhsl(');\n case 118: // 'v'\n return RE_VAR_COLOR.test(val);\n case 99: // 'c'\n return val === 'currentColor' || val === 'currentcolor';\n case 116: // 't'\n return val === 'transparent';\n default:\n return getNamedColorHex().has(val.toLowerCase());\n }\n}\n\n// Rate limiting for dev warnings to avoid spam\nlet colorWarningCount = 0;\nconst MAX_COLOR_WARNINGS = 10;\n\nexport const CUSTOM_UNITS = {\n r: '6px',\n cr: '10px',\n bw: '1px',\n ow: '3px',\n x: '8px',\n sf: function sf(num: number) {\n return `minmax(0, ${num}fr)`;\n },\n};\n\nexport const DIRECTIONS = ['top', 'right', 'bottom', 'left'];\n\n// Lazy-initialized to break the circular dependency:\n// parser.ts → classify.ts → utils/styles.ts → parser.ts\nlet __tastyParser: StyleParser | null = null;\n\nfunction getOrCreateParser(): StyleParser {\n if (!__tastyParser) {\n __tastyParser = new StyleParser({ units: CUSTOM_UNITS });\n __tastyParser.setFuncs(__tastyFuncs);\n }\n return __tastyParser;\n}\n\n// Registry for user-provided custom functions that the parser can call.\n// It is updated through the `customFunc` helper exported below.\n// okhsl is registered as a built-in function so it works regardless of\n// tree-shaking or module initialization order.\nconst __tastyFuncs: Record<string, (groups: StyleDetails[]) => string> = {\n okhsl: okhslFunc,\n};\n\nexport function customFunc(\n name: string,\n fn: (groups: StyleDetails[]) => string,\n) {\n __tastyFuncs[name] = fn;\n getOrCreateParser().setFuncs(__tastyFuncs);\n}\n\n/**\n * Get the global StyleParser instance.\n * Used by configure() to apply parser configuration.\n */\nexport function getGlobalParser(): StyleParser {\n return getOrCreateParser();\n}\n\n/**\n * Get the current custom functions registry.\n * Used by configure() to merge with new functions.\n */\nexport function getGlobalFuncs(): Record<\n string,\n (groups: StyleDetails[]) => string\n> {\n return __tastyFuncs;\n}\n\n// ============================================================================\n// Global Predefined Tokens\n// ============================================================================\n\n/**\n * Storage for predefined tokens that are replaced during style parsing.\n * Keys are token names (with $ or # prefix), values are pre-processed CSS values.\n */\nlet __globalPredefinedTokens: Record<string, string> | null = null;\n\n/**\n * Set global predefined tokens.\n * Called from configure() after processing token values.\n * Merges with existing tokens (new tokens override existing ones with same key).\n * Keys are normalized to lowercase (parser lowercases input before classification).\n * @internal\n */\nexport function setGlobalPredefinedTokens(\n tokens: Record<string, string>,\n): void {\n // Normalize keys to lowercase for case-insensitive matching\n const normalizedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(tokens)) {\n const lowerKey = key.toLowerCase();\n const lowerValue = value.toLowerCase();\n\n // Warn if trying to use bare #current to define other color tokens\n // #current represents currentcolor which cannot be used as a base for recursive token resolution\n // Note: #current.5 (with opacity) is allowed since it resolves to a concrete color-mix value\n if (lowerKey.startsWith('#') && lowerValue === '#current') {\n console.warn(\n `Tasty: Using #current to define color token \"${key}\" is not supported. ` +\n `The #current token represents currentcolor which cannot be used as a base for other tokens.`,\n );\n continue; // Skip this token\n }\n\n normalizedTokens[lowerKey] = value;\n }\n // Merge with existing tokens (consistent with how states, units, funcs are handled)\n __globalPredefinedTokens = __globalPredefinedTokens\n ? { ...__globalPredefinedTokens, ...normalizedTokens }\n : normalizedTokens;\n // Clear parser cache since token values affect parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n * Get the current global predefined tokens.\n * Returns null if no tokens are configured.\n */\nexport function getGlobalPredefinedTokens(): Record<string, string> | null {\n return __globalPredefinedTokens;\n}\n\n/**\n * Reset global predefined tokens.\n * Used for testing.\n * @internal\n */\nexport function resetGlobalPredefinedTokens(): void {\n __globalPredefinedTokens = null;\n // Clear parser cache since token availability affects parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n *\n * @param {String} value\n * @param {Number} mode\n * @returns {Object<String,String|Array>}\n */\nexport function parseStyle(value: StyleValue): ProcessedStyle {\n let str: string;\n\n if (typeof value === 'string') {\n str = value;\n } else if (typeof value === 'number') {\n str = String(value);\n } else {\n // boolean, null, undefined, objects etc. → empty string\n str = '';\n }\n\n return getOrCreateParser().process(str);\n}\n\n/**\n * Parse color. Find it value, name and opacity.\n * Optimized to avoid heavy parseStyle calls for simple color patterns.\n */\nexport function parseColor(val: string, ignoreError = false): ParsedColor {\n // Early return for non-strings or empty values\n if (typeof val !== 'string') {\n val = String(val ?? '');\n }\n\n val = val.trim();\n if (!val) return {};\n\n // Fast path: Check if it's a simple color pattern that doesn't need full parsing\n const isSimpleColor = isSimpleColorFast(val);\n\n let firstColor: string;\n if (isSimpleColor) {\n // For simple colors, use the value directly without parsing\n firstColor = val;\n } else {\n const processed = parseStyle(val);\n const extractedColor = processed.groups.find((g) => g.colors.length)\n ?.colors[0];\n\n if (!extractedColor) {\n // Rate-limited warning to avoid spam\n if (!ignoreError && devMode && colorWarningCount < MAX_COLOR_WARNINGS) {\n console.warn('Tasty: unable to parse color:', val);\n colorWarningCount++;\n if (colorWarningCount === MAX_COLOR_WARNINGS) {\n console.warn(\n 'Tasty: color parsing warnings will be suppressed from now on',\n );\n }\n }\n return {};\n }\n\n firstColor = extractedColor;\n }\n\n // Extract color name (if present) from variable pattern using precompiled regex\n let nameMatch = firstColor.match(COLOR_VAR_PATTERN);\n if (!nameMatch) {\n nameMatch = firstColor.match(COLOR_VAR_COMPONENTS_PATTERN);\n }\n\n let opacity: number | undefined;\n if (\n firstColor.startsWith('rgb') ||\n firstColor.startsWith('hsl') ||\n firstColor.startsWith('lch') ||\n firstColor.startsWith('oklch') ||\n firstColor.startsWith('okhsl')\n ) {\n const alphaMatch = firstColor.match(RGB_ALPHA_PATTERN);\n if (alphaMatch) {\n const v = parseFloat(alphaMatch[1]);\n if (!isNaN(v)) opacity = v * 100;\n }\n }\n\n return {\n color: firstColor,\n name: nameMatch ? nameMatch[1] : undefined,\n opacity,\n };\n}\n\nexport function filterMods(mods: string[], allowedMods: string[]): string[] {\n return mods.filter((mod) => allowedMods.includes(mod));\n}\n\n// ============================================================================\n// Style Stringification\n// ============================================================================\n\nconst _innerCache = new WeakMap();\nconst _topLevelCache = new WeakMap<object, string>();\n\nexport function stringifyStyles(styles: unknown): string {\n if (styles == null || typeof styles !== 'object') return '';\n\n const cached = _topLevelCache.get(styles as object);\n if (cached !== undefined) return cached;\n\n const obj = styles as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = obj[k];\n if (v === undefined || typeof v === 'function' || typeof v === 'symbol')\n continue;\n\n const c0 = k.charCodeAt(0);\n const needsInnerSort =\n ((c0 >= 65 && c0 <= 90) || c0 === 38) &&\n v &&\n typeof v === 'object' &&\n !Array.isArray(v);\n\n let sv: string;\n if (needsInnerSort) {\n sv = _innerCache.get(v);\n if (sv === undefined) {\n const innerObj = v as Record<string, unknown>;\n const innerKeys = Object.keys(innerObj).sort();\n const innerParts: string[] = [];\n for (const ik of innerKeys) {\n const ivs = JSON.stringify(innerObj[ik]);\n if (ivs !== undefined)\n innerParts.push(JSON.stringify(ik) + ':' + ivs);\n }\n sv = '{' + innerParts.join(',') + '}';\n _innerCache.set(v, sv);\n }\n } else {\n sv = JSON.stringify(v);\n }\n parts.push(JSON.stringify(k) + ':' + sv);\n }\n const result = '{' + parts.join(',') + '}';\n _topLevelCache.set(styles as object, result);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAgB,yBACd,OAC0B;AAC1B,KAAI,UAAU,KACZ,QAAO;AAET,KAAI,UAAU,MACZ,QAAO;AAET,QAAO;;AAkDT,MAAM,oBAAoB;AAC1B,MAAM,+BACJ;AACF,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AACrB,MAAM,eAAe;AAErB,SAAS,kBAAkB,KAAsB;AAG/C,SAFW,IAAI,WAAW,EAAE,EAE5B;EACE,KAAK,GACH,QAAO,aAAa,KAAK,IAAI;EAC/B,KAAK,IACH,QAAO,IAAI,WAAW,EAAE,KAAK,OAAO,IAAI,WAAW,EAAE,KAAK;EAC5D,KAAK,IACH,QAAO,IAAI,WAAW,EAAE,KAAK,OAAO,IAAI,WAAW,EAAE,KAAK;EAC5D,KAAK,IACH,QAAO,IAAI,WAAW,EAAE,KAAK,MAAM,IAAI,WAAW,EAAE,KAAK;EAC3D,KAAK,IACH,QAAO,IAAI,WAAW,SAAS,IAAI,IAAI,WAAW,SAAS;EAC7D,KAAK,IACH,QAAO,aAAa,KAAK,IAAI;EAC/B,KAAK,GACH,QAAO,QAAQ,kBAAkB,QAAQ;EAC3C,KAAK,IACH,QAAO,QAAQ;EACjB,QACE,QAAO,kBAAkB,CAAC,IAAI,IAAI,aAAa,CAAC;;;AAKtD,IAAI,oBAAoB;AACxB,MAAM,qBAAqB;AAE3B,MAAa,eAAe;CAC1B,GAAG;CACH,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,GAAG;CACH,IAAI,SAAS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AO,KAAK,IAAI,CAAC,MAAM;CACpC,MAAM,QAAkB,EAAE;AAC1B,MAAK,MAAM,KAAK,MAAM;EACpB,MAAM,IAAI,IAAI;AACd,MAAI,MAAM,UAAa,OAAO,MAAM,cAAc,OAAO,MAAM,SAC7D;EAEF,MAAM,KAAK,EAAE,WAAW,EAAE;EAC1B,MAAM,kBACF,MAAM,MAAM,MAAM,MAAO,OAAO,OAClC,KACA,OAAO,MAAM,YACb,CAAC,MAAM,QAAQ,EAAE;EAEnB,IAAI;AACJ,MAAI,gBAAgB;AAClB,QAAK,YAAY,IAAI,EAAE;AACvB,OAAI,OAAO,QAAW;IACpB,MAAM,WAAW;IACjB,MAAM,YAAY,OAAO,KAAK,SAAS,CAAC,MAAM;IAC9C,MAAM,aAAuB,EAAE;AAC/B,SAAK,MAAM,MAAM,WAAW;KAC1B,MAAM,MAAM,KAAK,UAAU,SAAS,IAAI;AACxC,SAAI,QAAQ,OACV,YAAW,KAAK,KAAK,UAAU,GAAG,GAAG,MAAM,IAAI;;AAEnD,SAAK,MAAM,WAAW,KAAK,IAAI,GAAG;AAClC,gBAAY,IAAI,GAAG,GAAG;;QAGxB,MAAK,KAAK,UAAU,EAAE;AAExB,QAAM,KAAK,KAAK,UAAU,EAAE,GAAG,MAAM,GAAG;;CAE1C,MAAM,SAAS,MAAM,MAAM,KAAK,IAAI,GAAG;AACvC,gBAAe,IAAI,QAAkB,OAAO;AAC5C,QAAO"}
|
package/docs/dsl.md
CHANGED
|
@@ -119,7 +119,6 @@ color: '(#primary, #secondary)', // Fallback syntax
|
|
|
119
119
|
| `cr` | Card border radius | `1cr` | `var(--card-radius)` |
|
|
120
120
|
| `bw` | Border width | `2bw` | `calc(var(--border-width) * 2)` |
|
|
121
121
|
| `ow` | Outline width | `1ow` | `var(--outline-width)` |
|
|
122
|
-
| `lh` | Line height | `1lh` | `var(--line-height)` |
|
|
123
122
|
| `sf` | Stable fraction | `1sf` | `minmax(0, 1fr)` |
|
|
124
123
|
|
|
125
124
|
You can register additional custom units via [`configure()`](configuration.md#options).
|