@tak-ps/vue-tabler 5.5.0 → 5.7.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.
@@ -36,4 +36,12 @@ jobs:
36
36
  run: npm run lint
37
37
 
38
38
  - name: Test
39
- run: npm test
39
+ run: npm run test:coverage
40
+
41
+ - name: Upload coverage
42
+ if: matrix.node-version == 24
43
+ uses: codecov/codecov-action@v5
44
+ with:
45
+ token: ${{ secrets.CODECOV_TOKEN }}
46
+ files: coverage/lcov.info
47
+ fail_ci_if_error: false
package/CHANGELOG.md CHANGED
@@ -12,6 +12,21 @@
12
12
 
13
13
  ### Pending
14
14
 
15
+ ### v5.7.0 - 2026-09-18
16
+
17
+ - :tada: Add `TablerMarkdownEditor`, a WYSIWYG Markdown editor built on Tiptap with a formatting toolbar & table editing. It is `v-model`'d with a Markdown string, emits `submit` on `Ctrl/Cmd+Enter` and is exported as an async component so ProseMirror is only loaded when an editor is first rendered
18
+ - :rocket: `TablerMarkdownEditor` never reports a change for a document that was only opened or was edited back to where it started, keeps bare URLs, `&`, `<`, `>` & intraword `_` readable as plain text and escapes a `|` typed into a table cell
19
+ - :tada: Add a `breaks` prop to `TablerMarkdown` to keep single line breaks inside of paragraphs without rendering the newlines between blocks as `autowrap` does
20
+ - :rocket: `TablerMarkdown` & `TablerMarkdownEditor` share a `tabler-markdown` stylesheet, including table styles, so Markdown looks the same read as it does edited
21
+ - :white_check_mark: Add `TablerMarkdownEditor` tests
22
+
23
+ ### v5.6.0 - 2026-09-15
24
+
25
+ - :white_check_mark: Add `TablerSchema` tests for editing every primitive input type and for default, const and nested default seeding across model and schema changes
26
+ - :white_check_mark: Collect v8 test coverage with `npm run test:coverage` and upload it to Codecov from the Test workflow
27
+ - :tada: Render a `type: object` property in `TablerSchema` as a nested form instead of a raw textarea
28
+ - :tada: Render an `anyOf`/`oneOf` of object shapes in `TablerSchema` with a variant picker, seeding `const` discriminators and resetting the value when the variant changes
29
+
15
30
  ### v5.5.0
16
31
 
17
32
  - :tada: Render an array of objects in `TablerSchema` as a table with a row editor modal, CSV import and clear, matching the CloudTAK Layer Environment form
package/README.md CHANGED
@@ -10,6 +10,9 @@
10
10
  <a href="https://github.com/tak-ps/vue-tabler/blob/main/LICENSE">
11
11
  <img src="https://img.shields.io/npm/l/@tak-ps/vue-tabler.svg" alt="License">
12
12
  </a>
13
+ <a href="https://codecov.io/gh/dfpc-coe/vue-tabler">
14
+ <img src="https://codecov.io/gh/dfpc-coe/vue-tabler/graph/badge.svg" alt="Coverage">
15
+ </a>
13
16
  </p>
14
17
 
15
18
  <p align="center">
@@ -71,6 +74,7 @@ import { TablerButton, TablerAlert } from '@tak-ps/vue-tabler';
71
74
  | **TablerList** | Display data in list format. |
72
75
  | **TablerLoading** | Loading indicators and spinners. |
73
76
  | **TablerMarkdown** | Render markdown content safely. |
77
+ | **TablerMarkdownEditor** | WYSIWYG Markdown editor with table editing, styled the same as `TablerMarkdown`. Loaded on first render. |
74
78
  | **TablerModal** | Dialog boxes for user interaction. |
75
79
  | **TablerNone** | Placeholder component for empty states. |
76
80
  | **TablerPager** | Pagination controls for lists and tables. |
