@larakit/react 0.0.0-stage → 0.5.1

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 +398 -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 +2210 -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,110 @@
1
+ import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react';
2
+ import { usePopoverPosition } from './hooks';
3
+ import { intlLocale, useT } from './i18n';
4
+ import { Icon } from './icons';
5
+
6
+ const two = (n: number) => String(n).padStart(2, '0');
7
+ const ymd = (d: Date) => `${String(d.getFullYear()).padStart(4, '0')}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;
8
+ const dayOf = (s: string) => { const [y, m, d] = s.split('-').map(Number); return new Date(y, m - 1, d); };
9
+ const good = (s: string) => /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(dayOf(s).getTime());
10
+ const plus = (s: string, days: number) => { const d = dayOf(s); d.setDate(d.getDate() + days); return ymd(d); };
11
+ const months = (s: string, n: number) => { const d = dayOf(s), want = d.getMonth() + n; d.setDate(1); d.setMonth(want); const last = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(); d.setDate(Math.min(dayOf(s).getDate(), last)); return ymd(d); };
12
+ // 1 January 2024 was a Monday. Weeks start on Monday.
13
+ const weekdays = Array.from({ length: 7 }, (_, i) => new Date(2024, 0, 1 + i));
14
+
15
+ type Props = {
16
+ id?: string; value: string; onChange: (v: string) => void; time?: boolean; seconds?: boolean; min?: string; max?: string;
17
+ invalid?: boolean; describedBy?: string; required?: boolean; labelledBy?: string; label?: string; placeholder?: string; disabled?: boolean; className?: string;
18
+ };
19
+
20
+ /**
21
+ * A date, or a date and time, chosen on a calendar. The value is as a date input's: 2026-12-04, or 2026-12-04T17:30
22
+ * in this person's time.
23
+ */
24
+ export function DatePicker({ id, value, onChange, time, seconds, min, max, invalid, describedBy, required, labelledBy, label, placeholder, disabled, className }: Props) {
25
+ const t = useT(), loc = intlLocale();
26
+ const own = useId(), panel = useRef<HTMLDivElement>(null), button = useRef<HTMLButtonElement>(null), grid = useRef<HTMLDivElement>(null);
27
+ const day = value.slice(0, 10), clock = value.slice(11) || (seconds ? '00:00:00' : '00:00');
28
+ const today = ymd(new Date());
29
+ const [open, setOpen] = useState(false);
30
+ const [focus, setFocus] = useState(good(day) ? day : today);
31
+ const [h, m, s] = clock.split(':').map((x) => Number(x) || 0);
32
+ const lo = min?.slice(0, 10), hi = max?.slice(0, 10);
33
+ const off = (d: string) => (!!lo && d < lo) || (!!hi && d > hi);
34
+ const put = (d: string, at = clock) => onChange(time ? `${d}T${at}` : d);
35
+ const place = usePopoverPosition({
36
+ open,
37
+ anchor: () => button.current?.closest('[data-lk=date]'),
38
+ panel,
39
+ width: 300,
40
+ margin: 8,
41
+ flipThreshold: 380,
42
+ gap: 6,
43
+ align: 'start',
44
+ constrainHeight: false,
45
+ });
46
+ // The chosen day has the focus, so the keys move from there.
47
+ useEffect(() => { if (open) grid.current?.querySelector<HTMLButtonElement>(`[data-day="${focus}"]`)?.focus(); }, [open, focus]);
48
+ const close = () => { panel.current?.hidePopover(); button.current?.focus(); };
49
+ const choose = (d: string) => {
50
+ if (off(d)) return;
51
+ put(d);
52
+ if (!time) close();
53
+ };
54
+ const keys = (e: KeyboardEvent) => {
55
+ const step: Record<string, () => string> = {
56
+ ArrowLeft: () => plus(focus, -1), ArrowRight: () => plus(focus, 1), ArrowUp: () => plus(focus, -7), ArrowDown: () => plus(focus, 7),
57
+ PageUp: () => months(focus, e.shiftKey ? -12 : -1), PageDown: () => months(focus, e.shiftKey ? 12 : 1),
58
+ Home: () => plus(focus, -((dayOf(focus).getDay() + 6) % 7)), End: () => plus(focus, 6 - ((dayOf(focus).getDay() + 6) % 7)),
59
+ };
60
+ if (step[e.key]) { e.preventDefault(); setFocus(step[e.key]()); }
61
+ };
62
+ const first = dayOf(focus.slice(0, 8) + '01'), start = plus(ymd(first), -((first.getDay() + 6) % 7));
63
+ const cells = Array.from({ length: 42 }, (_, i) => plus(start, i));
64
+ const shown = good(day) ? dayOf(day).toLocaleDateString(loc, { month: 'short', day: 'numeric', ...(day.slice(0, 4) === today.slice(0, 4) ? {} : { year: 'numeric' }) }) + (time ? ' ' + new Date(2000, 0, 1, h, m, s).toLocaleTimeString(loc, { hour: '2-digit', minute: '2-digit', ...(seconds ? { second: '2-digit' } : {}) }) : '') : '';
65
+ const setClock = (part: 0 | 1 | 2, n: number) => {
66
+ const now = [h, m, s];
67
+ now[part] = n;
68
+ put(good(day) ? day : today, now.slice(0, seconds ? 3 : 2).map(two).join(':'));
69
+ };
70
+ const unit = (part: 0 | 1 | 2, name: string, top: number) => <input type="number" aria-label={name} min={0} max={top} className="input w-16 px-2 py-1.5 text-center tabular-nums" value={two([h, m, s][part])}
71
+ onChange={(e) => { const n = Math.round(Number(e.target.value)); if (Number.isFinite(n)) setClock(part, Math.min(top, Math.max(0, n))); }} />;
72
+ return <div data-lk="date" className={'input frame flex items-center !p-0 ' + (disabled ? 'opacity-60 ' : '') + (className ?? '')} aria-invalid={invalid || undefined}>
73
+ <button ref={button} id={id} type="button" disabled={disabled} popoverTarget={own} aria-haspopup="dialog" aria-expanded={open} aria-labelledby={labelledBy} aria-label={labelledBy ? undefined : label}
74
+ aria-describedby={describedBy} aria-required={required || undefined} aria-invalid={invalid || undefined}
75
+ className="bare flex min-w-0 flex-1 items-center gap-2 px-3 py-2 text-left">
76
+ <Icon name="calendar" className="muted size-4.5" />
77
+ <span className={'truncate ' + (shown ? '' : 'muted')}>{shown || placeholder || (time ? t('picker.dateTime') : t('picker.date'))}</span>
78
+ {labelledBy && <span className="sr-only">{shown || t('picker.none')}</span>}
79
+ </button>
80
+ {value && !required && !disabled && <button type="button" data-lk="clear-date" className="icon-btn mr-2" aria-label={t('table.clear')} onClick={() => onChange('')}><Icon name="x" className="size-4" /></button>}
81
+ <div ref={panel} id={own} popover="auto" role="dialog" aria-label={label ?? t('picker.date')} data-lk="calendar" className="surface menu border p-3 shadow-lg"
82
+ onBeforeToggle={(e) => { if (e.target === e.currentTarget && e.newState === 'open') { setFocus(good(day) ? day : today); place(); } }} onToggle={(e) => { if (e.target === e.currentTarget) setOpen(e.newState === 'open'); }}
83
+ onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault(); close(); } }}>
84
+ {open && <>
85
+ <div className="mb-2 flex items-center gap-1">
86
+ <button type="button" data-lk="previous-month" className="tool" aria-label={t('picker.prevMonth')} onClick={() => setFocus(months(focus, -1))}><Icon name="left" className="size-4.5 rtl:rotate-180" /></button>
87
+ <span aria-live="polite" className="flex-1 text-center text-sm font-semibold">{first.toLocaleDateString(loc, { month: 'long', year: 'numeric' })}</span>
88
+ <button type="button" data-lk="next-month" className="tool" aria-label={t('picker.nextMonth')} onClick={() => setFocus(months(focus, 1))}><Icon name="right" className="size-4.5 rtl:rotate-180" /></button>
89
+ </div>
90
+ <div role="grid" ref={grid} onKeyDown={keys} className="grid grid-cols-7 gap-0.5 text-center text-sm">
91
+ {weekdays.map((w) => <abbr key={w.getDay()} title={w.toLocaleDateString(loc, { weekday: 'long' })} className="muted py-1 text-xs font-medium no-underline">{w.toLocaleDateString(loc, { weekday: 'narrow' })}</abbr>)}
92
+ {cells.map((c) => {
93
+ const mine = c === day, here = c.slice(0, 7) === focus.slice(0, 7);
94
+ return <button key={c} type="button" data-day={c} tabIndex={c === focus ? 0 : -1} disabled={off(c)} aria-pressed={mine} aria-current={c === today ? 'date' : undefined}
95
+ aria-label={dayOf(c).toLocaleDateString(loc, { dateStyle: 'full' })} className={'day grid aspect-square place-items-center tabular-nums ' + (here ? '' : 'muted opacity-60')}
96
+ onClick={() => { setFocus(c); choose(c); }}>{dayOf(c).getDate()}</button>;
97
+ })}
98
+ </div>
99
+ {time && <div className="mt-3 flex items-center justify-center gap-1.5 border-t pt-3 text-sm" data-lk="time">
100
+ <Icon name="clock" className="muted mr-1 size-4.5" />{unit(0, t('picker.hour'), 23)}<span aria-hidden="true">:</span>{unit(1, t('picker.minute'), 59)}{seconds && <><span aria-hidden="true">:</span>{unit(2, t('picker.second'), 59)}</>}
101
+ </div>}
102
+ <div className="mt-3 flex items-center justify-between gap-2 border-t pt-3">
103
+ <button type="button" data-lk="today" className="row-btn" disabled={off(today)} onClick={() => { setFocus(today); choose(today); }}>{t('dates.today')}</button>
104
+ {time ? <button type="button" className="btn primary px-3 py-1.5" onClick={close}>{t('form.close')}</button>
105
+ : !required && value && <button type="button" className="row-btn muted" onClick={() => { onChange(''); close(); }}>{t('table.clear')}</button>}
106
+ </div>
107
+ </>}
108
+ </div>
109
+ </div>;
110
+ }
@@ -0,0 +1,206 @@
1
+ import * as React from 'react';
2
+ import { Guard, pluginBars, pluginComponent, pluginHooks, replaced as replacedPart } from '../plugins';
3
+ import { type Action, type Button, type ButtonSize, type ButtonVariant, type ColumnEditable, type ColumnSummaries, type Field, type Group, type HookItem, type HookName, type Layout, type Look, type Place, type Panel, type Resource, type Row, type Stat, type SummarySpec, type TenantInfo, type Widget } from './api';
4
+ import { Badge, LinkBtn } from './button';
5
+ import { ActionBtn } from './create';
6
+ import { TONES } from './hooks';
7
+ import { Icon } from './icons';
8
+ import { Bridged } from './bridge';
9
+
10
+ /** The parts of the kit, and what Larakit's drawing of each gets. `Bridged` gives them to the panel's parts. */
11
+ export type Parts = {
12
+ nav: { name: string; items: { name: string; label: string; href: string; current: boolean; icon?: string; group?: string; badge?: number }[]; layout: Layout['nav']; mode: 'light' | 'dark'; onMode?: () => void; rail?: boolean; logo?: string; logoDark?: string;
13
+ /** Whether a click on a group's heading folds it away. */
14
+ collapsible?: boolean;
15
+ tenantSwitcher?: React.ReactNode };
16
+ tenantSwitcher: { tenants: TenantInfo[]; active?: TenantInfo; onChange: (tenant: TenantInfo) => void; rail?: boolean };
17
+ /** `start` is the menu or the button that opens it, `Tools` the buttons, the bell and the user menu. */
18
+ topbar: { start: React.ReactNode; Tools: React.ComponentType };
19
+ header: { title: string; description?: string; breadcrumb?: React.ReactNode; actions?: React.ReactNode; children?: React.ReactNode };
20
+ breadcrumb: { items: { label: string; href?: string; onClick?: () => void; current?: boolean }[] };
21
+ table: { resource: string; columns: { key: string; label: string; type: string; sortable: boolean; align?: 'center' | 'end'; noWrap?: boolean; look?: Look; summaries?: SummarySpec[] }[]; rows: Row[]; loading: boolean; actions: Action[]; sort: string;
22
+ onSort: (key: string) => void; onEdit: (id: string) => void; onView?: (id: string) => void; onAction: (id: string, action: string) => void; Cell: React.ComponentType<{ column: string; row: Row }>;
23
+ /** The pages of each record, in the ⋮ menu: `onPage` opens one. */
24
+ pages?: { name: string; label: string; icon?: string }[]; onPage?: (id: string, page: string) => void;
25
+ /** The chosen ids. `row.can.bulk` says whether a row can be chosen. Without bulk actions nothing can. */
26
+ selected: string[]; onSelect: (ids: string[]) => void; empty: { heading: string; description: string }; striped: boolean; iconActions?: boolean;
27
+ /** How the View and Edit buttons look. */
28
+ viewButton?: Button; editButton?: Button;
29
+ summaries?: Record<string, ColumnSummaries>; sortingColumn?: string;
30
+ group?: { key: string; label: string; dir: 'asc' | 'desc'; collapsible?: boolean } | null;
31
+ reordering?: boolean; onReorder?: (ids: string[]) => void };
32
+ cell: { column: { key: string; label?: string; type: string; props?: Record<string, unknown> | null; look?: Look; editable?: ColumnEditable }; row: Record<string, unknown>; value: unknown; editable?: boolean; onSave?: (value: unknown) => Promise<void> | void };
33
+ badge: { label: string; color?: string; title?: string; value?: string; className?: string; children?: React.ReactNode };
34
+ empty: { heading: string; description: string; resource?: string };
35
+ pagination: { page: number; lastPage: number; perPage: number; perPages: number[]; total: number; from: number; to: number; onPage: (page: number) => void; onPerPage: (perPage: number) => void };
36
+ filters: { resource: Resource; baseUrl?: string; chosen: Record<string, string[]>; words?: boolean; defer?: boolean; layout?: 'popover' | 'above' | 'modal'; aboveOpen?: boolean; onToggleAbove?: () => void; onChange: (chosen: Record<string, string[]>) => void; children?: React.ReactNode };
37
+ form: { resource: string; id: string | null; fields: { key: string; label: string; type: string }[]; Field: React.ComponentType<{ name: string }>;
38
+ /** What the fields hold now, and the errors by field: what the panel's `part("form", ...)` gets. */
39
+ values?: Record<string, unknown>; errors?: Record<string, string>;
40
+ /** Where the fields are: `{field}` or a group with `items`. Only what is shown. `wrong` are the fields with an error. */
41
+ layout: { columns: number; items: Place[]; spans: Record<string, number>; wrong: string[] } };
42
+ field: { field: Field; id: string; errorId: string; value: string | string[] | Record<string, string> | Record<string, unknown>[]; errors?: string[]; disabled?: boolean; required: boolean; children?: React.ReactNode };
43
+ button: { label?: React.ReactNode; icon?: string; color?: string; variant?: ButtonVariant; size?: ButtonSize; danger?: boolean; iconOnly?: boolean; disabled?: boolean; type?: 'button' | 'submit' | 'reset'; className?: string; title?: string; ariaLabel?: string; dataLk?: string; onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void; children?: React.ReactNode };
44
+ section: { group: Group; heading?: string; description?: string; collapsible?: boolean; open: boolean; aside?: boolean; compact?: boolean; wrong: boolean; onToggle?: (open: boolean) => void; children: React.ReactNode };
45
+ tabs: { tabs: { heading?: string; icon?: string; badge?: string; badgeColor?: string; wrong: boolean; content: React.ReactNode }[]; active: number; onSelect: (index: number) => void; /** The form's tabs group, whose `.component()` draws them. */ group?: Group };
46
+ modal: { kind: 'form' | 'confirm' | 'ask'; layout?: 'dialog' | 'drawer'; widthClass?: string; titleId?: string; eyebrow?: string; description?: string; dataLk?: string; dataView?: boolean; portal?: boolean; className?: string; onClose: () => void; onCancel?: () => void; onKeyDown?: (e: React.KeyboardEvent) => void; children: React.ReactNode };
47
+ dashboard: { widgets: { name: string; label: string; type: string; wide: boolean }[]; Widget: React.ComponentType<{ name: string }> };
48
+ widget: { widget: Widget; loading: boolean; error: string; stale: boolean; onRetry: () => void; children: React.ReactNode };
49
+ stat: { stat: Stat; href?: string; children?: React.ReactNode };
50
+ toast: { id: number; text: string; bad: boolean; onClose: () => void };
51
+ loading: { kind: 'panel' | 'table' | 'form' | 'widget' | 'page' | 'inline'; widgetType?: string; columns?: number };
52
+ };
53
+ export type Part = keyof Parts;
54
+
55
+ /** Draws a part of the UI: the application's or a plugin's (LA-306/LA-319/LA-322), or Larakit's own. */
56
+ export function Slot<P extends Part>({ part, own, props }: { part: P; own: React.ComponentType<Parts[P]>; props: Parts[P] }) {
57
+ return <Bridged part={part} own={own} props={props} />;
58
+ }
59
+
60
+ /** All 22 canonical UI render hook names. */
61
+ export const HOOKS = [
62
+ 'topbar.start',
63
+ 'topbar.before-search',
64
+ 'topbar.after-search',
65
+ 'topbar.end',
66
+ 'sidebar.header',
67
+ 'sidebar.nav.start',
68
+ 'sidebar.nav.end',
69
+ 'sidebar.footer',
70
+ 'content.start',
71
+ 'content.end',
72
+ 'page.header.actions.before',
73
+ 'page.header.actions.after',
74
+ 'table.toolbar.start',
75
+ 'table.toolbar.end',
76
+ 'table.before',
77
+ 'table.after',
78
+ 'form.before',
79
+ 'form.after',
80
+ 'infolist.before',
81
+ 'infolist.after',
82
+ 'body.start',
83
+ 'body.end',
84
+ ] as const;
85
+
86
+ export type HookProps = { hook: HookName; panel: Panel; screen: string; place?: 'topbar' | 'side' };
87
+
88
+ export const PanelHookContext = React.createContext<{ panel: Panel; screen: string; reload?: () => void } | null>(null);
89
+
90
+ type Listed = Panel & { plugins?: import('@larakit/core').PanelPlugin[]; parts?: Record<string, string> };
91
+
92
+ /** The bars of the panel's plugins, as `stars/ratings`. */
93
+ export const bars = (panel: Panel) => pluginBars((panel as Listed).plugins);
94
+ /** Whether anything but Larakit draws a part of the layout in this panel. */
95
+ export const replaces = (part: Part, panel: Panel) => replacedPart(part, (panel as Listed).plugins, (panel as Listed).parts?.[part]);
96
+ export const column = (type: string) => pluginComponent('columns', type);
97
+ export const field = (type: string) => pluginComponent('fields', type);
98
+ export const widget = (type: string) => pluginComponent('widgets', type);
99
+ export const page = (type: string) => pluginComponent('pages', type);
100
+ export { Guard };
101
+
102
+ /** Returns true if a hook has any server-declared items or plugin-registered components. */
103
+ export function useHasHook(name: HookName): boolean {
104
+ const ctx = React.useContext(PanelHookContext);
105
+ if (!ctx) return false;
106
+ return (ctx.panel.hooks?.[name]?.length ?? 0) > 0 || pluginHooks(name, (ctx.panel as Listed).plugins).length > 0;
107
+ }
108
+
109
+ function HookItemView({ item, reload }: { item: HookItem; reload?: () => void }) {
110
+ if (item.type === 'action') {
111
+ return (
112
+ <ActionBtn
113
+ action={item.action}
114
+ url={`/hooks/actions/${encodeURIComponent(item.action.name)}`}
115
+ dataLk={'hook-action-' + item.action.name}
116
+ onDone={reload}
117
+ />
118
+ );
119
+ }
120
+ if (item.type === 'badge') {
121
+ const inner = (
122
+ <Badge label={item.label} color={item.color}>
123
+ {item.icon ? (
124
+ <span className="inline-flex items-center gap-1">
125
+ <Icon name={item.icon} className="size-3.5 shrink-0" />
126
+ <span>{item.label}</span>
127
+ </span>
128
+ ) : undefined}
129
+ </Badge>
130
+ );
131
+ if (item.href) {
132
+ const out = item.href.startsWith('https://') ? { target: '_blank', rel: 'noreferrer' } : {};
133
+ return (
134
+ <a href={item.href} data-lk="hook-badge" className="inline-flex items-center hover:opacity-90" {...out}>
135
+ {inner}
136
+ </a>
137
+ );
138
+ }
139
+ return inner;
140
+ }
141
+ if (item.type === 'banner') {
142
+ const tone = item.color ?? 'info';
143
+ const toneClass = TONES.includes(tone) ? `tone-${tone}` : 'tone-info';
144
+ return (
145
+ <div
146
+ role={tone === 'danger' || tone === 'warning' ? 'alert' : 'status'}
147
+ data-lk="hook-banner"
148
+ data-color={tone}
149
+ className={`callout ${toneClass} border p-4`}
150
+ >
151
+ <div className="flex items-start gap-3">
152
+ {item.icon && <Icon name={item.icon} className="callout-icon mt-0.5 size-5 shrink-0" />}
153
+ <div className="min-w-0 flex-1">
154
+ <p data-lk="hook-banner-title" className="text-sm font-semibold">{item.title}</p>
155
+ {item.description && (
156
+ <p data-lk="hook-banner-description" className="callout-desc mt-1 text-sm">{item.description}</p>
157
+ )}
158
+ </div>
159
+ </div>
160
+ </div>
161
+ );
162
+ }
163
+ if (item.type === 'text') {
164
+ const toneClass = item.color && TONES.includes(item.color) ? `tone-text-${item.color}` : 'muted';
165
+ return (
166
+ <span
167
+ data-lk="hook-text"
168
+ data-color={item.color}
169
+ className={`inline-flex items-center gap-1.5 text-sm ${toneClass}`}
170
+ >
171
+ {item.icon && <Icon name={item.icon} className="size-4 shrink-0" />}
172
+ <span>{item.text}</span>
173
+ </span>
174
+ );
175
+ }
176
+ return <LinkBtn link={item} styled dataLk="hook-button" />;
177
+ }
178
+
179
+ /** Renders server-declared hook items and plugin-registered hook components for a named hook location. */
180
+ export function RenderHook({
181
+ name,
182
+ place,
183
+ className,
184
+ }: {
185
+ name: HookName;
186
+ place?: 'topbar' | 'side';
187
+ className?: string;
188
+ }) {
189
+ const ctx = React.useContext(PanelHookContext);
190
+ if (!ctx) return null;
191
+ const serverItems = ctx.panel.hooks?.[name] ?? [];
192
+ const own = pluginHooks(name, (ctx.panel as Listed).plugins);
193
+ if (serverItems.length === 0 && own.length === 0) return null;
194
+ return (
195
+ <div data-lk="hook" data-hook={name} className={className ?? 'inline-flex flex-wrap items-center gap-1.5'}>
196
+ {serverItems.map((item, i) => (
197
+ <HookItemView key={i} item={item} reload={ctx.reload} />
198
+ ))}
199
+ {own.map((Component, i) => (
200
+ <Guard key={i} fallback={null}>
201
+ <Component hook={name as never} panel={ctx.panel} screen={ctx.screen} place={place} />
202
+ </Guard>
203
+ ))}
204
+ </div>
205
+ );
206
+ }
@@ -0,0 +1,86 @@
1
+ import { useEffect, useId, useState, type FormEvent } from 'react';
2
+ import { api, ApiError, fail } from './api';
3
+ import { useT } from './i18n';
4
+ import { Icon } from './icons';
5
+ import { say } from './notice';
6
+
7
+ export type Errors = Record<string, string[]>;
8
+
9
+ /** Sends a form, and gives the errors of its fields, or the answer. */
10
+ export function useSend() {
11
+ const [errors, setErrors] = useState<Errors>({});
12
+ const [busy, setBusy] = useState(false);
13
+ const [problem, setProblem] = useState('');
14
+ const send = async <T,>(path: string, body: unknown): Promise<T | undefined> => {
15
+ setBusy(true); setErrors({}); setProblem('');
16
+ try { return await api<T>(path, 'POST', body); }
17
+ catch (e) {
18
+ const bad = e instanceof ApiError ? e.errors ?? {} : {};
19
+ setErrors(bad);
20
+ if (!Object.keys(bad).length) setProblem(fail(e));
21
+ } finally { setBusy(false); }
22
+ };
23
+ return { errors, busy, problem, send };
24
+ }
25
+
26
+ /** A labelled input, with its error. */
27
+ export function Input({ label, name, errors, type = 'text', value, set, auto, focus }: { label: string; name: string; errors: Errors; type?: string; value: string; set: (v: string) => void; auto?: string; focus?: boolean }) {
28
+ const id = useId(), t = useT(), bad = errors[name];
29
+ const [shown, setShown] = useState(false);
30
+ const secret = type === 'password';
31
+ return (
32
+ <div data-lk="auth-field">
33
+ <label htmlFor={id} className="mb-1 block text-sm font-medium">{label}</label>
34
+ <div className="relative">
35
+ <input id={id} name={name} type={secret && shown ? 'text' : type} className={'input w-full' + (secret ? ' pe-10' : '')} value={value} autoComplete={auto} autoFocus={focus} aria-invalid={!!bad} aria-describedby={bad ? id + '-e' : undefined} onChange={(e) => set(e.target.value)} />
36
+ {secret && <button type="button" className="muted absolute inset-y-0 end-0 grid w-10 place-items-center" aria-label={t(shown ? 'auth.hidePassword' : 'auth.showPassword')} aria-pressed={shown} onClick={() => setShown(!shown)}><Icon name={shown ? 'eye-off' : 'eye'} className="size-4" /></button>}
37
+ </div>
38
+ {bad && <p id={id + '-e'} data-lk="error" className="danger mt-1 text-sm">{bad.join(' ')}</p>}
39
+ </div>
40
+ );
41
+ }
42
+
43
+ export function Problem({ text }: { text: string }) {
44
+ return text ? <p role="alert" className="danger text-sm">{text}</p> : null;
45
+ }
46
+
47
+ /** The profile of who is signed in: their name and email, and their password. */
48
+ export function ProfilePage({ onSaved }: { onSaved: (name: string, email: string) => void }) {
49
+ const t = useT();
50
+ const [me, setMe] = useState({ name: '', email: '' });
51
+ const [loaded, setLoaded] = useState(false), [error, setError] = useState('');
52
+ const profile = useSend(), password = useSend();
53
+ const [pw, setPw] = useState({ current: '', password: '', confirmation: '' });
54
+ useEffect(() => { api<{ name: string; email: string }>('/profile').then((m) => { setMe(m); setLoaded(true); }).catch((e) => setError(fail(e))); }, []);
55
+ if (error) return <p role="alert" className="danger">{error}</p>;
56
+ if (!loaded) return null;
57
+ const save = async (e: FormEvent) => {
58
+ e.preventDefault();
59
+ const done = await profile.send<{ message: string; name: string; email: string }>('/profile', me);
60
+ if (done) { say(done.message); onSaved(done.name, done.email); }
61
+ };
62
+ const change = async (e: FormEvent) => {
63
+ e.preventDefault();
64
+ const done = await password.send<{ message: string }>('/profile/password', { current_password: pw.current, password: pw.password, password_confirmation: pw.confirmation });
65
+ if (done) { say(done.message); setPw({ current: '', password: '', confirmation: '' }); }
66
+ };
67
+ return (
68
+ <div data-lk="profile" className="grid max-w-2xl gap-6">
69
+ <form className="card grid gap-4 p-6" onSubmit={save} noValidate>
70
+ <div><h2 className="font-semibold">{t('auth.profile')}</h2><p className="muted text-sm">{t('auth.profileHint')}</p></div>
71
+ <Problem text={profile.problem} />
72
+ <Input label={t('auth.name')} name="name" value={me.name} set={(name) => setMe({ ...me, name })} errors={profile.errors} auto="name" />
73
+ <Input label={t('auth.email')} name="email" type="email" value={me.email} set={(email) => setMe({ ...me, email })} errors={profile.errors} auto="email" />
74
+ <div><button className="btn primary" disabled={profile.busy}>{t('form.save')}</button></div>
75
+ </form>
76
+ <form className="card grid gap-4 p-6" onSubmit={change} noValidate>
77
+ <div><h2 className="font-semibold">{t('auth.changePassword')}</h2><p className="muted text-sm">{t('auth.changePasswordHint')}</p></div>
78
+ <Problem text={password.problem} />
79
+ <Input label={t('auth.currentPassword')} name="current_password" type="password" value={pw.current} set={(current) => setPw({ ...pw, current })} errors={password.errors} auto="current-password" />
80
+ <Input label={t('auth.newPassword')} name="password" type="password" value={pw.password} set={(p) => setPw({ ...pw, password: p })} errors={password.errors} auto="new-password" />
81
+ <Input label={t('auth.confirmPassword')} name="password_confirmation" type="password" value={pw.confirmation} set={(confirmation) => setPw({ ...pw, confirmation })} errors={password.errors} auto="new-password" />
82
+ <div><button className="btn primary" disabled={password.busy}>{t('auth.changePassword')}</button></div>
83
+ </form>
84
+ </div>
85
+ );
86
+ }
@@ -0,0 +1,146 @@
1
+ import { useId, useState, type KeyboardEvent } from 'react';
2
+ import type { RelationResource, Resource } from './api';
3
+ import { useI18n, useT } from './i18n';
4
+ import { Icon } from './icons';
5
+ import { Table } from './table';
6
+
7
+ /** Builds the scoped API prefix for a parent record's relation manager. */
8
+ export function relationPrefix(
9
+ parentResource: Pick<Resource, 'name'>,
10
+ parentId: string,
11
+ relation: Pick<RelationResource, 'name'>,
12
+ ): string {
13
+ return `/${parentResource.name}/${encodeURIComponent(parentId)}/relations/${encodeURIComponent(relation.name)}`;
14
+ }
15
+
16
+ /** Builds a scoped virtual Resource object for an embedded relation table. */
17
+ export function scopeRelationResource(
18
+ rel: RelationResource,
19
+ parentResource: Pick<Resource, 'name'>,
20
+ parentId: string,
21
+ ): RelationResource {
22
+ return {
23
+ ...rel,
24
+ parentResource: rel.parentResource ?? parentResource.name,
25
+ relation: rel.relation ?? rel.name,
26
+ // Embedded relation managers always keep modals/drawers in-place without hash routing.
27
+ pages: undefined,
28
+ globalSearch: false,
29
+ badge: false,
30
+ };
31
+ }
32
+
33
+ /** Renders embedded relation manager panels/tabs below a record's infolist or form. */
34
+ export function RelationManagers({
35
+ parentResource,
36
+ parentId,
37
+ }: {
38
+ parentResource: Resource;
39
+ parentId: string;
40
+ }) {
41
+ const t = useT();
42
+ const { dir } = useI18n();
43
+ const baseId = useId();
44
+ const relations = parentResource.relations ?? [];
45
+ const [activeIndex, setActiveIndex] = useState(0);
46
+
47
+ if (!relations.length) return null;
48
+
49
+ const currentIndex = Math.min(activeIndex, relations.length - 1);
50
+
51
+ if (relations.length === 1) {
52
+ const rel = relations[0];
53
+ const prefix = relationPrefix(parentResource, parentId, rel);
54
+ const scoped = scopeRelationResource(rel, parentResource, parentId);
55
+ return (
56
+ <section data-lk="relations" aria-label={rel.label || t('relations.title')} className="mt-8">
57
+ <div data-lk="relation-panel" data-name={rel.name} className="surface overflow-hidden border shadow-sm">
58
+ <Table
59
+ key={prefix}
60
+ resource={scoped}
61
+ baseUrl={prefix}
62
+ form="dialog"
63
+ embedded
64
+ flat
65
+ title={rel.label}
66
+ icon={rel.icon}
67
+ />
68
+ </div>
69
+ </section>
70
+ );
71
+ }
72
+
73
+ const moveTab = (e: KeyboardEvent, index: number) => {
74
+ const forward = dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight';
75
+ const backward = dir === 'rtl' ? 'ArrowRight' : 'ArrowLeft';
76
+ const next =
77
+ e.key === forward
78
+ ? (index + 1) % relations.length
79
+ : e.key === backward
80
+ ? (index - 1 + relations.length) % relations.length
81
+ : e.key === 'Home'
82
+ ? 0
83
+ : e.key === 'End'
84
+ ? relations.length - 1
85
+ : -1;
86
+ if (next < 0) return;
87
+ e.preventDefault();
88
+ setActiveIndex(next);
89
+ document.getElementById(`${baseId}-rel-tab-${next}`)?.focus();
90
+ };
91
+
92
+ const activeRel = relations[currentIndex];
93
+ const activePrefix = relationPrefix(parentResource, parentId, activeRel);
94
+ const activeScoped = scopeRelationResource(activeRel, parentResource, parentId);
95
+
96
+ return (
97
+ <section data-lk="relations" aria-label={t('relations.title')} className="mt-8 space-y-4">
98
+ <div
99
+ data-lk="relations-tabs"
100
+ role="tablist"
101
+ aria-label={t('relations.tabs')}
102
+ className="tabs flex gap-1 overflow-x-auto border-b"
103
+ >
104
+ {relations.map((rel, i) => {
105
+ const selected = i === currentIndex;
106
+ return (
107
+ <button
108
+ key={rel.name}
109
+ id={`${baseId}-rel-tab-${i}`}
110
+ type="button"
111
+ role="tab"
112
+ data-lk="relations-tab"
113
+ data-name={rel.name}
114
+ aria-selected={selected}
115
+ aria-controls={`${baseId}-rel-panel-${i}`}
116
+ tabIndex={selected ? 0 : -1}
117
+ className="tab -mb-px inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm font-medium whitespace-nowrap"
118
+ onClick={() => setActiveIndex(i)}
119
+ onKeyDown={(e) => moveTab(e, i)}
120
+ >
121
+ {rel.icon && <Icon name={rel.icon} className="size-4 shrink-0" />}
122
+ <span>{rel.label}</span>
123
+ </button>
124
+ );
125
+ })}
126
+ </div>
127
+
128
+ <div
129
+ id={`${baseId}-rel-panel-${currentIndex}`}
130
+ role="tabpanel"
131
+ aria-labelledby={`${baseId}-rel-tab-${currentIndex}`}
132
+ data-lk="relation-panel"
133
+ data-name={activeRel.name}
134
+ >
135
+ <Table
136
+ key={activePrefix}
137
+ resource={activeScoped}
138
+ baseUrl={activePrefix}
139
+ form="dialog"
140
+ embedded
141
+ hideTitle
142
+ />
143
+ </div>
144
+ </section>
145
+ );
146
+ }