@tenphi/tasty 0.5.4 → 0.7.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.
@@ -1,4 +1,4 @@
1
- import { getRgbValuesFromRgbaString, strToRgb } from "../utils/styles.js";
1
+ import { RE_NUMBER, RE_RAW_UNIT } from "../parser/const.js";
2
2
 
3
3
  //#region src/properties/index.ts
4
4
  const PROPERTIES_KEY = "@properties";
@@ -88,7 +88,11 @@ function parsePropertyToken(token) {
88
88
  }
89
89
  /**
90
90
  * Normalize a property definition to a consistent string representation.
91
- * Used for comparing definitions to detect changes/conflicts.
91
+ * Used for comparing definitions to detect type conflicts.
92
+ *
93
+ * Only `syntax` and `inherits` are compared — `initialValue` is intentionally
94
+ * excluded because different components may set different defaults for the
95
+ * same typed property (e.g. auto-inferred `0px` vs explicit `6px`).
92
96
  *
93
97
  * Keys are sorted alphabetically to ensure consistent comparison:
94
98
  * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }
@@ -96,7 +100,6 @@ function parsePropertyToken(token) {
96
100
  function normalizePropertyDefinition(def) {
97
101
  const normalized = {};
98
102
  if (def.inherits !== void 0) normalized.inherits = def.inherits;
99
- if (def.initialValue !== void 0) normalized.initialValue = String(def.initialValue);
100
103
  if (def.syntax !== void 0) normalized.syntax = def.syntax;
101
104
  return JSON.stringify(normalized);
102
105
  }
@@ -134,25 +137,82 @@ function getEffectiveDefinition(token, userDefinition) {
134
137
  isValid: true
135
138
  };
136
139
  }
140
+ const UNIT_TO_SYNTAX = {};
141
+ const LENGTH_UNITS = [
142
+ "px",
143
+ "em",
144
+ "rem",
145
+ "vw",
146
+ "vh",
147
+ "vmin",
148
+ "vmax",
149
+ "ch",
150
+ "ex",
151
+ "cap",
152
+ "ic",
153
+ "lh",
154
+ "rlh",
155
+ "svw",
156
+ "svh",
157
+ "lvw",
158
+ "lvh",
159
+ "dvw",
160
+ "dvh",
161
+ "cqw",
162
+ "cqh",
163
+ "cqi",
164
+ "cqb",
165
+ "cqmin",
166
+ "cqmax"
167
+ ];
168
+ const ANGLE_UNITS = [
169
+ "deg",
170
+ "rad",
171
+ "grad",
172
+ "turn"
173
+ ];
174
+ const TIME_UNITS = ["ms", "s"];
175
+ for (const u of LENGTH_UNITS) UNIT_TO_SYNTAX[u] = {
176
+ syntax: "<length>",
177
+ initialValue: "0px"
178
+ };
179
+ UNIT_TO_SYNTAX["%"] = {
180
+ syntax: "<percentage>",
181
+ initialValue: "0%"
182
+ };
183
+ for (const u of ANGLE_UNITS) UNIT_TO_SYNTAX[u] = {
184
+ syntax: "<angle>",
185
+ initialValue: "0deg"
186
+ };
187
+ for (const u of TIME_UNITS) UNIT_TO_SYNTAX[u] = {
188
+ syntax: "<time>",
189
+ initialValue: "0s"
190
+ };
137
191
  /**
138
- * Extract RGB triplet string from a color initial value.
139
- * Used when auto-creating the companion `-rgb` property for color @property definitions.
192
+ * Infer CSS @property syntax from a concrete value.
193
+ * Only detects numeric types: \<number\>, \<length\>, \<percentage\>, \<angle\>, \<time\>.
194
+ * Color properties are handled separately via the #name token convention
195
+ * (--name-color gets \<color\> syntax automatically in getEffectiveDefinition).
140
196
  *
141
- * @param initialValue - The color property's initial value (e.g., 'rgb(255 255 255)', 'transparent', '#fff')
142
- * @returns Space-separated RGB triplet (e.g., '255 255 255'), defaults to '0 0 0'
197
+ * @param value - The CSS value to infer from (e.g. '10px', '1', '45deg')
198
+ * @returns Inferred syntax and initial value, or null if not inferable
143
199
  */