@@ -97,6 +101,7 @@ This library relies on the following core dependencies:
97
101
  - [Vue 3](https://vuejs.org/)
98
102
  - [@tabler/icons-vue](https://www.npmjs.com/package/@tabler/icons-vue)
99
103
  - [marked](https://www.npmjs.com/package/marked) (for Markdown rendering)
104
+ - [Tiptap](https://www.npmjs.com/package/@tiptap/vue-3) (for Markdown editing)
100
105
  - [DOMPurify](https://www.npmjs.com/package/dompurify) (for HTML sanitization)
101
106
 
102
107
  ## 📄 License
@@ -1,7 +1,9 @@
1
1
  <template>
2
2
  <!-- eslint-disable vue/no-v-html -->
3
3
  <div
4
- :style='autowrap ? `white-space: pre-wrap;` : ``'
4
+ class='tabler-markdown'
5
+ :class='{ "tabler-markdown--breaks": breaks }'
6
+ :style='autowrap && !breaks ? `white-space: pre-wrap;` : ``'
5
7
  v-html='html'
6
8
  />
7
9
  <!-- eslint-enable vue/no-v-html -->
@@ -15,10 +17,16 @@ import { marked } from 'marked'
15
17
  export interface MarkdownProps {
16
18
  markdown: string;
17
19
  autowrap?: boolean;
20
+ /**
21
+ * Keep single line breaks inside of paragraphs - unlike `autowrap` the newlines Markdown
22
+ * puts between blocks aren't rendered so tables & lists don't gain blank lines
23
+ */
24
+ breaks?: boolean;
18
25
  }
19
26
 
20
27
  const props = withDefaults(defineProps<MarkdownProps>(), {
21
- autowrap: true
28
+ autowrap: true,
29
+ breaks: false
22
30
  });
23
31
 
24
32
  function sanitizeHtml(html: string): string {
@@ -38,3 +46,5 @@ const html = computed(() => {
38
46
  return sanitizeHtml(rendered)
39
47
  })
40
48
  </script>
49
+
50
+ <style src='./internal/markdown.css' />
@@ -0,0 +1,289 @@
1
+ <template>
2
+ <div
3
+ class='tabler-markdown-editor rounded'
4
+ :class='{
5
+ "tabler-markdown-editor--focused": focused,
6
+ "tabler-markdown-editor--disabled": props.disabled
7
+ }'
8
+ >
9
+ <div
10
+ v-if='props.toolbar && editor'
11
+ class='tabler-markdown-editor__toolbar d-flex flex-wrap align-items-center px-1 py-1'
12
+ role='toolbar'
13
+ aria-label='Formatting'
14
+ >
15
+ <template
16
+ v-for='(group, index) in groups'
17
+ :key='index'
18
+ >
19
+ <span
20
+ v-if='index > 0'
21
+ class='tabler-markdown-editor__divider mx-1'
22
+ />
23
+ <button
24
+ v-for='action in group'
25
+ :key='action.title'
26
+ type='button'
27
+ class='tabler-markdown-editor__action rounded'
28
+ :class='{ "tabler-markdown-editor__action--active": action.active }'
29
+ :title='action.title'
30
+ :aria-label='action.title'
31
+ :aria-pressed='action.active'
32
+ :disabled='props.disabled || action.disabled'
33
+ @mousedown.prevent
34
+ @click='action.run()'
35
+ >
36
+ <component
37
+ :is='action.icon'
38
+ :size='18'
39
+ stroke='1.5'
40
+ />
41
+ </button>
42
+ </template>
43
+ </div>
44
+
45
+ <EditorContent
46
+ :editor='editor'
47
+ class='tabler-markdown-editor__body px-2 py-2'
48
+ />
49
+ </div>
50
+ </template>
51
+
52
+ <script setup lang="ts">
53
+ import { computed, ref, watch, onBeforeUnmount } from 'vue'
54
+ import type { Component } from 'vue'
55
+ import { useEditor, EditorContent } from '@tiptap/vue-3'
56
+ import {
57
+ IconBold,
58
+ IconItalic,
59
+ IconStrikethrough,
60
+ IconCode,
61
+ IconH2,
62
+ IconList,
63
+ IconListNumbers,
64
+ IconBlockquote,
65
+ IconTablePlus,
66
+ IconRowInsertBottom,
67
+ IconColumnInsertRight,
68
+ IconRowRemove,
69
+ IconColumnRemove,
70
+ IconTableMinus,
71
+ IconArrowBackUp,
72
+ IconArrowForwardUp
73
+ } from '@tabler/icons-vue'
74
+ import { markdownExtensions, tidyMarkdown } from './internal/markdown-editor'
75
+
76
+ export interface MarkdownEditorProps {
77
+ modelValue: string;
78
+ label?: string;
79
+ toolbar?: boolean;
80
+ autofocus?: boolean;
81
+ disabled?: boolean;
82
+ }
83
+
84
+ interface Action {
85
+ title: string;
86
+ icon: Component;
87
+ run: () => void;
88
+ active?: boolean;
89
+ disabled?: boolean;
90
+ }
91
+
92
+ const props = withDefaults(defineProps<MarkdownEditorProps>(), {
93
+ label: 'Markdown Editor',
94
+ toolbar: true,
95
+ autofocus: false,
96
+ disabled: false
97
+ });
98
+
99
+ const emit = defineEmits<{
100
+ (e: 'update:modelValue', value: string): void;
101
+ (e: 'submit', value: string): void;
102
+ (e: 'focus'): void;
103
+ (e: 'blur'): void;
104
+ }>();
105
+
106
+ const focused = ref(false);
107
+
108
+ // The Markdown the document was loaded from & what it serializes back to. Serializing
109
+ // normalises Markdown - table padding, escapes, list markers - so a document that is
110
+ // unchanged, or has been edited back to where it started, is reported as the Markdown
111
+ // it was given. Opening the editor must never be a change on its own.
112
+ //
113
+ // Serialized Markdown is compared and not the document as the editor makes changes of
114
+ // its own that aren't content, such as keeping an empty paragraph after a closing table
115
+ let loaded = props.modelValue;
116
+ let pristine = '';
117
+ let current = props.modelValue;
118
+
119
+ const editor = useEditor({
120
+ extensions: markdownExtensions(),
121
+ content: props.modelValue,
122
+ contentType: 'markdown',
123
+ editable: !props.disabled,
124
+ autofocus: props.autofocus ? 'end' : false,
125
+ editorProps: {
126
+ attributes: {
127
+ class: 'tabler-markdown tabler-markdown--breaks',
128
+ role: 'textbox',
129
+ 'aria-multiline': 'true',
130
+ 'aria-label': props.label
131
+ },
132
+ handleKeyDown: (view, event) => {
133
+ if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey)) return false;
134
+
135
+ emit('submit', current);
136
+ return true;
137
+ }
138
+ },
139
+ onUpdate: ({ editor }) => {
140
+ const markdown = tidyMarkdown(editor.getMarkdown());
141
+ current = markdown === pristine ? loaded : markdown;
142
+
143
+ emit('update:modelValue', current);
144
+ },
145
+ onFocus: () => {
146
+ focused.value = true;
147
+ emit('focus');
148
+ },
149
+ onBlur: () => {
150
+ focused.value = false;
151
+ emit('blur');
152
+ }
153
+ });
154
+
155
+ // Not taken in `onCreate` - it is emitted on a timer which an early edit can beat
156
+ watch(editor, (created) => {
157
+ if (created) pristine = tidyMarkdown(created.getMarkdown());
158
+ }, { immediate: true });
159
+
160
+ watch(() => props.modelValue, (value) => {
161
+ // The echo of a value this editor emitted
162
+ if (!editor.value || value === current) return;
163
+
164
+ loaded = value;
165
+ current = value;
166
+
167
+ editor.value.commands.setContent(value, { contentType: 'markdown', emitUpdate: false });
168
+ pristine = tidyMarkdown(editor.value.getMarkdown());
169
+ });
170
+
171
+ watch(() => props.disabled, (disabled) => {
172
+ editor.value?.setEditable(!disabled);
173
+ });
174
+
175
+ onBeforeUnmount(() => {
176
+ editor.value?.destroy();
177
+ });
178
+
179
+ const groups = computed<Action[][]>(() => {
180
+ const e = editor.value;
181
+ if (!e) return [];
182
+
183
+ const chain = () => e.chain().focus();
184
+
185
+ const res: Action[][] = [[
186
+ { title: 'Bold', icon: IconBold, active: e.isActive('bold'), run: () => chain().toggleBold().run() },
187
+ { title: 'Italic', icon: IconItalic, active: e.isActive('italic'), run: () => chain().toggleItalic().run() },
188
+ { title: 'Strikethrough', icon: IconStrikethrough, active: e.isActive('strike'), run: () => chain().toggleStrike().run() },
189
+ { title: 'Code', icon: IconCode, active: e.isActive('code'), run: () => chain().toggleCode().run() }
190
+ ], [
191
+ { title: 'Heading', icon: IconH2, active: e.isActive('heading', { level: 2 }), run: () => chain().toggleHeading({ level: 2 }).run() },
192
+ { title: 'Bullet List', icon: IconList, active: e.isActive('bulletList'), run: () => chain().toggleBulletList().run() },
193
+ { title: 'Numbered List', icon: IconListNumbers, active: e.isActive('orderedList'), run: () => chain().toggleOrderedList().run() },
194
+ { title: 'Quote', icon: IconBlockquote, active: e.isActive('blockquote'), run: () => chain().toggleBlockquote().run() }
195
+ ]];
196
+
197
+ if (e.isActive('table')) {
198
+ res.push([
199
+ { title: 'Add Row', icon: IconRowInsertBottom, run: () => chain().addRowAfter().run() },
200
+ { title: 'Add Column', icon: IconColumnInsertRight, run: () => chain().addColumnAfter().run() },
201
+ { title: 'Delete Row', icon: IconRowRemove, run: () => chain().deleteRow().run() },
202
+ { title: 'Delete Column', icon: IconColumnRemove, run: () => chain().deleteColumn().run() },
203
+ { title: 'Delete Table', icon: IconTableMinus, run: () => chain().deleteTable().run() }
204
+ ]);
205
+ } else {
206
+ res.push([
207
+ { title: 'Insert Table', icon: IconTablePlus, run: () => chain().insertTable({ rows: 2, cols: 2, withHeaderRow: true }).run() }
208
+ ]);
209
+ }
210
+
211
+ res.push([
212
+ { title: 'Undo', icon: IconArrowBackUp, disabled: !e.can().undo(), run: () => chain().undo().run() },
213
+ { title: 'Redo', icon: IconArrowForwardUp, disabled: !e.can().redo(), run: () => chain().redo().run() }
214
+ ]);
215
+
216
+ return res;
217
+ });
218
+
219
+ defineExpose({
220
+ focus: () => editor.value?.commands.focus('end')
221
+ });
222
+ </script>
223
+
224
+ <style src='./internal/markdown.css' />
225
+
226
+ <style>
227
+ .tabler-markdown-editor {
228
+ border: 1px solid var(--tblr-border-color);
229
+ background-color: var(--tblr-bg-forms, transparent);
230
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
231
+ }
232
+
233
+ .tabler-markdown-editor--focused {
234
+ border-color: rgba(var(--tblr-primary-rgb), 0.6);
235
+ box-shadow: 0 0 0 0.25rem rgba(var(--tblr-primary-rgb), 0.25);
236
+ }
237
+
238
+ .tabler-markdown-editor--disabled {
239
+ opacity: 0.65;
240
+ }
241
+
242
+ .tabler-markdown-editor__toolbar {
243
+ gap: 2px;
244
+ border-bottom: 1px solid var(--tblr-border-color);
245
+ }
246
+
247
+ .tabler-markdown-editor__divider {
248
+ width: 1px;
249
+ height: 18px;
250
+ background-color: var(--tblr-border-color);
251
+ }
252
+
253
+ .tabler-markdown-editor__action {
254
+ display: inline-flex;
255
+ align-items: center;
256
+ justify-content: center;
257
+ width: 28px;
258
+ height: 28px;
259
+ padding: 0;
260
+ border: 1px solid transparent;
261
+ background: transparent;
262
+ color: inherit;
263
+ cursor: pointer;
264
+ }
265
+
266
+ .tabler-markdown-editor__action:hover:not(:disabled),
267
+ .tabler-markdown-editor__action:focus-visible {
268
+ background-color: rgba(var(--tblr-primary-rgb), 0.12);
269
+ }
270
+
271
+ .tabler-markdown-editor__action--active {
272
+ color: var(--tblr-primary);
273
+ background-color: rgba(var(--tblr-primary-rgb), 0.16);
274
+ }
275
+
276
+ .tabler-markdown-editor__action:disabled {
277
+ opacity: 0.4;
278
+ cursor: default;
279
+ }
280
+
281
+ .tabler-markdown-editor__body .ProseMirror {
282
+ min-height: 6rem;
283
+ outline: none;
284
+ }
285
+
286
+ .tabler-markdown-editor__body .ProseMirror .selectedCell {
287
+ background-color: rgba(var(--tblr-primary-rgb), 0.16);
288
+ }
289
+ </style>
@@ -0,0 +1,7 @@
1
+ import { defineAsyncComponent } from 'vue'
2
+
3
+ /**
4
+ * The editor pulls in ProseMirror so it is only loaded when it is first rendered,
5
+ * keeping it out of the main bundle of every application that imports this library
6
+ */
7
+ export const TablerMarkdownEditor = defineAsyncComponent(() => import('./MarkdownEditor.vue'))
@@ -3,7 +3,7 @@
3
3
  <TablerLoading v-if='loading' />
4
4
  <template v-else>
5
5
  <div
6
- v-for='key in Object.keys(s.properties)'
6
+ v-for='key in visibleKeys'
7
7
  :key='key'
8
8
  class='py-2 floating-input'
9
9
  >
@@ -138,6 +138,46 @@
138
138
  @create='openRow(key)'
139
139
  />
140
140
  </template>
141
+ <template v-else-if='isUnion(s.properties[key])'>
142
+ <TablerEnum
143
+ :model-value='variantLabels(key)[variant[key] || 0]'
144
+ :label='key'
145
+ :disabled='disabled'
146
+ :required='s.properties[key].required || false'
147
+ :description='s.properties[key].description || ""'
148
+ :options='variantLabels(key)'
149
+ @update:model-value='selectVariant(key, $event)'
150
+ />
151
+
152
+ <div class='border rounded my-2 py-2 mx-2 px-2'>
153
+ <TablerSchema
154
+ :key='variant[key] || 0'
155
+ v-model='data[key]'
156
+ :schema='unionVariants(s.properties[key])[variant[key] || 0]'
157
+ :disabled='disabled'
158
+ />
159
+ </div>
160
+ </template>
161
+ <template v-else-if='isObject(s.properties[key])'>
162
+ <div class='d-flex align-items-center'>
163
+ <label
164
+ class='form-label mb-0'
165
+ v-text='key'
166
+ />
167
+ <span
168
+ v-if='s.properties[key].required'
169
+ class='text-red mx-1'
170
+ >*</span>
171
+ </div>
172
+
173
+ <div class='border rounded my-2 py-2 mx-2 px-2'>
174
+ <TablerSchema
175
+ v-model='data[key]'
176
+ :schema='s.properties[key]'
177
+ :disabled='disabled'
178
+ />
179
+ </div>
180
+ </template>
141
181
  <template v-else-if='s.properties[key].type === "array"'>
142
182
  <div class='d-flex'>
143
183
  <label
@@ -261,7 +301,7 @@
261
301
  </template>
262
302
 
263
303
  <script setup lang="ts">
264
- import { ref, reactive, watch, onMounted } from 'vue'
304
+ import { ref, reactive, computed, watch, onMounted } from 'vue'
265
305
  import TablerInput from './input/Input.vue';
266
306
  import TablerToggle from './input/Toggle.vue';
267
307
  import TablerEnum from './input/Enum.vue';
@@ -321,6 +361,103 @@ const csv = reactive({
321
361
  text: ''
322
362
  });
323
363
 
364
+ /** Selected union variant index per property key */
365
+ const variant = reactive<Record<string, number>>({});
366
+
367
+ /** Properties with a fixed const value are seeded but never rendered */
368
+ const visibleKeys = computed<string[]>(() => {
369
+ if (!s.value.properties) return [];
370
+ return Object.keys(s.value.properties).filter((key) => s.value.properties[key].const === undefined);
371
+ });
372
+
373
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
374
+ const isObject = (prop: any): boolean => {
375
+ return prop.type === 'object' && !!prop.properties;
376
+ }
377
+
378
+ /** The object members of an anyOf/oneOf, ignoring a null member used to mark a nullable value */
379
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
380
+ const unionVariants = (prop: any): any[] => {
381
+ const members = prop.oneOf || prop.anyOf;
382
+ if (!Array.isArray(members)) return [];
383
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
384
+ return members.filter((m: any) => m && m.type !== 'null');
385
+ }
386
+
387
+ /** A choice between two or more object shapes, rendered with a variant picker */
388
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
389
+ const isUnion = (prop: any): boolean => {
390
+ const variants = unionVariants(prop);
391
+ return variants.length >= 2 && variants.every((v) => isObject(v));
392
+ }
393
+
394
+ const variantLabels = (key: string): string[] => {
395
+ const labels: string[] = [];
396
+
397
+ unionVariants(s.value.properties[key]).forEach((v, i) => {
398
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
399
+ const discriminator = Object.values(v.properties as Record<string, any>).find((p) => p.const !== undefined);
400
+ let label = v.title || (discriminator ? String(discriminator.const) : `Option ${i + 1}`);
401
+ if (labels.includes(label)) label = `${label} (${i + 1})`;
402
+ labels.push(label);
403
+ });
404
+
405
+ return labels;
406
+ }
407
+
408
+ /** Pick the variant a stored value belongs to by discriminator, then by required keys */
409
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
410
+ const detectVariant = (prop: any, value: any): number => {
411
+ const variants = unionVariants(prop);
412
+ if (!value || typeof value !== 'object') return 0;
413
+
414
+ for (let i = 0; i < variants.length; i++) {
415
+ for (const [k, p] of Object.entries(variants[i].properties)) {
416
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
417
+ if ((p as any).const !== undefined && value[k] === (p as any).const) return i;
418
+ }
419
+ }
420
+
421
+ for (let i = 0; i < variants.length; i++) {
422
+ const required: string[] = variants[i].required || [];
423
+ if (required.length && required.every((k) => value[k] !== undefined)) return i;
424
+ }
425
+
426
+ return 0;
427
+ }
428
+
429
+ /** A fresh value for a variant holding only its const properties, the nested form seeds the rest */
430
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
431
+ const seedVariant = (prop: any, index: number): Record<string, unknown> => {
432
+ const seed: Record<string, unknown> = {};
433
+ const v = unionVariants(prop)[index];
434
+ if (!v) return seed;
435
+
436
+ for (const [k, p] of Object.entries(v.properties)) {
437
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
438
+ if ((p as any).const !== undefined) seed[k] = (p as any).const;
439
+ }
440
+
441
+ return seed;
442
+ }
443
+
444
+ const selectVariant = (key: string, label: string) => {
445
+ const index = variantLabels(key).indexOf(label);
446
+ if (index === -1 || index === variant[key]) return;
447
+
448
+ variant[key] = index;
449
+ data.value[key] = seedVariant(s.value.properties[key], index);
450
+ }
451
+
452
+ const resolveVariants = () => {
453
+ if (!s.value.properties) return;
454
+
455
+ for (const key in s.value.properties) {
456
+ const prop = s.value.properties[key];
457
+ if (isUnion(prop)) variant[key] = detectVariant(prop, data.value[key]);
458
+ }
459
+ }
460
+
324
461
  /** An array of objects with known properties is rendered as a table with a row editor */
325
462
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
326
463
  const isObjectTable = (prop: any): boolean => {
@@ -424,8 +561,12 @@ const updateDataDefaults = () => {
424
561
 
425
562
  const prop = s.value.properties[key];
426
563
 
427
- if (prop.default !== undefined) {
564
+ if (prop.const !== undefined) {
565
+ data.value[key] = JSON.parse(JSON.stringify(prop.const));
566
+ } else if (prop.default !== undefined) {
428
567
  data.value[key] = JSON.parse(JSON.stringify(prop.default));
568
+ } else if (isUnion(prop)) {
569
+ data.value[key] = seedVariant(prop, 0);
429
570
  } else if (prop.type === 'array') {
430
571
  data.value[key] = [];
431
572
  } else if (prop.type === 'boolean') {
@@ -444,12 +585,14 @@ const updateDataDefaults = () => {
444
585
  watch(() => props.schema, () => {
445
586
  updateSchema();
446
587
  updateDataDefaults();
588
+ resolveVariants();
447
589
  }, { deep: true });
448
590
 
449
591
  watch(() => props.modelValue, () => {
450
592
  if (JSON.stringify(props.modelValue) !== JSON.stringify(data.value)) {
451
593
  data.value = JSON.parse(JSON.stringify(props.modelValue));
452
594
  updateDataDefaults();
595
+ resolveVariants();
453
596
  }
454
597
  }, { deep: true });
455
598
 
@@ -459,6 +602,7 @@ onMounted(async () => {
459
602
  data.value = JSON.parse(JSON.stringify(props.modelValue));
460
603
  updateSchema();
461
604
  updateDataDefaults();
605
+ resolveVariants();
462
606
 
463
607
  loading.value = false;
464
608
  })
@@ -0,0 +1,96 @@
1
+ import type { Extensions, JSONContent } from '@tiptap/core'
2
+ import StarterKit from '@tiptap/starter-kit'
3
+ import { Table, TableRow, TableHeader, TableCell, renderTableToMarkdown } from '@tiptap/extension-table'
4
+ import { Markdown } from '@tiptap/markdown'
5
+
6
+ // Private use character standing in for a `|` while a table is serialized
7
+ const PIPE = ''
8
+
9
+ const FENCE = /^\s*(```|~~~)/
10
+
11
+ function maskPipes(node: JSONContent): JSONContent {
12
+ return {
13
+ ...node,
14
+ text: node.text === undefined ? undefined : node.text.replace(/\|/g, PIPE),
15
+ content: node.content ? node.content.map(maskPipes) : undefined
16
+ }
17
+ }
18
+
19
+ /**
20
+ * The table serializer writes a `|` typed in a cell as is, which splits the cell in two the
21
+ * next time the Markdown is parsed. It can't be escaped up front as the text serializer would
22
+ * escape the backslash, so it is masked while the table renders and written as `\|` after
23
+ */
24
+ const PipeSafeTable = Table.extend({
25
+ renderMarkdown: (node, h) => {
26
+ return renderTableToMarkdown(maskPipes(node), h).replaceAll(PIPE, '\\|')
27
+ }
28
+ })
29
+
30
+ export function markdownExtensions(): Extensions {
31
+ return [
32
+ StarterKit.configure({
33
+ // There is no Markdown for an underline - it would be lost on save
34
+ underline: false,
35
+ link: {
36
+ openOnClick: false
37
+ }
38
+ }),
39
+ PipeSafeTable.configure({ resizable: false }),
40
+ TableRow,
41
+ TableHeader,
42
+ TableCell,
43
+ Markdown
44
+ ]
45
+ }
46
+
47
+ /**
48
+ * Undo the parts of Tiptap's Markdown serialization that are only needed for HTML.
49
+ *
50
+ * The Markdown is also read as plain text - CoT remarks on a TAK device for instance - where
51
+ * `Kenny &amp; Nick` or `unit\_one` is noise. An entity or escape is only removed where the
52
+ * bare character can't be parsed as anything else, so the text renders the same either way.
53
+ */
54
+ function tidyText(text: string, lineStart: boolean): string {
55
+ return text
56
+ // `&` is only an entity when it is followed by a name or number and a `;`
57
+ .replace(/&amp;(?!#?\w+;)/g, '&')
58
+ // `<` only opens a tag or an autolink when it is followed by one of these
59
+ .replace(/&lt;(?![a-zA-Z/!?])/g, '<')
60
+ // `>` is only a blockquote at the start of a line
61
+ .replace(/&gt;/g, (match, offset: number) => {
62
+ return lineStart && !text.slice(0, offset).trim().length ? match : '>'
63
+ })
64
+ // `_` inside of a word is never emphasis in GFM
65
+ // (no lookbehind - Safari before 16.4 fails to parse the whole chunk)
66
+ .replace(/([a-zA-Z0-9])\\_(?=[a-zA-Z0-9])/g, '$1_')
67
+ // A bare URL is linked by GFM as is - it doesn't need to be written as [url](url)
68
+ .replace(/\[(https?:\/\/[^\]\s]+)\]\(([^)\s]+)\)/g, (match, label: string, href: string) => {
69
+ return label.replace(/\\([\\`*_[\]~])/g, '$1') === href ? href : match
70
+ })
71
+ }
72
+
73
+ export function tidyMarkdown(markdown: string): string {
74
+ const lines: string[] = []
75
+ let fenced = false
76
+
77
+ for (const line of markdown.split('\n')) {
78
+ if (FENCE.test(line)) {
79
+ fenced = !fenced
80
+ lines.push(line)
81
+ } else if (fenced) {
82
+ lines.push(line)
83
+ } else if (!line.trim().length) {
84
+ // Blocks are separated by a single blank line
85
+ if (lines.length && lines[lines.length - 1].length) lines.push('')
86
+ } else {
87
+ // Text inside of a code span is already written as is
88
+ lines.push(line
89
+ .split(/(`+[^`]*`+)/)
90
+ .map((part, i) => part.startsWith('`') ? part : tidyText(part, i === 0))
91
+ .join(''))
92
+ }
93
+ }
94
+
95
+ return lines.join('\n').trim()
96
+ }
@@ -0,0 +1,60 @@
1
+ /* Shared by TablerMarkdown & TablerMarkdownEditor so Markdown looks the same read as it does edited */
2
+
3
+ .tabler-markdown {
4
+ word-break: break-word;
5
+ }
6
+
7
+ .tabler-markdown > :first-child {
8
+ margin-top: 0;
9
+ }
10
+
11
+ .tabler-markdown > :last-child {
12
+ margin-bottom: 0;
13
+ }
14
+
15
+ /* Line breaks are kept inside of paragraphs only - kept on the container they would
16
+ * also render the newlines Markdown puts between block elements & table rows */
17
+ .tabler-markdown--breaks {
18
+ white-space: normal;
19
+ }
20
+
21
+ .tabler-markdown--breaks p {
22
+ white-space: pre-wrap;
23
+ }
24
+
25
+ .tabler-markdown table {
26
+ width: 100%;
27
+ margin-bottom: 1rem;
28
+ border-collapse: collapse;
29
+ font-size: 0.8125rem;
30
+ }
31
+
32
+ .tabler-markdown th,
33
+ .tabler-markdown td {
34
+ padding: 4px 8px;
35
+ border: 1px solid var(--tblr-border-color);
36
+ vertical-align: top;
37
+ text-align: left;
38
+ }
39
+
40
+ .tabler-markdown th {
41
+ font-weight: 600;
42
+ white-space: nowrap;
43
+ background-color: var(--tblr-bg-surface-secondary, rgba(0, 0, 0, 0.1));
44
+ }
45
+
46
+ /* Timestamps & short identifiers stay on a single line, the last column takes the text */
47
+ .tabler-markdown td:not(:last-child) {
48
+ white-space: nowrap;
49
+ }
50
+
51
+ /* The editor wraps the content of a cell in a paragraph */
52
+ .tabler-markdown th > p,
53
+ .tabler-markdown td > p {
54
+ margin: 0;
55
+ }
56
+
57
+ .tabler-markdown th:not(:last-child) > p,
58
+ .tabler-markdown td:not(:last-child) > p {
59
+ white-space: nowrap;
60
+ }
package/lib.ts CHANGED
@@ -30,6 +30,7 @@ export { default as TablerBytes } from './components/Bytes.vue';
30
30
  export { default as TablerEpoch } from './components/Epoch.vue';
31
31
  export { default as TablerEpochRange } from './components/EpochRange.vue';
32
32
  export { default as TablerMarkdown } from './components/Markdown.vue';
33
+ export { TablerMarkdownEditor } from './components/MarkdownEditorAsync';
33
34
  export { default as TablerDelete } from './components/Delete.vue';
34
35
  export { default as TablerPillGroup } from './components/PillGroup.vue';
35
36
  export { default as TablerSchema } from './components/Schema.vue';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tak-ps/vue-tabler",
3
3
  "type": "module",
4
- "version": "5.5.0",
4
+ "version": "5.7.0",
5
5
  "lib": "lib.ts",
6
6
  "main": "lib.ts",
7
7
  "module": "lib.ts",
@@ -12,6 +12,7 @@
12
12
  "scripts": {
13
13
  "test": "vitest run",
14
14
  "test:watch": "vitest",
15
+ "test:coverage": "vitest run --coverage",
15
16
  "check": "vue-tsc --noEmit",
16
17
  "lint": "eslint lib.ts components/"
17
18
  },
@@ -27,6 +28,11 @@
27
28
  "homepage": "https://github.com/tak-ps/vue-tabler#readme",
28
29
  "dependencies": {
29
30
  "@tabler/icons-vue": "^3.0.0",
31
+ "@tiptap/extension-table": "^3.31.3",
32
+ "@tiptap/markdown": "^3.31.3",
33
+ "@tiptap/pm": "^3.31.3",
34
+ "@tiptap/starter-kit": "^3.31.3",
35
+ "@tiptap/vue-3": "^3.31.3",
30
36
  "dompurify": "^3.4.1",
31
37
  "marked": "^18.0.2"
32
38
  },
@@ -38,6 +44,7 @@
38
44
  "@eslint/js": "^10.0.0",
39
45
  "@typescript-eslint/parser": "^8.8.1",
40
46
  "@vitejs/plugin-vue": "^6.0.5",
47
+ "@vitest/coverage-v8": "^5.0.1",
41
48
  "@vue/test-utils": "^2.4.6",
42
49
  "eslint": "^10.0.0",
43
50
  "eslint-plugin-vue": "^10.0.0",
@@ -0,0 +1,171 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { mount, flushPromises } from '@vue/test-utils'
3
+ import { Editor } from '@tiptap/core'
4
+ import MarkdownEditor from '../components/MarkdownEditor.vue'
5
+ import Markdown from '../components/Markdown.vue'
6
+ import { markdownExtensions, tidyMarkdown } from '../components/internal/markdown-editor'
7
+
8
+ // jsdom has no layout - ProseMirror measures the selection to scroll it into view on focus
9
+ const rects = () => [] as unknown as DOMRectList
10
+ Range.prototype.getClientRects = rects
11
+ Range.prototype.getBoundingClientRect = () => new DOMRect()
12
+ Element.prototype.getClientRects = rects
13
+ Element.prototype.scrollIntoView = () => undefined
14
+
15
+ const TABLE = [
16
+ '**Groups:** EN31',
17
+ '',
18
+ '| Time | Author | Note |',
19
+ '| --- | --- | --- |',
20
+ '| 13:21:10 | jdoe | GATE CODE 12\\|34 |',
21
+ '| 13:21:23 | jdoe | NOT FEELING SICK |'
22
+ ].join('\n')
23
+
24
+ function roundtrip(markdown: string): string {
25
+ const editor = new Editor({ extensions: markdownExtensions(), content: markdown, contentType: 'markdown' })
26
+ const out = tidyMarkdown(editor.getMarkdown())
27
+ editor.destroy()
28
+ return out
29
+ }
30
+
31
+ function cells(markdown: string): string[] {
32
+ const wrapper = mount(Markdown, { props: { markdown } })
33
+ return wrapper.findAll('th, td').map((cell) => cell.text())
34
+ }
35
+
36
+ describe('Markdown serialization', () => {
37
+ it('leaves plain text as it was written', () => {
38
+ const text = 'Missing Hunter Love Mesa\n\n1049 Kenny & Nick responding, BP > 140 & HR < 50\nsecond line for unit_one'
39
+
40
+ expect(roundtrip(text)).toBe(text)
41
+ })
42
+
43
+ it('keeps a bare URL bare', () => {
44
+ expect(roundtrip('see https://example.com/a_b?c=1&d=2 now')).toBe('see https://example.com/a_b?c=1&d=2 now')
45
+ })
46
+
47
+ it('keeps escapes & entities that change how the text is parsed', () => {
48
+ expect(roundtrip('a \\*literal\\* star')).toBe('a \\*literal\\* star')
49
+ expect(roundtrip('a &lt;b&gt; tag')).toBe('a &lt;b> tag')
50
+ expect(roundtrip('an &amp;amp; entity')).toBe('an &amp;amp; entity')
51
+ expect(roundtrip('&gt; not a quote')).toBe('&gt; not a quote')
52
+ })
53
+
54
+ it('renders a table the same after a round trip', () => {
55
+ const out = roundtrip(TABLE)
56
+
57
+ expect(out).not.toMatch(/\n{3,}/)
58
+ expect(cells(out)).toEqual(cells(TABLE))
59
+ expect(cells(out)).toContain('GATE CODE 12|34')
60
+ })
61
+
62
+ it('does not touch the contents of code', () => {
63
+ const text = 'inline `a &amp; b\\_c`\n\n```\nfenced &amp; code\n\n\n\nkept\n```'
64
+
65
+ expect(roundtrip(text)).toBe(text)
66
+ })
67
+ })
68
+
69
+ // Tiptap debounces the reactive editor state that the toolbar renders from over two frames
70
+ async function frames(): Promise<void> {
71
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
72
+ await flushPromises()
73
+ }
74
+
75
+ describe('TablerMarkdownEditor', () => {
76
+ async function mountEditor(modelValue: string) {
77
+ const wrapper = mount(MarkdownEditor, { props: { modelValue }, attachTo: document.body })
78
+ await flushPromises()
79
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
+ const editor = (wrapper.vm as any).editor as Editor
81
+ return { wrapper, editor }
82
+ }
83
+
84
+ it('renders the Markdown with the classes of the viewer', async () => {
85
+ const { wrapper } = await mountEditor(TABLE)
86
+
87
+ const content = wrapper.find('.ProseMirror')
88
+ expect(content.classes()).toContain('tabler-markdown')
89
+ expect(content.classes()).toContain('tabler-markdown--breaks')
90
+ expect(content.findAll('th').map((th) => th.text())).toEqual(['Time', 'Author', 'Note'])
91
+
92
+ wrapper.unmount()
93
+ })
94
+
95
+ it('does not emit when it is opened', async () => {
96
+ const { wrapper } = await mountEditor(TABLE)
97
+
98
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
99
+
100
+ wrapper.unmount()
101
+ })
102
+
103
+ it('emits tidy Markdown on an edit & the original Markdown when the edit is undone', async () => {
104
+ const { wrapper, editor } = await mountEditor(TABLE)
105
+
106
+ let cell = 0
107
+ editor.state.doc.descendants((node, pos) => {
108
+ if (node.type.name === 'tableCell') cell = pos
109
+ })
110
+
111
+ // The end of the text in the last cell
112
+ editor.chain().focus(cell + editor.state.doc.nodeAt(cell)!.nodeSize - 2).insertContent(' & MORE').run()
113
+
114
+ const edits = wrapper.emitted('update:modelValue') as string[][]
115
+ expect(edits).toHaveLength(1)
116
+ expect(edits[0][0]).toContain('NOT FEELING SICK & MORE')
117
+ expect(edits[0][0]).toContain('GATE CODE 12\\|34')
118
+
119
+ editor.commands.undo()
120
+
121
+ expect(edits).toHaveLength(2)
122
+ expect(edits[1][0]).toBe(TABLE)
123
+
124
+ wrapper.unmount()
125
+ })
126
+
127
+ it('loads a new value without emitting it back', async () => {
128
+ const { wrapper, editor } = await mountEditor('first')
129
+
130
+ await wrapper.setProps({ modelValue: 'second **value**' })
131
+
132
+ expect(editor.getText()).toBe('second value')
133
+ expect(wrapper.emitted('update:modelValue')).toBeUndefined()
134
+
135
+ wrapper.unmount()
136
+ })
137
+
138
+ it('shows table actions only inside of a table', async () => {
139
+ const { wrapper, editor } = await mountEditor('text\n\n| A | B |\n| --- | --- |\n| 1 | 2 |')
140
+
141
+ editor.commands.focus('start')
142
+ await frames()
143
+ expect(wrapper.find('[title="Insert Table"]').exists()).toBe(true)
144
+ expect(wrapper.find('[title="Add Row"]').exists()).toBe(false)
145
+
146
+ let cell = 0
147
+ editor.state.doc.descendants((node, pos) => {
148
+ if (node.type.name === 'tableCell') cell = pos
149
+ })
150
+
151
+ editor.commands.focus(cell + 2)
152
+ await frames()
153
+ expect(wrapper.find('[title="Add Row"]').exists()).toBe(true)
154
+
155
+ await wrapper.find('[title="Add Row"]').trigger('click')
156
+ expect(editor.getHTML().match(/<tr>/g)).toHaveLength(3)
157
+
158
+ wrapper.unmount()
159
+ })
160
+
161
+ it('submits the current Markdown with Ctrl+Enter', async () => {
162
+ const { wrapper, editor } = await mountEditor('first')
163
+
164
+ editor.chain().focus('end').insertContent(' note').run()
165
+ editor.view.dom.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', ctrlKey: true, bubbles: true }))
166
+
167
+ expect(wrapper.emitted('submit')).toEqual([['first note']])
168
+
169
+ wrapper.unmount()
170
+ })
171
+ })
@@ -162,3 +162,357 @@ describe('TablerSchema object tables', () => {
162
162
  })
163
163
  })
164
164
  })
