@kubex/zinc 1.1.68 → 1.1.70

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 (37) hide show
  1. package/dist/custom-elements.json +1719 -282
  2. package/dist/vscode.html-custom-data.json +160 -29
  3. package/dist/web-types.json +395 -70
  4. package/dist/zn.d.ts +395 -16
  5. package/dist/zn.min.js +580 -408
  6. package/docs/pages/components/collapsible.md +6 -2
  7. package/docs/pages/components/icon-picker.md +14 -0
  8. package/docs/pages/components/input.md +19 -1
  9. package/docs/pages/components/preview-frame-demo.njk +33 -4
  10. package/docs/pages/components/preview-frame.md +20 -0
  11. package/docs/pages/components/theme-editor.md +303 -0
  12. package/docs/superpowers/plans/2026-08-03-theme-editor.md +1536 -0
  13. package/docs/superpowers/specs/2026-08-03-theme-editor-design.md +327 -0
  14. package/package.json +1 -1
  15. package/src/components/collapsible/collapsible.component.ts +21 -23
  16. package/src/components/dropdown/dropdown.component.ts +9 -0
  17. package/src/components/editor/editor.component.ts +20 -21
  18. package/src/components/file/file.component.ts +15 -0
  19. package/src/components/icon-picker/icon-picker.component.ts +150 -16
  20. package/src/components/icon-picker/icon-picker.scss +32 -0
  21. package/src/components/input/input.component.ts +44 -21
  22. package/src/components/input/input.scss +134 -42
  23. package/src/components/input/input.test.ts +45 -0
  24. package/src/components/preview-frame/preview-frame.component.ts +126 -16
  25. package/src/components/preview-frame/preview-frame.scss +27 -0
  26. package/src/components/preview-frame/preview-frame.test.ts +253 -0
  27. package/src/components/theme-editor/index.ts +12 -0
  28. package/src/components/theme-editor/theme-editor.component.ts +918 -0
  29. package/src/components/theme-editor/theme-editor.scss +309 -0
  30. package/src/components/theme-editor/theme-editor.test.ts +1752 -0
  31. package/src/events/events.ts +2 -0
  32. package/src/events/zn-theme-change.ts +13 -0
  33. package/src/events/zn-theme-submit.ts +9 -0
  34. package/src/types/web-test-runner-commands.d.ts +6 -0
  35. package/src/zinc.ts +1 -0
  36. package/tsconfig.json +7 -1
  37. package/web-test-runner.config.js +3 -1
