@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,166 @@
1
+ import { useId, useState, type FormEvent } from 'react';
2
+ import { api, ApiError, base, fail, loginOf, type Action, type Choice, type Field, type ModalWidth } from './api';
3
+ import { Btn, Modal, modalWidthClass } from './button';
4
+ import { FieldView, FormErrors, holds, toForm, toSend, type Vals } from './field';
5
+ import { FormAlerts } from './form-shared';
6
+ import { useT } from './i18n';
7
+ import { complain, say } from './notice';
8
+
9
+ /** A small form over the form, that adds an option to a select. */
10
+ export function NewOption({ url, fields, typed, close }: { url: string; fields: Field[]; typed: string; close: (made?: Choice) => void }) {
11
+ const t = useT();
12
+ // What was searched for is most likely the name of the new option.
13
+ const first = fields.find((f) => f.type === 'text')?.key;
14
+ return <Ask url={url} fields={fields} title={t('form.newOption')} button={t('form.add')} start={first && typed ? { [first]: typed } : {}} close={(answer) => close((answer as { option?: Choice } | undefined)?.option)} />;
15
+ }
16
+
17
+ /** A form in a dialog or slide-over drawer that posts what was typed to `url`, such as an action's. */
18
+ export function Ask({
19
+ url,
20
+ fields,
21
+ title,
22
+ button,
23
+ danger,
24
+ eyebrow,
25
+ description,
26
+ slideOver,
27
+ modalWidth,
28
+ submitLabel,
29
+ cancelLabel,
30
+ start = {},
31
+ close,
32
+ }: {
33
+ url: string;
34
+ fields: Field[];
35
+ title: string;
36
+ button: string;
37
+ danger?: boolean;
38
+ eyebrow?: string;
39
+ description?: string;
40
+ slideOver?: boolean;
41
+ modalWidth?: ModalWidth;
42
+ submitLabel?: string;
43
+ cancelLabel?: string;
44
+ start?: Vals;
45
+ close: (answer?: unknown) => void;
46
+ }) {
47
+ const t = useT();
48
+ const own = useId();
49
+ const [values, setValues] = useState<Vals>(() => Object.fromEntries(fields.map((f) => [f.key, start[f.key] ?? toForm(f, f.default, () => {})])));
50
+ const [errors, setErrors] = useState<Record<string, string[]>>({});
51
+ const [problem, setProblem] = useState('');
52
+ const [login, setLogin] = useState('');
53
+ const [busy, setBusy] = useState(false);
54
+ const shown = fields.filter((f) => f.type !== 'hidden' && holds(f.visibleWhen, values));
55
+ const layout = slideOver ? 'drawer' : 'dialog';
56
+ const widthClass = modalWidthClass(modalWidth, layout, 'max-w-md');
57
+ const submit = async (e: FormEvent) => {
58
+ e.preventDefault();
59
+ e.stopPropagation(); // this is inside the other form for React
60
+ if (busy) return;
61
+ setBusy(true); setErrors({}); setProblem(''); setLogin('');
62
+ try {
63
+ close(await api<unknown>(url, 'POST', Object.fromEntries(fields.map((f) => [f.key, toSend(f, values[f.key])]))));
64
+ } catch (err) {
65
+ if (err instanceof ApiError && err.status === 422) setErrors(err.errors); else { setProblem(fail(err)); setLogin(loginOf(err)); }
66
+ setBusy(false);
67
+ }
68
+ };
69
+ // An error of a field that is not shown must still be seen.
70
+ // A field inside a list shows its error on its row.
71
+ const rest = Object.keys(errors).filter((k) => !shown.some((f) => f.key === k || f.type === 'repeater' && k.startsWith(f.key + '.')));
72
+ return (
73
+ <Modal kind="ask" dataLk="create-form" layout={layout} titleId={own} eyebrow={eyebrow} description={description} widthClass={widthClass} portal stopCancelPropagation
74
+ onClose={() => close()} onKeyDown={(e) => e.stopPropagation()}>
75
+ <FormErrors value={errors}><form onSubmit={submit} noValidate className="space-y-4">
76
+ <div className="space-y-1">
77
+ {eyebrow && <p data-lk="eyebrow" className="muted text-xs font-semibold tracking-wider uppercase">{eyebrow}</p>}
78
+ <h2 id={own} data-lk="title" className="text-lg font-bold">{title}</h2>
79
+ {description && <p data-lk="description" className="muted text-sm">{description}</p>}
80
+ </div>
81
+ <FormAlerts problem={problem} login={login} errors={errors} hiddenErrorKeys={rest} />
82
+ {/* A file goes to the action's own address, `uploads/{field}`, and is read back from its `files/{field}`. */}
83
+ {shown.map((f) => <FieldView key={f.key} id={own + f.key} errorId={own + f.key + 'e'} url="" uploadUrl={`${url}/uploads/${f.key}`} fileBaseUrl={`${base}${url}/files/${f.key}`} api={base + url} field={f} value={values[f.key]} values={values} errors={errors[f.key]} onKnown={() => {}} set={(v) => setValues((old) => ({ ...old, [f.key]: v }))} />)}
84
+ <div className="flex justify-end gap-2">
85
+ <Btn dataLk="cancel" label={cancelLabel || t('form.cancel')} onClick={() => close()} />
86
+ <Btn type="submit" dataLk="create" variant="solid" color={danger ? 'danger' : 'primary'} label={submitLabel || button} disabled={busy} />
87
+ </div>
88
+ </form></FormErrors>
89
+ </Modal>
90
+ );
91
+ }
92
+
93
+ /** Renders a standalone action button (topbar or hook) with optional confirmation/form modal via Ask. */
94
+ export function ActionBtn({
95
+ action: a,
96
+ url,
97
+ dataLk,
98
+ onDone,
99
+ }: {
100
+ action: Action;
101
+ url: string;
102
+ dataLk?: string;
103
+ onDone?: () => void;
104
+ }) {
105
+ const [asking, setAsking] = useState(false);
106
+ const [busy, setBusy] = useState(false);
107
+ const needsAsk = !!(a.confirm || a.form?.length || a.description || a.eyebrow || a.slideOver);
108
+
109
+ const run = async () => {
110
+ if (busy) return;
111
+ if (needsAsk) {
112
+ setAsking(true);
113
+ return;
114
+ }
115
+ setBusy(true);
116
+ try {
117
+ const r = await api<{ message?: string }>(url, 'POST', {});
118
+ if (r?.message) say(r.message);
119
+ onDone?.();
120
+ } catch (e) {
121
+ complain(fail(e));
122
+ } finally {
123
+ setBusy(false);
124
+ }
125
+ };
126
+
127
+ return (
128
+ <>
129
+ <Btn
130
+ dataLk={dataLk}
131
+ label={a.label}
132
+ icon={a.icon}
133
+ color={a.color}
134
+ variant={a.variant}
135
+ size={a.size}
136
+ danger={a.danger}
137
+ iconOnly={a.iconOnly}
138
+ disabled={busy}
139
+ onClick={() => void run()}
140
+ />
141
+ {asking && (
142
+ <Ask
143
+ url={url}
144
+ fields={a.form ?? []}
145
+ title={a.label}
146
+ button={a.label}
147
+ danger={a.danger}
148
+ eyebrow={a.eyebrow}
149
+ description={a.description || a.confirm || undefined}
150
+ slideOver={a.slideOver}
151
+ modalWidth={a.modalWidth}
152
+ submitLabel={a.submitLabel}
153
+ cancelLabel={a.cancelLabel}
154
+ close={(answer) => {
155
+ setAsking(false);
156
+ if (answer) {
157
+ const msg = (answer as { message?: string }).message;
158
+ if (msg) say(msg);
159
+ onDone?.();
160
+ }
161
+ }}
162
+ />
163
+ )}
164
+ </>
165
+ );
166
+ }
@@ -0,0 +1,335 @@
1
+ import { router } from '@inertiajs/react';
2
+ import { createContext, Suspense, useContext, useEffect, useState, type ComponentType } from 'react';
3
+ import { component as appComponent, Missing } from '../components';
4
+ import type { ComponentWidgetProps } from '../plugins';
5
+ import { Btn, PageHeader } from './button';
6
+ import { Cell } from './cell';
7
+ import { Area, Bars, Columns, DataTable, Doughnut, Key, Line, Pie, full, short, ticks } from './charts';
8
+ import { alignClass } from './hooks';
9
+ import { useT } from './i18n';
10
+ import { Icon } from './icons';
11
+ import { Loading, useDelayed } from './loading';
12
+ import { href as record } from './search';
13
+ import { Guard, Slot, widget as component, type Parts } from './plugins';
14
+ import { DateFilter, query, useDates } from './dates';
15
+ import { useActions } from './table';
16
+ import { PageForm } from './pageform';
17
+ import { api, currentPanelPath, text, fail, type Chart, type ListData, type MenuPage, type Panel, type Point, type Stat, type Widget, type WidgetFilter } from './api';
18
+
19
+ export { ticks };
20
+
21
+ /** Where a widget links to: a full web address as it is, or an address in the panel. */
22
+ export const to = (href: string) => (/^(https?:|mailto:|\/|#)/i.test(href) ? href : currentPanelPath() + '/' + href);
23
+ /** A link to another site opens in a new tab, as the menu's do. */
24
+ const away = (href: string) => (href.startsWith('https://') ? { target: '_blank', rel: 'noreferrer' } : {});
25
+
26
+ const PanelContext = createContext<Panel | null>(null);
27
+ const QueryContext = createContext('');
28
+ /** Where the widgets load from: the dashboard's, or a page's. */
29
+ const BaseContext = createContext('/dashboard/');
30
+
31
+ function WidgetBox({ name }: { name: string }) {
32
+ const panel = useContext(PanelContext), widget = panel?.dashboard.find((w) => w.name === name);
33
+ return panel && widget ? <Box widget={widget} panel={panel} /> : null;
34
+ }
35
+
36
+ function Widgets({ widgets, Widget }: Parts['dashboard']) {
37
+ return <div data-lk="dashboard" className="grid gap-4 lg:grid-cols-2">{widgets.map((w) => <Widget key={w.name} name={w.name} />)}</div>;
38
+ }
39
+
40
+ export function Dashboard({ panel }: { panel: Panel }) {
41
+ const t = useT();
42
+ const [choice, choose] = useDates(panel.dates);
43
+ const widgets = panel.dashboard.map(({ name, label, type, wide }) => ({ name, label, type, wide }));
44
+ return (
45
+ <PanelContext value={panel}><QueryContext value={panel.dates ? query(choice) : ''}>
46
+ <PageHeader title={t('nav.dashboard')} actions={panel.dates > 0 ? <DateFilter days={panel.dates} choice={choice} onChange={choose} /> : undefined} />
47
+ <Slot part="dashboard" own={Widgets} props={{ widgets, Widget: WidgetBox }} />
48
+ </QueryContext></PanelContext>
49
+ );
50
+ }
51
+
52
+ /** A page of the panel, or of a record when `at` is where it is asked, such as `posts/7/pages/history`. */
53
+ export function PanelPage({ page, panel, at = page.name ?? '', back }: { page: MenuPage; panel: Panel; at?: string; back?: { href: string; label: string } }) {
54
+ const [round, setRound] = useState(0);
55
+ // After an action, the widgets load again, as they may show what it changed.
56
+ const [run, asked] = useActions({ name: at, headerActions: page.actions }, () => setRound((n) => n + 1));
57
+ return (
58
+ <PanelContext value={panel}><BaseContext value={`/${at}/widgets/`}>
59
+ {back && <a data-lk="back" href={back.href} className="muted mb-3 inline-flex items-center gap-1 text-sm hover:underline"><Icon name="left" className="size-4 rtl:rotate-180" />{back.label}</a>}
60
+ <PageHeader title={page.label} description={page.description} actions={page.actions?.length ? <>{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={() => run(null, a.name)} />)}</> : undefined} />
61
+ {page.form && <div className={page.widgets?.length ? 'mb-6' : ''}><PageForm page={page.name ?? ''} fields={page.form.fields} items={page.form.items} columns={page.form.columns} canSave={page.form.canSave} /></div>}
62
+ {page.widgets?.length ? <div key={round} data-lk="page-widgets" className="grid gap-4 lg:grid-cols-2">{page.widgets.map((w) => <Box key={w.name} widget={w} panel={panel} />)}</div> : null}
63
+ {asked}
64
+ </BaseContext></PanelContext>
65
+ );
66
+ }
67
+
68
+ function initialFilters(filters?: WidgetFilter[]): Record<string, string> {
69
+ const out: Record<string, string> = {};
70
+ for (const f of filters ?? []) {
71
+ if (f.default !== undefined && f.default !== null && f.default !== '') out[f.name] = String(f.default);
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** Combines panel date query parameters with widget-level `filter_<name>=<val>` params. */
77
+ export function buildWidgetQuery(dateQuery: string, filters: Record<string, string>): string {
78
+ const params = new URLSearchParams(dateQuery.startsWith('?') ? dateQuery.slice(1) : dateQuery);
79
+ for (const [name, value] of Object.entries(filters)) {
80
+ if (value !== '') params.set('filter_' + name, value);
81
+ }
82
+ const qs = params.toString();
83
+ return qs ? '?' + qs : '';
84
+ }
85
+
86
+ function WidgetFilters({
87
+ widgetName,
88
+ filters,
89
+ defer,
90
+ values,
91
+ hasAny,
92
+ onSelect,
93
+ onApply,
94
+ onReset,
95
+ }: {
96
+ widgetName: string;
97
+ filters: WidgetFilter[];
98
+ defer: boolean;
99
+ values: Record<string, string>;
100
+ hasAny: boolean;
101
+ onSelect: (name: string, value: string) => void;
102
+ onApply: () => void;
103
+ onReset: () => void;
104
+ }) {
105
+ const t = useT();
106
+ return (
107
+ <div data-lk="widget-filters" className="flex flex-wrap items-center gap-1.5">
108
+ {filters.map((f) => {
109
+ const fid = `wf-${widgetName}-${f.name}`;
110
+ const hasEmpty = f.options.some((o) => String(o.value) === '');
111
+ return (
112
+ <span key={f.name} className="inline-flex items-center">
113
+ <label htmlFor={fid} className="sr-only">{f.label}</label>
114
+ <select
115
+ id={fid}
116
+ data-lk="widget-filter"
117
+ data-name={f.name}
118
+ aria-label={f.label}
119
+ className="input w-auto py-1 text-xs"
120
+ value={values[f.name] ?? ''}
121
+ onChange={(e) => onSelect(f.name, e.target.value)}
122
+ >
123
+ {!hasEmpty && <option value="">{f.placeholder ?? `${f.label}: ${t('form.all')}`}</option>}
124
+ {f.options.map((o) => (
125
+ <option key={String(o.value)} value={String(o.value)} disabled={o.disabled}>
126
+ {o.label}
127
+ </option>
128
+ ))}
129
+ </select>
130
+ </span>
131
+ );
132
+ })}
133
+ {defer && (
134
+ <>
135
+ <button type="button" data-lk="widget-filters-apply" data-size="xs" data-variant="solid" className="btn primary" onClick={onApply}>
136
+ {t('table.applyFilters')}
137
+ </button>
138
+ <button type="button" data-lk="widget-filters-reset" data-size="xs" className="btn" disabled={!hasAny} onClick={onReset}>
139
+ {t('table.reset')}
140
+ </button>
141
+ </>
142
+ )}
143
+ </div>
144
+ );
145
+ }
146
+
147
+ function Box({ widget, panel }: { widget: Widget; panel: Panel }) {
148
+ const t = useT();
149
+ const [data, setData] = useState<unknown>();
150
+ const [error, setError] = useState('');
151
+ const [again, setAgain] = useState(0);
152
+ const [appliedFilters, setAppliedFilters] = useState<Record<string, string>>(() => initialFilters(widget.filters));
153
+ const [draftFilters, setDraftFilters] = useState<Record<string, string>>(appliedFilters);
154
+ const query = useContext(QueryContext), base = useContext(BaseContext);
155
+ const requestQuery = buildWidgetQuery(query, appliedFilters);
156
+ const [answered, setAnswered] = useState(requestQuery); // the dates & filters that the data is for
157
+ const old = answered !== requestQuery;
158
+ const wait = useDelayed(data === undefined && !error);
159
+ useEffect(() => {
160
+ const stop = new AbortController();
161
+ let timer: ReturnType<typeof setTimeout> | undefined;
162
+ // The next request is planned after the last one ends, so slow answers never pile up.
163
+ const load = async () => {
164
+ if (!document.hidden) {
165
+ try {
166
+ const fresh = await api(base + widget.name + requestQuery, 'GET', undefined, stop.signal);
167
+ if (stop.signal.aborted) return;
168
+ setData(fresh); setAnswered(requestQuery); setError('');
169
+ } catch (e) {
170
+ if (stop.signal.aborted) return;
171
+ // Numbers for other dates/filters would be wrong here. After a failed poll, the last ones still help.
172
+ setAnswered((was) => { if (was !== requestQuery) setData(undefined); return requestQuery; });
173
+ setError(fail(e));
174
+ }
175
+ }
176
+ if (widget.poll && !stop.signal.aborted) timer = setTimeout(load, widget.poll * 1000);
177
+ };
178
+ load();
179
+ // A page that was opened in the background loads when it is first seen.
180
+ const seen = () => { if (!document.hidden) { clearTimeout(timer); load(); } };
181
+ const waiting = document.hidden;
182
+ if (waiting) document.addEventListener('visibilitychange', seen, { once: true });
183
+ return () => { stop.abort(); clearTimeout(timer); document.removeEventListener('visibilitychange', seen); };
184
+ }, [widget.name, widget.poll, again, requestQuery, base]);
185
+ const id = 'w-' + widget.name;
186
+ const defer = !!widget.deferFilters;
187
+ const shownFilters = defer ? draftFilters : appliedFilters;
188
+ const hasAnyFilter = Object.values(draftFilters).some(Boolean) || Object.values(appliedFilters).some(Boolean);
189
+ return (
190
+ <Slot part="widget" own={DefaultWidget} props={{ widget, loading: data === undefined && !error, error, stale: old, onRetry: () => { setError(''); setAgain((n) => n + 1); }, children: (
191
+ <section data-lk="widget" data-name={widget.name} data-type={widget.type} aria-labelledby={id} aria-busy={old || (data === undefined && !error)}
192
+ className={'surface min-w-0 border p-5 ' + (widget.wide ? 'lg:col-span-2' : '')}>
193
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
194
+ <h2 id={id} data-lk="title" className="text-[0.9375rem] font-semibold tracking-[-0.01em]">{widget.label}</h2>
195
+ {(!!widget.filters?.length || !!widget.links?.length) && (
196
+ <div className="flex flex-wrap items-center gap-2">
197
+ {!!widget.filters?.length && (
198
+ <WidgetFilters
199
+ widgetName={widget.name}
200
+ filters={widget.filters}
201
+ defer={defer}
202
+ values={shownFilters}
203
+ hasAny={hasAnyFilter}
204
+ onSelect={(name, val) => {
205
+ const next = { ...(defer ? draftFilters : appliedFilters) };
206
+ if (val === '') delete next[name];
207
+ else next[name] = val;
208
+ setDraftFilters(next);
209
+ if (!defer) setAppliedFilters(next);
210
+ }}
211
+ onApply={() => setAppliedFilters(draftFilters)}
212
+ onReset={() => {
213
+ setDraftFilters({});
214
+ setAppliedFilters({});
215
+ }}
216
+ />
217
+ )}
218
+ {widget.links?.map((l, i) => <a key={i} data-lk="widget-link" href={to(l.href)} {...away(l.href)} className="widget-link inline-flex items-center gap-1 text-sm font-medium">{l.label}<Icon name="right" className="size-4 rtl:rotate-180" /></a>)}
219
+ </div>
220
+ )}
221
+ </div>
222
+ {error && <p role="alert" data-lk="error" className="danger mb-3 text-sm">{error} <button className="underline" onClick={() => { setError(''); setAgain((n) => n + 1); }}>{t('page.tryAgain')}</button></p>}
223
+ {data === undefined ? !error && wait && <Loading kind="widget" widgetType={widget.type} /> : <div className={'transition-opacity duration-150 motion-reduce:transition-none ' + (old ? 'opacity-50' : '')}><Content widget={widget} data={data} panel={panel} reload={() => setAgain((n) => n + 1)} /></div>}
224
+ </section>
225
+ ) }} />
226
+ );
227
+ }
228
+
229
+ const DefaultWidget = ({ children }: Parts['widget']) => <>{children}</>;
230
+
231
+ function Content({ widget, data, panel, reload }: { widget: Widget; data: unknown; panel: Panel; reload: () => void }) {
232
+ const t = useT();
233
+ if (widget.type === 'component' && widget.component) {
234
+ // The application's own component, that the server's ComponentWidget (Go) or component_widget (Rust) names.
235
+ const Drawn = appComponent(widget.component) as ComponentType<ComponentWidgetProps> | null;
236
+ if (!Drawn) return <Missing name={widget.component} />;
237
+ return (
238
+ <Guard fallback={<p role="alert" className="danger text-sm">{t('page.wentWrong')}</p>}>
239
+ <Suspense fallback={null}><Drawn data={data as Record<string, unknown>} reload={reload} /></Suspense>
240
+ </Guard>
241
+ );
242
+ }
243
+ if (widget.type === 'stats') return <Stats stats={(data as { stats: Stat[] }).stats} panel={panel} empty={widget.empty} assistive={widget.assistive} />;
244
+ if (widget.type === 'list') return <List data={data as ListData} panel={panel} screen={widget.screen} empty={widget.empty} assistive={widget.assistive} />;
245
+ if (widget.type.includes('/')) {
246
+ const Part = component(widget.type);
247
+ const problem = <p className="danger text-sm">{t('page.pluginError')}</p>;
248
+ return Part ? <Guard fallback={problem}><Part data={data as Record<string, unknown>} /></Guard> : problem;
249
+ }
250
+ const points = 'points' in (data as object) ? (data as { points: Point[] }).points : undefined;
251
+ const chart: Chart = points
252
+ ? { labels: points.map((p) => p.label), series: [{ label: widget.label, values: points.map((p) => p.value) }], hrefs: points.map((p) => (p.href ? to(p.href) : '')) }
253
+ : (data as Chart);
254
+ if (chart.labels.length === 0 || chart.series.length === 0) return <p data-lk="empty" className="muted text-sm">{widget.empty || t('dashboard.noData')}</p>;
255
+ if (widget.type === 'doughnut' || widget.type === 'pie') {
256
+ const sum = chart.series[0].values.reduce((a, b) => a + b, 0);
257
+ if (sum <= 0) return <p data-lk="empty" className="muted text-sm">{widget.empty || t('dashboard.noData')}</p>;
258
+ const Shape = widget.type === 'pie' ? Pie : Doughnut;
259
+ return <><Shape {...chart} total={sum} label={widget.label} empty={widget.empty} assistive={widget.assistive} /><DataTable chart={chart} share={sum} /></>;
260
+ }
261
+ return (
262
+ <>
263
+ {chart.series.length > 1 && <ul data-lk="legend" className="mb-3 flex flex-wrap gap-x-4 gap-y-1 text-sm">
264
+ {chart.series.map((s, i) => <li key={i} className={'flex items-center gap-2 series-' + i}><Key line={widget.type === 'line' || widget.type === 'area'} />{s.label}</li>)}
265
+ </ul>}
266
+ {widget.type === 'bar'
267
+ ? <Bars {...chart} empty={widget.empty} assistive={widget.assistive} />
268
+ : widget.type === 'column'
269
+ ? <Columns {...chart} empty={widget.empty} assistive={widget.assistive} />
270
+ : widget.type === 'area'
271
+ ? <Area {...chart} label={widget.label} empty={widget.empty} assistive={widget.assistive} />
272
+ : <Line {...chart} label={widget.label} empty={widget.empty} assistive={widget.assistive} />}
273
+ {widget.type !== 'bar' && <DataTable chart={chart} />}
274
+ </>
275
+ );
276
+ }
277
+
278
+ function Spark({ values, color }: { values: number[]; color?: string }) {
279
+ const low = Math.min(...values), span = Math.max(...values) - low || 1;
280
+ const points = values.map((v, i) => `${(i / (values.length - 1)) * 100} ${95 - ((v - low) / span) * 85}`).join('L');
281
+ return (
282
+ <svg data-lk="spark" className={'mt-3 h-10 w-full tone-text-' + (color || 'primary')} viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
283
+ <path d={`M${points}L100 100L0 100Z`} fill="currentColor" opacity="0.08" />
284
+ <path d={'M' + points} fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
285
+ </svg>
286
+ );
287
+ }
288
+
289
+ function DefaultStat({ stat: s, href }: Parts['stat']) {
290
+ const value = typeof s.value === 'number' ? <span title={full(s.value)}>{short(s.value)}</span> : text(s.value);
291
+ return <div data-lk="stat" className="min-w-0">
292
+ <dt className="muted flex items-center gap-1.5 text-[13px] font-medium">{s.icon && <Icon name={s.icon} className="size-4 shrink-0" />}<span className="truncate">{s.label}</span></dt>
293
+ <dd className="mt-1.5 text-[1.75rem] leading-tight font-semibold tracking-[-0.025em] tabular-nums">{href ? <a className="hover:underline" href={href} {...away(href)}>{value}</a> : value}</dd>
294
+ {s.note && <dd className={'mt-1 text-xs font-medium ' + (s.color ? 'tone-text-' + s.color : 'muted')}>{s.note}</dd>}
295
+ {(s.chart?.length ?? 0) > 1 && <dd><Spark values={s.chart!} color={s.color} /></dd>}
296
+ </div>;
297
+ }
298
+
299
+ function Stats({ stats, panel, empty, assistive }: { stats: Stat[]; panel: Panel; empty?: string; assistive?: string }) {
300
+ const t = useT();
301
+ if (stats.length === 0) return <p data-lk="empty" className="muted text-sm">{empty || t('dashboard.noData')}</p>;
302
+ return (
303
+ <>
304
+ {assistive && <p data-lk="assistive" className="sr-only">{assistive}</p>}
305
+ <dl className="grid grid-cols-2 gap-6 sm:grid-cols-[repeat(auto-fit,minmax(10rem,1fr))]">
306
+ {stats.map((s, i) => {
307
+ const link = s.href ? to(s.href) : panel.resources.some((r) => r.name === s.screen) ? currentPanelPath() + '/' + s.screen : '';
308
+ return <Slot key={i} part="stat" own={DefaultStat} props={{ stat: s, href: link || undefined }} />;
309
+ })}
310
+ </dl>
311
+ </>
312
+ );
313
+ }
314
+
315
+ function List({ data, panel, screen, empty, assistive }: { data: ListData; panel: Panel; screen?: string; empty?: string; assistive?: string }) {
316
+ const t = useT();
317
+ if (data.rows.length === 0) return <p data-lk="empty" className="muted text-sm">{empty || t('table.empty')}</p>;
318
+ // Rows open their records when the screen is one this visitor may see.
319
+ const opens = !!screen && panel.resources.some((r) => r.name === screen);
320
+ const click = (e: React.MouseEvent, id: string) => {
321
+ if (!opens || (e.target as Element).closest('a, button') || getSelection()?.toString()) return;
322
+ router.visit(record(panel, screen, id));
323
+ };
324
+ return (
325
+ <div className="-mx-2 overflow-x-auto">
326
+ {assistive && <p data-lk="assistive" className="sr-only">{assistive}</p>}
327
+ <table className="w-full text-left text-sm">
328
+ <thead><tr className="border-b">{data.columns.map((c) => <th key={c.key} scope="col" className={'muted px-2 py-2 font-medium' + alignClass(c.look?.align)}>{c.label}</th>)}{opens && <th scope="col" className="w-8"><span className="sr-only">{t('dashboard.open')}</span></th>}</tr></thead>
329
+ <tbody>{data.rows.map((row) => <tr key={row.id} data-opens={opens ? '' : undefined} className="table-row border-b last:border-0" onClick={(e) => click(e, row.id)}>
330
+ {data.columns.map((c) => <td key={c.key} className={'px-2 py-2.5' + alignClass(c.look?.align)}><Cell column={c} row={row.cells} /></td>)}
331
+ {opens && <td className="px-2 text-right"><a href={record(panel, screen, row.id)} data-lk="open" aria-label={t('dashboard.open')} className="muted inline-flex rounded-md p-1 hover:text-[var(--lk-text)]"><Icon name="right" className="size-4 rtl:rotate-180" /></a></td>}
332
+ </tr>)}</tbody>
333
+ </table></div>
334
+ );
335
+ }
@@ -0,0 +1,62 @@
1
+ import { useState } from 'react';
2
+ import { currentPanelPath } from './api';
3
+ import { useT } from './i18n';
4
+ import { DatePicker } from './picker';
5
+ import { Select } from './select';
6
+
7
+ export type Choice = { kind: string; from: string; to: string };
8
+ const key = () => 'larakit:dates:' + currentPanelPath();
9
+ const day = 86400000;
10
+ // Days start at midnight UTC, as on the server.
11
+ const iso = (time: number) => new Date(time).toISOString().slice(0, 10);
12
+
13
+ const counts = (days: number) => [...new Set([7, 30, 90, days])].sort((a, b) => a - b);
14
+
15
+ /** The first and last day of a choice. */
16
+ function range({ kind, from, to }: Choice): [string, string] {
17
+ const now = Date.now(), today = iso(now);
18
+ if (kind === 'month') return [today.slice(0, 8) + '01', today];
19
+ if (kind === 'year') return [today.slice(0, 5) + '01-01', today];
20
+ if (kind === 'own') return [from, to];
21
+ return [iso(now - (Number(kind) - 1) * day), today];
22
+ }
23
+
24
+ /** What to send to the server, and whether it makes sense. */
25
+ export function query(choice: Choice): string {
26
+ const [from, to] = range(choice);
27
+ return '?' + new URLSearchParams({ from, to });
28
+ }
29
+
30
+ export function useDates(days: number): [Choice, (c: Choice) => void] {
31
+ const [choice, set] = useState<Choice>(() => {
32
+ try { // The setting may have changed since, and other code can write here too.
33
+ const c = JSON.parse(sessionStorage.getItem(key()) ?? '');
34
+ if (['month', 'year', ...counts(days).map(String)].includes(c.kind) || (c.kind === 'own' && c.from && c.to)) return { kind: c.kind, from: String(c.from), to: String(c.to) };
35
+ } catch { /* none yet */ }
36
+ return { kind: String(days), from: '', to: '' };
37
+ });
38
+ return [choice, (c) => { try { sessionStorage.setItem(key(), JSON.stringify(c)); } catch { /* private window */ } set(c); }];
39
+ }
40
+
41
+ export function DateFilter({ days, choice, onChange }: { days: number; choice: Choice; onChange: (c: Choice) => void }) {
42
+ const t = useT();
43
+ const [own, setOwn] = useState(choice.kind === 'own');
44
+ const [first, last] = range(choice);
45
+ const [from, setFrom] = useState(first), [to, setTo] = useState(last);
46
+ const kinds = [...counts(days).map((n) => ({ value: String(n), label: n === 1 ? t('dates.today') : t('dates.lastDays', { days: n }) })),
47
+ { value: 'month', label: t('dates.thisMonth') }, { value: 'year', label: t('dates.thisYear') }, { value: 'own', label: t('dates.custom') }];
48
+ const wrong = !from || !to || from > to;
49
+ return (
50
+ <div data-lk="dates" className="flex flex-wrap items-center gap-2 text-sm">
51
+ <Select label={t('dates.label')} className="!w-auto min-w-40" value={[own ? 'own' : choice.kind]} options={kinds} chosen={(v) => kinds.find((k) => k.value === v)?.label ?? v} onChange={([kind]) => {
52
+ setOwn(kind === 'own');
53
+ if (kind === 'own') { setFrom(first); setTo(last); } else onChange({ kind, from: '', to: '' });
54
+ }} />
55
+ {own && <form className="flex flex-wrap items-center gap-2" onSubmit={(e) => { e.preventDefault(); if (!wrong) onChange({ kind: 'own', from, to }); }}>
56
+ <DatePicker label={t('dates.from')} className="w-44" required value={from} max={to || undefined} onChange={setFrom} />
57
+ <DatePicker label={t('dates.to')} className="w-44" required value={to} min={from || undefined} onChange={setTo} />
58
+ <button data-lk="apply-dates" className="btn" disabled={wrong}>{t('dates.show')}</button>
59
+ </form>}
60
+ </div>
61
+ );
62
+ }
@@ -0,0 +1,87 @@
1
+ import { list, text, type Field, type Resource } from './api';
2
+ import { Cell, shown, withLabels } from './cell';
3
+ import { useContext } from 'react';
4
+ import { fileUrl, RecordId, type Val } from './field';
5
+ import { markdownToHtml } from './fields/MarkdownEditor';
6
+ import { useT } from './i18n';
7
+ import { Icon } from './icons';
8
+ import { RichView } from './rich';
9
+ import { Labels } from './select';
10
+
11
+ const choosing = (f: Field) => ['select', 'radio', 'checkboxes', 'buttons'].includes(f.type);
12
+
13
+ /** A field of a record that is only shown: its label, and its value as a person reads it. */
14
+ export function Entry({ resource, field: f, value, cells, baseUrl }: { resource: Resource; field: Field; value: Val; cells?: Record<string, unknown>; baseUrl?: string }) {
15
+ const t = useT(), record = useContext(RecordId);
16
+ const prefix = baseUrl ?? `/${resource.name}`;
17
+ const l = f.look ?? {}, all = list(value), url = `${prefix}/options/${f.key}`;
18
+ // A column of the same name knows how the value looks, such as money or a colored badge.
19
+ const column = cells && resource.columns.find((c) => c.key === f.key && c.type !== 'image' && !c.props);
20
+ let body: React.ReactNode;
21
+ if (f.type === 'checkbox' || f.type === 'toggle') {
22
+ const on = value === 'true';
23
+ body = <span className="inline-flex items-center gap-1.5"><span aria-hidden="true" className={'grid size-5 place-items-center rounded-full ' + (on ? 'tone-success' : 'tone-gray')}>
24
+ <Icon name={on ? 'check' : 'x'} className="size-3" strokeWidth={2.5} /></span>{on ? t('table.yes') : t('table.no')}</span>;
25
+ } else if (f.type === 'tags') {
26
+ body = all.length ? <span className="flex flex-wrap gap-1.5">{all.map((v) => <span key={v} className={`badge tone-${l.color ?? 'primary'} px-2 py-0.5 text-xs`}>{v}</span>)}</span>
27
+ : <span data-lk="placeholder" className="muted">—</span>;
28
+ } else if (f.type === 'keyvalue') {
29
+ const entries = value && typeof value === 'object' && !Array.isArray(value) ? Object.entries(value) : [];
30
+ body = entries.length ? <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">{entries.map(([k, v]) => <span key={k} className="contents"><dt className="muted font-medium">{k}</dt><dd className="min-w-0 break-words">{text(v)}</dd></span>)}</dl>
31
+ : <span data-lk="placeholder" className="muted">—</span>;
32
+ } else if (f.type === 'repeater') {
33
+ const rows = Array.isArray(value) ? (value as Record<string, unknown>[]) : [];
34
+ body = rows.length ? <ul className="space-y-1 text-sm">{rows.map((r, i) => <li key={i} className="surface-fill border px-2.5 py-1.5" style={{ borderRadius: 'var(--lk-radius)' }}>{Object.entries(r).map(([k, v]) => `${k}: ${text(v)}`).join(' · ')}</li>)}</ul>
35
+ : <span data-lk="placeholder" className="muted">—</span>;
36
+ } else if (f.type === 'slider') {
37
+ const label = Array.isArray(value) ? `${value[0] ?? ''} – ${value[1] ?? ''}` : text(value);
38
+ body = label ? <span className="tabular-nums">{[l.prefix, label, l.suffix].filter(Boolean).join('')}</span> : <span data-lk="placeholder" className="muted">—</span>;
39
+ } else if (f.type === 'code') {
40
+ const src = text(value);
41
+ body = src ? <pre className="rich-content overflow-x-auto rounded border p-2 font-mono text-xs"><code>{src}</code></pre> : <span data-lk="placeholder" className="muted">—</span>;
42
+ } else if (f.type === 'markdown') {
43
+ const md = text(value);
44
+ body = md ? <RichView html={markdownToHtml(md)} /> : <span data-lk="placeholder" className="muted">—</span>;
45
+ } else if (!all.length) {
46
+ body = <span data-lk="placeholder" className="muted">—</span>;
47
+ } else if (f.type === 'file') {
48
+ body = <ul className="flex flex-wrap gap-3">{all.map((p) => <li key={p}>{f.file?.image
49
+ ? <a href={fileUrl(resource.name, f.key, p, baseUrl, record)} target="_blank" rel="noopener"><img src={fileUrl(resource.name, f.key, p, baseUrl, record)} alt="" className="picture size-24 border object-cover" /></a>
50
+ : <a href={fileUrl(resource.name, f.key, p, baseUrl, record)} target="_blank" rel="noopener" className="underline">{p.split('/').pop()}</a>}</li>)}</ul>;
51
+ } else if (column) {
52
+ body = <Cell column={withLabels(resource, column)} row={cells!} />;
53
+ } else if (choosing(f)) {
54
+ const colors = l.colors;
55
+ body = colors ? <span className="flex flex-wrap gap-1.5">{all.map((v) => <span key={v} className={'badge px-2 py-1 text-xs ' + (colors[v] ? 'tone-' + colors[v] : '')}><Labels url={url} options={f.options} settings={f.select} value={[v]} /></span>)}</span>
56
+ : <Labels url={url} options={f.options} settings={f.select} value={all} />;
57
+ } else if (f.type === 'date' || f.type === 'datetime' || f.type === 'time') {
58
+ body = shown(f.type === 'time' ? `1970-01-01T${text(value)}` : text(value), { format: f.type });
59
+ } else if (f.type === 'rich') {
60
+ body = <RichView html={text(value)} />;
61
+ } else if (f.type === 'textarea') {
62
+ body = <p className="whitespace-pre-wrap">{text(value)}</p>;
63
+ } else if (l.input === 'color') {
64
+ body = <span className="inline-flex items-center gap-2"><span aria-hidden="true" className="swatch size-5 border" style={{ backgroundColor: text(value) }} /><code>{text(value)}</code></span>;
65
+ } else if (l.input === 'password') {
66
+ body = '••••••••';
67
+ } else {
68
+ body = [l.prefix, text(value), l.suffix].filter(Boolean).join(' ');
69
+ }
70
+ return <div data-lk="entry" data-name={f.key} className="min-w-0">
71
+ <div data-lk="label" className="muted text-sm font-medium">{f.label}</div>
72
+ <div data-lk="value" className="mt-1 break-words">{body}</div>
73
+ </div>;
74
+ }
75
+
76
+ /** What a record is called: the first column that holds text, such as an order's number. */
77
+ export function titleOf(resource: Resource, cells: Record<string, unknown> | undefined, id: string) {
78
+ const c = resource.columns.find((x) => (x.type === 'text' || x.type === 'badge') && !x.props && text(cells?.[x.key]) !== '');
79
+ return c ? (withLabels(resource, c).look?.labels?.[text(cells![c.key])] ?? shown(cells![c.key], c.look)) : `#${id}`;
80
+ }
81
+
82
+ /** One of a screen's records, such as Order for Orders. Labels in other languages stay as they are. */
83
+ export function one(label: string) {
84
+ if (/ies$/.test(label)) return label.slice(0, -3) + 'y';
85
+ if (/(ss|us|is)$/.test(label) || !/[a-z]s$/.test(label)) return label;
86
+ return label.slice(0, /(ches|shes|xes|sses)$/.test(label) ? -2 : -1);
87
+ }