windcraft-editor 0.0.0-stage → 0.1.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 (61) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +53 -2
  3. package/core/board-layout.js +71 -0
  4. package/core/class-groups.js +210 -0
  5. package/core/design-spec.js +303 -0
  6. package/core/exporters.js +156 -0
  7. package/core/pages.js +39 -0
  8. package/core/prop-tailwind.js +158 -0
  9. package/core/split-sections.js +99 -0
  10. package/core/theme.js +87 -0
  11. package/editor/design/agent.js +2118 -0
  12. package/editor/design/classes-section.js +103 -0
  13. package/editor/design/code-editor.js +293 -0
  14. package/editor/design/code-view.js +158 -0
  15. package/editor/design/color-picker.js +107 -0
  16. package/editor/design/config.js +5 -0
  17. package/editor/design/controls.js +132 -0
  18. package/editor/design/css-props.js +111 -0
  19. package/editor/design/design-tab.js +120 -0
  20. package/editor/design/device-frame.js +40 -0
  21. package/editor/design/editor/add-menu.js +151 -0
  22. package/editor/design/editor/api.js +47 -0
  23. package/editor/design/editor/base.js +55 -0
  24. package/editor/design/editor/code-panel.js +206 -0
  25. package/editor/design/editor/color-ui.js +135 -0
  26. package/editor/design/editor/designs.js +606 -0
  27. package/editor/design/editor/docs.js +121 -0
  28. package/editor/design/editor/frame-handles.js +223 -0
  29. package/editor/design/editor/frame-messages.js +195 -0
  30. package/editor/design/editor/inspector.js +461 -0
  31. package/editor/design/editor/layers.js +61 -0
  32. package/editor/design/editor/pages-panel.js +161 -0
  33. package/editor/design/editor/panel-resize.js +47 -0
  34. package/editor/design/editor/plane.js +132 -0
  35. package/editor/design/editor/present.js +52 -0
  36. package/editor/design/editor/toolbar.js +267 -0
  37. package/editor/design/editor.js +47 -0
  38. package/editor/design/figma-sections.js +440 -0
  39. package/editor/design/float-toolbar.js +163 -0
  40. package/editor/design/group-controls.js +52 -0
  41. package/editor/design/host.js +22 -0
  42. package/editor/design/panel-model.js +130 -0
  43. package/editor/design/panel-state.js +40 -0
  44. package/editor/design/panel.js +212 -0
  45. package/editor/design/presenter.js +312 -0
  46. package/editor/design/prop-sections.js +18 -0
  47. package/editor/design/selection-overlay.js +93 -0
  48. package/editor/design/store.js +29 -0
  49. package/editor/design/style-sections.js +315 -0
  50. package/editor/design/tailwind-classes.js +65 -0
  51. package/editor/embed-frame.js +43 -0
  52. package/editor/embed.html +15 -0
  53. package/editor/embed.js +60 -0
  54. package/editor/index.js +62 -0
  55. package/editor/playground/component-source.js +124 -0
  56. package/editor/styles.css +402 -0
  57. package/editor/template.js +247 -0
  58. package/editor/vendor/codemirror.js +24 -0
  59. package/editor/vendor/preact-htm.js +1 -0
  60. package/editor/vendor/prettier.js +171 -0
  61. package/package.json +39 -5