144
- function colorInitialValueToRgb(initialValue) {
145
- if (initialValue == null) return "0 0 0";
146
- const str = String(initialValue).trim();
147
- if (!str || str === "transparent") return "0 0 0";
148
- const rgba = strToRgb(str);
149
- if (rgba) {
150
- const values = getRgbValuesFromRgbaString(rgba);
151
- if (values.length >= 3) return values.slice(0, 3).join(" ");
200
+ function inferSyntaxFromValue(value) {
201
+ if (!value || typeof value !== "string") return null;
202
+ const trimmed = value.trim();
203
+ if (!trimmed) return null;
204
+ if (RE_NUMBER.test(trimmed)) return {
205
+ syntax: "<number>",
206
+ initialValue: "0"
207
+ };
208
+ const unitMatch = trimmed.match(RE_RAW_UNIT);
209
+ if (unitMatch) {
210
+ const mapping = UNIT_TO_SYNTAX[unitMatch[2]];
211
+ if (mapping) return mapping;
152
212
  }
153
- return "0 0 0";
213
+ return null;
154
214
  }
155
215
 
156
216
  //#endregion
157
- export { colorInitialValueToRgb, extractLocalProperties, getEffectiveDefinition, hasLocalProperties, normalizePropertyDefinition };
217
+ export { extractLocalProperties, getEffectiveDefinition, hasLocalProperties, inferSyntaxFromValue, normalizePropertyDefinition };
158
218
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/properties/index.ts"],"sourcesContent":["/**\n * Properties Utilities\n *\n * Utilities for extracting and processing CSS @property definitions in styles.\n * Unlike keyframes, properties are permanent once registered and don't need cleanup.\n *\n * Property names use tasty token syntax:\n * - `$name` for regular properties → `--name`\n * - `#name` for color properties → `--name-color` (auto-sets syntax: '<color>')\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport type { Styles } from '../styles/types';\nimport { getRgbValuesFromRgbaString, strToRgb } from '../utils/styles';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst PROPERTIES_KEY = '@properties';\n\n/**\n * Valid CSS custom property name pattern (after the -- prefix).\n * Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.\n */\nconst VALID_PROPERTY_NAME_PATTERN = /^[a-z_][a-z0-9-_]*$/i;\n\n// ============================================================================\n// Validation Functions\n// ============================================================================\n\n/**\n * Validate a CSS custom property name (the part after --).\n * Returns true if the name is valid for use as a CSS custom property.\n */\nexport function isValidPropertyName(name: string): boolean {\n return VALID_PROPERTY_NAME_PATTERN.test(name);\n}\n\n/**\n * Result of parsing a property token.\n */\nexport interface ParsedPropertyToken {\n /** The CSS custom property name (e.g., '--my-prop') */\n cssName: string;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @properties definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalProperties(styles: Styles): boolean {\n return PROPERTIES_KEY in styles;\n}\n\n/**\n * Extract local @properties from styles object.\n * Returns null if no local properties (fast path).\n */\nexport function extractLocalProperties(\n styles: Styles,\n): Record<string, PropertyDefinition> | null {\n const properties = styles[PROPERTIES_KEY];\n if (!properties || typeof properties !== 'object') {\n return null;\n }\n return properties as Record<string, PropertyDefinition>;\n}\n\n// ============================================================================\n// Token Parsing Functions\n// ============================================================================\n\n/**\n * Parse a property token name and return the CSS property name and whether it's a color.\n * Supports tasty token syntax and validates the property name.\n *\n * Token formats:\n * - `$name` → { cssName: '--name', isColor: false }\n * - `#name` → { cssName: '--name-color', isColor: true }\n * - `--name` → { cssName: '--name', isColor: false } (legacy, auto-detect color by suffix)\n * - `name` → { cssName: '--name', isColor: false } (legacy)\n *\n * @param token - The property token to parse\n * @returns Parsed result with cssName, isColor, isValid, and optional error\n */\nexport function parsePropertyToken(token: string): ParsedPropertyToken {\n if (!token || typeof token !== 'string') {\n return {\n cssName: '',\n isColor: false,\n isValid: false,\n error: 'Property token must be a non-empty string',\n };\n }\n\n let name: string;\n let isColor: boolean;\n\n if (token.startsWith('$')) {\n // Regular property token: $name → --name\n name = token.slice(1);\n isColor = false;\n } else if (token.startsWith('#')) {\n // Color property token: #name → --name-color\n name = token.slice(1);\n isColor = true;\n } else if (token.startsWith('--')) {\n // Legacy format with -- prefix\n name = token.slice(2);\n isColor = token.endsWith('-color');\n } else {\n // Legacy format without prefix\n name = token;\n isColor = token.endsWith('-color');\n }\n\n // Validate the name\n if (!name) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: 'Property name cannot be empty',\n };\n }\n\n if (!isValidPropertyName(name)) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: `Invalid property name \"${name}\". Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.`,\n };\n }\n\n // Build the CSS custom property name\n // For #name tokens, we add -color suffix\n // For legacy formats (--name-color or name-color), the name already includes -color\n let cssName: string;\n if (token.startsWith('#')) {\n // Color token: #name → --name-color\n cssName = `--${name}-color`;\n } else {\n // All other formats: just add -- prefix\n cssName = `--${name}`;\n }\n\n return {\n cssName,\n isColor,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Normalization Functions\n// ============================================================================\n\n/**\n * Normalize a property name to the CSS custom property format.\n *\n * @deprecated Use parsePropertyToken instead for proper token handling\n */\nexport function normalizePropertyName(name: string): string {\n const result = parsePropertyToken(name);\n return result.isValid ? result.cssName : `--${name}`;\n}\n\n/**\n * Normalize a property definition to a consistent string representation.\n * Used for comparing definitions to detect changes/conflicts.\n *\n * Keys are sorted alphabetically to ensure consistent comparison:\n * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }\n */\nexport function normalizePropertyDefinition(def: PropertyDefinition): string {\n const normalized: Record<string, unknown> = {};\n\n // Add properties in alphabetical order\n if (def.inherits !== undefined) {\n normalized.inherits = def.inherits;\n }\n if (def.initialValue !== undefined) {\n normalized.initialValue = String(def.initialValue);\n }\n if (def.syntax !== undefined) {\n normalized.syntax = def.syntax;\n }\n\n return JSON.stringify(normalized);\n}\n\n/**\n * Result of getEffectiveDefinition.\n */\nexport interface EffectiveDefinitionResult {\n /** The CSS custom property name */\n cssName: string;\n /** The effective property definition */\n definition: PropertyDefinition;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Get the effective property definition for a token.\n * For color tokens (#name), auto-sets syntax to '<color>' and defaults initialValue to 'transparent'.\n *\n * @param token - Property token ($name, #name, --name, or plain name)\n * @param userDefinition - User-provided definition options\n * @returns Effective definition with cssName, definition, isValid, and optional error\n */\nexport function getEffectiveDefinition(\n token: string,\n userDefinition: PropertyDefinition,\n): EffectiveDefinitionResult {\n const parsed = parsePropertyToken(token);\n\n if (!parsed.isValid) {\n return {\n cssName: '',\n definition: userDefinition,\n isColor: false,\n isValid: false,\n error: parsed.error,\n };\n }\n\n if (parsed.isColor) {\n // Color properties have fixed syntax and default initialValue\n return {\n cssName: parsed.cssName,\n definition: {\n syntax: '<color>', // Always '<color>' for color tokens, cannot be overridden\n inherits: userDefinition.inherits, // Allow inherits to be customized\n initialValue: userDefinition.initialValue ?? 'transparent', // Default to transparent\n },\n isColor: true,\n isValid: true,\n };\n }\n\n // Regular properties use the definition as-is\n return {\n cssName: parsed.cssName,\n definition: userDefinition,\n isColor: false,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Color RGB Companion Helpers\n// ============================================================================\n\n/**\n * Extract RGB triplet string from a color initial value.\n * Used when auto-creating the companion `-rgb` property for color @property definitions.\n *\n * @param initialValue - The color property's initial value (e.g., 'rgb(255 255 255)', 'transparent', '#fff')\n * @returns Space-separated RGB triplet (e.g., '255 255 255'), defaults to '0 0 0'\n */\nexport function colorInitialValueToRgb(initialValue?: string | number): string {\n if (initialValue == null) return '0 0 0';\n\n const str = String(initialValue).trim();\n if (!str || str === 'transparent') return '0 0 0';\n\n const rgba = strToRgb(str);\n if (rgba) {\n const values = getRgbValuesFromRgbaString(rgba);\n if (values.length >= 3) return values.slice(0, 3).join(' ');\n }\n\n return '0 0 0';\n}\n"],"mappings":";;;AAmBA,MAAM,iBAAiB;;;;;AAMvB,MAAM,8BAA8B;;;;;AAUpC,SAAgB,oBAAoB,MAAuB;AACzD,QAAO,4BAA4B,KAAK,KAAK;;;;;;AAyB/C,SAAgB,mBAAmB,QAAyB;AAC1D,QAAO,kBAAkB;;;;;;AAO3B,SAAgB,uBACd,QAC2C;CAC3C,MAAM,aAAa,OAAO;AAC1B,KAAI,CAAC,cAAc,OAAO,eAAe,SACvC,QAAO;AAET,QAAO;;;;;;;;;;;;;;;AAoBT,SAAgB,mBAAmB,OAAoC;AACrE,KAAI,CAAC,SAAS,OAAO,UA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gB;GAC9C;EACD,SAAS;EACT,SAAS;EACV;AAIH,QAAO;EACL,SAAS,OAAO;EAChB,YAAY;EACZ,SAAS;EACT,SAAS;EACV;;;;;;;;;AAcH,SAAgB,uBAAuB,cAAwC;AAC7E,KAAI,gBAAgB,KAAM,QAAO;CAEjC,MAAM,MAAM,OAAO,aAAa,CAAC,MAAM;AACvC,KAAI,CAAC,OAAO,QAAQ,cAAe,QAAO;CAE1C,MAAM,OAAO,SAAS,IAAI;AAC1B,KAAI,MAAM;EACR,MAAM,SAAS,2BAA2B,KAAK;AAC/C,MAAI,OAAO,UAAU,EAAG,QAAO,OAAO,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI;;AAG7D,QAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/properties/index.ts"],"sourcesContent":["/**\n * Properties Utilities\n *\n * Utilities for extracting and processing CSS @property definitions in styles.\n * Unlike keyframes, properties are permanent once registered and don't need cleanup.\n *\n * Property names use tasty token syntax:\n * - `$name` for regular properties → `--name`\n * - `#name` for color properties → `--name-color` (auto-sets syntax: '<color>')\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { RE_NUMBER, RE_RAW_UNIT } from '../parser/const';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst PROPERTIES_KEY = '@properties';\n\n/**\n * Valid CSS custom property name pattern (after the -- prefix).\n * Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.\n */\nconst VALID_PROPERTY_NAME_PATTERN = /^[a-z_][a-z0-9-_]*$/i;\n\n// ============================================================================\n// Validation Functions\n// ============================================================================\n\n/**\n * Validate a CSS custom property name (the part after --).\n * Returns true if the name is valid for use as a CSS custom property.\n */\nexport function isValidPropertyName(name: string): boolean {\n return VALID_PROPERTY_NAME_PATTERN.test(name);\n}\n\n/**\n * Result of parsing a property token.\n */\nexport interface ParsedPropertyToken {\n /** The CSS custom property name (e.g., '--my-prop') */\n cssName: string;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @properties definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalProperties(styles: Styles): boolean {\n return PROPERTIES_KEY in styles;\n}\n\n/**\n * Extract local @properties from styles object.\n * Returns null if no local properties (fast path).\n */\nexport function extractLocalProperties(\n styles: Styles,\n): Record<string, PropertyDefinition> | null {\n const properties = styles[PROPERTIES_KEY];\n if (!properties || typeof properties !== 'object') {\n return null;\n }\n return properties as Record<string, PropertyDefinition>;\n}\n\n// ============================================================================\n// Token Parsing Functions\n// ============================================================================\n\n/**\n * Parse a property token name and return the CSS property name and whether it's a color.\n * Supports tasty token syntax and validates the property name.\n *\n * Token formats:\n * - `$name` → { cssName: '--name', isColor: false }\n * - `#name` → { cssName: '--name-color', isColor: true }\n * - `--name` → { cssName: '--name', isColor: false } (legacy, auto-detect color by suffix)\n * - `name` → { cssName: '--name', isColor: false } (legacy)\n *\n * @param token - The property token to parse\n * @returns Parsed result with cssName, isColor, isValid, and optional error\n */\nexport function parsePropertyToken(token: string): ParsedPropertyToken {\n if (!token || typeof token !== 'string') {\n return {\n cssName: '',\n isColor: false,\n isValid: false,\n error: 'Property token must be a non-empty string',\n };\n }\n\n let name: string;\n let isColor: boolean;\n\n if (token.startsWith('$')) {\n // Regular property token: $name → --name\n name = token.slice(1);\n isColor = false;\n } else if (token.startsWith('#')) {\n // Color property token: #name → --name-color\n name = token.slice(1);\n isColor = true;\n } else if (token.startsWith('--')) {\n // Legacy format with -- prefix\n name = token.slice(2);\n isColor = token.endsWith('-color');\n } else {\n // Legacy format without prefix\n name = token;\n isColor = token.endsWith('-color');\n }\n\n // Validate the name\n if (!name) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: 'Property name cannot be empty',\n };\n }\n\n if (!isValidPropertyName(name)) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: `Invalid property name \"${name}\". Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.`,\n };\n }\n\n // Build the CSS custom property name\n // For #name tokens, we add -color suffix\n // For legacy formats (--name-color or name-color), the name already includes -color\n let cssName: string;\n if (token.startsWith('#')) {\n // Color token: #name → --name-color\n cssName = `--${name}-color`;\n } else {\n // All other formats: just add -- prefix\n cssName = `--${name}`;\n }\n\n return {\n cssName,\n isColor,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Normalization Functions\n// ============================================================================\n\n/**\n * Normalize a property name to the CSS custom property format.\n *\n * @deprecated Use parsePropertyToken instead for proper token handling\n */\nexport function normalizePropertyName(name: string): string {\n const result = parsePropertyToken(name);\n return result.isValid ? result.cssName : `--${name}`;\n}\n\n/**\n * Normalize a property definition to a consistent string representation.\n * Used for comparing definitions to detect type conflicts.\n *\n * Only `syntax` and `inherits` are compared — `initialValue` is intentionally\n * excluded because different components may set different defaults for the\n * same typed property (e.g. auto-inferred `0px` vs explicit `6px`).\n *\n * Keys are sorted alphabetically to ensure consistent comparison:\n * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }\n */\nexport function normalizePropertyDefinition(def: PropertyDefinition): string {\n const normalized: Record<string, unknown> = {};\n\n if (def.inherits !== undefined) {\n normalized.inherits = def.inherits;\n }\n if (def.syntax !== undefined) {\n normalized.syntax = def.syntax;\n }\n\n return JSON.stringify(normalized);\n}\n\n/**\n * Result of getEffectiveDefinition.\n */\nexport interface EffectiveDefinitionResult {\n /** The CSS custom property name */\n cssName: string;\n /** The effective property definition */\n definition: PropertyDefinition;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Get the effective property definition for a token.\n * For color tokens (#name), auto-sets syntax to '<color>' and defaults initialValue to 'transparent'.\n *\n * @param token - Property token ($name, #name, --name, or plain name)\n * @param userDefinition - User-provided definition options\n * @returns Effective definition with cssName, definition, isValid, and optional error\n */\nexport function getEffectiveDefinition(\n token: string,\n userDefinition: PropertyDefinition,\n): EffectiveDefinitionResult {\n const parsed = parsePropertyToken(token);\n\n if (!parsed.isValid) {\n return {\n cssName: '',\n definition: userDefinition,\n isColor: false,\n isValid: false,\n error: parsed.error,\n };\n }\n\n if (parsed.isColor) {\n // Color properties have fixed syntax and default initialValue\n return {\n cssName: parsed.cssName,\n definition: {\n syntax: '<color>', // Always '<color>' for color tokens, cannot be overridden\n inherits: userDefinition.inherits, // Allow inherits to be customized\n initialValue: userDefinition.initialValue ?? 'transparent', // Default to transparent\n },\n isColor: true,\n isValid: true,\n };\n }\n\n // Regular properties use the definition as-is\n return {\n cssName: parsed.cssName,\n definition: userDefinition,\n isColor: false,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Value Type Inference\n// ============================================================================\n\n/**\n * Result of inferring a CSS @property syntax from a value.\n */\nexport interface InferredSyntax {\n syntax: string;\n initialValue: string;\n}\n\nconst UNIT_TO_SYNTAX: Record<string, InferredSyntax> = {};\n\nconst LENGTH_UNITS = [\n 'px',\n 'em',\n 'rem',\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n 'ch',\n 'ex',\n 'cap',\n 'ic',\n 'lh',\n 'rlh',\n 'svw',\n 'svh',\n 'lvw',\n 'lvh',\n 'dvw',\n 'dvh',\n 'cqw',\n 'cqh',\n 'cqi',\n 'cqb',\n 'cqmin',\n 'cqmax',\n];\n\nconst ANGLE_UNITS = ['deg', 'rad', 'grad', 'turn'];\nconst TIME_UNITS = ['ms', 's'];\n\nfor (const u of LENGTH_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<length>', initialValue: '0px' };\n}\nUNIT_TO_SYNTAX['%'] = { syntax: '<percentage>', initialValue: '0%' };\nfor (const u of ANGLE_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<angle>', initialValue: '0deg' };\n}\nfor (const u of TIME_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<time>', initialValue: '0s' };\n}\n\n/**\n * Infer CSS @property syntax from a concrete value.\n * Only detects numeric types: \\<number\\>, \\<length\\>, \\<percentage\\>, \\<angle\\>, \\<time\\>.\n * Color properties are handled separately via the #name token convention\n * (--name-color gets \\<color\\> syntax automatically in getEffectiveDefinition).\n *\n * @param value - The CSS value to infer from (e.g. '10px', '1', '45deg')\n * @returns Inferred syntax and initial value, or null if not inferable\n */\nexport function inferSyntaxFromValue(value: string): InferredSyntax | null {\n if (!value || typeof value !== 'string') return null;\n\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n if (RE_NUMBER.test(trimmed)) {\n return { syntax: '<number>', initialValue: '0' };\n }\n\n const unitMatch = trimmed.match(RE_RAW_UNIT);\n if (unitMatch) {\n const unit = unitMatch[2];\n const mapping = UNIT_TO_SYNTAX[unit];\n if (mapping) return mapping;\n }\n\n return null;\n}\n"],"mappings":";;;AAmBA,MAAM,iBAAiB;;;;;AAMvB,MAAM,8BAA8B;;;;;AAUpC,SAAgB,oBAAoB,MAAuB;AACzD,QAAO,4BAA4B,KAAK,KAAK;;;;;;AAyB/C,SAAgB,mBAAmB,QAAyB;AAC1D,QAAO,kBAAkB;;;;;;AAO3B,SAAgB,uBACd,QAC2C;CAC3C,MAAM,aAAa,OAAO;AAC1B,KAAI,CAAC,cAAc,OAAO,eAAe,SACvC,QAAO;AAET,QAAO;;;;;;;;;;;;;;;AAoBT,SAAgB,mBAAmB,OAAoC;AACrE,KAAI,CAAC,SAAS,OAAO,UAAU,SAC7B,QAAO;EACL,SAAS;EACT,SAAS;EACT,SAAS;EACT,OAAO;EACR;CAGH,IAAI;CACJ,IAAI;AAEJ,KAAI,MAAM,WAAW,IAAI,EAAE;AAEzB,SAAO,MAAM,MAAM,EAAE;AACrB,YAAU;YACD,MAAM,WAAW,IAAI,EAAE;AAEhC,SAAO,MAAM,MAAM,EAAE;AACrB,YAAU;YACD,MAAM,WAAW,KAAK,EAAE;AAEjC,SAAO,MAAM,MAAM,EAAE;AACrB,YAAU,MAAM,SAAS,SAAS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ACd,gBAAe,KAAK;CAAE,QAAQ;CAAY,cAAc;CAAO;AAEjE,eAAe,OAAO;CAAE,QAAQ;CAAgB,cAAc;CAAM;AACpE,KAAK,MAAM,KAAK,YACd,gBAAe,KAAK;CAAE,QAAQ;CAAW,cAAc;CAAQ;AAEjE,KAAK,MAAM,KAAK,WACd,gBAAe,KAAK;CAAE,QAAQ;CAAU,cAAc;CAAM;;;;;;;;;;AAY9D,SAAgB,qBAAqB,OAAsC;AACzE,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;CAEhD,MAAM,UAAU,MAAM,MAAM;AAC5B,KAAI,CAAC,QAAS,QAAO;AAErB,KAAI,UAAU,KAAK,QAAQ,CACzB,QAAO;EAAE,QAAQ;EAAY,cAAc;EAAK;CAGlD,MAAM,YAAY,QAAQ,MAAM,YAAY;AAC5C,KAAI,WAAW;EAEb,MAAM,UAAU,eADH,UAAU;AAEvB,MAAI,QAAS,QAAO;;AAGtB,QAAO"}
@@ -0,0 +1,24 @@
1
+ //#region src/properties/property-type-resolver.d.ts
2
+ /**
3
+ * PropertyTypeResolver
4
+ *
5
+ * Automatically infers CSS @property types from custom property values.
6
+ * Supports deferred resolution for var() reference chains of arbitrary depth.
7
+ */
8
+ declare class PropertyTypeResolver {
9
+ /** propName → the prop it depends on */
10
+ private pendingDeps;
11
+ /** propName → list of props waiting on it */
12
+ private reverseDeps;
13
+ /**
14
+ * Scan CSS declarations and auto-register @property for custom properties
15
+ * whose types can be inferred from their values.
16
+ */
17
+ scanDeclarations(declarations: string, isPropertyDefined: (name: string) => boolean, registerProperty: (name: string, syntax: string, initialValue: string) => void): void;
18
+ private addDependency;
19
+ private resolve;
20
+ private isComplexValue;
21
+ }
22
+ //#endregion
23
+ export { PropertyTypeResolver };
24
+ //# sourceMappingURL=property-type-resolver.d.ts.map
@@ -0,0 +1,83 @@
1
+ import { inferSyntaxFromValue } from "./index.js";
2
+
3
+ //#region src/properties/property-type-resolver.ts
4
+ /**
5
+ * PropertyTypeResolver
6
+ *
7
+ * Automatically infers CSS @property types from custom property values.
8
+ * Supports deferred resolution for var() reference chains of arbitrary depth.
9
+ */
10
+ const CUSTOM_PROP_DECL = /^\s*(--[a-z0-9_-]+)\s*:\s*(.+?)\s*$/i;
11
+ const SINGLE_VAR_REF = /^var\((--[a-z0-9_-]+)\)$/i;
12
+ var PropertyTypeResolver = class {
13
+ /** propName → the prop it depends on */
14
+ pendingDeps = /* @__PURE__ */ new Map();
15
+ /** propName → list of props waiting on it */
16
+ reverseDeps = /* @__PURE__ */ new Map();
17
+ /**
18
+ * Scan CSS declarations and auto-register @property for custom properties
19
+ * whose types can be inferred from their values.
20
+ */
21
+ scanDeclarations(declarations, isPropertyDefined, registerProperty) {
22
+ if (!declarations.includes("--")) return;
23
+ const parts = declarations.split(/;+/);
24
+ for (const part of parts) {
25
+ if (!part.trim()) continue;
26
+ const match = CUSTOM_PROP_DECL.exec(part);
27
+ if (!match) continue;
28
+ const propName = match[1];
29
+ const value = match[2].trim();
30
+ if (isPropertyDefined(propName)) continue;
31
+ if (propName.endsWith("-color")) {
32
+ registerProperty(propName, "<color>", "transparent");
33
+ continue;
34
+ }
35
+ const varMatch = SINGLE_VAR_REF.exec(value);
36
+ if (varMatch) {
37
+ const depName = varMatch[1];
38
+ this.addDependency(propName, depName);
39
+ continue;
40
+ }
41
+ if (this.isComplexValue(value)) continue;
42
+ const inferred = inferSyntaxFromValue(value);
43
+ if (!inferred) continue;
44
+ this.resolve(propName, inferred.syntax, inferred.initialValue, isPropertyDefined, registerProperty);
45
+ }
46
+ }
47
+ addDependency(propName, depName) {
48
+ if (propName === depName) return;
49
+ this.pendingDeps.set(propName, depName);
50
+ let dependents = this.reverseDeps.get(depName);
51
+ if (!dependents) {
52
+ dependents = [];
53
+ this.reverseDeps.set(depName, dependents);
54
+ }
55
+ if (!dependents.includes(propName)) dependents.push(propName);
56
+ }
57
+ resolve(propName, syntax, initialValue, isPropertyDefined, registerProperty, resolving) {
58
+ if (!resolving) resolving = /* @__PURE__ */ new Set();
59
+ if (resolving.has(propName)) return;
60
+ resolving.add(propName);
61
+ if (!isPropertyDefined(propName)) registerProperty(propName, syntax, initialValue);
62
+ const dependents = this.reverseDeps.get(propName);
63
+ if (dependents) {
64
+ this.reverseDeps.delete(propName);
65
+ for (const dependent of dependents) {
66
+ this.pendingDeps.delete(dependent);
67
+ if (isPropertyDefined(dependent)) continue;
68
+ this.resolve(dependent, syntax, initialValue, isPropertyDefined, registerProperty, resolving);
69
+ }
70
+ }
71
+ }
72
+ isComplexValue(value) {
73
+ if (value.includes("calc(")) return true;
74
+ const firstVar = value.indexOf("var(");
75
+ if (firstVar === -1) return false;
76
+ if (value.indexOf("var(", firstVar + 4) !== -1) return true;
77
+ return !SINGLE_VAR_REF.test(value);
78
+ }
79
+ };
80
+
81
+ //#endregion
82
+ export { PropertyTypeResolver };
83
+ //# sourceMappingURL=property-type-resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"property-type-resolver.js","names":[],"sources":["../../src/properties/property-type-resolver.ts"],"sourcesContent":["/**\n * PropertyTypeResolver\n *\n * Automatically infers CSS @property types from custom property values.\n * Supports deferred resolution for var() reference chains of arbitrary depth.\n */\n\nimport { inferSyntaxFromValue } from './index';\n\nconst CUSTOM_PROP_DECL = /^\\s*(--[a-z0-9_-]+)\\s*:\\s*(.+?)\\s*$/i;\nconst SINGLE_VAR_REF = /^var\\((--[a-z0-9_-]+)\\)$/i;\n\nexport class PropertyTypeResolver {\n /** propName → the prop it depends on */\n private pendingDeps = new Map<string, string>();\n /** propName → list of props waiting on it */\n private reverseDeps = new Map<string, string[]>();\n\n /**\n * Scan CSS declarations and auto-register @property for custom properties\n * whose types can be inferred from their values.\n */\n scanDeclarations(\n declarations: string,\n isPropertyDefined: (name: string) => boolean,\n registerProperty: (\n name: string,\n syntax: string,\n initialValue: string,\n ) => void,\n ): void {\n if (!declarations.includes('--')) return;\n\n const parts = declarations.split(/;+/);\n\n for (const part of parts) {\n if (!part.trim()) continue;\n\n const match = CUSTOM_PROP_DECL.exec(part);\n if (!match) continue;\n\n const propName = match[1];\n const value = match[2].trim();\n\n if (isPropertyDefined(propName)) continue;\n\n // Name-based: --*-color properties are always <color> (from #name tokens)\n if (propName.endsWith('-color')) {\n registerProperty(propName, '<color>', 'transparent');\n continue;\n }\n\n // Single var() reference → record dependency for deferred resolution\n const varMatch = SINGLE_VAR_REF.exec(value);\n if (varMatch) {\n const depName = varMatch[1];\n this.addDependency(propName, depName);\n continue;\n }\n\n // Skip complex expressions (calc, multiple var, etc.)\n if (this.isComplexValue(value)) continue;\n\n const inferred = inferSyntaxFromValue(value);\n if (!inferred) continue;\n\n this.resolve(\n propName,\n inferred.syntax,\n inferred.initialValue,\n isPropertyDefined,\n registerProperty,\n );\n }\n }\n\n private addDependency(propName: string, depName: string): void {\n if (propName === depName) return;\n\n this.pendingDeps.set(propName, depName);\n\n let dependents = this.reverseDeps.get(depName);\n if (!dependents) {\n dependents = [];\n this.reverseDeps.set(depName, dependents);\n }\n if (!dependents.includes(propName)) {\n dependents.push(propName);\n }\n }\n\n private resolve(\n propName: string,\n syntax: string,\n initialValue: string,\n isPropertyDefined: (name: string) => boolean,\n registerProperty: (\n name: string,\n syntax: string,\n initialValue: string,\n ) => void,\n resolving?: Set<string>,\n ): void {\n if (!resolving) resolving = new Set();\n if (resolving.has(propName)) return;\n resolving.add(propName);\n\n if (!isPropertyDefined(propName)) {\n registerProperty(propName, syntax, initialValue);\n }\n\n const dependents = this.reverseDeps.get(propName);\n if (dependents) {\n this.reverseDeps.delete(propName);\n\n for (const dependent of dependents) {\n this.pendingDeps.delete(dependent);\n\n if (isPropertyDefined(dependent)) continue;\n\n this.resolve(\n dependent,\n syntax,\n initialValue,\n isPropertyDefined,\n registerProperty,\n resolving,\n );\n }\n }\n }\n\n private isComplexValue(value: string): boolean {\n if (value.includes('calc(')) return true;\n const firstVar = value.indexOf('var(');\n if (firstVar === -1) return false;\n if (value.indexOf('var(', firstVar + 4) !== -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MAAI,CAAC,UAAW,6BAAY,IAAI,KAAK;AACrC,MAAI,UAAU,IAAI,SAAS,CAAE;AAC7B,YAAU,IAAI,SAAS;AAEvB,MAAI,CAAC,kBAAkB,SAAS,CAC9B,kBAAiB,UAAU,QAAQ,aAAa;EAGlD,MAAM,aAAa,KAAK,YAAY,IAAI,SAAS;AACjD,MAAI,YAAY;AACd,QAAK,YAAY,OAAO,SAAS;AAEjC,QAAK,MAAM,aAAa,YAAY;AAClC,SAAK,YAAY,OAAO,UAAU;AAElC,QAAI,kBAAkB,UAAU,CAAE;AAElC,SAAK,QACH,WACA,QACA,cACA,mBACA,kBACA,UACD;;;;CAKP,AAAQ,eAAe,OAAwB;AAC7C,MAAI,MAAM,SAAS,QAAQ,CAAE,QAAO;EACpC,MAAM,WAAW,MAAM,QAAQ,OAAO;AACtC,MAAI,aAAa,GAAI,QAAO;AAC5B,MAAI,MAAM,QAAQ,QAAQ,WAAW,EAAE,KAAK,GAAI,QAAO;AACvD,SAAO,CAAC,eAAe,KAAK,MAAM"}
@@ -10,13 +10,14 @@ function fillStyle({ fill, backgroundColor, image, backgroundImage, backgroundPo
10
10
  const firstColor = parsed.groups[0]?.colors[0];
11
11
  const secondColor = parsed.groups[0]?.colors[1];
12
12
  result["background-color"] = firstColor || colorValue;
13
- if (secondColor && !backgroundImage && !image) {
14
- result["--tasty-second-fill-color"] = secondColor;
15
- result["background-image"] = "linear-gradient(var(--tasty-second-fill-color), var(--tasty-second-fill-color))";
16
- }
13
+ if (secondColor) result["--tasty-second-fill-color"] = secondColor;
17
14
  }
15
+ const gradientLayer = result["--tasty-second-fill-color"] ? "linear-gradient(var(--tasty-second-fill-color), var(--tasty-second-fill-color))" : null;
18
16
  const imageValue = backgroundImage ?? image;
19
- if (imageValue) result["background-image"] = parseStyle(imageValue).output || imageValue;
17
+ if (imageValue) {
18
+ const imgCss = parseStyle(imageValue).output || imageValue;
19
+ result["background-image"] = gradientLayer ? `${imgCss}, ${gradientLayer}` : imgCss;
20
+ } else if (gradientLayer) result["background-image"] = gradientLayer;
20
21
  if (backgroundPosition) result["background-position"] = parseStyle(backgroundPosition).output || backgroundPosition;
21
22
  if (backgroundSize) result["background-size"] = parseStyle(backgroundSize).output || backgroundSize;
22
23
  if (backgroundRepeat) result["background-repeat"] = backgroundRepeat;
@@ -1 +1 @@
1
- {"version":3,"file":"fill.js","names":[],"sources":["../../src/styles/fill.ts"],"sourcesContent":["import { parseStyle } from '../utils/styles';\n\nexport function fillStyle({\n fill,\n backgroundColor,\n image,\n backgroundImage,\n backgroundPosition,\n backgroundSize,\n backgroundRepeat,\n backgroundAttachment,\n backgroundOrigin,\n backgroundClip,\n background,\n}: {\n fill?: string;\n backgroundColor?: string;\n image?: string;\n backgroundImage?: string;\n backgroundPosition?: string;\n backgroundSize?: string;\n backgroundRepeat?: string;\n backgroundAttachment?: string;\n backgroundOrigin?: string;\n backgroundClip?: string;\n background?: string;\n}) {\n // If background is set, it overrides everything\n if (background) {\n const processed = parseStyle(background);\n return { background: processed.output || background };\n }\n\n const result: Record<string, string> = {};\n\n // Priority: backgroundColor > fill\n const colorValue = backgroundColor ?? fill;\n if (colorValue) {\n const parsed = parseStyle(colorValue);\n const firstColor = parsed.groups[0]?.colors[0];\n const secondColor = parsed.groups[0]?.colors[1];\n\n result['background-color'] = firstColor || colorValue;\n\n // Apply second color as gradient layer (only if no explicit backgroundImage/image)\n // Uses a registered custom property to enable CSS transitions\n if (secondColor && !backgroundImage && !image) {\n result['--tasty-second-fill-color'] = secondColor;\n result['background-image'] =\n 'linear-gradient(var(--tasty-second-fill-color), var(--tasty-second-fill-color))';\n }\n }\n\n // Priority: backgroundImage > image (overrides second fill color if set)\n const imageValue = backgroundImage ?? image;\n if (imageValue) {\n const parsed = parseStyle(imageValue);\n result['background-image'] = parsed.output || imageValue;\n }\n\n // Other background properties (pass through with parseStyle for token support)\n if (backgroundPosition) {\n result['background-position'] =\n parseStyle(backgroundPosition).output || backgroundPosition;\n }\n if (backgroundSize) {\n result['background-size'] =\n parseStyle(backgroundSize).output || backgroundSize;\n }\n if (backgroundRepeat) {\n result['background-repeat'] = backgroundRepeat;\n }\n if (backgroundAttachment) {\n result['background-attachment'] = backgroundAttachment;\n }\n if (backgroundOrigin) {\n result['background-origin'] = backgroundOrigin;\n }\n if (backgroundClip) {\n result['background-clip'] = backgroundClip;\n }\n\n if (Object.keys(result).length === 0) return;\n return result;\n}\n\nfillStyle.__lookupStyles = [\n 'fill',\n 'backgroundColor',\n 'image',\n 'backgroundImage',\n 'backgroundPosition',\n 'backgroundSize',\n 'backgroundRepeat',\n 'backgroundAttachment',\n 'backgroundOrigin',\n 'backgroundClip',\n 'background',\n];\n\nexport function svgFillStyle({ svgFill }: { svgFill?: string }) {\n if (!svgFill) return;\n\n const processed = parseStyle(svgFill);\n svgFill = processed.groups[0]?.colors[0] || svgFill;\n\n return { fill: svgFill };\n}\n\nsvgFillStyle.__lookupStyles = ['svgFill'];\n"],"mappings":";;;AAEA,SAAgB,UAAU,EACxB,MACA,iBACA,OACA,iBACA,oBACA,gBACA,kBACA,sBACA,kBACA,gBACA,cAaC;AAED,KAAI,WAEF,QAAO,EAAE,YADS,WAAW,WAAW,CACT,UAAU,YAAY;CAGvD,MAAM,SAAiC,EAAE;CAGzC,MAAM,aAAa,mBAAmB;AACtC,KAAI,YAAY;EACd,MAAM,SAAS,WAAW,WAAW;EACrC,MAAM,aAAa,OAAO,OAAO,IAAI,OAAO;EAC5C,MAAM,cAAc,OAAO,OAAO,IAAI,OAAO;AAE7C,SAAO,sBAAsB,cAAc;AAI3C,MAAI,eAAe,CAAC,mBAAmB,CAAC,OAAO;AAC7C,UAAO,+BAA+B;AACtC,UAAO,sBACL;;;CAKN,MAAM,aAAa,mBAAmB;AACtC,KAAI,WAEF,QAAO,sBADQ,WAAW,WAAW,CACD,UAAU;AAIhD,KAAI,mBACF,QAAO,yBACL,WAAW,mBAAmB,CAAC,UAAU;AAE7C,KAAI,eACF,QAAO,qBACL,WAAW,eAAe,CAAC,UAAU;AAEzC,KAAI,iBACF,QAAO,uBAAuB;AAEhC,KAAI,qBACF,QAAO,2BAA2B;AAEpC,KAAI,iBACF,QAAO,uBAAuB;AAEhC,KAAI,eACF,QAAO,qBAAqB;AAG9B,KAAI,OAAO,KAAK,OAAO,CAAC,WAAW,EAAG;AACtC,QAAO;;AAGT,UAAU,iBAAiB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAgB,aAAa,EAAE,WAAiC;AAC9D,KAAI,CAAC,QAAS;AAGd,WADkB,WAAW,QAAQ,CACjB,OAAO,IAAI,OAAO,MAAM;AAE5C,QAAO,EAAE,MAAM,SAAS;;AAG1B,aAAa,iBAAiB,CAAC,UAAU"}
1
+ {"version":3,"file":"fill.js","names":[],"sources":["../../src/styles/fill.ts"],"sourcesContent":["import { parseStyle } from '../utils/styles';\n\nexport function fillStyle({\n fill,\n backgroundColor,\n image,\n backgroundImage,\n backgroundPosition,\n backgroundSize,\n backgroundRepeat,\n backgroundAttachment,\n backgroundOrigin,\n backgroundClip,\n background,\n}: {\n fill?: string;\n backgroundColor?: string;\n image?: string;\n backgroundImage?: string;\n backgroundPosition?: string;\n backgroundSize?: string;\n backgroundRepeat?: string;\n backgroundAttachment?: string;\n backgroundOrigin?: string;\n backgroundClip?: string;\n background?: string;\n}) {\n // If background is set, it overrides everything\n if (background) {\n const processed = parseStyle(background);\n return { background: processed.output || background };\n }\n\n const result: Record<string, string> = {};\n\n // Priority: backgroundColor > fill\n const colorValue = backgroundColor ?? fill;\n if (colorValue) {\n const parsed = parseStyle(colorValue);\n const firstColor = parsed.groups[0]?.colors[0];\n const secondColor = parsed.groups[0]?.colors[1];\n\n result['background-color'] = firstColor || colorValue;\n\n if (secondColor) {\n result['--tasty-second-fill-color'] = secondColor;\n }\n }\n\n const gradientLayer = result['--tasty-second-fill-color']\n ? 'linear-gradient(var(--tasty-second-fill-color), var(--tasty-second-fill-color))'\n : null;\n\n // Priority: backgroundImage > image\n const imageValue = backgroundImage ?? image;\n if (imageValue) {\n const parsed = parseStyle(imageValue);\n const imgCss = parsed.output || imageValue;\n\n result['background-image'] = gradientLayer\n ? `${imgCss}, ${gradientLayer}`\n : imgCss;\n } else if (gradientLayer) {\n result['background-image'] = gradientLayer;\n }\n\n // Other background properties (pass through with parseStyle for token support)\n if (backgroundPosition) {\n result['background-position'] =\n parseStyle(backgroundPosition).output || backgroundPosition;\n }\n if (backgroundSize) {\n result['background-size'] =\n parseStyle(backgroundSize).output || backgroundSize;\n }\n if (backgroundRepeat) {\n result['background-repeat'] = backgroundRepeat;\n }\n if (backgroundAttachment) {\n result['background-attachment'] = backgroundAttachment;\n }\n if (backgroundOrigin) {\n result['background-origin'] = backgroundOrigin;\n }\n if (backgroundClip) {\n result['background-clip'] = backgroundClip;\n }\n\n if (Object.keys(result).length === 0) return;\n return result;\n}\n\nfillStyle.__lookupStyles = [\n 'fill',\n 'backgroundColor',\n 'image',\n 'backgroundImage',\n 'backgroundPosition',\n 'backgroundSize',\n 'backgroundRepeat',\n 'backgroundAttachment',\n 'backgroundOrigin',\n 'backgroundClip',\n 'background',\n];\n\nexport function svgFillStyle({ svgFill }: { svgFill?: string }) {\n if (!svgFill) return;\n\n const processed = parseStyle(svgFill);\n svgFill = processed.groups[0]?.colors[0] || svgFill;\n\n return { fill: svgFill };\n}\n\nsvgFillStyle.__lookupStyles = ['svgFill'];\n"],"mappings":";;;AAEA,SAAgB,UAAU,EACxB,MACA,iBACA,OACA,iBACA,oBACA,gBACA,kBACA,sBACA,kBACA,gBACA,cAaC;AAED,KAAI,WAEF,QAAO,EAAE,YADS,WAAW,WAAW,CACT,UAAU,YAAY;CAGvD,MAAM,SAAiC,EAAE;CAGzC,MAAM,aAAa,mBAAmB;AACtC,KAAI,YAAY;EACd,MAAM,SAAS,WAAW,WAAW;EACrC,MAAM,aAAa,OAAO,OAAO,IAAI,OAAO;EAC5C,MAAM,cAAc,OAAO,OAAO,IAAI,OAAO;AAE7C,SAAO,sBAAsB,cAAc;AAE3C,MAAI,YACF,QAAO,+BAA+B;;CAI1C,MAAM,gBAAgB,OAAO,+BACzB,oFACA;CAGJ,MAAM,aAAa,mBAAmB;AACtC,KAAI,YAAY;EAEd,MAAM,SADS,WAAW,WAAW,CACf,UAAU;AAEhC,SAAO,sBAAsB,gBACzB,GAAG,OAAO,IAAI,kBACd;YACK,cACT,QAAO,sBAAsB;AAI/B,KAAI,mBACF,QAAO,yBACL,WAAW,mBAAmB,CAAC,UAAU;AAE7C,KAAI,eACF,QAAO,qBACL,WAAW,eAAe,CAAC,UAAU;AAEzC,KAAI,iBACF,QAAO,uBAAuB;AAEhC,KAAI,qBACF,QAAO,2BAA2B;AAEpC,KAAI,iBACF,QAAO,uBAAuB;AAEhC,KAAI,eACF,QAAO,qBAAqB;AAG9B,KAAI,OAAO,KAAK,OAAO,CAAC,WAAW,EAAG;AACtC,QAAO;;AAGT,UAAU,iBAAiB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAgB,aAAa,EAAE,WAAiC;AAC9D,KAAI,CAAC,QAAS;AAGd,WADkB,WAAW,QAAQ,CACjB,OAAO,IAAI,OAAO,MAAM;AAE5C,QAAO,EAAE,MAAM,SAAS;;AAG1B,aAAa,iBAAiB,CAAC,UAAU"}
package/dist/tasty.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { processTokens, stringifyTokens } from "./utils/process-tokens.js";
2
+ import { isSelector } from "./pipeline/index.js";
2
3
  import { BASE_STYLES } from "./styles/list.js";
3
4
  import { _modAttrs } from "./utils/mod-attrs.js";
4
5
  import { mergeStyles } from "./utils/merge-styles.js";
@@ -104,8 +105,22 @@ function tastyElement(tastyOptions) {
104
105
  const { as: originalAs = "div", element: defaultElement, styles: defaultStyles, styleProps, variants, tokens: defaultTokens, elements, ...defaultProps } = tastyOptions;
105
106
  let variantStylesMap;
106
107
  if (variants) {
108
+ let baseStyles = defaultStyles;
109
+ let extensionStyles;
110
+ if (defaultStyles) for (const key of Object.keys(defaultStyles)) {
111
+ if (isSelector(key)) continue;
112
+ const value = defaultStyles[key];
113
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && !("" in value)) {
114
+ if (!extensionStyles) {
115
+ baseStyles = { ...defaultStyles };
116
+ extensionStyles = {};
117
+ }
118
+ extensionStyles[key] = value;
119
+ delete baseStyles[key];
120
+ }
121
+ }
107
122
  variantStylesMap = Object.entries(variants).reduce((map, [variant, variantStyles]) => {
108
- map[variant] = mergeStyles(defaultStyles, variantStyles);
123
+ map[variant] = extensionStyles ? mergeStyles(baseStyles, variantStyles, extensionStyles) : mergeStyles(baseStyles, variantStyles);
109
124
  return map;
110
125
  }, {});
111
126
  if (!variantStylesMap["default"]) variantStylesMap["default"] = defaultStyles;
package/dist/tasty.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tasty.js","names":["modAttrs"],"sources":["../src/tasty.tsx"],"sourcesContent":["import type {\n AllHTMLAttributes,\n ComponentType,\n ForwardRefExoticComponent,\n JSX,\n PropsWithoutRef,\n RefAttributes,\n} from 'react';\nimport { createElement, forwardRef, useMemo } from 'react';\nimport { useStyles } from './hooks/useStyles';\nimport { BASE_STYLES } from './styles/list';\nimport type { Styles, StylesInterface } from './styles/types';\nimport type {\n AllBaseProps,\n BaseProps,\n BaseStyleProps,\n Mods,\n Props,\n Tokens,\n} from './types';\nimport { getDisplayName } from './utils/get-display-name';\nimport { isValidElementType } from './utils/is-valid-element-type';\nimport { mergeStyles } from './utils/merge-styles';\nimport { modAttrs } from './utils/mod-attrs';\nimport { processTokens, stringifyTokens } from './utils/process-tokens';\n\nimport type { StyleValue, StyleValueStateMap } from './utils/styles';\n\n/**\n * Mapping of is* properties to their corresponding HTML attributes\n */\nconst IS_PROPERTIES_MAP = {\n isDisabled: 'disabled',\n isHidden: 'hidden',\n isChecked: 'checked',\n} as const;\n\n/**\n * Precalculated entries for performance optimization\n */\nconst IS_PROPERTIES_ENTRIES = Object.entries(IS_PROPERTIES_MAP);\n\n/**\n * Helper function to handle is* properties consistently\n * Transforms is* props to HTML attributes and adds corresponding data-* attributes\n */\nfunction handleIsProperties(props: Record<string, unknown>) {\n for (const [isProperty, targetAttribute] of IS_PROPERTIES_ENTRIES) {\n if (isProperty in props) {\n props[targetAttribute] = props[isProperty];\n delete props[isProperty];\n }\n\n // Add data-* attribute if target attribute is truthy and doesn't already exist\n const dataAttribute = `data-${targetAttribute}`;\n if (!(dataAttribute in props) && props[targetAttribute]) {\n props[dataAttribute] = '';\n }\n }\n}\n\n/**\n * Creates a sub-element component for compound component patterns.\n * Sub-elements are lightweight components with data-element attribute for CSS targeting.\n */\nfunction createSubElement<Tag extends keyof JSX.IntrinsicElements>(\n elementName: string,\n definition: SubElementDefinition<Tag>,\n): ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<Tag>> & RefAttributes<unknown>\n> {\n // Normalize definition to object form\n const config =\n typeof definition === 'string'\n ? { as: definition as Tag }\n : (definition as { as?: Tag; qa?: string; qaVal?: string | number });\n\n const tag = config.as ?? ('div' as Tag);\n const defaultQa = config.qa;\n const defaultQaVal = config.qaVal;\n\n const SubElement = forwardRef<unknown, SubElementProps<Tag>>((props, ref) => {\n const {\n qa,\n qaVal,\n mods,\n tokens,\n isDisabled,\n isHidden,\n isChecked,\n className,\n style,\n ...htmlProps\n } = props as SubElementProps<Tag> & {\n className?: string;\n style?: Record<string, unknown>;\n };\n\n // Build mod attributes\n let modProps: Record<string, unknown> | undefined;\n if (mods) {\n modProps = modAttrs(mods as Mods) as Record<string, unknown>;\n }\n\n // Process tokens into inline style properties\n const tokenStyle = tokens\n ? (processTokens(tokens) as Record<string, unknown>)\n : undefined;\n\n // Merge token styles with explicit style prop (style has priority)\n let mergedStyle: Record<string, unknown> | undefined;\n if (tokenStyle || style) {\n mergedStyle =\n tokenStyle && style\n ? { ...tokenStyle, ...style }\n : ((tokenStyle ?? style) as Record<string, unknown>);\n }\n\n const elementProps = {\n 'data-element': elementName,\n 'data-qa': qa ?? defaultQa,\n 'data-qaval': qaVal ?? defaultQaVal,\n ...(modProps || {}),\n ...htmlProps,\n className,\n style: mergedStyle,\n isDisabled,\n isHidden,\n isChecked,\n ref,\n } as Record<string, unknown>;\n\n // Handle is* properties (isDisabled -> disabled + data-disabled, etc.)\n handleIsProperties(elementProps);\n\n // Clean up undefined data attributes\n if (elementProps['data-qa'] === undefined) delete elementProps['data-qa'];\n if (elementProps['data-qaval'] === undefined)\n delete elementProps['data-qaval'];\n\n return createElement(tag, elementProps);\n });\n\n SubElement.displayName = `SubElement(${elementName})`;\n\n return SubElement as ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<Tag>> & RefAttributes<unknown>\n >;\n}\n\ntype StyleList = readonly (keyof {\n [key in keyof StylesInterface]: StylesInterface[key];\n})[];\n\nexport type PropsWithStyles = {\n styles?: Styles;\n} & Omit<Props, 'styles'>;\n\nexport type VariantMap = Record<string, Styles>;\n\nexport interface WithVariant<V extends VariantMap> {\n variant?: keyof V;\n}\n\n// ============================================================================\n// Sub-element types for compound components\n// ============================================================================\n\n/**\n * Definition for a sub-element. Can be either:\n * - A tag name string (e.g., 'div', 'span')\n * - An object with configuration options\n */\nexport type SubElementDefinition<\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> =\n | Tag\n | {\n as?: Tag;\n qa?: string;\n qaVal?: string | number;\n };\n\n/**\n * Map of sub-element definitions.\n * Keys become the sub-component names (e.g., { Icon: 'span' } -> Component.Icon)\n */\nexport type ElementsDefinition = Record<\n string,\n SubElementDefinition<keyof JSX.IntrinsicElements>\n>;\n\n/**\n * Resolves the tag from a SubElementDefinition\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ResolveElementTag<T extends SubElementDefinition<any>> = T extends string\n ? T\n : T extends { as?: infer Tag }\n ? Tag extends keyof JSX.IntrinsicElements\n ? Tag\n : 'div'\n : 'div';\n\n/**\n * Props for sub-element components.\n * Combines HTML attributes with tasty-specific props (qa, qaVal, mods, tokens, isDisabled, etc.)\n */\nexport type SubElementProps<Tag extends keyof JSX.IntrinsicElements = 'div'> =\n Omit<\n JSX.IntrinsicElements[Tag],\n 'ref' | 'color' | 'content' | 'translate'\n > & {\n qa?: string;\n qaVal?: string | number;\n mods?: Mods;\n tokens?: Tokens;\n isDisabled?: boolean;\n isHidden?: boolean;\n isChecked?: boolean;\n };\n\n/**\n * Generates the sub-element component types from an ElementsDefinition\n */\ntype SubElementComponents<E extends ElementsDefinition> = {\n [K in keyof E]: ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<ResolveElementTag<E[K]>>> &\n RefAttributes<\n ResolveElementTag<E[K]> extends keyof HTMLElementTagNameMap\n ? HTMLElementTagNameMap[ResolveElementTag<E[K]>]\n : Element\n >\n >;\n};\n\n/**\n * Base type containing common properties shared between TastyProps and TastyElementOptions.\n * Separated to avoid code duplication while allowing different type constraints.\n */\ntype TastyBaseProps<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n> = {\n /** Default styles of the element. */\n styles?: Styles;\n /** The list of styles that can be provided by props */\n styleProps?: K;\n element?: BaseProps['element'];\n variants?: V;\n /** Default tokens for inline CSS custom properties */\n tokens?: Tokens;\n /** Sub-element definitions for compound components */\n elements?: E;\n} & Pick<BaseProps, 'qa' | 'qaVal'> &\n WithVariant<V>;\n\nexport type TastyProps<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n DefaultProps = Props,\n> = TastyBaseProps<K, V, E> & {\n /** The tag name of the element or a React component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n as?: string | ComponentType<any>;\n} & Partial<Omit<DefaultProps, 'as' | 'styles' | 'styleProps' | 'tokens'>>;\n\n/**\n * TastyElementOptions is used for the element-creation overload of tasty().\n * It includes a Tag generic that allows TypeScript to infer the correct\n * HTML element type from the `as` prop.\n *\n * Note: Uses a separate index signature with `unknown` instead of inheriting\n * from Props (which has `any`) to ensure strict type checking for styles.\n */\nexport type TastyElementOptions<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> = TastyBaseProps<K, V, E> & {\n /** The tag name of the element or a React component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n as?: Tag | ComponentType<any>;\n} & Record<string, unknown>;\n\nexport type AllBasePropsWithMods<K extends StyleList> = AllBaseProps & {\n [key in K[number]]?:\n | StyleValue<StylesInterface[key]>\n | StyleValueStateMap<StylesInterface[key]>;\n} & BaseStyleProps;\n\n/**\n * Keys from BasePropsWithoutChildren that should be omitted from HTML attributes.\n * This excludes event handlers so they can be properly typed from JSX.IntrinsicElements.\n */\ntype TastySpecificKeys =\n | 'as'\n | 'qa'\n | 'qaVal'\n | 'element'\n | 'styles'\n | 'breakpoints'\n | 'block'\n | 'inline'\n | 'mods'\n | 'isHidden'\n | 'isDisabled'\n | 'css'\n | 'style'\n | 'theme'\n | 'tokens'\n | 'ref'\n | 'color';\n\n/**\n * Props type for tasty elements that combines:\n * - AllBasePropsWithMods for style props with strict tokens type\n * - HTML attributes for flexibility (properly typed based on tag)\n * - Variant support\n *\n * Uses AllHTMLAttributes as base for common attributes (like disabled),\n * but overrides event handlers with tag-specific types from JSX.IntrinsicElements.\n */\nexport type TastyElementProps<\n K extends StyleList,\n V extends VariantMap,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> = AllBasePropsWithMods<K> &\n WithVariant<V> &\n Omit<\n Omit<AllHTMLAttributes<HTMLElement>, keyof JSX.IntrinsicElements[Tag]> &\n JSX.IntrinsicElements[Tag],\n TastySpecificKeys | K[number]\n >;\n\ntype TastyComponentPropsWithDefaults<\n Props extends PropsWithStyles,\n DefaultProps extends Partial<Props>,\n> = keyof DefaultProps extends never\n ? Props\n : {\n [key in Extract<keyof Props, keyof DefaultProps>]?: Props[key];\n } & {\n [key in keyof Omit<Props, keyof DefaultProps>]: Props[key];\n };\n\nexport function tasty<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n>(\n options: TastyElementOptions<K, V, E, Tag>,\n secondArg?: never,\n): ForwardRefExoticComponent<\n PropsWithoutRef<TastyElementProps<K, V, Tag>> & RefAttributes<unknown>\n> &\n SubElementComponents<E>;\nexport function tasty<\n Props extends PropsWithStyles,\n DefaultProps extends Partial<Props> = Partial<Props>,\n>(\n Component: ComponentType<Props>,\n options?: TastyProps<never, never, Record<string, never>, Props>,\n): ComponentType<TastyComponentPropsWithDefaults<Props, DefaultProps>>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Implementation\nexport function tasty<\n K extends StyleList,\n V extends VariantMap,\n _C = Record<string, unknown>,\n>(Component: any, options?: any) {\n if (isValidElementType(Component)) {\n return tastyWrap(Component as ComponentType<any>, options);\n }\n\n return tastyElement(Component as TastyProps<K, V>);\n}\n\nfunction tastyWrap<\n P extends PropsWithStyles,\n DefaultProps extends Partial<P> = Partial<P>,\n>(\n Component: ComponentType<P>,\n options?: TastyProps<never, never, P>,\n): ComponentType<TastyComponentPropsWithDefaults<P, DefaultProps>> {\n const {\n as: extendTag,\n element: extendElement,\n ...defaultProps\n } = (options ?? {}) as TastyProps<never, never, P>;\n\n const propsWithStyles = ['styles'].concat(\n Object.keys(defaultProps).filter((prop) => prop.endsWith('Styles')),\n );\n\n const _WrappedComponent = forwardRef<any, any>((props, ref) => {\n const { as, element, ...restProps } = props as Record<string, unknown>;\n const propsWithStylesValues = propsWithStyles.map(\n (prop) => (props as any)[prop],\n );\n\n const mergedStylesMap: Styles | undefined = useMemo(() => {\n return propsWithStyles.reduce((map, prop) => {\n const restValue = (restProps as any)[prop];\n const defaultValue = (defaultProps as any)[prop];\n\n if (restValue != null && defaultValue != null) {\n (map as any)[prop] = mergeStyles(defaultValue, restValue);\n } else {\n (map as any)[prop] = restValue ?? defaultValue;\n }\n\n return map;\n }, {} as Styles);\n }, [propsWithStylesValues]);\n\n const elementProps = {\n ...(defaultProps as unknown as Record<string, unknown>),\n ...(restProps as unknown as Record<string, unknown>),\n ...(mergedStylesMap as unknown as Record<string, unknown>),\n as: (as as string | undefined) ?? extendTag,\n element: (element as string | undefined) || extendElement,\n ref,\n } as unknown as P;\n\n return createElement(Component as ComponentType<P>, elementProps);\n });\n\n _WrappedComponent.displayName = `TastyWrappedComponent(${getDisplayName(\n Component,\n (defaultProps as any).qa ?? (extendTag as any) ?? 'Anonymous',\n )})`;\n\n return _WrappedComponent as unknown as ComponentType<\n TastyComponentPropsWithDefaults<P, DefaultProps>\n >;\n}\n\nfunction tastyElement<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition,\n>(tastyOptions: TastyProps<K, V, E>) {\n const {\n as: originalAs = 'div',\n element: defaultElement,\n styles: defaultStyles,\n styleProps,\n variants,\n tokens: defaultTokens,\n elements,\n ...defaultProps\n } = tastyOptions;\n\n // Pre-compute merged styles for each variant (if variants are defined)\n // This avoids creating separate component instances per variant\n let variantStylesMap: Record<string, Styles | undefined> | undefined;\n if (variants) {\n const variantEntries = Object.entries(variants) as [string, Styles][];\n variantStylesMap = variantEntries.reduce(\n (map, [variant, variantStyles]) => {\n map[variant] = mergeStyles(defaultStyles, variantStyles);\n return map;\n },\n {} as Record<string, Styles | undefined>,\n );\n // Ensure 'default' variant always exists\n if (!variantStylesMap['default']) {\n variantStylesMap['default'] = defaultStyles;\n }\n }\n\n const {\n qa: defaultQa,\n qaVal: defaultQaVal,\n ...otherDefaultProps\n } = defaultProps ?? {};\n\n const _TastyComponent = forwardRef<\n unknown,\n AllBasePropsWithMods<K> & WithVariant<V>\n >((allProps, ref) => {\n const {\n as,\n styles: rawStyles,\n variant,\n mods,\n element,\n qa,\n qaVal,\n className: userClassName,\n tokens,\n style,\n ...otherProps\n } = allProps as Record<string, unknown> as AllBasePropsWithMods<K> &\n WithVariant<V> & {\n className?: string;\n tokens?: Tokens;\n style?: Record<string, unknown>;\n };\n\n let styles = rawStyles;\n\n // Optimize propStyles extraction - avoid creating empty objects\n let propStyles: Styles | null = null;\n const propsToCheck = styleProps\n ? (styleProps as StyleList).concat(BASE_STYLES)\n : BASE_STYLES;\n\n for (const prop of propsToCheck) {\n const key = prop as unknown as string;\n\n if (!propStyles) propStyles = {};\n\n if (key in otherProps) {\n (propStyles as any)[key] = (otherProps as any)[key];\n delete (otherProps as any)[key];\n }\n }\n\n if (\n !styles ||\n (styles && Object.keys(styles as Record<string, unknown>).length === 0)\n ) {\n styles = undefined as unknown as Styles;\n }\n\n // Determine base styles: use variant styles if available, otherwise default styles\n const baseStyles = variantStylesMap\n ? (variantStylesMap[(variant as string) || 'default'] ??\n variantStylesMap['default'])\n : defaultStyles;\n\n // Merge base styles with instance styles and prop styles\n const allStyles = useMemo(() => {\n const hasStyles =\n styles && Object.keys(styles as Record<string, unknown>).length > 0;\n const hasPropStyles = propStyles && Object.keys(propStyles).length > 0;\n\n if (!hasStyles && !hasPropStyles) {\n return baseStyles;\n }\n\n return mergeStyles(baseStyles, styles as Styles, propStyles as Styles);\n }, [baseStyles, styles, propStyles]);\n\n // Use the useStyles hook for style generation and injection\n const { className: stylesClassName } = useStyles(allStyles);\n\n // Merge default tokens with instance tokens (instance overrides defaults)\n const tokensKey = stringifyTokens(tokens as Tokens | undefined);\n const mergedTokens = useMemo(() => {\n if (!defaultTokens && !tokens) return undefined;\n if (!defaultTokens) return tokens as Tokens;\n if (!tokens) return defaultTokens;\n return { ...defaultTokens, ...tokens } as Tokens;\n }, [tokensKey]);\n\n // Process merged tokens into inline style properties\n const processedTokenStyle = useMemo(() => {\n return processTokens(mergedTokens);\n }, [mergedTokens]);\n\n // Merge processed tokens with explicit style prop (style has priority)\n const mergedStyle = useMemo(() => {\n if (!processedTokenStyle && !style) return undefined;\n if (!processedTokenStyle) return style;\n if (!style) return processedTokenStyle;\n return { ...processedTokenStyle, ...style };\n }, [processedTokenStyle, style]);\n\n let modProps: Record<string, unknown> | undefined;\n if (mods) {\n const modsObject = mods as unknown as Record<string, unknown>;\n modProps = modAttrs(modsObject as any) as Record<string, unknown>;\n }\n\n // Merge user className with generated className\n const finalClassName = [(userClassName as string) || '', stylesClassName]\n .filter(Boolean)\n .join(' ');\n\n const elementProps = {\n 'data-element': (element as string | undefined) || defaultElement,\n 'data-qa': (qa as string | undefined) || defaultQa,\n 'data-qaval': (qaVal as string | undefined) || defaultQaVal,\n ...(otherDefaultProps as unknown as Record<string, unknown>),\n ...(modProps || {}),\n ...(otherProps as unknown as Record<string, unknown>),\n className: finalClassName,\n style: mergedStyle,\n ref,\n } as Record<string, unknown>;\n\n // Apply the helper to handle is* properties\n handleIsProperties(elementProps);\n\n const renderedElement = createElement(\n (as as string | 'div') ?? originalAs,\n elementProps,\n );\n\n return renderedElement;\n });\n\n _TastyComponent.displayName = `TastyComponent(${\n (defaultProps as any).qa || originalAs\n })`;\n\n // Attach sub-element components if elements are defined\n if (elements) {\n const subElements = Object.entries(elements).reduce(\n (acc, [name, definition]) => {\n acc[name] = createSubElement(\n name,\n definition as SubElementDefinition<keyof JSX.IntrinsicElements>,\n );\n return acc;\n },\n {} as Record<string, ForwardRefExoticComponent<any>>,\n );\n\n return Object.assign(_TastyComponent, subElements);\n }\n\n return _TastyComponent;\n}\n\nexport const Element = tasty({});\n"],"mappings":";;;;;;;;;;;;;AAwCA,MAAM,wBAAwB,OAAO,QATX;CACxB,YAAY;CACZ,UAAU;CACV,WAAW;CACZ,CAK8D;;;;;AAM/D,SAAS,mBAAmB,OAAgC;AAC1D,MAAK,MAAM,CAAC,YAAY,oBAAoB,uBAAuB;AACjE,MAAI,cAAc,OAAO;AACvB,SAAM,mBAAmB,MAAM;AAC/B,UAAO,MAAM;;EAIf,MAAM,gBAAgB,QAAQ;AAC9B,MAAI,EAAE,iBAAiB,UAAU,MAAM,iBACrC,OAAM,iBAAiB;;;;;;;AAS7B,SAAS,iBACP,aACA,YAGA;CAEA,MAAM,SACJ,OAAO,eAAe,WAClB,EAAE,IAAI,YAA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AmB,aAAa;AAOhC,SALwB,cACrB,MAAyB,YAC1B,aACD;GAGD;AAEF,iBAAgB,cAAc,kBAC3B,aAAqB,MAAM,WAC7B;AAGD,KAAI,UAAU;EACZ,MAAM,cAAc,OAAO,QAAQ,SAAS,CAAC,QAC1C,KAAK,CAAC,MAAM,gBAAgB;AAC3B,OAAI,QAAQ,iBACV,MACA,WACD;AACD,UAAO;KAET,EAAE,CACH;AAED,SAAO,OAAO,OAAO,iBAAiB,YAAY;;AAGpD,QAAO;;AAGT,MAAa,UAAU,MAAM,EAAE,CAAC"}
1
+ {"version":3,"file":"tasty.js","names":["modAttrs"],"sources":["../src/tasty.tsx"],"sourcesContent":["import type {\n AllHTMLAttributes,\n ComponentType,\n ForwardRefExoticComponent,\n JSX,\n PropsWithoutRef,\n RefAttributes,\n} from 'react';\nimport { createElement, forwardRef, useMemo } from 'react';\nimport { useStyles } from './hooks/useStyles';\nimport { BASE_STYLES } from './styles/list';\nimport type { Styles, StylesInterface } from './styles/types';\nimport type {\n AllBaseProps,\n BaseProps,\n BaseStyleProps,\n Mods,\n Props,\n Tokens,\n} from './types';\nimport { getDisplayName } from './utils/get-display-name';\nimport { isValidElementType } from './utils/is-valid-element-type';\nimport { mergeStyles } from './utils/merge-styles';\nimport { isSelector } from './pipeline';\nimport { modAttrs } from './utils/mod-attrs';\nimport { processTokens, stringifyTokens } from './utils/process-tokens';\n\nimport type { StyleValue, StyleValueStateMap } from './utils/styles';\n\n/**\n * Mapping of is* properties to their corresponding HTML attributes\n */\nconst IS_PROPERTIES_MAP = {\n isDisabled: 'disabled',\n isHidden: 'hidden',\n isChecked: 'checked',\n} as const;\n\n/**\n * Precalculated entries for performance optimization\n */\nconst IS_PROPERTIES_ENTRIES = Object.entries(IS_PROPERTIES_MAP);\n\n/**\n * Helper function to handle is* properties consistently\n * Transforms is* props to HTML attributes and adds corresponding data-* attributes\n */\nfunction handleIsProperties(props: Record<string, unknown>) {\n for (const [isProperty, targetAttribute] of IS_PROPERTIES_ENTRIES) {\n if (isProperty in props) {\n props[targetAttribute] = props[isProperty];\n delete props[isProperty];\n }\n\n // Add data-* attribute if target attribute is truthy and doesn't already exist\n const dataAttribute = `data-${targetAttribute}`;\n if (!(dataAttribute in props) && props[targetAttribute]) {\n props[dataAttribute] = '';\n }\n }\n}\n\n/**\n * Creates a sub-element component for compound component patterns.\n * Sub-elements are lightweight components with data-element attribute for CSS targeting.\n */\nfunction createSubElement<Tag extends keyof JSX.IntrinsicElements>(\n elementName: string,\n definition: SubElementDefinition<Tag>,\n): ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<Tag>> & RefAttributes<unknown>\n> {\n // Normalize definition to object form\n const config =\n typeof definition === 'string'\n ? { as: definition as Tag }\n : (definition as { as?: Tag; qa?: string; qaVal?: string | number });\n\n const tag = config.as ?? ('div' as Tag);\n const defaultQa = config.qa;\n const defaultQaVal = config.qaVal;\n\n const SubElement = forwardRef<unknown, SubElementProps<Tag>>((props, ref) => {\n const {\n qa,\n qaVal,\n mods,\n tokens,\n isDisabled,\n isHidden,\n isChecked,\n className,\n style,\n ...htmlProps\n } = props as SubElementProps<Tag> & {\n className?: string;\n style?: Record<string, unknown>;\n };\n\n // Build mod attributes\n let modProps: Record<string, unknown> | undefined;\n if (mods) {\n modProps = modAttrs(mods as Mods) as Record<string, unknown>;\n }\n\n // Process tokens into inline style properties\n const tokenStyle = tokens\n ? (processTokens(tokens) as Record<string, unknown>)\n : undefined;\n\n // Merge token styles with explicit style prop (style has priority)\n let mergedStyle: Record<string, unknown> | undefined;\n if (tokenStyle || style) {\n mergedStyle =\n tokenStyle && style\n ? { ...tokenStyle, ...style }\n : ((tokenStyle ?? style) as Record<string, unknown>);\n }\n\n const elementProps = {\n 'data-element': elementName,\n 'data-qa': qa ?? defaultQa,\n 'data-qaval': qaVal ?? defaultQaVal,\n ...(modProps || {}),\n ...htmlProps,\n className,\n style: mergedStyle,\n isDisabled,\n isHidden,\n isChecked,\n ref,\n } as Record<string, unknown>;\n\n // Handle is* properties (isDisabled -> disabled + data-disabled, etc.)\n handleIsProperties(elementProps);\n\n // Clean up undefined data attributes\n if (elementProps['data-qa'] === undefined) delete elementProps['data-qa'];\n if (elementProps['data-qaval'] === undefined)\n delete elementProps['data-qaval'];\n\n return createElement(tag, elementProps);\n });\n\n SubElement.displayName = `SubElement(${elementName})`;\n\n return SubElement as ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<Tag>> & RefAttributes<unknown>\n >;\n}\n\ntype StyleList = readonly (keyof {\n [key in keyof StylesInterface]: StylesInterface[key];\n})[];\n\nexport type PropsWithStyles = {\n styles?: Styles;\n} & Omit<Props, 'styles'>;\n\nexport type VariantMap = Record<string, Styles>;\n\nexport interface WithVariant<V extends VariantMap> {\n variant?: keyof V;\n}\n\n// ============================================================================\n// Sub-element types for compound components\n// ============================================================================\n\n/**\n * Definition for a sub-element. Can be either:\n * - A tag name string (e.g., 'div', 'span')\n * - An object with configuration options\n */\nexport type SubElementDefinition<\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> =\n | Tag\n | {\n as?: Tag;\n qa?: string;\n qaVal?: string | number;\n };\n\n/**\n * Map of sub-element definitions.\n * Keys become the sub-component names (e.g., { Icon: 'span' } -> Component.Icon)\n */\nexport type ElementsDefinition = Record<\n string,\n SubElementDefinition<keyof JSX.IntrinsicElements>\n>;\n\n/**\n * Resolves the tag from a SubElementDefinition\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ResolveElementTag<T extends SubElementDefinition<any>> = T extends string\n ? T\n : T extends { as?: infer Tag }\n ? Tag extends keyof JSX.IntrinsicElements\n ? Tag\n : 'div'\n : 'div';\n\n/**\n * Props for sub-element components.\n * Combines HTML attributes with tasty-specific props (qa, qaVal, mods, tokens, isDisabled, etc.)\n */\nexport type SubElementProps<Tag extends keyof JSX.IntrinsicElements = 'div'> =\n Omit<\n JSX.IntrinsicElements[Tag],\n 'ref' | 'color' | 'content' | 'translate'\n > & {\n qa?: string;\n qaVal?: string | number;\n mods?: Mods;\n tokens?: Tokens;\n isDisabled?: boolean;\n isHidden?: boolean;\n isChecked?: boolean;\n };\n\n/**\n * Generates the sub-element component types from an ElementsDefinition\n */\ntype SubElementComponents<E extends ElementsDefinition> = {\n [K in keyof E]: ForwardRefExoticComponent<\n PropsWithoutRef<SubElementProps<ResolveElementTag<E[K]>>> &\n RefAttributes<\n ResolveElementTag<E[K]> extends keyof HTMLElementTagNameMap\n ? HTMLElementTagNameMap[ResolveElementTag<E[K]>]\n : Element\n >\n >;\n};\n\n/**\n * Base type containing common properties shared between TastyProps and TastyElementOptions.\n * Separated to avoid code duplication while allowing different type constraints.\n */\ntype TastyBaseProps<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n> = {\n /** Default styles of the element. */\n styles?: Styles;\n /** The list of styles that can be provided by props */\n styleProps?: K;\n element?: BaseProps['element'];\n variants?: V;\n /** Default tokens for inline CSS custom properties */\n tokens?: Tokens;\n /** Sub-element definitions for compound components */\n elements?: E;\n} & Pick<BaseProps, 'qa' | 'qaVal'> &\n WithVariant<V>;\n\nexport type TastyProps<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n DefaultProps = Props,\n> = TastyBaseProps<K, V, E> & {\n /** The tag name of the element or a React component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n as?: string | ComponentType<any>;\n} & Partial<Omit<DefaultProps, 'as' | 'styles' | 'styleProps' | 'tokens'>>;\n\n/**\n * TastyElementOptions is used for the element-creation overload of tasty().\n * It includes a Tag generic that allows TypeScript to infer the correct\n * HTML element type from the `as` prop.\n *\n * Note: Uses a separate index signature with `unknown` instead of inheriting\n * from Props (which has `any`) to ensure strict type checking for styles.\n */\nexport type TastyElementOptions<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> = TastyBaseProps<K, V, E> & {\n /** The tag name of the element or a React component. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n as?: Tag | ComponentType<any>;\n} & Record<string, unknown>;\n\nexport type AllBasePropsWithMods<K extends StyleList> = AllBaseProps & {\n [key in K[number]]?:\n | StyleValue<StylesInterface[key]>\n | StyleValueStateMap<StylesInterface[key]>;\n} & BaseStyleProps;\n\n/**\n * Keys from BasePropsWithoutChildren that should be omitted from HTML attributes.\n * This excludes event handlers so they can be properly typed from JSX.IntrinsicElements.\n */\ntype TastySpecificKeys =\n | 'as'\n | 'qa'\n | 'qaVal'\n | 'element'\n | 'styles'\n | 'breakpoints'\n | 'block'\n | 'inline'\n | 'mods'\n | 'isHidden'\n | 'isDisabled'\n | 'css'\n | 'style'\n | 'theme'\n | 'tokens'\n | 'ref'\n | 'color';\n\n/**\n * Props type for tasty elements that combines:\n * - AllBasePropsWithMods for style props with strict tokens type\n * - HTML attributes for flexibility (properly typed based on tag)\n * - Variant support\n *\n * Uses AllHTMLAttributes as base for common attributes (like disabled),\n * but overrides event handlers with tag-specific types from JSX.IntrinsicElements.\n */\nexport type TastyElementProps<\n K extends StyleList,\n V extends VariantMap,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n> = AllBasePropsWithMods<K> &\n WithVariant<V> &\n Omit<\n Omit<AllHTMLAttributes<HTMLElement>, keyof JSX.IntrinsicElements[Tag]> &\n JSX.IntrinsicElements[Tag],\n TastySpecificKeys | K[number]\n >;\n\ntype TastyComponentPropsWithDefaults<\n Props extends PropsWithStyles,\n DefaultProps extends Partial<Props>,\n> = keyof DefaultProps extends never\n ? Props\n : {\n [key in Extract<keyof Props, keyof DefaultProps>]?: Props[key];\n } & {\n [key in keyof Omit<Props, keyof DefaultProps>]: Props[key];\n };\n\nexport function tasty<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition = Record<string, never>,\n Tag extends keyof JSX.IntrinsicElements = 'div',\n>(\n options: TastyElementOptions<K, V, E, Tag>,\n secondArg?: never,\n): ForwardRefExoticComponent<\n PropsWithoutRef<TastyElementProps<K, V, Tag>> & RefAttributes<unknown>\n> &\n SubElementComponents<E>;\nexport function tasty<\n Props extends PropsWithStyles,\n DefaultProps extends Partial<Props> = Partial<Props>,\n>(\n Component: ComponentType<Props>,\n options?: TastyProps<never, never, Record<string, never>, Props>,\n): ComponentType<TastyComponentPropsWithDefaults<Props, DefaultProps>>;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// Implementation\nexport function tasty<\n K extends StyleList,\n V extends VariantMap,\n _C = Record<string, unknown>,\n>(Component: any, options?: any) {\n if (isValidElementType(Component)) {\n return tastyWrap(Component as ComponentType<any>, options);\n }\n\n return tastyElement(Component as TastyProps<K, V>);\n}\n\nfunction tastyWrap<\n P extends PropsWithStyles,\n DefaultProps extends Partial<P> = Partial<P>,\n>(\n Component: ComponentType<P>,\n options?: TastyProps<never, never, P>,\n): ComponentType<TastyComponentPropsWithDefaults<P, DefaultProps>> {\n const {\n as: extendTag,\n element: extendElement,\n ...defaultProps\n } = (options ?? {}) as TastyProps<never, never, P>;\n\n const propsWithStyles = ['styles'].concat(\n Object.keys(defaultProps).filter((prop) => prop.endsWith('Styles')),\n );\n\n const _WrappedComponent = forwardRef<any, any>((props, ref) => {\n const { as, element, ...restProps } = props as Record<string, unknown>;\n const propsWithStylesValues = propsWithStyles.map(\n (prop) => (props as any)[prop],\n );\n\n const mergedStylesMap: Styles | undefined = useMemo(() => {\n return propsWithStyles.reduce((map, prop) => {\n const restValue = (restProps as any)[prop];\n const defaultValue = (defaultProps as any)[prop];\n\n if (restValue != null && defaultValue != null) {\n (map as any)[prop] = mergeStyles(defaultValue, restValue);\n } else {\n (map as any)[prop] = restValue ?? defaultValue;\n }\n\n return map;\n }, {} as Styles);\n }, [propsWithStylesValues]);\n\n const elementProps = {\n ...(defaultProps as unknown as Record<string, unknown>),\n ...(restProps as unknown as Record<string, unknown>),\n ...(mergedStylesMap as unknown as Record<string, unknown>),\n as: (as as string | undefined) ?? extendTag,\n element: (element as string | undefined) || extendElement,\n ref,\n } as unknown as P;\n\n return createElement(Component as ComponentType<P>, elementProps);\n });\n\n _WrappedComponent.displayName = `TastyWrappedComponent(${getDisplayName(\n Component,\n (defaultProps as any).qa ?? (extendTag as any) ?? 'Anonymous',\n )})`;\n\n return _WrappedComponent as unknown as ComponentType<\n TastyComponentPropsWithDefaults<P, DefaultProps>\n >;\n}\n\nfunction tastyElement<\n K extends StyleList,\n V extends VariantMap,\n E extends ElementsDefinition,\n>(tastyOptions: TastyProps<K, V, E>) {\n const {\n as: originalAs = 'div',\n element: defaultElement,\n styles: defaultStyles,\n styleProps,\n variants,\n tokens: defaultTokens,\n elements,\n ...defaultProps\n } = tastyOptions;\n\n // Pre-compute merged styles for each variant (if variants are defined)\n // This avoids creating separate component instances per variant\n let variantStylesMap: Record<string, Styles | undefined> | undefined;\n if (variants) {\n // Split defaultStyles: extend-mode state maps (no '' key, non-selector)\n // are pulled out and applied AFTER variant merge so they survive\n // replace-mode maps in variants.\n let baseStyles = defaultStyles;\n let extensionStyles: Styles | undefined;\n\n if (defaultStyles) {\n for (const key of Object.keys(defaultStyles)) {\n if (isSelector(key)) continue;\n\n const value = (defaultStyles as Record<string, unknown>)[key];\n\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !('' in value)\n ) {\n if (!extensionStyles) {\n baseStyles = { ...defaultStyles } as Styles;\n extensionStyles = {} as Styles;\n }\n (extensionStyles as Record<string, unknown>)[key] = value;\n delete (baseStyles as Record<string, unknown>)[key];\n }\n }\n }\n\n const variantEntries = Object.entries(variants) as [string, Styles][];\n variantStylesMap = variantEntries.reduce(\n (map, [variant, variantStyles]) => {\n map[variant] = extensionStyles\n ? mergeStyles(baseStyles, variantStyles, extensionStyles)\n : mergeStyles(baseStyles, variantStyles);\n return map;\n },\n {} as Record<string, Styles | undefined>,\n );\n // Ensure 'default' variant always exists\n if (!variantStylesMap['default']) {\n variantStylesMap['default'] = defaultStyles;\n }\n }\n\n const {\n qa: defaultQa,\n qaVal: defaultQaVal,\n ...otherDefaultProps\n } = defaultProps ?? {};\n\n const _TastyComponent = forwardRef<\n unknown,\n AllBasePropsWithMods<K> & WithVariant<V>\n >((allProps, ref) => {\n const {\n as,\n styles: rawStyles,\n variant,\n mods,\n element,\n qa,\n qaVal,\n className: userClassName,\n tokens,\n style,\n ...otherProps\n } = allProps as Record<string, unknown> as AllBasePropsWithMods<K> &\n WithVariant<V> & {\n className?: string;\n tokens?: Tokens;\n style?: Record<string, unknown>;\n };\n\n let styles = rawStyles;\n\n // Optimize propStyles extraction - avoid creating empty objects\n let propStyles: Styles | null = null;\n const propsToCheck = styleProps\n ? (styleProps as StyleList).concat(BASE_STYLES)\n : BASE_STYLES;\n\n for (const prop of propsToCheck) {\n const key = prop as unknown as string;\n\n if (!propStyles) propStyles = {};\n\n if (key in otherProps) {\n (propStyles as any)[key] = (otherProps as any)[key];\n delete (otherProps as any)[key];\n }\n }\n\n if (\n !styles ||\n (styles && Object.keys(styles as Record<string, unknown>).length === 0)\n ) {\n styles = undefined as unknown as Styles;\n }\n\n // Determine base styles: use variant styles if available, otherwise default styles\n const baseStyles = variantStylesMap\n ? (variantStylesMap[(variant as string) || 'default'] ??\n variantStylesMap['default'])\n : defaultStyles;\n\n // Merge base styles with instance styles and prop styles\n const allStyles = useMemo(() => {\n const hasStyles =\n styles && Object.keys(styles as Record<string, unknown>).length > 0;\n const hasPropStyles = propStyles && Object.keys(propStyles).length > 0;\n\n if (!hasStyles && !hasPropStyles) {\n return baseStyles;\n }\n\n return mergeStyles(baseStyles, styles as Styles, propStyles as Styles);\n }, [baseStyles, styles, propStyles]);\n\n // Use the useStyles hook for style generation and injection\n const { className: stylesClassName } = useStyles(allStyles);\n\n // Merge default tokens with instance tokens (instance overrides defaults)\n const tokensKey = stringifyTokens(tokens as Tokens | undefined);\n const mergedTokens = useMemo(() => {\n if (!defaultTokens && !tokens) return undefined;\n if (!defaultTokens) return tokens as Tokens;\n if (!tokens) return defaultTokens;\n return { ...defaultTokens, ...tokens } as Tokens;\n }, [tokensKey]);\n\n // Process merged tokens into inline style properties\n const processedTokenStyle = useMemo(() => {\n return processTokens(mergedTokens);\n }, [mergedTokens]);\n\n // Merge processed tokens with explicit style prop (style has priority)\n const mergedStyle = useMemo(() => {\n if (!processedTokenStyle && !style) return undefined;\n if (!processedTokenStyle) return style;\n if (!style) return processedTokenStyle;\n return { ...processedTokenStyle, ...style };\n }, [processedTokenStyle, style]);\n\n let modProps: Record<string, unknown> | undefined;\n if (mods) {\n const modsObject = mods as unknown as Record<string, unknown>;\n modProps = modAttrs(modsObject as any) as Record<string, unknown>;\n }\n\n // Merge user className with generated className\n const finalClassName = [(userClassName as string) || '', stylesClassName]\n .filter(Boolean)\n .join(' ');\n\n const elementProps = {\n 'data-element': (element as string | undefined) || defaultElement,\n 'data-qa': (qa as string | undefined) || defaultQa,\n 'data-qaval': (qaVal as string | undefined) || defaultQaVal,\n ...(otherDefaultProps as unknown as Record<string, unknown>),\n ...(modProps || {}),\n ...(otherProps as unknown as Record<string, unknown>),\n className: finalClassName,\n style: mergedStyle,\n ref,\n } as Record<string, unknown>;\n\n // Apply the helper to handle is* properties\n handleIsProperties(elementProps);\n\n const renderedElement = createElement(\n (as as string | 'div') ?? originalAs,\n elementProps,\n );\n\n return renderedElement;\n });\n\n _TastyComponent.displayName = `TastyComponent(${\n (defaultProps as any).qa || originalAs\n })`;\n\n // Attach sub-element components if elements are defined\n if (elements) {\n const subElements = Object.entries(elements).reduce(\n (acc, [name, definition]) => {\n acc[name] = createSubElement(\n name,\n definition as SubElementDefinition<keyof JSX.IntrinsicElements>,\n );\n return acc;\n },\n {} as Record<string, ForwardRefExoticComponent<any>>,\n );\n\n return Object.assign(_TastyComponent, subElements);\n }\n\n return _TastyComponent;\n}\n\nexport const Element = tasty({});\n"],"mappings":";;;;;;;;;;;;;;AAyCA,MAAM,wBAAwB,OAAO,QATX;CACxB,YAAY;CACZ,UAAU;CACV,WAAW;CACZ,CAK8D;;;;;AAM/D,SAAS,mBA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