@larakit/react 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/package.json +30 -4
  2. package/src/Cell.tsx +35 -0
  3. package/src/Dashboard.tsx +79 -0
  4. package/src/Field.tsx +132 -0
  5. package/src/FileInput.tsx +76 -0
  6. package/src/Form.tsx +116 -0
  7. package/src/Layout.tsx +250 -0
  8. package/src/PanelPages.tsx +115 -0
  9. package/src/Repeater.tsx +46 -0
  10. package/src/ResourceIndex.tsx +271 -0
  11. package/src/action-upload.test.tsx +44 -0
  12. package/src/blocks.tsx +26 -0
  13. package/src/button-part.test.tsx +42 -0
  14. package/src/components.test.ts +22 -0
  15. package/src/components.tsx +435 -0
  16. package/src/confirm.test.tsx +68 -0
  17. package/src/context.tsx +19 -0
  18. package/src/custom-pages.test.tsx +177 -0
  19. package/src/errors.test.tsx +95 -0
  20. package/src/fixtures.ts +20 -0
  21. package/src/index.ts +29 -0
  22. package/src/kit/api.ts +305 -0
  23. package/src/kit/auth.tsx +109 -0
  24. package/src/kit/bridge.tsx +142 -0
  25. package/src/kit/button.tsx +396 -0
  26. package/src/kit/cell.tsx +260 -0
  27. package/src/kit/charts.tsx +638 -0
  28. package/src/kit/create.tsx +166 -0
  29. package/src/kit/dashboard.tsx +335 -0
  30. package/src/kit/dates.tsx +62 -0
  31. package/src/kit/entry.tsx +87 -0
  32. package/src/kit/field.tsx +449 -0
  33. package/src/kit/fields/CodeEditor.tsx +157 -0
  34. package/src/kit/fields/KeyValue.tsx +215 -0
  35. package/src/kit/fields/MarkdownEditor.tsx +380 -0
  36. package/src/kit/fields/OneTimeCode.tsx +192 -0
  37. package/src/kit/fields/Repeater.tsx +350 -0
  38. package/src/kit/fields/Slider.tsx +185 -0
  39. package/src/kit/fields/TagsInput.tsx +219 -0
  40. package/src/kit/filters.tsx +214 -0
  41. package/src/kit/form-shared.tsx +62 -0
  42. package/src/kit/form.tsx +253 -0
  43. package/src/kit/hooks.ts +119 -0
  44. package/src/kit/i18n.tsx +67 -0
  45. package/src/kit/icons.tsx +190 -0
  46. package/src/kit/infolist.tsx +452 -0
  47. package/src/kit/kit.test.tsx +2200 -0
  48. package/src/kit/layout.tsx +236 -0
  49. package/src/kit/loading.tsx +120 -0
  50. package/src/kit/notice.tsx +72 -0
  51. package/src/kit/page.tsx +103 -0
  52. package/src/kit/pageform.tsx +75 -0
  53. package/src/kit/picker.tsx +110 -0
  54. package/src/kit/plugins.tsx +206 -0
  55. package/src/kit/profile.tsx +86 -0
  56. package/src/kit/relations.tsx +146 -0
  57. package/src/kit/rich.tsx +276 -0
  58. package/src/kit/search.tsx +92 -0
  59. package/src/kit/select.tsx +244 -0
  60. package/src/kit/shell.tsx +401 -0
  61. package/src/kit/table-extras.tsx +457 -0
  62. package/src/kit/table.tsx +734 -0
  63. package/src/kit/theme.ts +57 -0
  64. package/src/layout-parts.test.tsx +159 -0
  65. package/src/pages/index.ts +7 -0
  66. package/src/part.test.tsx +56 -0
  67. package/src/plugins.test.tsx +159 -0
  68. package/src/plugins.tsx +240 -0
  69. package/src/preview.test.tsx +81 -0
  70. package/src/rail.test.tsx +56 -0
  71. package/src/repeater.test.tsx +48 -0
  72. package/src/resource-pages.test.tsx +119 -0
  73. package/src/screens.test.tsx +121 -0
  74. package/src/ssr.test.tsx +86 -0
  75. package/src/tenant.test.tsx +94 -0
  76. package/src/ui.tsx +100 -0
  77. package/theme.css +467 -0
  78. package/README.md +0 -3