@@ -0,0 +1,918 @@
1
+ import { type CSSResultGroup, html, nothing, type PropertyValues, unsafeCSS } from 'lit';
2
+ import { HasSlotController } from '../../internal/slot';
3
+ import { ifDefined } from 'lit/directives/if-defined.js';
4
+ import { MutationController } from '@lit-labs/observers/mutation-controller.js';
5
+ import { property, query, queryAll, state } from 'lit/decorators.js';
6
+ import ZincElement from '../../internal/zinc-element';
7
+ import ZnButton from '../button';
8
+ import ZnCollapsible from '../collapsible';
9
+ import ZnIcon from '../icon';
10
+ import ZnNavbar from '../navbar';
11
+ import ZnOption from '../option';
12
+ import ZnPreviewFrame from '../preview-frame';
13
+ import ZnSelect from '../select';
14
+ import ZnTabs from '../tabs';
15
+ import type { ZnErrorEvent } from '../../events/zn-error';
16
+
17
+ import styles from './theme-editor.scss';
18
+
19
+ export type ThemeEditorMode = 'light' | 'dark';
20
+ export type ThemeEditorDevice = 'desktop' | 'tablet' | 'mobile';
21
+
22
+ export interface ThemeEditorGroup {
23
+ /** The slot name controls are assigned to with `slot="<name>"`. */
24
+ name: string;
25
+ caption: string;
26
+ description?: string;
27
+ /** Renders expanded initially. */
28
+ open?: boolean;
29
+ }
30
+
31
+ export interface ThemeEditorSection extends ThemeEditorGroup {
32
+ /**
33
+ * Nests a collapsible per group inside this section's tab instead of the
34
+ * section's own controls directly. A non-empty `groups` on ANY section
35
+ * switches every section to `zn-tabs`, regardless of `section-layout`.
36
+ */
37
+ groups?: ThemeEditorGroup[];
38
+ }
39
+
40
+ export interface ThemeEditorSource {
41
+ label: string;
42
+ src: string;
43
+ }
44
+
45
+ // Controls whose state lives on `checked` rather than `value`.
46
+ const BOOLEAN_CONTROLS = new Set(['zn-checkbox', 'zn-toggle']);
47
+
48
+ // Matches theme-editor.scss's stacked breakpoint - keep both in sync.
49
+ const STACKED_QUERY = '(max-width: 768px)';
50
+
51
+ const DEVICES: { id: ThemeEditorDevice; icon: string; label: string }[] = [
52
+ { id: 'desktop', icon: 'monitor', label: 'Desktop' },
53
+ { id: 'tablet', icon: 'tablet', label: 'Tablet' },
54
+ { id: 'mobile', icon: 'smartphone', label: 'Mobile' },
55
+ ];
56
+
57
+ interface HarvestableControl extends HTMLElement {
58
+ name?: string;
59
+ value?: unknown;
60
+ checked?: boolean;
61
+ disabled?: boolean;
62
+ type?: string;
63
+ }
64
+
65
+ /** Turns a freeform `group`/`category` label into a slot-safe name. */
66
+ function slugify(label: string): string {
67
+ return label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
68
+ }
69
+
70
+ interface DerivedStructure {
71
+ sections: ThemeEditorSection[];
72
+ /** The slot name each control must be assigned to. */
73
+ assignments: Map<Element, string>;
74
+ }
75
+
76
+ /**
77
+ * @summary A theme editor: slotted form controls drive a live preview frame,
78
+ * with a toolbar for the preview's light/dark mode and device width.
79
+ * @documentation https://zinc.style/components/theme-editor
80
+ * @status experimental
81
+ * @since 1.0
82
+ *
83
+ * @dependency zn-collapsible
84
+ * @dependency zn-preview-frame
85
+ * @dependency zn-icon
86
+ * @dependency zn-button
87
+ * @dependency zn-tabs
88
+ * @dependency zn-navbar
89
+ * @dependency zn-select
90
+ *
91
+ * @event zn-theme-change - Emitted when the values, mode or device change.
92
+ * @event zn-theme-submit - Emitted on submit (button click), carrying the
93
+ * current values. With `action` set, only fires after a successful save.
94
+ * @event zn-error - Emitted when a save fails. Also seen for preview render
95
+ * failures: the frame's zn-error is composed and not stopped, so it bubbles
96
+ * out through the editor too.
97
+ *
98
+ * @slot - Ungrouped theme controls, rendered above any sections. Controls
99
+ * assigned `slot="<name>"` matching a `sections` entry (or, when nested, a
100
+ * `groups` entry) render inside that section/group instead. Harvesting and
101
+ * change detection walk every slot's full assigned subtree, not just direct
102
+ * children.
103
+ *
104
+ * With `sections` left unset, the structure is instead derived from the
105
+ * controls' own attributes: `group="<label>"` becomes a tab and
106
+ * `category="<label>"` a collapsible within it, and the control is slotted
107
+ * into that collapsible automatically. Either attribute works alone - a
108
+ * control with only `group` sits directly in its tab, and one with only
109
+ * `category` becomes its own top-level section. Setting `sections`
110
+ * explicitly disables the derivation entirely.
111
+ * @slot toolbar - Actions in the toolbar, right-aligned beside the device
112
+ * controls. Where a save button belongs.
113
+ * @slot footer - Actions pinned beneath the controls. The built-in submit button
114
+ * lives in the toolbar, not here.
115
+ *
116
+ * @csspart base - The component's base wrapper.
117
+ * @csspart controls - The left-hand controls column, full height.
118
+ * @csspart controls-header - The controls column's header row: `controls-caption` on the left, the light/dark mode toggle on the right.
119
+ * @csspart toolbar - The preview column's header row: `preview-caption` on the left, the device switcher (and sources/submit) on the right. Spans the preview column only.
120
+ * @csspart section - A rendered section's or group's collapsible (`section-layout="collapsible"`, or any nested group).
121
+ * @csspart footer - The footer wrapper beneath the controls.
122
+ * @csspart preview - The preview column.
123
+ * @csspart error - The inline error strip.
124
+ * @csspart preview__base - The frame's base wrapper (forwarded from zn-preview-frame).
125
+ * @csspart preview__stage - The frame's device-width wrapper (forwarded from zn-preview-frame).
126
+ * @csspart preview__iframe - The frame's iframe (forwarded from zn-preview-frame).
127
+ * @csspart preview__error - The frame's own error overlay (forwarded from zn-preview-frame).
128
+ *
129
+ * @cssproperty --zn-theme-editor-controls-width - Width of the controls column.
130
+ */
131
+ export default class ZnThemeEditor extends ZincElement {
132
+ static styles: CSSResultGroup = unsafeCSS(styles);
133
+ static dependencies = {
134
+ 'zn-collapsible': ZnCollapsible,
135
+ 'zn-preview-frame': ZnPreviewFrame,
136
+ 'zn-icon': ZnIcon,
137
+ 'zn-button': ZnButton,
138
+ 'zn-tabs': ZnTabs,
139
+ 'zn-navbar': ZnNavbar,
140
+ 'zn-select': ZnSelect,
141
+ 'zn-option': ZnOption,
142
+ };
143
+
144
+ /** URL of the preview shell page; forwarded to the frame. */
145
+ @property() src = '';
146
+
147
+ /** Expected origin of the iframe; forwarded to the frame. */
148
+ @property({ attribute: 'frame-origin' }) frameOrigin = '';
149
+
150
+ /** Optional endpoint returning the base hp-preview:config payload. */
151
+ @property({ attribute: 'data-uri' }) dataUri = '';
152
+
153
+ /** Which mode the preview renders in. Travels in the theme payload. */
154
+ @property({ reflect: true }) mode: ThemeEditorMode = 'light';
155
+
156
+ /** Preview viewport width. Resizes the frame only; not part of the payload. */
157
+ @property({ reflect: true }) device: ThemeEditorDevice = 'desktop';
158
+
159
+ /** Minimum height of the preview row, in pixels; forwarded to the frame as its own floor. */
160
+ @property({ type: Number, attribute: 'min-height' }) minHeight = 480;
161
+
162
+ /** Debounce in ms between a control change and the push to the preview. */
163
+ @property({ type: Number }) debounce = 150;
164
+
165
+ /** Optional endpoint the values are POSTed to. Empty = no persistence. */
166
+ @property() action = '';
167
+
168
+ /** Debounce in ms between a control change and the save POST. */
169
+ @property({ type: Number, attribute: 'save-debounce' }) saveDebounce = 1000;
170
+
171
+ /**
172
+ * Groups controls into named sections. Empty/unset falls back to deriving the
173
+ * structure from the controls' own `group`/`category` attributes, and renders
174
+ * one ungrouped column when they carry neither. A section with a non-empty
175
+ * `groups` nests a collapsible per group inside a `zn-tabs` tab for that
176
+ * section - see `groups` on `ThemeEditorSection`.
177
+ */
178
+ @property({ type: Array }) sections: ThemeEditorSection[] = [];
179
+
180
+ /**
181
+ * Presentation for flat, group-less `sections`: stacked `zn-collapsible`s
182
+ * (default) or a `zn-tabs` strip. Ignored once any section has `groups` -
183
+ * nested sections always render as tabs.
184
+ */
185
+ @property({ attribute: 'section-layout' }) sectionLayout: 'collapsible' | 'tabs' = 'collapsible';
186
+
187
+ /** Dropdown of preview sources, `{label, src}`, rendered in the toolbar. Empty/unset renders no dropdown; the first entry wins over an explicit `src` when non-empty. */
188
+ @property({ type: Array }) sources: ThemeEditorSource[] = [];
189
+
190
+ /** Collapses the controls column. */
191
+ @property({ type: Boolean, reflect: true, attribute: 'controls-collapsed' }) controlsCollapsed = false;
192
+
193
+ /** Presents the editor as its own bordered, rounded panel with a plain preview backdrop, rather than embedded in a dotted canvas. */
194
+ @property({ type: Boolean, reflect: true }) standalone = false;
195
+
196
+ /** Caption in the controls column's header row. Empty (default) renders no text; the row itself always renders. */
197
+ @property({ attribute: 'controls-caption' }) controlsCaption = '';
198
+
199
+ /** Caption at the left of the toolbar, opposite the device and mode controls. Empty (default) renders no text. */
200
+ @property({ attribute: 'preview-caption' }) previewCaption = '';
201
+
202
+ /** Label for the built-in submit button. Empty (default) renders no button. */
203
+ @property({ attribute: 'submit-label' }) submitLabel = '';
204
+
205
+ /** Disables the debounced auto-save; saving then happens only via submit. Preview pushes are unaffected. */
206
+ @property({ type: Boolean }) manual = false;
207
+
208
+ @query('zn-preview-frame') frame: ZnPreviewFrame;
209
+
210
+ @query('slot:not([name])') private controlsSlot: HTMLSlotElement;
211
+
212
+ @queryAll('.editor__section-slot') private sectionSlots: NodeListOf<HTMLSlotElement>;
213
+
214
+ @state() protected error = '';
215
+
216
+ @state() private _submitting = false;
217
+
218
+ // Which `sources` entry drives the frame's src. Purely a view toggle -
219
+ // never read by harvesting, seeding or the push/save pipeline.
220
+ @state() private _sourceIndex = 0;
221
+
222
+ private readonly hasSlotController = new HasSlotController(this, 'footer', '[default]');
223
+
224
+ private _pushTimer?: number;
225
+ private _saveTimer?: number;
226
+ private _saving = false;
227
+ private _saveQueued = false;
228
+ private _saveWaiters: ((ok: boolean) => void)[] = [];
229
+
230
+ // Mirrors page-builder's one-shot auto-collapse on crossing into narrow.
231
+ private readonly _narrowQuery = window.matchMedia(STACKED_QUERY);
232
+ private _wasNarrow = false;
233
+
234
+ // firstUpdated(), slotchange and the mutation observer below all race to
235
+ // report the same initial state. Track the deep set of named controls (not
236
+ // their values) so any redundant echo is a no-op while a genuine change -
237
+ // including one nested inside an already-assigned section - still pushes.
238
+ // Never gates _push() itself: any real control value change always pushes.
239
+ private _mounted = false;
240
+ private _lastControls: HarvestableControl[] = [];
241
+
242
+ // childList+subtree only, NEVER attributes - zn-checkbox reflects `checked`
243
+ // to an attribute, and write-back assigns .checked on mode toggle, which
244
+ // would otherwise feed straight back into this guard. Exposed as a field
245
+ // (rather than inlined) so a test can pin the config directly.
246
+ private readonly _controlsObserverConfig: MutationObserverInit = { childList: true, subtree: true };
247
+
248
+ private readonly _controlsObserver = new MutationController(this, {
249
+ target: null,
250
+ config: this._controlsObserverConfig,
251
+ callback: () => this._pushIfControlsChanged(),
252
+ });
253
+
254
+ // Per-mode value sets. Seeded once per control name (never re-seeded, so a
255
+ // user's edits survive later controls being added) and otherwise updated by
256
+ // harvesting the DOM into the active mode only.
257
+ private _modeValues: Record<ThemeEditorMode, Record<string, unknown>> = { light: {}, dark: {} };
258
+
259
+ // Suppresses _onControlChange while write-back assigns .value/.checked
260
+ // programmatically. This IS load-bearing: zn-input's color-format watcher
261
+ // can emit zn-change from inside a later Lit update() - after the
262
+ // microtasks of this call stack, not during it - e.g. when a dark-value is
263
+ // authored in a different colour-string representation than value. A depth
264
+ // counter (not a boolean) so overlapping write-backs (e.g. a slot change
265
+ // and a mode toggle landing close together) don't let one's cleanup clear
266
+ // the other's guard early.
267
+ private _suppressDepth = 0;
268
+
269
+ // One-shot: the initial auto-expand must not fight a user who closes it.
270
+ private _openedInitialCollapsible = false;
271
+
272
+ /** The current per-mode value sets. Returns copies. */
273
+ get values(): { light: Record<string, unknown>; dark: Record<string, unknown> } {
274
+ return { light: { ...this._modeValues.light }, dark: { ...this._modeValues.dark } };
275
+ }
276
+
277
+ /** The active mode's values - what gets pushed to the preview frame. */
278
+ get activeValues(): Record<string, unknown> {
279
+ return { ...this._modeValues[this.mode] };
280
+ }
281
+
282
+ /** The default slot plus every rendered section slot. */
283
+ private _controlSlots(): HTMLSlotElement[] {
284
+ return [this.controlsSlot, ...Array.from(this.sectionSlots ?? [])]
285
+ .filter((slot): slot is HTMLSlotElement => !!slot);
286
+ }
287
+
288
+ /** Walks every control slot (default and sections) for every enabled, named control. */
289
+ private _harvestNamed(): { name: string; control: HarvestableControl }[] {
290
+ const found: { name: string; control: HarvestableControl }[] = [];
291
+
292
+ for (const slot of this._controlSlots()) {
293
+ const roots = slot.assignedElements({ flatten: true });
294
+ for (const root of roots) {
295
+ const candidates = [root, ...Array.from(root.querySelectorAll('[name]'))];
296
+ for (const candidate of candidates) {
297
+ const control = candidate as HarvestableControl;
298
+ if (!control.getAttribute?.('name') || control.disabled) continue;
299
+ found.push({ name: control.getAttribute('name')!, control });
300
+ }
301
+ }
302
+ }
303
+
304
+ return found;
305
+ }
306
+
307
+ /** Whether a direct child is assigned to the named slot — an empty section renders no chrome. */
308
+ private _hasAssignedControls(slotName: string): boolean {
309
+ return Array.from(this.children).some(el => el.getAttribute('slot') === slotName);
310
+ }
311
+
312
+ private _isBooleanControl(control: HarvestableControl): boolean {
313
+ return BOOLEAN_CONTROLS.has(control.tagName.toLowerCase()) || control.type === 'checkbox';
314
+ }
315
+
316
+ private _readControlValue(control: HarvestableControl): unknown {
317
+ return this._isBooleanControl(control) ? !!control.checked : control.value;
318
+ }
319
+
320
+ /** Seeds light/dark entries for any control name not already present. */
321
+ private _seed() {
322
+ for (const { name, control } of this._harvestNamed()) {
323
+ if (name in this._modeValues.light) continue;
324
+
325
+ const light = this._readControlValue(control);
326
+ this._modeValues.light[name] = light;
327
+
328
+ const darkAttr = control.getAttribute('dark-value');
329
+ this._modeValues.dark[name] = darkAttr === null
330
+ ? light
331
+ : this._isBooleanControl(control)
332
+ ? (darkAttr === '1' || darkAttr === 'true')
333
+ : darkAttr;
334
+ }
335
+ }
336
+
337
+ /** Writes a mode's value set back into the controls so they display it. */
338
+ private _writeBack(mode: ThemeEditorMode = this.mode) {
339
+ // Only assign - and only suppress - controls whose displayed value is
340
+ // actually about to change. Most write-backs (e.g. mount seeding a
341
+ // control from its own current value) are true no-ops; skipping the
342
+ // assignment entirely means no Lit update is triggered for them, so
343
+ // there is nothing to suppress and no window during which an unrelated,
344
+ // genuinely new edit to that same control could be wrongly swallowed.
345
+ let wrote = false;
346
+ for (const { name, control } of this._harvestNamed()) {
347
+ if (!(name in this._modeValues[mode])) continue;
348
+ const value = this._modeValues[mode][name];
349
+ const isBoolean = this._isBooleanControl(control);
350
+ const current = isBoolean ? !!control.checked : control.value;
351
+ if (isBoolean ? current === value : String(current) === String(value)) continue;
352
+
353
+ wrote = true;
354
+ if (isBoolean) {
355
+ control.checked = !!value;
356
+ } else {
357
+ control.value = value;
358
+ }
359
+ }
360
+
361
+ if (!wrote) return;
362
+
363
+ // Lit's update cycle is never synchronous with the assignments above, and
364
+ // a watched-property handler can emit after several microtask hops of
365
+ // its own (e.g. an internal `await this.updateComplete`). A macrotask
366
+ // boundary is cruder than awaiting updateComplete directly, but it
367
+ // reliably outlasts however many microtask hops that chain takes,
368
+ // without this method needing to know the shape of that chain.
369
+ this._suppressDepth++;
370
+ window.setTimeout(() => {
371
+ this._suppressDepth--;
372
+ }, 0);
373
+ }
374
+
375
+ /** Harvests the controls' current displayed values into a mode's set. */
376
+ private _harvestInto(mode: ThemeEditorMode) {
377
+ for (const { name, control } of this._harvestNamed()) {
378
+ this._modeValues[mode][name] = this._readControlValue(control);
379
+ }
380
+ }
381
+
382
+ connectedCallback() {
383
+ super.connectedCallback();
384
+ this._controlsObserver.observe(this);
385
+ this._narrowQuery.addEventListener('change', this._onNarrowChange);
386
+ this._onNarrowChange(this._narrowQuery);
387
+ }
388
+
389
+ disconnectedCallback() {
390
+ if (this._pushTimer) window.clearTimeout(this._pushTimer);
391
+ if (this._saveTimer) window.clearTimeout(this._saveTimer);
392
+ this._narrowQuery.removeEventListener('change', this._onNarrowChange);
393
+ super.disconnectedCallback();
394
+ }
395
+
396
+ private readonly _onNarrowChange = (e: MediaQueryList | MediaQueryListEvent) => {
397
+ if (e.matches && !this._wasNarrow) this.controlsCollapsed = true;
398
+ this._wasNarrow = e.matches;
399
+ };
400
+
401
+ protected firstUpdated() {
402
+ // Push the authored defaults immediately so the preview never renders
403
+ // un-themed and then snaps to the real values. The frame retains the
404
+ // payload and replays it after its ready handshake. Routed through the
405
+ // same assignment-change gate as _onSlotChange so that whichever of the
406
+ // two fires first performs the mount push and the other — seeing an
407
+ // unchanged control set — is a no-op, regardless of firing order.
408
+ this._pushIfControlsChanged();
409
+ }
410
+
411
+ /** Pushes the active mode's values into the preview and announces it. */
412
+ private _push() {
413
+ // Optimistically clear a frame-sourced error: the frame clears its own
414
+ // overlay on hp-preview:rendered, and a failing save re-sets this on its
415
+ // own (longer) debounce.
416
+ this.error = '';
417
+ this.frame?.setTheme({ mode: this.mode, values: this.activeValues });
418
+ this._announce();
419
+ }
420
+
421
+ private _queueSave() {
422
+ if (!this.action || this.manual) return;
423
+ if (this._saveTimer) window.clearTimeout(this._saveTimer);
424
+ this._saveTimer = window.setTimeout(() => {
425
+ this._saveTimer = undefined;
426
+ void this._save();
427
+ }, this.saveDebounce);
428
+ }
429
+
430
+ // Saves serialize through a single slot: changes arriving mid-flight collapse
431
+ // into exactly one follow-up save, so overlapping POSTs can't land out of
432
+ // order and persist a stale value. Waiters queued via _awaitSave() are only
433
+ // resolved by whichever run finishes with nothing further queued behind it -
434
+ // the run that actually carries their values, not necessarily this call.
435
+ private async _save() {
436
+ if (this._saving) {
437
+ this._saveQueued = true;
438
+ return;
439
+ }
440
+ this._saving = true;
441
+ let ok = false;
442
+
443
+ try {
444
+ const body = new FormData();
445
+ for (const mode of ['light', 'dark'] as ThemeEditorMode[]) {
446
+ for (const [name, value] of Object.entries(this._modeValues[mode])) {
447
+ body.append(`${mode}[${name}]`, typeof value === 'boolean' ? (value ? '1' : '') : String(value ?? ''));
448
+ }
449
+ }
450
+ const response = await fetch(this.action, {
451
+ method: 'POST',
452
+ credentials: 'same-origin',
453
+ body,
454
+ });
455
+ if (!response.ok) {
456
+ throw new Error(await response.text() || response.statusText);
457
+ }
458
+ this.error = '';
459
+ ok = true;
460
+ } catch (err) {
461
+ this._fail(err instanceof Error ? err.message : String(err));
462
+ } finally {
463
+ this._saving = false;
464
+ if (this._saveQueued) {
465
+ this._saveQueued = false;
466
+ void this._save();
467
+ } else {
468
+ const waiters = this._saveWaiters;
469
+ this._saveWaiters = [];
470
+ waiters.forEach(resolve => resolve(ok));
471
+ }
472
+ }
473
+ }
474
+
475
+ /** Resolves once a save actually carrying the current values has settled. */
476
+ private _awaitSave(): Promise<boolean> {
477
+ return new Promise(resolve => {
478
+ this._saveWaiters.push(resolve);
479
+ void this._save();
480
+ });
481
+ }
482
+
483
+ /**
484
+ * Pushes only if the deep set of named controls (the same set harvesting
485
+ * walks, so it includes controls nested inside sections) has changed since
486
+ * the last push. Comparison is by element identity only, never by value.
487
+ */
488
+ private _pushIfControlsChanged() {
489
+ // A section's rendered chrome depends on live slot assignment - recompute every time.
490
+ this.requestUpdate();
491
+
492
+ const current = this._harvestNamed().map(({ control }) => control);
493
+ const changed = !this._mounted
494
+ || current.length !== this._lastControls.length
495
+ || current.some((el, i) => el !== this._lastControls[i]);
496
+
497
+ if (!changed) return;
498
+
499
+ this._flushPendingEdit();
500
+ this._mounted = true;
501
+ this._lastControls = current;
502
+ this._seed();
503
+ // Write back so an editor authored with mode="dark" displays its dark
504
+ // values on first render rather than the light defaults just seeded.
505
+ this._writeBack();
506
+ this._push();
507
+ }
508
+
509
+ /** Harvests and queues a save for a pending debounced edit, then cancels its timer. */
510
+ private _flushPendingEdit() {
511
+ if (!this._pushTimer) return;
512
+ window.clearTimeout(this._pushTimer);
513
+ this._pushTimer = undefined;
514
+ this._harvestInto(this.mode);
515
+ this._queueSave();
516
+ }
517
+
518
+ // Reuses _save()'s single-slot queue rather than POSTing directly, so a
519
+ // submit mid-flight can't land as a second concurrent request.
520
+ private readonly _onSubmit = () => {
521
+ if (this._submitting) return;
522
+
523
+ this._flushPendingEdit();
524
+ if (this._saveTimer) {
525
+ window.clearTimeout(this._saveTimer);
526
+ this._saveTimer = undefined;
527
+ }
528
+
529
+ if (!this.action) {
530
+ this.emit('zn-theme-submit', { detail: { values: this.values } });
531
+ return;
532
+ }
533
+
534
+ this._submitting = true;
535
+ void this._awaitSave()
536
+ .then(ok => {
537
+ if (ok) this.emit('zn-theme-submit', { detail: { values: this.values } });
538
+ })
539
+ .finally(() => {
540
+ this._submitting = false;
541
+ });
542
+ };
543
+
544
+ private _announce() {
545
+ this.emit('zn-theme-change', { detail: { values: this.values, mode: this.mode, device: this.device } });
546
+ }
547
+
548
+ private _fail(message: string) {
549
+ this.error = message;
550
+ this.emit('zn-error', { detail: { message } });
551
+ }
552
+
553
+ private readonly _onControlChange = () => {
554
+ if (this._suppressDepth > 0) return;
555
+ if (this._pushTimer) window.clearTimeout(this._pushTimer);
556
+ this._pushTimer = window.setTimeout(() => {
557
+ this._pushTimer = undefined;
558
+ this._harvestInto(this.mode);
559
+ this._push();
560
+ this._queueSave();
561
+ }, this.debounce);
562
+ };
563
+
564
+ private readonly _onSlotChange = () => {
565
+ this._pushIfControlsChanged();
566
+ };
567
+
568
+ private readonly _setDevice = (device: ThemeEditorDevice) => {
569
+ if (this.device === device) return;
570
+ this.device = device;
571
+ // device only resizes the frame — the embed reads its width from the
572
+ // iframe box, so there's nothing new to push
573
+ this._announce();
574
+ };
575
+
576
+ private readonly _toggleMode = () => {
577
+ // A pending debounced edit reads this.mode at fire time, not schedule
578
+ // time - if it fired after the flip below, it would harvest the value
579
+ // write-back is about to overwrite, into the wrong mode's bucket, and
580
+ // the edit would land nowhere. Flush it into the mode it was actually
581
+ // made in before switching.
582
+ this._flushPendingEdit();
583
+
584
+ this.mode = this.mode === 'dark' ? 'light' : 'dark';
585
+ this._writeBack();
586
+ this._push();
587
+ };
588
+
589
+ private readonly _onFrameError = (e: ZnErrorEvent) => {
590
+ // zn-error already bubbles and composes out to the host; just display it.
591
+ this.error = e.detail.message ?? 'Preview failed to render';
592
+ };
593
+
594
+ private _sourcesSafe(): ThemeEditorSource[] {
595
+ return Array.isArray(this.sources) ? this.sources : [];
596
+ }
597
+
598
+ // The first source wins over an explicit `src` when sources is non-empty.
599
+ // The frame reloads on switch; setTheme()'s retained payload replays after
600
+ // its next hp-preview:ready, so nothing further is needed here.
601
+ private _frameSrc(): string {
602
+ const sources = this._sourcesSafe();
603
+ return sources.length > 0 ? (sources[this._sourceIndex] ?? sources[0]).src : this.src;
604
+ }
605
+
606
+ private readonly _onSourceChange = (e: Event) => {
607
+ const index = Number((e.target as HTMLElement & { value: string }).value);
608
+ if (!Number.isNaN(index)) this._sourceIndex = index;
609
+ };
610
+
611
+ private _sectionsSafe(): ThemeEditorSection[] {
612
+ // Lit's default converter falls back to null on bad JSON, and does nothing
613
+ // to coerce valid-but-non-array JSON - both would otherwise crash render().
614
+ return Array.isArray(this.sections) ? this.sections : [];
615
+ }
616
+
617
+ private _groupsFor(section: ThemeEditorSection): ThemeEditorGroup[] {
618
+ return Array.isArray(section?.groups) ? section.groups : [];
619
+ }
620
+
621
+ /** Whether any direct child carries the `group`/`category` structure attributes. */
622
+ private _hasStructureAttributes(): boolean {
623
+ return Array.from(this.children).some(el => el.hasAttribute('group') || el.hasAttribute('category'));
624
+ }
625
+
626
+ /** Attribute-derived structure applies only when `sections` is left unset. */
627
+ private _usesDerivedSections(): boolean {
628
+ return this._sectionsSafe().length === 0 && this._hasStructureAttributes();
629
+ }
630
+
631
+ /**
632
+ * Builds the tab/collapsible tree from the controls' own `group` (tab) and
633
+ * `category` (collapsible) attributes, alongside the slot name each control
634
+ * needs assigning to. Only direct children are considered, since `slot` only
635
+ * works one level deep. Slot names are slugged from the labels and made
636
+ * unique across the whole tree, so two tabs can each hold a "Colors"
637
+ * category without their slots colliding.
638
+ */
639
+ private _derive(): DerivedStructure {
640
+ const used = new Set<string>();
641
+ const unique = (label: string) => {
642
+ const base = slugify(label) || 'group';
643
+ let name = base;
644
+ for (let i = 2; used.has(name); i++) name = `${base}-${i}`;
645
+ used.add(name);
646
+ return name;
647
+ };
648
+
649
+ const sections = new Map<string, ThemeEditorSection & { groups: ThemeEditorGroup[] }>();
650
+ const groupNames = new Map<string, string>();
651
+ const assignments = new Map<Element, string>();
652
+
653
+ for (const child of Array.from(this.children)) {
654
+ const group = child.getAttribute('group')?.trim() ?? '';
655
+ const category = child.getAttribute('category')?.trim() ?? '';
656
+ if (!group && !category) continue;
657
+
658
+ // A `category` with no `group` becomes its own top-level section.
659
+ const sectionLabel = group || category;
660
+ let section = sections.get(sectionLabel);
661
+ if (!section) {
662
+ section = { name: unique(sectionLabel), caption: sectionLabel, groups: [] };
663
+ sections.set(sectionLabel, section);
664
+ }
665
+
666
+ // Only one of the two present: the control sits directly in the section.
667
+ if (!group || !category) {
668
+ assignments.set(child, section.name);
669
+ continue;
670
+ }
671
+
672
+ const key = `${sectionLabel}${category}`;
673
+ let groupName = groupNames.get(key);
674
+ if (!groupName) {
675
+ groupName = unique(`${sectionLabel}-${category}`);
676
+ groupNames.set(key, groupName);
677
+ section.groups.push({ name: groupName, caption: category });
678
+ }
679
+ assignments.set(child, groupName);
680
+ }
681
+
682
+ return { sections: Array.from(sections.values()), assignments };
683
+ }
684
+
685
+ /** Explicit `sections` when set, otherwise the attribute-derived tree. */
686
+ private _effectiveSections(): ThemeEditorSection[] {
687
+ return this._usesDerivedSections() ? this._derive().sections : this._sectionsSafe();
688
+ }
689
+
690
+ // Assignment is idempotent: the `slot` attribute is only written when it
691
+ // actually differs, so the slotchange this triggers settles in one pass. The
692
+ // observer's childList-only config means these writes never feed back into it.
693
+ private _assignDerivedSlots() {
694
+ if (!this._usesDerivedSections()) return;
695
+ for (const [el, slotName] of this._derive().assignments) {
696
+ if (el.getAttribute('slot') !== slotName) el.setAttribute('slot', slotName);
697
+ }
698
+ }
699
+
700
+ protected willUpdate(changed: PropertyValues) {
701
+ super.willUpdate(changed);
702
+ this._assignDerivedSlots();
703
+ }
704
+
705
+ /** Whether any section has a populated `groups` - the switch to nested tabs+collapsibles. */
706
+ private _hasNestedGroups(): boolean {
707
+ return this._effectiveSections().some(section => this._groupsFor(section).length > 0);
708
+ }
709
+
710
+ private _visibleGroups(section: ThemeEditorSection): ThemeEditorGroup[] {
711
+ return this._groupsFor(section).filter(group => this._hasAssignedControls(group.name));
712
+ }
713
+
714
+ /** Configured sections that have an assigned control, or (nested) a populated group - shared by every presentation. */
715
+ private _visibleSections(): ThemeEditorSection[] {
716
+ const sections = this._effectiveSections();
717
+ return this._hasNestedGroups()
718
+ ? sections.filter(section => this._visibleGroups(section).length > 0)
719
+ : sections.filter(section => this._hasAssignedControls(section.name));
720
+ }
721
+
722
+ private _renderSections() {
723
+ return this._visibleSections().map(section => html`
724
+ <zn-collapsible
725
+ class="editor__section"
726
+ part="section"
727
+ caption="${section.caption}"
728
+ description="${ifDefined(section.description)}"
729
+ default="${section.open ? 'open' : 'closed'}">
730
+ <div class="editor__section-fields">
731
+ <slot name="${section.name}" class="editor__section-slot" @slotchange="${this._onSlotChange}"></slot>
732
+ </div>
733
+ </zn-collapsible>`);
734
+ }
735
+
736
+ private _renderGroups(section: ThemeEditorSection) {
737
+ return this._visibleGroups(section).map(group => html`
738
+ <zn-collapsible
739
+ class="editor__section"
740
+ part="section"
741
+ caption="${group.caption}"
742
+ description="${ifDefined(group.description)}"
743
+ default="${group.open ? 'open' : 'closed'}">
744
+ <div class="editor__section-fields">
745
+ <slot name="${group.name}" class="editor__section-slot" @slotchange="${this._onSlotChange}"></slot>
746
+ </div>
747
+ </zn-collapsible>`);
748
+ }
749
+
750
+ /** Every collapsible inside a tab's panel, in document order. */
751
+ private _tabCollapsibles(section: ThemeEditorSection): ZnCollapsible[] {
752
+ const panel = Array.from(this.renderRoot.querySelectorAll<HTMLElement>('.editor__tab-panel'))
753
+ .find(el => el.id === section.name);
754
+ if (!panel) return [];
755
+
756
+ // Author-slotted collapsibles stay in the light DOM, so they aren't
757
+ // descendants of the panel - reach them through the slot's assignment.
758
+ // They precede any group collapsibles the editor renders itself.
759
+ const slotted = Array.from(panel.querySelectorAll('slot'))
760
+ .flatMap(slot => slot.assignedElements({ flatten: true }))
761
+ .filter((el): el is ZnCollapsible => el.tagName.toLowerCase() === 'zn-collapsible');
762
+
763
+ return [...slotted, ...Array.from(panel.querySelectorAll<ZnCollapsible>('zn-collapsible'))];
764
+ }
765
+
766
+ /** Expands the first collapsible, unless one is already open. */
767
+ private _expandFirst(collapsibles: ZnCollapsible[]) {
768
+ if (collapsibles.length === 0 || collapsibles.some(collapsible => collapsible.expanded)) return;
769
+ collapsibles[0].expanded = true;
770
+ }
771
+
772
+ // zn-tabs emits no selection event, so this hangs off the same <li> zn-tabs
773
+ // binds its own click handler to. Independent of that handler: expanding a
774
+ // collapsible in a panel that is about to be selected needs no ordering.
775
+ private _openFirstCollapsible(section: ThemeEditorSection) {
776
+ this._expandFirst(this._tabCollapsibles(section));
777
+ }
778
+
779
+ // Same rule as a tab click, applied once to whatever renders first, so the
780
+ // editor never opens with every collapsible shut. Runs from updated() rather
781
+ // than firstUpdated() because the sections themselves only appear once slot
782
+ // assignment (including the derived kind) has settled.
783
+ protected updated(changed: PropertyValues) {
784
+ super.updated(changed);
785
+ if (this._openedInitialCollapsible) return;
786
+
787
+ const sections = this._visibleSections();
788
+ if (sections.length === 0) return;
789
+ this._openedInitialCollapsible = true;
790
+
791
+ this._expandFirst(this._hasNestedGroups() || this.sectionLayout === 'tabs'
792
+ ? this._tabCollapsibles(sections[0])
793
+ : Array.from(this.renderRoot.querySelectorAll<ZnCollapsible>('.editor__section')));
794
+ }
795
+
796
+ // zn-tabs never removes a panel - it toggles `selected` on it and hides the
797
+ // rest via its own shadow stylesheet - so every section's slot(s) stay
798
+ // assigned and switching tabs can never drop a control's value from the
799
+ // theme. The first visible section is the initial `active` tab; once set,
800
+ // Lit only re-touches the attribute (resetting zn-tabs' own tracked
801
+ // selection) if that name actually changes between renders.
802
+ private _renderTabs(panel: (section: ThemeEditorSection) => unknown) {
803
+ const sections = this._visibleSections();
804
+ if (sections.length === 0) return nothing;
805
+
806
+ return html`
807
+ <zn-tabs class="editor__tabs" flush active="${sections[0].name}">
808
+ <zn-navbar slot="top" border>
809
+ ${sections.map(section => html`
810
+ <li tab="${section.name}" @click="${() => this._openFirstCollapsible(section)}">${section.caption}</li>`)}
811
+ </zn-navbar>
812
+ ${sections.map(section => html`
813
+ <div id="${section.name}" class="editor__tab-panel">${panel(section)}</div>`)}
814
+ </zn-tabs>`;
815
+ }
816
+
817
+ render() {
818
+ return html`
819
+ <div part="base" class="editor ${this.controlsCollapsed ? 'editor--controls-collapsed' : ''}"
820
+ style="min-height: ${this.minHeight}px">
821
+ <div part="controls" class="editor__controls">
822
+ <div part="controls-header" class="editor__controls-header">
823
+ ${this.controlsCaption ? html`<span class="editor__caption">${this.controlsCaption}</span>` : nothing}
824
+ <button type="button"
825
+ class="editor__mode"
826
+ data-mode-toggle
827
+ aria-label="${this.mode === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}"
828
+ @click="${this._toggleMode}">
829
+ <zn-icon src="${this.mode === 'dark' ? 'sun' : 'moon'}" library="lucide" size="16"></zn-icon>
830
+ </button>
831
+ </div>
832
+ <div class="editor__controls-body">
833
+ <div
834
+ class="editor__fields ${this.hasSlotController.test('[default]') ? '' : 'editor__fields--sections-only'}"
835
+ @zn-change="${this._onControlChange}"
836
+ @zn-input="${this._onControlChange}"
837
+ @change="${this._onControlChange}"
838
+ @input="${this._onControlChange}">
839
+ <slot @slotchange="${this._onSlotChange}"></slot>
840
+ ${this._hasNestedGroups()
841
+ ? this._renderTabs(section => html`
842
+ ${this._hasAssignedControls(section.name) ? html`
843
+ <slot name="${section.name}" class="editor__section-slot" @slotchange="${this._onSlotChange}"></slot>` : nothing}
844
+ ${this._renderGroups(section)}`)
845
+ : this.sectionLayout === 'tabs'
846
+ ? this._renderTabs(section => html`
847
+ <slot name="${section.name}" class="editor__section-slot" @slotchange="${this._onSlotChange}"></slot>`)
848
+ : this._renderSections()}
849
+ </div>
850
+ ${this.hasSlotController.test('footer') ? html`
851
+ <div part="footer" class="editor__footer">
852
+ <slot name="footer"></slot>
853
+ </div>` : nothing}
854
+ </div>
855
+ </div>
856
+
857
+ <div class="editor__main">
858
+ <button type="button"
859
+ class="panel-toggle panel-toggle--left ${this.controlsCollapsed ? 'panel-toggle--tucked' : ''}"
860
+ title="${this.controlsCollapsed ? 'Show controls' : 'Hide controls'}"
861
+ aria-label="${this.controlsCollapsed ? 'Show controls' : 'Hide controls'}"
862
+ @click="${() => (this.controlsCollapsed = !this.controlsCollapsed)}">
863
+ <zn-icon src="${this.controlsCollapsed ? 'chevron-right@lu' : 'chevron-left@lu'}" size="16"></zn-icon>
864
+ </button>
865
+
866
+ <div part="toolbar" class="editor__toolbar">
867
+ ${this.previewCaption ? html`<span class="editor__caption">${this.previewCaption}</span>` : nothing}
868
+ <div class="editor__toolbar-actions">
869
+ <div class="editor__devices" role="group" aria-label="Preview width">
870
+ ${DEVICES.map(d => html`
871
+ <button type="button"
872
+ class="editor__device"
873
+ data-device="${d.id}"
874
+ aria-label="${d.label}"
875
+ aria-pressed="${this.device === d.id ? 'true' : 'false'}"
876
+ @click="${() => this._setDevice(d.id)}">
877
+ <zn-icon src="${d.icon}" library="lucide" size="16"></zn-icon>
878
+ </button>`)}
879
+ </div>
880
+ ${this._sourcesSafe().length > 0 ? html`
881
+ <zn-select
882
+ class="editor__sources"
883
+ size="small"
884
+ label="Preview source"
885
+ hoist
886
+ .value="${String(this._sourceIndex)}"
887
+ @zn-change="${this._onSourceChange}">
888
+ ${this._sourcesSafe().map((source, i) => html`
889
+ <zn-option value="${i}">${source.label}</zn-option>`)}
890
+ </zn-select>` : nothing}
891
+ <slot name="toolbar"></slot>
892
+ ${this.submitLabel ? html`
893
+ <zn-button class="editor__submit"
894
+ color="primary"
895
+ @click="${this._onSubmit}"
896
+ ?loading="${this._submitting}">${this.submitLabel}
897
+ </zn-button>` : nothing}
898
+ </div>
899
+ </div>
900
+
901
+ <div part="preview" class="editor__preview">
902
+ ${this.error ? html`
903
+ <div part="error" class="editor__error">${this.error}</div>` : nothing}
904
+ <zn-preview-frame
905
+ src="${this._frameSrc()}"
906
+ frame-origin="${this.frameOrigin}"
907
+ data-uri="${this.dataUri}"
908
+ device="${this.device}"
909
+ min-height="${this.minHeight}"
910
+ fill
911
+ backdrop="${this.standalone ? 'panel' : 'dots'}"
912
+ exportparts="base:preview__base,stage:preview__stage,iframe:preview__iframe,error:preview__error"
913
+ @zn-error="${this._onFrameError}"></zn-preview-frame>
914
+ </div>
915
+ </div>
916
+ </div>`;
917
+ }
918
+ }