Repository navigation
Expand file tree
/
Copy pathview.html
More file actions
797 lines (754 loc) · 37.6 KB
/
Copy pathview.html
File metadata and controls
797 lines (754 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Design System</title>
<!-- RELATIVE, deliberately: the kit lives at <base>/_ds/ where <base> is "" in the host
window and "/agents/<slug>" under the fleet proxy. "../../" resolves correctly in BOTH
from this page's own path, which a root-absolute "/_ds/..." would not. Kept in the HTML
rather than assigned from JS so the browser starts the fetch during parse and blocks
the first paint on it — an href filled in by script means the page paints once with NO
--pl-* tokens defined, i.e. white. (Depth is coupled to the view path; a test asserts it.) -->
<link rel="stylesheet" href="../../_ds/plugin-kit.css" id="ds-kit" />
<style>
/* Bootstrap ground — applies before the kit stylesheet resolves and whenever it can't.
The literals are the ONLY hardcoded colours in this file and exist purely so an
unstyled first paint lands on the right ground instead of white; the tokens win the
moment they exist. Follows the OS scheme, since the console's theme only arrives later
over the handshake. */
:root { color-scheme: dark; }
html { background: var(--pl-color-bg, #0a0a0c); }
@media (prefers-color-scheme: light) {
:root { color-scheme: light; }
html { background: var(--pl-color-bg, #f6f7f9); }
}
html, body { height: 100%; }
body {
margin: 0; display: flex; flex-direction: column;
font-family: var(--pl-font-sans); font-size: var(--pl-font-base-size);
color: var(--pl-color-fg); background: var(--pl-color-bg, transparent);
}
.bar {
display: flex; align-items: center; gap: var(--pl-space-3);
padding: var(--pl-space-3) var(--pl-space-4);
border-bottom: var(--pl-border-width) solid var(--pl-color-border);
background: var(--pl-color-bg-raised); flex: 0 0 auto; flex-wrap: wrap;
}
.bar h1 { font-size: 15px; font-weight: var(--pl-font-weight-semibold); margin: 0; }
.src { color: var(--pl-color-fg-subtle); font-family: var(--pl-font-mono); font-size: 12px; }
.grow { flex: 1 1 auto; }
.body { flex: 1 1 auto; min-height: 0; display: flex; }
.side {
flex: 0 0 216px; overflow-y: auto; padding: var(--pl-space-3) 0;
border-right: var(--pl-border-width) solid var(--pl-color-border);
background: var(--pl-color-bg-raised);
}
.side .grp {
padding: var(--pl-space-3) var(--pl-space-4) var(--pl-space-1);
font-size: 11px; letter-spacing: .06em; text-transform: uppercase;
color: var(--pl-color-fg-subtle);
}
.side button {
display: block; width: 100%; text-align: left; cursor: pointer;
padding: 6px var(--pl-space-4); border: 0; background: none;
color: var(--pl-color-fg-muted); font: inherit;
border-left: 2px solid transparent;
}
.side button:hover { background: var(--pl-color-bg-hover); color: var(--pl-color-fg); }
.side button[aria-current="true"] {
color: var(--pl-color-fg); background: var(--pl-color-bg-subtle);
border-left-color: var(--pl-color-accent);
}
.side .count { color: var(--pl-color-fg-subtle); font-size: 11px; }
.main { flex: 1 1 auto; overflow-y: auto; padding: var(--pl-space-5); min-width: 0; }
.lede { color: var(--pl-color-fg-muted); margin: 0 0 var(--pl-space-5); max-width: 62ch; }
h2.sec {
font-size: 12px; letter-spacing: .07em; text-transform: uppercase;
color: var(--pl-color-fg-subtle); font-weight: var(--pl-font-weight-semibold);
margin: var(--pl-space-6) 0 var(--pl-space-3);
padding-bottom: var(--pl-space-2);
border-bottom: var(--pl-border-width) solid var(--pl-color-border);
}
h2.sec:first-child { margin-top: 0; }
.comp-head { margin: 0 0 var(--pl-space-4); }
.comp-head .eyebrow {
font-size: 11px; letter-spacing: .07em; text-transform: uppercase;
color: var(--pl-color-fg-subtle);
}
.comp-head h2 { font-size: 18px; margin: 2px 0 0; font-weight: var(--pl-font-weight-semibold); }
.comp-head .count { font-weight: 400; color: var(--pl-color-fg-subtle); font-size: 13px; }
.toks { display: grid; grid-template-columns: repeat(auto-fill, minmax(232px, 1fr)); gap: var(--pl-space-3); }
.tok {
display: flex; gap: var(--pl-space-3); align-items: center; cursor: pointer;
padding: var(--pl-space-2); border-radius: var(--pl-radius); border: 0;
background: var(--pl-color-bg-raised); text-align: left; width: 100%;
color: inherit; font: inherit;
}
.tok:hover { background: var(--pl-color-bg-hover); }
.tok .meta { min-width: 0; flex: 1 1 auto; }
.tok .nm {
font-family: var(--pl-font-mono); font-size: 11.5px; color: var(--pl-color-fg);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.tok .vl { font-family: var(--pl-font-mono); font-size: 11px; color: var(--pl-color-fg-subtle); }
.chip {
flex: 0 0 auto; width: 44px; height: 34px; border-radius: var(--pl-radius);
border: var(--pl-border-width) solid var(--pl-color-border-strong);
display: grid; place-items: center; overflow: hidden;
}
.chip.split { position: relative; }
.chip.split i { position: absolute; inset: 0; }
.chip.split i.l { clip-path: polygon(0 0, 100% 0, 0 100%); }
.bararea { height: 10px; background: var(--pl-color-accent); border-radius: 2px; }
.swatchrow { display: flex; align-items: center; gap: var(--pl-space-2); }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(420px, 100%), 1fr)); gap: var(--pl-space-4); }
.card {
border: var(--pl-border-width) solid var(--pl-color-border);
border-radius: var(--pl-radius); overflow: hidden; background: var(--pl-color-bg-raised);
display: flex; flex-direction: column;
}
.card header {
display: flex; align-items: center; gap: var(--pl-space-2);
padding: var(--pl-space-2) var(--pl-space-3);
border-bottom: var(--pl-border-width) solid var(--pl-color-border);
}
.card header .nm { font-weight: var(--pl-font-weight-medium); font-size: 12.5px; }
/* The frame WELL owns the height and the ground colour. The iframe is cross-origin, so
we can't style its document — before its CSS lands the browser paints that document's
default canvas WHITE, which is the flash. Two defences, both from outside the frame:
`color-scheme` below (so the pre-CSS canvas is painted in our mode, not white), and
holding the frame hidden over a themed skeleton until it has actually painted. */
.well { position: relative; height: 560px; background: var(--pl-color-bg-raised, #131316); }
.well iframe {
width: 100%; height: 100%; border: 0; display: block;
background: var(--pl-color-bg-raised, #131316);
/* Paints the embedded document's initial canvas in our scheme instead of white. */
color-scheme: dark;
opacity: 0;
}
body.lightmode .well iframe { color-scheme: light; }
.card.ready .well iframe { opacity: 1; }
.well .skel {
position: absolute; inset: 0; display: grid; place-items: center;
background: var(--pl-color-bg-raised, #131316); pointer-events: none;
}
.card.ready .well .skel { display: none; }
.well .skel span {
width: 42%; height: 10px; border-radius: 999px;
background: var(--pl-color-bg-subtle);
animation: pulse var(--pl-motion-loading, 1000ms) ease-in-out infinite;
}
@keyframes pulse { 0%, 100% { opacity: .45 } 50% { opacity: .9 } }
@media (prefers-reduced-motion: reduce) { .well .skel span { animation: none } }
/* Playground — a full-size stage plus controls generated from the story's own argTypes.
Storybook hands us those over its channel, so the panel always matches the real
component API rather than a schema we'd have to keep in step by hand. */
/* Full-height playground: every ancestor between .main and the stage has to be a
zero-min flex box, or `height: 100%` on .pg resolves against an auto-height block and
collapses to content — which is what left the stage short with dead space under it. */
body.pg-full .main { overflow: hidden; display: flex; flex-direction: column; padding: var(--pl-space-4); }
body.pg-full #playground { flex: 1 1 auto; min-height: 0; display: flex; }
body.pg-full .pg { flex: 1 1 auto; }
.pg { display: flex; gap: 0; height: 100%; min-height: 0; }
.pg-main { flex: 1 1 auto; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
.pg-bar {
display: flex; align-items: center; gap: var(--pl-space-3); flex-wrap: wrap;
padding: 0 0 var(--pl-space-3);
}
.pg-bar .sp { flex: 1 1 auto; }
.pg-stage {
flex: 1 1 auto; min-height: 0; display: flex; justify-content: center;
overflow: auto; padding: var(--pl-space-3);
background: var(--pl-color-bg-inset, #060608);
border: var(--pl-border-width) solid var(--pl-color-border);
border-radius: var(--pl-radius);
}
.pg-frame {
position: relative; width: 100%; height: 100%; min-height: 0;
background: var(--pl-color-bg-raised, #131316);
border-radius: var(--pl-radius); overflow: hidden;
transition: width var(--pl-motion-base, 200ms) ease;
}
.pg-frame iframe { width: 100%; height: 100%; border: 0; display: block; color-scheme: dark; opacity: 0; }
body.lightmode .pg-frame iframe { color-scheme: light; }
.pg-frame.ready iframe { opacity: 1; }
.pg-frame .skel { position: absolute; inset: 0; display: grid; place-items: center;
background: var(--pl-color-bg-raised, #131316); pointer-events: none; }
.pg-frame.ready .skel { display: none; }
.pg-panel {
flex: 0 0 288px; overflow-y: auto; padding: 0 0 0 var(--pl-space-4);
margin-left: var(--pl-space-4);
border-left: var(--pl-border-width) solid var(--pl-color-border);
}
.pg-panel h3 {
font-size: 11px; letter-spacing: .07em; text-transform: uppercase;
color: var(--pl-color-fg-subtle); margin: 0 0 var(--pl-space-3);
}
.ctl { margin-bottom: var(--pl-space-4); }
.ctl label { display: block; font-size: 12px; margin-bottom: 4px; color: var(--pl-color-fg-muted); }
.ctl label code { color: var(--pl-color-fg); font-size: 11.5px; }
.ctl .pl-input, .ctl .pl-select, .ctl select, .ctl input[type="text"], .ctl input[type="number"] { width: 100%; }
.ctl .segbtns { display: flex; flex-wrap: wrap; gap: 4px; }
.ctl .segbtns button {
font: inherit; font-size: 12px; cursor: pointer; padding: 3px 9px;
border-radius: var(--pl-radius); color: var(--pl-color-fg-muted);
background: var(--pl-color-bg-subtle);
border: var(--pl-border-width) solid var(--pl-color-border);
}
.ctl .segbtns button[aria-pressed="true"] {
color: var(--pl-color-fg); border-color: var(--pl-color-accent);
background: var(--pl-color-bg-hover);
}
.pg-code {
margin-top: var(--pl-space-4); padding: var(--pl-space-3);
background: var(--pl-color-bg-inset, #060608); border-radius: var(--pl-radius);
font-family: var(--pl-font-mono); font-size: 11.5px; white-space: pre-wrap;
word-break: break-word; color: var(--pl-color-fg-muted);
border: var(--pl-border-width) solid var(--pl-color-border);
}
/* The view ships at `placement: right`, so it has to survive a rail, not just a full
window. Two fixed columns (216px rail + 288px controls) leave the stage at 88px by
640px wide — the opposite of the full-view brief. So: stack the controls under the
stage before that bites, then lay the component list out as a strip above it. */
@media (max-width: 1100px) {
.pg { flex-direction: column; }
.pg-panel {
flex: 0 0 auto; max-height: 38%;
border-left: 0; border-top: var(--pl-border-width) solid var(--pl-color-border);
margin-left: 0; padding: var(--pl-space-3) 0 0;
}
}
@media (max-width: 760px) {
.body { flex-direction: column; }
.side {
flex: 0 0 auto; max-height: 124px;
border-right: 0; border-bottom: var(--pl-border-width) solid var(--pl-color-border);
}
.cards { grid-template-columns: 1fr; }
}
.status { color: var(--pl-color-fg-muted); padding: var(--pl-space-6); text-align: center; }
.hide { display: none !important; }
a.plain { color: var(--pl-color-accent-fg); text-decoration: none; font-size: 12px; }
a.plain:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="bar">
<h1>Design System</h1>
<span class="src" id="src"></span>
<div class="pl-tabs pl-tabs--segmented" role="group" id="tabs">
<button class="pl-tab pl-tab--active" data-tab="foundations" aria-pressed="true">Foundations</button>
<button class="pl-tab" data-tab="components" aria-pressed="false">Components</button>
<button class="pl-tab" data-tab="playground" aria-pressed="false">Playground</button>
</div>
<span class="grow"></span>
<input class="pl-input" id="q" type="search" placeholder="Filter…" style="max-width:200px" />
<button class="pl-btn pl-btn--sm" id="refresh" title="Re-read the design system">Refresh</button>
<a class="plain" id="sblink" target="_blank" rel="noopener"></a>
</div>
<div class="body">
<nav class="side hide" id="side"></nav>
<main class="main">
<div class="status" id="status">Reading the design system…</div>
<section id="foundations" class="hide"></section>
<section id="components" class="hide"></section>
<section id="playground" class="hide"></section>
</main>
</div>
<script type="module">
// Rule 3: derive the base so this works behind the /agents/<slug>/ fleet proxy too.
const base = location.pathname.split("/plugins/")[0];
// NOTE: the kit STYLESHEET is linked statically in the head (see the comment there) — do
// not set its href from here, or the fetch restarts and the page paints untokenised first.
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => (
{ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
let kit;
try {
// plugin-kit.js is an ES module AND the URL is slug-dependent, so it must be a dynamic
// import — a classic <script src> throws "Unexpected token 'export'" and never runs.
kit = await import(base + "/_ds/plugin-kit.js");
// The callback fires on the initial handshake AND on every live operator re-theme,
// so the story frames follow the console instead of freezing at load-time theme.
kit.initPluginView(() => {
syncMode();
if (!DATA) return;
if (tab === "components") renderComponent();
else if (tab === "playground" && PG.theme === "auto") sendToStory("updateGlobals", { globals: { theme: pgMode() } });
});
} catch (err) {
// Fail loudly: the bearer arrives THROUGH the kit handshake, so a bare-fetch fallback
// could only 401 and would blame auth for a missing /_ds bundle.
$("status").textContent = "Could not load the design-system kit (" + base + "/_ds/plugin-kit.js): " + err;
throw err;
}
let DATA = null, active = null, tab = "foundations";
// The console hands the kit a CURATED palette ({bg, fg, brand, …}), not a mode name — so
// read the mode back off the token the kit actually applied. Rendering each story in the
// operator's own theme is the point: a gallery stuck in dark while the console is light
// is how a contrast bug stays invisible until someone ships it.
function currentMode() {
const bg = getComputedStyle(document.documentElement).getPropertyValue("--pl-color-bg").trim();
const m = bg.match(/^#([0-9a-f]{3,8})$/i);
let lum = 0;
if (m) {
let h = m[1];
if (h.length === 3) h = h.split("").map((c) => c + c).join("");
const [r, g, b] = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255);
lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
} else {
const nums = bg.match(/[\d.]+/g);
if (nums && nums.length >= 3) {
const [r, g, b] = nums.slice(0, 3).map(Number);
lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
}
}
return lum > 0.5 ? "light" : "dark";
}
const themed = (url) => url + "&globals=theme:" + currentMode();
// Mirror the resolved mode onto <body> so `color-scheme` on the frames matches it. Without
// this the embedded document's pre-CSS canvas is painted in the WRONG scheme — still a
// flash, just a dark one on a light console.
function syncMode() {
document.body.classList.toggle("lightmode", currentMode() === "light");
}
// Storybook is a CLIENT-RENDERED preview: `load` fires when the iframe document has
// finished loading, but the story CSS is injected by its JS afterwards, so between `load`
// and the first story paint the document is a blank WHITE page. Revealing on `load`
// therefore shows that white — measured at ~290ms of it (load 391ms, storyRendered 683ms).
//
// So we reveal on Storybook's OWN render event, which it posts to us over its
// `storybook-channel` postMessage protocol. `load` only starts a grace timer, so a
// Storybook that doesn't speak the protocol still resolves instead of pulsing forever.
const SB_DONE = new Set([
"storyRendered", "storyFinished", "storyMissing", "storyErrored", "storyThrewException",
]);
const GRACE_AFTER_LOAD_MS = 2500;
const FRAME_TIMEOUT_MS = 12000;
function markReady(frame) {
const card = frame && frame.closest(".card");
if (card) card.classList.add("ready");
}
// One listener for the whole page; each message is matched back to its frame by source
// window. Registered once — re-registering per render would leak a listener per switch.
window.addEventListener("message", (e) => {
const origin = DATA && DATA.meta && DATA.meta.storybook_url;
if (!origin || e.origin !== new URL(origin).origin) return; // only our Storybook
let d = e.data;
if (typeof d === "string") { try { d = JSON.parse(d); } catch { return; } }
if (!d || d.key !== "storybook-channel" || !d.event) return;
const { type, args } = d.event;
// The playground's own frame: capture the story's real control schema when Storybook
// announces it, and keep our mirror of the args in step with what it actually applied.
const pgFrame = document.querySelector("#playground .pg-frame iframe");
if (pgFrame && pgFrame.contentWindow === e.source) {
if (type === "storyPrepared" && args && args[0]) {
const prep = args[0];
prep.argTypes = undup(prep.argTypes, d) || {};
prep.initialArgs = undup(prep.initialArgs, d) || {};
const live = undup(prep.args, d);
PG.prepared = prep;
PG.args = { ...(isPlainObject(live) ? live : prep.initialArgs) };
renderControls();
}
if (type === "storyArgsUpdated" && args && args[0]) {
const next = undup(args[0].args, d);
if (isPlainObject(next)) { PG.args = { ...next }; renderArgsCode(); }
}
if (SB_DONE.has(type)) pgFrame.closest(".pg-frame").classList.add("ready");
}
if (!SB_DONE.has(type)) return;
for (const frame of document.querySelectorAll("#components .well iframe")) {
if (frame.contentWindow === e.source) { markReady(frame); return; }
}
});
// Every story frame — gallery card or playground stage — reveals the same way, so the rules
// live in one place.
//
// The backstop hangs off `load`, NOT off render time. Frames are `loading="lazy"`, so a
// render-time timer can fire on a card that has not begun loading yet — marking it ready
// while it is still blank, which puts the original white flash straight back on scroll. If
// `load` never fires the frame is off-screen or still fetching, and a pulsing skeleton is the
// honest thing to show.
function armReveal(frame, onReady) {
const show = () => onReady(frame);
frame.addEventListener("error", show, { once: true });
frame.addEventListener("load", () => {
// `load` alone is too early — Storybook injects the story CSS afterwards. Wait for its
// storyRendered message, and fall back so a preview that doesn't speak the channel (or a
// story that throws) still resolves instead of pulsing forever.
setTimeout(show, GRACE_AFTER_LOAD_MS);
setTimeout(show, FRAME_TIMEOUT_MS);
}, { once: true });
}
function revealFramesIn(host) {
for (const frame of host.querySelectorAll(".well iframe")) armReveal(frame, markReady);
}
function tokenChip(t) {
const dark = esc(t.value), light = esc(t.light);
if (t.kind === "color" || t.kind === "gradient") {
return t.themed
// Themed tokens get a split chip: the pair is what you actually judge, and a
// single-theme swatch is how contrast regressions ship unnoticed.
? `<span class="chip split" title="dark / light"><i style="background:${dark}"></i><i class="l" style="background:${light}"></i></span>`
: `<span class="chip" style="background:${dark}"></span>`;
}
if (t.kind === "shadow") return `<span class="chip" style="box-shadow:${dark};background:var(--pl-color-bg-subtle)"></span>`;
if (t.kind === "font") return `<span class="chip" style="font-family:${dark};font-size:15px">Ag</span>`;
if (t.kind === "length") {
const px = Math.min(parseFloat(t.value) || 0, 40);
return `<span class="chip"><span class="bararea" style="width:${Math.max(px, 2)}px"></span></span>`;
}
if (t.kind === "duration") return `<span class="chip" style="font-size:10px;color:var(--pl-color-fg-subtle)">${dark}</span>`;
return `<span class="chip" style="font-size:10px;color:var(--pl-color-fg-subtle)">—</span>`;
}
function renderFoundations(filter) {
const host = $("foundations");
if (DATA.tokens_error) {
host.innerHTML = `<div class="pl-alert pl-alert--warning">Tokens unavailable — ${esc(DATA.tokens_error)}</div>`;
return;
}
const f = (filter || "").toLowerCase();
let html = `<p class="lede">The live token vocabulary from <code>${esc(DATA.meta.repo)}</code>.
These are the only values to style with — click any token to copy its <code>var()</code>.</p>`;
let shown = 0;
for (const sec of DATA.tokens) {
const toks = sec.tokens.filter((t) => !f || t.name.includes(f) || String(t.value).toLowerCase().includes(f));
if (!toks.length) continue;
shown += toks.length;
html += `<h2 class="sec">${esc(sec.section)} <span class="count">${toks.length}</span></h2><div class="toks">`;
for (const t of toks) {
html += `<button class="tok" data-copy="var(${esc(t.var)})" title="Copy var(${esc(t.var)})">
${tokenChip(t)}
<span class="meta"><span class="nm">${esc(t.name)}</span><br />
<span class="vl">${esc(t.value)}${t.themed ? " · " + esc(t.light) : ""}</span></span></button>`;
}
html += `</div>`;
}
host.innerHTML = shown ? html : `<div class="status">No tokens match that filter.</div>`;
}
function renderSide(filter) {
const f = (filter || "").toLowerCase();
let html = "";
for (const g of DATA.groups) {
// Match VARIANT names too: people search for the thing they saw ("toast", "skeleton"),
// which is often a story under a broader component ("Overlays"), not a component name.
const comps = g.components.filter((c) => !f
|| c.title.toLowerCase().includes(f)
|| c.stories.some((s) => s.name.toLowerCase().includes(f)));
if (!comps.length) continue;
if (g.group) html += `<div class="grp">${esc(g.group.replace(/^Components\/?/, "") || "Components")}</div>`;
for (const c of comps) {
html += `<button data-comp="${esc(c.title)}" aria-current="${c.title === active}">
${esc(c.label)} <span class="count">${c.stories.length}</span></button>`;
}
}
$("side").innerHTML = html || `<div class="grp">No matches</div>`;
}
function renderComponent() {
const host = $("components");
if (DATA.components_error) {
host.innerHTML = `<div class="pl-alert pl-alert--warning">Gallery unavailable — ${esc(DATA.components_error)}
<br />Set the published Storybook URL in Settings ▸ Plugins ▸ Design System.</div>`;
return;
}
const comp = DATA.groups.flatMap((g) => g.components).find((c) => c.title === active);
if (!comp) { host.innerHTML = `<div class="status">Pick a component.</div>`; return; }
const grp = comp.group.replace(/^Components\/?/, "");
let html = `<div class="comp-head">${grp ? `<div class="eyebrow">${esc(grp)}</div>` : ""}
<h2>${esc(comp.label)} <span class="count">${comp.stories.length} variant${comp.stories.length === 1 ? "" : "s"}</span></h2></div>`;
if (!comp.stories.length) html += `<div class="status">This entry has docs but no rendered stories.</div>`;
html += `<div class="cards">`;
for (const s of comp.stories) {
html += `<div class="card"><header><span class="nm">${esc(s.name)}</span>
<span class="grow" style="flex:1"></span>
<a class="plain" href="${esc(s.docs)}" target="_blank" rel="noopener">Storybook ↗</a></header>
<div class="well"><div class="skel"><span></span></div>
<iframe loading="lazy" title="${esc(comp.label)} — ${esc(s.name)}" src="${esc(themed(s.preview))}"></iframe></div></div>`;
}
host.innerHTML = html + `</div>`;
revealFramesIn(host);
}
// ── playground ────────────────────────────────────────────────────────────────
// Storybook drives its own preview through a postMessage channel; `updateStoryArgs` is the
// same message its manager UI sends. So the controls here manipulate the REAL component
// live — no reload, no reimplementation of its rendering.
const PG = { storyId: null, prepared: null, args: {}, width: "fill", theme: "auto" };
// Storybook serialises its channel with telejson, which replaces any structure that already
// appeared in the message with a marker string: `_duplicate_["event","args","0","initialArgs"]`
// — a PATH back to the original. Spreading one of those as an object yields a char map
// (`{0:"_",1:"d",…}`), which is how the props panel first rendered `<Button 0="_" 1="d" …>`.
// Resolve the path against the whole message instead.
const DUP = /^_duplicate_(\[.*\])$/;
function undup(value, root, seen = 0) {
if (typeof value !== "string" || seen > 4) return value;
const m = DUP.exec(value);
if (!m) return value;
let path;
try { path = JSON.parse(m[1]); } catch { return undefined; }
let node = root;
for (const key of path) {
if (node == null) return undefined;
node = node[key];
}
return undup(node, root, seen + 1); // a marker may point at another marker
}
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
const WIDTHS = [
{ id: "fill", label: "Fill", css: "100%" },
{ id: "desktop", label: "1280", css: "1280px" },
{ id: "tablet", label: "768", css: "768px" },
{ id: "mobile", label: "390", css: "390px" },
];
function pgMode() {
return PG.theme === "auto" ? currentMode() : PG.theme;
}
function pgStories() {
return DATA ? DATA.groups.flatMap((g) => g.components).flatMap((c) => c.stories.map((s) => ({ ...s, comp: c }))) : [];
}
function sendToStory(type, payload) {
const frame = document.querySelector("#playground .pg-frame iframe");
if (!frame || !frame.contentWindow) return;
frame.contentWindow.postMessage(
JSON.stringify({ key: "storybook-channel", event: { type, args: [payload], from: "manager" } }),
new URL(DATA.meta.storybook_url).origin,
);
}
function setArg(name, value) {
PG.args[name] = value;
sendToStory("updateStoryArgs", { storyId: PG.storyId, updatedArgs: { [name]: value } });
renderArgsCode();
}
function renderPlayground() {
const host = $("playground");
if (DATA.components_error) {
host.innerHTML = `<div class="pl-alert pl-alert--warning">Playground unavailable — ${esc(DATA.components_error)}</div>`;
return;
}
const all = pgStories();
if (!all.length) { host.innerHTML = `<div class="status">No stories to play with.</div>`; return; }
const comp = DATA.groups.flatMap((g) => g.components).find((c) => c.title === active) || all[0].comp;
if (!comp.stories.some((s) => s.id === PG.storyId)) PG.storyId = (comp.stories[0] || {}).id || null;
const story = comp.stories.find((s) => s.id === PG.storyId);
if (!story) { host.innerHTML = `<div class="status">This entry has no rendered stories.</div>`; return; }
const w = WIDTHS.find((x) => x.id === PG.width) || WIDTHS[0];
host.innerHTML = `
<div class="pg">
<div class="pg-main">
<div class="comp-head">${comp.group ? `<div class="eyebrow">${esc(comp.group.replace(/^Components\/?/, ""))}</div>` : ""}
<h2>${esc(comp.label)}</h2></div>
<div class="pg-bar">
<select class="pl-select" id="pg-variant" aria-label="Variant">
${comp.stories.map((s) => `<option value="${esc(s.id)}"${s.id === PG.storyId ? " selected" : ""}>${esc(s.name)}</option>`).join("")}
</select>
<div class="segbtns" id="pg-width" role="group" aria-label="Preview width">
${WIDTHS.map((x) => `<button data-w="${x.id}" aria-pressed="${x.id === PG.width}">${x.label}</button>`).join("")}
</div>
<div class="segbtns" id="pg-theme" role="group" aria-label="Preview theme">
${["auto", "dark", "light"].map((t) => `<button data-t="${t}" aria-pressed="${t === PG.theme}">${t}</button>`).join("")}
</div>
<span class="sp"></span>
<a class="plain" href="${esc(story.docs)}" target="_blank" rel="noopener">Storybook ↗</a>
</div>
<div class="pg-stage">
<div class="pg-frame" style="width:${w.css};max-width:100%">
<div class="skel"><span></span></div>
<iframe title="${esc(comp.label)} playground"
src="${esc(story.preview)}&globals=theme:${esc(pgMode())}"></iframe>
</div>
</div>
</div>
<aside class="pg-panel">
<h3>Controls</h3>
<div id="pg-controls"><div class="status" style="padding:var(--pl-space-4)">Waiting for the story…</div></div>
<button class="pl-btn pl-btn--sm" id="pg-reset">Reset to story defaults</button>
<div class="pg-code" id="pg-code"></div>
</aside>
</div>`;
armPlaygroundFrame();
}
// The stage frame is re-created on every renderPlayground(), so arm it each time.
function armPlaygroundFrame() {
const frame = document.querySelector("#playground .pg-frame iframe");
if (frame) armReveal(frame, (f) => f.closest(".pg-frame").classList.add("ready"));
}
function renderControls() {
const host = $("pg-controls");
if (!host) return;
const types = (PG.prepared && PG.prepared.argTypes) || {};
// Storybook's channel dedupes repeated structures into "_duplicate_[…]" strings, so a
// value that should be an array can arrive as one. Anything we can't read as a real
// control degrades to a text field rather than rendering a broken widget.
const opts = (t) => {
for (const cand of [t.options, t.type && t.type.value]) {
if (Array.isArray(cand)) return cand;
}
return null;
};
const rows = Object.entries(types).filter(([, t]) => t && t.control && t.control.disable !== true);
if (!rows.length) { host.innerHTML = `<div class="status" style="padding:var(--pl-space-3)">This story exposes no controls.</div>`; return; }
let html = "";
for (const [name, t] of rows) {
const kind = (t.control && t.control.type) || "text";
const cur = PG.args[name];
const id = "c_" + name.replace(/[^a-zA-Z0-9_]/g, "_");
html += `<div class="ctl"><label for="${id}"><code>${esc(name)}</code></label>`;
const choices = opts(t);
if (kind === "boolean") {
html += `<input type="checkbox" id="${id}" data-arg="${esc(name)}" data-kind="boolean"${cur ? " checked" : ""} />`;
} else if (choices) {
html += `<div class="segbtns" data-arg="${esc(name)}" data-kind="choice">` +
choices.map((o) => `<button data-v="${esc(String(o))}" aria-pressed="${String(o) === String(cur)}">${esc(String(o))}</button>`).join("") + `</div>`;
} else if (kind === "number" || kind === "range") {
html += `<input class="pl-input" type="number" id="${id}" data-arg="${esc(name)}" data-kind="number" value="${esc(cur ?? "")}" />`;
} else if (kind === "color") {
html += `<input type="color" id="${id}" data-arg="${esc(name)}" data-kind="text" value="${esc(cur || "#000000")}" />`;
} else if (typeof cur === "object" && cur !== null) {
html += `<div class="status" style="padding:4px 0;text-align:left">object — edit in Storybook</div>`;
} else {
html += `<input class="pl-input" type="text" id="${id}" data-arg="${esc(name)}" data-kind="text" value="${esc(cur ?? "")}" />`;
}
html += `</div>`;
}
host.innerHTML = html;
renderArgsCode();
}
function renderArgsCode() {
const el = $("pg-code");
if (!el || !PG.prepared) return;
const comp = DATA.groups.flatMap((g) => g.components).find((c) => c.stories.some((s) => s.id === PG.storyId));
const name = comp ? comp.label.replace(/\s+/g, "") : "Component";
const entries = Object.entries(PG.args).filter(([k, v]) => v !== undefined && v !== "" && k !== "children");
const props = entries.map(([k, v]) =>
typeof v === "boolean" ? (v ? ` ${k}` : ` ${k}={false}`) :
typeof v === "number" ? ` ${k}={${v}}` : ` ${k}="${String(v)}"`).join("");
const kids = PG.args.children;
el.textContent = typeof kids === "string" && kids
? `<${name}${props}>${kids}</${name}>`
: `<${name}${props} />`;
}
function render() {
const f = $("q").value.trim();
$("status").classList.add("hide");
const isComp = tab === "components";
const isPg = tab === "playground";
document.body.classList.toggle("pg-full", isPg);
$("foundations").classList.toggle("hide", isComp || isPg);
$("components").classList.toggle("hide", !isComp);
$("playground").classList.toggle("hide", !isPg);
// The component list drives the playground too, so the rail stays up for both.
$("side").classList.toggle("hide", !isComp && !isPg);
if (isPg) { renderSide(f); renderPlayground(); return; }
if (isComp) {
renderSide(f);
// A filter that hides the selected component would otherwise strand the pane on
// something the sidebar no longer offers a way back to.
if (f && !document.querySelector(`#side [data-comp="${CSS.escape(active || "")}"]`)) {
const first = document.querySelector("#side [data-comp]");
if (first) active = first.dataset.comp;
renderSide(f);
}
renderComponent();
} else { renderFoundations(f); }
}
async function load() {
syncMode();
const res = await kit.apiFetch("/api/plugins/design-system/catalog");
if (!res.ok) { $("status").textContent = `Could not read the catalog (HTTP ${res.status}).`; return; }
DATA = await res.json();
$("src").textContent = `${DATA.meta.repo}@${DATA.meta.ref}`;
const sb = DATA.meta.storybook_url;
if (sb) { $("sblink").href = sb; $("sblink").textContent = "Storybook ↗"; }
const all = DATA.groups.flatMap((g) => g.components);
active = active || (all.find((c) => c.label === "Button") || all[0] || {}).title || null;
render();
}
$("tabs").addEventListener("click", (e) => {
const b = e.target.closest("[data-tab]"); if (!b) return;
tab = b.dataset.tab;
for (const t of $("tabs").children) {
const on = t === b;
t.classList.toggle("pl-tab--active", on);
t.setAttribute("aria-pressed", String(on));
}
render();
});
$("side").addEventListener("click", (e) => {
const b = e.target.closest("[data-comp]"); if (!b) return;
active = b.dataset.comp;
PG.storyId = null; // fall to the new component's first variant
render();
});
// Playground controls. Delegated from the section, so a re-render never orphans a handler.
$("playground").addEventListener("click", (e) => {
// Width and theme must NOT re-render: that recreates the iframe, which reloads the story
// and silently discards every arg the user has set. Resize the stage in place, and switch
// the theme through Storybook's own globals channel instead of a new URL.
const w = e.target.closest("#pg-width [data-w]");
if (w) {
PG.width = w.dataset.w;
const preset = WIDTHS.find((x) => x.id === PG.width) || WIDTHS[0];
document.querySelector("#playground .pg-frame").style.width = preset.css;
for (const btn of e.currentTarget.querySelectorAll("#pg-width [data-w]")) {
btn.setAttribute("aria-pressed", String(btn === w));
}
return;
}
const t = e.target.closest("#pg-theme [data-t]");
if (t) {
PG.theme = t.dataset.t;
for (const btn of e.currentTarget.querySelectorAll("#pg-theme [data-t]")) {
btn.setAttribute("aria-pressed", String(btn === t));
}
sendToStory("updateGlobals", { globals: { theme: pgMode() } });
return;
}
if (e.target.closest("#pg-reset")) {
const init = (PG.prepared && PG.prepared.initialArgs) || {};
PG.args = { ...init };
// resetStoryArgs clears everything the manager set; then re-apply the story's own args.
sendToStory("resetStoryArgs", { storyId: PG.storyId });
renderControls();
return;
}
const choice = e.target.closest('.segbtns[data-kind="choice"] [data-v]');
if (choice) {
const group = choice.closest("[data-arg]");
for (const b of group.querySelectorAll("button")) b.setAttribute("aria-pressed", String(b === choice));
setArg(group.dataset.arg, choice.dataset.v);
}
});
$("playground").addEventListener("input", (e) => {
const el = e.target.closest("[data-arg]");
if (!el || el.tagName === "DIV") return;
const kind = el.dataset.kind;
const value = kind === "boolean" ? el.checked : kind === "number" ? Number(el.value) : el.value;
setArg(el.dataset.arg, value);
});
$("playground").addEventListener("change", (e) => {
const sel = e.target.closest("#pg-variant");
if (!sel) return;
PG.storyId = sel.value;
PG.prepared = null; PG.args = {};
renderPlayground();
});
$("foundations").addEventListener("click", async (e) => {
const b = e.target.closest("[data-copy]"); if (!b) return;
try {
await navigator.clipboard.writeText(b.dataset.copy);
const meta = b.querySelector(".vl"), was = meta.textContent;
meta.textContent = "copied ✓";
setTimeout(() => { meta.textContent = was; }, 900);
} catch { /* clipboard blocked in this frame; the name is on screen to copy by hand */ }
});
$("q").addEventListener("input", () => { if (DATA) render(); });
$("refresh").addEventListener("click", async () => {
$("refresh").disabled = true;
try { await kit.apiFetch("/api/plugins/design-system/refresh", { method: "POST" }); await load(); }
finally { $("refresh").disabled = false; }
});
await load();
</script>
</body>
</html>