miral 0.0.3 → 0.0.5

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.
package/src/Viewer.tsx DELETED
@@ -1,646 +0,0 @@
1
- import React from "react";
2
- import { createRoot } from "react-dom/client";
3
- import type * as z from "zod/mini";
4
- import { Icon } from "./icons.tsx";
5
- import "/__glasso-viewer.css";
6
-
7
- import { Assets } from "./Assets.tsx";
8
- import { Controls, type Values } from "./Controls.tsx";
9
- import { Nav } from "./Nav.tsx";
10
- import { Spinner } from "./Spinner.tsx";
11
- import { Toolbar } from "./Toolbar.tsx";
12
-
13
- type ExampleModule = {
14
- Preview?: React.ComponentType;
15
- Playground?: React.ComponentType<Values>;
16
- schema?: z.ZodMiniObject;
17
- defaults?: Values;
18
- layout?: string;
19
- playgroundLayout?: string;
20
- } & Record<string, unknown>;
21
-
22
- const modules = import.meta.glob<ExampleModule>([
23
- "/**/*.ui.tsx",
24
- "!/**/node_modules/**",
25
- "!/**/dist/**",
26
- "!/**/.git/**",
27
- ]);
28
-
29
- const sections = import.meta.glob<string>(
30
- ["/**/*.ui.tsx", "!/**/node_modules/**", "!/**/dist/**", "!/**/.git/**"],
31
- { eager: true, query: "?glasso-section", import: "default" },
32
- );
33
-
34
- type GlassoConfig = {
35
- title?: string;
36
- assetsDir?: string;
37
- stylesheet?: string;
38
- order?: string[];
39
- componentOrder?: string[];
40
- };
41
-
42
- const configs = import.meta.glob<{
43
- default: GlassoConfig;
44
- assetFiles?: Record<string, string>;
45
- }>("/glasso.config.ts", { eager: true });
46
-
47
- const config = configs["/glasso.config.ts"];
48
-
49
- const {
50
- title,
51
- order = [],
52
- componentOrder = [],
53
- stylesheet,
54
- } = config?.default ?? {};
55
-
56
- const catalogTitle = title?.trim();
57
-
58
- document.title = catalogTitle ? `${catalogTitle} | Glasso` : "Glasso";
59
-
60
- const assets = config?.assetFiles;
61
- const assetsEntry = { path: "assets", name: "Assets", section: "" };
62
-
63
- const assetsPage: ExampleModule = {
64
- Preview: () => <Assets files={assets ?? {}} />,
65
- layout: "padded",
66
- };
67
-
68
- function compare(a: string, b: string, preferred: string[]) {
69
- const rank = (name: string) =>
70
- preferred.includes(name) ? preferred.indexOf(name) : preferred.length;
71
-
72
- return rank(a) - rank(b) || a.localeCompare(b);
73
- }
74
-
75
- const entries = Object.keys(modules)
76
- .map((path) => {
77
- const parts = path.split("/");
78
- const section = sections[path] || "Elements";
79
- return {
80
- path,
81
- section,
82
- name: parts.at(-1)?.replace(/\.ui\.tsx$/, "") ?? path,
83
- };
84
- })
85
- .sort(
86
- (a, b) =>
87
- compare(a.section, b.section, order) ||
88
- compare(a.name, b.name, componentOrder),
89
- );
90
-
91
- const layouts = {
92
- Mobile: [390, 844],
93
- Tablet: [768, 1024],
94
- Desktop: null,
95
- };
96
-
97
- const devices = [
98
- { name: "Mobile", label: "Smartphone", icon: "phone" },
99
- { name: "Tablet", label: "Tablet", icon: "tablet" },
100
- { name: "Desktop", label: "Desktop", icon: "desktop" },
101
- ] as const;
102
-
103
- type Shortcut = "layout" | "theme" | "fullscreen" | "escape" | "toolbar";
104
-
105
- function getShortcut(event: KeyboardEvent): Shortcut | undefined {
106
- if (
107
- event.defaultPrevented ||
108
- event.repeat ||
109
- event.isComposing ||
110
- event.ctrlKey ||
111
- event.altKey ||
112
- event.metaKey
113
- )
114
- return;
115
-
116
- if (
117
- event.key === "Escape" &&
118
- !document.querySelector("dialog[open], [role=dialog][aria-modal=true]")
119
- )
120
- return "escape";
121
-
122
- if (
123
- !event.shiftKey ||
124
- (event.target instanceof Element &&
125
- event.target.closest(
126
- "input, textarea, select, [contenteditable]:not([contenteditable=false])",
127
- ))
128
- )
129
- return;
130
-
131
- switch (event.key.toLowerCase()) {
132
- case "c":
133
- return "toolbar";
134
- case "l":
135
- return "layout";
136
- case "t":
137
- return "theme";
138
- case "f":
139
- return "fullscreen";
140
- }
141
- }
142
-
143
- const initialUrl = new URL(location.href);
144
- const frame = initialUrl.searchParams.has("frame");
145
-
146
- const emptyPage: ExampleModule = {};
147
- const pages = new Map<string, Promise<ExampleModule>>();
148
-
149
- function loadPage(path: string) {
150
- const cached = pages.get(path);
151
- if (cached) return cached;
152
-
153
- const result = modules[path]();
154
-
155
- pages.set(path, result);
156
- return result;
157
- }
158
-
159
- function link(params: Record<string, string>) {
160
- const result = new URL(location.pathname, location.origin);
161
-
162
- result.search = new URLSearchParams(params).toString();
163
- return result.href;
164
- }
165
-
166
- function readValues(page: ExampleModule, url: URL) {
167
- try {
168
- const stored = url.searchParams.get("props");
169
- const values = stored ? JSON.parse(stored) : (page.defaults ?? {});
170
- if (page.schema?.safeParse(values).success) return values as Values;
171
- } catch {}
172
-
173
- return page.defaults ?? {};
174
- }
175
-
176
- function animateIsolation(canvas: HTMLIFrameElement, open: boolean) {
177
- const slot = canvas.parentElement;
178
- const stage = slot?.parentElement;
179
- if (!slot || !stage) return;
180
-
181
- const current = canvas.getBoundingClientRect();
182
- const normal = slot.getBoundingClientRect();
183
- const visible = stage.getBoundingClientRect();
184
-
185
- const edges = [
186
- visible.top - normal.top,
187
- normal.right - visible.right,
188
- normal.bottom - visible.bottom,
189
- visible.left - normal.left,
190
- ];
191
-
192
- const clipped =
193
- "inset(" + edges.map((edge) => Math.max(0, edge) + "px").join(" ") + ")";
194
-
195
- const animations = canvas.getAnimations();
196
-
197
- const currentClip =
198
- !animations.length && open ? clipped : getComputedStyle(canvas).clipPath;
199
-
200
- for (const animation of animations) animation.cancel();
201
-
202
- if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
203
-
204
- const bounds = (rect: DOMRect, clipPath: string) => ({
205
- position: "fixed",
206
- transform: "none",
207
- zIndex: "1",
208
- top: rect.top + "px",
209
- left: rect.left + "px",
210
- width: rect.width + "px",
211
- height: rect.height + "px",
212
- clipPath,
213
- });
214
-
215
- const full = new DOMRect(
216
- 0,
217
- 0,
218
- document.documentElement.clientWidth,
219
- window.innerHeight,
220
- );
221
-
222
- canvas.animate(
223
- [
224
- bounds(current, currentClip === "none" ? "inset(0px)" : currentClip),
225
- bounds(open ? full : normal, open ? "inset(0px)" : clipped),
226
- ],
227
- { duration: 200, easing: "ease-out" },
228
- );
229
- }
230
-
231
- const FrameLoading = () => {
232
- React.useLayoutEffect(() => {
233
- parent.postMessage({ type: "glasso-loading" }, location.origin);
234
- }, []);
235
-
236
- return null;
237
- };
238
-
239
- const Viewer = () => {
240
- const [url, setUrl] = React.useState(initialUrl);
241
-
242
- const entry =
243
- assets &&
244
- (url.searchParams.get("component") === assetsEntry.path || !entries.length)
245
- ? assetsEntry
246
- : (entries.find(
247
- (item) => item.path === url.searchParams.get("component"),
248
- ) ?? entries[0]);
249
-
250
- const example = url.searchParams.get("example") || "Preview";
251
- let page = emptyPage;
252
-
253
- if (entry === assetsEntry) page = assetsPage;
254
- else if (entry) page = React.use(loadPage(entry.path));
255
-
256
- const [values, setValues] = React.useState<Values>(() =>
257
- readValues(page, url),
258
- );
259
-
260
- const [previousUrl, setPreviousUrl] = React.useState(url);
261
-
262
- if (previousUrl !== url) {
263
- setPreviousUrl(url);
264
-
265
- if (
266
- ["component", "example", "props"].some(
267
- (key) =>
268
- previousUrl.searchParams.get(key) !== url.searchParams.get(key),
269
- )
270
- )
271
- setValues(readValues(page, url));
272
- }
273
-
274
- React.useEffect(() => {
275
- const handlePopState = () =>
276
- React.startTransition(() => setUrl(new URL(location.href)));
277
-
278
- window.addEventListener("popstate", handlePopState);
279
- return () => window.removeEventListener("popstate", handlePopState);
280
- }, []);
281
-
282
- const handleLinkClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
283
- if (
284
- event.defaultPrevented ||
285
- event.button !== 0 ||
286
- event.metaKey ||
287
- event.ctrlKey ||
288
- event.shiftKey ||
289
- event.altKey
290
- )
291
- return;
292
-
293
- event.preventDefault();
294
-
295
- const next = new URL(event.currentTarget.href);
296
- if (next.href === location.href) return;
297
- history.pushState(null, "", next.href);
298
- React.startTransition(() => setUrl(next));
299
- };
300
-
301
- const [theme, setTheme] = React.useState(
302
- url.searchParams.get("theme") === "dark" ? "dark" : "light",
303
- );
304
-
305
- const requestedLayout = url.searchParams.get("layout") ?? "";
306
-
307
- const layout = Object.hasOwn(layouts, requestedLayout)
308
- ? (requestedLayout as keyof typeof layouts)
309
- : "Desktop";
310
-
311
- const changeLayout = (nextLayout: keyof typeof layouts) => {
312
- const next = new URL(location.href);
313
-
314
- next.searchParams.set("layout", nextLayout);
315
- history.replaceState(history.state, "", next.href);
316
- setUrl(next);
317
- };
318
-
319
- const iframe = React.useRef<HTMLIFrameElement>(null);
320
- const [frameLoading, setFrameLoading] = React.useState(true);
321
- const stage = React.useRef<HTMLDivElement>(null);
322
- const [stageWidth, setStageWidth] = React.useState<number>();
323
- const hasPreview = !!entry && !frame;
324
-
325
- React.useLayoutEffect(() => {
326
- const element = stage.current;
327
- if (!element) return;
328
-
329
- const measure = () => setStageWidth(element.clientWidth);
330
-
331
- measure();
332
-
333
- const observer = new ResizeObserver(measure);
334
-
335
- observer.observe(element);
336
- return () => observer.disconnect();
337
- }, [hasPreview]);
338
-
339
- const isolationButton = React.useRef<HTMLButtonElement>(null);
340
-
341
- const [toolbarHidden, setToolbarHidden] = React.useState(false);
342
-
343
- const [isolated, setIsolated] = React.useState(
344
- !frame && initialUrl.searchParams.has("isolated"),
345
- );
346
-
347
- const handleThemeClick = () =>
348
- setTheme((current) => (current === "light" ? "dark" : "light"));
349
-
350
- const handleLayoutClick = (event: React.MouseEvent<HTMLButtonElement>) =>
351
- changeLayout(event.currentTarget.value as keyof typeof layouts);
352
-
353
- const handleIsolationClick = () => {
354
- if (iframe.current) animateIsolation(iframe.current, !isolated);
355
- setIsolated(!isolated);
356
-
357
- if (!isolated) return;
358
-
359
- const current = new URL(location.href);
360
-
361
- current.searchParams.delete("isolated");
362
-
363
- if (current.href !== location.href)
364
- history.replaceState(history.state, "", current);
365
-
366
- requestAnimationFrame(() =>
367
- isolationButton.current?.focus({ preventScroll: true }),
368
- );
369
- };
370
-
371
- React.useEffect(() => {
372
- if (isolated) iframe.current?.focus({ preventScroll: true });
373
- }, [isolated]);
374
-
375
- const runShortcut = React.useEffectEvent((action: Shortcut) => {
376
- if (action === "toolbar" && !isolated)
377
- setToolbarHidden((hidden) => !hidden);
378
-
379
- if (action === "theme") handleThemeClick();
380
-
381
- if (action === "layout")
382
- changeLayout(
383
- devices[
384
- (devices.findIndex((device) => device.name === layout) + 1) %
385
- devices.length
386
- ].name,
387
- );
388
-
389
- if (action === "fullscreen" || (isolated && action === "escape"))
390
- handleIsolationClick();
391
- });
392
-
393
- React.useEffect(() => {
394
- const handleKeyDown = (event: KeyboardEvent) => {
395
- const action = getShortcut(event);
396
- if (!action) return;
397
-
398
- if (action !== "escape") {
399
- event.preventDefault();
400
- event.stopPropagation();
401
- }
402
-
403
- if (frame)
404
- parent.postMessage(
405
- { type: "glasso-shortcut", action },
406
- location.origin,
407
- );
408
- else runShortcut(action);
409
- };
410
-
411
- const handleMessage = (event: MessageEvent) => {
412
- if (
413
- !frame &&
414
- event.source === iframe.current?.contentWindow &&
415
- event.origin === location.origin &&
416
- event.data?.type === "glasso-shortcut"
417
- )
418
- runShortcut(event.data.action);
419
- };
420
-
421
- window.addEventListener("keydown", handleKeyDown, true);
422
- window.addEventListener("message", handleMessage);
423
-
424
- return () => {
425
- window.removeEventListener("keydown", handleKeyDown, true);
426
- window.removeEventListener("message", handleMessage);
427
- };
428
- }, []);
429
-
430
- React.useEffect(() => {
431
- document.documentElement.classList.toggle("dark", theme === "dark");
432
- document.documentElement.classList.toggle("light", theme === "light");
433
- }, [theme]);
434
-
435
- React.useLayoutEffect(() => {
436
- if (frame) {
437
- const receive = (event: MessageEvent) => {
438
- if (
439
- event.origin !== location.origin ||
440
- event.source !== parent ||
441
- event.data?.type !== "glasso-settings"
442
- )
443
- return;
444
-
445
- setTheme(event.data.theme === "dark" ? "dark" : "light");
446
-
447
- if (page.schema?.safeParse(event.data.values).success)
448
- setValues(event.data.values);
449
- };
450
-
451
- window.addEventListener("message", receive);
452
- parent.postMessage({ type: "glasso-ready" }, location.origin);
453
-
454
- return () => {
455
- window.removeEventListener("message", receive);
456
- };
457
- }
458
- }, [page]);
459
-
460
- React.useEffect(() => {
461
- if (frame) return;
462
-
463
- const sync = () =>
464
- iframe.current?.contentWindow?.postMessage(
465
- { type: "glasso-settings", theme, values },
466
- location.origin,
467
- );
468
-
469
- const ready = (event: MessageEvent) => {
470
- if (
471
- event.origin !== location.origin ||
472
- event.source !== iframe.current?.contentWindow
473
- )
474
- return;
475
-
476
- if (event.data?.type === "glasso-ready") {
477
- setFrameLoading(false);
478
- sync();
479
- } else if (event.data?.type === "glasso-loading") {
480
- setFrameLoading(true);
481
- }
482
- };
483
-
484
- window.addEventListener("message", ready);
485
- sync();
486
- return () => window.removeEventListener("message", ready);
487
- }, [theme, values]);
488
-
489
- const names = Object.keys(page).filter(
490
- (key) =>
491
- /^[A-Z]/.test(key) &&
492
- (typeof page[key] === "function" ||
493
- (page[key] !== null &&
494
- typeof page[key] === "object" &&
495
- "$$typeof" in page[key])) &&
496
- !["Preview", "Playground"].includes(key),
497
- );
498
-
499
- if (page.Playground) names.unshift("Playground");
500
-
501
- const selected = names.includes(example) ? example : "Preview";
502
-
503
- const frameUrl =
504
- entry && link({ component: entry.path, example: selected, frame: "1" });
505
-
506
- React.useLayoutEffect(() => {
507
- if (!frame && frameUrl) setFrameLoading(true);
508
- }, [frameUrl]);
509
-
510
- if (frame && entry) {
511
- const Component = page[selected] as React.ComponentType<Values>;
512
- if (!Component) return <p>Export Preview from {entry.name}.ui.tsx.</p>;
513
-
514
- return (
515
- <main
516
- className="gl:box-border gl:min-h-dvh gl:bg-paper gl:text-ink gl:data-[layout=centered]:grid gl:data-[layout=centered]:place-items-center gl:data-[layout=centered]:p-4 gl:data-[layout=padded]:p-4"
517
- data-layout={
518
- (selected === "Playground" ? page.playgroundLayout : page.layout) ??
519
- "centered"
520
- }
521
- >
522
- {!!stylesheet && (
523
- <link rel="stylesheet" href={stylesheet} precedence="preview" />
524
- )}
525
- <Component {...(selected === "Playground" ? values : {})} />
526
- </main>
527
- );
528
- }
529
-
530
- const size = layouts[layout];
531
-
532
- const scale =
533
- size && stageWidth !== undefined ? Math.min(1, stageWidth / size[0]) : 1;
534
-
535
- return (
536
- <div
537
- className="preview-shell gl:group/shell"
538
- data-isolated={isolated || undefined}
539
- >
540
- {!!entry && frameLoading && <Spinner />}
541
- <Nav
542
- title={title}
543
- entries={entries}
544
- assetsPath={assets && assetsEntry.path}
545
- activePath={entry?.path}
546
- names={names}
547
- selected={selected}
548
- theme={theme}
549
- layout={layout}
550
- isolated={isolated}
551
- link={link}
552
- onLinkClick={handleLinkClick}
553
- />
554
- <main className="gl:flex gl:min-h-0 gl:flex-col gl:[@media(max-width:600px)]:flex-1">
555
- {!!entry && (
556
- <>
557
- <div
558
- className="gl:sticky gl:top-0 gl:z-1 gl:transition-opacity gl:duration-200 gl:ease-out gl:group-data-isolated/shell:opacity-0 gl:motion-reduce:transition-none"
559
- inert={isolated}
560
- >
561
- <Toolbar hidden={toolbarHidden} isolated={isolated}>
562
- {devices.map(({ name, label, icon }) => (
563
- <button
564
- key={name}
565
- type="button"
566
- value={name}
567
- aria-label={label}
568
- aria-pressed={layout === name}
569
- aria-keyshortcuts="Shift+L"
570
- title={label + " · Shift + L to cycle layouts"}
571
- onClick={handleLayoutClick}
572
- >
573
- <Icon name={icon} />
574
- </button>
575
- ))}
576
- <button
577
- type="button"
578
- role="switch"
579
- aria-label="Dark preview"
580
- aria-keyshortcuts="Shift+T"
581
- title="Switch theme · Shift + T"
582
- aria-checked={theme === "dark"}
583
- onClick={handleThemeClick}
584
- >
585
- <Icon name={theme === "light" ? "sun" : "moon"} />
586
- </button>
587
- <button
588
- type="button"
589
- ref={isolationButton}
590
- onClick={handleIsolationClick}
591
- aria-label="Full screen"
592
- aria-keyshortcuts="Shift+F"
593
- title="Full screen · Shift + F (Esc to exit)"
594
- >
595
- <Icon name="expand" />
596
- </button>
597
- </Toolbar>
598
- </div>
599
- <div className="gl:flex-1 gl:overflow-auto" ref={stage}>
600
- <div
601
- className="gl:h-full gl:overflow-clip"
602
- style={
603
- size
604
- ? { width: size[0] * scale, height: size[1] * scale }
605
- : undefined
606
- }
607
- >
608
- <iframe
609
- key={frameUrl}
610
- className="gl:block gl:origin-top-left gl:transition-none gl:max-w-none gl:border-0 gl:bg-paper gl:group-has-[[data-dragging]]/shell:pointer-events-none gl:group-data-isolated/shell:fixed gl:group-data-isolated/shell:inset-0 gl:group-data-isolated/shell:w-full gl:group-data-isolated/shell:h-dvh gl:group-data-isolated/shell:z-1"
611
- ref={iframe}
612
- style={{
613
- transform:
614
- isolated || scale === 1 ? "none" : "scale(" + scale + ")",
615
- }}
616
- title={entry.name}
617
- width={size?.[0] ?? "100%"}
618
- height={size?.[1] ?? "100%"}
619
- src={frameUrl}
620
- />
621
- </div>
622
- </div>
623
- {selected === "Playground" && !!page.schema && (
624
- <Controls
625
- schema={page.schema}
626
- values={values}
627
- onChange={setValues}
628
- />
629
- )}
630
- </>
631
- )}
632
- </main>
633
- </div>
634
- );
635
- };
636
-
637
- const container = document.getElementById("root");
638
-
639
- if (container)
640
- createRoot(container).render(
641
- <React.Suspense
642
- fallback={frame && parent !== window ? <FrameLoading /> : <Spinner />}
643
- >
644
- <Viewer />
645
- </React.Suspense>,
646
- );