@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,215 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { useT } from '../i18n';
3
+ import { Icon } from '../icons';
4
+
5
+ type RowItem = { uid: number; key: string; val: string };
6
+
7
+ export type KeyValueProps = {
8
+ id: string;
9
+ value: Record<string, string>;
10
+ set: (v: Record<string, string>) => void;
11
+ invalid?: boolean;
12
+ describedBy?: string;
13
+ labelledBy?: string;
14
+ readOnly?: boolean;
15
+ keyLabel?: string;
16
+ valueLabel?: string;
17
+ keyPlaceholder?: string;
18
+ valuePlaceholder?: string;
19
+ addLabel?: string;
20
+ editableKeys?: boolean;
21
+ editableValues?: boolean;
22
+ reorderable?: boolean;
23
+ minItems?: number;
24
+ maxItems?: number;
25
+ };
26
+
27
+ function serializeRows(rows: RowItem[]): Record<string, string> {
28
+ const out: Record<string, string> = {};
29
+ for (const r of rows) {
30
+ if (r.key !== '') out[r.key] = r.val;
31
+ }
32
+ return out;
33
+ }
34
+
35
+ /** Editable key-value pair table with optional reordering and read-only keys/values. */
36
+ export function KeyValue({
37
+ id,
38
+ value,
39
+ set,
40
+ invalid,
41
+ describedBy,
42
+ labelledBy,
43
+ readOnly,
44
+ keyLabel,
45
+ valueLabel,
46
+ keyPlaceholder,
47
+ valuePlaceholder,
48
+ addLabel,
49
+ editableKeys = true,
50
+ editableValues = true,
51
+ reorderable = false,
52
+ minItems = 0,
53
+ maxItems,
54
+ }: KeyValueProps) {
55
+ const t = useT();
56
+ const uidRef = useRef(1);
57
+ const toRows = (obj: Record<string, string>): RowItem[] =>
58
+ Object.entries(obj ?? {}).map(([k, v]) => ({ uid: uidRef.current++, key: k, val: String(v ?? '') }));
59
+
60
+ const [rows, setRows] = useState<RowItem[]>(() => toRows(value));
61
+ const lastJson = useRef(JSON.stringify(value ?? {}));
62
+
63
+ useEffect(() => {
64
+ const incoming = JSON.stringify(value ?? {});
65
+ if (incoming !== lastJson.current) {
66
+ lastJson.current = incoming;
67
+ setRows(toRows(value));
68
+ }
69
+ }, [value]);
70
+
71
+ const commit = (next: RowItem[]) => {
72
+ setRows(next);
73
+ const map = serializeRows(next);
74
+ const nextJson = JSON.stringify(map);
75
+ if (nextJson !== lastJson.current) {
76
+ lastJson.current = nextJson;
77
+ set(map);
78
+ }
79
+ };
80
+
81
+ const kLabel = keyLabel ?? t('form.keyLabel');
82
+ const vLabel = valueLabel ?? t('form.valueLabel');
83
+ const canAdd = !readOnly && editableKeys && (maxItems === undefined || rows.length < maxItems);
84
+ const canDelete = !readOnly && editableKeys && rows.length > minItems;
85
+ const showActions = !readOnly && (reorderable || editableKeys);
86
+
87
+ const move = (index: number, delta: number) => {
88
+ const target = index + delta;
89
+ if (target < 0 || target >= rows.length) return;
90
+ const next = [...rows];
91
+ const [picked] = next.splice(index, 1);
92
+ next.splice(target, 0, picked);
93
+ commit(next);
94
+ };
95
+
96
+ return (
97
+ <div
98
+ id={id}
99
+ data-lk="keyvalue"
100
+ role="group"
101
+ aria-labelledby={labelledBy}
102
+ aria-describedby={describedBy}
103
+ aria-invalid={invalid || undefined}
104
+ className="kv-box surface border"
105
+ >
106
+ <table className="w-full border-collapse text-sm">
107
+ <thead>
108
+ <tr className="kv-head border-b">
109
+ <th scope="col" className="px-3 py-2 text-start font-medium">{kLabel}</th>
110
+ <th scope="col" className="px-3 py-2 text-start font-medium">{vLabel}</th>
111
+ {showActions && <th scope="col" className="w-px px-2 py-2"><span className="sr-only">{t('table.actions')}</span></th>}
112
+ </tr>
113
+ </thead>
114
+ <tbody>
115
+ {rows.length === 0 ? (
116
+ <tr>
117
+ <td colSpan={showActions ? 3 : 2} className="muted px-3 py-3 text-center text-xs">
118
+ {t('form.empty')}
119
+ </td>
120
+ </tr>
121
+ ) : (
122
+ rows.map((row, idx) => (
123
+ <tr key={row.uid} data-lk="kv-row" className="border-b last:border-b-0">
124
+ <td className="p-2 align-middle">
125
+ <input
126
+ type="text"
127
+ className="input text-sm"
128
+ value={row.key}
129
+ readOnly={readOnly || !editableKeys}
130
+ placeholder={keyPlaceholder ?? t('form.keyPlaceholder')}
131
+ aria-label={`${kLabel} ${idx + 1}`}
132
+ onChange={(e) => {
133
+ const next = rows.map((r, i) => (i === idx ? { ...r, key: e.target.value } : r));
134
+ commit(next);
135
+ }}
136
+ />
137
+ </td>
138
+ <td className="p-2 align-middle">
139
+ <input
140
+ type="text"
141
+ className="input text-sm"
142
+ value={row.val}
143
+ readOnly={readOnly || !editableValues}
144
+ placeholder={valuePlaceholder ?? t('form.valuePlaceholder')}
145
+ aria-label={`${vLabel} ${idx + 1}`}
146
+ onChange={(e) => {
147
+ const next = rows.map((r, i) => (i === idx ? { ...r, val: e.target.value } : r));
148
+ commit(next);
149
+ }}
150
+ />
151
+ </td>
152
+ {showActions && (
153
+ <td className="p-2 align-middle whitespace-nowrap">
154
+ <div className="flex items-center justify-end gap-1">
155
+ {reorderable && (
156
+ <>
157
+ <button
158
+ type="button"
159
+ data-lk="kv-up"
160
+ className="icon-btn"
161
+ disabled={idx === 0}
162
+ aria-label={t('form.moveUp')}
163
+ onClick={() => move(idx, -1)}
164
+ >
165
+ <Icon name="up" className="size-4" />
166
+ </button>
167
+ <button
168
+ type="button"
169
+ data-lk="kv-down"
170
+ className="icon-btn"
171
+ disabled={idx === rows.length - 1}
172
+ aria-label={t('form.moveDown')}
173
+ onClick={() => move(idx, 1)}
174
+ >
175
+ <Icon name="down" className="size-4" />
176
+ </button>
177
+ </>
178
+ )}
179
+ {canDelete && (
180
+ <button
181
+ type="button"
182
+ data-lk="kv-remove"
183
+ className="icon-btn danger"
184
+ aria-label={t('form.removeItem', { label: row.key || `#${idx + 1}` })}
185
+ onClick={() => commit(rows.filter((_, i) => i !== idx))}
186
+ >
187
+ <Icon name="trash" className="size-4" />
188
+ </button>
189
+ )}
190
+ </div>
191
+ </td>
192
+ )}
193
+ </tr>
194
+ ))
195
+ )}
196
+ </tbody>
197
+ </table>
198
+ {!readOnly && editableKeys && (
199
+ <div className="border-t p-2">
200
+ <button
201
+ type="button"
202
+ data-lk="kv-add"
203
+ disabled={!canAdd}
204
+ className="btn inline-flex items-center gap-1.5 text-xs"
205
+ data-size="sm"
206
+ onClick={() => setRows([...rows, { uid: uidRef.current++, key: '', val: '' }])}
207
+ >
208
+ <Icon name="plus" className="size-3.5" />
209
+ <span>{addLabel ?? t('form.addRow')}</span>
210
+ </button>
211
+ </div>
212
+ )}
213
+ </div>
214
+ );
215
+ }
@@ -0,0 +1,380 @@
1
+ import { useId, useRef, useState } from 'react';
2
+ import { useT } from '../i18n';
3
+ import { Icon } from '../icons';
4
+
5
+ const DEFAULT_TOOLBAR = ['bold', 'italic', 'strike', 'h2', 'h3', 'bulletList', 'orderedList', 'quote', 'code', 'link'];
6
+ const SAFE_URL = /^(https?:\/\/|\/)/i;
7
+ const UNSAFE_URL_CHARS = /[\s"'<>`]|&quot;|&#39;|&lt;|&gt;/i;
8
+
9
+ function escapeHtml(raw: string): string {
10
+ return raw
11
+ .replace(/&/g, '&amp;')
12
+ .replace(/</g, '&lt;')
13
+ .replace(/>/g, '&gt;')
14
+ .replace(/"/g, '&quot;')
15
+ .replace(/'/g, '&#39;');
16
+ }
17
+
18
+ function formatInline(escaped: string, slots: string[]): string {
19
+ // Preserve inline code spans before formatting bold/italic/links.
20
+ let out = escaped.replace(/`([^`\n]+)`/g, (_, code: string) => {
21
+ const idx = slots.push(`<code>${code}</code>`) - 1;
22
+ return `\u0000SLOT${idx}\u0000`;
23
+ });
24
+
25
+ out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (full, label: string, url: string) => {
26
+ const trimmed = url.trim();
27
+ if (!SAFE_URL.test(trimmed) || UNSAFE_URL_CHARS.test(trimmed)) return label;
28
+ const isExternal = /^https?:/i.test(trimmed);
29
+ const attrs = isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
30
+ return `<a href="${trimmed}"${attrs}>${label}</a>`;
31
+ });
32
+
33
+ out = out
34
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
35
+ .replace(/~~([^~]+)~~/g, '<del>$1</del>')
36
+ .replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
37
+
38
+ return out.replace(/\u0000SLOT(\d+)\u0000/g, (_, i: string) => slots[Number(i)] ?? '');
39
+ }
40
+
41
+ /** Converts Markdown to safe HTML by escaping all HTML entities first and allowlisting safe link URLs. */
42
+ export function markdownToHtml(md: string): string {
43
+ if (!md || !md.trim()) return '';
44
+ const escaped = escapeHtml(md.replace(/\r\n?/g, '\n'));
45
+ const slots: string[] = [];
46
+
47
+ // Extract fenced code blocks before block-level parsing.
48
+ const withFences = escaped.replace(/```[^\n]*\n([\s\S]*?)```/g, (_, body: string) => {
49
+ const idx = slots.push(`<pre><code>${body.replace(/\n$/, '')}</code></pre>`) - 1;
50
+ return `\n\u0000BLOCK${idx}\u0000\n`;
51
+ });
52
+
53
+ const lines = withFences.split('\n');
54
+ const html: string[] = [];
55
+ let listType: 'ul' | 'ol' | null = null;
56
+ let quoteLines: string[] = [];
57
+
58
+ const flushList = () => {
59
+ if (listType) {
60
+ html.push(`</${listType}>`);
61
+ listType = null;
62
+ }
63
+ };
64
+
65
+ const flushQuote = () => {
66
+ if (quoteLines.length) {
67
+ html.push(`<blockquote><p>${quoteLines.map((l) => formatInline(l, slots)).join('<br />')}</p></blockquote>`);
68
+ quoteLines = [];
69
+ }
70
+ };
71
+
72
+ for (const line of lines) {
73
+ const blockMatch = line.match(/^\u0000BLOCK(\d+)\u0000$/);
74
+ if (blockMatch) {
75
+ flushList();
76
+ flushQuote();
77
+ html.push(slots[Number(blockMatch[1])] ?? '');
78
+ continue;
79
+ }
80
+
81
+ const trimmed = line.trim();
82
+ if (!trimmed) {
83
+ flushList();
84
+ flushQuote();
85
+ continue;
86
+ }
87
+
88
+ if (/^###\s+/.test(trimmed)) {
89
+ flushList();
90
+ flushQuote();
91
+ html.push(`<h3>${formatInline(trimmed.replace(/^###\s+/, ''), slots)}</h3>`);
92
+ continue;
93
+ }
94
+ if (/^##\s+/.test(trimmed)) {
95
+ flushList();
96
+ flushQuote();
97
+ html.push(`<h2>${formatInline(trimmed.replace(/^##\s+/, ''), slots)}</h2>`);
98
+ continue;
99
+ }
100
+ if (/^#\s+/.test(trimmed)) {
101
+ flushList();
102
+ flushQuote();
103
+ html.push(`<h2>${formatInline(trimmed.replace(/^#\s+/, ''), slots)}</h2>`);
104
+ continue;
105
+ }
106
+
107
+ if (/^&gt;\s?/.test(trimmed)) {
108
+ flushList();
109
+ quoteLines.push(trimmed.replace(/^&gt;\s?/, ''));
110
+ continue;
111
+ }
112
+ flushQuote();
113
+
114
+ if (/^[-*+]\s+/.test(trimmed)) {
115
+ if (listType !== 'ul') {
116
+ flushList();
117
+ listType = 'ul';
118
+ html.push('<ul>');
119
+ }
120
+ html.push(`<li>${formatInline(trimmed.replace(/^[-*+]\s+/, ''), slots)}</li>`);
121
+ continue;
122
+ }
123
+
124
+ if (/^\d+\.\s+/.test(trimmed)) {
125
+ if (listType !== 'ol') {
126
+ flushList();
127
+ listType = 'ol';
128
+ html.push('<ol>');
129
+ }
130
+ html.push(`<li>${formatInline(trimmed.replace(/^\d+\.\s+/, ''), slots)}</li>`);
131
+ continue;
132
+ }
133
+
134
+ flushList();
135
+ html.push(`<p>${formatInline(trimmed, slots)}</p>`);
136
+ }
137
+
138
+ flushList();
139
+ flushQuote();
140
+ return html.join('\n');
141
+ }
142
+
143
+ export type MarkdownEditorProps = {
144
+ id: string;
145
+ value: string;
146
+ set: (v: string) => void;
147
+ invalid?: boolean;
148
+ describedBy?: string;
149
+ required?: boolean;
150
+ readOnly?: boolean;
151
+ placeholder?: string;
152
+ toolbar?: string[];
153
+ minHeight?: number;
154
+ maxHeight?: number;
155
+ };
156
+
157
+ type ToolDef = { id: string; labelKey: string; icon: string; run: () => void };
158
+
159
+ /** Markdown editor with formatting toolbar, Write/Preview tabs, and XSS-safe HTML preview. */
160
+ export function MarkdownEditor({
161
+ id,
162
+ value,
163
+ set,
164
+ invalid,
165
+ describedBy,
166
+ required,
167
+ readOnly,
168
+ placeholder,
169
+ toolbar = DEFAULT_TOOLBAR,
170
+ minHeight = 180,
171
+ maxHeight = 480,
172
+ }: MarkdownEditorProps) {
173
+ const t = useT();
174
+ const tabId = useId();
175
+ const areaRef = useRef<HTMLTextAreaElement>(null);
176
+ const linkInputRef = useRef<HTMLInputElement>(null);
177
+ const [tab, setTab] = useState<'write' | 'preview'>('write');
178
+ const [linkOpen, setLinkOpen] = useState(false);
179
+ const [linkUrl, setLinkUrl] = useState('https://');
180
+ const savedSel = useRef<{ start: number; end: number }>({ start: 0, end: 0 });
181
+
182
+ const wrapSelection = (before: string, after: string, fallbackText = '') => {
183
+ if (readOnly) return;
184
+ const el = areaRef.current;
185
+ const start = el ? el.selectionStart : value.length;
186
+ const end = el ? el.selectionEnd : value.length;
187
+ const selected = value.slice(start, end) || fallbackText;
188
+ const next = value.slice(0, start) + before + selected + after + value.slice(end);
189
+ set(next);
190
+ setTab('write');
191
+ requestAnimationFrame(() => {
192
+ if (!areaRef.current) return;
193
+ areaRef.current.focus();
194
+ const posStart = start + before.length;
195
+ areaRef.current.setSelectionRange(posStart, posStart + selected.length);
196
+ });
197
+ };
198
+
199
+ const prefixLine = (prefix: string) => {
200
+ if (readOnly) return;
201
+ const el = areaRef.current;
202
+ const start = el ? el.selectionStart : value.length;
203
+ const lineStart = value.lastIndexOf('\n', start - 1) + 1;
204
+ const next = value.slice(0, lineStart) + prefix + value.slice(lineStart);
205
+ set(next);
206
+ setTab('write');
207
+ requestAnimationFrame(() => {
208
+ if (!areaRef.current) return;
209
+ areaRef.current.focus();
210
+ const cursor = start + prefix.length;
211
+ areaRef.current.setSelectionRange(cursor, cursor);
212
+ });
213
+ };
214
+
215
+ const openLinkPopover = () => {
216
+ if (readOnly) return;
217
+ if (linkOpen) {
218
+ setLinkOpen(false);
219
+ return;
220
+ }
221
+ const el = areaRef.current;
222
+ savedSel.current = {
223
+ start: el ? el.selectionStart : value.length,
224
+ end: el ? el.selectionEnd : value.length,
225
+ };
226
+ setLinkUrl('https://');
227
+ setLinkOpen(true);
228
+ requestAnimationFrame(() => linkInputRef.current?.focus());
229
+ };
230
+
231
+ const applyLink = () => {
232
+ const trimmed = linkUrl.trim();
233
+ if (!trimmed || !SAFE_URL.test(trimmed)) {
234
+ setLinkOpen(false);
235
+ return;
236
+ }
237
+ const { start, end } = savedSel.current;
238
+ const label = value.slice(start, end) || 'link';
239
+ const inserted = `[${label}](${trimmed})`;
240
+ set(value.slice(0, start) + inserted + value.slice(end));
241
+ setLinkOpen(false);
242
+ setTab('write');
243
+ requestAnimationFrame(() => {
244
+ areaRef.current?.focus();
245
+ });
246
+ };
247
+
248
+ const tools: Record<string, ToolDef> = {
249
+ bold: { id: 'bold', labelKey: 'rich.bold', icon: 'bold', run: () => wrapSelection('**', '**', 'bold') },
250
+ italic: { id: 'italic', labelKey: 'rich.italic', icon: 'italic', run: () => wrapSelection('*', '*', 'italic') },
251
+ strike: { id: 'strike', labelKey: 'rich.strike', icon: 'strike', run: () => wrapSelection('~~', '~~', 'text') },
252
+ h2: { id: 'h2', labelKey: 'rich.h2', icon: 'h2', run: () => prefixLine('## ') },
253
+ h3: { id: 'h3', labelKey: 'rich.h3', icon: 'h3', run: () => prefixLine('### ') },
254
+ bulletList: { id: 'bulletList', labelKey: 'rich.bulletList', icon: 'list', run: () => prefixLine('- ') },
255
+ orderedList: { id: 'orderedList', labelKey: 'rich.orderedList', icon: 'list-ordered', run: () => prefixLine('1. ') },
256
+ quote: { id: 'quote', labelKey: 'rich.quote', icon: 'quote', run: () => prefixLine('> ') },
257
+ code: { id: 'code', labelKey: 'rich.code', icon: 'code', run: () => wrapSelection('`', '`', 'code') },
258
+ link: { id: 'link', labelKey: 'rich.link', icon: 'link', run: openLinkPopover },
259
+ };
260
+
261
+ const activeTools = toolbar.map((name) => tools[name]).filter(Boolean);
262
+ const previewHtml = tab === 'preview' ? markdownToHtml(value) : '';
263
+
264
+ return (
265
+ <div data-lk="markdown-editor" className="surface overflow-hidden border" aria-invalid={invalid || undefined}>
266
+ <div className="rich-toolbar flex flex-wrap items-center justify-between gap-2 border-b px-2 py-1.5">
267
+ <div role="tablist" className="flex items-center gap-1">
268
+ <button
269
+ type="button"
270
+ role="tab"
271
+ id={tabId + '-write'}
272
+ aria-selected={tab === 'write'}
273
+ className="btn px-2 py-1 text-xs"
274
+ data-variant={tab === 'write' ? 'soft' : 'ghost'}
275
+ data-color={tab === 'write' ? 'primary' : undefined}
276
+ data-size="xs"
277
+ onClick={() => setTab('write')}
278
+ >
279
+ {t('form.markdownWrite')}
280
+ </button>
281
+ <button
282
+ type="button"
283
+ role="tab"
284
+ id={tabId + '-preview'}
285
+ aria-selected={tab === 'preview'}
286
+ className="btn px-2 py-1 text-xs"
287
+ data-variant={tab === 'preview' ? 'soft' : 'ghost'}
288
+ data-color={tab === 'preview' ? 'primary' : undefined}
289
+ data-size="xs"
290
+ onClick={() => {
291
+ setLinkOpen(false);
292
+ setTab('preview');
293
+ }}
294
+ >
295
+ {t('form.markdownPreview')}
296
+ </button>
297
+ </div>
298
+
299
+ {tab === 'write' && !readOnly && (
300
+ <div role="toolbar" aria-label={t('rich.toolbar')} className="flex flex-wrap items-center gap-0.5">
301
+ {activeTools.map((tool) => (
302
+ <button
303
+ key={tool.id}
304
+ type="button"
305
+ className="rich-btn"
306
+ title={t(tool.labelKey)}
307
+ aria-label={t(tool.labelKey)}
308
+ aria-expanded={tool.id === 'link' ? linkOpen : undefined}
309
+ onMouseDown={(e) => e.preventDefault()}
310
+ onClick={tool.run}
311
+ >
312
+ <Icon name={tool.icon} className="size-4" />
313
+ </button>
314
+ ))}
315
+ </div>
316
+ )}
317
+ </div>
318
+
319
+ {linkOpen && (
320
+ <div className="rich-link-popover flex items-center gap-2 border-b px-3 py-2">
321
+ <input
322
+ ref={linkInputRef}
323
+ type="url"
324
+ className="input flex-1 text-sm"
325
+ value={linkUrl}
326
+ aria-label={t('rich.linkPrompt')}
327
+ placeholder="https://"
328
+ onChange={(e) => setLinkUrl(e.target.value)}
329
+ onKeyDown={(e) => {
330
+ if (e.key === 'Enter') {
331
+ e.preventDefault();
332
+ applyLink();
333
+ } else if (e.key === 'Escape') {
334
+ e.preventDefault();
335
+ setLinkOpen(false);
336
+ }
337
+ }}
338
+ />
339
+ <button type="button" className="btn" data-size="sm" data-variant="solid" data-color="primary" onClick={applyLink}>
340
+ {t('form.add')}
341
+ </button>
342
+ <button type="button" className="btn" data-size="sm" onClick={() => setLinkOpen(false)}>
343
+ {t('form.cancel')}
344
+ </button>
345
+ </div>
346
+ )}
347
+
348
+ {tab === 'write' ? (
349
+ <textarea
350
+ ref={areaRef}
351
+ id={id}
352
+ readOnly={readOnly}
353
+ value={value}
354
+ placeholder={placeholder}
355
+ aria-invalid={invalid || undefined}
356
+ aria-describedby={describedBy}
357
+ aria-required={required || undefined}
358
+ className="bare block w-full resize-y px-3 py-2.5 font-mono text-sm leading-6"
359
+ style={{ minHeight: `${minHeight}px`, maxHeight: `${maxHeight}px` }}
360
+ onChange={(e) => set(e.target.value)}
361
+ />
362
+ ) : (
363
+ <div
364
+ id={id}
365
+ role="tabpanel"
366
+ aria-labelledby={tabId + '-preview'}
367
+ data-lk="markdown-preview"
368
+ className="rich-content overflow-y-auto px-3 py-2.5 text-sm"
369
+ style={{ minHeight: `${minHeight}px`, maxHeight: `${maxHeight}px` }}
370
+ >
371
+ {previewHtml ? (
372
+ <div dangerouslySetInnerHTML={{ __html: previewHtml }} />
373
+ ) : (
374
+ <p className="muted text-sm">{t('form.markdownEmpty')}</p>
375
+ )}
376
+ </div>
377
+ )}
378
+ </div>
379
+ );
380
+ }