@theweekendprojects/emvb-daisyui 0.0.0-stage → 0.2.1

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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -2
  3. package/licenses/daisyui-MIT.txt +3 -0
  4. package/package.json +55 -4
  5. package/src/catalog/basic.ts +407 -0
  6. package/src/catalog/class-names.ts +623 -0
  7. package/src/catalog/countdown.ts +392 -0
  8. package/src/catalog/data-display.ts +563 -0
  9. package/src/catalog/forms.ts +433 -0
  10. package/src/catalog/index.ts +77 -0
  11. package/src/catalog/interactive.ts +567 -0
  12. package/src/catalog/layout-marketing.ts +641 -0
  13. package/src/catalog/missing-complex.ts +430 -0
  14. package/src/catalog/missing-primitives.ts +409 -0
  15. package/src/catalog/navigation.ts +438 -0
  16. package/src/catalog/value-class.ts +20 -0
  17. package/src/compatibility/index.ts +104 -0
  18. package/src/compound/editor.ts +299 -0
  19. package/src/compound/index.ts +157 -0
  20. package/src/conformance/cli.ts +9 -0
  21. package/src/conformance/compile.ts +77 -0
  22. package/src/conformance/index.ts +4 -0
  23. package/src/conformance/manifest.ts +39 -0
  24. package/src/conformance/official-inventory.ts +135 -0
  25. package/src/conformance/report-cli.ts +5 -0
  26. package/src/conformance/report.ts +59 -0
  27. package/src/conformance/verify-css.ts +22 -0
  28. package/src/extension/class-token.ts +11 -0
  29. package/src/extension/classes.ts +636 -0
  30. package/src/extension/collect-classes.ts +73 -0
  31. package/src/extension/content.ts +93 -0
  32. package/src/extension/daisy.css +12441 -0
  33. package/src/extension/daisy.js +1 -0
  34. package/src/extension/elements.ts +262 -0
  35. package/src/extension/index.ts +39 -0
  36. package/src/extension/to-output.ts +113 -0
  37. package/src/generator/artifacts.ts +81 -0
  38. package/src/generator/class-names.ts +35 -0
  39. package/src/generator/cli.ts +21 -0
  40. package/src/generator/generate.ts +122 -0
  41. package/src/generator/index.ts +2 -0
  42. package/src/generator/write-class-names.ts +10 -0
  43. package/src/index.ts +12 -0
  44. package/src/render/classes.ts +48 -0
  45. package/src/render/href.ts +19 -0
  46. package/src/render/index.ts +3 -0
  47. package/src/render/provider.ts +37 -0
  48. package/src/renderer.ts +6 -0
  49. package/src/runtime/browser.ts +11 -0
  50. package/src/runtime/index.ts +41 -0
  51. package/src/test-support.ts +13 -0
  52. package/src/themes/index.ts +72 -0
  53. package/src/types.ts +116 -0
  54. package/src/validation/index.ts +153 -0
  55. package/src/verified/primitives.ts +62 -0
