@refrakt-md/editor 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/app/dist/assets/{index-CCkzIGTi.js → index-3XGwrbJi.js} +1 -1
  2. package/app/dist/assets/{index-CXeK-dZx.js → index-4QIVBXA2.js} +1 -1
  3. package/app/dist/assets/{index-80NtMar1.js → index-64pKPA7X.js} +1 -1
  4. package/app/dist/assets/{index-DNJBunzP.js → index-87jnOwXd.js} +1 -1
  5. package/app/dist/assets/{index-BDj1XPol.js → index-BC2x3b2t.js} +1 -1
  6. package/app/dist/assets/{index-Bn8ajfVl.js → index-Bb8l840O.js} +1 -1
  7. package/app/dist/assets/{index-BXe1fKaT.js → index-BcejoAP1.js} +1 -1
  8. package/app/dist/assets/{index-CaRBCHaX.js → index-BfRxJzFS.js} +1 -1
  9. package/app/dist/assets/{index-DQUOY-pF.js → index-Bx44CkAs.js} +1 -1
  10. package/app/dist/assets/{index-DGYxLhpR.js → index-CARyuClI.js} +1 -1
  11. package/app/dist/assets/{index-xo7v6nRB.js → index-CEUDrca1.js} +1 -1
  12. package/app/dist/assets/{index-Cgbvx23V.js → index-CNd1XgyZ.js} +1 -1
  13. package/app/dist/assets/{index-DskvyNKT.js → index-CO6-R3qL.js} +1 -1
  14. package/app/dist/assets/{index-DNtuldOx.js → index-Chzl2Gom.js} +1 -1
  15. package/app/dist/assets/{index-D5ucdUTo.js → index-Cj0n5HXq.js} +1 -1
  16. package/app/dist/assets/index-CzvG5PZT.css +1 -0
  17. package/app/dist/assets/index-DdNJVnBL.js +555 -0
  18. package/app/dist/assets/{index-dGztG-54.js → index-DiK4QBVK.js} +1 -1
  19. package/app/dist/assets/{index-BfxTGrHB.js → index-SvR5c3Vk.js} +1 -1
  20. package/app/dist/assets/{index-aPeHMqUX.js → index-YNSVyj5l.js} +1 -1
  21. package/app/dist/index.html +2 -2
  22. package/app/src/lib/components/BlockEditor.svelte +381 -47
  23. package/app/src/lib/components/InlineEditor.svelte +15 -5
  24. package/app/src/lib/components/ProseBlockCard.svelte +446 -0
  25. package/app/src/lib/components/ProseEditPanel.svelte +470 -0
  26. package/app/src/lib/editor/attribute-completion.ts +159 -0
  27. package/app/src/lib/editor/block-parser.ts +59 -2
  28. package/app/src/lib/editor/codemirror-theme.ts +115 -0
  29. package/app/src/lib/editor/content-model-resolver.ts +196 -0
  30. package/app/src/lib/editor/inline-markdown.ts +237 -0
  31. package/app/src/lib/editor/markdoc-highlight.ts +74 -0
  32. package/app/src/lib/editor/rune-palette.ts +77 -0
  33. package/app/src/lib/editor/section-mapper.ts +476 -0
  34. package/app/src/lib/state/editor.svelte.ts +151 -0
  35. package/app/src/lib/utils/frontmatter.ts +43 -0
  36. package/app/src/lib/utils/layout-parser.ts +197 -0
  37. package/package.json +10 -8
  38. package/app/dist/assets/index-B6H6LF1M.css +0 -1
  39. package/app/dist/assets/index-Cd12jZId.js +0 -479
