@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,276 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { Icon } from './icons';
3
+ import { useT } from './i18n';
4
+
5
+ const ALLOWED_TAGS = new Set(['p', 'br', 'strong', 'b', 'em', 'i', 'u', 's', 'del', 'h2', 'h3', 'h4', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'a', 'hr', 'div', 'span']);
6
+ const SAFE_HREF = /^(https?:|mailto:|\/|#)/i;
7
+
8
+ const DEFAULT_TOOLBAR = ['bold', 'italic', 'underline', 'strike', 'h2', 'h3', 'bulletList', 'orderedList', 'quote', 'code', 'link', 'undo', 'redo', 'clear'];
9
+
10
+ /** Sanitizes rich HTML strictly to safe prose tags and safe URLs. */
11
+ export function sanitizeHtml(html: string): string {
12
+ if (!html) return '';
13
+ if (typeof DOMParser === 'undefined') return html.replace(/<[^>]+>/g, '');
14
+ const doc = new DOMParser().parseFromString(html, 'text/html');
15
+ const clean = (node: Node): Node | null => {
16
+ if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.textContent ?? '');
17
+ if (node.nodeType !== Node.ELEMENT_NODE) return null;
18
+ const el = node as Element, tag = el.tagName.toLowerCase();
19
+ if (tag === 'script' || tag === 'style' || tag === 'iframe' || tag === 'object' || tag === 'embed' || tag === 'svg' || tag === 'form') return null;
20
+ const frag = document.createDocumentFragment();
21
+ for (const child of [...el.childNodes]) {
22
+ const next = clean(child);
23
+ if (next) frag.appendChild(next);
24
+ }
25
+ if (!ALLOWED_TAGS.has(tag)) return frag;
26
+ const out = document.createElement(tag);
27
+ if (tag === 'a') {
28
+ const href = (el.getAttribute('href') ?? '').trim();
29
+ if (SAFE_HREF.test(href)) {
30
+ out.setAttribute('href', href);
31
+ if (/^https?:/i.test(href)) {
32
+ out.setAttribute('target', '_blank');
33
+ out.setAttribute('rel', 'noopener noreferrer');
34
+ }
35
+ }
36
+ }
37
+ out.appendChild(frag);
38
+ return out;
39
+ };
40
+ const wrap = document.createElement('div');
41
+ for (const child of [...doc.body.childNodes]) {
42
+ const next = clean(child);
43
+ if (next) wrap.appendChild(next);
44
+ }
45
+ return wrap.innerHTML;
46
+ }
47
+
48
+ type ToolDef = { id: string; labelKey: string; icon: string; run: () => void };
49
+
50
+ /** Built-in accessible rich text editor with sanitization and configurable toolbar. */
51
+ export function RichEditor({ id, value, set, invalid, describedBy, required, readOnly, placeholder, toolbar, minHeight, maxHeight }: {
52
+ id: string;
53
+ value: string;
54
+ set: (v: string) => void;
55
+ invalid: boolean;
56
+ describedBy?: string;
57
+ required?: boolean;
58
+ readOnly?: boolean;
59
+ placeholder?: string;
60
+ toolbar?: string[];
61
+ minHeight?: number;
62
+ maxHeight?: number;
63
+ }) {
64
+ const t = useT();
65
+ const ref = useRef<HTMLDivElement>(null);
66
+ const linkInput = useRef<HTMLInputElement>(null);
67
+ const savedRange = useRef<Range | null>(null);
68
+ const initialized = useRef(false);
69
+ const last = useRef(value);
70
+ const [linkOpen, setLinkOpen] = useState(false);
71
+ const [linkUrl, setLinkUrl] = useState('https://');
72
+
73
+ useEffect(() => {
74
+ const el = ref.current;
75
+ if (!el) return;
76
+ const safe = sanitizeHtml(value);
77
+ if (!initialized.current || value !== last.current) {
78
+ initialized.current = true;
79
+ if (el.innerHTML !== safe) el.innerHTML = safe;
80
+ last.current = safe;
81
+ }
82
+ }, [value]);
83
+
84
+ useEffect(() => {
85
+ if (linkOpen) linkInput.current?.focus();
86
+ }, [linkOpen]);
87
+
88
+ const emit = () => {
89
+ const el = ref.current;
90
+ if (!el) return;
91
+ const textOnly = (el.textContent ?? '').trim();
92
+ const raw = textOnly || /<(img|hr|br|li|pre|blockquote)/i.test(el.innerHTML) ? el.innerHTML : '';
93
+ const next = raw ? sanitizeHtml(raw) : '';
94
+ if (next !== last.current) {
95
+ last.current = next;
96
+ set(next);
97
+ }
98
+ };
99
+
100
+ const exec = (cmd: string, arg?: string) => {
101
+ if (readOnly) return;
102
+ ref.current?.focus();
103
+ document.execCommand(cmd, false, arg);
104
+ emit();
105
+ };
106
+
107
+ const toggleBlock = (tag: string) => {
108
+ if (readOnly) return;
109
+ ref.current?.focus();
110
+ const current = document.queryCommandValue('formatBlock').toLowerCase();
111
+ document.execCommand('formatBlock', false, current === tag ? '<p>' : `<${tag}>`);
112
+ emit();
113
+ };
114
+
115
+ const openLinkPopover = () => {
116
+ if (readOnly) return;
117
+ if (linkOpen) {
118
+ setLinkOpen(false);
119
+ savedRange.current = null;
120
+ return;
121
+ }
122
+ const sel = window.getSelection();
123
+ if (sel && sel.rangeCount > 0 && ref.current?.contains(sel.anchorNode)) {
124
+ savedRange.current = sel.getRangeAt(0).cloneRange();
125
+ } else {
126
+ savedRange.current = null;
127
+ }
128
+ let initial = 'https://';
129
+ if (sel?.anchorNode) {
130
+ const anchor = (sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode.parentElement)?.closest('a');
131
+ if (anchor && ref.current?.contains(anchor)) initial = anchor.getAttribute('href') ?? 'https://';
132
+ }
133
+ setLinkUrl(initial);
134
+ setLinkOpen(true);
135
+ };
136
+
137
+ const closeLinkPopover = () => {
138
+ setLinkOpen(false);
139
+ savedRange.current = null;
140
+ ref.current?.focus();
141
+ };
142
+
143
+ const applyLink = () => {
144
+ if (readOnly) return;
145
+ ref.current?.focus();
146
+ const sel = window.getSelection();
147
+ if (sel && savedRange.current) {
148
+ sel.removeAllRanges();
149
+ sel.addRange(savedRange.current);
150
+ }
151
+ const trimmed = linkUrl.trim();
152
+ if (!trimmed) document.execCommand('unlink', false);
153
+ else if (SAFE_HREF.test(trimmed)) document.execCommand('createLink', false, trimmed);
154
+ emit();
155
+ setLinkOpen(false);
156
+ savedRange.current = null;
157
+ };
158
+
159
+ const tools: Record<string, ToolDef> = {
160
+ bold: { id: 'bold', labelKey: 'rich.bold', icon: 'bold', run: () => exec('bold') },
161
+ italic: { id: 'italic', labelKey: 'rich.italic', icon: 'italic', run: () => exec('italic') },
162
+ underline: { id: 'underline', labelKey: 'rich.underline', icon: 'underline', run: () => exec('underline') },
163
+ strike: { id: 'strike', labelKey: 'rich.strike', icon: 'strike', run: () => exec('strikeThrough') },
164
+ h2: { id: 'h2', labelKey: 'rich.h2', icon: 'h2', run: () => toggleBlock('h2') },
165
+ h3: { id: 'h3', labelKey: 'rich.h3', icon: 'h3', run: () => toggleBlock('h3') },
166
+ bulletList: { id: 'bulletList', labelKey: 'rich.bulletList', icon: 'list', run: () => exec('insertUnorderedList') },
167
+ orderedList: { id: 'orderedList', labelKey: 'rich.orderedList', icon: 'list-ordered', run: () => exec('insertOrderedList') },
168
+ quote: { id: 'quote', labelKey: 'rich.quote', icon: 'quote', run: () => toggleBlock('blockquote') },
169
+ code: { id: 'code', labelKey: 'rich.code', icon: 'code', run: () => toggleBlock('pre') },
170
+ link: { id: 'link', labelKey: 'rich.link', icon: 'link', run: openLinkPopover },
171
+ undo: { id: 'undo', labelKey: 'rich.undo', icon: 'undo', run: () => exec('undo') },
172
+ redo: { id: 'redo', labelKey: 'rich.redo', icon: 'redo', run: () => exec('redo') },
173
+ clear: { id: 'clear', labelKey: 'rich.clear', icon: 'remove-formatting', run: () => exec('removeFormat') },
174
+ };
175
+
176
+ const activeTools = (toolbar?.length ? toolbar : DEFAULT_TOOLBAR).map((name) => tools[name]).filter(Boolean);
177
+ const rawToolbarLabel = t('rich.toolbar');
178
+ const toolbarLabel = rawToolbarLabel === 'rich.toolbar' ? 'Formatting toolbar' : rawToolbarLabel;
179
+
180
+ return (
181
+ <div data-lk="rich-editor" className="rich-editor input !p-0" aria-invalid={invalid || undefined}>
182
+ {!readOnly && (
183
+ <div role="toolbar" aria-label={toolbarLabel} className="rich-toolbar relative border-b px-2 py-1.5">
184
+ <div className="flex flex-wrap items-center gap-0.5">
185
+ {activeTools.map((tool) => (
186
+ <button
187
+ key={tool.id}
188
+ type="button"
189
+ data-lk={'rich-' + tool.id}
190
+ title={t(tool.labelKey)}
191
+ aria-label={t(tool.labelKey)}
192
+ aria-expanded={tool.id === 'link' ? linkOpen : undefined}
193
+ className="rich-btn"
194
+ onMouseDown={(e) => {
195
+ if (tool.id !== 'link') e.preventDefault();
196
+ }}
197
+ onClick={tool.run}
198
+ >
199
+ <Icon name={tool.icon} className="size-4" />
200
+ </button>
201
+ ))}
202
+ </div>
203
+ {linkOpen && (
204
+ <div data-lk="rich-link-popover" className="rich-link-popover surface mt-1.5 flex flex-wrap items-center gap-1.5 border p-2 shadow-sm">
205
+ <input
206
+ ref={linkInput}
207
+ type="url"
208
+ data-lk="rich-link-input"
209
+ aria-label={t('rich.linkPrompt')}
210
+ placeholder="https://"
211
+ className="input min-w-44 flex-1 px-2.5 py-1 text-sm"
212
+ value={linkUrl}
213
+ onChange={(e) => setLinkUrl(e.target.value)}
214
+ onKeyDown={(e) => {
215
+ if (e.key === 'Enter') {
216
+ e.preventDefault();
217
+ e.stopPropagation();
218
+ applyLink();
219
+ } else if (e.key === 'Escape') {
220
+ e.preventDefault();
221
+ e.stopPropagation();
222
+ closeLinkPopover();
223
+ }
224
+ }}
225
+ />
226
+ <button type="button" data-lk="rich-link-apply" className="btn primary" data-size="sm" onClick={applyLink}>
227
+ {t('form.add')}
228
+ </button>
229
+ <button type="button" data-lk="rich-link-cancel" className="btn" data-size="sm" onClick={closeLinkPopover}>
230
+ {t('form.cancel')}
231
+ </button>
232
+ </div>
233
+ )}
234
+ </div>
235
+ )}
236
+ <div
237
+ ref={ref}
238
+ id={id}
239
+ role="textbox"
240
+ aria-multiline="true"
241
+ aria-invalid={invalid || undefined}
242
+ aria-describedby={describedBy}
243
+ aria-required={required || undefined}
244
+ contentEditable={!readOnly}
245
+ suppressContentEditableWarning
246
+ data-placeholder={placeholder}
247
+ style={{
248
+ minHeight: minHeight !== undefined ? `${minHeight}px` : undefined,
249
+ maxHeight: maxHeight !== undefined ? `${maxHeight}px` : undefined,
250
+ }}
251
+ className={
252
+ 'rich-body rich-content overflow-y-auto px-3.5 py-2.5 text-sm focus:outline-none ' +
253
+ (minHeight === undefined ? 'min-h-36 ' : '') +
254
+ (maxHeight === undefined ? 'max-h-96' : '')
255
+ }
256
+ onBlur={emit}
257
+ onInput={emit}
258
+ onPaste={(e) => {
259
+ e.preventDefault();
260
+ const html = e.clipboardData.getData('text/html');
261
+ if (html) {
262
+ document.execCommand('insertHTML', false, sanitizeHtml(html));
263
+ } else {
264
+ document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
265
+ }
266
+ emit();
267
+ }}
268
+ />
269
+ </div>
270
+ );
271
+ }
272
+
273
+ /** Read-only view of rich editor HTML. */
274
+ export function RichView({ html }: { html: string }) {
275
+ return <div data-lk="rich-view" className="rich-content text-sm" dangerouslySetInnerHTML={{ __html: sanitizeHtml(html) }} />;
276
+ }
@@ -0,0 +1,92 @@
1
+ import { router } from '@inertiajs/react';
2
+ import { useEffect, useId, useRef, useState } from 'react';
3
+ import { api, currentPanelPath, fail, type Panel } from './api';
4
+ import { useT } from './i18n';
5
+ import { Icon } from './icons';
6
+
7
+ type Found = { groups: { screen: string; label: string; results: { id: string; title: string; details: string[] }[] }[] };
8
+
9
+ // Asked in the browser only: the page drawn on the server can't know, and must match the first draw in the browser.
10
+ const onMac = () => typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
11
+
12
+ /**
13
+ * The panel's search: a button that opens a box, with ⌘K or Ctrl+K too. It finds records of every
14
+ * screen that may be searched, a few of each.
15
+ */
16
+ export function Search({ panel, wide }: { panel: Panel; wide?: boolean }) {
17
+ const t = useT();
18
+ const dialog = useRef<HTMLDialogElement>(null), input = useRef<HTMLInputElement>(null), list = useId();
19
+ const [mac, setMac] = useState(false), [text, setText] = useState(''), [found, setFound] = useState<Found>(), [problem, setProblem] = useState(''), [at, setAt] = useState(0);
20
+ const open = () => { if (!dialog.current?.open) { dialog.current?.showModal(); input.current?.select(); } };
21
+ useEffect(() => {
22
+ const mac = onMac();
23
+ setMac(mac);
24
+ const keys = (e: KeyboardEvent) => { if ((mac ? e.metaKey : e.ctrlKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); open(); } };
25
+ const shut = () => dialog.current?.close();
26
+ addEventListener('keydown', keys); addEventListener('hashchange', shut);
27
+ return () => { removeEventListener('keydown', keys); removeEventListener('hashchange', shut); };
28
+ }, []);
29
+ // An older answer must not undo a newer one, and typing waits a moment before it asks.
30
+ useEffect(() => {
31
+ const q = text.trim();
32
+ if (q.length < 2) { setFound(undefined); setProblem(''); return; }
33
+ let live = true;
34
+ const t = setTimeout(() => api<Found>('/search?q=' + encodeURIComponent(q)).then(
35
+ (f) => { if (live) { setFound(f); setProblem(''); setAt(0); } },
36
+ (e) => { if (live) setProblem(fail(e)); }), 250);
37
+ return () => { live = false; clearTimeout(t); };
38
+ }, [text]);
39
+ const links = found?.groups.flatMap((g) => g.results.map((r) => ({ ...r, group: g, href: href(panel, g.screen, r.id) }))) ?? [];
40
+ const keys = (e: React.KeyboardEvent) => {
41
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
42
+ e.preventDefault();
43
+ if (links.length) setAt((at + (e.key === 'ArrowDown' ? 1 : -1) + links.length) % links.length);
44
+ } else if (e.key === 'Enter' && links[at]) {
45
+ e.preventDefault();
46
+ router.visit(links[at].href);
47
+ }
48
+ };
49
+ const hint = mac ? '⌘K' : 'Ctrl K';
50
+ return <>
51
+ <button type="button" data-lk="search" aria-haspopup="dialog" aria-keyshortcuts={mac ? 'Meta+K' : 'Control+K'} title={wide ? undefined : `${t('search.label')} (${hint})`} aria-label={wide ? undefined : t('search.label')}
52
+ className={wide ? 'search-button input flex w-56 items-center gap-2 py-1.5 text-left text-sm max-md:hidden' : 'tool'} onClick={open}>
53
+ <Icon name="search" className={wide ? 'muted size-4' : undefined} />
54
+ {wide && <><span className="muted flex-1">{t('search.label')}</span><kbd className="muted text-xs">{hint}</kbd></>}
55
+ </button>
56
+ {wide && <button type="button" data-lk="search-small" className="tool md:hidden" aria-label={t('search.label')} onClick={open}><Icon name="search" /></button>}
57
+ <dialog ref={dialog} data-lk="search-box" aria-label={t('search.label')} className="search-box surface m-auto mt-[12vh] w-[min(36rem,calc(100vw-2rem))] border p-0 shadow-xl"
58
+ onClick={(e) => { if (e.target === e.currentTarget) dialog.current?.close(); }}>
59
+ <div className="flex items-center gap-3 border-b px-4">
60
+ <Icon name="search" className="muted size-5" />
61
+ <input ref={input} type="search" role="combobox" aria-expanded={links.length > 0} aria-controls={list} aria-activedescendant={links[at] ? `${list}-${at}` : undefined} aria-autocomplete="list"
62
+ placeholder={t('search.label')} aria-label={t('search.label')} autoComplete="off" spellCheck={false} className="min-w-0 flex-1 bg-transparent py-4 outline-none" value={text} onChange={(e) => setText(e.target.value)} onKeyDown={keys} />
63
+ <kbd className="muted text-xs">Esc</kbd>
64
+ </div>
65
+ <div className="max-h-[60vh] overflow-y-auto">
66
+ {problem ? <p role="alert" className="danger px-4 py-6 text-sm">{problem}</p>
67
+ : text.trim().length < 2 ? <p className="muted px-4 py-6 text-center text-sm">{t('search.minChars')}</p>
68
+ : found && !links.length ? <p role="status" className="muted px-4 py-6 text-center text-sm">{t('search.empty')}</p>
69
+ : <ul id={list} role="listbox" aria-label={t('search.results')} className="p-2">{found?.groups.map((g) => <li key={g.screen} role="presentation">
70
+ <p data-lk="search-group" className="muted px-2 pt-2 pb-1 text-xs font-semibold">{g.label}</p>
71
+ <ul role="presentation">{g.results.map((r) => {
72
+ const n = links.findIndex((l) => l.group === g && l.id === r.id);
73
+ return <li key={r.id} role="presentation"><a id={`${list}-${n}`} role="option" aria-selected={n === at} data-lk="search-result" href={links[n].href}
74
+ className="search-result flex flex-col rounded-md px-3 py-2" onMouseMove={() => setAt(n)}>
75
+ <span className="truncate text-sm font-medium">{r.title}</span>
76
+ {r.details.length > 0 && <span className="muted truncate text-xs">{r.details.join(' · ')}</span>}
77
+ </a></li>;
78
+ })}</ul>
79
+ </li>)}</ul>}
80
+ </div>
81
+ </dialog>
82
+ </>;
83
+ }
84
+
85
+ /** Where a record opens: its view when the screen has one, its form otherwise. */
86
+ export function href(panel: Panel, screen: string, id: string) {
87
+ const r = panel.resources.find((x) => x.name === screen);
88
+ return `${currentPanelPath()}/${screen}/${encodeURIComponent(id)}${r?.view ? '' : '/edit'}`;
89
+ }
90
+
91
+ /** Whether any screen may be searched from the top. */
92
+ export const searchable = (panel: Panel) => panel.resources.some((r) => r.globalSearch);
@@ -0,0 +1,244 @@
1
+ import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
2
+ import { NewOption } from './create';
3
+ import { usePopoverPosition } from './hooks';
4
+ import { useT } from './i18n';
5
+ import { Icon } from './icons';
6
+ import { InlineSkeleton, useDelayed } from './loading';
7
+ import { api, fail, type Choice, type Choosing } from './api';
8
+
9
+ /** The record a form shows, so that its files and labels are read through it. */
10
+ export const RecordId = createContext('');
11
+
12
+ type Answer = { options: Choice[]; more: boolean };
13
+ type Load = (query: string, signal: AbortSignal) => Promise<Answer>;
14
+ type Props = {
15
+ id?: string; label?: string; value: string[]; onChange: (value: string[]) => void;
16
+ options: Choice[]; settings?: Choosing; chosen: (value: string) => string; load?: Load; create?: (typed: string) => void;
17
+ invalid?: boolean; describedBy?: string; className?: string;
18
+ };
19
+
20
+ const key = (c: Choice) => String(c.value);
21
+ // The four kinds of i count as one letter, as on the server.
22
+ const fold = (s: string) => s.replace(/[Iİı]/g, 'i').toLowerCase().replace(/̇/g, '');
23
+ const SHOWN = 200;
24
+
25
+ const NEW = '\0new';
26
+
27
+ /** A select with search, groups and several values. */
28
+ export function Select({ id, label, value, onChange, options, settings = {}, chosen, load, create, invalid, describedBy, className = '' }: Props) {
29
+ const t = useT();
30
+ const { multiple, searchable, clearable, maxItems, placeholder = t('form.selectPlaceholder') } = settings;
31
+ const own = useId(), list = own + 'list';
32
+ const [open, setOpen] = useState(false);
33
+ const [query, setQuery] = useState('');
34
+ const [at, setAt] = useState<string>(); // the value that the arrow keys are on
35
+ const [found, setFound] = useState<Answer>();
36
+ const [problem, setProblem] = useState('');
37
+ const box = useRef<HTMLDivElement>(null), button = useRef<HTMLButtonElement>(null), input = useRef<HTMLInputElement>(null), popup = useRef<HTMLDivElement>(null);
38
+ const dragging = useRef<string | undefined>(undefined);
39
+ const typed = useRef({ text: '', time: 0 });
40
+
41
+ useEffect(() => {
42
+ if (!open || !load) return;
43
+ const stop = new AbortController();
44
+ setFound(undefined); setProblem('');
45
+ const timer = setTimeout(() => load(query.trim(), stop.signal).then(setFound).catch((e) => stop.signal.aborted || setProblem(fail(e))), query ? 250 : 0);
46
+ return () => { clearTimeout(timer); stop.abort(); };
47
+ }, [open, query]);
48
+
49
+ const words = fold(query.trim());
50
+ const matches = load ? found?.options ?? [] : words ? options.filter((o) => fold([o.label, o.description, o.group].join(' ')).includes(words)) : options;
51
+ const shown = matches.slice(0, SHOWN);
52
+ const more = load ? !!found?.more : matches.length > SHOWN;
53
+ const full = !!multiple && !!maxItems && value.length >= maxItems;
54
+ const off = (o: Choice) => !!o.disabled || (full && !value.includes(key(o)));
55
+ // The last row adds an option. It is there with the others, so the arrow keys reach it.
56
+ const adding: Choice | undefined = create && !full && (!load || found || problem) ? { value: NEW, label: query.trim() ? t('form.newQuoted', { query: query.trim() }) : t('table.new') } : undefined;
57
+ const usable = [...shown.filter((o) => !off(o)), ...(adding ? [adding] : [])];
58
+ const active = usable.find((o) => key(o) === at) ?? (searchable ? usable[0] : undefined);
59
+ const optionId = (o: Choice) => own + 'o' + (o === adding ? 'new' : shown.indexOf(o));
60
+ const wait = useDelayed(!!(open && load && !found));
61
+
62
+ const show = (start = '') => {
63
+ if (open) return;
64
+ setQuery(start); setAt(value[0]); setOpen(true);
65
+ };
66
+ const hide = (focus = true) => { setOpen(false); setQuery(''); if (focus) button.current?.focus(); };
67
+ const pick = (o: Choice) => {
68
+ if (off(o)) return;
69
+ if (o === adding) { const typed = query.trim(); hide(); return create!(typed); }
70
+ const v = key(o);
71
+ if (!multiple) { onChange([v]); return hide(); }
72
+ onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v]);
73
+ setAt(v);
74
+ };
75
+ const reorder = (over: string) => {
76
+ const from = dragging.current;
77
+ if (!from || from === over) return;
78
+ const next = [...value], a = next.indexOf(from), b = next.indexOf(over);
79
+ if (a < 0 || b < 0) return;
80
+ next.splice(a, 1);
81
+ next.splice(b, 0, from);
82
+ onChange(next);
83
+ };
84
+
85
+ usePopoverPosition({
86
+ open,
87
+ anchor: () => box.current,
88
+ panel: popup,
89
+ width: (r) => Math.min(Math.max(r.width, 176), innerWidth - 16),
90
+ margin: 8,
91
+ flipThreshold: 232,
92
+ gap: 4,
93
+ align: 'start',
94
+ minHeight: 120,
95
+ maxHeight: 340,
96
+ heightOffset: 12,
97
+ });
98
+
99
+ // The popup is in the browser's top layer, so a dialog can't cut it off.
100
+ useLayoutEffect(() => {
101
+ if (!open) return;
102
+ const pop = popup.current!, near = box.current!;
103
+ pop.showPopover();
104
+ if (searchable) input.current?.focus();
105
+ const away = (e: Event) => { const t = e.target as Node; if (!near.contains(t) && !pop.contains(t)) { setOpen(false); setQuery(''); } };
106
+ document.addEventListener('pointerdown', away, true);
107
+ return () => { document.removeEventListener('pointerdown', away, true); };
108
+ }, [open]);
109
+ useEffect(() => { if (open && active) document.getElementById(optionId(active))?.scrollIntoView({ block: 'nearest' }); }, [open, active && key(active), shown.length]);
110
+
111
+ const move = (to: number) => { if (usable.length) setAt(key(usable[Math.max(0, Math.min(usable.length - 1, to))])); };
112
+ const keys = (e: KeyboardEvent) => {
113
+ if (e.nativeEvent.isComposing) return;
114
+ const on = active ? usable.indexOf(active) : -1, typing = e.target === input.current;
115
+ const letter = e.key.length === 1 && e.key !== ' ' && !e.ctrlKey && !e.metaKey && !e.altKey;
116
+ if (e.key === 'Escape') { if (!open) return; e.preventDefault(); e.stopPropagation(); return hide(); }
117
+ // With several values there are buttons below the list, and Tab goes to them.
118
+ if (e.key === 'Tab') { if (open && !multiple) hide(); return; }
119
+ if ((e.key === 'Enter' || e.key === ' ') && (e.target as Element).closest('[data-lk=options] button, [data-lk=clear]')) return;
120
+ if (e.key === 'Backspace' && multiple && value.length && (!typing || !query)) { e.preventDefault(); return onChange(value.slice(0, -1)); }
121
+ if (e.key === 'Delete' && clearable && !typing && value.length) return onChange([]);
122
+ if (!open) {
123
+ if (['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(e.key)) { e.preventDefault(); show(); }
124
+ else if (letter && searchable) { e.preventDefault(); show(e.key); }
125
+ else if (letter) { show(); jump(e.key); }
126
+ return;
127
+ }
128
+ if (e.key === 'ArrowDown') { e.preventDefault(); move(on + 1); }
129
+ else if (e.key === 'ArrowUp') { e.preventDefault(); move(on < 0 ? usable.length - 1 : on - 1); }
130
+ else if (e.key === 'PageDown') { e.preventDefault(); move(on + 8); }
131
+ else if (e.key === 'PageUp') { e.preventDefault(); move(on - 8); }
132
+ else if (!typing && e.key === 'Home') { e.preventDefault(); move(0); }
133
+ else if (!typing && e.key === 'End') { e.preventDefault(); move(usable.length - 1); }
134
+ else if (e.key === 'Enter' || (!typing && e.key === ' ')) { e.preventDefault(); if (active) pick(active); }
135
+ else if (!typing && letter) jump(e.key);
136
+ };
137
+ // Typing the start of a label goes to it.
138
+ const jump = (letter: string) => {
139
+ const t = typed.current, now = Date.now();
140
+ t.text = now - t.time > 700 ? letter : t.text + letter; t.time = now;
141
+ const hit = usable.find((o) => fold(o.label).startsWith(fold(t.text)));
142
+ if (hit) setAt(key(hit));
143
+ };
144
+ const control = { role: 'combobox', 'aria-haspopup': 'listbox' as const, 'aria-expanded': open, 'aria-controls': open ? list : undefined, 'aria-activedescendant': open && active ? optionId(active) : undefined };
145
+ const empty = value.length === 0;
146
+ const note = problem ? <p role="alert" className="danger px-3 py-2 text-sm">{problem}</p>
147
+ : load && !found ? (wait ? <InlineSkeleton /> : null)
148
+ : shown.length === 0 ? <p role="status" className="muted px-3 py-2 text-sm">{words ? t('table.empty') : t('form.noOptions')}</p> : null;
149
+ const groups = [...new Set(shown.map((o) => o.group ?? ''))];
150
+ const row = (o: Choice) => {
151
+ const on = value.includes(key(o));
152
+ return <div key={key(o)} id={optionId(o)} role="option" aria-selected={on} aria-disabled={off(o) || undefined} data-lk="option" data-active={o === active || undefined}
153
+ className="option flex items-start gap-2 px-3 py-2 text-sm" onPointerMove={() => off(o) || setAt(key(o))} onClick={() => pick(o)}>
154
+ <span className="min-w-0 flex-1"><span className="block break-words">{o.label}</span>{o.description && <span className="block text-xs opacity-70">{o.description}</span>}</span>
155
+ <span className={'mt-0.5 ' + (on ? '' : 'invisible')}><Icon name="check" className="size-4" /></span>
156
+ </div>;
157
+ };
158
+ return (
159
+ <div ref={box} data-lk="select" data-open={open || undefined} aria-invalid={invalid || undefined} className={'input flex items-center gap-1 !p-0 ' + className} onKeyDown={keys}>
160
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 self-stretch">
161
+ {multiple && value.map((v) => <span key={v} data-lk="chip" draggable={value.length > 1} onDragStart={(e) => { dragging.current = v; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', v); }} onDragOver={(e) => { if (dragging.current) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; } }} onDrop={(e) => { e.preventDefault(); reorder(v); }} onDragEnd={() => { dragging.current = undefined; }} className="badge ml-1 flex max-w-full cursor-grab items-center gap-1 py-0.5 pr-1 pl-2 text-sm first:ml-2 active:cursor-grabbing"><span className="truncate">{chosen(v)}</span>
162
+ <button type="button" tabIndex={-1} aria-label={t('form.removeItem', { label: chosen(v) })} className="chip-remove" onClick={() => { onChange(value.filter((x) => x !== v)); button.current?.focus(); }}><Icon name="x" className="size-4" /></button></span>)}
163
+ <button ref={button} type="button" id={id} {...(searchable ? { role: 'combobox', 'aria-haspopup': 'dialog' as const, 'aria-expanded': open, 'aria-controls': open ? own + 'pop' : undefined } : control)} aria-label={label} aria-invalid={invalid || undefined} aria-describedby={describedBy}
164
+ className={'min-h-10 min-w-12 flex-1 truncate py-2 text-left focus-visible:outline-none ' + (multiple && !empty ? 'pl-1' : 'pl-3')} onClick={() => (open ? hide() : show())}>
165
+ {multiple ? (empty ? <span className="muted">{placeholder}</span> : <span className="sr-only">{value.map(chosen).join(', ')}</span>) : empty ? <span className="muted">{placeholder}</span> : chosen(value[0])}
166
+ </button>
167
+ </div>
168
+ {clearable && !empty && <button type="button" data-lk="clear" aria-label={t('table.clear')} className="icon-btn" onClick={() => { onChange([]); button.current?.focus(); }}><Icon name="x" className="size-4" /></button>}
169
+ <span aria-hidden="true" className={'muted mr-3 transition-transform motion-reduce:transition-none ' + (open ? 'rotate-180' : '')} onClick={() => (open ? hide() : show())}><Icon name="down" className="size-4" /></span>
170
+ {open && <div ref={popup} id={own + 'pop'} role={searchable ? 'dialog' : undefined} aria-label={searchable ? label ?? placeholder : undefined} popover="manual" data-lk="options" className="popup surface border shadow-lg" onBlur={(e) => { const to = e.relatedTarget as Node | null; if (to && !popup.current?.contains(to) && !box.current?.contains(to)) hide(false); }}>
171
+ {searchable && <div className="border-b"><input ref={input} {...control} aria-label={t('search.label')} aria-autocomplete="list" autoComplete="off" className="search w-full px-3 py-2.5 text-sm" placeholder={t('search.label')} value={query} onChange={(e) => { setQuery(e.target.value); setAt(undefined); }} /></div>}
172
+ <div id={list} role="listbox" aria-label={label ?? t('form.options')} aria-multiselectable={multiple || undefined} className="min-h-0 flex-1 overflow-y-auto p-1" onPointerDown={(e) => e.preventDefault()}>
173
+ {groups.map((g) => {
174
+ const rows: ReactNode = shown.filter((o) => (o.group ?? '') === g).map(row);
175
+ return g ? <div key={g} role="group" aria-label={g}><p aria-hidden="true" data-lk="group" className="muted px-3 pt-2 pb-1 text-xs font-semibold">{g}</p>{rows}</div> : <div key="" role="presentation">{rows}</div>;
176
+ })}
177
+ {adding && <div role="presentation" className="sticky -bottom-1 surface-fill"><div id={optionId(adding)} role="option" aria-selected={false} data-lk="new-option" data-active={adding === active || undefined} className="option flex items-center gap-2 px-3 py-2 text-sm"
178
+ onPointerMove={() => setAt(NEW)} onClick={() => pick(adding)}><Icon name="plus" className="size-4" /><span className="min-w-0 break-words">{adding.label}</span></div></div>}
179
+ </div>
180
+ {note}
181
+ {more && <p className="muted border-t px-3 py-2 text-xs">{t('form.moreOptions')}</p>}
182
+ {multiple && <div className="flex items-center gap-3 border-t px-3 py-2 text-xs">
183
+ <span role="status" className="muted mr-auto">{t('form.chosenCount', { count: maxItems ? `${value.length} / ${maxItems}` : value.length })}</span>
184
+ {!load && !maxItems && <button type="button" data-lk="all" className="underline" onClick={() => onChange([...new Set([...value, ...matches.filter((o) => !o.disabled).map(key)])])}>{t('form.all')}</button>}
185
+ {!empty && <button type="button" data-lk="none" className="underline" onClick={() => onChange([])}>{t('form.none')}</button>}
186
+ </div>}
187
+ </div>}
188
+ </div>
189
+ );
190
+ }
191
+
192
+ /** The select of a form field: the options come with the field or from the server. */
193
+ export function FieldSelect({ url, options = [], settings = {}, value, onKnown, ...rest }: Omit<Props, 'options' | 'chosen' | 'load'> & { url: string; options?: Choice[]; onKnown: (c: Choice[]) => void }) {
194
+ const t = useT();
195
+ const [known, learn] = useLabels(url, options, settings, value, onKnown);
196
+ const chosen = (v: string) => known[v] ?? v;
197
+ const [typed, setTyped] = useState<string>();
198
+ if (settings.native) return (
199
+ <select id={rest.id} className="input" aria-invalid={rest.invalid} aria-describedby={rest.describedBy} value={value[0] ?? ''} onChange={(e) => rest.onChange(e.target.value ? [e.target.value] : [])}>
200
+ {(settings.clearable || !value.length) && <option value="">{settings.placeholder ?? t('form.selectPlaceholder')}</option>}
201
+ {!!value.length && !options.some((o) => key(o) === value[0]) && <option>{value[0]}</option>}
202
+ {[...new Set(options.map((o) => o.group ?? ''))].map((g) => {
203
+ const rows = options.filter((o) => (o.group ?? '') === g).map((o) => <option key={key(o)} value={key(o)} disabled={o.disabled}>{o.label}</option>);
204
+ return g ? <optgroup key={g} label={g}>{rows}</optgroup> : rows;
205
+ })}
206
+ </select>
207
+ );
208
+ const load: Load | undefined = settings.remote ? async (query, signal) => {
209
+ const answer = await api<Answer>(`${url}?${new URLSearchParams({ search: query })}`, 'GET', undefined, signal);
210
+ learn(answer.options);
211
+ return answer;
212
+ } : undefined;
213
+ return <>
214
+ <Select {...rest} value={value} options={options} settings={settings} chosen={chosen} load={load} create={settings.create && setTyped} />
215
+ {settings.create && typed !== undefined && <NewOption url={url} fields={settings.create.fields} typed={typed} close={(made) => {
216
+ setTyped(undefined);
217
+ if (made) { learn([made]); rest.onChange(settings.multiple ? [...value, key(made)] : [key(made)]); }
218
+ }} />}
219
+ </>;
220
+ }
221
+
222
+ /** Labels for values, also for ones that no search has brought yet. */
223
+ export function useLabels(url: string, options: Choice[], settings: Choosing, value: string[], onKnown?: (c: Choice[]) => void) {
224
+ const [extra, setExtra] = useState<Record<string, string>>({});
225
+ // Someone who only looks at a record gets the labels through it.
226
+ const record = useContext(RecordId);
227
+ const known = { ...extra, ...Object.fromEntries(options.map((o) => [key(o), o.label])) };
228
+ const learn = (list: Choice[]) => { onKnown?.(list); setExtra((old) => ({ ...old, ...Object.fromEntries(list.map((o) => [key(o), o.label])) })); };
229
+ const missing = settings.remote ? value.filter((v) => !(v in known)) : [];
230
+ useEffect(() => {
231
+ if (!missing.length) return;
232
+ const stop = new AbortController();
233
+ const query = new URLSearchParams([...missing.slice(0, SHOWN).map((v) => ['value', v]), ...(record ? [['record', record]] : [])]);
234
+ // Without an answer the value itself is shown.
235
+ api<Answer>(`${url}?${query}`, 'GET', undefined, stop.signal).then((a) => learn(a.options)).catch(() => {});
236
+ return () => stop.abort();
237
+ }, [missing.join('\n')]);
238
+ return [known, learn] as const;
239
+ }
240
+
241
+ export function Labels({ url, options = [], settings = {}, value }: { url: string; options?: Choice[]; settings?: Choosing; value: string[] }) {
242
+ const [known] = useLabels(url, options, settings, value);
243
+ return <>{value.map((v) => known[v] ?? v).join(', ')}</>;
244
+ }