@airalogy/aimd-editor 1.15.0 → 1.16.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.
@@ -1,7 +1,8 @@
1
1
  import { ref, shallowRef, computed, watch, nextTick } from 'vue'
2
2
  import { protectAimdInlineTemplates, restoreAimdInlineTemplates } from '@airalogy/aimd-core'
3
3
  import { parseAndExtract } from '@airalogy/aimd-renderer'
4
- import type { Editor } from '@milkdown/kit/core'
4
+ import { editorViewCtx, type Editor } from '@milkdown/kit/core'
5
+ import type { Node } from '@milkdown/kit/prose/model'
5
6
  import { replaceAll, getMarkdown, insert } from '@milkdown/kit/utils'
6
7
  import { insertTableCommand } from '@milkdown/kit/preset/gfm'
7
8
  import { callCommand } from '@milkdown/kit/utils'
@@ -27,6 +28,12 @@ export function useEditorContent(options: UseEditorContentOptions) {
27
28
  const milkdownEditorRef = shallowRef<Editor | null>(null)
28
29
 
29
30
  let isSyncing = false
31
+ let syncedVisualDoc: Node | undefined
32
+ let syncedVisualSource = initialContent
33
+
34
+ function visualDoc(editor: Editor) {
35
+ return editor.action(ctx => ctx.get(editorViewCtx).state.doc)
36
+ }
30
37
 
31
38
  function commitUserContent(nextContent: string) {
32
39
  if (nextContent === content.value) {
@@ -92,9 +99,13 @@ export function useEditorContent(options: UseEditorContentOptions) {
92
99
 
93
100
  if (editorMode.value === 'wysiwyg' && milkdownEditorRef.value) {
94
101
  try {
95
- const md = milkdownEditorRef.value.action(getMarkdown())
96
- if (typeof md === 'string') {
97
- content.value = normalizeMilkdownMarkdown(md, content.value)
102
+ // A visual-only interaction (such as expanding an image) must not
103
+ // reserialize the file on the way back to source mode.
104
+ if (syncedVisualDoc?.eq(visualDoc(milkdownEditorRef.value))) {
105
+ commitUserContent(syncedVisualSource)
106
+ } else {
107
+ const md = milkdownEditorRef.value.action(getMarkdown())
108
+ if (typeof md === 'string') commitUserContent(normalizeMilkdownMarkdown(md, content.value))
98
109
  }
99
110
  } catch {}
100
111
  }
@@ -115,6 +126,8 @@ export function useEditorContent(options: UseEditorContentOptions) {
115
126
  try {
116
127
  isSyncing = true
117
128
  milkdownEditorRef.value.action(replaceAll(toMilkdownMarkdown(content.value)))
129
+ syncedVisualDoc = visualDoc(milkdownEditorRef.value)
130
+ syncedVisualSource = content.value
118
131
  isSyncing = false
119
132
  } catch { isSyncing = false }
120
133
  }
@@ -129,7 +142,11 @@ export function useEditorContent(options: UseEditorContentOptions) {
129
142
  if (editorMode.value === 'source' && monacoEditor.value) {
130
143
  monacoEditor.value.setValue(val)
131
144
  } else if (editorMode.value === 'wysiwyg' && milkdownEditorRef.value) {
132
- try { milkdownEditorRef.value.action(replaceAll(toMilkdownMarkdown(val))) } catch {}
145
+ try {
146
+ milkdownEditorRef.value.action(replaceAll(toMilkdownMarkdown(val)))
147
+ syncedVisualDoc = visualDoc(milkdownEditorRef.value)
148
+ syncedVisualSource = val
149
+ } catch {}
133
150
  }
134
151
  isSyncing = false
135
152
  }
@@ -236,6 +253,8 @@ export function useEditorContent(options: UseEditorContentOptions) {
236
253
 
237
254
  function onMilkdownReady(editor: Editor) {
238
255
  milkdownEditorRef.value = editor
256
+ syncedVisualDoc = visualDoc(editor)
257
+ syncedVisualSource = content.value
239
258
  }
240
259
 
241
260
  return {
@@ -1,424 +0,0 @@
1
- import { defineComponent as Q, ref as N, onMounted as Y, onBeforeUnmount as J, watch as O, openBlock as T, createElementBlock as $, normalizeStyle as X, toDisplayString as ee, createCommentVNode as te, createElementVNode as ne } from "vue";
2
- import { c as oe, a as ie, d as se, e as re } from "./lexer-DKU2sEoR.js";
3
- import { s as de, n as ae } from "./fig-oCdVp2EF.js";
4
- import "@airalogy/aimd-renderer";
5
- const le = /\{\{\s*(var_table|var)\s*\|([\s\S]*?)\}\}/g, ce = /^[ \t]*(```|~~~)[ \t]*media(?:[^\n]*)?\r?\n([\s\S]*?)^[ \t]*\1[ \t]*$/gm, ue = {
6
- figureMissingId: "This figure is missing the required ID. Generate or enter a unique ID.",
7
- figureMissingSrc: "This figure is missing the required src field.",
8
- figureDuplicateId: (a) => `Figure ID "${a}" is already used in this document.`,
9
- generateFigureId: "Generate figure ID"
10
- };
11
- function D(a, p = ue) {
12
- const c = [];
13
- for (const o of a.matchAll(le)) {
14
- const r = o.index ?? 0, f = o[0], u = o[2] ?? "";
15
- try {
16
- const m = oe(ie(u));
17
- m.length > 0 && c.push({
18
- message: m.join(`
19
- `),
20
- severity: "warning",
21
- startOffset: r,
22
- endOffset: r + f.length
23
- });
24
- } catch {
25
- }
26
- }
27
- for (const o of a.matchAll(ce)) {
28
- const r = o.index ?? 0, f = o[0], u = o[2] ?? "";
29
- try {
30
- const m = se(re(u));
31
- m.length > 0 && c.push({
32
- message: m.join(`
33
- `),
34
- severity: "error",
35
- startOffset: r,
36
- endOffset: r + f.length
37
- });
38
- } catch {
39
- }
40
- }
41
- const s = de(a), b = new Map(
42
- ae(a).generated.map((o) => [o.blockStartOffset, o])
43
- ), h = /* @__PURE__ */ new Set();
44
- for (const o of s) {
45
- const r = o.id?.value ?? "", f = o.src?.value ?? "";
46
- if (!r) {
47
- const u = b.get(o.startOffset);
48
- c.push({
49
- code: "fig-missing-id",
50
- message: p.figureMissingId,
51
- severity: "error",
52
- startOffset: o.startOffset,
53
- endOffset: o.endOffset,
54
- ...u ? {
55
- quickFix: {
56
- title: p.generateFigureId,
57
- edit: u.edit
58
- }
59
- } : {}
60
- });
61
- }
62
- f || c.push({
63
- code: "fig-missing-src",
64
- message: p.figureMissingSrc,
65
- severity: "error",
66
- startOffset: o.startOffset,
67
- endOffset: o.endOffset
68
- }), r && (h.has(r) && c.push({
69
- code: "fig-duplicate-id",
70
- message: p.figureDuplicateId(r),
71
- severity: "error",
72
- startOffset: o.startOffset,
73
- endOffset: o.endOffset
74
- }), h.add(r));
75
- }
76
- return c;
77
- }
78
- const fe = {
79
- key: 0,
80
- class: "aimd-editor-loading"
81
- }, w = "airalogy-aimd", be = /* @__PURE__ */ Q({
82
- __name: "AimdSourceEditor",
83
- props: {
84
- content: {},
85
- theme: {},
86
- minHeight: {},
87
- readonly: { type: Boolean },
88
- monacoOptions: {},
89
- resolvedMessages: {}
90
- },
91
- emits: ["content-change", "ready", "monaco-loaded"],
92
- setup(a, { expose: p, emit: c }) {
93
- const s = a, b = c, h = /^\s*(```|~~~)\s*assigner(?:\s+.*\bruntime\s*=\s*(?:"client"|'client'|client)\b.*)\s*$/, o = /^\s*(```|~~~)\s*assigner(?:\s+.*)?\s*$/, r = /^\s*(```|~~~)\s*quiz(?:\s+.*)?\s*$/, f = /^\s*(```|~~~)\s*connectors(?:\s+.*)?\s*$/, u = /^\s*(```|~~~)\s*((?:\w|[/#-])+)(?:\s+.*)?\s*$/, m = /^\s*(```|~~~)\s*$/, C = N(null);
94
- let t = null, l = null, x = null, y = !1;
95
- const v = N(!0);
96
- function F(e) {
97
- const n = s.resolvedMessages;
98
- e.languages.getLanguages().some((d) => d.id === "aimd") || (e.languages.register({
99
- id: "aimd",
100
- extensions: [".aimd"],
101
- aliases: ["AIMD", "aimd"],
102
- mimetypes: ["text/x-aimd"]
103
- }), e.languages.setLanguageConfiguration("aimd", {
104
- brackets: [
105
- ["{", "}"],
106
- ["[", "]"],
107
- ["(", ")"]
108
- ],
109
- autoClosingPairs: [
110
- { open: "{", close: "}" },
111
- { open: "[", close: "]" },
112
- { open: "(", close: ")" },
113
- { open: '"', close: '"' },
114
- { open: "'", close: "'" },
115
- { open: "`", close: "`" },
116
- { open: "{{", close: "}}" }
117
- ],
118
- surroundingPairs: [
119
- { open: "{", close: "}" },
120
- { open: "[", close: "]" },
121
- { open: "(", close: ")" },
122
- { open: '"', close: '"' },
123
- { open: "'", close: "'" },
124
- { open: "`", close: "`" }
125
- ]
126
- }), e.languages.setMonarchTokensProvider("aimd", {
127
- defaultToken: "",
128
- tokenPostfix: ".aimd",
129
- tokenizer: {
130
- root: [
131
- [/\{\{/, { token: "delimiter.bracket.aimd", next: "@aimdField" }],
132
- [/^#{1,6}\s.*$/, "keyword.md"],
133
- [r, { token: "string.code", next: "@embeddedCodeblock", nextEmbedded: "yaml" }],
134
- [f, { token: "string.code", next: "@embeddedCodeblock", nextEmbedded: "yaml" }],
135
- [h, { token: "string.code", next: "@embeddedCodeblock", nextEmbedded: "javascript" }],
136
- [o, { token: "string.code", next: "@embeddedCodeblock", nextEmbedded: "python" }],
137
- [u, { token: "string.code", next: "@embeddedCodeblock", nextEmbedded: "$2" }],
138
- [m, { token: "string.code", next: "@codeblock" }],
139
- [/`[^`]+`/, "string.code"],
140
- [/\*\*[^*]+\*\*/, "strong"],
141
- [/__[^_]+__/, "strong"],
142
- [/\*[^*]+\*/, "emphasis"],
143
- [/_[^_]+_/, "emphasis"],
144
- [/\[[^\]]+\]\([^)]+\)/, "string.link"],
145
- [/!\[[^\]]*\]\([^)]+\)/, "string.link"],
146
- [/^>.*$/, "comment.quote"],
147
- [/^\s*[-*+]\s/, "keyword.list"],
148
- [/^\s*\d+\.\s/, "keyword.list"],
149
- [/^[-*_]{3,}\s*$/, "keyword.hr"],
150
- [/<\/?[\w-][^>]*>/, "tag"]
151
- ],
152
- aimdField: [
153
- [/\}\}/, { token: "delimiter.bracket.aimd", next: "@pop" }],
154
- [/\b(var_table|var|step|check|task|ref_step|ref_var|ref_fig|cite)\b/, "keyword.aimd"],
155
- [/\|/, "delimiter.aimd"],
156
- [/:/, "delimiter"],
157
- [/\b(str|int|float|bool|list|dict|any)\b/, "type.aimd"],
158
- [/\b[A-Z][A-Za-z0-9_]*(?:\[[A-Za-z0-9_,\s]+\])?\b/, "type.aimd"],
159
- [/[[\]()]/, "delimiter.bracket"],
160
- [/=/, "delimiter"],
161
- [/"[^"]*"/, "string"],
162
- [/'[^']*'/, "string"],
163
- [/-?\d+\.?\d*/, "number"],
164
- [/\b(true|false|True|False|null|None)\b/, "constant"],
165
- [/\bsubvars\b/, "keyword"],
166
- [/,/, "delimiter"],
167
- [/[A-Za-z_]\w*/, "variable.aimd"],
168
- [/\s+/, ""]
169
- ],
170
- codeblock: [
171
- [/^```\s*$/, { token: "string.code", next: "@pop" }],
172
- [/^~~~\s*$/, { token: "string.code", next: "@pop" }],
173
- [/.*$/, "string.code"]
174
- ],
175
- embeddedCodeblock: [
176
- [/^```\s*$/, { token: "string.code", next: "@pop", nextEmbedded: "@pop" }],
177
- [/^~~~\s*$/, { token: "string.code", next: "@pop", nextEmbedded: "@pop" }],
178
- [/.*$/, ""]
179
- ]
180
- }
181
- }), e.languages.registerCompletionItemProvider("aimd", {
182
- provideCompletionItems: () => {
183
- const d = ["var", "var_table", "step", "check", "ref_step", "ref_var", "ref_fig", "cite"], k = {
184
- var: "var_id",
185
- var_table: "table_id",
186
- step: "step_id",
187
- check: "check_id",
188
- ref_step: "step_id",
189
- ref_var: "var_id",
190
- ref_fig: "fig_id",
191
- cite: "ref_id"
192
- }, E = d.map((_) => ({
193
- label: `{{${_}|}}`,
194
- kind: e.languages.CompletionItemKind.Snippet,
195
- insertText: `{{${_}|\${1:${k[_] ?? "id"}}}}`,
196
- insertTextRules: e.languages.CompletionItemInsertTextRule.InsertAsSnippet,
197
- documentation: n.completions.insertAimdField(_)
198
- }));
199
- return E.push({
200
- label: n.completions.quizBlockLabel,
201
- kind: e.languages.CompletionItemKind.Snippet,
202
- insertText: [
203
- "```quiz",
204
- "id: ${1:quiz_choice_1}",
205
- "type: choice",
206
- "mode: single",
207
- "stem: |",
208
- ` \${2:${n.defaults.questionStem}}`,
209
- "options:",
210
- " - key: A",
211
- ` text: ${n.defaults.optionText("A")}`,
212
- " - key: B",
213
- ` text: ${n.defaults.optionText("B")}`,
214
- "answer: A",
215
- "```"
216
- ].join(`
217
- `),
218
- insertTextRules: e.languages.CompletionItemInsertTextRule.InsertAsSnippet,
219
- documentation: n.completions.quizBlock
220
- }), { suggestions: E };
221
- }
222
- }), e.editor.defineTheme("aimd-light", {
223
- base: "vs",
224
- inherit: !0,
225
- rules: [
226
- { token: "delimiter.bracket.aimd", foreground: "2563eb" },
227
- { token: "keyword.aimd", foreground: "2563eb", fontStyle: "bold" },
228
- { token: "delimiter.aimd", foreground: "6b7280" },
229
- { token: "type.aimd", foreground: "7c3aed" },
230
- { token: "variable.aimd", foreground: "059669" },
231
- { token: "keyword.md", foreground: "1e40af" },
232
- { token: "string.code", foreground: "be185d" },
233
- { token: "strong", fontStyle: "bold" },
234
- { token: "emphasis", fontStyle: "italic" },
235
- { token: "string.link", foreground: "2563eb" },
236
- { token: "comment.quote", foreground: "6b7280", fontStyle: "italic" }
237
- ],
238
- colors: {}
239
- }), e.editor.defineTheme("aimd-dark", {
240
- base: "vs-dark",
241
- inherit: !0,
242
- rules: [
243
- { token: "delimiter.bracket.aimd", foreground: "60a5fa" },
244
- { token: "keyword.aimd", foreground: "60a5fa", fontStyle: "bold" },
245
- { token: "delimiter.aimd", foreground: "9ca3af" },
246
- { token: "type.aimd", foreground: "a78bfa" },
247
- { token: "variable.aimd", foreground: "34d399" },
248
- { token: "keyword.md", foreground: "93c5fd" },
249
- { token: "string.code", foreground: "f472b6" },
250
- { token: "strong", fontStyle: "bold" },
251
- { token: "emphasis", fontStyle: "italic" },
252
- { token: "string.link", foreground: "60a5fa" },
253
- { token: "comment.quote", foreground: "9ca3af", fontStyle: "italic" }
254
- ],
255
- colors: {}
256
- }));
257
- }
258
- function S() {
259
- if (!l || !t) return;
260
- const e = t.getModel();
261
- if (!e) return;
262
- const n = D(e.getValue(), s.resolvedMessages.diagnostics).map((i) => {
263
- const d = e.getPositionAt(i.startOffset), k = e.getPositionAt(i.endOffset);
264
- return {
265
- severity: i.severity === "error" ? l.MarkerSeverity.Error : l.MarkerSeverity.Warning,
266
- message: i.message,
267
- code: i.code,
268
- source: "AIMD",
269
- startLineNumber: d.lineNumber,
270
- startColumn: d.column,
271
- endLineNumber: k.lineNumber,
272
- endColumn: k.column
273
- };
274
- });
275
- l.editor.setModelMarkers(e, w, n);
276
- }
277
- function L(e, n, i, d) {
278
- return e <= d && n >= i;
279
- }
280
- function P(e) {
281
- x?.dispose(), x = e.languages.registerCodeActionProvider("aimd", {
282
- provideCodeActions(n, i, d) {
283
- if (s.readonly || n !== t?.getModel())
284
- return { actions: [], dispose() {
285
- } };
286
- const k = n.getOffsetAt({
287
- lineNumber: i.startLineNumber,
288
- column: i.startColumn
289
- }), E = n.getOffsetAt({
290
- lineNumber: i.endLineNumber,
291
- column: i.endColumn
292
- });
293
- return { actions: D(n.getValue(), s.resolvedMessages.diagnostics).filter((g) => g.quickFix && L(
294
- g.startOffset,
295
- g.endOffset,
296
- k,
297
- E
298
- )).map((g) => {
299
- const A = g.quickFix.edit, I = n.getPositionAt(A.startOffset), M = n.getPositionAt(A.endOffset);
300
- return {
301
- title: g.quickFix.title,
302
- kind: "quickfix",
303
- isPreferred: !0,
304
- diagnostics: d.markers.filter((W) => W.code === g.code),
305
- edit: {
306
- edits: [{
307
- resource: n.uri,
308
- textEdit: {
309
- range: {
310
- startLineNumber: I.lineNumber,
311
- startColumn: I.column,
312
- endLineNumber: M.lineNumber,
313
- endColumn: M.column
314
- },
315
- text: A.text
316
- },
317
- versionId: n.getVersionId()
318
- }]
319
- }
320
- };
321
- }), dispose() {
322
- } };
323
- }
324
- });
325
- }
326
- function q() {
327
- if (!l || !t) return;
328
- const e = t.getModel();
329
- e && l.editor.setModelMarkers(e, w, []);
330
- }
331
- function V(e) {
332
- if (!C.value || t) return;
333
- const n = /* @__PURE__ */ new Set(["value", "language", "model"]), i = Object.fromEntries(
334
- Object.entries(s.monacoOptions).filter(([d]) => !n.has(d))
335
- );
336
- t = e.editor.create(C.value, {
337
- value: s.content,
338
- language: "aimd",
339
- theme: s.theme,
340
- minimap: { enabled: !1 },
341
- fontSize: 14,
342
- lineNumbers: "on",
343
- wordWrap: "on",
344
- scrollBeyondLastLine: !1,
345
- automaticLayout: !0,
346
- tabSize: 2,
347
- padding: { top: 12 },
348
- readOnly: s.readonly,
349
- ...i
350
- }), P(e), t.onDidChangeModelContent(() => {
351
- S(), y || b("content-change", t.getValue());
352
- }), S(), b("ready", t), b("monaco-loaded", e, t);
353
- }
354
- Y(async () => {
355
- try {
356
- v.value = !0;
357
- const e = await import("monaco-editor");
358
- l = e, F(e), V(e);
359
- } finally {
360
- v.value = !1;
361
- }
362
- }), J(() => {
363
- q(), x?.dispose(), t?.dispose();
364
- }), O(() => s.content, (e) => {
365
- !t || e === t.getValue() || (y = !0, t.setValue(e), y = !1);
366
- }), O(() => s.theme, (e) => {
367
- l && l.editor.setTheme(e);
368
- }), O(() => s.readonly, (e) => {
369
- t?.updateOptions({ readOnly: e });
370
- });
371
- function B() {
372
- return t;
373
- }
374
- function R() {
375
- return l;
376
- }
377
- function z(e) {
378
- t && (y = !0, t.setValue(e), y = !1);
379
- }
380
- function G() {
381
- return t?.getSelection();
382
- }
383
- function j(e, n) {
384
- t?.executeEdits(e, n);
385
- }
386
- function K() {
387
- t?.focus();
388
- }
389
- function Z() {
390
- return t?.getModel();
391
- }
392
- function H() {
393
- return t?.getPosition();
394
- }
395
- function U() {
396
- return t?.getValue();
397
- }
398
- return p({
399
- getEditor: B,
400
- getMonaco: R,
401
- setValue: z,
402
- getSelection: G,
403
- executeEdits: j,
404
- focus: K,
405
- getModel: Z,
406
- getPosition: H,
407
- getValue: U,
408
- loading: v
409
- }), (e, n) => (T(), $("div", {
410
- class: "aimd-editor-source-mode",
411
- style: X({ minHeight: a.minHeight + "px" })
412
- }, [
413
- v.value ? (T(), $("div", fe, ee(a.resolvedMessages.common.loadingEditor), 1)) : te("", !0),
414
- ne("div", {
415
- ref_key: "editorContainer",
416
- ref: C,
417
- class: "aimd-editor-container"
418
- }, null, 512)
419
- ], 4));
420
- }
421
- });
422
- export {
423
- be as _
424
- };