@@ -0,0 +1,115 @@
1
+ import { EditorView } from '@codemirror/view';
2
+ import { HighlightStyle } from '@codemirror/language';
3
+ import { tags } from '@lezer/highlight';
4
+
5
+ export const lightTheme = EditorView.theme(
6
+ {
7
+ '&': {
8
+ backgroundColor: '#f8fafc',
9
+ color: '#1a1a2e',
10
+ fontSize: '13px',
11
+ height: '100%',
12
+ },
13
+ '.cm-scroller': {
14
+ overflow: 'auto',
15
+ fontFamily: "'SF Mono', 'Fira Code', ui-monospace, monospace",
16
+ lineHeight: '1.6',
17
+ },
18
+ '.cm-content': {
19
+ padding: '1rem 0',
20
+ caretColor: '#1e293b',
21
+ },
22
+ '.cm-gutters': {
23
+ backgroundColor: '#f8fafc',
24
+ color: '#94a3b8',
25
+ border: 'none',
26
+ paddingRight: '0.5rem',
27
+ },
28
+ '.cm-activeLineGutter': {
29
+ backgroundColor: '#e2e8f0',
30
+ color: '#64748b',
31
+ },
32
+ '.cm-activeLine': {
33
+ backgroundColor: 'rgba(0, 0, 0, 0.03)',
34
+ },
35
+ '.cm-cursor': {
36
+ borderLeftColor: '#1e293b',
37
+ },
38
+ '&.cm-focused .cm-selectionBackground, ::selection': {
39
+ backgroundColor: 'rgba(14, 165, 233, 0.2)',
40
+ },
41
+ '.cm-selectionBackground': {
42
+ backgroundColor: 'rgba(14, 165, 233, 0.12)',
43
+ },
44
+ '&.cm-focused': {
45
+ outline: 'none',
46
+ },
47
+ // Autocomplete dropdown styling
48
+ '.cm-tooltip.cm-tooltip-autocomplete': {
49
+ border: '1px solid #e2e8f0',
50
+ borderRadius: '6px',
51
+ boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)',
52
+ backgroundColor: '#ffffff',
53
+ overflow: 'hidden',
54
+ },
55
+ '.cm-tooltip.cm-tooltip-autocomplete ul': {
56
+ fontFamily: 'system-ui, -apple-system, sans-serif',
57
+ fontSize: '12px',
58
+ maxHeight: '280px',
59
+ },
60
+ '.cm-tooltip.cm-tooltip-autocomplete ul li': {
61
+ padding: '4px 8px',
62
+ borderBottom: '1px solid #f1f5f9',
63
+ },
64
+ '.cm-tooltip.cm-tooltip-autocomplete ul li[aria-selected]': {
65
+ backgroundColor: '#f0f9ff',
66
+ color: '#0369a1',
67
+ },
68
+ '.cm-tooltip.cm-completionInfo': {
69
+ border: '1px solid #e2e8f0',
70
+ borderRadius: '6px',
71
+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08)',
72
+ backgroundColor: '#ffffff',
73
+ padding: '6px 10px',
74
+ fontFamily: 'system-ui, -apple-system, sans-serif',
75
+ fontSize: '12px',
76
+ color: '#475569',
77
+ maxWidth: '300px',
78
+ },
79
+ '.cm-completionDetail': {
80
+ color: '#94a3b8',
81
+ fontStyle: 'normal',
82
+ marginLeft: '0.5em',
83
+ },
84
+ // Markdoc tag highlighting
85
+ '.cm-markdoc-tag': {
86
+ backgroundColor: 'rgba(217, 119, 6, 0.06)',
87
+ borderRadius: '2px',
88
+ },
89
+ '.cm-markdoc-bracket': {
90
+ color: '#94a3b8',
91
+ },
92
+ '.cm-markdoc-name': {
93
+ color: '#d97706',
94
+ fontWeight: '600',
95
+ },
96
+ },
97
+ { dark: false },
98
+ );
99
+
100
+ export const highlightTheme = HighlightStyle.define([
101
+ { tag: tags.heading1, color: '#0369a1', fontWeight: 'bold', fontSize: '1.4em' },
102
+ { tag: tags.heading2, color: '#0369a1', fontWeight: 'bold', fontSize: '1.2em' },
103
+ { tag: tags.heading3, color: '#0369a1', fontWeight: 'bold', fontSize: '1.1em' },
104
+ { tag: tags.heading, color: '#0369a1', fontWeight: 'bold' },
105
+ { tag: tags.emphasis, color: '#9333ea', fontStyle: 'italic' },
106
+ { tag: tags.strong, color: '#9333ea', fontWeight: 'bold' },
107
+ { tag: tags.link, color: '#0ea5e9', textDecoration: 'underline' },
108
+ { tag: tags.url, color: '#0ea5e9' },
109
+ { tag: tags.quote, color: '#64748b' },
110
+ { tag: tags.monospace, color: '#16a34a' },
111
+ { tag: tags.processingInstruction, color: '#d97706' },
112
+ { tag: tags.meta, color: '#94a3b8' },
113
+ { tag: tags.comment, color: '#94a3b8' },
114
+ { tag: tags.punctuation, color: '#94a3b8' },
115
+ ]);
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Client-side content model resolver.
3
+ *
4
+ * Matches parsed ContentNodes (from parseContentTree) against a serialized
5
+ * content model to determine which fields are filled and which are empty.
6
+ */
7
+
8
+ import type { ContentNode } from './block-parser.js';
9
+ import type {
10
+ SerializedContentModel,
11
+ SerializedFieldDef,
12
+ SerializedSequenceModel,
13
+ SerializedDelimitedZone,
14
+ } from '../api/client.js';
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Output types
18
+ // ---------------------------------------------------------------------------
19
+
20
+ export interface ResolvedField {
21
+ /** Field name from the content model */
22
+ name: string;
23
+ /** Expected node type pattern (e.g. 'paragraph', 'heading', 'list|fence') */
24
+ match: string;
25
+ /** Whether the field can be absent */
26
+ optional: boolean;
27
+ /** Whether the field consumes multiple consecutive matches */
28
+ greedy: boolean;
29
+ /** Whether content was matched to this field */
30
+ filled: boolean;
31
+ /** Matched content nodes (empty if unfilled) */
32
+ nodes: ContentNode[];
33
+ /** Human-readable description from field definition */
34
+ description?: string;
35
+ /** Markdoc template for inserting content */
36
+ template?: string;
37
+ /** If field emits child rune tags */
38
+ emitTag?: string;
39
+ }
40
+
41
+ export interface ResolvedZone {
42
+ name: string;
43
+ fields: ResolvedField[];
44
+ }
45
+
46
+ export type ResolvedStructure =
47
+ | { type: 'sequence'; fields: ResolvedField[] }
48
+ | { type: 'delimited'; delimiter: string; zones: ResolvedZone[] }
49
+ | { type: 'sections'; description: string }
50
+ | { type: 'custom'; description: string };
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Node matching
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /** Check if a ContentNode matches a field's match pattern */
57
+ function nodeMatchesType(node: ContentNode, match: string): boolean {
58
+ if (match === 'any') return true;
59
+
60
+ // Pipe-separated alternatives: 'list|fence'
61
+ if (match.includes('|')) {
62
+ return match.split('|').some(m => nodeMatchesType(node, m));
63
+ }
64
+
65
+ // heading:N
66
+ if (match.startsWith('heading:')) {
67
+ const level = parseInt(match.slice(8), 10);
68
+ return node.type === 'heading' && node.headingLevel === level;
69
+ }
70
+
71
+ // list:ordered / list:unordered
72
+ if (match === 'list:ordered') {
73
+ return node.type === 'list' && node.listOrdered === true;
74
+ }
75
+ if (match === 'list:unordered') {
76
+ return node.type === 'list' && node.listOrdered !== true;
77
+ }
78
+
79
+ // tag:NAME — ContentNodes use 'rune' type
80
+ if (match.startsWith('tag:')) {
81
+ const tagName = match.slice(4);
82
+ return node.type === 'rune' && node.runeName === tagName;
83
+ }
84
+
85
+ // Simple type match (ContentNode types: rune, heading, paragraph, fence, list, quote, hr, image)
86
+ // Map content model match names to ContentNode type names
87
+ if (match === 'blockquote') return node.type === 'quote';
88
+
89
+ return node.type === match;
90
+ }
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // Sequence resolver
94
+ // ---------------------------------------------------------------------------
95
+
96
+ function resolveSequence(nodes: ContentNode[], fields: SerializedFieldDef[]): ResolvedField[] {
97
+ const result: ResolvedField[] = [];
98
+ let cursor = 0;
99
+
100
+ for (const field of fields) {
101
+ const resolved: ResolvedField = {
102
+ name: field.name,
103
+ match: field.match,
104
+ optional: field.optional ?? false,
105
+ greedy: field.greedy ?? false,
106
+ filled: false,
107
+ nodes: [],
108
+ description: field.description,
109
+ template: field.template,
110
+ emitTag: field.emitTag,
111
+ };
112
+
113
+ if (field.greedy) {
114
+ // Consume all consecutive matching nodes
115
+ while (cursor < nodes.length && nodeMatchesType(nodes[cursor], field.match)) {
116
+ resolved.nodes.push(nodes[cursor]);
117
+ cursor++;
118
+ }
119
+ resolved.filled = resolved.nodes.length > 0;
120
+ } else {
121
+ // Match the next node if it fits
122
+ if (cursor < nodes.length && nodeMatchesType(nodes[cursor], field.match)) {
123
+ resolved.nodes.push(nodes[cursor]);
124
+ resolved.filled = true;
125
+ cursor++;
126
+ }
127
+ }
128
+
129
+ result.push(resolved);
130
+ }
131
+
132
+ return result;
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Main resolver
137
+ // ---------------------------------------------------------------------------
138
+
139
+ /**
140
+ * Resolve a content tree against a serialized content model.
141
+ * Returns a structure describing which fields are filled and which are empty.
142
+ */
143
+ export function resolveContentStructure(
144
+ nodes: ContentNode[],
145
+ model: SerializedContentModel,
146
+ ): ResolvedStructure {
147
+ switch (model.type) {
148
+ case 'sequence':
149
+ return {
150
+ type: 'sequence',
151
+ fields: resolveSequence(nodes, model.fields),
152
+ };
153
+
154
+ case 'delimited': {
155
+ // Split nodes at delimiter (hr) boundaries
156
+ const zones: ResolvedZone[] = [];
157
+ const chunks: ContentNode[][] = [[]];
158
+ for (const node of nodes) {
159
+ if (node.type === 'hr') {
160
+ chunks.push([]);
161
+ } else {
162
+ chunks[chunks.length - 1].push(node);
163
+ }
164
+ }
165
+
166
+ if (model.zones) {
167
+ for (let i = 0; i < model.zones.length; i++) {
168
+ const zone = model.zones[i];
169
+ const chunk = chunks[i] ?? [];
170
+ zones.push({
171
+ name: zone.name,
172
+ fields: resolveSequence(chunk, zone.fields),
173
+ });
174
+ }
175
+ } else if (model.dynamicZones && model.zoneModel) {
176
+ for (let i = 0; i < chunks.length; i++) {
177
+ zones.push({
178
+ name: `zone-${i + 1}`,
179
+ fields: resolveSequence(chunks[i], model.zoneModel.fields),
180
+ });
181
+ }
182
+ }
183
+
184
+ return { type: 'delimited', delimiter: model.delimiter, zones };
185
+ }
186
+
187
+ case 'sections':
188
+ return {
189
+ type: 'sections',
190
+ description: `Sections split by ${model.sectionHeading}${model.emitTag ? `, each emits ${model.emitTag}` : ''}`,
191
+ };
192
+
193
+ case 'custom':
194
+ return { type: 'custom', description: model.description };
195
+ }
196
+ }
@@ -0,0 +1,237 @@
1
+ import Markdoc from '@markdoc/markdoc';
2
+ import type { Node } from '@markdoc/markdoc';
3
+
4
+ /**
5
+ * Parse inline markdown source into HTML suitable for contentEditable.
6
+ *
7
+ * Uses Markdoc.parse() on a synthetic paragraph, then walks the inline AST
8
+ * to produce clean HTML with only the inline elements we support:
9
+ * strong, em, code, and links.
10
+ */
11
+ export function parseInlineMarkdown(source: string): string {
12
+ if (!source) return '';
13
+
14
+ const ast = Markdoc.parse(source);
15
+ // The AST is: document > paragraph > inline children
16
+ const doc = ast;
17
+ if (!doc.children?.length) return escapeHtml(source);
18
+
19
+ const paragraph = doc.children[0];
20
+ if (!paragraph?.children?.length) return escapeHtml(source);
21
+
22
+ return renderInlineNodes(paragraph.children);
23
+ }
24
+
25
+ function renderInlineNodes(nodes: Node[]): string {
26
+ return nodes.map(renderInlineNode).join('');
27
+ }
28
+
29
+ function renderInlineNode(node: Node): string {
30
+ switch (node.type) {
31
+ case 'text':
32
+ return escapeHtml(node.attributes.content ?? '');
33
+
34
+ case 'strong':
35
+ return `<strong>${renderInlineNodes(node.children)}</strong>`;
36
+
37
+ case 'em':
38
+ return `<em>${renderInlineNodes(node.children)}</em>`;
39
+
40
+ case 's':
41
+ return `<s>${renderInlineNodes(node.children)}</s>`;
42
+
43
+ case 'code':
44
+ return `<code>${escapeHtml(node.attributes.content ?? '')}</code>`;
45
+
46
+ case 'link': {
47
+ const href = node.attributes.href ?? '';
48
+ const title = node.attributes.title;
49
+ const titleAttr = title ? ` title="${escapeAttr(title)}"` : '';
50
+ return `<a href="${escapeAttr(href)}"${titleAttr}>${renderInlineNodes(node.children)}</a>`;
51
+ }
52
+
53
+ case 'hardbreak':
54
+ return ' ';
55
+
56
+ case 'softbreak':
57
+ return ' ';
58
+
59
+ default:
60
+ // Graceful fallback: render children if any
61
+ if (node.children?.length) {
62
+ return renderInlineNodes(node.children);
63
+ }
64
+ return '';
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Serialize the DOM contents of a contentEditable element back to inline markdown.
70
+ */
71
+ export function serializeInlineHtml(el: HTMLElement): string {
72
+ return serializeNodes(el.childNodes);
73
+ }
74
+
75
+ function serializeNodes(nodes: NodeListOf<ChildNode> | ChildNode[]): string {
76
+ const parts: string[] = [];
77
+ for (const node of nodes) {
78
+ parts.push(serializeNode(node));
79
+ }
80
+ return parts.join('');
81
+ }
82
+
83
+ const TEXT_NODE = 3;
84
+ const ELEMENT_NODE = 1;
85
+
86
+ function serializeNode(node: ChildNode): string {
87
+ if (node.nodeType === TEXT_NODE) {
88
+ return escapeMarkdown(node.textContent ?? '');
89
+ }
90
+
91
+ if (node.nodeType !== ELEMENT_NODE) return '';
92
+
93
+ const el = node as HTMLElement;
94
+ const tag = el.tagName;
95
+
96
+ switch (tag) {
97
+ case 'STRONG':
98
+ case 'B':
99
+ return `**${serializeNodes(el.childNodes)}**`;
100
+
101
+ case 'EM':
102
+ case 'I':
103
+ return `*${serializeNodes(el.childNodes)}*`;
104
+
105
+ case 'S':
106
+ case 'STRIKE':
107
+ case 'DEL':
108
+ return `~~${serializeNodes(el.childNodes)}~~`;
109
+
110
+ case 'CODE':
111
+ return `\`${el.textContent ?? ''}\``;
112
+
113
+ case 'A': {
114
+ const href = el.getAttribute('href') ?? '';
115
+ const text = serializeNodes(el.childNodes);
116
+ return `[${text}](${href})`;
117
+ }
118
+
119
+ case 'BR':
120
+ return ' ';
121
+
122
+ // Browser quirks: contentEditable may wrap text in divs/spans
123
+ case 'DIV':
124
+ case 'P':
125
+ case 'SPAN':
126
+ return serializeNodes(el.childNodes);
127
+
128
+ default:
129
+ return serializeNodes(el.childNodes);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Strip inline markdown formatting to produce plain text (for matching).
135
+ */
136
+ export function stripInlineMarkdown(source: string): string {
137
+ return source
138
+ // Links: [text](url) or [text](url "title") → text
139
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
140
+ // Images: ![alt](url) → alt
141
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
142
+ // Bold: **text** or __text__
143
+ .replace(/\*\*(.+?)\*\*/g, '$1')
144
+ .replace(/__(.+?)__/g, '$1')
145
+ // Italic: *text* or _text_
146
+ .replace(/\*(.+?)\*/g, '$1')
147
+ .replace(/_(.+?)_/g, '$1')
148
+ // Strikethrough: ~~text~~
149
+ .replace(/~~(.+?)~~/g, '$1')
150
+ // Inline code: `text`
151
+ .replace(/`([^`]+)`/g, '$1');
152
+ }
153
+
154
+ // ── Helpers ──────────────────────────────────────────────────
155
+
156
+ function escapeHtml(s: string): string {
157
+ return s
158
+ .replace(/&/g, '&amp;')
159
+ .replace(/</g, '&lt;')
160
+ .replace(/>/g, '&gt;')
161
+ .replace(/"/g, '&quot;');
162
+ }
163
+
164
+ function escapeAttr(s: string): string {
165
+ return s
166
+ .replace(/&/g, '&amp;')
167
+ .replace(/"/g, '&quot;')
168
+ .replace(/</g, '&lt;')
169
+ .replace(/>/g, '&gt;');
170
+ }
171
+
172
+ /**
173
+ * Escape markdown-significant characters in plain text that will be
174
+ * inserted into a markdown context. Only escapes characters that would
175
+ * otherwise trigger formatting.
176
+ */
177
+ function escapeMarkdown(s: string): string {
178
+ // Escape characters that start markdown formatting tokens
179
+ // when they appear in text nodes (i.e. user typed them literally)
180
+ return s.replace(/([\\*_`~\[\]])/g, '\\$1');
181
+ }
182
+
183
+ /**
184
+ * Normalize a contentEditable element's DOM to clean up browser quirks.
185
+ * Call this after paste or format operations.
186
+ */
187
+ export function normalizeEditableDom(el: HTMLElement): void {
188
+ // Replace <b> with <strong>, <i> with <em>
189
+ for (const b of Array.from(el.querySelectorAll('b'))) {
190
+ const strong = document.createElement('strong');
191
+ strong.innerHTML = b.innerHTML;
192
+ b.replaceWith(strong);
193
+ }
194
+ for (const i of Array.from(el.querySelectorAll('i'))) {
195
+ const em = document.createElement('em');
196
+ em.innerHTML = i.innerHTML;
197
+ i.replaceWith(em);
198
+ }
199
+
200
+ // Remove styled spans (browser formatting artifacts)
201
+ for (const span of Array.from(el.querySelectorAll('span[style]'))) {
202
+ // Check if the style indicates bold or italic and convert
203
+ const style = (span as HTMLElement).style;
204
+ const parent = span.parentNode;
205
+ if (!parent) continue;
206
+
207
+ if (style.fontWeight === 'bold' || parseInt(style.fontWeight) >= 700) {
208
+ const strong = document.createElement('strong');
209
+ strong.innerHTML = span.innerHTML;
210
+ span.replaceWith(strong);
211
+ } else if (style.fontStyle === 'italic') {
212
+ const em = document.createElement('em');
213
+ em.innerHTML = span.innerHTML;
214
+ span.replaceWith(em);
215
+ } else {
216
+ // Unwrap the span, keeping its children
217
+ while (span.firstChild) {
218
+ parent.insertBefore(span.firstChild, span);
219
+ }
220
+ span.remove();
221
+ }
222
+ }
223
+
224
+ // Flatten block elements that contentEditable may create
225
+ for (const div of Array.from(el.querySelectorAll('div, p'))) {
226
+ const parent = div.parentNode;
227
+ if (!parent || div === el) continue;
228
+ // Replace with a space + children
229
+ if (div.previousSibling) {
230
+ parent.insertBefore(document.createTextNode(' '), div);
231
+ }
232
+ while (div.firstChild) {
233
+ parent.insertBefore(div.firstChild, div);
234
+ }
235
+ div.remove();
236
+ }
237
+ }
@@ -0,0 +1,74 @@
1
+ import {
2
+ ViewPlugin,
3
+ Decoration,
4
+ type DecorationSet,
5
+ type EditorView,
6
+ type ViewUpdate,
7
+ } from '@codemirror/view';
8
+ import { RangeSetBuilder } from '@codemirror/state';
9
+ import type { Extension } from '@codemirror/state';
10
+
11
+ const tagDeco = Decoration.mark({ class: 'cm-markdoc-tag' });
12
+ const bracketDeco = Decoration.mark({ class: 'cm-markdoc-bracket' });
13
+ const nameDeco = Decoration.mark({ class: 'cm-markdoc-name' });
14
+
15
+ // Matches: {% tagname ... %}, {% /tagname %}, {% tagname ... /%}
16
+ const TAG_RE = /\{%\s*(\/?)(\w[\w-]*)((?:\s+[^%]*)?)(\/?)\s*%\}/g;
17
+
18
+ function buildDecorations(view: EditorView): DecorationSet {
19
+ const ranges: { from: number; to: number; deco: Decoration }[] = [];
20
+
21
+ for (const { from, to } of view.visibleRanges) {
22
+ const text = view.state.doc.sliceString(from, to);
23
+ TAG_RE.lastIndex = 0;
24
+
25
+ let match: RegExpExecArray | null;
26
+ while ((match = TAG_RE.exec(text)) !== null) {
27
+ const start = from + match.index;
28
+ const end = start + match[0].length;
29
+
30
+ ranges.push({ from: start, to: end, deco: tagDeco });
31
+ ranges.push({ from: start, to: start + 2, deco: bracketDeco });
32
+ ranges.push({ from: end - 2, to: end, deco: bracketDeco });
33
+
34
+ const slash = match[1];
35
+ const name = match[2];
36
+ const nameOffset = match[0].indexOf(slash + name, 2);
37
+ const nameStart = start + nameOffset + slash.length;
38
+ ranges.push({ from: nameStart, to: nameStart + name.length, deco: nameDeco });
39
+ }
40
+ }
41
+
42
+ ranges.sort((a, b) => a.from - b.from || a.to - b.to);
43
+
44
+ const builder = new RangeSetBuilder<Decoration>();
45
+ for (const r of ranges) {
46
+ builder.add(r.from, r.to, r.deco);
47
+ }
48
+ return builder.finish();
49
+ }
50
+
51
+ const markdocPlugin = ViewPlugin.fromClass(
52
+ class {
53
+ decorations: DecorationSet;
54
+
55
+ constructor(view: EditorView) {
56
+ this.decorations = buildDecorations(view);
57
+ }
58
+
59
+ update(update: ViewUpdate) {
60
+ if (update.docChanged || update.viewportChanged) {
61
+ this.decorations = buildDecorations(update.view);
62
+ }
63
+ }
64
+ },
65
+ { decorations: (v) => v.decorations },
66
+ );
67
+
68
+ /**
69
+ * Creates a CodeMirror extension that highlights Markdoc tag syntax.
70
+ * Adds visual decoration to `{% tagname %}` and `{% /tagname %}` blocks.
71
+ */
72
+ export function markdocHighlight(): Extension {
73
+ return markdocPlugin;
74
+ }
@@ -0,0 +1,77 @@
1
+ import {
2
+ type CompletionContext,
3
+ type CompletionResult,
4
+ type Completion,
5
+ type CompletionSource,
6
+ } from '@codemirror/autocomplete';
7
+ import type { RuneInfo } from '../api/client.js';
8
+
9
+ /**
10
+ * Build a snippet string for inserting a rune.
11
+ * Self-closing runes: `{% name /%}`
12
+ * Block runes: `{% name %}\n\n{% /name %}`
13
+ */
14
+ function buildSnippet(rune: RuneInfo): string {
15
+ // Build required attribute defaults
16
+ const attrParts: string[] = [];
17
+ for (const [name, attr] of Object.entries(rune.attributes)) {
18
+ if (attr.required) {
19
+ const defaultVal = attr.values?.[0] ?? '';
20
+ attrParts.push(`${name}="${defaultVal}"`);
21
+ }
22
+ }
23
+ const attrStr = attrParts.length > 0 ? ' ' + attrParts.join(' ') : '';
24
+
25
+ if (rune.selfClosing) {
26
+ return `{% ${rune.name}${attrStr} /%}`;
27
+ }
28
+ return `{% ${rune.name}${attrStr} %}\n\n{% /${rune.name} %}`;
29
+ }
30
+
31
+ /**
32
+ * Creates a CompletionSource for the rune palette triggered by `/`.
33
+ * Accepts a getter function so runes are read at query time (not creation time).
34
+ */
35
+ export function runeCompletionSource(getRunes: () => RuneInfo[]): CompletionSource {
36
+ return (context: CompletionContext): CompletionResult | null => {
37
+ const word = context.matchBefore(/\/\w*/);
38
+ if (!word) return null;
39
+
40
+ // Only trigger at start of line or after whitespace
41
+ if (word.from > 0) {
42
+ const charBefore = context.state.doc.sliceString(word.from - 1, word.from);
43
+ if (charBefore.trim() !== '') return null;
44
+ }
45
+
46
+ const runes = getRunes();
47
+ if (runes.length === 0) return null;
48
+
49
+ const slashFrom = word.from; // position of the `/` trigger character
50
+
51
+ const completions: Completion[] = runes.map((rune) => ({
52
+ label: rune.name,
53
+ detail: rune.category,
54
+ info: rune.description,
55
+ section: rune.category,
56
+ type: 'keyword',
57
+ apply: (view, _completion, from, to) => {
58
+ const snippet = buildSnippet(rune);
59
+ // Replace from the `/` to remove the trigger character
60
+ view.dispatch({
61
+ changes: { from: slashFrom, to, insert: snippet },
62
+ selection: {
63
+ anchor: rune.selfClosing
64
+ ? slashFrom + snippet.indexOf('/%}')
65
+ : slashFrom + snippet.indexOf('%}') + 2 + 1,
66
+ },
67
+ });
68
+ },
69
+ }));
70
+
71
+ return {
72
+ from: slashFrom + 1, // filter starts after `/` so "hint" matches typed "h"
73
+ options: completions,
74
+ filter: true,
75
+ };
76
+ };
77
+ }