@tak-ps/vue-tabler 5.6.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.
package/CHANGELOG.md CHANGED
@@ -12,6 +12,14 @@
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
+
15
23
  ### v5.6.0 - 2026-09-15
16
24
 
17
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
package/README.md CHANGED
@@ -74,6 +74,7 @@ import { TablerButton, TablerAlert } from '@tak-ps/vue-tabler';
74
74
  | **TablerList** | Display data in list format. |
75
75
  | **TablerLoading** | Loading indicators and spinners. |
76
76
  | **TablerMarkdown** | Render markdown content safely. |
77
+ | **TablerMarkdownEditor** | WYSIWYG Markdown editor with table editing, styled the same as `TablerMarkdown`. Loaded on first render. |
77
78
  | **TablerModal** | Dialog boxes for user interaction. |
78
79
  | **TablerNone** | Placeholder component for empty states. |
79
80
  | **TablerPager** | Pagination controls for lists and tables. |
@@ -100,6 +101,7 @@ This library relies on the following core dependencies:
100
101
  - [Vue 3](https://vuejs.org/)
101
102
  - [@tabler/icons-vue](https://www.npmjs.com/package/@tabler/icons-vue)
102
103
  - [marked](https://www.npmjs.com/package/marked) (for Markdown rendering)
104
+ - [Tiptap](https://www.npmjs.com/package/@tiptap/vue-3) (for Markdown editing)
103
105
  - [DOMPurify](https://www.npmjs.com/package/dompurify) (for HTML sanitization)
104
106
 
105
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'))
@@ -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.6.0",
4
+ "version": "5.7.0",
5
5
  "lib": "lib.ts",
6
6
  "main": "lib.ts",
7
7
  "module": "lib.ts",
@@ -28,6 +28,11 @@
28
28
  "homepage": "https://github.com/tak-ps/vue-tabler#readme",
29
29
  "dependencies": {
30
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",
31
36
  "dompurify": "^3.4.1",
32
37
  "marked": "^18.0.2"
33
38
  },
@@ -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
+ })