@wirecore/wirelayer-recipes 0.5.0 → 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.
Files changed (134) hide show
  1. package/dist/alert.d.ts +30 -0
  2. package/dist/alert.d.ts.map +1 -1
  3. package/dist/alert.js +8 -0
  4. package/dist/alert.js.map +1 -1
  5. package/dist/app.js +2 -2
  6. package/dist/app.js.map +1 -1
  7. package/dist/button.js +8 -8
  8. package/dist/button.js.map +1 -1
  9. package/dist/card.d.ts +1 -1
  10. package/dist/card.js +1 -1
  11. package/dist/card.js.map +1 -1
  12. package/dist/control-ids.d.ts +10 -0
  13. package/dist/control-ids.d.ts.map +1 -0
  14. package/dist/control-ids.js +15 -0
  15. package/dist/control-ids.js.map +1 -0
  16. package/dist/controls.d.ts +3 -3
  17. package/dist/data.d.ts +70 -0
  18. package/dist/data.d.ts.map +1 -1
  19. package/dist/data.js +20 -0
  20. package/dist/data.js.map +1 -1
  21. package/dist/dev.d.ts +5 -0
  22. package/dist/dev.d.ts.map +1 -1
  23. package/dist/dev.js +13 -0
  24. package/dist/dev.js.map +1 -1
  25. package/dist/editor.d.ts +3 -3
  26. package/dist/extras.d.ts.map +1 -1
  27. package/dist/extras.js +7 -3
  28. package/dist/extras.js.map +1 -1
  29. package/dist/field.d.ts +39 -9
  30. package/dist/field.d.ts.map +1 -1
  31. package/dist/field.js +18 -10
  32. package/dist/field.js.map +1 -1
  33. package/dist/filters.d.ts +3 -3
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5 -4
  37. package/dist/index.js.map +1 -1
  38. package/dist/inputs.d.ts +57 -0
  39. package/dist/inputs.d.ts.map +1 -1
  40. package/dist/inputs.js +77 -40
  41. package/dist/inputs.js.map +1 -1
  42. package/dist/list-items.d.ts +8 -0
  43. package/dist/list-items.d.ts.map +1 -1
  44. package/dist/list-items.js +16 -2
  45. package/dist/list-items.js.map +1 -1
  46. package/dist/media.d.ts +24 -0
  47. package/dist/media.d.ts.map +1 -1
  48. package/dist/media.js +15 -0
  49. package/dist/media.js.map +1 -1
  50. package/dist/native/controls.d.ts +18 -0
  51. package/dist/native/controls.d.ts.map +1 -1
  52. package/dist/native/controls.js +4 -0
  53. package/dist/native/controls.js.map +1 -1
  54. package/dist/native/data.d.ts +90 -0
  55. package/dist/native/data.d.ts.map +1 -1
  56. package/dist/native/data.js +23 -0
  57. package/dist/native/data.js.map +1 -1
  58. package/dist/native/display.d.ts +128 -32
  59. package/dist/native/display.d.ts.map +1 -1
  60. package/dist/native/display.js +27 -0
  61. package/dist/native/display.js.map +1 -1
  62. package/dist/native/form.d.ts +30 -0
  63. package/dist/native/form.d.ts.map +1 -1
  64. package/dist/native/form.js +8 -0
  65. package/dist/native/form.js.map +1 -1
  66. package/dist/native/overlay.d.ts +30 -0
  67. package/dist/native/overlay.d.ts.map +1 -1
  68. package/dist/native/overlay.js +10 -0
  69. package/dist/native/overlay.js.map +1 -1
  70. package/dist/native/widgets.d.ts +3 -3
  71. package/dist/navigation.d.ts +117 -3
  72. package/dist/navigation.d.ts.map +1 -1
  73. package/dist/navigation.js +64 -8
  74. package/dist/navigation.js.map +1 -1
  75. package/dist/overlay.d.ts +66 -0
  76. package/dist/overlay.d.ts.map +1 -1
  77. package/dist/overlay.js +20 -2
  78. package/dist/overlay.js.map +1 -1
  79. package/dist/overrides.d.ts +27 -2
  80. package/dist/overrides.d.ts.map +1 -1
  81. package/dist/overrides.js +100 -11
  82. package/dist/overrides.js.map +1 -1
  83. package/dist/sources/alert.css +1 -1
  84. package/dist/sources/button.css +1 -1
  85. package/dist/sources/card.css +1 -1
  86. package/dist/sources/colorPicker.css +1 -1
  87. package/dist/sources/combobox.css +1 -1
  88. package/dist/sources/dataTable.css +1 -1
  89. package/dist/sources/datePicker.css +1 -1
  90. package/dist/sources/dialog.css +1 -1
  91. package/dist/sources/drawer.css +1 -1
  92. package/dist/sources/iconButton.css +1 -1
  93. package/dist/sources/input.css +1 -1
  94. package/dist/sources/multiSelect.css +1 -1
  95. package/dist/sources/nativeSelect.css +1 -1
  96. package/dist/sources/numberInput.css +1 -1
  97. package/dist/sources/passwordInput.css +1 -1
  98. package/dist/sources/progress.css +1 -1
  99. package/dist/sources/select.css +1 -1
  100. package/dist/sources/slider.css +1 -1
  101. package/dist/sources/tagsInput.css +1 -1
  102. package/dist/sources/textarea.css +1 -1
  103. package/dist/utils.d.ts +9 -0
  104. package/dist/utils.d.ts.map +1 -1
  105. package/dist/utils.js +24 -0
  106. package/dist/utils.js.map +1 -1
  107. package/dist/vite.d.ts +19 -0
  108. package/dist/vite.d.ts.map +1 -0
  109. package/dist/vite.js +161 -0
  110. package/dist/vite.js.map +1 -0
  111. package/package.json +15 -2
  112. package/src/alert.ts +8 -0
  113. package/src/app.ts +2 -2
  114. package/src/button.ts +8 -8
  115. package/src/card.ts +1 -1
  116. package/src/control-ids.ts +21 -0
  117. package/src/data.ts +24 -0
  118. package/src/dev.ts +14 -0
  119. package/src/extras.ts +7 -3
  120. package/src/field.ts +18 -10
  121. package/src/index.ts +8 -2
  122. package/src/inputs.ts +81 -40
  123. package/src/list-items.ts +21 -0
  124. package/src/media.ts +15 -0
  125. package/src/native/controls.ts +4 -0
  126. package/src/native/data.ts +23 -0
  127. package/src/native/display.ts +27 -0
  128. package/src/native/form.ts +8 -0
  129. package/src/native/overlay.ts +10 -0
  130. package/src/navigation.ts +66 -8
  131. package/src/overlay.ts +20 -2
  132. package/src/overrides.ts +130 -15
  133. package/src/utils.ts +22 -0
  134. package/src/vite.ts +162 -0