165
+
166
+ const UNION_SCHEMA = {
167
+ type: 'object',
168
+ required: ['Source'],
169
+ properties: {
170
+ Source: {
171
+ anyOf: [
172
+ {
173
+ title: 'Single Map',
174
+ type: 'object',
175
+ required: ['Mode', 'MapId'],
176
+ properties: {
177
+ Mode: { const: 'Map', type: 'string' },
178
+ MapId: { type: 'string' },
179
+ },
180
+ },
181
+ {
182
+ title: 'Team Account',
183
+ type: 'object',
184
+ required: ['Mode', 'TeamId'],
185
+ properties: {
186
+ Mode: { const: 'Team', type: 'string' },
187
+ TeamId: { type: 'string' },
188
+ Verbose: { type: 'boolean', default: true },
189
+ },
190
+ },
191
+ ],
192
+ },
193
+ },
194
+ }
195
+
196
+ describe('TablerSchema nested objects', () => {
197
+ it('renders an object property as a nested form and emits the nested value', async () => {
198
+ const wrapper = mount(Schema, {
199
+ props: {
200
+ modelValue: {},
201
+ schema: {
202
+ type: 'object',
203
+ properties: {
204
+ Auth: {
205
+ type: 'object',
206
+ properties: {
207
+ Username: { type: 'string' },
208
+ Remember: { type: 'boolean' },
209
+ },
210
+ },
211
+ },
212
+ },
213
+ },
214
+ })
215
+
216
+ await flushPromises()
217
+
218
+ const input = wrapper.find('input[type="text"]')
219
+ await input.setValue('fred')
220
+ await flushPromises()
221
+
222
+ expect(lastEmitted(wrapper)).toEqual({ Auth: { Username: 'fred', Remember: false } })
223
+ expect(wrapper.find('textarea').exists()).toBe(false)
224
+ })
225
+ })
226
+
227
+ describe('TablerSchema unions', () => {
228
+ it('seeds the first variant and hides the const discriminator', async () => {
229
+ const wrapper = mount(Schema, {
230
+ props: { modelValue: {}, schema: UNION_SCHEMA },
231
+ })
232
+
233
+ await flushPromises()
234
+
235
+ const select = wrapper.find('select')
236
+ expect(select.findAll('option').map((o) => o.text())).toEqual(['Single Map', 'Team Account'])
237
+ expect((select.element as HTMLSelectElement).value).toBe('Single Map')
238
+ expect(wrapper.findAll('input[type="text"]').length).toBe(1)
239
+ expect(lastEmitted(wrapper)).toEqual({ Source: { Mode: 'Map', MapId: '' } })
240
+ })
241
+
242
+ it('selects the variant matching a stored discriminator', async () => {
243
+ const wrapper = mount(Schema, {
244
+ props: {
245
+ modelValue: { Source: { Mode: 'Team', TeamId: 'abc', Verbose: false } },
246
+ schema: UNION_SCHEMA,
247
+ },
248
+ })
249
+
250
+ await flushPromises()
251
+
252
+ expect((wrapper.find('select').element as HTMLSelectElement).value).toBe('Team Account')
253
+ expect((wrapper.find('input[type="text"]').element as HTMLInputElement).value).toBe('abc')
254
+ })
255
+
256
+ it('resets the value to the new variant when switched', async () => {
257
+ const wrapper = mount(Schema, {
258
+ props: {
259
+ modelValue: { Source: { Mode: 'Map', MapId: 'xyz' } },
260
+ schema: UNION_SCHEMA,
261
+ },
262
+ })
263
+
264
+ await flushPromises()
265
+ await wrapper.find('select').setValue('Team Account')
266
+ await flushPromises()
267
+
268
+ expect(lastEmitted(wrapper)).toEqual({ Source: { Mode: 'Team', TeamId: '', Verbose: true } })
269
+ expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true)
270
+ })
271
+
272
+ it('does not treat a nullable anyOf as a union', async () => {
273
+ const wrapper = mount(Schema, {
274
+ props: {
275
+ modelValue: {},
276
+ schema: {
277
+ type: 'object',
278
+ properties: {
279
+ Note: { anyOf: [{ type: 'string' }, { type: 'null' }] },
280
+ },
281
+ },
282
+ },
283
+ })
284
+
285
+ await flushPromises()
286
+
287
+ expect(wrapper.find('select').exists()).toBe(false)
288
+ })
289
+ })
290
+
291
+ const PRIMITIVE_SCHEMA = {
292
+ type: 'object',
293
+ properties: {
294
+ Name: { type: 'string' },
295
+ Count: { type: 'integer' },
296
+ Ratio: { type: 'number' },
297
+ Flag: { type: 'boolean' },
298
+ Level: { type: 'string', enum: ['low', 'high'] },
299
+ Roles: { type: 'array', uniqueItems: true, items: { type: 'string', enum: ['admin', 'user'] } },
300
+ },
301
+ }
302
+
303
+ describe('TablerSchema editing primitives', () => {
304
+ it('emits typed values for string, integer, number and boolean inputs', async () => {
305
+ const wrapper = mount(Schema, {
306
+ props: { modelValue: {}, schema: PRIMITIVE_SCHEMA },
307
+ })
308
+
309
+ await flushPromises()
310
+
311
+ await wrapper.find('input[type="text"]').setValue('Fred')
312
+ const numbers = wrapper.findAll('input[type="number"]')
313
+ await numbers[0].setValue('3')
314
+ await numbers[1].setValue('1.5')
315
+ await wrapper.find('.form-switch input').setValue(true)
316
+ await flushPromises()
317
+
318
+ const data = lastEmitted(wrapper)
319
+ expect(data.Name).toBe('Fred')
320
+ expect(data.Count).toBe(3)
321
+ expect(data.Ratio).toBe(1.5)
322
+ expect(data.Flag).toBe(true)
323
+ })
324
+
325
+ it('emits the selected enum option', async () => {
326
+ const wrapper = mount(Schema, {
327
+ props: { modelValue: {}, schema: PRIMITIVE_SCHEMA },
328
+ })
329
+
330
+ await flushPromises()
331
+ await wrapper.find('select').setValue('high')
332
+ await flushPromises()
333
+
334
+ expect(lastEmitted(wrapper).Level).toBe('high')
335
+ })
336
+
337
+ it('toggles multi enum options in and out of the array', async () => {
338
+ const wrapper = mount(Schema, {
339
+ props: { modelValue: {}, schema: PRIMITIVE_SCHEMA },
340
+ })
341
+
342
+ await flushPromises()
343
+
344
+ const boxes = wrapper.findAll('.form-check input[type="checkbox"]')
345
+ expect(boxes.length).toBe(2)
346
+
347
+ await boxes[0].trigger('change')
348
+ await boxes[1].trigger('change')
349
+ await flushPromises()
350
+ expect(lastEmitted(wrapper).Roles).toEqual(['admin', 'user'])
351
+
352
+ await boxes[0].trigger('change')
353
+ await flushPromises()
354
+ expect(lastEmitted(wrapper).Roles).toEqual(['user'])
355
+ })
356
+
357
+ it('renders a multi line string as a textarea and keeps newlines', async () => {
358
+ const wrapper = mount(Schema, {
359
+ props: {
360
+ modelValue: { Name: 'one\ntwo' },
361
+ schema: { type: 'object', properties: { Name: { type: 'string' } } },
362
+ },
363
+ })
364
+
365
+ await flushPromises()
366
+
367
+ const textarea = wrapper.find('textarea')
368
+ expect(textarea.exists()).toBe(true)
369
+ await textarea.setValue('one\ntwo\nthree')
370
+ await flushPromises()
371
+
372
+ expect(lastEmitted(wrapper).Name).toBe('one\ntwo\nthree')
373
+ })
374
+
375
+ it('disables every primitive input when disabled', async () => {
376
+ const wrapper = mount(Schema, {
377
+ props: { modelValue: {}, schema: PRIMITIVE_SCHEMA, disabled: true },
378
+ })
379
+
380
+ await flushPromises()
381
+
382
+ const controls = wrapper.findAll('input, select')
383
+ expect(controls.length).toBeGreaterThan(0)
384
+ expect(controls.every((c) => (c.element as HTMLInputElement).disabled)).toBe(true)
385
+ })
386
+ })
387
+
388
+ const DEFAULT_SCHEMA = {
389
+ type: 'object',
390
+ properties: {
391
+ Name: { type: 'string', default: 'Fred' },
392
+ Count: { type: 'integer', default: 5 },
393
+ Level: { type: 'string', enum: ['low', 'high'], default: 'high' },
394
+ Tags: { type: 'array', items: { type: 'string' }, default: ['a'] },
395
+ Kind: { type: 'string', const: 'thing' },
396
+ Auth: {
397
+ type: 'object',
398
+ properties: {
399
+ Remember: { type: 'boolean', default: true },
400
+ Username: { type: 'string' },
401
+ },
402
+ },
403
+ },
404
+ }
405
+
406
+ describe('TablerSchema applying default values', () => {
407
+ it('keeps existing values and only fills missing keys', async () => {
408
+ const wrapper = mount(Schema, {
409
+ props: {
410
+ modelValue: { Name: 'Bob', Tags: [] },
411
+ schema: DEFAULT_SCHEMA,
412
+ },
413
+ })
414
+
415
+ await flushPromises()
416
+
417
+ const data = lastEmitted(wrapper)
418
+ expect(data.Name).toBe('Bob')
419
+ expect(data.Tags).toEqual([])
420
+ expect(data.Count).toBe(5)
421
+ expect(data.Level).toBe('high')
422
+ })
423
+
424
+ it('seeds a root level const and hides it from the form', async () => {
425
+ const wrapper = mount(Schema, {
426
+ props: { modelValue: {}, schema: DEFAULT_SCHEMA },
427
+ })
428
+
429
+ await flushPromises()
430
+
431
+ expect(lastEmitted(wrapper).Kind).toBe('thing')
432
+ expect(wrapper.findAll('label').map((l) => l.text())).not.toContain('Kind')
433
+ })
434
+
435
+ it('seeds nested object defaults through the nested form', async () => {
436
+ const wrapper = mount(Schema, {
437
+ props: { modelValue: {}, schema: DEFAULT_SCHEMA },
438
+ })
439
+
440
+ await flushPromises()
441
+
442
+ expect(lastEmitted(wrapper).Auth).toEqual({ Remember: true, Username: '' })
443
+ })
444
+
445
+ it('clones array defaults so edits do not leak back into the schema', async () => {
446
+ const schema = JSON.parse(JSON.stringify(DEFAULT_SCHEMA))
447
+ const wrapper = mount(Schema, {
448
+ props: { modelValue: {}, schema },
449
+ })
450
+
451
+ await flushPromises()
452
+
453
+ const tags = lastEmitted(wrapper).Tags as string[]
454
+ expect(tags).toEqual(['a'])
455
+ tags.push('b')
456
+ expect(schema.properties.Tags.default).toEqual(['a'])
457
+ })
458
+
459
+ it('applies defaults again when the parent replaces the model value', async () => {
460
+ const wrapper = mount(Schema, {
461
+ props: { modelValue: { Name: 'Bob' }, schema: DEFAULT_SCHEMA },
462
+ })
463
+
464
+ await flushPromises()
465
+ await wrapper.setProps({ modelValue: { Name: 'Zed' } })
466
+ await flushPromises()
467
+
468
+ const data = lastEmitted(wrapper)
469
+ expect(data.Name).toBe('Zed')
470
+ expect(data.Count).toBe(5)
471
+ expect(data.Kind).toBe('thing')
472
+ })
473
+
474
+ it('applies defaults for properties added when the schema changes', async () => {
475
+ const wrapper = mount(Schema, {
476
+ props: {
477
+ modelValue: {},
478
+ schema: { type: 'object', properties: { Name: { type: 'string' } } },
479
+ },
480
+ })
481
+
482
+ await flushPromises()
483
+ expect(lastEmitted(wrapper)).toEqual({ Name: '' })
484
+
485
+ await wrapper.setProps({
486
+ schema: {
487
+ type: 'object',
488
+ required: ['Name'],
489
+ properties: {
490
+ Name: { type: 'string' },
491
+ Count: { type: 'integer', default: 7 },
492
+ },
493
+ },
494
+ })
495
+ await flushPromises()
496
+
497
+ expect(lastEmitted(wrapper)).toEqual({ Name: '', Count: 7 })
498
+ expect(wrapper.find('.text-red').exists()).toBe(true)
499
+ })
500
+
501
+ it('re-detects the union variant when the parent replaces the model value', async () => {
502
+ const wrapper = mount(Schema, {
503
+ props: {
504
+ modelValue: { Source: { Mode: 'Map', MapId: 'x' } },
505
+ schema: UNION_SCHEMA,
506
+ },
507
+ })
508
+
509
+ await flushPromises()
510
+ expect((wrapper.find('select').element as HTMLSelectElement).value).toBe('Single Map')
511
+
512
+ await wrapper.setProps({ modelValue: { Source: { Mode: 'Team', TeamId: 't' } } })
513
+ await flushPromises()
514
+
515
+ expect((wrapper.find('select').element as HTMLSelectElement).value).toBe('Team Account')
516
+ expect(lastEmitted(wrapper)).toEqual({ Source: { Mode: 'Team', TeamId: 't', Verbose: true } })
517
+ })
518
+ })
package/vitest.config.mjs CHANGED
@@ -6,5 +6,10 @@ export default defineConfig({
6
6
  test: {
7
7
  environment: 'jsdom',
8
8
  include: ['test/**/*.spec.ts'],
9
+ coverage: {
10
+ provider: 'v8',
11
+ include: ['components/**', 'lib.ts'],
12
+ reporter: ['text-summary', 'lcov'],
13
+ },
9
14
  },
10
15
  })