@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
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@larakit/react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.1",
4
+ "description": "Larakit's React components and pages for Inertia.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts",
8
+ "./pages": "./src/pages/index.ts",
9
+ "./theme.css": "./theme.css"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "theme.css"
14
+ ],
15
+ "dependencies": {
16
+ "lucide-react": "^1.88.0"
17
+ },
18
+ "peerDependencies": {
19
+ "@inertiajs/react": "^3",
20
+ "@larakit/core": "0.5.1",
21
+ "react": "^19"
22
+ },
23
+ "license": "MIT",
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/larakitdev/larakit.git",
30
+ "directory": "ui/packages/react"
31
+ }
32
+ }
package/src/Cell.tsx ADDED
@@ -0,0 +1,35 @@
1
+ import { shown, text, type Column, type Row } from '@larakit/core';
2
+ import { useLarakit } from './context';
3
+ import { LayoutPart, type ColumnCellProps } from './components';
4
+ import { Badge } from './ui';
5
+
6
+ /**
7
+ * One cell of the table: the column's own `.component(...)`, else the panel's `part("cell", ...)`, else Larakit's
8
+ * drawing. Either way the component gets the column's `.props(...)` as `data`.
9
+ */
10
+ export function Cell({ column, row }: { column: Column; row: Row }) {
11
+ const props = { value: row.cells[column.key], row, column };
12
+ return <LayoutPart part="cell" name={column.component} data={column.props} partKey={column.partKey ?? column.key} props={props} Default={CellView} />;
13
+ }
14
+
15
+ /** Larakit's own drawing of a cell, by the column's type. */
16
+ export function CellView({ column, row }: Pick<ColumnCellProps, 'column' | 'row'>) {
17
+ const cells = row.cells;
18
+ const { locale } = useLarakit();
19
+ const look = column.look ?? {};
20
+ const value = cells[column.key];
21
+ let main;
22
+ if (column.type === 'badge') {
23
+ const raw = text(value);
24
+ main = raw === '' ? <span className="text-(--lk-muted)">{look.placeholder ?? ''}</span> : <Badge color={look.colors?.[raw]}>{look.labels?.[raw] ?? raw}</Badge>;
25
+ } else if (column.type === 'boolean' || column.type === 'bool') {
26
+ main = value === true || value === 'true' ? <span aria-label="yes" className="text-(--lk-success)">✓</span> : <span aria-label="no" className="text-(--lk-muted)">–</span>;
27
+ } else if (column.type === 'image') {
28
+ main = text(value) ? <img src={text(value)} alt="" className="size-8 rounded object-cover" /> : null;
29
+ } else {
30
+ const said = look.labels?.[text(value)] ?? shown(value, look, locale);
31
+ main = <span className={said === look.placeholder ? 'text-(--lk-muted)' : ''}>{said}</span>;
32
+ }
33
+ const below = look.description ? text(cells[column.key + ':description']) : '';
34
+ return below ? <>{main}<span data-lk="description" className="block text-xs text-(--lk-muted)">{below}</span></> : main;
35
+ }
@@ -0,0 +1,79 @@
1
+ import { useMemo, type ReactNode } from 'react';
2
+ import { Link } from '@inertiajs/react';
3
+ import { shown, type Stat, type Widget } from '@larakit/core';
4
+ import { LayoutPart, type DashboardProps, type PartOwn, type StatProps, type WidgetProps } from './components';
5
+ import { useLarakit } from './context';
6
+ import { Loading } from './ui';
7
+
8
+ /**
9
+ * What each widget shows, by its name: a stats widget's numbers as `{ stats: [...] }`. A widget without its data
10
+ * yet shows the `loading` part.
11
+ */
12
+ export type WidgetData = Record<string, { stats?: Stat[] } | undefined>;
13
+
14
+ /**
15
+ * The dashboard: its widgets in a grid, through the `dashboard`, `widget` and `stat` parts. Larakit draws a stats
16
+ * widget's numbers; the charts and lists come with the dashboard page.
17
+ */
18
+ export function Dashboard({ widgets, data }: { widgets: Widget[]; data: WidgetData }) {
19
+ const Widget = useMemo(() => function OneWidget({ widget }: { widget: Widget }) {
20
+ return <WidgetBox widget={widget} data={data[widget.name]} />;
21
+ }, [data]);
22
+ return <LayoutPart part="dashboard" Default={DefaultDashboard} props={{ widgets, Widget }} />;
23
+ }
24
+
25
+ /** One widget, with what it shows. */
26
+ function WidgetBox({ widget, data }: { widget: Widget; data: WidgetData[string] }) {
27
+ let children: ReactNode;
28
+ if (data === undefined) children = <LayoutPart part="loading" Default={Loading} props={{ kind: 'widget' }} />;
29
+ else if (data.stats) children = <Stats stats={data.stats} />;
30
+ else children = null;
31
+ return <LayoutPart part="widget" Default={DefaultWidget} props={{ widget, children }} />;
32
+ }
33
+
34
+ /** A stats widget's numbers, each through the `stat` part. */
35
+ function Stats({ stats }: { stats: Stat[] }) {
36
+ const { path } = useLarakit();
37
+ return (
38
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
39
+ {stats.map((stat, i) => {
40
+ const href = stat.href ? (/^(https?:)?\/\//.test(stat.href) ? stat.href : `${path}/${stat.href}`) : stat.screen ? `${path}/${stat.screen}` : undefined;
41
+ return <LayoutPart key={i} part="stat" Default={DefaultStat} props={{ stat, href }} />;
42
+ })}
43
+ </div>
44
+ );
45
+ }
46
+
47
+ /** Larakit's dashboard: the widgets in two columns, a wide one across both. */
48
+ export function DefaultDashboard({ widgets, Widget }: PartOwn<DashboardProps>) {
49
+ return (
50
+ <div data-lk="dashboard" className="grid gap-6 lg:grid-cols-2">
51
+ {widgets.map((w) => <div key={w.name} className={w.wide ? 'lg:col-span-2' : ''}><Widget widget={w} /></div>)}
52
+ </div>
53
+ );
54
+ }
55
+
56
+ /** Larakit's widget: a card with its label. */
57
+ export function DefaultWidget({ widget, children }: PartOwn<WidgetProps>) {
58
+ return (
59
+ <section data-lk="widget" data-key={widget.name} className="rounded-(--lk-radius) bg-(--lk-surface) p-4 ring-1 ring-(--lk-border)">
60
+ <h2 className="mb-3 text-sm font-semibold">{widget.label}</h2>
61
+ {children}
62
+ </section>
63
+ );
64
+ }
65
+
66
+ /** Larakit's number: its label, the value and the note, a link when it has one. */
67
+ export function DefaultStat({ stat, href }: PartOwn<StatProps>) {
68
+ const { locale } = useLarakit();
69
+ const value = typeof stat.value === 'number' ? shown(stat.value, {}, locale) : String(stat.value ?? '');
70
+ const body = (
71
+ <>
72
+ <p className="text-xs text-(--lk-muted)">{stat.label}</p>
73
+ <p className="mt-1 text-2xl font-semibold">{value}</p>
74
+ {stat.note && <p className="mt-1 text-xs text-(--lk-muted)">{stat.note}</p>}
75
+ </>
76
+ );
77
+ const look = 'block rounded-(--lk-radius) p-3 ring-1 ring-(--lk-border)';
78
+ return href ? <Link data-lk="stat" href={href} className={look + ' hover:bg-black/2'}>{body}</Link> : <div data-lk="stat" className={look}>{body}</div>;
79
+ }
package/src/Field.tsx ADDED
@@ -0,0 +1,132 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { json, list, text, type Choice, type Field as FieldSpec } from '@larakit/core';
3
+ import { LayoutPart, Part, type FieldProps as FieldPartProps, type PartOwn } from './components';
4
+ import { FileInput } from './FileInput';
5
+ import { Repeater } from './Repeater';
6
+
7
+ const input = 'block w-full rounded-(--lk-radius) border-0 bg-(--lk-surface) px-3 py-1.5 text-sm text-(--lk-text) ring-1 ring-inset ring-(--lk-border) focus:ring-2 focus:ring-(--lk-primary) aria-[invalid=true]:ring-(--lk-danger)';
8
+
9
+ export type FieldArgs = {
10
+ field: FieldSpec;
11
+ value: unknown;
12
+ set: (value: unknown) => void;
13
+ error?: string;
14
+ required?: boolean;
15
+ disabled?: boolean;
16
+ /** The screen's JSON endpoints, `/admin/api/orders`: a select's options, a file's uploads and files. In an action's form, the action's address. */
17
+ api?: string;
18
+ /** The record the form edits, so a file it already has can be shown. */
19
+ record?: string;
20
+ /** Every error of the form, as Inertia gives them: a repeater finds its rows' errors here, as `items.0.sku`. */
21
+ errors?: Record<string, string>;
22
+ /** The input's id; a repeater gives each row's fields their own. */
23
+ id?: string;
24
+ /** The field's place in the form's errors: `items.0.sku` for a field of a repeater row. */
25
+ path?: string;
26
+ };
27
+
28
+ /**
29
+ * A field of a form: its label, input, helper and error. The field's own `.component(...)` draws the input; the
30
+ * panel's `part("field", ...)` draws everything around it.
31
+ */
32
+ export function Field({ field: f, value, set, error, required, disabled, api, record, errors, id = 'lk-' + f.key, path = f.key }: FieldArgs) {
33
+ const errorId = id + '-error';
34
+ const look = f.look ?? {};
35
+ const options = api ? api + '/options' : undefined;
36
+ const input = { id, field: f, value, set, invalid: !!error, describedBy: error ? errorId : undefined, required, disabled: disabled || look.readOnly, options, api, record, errors, path };
37
+ const control = <Part name={f.component} data={f.props} partKey={f.partKey ?? f.key} props={input} Default={Control} />;
38
+ if (f.type === 'hidden') return null;
39
+ return (
40
+ <LayoutPart part="field" data={f.props} partKey={f.partKey ?? f.key} Default={FieldFrame}
41
+ props={{ field: f, id, path, error, required, disabled: disabled || look.readOnly, children: control }} />
42
+ );
43
+ }
44
+
45
+ /** Larakit's frame of a field: the label, the input, the helper and the error. */
46
+ export function FieldFrame({ field: f, id, path, error, required, children, partKey }: PartOwn<FieldPartProps>) {
47
+ const errorId = id + '-error';
48
+ const look = f.look ?? {};
49
+ const check = f.type === 'toggle' || f.type === 'checkbox';
50
+ const control = children;
51
+ return (
52
+ <div data-lk="field" data-key={partKey ?? f.key} data-path={path} style={look.span === 12 ? { gridColumn: '1 / -1' } : undefined} className={f.type === 'textarea' ? 'sm:col-span-full' : ''}>
53
+ {check ? (
54
+ <label htmlFor={id} className="flex items-center gap-2 text-sm font-medium">{control}{f.label}</label>
55
+ ) : (
56
+ <>
57
+ <label htmlFor={id} className="mb-1 block text-sm font-medium">{f.label}{required && <span className="text-(--lk-danger)"> *</span>}</label>
58
+ {control}
59
+ </>
60
+ )}
61
+ {look.helper && <p className="mt-1 text-xs text-(--lk-muted)">{look.helper}</p>}
62
+ {error && <p id={errorId} className="mt-1 text-xs text-(--lk-danger)">{error}</p>}
63
+ </div>
64
+ );
65
+ }
66
+
67
+ export type ControlProps = {
68
+ id: string; field: FieldSpec; value: unknown; set: (value: unknown) => void; invalid: boolean; describedBy?: string; required?: boolean; disabled?: boolean;
69
+ /** Where a select that asks the server gets its options: the screen's `/api/{screen}/options`. */
70
+ options?: string;
71
+ api?: string; record?: string; errors?: Record<string, string>; path?: string;
72
+ };
73
+
74
+ /** Larakit's own input of a field, which an application's field component gets as `Default`. */
75
+ export function Control(props: ControlProps) {
76
+ const { id, field: f, value, set, invalid, describedBy, required, disabled, options } = props;
77
+ if (f.type === 'repeater') return <Repeater {...props} />;
78
+ if (f.type === 'file') return <FileInput {...props} />;
79
+ const look = f.look ?? {};
80
+ const common = { id, 'aria-invalid': invalid, 'aria-describedby': describedBy, required, disabled };
81
+ if (f.type === 'toggle' || f.type === 'checkbox') {
82
+ return <input type="checkbox" role={f.type === 'toggle' ? 'switch' : undefined} checked={value === true || value === 'true'} onChange={(e) => set(e.target.checked)} {...common} className="size-4 accent-(--lk-primary)" />;
83
+ }
84
+ if (f.type === 'textarea') {
85
+ return <textarea rows={look.rows ?? 3} value={text(value)} placeholder={look.placeholder} onChange={(e) => set(e.target.value)} {...common} className={input} />;
86
+ }
87
+ if (f.type === 'select' || f.type === 'radio') {
88
+ return <Select field={f} value={value} set={set} url={options ? options + '/' + f.key : ''} {...common} />;
89
+ }
90
+ const kind = f.type === 'date' ? 'date' : f.type === 'datetime' ? 'datetime-local' : f.type === 'time' ? 'time' : look.input === 'password' ? 'password' : look.input ?? 'text';
91
+ const shownValue = f.type === 'datetime' ? text(value).slice(0, 16) : f.type === 'date' ? text(value).slice(0, 10) : text(value);
92
+ const field = <input type={kind} value={shownValue} placeholder={look.placeholder} step={look.step as number | undefined} min={look.min as number | undefined} max={look.max as number | undefined} onChange={(e) => set(e.target.value)} {...common} className={input} />;
93
+ if (!look.prefix && !look.suffix) return field;
94
+ return (
95
+ <div className="flex items-center gap-2">
96
+ {look.prefix && <span className="text-sm text-(--lk-muted)">{look.prefix}</span>}
97
+ {field}
98
+ {look.suffix && <span className="text-sm text-(--lk-muted)">{look.suffix}</span>}
99
+ </div>
100
+ );
101
+ }
102
+
103
+ /** A select. One that asks the server loads its options from the JSON endpoint, which stays for this. */
104
+ export function Select({ field: f, value, set, url, id, disabled, required, ...aria }: { field: FieldSpec; value: unknown; set: (v: unknown) => void; url: string; id: string; disabled?: boolean; required?: boolean; 'aria-invalid': boolean; 'aria-describedby'?: string }) {
105
+ const [asked, setAsked] = useState<Choice[] | null>(null);
106
+ const remote = Boolean(f.select?.remote) && !f.options?.length && url !== '';
107
+ useEffect(() => {
108
+ if (!remote) return;
109
+ const stop = new AbortController();
110
+ // The chosen values come first, so their labels are known; then the first page of the rest.
111
+ const chosen = list(value).map((v) => 'value=' + encodeURIComponent(v)).join('&');
112
+ Promise.all([
113
+ chosen ? json<{ options: Choice[] }>(`${url}?${chosen}`, { signal: stop.signal }) : Promise.resolve({ options: [] }),
114
+ json<{ options: Choice[] }>(url, { signal: stop.signal }),
115
+ ]).then(([a, b]) => {
116
+ const seen = new Set<string>();
117
+ setAsked([...a.options, ...b.options].filter((o) => !seen.has(String(o.value)) && seen.add(String(o.value))));
118
+ }, () => {});
119
+ return () => stop.abort();
120
+ }, [remote, url]);
121
+ const choices = remote ? asked ?? [] : f.options ?? [];
122
+ const multiple = Boolean(f.select?.multiple);
123
+ return (
124
+ <select id={id} multiple={multiple} disabled={disabled} required={required} {...aria}
125
+ value={multiple ? list(value) : text(value)}
126
+ onChange={(e) => set(multiple ? [...e.target.selectedOptions].map((o) => o.value) : e.target.value)}
127
+ className={input}>
128
+ {!multiple && <option value="">{f.select?.placeholder ?? '—'}</option>}
129
+ {choices.map((o) => <option key={String(o.value)} value={String(o.value)} disabled={o.disabled}>{o.label}</option>)}
130
+ </select>
131
+ );
132
+ }
@@ -0,0 +1,76 @@
1
+ import { useState } from 'react';
2
+ import { list, RequestError, upload } from '@larakit/core';
3
+ import { useLarakit } from './context';
4
+ import type { ControlProps } from './Field';
5
+ import { Button } from './ui';
6
+
7
+ const bytes = (n: number) => (n >= 1048576 ? `${+(n / 1048576).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`);
8
+
9
+ /**
10
+ * Larakit's file field. A chosen file goes at once to `uploads/{field}` under `api` (the screen's, or the action's for
11
+ * an action's form), which checks its
12
+ * size and kind and keeps it for this visitor; the form then sends only its path, as JSON, with the other fields.
13
+ * So a form that fails on another field doesn't send the file again, and the record's own endpoint stays JSON.
14
+ */
15
+ export function FileInput({ id, field: f, value, set, invalid, describedBy, required, disabled, api, record }: ControlProps) {
16
+ const { t } = useLarakit();
17
+ const s = f.file ?? { maxSize: 10240 };
18
+ const many = Boolean(s.multiple);
19
+ const chosen = list(value);
20
+ const [busy, setBusy] = useState(0);
21
+ const [problem, setProblem] = useState('');
22
+ const [names, setNames] = useState<Record<string, string>>({});
23
+ const room = many ? (s.maxFiles ? s.maxFiles - chosen.length : Infinity) : 1;
24
+ // A kind such as "pdf" is an extension to the browser.
25
+ const accept = s.accept?.map((k) => (k.includes('/') || k.startsWith('.') ? k : '.' + k)).join(',');
26
+ const link = (p: string) => api && `${api}/files/${f.key}?${new URLSearchParams(record ? { path: p, record } : { path: p })}`;
27
+
28
+ async function add(files: FileList | null) {
29
+ if (!files?.length || !api) return;
30
+ setProblem('');
31
+ let now = many ? chosen : [];
32
+ for (const file of [...files].slice(0, Math.max(0, room === Infinity ? files.length : room))) {
33
+ if (file.size > s.maxSize * 1024) {
34
+ setProblem(t('form.fileTooLarge', '{name} is larger than {max}.', { name: file.name, max: bytes(s.maxSize * 1024) }));
35
+ continue;
36
+ }
37
+ setBusy((n) => n + 1);
38
+ try {
39
+ const done = await upload(`${api}/uploads/${f.key}`, file);
40
+ setNames((old) => ({ ...old, [done.value]: done.name }));
41
+ now = many ? [...now, done.value] : [done.value];
42
+ set(many ? now : done.value);
43
+ } catch (e) {
44
+ setProblem(e instanceof RequestError && e.errors.file ? e.errors.file.join(' ') : e instanceof Error ? e.message : String(e));
45
+ } finally {
46
+ setBusy((n) => n - 1);
47
+ }
48
+ }
49
+ }
50
+
51
+ return (
52
+ <div data-lk="files" className="space-y-2">
53
+ {chosen.length > 0 && (
54
+ <ul className="space-y-2">
55
+ {chosen.map((p) => (
56
+ <li key={p} data-lk="file" className="flex items-center gap-3">
57
+ {s.image && link(p) && <img src={link(p)} alt="" className="size-12 rounded object-cover ring-1 ring-(--lk-border)" />}
58
+ <a href={link(p)} target="_blank" rel="noopener" className="min-w-0 flex-1 truncate text-sm underline">{names[p] ?? p.split('/').pop()}</a>
59
+ {!disabled && <Button data-lk="remove-file" tone="danger" onClick={() => set(many ? chosen.filter((x) => x !== p) : '')}>{t('form.remove', 'Remove')}</Button>}
60
+ </li>
61
+ ))}
62
+ </ul>
63
+ )}
64
+ {!disabled && room > 0 && (
65
+ <label className="flex cursor-pointer flex-col items-center gap-1 rounded-(--lk-radius) px-4 py-5 text-center text-sm ring-1 ring-dashed ring-(--lk-border) hover:bg-black/2">
66
+ <span className="font-medium underline-offset-2 hover:underline">{t(many ? 'form.chooseFiles' : 'form.chooseFile', many ? 'Choose files' : 'Choose a file')}</span>
67
+ <span className="text-xs text-(--lk-muted)">{t('form.maxSizeLimit', 'Max {size}', { size: bytes(s.maxSize * 1024) })}</span>
68
+ <input id={id} type="file" className="sr-only" accept={accept} multiple={many} aria-invalid={invalid} aria-describedby={describedBy}
69
+ aria-required={(required && !chosen.length) || undefined} onChange={(e) => { void add(e.target.files); e.target.value = ''; }} />
70
+ </label>
71
+ )}
72
+ {busy > 0 && <p role="status" className="text-xs text-(--lk-muted)">{t('form.uploading', 'Uploading…')}</p>}
73
+ {problem && <p role="alert" data-lk="file-error" className="text-xs text-(--lk-danger)">{problem}</p>}
74
+ </div>
75
+ );
76
+ }
package/src/Form.tsx ADDED
@@ -0,0 +1,116 @@
1
+ import { useRef, useState, type ReactNode } from 'react';
2
+ import { disabled, holds, required, visible, type Field as FieldSpec, type FormMode, type Group, type Place } from '@larakit/core';
3
+ import { LayoutPart, Part, type FormProps, type PartOwn, type SectionProps } from './components';
4
+ import { Field } from './Field';
5
+ import { Tabs } from './ui';
6
+
7
+ export type FormArgs = {
8
+ fields: FieldSpec[];
9
+ items?: Place[];
10
+ columns?: number;
11
+ mode: FormMode;
12
+ values: Record<string, unknown>;
13
+ set: (key: string, value: unknown) => void;
14
+ errors: Record<string, string>;
15
+ /** The screen's JSON endpoints, `/admin/api/orders`: a select's options, a file's uploads. */
16
+ api?: string;
17
+ /** The record the form edits. */
18
+ record?: string;
19
+ };
20
+
21
+ const grid = (columns = 1) => (columns >= 3 ? 'grid gap-4 sm:grid-cols-3' : columns === 2 ? 'grid gap-4 sm:grid-cols-2' : 'grid gap-4');
22
+
23
+ /**
24
+ * The fields of a form, in the screen's layout: sections, grids and tabs, each with its columns. The panel's
25
+ * `part("form", ...)` can draw the whole form.
26
+ */
27
+ export function Form({ fields, items, columns, ...rest }: FormArgs) {
28
+ const byKey = new Map(fields.map((f) => [f.key, f]));
29
+ const places = items?.length ? items : fields.map((f) => ({ field: f.key }));
30
+ const latest = useRef({ byKey, ...rest });
31
+ latest.current = { byKey, ...rest };
32
+ // One field by its key, for an application's form that lays the fields out itself. It reads the latest values.
33
+ const [OneField] = useState(() => function FormField({ name }: { name: string }) {
34
+ return <PlaceView place={{ field: name }} {...latest.current} />;
35
+ });
36
+ const children = <div className={grid(columns)}>{places.map((p, i) => <PlaceView key={i} place={p} byKey={byKey} {...rest} />)}</div>;
37
+ return <LayoutPart part="form" Default={DefaultForm}
38
+ props={{ fields, mode: rest.mode, values: rest.values, errors: rest.errors, children, Field: OneField }} />;
39
+ }
40
+
41
+ /** Larakit's form: the fields in their layout. */
42
+ export function DefaultForm({ children }: PartOwn<FormProps>) {
43
+ return <div data-lk="form">{children}</div>;
44
+ }
45
+
46
+ type PlaceArgs = Omit<FormArgs, 'fields' | 'items' | 'columns'> & { place: Place; byKey: Map<string, FieldSpec> };
47
+
48
+ function PlaceView({ place, byKey, mode, values, set, errors, api, record }: PlaceArgs): ReactNode {
49
+ if ('field' in place) {
50
+ const f = byKey.get(place.field);
51
+ if (!f || !visible(f, mode, values)) return null;
52
+ return <Field field={f} value={values[f.key]} set={(v) => set(f.key, v)} error={errors[f.key]} errors={errors} required={required(f, values)} disabled={disabled(f, mode, values)} api={api} record={record} />;
53
+ }
54
+ if (!holds(place.visibleWhen, values)) return null;
55
+ const rest = { byKey, mode, values, set, errors, api, record };
56
+ if (place.type === 'tabs' && !place.component) return <TabsGroup group={place} {...rest} />;
57
+ const children = place.items.map((p, i) => <PlaceView key={i} place={p} {...rest} />);
58
+ const props = { heading: place.heading, description: place.description, place, children };
59
+ const partKey = place.partKey ?? place.heading ?? place.type;
60
+ // A card-like group can be drawn by the panel's `part("section", ...)`; the group's own component comes first.
61
+ if (cards.includes(place.type)) return <LayoutPart part="section" name={place.component} data={place.props} partKey={partKey} props={props} Default={GroupView} />;
62
+ return <Part name={place.component} data={place.props} partKey={partKey} props={props} Default={GroupView} />;
63
+ }
64
+
65
+ /** The groups that the `section` part draws: a card with a heading. */
66
+ const cards = ['section', 'fieldset', 'step'];
67
+
68
+ /** The keys of the fields in a group, at any depth. */
69
+ function keysIn(places: Place[]): string[] {
70
+ return places.flatMap((p) => ('field' in p ? [p.field] : keysIn(p.items)));
71
+ }
72
+
73
+ /** A group of tabs: one tab open, through the `tabs` part. A tab with an error says so. */
74
+ function TabsGroup({ group, ...rest }: Omit<PlaceArgs, 'place'> & { group: Group }) {
75
+ const tabs = group.items.filter((p): p is Group => !('field' in p) && holds(p.visibleWhen, rest.values));
76
+ const names = tabs.map((tab, i) => tab.partKey ?? tab.heading ?? String(i));
77
+ const [active, setActive] = useState(names[0] ?? '');
78
+ const open = tabs[Math.max(names.indexOf(active), 0)];
79
+ return (
80
+ <div data-key={group.partKey} className="col-span-full">
81
+ <LayoutPart part="tabs" Default={Tabs} props={{
82
+ tabs: tabs.map((tab, i) => ({
83
+ name: names[i], label: tab.heading ?? `#${i + 1}`, badge: tab.badge, color: tab.badgeColor,
84
+ wrong: keysIn(tab.items).some((k) => Object.keys(rest.errors).some((e) => e === k || e.startsWith(k + '.'))),
85
+ })),
86
+ active: names[Math.max(names.indexOf(active), 0)] ?? '',
87
+ select: setActive,
88
+ children: open ? <PlaceView place={open.component ? open : { ...open, type: 'grid' }} {...rest} /> : null,
89
+ }} />
90
+ </div>
91
+ );
92
+ }
93
+
94
+ type GroupArgs = Omit<SectionProps<unknown>, 'data' | 'Default' | 'partKey'> & { partKey?: string };
95
+
96
+ /** Larakit's own drawing of a group: a card with a heading, or the fields in a grid. */
97
+ function GroupView(props: GroupArgs) {
98
+ const { place, children, partKey } = props;
99
+ if (place.type === 'section' || place.type === 'fieldset' || place.type === 'tab' || place.type === 'step') return <Section {...props} />;
100
+ return <div data-lk="group" data-key={partKey} className={'col-span-full ' + grid(place.columns)}>{children}</div>;
101
+ }
102
+
103
+ /** Larakit's section: a card with a heading. An application's own component can draw it with a heading of its own. */
104
+ export function Section({ heading, description, place, children, partKey }: GroupArgs) {
105
+ return (
106
+ <section data-lk="section" data-key={partKey} className="col-span-full rounded-(--lk-radius) ring-1 ring-(--lk-border)">
107
+ {heading && (
108
+ <header className="border-b border-(--lk-border) px-4 py-2.5">
109
+ <h3 className="text-sm font-semibold">{heading}</h3>
110
+ {description && <p className="text-xs text-(--lk-muted)">{description}</p>}
111
+ </header>
112
+ )}
113
+ <div className={'p-4 ' + grid(place.columns)}>{children}</div>
114
+ </section>
115
+ );
116
+ }