@@ -0,0 +1 @@
1
+ (()=>{const q=(id)=>id&&document.getElementById(id);document.addEventListener('click',e=>{const b=e.target.closest('[data-daisy-command]');if(!b)return;const el=q(b.getAttribute('aria-controls'));if(!el)return;const c=b.dataset.daisyCommand;if(c==='show-modal'&&el.showModal){b.dataset.returnFocus='true';el.showModal();const f=el.querySelector('button,[href],input,select,textarea,[tabindex]:not([tabindex="-1"])');f&&f.focus();}if(c==='close'&&el.close)el.close();});document.addEventListener('close',e=>{const d=e.target;if(!(d instanceof HTMLDialogElement))return;const b=document.querySelector('[data-daisy-command="show-modal"][aria-controls="'+CSS.escape(d.id)+'"]');b&&b.focus();},true);document.addEventListener('keydown',e=>{const tab=e.target.closest('[role="tab"]');if(!tab)return;const list=[...tab.closest('[role="tablist"]').querySelectorAll('[role="tab"]')];let i=list.indexOf(tab);if(e.key==='ArrowRight')i=(i+1)%list.length;else if(e.key==='ArrowLeft')i=(i-1+list.length)%list.length;else if(e.key==='Home')i=0;else if(e.key==='End')i=list.length-1;else return;e.preventDefault();list.forEach((x,n)=>{x.tabIndex=n===i?0:-1;x.setAttribute('aria-selected',n===i?'true':'false');const p=q(x.getAttribute('aria-controls'));if(p)p.hidden=n!==i;});list[i].focus();});})();(()=>{const put=(el,n)=>{el.style.setProperty('--daisy-value',n);el.textContent=String(n);};const when=(r)=>{const abs=r.dataset.daisyCountdown;if(abs){const t=Date.parse(abs);return t;}const w=(r.dataset.daisyCountdownLocal||'').split(/[-T:]/).map(Number);if(w.length<5||w.some(Number.isNaN))return NaN;return new Date(w[0],w[1]-1,w[2],w[3],w[4],w[5]||0).getTime();};const tick=()=>{const now=Date.now();document.querySelectorAll('[data-daisy-countdown],[data-daisy-countdown-local]').forEach(r=>{const t=when(r);if(Number.isNaN(t))return;const s=Math.max(0,Math.floor((t-now)/1000));const days=!!r.querySelector('[data-daisy-unit="d"]');const v={d:Math.floor(s/86400),h:days?Math.floor(s%86400/3600):Math.floor(s/3600),m:Math.floor(s%3600/60),s:s%60};r.querySelectorAll('[data-daisy-unit]').forEach(el=>{const n=v[el.dataset.daisyUnit];if(n!==undefined)put(el,Math.min(n,999));});const done=r.querySelector('[data-daisy-done]');if(t<=now&&done){const live=r.querySelector('[data-daisy-live]');if(live)live.classList.add('hidden');done.classList.remove('hidden');r.setAttribute('role','status');}});};const start=()=>{document.querySelectorAll('[data-daisy-value]').forEach(el=>{const n=Number(el.dataset.daisyValue);if(Number.isFinite(n))put(el,n);});if(!document.querySelector('[data-daisy-countdown],[data-daisy-countdown-local]'))return;tick();setInterval(()=>{if(!document.hidden)tick();},1000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)tick();});};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start);else start();})();
@@ -0,0 +1,262 @@
1
+ /**
2
+ * One extension element per daisyUI component (extensionApi 1.x).
3
+ *
4
+ * The element name is `daisy-<component>`. The prefix keeps every name clear of EmVB's built-in
5
+ * element types (`tabs`, `accordion`, `menu`, `carousel`, ... are built in).
6
+ * Rendering reuses the daisyUI renderer, so the markup is the same as before, and the
7
+ * render mode from the core ("editor" or "public") is passed through, so an open modal shows open
8
+ * on the canvas.
9
+ */
10
+ import { COMPOUND_CONFIG } from "../compound/editor.ts";
11
+ import { daisyRenderer } from "../renderer.ts";
12
+ import { safeHref } from "../render/href.ts";
13
+ import type { DaisyComponentDefinition, DaisyFieldDefinition, DaisyVNode } from "../types.ts";
14
+ import { contentChildren, idFor, nodeFor, parseCells, parseItems, type Item } from "./content.ts";
15
+ import { SLOT_TAG } from "./to-output.ts";
16
+
17
+ /** Minimal structural types, so this file needs no runtime import from EmVB core. */
18
+ export type Json = string | number | boolean;
19
+ export type PropSchema =
20
+ | { type: "string"; maxLength?: number; default?: string }
21
+ | { type: "number"; default?: number }
22
+ | { type: "boolean"; default?: boolean }
23
+ | { type: "enum"; values: readonly string[]; default?: string };
24
+ export type FieldOption = { value: string | number | boolean; label: string };
25
+ export type Field = {
26
+ key: string;
27
+ kind: "text" | "textarea" | "number" | "int" | "select" | "boolean" | "href";
28
+ label: string;
29
+ options?: FieldOption[];
30
+ };
31
+ export type VNode = { tag: string; attrs: Record<string, string>; children: (VNode | string)[] };
32
+ export type RenderMode = "public" | "editor";
33
+ export type ExtensionElement = {
34
+ name: string;
35
+ label: string;
36
+ group: "layout" | "content" | "form" | "dynamic";
37
+ schema: { type: "object"; properties: Record<string, PropSchema> };
38
+ fields: Field[];
39
+ /** Holds the author's own elements: its markup has a slot where they go. */
40
+ container?: boolean;
41
+ render: (props: Record<string, unknown>, ctx?: { mode: RenderMode }) => { markup: VNode };
42
+ };
43
+
44
+ const slot = (): DaisyVNode => ({ tag: SLOT_TAG, attrs: {}, children: [] });
45
+
46
+ export const ELEMENT_PREFIX = "daisy-";
47
+ /** Daisy themes a block can set. The empty value inherits the page theme. */
48
+ export const THEMES = ["", "light", "dark", "corporate", "business", "cupcake"] as const;
49
+ const MAX_TEXT_FIELD = 2000;
50
+ const MAX_LONG_FIELD = 4000;
51
+ const ITEMS_FIELD = "items";
52
+ const CONTENT_FIELD = "content";
53
+ const THEME_FIELD = "theme";
54
+ const DEFAULT_MODE: { mode: RenderMode } = { mode: "public" };
55
+
56
+ /** The renderer's VNode, as the extension output type: no undefined attributes. */
57
+ export function toVNode(node: DaisyVNode): VNode {
58
+ const attrs: Record<string, string> = {};
59
+ for (const [key, value] of Object.entries(node.attrs)) {
60
+ // An empty class attribute carries nothing; other empty attributes (alt="") can mean something.
61
+ if (value === undefined || (key === "class" && value === "")) continue;
62
+ attrs[key] = value;
63
+ }
64
+ return {
65
+ tag: node.tag,
66
+ attrs,
67
+ children: node.children.map((child) => (typeof child === "string" ? child : toVNode(child))),
68
+ };
69
+ }
70
+
71
+ /** Rows of a `table` root: each line is one row, its `|` cells are the cells. */
72
+ function tableRows(
73
+ text: string,
74
+ mode: RenderMode,
75
+ ): { nodes: ReturnType<typeof nodeFor>[]; vnodes: DaisyVNode[] } {
76
+ const rows = text
77
+ .split("\n")
78
+ .map((line) => line.trim())
79
+ .filter((line) => line.length > 0)
80
+ .slice(0, 40);
81
+ const nodes: ReturnType<typeof nodeFor>[] = [];
82
+ const vnodes: DaisyVNode[] = [];
83
+ for (const line of rows) {
84
+ const cells = parseCells(line);
85
+ const cellVNodes = cells.map((cell) =>
86
+ daisyRenderer.render(nodeFor("table-cell", { text: cell }), {}, [], { mode }),
87
+ );
88
+ nodes.push(nodeFor("table-row", {}, cells.map((cell) => nodeFor("table-cell", { text: cell }))));
89
+ vnodes.push(daisyRenderer.render(nodeFor("table-row", {}), {}, cellVNodes, { mode }));
90
+ }
91
+ return { nodes, vnodes };
92
+ }
93
+
94
+ /** The item nodes and their rendered children for one compound root. */
95
+ export function itemsFor(
96
+ root: string,
97
+ text: string,
98
+ mode: RenderMode,
99
+ ): { nodes: ReturnType<typeof nodeFor>[]; vnodes: DaisyVNode[] } {
100
+ if (root === "table") return tableRows(text, mode);
101
+ const items: Item[] = parseItems(text);
102
+ const part = COMPOUND_CONFIG[root as keyof typeof COMPOUND_CONFIG]?.part ?? "";
103
+ const nodes: ReturnType<typeof nodeFor>[] = [];
104
+ const vnodes: DaisyVNode[] = [];
105
+ items.forEach((item, index) => {
106
+ const props: Record<string, string | number | boolean> = { label: item.label };
107
+ if (root === "tabs") props.selected = index === 0;
108
+ if (root === "accordion") props.defaultOpen = index === 0;
109
+ if (root === "menu") props.href = item.body || "#";
110
+ const bodyChildren = root === "menu" ? [] : contentChildren(item.body);
111
+ nodes.push(nodeFor(part, props));
112
+ vnodes.push(daisyRenderer.render(nodeFor(part, props), {}, bodyChildren, { mode }));
113
+ });
114
+ return { nodes, vnodes };
115
+ }
116
+
117
+ const GROUP: Record<DaisyComponentDefinition["category"], ExtensionElement["group"]> = {
118
+ Actions: "form",
119
+ "Data display": "content",
120
+ Feedback: "content",
121
+ Layout: "layout",
122
+ Marketing: "content",
123
+ Navigation: "content",
124
+ Interactive: "content",
125
+ };
126
+
127
+ const titleCase = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);
128
+
129
+ // Core drops a field whose label is longer than 80 characters, so these labels stay short.
130
+ const IMAGE_URL_LABEL = "Image URL: in Media, open the image and click Copy URL";
131
+ const IMAGE_URLS_LABEL = "Image URLs, one per line: in Media, open each image and click Copy URL";
132
+
133
+ function fieldFor(field: DaisyFieldDefinition, componentId: string): Field {
134
+ // A media field is an image URL. The editor has no media picker for extension fields, so the
135
+ // label says where the URL comes from.
136
+ if (field.kind === "media") return { key: field.key, kind: "href", label: IMAGE_URL_LABEL };
137
+ if (componentId === "hover-gallery" && field.key === "images") {
138
+ return { key: field.key, kind: "textarea", label: IMAGE_URLS_LABEL };
139
+ }
140
+ const kind =
141
+ field.kind === "textarea" ? "textarea"
142
+ : field.kind === "number" ? "number"
143
+ : field.kind === "boolean" ? "boolean"
144
+ : field.kind === "select" ? "select"
145
+ : field.kind === "href" ? "href"
146
+ : "text";
147
+ const options = field.options?.map((value) => ({
148
+ value,
149
+ label: field.optionLabels?.[value] ?? titleCase(value),
150
+ }));
151
+ return { key: field.key, kind, label: field.label, ...(options ? { options } : {}) };
152
+ }
153
+
154
+ function schemaFor(field: DaisyFieldDefinition): PropSchema {
155
+ if (field.kind === "number") return { type: "number", default: Number(field.default) };
156
+ if (field.kind === "boolean") return { type: "boolean", default: Boolean(field.default) };
157
+ if (field.kind === "select" && field.options && field.options.length > 0) {
158
+ const current = String(field.default);
159
+ return {
160
+ type: "enum",
161
+ values: [...field.options],
162
+ default: field.options.includes(current) ? current : field.options[0],
163
+ };
164
+ }
165
+ const max = field.kind === "textarea" ? MAX_LONG_FIELD : MAX_TEXT_FIELD;
166
+ return { type: "string", maxLength: max, default: String(field.default ?? "") };
167
+ }
168
+
169
+ const THEME_LABELS: Record<string, string> = { "": "Inherit page theme" };
170
+
171
+ /** The extension element for one daisyUI definition. */
172
+ export function elementFor(definition: DaisyComponentDefinition): ExtensionElement {
173
+ const id = definition.id;
174
+ const isRoot = Object.hasOwn(COMPOUND_CONFIG, id);
175
+ // A compound root reads its text from its own textarea (items for menus, slides for carousels).
176
+ const textKey = isRoot ? (definition.fields.find((f) => f.kind === "textarea")?.key ?? ITEMS_FIELD) : ITEMS_FIELD;
177
+ // A container that has its own `content` field (tooltip, collapse, the mockups) draws that text
178
+ // itself, so the generic content lines would draw it a second time.
179
+ const ownsContent = definition.fields.some((field) => field.key === CONTENT_FIELD);
180
+ const extraKey = isRoot ? textKey : definition.container && !ownsContent ? CONTENT_FIELD : undefined;
181
+ const properties: Record<string, PropSchema> = {};
182
+ for (const field of definition.fields) properties[field.key] = schemaFor(field);
183
+ const fields: Field[] = definition.fields.map((field) => fieldFor(field, id));
184
+ if (extraKey) {
185
+ // A compound root already has its items field from the catalog, with its sample text as the
186
+ // default. Keep that default, so a new root starts with the same items the settings panel shows.
187
+ const own = definition.fields.find((field) => field.key === extraKey);
188
+ const ownLabel = fields.find((field) => field.key === extraKey)?.label;
189
+ const label = isRoot
190
+ ? (ownLabel ?? "Items (Label|text per line)")
191
+ : "Content (one block per line)";
192
+ properties[extraKey] = {
193
+ type: "string",
194
+ maxLength: MAX_LONG_FIELD,
195
+ default: own ? String(own.default ?? "") : "",
196
+ };
197
+ const entry: Field = { key: extraKey, kind: "textarea", label };
198
+ const at = fields.findIndex((field) => field.key === extraKey);
199
+ if (at >= 0) fields[at] = entry;
200
+ else fields.push(entry);
201
+ }
202
+ properties[THEME_FIELD] = { type: "enum", values: [...THEMES], default: "" };
203
+ fields.push({
204
+ key: THEME_FIELD,
205
+ kind: "select",
206
+ label: "Theme",
207
+ options: THEMES.map((value) => ({ value, label: THEME_LABELS[value] ?? titleCase(value) })),
208
+ });
209
+ const daisyKeys = new Set(definition.fields.map((field) => field.key));
210
+ // Compound roots take their items as text, so only the other containers take the author's elements.
211
+ const holdsChildren = definition.container === true && !isRoot;
212
+
213
+ return {
214
+ name: `${ELEMENT_PREFIX}${id}`,
215
+ label: definition.label,
216
+ group: GROUP[definition.category],
217
+ schema: { type: "object", properties },
218
+ fields,
219
+ ...(holdsChildren ? { container: true } : {}),
220
+ render: (props, ctx = DEFAULT_MODE) => {
221
+ const mode = ctx.mode;
222
+ const values: Record<string, string | number | boolean> = {};
223
+ for (const key of daisyKeys) {
224
+ const value = props[key];
225
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
226
+ values[key] = value;
227
+ }
228
+ }
229
+ const nodeId = idFor(props);
230
+ let markup: DaisyVNode;
231
+ if (isRoot) {
232
+ const items = itemsFor(id, String(props[textKey] ?? ""), mode);
233
+ // The renderer turns a root's items text into rows when it has no children, so clear it here.
234
+ // The text is read by itemsFor and passed as children, so the catalog build must not also
235
+ // read it: that would draw every row twice (a carousel's slides, a menu's rows).
236
+ // Carousels and accordions draw their rows through the children path, so their catalog build
237
+ // must not also read the text: that would draw every row twice. Menus and tabs draw theirs
238
+ // from the text itself, so for them the text stays on the node.
239
+ const { [textKey]: _text, ...rowValues } = values;
240
+ const rowsFromChildren = id === "carousel" || id === "accordion";
241
+ const node = nodeFor(id, rowsFromChildren ? rowValues : values, items.nodes, nodeId);
242
+ markup = daisyRenderer.render(node, {}, items.vnodes, { mode });
243
+ } else {
244
+ // Content lines come first, then the slot where the author's own elements go. The slot is
245
+ // always there: an element's `render()` is not told whether it has children.
246
+ const lines = holdsChildren && !ownsContent ? contentChildren(String(props[CONTENT_FIELD] ?? "")) : [];
247
+ const children = holdsChildren ? [...lines, slot()] : lines;
248
+ markup = daisyRenderer.render(nodeFor(id, values, [], nodeId), {}, children, { mode });
249
+ }
250
+ const root = toVNode(markup);
251
+ const theme = typeof props[THEME_FIELD] === "string" ? props[THEME_FIELD] : "";
252
+ if (theme && (THEMES as readonly string[]).includes(theme)) {
253
+ root.attrs["data-theme"] = theme;
254
+ }
255
+ return { markup: root };
256
+ },
257
+ };
258
+ }
259
+ /** Elements for a list of definitions, in catalog order. */
260
+ export function daisyElements(definitions: readonly DaisyComponentDefinition[]): ExtensionElement[] {
261
+ return definitions.map(elementFor);
262
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The daisyUI extension for EmVB 1.5 (extensionApi 1).
3
+ *
4
+ * Register it in the site config:
5
+ * import { daisyUIExtension } from "@theweekendprojects/emvb-daisyui/extension";
6
+ * emvb({ extensions: [daisyUIExtension] })
7
+ *
8
+ * Its stylesheet and script are files of this package, loaded only on pages that draw one of its
9
+ * elements. EmVB scopes the stylesheet to the extension's own elements.
10
+ */
11
+ import { DAISY_COMPONENT_CATALOG } from "../catalog/index.ts";
12
+ import { COLUMNS } from "../catalog/layout-marketing.ts";
13
+ import { CLASSES_FOR_EXTENSION } from "./classes.ts";
14
+ import { daisyElements, type ExtensionElement } from "./elements.ts";
15
+ import { CLASS_PREFIX, SLOT_NAME, toOutput } from "./to-output.ts";
16
+
17
+ /** The extension id is the package's name without its scope (EmVB checks this at build time). */
18
+ export const EXTENSION_ID = "emvb-daisyui";
19
+
20
+ /** One element as the extension manifest lists it: a render() that returns output nodes. */
21
+ function manifestElement(element: ExtensionElement) {
22
+ const { container, render, ...rest } = element;
23
+ return {
24
+ ...rest,
25
+ ...(container ? { slots: [{ name: SLOT_NAME, label: "Content" }] } : {}),
26
+ render: (props: Record<string, unknown>) => [toOutput(render(props, { mode: "public" }).markup)],
27
+ };
28
+ }
29
+
30
+ export const daisyUIExtension = {
31
+ extensionApi: 1 as const,
32
+ id: EXTENSION_ID,
33
+ label: "daisyUI",
34
+ module: import.meta.url,
35
+ classes: { prefix: CLASS_PREFIX, allow: CLASSES_FOR_EXTENSION },
36
+ css: "./daisy.css",
37
+ runtime: "./daisy.js",
38
+ elements: daisyElements([...DAISY_COMPONENT_CATALOG, COLUMNS]).map(manifestElement),
39
+ };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The daisyUI renderer's markup as EmVB 1.5 extension output.
3
+ *
4
+ * The renderer returns a VNode tree with plain daisyUI class names (`btn`, `[--value:70]`). EmVB 1.5
5
+ * wants output nodes: `{ type: "markup", props: { tag, attrs, text }, extClasses, extVars, children }`
6
+ * for markup, and `{ type: "ext-slot", name }` where the author's own content goes. This turns one
7
+ * into the other:
8
+ *
9
+ * - Class names get the extension's prefix, so they match its allowlist exactly.
10
+ * - A per-instance variable class (`[--value:70]`) is not a class any more: it is a CSS variable on
11
+ * the node (`extVars`), under the prefixed name daisyUI reads (`--daisy-value`).
12
+ * - The three arbitrary-value utilities the catalog uses are named classes in the kit's CSS, because
13
+ * EmVB refuses `[` and `]` in a class name.
14
+ * - A node with text and element children becomes a node with element children, the text in
15
+ * `span`s: the markup node takes `text` or `children`, not both.
16
+ * - The `emvb-slot` marker becomes an `ext-slot`.
17
+ */
18
+ import { prefixClassToken } from "./class-token.ts";
19
+
20
+ export const CLASS_PREFIX = "daisy-";
21
+ /** The marker the renderer puts where the author's content goes. */
22
+ export const SLOT_TAG = "emvb-slot";
23
+ export const SLOT_NAME = "body";
24
+
25
+ export type VNode = { tag: string; attrs: Record<string, string>; children: (VNode | string)[] };
26
+
27
+ /** An output node as 1.5 reads it. Loose on purpose: the core checks it. */
28
+ export type OutputNode =
29
+ | { type: "ext-slot"; name: string }
30
+ | {
31
+ type: "markup";
32
+ props: { tag: string; attrs: Record<string, string>; text?: string };
33
+ extClasses?: string[];
34
+ extVars?: Record<string, string>;
35
+ children?: OutputNode[];
36
+ };
37
+
38
+ /**
39
+ * Arbitrary-value utilities have no valid class name. Each becomes a named class that the kit's CSS
40
+ * (`styles/kit-extras.css`) defines, with the same rule Tailwind would have written.
41
+ */
42
+ export const NAMED_FOR_ARBITRARY: Readonly<Record<string, string>> = {
43
+ "min-h-[32rem]": "min-h-128",
44
+ "md:grid-cols-[16rem_1fr]": "sidebar-columns",
45
+ "[&>*]:my-0!": "children-flush",
46
+ };
47
+
48
+ /** A per-instance variable class: `[--value:70]`, `[--digits:2]`. */
49
+ const VARIABLE_CLASS = /^\[--([a-z][a-z0-9-]*):(-?\d+(?:\.\d+)?)\]$/;
50
+
51
+ /** The class tokens of a `class` attribute, split into classes and variables. */
52
+ export function splitClasses(value: string | undefined): {
53
+ classes: string[];
54
+ vars: Record<string, string>;
55
+ } {
56
+ const classes: string[] = [];
57
+ const vars: Record<string, string> = {};
58
+ for (const raw of (value ?? "").split(/\s+/).filter(Boolean)) {
59
+ const variable = VARIABLE_CLASS.exec(raw);
60
+ if (variable) {
61
+ vars[`--${CLASS_PREFIX}${variable[1]}`] = variable[2] as string;
62
+ continue;
63
+ }
64
+ const token = NAMED_FOR_ARBITRARY[raw] ?? raw;
65
+ const prefixed = prefixClassToken(token);
66
+ if (/[[\]]/.test(prefixed)) {
67
+ throw new Error(`daisyUI class "${raw}" has brackets and no named replacement`);
68
+ }
69
+ classes.push(prefixed);
70
+ }
71
+ return { classes, vars };
72
+ }
73
+
74
+ /** Everything but `class`, dropping attributes with no value. */
75
+ function plainAttrs(attrs: Record<string, string | undefined>): Record<string, string> {
76
+ const out: Record<string, string> = {};
77
+ for (const [name, value] of Object.entries(attrs)) {
78
+ if (name !== "class" && value !== undefined) out[name] = value;
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** A text child as a node of its own, for a parent that also has element children. */
84
+ const spanOf = (text: string): OutputNode => ({
85
+ type: "markup",
86
+ props: { tag: "span", attrs: {}, text },
87
+ });
88
+
89
+ /** One renderer node as an output node. */
90
+ export function toOutput(node: VNode | string): OutputNode {
91
+ if (typeof node === "string") return spanOf(node);
92
+ if (node.tag === SLOT_TAG) return { type: "ext-slot", name: SLOT_NAME };
93
+ const { classes, vars } = splitClasses(node.attrs.class);
94
+ const texts = node.children.filter((child): child is string => typeof child === "string");
95
+ const onlyText = texts.length > 0 && texts.length === node.children.length;
96
+ const out: OutputNode = {
97
+ type: "markup",
98
+ props: {
99
+ tag: node.tag,
100
+ attrs: plainAttrs(node.attrs),
101
+ ...(onlyText ? { text: texts.join("") } : {}),
102
+ },
103
+ ...(classes.length > 0 ? { extClasses: classes } : {}),
104
+ ...(Object.keys(vars).length > 0 ? { extVars: vars } : {}),
105
+ };
106
+ if (!onlyText && node.children.length > 0) out.children = node.children.map(toOutput);
107
+ return out;
108
+ }
109
+
110
+ /** Whether a rendered tree has a slot marker anywhere in it. */
111
+ export function hasSlot(node: VNode | string): boolean {
112
+ return typeof node !== "string" && (node.tag === SLOT_TAG || node.children.some(hasSlot));
113
+ }
@@ -0,0 +1,81 @@
1
+ import type { DaisyComponentDefinition } from "../types.ts";
2
+
3
+ // Utilities the renderer adds itself (centring, mobile fallbacks). They are not in any catalog
4
+ // classMap, so the safelist must name them or Tailwind never emits their rules.
5
+ const RUNTIME_UTILITIES = [
6
+ "mx-auto",
7
+ "w-fit",
8
+ "relative",
9
+ "text-start",
10
+ "text-end",
11
+ "p-4",
12
+ "w-full",
13
+ "max-w-md",
14
+ "bg-base-300",
15
+ "aspect-video",
16
+ "max-w-xs",
17
+ "flex",
18
+ "items-center",
19
+ "justify-center",
20
+ "rounded-box",
21
+ "text-base-content/60",
22
+ "my-4",
23
+ "opacity-60",
24
+ "grid",
25
+ "place-items-center",
26
+ "size-24!",
27
+ "flex",
28
+ "items-center",
29
+ "gap-2",
30
+ "cursor-pointer",
31
+ "step-neutral",
32
+ "step-primary",
33
+ "step-secondary",
34
+ "step-accent",
35
+ "step-info",
36
+ "step-success",
37
+ "step-warning",
38
+ "step-error",
39
+ "p-6",
40
+ "bg-base-200",
41
+ "w-auto!",
42
+ "bg-linear-to-br",
43
+ "from-primary",
44
+ "to-secondary",
45
+ "bg-primary",
46
+ "text-primary-content",
47
+ "max-sm:timeline-vertical",
48
+ "max-sm:megamenu-vertical",
49
+ ];
50
+
51
+ export function generateSafelistCss(definitions: readonly DaisyComponentDefinition[]): string {
52
+ const classes = new Set<string>(RUNTIME_UTILITIES);
53
+ for (const definition of definitions) {
54
+ classes.add(definition.rootClass);
55
+ for (const field of definition.fields)
56
+ for (const className of Object.values(field.classMap ?? {})) {
57
+ for (const token of className.split(/\s+/)) if (token) classes.add(token);
58
+ }
59
+ }
60
+ return `/* Generated. Ensures Tailwind discovers every allowlisted daisyUI class. */\n${[
61
+ ...classes,
62
+ ]
63
+ .toSorted()
64
+ .map((className) => `.${className} {}`)
65
+ .join("\n")}\n`;
66
+ }
67
+
68
+ export function generateGallery(definitions: readonly DaisyComponentDefinition[]): string {
69
+ return (
70
+ JSON.stringify(
71
+ definitions.map((definition) => ({
72
+ id: definition.id,
73
+ label: definition.label,
74
+ category: definition.category,
75
+ defaults: Object.fromEntries(definition.fields.map((field) => [field.key, field.default])),
76
+ })),
77
+ null,
78
+ 2,
79
+ ) + "\n"
80
+ );
81
+ }
@@ -0,0 +1,35 @@
1
+ import type { DaisyComponentDefinition } from "../types.ts";
2
+ import { DIGITS_2_CLASS, VALUE_CLASS_NAMES } from "../catalog/value-class.ts";
3
+
4
+ /**
5
+ * Every class name the catalog can emit: each component's root class and every option's class map
6
+ * value. Tailwind only generates classes it finds written out in the source, and the option classes
7
+ * are built from templates, so the stylesheet would miss them. Writing this list out as literal
8
+ * strings in `src/catalog/class-names.ts` puts every name in front of the scanner.
9
+ */
10
+ export function catalogClassNames(catalog: readonly DaisyComponentDefinition[]): string[] {
11
+ const names = new Set<string>();
12
+ for (const definition of catalog) {
13
+ for (const token of definition.rootClass.split(/\s+/)) if (token) names.add(token);
14
+ for (const field of definition.fields) {
15
+ if (!field.classMap) continue;
16
+ for (const value of Object.values(field.classMap))
17
+ for (const token of String(value).split(/\s+/)) if (token) names.add(token);
18
+ }
19
+ }
20
+ // Classes a build function adds itself rather than through an option.
21
+ for (const name of VALUE_CLASS_NAMES) names.add(name);
22
+ names.add(DIGITS_2_CLASS);
23
+ return [...names].toSorted();
24
+ }
25
+
26
+ /** The source text of `src/catalog/class-names.ts` for a catalog. */
27
+ export function classNamesModule(names: readonly string[]): string {
28
+ const lines = names.map((name) => ` ${JSON.stringify(name)},`).join("\n");
29
+ return `// Generated from the catalog by \`bun run --cwd packages/emvb-daisyui classes:write\`.
30
+ // Tailwind scans this file so every option class is generated. Do not edit by hand.
31
+ export const CATALOG_CLASS_NAMES = [
32
+ ${lines}
33
+ ] as const;
34
+ `;
35
+ }
@@ -0,0 +1,21 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { DAISY_COMPONENT_CATALOG } from "../catalog/index.ts";
5
+ import { generateGallery, generateSafelistCss } from "./artifacts.ts";
6
+ import { validateDefinition } from "./generate.ts";
7
+
8
+ const here = dirname(fileURLToPath(import.meta.url));
9
+ const generated = resolve(here, "../../generated");
10
+ await mkdir(generated, { recursive: true });
11
+ const ids = new Set<string>();
12
+ for (const definition of DAISY_COMPONENT_CATALOG) {
13
+ validateDefinition(definition);
14
+ if (ids.has(definition.id)) throw new Error(`Duplicate component id: ${definition.id}`);
15
+ ids.add(definition.id);
16
+ }
17
+ await Promise.all([
18
+ writeFile(resolve(generated, "safelist.css"), generateSafelistCss(DAISY_COMPONENT_CATALOG)),
19
+ writeFile(resolve(generated, "component-gallery.json"), generateGallery(DAISY_COMPONENT_CATALOG)),
20
+ ]);
21
+ console.log(`Generated ${DAISY_COMPONENT_CATALOG.length} daisyUI components.`);