@larakit/react 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/package.json +30 -4
  2. package/src/Cell.tsx +35 -0
  3. package/src/Dashboard.tsx +79 -0
  4. package/src/Field.tsx +132 -0
  5. package/src/FileInput.tsx +76 -0
  6. package/src/Form.tsx +116 -0
  7. package/src/Layout.tsx +250 -0
  8. package/src/PanelPages.tsx +115 -0
  9. package/src/Repeater.tsx +46 -0
  10. package/src/ResourceIndex.tsx +271 -0
  11. package/src/action-upload.test.tsx +44 -0
  12. package/src/blocks.tsx +26 -0
  13. package/src/button-part.test.tsx +42 -0
  14. package/src/components.test.ts +22 -0
  15. package/src/components.tsx +435 -0
  16. package/src/confirm.test.tsx +68 -0
  17. package/src/context.tsx +19 -0
  18. package/src/custom-pages.test.tsx +177 -0
  19. package/src/errors.test.tsx +95 -0
  20. package/src/fixtures.ts +20 -0
  21. package/src/index.ts +29 -0
  22. package/src/kit/api.ts +305 -0
  23. package/src/kit/auth.tsx +109 -0
  24. package/src/kit/bridge.tsx +142 -0
  25. package/src/kit/button.tsx +396 -0
  26. package/src/kit/cell.tsx +260 -0
  27. package/src/kit/charts.tsx +638 -0
  28. package/src/kit/create.tsx +166 -0
  29. package/src/kit/dashboard.tsx +335 -0
  30. package/src/kit/dates.tsx +62 -0
  31. package/src/kit/entry.tsx +87 -0
  32. package/src/kit/field.tsx +449 -0
  33. package/src/kit/fields/CodeEditor.tsx +157 -0
  34. package/src/kit/fields/KeyValue.tsx +215 -0
  35. package/src/kit/fields/MarkdownEditor.tsx +380 -0
  36. package/src/kit/fields/OneTimeCode.tsx +192 -0
  37. package/src/kit/fields/Repeater.tsx +350 -0
  38. package/src/kit/fields/Slider.tsx +185 -0
  39. package/src/kit/fields/TagsInput.tsx +219 -0
  40. package/src/kit/filters.tsx +214 -0
  41. package/src/kit/form-shared.tsx +62 -0
  42. package/src/kit/form.tsx +253 -0
  43. package/src/kit/hooks.ts +119 -0
  44. package/src/kit/i18n.tsx +67 -0
  45. package/src/kit/icons.tsx +190 -0
  46. package/src/kit/infolist.tsx +452 -0
  47. package/src/kit/kit.test.tsx +2200 -0
  48. package/src/kit/layout.tsx +236 -0
  49. package/src/kit/loading.tsx +120 -0
  50. package/src/kit/notice.tsx +72 -0
  51. package/src/kit/page.tsx +103 -0
  52. package/src/kit/pageform.tsx +75 -0
  53. package/src/kit/picker.tsx +110 -0
  54. package/src/kit/plugins.tsx +206 -0
  55. package/src/kit/profile.tsx +86 -0
  56. package/src/kit/relations.tsx +146 -0
  57. package/src/kit/rich.tsx +276 -0
  58. package/src/kit/search.tsx +92 -0
  59. package/src/kit/select.tsx +244 -0
  60. package/src/kit/shell.tsx +401 -0
  61. package/src/kit/table-extras.tsx +457 -0
  62. package/src/kit/table.tsx +734 -0
  63. package/src/kit/theme.ts +57 -0
  64. package/src/layout-parts.test.tsx +159 -0
  65. package/src/pages/index.ts +7 -0
  66. package/src/part.test.tsx +56 -0
  67. package/src/plugins.test.tsx +159 -0
  68. package/src/plugins.tsx +240 -0
  69. package/src/preview.test.tsx +81 -0
  70. package/src/rail.test.tsx +56 -0
  71. package/src/repeater.test.tsx +48 -0
  72. package/src/resource-pages.test.tsx +119 -0
  73. package/src/screens.test.tsx +121 -0
  74. package/src/ssr.test.tsx +86 -0
  75. package/src/tenant.test.tsx +94 -0
  76. package/src/ui.tsx +100 -0
  77. package/theme.css +467 -0
  78. package/README.md +0 -3
