miral 0.0.4 → 0.0.6

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,643 +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 "/__miral-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
- "/**/*.mira.tsx",
24
- "!/**/node_modules/**",
25
- "!/**/dist/**",
26
- "!/**/.git/**",
27
- ]);
28
-
29
- const sections = import.meta.glob<string>(
30
- ["/**/*.mira.tsx", "!/**/node_modules/**", "!/**/dist/**", "!/**/.git/**"],
31
- { eager: true, query: "?miral-section", import: "default" },
32
- );
33
-
34
- type MiralConfig = {
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: MiralConfig;
44
- assetFiles?: Record<string, string>;
45
- }>("/miral.config.ts", { eager: true });
46
-
47
- const config = configs["/miral.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} | Miral` : "Miral";
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(/\.mira\.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: "miral-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({ type: "miral-shortcut", action }, location.origin);
405
- else runShortcut(action);
406
- };
407
-
408
- const handleMessage = (event: MessageEvent) => {
409
- if (
410
- !frame &&
411
- event.source === iframe.current?.contentWindow &&
412
- event.origin === location.origin &&
413
- event.data?.type === "miral-shortcut"
414
- )
415
- runShortcut(event.data.action);
416
- };
417
-
418
- window.addEventListener("keydown", handleKeyDown, true);
419
- window.addEventListener("message", handleMessage);
420
-
421
- return () => {
422
- window.removeEventListener("keydown", handleKeyDown, true);
423
- window.removeEventListener("message", handleMessage);
424
- };
425
- }, []);
426
-
427
- React.useEffect(() => {
428
- document.documentElement.classList.toggle("dark", theme === "dark");
429
- document.documentElement.classList.toggle("light", theme === "light");
430
- }, [theme]);
431
-
432
- React.useLayoutEffect(() => {
433
- if (frame) {
434
- const receive = (event: MessageEvent) => {
435
- if (
436
- event.origin !== location.origin ||
437
- event.source !== parent ||
438
- event.data?.type !== "miral-settings"
439
- )
440
- return;
441
-
442
- setTheme(event.data.theme === "dark" ? "dark" : "light");
443
-
444
- if (page.schema?.safeParse(event.data.values).success)
445
- setValues(event.data.values);
446
- };
447
-
448
- window.addEventListener("message", receive);
449
- parent.postMessage({ type: "miral-ready" }, location.origin);
450
-
451
- return () => {
452
- window.removeEventListener("message", receive);
453
- };
454
- }
455
- }, [page]);
456
-
457
- React.useEffect(() => {
458
- if (frame) return;
459
-
460
- const sync = () =>
461
- iframe.current?.contentWindow?.postMessage(
462
- { type: "miral-settings", theme, values },
463
- location.origin,
464
- );
465
-
466
- const ready = (event: MessageEvent) => {
467
- if (
468
- event.origin !== location.origin ||
469
- event.source !== iframe.current?.contentWindow
470
- )
471
- return;
472
-
473
- if (event.data?.type === "miral-ready") {
474
- setFrameLoading(false);
475
- sync();
476
- } else if (event.data?.type === "miral-loading") {
477
- setFrameLoading(true);
478
- }
479
- };
480
-
481
- window.addEventListener("message", ready);
482
- sync();
483
- return () => window.removeEventListener("message", ready);
484
- }, [theme, values]);
485
-
486
- const names = Object.keys(page).filter(
487
- (key) =>
488
- /^[A-Z]/.test(key) &&
489
- (typeof page[key] === "function" ||
490
- (page[key] !== null &&
491
- typeof page[key] === "object" &&
492
- "$$typeof" in page[key])) &&
493
- !["Preview", "Playground"].includes(key),
494
- );
495
-
496
- if (page.Playground) names.unshift("Playground");
497
-
498
- const selected = names.includes(example) ? example : "Preview";
499
-
500
- const frameUrl =
501
- entry && link({ component: entry.path, example: selected, frame: "1" });
502
-
503
- React.useLayoutEffect(() => {
504
- if (!frame && frameUrl) setFrameLoading(true);
505
- }, [frameUrl]);
506
-
507
- if (frame && entry) {
508
- const Component = page[selected] as React.ComponentType<Values>;
509
- if (!Component) return <p>Export Preview from {entry.name}.mira.tsx.</p>;
510
-
511
- return (
512
- <main
513
- className="miral:box-border miral:min-h-dvh miral:bg-paper miral:text-ink miral:data-[layout=centered]:grid miral:data-[layout=centered]:place-items-center miral:data-[layout=centered]:p-4 miral:data-[layout=padded]:p-4"
514
- data-layout={
515
- (selected === "Playground" ? page.playgroundLayout : page.layout) ??
516
- "centered"
517
- }
518
- >
519
- {!!stylesheet && (
520
- <link rel="stylesheet" href={stylesheet} precedence="preview" />
521
- )}
522
- <Component {...(selected === "Playground" ? values : {})} />
523
- </main>
524
- );
525
- }
526
-
527
- const size = layouts[layout];
528
-
529
- const scale =
530
- size && stageWidth !== undefined ? Math.min(1, stageWidth / size[0]) : 1;
531
-
532
- return (
533
- <div
534
- className="preview-shell miral:group/shell"
535
- data-isolated={isolated || undefined}
536
- >
537
- {!!entry && frameLoading && <Spinner />}
538
- <Nav
539
- title={title}
540
- entries={entries}
541
- assetsPath={assets && assetsEntry.path}
542
- activePath={entry?.path}
543
- names={names}
544
- selected={selected}
545
- theme={theme}
546
- layout={layout}
547
- isolated={isolated}
548
- link={link}
549
- onLinkClick={handleLinkClick}
550
- />
551
- <main className="miral:flex miral:min-h-0 miral:flex-col miral:[@media(max-width:600px)]:flex-1">
552
- {!!entry && (
553
- <>
554
- <div
555
- className="miral:sticky miral:top-0 miral:z-1 miral:transition-opacity miral:duration-200 miral:ease-out miral:group-data-isolated/shell:opacity-0 miral:motion-reduce:transition-none"
556
- inert={isolated}
557
- >
558
- <Toolbar hidden={toolbarHidden} isolated={isolated}>
559
- {devices.map(({ name, label, icon }) => (
560
- <button
561
- key={name}
562
- type="button"
563
- value={name}
564
- aria-label={label}
565
- aria-pressed={layout === name}
566
- aria-keyshortcuts="Shift+L"
567
- title={label + " · Shift + L to cycle layouts"}
568
- onClick={handleLayoutClick}
569
- >
570
- <Icon name={icon} />
571
- </button>
572
- ))}
573
- <button
574
- type="button"
575
- role="switch"
576
- aria-label="Dark preview"
577
- aria-keyshortcuts="Shift+T"
578
- title="Switch theme · Shift + T"
579
- aria-checked={theme === "dark"}
580
- onClick={handleThemeClick}
581
- >
582
- <Icon name={theme === "light" ? "sun" : "moon"} />
583
- </button>
584
- <button
585
- type="button"
586
- ref={isolationButton}
587
- onClick={handleIsolationClick}
588
- aria-label="Full screen"
589
- aria-keyshortcuts="Shift+F"
590
- title="Full screen · Shift + F (Esc to exit)"
591
- >
592
- <Icon name="expand" />
593
- </button>
594
- </Toolbar>
595
- </div>
596
- <div className="miral:flex-1 miral:overflow-auto" ref={stage}>
597
- <div
598
- className="miral:h-full miral:overflow-clip"
599
- style={
600
- size
601
- ? { width: size[0] * scale, height: size[1] * scale }
602
- : undefined
603
- }
604
- >
605
- <iframe
606
- key={frameUrl}
607
- className="miral:block miral:origin-top-left miral:transition-none miral:max-w-none miral:border-0 miral:bg-paper miral:group-has-[[data-dragging]]/shell:pointer-events-none miral:group-data-isolated/shell:fixed miral:group-data-isolated/shell:inset-0 miral:group-data-isolated/shell:w-full miral:group-data-isolated/shell:h-dvh miral:group-data-isolated/shell:z-1"
608
- ref={iframe}
609
- style={{
610
- transform:
611
- isolated || scale === 1 ? "none" : "scale(" + scale + ")",
612
- }}
613
- title={entry.name}
614
- width={size?.[0] ?? "100%"}
615
- height={size?.[1] ?? "100%"}
616
- src={frameUrl}
617
- />
618
- </div>
619
- </div>
620
- {selected === "Playground" && !!page.schema && (
621
- <Controls
622
- schema={page.schema}
623
- values={values}
624
- onChange={setValues}
625
- />
626
- )}
627
- </>
628
- )}
629
- </main>
630
- </div>
631
- );
632
- };
633
-
634
- const container = document.getElementById("root");
635
-
636
- if (container)
637
- createRoot(container).render(
638
- <React.Suspense
639
- fallback={frame && parent !== window ? <FrameLoading /> : <Spinner />}
640
- >
641
- <Viewer />
642
- </React.Suspense>,
643
- );