@xleddyl/443-components-vue 0.16.80 → 0.16.81

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.
package/CATALOG.md CHANGED
@@ -41,6 +41,7 @@ Playground paths in this file are relative to `playground/nuxt/app/pages/compone
41
41
  | Single line text | `Input` |
42
42
  | Multi line text | `Textarea` |
43
43
  | Rich text (bold, lists, links) | `RichTextEditor` (group `editor`) |
44
+ | Template with placeholders ({name} {size}) | `TemplateEditor`, `TemplateText` (group `editor`) |
44
45
  | Password with strength meter and generator | `PasswordInput` |
45
46
  | Number with stepper, locale format | `NumberInput` |
46
47
  | Money or unit prefix and suffix around an input | `InputGroup` + `InputAddon` |
@@ -310,9 +311,11 @@ Grid helpers: `registerGridModules`, `registerGridEditorModules`, `registerGridF
310
311
 
311
312
  ## Editor (group `editor`)
312
313
 
313
- | Component | Purpose and when to use it | Main props, models, slots, events | Playground |
314
- | ---------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
315
- | `RichTextEditor` | Rich text field (Tiptap): headings, bold, italic, lists, quote, code, links. Use `Textarea` for plain text. | Model: `v-model` (HTML string or JSON, per `format`). Props: `format` (html, json), `placeholder`, `readonly`, `disabled`, `invalid`, `required`, `maxLength`, `showCount`, `minHeight`, `maxHeight`, `toolbar` (items and `'\|'` separators, `'source'` for the raw value toggle), `source` (adds the raw value toggle to the default toolbar), `headings`, `headingLabel`, `linkTypes` (url, email, phone), `extensions`, `messages`. Works inside `FormField`. | `editor/rich-text-editor.vue` |
314
+ | Component | Purpose and when to use it | Main props, models, slots, events | Playground |
315
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
316
+ | `RichTextEditor` | Rich text field (Tiptap): headings, bold, italic, lists, quote, code, links. Use `Textarea` for plain text. | Model: `v-model` (HTML string or JSON, per `format`). Props: `format` (html, json), `placeholder`, `readonly`, `disabled`, `invalid`, `required`, `maxLength`, `showCount`, `minHeight`, `maxHeight`, `toolbar` (items and `'\|'` separators, `'source'` for the raw value toggle), `source` (adds the raw value toggle to the default toolbar), `headings`, `headingLabel`, `linkTypes` (url, email, phone), `extensions`, `messages`. Works inside `FormField`. | `editor/rich-text-editor.vue` |
317
+ | `TemplateEditor` | Single line template with `{key}` placeholders for users who do not know the syntax: each placeholder is one block with its label, an insert button lists the tokens with their description, a click on a block changes or removes it, typed or pasted `{key}` becomes a block. | Model: `v-model` (plain text with `{key}`). Props: `tokens` (`TemplateToken[]`: `key`, `label`, `description`, `group`), `preview` (result text under the field, empty shows `editor.previewEmpty`), `placeholder`, `readonly`, `disabled`, `invalid`, `required`, `maxLength` (of the stored text), `label`, `messages`. Slot: `preview` (`{ value }`). Works inside `FormField`. | `editor/template-editor.vue` |
318
+ | `TemplateText` | Read only render of a template value with the same blocks (lists, grid cells). | Props: `value`, `tokens`. Helpers: `templateParts(value, tokens)` (text and token parts, unknown `{key}` stays text), `templateToken(key)`, `TEMPLATE_TOKEN_PATTERN`. | `editor/template-editor.vue` |
316
319
 
317
320
  ## Chart (group `chart`)
318
321
 
package/README.md CHANGED
@@ -63,7 +63,7 @@ Every component is registered with the prefix (`Button.vue` becomes `<KButton>`)
63
63
  | `icons.defaultCollection` | none | Collection tried for names without a prefix that are not registered or built in. |