@@ -0,0 +1,93 @@
1
+ // Draws the selection (box, resize handles, rotate zones, radius dots, size label) in the editor, above the frame,
2
+ // so the frame's edge never clips it and an element hanging outside the frame keeps its full outline.
3
+ // The in-frame agent only describes the selection (boxes in the frame's own coordinates) and runs the gestures.
4
+ //
5
+ // Everything here is laid out in SCREEN pixels, not inside the zoomed plane. A handle that is 9px must be exactly 9px at
6
+ // any zoom: sized in plane units it shrinks to a fraction of a pixel at high zoom, the browser rounds that, and the
7
+ // ring vanishes and the circle turns into a blob.
8
+
9
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
10
+ const round = (n) => Math.round(n * 100) / 100;
11
+
12
+ // The rotate cursor is an arc that wraps around the corner it belongs to (drawn for the bottom-right corner and turned
13
+ // a quarter for each of the others), plus however far the element itself is already rotated.
14
+ // (These cursor URLs go inside style="..." attributes, so they use single quotes.)
15
+ const ARC = '<path d="M19 6A13 13 0 0 1 6 19"/><path d="M15.5 9.5 19 5.5 22.5 9.5"/><path d="M9.5 15.5 5.5 19 9.5 22.5"/>';
16
+ const CORNER_TURN = { se: 0, sw: 90, nw: 180, ne: 270 };
17
+ const rotateCursor = (deg) => {
18
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><g transform="rotate(${Math.round(deg)} 12 12)"><g stroke="#fff" stroke-width="4.2">${ARC}</g><g stroke="#111" stroke-width="1.8">${ARC}</g></g></svg>`;
19
+ return `url('data:image/svg+xml,${encodeURIComponent(svg)}') 12 12, crosshair`;
20
+ };
21
+
22
+ // The radius cursor, like Figma's: the black pointer with a thick white outline and a small corner curve beside it.
23
+ // 32px canvas; the hotspot is the pointer's tip.
24
+ const POINTER = "M6.5 3.5V22.6l4.6-4.3 3.1 7 3.4-1.5-3.1-6.9h6.6z";
25
+ const RADIUS_PATH = '<path d="M21.5 29.5V27a5 5 0 0 1 5-5h2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>';
26
+ export const radiusCursorSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><path d="${POINTER}" fill="#000" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/><g stroke="#fff" stroke-width="4.2">${RADIUS_PATH}</g><g stroke="#000" stroke-width="1.9">${RADIUS_PATH}</g></svg>`;
27
+ const radiusCursor = `url('data:image/svg+xml,${encodeURIComponent(radiusCursorSvg)}') 6 3, default`;
28
+
29
+ const CORNERS = { nw: [0, 0], ne: [1, 0], se: [1, 1], sw: [0, 1] };
30
+ export const HANDLE_CURSORS = { nw: "nwse-resize", se: "nwse-resize", ne: "nesw-resize", sw: "nesw-resize", n: "ns-resize", s: "ns-resize", e: "ew-resize", w: "ew-resize" };
31
+
32
+ /** Handles for one selected box. W and H are its size on screen. */
33
+ function handles(it, W, H, z) {
34
+ const out = [];
35
+ const add = (name, css, cursor, cls = "") => out.push(`<div class="sh ${cls}" data-sh="${name}" style="${css}cursor:${cursor};"></div>`);
36
+ // rotating: the area just outside each corner (under the squares)
37
+ Object.entries(CORNERS).forEach(([name, [fx, fy]]) => {
38
+ const tx = fx ? "-4.5px" : "calc(-100% + 4.5px)";
39
+ const ty = fy ? "-4.5px" : "calc(-100% + 4.5px)";
40
+ add(`rot-${name}`, `left:${fx * 100}%;top:${fy * 100}%;width:24px;height:24px;transform:translate(${tx}, ${ty});`, rotateCursor(CORNER_TURN[name] + it.rot));
41
+ });
42
+ // corner radius: a dot just inside each corner, further in the rounder the corner is (11px from the corner when square)
43
+ if (Math.min(W, H) >= 40) {
44
+ const inset = Math.min(it.r0 * z + 11, Math.min(W, H) / 2);
45
+ Object.entries(CORNERS).forEach(([name, [fx, fy]]) => add(`rad-${name}`, `left:${round(fx ? W - inset : inset)}px;top:${round(fy ? H - inset : inset)}px;transform:translate(-50%, -50%);`, radiusCursor, "sd"));
46
+ }
47
+ // resizing: the whole length of each edge, then a square on each corner
48
+ add("n", "left:0;top:0;width:100%;height:10px;transform:translateY(-50%);", HANDLE_CURSORS.n);
49
+ add("s", "left:0;top:100%;width:100%;height:10px;transform:translateY(-50%);", HANDLE_CURSORS.s);
50
+ add("w", "left:0;top:0;height:100%;width:10px;transform:translateX(-50%);", HANDLE_CURSORS.w);
51
+ add("e", "left:100%;top:0;height:100%;width:10px;transform:translateX(-50%);", HANDLE_CURSORS.e);
52
+ Object.entries(CORNERS).forEach(([name, [fx, fy]]) => add(name, `left:${fx * 100}%;top:${fy * 100}%;transform:translate(-50%, -50%);`, HANDLE_CURSORS[name], "sc"));
53
+ return out.join("");
54
+ }
55
+
56
+ /**
57
+ * The outline of one box as an SVG path: rotated about its centre, with each corner's own radius. A CSS box this big
58
+ * (tens of thousands of pixels at high zoom) silently stops painting its shadow, but a path is clipped, not skipped.
59
+ * It is inset by half the stroke so the line sits inside the box, like the handles expect.
60
+ */
61
+ function outline(it, z, ox, oy) {
62
+ const k = 0.75;
63
+ const x = ox + it.x * z + k, y = oy + it.y * z + k, W = Math.max(0, it.w * z - 2 * k), H = Math.max(0, it.h * z - 2 * k);
64
+ let h = it.rh.map((v) => Math.max(0, v * z - k)), v = it.rv.map((r) => Math.max(0, r * z - k)); // tl tr br bl
65
+ // like CSS, shrink every radius together when neighbouring corners would overlap
66
+ const f = Math.min(1, W / ((h[0] + h[1]) || Infinity), W / ((h[3] + h[2]) || Infinity), H / ((v[0] + v[3]) || Infinity), H / ((v[1] + v[2]) || Infinity));
67
+ h = h.map((r) => r * f); v = v.map((r) => r * f);
68
+ const d = `M${round(x + h[0])} ${round(y)}H${round(x + W - h[1])}A${round(h[1])} ${round(v[1])} 0 0 1 ${round(x + W)} ${round(y + v[1])}V${round(y + H - v[2])}A${round(h[2])} ${round(v[2])} 0 0 1 ${round(x + W - h[2])} ${round(y + H)}H${round(x + h[3])}A${round(h[3])} ${round(v[3])} 0 0 1 ${round(x)} ${round(y + H - v[3])}V${round(y + v[0])}A${round(h[0])} ${round(v[0])} 0 0 1 ${round(x + h[0])} ${round(y)}Z`;
69
+ return `<path d="${d}" transform="rotate(${it.rot} ${round(x + W / 2)} ${round(y + H / 2)})" fill="none" stroke="#fff" stroke-width="1.5"/>`;
70
+ }
71
+
72
+ /**
73
+ * Returns { lines, html }: the outlines go in their own layer that inverts what is under it; the handles and label go above it.
74
+ * data: what the agent posted ({ items, handles, label, bbox, at }), in the frame's own coordinates.
75
+ * view: { zoom, ox, oy }: the zoom, and where the frame's top-left corner is on screen (relative to the canvas).
76
+ */
77
+ export function selectionHtml(data, { zoom: z, ox, oy }) {
78
+ if (!data || !data.items || !data.items.length) return { lines: "", html: "", label: "" };
79
+ const boxes = data.items.map((it) => {
80
+ const W = it.w * z, H = it.h * z;
81
+ const inner = data.handles && data.items.length === 1 ? handles(it, W, H, z) : "";
82
+ const radius = `${it.rh.map((v) => `${round(v * z)}px`).join(" ")} / ${it.rv.map((v) => `${round(v * z)}px`).join(" ")}`;
83
+ return `<div class="sbox" style="left:${round(ox + it.x * z)}px;top:${round(oy + it.y * z)}px;width:${round(W)}px;height:${round(H)}px;transform:rotate(${it.rot}deg);border-radius:${radius};">${inner}</div>`;
84
+ }).join("");
85
+ // a size label sits under the element; the radius label follows the pointer, like the size label does while resizing
86
+ const label = data.label && data.at
87
+ ? `<div class="slabel pt" style="left:${round(ox + data.at.x * z + 16)}px;top:${round(oy + data.at.y * z + 14)}px;">${esc(data.label)}</div>`
88
+ : data.label && data.bbox
89
+ ? `<div class="slabel" style="left:${round(ox + (data.bbox.x + data.bbox.w / 2) * z)}px;top:${round(oy + (data.bbox.y + data.bbox.h) * z + 8)}px;">${esc(data.label)}</div>`
90
+ : "";
91
+ const lines = `<svg class="sout">${data.items.map((it) => outline(it, z, ox, oy)).join("")}</svg>`;
92
+ return { lines, html: boxes, label };
93
+ }
@@ -0,0 +1,29 @@
1
+ // @ts-check
2
+ // A tiny store for state several parts of the page share. State is replaced, never changed in place (a Set that changes is
3
+ // replaced by a new Set), so "did it change" is a plain comparison; `set` takes the changed keys (or a function of the current
4
+ // state that returns them) and tells the subscribers once, and not at all when nothing changed.
5
+
6
+ /**
7
+ * @template {Record<string, any>} T
8
+ * @param {T} initial
9
+ */
10
+ export function createStore(initial) {
11
+ let state = initial;
12
+ /** @type {Set<(state: T) => void>} */
13
+ const subscribers = new Set();
14
+ return {
15
+ get: () => state,
16
+ /** @param {Partial<T> | ((state: T) => Partial<T>)} patch */
17
+ set(patch) {
18
+ const changes = typeof patch === "function" ? patch(state) : patch;
19
+ if (Object.keys(changes).every((k) => Object.is(state[k], changes[k]))) return;
20
+ state = { ...state, ...changes };
21
+ subscribers.forEach((fn) => fn(state));
22
+ },
23
+ /** Calls `fn(state)` after each change. Returns a function that stops it. */
24
+ subscribe(/** @type {(state: T) => void} */ fn) {
25
+ subscribers.add(fn);
26
+ return () => { subscribers.delete(fn); };
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,315 @@
1
+ // The Design tab's style sections after Position, Layout and the flex / grid item, named as a frontend developer knows them:
2
+ // Typography, Background, Border, Effects, Transform, Motion and Interaction, then a box to add any class or CSS (Spacing is in figma-sections.js). Each
3
+ // starts from what the element already has: a background, a border or an effect it has is a row; one it has not is not, and the
4
+ // section's + adds it. Set values are solid and marked with where they come from (a class or CSS), with a × to take them off;
5
+ // defaults are faint. Every edit goes through the same actions as the rest of the panel, so it is written where the value comes
6
+ // from: setProp · setProps · resetProp · setPropLive · setPropDone · setPropsLive · setPropsDone · applyValue · applyColor · addClasses
7
+ import { html, useState } from "../vendor/preact-htm.js";
8
+ import { rgbToHex } from "./css-props.js";
9
+ import { srcOf, shownOf, val, variant } from "./panel-model.js";
10
+ import { useUi } from "./panel-state.js";
11
+ import { TextInput, ColorInput } from "./controls.js";
12
+ import { GroupColor } from "./group-controls.js";
13
+ import { I, IconBtn, NumField, FSection, Sub, PropField, PropSelect, TwField, TwSelect, num, owns, has, off, comp, srcKind, srcNote, atVariant } from "./figma-sections.js";
14
+ import { twShown } from "../../core/prop-tailwind.js";
15
+ import { brandScale, normalizeTheme } from "../../core/theme.js";
16
+ import { data } from "./editor/base.js";
17
+ import { PropRow } from "./prop-sections.js";
18
+
19
+ const SIDES = ["top", "right", "bottom", "left"];
20
+ const CORNERS = [["top-left", "radiusTL", "↖"], ["top-right", "radiusTR", "↗"], ["bottom-right", "radiusBR", "↘"], ["bottom-left", "radiusBL", "↙"]];
21
+ /** The alpha of an rgb() / rgba() colour: its fourth value, if it has one. */
22
+ const alphaOf = (c) => {
23
+ const m = String(c).match(/^rgba?\(([^)]*)\)$/);
24
+ const parts = m ? m[1].split(/[\s,/]+/).filter(Boolean) : [];
25
+ if (parts.length < 4) return 1;
26
+ return parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3]);
27
+ };
28
+ const clear = (c) => !c || c === "transparent" || alphaOf(c) === 0;
29
+ /** The same value on every side (or corner), or "Mixed". */
30
+ const same = (s, props) => { const v = props.map((p) => comp(s, p)); return v.every((x) => x === v[0]) ? num(v[0]) : "Mixed"; };
31
+ const anyHas = (s, props) => props.some((p) => has(s, p));
32
+ /**
33
+ * Whether the element has something: with a breakpoint or state picked (md:, hover:), whether it has a class for it there (the
34
+ * computed look is the normal one, which says nothing about hover); else what the page shows (`showing`).
35
+ */
36
+ const present = (s, props, showing) => (variant() ? props.some((p) => has(s, p)) : showing);
37
+ /** The hex of a Tailwind colour name (black, blue-500), read from a hidden probe in the editor's own page, which has Tailwind. */
38
+ let probe = null;
39
+ function hexOf(name) {
40
+ if (!name) return "#000000";
41
+ if (/^(#|rgb|hsl)/.test(name)) return rgbToHex(name) || name;
42
+ const brand = /^brand-(\d+)$/.exec(name); // the project's own scale: the editor's page has no project theme to read it from
43
+ if (brand) return brandScale(normalizeTheme(data.theme).brand)[brand[1]] || "#000000";
44
+ if (!probe) { probe = document.createElement("span"); probe.style.display = "none"; document.body.appendChild(probe); }
45
+ probe.className = `bg-${name.replace(/\/\d+$/, "")}`;
46
+ return rgbToHex(getComputedStyle(probe).backgroundColor) || "#000000";
47
+ }
48
+ /** A × for a field made of several properties (every side, every corner): takes off each one the element sets, or null when none is. */
49
+ const resetAll = (s, actions, props) => (props.some((p) => has(s, p)) ? () => props.forEach((p) => off(s, actions, p)) : null);
50
+ const firstSrc = (s, props) => props.map((p) => srcKind(s, p)).find(Boolean) || "";
51
+ /** A + that opens a short menu of what can be added (only what the element does not have yet). `items`: [value, label]. */
52
+ const AddMenu = ({ title, items, onPick }) => (items.length ? html`<label class="ib addsel" title=${title}>${I.plus}<select onChange=${(e) => { const v = e.target.value; e.target.value = ""; if (v) onPick(v); }}>
53
+ <option value="" selected>${title}</option>${items.map(([v, l]) => html`<option value=${v}>${l}</option>`)}</select></label>` : null);
54
+ /** − takes a style off the element (its tooltip says which); a row that has no value yet gets × to cancel instead. */
55
+ const Remove = ({ title, onClick }) => html`<${IconBtn} icon=${I.minus} title=${title} onClick=${onClick} />`;
56
+ const Cancel = ({ onClick }) => html`<${IconBtn} icon=${I.minus} title="Remove" onClick=${onClick} />`;
57
+
58
+ /** A colour as a row: a swatch, its value (a Tailwind name where a class gives it, else hex), its opacity when not full. */
59
+ function ColorRow({ s, actions, p, all, group, onRemove, removeTitle, title, label }) {
60
+ const src = srcOf(s, p), c = comp(s, p), at = atVariant(s, p);
61
+ // at a picked breakpoint / state: its class's colour (the swatch too); else a Tailwind name where a class gives it, or the hex
62
+ const atName = at ? twShown(p, at.token) : null;
63
+ const hex = atName ? hexOf(atName) : rgbToHex(c) || "#000000", a = atName ? 1 : alphaOf(c);
64
+ const shown = atName ?? (src.source === "tailwind" ? shownOf(s, p, src) : hex.replace(/^#/, "").toUpperCase());
65
+ const value = (v) => (/^[0-9a-f]{3}([0-9a-f]{3})?$/i.test(v.trim()) ? `#${v.trim()}` : v);
66
+ // `all`: the colour goes on every one of these properties (a border's four sides), as one class where it can
67
+ const commit = (v) => (all ? actions.setProps(all, value(v), group) : actions.setProp(p, value(v)));
68
+ return html`<div class="frow">
69
+ <div class=${`nf ${has(s, p) ? "" : "unset"} ${srcKind(s, p) ? `src-${srcKind(s, p)}` : ""}`} title=${`${title || p} · ${srcNote(s, p)}`}>
70
+ ${label && html`<span class="nfl">${label}</span>`}
71
+ <${ColorInput} class="cin" value=${hex} title="Pick a colour" hook=${{ "data-propcolor": p }}
72
+ onLive=${(h) => (all ? actions.setPropsLive(all, h, group) : actions.setPropLive(p, h))}
73
+ onDone=${(h, input) => (all ? actions.setPropsDone(all, h, group, input) : actions.setPropDone(p, h, input))} />
74
+ <${TextInput} class="nfi" list="dl-colors" value=${shown} onCommit=${commit} />
75
+ ${a < 1 && html`<span class="nfu">${Math.round(a * 100)}%</span>`}</div>
76
+ ${onRemove && html`<${Remove} title=${removeTitle || "Remove"} onClick=${onRemove} />`}</div>`;
77
+ }
78
+
79
+ // ── Typography ────────────────────────────────────────────────────────────────────────────────────────────────────────────
80
+ const TYPE = ["font-family", "font-size", "font-weight", "line-height", "letter-spacing", "text-align", "color", "text-decoration-line", "text-transform", "font-style", "white-space"];
81
+ const WEIGHTS = [["100", "100 Thin"], ["200", "200 Extra light"], ["300", "300 Light"], ["400", "400 Regular"], ["500", "500 Medium"], ["600", "600 Semibold"], ["700", "700 Bold"], ["800", "800 Extra bold"], ["900", "900 Black"]];
82
+ // the three Tailwind families as words (font-sans...), with their stack as the CSS to write when the element is styled with CSS
83
+ const STACKS = { sans: "ui-sans-serif, system-ui, sans-serif", serif: "ui-serif, Georgia, serif", mono: "ui-monospace, SFMono-Regular, monospace" };
84
+ const MORE_TYPE = [
85
+ { p: "text-decoration-line", l: "Decor", t: "select", o: ["none", "underline", "line-through", "overline"] },
86
+ { p: "text-transform", l: "Case", t: "select", o: ["none", "uppercase", "lowercase", "capitalize"] },
87
+ { p: "font-style", l: "Style", t: "select", o: ["normal", "italic"] },
88
+ { p: "white-space", l: "Wrap", t: "select", o: ["normal", "nowrap", "pre", "pre-wrap", "pre-line"] },
89
+ ];
90
+ export function TypographySection({ s, actions }) {
91
+ const [open, setOpen] = useState(false);
92
+ const [more, setMore] = useState(false);
93
+ const ui = useUi();
94
+ const shown = open || s.ownText || s.tag === "body" || anyHas(s, TYPE);
95
+ if (!shown) return html`<${FSection} title="Typography" extra=${html`<${IconBtn} icon=${I.plus} title="Set this element's text style (its children inherit it)" onClick=${() => setOpen(true)} />`} />`;
96
+ const fam = comp(s, "font-family"), src = srcOf(s, "font-family");
97
+ const famShown = src.source === "tailwind" ? shownOf(s, "font-family", src) : (fam.split(",")[0] || "").replace(/["']/g, "").trim();
98
+ const setFont = (t) => { const v = t.trim().toLowerCase(); return STACKS[v] ? actions.setProp("font-family", v, STACKS[v]) : actions.setProp("font-family", t.trim()); };
99
+ const align = comp(s, "text-align");
100
+ const al = (v, icon, title) => html`<${IconBtn} icon=${icon} title=${title} on=${align === v || (v === "left" && align === "start")} onClick=${() => actions.setProp("text-align", v)} />`;
101
+ const extra = MORE_TYPE.filter((c) => more || has(s, c.p));
102
+ const clamp = val(s, "lineClamp", ui), trunc = val(s, "textOverflow", ui);
103
+ const own = TYPE.filter((p) => has(s, p));
104
+ const removeAll = () => {
105
+ own.forEach((p) => off(s, actions, p, "inherit"));
106
+ if (clamp) actions.applyValue("lineClamp", "");
107
+ if (trunc) actions.applyValue("textOverflow", "");
108
+ setOpen(false); setMore(false);
109
+ };
110
+ return html`<${FSection} title="Typography" extra=${html`${(own.length > 0 || clamp || trunc || (open && !s.ownText)) && html`<${Remove} title=${own.length || clamp || trunc ? "Remove this element's text styles (it goes back to what it inherits)" : "Close"} onClick=${removeAll} />`}
111
+ <${IconBtn} icon=${I.dots} on=${more} title=${more ? "Fewer text settings" : "Decoration, case, italic, wrapping, line clamp, truncate"} onClick=${() => setMore(!more)} />`}>
112
+ <div class="frow"><${NumField} label="Font" title=${`font-family: ${fam} · ${srcNote(s, "font-family")} (type any font, or sans / serif / mono)`} value=${famShown} list="dl-fonts"
113
+ set=${has(s, "font-family")} src=${srcKind(s, "font-family")} onReset=${has(s, "font-family") ? () => off(s, actions, "font-family", "inherit") : null} onCommit=${setFont} /></div>
114
+ <div class="frow">
115
+ <${PropSelect} s=${s} actions=${actions} p="font-weight" title="Weight" options=${WEIGHTS} />
116
+ <${PropField} s=${s} actions=${actions} p="font-size" label="Size" title="Font size (px, or text-sm, 2xl...)" list="dl-fontSize" />
117
+ </div>
118
+ <div class="frow">
119
+ <${PropField} s=${s} actions=${actions} p="line-height" label="Line" title="Line height" list="dl-leading" />
120
+ <${PropField} s=${s} actions=${actions} p="letter-spacing" label="Letter" title="Letter spacing" list="dl-tracking" />
121
+ </div>
122
+ <div class="frow"><div class="ibg wide">${al("left", I.textL, "Align left")}${al("center", I.textC, "Align centre")}${al("right", I.textR, "Align right")}${al("justify", I.textJ, "Justify")}</div></div>
123
+ <${ColorRow} s=${s} actions=${actions} p="color" title="Text colour" />
124
+ ${extra.map((c) => html`<${PropRow} s=${s} actions=${actions} c=${c} />`)}
125
+ ${(more || clamp) && html`<div class="frow"><${TwField} s=${s} k="lineClamp" label="Clamp" title="Show at most this many lines (line-clamp-*)" actions=${actions} />
126
+ ${clamp && html`<${Remove} title="Remove the line clamp" onClick=${() => actions.applyValue("lineClamp", "")} />`}</div>`}
127
+ ${(more || trunc) && html`<div class="frow"><${TwSelect} s=${s} k="textOverflow" label="Overflow" title="Cut long text off with … (truncate)" actions=${actions} />
128
+ ${trunc && html`<${Remove} title="Remove the text overflow" onClick=${() => actions.applyValue("textOverflow", "")} />`}</div>`}
129
+ </${FSection}>`;
130
+ }
131
+
132
+ // ── Background: a colour, a gradient, an image ───────────────────────────────────────────────────────────────────────────
133
+ export function BackgroundSection({ s, actions }) {
134
+ const ui = useUi();
135
+ const [adding, setAdding] = useState("");
136
+ const color = present(s, ["background-color"], !clear(comp(s, "background-color"))), img = comp(s, "background-image");
137
+ const grad = Boolean(val(s, "bgImage", ui)) || adding === "gradient";
138
+ const imgSet = Boolean(img) && img !== "none" && !/gradient/.test(img), image = imgSet || adding === "image";
139
+ const cssGrad = /gradient/.test(img) && !val(s, "bgImage", ui); // a gradient from CSS: shown as its value
140
+ // a value this element sets comes off; one from the design's CSS is covered (transparent / none)
141
+ const remove = (p) => (owns(s, p) ? actions.resetProp(p) : actions.setProp(p, p === "background-color" ? "transparent" : "none"));
142
+ const add = (kind) => {
143
+ if (kind === "color") actions.setProp("background-color", "white");
144
+ if (kind === "gradient") { setAdding("gradient"); actions.applyValue("bgImage", "bg-gradient-to-r"); }
145
+ if (kind === "image") setAdding("image");
146
+ };
147
+ const items = [!color && ["color", "Colour"], !grad && !cssGrad && ["gradient", "Gradient"], !image && ["image", "Bg image"]].filter(Boolean);
148
+ return html`<${FSection} title="Background" extra=${html`<${AddMenu} title="Add a background" items=${items} onPick=${add} />`}>
149
+ ${color && html`<${ColorRow} s=${s} actions=${actions} p="background-color" title="Background colour" removeTitle="Remove the background colour" onRemove=${() => remove("background-color")} />`}
150
+ ${grad && html`<div class="frow"><${TwSelect} s=${s} k="bgImage" label="Gradient" title="Gradient direction (bg-gradient-to-*)" actions=${actions} />
151
+ <${Remove} title="Remove the gradient" onClick=${() => { setAdding(""); ["bgImage", "gradFrom", "gradVia", "gradTo"].forEach((k) => actions.applyValue(k, "")); }} /></div>
152
+ <${GroupColor} s=${s} k="gradFrom" label="From" actions=${actions} /><${GroupColor} s=${s} k="gradVia" label="Via" actions=${actions} /><${GroupColor} s=${s} k="gradTo" label="To" actions=${actions} />`}
153
+ ${(image || cssGrad) && html`<div class="frow">
154
+ <${NumField} label=${cssGrad ? "Gradient" : "Bg image"} title=${`A picture behind the content (background-image) · ${srcNote(s, "background-image")}`} placeholder="Paste an image address…"
155
+ value=${imgSet || cssGrad ? shownOf(s, "background-image", srcOf(s, "background-image")) : ""}
156
+ set=${has(s, "background-image")} src=${srcKind(s, "background-image")} onCommit=${(t) => { setAdding(""); actions.setProp("background-image", /^(https?:|\/|data:)/.test(t.trim()) ? `url("${t.trim()}")` : t); }} />
157
+ ${imgSet || cssGrad ? html`<${Remove} title="Remove the bg image" onClick=${() => remove("background-image")} />` : html`<${Cancel} onClick=${() => setAdding("")} />`}</div>
158
+ ${imgSet && html`<div class="frow"><${PropSelect} s=${s} actions=${actions} p="background-size" label="Size" options=${[["auto", "Auto"], ["cover", "Cover"], ["contain", "Contain"]]} />
159
+ <${PropSelect} s=${s} actions=${actions} p="background-repeat" label="Repeat" options=${[["repeat", "Repeat"], ["no-repeat", "No repeat"], ["repeat-x", "Across"], ["repeat-y", "Down"]]} /></div>
160
+ <div class="frow"><${PropField} s=${s} actions=${actions} p="background-position" label="Position" title="background-position (center, top, 50% 20%...)" /></div>`}`}
161
+ </${FSection}>`;
162
+ }
163
+
164
+ // ── Border: radius, the border itself, outline and ring ──────────────────────────────────────────────────────────────────
165
+ export function BorderSection({ s, actions }) {
166
+ const ui = useUi();
167
+ const widths = SIDES.map((d) => `border-${d}-width`), styles = SIDES.map((d) => `border-${d}-style`), corners = CORNERS.map(([c]) => `border-${c}-radius`);
168
+ const on = present(s, [...SIDES.map((d) => `border-${d}-width`), "border-top-color"], SIDES.some((d) => parseFloat(comp(s, `border-${d}-width`)) > 0 && comp(s, `border-${d}-style`) !== "none"));
169
+ const outline = Boolean(comp(s, "outline-style")) && comp(s, "outline-style") !== "none", ring = Boolean(val(s, "ring", ui));
170
+ const [sides, setSides] = useState(false);
171
+ const [each, setEach] = useState(false);
172
+ const mixedW = same(s, widths) === "Mixed", mixedR = same(s, corners) === "Mixed";
173
+ const addBorder = () => {
174
+ actions.setProps(widths, "1", "borderWidth", ["borderT", "borderR", "borderB", "borderL"]);
175
+ if (comp(s, "border-top-style") === "none") actions.setProps(styles, "solid", "borderStyle"); // Tailwind's base styles already make it solid
176
+ };
177
+ // a border from classes loses them (its colour and style too); one from CSS (or the design's stylesheet) gets a width of 0
178
+ const removeBorder = () => (widths.some((p) => srcOf(s, p).source === "tailwind")
179
+ ? ["borderWidth", "borderT", "borderR", "borderB", "borderL", "borderColor", "borderStyle"].forEach((k) => actions.applyValue(k, ""))
180
+ : actions.setProps(widths, "0", "borderWidth"));
181
+ const removeRadius = () => (corners.some((p) => srcOf(s, p).source === "tailwind")
182
+ ? ["radius", ...CORNERS.map(([, k]) => k)].forEach((k) => actions.applyValue(k, ""))
183
+ : actions.setProps(corners, "0", "radius"));
184
+ const add = (kind) => {
185
+ if (kind === "border") addBorder();
186
+ if (kind === "outline") actions.setProp("outline", "2px solid blue-500");
187
+ if (kind === "ring") actions.applyValue("ring", "2");
188
+ };
189
+ const items = [!on && ["border", "Border (1px)"], !outline && ["outline", "Outline"], !ring && ["ring", "Ring"]].filter(Boolean);
190
+ const style = comp(s, "border-top-style");
191
+ return html`<${FSection} title="Border" extra=${html`<${AddMenu} title="Add a border, outline or ring" items=${items} onPick=${add} />`}>
192
+ <div class="frow">
193
+ <${NumField} label="Radius" title=${`border-radius · ${srcNote(s, "border-top-left-radius")}`} value=${same(s, corners)} set=${anyHas(s, corners)} src=${firstSrc(s, corners)} list="dl-radius"
194
+ onReset=${corners.some((p) => has(s, p)) ? removeRadius : null} onCommit=${(t) => actions.setProps(corners, t, "radius", CORNERS.map(([, k]) => k))} />
195
+ <${IconBtn} icon=${I.corners} on=${each || mixedR} title="Each corner on its own" onClick=${() => setEach(!each)} />
196
+ </div>
197
+ ${(each || mixedR) && html`<div class="frow two2">${CORNERS.map(([c, k, l]) => html`<${NumField} label=${l} title=${`${c} radius`} value=${num(comp(s, `border-${c}-radius`))}
198
+ set=${has(s, `border-${c}-radius`)} src=${srcKind(s, `border-${c}-radius`)} onReset=${resetAll(s, actions, [`border-${c}-radius`])} onCommit=${(t) => actions.setProps([`border-${c}-radius`], t, k)} />`)}</div>`}
199
+ ${on && html`<${Sub}>Border</${Sub}>
200
+ <${ColorRow} s=${s} actions=${actions} p="border-top-color" all=${SIDES.map((d) => `border-${d}-color`)} group="borderColor" title="Border colour (every side)" removeTitle="Remove the border" onRemove=${removeBorder} />
201
+ <div class="frow">
202
+ <${NumField} label="Width" title="Border width" value=${same(s, widths)} set=${anyHas(s, widths)} src=${firstSrc(s, widths)} list="dl-borderWidth" onReset=${resetAll(s, actions, widths)}
203
+ onCommit=${(t) => actions.setProps(widths, t, "borderWidth", ["borderT", "borderR", "borderB", "borderL"])} />
204
+ <label class=${`nf ${anyHas(s, styles) ? "" : "unset"}`} title="Line style"><select class="nfs wide" onChange=${(e) => actions.setProps(styles, e.target.value, "borderStyle")}>
205
+ ${["solid", "dashed", "dotted", "double"].map((v) => html`<option value=${v} selected=${style === v}>${v[0].toUpperCase() + v.slice(1)}</option>`)}</select></label>
206
+ <${IconBtn} icon=${I.sides} on=${sides || mixedW} title="Each side on its own" onClick=${() => setSides(!sides)} />
207
+ </div>
208
+ ${(sides || mixedW) && html`<div class="frow two2">${SIDES.map((d, i) => html`<${NumField} label=${["T", "R", "B", "L"][i]} title=${`border-${d}-width`} value=${num(comp(s, `border-${d}-width`))}
209
+ set=${has(s, `border-${d}-width`)} src=${srcKind(s, `border-${d}-width`)} onReset=${resetAll(s, actions, [`border-${d}-width`])} onCommit=${(t) => actions.setProps([`border-${d}-width`], t, ["borderT", "borderR", "borderB", "borderL"][i])} />`)}</div>`}`}
210
+ ${outline && html`<${Sub}>Outline</${Sub}><div class="frow"><${PropField} s=${s} actions=${actions} p="outline" label="Outline" title="outline (width style colour)" />
211
+ <${Remove} title="Remove the outline" onClick=${() => (val(s, "outlineStyle") || val(s, "outlineW") || val(s, "outlineColor") ? actions.setProp("outline", "none") : owns(s, "outline") ? actions.resetProp("outline") : actions.setProp("outline", "none"))} /></div>
212
+ <div class="frow"><${PropField} s=${s} actions=${actions} p="outline-offset" label="Offset" title="Gap between the element and its outline" /></div>`}
213
+ ${ring && html`<${Sub}>Ring</${Sub}><div class="frow"><${TwField} s=${s} k="ring" label="Ring" title="A ring around the element (ring-*)" actions=${actions} />
214
+ <${Remove} title="Remove the ring" onClick=${() => { actions.applyValue("ring", ""); actions.applyValue("ringColor", ""); }} /></div>
215
+ <${GroupColor} s=${s} k="ringColor" label="Colour" actions=${actions} />`}
216
+ </${FSection}>`;
217
+ }
218
+
219
+ // ── Effects: opacity, blend, shadows and filters ─────────────────────────────────────────────────────────────────────────
220
+ // the CSS each Tailwind shadow stands for, written when the element is styled with CSS rather than classes
221
+ const SHADOWS = {
222
+ sm: "0 1px 2px 0 rgb(0 0 0 / 0.05)", default: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
223
+ md: "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)", lg: "0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",
224
+ xl: "0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)", "2xl": "0 25px 50px -12px rgb(0 0 0 / 0.25)", inner: "inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",
225
+ };
226
+ const SHADOW_NAMES = [["sm", "Small"], ["default", "Default"], ["md", "Medium"], ["lg", "Large"], ["xl", "Extra large"], ["2xl", "2XL"], ["inner", "Inner"], ["custom", "Custom…"]];
227
+ const BLEND = [["normal", "Normal"], ["multiply", "Multiply"], ["screen", "Screen"], ["overlay", "Overlay"], ["darken", "Darken"], ["lighten", "Lighten"], ["difference", "Difference"]];
228
+ export function EffectsSection({ s, actions }) {
229
+ const ui = useUi();
230
+ const [custom, setCustom] = useState(false);
231
+ const [adding, setAdding] = useState(/** @type {string[]} */ ([]));
232
+ const sh = comp(s, "box-shadow"), shTok = ((variant() ? (atVariant(s, "box-shadow") || {}).token : srcOf(s, "box-shadow").token) || "").replace(/^(?:[\w-]+:)*/, "");
233
+ // Tailwind draws a ring with box-shadow too: that is the Border section's ring, not a shadow
234
+ const ringOnly = /^ring/.test(shTok) && !val(s, "shadow", ui);
235
+ const shadow = present(s, ["box-shadow"], Boolean(sh) && sh !== "none" && !ringOnly);
236
+ const shName = shTok === "shadow" ? "default" : /^shadow-/.test(shTok) ? shTok.replace(/^shadow-/, "") : "";
237
+ const preset = shadow && shName && !custom ? shName : "custom";
238
+ const setShadow = (v) => { if (v === "custom") return setCustom(true); setCustom(false); return actions.setProp("box-shadow", v, SHADOWS[v] || v); };
239
+ const tw = (k) => Boolean(val(s, k, ui)) || adding.includes(k);
240
+ const drop = (k) => { setAdding(adding.filter((x) => x !== k)); actions.applyValue(k, ""); };
241
+ const op = comp(s, "opacity");
242
+ const add = (kind) => {
243
+ if (kind === "shadow") setShadow("md");
244
+ else if (kind === "blur" || kind === "backdropBlur") actions.applyValue(kind, "md");
245
+ else setAdding([...adding, kind]);
246
+ };
247
+ const items = [!shadow && ["shadow", "Shadow"], !tw("blur") && ["blur", "Blur"], !tw("backdropBlur") && ["backdropBlur", "Background blur"],
248
+ !tw("brightness") && ["brightness", "Brightness"], !tw("grayscale") && ["grayscale", "Grayscale"]].filter(Boolean);
249
+ return html`<${FSection} title="Effects" extra=${html`<${AddMenu} title="Add an effect" items=${items} onPick=${add} />`}>
250
+ <div class="frow">
251
+ <${NumField} label="Opacity" title=${`opacity · ${srcNote(s, "opacity")}`} value=${op === "" ? "100" : String(Math.round(parseFloat(op) * 100))} set=${has(s, "opacity")} src=${srcKind(s, "opacity")}
252
+ onReset=${has(s, "opacity") ? () => off(s, actions, "opacity") : null}
253
+ onCommit=${(t) => { const n = parseFloat(t); if (Number.isFinite(n)) actions.setProp("opacity", String(Math.max(0, Math.min(100, n)) / 100)); }}><span class="nfu">%</span></${NumField}>
254
+ <${PropSelect} s=${s} actions=${actions} p="mix-blend-mode" title="Blend mode" options=${BLEND} />
255
+ </div>
256
+ ${shadow && html`<div class="frow"><label class=${`nf ${has(s, "box-shadow") ? "" : "unset"} ${srcKind(s, "box-shadow") ? `src-${srcKind(s, "box-shadow")}` : ""}`} title=${`box-shadow · ${srcNote(s, "box-shadow")}`}>
257
+ <span class="nfl">Shadow</span><select class="nfs wide" onChange=${(e) => setShadow(e.target.value)}>${SHADOW_NAMES.map(([v, l]) => html`<option value=${v} selected=${v === preset}>${l}</option>`)}</select></label>
258
+ <${Remove} title="Remove the shadow" onClick=${() => { setCustom(false); return owns(s, "box-shadow") ? actions.resetProp("box-shadow") : actions.setProp("box-shadow", "none"); }} /></div>
259
+ ${preset === "custom" && html`<div class="frow"><${NumField} label="CSS" title="box-shadow: x y blur spread colour" value=${sh} set src=${srcKind(s, "box-shadow")} onReset=${resetAll(s, actions, ["box-shadow"])} onCommit=${(t) => actions.setProp("box-shadow", t)} /></div>`}`}
260
+ ${tw("blur") && html`<div class="frow"><${TwSelect} s=${s} k="blur" label="Blur" title="Blur the element (blur-*)" actions=${actions} /><${Remove} title="Remove the blur" onClick=${() => drop("blur")} /></div>`}
261
+ ${tw("backdropBlur") && html`<div class="frow"><${TwSelect} s=${s} k="backdropBlur" label="Backdrop" title="Blur what is behind it (backdrop-blur-*)" actions=${actions} /><${Remove} title="Remove the background blur" onClick=${() => drop("backdropBlur")} /></div>`}
262
+ ${tw("brightness") && html`<div class="frow"><${TwField} s=${s} k="brightness" label="Bright" title="Brightness % (brightness-*)" actions=${actions} /><${Remove} title="Remove the brightness" onClick=${() => drop("brightness")} /></div>`}
263
+ ${tw("grayscale") && html`<div class="frow"><${TwSelect} s=${s} k="grayscale" label="Gray" title="Grayscale (grayscale)" actions=${actions} /><${Remove} title="Remove the grayscale" onClick=${() => drop("grayscale")} /></div>`}
264
+ </${FSection}>`;
265
+ }
266
+
267
+ // ── Transform, Motion, Interaction: only what is set, + to add ───────────────────────────────────────────────────────────
268
+ /** A section of Tailwind groups that shows only the ones the element has (or that were just added), each with a ×. */
269
+ function GroupsSection({ s, actions, title, groups, addTitle }) {
270
+ const ui = useUi();
271
+ const [added, setAdded] = useState(/** @type {string[]} */ ([]));
272
+ const shown = groups.filter(([k]) => val(s, k, ui) || added.includes(k));
273
+ const items = groups.filter(([k]) => !shown.some(([x]) => x === k)).map(([k, l]) => [k, l]);
274
+ const drop = (k) => setAdded(added.filter((x) => x !== k));
275
+ return html`<${FSection} title=${title} extra=${html`<${AddMenu} title=${addTitle} items=${items} onPick=${(k) => setAdded([...added, k])} />`}>
276
+ ${shown.map(([k, l, kind]) => html`<div class="frow">${kind === "select"
277
+ ? html`<${TwSelect} s=${s} k=${k} label=${l} actions=${actions} />` : html`<${TwField} s=${s} k=${k} label=${l} actions=${actions} />`}
278
+ ${val(s, k, ui) ? html`<${Remove} title=${`Remove ${l.toLowerCase()}`} onClick=${() => { drop(k); actions.applyValue(k, ""); }} />` : html`<${Cancel} onClick=${() => drop(k)} />`}</div>`)}
279
+ </${FSection}>`;
280
+ }
281
+ export const TransformSection = ({ s, actions }) => html`<${GroupsSection} s=${s} actions=${actions} title="Transform" addTitle="Add a transform"
282
+ groups=${[["scale", "Scale"], ["rotate", "Rotate"], ["translateX", "Move X"], ["translateY", "Move Y"]]} />`;
283
+ export const MotionSection = ({ s, actions }) => html`<${GroupsSection} s=${s} actions=${actions} title="Motion" addTitle="Add a transition"
284
+ groups=${[["transition", "Transition", "select"], ["duration", "Time"], ["delay", "Delay"], ["ease", "Easing", "select"]]} />`;
285
+
286
+ const INTERACTION = [
287
+ { p: "cursor", l: "Cursor", t: "select", o: ["auto", "default", "pointer", "text", "move", "not-allowed", "grab", "grabbing", "crosshair", "help", "wait"] },
288
+ { p: "pointer-events", l: "Pointer", t: "select", o: ["auto", "none"] },
289
+ { p: "user-select", l: "Select", t: "select", o: ["auto", "none", "text", "all"] },
290
+ { p: "visibility", l: "Visible", t: "select", o: ["visible", "hidden"] },
291
+ { p: "object-fit", l: "Object fit", t: "select", o: ["fill", "contain", "cover", "none", "scale-down"] },
292
+ { p: "object-position", l: "Object pos", t: "text" },
293
+ ];
294
+ export function InteractionSection({ s, actions }) {
295
+ const [added, setAdded] = useState(/** @type {string[]} */ ([]));
296
+ const rows = INTERACTION.filter((c) => (has(s, c.p) && shownOf(s, c.p, srcOf(s, c.p)) !== "initial") || added.includes(c.p));
297
+ const left = INTERACTION.filter((c) => !rows.includes(c));
298
+ return html`<${FSection} title="Interaction" extra=${html`<${AddMenu} title="Add a setting" items=${left.map((c) => [c.p, c.l])} onPick=${(p) => setAdded([...added, p])} />`}>
299
+ ${rows.map((c) => html`<${PropRow} s=${s} actions=${actions} c=${c} onCancel=${added.includes(c.p) ? () => setAdded(added.filter((p) => p !== c.p)) : null} />`)}
300
+ </${FSection}>`;
301
+ }
302
+
303
+ // ── Anything else: a class, or a CSS declaration ─────────────────────────────────────────────────────────────────────────
304
+ /** "color: red" (a CSS declaration the browser knows) is set as a property; anything else is added as classes (hover:bg-blue-500 md:flex). */
305
+ export function AddBox({ actions }) {
306
+ const commit = (t) => {
307
+ const text = t.trim();
308
+ if (!text) return;
309
+ const m = text.match(/^([a-z-]+)\s*:\s+([^;]+);?$/i); // a space after the colon: a declaration, not hover:bg-...
310
+ if (m && CSS.supports(m[1], m[2].trim())) return actions.setProp(m[1].toLowerCase(), m[2].trim());
311
+ actions.addClasses(text);
312
+ };
313
+ return html`<div class="fsec"><div class="fsech"><span>Add class or CSS</span></div>
314
+ <${NumField} label="+" title="A class (hover:bg-blue-500, md:grid-cols-3) or a CSS declaration (color: red), then Enter" placeholder="hover:underline or color: red" value="" set onCommit=${commit} /></div>`;
315
+ }
@@ -0,0 +1,65 @@
1
+ // The Tailwind class names the code editor offers while typing inside class="…": the utilities people use every day (spacing, sizing,
2
+ // layout, type, colour, borders, effects, motion) and the variants that go in front of them (hover:, md:, dark:…). Built once, on first use.
3
+ const SPACING = ["0", "px", "0.5", "1", "1.5", "2", "2.5", "3", "3.5", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "16", "20", "24", "28", "32", "36", "40", "44", "48", "52", "56", "60", "64", "72", "80", "96"];
4
+ const FRACTIONS = ["1/2", "1/3", "2/3", "1/4", "2/4", "3/4", "1/5", "2/5", "3/5", "4/5", "1/6", "5/6", "1/12", "11/12"];
5
+ const SIZE_WORDS = ["auto", "full", "screen", "min", "max", "fit", "svw", "dvh", "lvh", "svh"];
6
+ const PALETTES = ["slate", "gray", "zinc", "neutral", "stone", "red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", "cyan", "sky", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose"];
7
+ const SHADES = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900", "950"];
8
+ const COLOR_WORDS = ["white", "black", "transparent", "current", "inherit"];
9
+ const SCALE = ["xs", "sm", "base", "lg", "xl", "2xl", "3xl", "4xl", "5xl", "6xl", "7xl", "8xl", "9xl"];
10
+
11
+ const STATIC = `block inline-block inline flex inline-flex grid inline-grid contents hidden table flow-root
12
+ static fixed absolute relative sticky visible invisible collapse
13
+ flex-row flex-row-reverse flex-col flex-col-reverse flex-wrap flex-wrap-reverse flex-nowrap flex-1 flex-auto flex-initial flex-none grow grow-0 shrink shrink-0
14
+ justify-start justify-end justify-center justify-between justify-around justify-evenly justify-stretch
15
+ items-start items-end items-center items-baseline items-stretch content-start content-end content-center content-between content-around
16
+ self-auto self-start self-end self-center self-stretch place-content-center place-items-center
17
+ overflow-auto overflow-hidden overflow-clip overflow-visible overflow-scroll overflow-x-auto overflow-y-auto overflow-x-hidden overflow-y-hidden
18
+ truncate text-ellipsis text-clip whitespace-normal whitespace-nowrap whitespace-pre whitespace-pre-line whitespace-pre-wrap break-normal break-words break-all
19
+ text-left text-center text-right text-justify text-start text-end uppercase lowercase capitalize normal-case italic not-italic underline overline line-through no-underline
20
+ font-thin font-extralight font-light font-normal font-medium font-semibold font-bold font-extrabold font-black font-sans font-serif font-mono
21
+ leading-none leading-tight leading-snug leading-normal leading-relaxed leading-loose tracking-tighter tracking-tight tracking-normal tracking-wide tracking-wider tracking-widest
22
+ border border-0 border-2 border-4 border-8 border-t border-r border-b border-l border-x border-y border-solid border-dashed border-dotted border-double border-none border-collapse border-separate
23
+ rounded rounded-none rounded-sm rounded-md rounded-lg rounded-xl rounded-2xl rounded-3xl rounded-full rounded-t rounded-b rounded-l rounded-r rounded-t-lg rounded-b-lg rounded-l-lg rounded-r-lg
24
+ shadow shadow-sm shadow-md shadow-lg shadow-xl shadow-2xl shadow-inner shadow-none ring ring-0 ring-1 ring-2 ring-4 ring-8 ring-inset outline outline-none outline-dashed outline-2
25
+ blur blur-none blur-sm blur-md blur-lg blur-xl backdrop-blur backdrop-blur-sm backdrop-blur-md backdrop-blur-lg backdrop-blur-xl grayscale invert sepia
26
+ transition transition-all transition-colors transition-opacity transition-shadow transition-transform transition-none ease-linear ease-in ease-out ease-in-out
27
+ duration-75 duration-100 duration-150 duration-200 duration-300 duration-500 duration-700 duration-1000 delay-75 delay-100 delay-150 delay-200 delay-300 delay-500
28
+ transform scale-0 scale-50 scale-75 scale-90 scale-95 scale-100 scale-105 scale-110 scale-125 scale-150 rotate-0 rotate-1 rotate-2 rotate-3 rotate-6 rotate-12 rotate-45 rotate-90 rotate-180
29
+ -rotate-1 -rotate-2 -rotate-3 -rotate-6 -rotate-12 -rotate-45 -rotate-90 -rotate-180
30
+ animate-none animate-spin animate-ping animate-pulse animate-bounce
31
+ cursor-auto cursor-default cursor-pointer cursor-wait cursor-text cursor-move cursor-not-allowed cursor-grab cursor-grabbing select-none select-text select-all pointer-events-none pointer-events-auto resize resize-none resize-x resize-y
32
+ object-contain object-cover object-fill object-none object-scale-down object-center object-top object-bottom object-left object-right
33
+ aspect-auto aspect-square aspect-video list-none list-disc list-decimal list-inside list-outside
34
+ opacity-0 opacity-5 opacity-10 opacity-20 opacity-25 opacity-30 opacity-40 opacity-50 opacity-60 opacity-70 opacity-75 opacity-80 opacity-90 opacity-95 opacity-100
35
+ z-0 z-10 z-20 z-30 z-40 z-50 z-auto sr-only not-sr-only container mx-auto my-auto
36
+ bg-fixed bg-local bg-scroll bg-cover bg-contain bg-center bg-top bg-bottom bg-left bg-right bg-no-repeat bg-repeat bg-clip-text bg-none
37
+ bg-gradient-to-t bg-gradient-to-tr bg-gradient-to-r bg-gradient-to-br bg-gradient-to-b bg-gradient-to-bl bg-gradient-to-l bg-gradient-to-tl
38
+ grid-cols-1 grid-cols-2 grid-cols-3 grid-cols-4 grid-cols-5 grid-cols-6 grid-cols-12 grid-rows-1 grid-rows-2 grid-rows-3 grid-rows-4 col-span-1 col-span-2 col-span-3 col-span-4 col-span-6 col-span-full row-span-1 row-span-2 row-span-3
39
+ isolate mix-blend-multiply mix-blend-screen mix-blend-overlay`.split(/\s+/);
40
+
41
+ const VARIANTS = ["hover", "focus", "focus-visible", "focus-within", "active", "visited", "disabled", "checked", "required", "invalid", "placeholder-shown", "read-only", "first", "last", "odd", "even", "only", "empty", "group-hover", "group-focus", "peer-hover", "peer-focus", "peer-checked", "placeholder", "before", "after", "selection", "marker", "file", "dark", "print", "motion-reduce", "sm", "md", "lg", "xl", "2xl", "max-sm", "max-md", "max-lg", "max-xl"];
42
+
43
+ let all = null;
44
+ /** Every class name offered, with the variants as `hover:` entries on their own. */
45
+ export function tailwindClasses() {
46
+ if (all) return all;
47
+ const out = new Set(STATIC);
48
+ const sizes = [...SPACING, ...FRACTIONS, ...SIZE_WORDS];
49
+ for (const p of ["p", "px", "py", "pt", "pr", "pb", "pl", "ps", "pe"]) SPACING.forEach((v) => out.add(`${p}-${v}`));
50
+ for (const p of ["m", "mx", "my", "mt", "mr", "mb", "ml", "ms", "me"]) { SPACING.forEach((v) => { out.add(`${p}-${v}`); if (v !== "0") out.add(`-${p}-${v}`); }); out.add(`${p}-auto`); }
51
+ for (const p of ["gap", "gap-x", "gap-y", "space-x", "space-y"]) SPACING.forEach((v) => out.add(`${p}-${v}`));
52
+ for (const p of ["w", "h", "size", "min-w", "min-h"]) sizes.forEach((v) => out.add(`${p}-${v}`));
53
+ for (const p of ["inset", "inset-x", "inset-y", "top", "right", "bottom", "left"]) [...SPACING, ...FRACTIONS, "auto", "full"].forEach((v) => { out.add(`${p}-${v}`); if (v !== "0" && v !== "auto") out.add(`-${p}-${v}`); });
54
+ ["none", "xs", "sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl", "6xl", "7xl", "full", "screen", "prose", "min", "max", "fit"].forEach((v) => { out.add(`max-w-${v}`); out.add(`max-h-${v}`); });
55
+ SCALE.forEach((v) => out.add(`text-${v}`));
56
+ ["text", "bg", "border", "ring", "from", "via", "to", "fill", "stroke", "divide", "outline", "decoration", "accent", "caret", "shadow", "placeholder"].forEach((p) => {
57
+ COLOR_WORDS.forEach((c) => out.add(`${p}-${c}`));
58
+ PALETTES.forEach((c) => SHADES.forEach((s) => out.add(`${p}-${c}-${s}`)));
59
+ });
60
+ for (const side of ["t", "r", "b", "l", "x", "y"]) PALETTES.forEach((c) => SHADES.forEach((s) => out.add(`border-${side}-${c}-${s}`)));
61
+ VARIANTS.forEach((v) => out.add(`${v}:`));
62
+ all = [...out];
63
+ return all;
64
+ }
65
+ export const TAILWIND_VARIANTS = VARIANTS;
@@ -0,0 +1,43 @@
1
+ // The editor's side of embedEditor() (embed.js): it runs inside the iframe, takes its settings from the embedding page, asks that page's
2
+ // host for saving through messages, and reports changes back. See embed.js for the messages.
3
+ import { mountEditor } from "./index.js";
4
+
5
+ const parentWin = window.parent;
6
+ const post = (msg) => parentWin.postMessage({ wc: "editor", ...msg }, "*");
7
+ let seq = 0;
8
+ const waiting = new Map();
9
+
10
+ /** A host whose methods are answered by the embedding page. */
11
+ const proxyHost = (names) => Object.fromEntries(names.map((name) => [name, (...args) => new Promise((resolve, reject) => {
12
+ const id = ++seq;
13
+ waiting.set(id, { resolve, reject });
14
+ post({ t: "rpc", id, method: name, args: args.filter((a) => typeof a !== "function") });
15
+ })]));
16
+
17
+ let api = null;
18
+ addEventListener("message", async (e) => {
19
+ const m = e.data;
20
+ if (e.source !== parentWin || !m || m.wc !== "host") return;
21
+ if (m.t === "init") {
22
+ api = await mountEditor(document.getElementById("root"), {
23
+ host: proxyHost(m.hostMethods), data: m.data, ui: { ...m.ui, onDetails: (fields) => post({ t: "details", fields }) }, tailwind: m.tailwind !== false,
24
+ });
25
+ api.onChange((state) => post({ t: "change", state }));
26
+ post({ t: "mounted", html: api.getHtml(), details: api.details() });
27
+ // the first design is on the canvas: the embedding page can drop its loading message (or after 8 seconds, whatever happens)
28
+ let told = false;
29
+ const painted = () => { if (!told) { told = true; post({ t: "painted" }); } };
30
+ document.addEventListener("wc-editor-ready", painted, { once: true });
31
+ setTimeout(painted, 8000);
32
+ } else if (m.t === "rpcResult") {
33
+ const w = waiting.get(m.id);
34
+ waiting.delete(m.id);
35
+ if (w) m.ok ? w.resolve(m.value) : w.reject(new Error(m.error));
36
+ } else if (api && m.t === "setHtml") api.setHtml(m.html);
37
+ else if (api && m.t === "save") api.save();
38
+ else if (api && m.t === "release") api.release();
39
+ else if (api && m.t === "saveDetails") {
40
+ try { await api.saveDetails(m.fields); post({ t: "detailsResult", id: m.id, ok: true }); } catch (err) { post({ t: "detailsResult", id: m.id, ok: false, error: err.message || "Could not save" }); }
41
+ }
42
+ });
43
+ post({ t: "ready" });
@@ -0,0 +1,15 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Windcraft editor</title>
7
+ <!-- The page embedEditor() puts in an iframe. Map the package names the way the page that embeds it does (a bundler does the same). -->
8
+ <script type="importmap">{ "imports": { "@windcraft/core/": "/core/", "@windcraft/editor/": "/editor/" } }</script>
9
+ <style>html, body, #root { height: 100%; margin: 0; }</style>
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ <script type="module" src="./embed-frame.js"></script>
14
+ </body>
15
+ </html>