package/src/navigation.ts CHANGED
@@ -67,7 +67,7 @@ export const select = tv({
67
67
  slots: {
68
68
  base: 'flex w-full flex-col',
69
69
  trigger: [
70
- 'flex h-10 w-full cursor-pointer items-center justify-between gap-2.5 rounded-lg border border-line-strong bg-bg pe-2.5 ps-3 text-start text-[15px] text-fg',
70
+ 'flex h-[var(--wc-control-h-md,2.5rem)] w-full cursor-pointer items-center justify-between gap-2.5 rounded-[var(--wc-control-radius-md,0.5rem)] border border-line-strong bg-bg pe-2.5 ps-3 text-start text-[length:var(--wc-control-text-md,15px)] text-fg',
71
71
  'outline-none transition-colors motion-reduce:transition-none focus-visible:border-primary data-[state=open]:border-primary',
72
72
  'data-invalid:border-danger data-disabled:cursor-not-allowed data-disabled:border-line data-disabled:bg-bg-2 data-disabled:text-muted',
73
73
  ],
@@ -90,9 +90,15 @@ export const select = tv({
90
90
  },
91
91
  variants: {
92
92
  size: {
93
- sm: { trigger: 'h-8 rounded-md ps-2.5 pe-2 text-[13px]' },
93
+ sm: {
94
+ trigger:
95
+ 'h-[var(--wc-control-h-sm,2rem)] rounded-[var(--wc-control-radius-sm,0.375rem)] ps-2.5 pe-2 text-[length:var(--wc-control-text-sm,13px)]',
96
+ },
94
97
  md: {},
95
- lg: { trigger: 'h-12 rounded-[10px] ps-4 pe-3 text-base' },
98
+ lg: {
99
+ trigger:
100
+ 'h-[var(--wc-control-h-lg,3rem)] rounded-[var(--wc-control-radius-lg,10px)] ps-4 pe-3 text-[length:var(--wc-control-text-lg,1rem)] leading-normal',
101
+ },
96
102
  },
97
103
  // Room for the clear button between value and arrow
98
104
  clearable: {
@@ -234,8 +240,32 @@ export const progress = tv({
234
240
  legendItem: 'flex items-center gap-1.5',
235
241
  swatch: 'size-2 shrink-0 rounded-full',
236
242
  legendValue: 'text-muted tabular-nums',
243
+ /** Text in the bar (`barText`) over the empty part */
244
+ barText: [
245
+ 'pointer-events-none absolute inset-0 flex items-center justify-center overflow-hidden px-1.5',
246
+ 'font-mono text-[10.5px] leading-none whitespace-nowrap text-fg tabular-nums',
247
+ ],
248
+ /** The same text in the range, as wide as the track (100cqw) and cut by the range – in the colour for the fill */
249
+ barTextFill: [
250
+ 'pointer-events-none absolute inset-y-0 start-0 flex w-[100cqw] items-center justify-center px-1.5',
251
+ 'font-mono text-[10.5px] leading-none whitespace-nowrap text-on-primary tabular-nums',
252
+ 'forced-colors:text-[HighlightText]',
253
+ ],
237
254
  },
238
255
  variants: {
256
+ /** `xs`: a thin bar with small text, e.g. in a list or a status bar */
257
+ size: {
258
+ xs: { base: 'gap-1', header: 'text-[10px]', track: 'h-1' },
259
+ md: {},
260
+ },
261
+ /** The label only names the bar for screen readers; the value stays at the end */
262
+ hideLabel: {
263
+ true: { header: 'justify-end' },
264
+ },
265
+ /** Text in the bar: a taller track, the range covers the text below and cuts the text in it */
266
+ hasText: {
267
+ true: { track: 'relative @container h-4', range: 'relative overflow-hidden' },
268
+ },
239
269
  /** Vertical bar: grows from the bottom (fill the height of the parent) */
240
270
  orientation: {
241
271
  horizontal: {},
@@ -265,19 +295,47 @@ export const progress = tv({
265
295
  animated: {
266
296
  true: { range: 'motion-safe:animate-progress-stripes', segment: 'motion-safe:animate-progress-stripes' },
267
297
  },
268
- /** Colour of a segment */
298
+ /** Colour of a segment – and of the filled part (`status`) */
269
299
  color: {
270
300
  primary: { segment: 'bg-primary', swatch: 'bg-primary' },
271
- info: { segment: 'bg-info', swatch: 'bg-info' },
272
- success: { segment: 'bg-success', swatch: 'bg-success' },
273
- warn: { segment: 'bg-warn', swatch: 'bg-warn' },
274
- danger: { segment: 'bg-danger', swatch: 'bg-danger' },
301
+ info: {
302
+ segment: 'bg-info',
303
+ swatch: 'bg-info',
304
+ range: 'bg-info',
305
+ step: 'data-[state=complete]:bg-info',
306
+ barTextFill: 'text-on-info',
307
+ },
308
+ success: {
309
+ segment: 'bg-success',
310
+ swatch: 'bg-success',
311
+ range: 'bg-success',
312
+ step: 'data-[state=complete]:bg-success',
313
+ barTextFill: 'text-on-success',
314
+ },
315
+ warn: {
316
+ segment: 'bg-warn',
317
+ swatch: 'bg-warn',
318
+ range: 'bg-warn',
319
+ step: 'data-[state=complete]:bg-warn',
320
+ barTextFill: 'text-on-warn',
321
+ },
322
+ danger: {
323
+ segment: 'bg-danger',
324
+ swatch: 'bg-danger',
325
+ range: 'bg-danger',
326
+ step: 'data-[state=complete]:bg-danger',
327
+ barTextFill: 'text-on-danger',
328
+ },
275
329
  muted: { segment: 'bg-muted', swatch: 'bg-muted' },
276
330
  },
277
331
  },
332
+ compoundVariants: [
333
+ { size: 'xs', hasText: true, class: { track: 'h-3.5', barText: 'text-[10px]', barTextFill: 'text-[10px]' } },
334
+ ],
278
335
  defaultVariants: {
279
336
  orientation: 'horizontal',
280
337
  color: 'primary',
338
+ size: 'md',
281
339
  },
282
340
  });
283
341
 
package/src/overlay.ts CHANGED
@@ -96,7 +96,7 @@ export type DialogStatus = 'neutral' | 'success' | 'info' | 'warn' | 'danger';
96
96
  export const dialog = tv({
97
97
  slots: {
98
98
  backdrop: [
99
- 'fixed inset-0 z-50 bg-black/60',
99
+ 'fixed inset-0 z-50 bg-[var(--wc-backdrop,rgb(0_0_0/0.6))]',
100
100
  'motion-safe:data-[state=open]:animate-fade-in motion-safe:data-[state=closed]:animate-fade-out',
101
101
  ],
102
102
  positioner: 'fixed inset-0 z-50 flex items-center justify-center overflow-y-auto p-4',
@@ -126,6 +126,20 @@ export const dialog = tv({
126
126
  maximizeIcon: 'size-4',
127
127
  },
128
128
  variants: {
129
+ /** The title only for screen readers – it still names the dialog */
130
+ hideTitle: {
131
+ true: { title: 'sr-only' },
132
+ },
133
+ /** `titlePosition: 'header'`: the title in the row of the close button (a smaller icon before it), as on the Drawer */
134
+ titleInHeader: {
135
+ true: {
136
+ header: 'border-b border-line pb-3',
137
+ iconBox: 'size-7 shrink-0 rounded-lg',
138
+ icon: 'size-4',
139
+ title: 'min-w-0 flex-1 text-base break-words',
140
+ body: 'pt-4',
141
+ },
142
+ },
129
143
  status: {
130
144
  neutral: { iconBox: 'bg-line text-fg' },
131
145
  success: { iconBox: 'bg-success/14 text-success' },
@@ -189,7 +203,7 @@ const drawerSizes: OverlaySize[] = ['sm', 'md', 'lg', 'xl', 'full'];
189
203
  export const drawer = tv({
190
204
  slots: {
191
205
  backdrop: [
192
- 'fixed inset-0 z-50 bg-black/60',
206
+ 'fixed inset-0 z-50 bg-[var(--wc-backdrop,rgb(0_0_0/0.6))]',
193
207
  'motion-safe:data-[state=open]:animate-fade-in motion-safe:data-[state=closed]:animate-fade-out',
194
208
  ],
195
209
  positioner: 'fixed inset-0 z-50 flex',
@@ -210,6 +224,10 @@ export const drawer = tv({
210
224
  footer: 'flex flex-wrap justify-end gap-2 border-t border-line px-5 py-3',
211
225
  },
212
226
  variants: {
227
+ /** The title only for screen readers – it still names the drawer */
228
+ hideTitle: {
229
+ true: { title: 'sr-only' },
230
+ },
213
231
  placement: {
214
232
  right: {
215
233
  positioner: 'justify-end',
package/src/overrides.ts CHANGED
@@ -13,12 +13,28 @@ type Variants<R extends AnyRecipe> = NonNullable<Parameters<R>[0]>;
13
13
  export type RecipeSlot<R extends AnyRecipe> = ReturnType<R> extends string ? 'base' : keyof ReturnType<R> & string;
14
14
  /** Extra classes per part, e.g. `{ base: 'rounded-none', icon: 'text-primary' }` */
15
15
  export type RecipeClasses<R extends AnyRecipe> = Partial<Record<RecipeSlot<R>, ClassValue>>;
16
+ /** Names of the variants of a recipe (`size`, `invalid` …) */
17
+ export type RecipeVariantName<R extends AnyRecipe> = Exclude<keyof Variants<R>, 'class' | 'className'> & string;
18
+ /** The values of a variant as the recipe writes them: `'sm' | 'md'`, `'true' | 'false'` for a flag */
19
+ type ValueKey<V> = V extends boolean ? 'true' | 'false' : V extends string | number ? `${V}` : never;
20
+ /** Extra classes per part for single values of a variant, e.g. `{ size: { md: { base: 'h-11' } } }` */
21
+ export type RecipeVariantClasses<R extends AnyRecipe> = {
22
+ [K in RecipeVariantName<R>]?: { [V in ValueKey<NonNullable<Variants<R>[K]>>]?: RecipeClasses<R> };
23
+ };
24
+ /** Extra classes per part when all the given variants match, e.g. `{ size: 'md', shape: 'rounded', classes: … }` */
25
+ export type RecipeCompoundClasses<R extends AnyRecipe> = {
26
+ [K in RecipeVariantName<R>]?: NonNullable<Variants<R>[K]> | NonNullable<Variants<R>[K]>[];
27
+ } & { classes: RecipeClasses<R> };
16
28
 
17
29
  /** Defaults and classes for one recipe */
18
30
  export interface RecipeOverride<R extends AnyRecipe = AnyRecipe> {
19
31
  /** Variants used when a component does not set them, e.g. `{ size: 'sm' }` */
20
32
  defaultVariants?: Partial<Omit<Variants<R>, 'class' | 'className'>>;
21
33
  classes?: RecipeClasses<R>;
34
+ /** Classes per part for single values of a variant, e.g. `{ size: { md: { base: 'h-11' } } }` */
35
+ variants?: RecipeVariantClasses<R>;
36
+ /** Classes per part for combinations of variants, e.g. `[{ size: 'md', shape: 'rounded', classes: … }]` */
37
+ compoundVariants?: RecipeCompoundClasses<R>[];
22
38
  }
23
39
 
24
40
  /** Overrides by recipe name (the export name: `button`, `iconButton`, `dataTable` …) */
@@ -32,7 +48,10 @@ export type RecipeName = {
32
48
  /** Typed overrides for RecipesProvider: variants and part names per recipe */
33
49
  export type RecipeConfig = { [K in RecipeName]?: RecipeOverride<Extract<Exports[K], AnyRecipe>> };
34
50
 
35
- /** Inner overrides win: defaults per variant, classes per part are joined (later ones win in tailwind-merge) */
51
+ /**
52
+ * Inner overrides win: defaults per variant, classes per part (also per variant value) are joined and compound
53
+ * variants appended – later ones win in tailwind-merge
54
+ */
36
55
  export function mergeRecipeOverrides(outer: RecipeOverrides, inner: RecipeOverrides): RecipeOverrides {
37
56
  const merged: RecipeOverrides = { ...outer };
38
57
  for (const [name, override] of Object.entries(inner)) {
@@ -42,12 +61,28 @@ export function mergeRecipeOverrides(outer: RecipeOverrides, inner: RecipeOverri
42
61
  ? {
43
62
  defaultVariants: { ...before.defaultVariants, ...override.defaultVariants },
44
63
  classes: joinClasses(before.classes, override.classes),
64
+ variants: joinVariants(before.variants, override.variants),
65
+ compoundVariants: [...(before.compoundVariants ?? []), ...(override.compoundVariants ?? [])],
45
66
  }
46
67
  : override;
47
68
  }
48
69
  return merged;
49
70
  }
50
71
 
72
+ type VariantClasses = Record<string, Record<string, Record<string, ClassValue> | undefined> | undefined>;
73
+
74
+ function joinVariants(first: VariantClasses | undefined, second: VariantClasses | undefined) {
75
+ if (!first) return second;
76
+ if (!second) return first;
77
+ const joined: VariantClasses = { ...first };
78
+ for (const [variant, values] of Object.entries(second)) {
79
+ const all = { ...joined[variant] };
80
+ for (const [value, classes] of Object.entries(values ?? {})) all[value] = joinClasses(all[value], classes);
81
+ joined[variant] = all;
82
+ }
83
+ return joined;
84
+ }
85
+
51
86
  function joinClasses(
52
87
  first: Record<string, ClassValue> | undefined,
53
88
  second: Record<string, ClassValue> | undefined
@@ -59,34 +94,114 @@ function joinClasses(
59
94
  return joined;
60
95
  }
61
96
 
97
+ /**
98
+ * Variants that are states: with classes for a part, the classes of an active state are added again after them – a
99
+ * changed border keeps the red of an invalid field. The class passed to the part comes last and still wins.
100
+ */
101
+ const STATE_VARIANTS = new Set([
102
+ 'invalid',
103
+ 'success',
104
+ 'disabled',
105
+ 'readOnly',
106
+ 'current',
107
+ 'selected',
108
+ 'checked',
109
+ 'loading',
110
+ ]);
111
+
112
+ type PartClasses = Record<string, ClassValue[]>;
113
+ /** A recipe (tv: `class` per value, a string for the base part) or an override (`classes` per part) */
114
+ interface VariantSource {
115
+ classes?: Record<string, ClassValue>;
116
+ variants?: Record<string, Record<string, unknown> | undefined>;
117
+ compoundVariants?: Record<string, unknown>[];
118
+ defaultVariants?: Record<string, unknown>;
119
+ }
120
+
121
+ /** Adds classes of a variant (a class value for the base part or classes per part) */
122
+ function addClasses(into: PartClasses, value: unknown) {
123
+ if (value === undefined || value === null || value === '') return;
124
+ if (typeof value === 'string' || Array.isArray(value)) (into.base ??= []).push(value as ClassValue);
125
+ else
126
+ for (const [slot, classes] of Object.entries(value as Record<string, ClassValue>))
127
+ (into[slot] ??= []).push(classes);
128
+ }
129
+
130
+ const matches = (value: unknown, condition: unknown) =>
131
+ Array.isArray(condition)
132
+ ? condition.some((item) => String(item) === String(value))
133
+ : String(condition) === String(value);
134
+
135
+ /**
136
+ * Adds the classes of the matching variant values and compound variants of `source` – either those of states (a state
137
+ * variant, or a compound variant with one) or all others
138
+ */
139
+ function addMatching(into: PartClasses, source: VariantSource, active: Record<string, unknown>, states: boolean) {
140
+ for (const [name, values] of Object.entries(source.variants ?? {})) {
141
+ if (STATE_VARIANTS.has(name) === states && active[name] !== undefined)
142
+ addClasses(into, values?.[String(active[name])]);
143
+ }
144
+ for (const { class: value, className, classes, ...conditions } of source.compoundVariants ?? []) {
145
+ const names = Object.keys(conditions);
146
+ if (names.some((name) => STATE_VARIANTS.has(name)) !== states) continue;
147
+ if (names.every((name) => matches(active[name], conditions[name])))
148
+ addClasses(into, classes ?? value ?? className);
149
+ }
150
+ return into;
151
+ }
152
+
153
+ const defined = (props: Record<string, unknown>) =>
154
+ Object.fromEntries(Object.entries(props).filter(([, value]) => value !== undefined));
155
+
62
156
  /**
63
157
  * The recipe with the overrides applied, outer first: provider defaults fill the variants a component left open
64
- * (explicit values win), classes are added to their part before the class the component passes for it.
158
+ * (explicit values win). Each part then gets, in this order: the override classes, the override classes of matching
159
+ * variant values and compound variants, the classes of the active states (see STATE_VARIANTS), the override classes
160
+ * of those states – and last the class the component passes for it.
65
161
  */
66
162
  export function withRecipeOverrides<R extends AnyRecipe>(recipe: R, overrides: (RecipeOverride | undefined)[]): R {
67
- const active = overrides.filter((override): override is RecipeOverride => !!override);
163
+ const active = overrides.filter((override): override is RecipeOverride => !!override) as VariantSource[];
68
164
  if (active.length === 0) return recipe;
69
165
  const defaults = Object.assign({}, ...active.map((override) => override.defaultVariants));
70
- const classes = active.reduce<Record<string, ClassValue> | undefined>(
71
- (all, override) => joinClasses(all, override.classes as Record<string, ClassValue> | undefined),
72
- undefined
73
- );
166
+ const styled = active.some((override) => override.classes || override.variants || override.compoundVariants);
167
+ const own = recipe as unknown as VariantSource;
168
+ /** Classes for the parts with the given variants: undefined for a part without overrides */
169
+ const partClasses = (variants: Record<string, unknown>) => {
170
+ const current = { ...own.defaultVariants, ...variants };
171
+ const look: PartClasses = {};
172
+ const states: PartClasses = {};
173
+ for (const override of active) {
174
+ addClasses(look, override.classes);
175
+ addMatching(look, override, current, false);
176
+ }
177
+ for (const override of active) addMatching(states, override, current, true);
178
+ const recipeStates = addMatching({}, own, current, true);
179
+ return (slot: string) =>
180
+ look[slot] || states[slot] ? [look[slot], recipeStates[slot], states[slot]] : undefined;
181
+ };
74
182
  return ((props: Record<string, unknown> = {}) => {
75
- const given = Object.fromEntries(Object.entries(props).filter(([, value]) => value !== undefined));
183
+ const given = defined(props);
76
184
  const variants = { ...defaults, ...given };
77
- if (!classes) return recipe(variants);
185
+ if (!styled) return recipe(variants);
78
186
  const result = recipe(variants);
79
187
  // Recipes without parts: the classes join the class of the call
80
- if (typeof result === 'string') return recipe({ ...variants, class: [classes.base, given.class] });
81
- // Slot recipes: every part gets its classes before the class passed for it
188
+ if (typeof result === 'string') {
189
+ const classes = partClasses(variants)('base');
190
+ return classes ? recipe({ ...variants, class: [classes, given.class] }) : result;
191
+ }
192
+ // Slot recipes: the parts with overrides get them (with variants passed to the part as well)
193
+ const forCall = partClasses(variants);
82
194
  return Object.fromEntries(
83
195
  Object.entries(result as Record<string, (slotProps?: Record<string, unknown>) => string>).map(
84
196
  ([slot, part]) => [
85
197
  slot,
86
- classes[slot]
87
- ? (slotProps: Record<string, unknown> = {}) =>
88
- part({ ...slotProps, class: [classes[slot], slotProps.class] })
89
- : part,
198
+ (slotProps: Record<string, unknown> = {}) => {
199
+ const passed = defined(slotProps);
200
+ const classes = Object.keys(passed).some((key) => key !== 'class' && key !== 'className')
201
+ ? partClasses({ ...variants, ...passed })(slot)
202
+ : forCall(slot);
203
+ return classes ? part({ ...slotProps, class: [classes, slotProps.class] }) : part(slotProps);
204
+ },
90
205
  ]
91
206
  )
92
207
  );
package/src/utils.ts CHANGED
@@ -867,3 +867,25 @@ export function highlightFirstMenuItem(
867
867
  if (first) menu.setHighlightedValue(first.dataset.value ?? '');
868
868
  return first?.id;
869
869
  }
870
+
871
+ /**
872
+ * Closes an open menu on what it does not follow: the page scrolling (not a scroll inside a menu), the window being
873
+ * resized or losing the focus (switching to another window). Returns the cleanup. Browser only.
874
+ */
875
+ export function closeMenuOnPageEvents(
876
+ close: () => void,
877
+ events: { scroll?: boolean; resize?: boolean; blur?: boolean }
878
+ ): () => void {
879
+ const onScroll = (event: Event) => {
880
+ if (event.target instanceof Element && event.target.closest('[data-scope=menu]')) return;
881
+ close();
882
+ };
883
+ const listeners: [string, EventListener, AddEventListenerOptions][] = [];
884
+ if (events.scroll) listeners.push(['scroll', onScroll, { capture: true, passive: true }]);
885
+ if (events.resize) listeners.push(['resize', close, {}]);
886
+ if (events.blur) listeners.push(['blur', close, {}]);
887
+ for (const [type, listener, options] of listeners) window.addEventListener(type, listener, options);
888
+ return () => {
889
+ for (const [type, listener, options] of listeners) window.removeEventListener(type, listener, options);
890
+ };
891
+ }
package/src/vite.ts ADDED
@@ -0,0 +1,162 @@
1
+ /// <reference types="node" />
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, extname, join, relative } from 'node:path';
5
+ import type { Plugin, ViteDevServer } from 'vite';
6
+
7
+ // Vite plugin: adds the sources files of the WireLayer components and recipes an app imports to its CSS, so only their
8
+ // classes end up in it (instead of all of them with styles.css). Node only – @wirecore/wirelayer-recipes/vite.
9
+
10
+ export interface WireLayerSourcesOptions {
11
+ /** Folders searched for imports, relative to the Vite root (default: the root) */
12
+ include?: string[];
13
+ /** Folder names skipped while searching (default: node_modules, dist and the build folders of Nuxt, Next, Astro) */
14
+ exclude?: string[];
15
+ }
16
+
17
+ const PACKAGES = ['vue', 'react', 'blocks-vue', 'blocks-react', 'recipes'].map((name) => `@wirecore/wirelayer-${name}`);
18
+ /** The CSS file that gets the imports: the one importing the theme without component classes */
19
+ const ENTRY = /@import\s+['"]@wirecore\/wirelayer-(?:vue|react)\/(?:theme|styles-core)\.css['"]/;
20
+ const IMPORT =
21
+ /(?:import|export)\s+(type\s+)?(\{[^}]*\}|\*\s+as\s+\w+)\s+from\s+['"](@wirecore\/wirelayer-[\w-]+)(?:\/[\w-]+)?['"]/g;
22
+ const SOURCE_FILES = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.mts', '.astro', '.mdx', '.svelte']);
23
+ const SKIPPED = ['node_modules', 'dist', '.git', '.nuxt', '.output', '.next', '.astro', '.vercel', 'storybook-static'];
24
+
25
+ /** Names imported from the WireLayer packages, by package; `*` for a namespace import (`import * as W`) */
26
+ export function findImports(code: string, found = new Map<string, Set<string>>()) {
27
+ for (const [, typeOnly, names, pkg] of code.matchAll(IMPORT)) {
28
+ if (typeOnly || !PACKAGES.includes(pkg!)) continue;
29
+ const set = found.get(pkg!) ?? new Set<string>();
30
+ found.set(pkg!, set);
31
+ if (names!.startsWith('*')) {
32
+ set.add('*');
33
+ continue;
34
+ }
35
+ for (const part of names!.slice(1, -1).split(',')) {
36
+ const name = part.trim().split(/\s+as\s+/)[0]!;
37
+ if (name && !name.startsWith('type ')) set.add(name);
38
+ }
39
+ }
40
+ return found;
41
+ }
42
+
43
+ /** The sources files (absolute paths) for the imported names – names without one (helpers, types) are skipped */
44
+ export function sourcesFiles(imports: Map<string, Set<string>>, root: string) {
45
+ const require = createRequire(join(root, 'package.json'));
46
+ const files = new Set<string>();
47
+ for (const [pkg, names] of imports) {
48
+ const folder = sourcesFolder(require, pkg);
49
+ if (!folder) continue;
50
+ if (!existsSync(folder)) continue;
51
+ const wanted = names.has('*') ? readdirSync(folder).map((file) => file.slice(0, -4)) : [...names];
52
+ for (const name of wanted) {
53
+ const file = join(folder, `${name}.css`);
54
+ if (existsSync(file)) files.add(file);
55
+ }
56
+ }
57
+ return [...files].sort();
58
+ }
59
+
60
+ /** dist/sources of an installed package: up from its main entry to the folder of its package.json */
61
+ function sourcesFolder(require: NodeJS.Require, pkg: string) {
62
+ let folder: string;
63
+ try {
64
+ folder = dirname(require.resolve(pkg));
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ while (!existsSync(join(folder, 'package.json'))) {
69
+ const parent = dirname(folder);
70
+ if (parent === folder) return undefined;
71
+ folder = parent;
72
+ }
73
+ return join(folder, 'dist/sources');
74
+ }
75
+
76
+ function sourceFilesIn(folder: string, skipped: Set<string>, out: string[] = []) {
77
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
78
+ if (entry.isDirectory()) {
79
+ if (!skipped.has(entry.name)) sourceFilesIn(join(folder, entry.name), skipped, out);
80
+ } else if (SOURCE_FILES.has(extname(entry.name))) out.push(join(folder, entry.name));
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * Vite plugin for smaller CSS: imports the sources files of the components and recipes used in the app into the CSS
87
+ * file that imports `@wirecore/wirelayer-vue/theme.css` (or `styles-core.css`; the same for React). Put it before
88
+ * Tailwind's plugin. Components that are registered globally or imported automatically are not found – the warning
89
+ * "classes … are missing" names them in development; import their sources files by hand.
90
+ */
91
+ export function wirelayer(options: WireLayerSourcesOptions = {}): Plugin {
92
+ let root = process.cwd();
93
+ const skipped = new Set(options.exclude ?? SKIPPED);
94
+ /** Imports per source file, so a changed file is read again on its own */
95
+ const perFile = new Map<string, Map<string, Set<string>>>();
96
+ let imports = '';
97
+ const entries = new Set<string>();
98
+
99
+ const read = (file: string) => {
100
+ try {
101
+ perFile.set(file, findImports(readFileSync(file, 'utf8')));
102
+ } catch {
103
+ perFile.delete(file);
104
+ }
105
+ };
106
+ const collect = () => {
107
+ const all = new Map<string, Set<string>>();
108
+ for (const found of perFile.values())
109
+ for (const [pkg, names] of found) all.set(pkg, new Set([...(all.get(pkg) ?? []), ...names]));
110
+ return sourcesFiles(all, root)
111
+ .map((file) => `@import '${file.replaceAll('\\', '/')}';`)
112
+ .join('\n');
113
+ };
114
+ const scan = () => {
115
+ perFile.clear();
116
+ for (const folder of options.include ?? ['.']) {
117
+ const path = join(root, folder);
118
+ if (existsSync(path) && statSync(path).isDirectory())
119
+ for (const file of sourceFilesIn(path, skipped)) read(file);
120
+ }
121
+ imports = collect();
122
+ };
123
+
124
+ return {
125
+ name: 'wirelayer-sources',
126
+ enforce: 'pre',
127
+ configResolved(config) {
128
+ root = config.root;
129
+ },
130
+ buildStart() {
131
+ scan();
132
+ },
133
+ transform(code, id) {
134
+ const entry = id.split('?')[0]!.endsWith('.css') ? ENTRY.exec(code) : null;
135
+ if (!entry) return;
136
+ entries.add(id);
137
+ // Right after the theme import – @import rules come before all others
138
+ const end = code.indexOf(';', entry.index) + 1;
139
+ return {
140
+ code: `${code.slice(0, end)}\n/* added by wirelayer() */\n${imports}\n${code.slice(end)}`,
141
+ map: null,
142
+ };
143
+ },
144
+ configureServer(server: ViteDevServer) {
145
+ // A new or changed import adds its sources file: the CSS is built again
146
+ const update = (file: string) => {
147
+ if (!SOURCE_FILES.has(extname(file)) || relative(root, file).startsWith('..')) return;
148
+ if ([...skipped].some((name) => file.split(/[\\/]/).includes(name))) return;
149
+ read(file);
150
+ const next = collect();
151
+ if (next === imports) return;
152
+ imports = next;
153
+ for (const id of entries) {
154
+ const module = server.moduleGraph.getModuleById(id);
155
+ if (module) void server.reloadModule(module);
156
+ }
157
+ };
158
+ server.watcher.on('add', update);
159
+ server.watcher.on('change', update);
160
+ },
161
+ };
162
+ }