64
64
  | `icons.aliases` | `{}` | Replaces any icon, built-ins included: `{ 'x-mark': 'lucide:x', logo: 'brand-logo' }` (a collection icon or a file of `icons.dir`). |
65
65
  | `grid` | `false` | Registers `KDataGrid` and `KGridToolbar` and injects their CSS. An object (`{ density, columnMenu, exportable, pageSizes }`, `GridConfig`) does the same and sets these props for every grid of the app; a prop on a grid still wins. See [Grid defaults](#grid-defaults). |
66
- | `editor` | `false` | Registers `KRichTextEditor` and injects its CSS. |
66
+ | `editor` | `false` | Registers `KRichTextEditor`, `KTemplateEditor`, `KTemplateText` and injects their CSS. |
67
67
  | `chart` | `false` | Registers `KChartPanel`, `KChartLegend`, `KLineChart`, `KBarChart`, `KDoughnutChart` and injects their CSS. |
68
68
  | `layouts` | `false` | Registers the ready Nuxt layouts `k-dashboard` and `k-auth` (configured from `app.config.ts`, see [Layouts](#layouts-and-page-templates)). Pass `{ dashboard: 'admin', auth: false }` to rename or skip one. |
69
69
  | `cssTarget` | modern browsers | Sets `vite.build.cssTarget` when the host did not, so Lightning CSS keeps `light-dark()`. Pass `false` to leave the build target alone. |
@@ -471,7 +471,7 @@ async function switchView() {
471
471
  | templates | DashboardLayout, AuthLayout, AuthLogin, AuthLogout, DashboardPage, ListPage, DetailPage, FormPage, SettingsPage, SettingsSection, SettingsModal, SettingsGroup, AppearanceSettings, SaveBar, ErrorPage, NotFoundPage, EmptyPage, Brand, AccountMenu, FormDrawer |
472
472
  | feedback | Alert, EmptyState, LoadingOverlay, Meter, Progress, ProgressRing, Skeleton, SkeletonForm, SkeletonList |
473
473
  | grid | DataGrid, GridToolbar, cell renderers (BadgeCell, BooleanCell, ButtonCell, DateCell, EmptyCell, ImageCell, LinkCell) |
474
- | editor | RichTextEditor |
474
+ | editor | RichTextEditor, TemplateEditor, TemplateText |
475
475
  | chart | ChartPanel, ChartLegend, LineChart, BarChart, DoughnutChart |
476
476
 
477
477
  Composables: `useTheme`, `usePreset`, `useForm`, `useField`, `useFieldControl`, `useToast` (and `toast`), `useConfirm`, `useAlert`, `usePrompt`, `useModal`, `useDrawer`, `useOverlay`, `useModalContext`, `useLoading` (and `withLoading`), `useLoadingState`, `useHotkey`, `useCopy`, `useFileDrop` (with `readDroppedFiles`), `useSortable`, `usePasswordStrength`, `useTableSort`, `useAppShell`, `useRouteState`, `useRouteRecord`, `usePageCommands`, `usePreference` (with `usePreferences`, `createPreferences`, `providePreferences`), `useScrollLock`, `useLeaveGuard` (with `useLeaveScope`, `provideLeaveScope`), `useDirtyGuard`, `useIcons` helpers and `useLinkComponent`, `provideFieldBoundary`, `provideAuxiliaryControls`, `provideForm`, `provideGridConfig` (with `createGridConfig`, `useGridConfig`), `useLocale`. With the Nuxt module also `useDashboard()` (runtime account, breadcrumbs and badges for the `k-dashboard` layout) and `useNavigationPending()` (`true` while a navigation to another path renders the new page).
@@ -0,0 +1,390 @@
1
+ <template>
2
+ <div
3
+ class="k-template-editor"
4
+ :class="{
5
+ 'is-invalid': control.invalid.value,
6
+ 'is-disabled': control.disabled.value,
7
+ 'is-readonly': readonly
8
+ }"
9
+ data-k-shake
10
+ >
11
+ <div class="k-template-editor-row">
12
+ <EditorContent class="k-template-editor-content" :editor="editor" />
13
+ <Button
14
+ v-if="editable && tokens.length"
15
+ ref="insertRef"
16
+ variant="ghost"
17
+ tone="neutral"
18
+ size="xs"
19
+ icon="plus"
20
+ class="k-template-editor-insert"
21
+ :label="text.insertToken"
22
+ aria-haspopup="menu"
23
+ :aria-expanded="menuOpen && !menuTarget ? 'true' : 'false'"
24
+ @mousedown.prevent
25
+ @click="openInsertMenu"
26
+ />
27
+ </div>
28
+ <div v-if="showPreview" class="k-template-editor-preview">
29
+ <span class="k-template-editor-preview-label">{{ text.preview }}</span>
30
+ <span class="k-template-editor-preview-text">
31
+ <slot name="preview" :value="model">
32
+ <span v-if="preview" class="k-template-editor-preview-value">{{ preview }}</span>
33
+ <span v-else class="k-template-editor-preview-empty">{{ text.previewEmpty }}</span>
34
+ </slot>
35
+ </span>
36
+ </div>
37
+ <MenuList
38
+ ref="menuRef"
39
+ :items="menuItems"
40
+ :anchor="() => menuAnchor"
41
+ :label="text.tokens"
42
+ class="k-template-editor-menu"
43
+ @open-change="onMenuOpenChange"
44
+ />
45
+ </div>
46
+ </template>
47
+
48
+ <script setup>
49
+ import Placeholder from "@tiptap/extension-placeholder";
50
+ import StarterKit from "@tiptap/starter-kit";
51
+ import {
52
+ EditorContent,
53
+ Extension,
54
+ Node,
55
+ mergeAttributes,
56
+ nodeInputRule,
57
+ nodePasteRule,
58
+ useEditor
59
+ } from "@tiptap/vue-3";
60
+ import { Plugin, NodeSelection } from "@tiptap/pm/state";
61
+ import { computed, onBeforeUnmount, ref, shallowRef, useSlots, useTemplateRef, watch } from "vue";
62
+ import Button from "../components/core/Button.vue";
63
+ import { useFieldControl } from "../composables/useField";
64
+ import { useLocale } from "../composables/useLocale";
65
+ import MenuList from "../internal/overlays/MenuList.vue";
66
+ import { templateParts, templateToken } from "./template";
67
+ const TOKEN_NODE = "templateToken";
68
+ const TYPED_TOKEN = /\{(\w+)\}$/;
69
+ const PASTED_TOKEN = /\{(\w+)\}/g;
70
+ const props = defineProps({
71
+ tokens: { type: Array, required: true },
72
+ placeholder: { type: String, required: false },
73
+ readonly: { type: Boolean, required: false },
74
+ disabled: { type: Boolean, required: false },
75
+ invalid: { type: Boolean, required: false, default: void 0 },
76
+ required: { type: Boolean, required: false },
77
+ maxLength: { type: Number, required: false },
78
+ label: { type: String, required: false },
79
+ preview: { type: [String, null], required: false, default: void 0 },
80
+ messages: { type: Object, required: false }
81
+ });
82
+ const model = defineModel({ type: [String, null], ...{ default: "" } });
83
+ const slots = useSlots();
84
+ const control = useFieldControl({
85
+ invalid: () => props.invalid,
86
+ disabled: () => props.disabled,
87
+ required: () => props.required,
88
+ labelable: false
89
+ });
90
+ const { locale } = useLocale();
91
+ const text = computed(() => ({ ...locale.value.messages.editor, ...props.messages }));
92
+ const editable = computed(() => !props.readonly && !control.disabled.value);
93
+ const showPreview = computed(() => props.preview !== void 0 || !!slots.preview);
94
+ const tokenByKey = computed(() => new Map(props.tokens.map((token) => [token.key, token])));
95
+ const insertRef = useTemplateRef("insertRef");
96
+ const menuRef = useTemplateRef("menuRef");
97
+ const menuAnchor = shallowRef(null);
98
+ const menuTarget = ref(null);
99
+ const menuOpen = ref(false);
100
+ const focusedOnce = ref(false);
101
+ function serialize(doc) {
102
+ return doc.textBetween(
103
+ 0,
104
+ doc.content.size,
105
+ " ",
106
+ (leaf) => leaf.type.name === TOKEN_NODE ? templateToken(String(leaf.attrs.key)) : ""
107
+ );
108
+ }
109
+ function documentOf(value) {
110
+ const content = templateParts(value, props.tokens).map(
111
+ (part) => part.type === "token" ? { type: TOKEN_NODE, attrs: { key: part.key } } : { type: "text", text: part.text }
112
+ );
113
+ return { type: "doc", content: [{ type: "paragraph", content }] };
114
+ }
115
+ function knownKey(key) {
116
+ return !!key && tokenByKey.value.has(key);
117
+ }
118
+ const TemplateTokenNode = Node.create({
119
+ name: TOKEN_NODE,
120
+ group: "inline",
121
+ inline: true,
122
+ atom: true,
123
+ selectable: true,
124
+ draggable: false,
125
+ addAttributes() {
126
+ return {
127
+ key: {
128
+ default: "",
129
+ parseHTML: (element) => element.getAttribute("data-token"),
130
+ renderHTML: (attributes) => ({ "data-token": attributes.key })
131
+ }
132
+ };
133
+ },
134
+ parseHTML() {
135
+ return [{ tag: "span[data-token]" }];
136
+ },
137
+ renderHTML({ node, HTMLAttributes }) {
138
+ const key = String(node.attrs.key);
139
+ return [
140
+ "span",
141
+ mergeAttributes(HTMLAttributes, {
142
+ class: "k-template-token",
143
+ contenteditable: "false"
144
+ }),
145
+ tokenByKey.value.get(key)?.label ?? templateToken(key)
146
+ ];
147
+ },
148
+ renderText({ node }) {
149
+ return templateToken(String(node.attrs.key));
150
+ },
151
+ addInputRules() {
152
+ return [
153
+ nodeInputRule({
154
+ find: (value) => {
155
+ const match = TYPED_TOKEN.exec(value);
156
+ if (!match || !knownKey(match[1])) return null;
157
+ return { index: match.index, text: match[0], match };
158
+ },
159
+ type: this.type,
160
+ getAttributes: (match) => ({ key: match[1] })
161
+ })
162
+ ];
163
+ },
164
+ addPasteRules() {
165
+ return [
166
+ nodePasteRule({
167
+ find: (value) => [...value.matchAll(PASTED_TOKEN)].filter((match) => knownKey(match[1])).map((match) => ({ index: match.index, text: match[0], match })),
168
+ type: this.type,
169
+ getAttributes: (match) => ({ key: match[1] })
170
+ })
171
+ ];
172
+ }
173
+ });
174
+ const SingleLine = Extension.create({
175
+ name: "templateSingleLine",
176
+ addKeyboardShortcuts() {
177
+ return {
178
+ Enter: () => openSelectedToken(),
179
+ "Shift-Enter": () => true,
180
+ "Mod-Enter": () => true
181
+ };
182
+ },
183
+ addProseMirrorPlugins() {
184
+ return [
185
+ new Plugin({
186
+ filterTransaction: (transaction, state) => {
187
+ if (!transaction.docChanged || props.maxLength === void 0) return true;
188
+ const next = serialize(transaction.doc).length;
189
+ return next <= props.maxLength || next <= serialize(state.doc).length;
190
+ }
191
+ })
192
+ ];
193
+ }
194
+ });
195
+ function labelledBy() {
196
+ return props.label ? void 0 : control.field?.labelId;
197
+ }
198
+ function contentAttributes() {
199
+ return {
200
+ id: control.id.value ?? "",
201
+ role: "textbox",
202
+ "aria-multiline": "false",
203
+ "aria-label": props.label ?? "",
204
+ "aria-labelledby": labelledBy() ?? "",
205
+ "aria-invalid": control.invalid.value ? "true" : "",
206
+ "aria-describedby": control.describedBy.value ?? "",
207
+ "aria-required": control.required.value ? "true" : "",
208
+ "aria-readonly": props.readonly ? "true" : "",
209
+ "aria-disabled": control.disabled.value ? "true" : "",
210
+ "aria-placeholder": props.placeholder && !model.value ? props.placeholder : "",
211
+ class: "k-template-editor-prose"
212
+ };
213
+ }
214
+ const editor = useEditor({
215
+ content: documentOf(model.value),
216
+ editable: editable.value,
217
+ extensions: [
218
+ StarterKit.configure({
219
+ blockquote: false,
220
+ bold: false,
221
+ bulletList: false,
222
+ code: false,
223
+ codeBlock: false,
224
+ dropcursor: false,
225
+ gapcursor: false,
226
+ hardBreak: false,
227
+ heading: false,
228
+ horizontalRule: false,
229
+ italic: false,
230
+ link: false,
231
+ listItem: false,
232
+ listKeymap: false,
233
+ orderedList: false,
234
+ strike: false,
235
+ underline: false,
236
+ trailingNode: false
237
+ }),
238
+ Placeholder.configure({ placeholder: () => props.placeholder ?? "" }),
239
+ TemplateTokenNode,
240
+ SingleLine
241
+ ],
242
+ editorProps: {
243
+ attributes: contentAttributes(),
244
+ handleClickOn: (view, position, node, nodePosition, event) => {
245
+ if (node.type.name !== TOKEN_NODE || !editable.value) return false;
246
+ view.dispatch(
247
+ view.state.tr.setSelection(NodeSelection.create(view.state.doc, nodePosition))
248
+ );
249
+ const element = event.target.closest(".k-template-token");
250
+ openTokenMenu(nodePosition, element);
251
+ return true;
252
+ }
253
+ },
254
+ onFocus: () => {
255
+ focusedOnce.value = true;
256
+ },
257
+ onUpdate: ({ editor: current }) => {
258
+ model.value = serialize(current.state.doc);
259
+ }
260
+ });
261
+ watch(model, (value) => {
262
+ const current = editor.value;
263
+ if (!current || serialize(current.state.doc) === (value ?? "")) return;
264
+ current.commands.setContent(documentOf(value), { emitUpdate: false });
265
+ });
266
+ watch(
267
+ () => props.tokens.map((token) => `${token.key}:${token.label}`).join("|"),
268
+ () => editor.value?.commands.setContent(documentOf(model.value), { emitUpdate: false })
269
+ );
270
+ watch(editable, (value) => editor.value?.setEditable(value));
271
+ watch(
272
+ [
273
+ () => props.label,
274
+ () => props.readonly,
275
+ () => props.placeholder,
276
+ model,
277
+ control.disabled,
278
+ control.invalid,
279
+ control.describedBy,
280
+ control.required,
281
+ control.id
282
+ ],
283
+ () => editor.value?.setOptions({ editorProps: { attributes: contentAttributes() } })
284
+ );
285
+ onBeforeUnmount(() => editor.value?.destroy());
286
+ function openSelectedToken() {
287
+ const current = editor.value;
288
+ const selection = current?.state.selection;
289
+ if (current && selection instanceof NodeSelection && selection.node.type.name === TOKEN_NODE && editable.value) {
290
+ const element = current.view.nodeDOM(selection.from);
291
+ openTokenMenu(selection.from, element instanceof HTMLElement ? element : null);
292
+ }
293
+ return true;
294
+ }
295
+ function openTokenMenu(position, element) {
296
+ menuTarget.value = position;
297
+ menuAnchor.value = element;
298
+ menuRef.value?.show("first", element);
299
+ }
300
+ function openInsertMenu() {
301
+ if (menuOpen.value && menuTarget.value === null) {
302
+ menuRef.value?.hide();
303
+ return;
304
+ }
305
+ const button = insertRef.value?.$el ?? null;
306
+ menuTarget.value = null;
307
+ menuAnchor.value = button;
308
+ menuRef.value?.show("first", button);
309
+ }
310
+ function onMenuOpenChange(open) {
311
+ menuOpen.value = open;
312
+ if (open) return;
313
+ const fromToken = menuTarget.value !== null;
314
+ menuTarget.value = null;
315
+ if (fromToken)
316
+ requestAnimationFrame(() => {
317
+ if (!document.activeElement || document.activeElement === document.body)
318
+ editor.value?.commands.focus();
319
+ });
320
+ }
321
+ function targetKey() {
322
+ const position = menuTarget.value;
323
+ if (position === null) return null;
324
+ const node = editor.value?.state.doc.nodeAt(position);
325
+ return node?.type.name === TOKEN_NODE ? String(node.attrs.key) : null;
326
+ }
327
+ function grouped(entries) {
328
+ const groups = /* @__PURE__ */ new Map();
329
+ for (const token of props.tokens) {
330
+ const group = token.group ?? "";
331
+ groups.set(group, [...groups.get(group) ?? [], token]);
332
+ }
333
+ return [...groups].map(([group, tokens]) => [
334
+ ...group ? [{ type: "label", label: group }] : [],
335
+ ...tokens.map(entries)
336
+ ]);
337
+ }
338
+ const menuItems = computed(() => {
339
+ const current = menuOpen.value ? targetKey() : null;
340
+ if (menuTarget.value === null || current === null)
341
+ return grouped((token) => ({
342
+ label: token.label,
343
+ description: token.description,
344
+ onSelect: () => insertToken(token.key)
345
+ }));
346
+ return [
347
+ ...grouped((token) => ({
348
+ type: "radio",
349
+ label: token.label,
350
+ description: token.description,
351
+ checked: token.key === current,
352
+ onSelect: () => replaceToken(token.key)
353
+ })),
354
+ [{ label: text.value.removeToken, icon: "trash", tone: "danger", onSelect: removeToken }]
355
+ ];
356
+ });
357
+ function needsSpace(character) {
358
+ return !!character && !/\s/.test(character);
359
+ }
360
+ function insertToken(key) {
361
+ const current = editor.value;
362
+ if (!current) return;
363
+ current.chain().focus(focusedOnce.value ? void 0 : "end").command(({ tr, commands }) => {
364
+ const { from, to } = tr.selection;
365
+ const before = tr.doc.textBetween(Math.max(0, from - 1), from, " ", "x");
366
+ const after = tr.doc.textBetween(to, Math.min(tr.doc.content.size, to + 1), " ", "x");
367
+ const content = [{ type: TOKEN_NODE, attrs: { key } }];
368
+ if (needsSpace(before)) content.unshift({ type: "text", text: " " });
369
+ if (needsSpace(after)) content.push({ type: "text", text: " " });
370
+ return commands.insertContent(content);
371
+ }).run();
372
+ }
373
+ function replaceToken(key) {
374
+ const position = menuTarget.value;
375
+ if (position === null) return;
376
+ editor.value?.chain().focus().command(({ tr }) => {
377
+ tr.setNodeMarkup(position, void 0, { key });
378
+ tr.setSelection(NodeSelection.create(tr.doc, position));
379
+ return true;
380
+ }).run();
381
+ }
382
+ function removeToken() {
383
+ const position = menuTarget.value;
384
+ const current = editor.value;
385
+ const node = position === null ? null : current?.state.doc.nodeAt(position);
386
+ if (!current || position === null || !node) return;
387
+ current.chain().focus().deleteRange({ from: position, to: position + node.nodeSize }).run();
388
+ }
389
+ defineExpose({ editor, focus: () => editor.value?.commands.focus() });
390
+ </script>