@@ -0,0 +1,457 @@
1
+ import { useId, useRef, useState, type KeyboardEvent } from 'react';
2
+ import {
3
+ api,
4
+ fail,
5
+ text,
6
+ type ColumnSummaries,
7
+ type GroupOption,
8
+ type ImportColumn,
9
+ type ImportConfig,
10
+ type ImportResult,
11
+ type Look,
12
+ type Resource,
13
+ type Row,
14
+ type SummaryResult,
15
+ type SummarySpec,
16
+ type TableTab,
17
+ } from './api';
18
+ import { LayoutPart } from '../components';
19
+ import { KitDefault } from './bridge';
20
+ import { Badge, Btn, Modal } from './button';
21
+ import { shown } from './cell';
22
+ import { intlLocale, useI18n, useT } from './i18n';
23
+ import { Icon } from './icons';
24
+
25
+ type TableTabsArgs = { tabs: TableTab[]; active: string; counts?: Record<string, number>; onChange: (name: string) => void };
26
+
27
+ /**
28
+ * Pill/tab bar rendered above the table card when `resource.tabs` is configured. It is the `tabs` part: the application's
29
+ * component that `part("tabs", ...)` names gets the tabs (the badge is the tab's count) and `Default`, Larakit's bar.
30
+ */
31
+ export function TableTabs(args: TableTabsArgs) {
32
+ const { tabs, active, counts, onChange } = args;
33
+ if (!tabs.length) return null;
34
+ const current = tabs.some((tab) => tab.name === active) ? active : tabs[0].name;
35
+ const props = {
36
+ tabs: tabs.map((tab) => ({ name: tab.name, label: tab.label, badge: counts?.[tab.name], color: tab.color })),
37
+ active: current, select: onChange, __own: DefaultTableTabs, __kit: args,
38
+ };
39
+ return <LayoutPart part="tabs" props={props as never} Default={KitDefault} />;
40
+ }
41
+
42
+ function DefaultTableTabs({ tabs, active, counts, onChange }: TableTabsArgs) {
43
+ const t = useT();
44
+ const { dir } = useI18n();
45
+ const id = useId();
46
+ if (!tabs.length) return null;
47
+
48
+ const current = tabs.some((tab) => tab.name === active) ? active : tabs[0].name;
49
+
50
+ const onKeyDown = (e: KeyboardEvent, index: number) => {
51
+ const forward = dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight';
52
+ const backward = dir === 'rtl' ? 'ArrowRight' : 'ArrowLeft';
53
+ const nextIndex =
54
+ e.key === forward
55
+ ? (index + 1) % tabs.length
56
+ : e.key === backward
57
+ ? (index - 1 + tabs.length) % tabs.length
58
+ : e.key === 'Home'
59
+ ? 0
60
+ : e.key === 'End'
61
+ ? tabs.length - 1
62
+ : -1;
63
+ if (nextIndex < 0) return;
64
+ e.preventDefault();
65
+ const target = tabs[nextIndex];
66
+ onChange(target.name);
67
+ document.getElementById(`${id}-tab-${target.name}`)?.focus();
68
+ };
69
+
70
+ return (
71
+ <div
72
+ data-lk="table-tabs"
73
+ role="tablist"
74
+ aria-label={t('table.tabs')}
75
+ className="table-tabs flex flex-wrap items-center gap-1.5"
76
+ >
77
+ {tabs.map((tab, index) => {
78
+ const selected = tab.name === current;
79
+ const count = counts?.[tab.name];
80
+ return (
81
+ <button
82
+ key={tab.name}
83
+ id={`${id}-tab-${tab.name}`}
84
+ type="button"
85
+ role="tab"
86
+ data-lk="table-tab"
87
+ data-name={tab.name}
88
+ data-color={selected && tab.color ? tab.color : undefined}
89
+ aria-selected={selected}
90
+ tabIndex={selected ? 0 : -1}
91
+ className="table-tab inline-flex items-center gap-1.5 border px-3 py-1.5 text-sm font-medium whitespace-nowrap"
92
+ onClick={() => onChange(tab.name)}
93
+ onKeyDown={(e) => onKeyDown(e, index)}
94
+ >
95
+ {tab.icon && <Icon name={tab.icon} className="size-4 shrink-0" />}
96
+ <span>{tab.label}</span>
97
+ {typeof count === 'number' && (
98
+ <Badge label={count.toLocaleString(intlLocale())} color={tab.color} />
99
+ )}
100
+ </button>
101
+ );
102
+ })}
103
+ </div>
104
+ );
105
+ }
106
+
107
+ export type GroupState = { key: string; dir: 'asc' | 'desc' };
108
+
109
+ /** Toolbar dropdown + Asc/Desc toggle for row grouping. */
110
+ export function GroupControls({
111
+ groups,
112
+ value,
113
+ onChange,
114
+ }: {
115
+ groups: GroupOption[];
116
+ value: GroupState;
117
+ onChange: (next: GroupState) => void;
118
+ }) {
119
+ const t = useT();
120
+ if (!groups.length) return null;
121
+ return (
122
+ <div className="inline-flex items-center gap-1">
123
+ <select
124
+ data-lk="group-select"
125
+ aria-label={t('table.groupBy')}
126
+ className="input w-auto py-1.5 text-sm"
127
+ value={value.key}
128
+ onChange={(e) => onChange({ ...value, key: e.target.value })}
129
+ >
130
+ <option value="">{t('table.groupNone')}</option>
131
+ {groups.map((g) => (
132
+ <option key={g.key} value={g.key}>
133
+ {g.label}
134
+ </option>
135
+ ))}
136
+ </select>
137
+ {value.key && (
138
+ <button
139
+ type="button"
140
+ data-lk="group-dir"
141
+ className="tool"
142
+ title={value.dir === 'asc' ? t('table.groupAsc') : t('table.groupDesc')}
143
+ aria-label={value.dir === 'asc' ? t('table.groupAsc') : t('table.groupDesc')}
144
+ onClick={() => onChange({ ...value, dir: value.dir === 'asc' ? 'desc' : 'asc' })}
145
+ >
146
+ <Icon name={value.dir === 'asc' ? 'arrow-up' : 'arrow-down'} className="size-4" />
147
+ </button>
148
+ )}
149
+ </div>
150
+ );
151
+ }
152
+
153
+ export type RowGroup = { key: string; display: string; rows: Row[] };
154
+
155
+ /** Groups visible rows by `group.key` and sorts groups according to `group.dir`. */
156
+ export function groupRows(
157
+ rows: Row[],
158
+ group: { key: string; dir: 'asc' | 'desc' },
159
+ columnLook: Look | undefined,
160
+ emptyLabel: string,
161
+ ): RowGroup[] {
162
+ const buckets = new Map<string, { display: string; rows: Row[] }>();
163
+ for (const row of rows) {
164
+ const raw = row.cells[group.key];
165
+ const key = raw === null || raw === undefined || raw === '' ? '' : String(raw);
166
+ let bucket = buckets.get(key);
167
+ if (!bucket) {
168
+ const display =
169
+ key === ''
170
+ ? emptyLabel
171
+ : columnLook?.labels?.[key] ?? (shown(raw, columnLook) || key);
172
+ bucket = { display, rows: [] };
173
+ buckets.set(key, bucket);
174
+ }
175
+ bucket.rows.push(row);
176
+ }
177
+ const factor = group.dir === 'desc' ? -1 : 1;
178
+ return [...buckets.entries()]
179
+ .sort(([aKey, a], [bKey, b]) => {
180
+ if (aKey === '' && bKey !== '') return 1;
181
+ if (bKey === '' && aKey !== '') return -1;
182
+ return a.display.localeCompare(b.display, intlLocale(), { numeric: true, sensitivity: 'base' }) * factor;
183
+ })
184
+ .map(([key, bucket]) => ({ key, display: bucket.display, rows: bucket.rows }));
185
+ }
186
+
187
+ /** Resolves either legacy array summaries or protocol `{ [kind]: value }` summary maps alongside column specs. */
188
+ export function resolveColumnSummaries(
189
+ raw?: ColumnSummaries,
190
+ specs?: SummarySpec[],
191
+ ): { item: SummaryResult; spec?: SummarySpec }[] {
192
+ if (!raw) return [];
193
+ if (Array.isArray(raw)) {
194
+ return raw.map((item, i) => ({ item, spec: specs?.[i] }));
195
+ }
196
+ if (typeof raw !== 'object') return [];
197
+ const entries = raw as Record<string, unknown>;
198
+ const used = new Set<string>();
199
+ const resolved: { item: SummaryResult; spec?: SummarySpec }[] = [];
200
+ for (const spec of specs ?? []) {
201
+ const key = spec.kind ?? spec.type ?? '';
202
+ if (!key || !Object.prototype.hasOwnProperty.call(entries, key)) continue;
203
+ used.add(key);
204
+ resolved.push({
205
+ item: {
206
+ kind: key,
207
+ type: key,
208
+ label: spec.label,
209
+ hiddenLabel: spec.hiddenLabel,
210
+ value: entries[key],
211
+ },
212
+ spec,
213
+ });
214
+ }
215
+ for (const [key, value] of Object.entries(entries)) {
216
+ if (used.has(key)) continue;
217
+ resolved.push({ item: { kind: key, type: key, value } });
218
+ }
219
+ return resolved;
220
+ }
221
+
222
+ /** Formats a summary result value using `shown()` for money/number/decimals/cents/prefix/suffix. */
223
+ export function formatSummaryValue(
224
+ item: SummaryResult,
225
+ columnLook?: Look,
226
+ spec?: SummarySpec,
227
+ ): string {
228
+ const kind = item.kind ?? item.type ?? spec?.kind ?? spec?.type;
229
+ const hasExplicitFormat = !!(
230
+ item.look?.format ||
231
+ item.format ||
232
+ spec?.look?.format ||
233
+ spec?.format ||
234
+ item.currency ||
235
+ item.look?.currency ||
236
+ spec?.currency ||
237
+ spec?.look?.currency ||
238
+ item.cents !== undefined ||
239
+ spec?.cents !== undefined ||
240
+ item.decimals !== undefined ||
241
+ spec?.decimals !== undefined
242
+ );
243
+ // Count summaries on a money/date column shouldn't inherit the column's currency format unless specified.
244
+ const baseLook: Look = kind === 'count' && !hasExplicitFormat ? { format: 'number' } : (columnLook ?? {});
245
+ const specFlatLook: Look = {
246
+ ...(spec?.format !== undefined ? { format: spec.format } : {}),
247
+ ...(spec?.decimals !== undefined ? { decimals: spec.decimals } : {}),
248
+ ...(spec?.currency !== undefined ? { currency: spec.currency } : {}),
249
+ ...(spec?.cents !== undefined ? { cents: spec.cents } : {}),
250
+ ...(spec?.prefix !== undefined ? { prefix: spec.prefix } : {}),
251
+ ...(spec?.suffix !== undefined ? { suffix: spec.suffix } : {}),
252
+ };
253
+ const merged: Look = {
254
+ ...baseLook,
255
+ ...spec?.look,
256
+ ...specFlatLook,
257
+ ...item.look,
258
+ ...(item.format !== undefined ? { format: item.format } : {}),
259
+ ...(item.decimals !== undefined ? { decimals: item.decimals } : {}),
260
+ ...(item.currency !== undefined ? { currency: item.currency } : {}),
261
+ ...(item.cents !== undefined ? { cents: item.cents } : {}),
262
+ ...(item.prefix !== undefined ? { prefix: item.prefix } : {}),
263
+ ...(item.suffix !== undefined ? { suffix: item.suffix } : {}),
264
+ };
265
+ return shown(item.value, merged);
266
+ }
267
+
268
+ /** CSV import dialog displaying expected columns, upload dropzone, progress, and per-row error results. */
269
+ export function ImportModal({
270
+ resource,
271
+ baseUrl,
272
+ config,
273
+ onClose,
274
+ onImported,
275
+ }: {
276
+ resource: Resource;
277
+ baseUrl?: string;
278
+ config: boolean | ImportConfig;
279
+ onClose: () => void;
280
+ onImported: () => void;
281
+ }) {
282
+ const t = useT();
283
+ const titleId = useId();
284
+ const inputRef = useRef<HTMLInputElement>(null);
285
+ const [file, setFile] = useState<File | null>(null);
286
+ const [over, setOver] = useState(false);
287
+ const [busy, setBusy] = useState(false);
288
+ const [error, setError] = useState('');
289
+ const [result, setResult] = useState<ImportResult | null>(null);
290
+
291
+ const cfg: ImportConfig = typeof config === 'object' && config !== null ? config : {};
292
+ const expectedColumns: ImportColumn[] = cfg.columns?.length
293
+ ? cfg.columns
294
+ : resource.fields
295
+ .filter((f) => f.type !== 'hidden')
296
+ .map((f) => ({ key: f.key, label: f.label, required: !!f.look?.required }));
297
+
298
+ const accept = cfg.accept?.length ? cfg.accept.join(',') : '.csv,text/csv';
299
+
300
+ const pickFile = (picked: File | null) => {
301
+ setError('');
302
+ setResult(null);
303
+ setFile(picked);
304
+ };
305
+
306
+ const upload = async () => {
307
+ if (!file || busy) return;
308
+ setBusy(true);
309
+ setError('');
310
+ try {
311
+ const form = new FormData();
312
+ form.append('file', file);
313
+ const res = await api<ImportResult>(`${baseUrl ?? `/${resource.name}`}/import`, 'POST', form);
314
+ setResult(res);
315
+ if (res.imported > 0) onImported();
316
+ } catch (e) {
317
+ setError(fail(e));
318
+ } finally {
319
+ setBusy(false);
320
+ }
321
+ };
322
+
323
+ return (
324
+ <Modal kind="ask" dataLk="import-modal" titleId={titleId} widthClass="max-w-lg" portal onClose={onClose}>
325
+ <div className="space-y-4">
326
+ <div className="flex items-center gap-2">
327
+ <h2 id={titleId} className="mr-auto text-lg font-semibold">
328
+ {t('table.importTitle', { label: resource.label })}
329
+ </h2>
330
+ <button type="button" className="icon-btn" aria-label={t('form.close')} onClick={onClose}>
331
+ <Icon name="x" className="size-4" />
332
+ </button>
333
+ </div>
334
+
335
+ {expectedColumns.length > 0 && (
336
+ <div data-lk="import-columns" className="space-y-2">
337
+ <p className="text-xs font-medium text-[var(--lk-muted)]">{t('table.importExpectedColumns')}</p>
338
+ <ul className="flex flex-wrap gap-1.5">
339
+ {expectedColumns.map((col) => (
340
+ <li key={col.key} className="badge inline-flex items-center gap-1.5 px-2 py-1 text-xs">
341
+ <span>{col.label}</span>
342
+ <code className="opacity-75">({col.key})</code>
343
+ {col.required && (
344
+ <Badge label={t('table.importRequired')} color="warning" />
345
+ )}
346
+ </li>
347
+ ))}
348
+ </ul>
349
+ </div>
350
+ )}
351
+
352
+ <div
353
+ data-lk="import-dropzone"
354
+ data-over={over || undefined}
355
+ className="dropzone p-5 text-center"
356
+ onDragOver={(e) => {
357
+ e.preventDefault();
358
+ setOver(true);
359
+ }}
360
+ onDragLeave={() => setOver(false)}
361
+ onDrop={(e) => {
362
+ e.preventDefault();
363
+ setOver(false);
364
+ pickFile(e.dataTransfer.files?.[0] ?? null);
365
+ }}
366
+ >
367
+ <input
368
+ ref={inputRef}
369
+ data-lk="import-file"
370
+ type="file"
371
+ accept={accept}
372
+ className="sr-only"
373
+ aria-label={t('table.importChooseFile')}
374
+ onChange={(e) => pickFile(e.target.files?.[0] ?? null)}
375
+ />
376
+ <Icon name="upload" className="muted mx-auto mb-2 size-6" />
377
+ <div className="flex flex-wrap items-center justify-center gap-1.5 text-sm">
378
+ <button
379
+ type="button"
380
+ className="font-semibold underline"
381
+ onClick={() => inputRef.current?.click()}
382
+ >
383
+ {t('table.importChooseFile')}
384
+ </button>
385
+ <span className="muted">{t('table.importDropHint')}</span>
386
+ </div>
387
+ {file && (
388
+ <p data-lk="import-filename" className="mt-2 text-xs font-medium">
389
+ {file.name}
390
+ </p>
391
+ )}
392
+ </div>
393
+
394
+ {busy && (
395
+ <div role="status" data-lk="import-progress" className="flex items-center gap-2 text-sm">
396
+ <Icon name="loader" className="size-4 animate-spin" />
397
+ <span>{t('table.importUploading')}</span>
398
+ </div>
399
+ )}
400
+
401
+ {error && (
402
+ <p role="alert" data-lk="import-error" className="danger text-sm">
403
+ {error}
404
+ </p>
405
+ )}
406
+
407
+ {result && (
408
+ <div data-lk="import-result" className="space-y-3 border-t pt-3">
409
+ <div className="flex flex-wrap items-center gap-2">
410
+ <Badge label={t('table.importImported', { count: result.imported })} color="success" />
411
+ <Badge
412
+ label={t('table.importFailed', { count: result.failed })}
413
+ color={result.failed > 0 ? 'danger' : 'gray'}
414
+ />
415
+ </div>
416
+ {result.errors && result.errors.length > 0 && (
417
+ <div className="max-h-48 overflow-auto border">
418
+ <table data-lk="import-errors" className="w-full text-left text-xs">
419
+ <thead className="table-head border-b">
420
+ <tr>
421
+ <th scope="col" className="px-3 py-2 font-medium">{t('table.importRow')}</th>
422
+ <th scope="col" className="px-3 py-2 font-medium">{t('table.importMessage')}</th>
423
+ </tr>
424
+ </thead>
425
+ <tbody>
426
+ {result.errors.map((err, i) => (
427
+ <tr key={i} className="border-b last:border-0">
428
+ <td className="px-3 py-1.5 font-medium tabular-nums">{err.row}</td>
429
+ <td className="px-3 py-1.5">
430
+ {err.column ? <span className="font-medium">{err.column}: </span> : null}
431
+ {err.message}
432
+ </td>
433
+ </tr>
434
+ ))}
435
+ </tbody>
436
+ </table>
437
+ </div>
438
+ )}
439
+ </div>
440
+ )}
441
+
442
+ <div className="flex justify-end gap-2 border-t pt-4">
443
+ <Btn dataLk="import-close" label={t('form.close')} onClick={onClose} />
444
+ <Btn
445
+ dataLk="import-submit"
446
+ variant="solid"
447
+ color="primary"
448
+ icon="upload"
449
+ label={t('table.importStart')}
450
+ disabled={!file || busy}
451
+ onClick={() => void upload()}
452
+ />
453
+ </div>
454
+ </div>
455
+ </Modal>
456
+ );
457
+ }