@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,449 @@
1
+ import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
2
+ import { api, ApiError, base, fail, list, text, type Choice, type Condition, type Field } from './api';
3
+ import { useT } from './i18n';
4
+ import { InlineSkeleton, useDelayed } from './loading';
5
+ import { field as fieldPart, Guard, Slot, type Parts } from './plugins';
6
+ import { DatePicker } from './picker';
7
+ import { RichEditor } from './rich';
8
+ import { Icon } from './icons';
9
+ import { Part as PartOf } from '../components';
10
+ import { KitDefault } from './bridge';
11
+ import { FieldSelect, RecordId, useLabels } from './select';
12
+ import { CodeEditor } from './fields/CodeEditor';
13
+ import { KeyValue } from './fields/KeyValue';
14
+ import { MarkdownEditor } from './fields/MarkdownEditor';
15
+ import { OneTimeCode } from './fields/OneTimeCode';
16
+ import { Repeater, type RepeaterItem } from './fields/Repeater';
17
+ import { Slider } from './fields/Slider';
18
+ import { TagsInput } from './fields/TagsInput';
19
+
20
+ /** What a field holds in the browser: text, list of texts, key-value map, or repeater rows. */
21
+ export type Val = string | string[] | Record<string, string> | Record<string, unknown>[];
22
+ export type Vals = Record<string, Val>;
23
+ /** The server's own value for a text, such as a number for "1". */
24
+ export type Known = Record<string, unknown>;
25
+
26
+ const check = (f: Field) => f.type === 'checkbox' || f.type === 'toggle';
27
+ const options = (f: Field) => ['select', 'radio', 'checkboxes', 'buttons'].includes(f.type);
28
+ const picker = (f: Field) => f.type === 'datetime' || f.type === 'time' || f.type === 'date';
29
+ const two = (n: number) => String(n).padStart(2, '0');
30
+
31
+ /** A moment in this person's time zone, as a datetime-local input wants it. */
32
+ function local(v: string, seconds?: boolean) {
33
+ const d = new Date(v);
34
+ if (Number.isNaN(d.getTime())) return '';
35
+ return `${String(d.getFullYear()).padStart(4, '0')}-${two(d.getMonth() + 1)}-${two(d.getDate())}T${two(d.getHours())}:${two(d.getMinutes())}${seconds ? ':' + two(d.getSeconds()) : ''}`;
36
+ }
37
+
38
+ /** Turns what the server sent into what the form holds, and remembers the server's own value. */
39
+ export function toForm(f: Field, v: unknown, know: (shown: string, own: unknown) => void): Val {
40
+ if (f.type === 'file') return f.file?.multiple ? list(v) : text(v);
41
+ if (f.type === 'tags') return list(v);
42
+ if (f.type === 'keyvalue') {
43
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
44
+ return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, val]) => [String(k), text(val)]));
45
+ }
46
+ return {};
47
+ }
48
+ if (f.type === 'repeater') {
49
+ const subFields = f.look?.fields ?? [];
50
+ if (!Array.isArray(v)) return [];
51
+ return v.map((row) => {
52
+ const src = row && typeof row === 'object' ? (row as Record<string, unknown>) : {};
53
+ const out: Record<string, unknown> = { ...src };
54
+ for (const cf of subFields) {
55
+ const has = cf.key in src && src[cf.key] !== undefined;
56
+ out[cf.key] = toForm(cf, has ? src[cf.key] : cf.default, () => {});
57
+ }
58
+ return out;
59
+ });
60
+ }
61
+ if (f.type === 'slider') {
62
+ const minVal = f.look?.min !== undefined && f.look?.min !== null ? String(f.look.min) : '0';
63
+ const maxVal = f.look?.max !== undefined && f.look?.max !== null ? String(f.look.max) : '100';
64
+ if (f.look?.range) {
65
+ if (Array.isArray(v)) {
66
+ const a = v[0] !== undefined && v[0] !== null && v[0] !== '' ? String(v[0]) : minVal;
67
+ const b = v[1] !== undefined && v[1] !== null && v[1] !== '' ? String(v[1]) : maxVal;
68
+ return [a, b];
69
+ }
70
+ if (typeof v === 'string' && v.includes(',')) {
71
+ const [a = '', b = ''] = v.split(',');
72
+ return [a.trim() || minVal, b.trim() || maxVal];
73
+ }
74
+ return [minVal, maxVal];
75
+ }
76
+ return v === undefined || v === null || v === '' ? minVal : text(v);
77
+ }
78
+ if (check(f)) return v === true || v === 'true' || v === 1 ? 'true' : 'false';
79
+ if (options(f)) {
80
+ const all = Array.isArray(v) ? v : v === undefined || v === null || v === '' ? [] : [v];
81
+ for (const x of all) know(String(x), x);
82
+ return f.select?.multiple ? all.map(String) : text(all[0]);
83
+ }
84
+ const t = text(v);
85
+ if (!picker(f) || !t) return t;
86
+ const shown = f.type === 'datetime' ? local(t, f.look?.seconds) : f.type === 'date' ? t.slice(0, 10) : t.slice(0, f.look?.seconds ? 8 : 5);
87
+ // The form may show less than there is, such as no seconds. Unchanged, it goes back as it came.
88
+ if (shown) know(shown, v);
89
+ return shown;
90
+ }
91
+
92
+ /** Turns what the form holds into what the server gets. */
93
+ export function toSend(f: Field, v: Val, known: Known = {}): unknown {
94
+ if (f.type === 'tags') return Array.isArray(v) ? v.map(String) : list(v);
95
+ if (f.type === 'keyvalue') {
96
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
97
+ return Object.fromEntries(Object.entries(v).filter(([k]) => k !== '').map(([k, val]) => [k, text(val)]));
98
+ }
99
+ return {};
100
+ }
101
+ if (f.type === 'repeater') {
102
+ const subFields = f.look?.fields ?? [];
103
+ if (!Array.isArray(v)) return [];
104
+ return v.map((row) => {
105
+ const src = row && typeof row === 'object' ? (row as Record<string, unknown>) : {};
106
+ const out: Record<string, unknown> = { ...src };
107
+ for (const cf of subFields) {
108
+ out[cf.key] = toSend(cf, (src[cf.key] ?? '') as Val);
109
+ }
110
+ return out;
111
+ });
112
+ }
113
+ if (f.type === 'slider') {
114
+ const toNum = (raw: unknown) => {
115
+ const s = text(raw);
116
+ if (s === '') return null;
117
+ const n = Number(s);
118
+ return Number.isFinite(n) && (!Number.isInteger(n) || Number.isSafeInteger(n)) ? n : s;
119
+ };
120
+ if (f.look?.range) {
121
+ const pair = Array.isArray(v) ? v : list(v);
122
+ return pair.map((x) => toNum(x));
123
+ }
124
+ return toNum(v);
125
+ }
126
+ if (check(f)) return v === 'true';
127
+ if (options(f)) {
128
+ const of = (x: string) => f.options?.find((o) => String(o.value) === x)?.value ?? known[x] ?? x;
129
+ return Array.isArray(v) ? v.map((x) => of(String(x))) : v ? of(String(v)) : '';
130
+ }
131
+ if (picker(f)) {
132
+ if (!v) return null;
133
+ if (known[String(v)] !== undefined) return known[String(v)];
134
+ if (f.type !== 'datetime') return v;
135
+ const d = new Date(String(v));
136
+ return Number.isNaN(d.getTime()) ? v : d.toISOString().replace('.000Z', 'Z');
137
+ }
138
+ if (f.look?.input === 'number') {
139
+ const n = Number(v);
140
+ return v === '' ? null : Number.isFinite(n) && (!Number.isInteger(n) || Number.isSafeInteger(n)) ? n : v;
141
+ }
142
+ return v;
143
+ }
144
+
145
+ /** Whether all conditions hold. */
146
+ export const holds = (when: Condition[] | undefined, values: Record<string, unknown>) => (when ?? []).every((c) => {
147
+ const raw = values[c.field];
148
+ const now = raw && typeof raw === 'object' && !Array.isArray(raw) ? Object.keys(raw) : list(raw);
149
+ const yes = c.values ? now.some((v) => c.values!.includes(v)) || (!now.length && c.values.includes('')) : now.some((v) => v !== 'false');
150
+ return yes !== !!c.not;
151
+ });
152
+
153
+ /** Shapes a text: 9 is a digit, a is a letter, * is either. */
154
+ export function shape(pattern: string, typed: string) {
155
+ let out = '', i = 0;
156
+ const fits: Record<string, RegExp> = { 9: /\d/, a: /\p{L}/u, '*': /[\p{L}\d]/u };
157
+ for (const p of pattern) {
158
+ if (i >= typed.length) break;
159
+ if (fits[p]) {
160
+ while (i < typed.length && !fits[p].test(typed[i])) i++;
161
+ if (i >= typed.length) break;
162
+ out += typed[i++];
163
+ } else {
164
+ out += p;
165
+ if (typed[i] === p) i++;
166
+ }
167
+ }
168
+ return out;
169
+ }
170
+
171
+ type Props = { id: string; url: string; uploadUrl?: string; fileBaseUrl?: string;
172
+ /** The JSON endpoints an application's field component gets as `api`: the screen's, or the action's for an action's form. */ api?: string; field: Field; value: Val; set: (v: Val) => void; invalid: boolean; describedBy?: string; required: boolean; onKnown: (c: Choice[]) => void; labelledBy?: string };
173
+ const columns = (n?: number) => (n ? { className: 'choice-grid', style: { '--cols': n } as React.CSSProperties } : {});
174
+
175
+ function TextBox({ id, field: f, value, set, invalid, describedBy, required }: Props) {
176
+ const t = useT();
177
+ const l = f.look ?? {}, [shown, show] = useState(false), [copied, setCopied] = useState(false);
178
+ const kind = f.type === 'datetime' ? 'datetime-local' : f.type === 'date' || f.type === 'time' ? f.type : l.input === 'password' && shown ? 'text' : l.input ?? 'text';
179
+ if (kind === 'color') {
180
+ return <div data-lk="color-field" className="flex items-center gap-2">
181
+ <input id={id} type="color" className="h-10 w-14 shrink-0 cursor-pointer rounded border border-[var(--lk-border)] bg-transparent p-1" value={String(value) || '#0e7a4d'} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required || undefined} onChange={(e) => set(e.target.value)} />
182
+ <input type="text" aria-label={f.label} className="input font-mono text-sm" value={String(value)} placeholder={l.placeholder || '#0e7a4d'} readOnly={l.readOnly} onChange={(e) => set(e.target.value)} />
183
+ </div>;
184
+ }
185
+ const framed = !!(l.prefix || l.suffix || l.revealable || l.copyable);
186
+ // A moment is written in UTC, the input is in this person's time.
187
+ const limit = (v: unknown) => (v === undefined ? undefined : f.type === 'datetime' ? local(String(v), l.seconds) : String(v));
188
+ const input = <input id={id} type={kind} className={framed ? 'bare min-w-0 flex-1 px-3 py-2' : 'input'} value={String(value)} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required || undefined}
189
+ placeholder={l.placeholder} readOnly={l.readOnly} inputMode={l.inputMode as 'text'} autoComplete={l.autocomplete} autoCapitalize={l.autocapitalize} min={limit(l.min)} max={limit(l.max)} step={l.step !== undefined ? String(l.step) : picker(f) && l.seconds ? 1 : l.input === 'number' ? 'any' : undefined}
190
+ minLength={l.minLength} maxLength={l.maxLength} list={l.datalist ? id + '-list' : undefined} onChange={(e) => set(l.mask ? shape(l.mask, e.target.value) : e.target.value)} />;
191
+ const copy = () => navigator.clipboard?.writeText(String(value)).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }, () => {});
192
+ return <>
193
+ {framed ? <div className="input frame flex items-center !p-0" aria-invalid={invalid}>
194
+ {l.prefix && <span data-lk="prefix" className="muted pl-3 whitespace-nowrap">{l.prefix}</span>}{input}{l.suffix && <span data-lk="suffix" className="muted pr-3 whitespace-nowrap">{l.suffix}</span>}
195
+ {l.revealable && <button type="button" data-lk="reveal" className="icon-btn mr-2" aria-pressed={shown} aria-label={t('form.showPassword')} onClick={() => show(!shown)}><Icon name={shown ? 'eye-off' : 'eye'} className="size-4" /></button>}
196
+ {l.copyable && <button type="button" data-lk="copy" className="icon-btn mr-2" aria-label={copied ? t('table.copied') : t('table.copy')} onClick={copy}><Icon name={copied ? 'check' : 'copy'} className="size-4" /></button>}
197
+ {l.copyable && <span role="status" className="sr-only">{copied ? t('table.copied') : ''}</span>}
198
+ </div> : input}
199
+ {l.datalist && <datalist id={id + '-list'}>{l.datalist.map((t) => <option key={t} value={t} />)}</datalist>}
200
+ </>;
201
+ }
202
+
203
+ /** Options that are all in sight: a radio, a checkbox list or buttons. */
204
+ function Choices({ id, url, field: f, value, set, invalid, describedBy, required, onKnown, labelledBy }: Props) {
205
+ const t = useT();
206
+ const l = f.look ?? {}, s = f.select ?? {}, chosen = list(value), many = !!s.multiple;
207
+ const [query, setQuery] = useState(''), [found, setFound] = useState<{ options: Choice[]; more: boolean }>(), [problem, setProblem] = useState(false);
208
+ const [known, learn] = useLabels(url, f.options ?? [], s, chosen, onKnown);
209
+ const wait = useDelayed(!!(s.remote && !found));
210
+ useEffect(() => {
211
+ if (!s.remote) return;
212
+ const stop = new AbortController();
213
+ const timer = setTimeout(() => api<{ options: Choice[]; more: boolean }>(`${url}?${new URLSearchParams({ search: query.trim() })}`, 'GET', undefined, stop.signal)
214
+ .then((a) => { learn(a.options); setFound(a); setProblem(false); }).catch(() => stop.signal.aborted || setProblem(true)), query ? 250 : 0);
215
+ return () => { clearTimeout(timer); stop.abort(); };
216
+ }, [query, url, s.remote]);
217
+ const words = query.trim().toLocaleLowerCase();
218
+ let shown = s.remote ? found?.options ?? [] : (f.options ?? []).filter((o) => !words || `${o.label} ${o.description ?? ''}`.toLocaleLowerCase().includes(words));
219
+ // What is chosen stays in sight, also when the server did not list it.
220
+ if (s.remote && !words) shown = [...shown, ...chosen.filter((v) => !shown.some((o) => String(o.value) === v)).map((v) => ({ value: v, label: known[v] ?? v }))];
221
+ const off = (o: Choice) => !!o.disabled || (many && !!s.maxItems && chosen.length >= s.maxItems && !chosen.includes(String(o.value)));
222
+ const pick = (v: string, on: boolean) => set(many ? (on ? [...chosen, v] : chosen.filter((x) => x !== v)) : v);
223
+ const buttons = f.type === 'buttons', free = shown.filter((o) => !o.disabled).map((o) => String(o.value));
224
+ const name = id + '-choice', grid = columns(l.columns);
225
+ // A checkbox list whose choices have groups shows each group on its own, with a box for the whole group.
226
+ const grouped = many && !buttons && shown.some((o) => o.group);
227
+ const option = (o: Choice, i: number) => {
228
+ const v = String(o.value), on = chosen.includes(v), about = o.description ? `${id}-d${i}` : undefined;
229
+ const input = <input type={many ? 'checkbox' : 'radio'} name={name} value={v} checked={on} disabled={off(o)} aria-describedby={about} className={buttons ? 'sr-only' : 'check mt-0.5' + (many ? '' : ' rounded-full')} onChange={(e) => pick(v, e.target.checked)} />;
230
+ return buttons ? <label key={v} data-lk="choice" data-on={on || undefined} data-variant={on ? (l.variant ?? 'soft') : undefined} data-color={on ? (l.colors?.[v] ?? 'primary') : undefined} data-size={l.size ?? 'md'} className={`btn choice relative inline-flex items-center justify-center ${l.fullWidth ? 'flex-1 ' : ''}${on ? 'tone-' + (l.colors?.[v] ?? 'primary') : ''}`}>{input}{o.icon && <Icon name={o.icon} className="size-4 shrink-0" />}<span>{o.label}</span>{o.description && <span id={about} className="sr-only">{o.description}</span>}</label>
231
+ : <label key={v} data-lk="choice" className={'flex items-start gap-2 text-sm ' + (off(o) ? 'opacity-50' : 'cursor-pointer')}>{input}<span className="min-w-0"><span className="inline-flex items-center gap-1.5 break-words">{o.icon && <Icon name={o.icon} className="size-4 shrink-0" />}<span>{o.label}</span></span>{o.description && <span id={about} className="muted block text-xs">{o.description}</span>}</span></label>;
232
+ };
233
+ return <div id={id} role={many ? 'group' : 'radiogroup'} tabIndex={-1} aria-labelledby={labelledBy} aria-describedby={describedBy} aria-invalid={invalid || undefined} aria-required={!many && required || undefined} data-lk="choices">
234
+ {s.searchable && <input type="search" aria-label={`${t('search.label')} ${f.label}`} placeholder={t('search.label')} className="input mb-2" value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') e.preventDefault(); }} />}
235
+ {l.selectAll && <div className="mb-2 flex gap-3 text-xs">
236
+ {!s.maxItems && <button type="button" data-lk="all" className="underline" onClick={() => set([...new Set([...chosen, ...free])])}>{t('form.selectAll')}</button>}
237
+ <button type="button" data-lk="none" className="underline" onClick={() => set([])}>{t('form.selectNone')}</button></div>}
238
+ {problem ? <p role="alert" className="danger text-sm">{t('form.optionsError')}</p> : s.remote && !found ? (wait ? <InlineSkeleton /> : null) : !shown.length ? <p role="status" className="muted text-sm">{t('table.empty')}</p> : null}
239
+ {grouped ? <div {...grid} data-lk="choice-groups" className={grid.className ? grid.className + ' choice-groups' : 'choice-groups'}>
240
+ {[...new Set(shown.map((o) => o.group ?? ''))].map((g) => {
241
+ const these = shown.filter((o) => (o.group ?? '') === g), open = these.filter((o) => !off(o)).map((o) => String(o.value));
242
+ const on = these.filter((o) => chosen.includes(String(o.value))).length, all = !!open.length && open.every((v) => chosen.includes(v));
243
+ return <section key={g} data-lk="choice-group" className="choice-group" aria-label={g || f.label}>
244
+ {g && <div className="choice-group-head">
245
+ <label className="flex min-w-0 items-center gap-2 text-sm font-medium cursor-pointer"><input type="checkbox" className="check" checked={all} disabled={!open.length || !!s.maxItems}
246
+ ref={(e) => { if (e) e.indeterminate = on > 0 && !all; }} onChange={(e) => set(e.target.checked ? [...new Set([...chosen, ...open])] : chosen.filter((v) => !open.includes(v)))} /><span className="truncate">{g}</span></label>
247
+ <span data-lk="choice-count" className="muted ml-auto text-xs tabular-nums">{t('form.chosenOf', { count: on, total: these.length })}</span></div>}
248
+ <div className="space-y-2">{these.map((o) => option(o, shown.indexOf(o)))}</div>
249
+ </section>;
250
+ })}
251
+ </div> : <div {...grid} className={grid.className ?? (buttons ? (l.grouped ? (l.fullWidth ? 'grouped flex w-full flex-wrap' : 'grouped flex flex-wrap') : l.fullWidth ? 'flex w-full flex-wrap gap-2' : 'flex flex-wrap gap-2') : l.inline ? 'flex flex-wrap gap-x-5 gap-y-2' : 'space-y-2')}>
252
+ {shown.map((o, i) => option(o, i))}
253
+ </div>}
254
+ {found?.more && <p className="muted mt-2 text-xs">{s.searchable ? t('form.searchMore') : t('form.moreAvailable')}</p>}
255
+ {!!f.props?.grants && <Abilities props={f.props as Grants} options={f.options ?? []} chosen={chosen} />}
256
+ </div>;
257
+ }
258
+
259
+ type Grants = { grants: Record<string, string[]>; permissions: { name: string; label: string; group: string }[]; supers?: string[] };
260
+
261
+ /** What someone can do with the roles that are ticked, and which role gives each permission. */
262
+ function Abilities({ props: p, options, chosen }: { props: Grants; options: Choice[]; chosen: string[] }) {
263
+ const t = useT();
264
+ const record = useContext(RecordId);
265
+ const labelOf = (role: string) => options.find((o) => String(o.value) === role)?.label ?? role;
266
+ if (record && p.supers?.includes(record)) return <p data-lk="abilities" className="callout tone-info mt-3 border p-3 text-sm">{t('roles.superAll')}</p>;
267
+ const groups = new Map<string, { name: string; label: string; by: string[] }[]>();
268
+ let count = 0;
269
+ for (const perm of p.permissions) {
270
+ const by = chosen.filter((role) => p.grants[role]?.includes(perm.name));
271
+ if (!by.length) continue;
272
+ count++;
273
+ groups.set(perm.group, [...(groups.get(perm.group) ?? []), { name: perm.name, label: perm.label, by: by.map(labelOf) }]);
274
+ }
275
+ return <details data-lk="abilities" className="choice-group mt-3">
276
+ <summary className="cursor-pointer text-sm font-medium">{t('roles.canDo', { count })}</summary>
277
+ {!count ? <p className="muted mt-3 text-sm">{t('roles.nothingHeld')}</p> : <div className="mt-3 space-y-3">
278
+ {[...groups].map(([group, items]) => <div key={group}>
279
+ <p className="muted mb-1 text-xs font-semibold uppercase tracking-wide">{group}</p>
280
+ <ul className="space-y-1">{items.map((item) => <li key={item.name} className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
281
+ <span>{item.label}</span>{item.by.map((role) => <span key={role} className="badge px-1.5 py-0.5 text-xs">{role}</span>)}
282
+ </li>)}</ul>
283
+ </div>)}
284
+ </div>}
285
+ </details>;
286
+ }
287
+
288
+ export { RecordId };
289
+ /** Where a stored file of a field is read: through its record, or as an upload of this visitor. */
290
+ export const fileUrl = (resource: string, key: string, path: string, baseUrl?: string, record = '') => `${base}${baseUrl ?? `/${resource}`}/files/${key}?${new URLSearchParams(record ? { path, record } : { path })}`;
291
+ const bytes = (n: number) => (n >= 1048576 ? `${+(n / 1048576).toFixed(1)} MB` : `${Math.ceil(n / 1024)} KB`);
292
+
293
+ /** Uploads files at once, so the form only sends their paths. */
294
+ function FileBox({ id, uploadUrl, fileBaseUrl, field: f, value, set, invalid, describedBy, required }: Props) {
295
+ const t = useT();
296
+ const s = f.file ?? { maxSize: 10240 }, chosen = list(value), many = !!s.multiple;
297
+ const [busy, setBusy] = useState(0), [problem, setProblem] = useState(''), [names, setNames] = useState<Record<string, string>>({}), [over, setOver] = useState(false);
298
+ const record = useContext(RecordId);
299
+ const fileLink = (p: string) => (fileBaseUrl ? `${fileBaseUrl}?${new URLSearchParams(record ? { path: p, record } : { path: p })}` : undefined);
300
+ const room = many ? (s.maxFiles ? s.maxFiles - chosen.length : Infinity) : 1;
301
+ // A kind such as "pdf" is an extension to the browser.
302
+ const accept = s.accept?.map((k) => (k.includes('/') || k.startsWith('.') ? k : '.' + k)).join(',');
303
+ async function add(files: FileList | null) {
304
+ if (!files?.length || !uploadUrl) return;
305
+ setProblem('');
306
+ const picked = [...files].slice(0, Math.max(0, room));
307
+ if (files.length > picked.length) setProblem(t('form.maxFiles', { count: s.maxFiles ?? 0 }));
308
+ let now = many ? chosen : [];
309
+ for (const file of picked) {
310
+ if (file.size > s.maxSize * 1024) { setProblem(t('form.fileTooLarge', { name: file.name, max: bytes(s.maxSize * 1024) })); continue; }
311
+ const body = new FormData();
312
+ body.append('file', file);
313
+ setBusy((n) => n + 1);
314
+ try {
315
+ const done = await api<{ value: string; name: string }>(uploadUrl, 'POST', body);
316
+ setNames((old) => ({ ...old, [done.value]: done.name }));
317
+ now = many ? [...now, done.value] : [done.value];
318
+ set(many ? now : done.value);
319
+ } catch (e) {
320
+ setProblem(e instanceof ApiError && e.errors.file ? e.errors.file.join(' ') : fail(e));
321
+ } finally {
322
+ setBusy((n) => n - 1);
323
+ }
324
+ }
325
+ }
326
+ const drop = (p: string) => set(many ? chosen.filter((x) => x !== p) : '');
327
+ return <div data-lk="files" className="space-y-2">
328
+ {chosen.length > 0 && <ul className="space-y-2">
329
+ {chosen.map((p) => <li key={p} data-lk="file" className="file-item flex items-center gap-3">
330
+ {s.image && fileBaseUrl && <img src={fileLink(p)} alt="" className="picture size-12 rounded object-cover" />}
331
+ <a href={fileLink(p)} target="_blank" rel="noopener" className="min-w-0 flex-1 truncate text-sm underline">{names[p] ?? p.split('/').pop()}</a>
332
+ <button type="button" data-lk="remove-file" className="row-btn danger" onClick={() => drop(p)}>{t('form.remove')}</button>
333
+ </li>)}
334
+ </ul>}
335
+ {room > 0 && <label data-lk="dropzone" data-over={over || undefined} className="dropzone frame flex cursor-pointer flex-col items-center gap-1 px-4 py-6 text-center text-sm"
336
+ onDragOver={(e) => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={(e) => { e.preventDefault(); setOver(false); add(e.dataTransfer.files); }}>
337
+ <Icon name="upload" className="muted mb-1 size-6" />
338
+ <span><span className="font-semibold underline-offset-2 hover:underline">{t(many ? 'form.chooseFiles' : 'form.chooseFile')}</span> {t(many ? 'form.dragFiles' : 'form.dragFile')}</span>
339
+ <span className="muted text-xs">{many && s.maxFiles ? t('form.maxFilesLimit', { count: s.maxFiles }) + ' · ' : ''}{t('form.maxSizeLimit', { size: bytes(s.maxSize * 1024) })}{chosen.length && !many ? ' · ' + t('form.replaceFileNote') : ''}</span>
340
+ <input id={id} type="file" className="sr-only" accept={accept} multiple={many} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required && !chosen.length || undefined}
341
+ onChange={(e) => { add(e.target.files); e.target.value = ''; }} />
342
+ </label>}
343
+ {!!busy && <p role="status" className="muted text-sm">{t('form.uploading')}</p>}
344
+ {problem && <p role="alert" data-lk="file-error" className="danger text-sm">{problem}</p>}
345
+ </div>;
346
+ }
347
+
348
+ const supportsFieldSizing = typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('field-sizing', 'content');
349
+
350
+ function AutosizeTextarea({ id, field: f, value, set, invalid, describedBy, required }: {
351
+ id: string; field: Field; value: string; set: (v: string) => void; invalid: boolean; describedBy?: string; required: boolean;
352
+ }) {
353
+ const l = f.look ?? {};
354
+ const ref = useRef<HTMLTextAreaElement>(null);
355
+
356
+ useLayoutEffect(() => {
357
+ const el = ref.current;
358
+ if (!el || !l.autosize || supportsFieldSizing) return;
359
+ el.style.height = 'auto';
360
+ if (el.scrollHeight > 0) el.style.height = `${el.scrollHeight}px`;
361
+ }, [value, l.autosize]);
362
+
363
+ return <textarea ref={ref} id={id} className={'input' + (l.autosize ? ' autosize' : '')} rows={l.rows ?? 3} value={value} placeholder={l.placeholder} readOnly={l.readOnly} minLength={l.minLength} maxLength={l.maxLength} autoCapitalize={l.autocapitalize} autoComplete={l.autocomplete}
364
+ aria-invalid={invalid} aria-describedby={describedBy} aria-required={required || undefined} onChange={(e) => set(e.target.value)} />;
365
+ }
366
+
367
+ /** Every error of the form, by its path, for the fields inside a list: `items.1.sku` is drawn under the second row's SKU. */
368
+ export const FormErrors = createContext<Record<string, string[]>>({});
369
+
370
+ function Control(p: Props) {
371
+ const { id, url, field: f, value, set, invalid, describedBy, required, labelledBy } = p, l = f.look ?? {};
372
+ const formErrors = useContext(FormErrors);
373
+ if (f.type === 'file') return <FileBox {...p} />;
374
+ if (f.type === 'tags') return <TagsInput id={id} value={list(value)} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} required={required} readOnly={l.readOnly} placeholder={l.placeholder} color={l.color} separator={l.separator} suggestions={l.suggestions} maxItems={l.maxItems} />;
375
+ if (f.type === 'keyvalue') {
376
+ const map = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, string>) : {};
377
+ return <KeyValue id={id} value={map} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} labelledBy={labelledBy} readOnly={l.readOnly} keyLabel={l.keyLabel} valueLabel={l.valueLabel} keyPlaceholder={l.keyPlaceholder} valuePlaceholder={l.valuePlaceholder} addLabel={l.addLabel} editableKeys={l.editableKeys} editableValues={l.editableValues} reorderable={l.reorderable} minItems={l.minItems} maxItems={l.maxItems} />;
378
+ }
379
+ if (f.type === 'repeater') {
380
+ const subFields = l.fields ?? [];
381
+ const rows = Array.isArray(value) ? (value as RepeaterItem[]) : [];
382
+ const makeItem = (): RepeaterItem => Object.fromEntries(subFields.map((cf) => [cf.key, toForm(cf, cf.default, () => {})]));
383
+ return <Repeater id={id} fields={subFields} value={rows} set={(v) => set(v)} makeItem={makeItem} invalid={invalid} describedBy={describedBy} labelledBy={labelledBy} readOnly={l.readOnly} columns={l.columns} itemLabel={l.itemLabel} addLabel={l.addLabel} collapsible={l.collapsible} collapsed={l.collapsed} cloneable={l.cloneable} reorderable={l.reorderable} table={l.table} minItems={l.minItems} maxItems={l.maxItems}
384
+ renderField={({ field: cf, id: cfId, errorId: cfErrId, value: cfVal, item, index, compact, onChange }) => {
385
+ if (!holds(cf.visibleWhen, item as Vals)) return null;
386
+ const viewField = compact ? { ...cf, look: { ...cf.look, hiddenLabel: true } } : cf;
387
+ const normalized = cfVal === undefined ? toForm(cf, cf.default, () => {}) : (cfVal as Val);
388
+ const path = `${f.key}.${index}.${cf.key}`;
389
+ return <FieldView id={cfId} errorId={cfErrId} errorFor={path} errors={formErrors[path]} url={url ? `${url}/${cf.key}` : ''} field={viewField} value={normalized} values={item as Vals} disabled={l.readOnly} onKnown={() => {}} set={(next) => onChange(next)} />;
390
+ }} />;
391
+ }
392
+ if (f.type === 'slider') {
393
+ const min = l.min !== undefined ? Number(l.min) : 0;
394
+ const max = l.max !== undefined ? Number(l.max) : 100;
395
+ const step = l.step !== undefined ? Number(l.step) : 1;
396
+ const val: string | [string, string] = l.range
397
+ ? (Array.isArray(value) ? [String(value[0] ?? min), String(value[1] ?? max)] : [String(min), String(max)])
398
+ : text(value);
399
+ return <Slider id={id} label={f.label} value={val} set={(v) => set(v)} min={Number.isFinite(min) ? min : 0} max={Number.isFinite(max) ? max : 100} step={Number.isFinite(step) && step > 0 ? step : 1} range={l.range} marks={l.marks} color={l.color} prefix={l.prefix} suffix={l.suffix} readOnly={l.readOnly} invalid={invalid} describedBy={describedBy} labelledBy={labelledBy} />;
400
+ }
401
+ if (f.type === 'code') return <CodeEditor id={id} value={text(value)} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} required={required} readOnly={l.readOnly} placeholder={l.placeholder} language={l.language} wrap={l.wrap} minHeight={l.minHeight} maxHeight={l.maxHeight} />;
402
+ if (f.type === 'markdown') return <MarkdownEditor id={id} value={text(value)} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} required={required} readOnly={l.readOnly} placeholder={l.placeholder} toolbar={l.toolbar} minHeight={l.minHeight} maxHeight={l.maxHeight} />;
403
+ if (f.type === 'otp') return <OneTimeCode id={id} value={text(value)} set={(v) => set(v)} length={l.length} numeric={l.numeric} submitOnCompletion={l.submitOnCompletion} readOnly={l.readOnly} invalid={invalid} describedBy={describedBy} required={required} />;
404
+ if (f.type === 'rich') return <RichEditor id={id} value={String(value)} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} required={required} readOnly={l.readOnly} placeholder={l.placeholder} toolbar={l.toolbar} minHeight={l.minHeight} maxHeight={l.maxHeight} />;
405
+ if (f.type === 'date' || f.type === 'datetime') {
406
+ // A moment's limits are in UTC, the picker is in this person's time.
407
+ const limit = (v: unknown) => (v === undefined || v === null ? undefined : f.type === 'datetime' ? local(String(v)) : String(v));
408
+ return <DatePicker id={id} value={String(value)} time={f.type === 'datetime'} seconds={l.seconds} min={limit(l.min)} max={limit(l.max)} invalid={invalid} describedBy={describedBy}
409
+ required={required} labelledBy={p.labelledBy} placeholder={l.placeholder} disabled={l.readOnly} onChange={(v) => set(v)} />;
410
+ }
411
+ if (f.type === 'select') return <FieldSelect id={id} url={url} options={f.options} settings={f.select} value={list(value)} invalid={invalid} describedBy={describedBy} onKnown={p.onKnown} onChange={(v) => set(f.select?.multiple ? v : v[0] ?? '')} />;
412
+ if (options(f)) return <Choices {...p} />;
413
+ if (check(f)) return <input id={id} type="checkbox" role={f.type === 'toggle' ? 'switch' : undefined} checked={value === 'true'} aria-invalid={invalid} aria-describedby={describedBy} aria-required={required || undefined} onChange={(e) => set(e.target.checked ? 'true' : 'false')}
414
+ className={f.type === 'toggle' ? `switch on-${l.onColor ?? 'primary'} off-${l.offColor ?? 'gray'}` : 'check'} />;
415
+ if (f.type === 'textarea') return <AutosizeTextarea id={id} field={f} value={String(value)} set={(v) => set(v)} invalid={invalid} describedBy={describedBy} required={required} />;
416
+ const Part = fieldPart(f.type), plain = <TextBox {...p} />;
417
+ return Part ? <Guard fallback={plain}><Part id={id} value={String(value)} invalid={invalid} describedBy={describedBy} props={f.props ?? {}} onChange={(v) => set(String(v))} /></Guard> : plain;
418
+ }
419
+
420
+ type View = Omit<Props, 'invalid' | 'describedBy' | 'required' | 'labelledBy'> & { errors?: string[]; errorId: string; values: Vals; disabled?: boolean; children?: ReactNode;
421
+ /** The path of the input that the error is for, such as `items.1.sku`; the field's key by default. */ errorFor?: string };
422
+
423
+ function DefaultField({ field: f, id, errorId, value, errors, disabled, required, children }: Parts['field'] & { body: ReactNode }) {
424
+ return <div data-lk="field" data-name={f.key} data-type={f.type} data-disabled={disabled || undefined} data-invalid={!!errors || undefined} data-required={required || undefined}>{disabled ? <fieldset disabled className="min-w-0">{children}</fieldset> : children}</div>;
425
+ }
426
+
427
+ /** A field with its label, help and error. */
428
+ export function FieldView({ errors, errorId, errorFor, values, disabled, children, ...p }: View) {
429
+ const { field: f, id } = p, l = f.look ?? {};
430
+ if (f.type === 'hidden') return null;
431
+ const required = !!l.required || (!!f.requiredWhen?.length && holds(f.requiredWhen, values));
432
+ const group = (options(f) && f.type !== 'select') || f.type === 'keyvalue' || f.type === 'repeater' || (f.type === 'slider' && !!l.range), beside = check(f) && !l.labelAbove, bad = !!errors;
433
+ const about = [l.hint && id + '-hint', l.helper && id + '-help', bad && errorId].filter(Boolean).join(' ') || undefined;
434
+ const star = required && <span data-lk="required" aria-hidden="true" className="danger"> *</span>;
435
+ const name = group ? <span data-lk="label" id={id + '-label'} className="text-sm font-medium">{f.label}{star}</span> : <label data-lk="label" id={id + '-label'} htmlFor={id} className={'text-sm font-medium ' + (beside ? 'cursor-pointer' : '')}>{f.label}{star}</label>;
436
+ const hint = l.hint && <span data-lk="hint" id={id + '-hint'} className="muted ml-auto text-xs">{l.hint}</span>;
437
+ const own = { ...p, invalid: bad, describedBy: about, required, labelledBy: id + '-label' };
438
+ // The field's own `.component(...)` draws the input (LA-306); Larakit keeps the label, helper and error.
439
+ const control = f.component
440
+ ? <PartOf name={f.component} data={f.props ?? {}} partKey={f.partKey ?? f.key} Default={KitDefault}
441
+ props={{ value: p.value, set: (v: unknown) => p.set(v as Val), field: f, id, invalid: bad, describedBy: about, required, disabled: !!l.readOnly,
442
+ options: p.url || undefined, api: p.api, path: f.key, __own: Control, __kit: own } as never} />
443
+ : <Control {...own} />;
444
+ const help = <>{l.helper && <p data-lk="helper" id={id + '-help'} className="muted mt-1 text-xs">{l.helper}</p>}{children}{bad && <p id={errorId} data-lk="error" data-error-for={errorFor ?? f.key} className="danger mt-1 text-sm">{errors.join(' ')}</p>}</>;
445
+ const body = beside ? <><div className="flex items-center gap-2">{control}<span className={l.hiddenLabel ? 'sr-only' : ''}>{name}</span>{hint}</div>{help}</>
446
+ : <div className={l.inlineLabel ? 'inline-label' : ''}><div className={l.hiddenLabel && !hint ? 'sr-only' : 'mb-1 flex flex-wrap items-baseline gap-x-2'}><span className={l.hiddenLabel ? 'sr-only' : ''}>{name}</span>{hint}</div><div className="min-w-0">{control}{help}</div></div>;
447
+ const locked = disabled || (!!f.disabledWhen?.length && holds(f.disabledWhen, values));
448
+ return <Slot part="field" own={DefaultField as React.ComponentType<Parts['field']>} props={{ field: f, id, errorId, value: p.value, errors, disabled: locked, required, children: body }} />;
449
+ }
@@ -0,0 +1,157 @@
1
+ import { useRef, useState, type KeyboardEvent } from 'react';
2
+ import { useT } from '../i18n';
3
+ import { Icon } from '../icons';
4
+
5
+ export type CodeEditorProps = {
6
+ id: string;
7
+ value: string;
8
+ set: (v: string) => void;
9
+ invalid?: boolean;
10
+ describedBy?: string;
11
+ required?: boolean;
12
+ readOnly?: boolean;
13
+ placeholder?: string;
14
+ language?: string;
15
+ wrap?: boolean;
16
+ minHeight?: number;
17
+ maxHeight?: number;
18
+ };
19
+
20
+ /** Monospace code editor with line numbers, Tab indent, wrap toggle, language badge, and copy button. */
21
+ export function CodeEditor({
22
+ id,
23
+ value,
24
+ set,
25
+ invalid,
26
+ describedBy,
27
+ required,
28
+ readOnly,
29
+ placeholder,
30
+ language = 'text',
31
+ wrap: initialWrap = false,
32
+ minHeight = 160,
33
+ maxHeight = 480,
34
+ }: CodeEditorProps) {
35
+ const t = useT();
36
+ const areaRef = useRef<HTMLTextAreaElement>(null);
37
+ const gutterRef = useRef<HTMLDivElement>(null);
38
+ const [wrapped, setWrapped] = useState(initialWrap);
39
+ const [copied, setCopied] = useState(false);
40
+
41
+ const lines = Math.max(1, value.split('\n').length);
42
+
43
+ const syncScroll = () => {
44
+ if (gutterRef.current && areaRef.current) {
45
+ gutterRef.current.scrollTop = areaRef.current.scrollTop;
46
+ }
47
+ };
48
+
49
+ const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
50
+ if (readOnly || e.key !== 'Tab') return;
51
+ e.preventDefault();
52
+ const el = e.currentTarget;
53
+ const start = el.selectionStart;
54
+ const end = el.selectionEnd;
55
+ if (!e.shiftKey) {
56
+ const next = value.slice(0, start) + ' ' + value.slice(end);
57
+ set(next);
58
+ requestAnimationFrame(() => {
59
+ el.selectionStart = el.selectionEnd = start + 2;
60
+ });
61
+ } else {
62
+ const lineStart = value.lastIndexOf('\n', start - 1) + 1;
63
+ const linePrefix = value.slice(lineStart, start);
64
+ const trimLen = linePrefix.startsWith(' ') ? 2 : linePrefix.startsWith(' ') || linePrefix.startsWith('\t') ? 1 : 0;
65
+ if (trimLen > 0) {
66
+ const next = value.slice(0, lineStart) + value.slice(lineStart + trimLen);
67
+ set(next);
68
+ requestAnimationFrame(() => {
69
+ el.selectionStart = el.selectionEnd = Math.max(lineStart, start - trimLen);
70
+ });
71
+ }
72
+ }
73
+ };
74
+
75
+ const copy = () => {
76
+ navigator.clipboard?.writeText(value).then(
77
+ () => {
78
+ setCopied(true);
79
+ setTimeout(() => setCopied(false), 1500);
80
+ },
81
+ () => {},
82
+ );
83
+ };
84
+
85
+ return (
86
+ <div
87
+ data-lk="code-editor"
88
+ className="code-editor surface overflow-hidden border"
89
+ aria-invalid={invalid || undefined}
90
+ >
91
+ <div className="code-header flex items-center justify-between gap-2 border-b px-3 py-1.5">
92
+ <span data-lk="code-language" className="badge tone-gray px-2 py-0.5 font-mono text-xs">
93
+ {language || 'text'}
94
+ </span>
95
+ <div className="flex items-center gap-1">
96
+ <button
97
+ type="button"
98
+ data-lk="code-wrap"
99
+ aria-pressed={wrapped}
100
+ aria-label={t('form.wrapLines')}
101
+ title={t('form.wrapLines')}
102
+ className="rich-btn"
103
+ onClick={() => setWrapped((w) => !w)}
104
+ >
105
+ <Icon name="wrap" className="size-4" />
106
+ </button>
107
+ <button
108
+ type="button"
109
+ data-lk="code-copy"
110
+ aria-label={copied ? t('table.copied') : t('table.copy')}
111
+ title={copied ? t('table.copied') : t('table.copy')}
112
+ className="rich-btn"
113
+ onClick={copy}
114
+ >
115
+ <Icon name={copied ? 'check' : 'copy'} className="size-4" />
116
+ </button>
117
+ <span role="status" className="sr-only">
118
+ {copied ? t('table.copied') : ''}
119
+ </span>
120
+ </div>
121
+ </div>
122
+ <div dir="ltr" className="code-body flex" style={{ minHeight: `${minHeight}px`, maxHeight: `${maxHeight}px` }}>
123
+ <div
124
+ ref={gutterRef}
125
+ aria-hidden="true"
126
+ className="code-gutter muted overflow-hidden border-e px-2.5 py-2.5 text-end font-mono text-xs leading-6 select-none"
127
+ >
128
+ {Array.from({ length: lines }, (_, i) => (
129
+ <div key={i + 1}>{i + 1}</div>
130
+ ))}
131
+ </div>
132
+ <textarea
133
+ ref={areaRef}
134
+ id={id}
135
+ spellCheck={false}
136
+ autoCapitalize="off"
137
+ autoComplete="off"
138
+ readOnly={readOnly}
139
+ value={value}
140
+ placeholder={placeholder}
141
+ wrap={wrapped ? 'soft' : 'off'}
142
+ aria-invalid={invalid || undefined}
143
+ aria-describedby={describedBy}
144
+ aria-required={required || undefined}
145
+ className={
146
+ 'code-textarea bare min-w-0 flex-1 resize-y overflow-auto px-3 py-2.5 font-mono text-xs leading-6 ' +
147
+ (wrapped ? 'whitespace-pre-wrap' : 'whitespace-pre')
148
+ }
149
+ style={{ minHeight: `${minHeight}px`, maxHeight: `${maxHeight}px` }}
150
+ onScroll={syncScroll}
151
+ onChange={(e) => set(e.target.value)}
152
+ onKeyDown={handleKeyDown}
153
+ />
154
+ </div>
155
+ </div>
156
+ );
157
+ }