@@ -0,0 +1,236 @@
1
+ import { useEffect, useId, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
2
+ import type { Group, Place } from './api';
3
+ import { Badge } from './button';
4
+ import { useT } from './i18n';
5
+ import { Icon } from './icons';
6
+ import { Slot, type Parts } from './plugins';
7
+
8
+ type All = { columns: number; spans: Record<string, number>; wrong: string[]; Field: Parts['form']['Field'] };
9
+ const keys = (list: Place[]): string[] => list.flatMap((p) => ('field' in p ? [p.field] : keys(p.items)));
10
+ const cell = (span: number, columns: number): CSSProperties => ({ '--span': span === 1 ? 'auto' : span < 0 ? '1 / -1' : `span ${Math.min(span, columns)}` } as CSSProperties);
11
+
12
+ function Items({ items, columns, ...all }: All & { items: Place[] }) {
13
+ return <div className="form-grid" style={{ '--cols': columns } as CSSProperties}>
14
+ {items.map((p, i) => 'field' in p ? <div key={p.field} className="min-w-0" style={cell(all.spans[p.field] ?? 1, columns)}><all.Field name={p.field} /></div>
15
+ : <div key={(keys(p.items)[0] ?? p.type) + '-' + i} className="min-w-0" style={cell(p.span ?? -1, columns)}><Box {...all} columns={columns} group={p} /></div>)}
16
+ </div>;
17
+ }
18
+
19
+ function DefaultTabs({ tabs, active, onSelect }: Parts['tabs']) {
20
+ const tr = useT();
21
+ const id = useId();
22
+ const now = Math.min(active, Math.max(0, tabs.length - 1));
23
+ const move = (e: KeyboardEvent, i: number) => {
24
+ const to = e.key === 'ArrowRight' ? (i + 1) % tabs.length : e.key === 'ArrowLeft' ? (i - 1 + tabs.length) % tabs.length : e.key === 'Home' ? 0 : e.key === 'End' ? tabs.length - 1 : -1;
25
+ if (to < 0) return;
26
+ e.preventDefault(); onSelect(to);
27
+ document.getElementById(id + 't' + to)?.focus();
28
+ };
29
+ return <div data-lk="tabs">
30
+ <div role="tablist" className="tabs mb-4 flex gap-1 overflow-x-auto border-b">
31
+ {tabs.map((t, i) => <button key={i} type="button" role="tab" id={id + 't' + i} data-lk="tab" aria-selected={i === now} aria-controls={id + 'p' + i} tabIndex={i === now ? 0 : -1}
32
+ className="tab -mb-px inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm font-medium whitespace-nowrap" onClick={() => onSelect(i)} onKeyDown={(e) => move(e, i)}>
33
+ {t.icon && <Icon name={t.icon} className="size-4 shrink-0" />}
34
+ <span>{t.heading}</span>
35
+ {t.badge && <Badge label={t.badge} color={t.badgeColor} />}
36
+ {t.wrong && <><span className="sr-only">{tr('form.hasErrors')}</span><span aria-hidden="true" className="danger ml-1">●</span></>}</button>)}
37
+ </div>
38
+ {tabs.map((t, i) => <div key={i} role="tabpanel" id={id + 'p' + i} aria-labelledby={id + 't' + i} hidden={i !== now}>{t.content}</div>)}
39
+ </div>;
40
+ }
41
+
42
+ /** One tab at a time. A tab with an error opens, so the error is seen. */
43
+ function Tabs({ group: g, ...all }: All & { group: Group }) {
44
+ const rawTabs = g.items.filter((p): p is Group => 'items' in p);
45
+ const [open, setOpen] = useState(0);
46
+ const wrong = rawTabs.findIndex((t) => keys(t.items).some((k) => all.wrong.includes(k)));
47
+ useEffect(() => { if (wrong >= 0 && !keys(rawTabs[open]?.items ?? []).some((k) => all.wrong.includes(k))) setOpen(wrong); }, [all.wrong.join()]);
48
+ const rendered = rawTabs.map((t) => ({
49
+ heading: t.heading,
50
+ icon: t.icon,
51
+ badge: t.badge,
52
+ badgeColor: t.badgeColor,
53
+ wrong: keys(t.items).some((k) => all.wrong.includes(k)),
54
+ content: <Items {...all} columns={t.columns ?? 1} items={t.items} />,
55
+ }));
56
+ return <Slot part="tabs" own={DefaultTabs} props={{ tabs: rendered, active: open, onSelect: setOpen, group: g }} />;
57
+ }
58
+
59
+ function Callout({ group: g, ...all }: All & { group: Group }) {
60
+ const tone = g.color ?? 'info';
61
+ const pad = g.compact ? 'p-3' : 'p-4';
62
+ return (
63
+ <div data-lk="callout" data-color={tone} className={`callout tone-${tone} border ${pad}`}>
64
+ <div className="flex items-start gap-3">
65
+ {g.icon && <Icon name={g.icon} className="callout-icon mt-0.5 size-5 shrink-0" />}
66
+ <div className="min-w-0 flex-1">
67
+ {(g.heading || g.badge) && (
68
+ <div className="flex flex-wrap items-center gap-2">
69
+ {g.heading && <h3 data-lk="heading" className="text-sm font-semibold">{g.heading}</h3>}
70
+ {g.badge && <Badge label={g.badge} color={g.badgeColor ?? tone} />}
71
+ </div>
72
+ )}
73
+ {g.description && <p className={'callout-desc text-sm ' + (g.heading ? 'mt-1' : '')}>{g.description}</p>}
74
+ {g.items.length > 0 && (
75
+ <div className="mt-3">
76
+ <Items {...all} columns={g.columns ?? 1} items={g.items} />
77
+ </div>
78
+ )}
79
+ </div>
80
+ </div>
81
+ </div>
82
+ );
83
+ }
84
+
85
+ /** Multi-step wizard stepper with error auto-jump and optional skippable navigation. */
86
+ function Wizard({ group: g, ...all }: All & { group: Group }) {
87
+ const tr = useT();
88
+ const steps = g.items.filter((p): p is Group => 'items' in p);
89
+ const [active, setActive] = useState(0);
90
+ const now = Math.min(active, Math.max(0, steps.length - 1));
91
+ const stepHasError = (s?: Group) => (s ? keys(s.items).some((k) => all.wrong.includes(k)) : false);
92
+ const firstWrong = steps.findIndex((s) => stepHasError(s));
93
+
94
+ useEffect(() => {
95
+ if (firstWrong >= 0 && !stepHasError(steps[now])) setActive(firstWrong);
96
+ }, [all.wrong.join()]);
97
+
98
+ if (!steps.length) return null;
99
+
100
+ return (
101
+ <div data-lk="wizard" className="wizard surface space-y-4 border p-4">
102
+ {(g.heading || g.description) && (
103
+ <div>
104
+ {g.heading && <h3 data-lk="heading" className="font-semibold">{g.heading}</h3>}
105
+ {g.description && <p className="muted text-sm">{g.description}</p>}
106
+ </div>
107
+ )}
108
+ <nav aria-label={g.heading || tr('form.wizardSteps')}>
109
+ <ol className="wizard-steps flex flex-wrap gap-2 border-b pb-3">
110
+ {steps.map((s, i) => {
111
+ const hasError = stepHasError(s);
112
+ const isCurrent = i === now;
113
+ const isDone = i < now && !hasError;
114
+ const canClick = !!g.skippable || i <= now || hasError;
115
+ return (
116
+ <li key={i} className="min-w-0">
117
+ <button
118
+ type="button"
119
+ data-lk="wizard-step"
120
+ data-state={hasError ? 'error' : isCurrent ? 'current' : isDone ? 'done' : 'upcoming'}
121
+ aria-current={isCurrent ? 'step' : undefined}
122
+ disabled={!canClick}
123
+ className="wizard-step btn inline-flex items-center gap-2 text-sm"
124
+ data-size="sm"
125
+ data-variant={isCurrent ? 'soft' : 'ghost'}
126
+ data-color={hasError ? 'danger' : isCurrent ? 'primary' : undefined}
127
+ onClick={() => setActive(i)}
128
+ >
129
+ <span className="wizard-num grid size-5 shrink-0 place-items-center rounded-full text-xs font-semibold">
130
+ {hasError ? '!' : isDone ? <Icon name="check" className="size-3.5" strokeWidth={2.5} /> : s.icon ? <Icon name={s.icon} className="size-3.5" /> : i + 1}
131
+ </span>
132
+ <span className="truncate">{s.heading || String(i + 1)}</span>
133
+ {s.badge && <Badge label={s.badge} color={s.badgeColor} />}
134
+ {hasError && (
135
+ <>
136
+ <span className="sr-only">{tr('form.hasErrors')}</span>
137
+ <span aria-hidden="true" className="danger">●</span>
138
+ </>
139
+ )}
140
+ </button>
141
+ </li>
142
+ );
143
+ })}
144
+ </ol>
145
+ </nav>
146
+ {steps.map((s, i) => (
147
+ <div key={i} data-lk="step" hidden={i !== now}>
148
+ {s.description && <p className="muted mb-3 text-sm">{s.description}</p>}
149
+ <Items {...all} columns={s.columns ?? 1} items={s.items} />
150
+ </div>
151
+ ))}
152
+ <div data-lk="wizard-nav" className="flex items-center justify-between gap-2 border-t pt-3">
153
+ <button
154
+ type="button"
155
+ data-lk="wizard-prev"
156
+ disabled={now === 0}
157
+ className="btn inline-flex items-center gap-1.5"
158
+ data-size="sm"
159
+ onClick={() => setActive((x) => Math.max(0, x - 1))}
160
+ >
161
+ <Icon name="left" className="size-4 rtl:rotate-180" />
162
+ <span>{tr('form.previous')}</span>
163
+ </button>
164
+ {now < steps.length - 1 && (
165
+ <button
166
+ type="button"
167
+ data-lk="wizard-next"
168
+ className="btn inline-flex items-center gap-1.5"
169
+ data-size="sm"
170
+ data-variant="soft"
171
+ data-color="primary"
172
+ onClick={() => setActive((x) => Math.min(steps.length - 1, x + 1))}
173
+ >
174
+ <span>{tr('form.next')}</span>
175
+ <Icon name="right" className="size-4 rtl:rotate-180" />
176
+ </button>
177
+ )}
178
+ </div>
179
+ </div>
180
+ );
181
+ }
182
+
183
+ function Box({ group: g, ...all }: All & { group: Group }) {
184
+ if (g.type === 'tabs') return <Tabs group={g} {...all} />;
185
+ if (g.type === 'callout') return <Callout group={g} {...all} />;
186
+ if (g.type === 'wizard') return <Wizard group={g} {...all} />;
187
+ return <Card group={g} {...all} />;
188
+ }
189
+
190
+ function DefaultSection({ group: g, open, onToggle, children }: Parts['section']) {
191
+ const id = useId();
192
+ if (g.type === 'fieldset') {
193
+ return (
194
+ <fieldset data-lk="fieldset" className="surface min-w-0 border p-4">
195
+ <legend className="inline-flex items-center gap-1.5 px-1 text-sm font-medium">
196
+ {g.icon && <Icon name={g.icon} className="muted size-4 shrink-0" />}
197
+ <span>{g.heading}</span>
198
+ {g.badge && <Badge label={g.badge} color={g.badgeColor} />}
199
+ </legend>
200
+ {children}
201
+ </fieldset>
202
+ );
203
+ }
204
+ const head: ReactNode = (
205
+ <>
206
+ <div className="flex flex-wrap items-center gap-2">
207
+ {g.icon && <Icon name={g.icon} className="muted size-5 shrink-0" />}
208
+ <h3 id={id} data-lk="heading" className="font-semibold">{g.heading}</h3>
209
+ {g.badge && <Badge label={g.badge} color={g.badgeColor} />}
210
+ </div>
211
+ {g.description && <p className="muted text-sm">{g.description}</p>}
212
+ </>
213
+ );
214
+ const pad = g.compact ? 'p-3' : 'p-4';
215
+ if (g.collapsible) return <details data-lk="section" className={'section surface border ' + pad} open={open} onToggle={(e) => { if (e.target === e.currentTarget) onToggle?.(e.currentTarget.open); }}>
216
+ <summary className="flex items-center gap-3"><span className="min-w-0 flex-1">{head}</span><Icon name="down" className="arrow muted size-4 transition-[rotate] motion-reduce:transition-none" /></summary>
217
+ <div className={g.compact ? 'mt-3' : 'mt-4'}>{children}</div>
218
+ </details>;
219
+ return <section data-lk="section" aria-labelledby={id} className={(g.aside ? 'aside ' : 'surface border ' + pad)}>
220
+ <div className={g.aside ? '' : g.compact ? 'mb-3' : 'mb-4'}>{head}</div>
221
+ {g.aside ? <div className={'surface min-w-0 border ' + pad}>{children}</div> : children}
222
+ </section>;
223
+ }
224
+
225
+ function Card({ group: g, ...all }: All & { group: Group }) {
226
+ const [open, setOpen] = useState(!g.collapsed);
227
+ const own = keys(g.items), wrong = own.some((k) => all.wrong.includes(k));
228
+ // An error in a closed section would not be seen.
229
+ useEffect(() => { if (wrong) setOpen(true); }, [wrong, all.wrong.join()]);
230
+ const inner = <Items {...all} columns={g.columns ?? 1} items={g.items} />;
231
+ if (g.type === 'grid' || g.type === 'step') return inner;
232
+ return <Slot part="section" own={DefaultSection} props={{ group: g, heading: g.heading, description: g.description, collapsible: g.collapsible, open, aside: g.aside, compact: g.compact, wrong, onToggle: setOpen, children: inner }} />;
233
+ }
234
+
235
+ /** The fields of a form where the server puts them. */
236
+ export const Fields = ({ layout, Field }: Parts['form']) => <Items columns={layout.columns} spans={layout.spans} wrong={layout.wrong} items={layout.items} Field={Field} />;
@@ -0,0 +1,120 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { loadingDelay } from './api';
3
+ import { useT } from './i18n';
4
+ import { Slot, type Parts } from './plugins';
5
+
6
+ /**
7
+ * Delays showing a loading placeholder until `delay` ms have elapsed, so fast
8
+ * navigation or responses never flash skeletons.
9
+ */
10
+ export function useDelayed(active: boolean, delay = loadingDelay()): boolean {
11
+ const immediate = delay <= 0;
12
+ const [shown, setShown] = useState(active && immediate);
13
+ useEffect(() => {
14
+ if (!active) { setShown(false); return; }
15
+ if (immediate) { setShown(true); return; }
16
+ setShown(false);
17
+ const id = setTimeout(() => setShown(true), delay);
18
+ return () => clearTimeout(id);
19
+ }, [active, delay, immediate]);
20
+ return active && shown;
21
+ }
22
+
23
+ /** Full app-shell skeleton displayed only if initial /api/panel takes longer than loadingDelay. */
24
+ export function PanelSkeleton() {
25
+ const t = useT();
26
+ return (
27
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="min-h-screen md:flex">
28
+ <aside aria-hidden="true" className="surface-fill hidden w-64 shrink-0 flex-col gap-3 border-e p-4 md:flex">
29
+ <span className="bone mb-4 block h-8 w-32 rounded" />
30
+ {[72, 58, 66, 52, 68, 60].map((w, i) => <span key={i} className="bone block h-8 rounded-md" style={{ width: w + '%' }} />)}
31
+ </aside>
32
+ <div aria-hidden="true" className="min-w-0 flex-1">
33
+ <div className="surface-fill flex h-14 items-center justify-end gap-3 border-b px-6">
34
+ <span className="bone h-8 w-44 rounded-md" />
35
+ <span className="bone size-8 rounded-full" />
36
+ </div>
37
+ <div className="space-y-6 p-6 sm:p-8">
38
+ <span className="bone block h-7 w-48 rounded" />
39
+ <div className="grid gap-4 sm:grid-cols-3">
40
+ {[0, 1, 2].map((i) => <div key={i} className="surface space-y-3 border p-5"><span className="bone block h-3.5 w-24 rounded" /><span className="bone block h-7 w-20 rounded" /></div>)}
41
+ </div>
42
+ <div className="surface space-y-4 border p-6">
43
+ {[80, 92, 68, 86, 74].map((w, i) => <span key={i} className="bone block h-4 rounded" style={{ width: w + '%' }} />)}
44
+ </div>
45
+ </div>
46
+ </div>
47
+ </div>
48
+ );
49
+ }
50
+
51
+ export function FormSkeleton() {
52
+ const t = useT();
53
+ return (
54
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="surface space-y-5 border p-6">
55
+ {[55, 78, 42, 65].map((w, i) => (
56
+ <div key={i} aria-hidden="true" className="space-y-2">
57
+ <span className="bone block h-3.5 w-28 rounded" />
58
+ <span className="bone block h-9 rounded" style={{ width: w + '%' }} />
59
+ </div>
60
+ ))}
61
+ </div>
62
+ );
63
+ }
64
+
65
+ export function WidgetSkeleton({ widgetType }: { widgetType?: string }) {
66
+ const t = useT();
67
+ if (widgetType === 'stats') {
68
+ return (
69
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="grid gap-4 sm:grid-cols-3">
70
+ {[0, 1, 2].map((i) => <div key={i} aria-hidden="true" className="space-y-2.5"><span className="bone block h-3 w-20 rounded" /><span className="bone block h-7 w-16 rounded" /></div>)}
71
+ </div>
72
+ );
73
+ }
74
+ if (widgetType === 'list') {
75
+ return (
76
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="space-y-3">
77
+ {[82, 68, 90, 74].map((w, i) => <span key={i} aria-hidden="true" className="bone block h-4 rounded" style={{ width: w + '%' }} />)}
78
+ </div>
79
+ );
80
+ }
81
+ return (
82
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="space-y-3">
83
+ <span aria-hidden="true" className="bone block h-40 w-full rounded" />
84
+ <span aria-hidden="true" className="bone block h-3.5 w-36 rounded" />
85
+ </div>
86
+ );
87
+ }
88
+
89
+ export function PageSkeleton() {
90
+ const t = useT();
91
+ return (
92
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="surface space-y-4 border p-6">
93
+ {[65, 85, 50].map((w, i) => <span key={i} aria-hidden="true" className="bone block h-4 rounded" style={{ width: w + '%' }} />)}
94
+ </div>
95
+ );
96
+ }
97
+
98
+ export function InlineSkeleton() {
99
+ const t = useT();
100
+ return (
101
+ <div data-lk="skeleton" role="status" aria-busy="true" aria-label={t('page.loading')} className="space-y-2 px-3 py-2">
102
+ <span aria-hidden="true" className="bone block h-3.5 w-3/4 rounded" />
103
+ <span aria-hidden="true" className="bone block h-3.5 w-1/2 rounded" />
104
+ </div>
105
+ );
106
+ }
107
+
108
+ function BuiltInLoading({ kind, widgetType }: Parts['loading']) {
109
+ if (kind === 'panel') return <PanelSkeleton />;
110
+ if (kind === 'form') return <FormSkeleton />;
111
+ if (kind === 'widget') return <WidgetSkeleton widgetType={widgetType} />;
112
+ if (kind === 'page') return <PageSkeleton />;
113
+ if (kind === 'inline') return <InlineSkeleton />;
114
+ return <PageSkeleton />;
115
+ }
116
+
117
+ /** Renders the panel's loading skeleton or a plugin's custom `loading` replacement. */
118
+ export function Loading(props: Parts['loading']) {
119
+ return <Slot part="loading" own={BuiltInLoading} props={props} />;
120
+ }
@@ -0,0 +1,72 @@
1
+ import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
2
+ import { Btn, Modal } from './button';
3
+ import { useT } from './i18n';
4
+ import { Icon } from './icons';
5
+ import { Slot, type Parts } from './plugins';
6
+
7
+ type Toast = { id: number; text: string; bad: boolean };
8
+ type Question = { id: number; text: string; button: string; danger: boolean; detail?: ReactNode; answer: (yes: boolean) => void };
9
+ let next = 1, show: (t: Toast) => void = () => {}, put: (q: Question) => void = () => {};
10
+
11
+ /** Tells the visitor something for a few seconds. */
12
+ export const say = (text: string) => { if (text) show({ id: next++, text, bad: false }); };
13
+ export const complain = (text: string) => show({ id: next++, text, bad: true });
14
+ /** Asks before something happens. The detail, if any, says more under the question. */
15
+ export const sure = (text: string, button: string, danger: boolean, detail?: ReactNode) => new Promise<boolean>((answer) => put({ id: next++, text, button, danger, detail, answer }));
16
+
17
+ function DefaultToast({ text, bad, onClose }: Parts['toast']) {
18
+ const t = useT();
19
+ const [held, hold] = useState(false);
20
+ useEffect(() => {
21
+ if (held) return;
22
+ const timer = setTimeout(onClose, bad ? 10000 : 5000);
23
+ return () => clearTimeout(timer);
24
+ }, [held]);
25
+ return <div data-lk="notice" data-bad={bad || undefined} className="surface toast flex items-start gap-3 border p-4 text-sm shadow-lg" onMouseEnter={() => hold(true)} onMouseLeave={() => hold(false)} onFocus={() => hold(true)} onBlur={() => hold(false)}>
26
+ <Icon name={bad ? 'warning' : 'check'} className={'size-5 ' + (bad ? 'tone-text-danger' : 'tone-text-success')} />
27
+ <p className="min-w-0 flex-1 font-medium break-words">{text}</p>
28
+ <button type="button" className="icon-btn -m-1" aria-label={t('form.closeMessage')} onClick={onClose}><Icon name="x" className="size-4" /></button>
29
+ </div>;
30
+ }
31
+
32
+ function Line({ toast, close }: { toast: Toast; close: () => void }) {
33
+ return <Slot part="toast" own={DefaultToast} props={{ id: toast.id, text: toast.text, bad: toast.bad, onClose: close }} />;
34
+ }
35
+
36
+ function Ask({ q, done }: { q: Question; done: () => void }) {
37
+ const t = useT();
38
+ const titleId = useId();
39
+ const dialog = useRef<HTMLDialogElement>(null), yes = useRef(false), answered = useRef(false);
40
+ const answer = () => { if (answered.current) return; answered.current = true; q.answer(yes.current); done(); };
41
+ // An app's own `modal` part may draw no <dialog>, so the ref can be empty: then answer at once.
42
+ const finish = (ok: boolean) => {
43
+ yes.current = ok;
44
+ const d = dialog.current;
45
+ if (d && typeof d.close === 'function' && d.open) d.close(); else answer();
46
+ };
47
+ return <Modal kind="confirm" dataLk="confirm" titleId={titleId} dialogRef={dialog} portal
48
+ className="surface m-auto w-full max-w-md border p-6 text-center shadow-lg backdrop:bg-black/50"
49
+ onClose={answer}>
50
+ <span className={'mx-auto mb-4 grid size-12 place-items-center rounded-full ' + (q.danger ? 'tone-danger' : 'tone-info')}><Icon name={q.danger ? 'warning' : 'help'} className="size-6" /></span>
51
+ <p id={titleId} className="mb-6 text-lg font-semibold break-words">{q.text}</p>
52
+ {q.detail && <div data-lk="confirm-detail" className="-mt-2 mb-6 max-h-72 overflow-y-auto text-start text-sm">{q.detail}</div>}
53
+ <div className="grid grid-cols-2 gap-3">
54
+ <Btn dataLk="confirm-no" label={t('form.cancel')} onClick={() => finish(false)} />
55
+ <Btn dataLk="confirm-yes" variant="solid" color={q.danger ? 'danger' : 'primary'} label={q.button} onClick={() => finish(true)} />
56
+ </div>
57
+ </Modal>;
58
+ }
59
+
60
+ /** Where messages and questions appear. */
61
+ export function Notices() {
62
+ const [toasts, set] = useState<Toast[]>([]), [asked, setAsked] = useState<Question[]>([]);
63
+ useEffect(() => {
64
+ show = (t) => set((all) => [...all, t].slice(-4));
65
+ put = (q) => setAsked((all) => [...all, q]);
66
+ }, []);
67
+ const draw = (bad: boolean) => toasts.filter((t) => t.bad === bad).map((t) => <Line key={t.id} toast={t} close={() => set((all) => all.filter((x) => x.id !== t.id))} />);
68
+ return <>
69
+ <div className="pointer-events-none fixed inset-x-4 top-20 z-50 flex flex-col gap-3 *:space-y-3 sm:left-auto sm:w-96 *:pointer-events-auto"><div role="alert">{draw(true)}</div><div role="status">{draw(false)}</div></div>
70
+ {asked[0] && <Ask key={asked[0].id} q={asked[0]} done={() => setAsked((all) => all.slice(1))} />}
71
+ </>;
72
+ }
@@ -0,0 +1,103 @@
1
+ import { Suspense, useCallback, type ComponentType, type ReactNode } from 'react';
2
+ import { router } from '@inertiajs/react';
3
+ import type { PanelPlugin } from '@larakit/core';
4
+ import { ApiError, api, fail, type MenuPage } from './api';
5
+ import { Btn, PageHeader } from './button';
6
+ import { useT } from './i18n';
7
+ import { complain, say } from './notice';
8
+ import { useActions } from './table';
9
+ import { component as appComponent, Missing } from '../components';
10
+ import { Guard, missingPlugins, registered, type PageProps, type RunResult } from '../plugins';
11
+ import { page as pluginComponent } from './plugins';
12
+
13
+ /** Runs a page's action or call at `{p}/api/{at}/actions/{name}`, says how it went, and loads the page's data again. */
14
+ export function useRun(at: string): PageProps['run'] {
15
+ return useCallback(async (name: string, payload?: Record<string, unknown>): Promise<RunResult> => {
16
+ try {
17
+ const answer = await api<{ message?: string }>(`/${at}/actions/${encodeURIComponent(name)}`, 'POST', payload ?? {});
18
+ const message = typeof answer?.message === 'string' ? answer.message : '';
19
+ say(message);
20
+ router.reload({ only: ['data'] });
21
+ return { ok: true, message };
22
+ } catch (e) {
23
+ const message = fail(e);
24
+ complain(message);
25
+ return { ok: false, status: e instanceof ApiError ? e.status : 0, message, errors: e instanceof ApiError ? e.errors : {} };
26
+ }
27
+ }, [at]);
28
+ }
29
+
30
+ /**
31
+ * A page whose body a component draws: the application's, that the server's `.component(...)` names, or a plugin's.
32
+ * Larakit draws the heading, the description and the page's buttons; the component gets the page's data, which comes
33
+ * with the page (so the server draws it too), `run` and `reload`.
34
+ */
35
+ function DrawnPage({ page, at, data, path, href, Drawn, problem }: {
36
+ page: MenuPage;
37
+ /** Where the page's actions run, below the panel's API. */
38
+ at: string;
39
+ data: Record<string, unknown> | undefined;
40
+ path: string;
41
+ href: (p?: string) => string;
42
+ Drawn: ComponentType<PageProps> | null;
43
+ problem: ReactNode;
44
+ }) {
45
+ const run = useRun(at);
46
+ const reload = useCallback(() => router.reload({ only: ['data'] }), []);
47
+ // A button of the heading runs as on any page, and the data shows what it changed.
48
+ const [press, asked] = useActions({ name: at, headerActions: page.actions }, reload);
49
+ const buttons = page.actions?.length
50
+ ? <>{page.actions.map((a) => <Btn key={a.name} dataLk={'header-' + a.name} label={a.label} icon={a.icon} color={a.color} variant={a.variant} size={a.size} danger={a.danger} iconOnly={a.iconOnly} onClick={() => press(null, a.name)} />)}</>
51
+ : undefined;
52
+ return (
53
+ <div data-lk="drawn-page">
54
+ <PageHeader title={page.label} description={page.description} actions={buttons} />
55
+ {!Drawn ? problem : (
56
+ <Guard key={path} fallback={problem}>
57
+ <Suspense fallback={null}>
58
+ <Drawn data={data ?? {}} path={path} href={href} reload={reload} run={run} />
59
+ </Suspense>
60
+ </Guard>
61
+ )}
62
+ {asked}
63
+ </div>
64
+ );
65
+ }
66
+
67
+ /** A page of the panel that the application's own component draws: `GET {p}/{page}`. */
68
+ export function AppPage({ page, data, base }: { page: MenuPage & { component: string }; data: Record<string, unknown> | undefined; base: string }) {
69
+ const t = useT();
70
+ const Drawn = appComponent(page.component) as ComponentType<PageProps> | null;
71
+ const name = page.name ?? '';
72
+ const problem = Drawn ? <p role="alert" className="danger">{t('page.wentWrong')}</p> : <Missing name={page.component} />;
73
+ return <DrawnPage page={page} at={name} data={data} path="" href={() => base + '/' + name} Drawn={Drawn} problem={problem} />;
74
+ }
75
+
76
+ /**
77
+ * A page that a plugin brings, drawn by the plugin's ui. Its data comes with the page (`data`), so the
78
+ * server draws it too; `reload` asks for `data` again, and `run` runs its buttons and calls.
79
+ */
80
+ export function PluginPage({ page, data, path, base, plugins }: {
81
+ page: MenuPage & { type: string };
82
+ data: Record<string, unknown> | undefined;
83
+ /** What follows the page in the address. */
84
+ path: string;
85
+ /** Where the panel lives. */
86
+ base: string;
87
+ plugins: PanelPlugin[] | undefined;
88
+ }) {
89
+ const t = useT();
90
+ const { type } = page;
91
+ const id = type.split('/')[0];
92
+ const Drawn = pluginComponent(type) ?? null;
93
+ const listed = plugins?.find((p) => p.id === id);
94
+ const missing = !registered(id) && listed && missingPlugins(plugins).includes(listed);
95
+ const problem = missing
96
+ ? <p role="alert" data-lk="missing-plugin" className="danger text-sm">
97
+ Larakit: the plugin {listed.name} draws this page with its ui, which larakit(&#123; plugins &#125;) in app.tsx
98
+ doesn't have. Copy it to resources/js/larakit/plugins/{listed.id}, pass it there and run larakit:doctor.
99
+ </p>
100
+ : <p className="danger">{t('page.pluginError')}</p>;
101
+ const href = (p?: string) => base + '/' + type + (p ? '/' + p : '');
102
+ return <DrawnPage page={page} at={type} data={data} path={path} href={href} Drawn={Drawn as ComponentType<PageProps> | null} problem={problem} />;
103
+ }
@@ -0,0 +1,75 @@
1
+ import { createContext, useContext, useEffect, useId, useState, type FormEvent, type ReactNode } from 'react';
2
+ import { api, ApiError, fail, loginOf, type Field, type Place } from './api';
3
+ import { Btn } from './button';
4
+ import { FieldView, FormErrors, holds, toForm, toSend, type Vals } from './field';
5
+ import { filterVisiblePlaces, FormAlerts } from './form-shared';
6
+ import { useT } from './i18n';
7
+ import { Fields } from './layout';
8
+ import { Loading, useDelayed } from './loading';
9
+ import { say } from './notice';
10
+ import { RenderHook } from './plugins';
11
+
12
+ const PageFieldContext = createContext<(name: string) => ReactNode>(() => null);
13
+ const PageField = ({ name }: { name: string }) => useContext(PageFieldContext)(name);
14
+
15
+ /** The form of a page of the panel, such as its settings, with a Save button. */
16
+ export function PageForm({ page, fields, items, columns = 1, canSave }: { page: string; fields: Field[]; items?: Place[]; columns?: number; canSave: boolean }) {
17
+ const t = useT();
18
+ const own = useId(), url = `/${page}/form`;
19
+ const [values, setValues] = useState<Vals>();
20
+ const [errors, setErrors] = useState<Record<string, string[]>>({});
21
+ const [problem, setProblem] = useState('');
22
+ const [login, setLogin] = useState('');
23
+ const [busy, setBusy] = useState(false);
24
+ const showSkeleton = useDelayed(!values && !problem);
25
+ const read = () => api<{ values: Record<string, unknown> }>(url)
26
+ .then((d) => setValues(Object.fromEntries(fields.map((f) => [f.key, toForm(f, d.values?.[f.key] ?? f.default, () => {})]))))
27
+ .catch((e) => { setProblem(fail(e)); setLogin(loginOf(e)); });
28
+ useEffect(() => { read(); }, [url]);
29
+ if (!values) return problem ? <p role="alert" data-lk="error" className="danger">{problem}</p> : showSkeleton ? <Loading kind="form" /> : null;
30
+ const shown = fields.filter((f) => f.type !== 'hidden' && !f.hiddenOn?.includes('edit') && holds(f.visibleWhen, values));
31
+ const tree = items?.length ? filterVisiblePlaces(items, shown.map((f) => f.key), values) : undefined;
32
+ const hasGroups = !!tree?.some((p) => 'items' in p);
33
+ const containerClass = hasGroups || columns > 1 ? 'max-w-5xl' : 'max-w-2xl';
34
+ const submit = async (e: FormEvent) => {
35
+ e.preventDefault();
36
+ if (busy || !canSave) return;
37
+ setBusy(true); setErrors({}); setProblem(''); setLogin('');
38
+ try {
39
+ const done = await api<{ message?: string }>(url, 'POST', Object.fromEntries(fields.map((f) => [f.key, toSend(f, values[f.key])])));
40
+ say(done.message ?? t('form.saved'));
41
+ await read();
42
+ } catch (err) {
43
+ if (err instanceof ApiError && err.status === 422) setErrors(err.errors); else { setProblem(fail(err)); setLogin(loginOf(err)); }
44
+ }
45
+ setBusy(false);
46
+ };
47
+ // An error of a field that is not shown must still be seen.
48
+ // A field inside a list shows its error on its row.
49
+ const rest = Object.keys(errors).filter((k) => !shown.some((f) => f.key === k || f.type === 'repeater' && k.startsWith(f.key + '.')));
50
+ const drawField = (name: string) => {
51
+ const f = shown.find((x) => x.key === name);
52
+ if (!f) return null;
53
+ return <FieldView id={own + f.key} errorId={own + f.key + 'e'} url="" field={f} value={values[f.key]} values={values} errors={errors[f.key]} disabled={!canSave || !!f.disabledOn?.includes('edit')} onKnown={() => {}} set={(v) => setValues((old) => ({ ...old, [f.key]: v }))} />;
54
+ };
55
+ const alerts = <FormAlerts problem={problem} login={login} errors={errors} hiddenErrorKeys={rest} />;
56
+ if (hasGroups && tree) {
57
+ const loose = tree.some((p) => 'field' in p);
58
+ const body = <PageFieldContext value={drawField}><Fields resource={page} id={null} fields={shown.map(({ key, label, type }) => ({ key, label, type }))} Field={PageField}
59
+ layout={{ columns, items: tree, spans: Object.fromEntries(shown.map((f) => [f.key, f.look?.span ?? 1])), wrong: Object.keys(errors) }} /></PageFieldContext>;
60
+ return <FormErrors value={errors}><form data-lk="page-form" onSubmit={submit} noValidate className={containerClass + ' space-y-6'}>
61
+ {alerts}
62
+ <RenderHook name="form.before" className="flex flex-col gap-3" />
63
+ {loose ? <div className="surface border p-6">{body}</div> : body}
64
+ <RenderHook name="form.after" className="flex flex-col gap-3" />
65
+ {canSave && <div className="flex justify-end"><Btn type="submit" dataLk="save" variant="solid" color="primary" label={t('form.save')} disabled={busy} /></div>}
66
+ </form></FormErrors>;
67
+ }
68
+ return <FormErrors value={errors}><form data-lk="page-form" onSubmit={submit} noValidate className={'card ' + containerClass + ' space-y-4 p-6'}>
69
+ {alerts}
70
+ <RenderHook name="form.before" className="flex flex-col gap-3" />
71
+ {shown.map((f) => <FieldView key={f.key} id={own + f.key} errorId={own + f.key + 'e'} url="" field={f} value={values[f.key]} values={values} errors={errors[f.key]} disabled={!canSave || !!f.disabledOn?.includes('edit')} onKnown={() => {}} set={(v) => setValues((old) => ({ ...old, [f.key]: v }))} />)}
72
+ <RenderHook name="form.after" className="flex flex-col gap-3" />
73
+ {canSave && <div className="flex justify-end"><Btn type="submit" dataLk="save" variant="solid" color="primary" label={t('form.save')} disabled={busy} /></div>}
74
+ </form></FormErrors>;
75
+ }