-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1042 lines (1022 loc) · 43.4 KB
/
Copy pathApp.tsx
File metadata and controls
1042 lines (1022 loc) · 43.4 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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { lazy, Suspense, useEffect, useState } from "react"
import {
Activity,
BriefcaseBusiness,
CalendarDays,
ChevronDown,
Clock3,
CircleDollarSign,
Braces,
Check,
Copy,
Inbox,
LayoutDashboard,
Menu,
Moon,
Newspaper,
PanelLeftClose,
PanelLeftOpen,
RefreshCcw,
Rocket,
Settings2,
ShieldCheck,
Sparkles,
Sun,
X,
} from "lucide-react"
import { BlockRenderer } from "@/components/BlockRenderer"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
import { snapshotFreshness, type FreshnessState } from "@/lib/freshness"
import type { DashboardData, InstanceConfig, Snapshot, SourceDefinition } from "@/types"
const Onboarding = lazy(() => import("@/components/Onboarding"))
const DemoTour = lazy(() => import("@/components/DemoTour"))
const domainIcons = {
overview: LayoutDashboard,
agenda: CalendarDays,
inbox: Inbox,
work: BriefcaseBusiness,
money: CircleDollarSign,
news: Newspaper,
review: Activity,
} as const
const START_ID = "__start"
const COMPONENTS_ID = "__components"
const publicAsset = (file: string) => `${import.meta.env.BASE_URL}${file.replace(/^\//, "")}`
const health = {
fresh: { label: "Fresh and complete", dot: "bg-positive" },
aging: { label: "Refresh expected soon", dot: "bg-info" },
stale: { label: "Expired snapshot", dot: "bg-warning" },
partial: { label: "Some evidence limited", dot: "bg-warning" },
failed: { label: "Source unavailable", dot: "bg-destructive" },
missing: { label: "No snapshot yet", dot: "bg-muted-foreground" },
} satisfies Record<FreshnessState, { label: string; dot: string }>
type ThemeMode = "light" | "dark"
type Density = "compact" | "comfortable"
type FontFamily = InstanceConfig["theme"]["font_family"]
type HeadingStyle = InstanceConfig["theme"]["heading_style"]
function initialMode(data: DashboardData): ThemeMode {
const stored = localStorage.getItem("zaati-theme")
if (stored === "light" || stored === "dark") return stored
if (data.instance.theme.default_mode !== "system") return data.instance.theme.default_mode
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
}
function initialView(data: DashboardData, fallback: string) {
const requested = new URL(window.location.href).searchParams.get("view")
if (requested === "start") return START_ID
if (requested === "components" && data.demoMode) return COMPONENTS_ID
if (data.sources.some((item) => item.definition.id === requested)) return requested as string
return data.demoMode || data.sources.every((item) => !item.snapshot) ? START_ID : fallback
}
function initialNow(data: DashboardData) {
const injected = data.demoMode ? new URL(window.location.href).searchParams.get("at") : null
const parsed = injected ? Date.parse(injected) : Number.NaN
return Number.isFinite(parsed) ? parsed : Date.now()
}
export function App() {
const [data, setData] = useState<DashboardData | null>(null)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const controller = new AbortController()
fetch(publicAsset("data/dashboard-data.json"), { cache: "no-store", credentials: "same-origin", signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error(`Dashboard data returned ${response.status}.`)
return response.json() as Promise<DashboardData>
})
.then(setData)
.catch((reason: unknown) => {
if (reason instanceof Error && reason.name === "AbortError") return
setError(reason instanceof Error ? reason.message : "Dashboard data could not be loaded.")
})
return () => controller.abort()
}, [])
if (error) return <LoadError message={error} />
if (!data) return <AppLoading />
return <DashboardApp data={data} />
}
function DashboardApp({ data }: { data: DashboardData }) {
const overviewId =
data.sources.find((item) => item.definition.id === "overview:daily")?.definition.id || data.sources[0]?.definition.id || ""
const [selectedId, setSelectedId] = useState(() => initialView(data, overviewId))
const [mode, setMode] = useState<ThemeMode>(() => initialMode(data))
const [palette, setPalette] = useState(() => localStorage.getItem("zaati-palette") || data.instance.theme.preset)
const [density, setDensity] = useState<Density>(() => (localStorage.getItem("zaati-density") as Density) || data.instance.theme.density)
const [fontFamily, setFontFamily] = useState<FontFamily>(
() => (localStorage.getItem("zaati-font") as FontFamily) || data.instance.theme.font_family,
)
const [headingStyle, setHeadingStyle] = useState<HeadingStyle>(
() => (localStorage.getItem("zaati-headings") as HeadingStyle) || data.instance.theme.heading_style,
)
const [radius, setRadius] = useState(() => localStorage.getItem("zaati-radius") || data.instance.theme.radius)
const [settingsOpen, setSettingsOpen] = useState(false)
const [mobileOpen, setMobileOpen] = useState(false)
const [sidebarCompact, setSidebarCompact] = useState(false)
const [now, setNow] = useState(() => initialNow(data))
const [historySnapshotId, setHistorySnapshotId] = useState("")
const [tourOpen, setTourOpen] = useState(
() =>
data.demoMode &&
data.instance.experience.show_tour &&
initialView(data, overviewId) === START_ID &&
localStorage.getItem("zaati-demo-tour") !== "complete",
)
const selected = data.sources.find((item) => item.definition.id === selectedId)
const history = data.historyBySource[selectedId] || []
const activeSnapshot = historySnapshotId
? history.find((snapshot) => snapshot.snapshot_id === historySnapshotId) || selected?.snapshot
: selected?.snapshot
const selectedLabel =
selectedId === START_ID ? "Start here" : selectedId === COMPONENTS_ID ? "Component lab" : selected?.definition.label || "Dashboard"
useEffect(() => {
const root = document.documentElement
root.classList.toggle("dark", mode === "dark")
root.dataset.palette = palette
root.dataset.density = density
root.dataset.font = fontFamily
root.dataset.heading = headingStyle
root.style.setProperty("--radius", radius)
const tokenMap = {
primary: "--primary",
primary_foreground: "--primary-foreground",
accent: "--accent",
accent_foreground: "--accent-foreground",
background: "--background",
foreground: "--foreground",
card: "--card",
card_foreground: "--card-foreground",
border: "--border",
sidebar: "--sidebar",
sidebar_foreground: "--sidebar-foreground",
chart_1: "--chart-1",
chart_2: "--chart-2",
chart_3: "--chart-3",
} as const
for (const token of Object.values(tokenMap)) root.style.removeProperty(token)
if (palette === "custom") {
for (const [key, value] of Object.entries(data.instance.theme.custom_tokens[mode] || {})) {
if (key in tokenMap && /^#[0-9a-f]{6}$/i.test(value)) root.style.setProperty(tokenMap[key as keyof typeof tokenMap], value)
}
}
document.title = data.instance.brand_name
document.documentElement.lang = data.instance.locale
try {
const locale = new Intl.Locale(data.instance.locale) as Intl.Locale & {
getTextInfo?: () => { direction: "ltr" | "rtl" }
textInfo?: { direction: "ltr" | "rtl" }
}
document.documentElement.dir = locale.getTextInfo?.().direction || locale.textInfo?.direction || "ltr"
} catch {
document.documentElement.dir = "ltr"
}
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", mode === "dark" ? "#111512" : "#f6f7f4")
localStorage.setItem("zaati-palette", palette)
localStorage.setItem("zaati-density", density)
localStorage.setItem("zaati-font", fontFamily)
localStorage.setItem("zaati-headings", headingStyle)
localStorage.setItem("zaati-radius", radius)
}, [data.instance, density, fontFamily, headingStyle, mode, palette, radius])
useEffect(() => {
if (localStorage.getItem("zaati-theme") || data.instance.theme.default_mode !== "system") return
const media = window.matchMedia("(prefers-color-scheme: dark)")
const sync = () => setMode(media.matches ? "dark" : "light")
media.addEventListener("change", sync)
return () => media.removeEventListener("change", sync)
}, [data.instance.theme.default_mode, mode])
useEffect(() => {
const close = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSettingsOpen(false)
setMobileOpen(false)
}
}
document.addEventListener("keydown", close)
return () => document.removeEventListener("keydown", close)
}, [])
useEffect(() => {
const onPopState = () => setSelectedId(initialView(data, overviewId))
window.addEventListener("popstate", onPopState)
return () => window.removeEventListener("popstate", onPopState)
}, [data, overviewId])
useEffect(() => {
const timer = window.setInterval(() => setNow(Date.now()), 60_000)
return () => window.clearInterval(timer)
}, [])
const select = (id: string) => {
setSelectedId(id)
setHistorySnapshotId("")
setMobileOpen(false)
const url = new URL(window.location.href)
url.searchParams.set("view", id === START_ID ? "start" : id === COMPONENTS_ID ? "components" : id)
window.history.pushState({}, "", url)
}
const chooseMode = (value: ThemeMode) => {
localStorage.setItem("zaati-theme", value)
setMode(value)
}
const completeTour = () => {
localStorage.setItem("zaati-demo-tour", "complete")
setTourOpen(false)
}
return (
<div className="min-h-screen bg-background text-foreground">
{data.demoMode && tourOpen ? (
<Suspense fallback={null}>
<DemoTour
onComplete={completeTour}
onOpenComponentLab={() => select(COMPONENTS_ID)}
open={tourOpen}
sources={data.sources.map((item) => item.definition)}
/>
</Suspense>
) : null}
<a
className="fixed left-3 top-3 z-[70] -translate-y-20 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground shadow-lg transition-transform focus:translate-y-0"
href="#main-content"
>
Skip to content
</a>
<Sidebar
compact={sidebarCompact}
data={data}
now={now}
mobileOpen={mobileOpen}
onClose={() => setMobileOpen(false)}
onCompact={() => setSidebarCompact((value) => !value)}
onSelect={select}
selectedId={selectedId}
/>
<div className={cn("transition-[padding] duration-200 md:pl-72", sidebarCompact && "md:pl-[76px]")}>
<header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b border-border/80 bg-background/95 px-4 backdrop-blur-md sm:px-6 lg:px-8">
<div className="flex min-w-0 items-center gap-3">
<Button
className="md:hidden"
onClick={() => setMobileOpen(true)}
size="icon"
variant="ghost"
aria-controls="primary-navigation"
aria-expanded={mobileOpen}
aria-label="Open navigation"
>
<Menu className="size-5" />
</Button>
<div className="min-w-0">
<p className="truncate text-sm font-semibold">{selectedLabel}</p>
<p className="hidden truncate text-xs text-muted-foreground sm:block">{data.instance.tagline}</p>
</div>
</div>
<div className="flex items-center gap-2">
{data.demoMode || data.syntheticData ? (
<Badge variant="info">
<Sparkles className="size-3 min-[360px]:mr-1" />
<span aria-hidden="true" className="hidden min-[360px]:inline">
{data.demoMode ? "Synthetic demo" : "Synthetic test data"}
</span>
<span className="sr-only">{data.demoMode ? "Synthetic demo" : "Synthetic test data"}</span>
</Badge>
) : (
<Badge className="hidden sm:inline-flex" variant="positive">
<ShieldCheck className="mr-1 size-3" />
Private data
</Badge>
)}
<Button
onClick={() => chooseMode(mode === "light" ? "dark" : "light")}
size="icon"
variant="ghost"
aria-label={`Use ${mode === "light" ? "dark" : "light"} mode`}
>
{mode === "light" ? <Moon className="size-4" /> : <Sun className="size-4" />}
</Button>
<Dialog onOpenChange={setSettingsOpen} open={settingsOpen}>
<DialogTrigger asChild>
<Button size="icon" variant="outline" aria-label="Open theme studio">
<Settings2 className="size-4" />
</Button>
</DialogTrigger>
{settingsOpen ? (
<ThemeMenu
density={density}
fontFamily={fontFamily}
hasCustomTheme={Boolean(data.instance.theme.custom_tokens.light && data.instance.theme.custom_tokens.dark)}
headingStyle={headingStyle}
mode={mode}
onDensity={setDensity}
onFont={setFontFamily}
onHeading={setHeadingStyle}
onMode={chooseMode}
onPalette={setPalette}
onRadius={setRadius}
palette={palette}
radius={radius}
/>
) : null}
</Dialog>
</div>
</header>
<main className="mx-auto w-full max-w-[1380px] px-4 py-5 sm:px-6 lg:px-8 lg:py-8" id="main-content" tabIndex={-1}>
{selectedId === START_ID ? (
<Suspense fallback={<InlineLoading />}>
<Onboarding
demoMode={data.demoMode}
hasSnapshots={data.sources.some((item) => item.snapshot)}
instance={data.instance}
onOpenDashboard={() => select(overviewId)}
onStartTour={() => setTourOpen(true)}
/>
</Suspense>
) : selectedId === COMPONENTS_ID ? (
<ComponentLab data={data} />
) : selected ? (
<DashboardPage
definition={selected.definition}
history={history}
instance={data.instance}
now={now}
onHistory={setHistorySnapshotId}
prompt={data.demoPromptsBySource[selected.definition.id]}
snapshot={activeSnapshot || null}
/>
) : (
<EmptyDashboard />
)}
</main>
</div>
</div>
)
}
function Sidebar({
compact,
data,
mobileOpen,
now,
onClose,
onCompact,
onSelect,
selectedId,
}: {
compact: boolean
data: DashboardData
mobileOpen: boolean
now: number
onClose: () => void
onCompact: () => void
onSelect: (id: string) => void
selectedId: string
}) {
return (
<>
<Dialog onOpenChange={(open) => !open && onClose()} open={mobileOpen}>
<DialogContent
className="md:hidden"
onCloseAutoFocus={(event) => {
event.preventDefault()
document.querySelector<HTMLButtonElement>('button[aria-label="Open navigation"]')?.focus()
}}
side="left"
>
<DialogTitle className="sr-only">Dashboard navigation</DialogTitle>
<DialogDescription className="sr-only">Choose a Zaati OS section.</DialogDescription>
<SidebarPanel
compact={false}
data={data}
now={now}
onClose={onClose}
onCompact={onCompact}
onSelect={onSelect}
selectedId={selectedId}
/>
</DialogContent>
</Dialog>
<aside
className={cn(
"fixed inset-y-0 left-0 z-40 hidden w-72 flex-col border-r border-sidebar-border bg-sidebar text-sidebar-foreground transition-[width] duration-200 md:flex",
compact && "md:w-[76px]",
)}
id="primary-navigation"
>
<SidebarPanel
compact={compact}
data={data}
now={now}
onClose={onClose}
onCompact={onCompact}
onSelect={onSelect}
selectedId={selectedId}
/>
</aside>
</>
)
}
function SidebarPanel({ compact, data, now, onClose, onCompact, onSelect, selectedId }: Omit<Parameters<typeof Sidebar>[0], "mobileOpen">) {
return (
<>
<div className="flex h-16 items-center gap-3 border-b border-sidebar-border px-4">
{data.instance.brand_name === "Zaati OS" ? (
<div className="grid size-9 shrink-0 overflow-hidden rounded-xl border border-sidebar-border bg-white shadow-sm">
<img alt="" aria-hidden="true" className="size-full object-cover" src={publicAsset("logo-mark.png")} />
</div>
) : (
<div className="grid size-9 shrink-0 place-items-center rounded-xl bg-sidebar-primary text-sidebar-primary-foreground shadow-sm">
<span className="text-base font-black tracking-tight">{data.instance.brand_mark}</span>
</div>
)}
<div className={cn("min-w-0 flex-1", compact && "md:hidden")}>
<p className="truncate text-sm font-semibold">{data.instance.brand_name}</p>
<p className="truncate text-[11px] text-sidebar-foreground/75">Private by default</p>
</div>
<Button aria-label="Close navigation" className="md:hidden" onClick={onClose} size="icon" variant="ghost">
<X className="size-4" />
</Button>
</div>
<nav className="flex-1 space-y-1 overflow-y-auto p-3" aria-label="Dashboard sections">
<button
aria-current={selectedId === START_ID ? "page" : undefined}
className={cn(
"group flex min-h-10 w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
selectedId === START_ID && "bg-sidebar-accent font-medium text-sidebar-accent-foreground",
compact && "md:justify-center md:px-2",
)}
onClick={() => onSelect(START_ID)}
title={compact ? "Start here" : undefined}
>
<Rocket className={cn("size-4 shrink-0 text-sidebar-foreground/55", selectedId === START_ID && "text-sidebar-primary")} />
<span className={cn("min-w-0 flex-1 truncate", compact && "md:hidden")}>Start here</span>
</button>
<p
className={cn(
"px-3 pb-2 pt-5 text-[10px] font-semibold uppercase tracking-[0.16em] text-sidebar-foreground/70",
compact && "md:hidden",
)}
>
Your system
</p>
{data.demoMode ? (
<button
aria-current={selectedId === COMPONENTS_ID ? "page" : undefined}
className={cn(
"group flex min-h-10 w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
selectedId === COMPONENTS_ID && "bg-sidebar-accent font-medium text-sidebar-accent-foreground",
compact && "md:justify-center md:px-2",
)}
onClick={() => onSelect(COMPONENTS_ID)}
title={compact ? "Component lab" : undefined}
>
<Braces className={cn("size-4 shrink-0 text-sidebar-foreground/55", selectedId === COMPONENTS_ID && "text-sidebar-primary")} />
<span className={cn("min-w-0 flex-1 truncate", compact && "md:hidden")}>Component lab</span>
</button>
) : null}
{data.sources.map(({ definition, snapshot }) => {
const Icon = Object.hasOwn(domainIcons, definition.domain) ? domainIcons[definition.domain as keyof typeof domainIcons] : Activity
const active = definition.id === selectedId
const status = snapshotFreshness(snapshot, now)
return (
<button
aria-current={active ? "page" : undefined}
className={cn(
"group flex min-h-10 w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
active && "bg-sidebar-accent font-medium text-sidebar-accent-foreground",
compact && "md:justify-center md:px-2",
)}
key={definition.id}
onClick={() => onSelect(definition.id)}
title={`${definition.label}, ${health[status].label}`}
>
<Icon className={cn("size-4 shrink-0 text-sidebar-foreground/55", active && "text-sidebar-primary")} />
<span className={cn("min-w-0 flex-1 truncate", compact && "md:hidden")}>{definition.label}</span>
<span aria-hidden="true" className={cn("size-1.5 rounded-full", health[status].dot, compact && "md:hidden")} />
<span className="sr-only">{health[status].label}</span>
</button>
)
})}
</nav>
<div className="hidden border-t border-sidebar-border p-3 md:block">
<button
aria-label={compact ? "Expand sidebar" : "Collapse sidebar"}
className={cn(
"flex min-h-10 w-full items-center gap-3 rounded-lg px-3 py-2 text-xs text-sidebar-foreground/75 hover:bg-sidebar-accent",
compact && "md:justify-center md:px-2",
)}
onClick={onCompact}
>
<span className="hidden md:block">{compact ? <PanelLeftOpen className="size-4" /> : <PanelLeftClose className="size-4" />}</span>
<ShieldCheck className="size-4 md:hidden" />
<span className={cn(compact && "md:hidden")}>{compact ? "Expand" : "Collapse sidebar"}</span>
</button>
</div>
</>
)
}
function DashboardPage({
definition,
history,
instance,
now,
onHistory,
prompt,
snapshot,
}: {
definition: SourceDefinition
history: Snapshot[]
instance: InstanceConfig
now: number
onHistory: (snapshotId: string) => void
prompt?: string
snapshot: Snapshot | null
}) {
if (!snapshot)
return (
<section>
<PageEyebrow definition={definition} instance={instance} snapshot={null} />
<div className="mt-16 rounded-xl border border-dashed border-border p-8 text-center sm:p-12">
<RefreshCcw className="mx-auto size-7 text-muted-foreground" />
<h1 className="mt-4 text-xl font-semibold">Waiting for the first snapshot</h1>
<p className="mx-auto mt-2 max-w-lg text-sm leading-relaxed text-muted-foreground">
Run the registered prompt and publish one valid file to the worker-owned path. Missing data stays visible, it never becomes a
suspiciously confident zero.
</p>
</div>
</section>
)
const freshness = snapshotFreshness(snapshot, now)
const layout = snapshot.data.presentation.layout
const blockGrid = {
dashboard: "lg:grid-cols-3",
focus: "mx-auto max-w-5xl lg:grid-cols-2",
timeline: "mx-auto max-w-3xl lg:grid-cols-1",
}[layout]
return (
<section>
<div className="flex flex-wrap items-center justify-between gap-3">
<PageEyebrow definition={definition} instance={instance} snapshot={snapshot} />
<div className="flex flex-wrap items-center gap-2">
{history.length > 1 ? (
<label className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
Snapshot
<select
className="min-h-9 rounded-md border border-input bg-background px-2 text-foreground"
onChange={(event) => onHistory(event.target.value)}
value={snapshot.snapshot_id === history.at(-1)?.snapshot_id ? "" : snapshot.snapshot_id}
>
<option value="">Latest</option>
{[...history]
.reverse()
.slice(1)
.map((item) => (
<option key={item.snapshot_id} value={item.snapshot_id}>
{formatTimestamp(item.generated_at, instance)}
</option>
))}
</select>
</label>
) : null}
{prompt ? <PromptDrawer prompt={prompt} sourceLabel={definition.label} /> : null}
</div>
</div>
<div className="mt-4 flex flex-col justify-between gap-4 border-b border-border pb-6 lg:flex-row lg:items-end">
<div className="max-w-3xl">
<h1 className="text-pretty text-3xl font-semibold tracking-[-0.035em] sm:text-4xl">{snapshot.data.title}</h1>
<p className="mt-3 max-w-2xl text-base leading-7 text-muted-foreground">{snapshot.data.summary}</p>
</div>
<details className="group shrink-0 rounded-lg border border-border bg-card text-xs text-muted-foreground lg:max-w-md">
<summary className="flex min-h-10 cursor-pointer list-none items-center gap-2 px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<span aria-hidden="true" className={cn("size-2 rounded-full", health[freshness].dot)} />
<span>{health[freshness].label}</span>
{snapshot.quality.warnings.length ? (
<span className="rounded-full bg-warning/10 px-2 py-0.5 text-[11px] font-medium text-warning-foreground">
{snapshot.quality.warnings.length} note{snapshot.quality.warnings.length === 1 ? "" : "s"}
</span>
) : null}
<ChevronDown aria-hidden="true" className="size-3.5 opacity-50 transition-transform group-open:rotate-180" />
</summary>
<div className="max-h-[min(70vh,34rem)] overflow-y-auto border-t border-border px-3 py-3">
{snapshot.quality.warnings.length ? (
<div className="mb-3 rounded-md bg-warning/10 px-3 py-2.5 text-foreground/80">
<p className="font-medium text-foreground">Evidence notes</p>
<ul className="mt-1.5 space-y-1.5 leading-relaxed">
{snapshot.quality.warnings.map((warning) => (
<li className="flex gap-2" key={warning}>
<span aria-hidden="true" className="mt-1.5 size-1 shrink-0 rounded-full bg-warning" />
<span>{warning}</span>
</li>
))}
</ul>
</div>
) : null}
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5">
<dt>Generated</dt>
<dd className="text-foreground">{formatTimestamp(snapshot.generated_at, instance)}</dd>
<dt>Expires</dt>
<dd className="text-foreground">{formatTimestamp(snapshot.freshness.expires_at, instance)}</dd>
{snapshot.freshness.next_expected_at ? (
<>
<dt>Next run</dt>
<dd className="text-foreground">{formatTimestamp(snapshot.freshness.next_expected_at, instance)}</dd>
</>
) : null}
</dl>
<p className="mt-3 font-medium text-foreground">Evidence consulted</p>
<ul className="mt-2 space-y-2">
{snapshot.sources.map((source, index) => (
<li className="flex items-start justify-between gap-4" key={`${source.label}-${source.as_of}-${index}`}>
<span>
<span className="text-foreground">{source.label}</span>
<span className="block">As of {formatTimestamp(source.as_of, instance)}</span>
{source.reference ? (
/^https:\/\//.test(source.reference) ? (
<a className="block underline underline-offset-2" href={source.reference} rel="noreferrer" target="_blank">
Open evidence
</a>
) : (
<span className="block break-all">Reference: {source.reference}</span>
)
) : null}
</span>
<Badge variant={source.status === "ok" ? "positive" : source.status === "unavailable" ? "danger" : "warning"}>
{source.status}
</Badge>
</li>
))}
</ul>
</div>
</details>
</div>
<div className={cn("mt-5 grid grid-cols-1 gap-5", blockGrid)} data-layout={layout}>
{snapshot.data.presentation.blocks.map((block, index) => (
<BlockRenderer block={block} emphasized={layout === "focus" && index === 0} instance={instance} key={block.id} layout={layout} />
))}
</div>
<footer className="mt-8 flex flex-col justify-between gap-3 border-t border-border pt-5 text-xs text-muted-foreground sm:flex-row">
<span className="inline-flex items-center gap-1.5">
<Clock3 className="size-3.5" /> Updated {formatTimestamp(snapshot.generated_at, instance)}
</span>
<span>
{snapshot.quality.confidence} confidence, {snapshot.sources.length} source{snapshot.sources.length === 1 ? "" : "s"}, expires{" "}
{formatTimestamp(snapshot.freshness.expires_at, instance)}
</span>
</footer>
</section>
)
}
function PromptDrawer({ prompt, sourceLabel }: { prompt: string; sourceLabel: string }) {
const [copyState, setCopyState] = useState<"idle" | "copied" | "failed">("idle")
const copyPrompt = async () => {
try {
await Promise.race([
navigator.clipboard.writeText(prompt),
new Promise<never>((_, reject) => window.setTimeout(() => reject(new Error("Clipboard permission timed out.")), 600)),
])
setCopyState("copied")
} catch {
const field = document.createElement("textarea")
field.value = prompt
field.setAttribute("readonly", "")
field.style.position = "fixed"
field.style.opacity = "0"
document.body.append(field)
field.focus()
field.select()
const copied = document.execCommand("copy")
field.remove()
setCopyState(copied ? "copied" : "failed")
}
window.setTimeout(() => setCopyState("idle"), 2400)
}
return (
<Dialog>
<DialogTrigger asChild>
<Button size="sm" variant="outline">
<Braces className="size-3.5" />
Recreate this page
</Button>
</DialogTrigger>
<DialogContent side="right">
<div className="flex items-start justify-between gap-4 border-b border-border p-5 pr-14">
<div>
<DialogTitle className="text-base font-semibold">{sourceLabel} scheduled-task prompt</DialogTitle>
<DialogDescription className="mt-1 text-sm leading-6 text-muted-foreground">
One standalone Markdown prompt with the worker, source registration, permissions, and current schemas included. Replace the
three environment placeholders, review it, then paste the complete document into your LLM workflow.
</DialogDescription>
</div>
<Button aria-live="polite" onClick={() => void copyPrompt()} size="sm" variant="secondary">
{copyState === "copied" ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
{copyState === "copied" ? "Complete prompt copied" : copyState === "failed" ? "Select and copy below" : "Copy complete prompt"}
</Button>
</div>
<div
aria-label="Complete scheduled-task prompt"
className="min-h-0 flex-1 overflow-auto bg-muted/35 p-4 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring sm:p-5"
role="region"
tabIndex={0}
>
<pre className="whitespace-pre-wrap break-words rounded-lg border border-border bg-card p-4 font-mono text-xs leading-6 text-card-foreground">
{prompt}
</pre>
</div>
</DialogContent>
</Dialog>
)
}
function ComponentLab({ data }: { data: DashboardData }) {
const [copiedId, setCopiedId] = useState("")
const copyContract = async (id: string, value: string) => {
await navigator.clipboard.writeText(value)
setCopiedId(id)
window.setTimeout(() => setCopiedId(""), 1800)
}
return (
<section>
<div className="max-w-3xl border-b border-border pb-7">
<p className="text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground">Safe presentation contract / Synthetic</p>
<h1 className="mt-4 text-pretty text-3xl font-semibold tracking-[-0.035em] sm:text-4xl">
Build richer pages without shipping UI code
</h1>
<p className="mt-3 text-base leading-7 text-muted-foreground">
Your LLM chooses an audited block, a semantic page layout, and a span. Zaati OS owns rendering, responsive behavior, theme tokens,
focus handling, and accessibility.
</p>
</div>
<div className="mt-5 grid gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-3">
{[
["dashboard", "Three-column canvas", "Use one dominant two-column block with supporting evidence."],
["focus", "Focused decision", "The first block leads; supporting blocks stay quieter."],
["timeline", "Linear narrative", "Sequence and review pages remain deliberately narrow."],
].map(([name, label, description]) => (
<div className="bg-card p-4" key={name}>
<code className="text-xs font-semibold text-primary">{name}</code>
<p className="mt-2 text-sm font-medium">{label}</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">{description}</p>
</div>
))}
</div>
<div className="mt-10 space-y-10">
{data.componentExamples.map(({ sourceId, block }) => {
const contract = JSON.stringify(block, null, 2)
return (
<article className="border-t border-border pt-5" id={`component-${block.kind}`} key={block.kind}>
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
<div>
<p className="text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground">{sourceId}</p>
<h2 className="mt-1 text-xl font-semibold">{block.kind}</h2>
</div>
<Badge variant="outline">Audited JSON only</Badge>
</div>
<div className="grid overflow-hidden rounded-xl border border-border xl:grid-cols-2">
<div className="min-w-0 border-b border-border bg-muted/35 xl:border-b-0 xl:border-r">
<div className="flex min-h-11 items-center justify-between border-b border-border px-3">
<span className="text-xs font-medium text-foreground">JSON contract</span>
<Button aria-live="polite" onClick={() => void copyContract(block.id, contract)} size="sm" variant="ghost">
{copiedId === block.id ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
{copiedId === block.id ? "Copied" : "Copy"}
</Button>
</div>
<pre
aria-label={`${block.kind} JSON contract`}
className="max-h-[32rem] overflow-auto whitespace-pre-wrap break-words p-4 font-mono text-xs leading-6 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
tabIndex={0}
>
{contract}
</pre>
</div>
<div className="min-w-0 bg-background p-4 sm:p-5">
<p className="mb-3 text-xs font-medium text-muted-foreground">Rendered result</p>
<div className="grid grid-cols-1">
<BlockRenderer block={block} instance={data.instance} />
</div>
</div>
</div>
</article>
)
})}
</div>
</section>
)
}
function PageEyebrow({
definition,
instance,
snapshot,
}: {
definition: SourceDefinition
instance: InstanceConfig
snapshot: Snapshot | null
}) {
const date = snapshot
? new Intl.DateTimeFormat(instance.locale, { weekday: "long", month: "long", day: "numeric", timeZone: instance.timezone }).format(
new Date(snapshot.effective_period.start),
)
: "No snapshot yet"
return (
<div className="flex flex-wrap items-center gap-2 text-xs font-medium uppercase tracking-[0.14em] text-muted-foreground">
<span>{date}</span>
<span className="text-border">/</span>
<span>{definition.domain}</span>
{snapshot?.privacy.synthetic ? (
<>
<span className="text-border">/</span>
<span className="text-info-foreground">Synthetic</span>
</>
) : null}
</div>
)
}
function ThemeMenu({
density,
fontFamily,
hasCustomTheme,
headingStyle,
mode,
onDensity,
onFont,
onHeading,
onMode,
onPalette,
onRadius,
palette,
radius,
}: {
density: Density
fontFamily: FontFamily
hasCustomTheme: boolean
headingStyle: HeadingStyle
mode: ThemeMode
onDensity: (value: Density) => void
onFont: (value: FontFamily) => void
onHeading: (value: HeadingStyle) => void
onMode: (mode: ThemeMode) => void
onPalette: (palette: string) => void
onRadius: (radius: string) => void
palette: string
radius: string
}) {
return (
<DialogContent id="theme-studio">
<DialogTitle className="pr-10 text-sm font-semibold">Theme studio</DialogTitle>
<DialogDescription className="mt-1 text-xs leading-5 text-muted-foreground">
Preview freely. Deployment defaults live in your ignored instance configuration.
</DialogDescription>
<div className="mt-4 grid grid-cols-2 gap-2">
<Button
onClick={() => onMode("light")}
size="sm"
variant={mode === "light" ? "secondary" : "ghost"}
aria-pressed={mode === "light"}
>
<Sun className="size-3.5" />
Light
</Button>
<Button onClick={() => onMode("dark")} size="sm" variant={mode === "dark" ? "secondary" : "ghost"} aria-pressed={mode === "dark"}>
<Moon className="size-3.5" />
Dark
</Button>
</div>
<Separator className="my-4" />
<fieldset>
<legend className="text-xs font-semibold">Palette</legend>
<div className="mt-3 grid grid-cols-5 gap-2">
{["sage", "ocean", "plum", "sand", "custom"].map((item) => (
<button
aria-label={`${item} palette`}
aria-pressed={palette === item}
className={cn(
"grid min-h-14 place-items-center rounded-lg border p-2 capitalize",
palette === item ? "border-primary bg-accent" : "border-border",
)}
disabled={item === "custom" && !hasCustomTheme}
key={item}
onClick={() => onPalette(item)}
title={item === "custom" && !hasCustomTheme ? "Configure accessible light and dark tokens first" : undefined}
>
<span className={cn("palette-dot", `palette-${item}`)} />
<span className="mt-1 text-[10px]">{item}</span>
</button>
))}
</div>
</fieldset>
{!hasCustomTheme ? (
<p className="mt-2 text-xs leading-5 text-muted-foreground">
Custom palettes unlock after both validated light and dark token sets are configured.
</p>
) : null}
<div className="mt-4 grid grid-cols-2 gap-3">
<label className="text-xs font-semibold">
Font
<select
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-2 text-sm"
onChange={(event) => onFont(event.target.value as FontFamily)}
value={fontFamily}
>
{["system", "humanist", "editorial", "rounded", "mono"].map((item) => (
<option key={item}>{item}</option>
))}
</select>
</label>
<label className="text-xs font-semibold">
Headers
<select
className="mt-2 h-9 w-full rounded-md border border-input bg-background px-2 text-sm"
onChange={(event) => onHeading(event.target.value as HeadingStyle)}
value={headingStyle}
>
{["plain", "compact", "expressive"].map((item) => (
<option key={item}>{item}</option>
))}
</select>
</label>
</div>
<Separator className="my-4" />
<fieldset>
<legend className="text-xs font-semibold">Density</legend>
<div className="mt-2 grid grid-cols-2 gap-2">
{["comfortable", "compact"].map((item) => (
<Button
aria-pressed={density === item}
key={item}
onClick={() => onDensity(item as Density)}
size="sm"
variant={density === item ? "secondary" : "ghost"}
>
{item}
</Button>
))}
</div>
</fieldset>
<fieldset className="mt-4">
<legend className="text-xs font-semibold">Corner radius</legend>
<div className="mt-2 grid grid-cols-3 gap-2">
{[
["0.35rem", "Tight"],
["0.9rem", "Soft"],
["1.25rem", "Round"],
].map(([value, label]) => (
<Button
aria-pressed={radius === value}
key={value}
onClick={() => onRadius(value)}
size="sm"
variant={radius === value ? "secondary" : "ghost"}
>
{label}
</Button>
))}
</div>
</fieldset>
</DialogContent>
)
}
function AppLoading() {
return (
<div className="grid min-h-screen place-items-center bg-background text-foreground" role="status">
<div className="text-center">
<div className="mx-auto size-10 overflow-hidden rounded-xl border border-border bg-white shadow-sm">
<img alt="" aria-hidden="true" className="size-full object-cover" src={publicAsset("logo-mark.png")} />
</div>
<p className="mt-4 text-sm font-medium">Preparing your dashboard</p>
<p className="mt-1 text-xs text-muted-foreground">Loading the private data index</p>
</div>
</div>