@mdzip/editor 2.4.2 → 2.6.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.
Files changed (77) hide show
  1. package/AGENTS.md +8 -0
  2. package/README.md +322 -5
  3. package/dist/diff-rendered.d.ts +54 -0
  4. package/dist/diff-rendered.d.ts.map +1 -0
  5. package/dist/diff-rendered.js +462 -0
  6. package/dist/diff-rendered.js.map +1 -0
  7. package/dist/diff-view-css.d.ts +2 -0
  8. package/dist/diff-view-css.d.ts.map +1 -1
  9. package/dist/diff-view-css.js +69 -6
  10. package/dist/diff-view-css.js.map +1 -1
  11. package/dist/diff-view.d.ts +112 -9
  12. package/dist/diff-view.d.ts.map +1 -1
  13. package/dist/diff-view.js +435 -49
  14. package/dist/diff-view.js.map +1 -1
  15. package/dist/front-matter-extension.d.ts.map +1 -1
  16. package/dist/front-matter-extension.js +2 -8
  17. package/dist/front-matter-extension.js.map +1 -1
  18. package/dist/heading-outline.d.ts +66 -0
  19. package/dist/heading-outline.d.ts.map +1 -0
  20. package/dist/heading-outline.js +208 -0
  21. package/dist/heading-outline.js.map +1 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +4 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/json-validation.d.ts +97 -0
  27. package/dist/json-validation.d.ts.map +1 -0
  28. package/dist/json-validation.js +496 -0
  29. package/dist/json-validation.js.map +1 -0
  30. package/dist/library-info.d.ts +7 -2
  31. package/dist/library-info.d.ts.map +1 -1
  32. package/dist/library-info.js +8 -2
  33. package/dist/library-info.js.map +1 -1
  34. package/dist/manifest-form.d.ts +46 -0
  35. package/dist/manifest-form.d.ts.map +1 -0
  36. package/dist/manifest-form.js +327 -0
  37. package/dist/manifest-form.js.map +1 -0
  38. package/dist/merge-conflicts.d.ts +56 -0
  39. package/dist/merge-conflicts.d.ts.map +1 -0
  40. package/dist/merge-conflicts.js +130 -0
  41. package/dist/merge-conflicts.js.map +1 -0
  42. package/dist/merge-regions.d.ts +92 -0
  43. package/dist/merge-regions.d.ts.map +1 -0
  44. package/dist/merge-regions.js +416 -0
  45. package/dist/merge-regions.js.map +1 -0
  46. package/dist/merge-view.d.ts +267 -0
  47. package/dist/merge-view.d.ts.map +1 -0
  48. package/dist/merge-view.js +2039 -0
  49. package/dist/merge-view.js.map +1 -0
  50. package/dist/preview-find.d.ts +30 -0
  51. package/dist/preview-find.d.ts.map +1 -0
  52. package/dist/preview-find.js +172 -0
  53. package/dist/preview-find.js.map +1 -0
  54. package/dist/rendering.d.ts +17 -52
  55. package/dist/rendering.d.ts.map +1 -1
  56. package/dist/rendering.js +21 -324
  57. package/dist/rendering.js.map +1 -1
  58. package/dist/scroll-anchors.d.ts +33 -0
  59. package/dist/scroll-anchors.d.ts.map +1 -0
  60. package/dist/scroll-anchors.js +80 -0
  61. package/dist/scroll-anchors.js.map +1 -0
  62. package/dist/view-css.d.ts.map +1 -1
  63. package/dist/view-css.js +679 -0
  64. package/dist/view-css.js.map +1 -1
  65. package/dist/view.d.ts +412 -9
  66. package/dist/view.d.ts.map +1 -1
  67. package/dist/view.js +2276 -427
  68. package/dist/view.js.map +1 -1
  69. package/dist/workspace-view.d.ts +2 -0
  70. package/dist/workspace-view.d.ts.map +1 -1
  71. package/dist/workspace-view.js +25 -2
  72. package/dist/workspace-view.js.map +1 -1
  73. package/dist/workspace.d.ts +29 -0
  74. package/dist/workspace.d.ts.map +1 -1
  75. package/dist/workspace.js +124 -9
  76. package/dist/workspace.js.map +1 -1
  77. package/package.json +93 -83
package/dist/diff-view.js CHANGED
@@ -1,12 +1,18 @@
1
1
  import { markdown } from '@codemirror/lang-markdown';
2
- import { MergeView } from '@codemirror/merge';
3
- import { EditorState } from '@codemirror/state';
4
- import { EditorView, lineNumbers } from '@codemirror/view';
2
+ import { MergeView, getChunks } from '@codemirror/merge';
3
+ import { Annotation, EditorState } from '@codemirror/state';
4
+ import { search, searchKeymap } from '@codemirror/search';
5
+ import { EditorView, keymap, lineNumbers } from '@codemirror/view';
5
6
  import { MdzArchiveCore } from '@mdzip/core-js';
6
- import { ChevronDown, ChevronUp, Eye, PanelLeft, RefreshCw } from 'lucide';
7
+ import { ChevronDown, ChevronUp, Eye, Hash, ListFilter, PanelLeft, RefreshCw, Save, SquarePen } from 'lucide';
7
8
  import { createArchiveInventoryFromArchive, diffArchiveInventories } from './diff.js';
8
- import { injectDiffViewStyles } from './diff-view-css.js';
9
+ import { markBlockChanges, renderSideFragment, syncScroll } from './diff-rendered.js';
10
+ import { injectDiffViewStyles, injectPreviewStyles } from './diff-view-css.js';
11
+ import { sha256Hex } from './sha256.js';
12
+ /** Marks a change the host pushed in with updateMarkdown(), so it isn't reported back as an edit. */
13
+ const hostUpdate = Annotation.define();
9
14
  const EMPTY_INVENTORY = { entries: [], entryPoint: '', manifest: null };
15
+ const DEFAULT_MARKDOWN_PATH = 'document.md';
10
16
  export class MdzipDiffView {
11
17
  constructor(container, options) {
12
18
  this.generation = 0;
@@ -18,35 +24,50 @@ export class MdzipDiffView {
18
24
  this.mergeView = null;
19
25
  this.editorViews = [];
20
26
  this.objectUrls = [];
27
+ this.renderAbort = null;
28
+ /** The change in the selected entry that previous/next last moved to; -1 before the first. */
29
+ this.changeCursor = -1;
30
+ /** Rendered view: the changed blocks, in reading order, with the pane each scrolls. */
31
+ this.renderedChanges = [];
32
+ this.stopScrollSync = null;
21
33
  this.openingOptions = null;
22
34
  this.openingPromise = null;
23
35
  this.pendingToolbarAction = null;
24
36
  this.options = options;
25
37
  this.showUnchanged = options.showUnchanged ?? true;
26
- this.navigationVisible = options.navigationVisible ?? true;
27
- this.controls = resolveControls(options.controls);
38
+ // A plain-Markdown comparison has a single entry, so the list adds nothing.
39
+ this.navigationVisible = options.navigationVisible ?? !isMarkdownOnly(options);
40
+ this.rendered = options.rendered ?? false;
41
+ this.colorScheme = options.colorScheme ?? 'light';
42
+ this.controls = resolveControls(options.controls, isMarkdownOnly(options));
28
43
  this.toolbarActions = options.toolbarActions ?? [];
29
44
  injectDiffViewStyles(container.ownerDocument);
30
45
  container.replaceChildren();
31
46
  this.root = container.ownerDocument.createElement('div');
32
- this.root.className = 'mdzip-diff-root';
33
- this.root.innerHTML = `
34
- <div class="mdzip-diff-toolbar" role="toolbar" aria-label="Comparison controls">
35
- <button class="mdzip-diff-toolbar-button" type="button" data-ref="navigation" title="Toggle navigation" aria-label="Toggle navigation"></button>
36
- <button class="mdzip-diff-toolbar-button" type="button" data-ref="prev-change" title="Previous change" aria-label="Previous change"></button>
37
- <button class="mdzip-diff-toolbar-button" type="button" data-ref="next-change" title="Next change" aria-label="Next change"></button>
38
- <button class="mdzip-diff-toolbar-button" type="button" data-ref="show-unchanged" title="Show unchanged" aria-label="Show unchanged"></button>
39
- <div class="mdzip-diff-toolbar-actions" data-ref="actions"></div>
40
- </div>
41
- <div class="mdzip-diff-workspace">
42
- <aside class="mdzip-diff-nav">
43
- <div class="mdzip-diff-summary"></div>
44
- <div class="mdzip-diff-list" role="tree" aria-label="Archive comparison files"></div>
45
- </aside>
46
- <main class="mdzip-diff-content">
47
- <div class="mdzip-diff-heading"></div>
48
- <div class="mdzip-diff-body"><div class="mdzip-diff-message">Loading comparison...</div></div>
49
- </main>
47
+ this.density = options.toolbarDensity ?? 'comfortable';
48
+ this.applyRootClass();
49
+ this.root.innerHTML = `
50
+ <div class="mdzip-diff-toolbar" role="toolbar" aria-label="Comparison controls">
51
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="navigation" title="Toggle navigation" aria-label="Toggle navigation"></button>
52
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="prev-change" title="Previous change" aria-label="Previous change"></button>
53
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="next-change" title="Next change" aria-label="Next change"></button>
54
+ <span class="mdzip-diff-change-count" data-ref="change-count" aria-live="polite" hidden></span>
55
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="show-unchanged" title="Show unchanged files" aria-label="Show unchanged files"></button>
56
+ <div class="mdzip-diff-toolbar-group" data-ref="view-mode" role="group" aria-label="Markdown view">
57
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="source" title="Show Markdown source" aria-label="Show Markdown source"></button>
58
+ <button class="mdzip-diff-toolbar-button" type="button" data-ref="rendered" title="Show rendered Markdown" aria-label="Show rendered Markdown"></button>
59
+ </div>
60
+ <div class="mdzip-diff-toolbar-actions" data-ref="actions"></div>
61
+ </div>
62
+ <div class="mdzip-diff-workspace">
63
+ <aside class="mdzip-diff-nav">
64
+ <div class="mdzip-diff-summary"></div>
65
+ <div class="mdzip-diff-list" role="tree" aria-label="Archive comparison files"></div>
66
+ </aside>
67
+ <main class="mdzip-diff-content">
68
+ <div class="mdzip-diff-heading"></div>
69
+ <div class="mdzip-diff-body"><div class="mdzip-diff-message">Loading comparison...</div></div>
70
+ </main>
50
71
  </div>`;
51
72
  container.appendChild(this.root);
52
73
  this.workspace = this.root.querySelector('.mdzip-diff-workspace');
@@ -54,7 +75,11 @@ export class MdzipDiffView {
54
75
  this.navButton = this.root.querySelector('[data-ref="navigation"]');
55
76
  this.prevChangeButton = this.root.querySelector('[data-ref="prev-change"]');
56
77
  this.nextChangeButton = this.root.querySelector('[data-ref="next-change"]');
78
+ this.changeCountLabel = this.root.querySelector('[data-ref="change-count"]');
57
79
  this.showUnchangedButton = this.root.querySelector('[data-ref="show-unchanged"]');
80
+ this.viewModeGroup = this.root.querySelector('[data-ref="view-mode"]');
81
+ this.sourceButton = this.root.querySelector('[data-ref="source"]');
82
+ this.renderedButton = this.root.querySelector('[data-ref="rendered"]');
58
83
  this.actionHost = this.root.querySelector('[data-ref="actions"]');
59
84
  this.nav = this.root.querySelector('.mdzip-diff-nav');
60
85
  this.summary = this.root.querySelector('.mdzip-diff-summary');
@@ -67,8 +92,13 @@ export class MdzipDiffView {
67
92
  this.prevChangeButton.addEventListener('click', () => { void this.openPreviousChange(); });
68
93
  this.nextChangeButton.innerHTML = iconHtml(ChevronDown);
69
94
  this.nextChangeButton.addEventListener('click', () => { void this.openNextChange(); });
70
- this.showUnchangedButton.innerHTML = iconHtml(Eye);
95
+ this.showUnchangedButton.innerHTML = iconHtml(ListFilter);
71
96
  this.showUnchangedButton.addEventListener('click', () => this.setShowUnchanged(!this.showUnchanged));
97
+ // Same icons as the editor's view modes: the pen for editable source (# when
98
+ // it's read-only), the eye for rendered. Set in renderToolbar.
99
+ this.sourceButton.addEventListener('click', () => { void this.setRendered(false); });
100
+ this.renderedButton.innerHTML = iconHtml(Eye);
101
+ this.renderedButton.addEventListener('click', () => { void this.setRendered(true); });
72
102
  this.renderToolbar();
73
103
  void this.open(options);
74
104
  }
@@ -93,8 +123,12 @@ export class MdzipDiffView {
93
123
  this.options = options;
94
124
  this.showUnchanged = options.showUnchanged ?? this.showUnchanged;
95
125
  this.navigationVisible = options.navigationVisible ?? this.navigationVisible;
126
+ this.rendered = options.rendered ?? this.rendered;
127
+ this.colorScheme = options.colorScheme ?? this.colorScheme;
128
+ this.density = options.toolbarDensity ?? this.density;
129
+ this.applyRootClass();
96
130
  if (options.controls)
97
- this.controls = resolveControls(options.controls);
131
+ this.controls = resolveControls(options.controls, isMarkdownOnly(options));
98
132
  this.toolbarActions = options.toolbarActions ?? this.toolbarActions;
99
133
  this.renderToolbar();
100
134
  this.selectedPath = null;
@@ -107,6 +141,7 @@ export class MdzipDiffView {
107
141
  ]);
108
142
  if (generation !== this.generation)
109
143
  return;
144
+ assignMarkdownEntries(before, after);
110
145
  this.before = before;
111
146
  this.after = after;
112
147
  this.diff = diffArchiveInventories(before.inventory, after.inventory);
@@ -135,21 +170,123 @@ export class MdzipDiffView {
135
170
  this.renderNavigation();
136
171
  }
137
172
  /**
138
- * Selects the previous entry whose status is not `unchanged`. Resolves
139
- * `false` (without changing selection) when already at the first change.
173
+ * Shows Markdown entries rendered (both sides as the preview shows them,
174
+ * with differing blocks marked) or as source. Re-renders the selected
175
+ * entry when it's Markdown.
176
+ */
177
+ async setRendered(rendered) {
178
+ if (this.rendered === rendered)
179
+ return;
180
+ this.rendered = rendered;
181
+ this.updateBuiltInControls();
182
+ this.options.onRenderedChanged?.(rendered);
183
+ if (this.selectedPath && this.selectedEntry()?.kind === 'markdown') {
184
+ await this.renderSelection(this.selectedPath);
185
+ }
186
+ }
187
+ /**
188
+ * Replaces a plain-Markdown side's text, for a change made somewhere else
189
+ * (another editor, undo, revert). The source view updates in place, keeping
190
+ * the cursor and scroll position, and doesn't call `onMarkdownChange`; the
191
+ * rendered view re-renders. A side that had no text (missing) needs
192
+ * `open()` instead.
193
+ */
194
+ async updateMarkdown(which, text) {
195
+ const side = which === 'before' ? this.before : this.after;
196
+ if (!side?.markdown || side.markdown.text === text)
197
+ return;
198
+ side.markdown = { ...side.markdown, text, bytes: new TextEncoder().encode(text) };
199
+ const entry = this.selectedEntry();
200
+ if (!entry || !this.selectedPath || entry.path !== side.inventory.entryPoint)
201
+ return;
202
+ if (this.mergeView) {
203
+ const editor = which === 'before' ? this.mergeView.a : this.mergeView.b;
204
+ const current = editor.state.doc.toString();
205
+ let start = 0;
206
+ while (start < current.length && start < text.length && current[start] === text[start])
207
+ start += 1;
208
+ let endCurrent = current.length;
209
+ let endText = text.length;
210
+ while (endCurrent > start && endText > start && current[endCurrent - 1] === text[endText - 1]) {
211
+ endCurrent -= 1;
212
+ endText -= 1;
213
+ }
214
+ editor.dispatch({
215
+ changes: { from: start, to: endCurrent, insert: text.slice(start, endText) },
216
+ annotations: hostUpdate.of(true)
217
+ });
218
+ return;
219
+ }
220
+ await this.renderSelection(this.selectedPath);
221
+ }
222
+ get isRendered() {
223
+ return this.rendered;
224
+ }
225
+ selectedEntry() {
226
+ return this.diff?.entries.find((entry) => entry.path === this.selectedPath);
227
+ }
228
+ /**
229
+ * Moves to the previous change: within the selected entry first (a changed
230
+ * chunk of text, or a changed block in the rendered view), then to the
231
+ * last change of the previous changed entry. Resolves `false` when already
232
+ * at the first change.
140
233
  */
141
234
  async openPreviousChange() {
235
+ if (this.moveWithinEntry(-1))
236
+ return true;
142
237
  const target = this.adjacentChange(-1);
143
- return target ? this.openPath(target.path) : false;
238
+ if (!target)
239
+ return false;
240
+ await this.openPath(target.path);
241
+ const count = this.entryChangeCount();
242
+ if (count > 0)
243
+ this.goToEntryChange(count - 1);
244
+ return true;
144
245
  }
145
246
  /**
146
- * Selects the next entry whose status is not `unchanged`. Resolves `false`
147
- * (without changing selection) when already at the last change.
247
+ * Moves to the next change: within the selected entry first, then to the
248
+ * next changed entry (which opens at its first change). Resolves `false`
249
+ * when already at the last change.
148
250
  */
149
251
  async openNextChange() {
252
+ if (this.moveWithinEntry(1))
253
+ return true;
150
254
  const target = this.adjacentChange(1);
151
255
  return target ? this.openPath(target.path) : false;
152
256
  }
257
+ /** How many changes the selected entry shows (text chunks, or changed rendered blocks). */
258
+ entryChangeCount() {
259
+ if (this.mergeView)
260
+ return getChunks(this.mergeView.b.state)?.chunks.length ?? 0;
261
+ return this.renderedChanges.length;
262
+ }
263
+ moveWithinEntry(direction) {
264
+ const next = this.changeCursor + direction;
265
+ if (next < 0 || next >= this.entryChangeCount())
266
+ return false;
267
+ this.goToEntryChange(next);
268
+ return true;
269
+ }
270
+ /** Scrolls the selected entry to one of its changes, leaving a little context above it. */
271
+ goToEntryChange(index) {
272
+ if (this.mergeView) {
273
+ const chunk = getChunks(this.mergeView.b.state)?.chunks[index];
274
+ if (!chunk)
275
+ return;
276
+ this.mergeView.b.dispatch({
277
+ selection: { anchor: chunk.fromB },
278
+ effects: EditorView.scrollIntoView(chunk.fromB, { y: 'start', yMargin: 48 })
279
+ });
280
+ }
281
+ else {
282
+ const target = this.renderedChanges[index];
283
+ if (!target)
284
+ return;
285
+ target.side.scrollTop = Math.max(0, offsetWithin(target.side, target.block) - 48);
286
+ }
287
+ this.changeCursor = index;
288
+ this.updateBuiltInControls();
289
+ }
153
290
  adjacentChange(direction) {
154
291
  const entries = this.diff?.entries ?? [];
155
292
  const changed = entries.filter((entry) => entry.status !== 'unchanged');
@@ -190,6 +327,16 @@ export class MdzipDiffView {
190
327
  this.prevChangeButton.hidden = !this.controls.changeTraversal;
191
328
  this.nextChangeButton.hidden = !this.controls.changeTraversal;
192
329
  this.showUnchangedButton.hidden = !this.controls.showUnchanged;
330
+ this.viewModeGroup.hidden = !this.controls.rendered;
331
+ const editable = [this.options.before, this.options.after]
332
+ .some((side) => side?.markdown !== undefined && side.editable === true);
333
+ const sourceLabel = editable ? 'Edit Markdown source' : 'Show Markdown source';
334
+ if (this.sourceButton.dataset.icon !== (editable ? 'edit' : 'source')) {
335
+ this.sourceButton.dataset.icon = editable ? 'edit' : 'source';
336
+ this.sourceButton.innerHTML = iconHtml(editable ? SquarePen : Hash);
337
+ }
338
+ this.sourceButton.title = sourceLabel;
339
+ this.sourceButton.setAttribute('aria-label', sourceLabel);
193
340
  this.setNavigationVisible(this.navigationVisible);
194
341
  this.updateBuiltInControls();
195
342
  this.actionHost.replaceChildren();
@@ -206,6 +353,8 @@ export class MdzipDiffView {
206
353
  button.disabled = action.disabled === true || this.pendingToolbarAction === action.id;
207
354
  if (action.icon === 'refresh')
208
355
  button.innerHTML = iconHtml(RefreshCw);
356
+ else if (action.icon === 'save')
357
+ button.innerHTML = iconHtml(Save);
209
358
  else
210
359
  button.textContent = action.label;
211
360
  button.addEventListener('click', () => void this.runToolbarAction(action));
@@ -214,11 +363,31 @@ export class MdzipDiffView {
214
363
  this.toolbar.hidden = false;
215
364
  }
216
365
  /** Syncs the pressed/disabled state of the built-in change + filter controls. */
366
+ applyRootClass() {
367
+ this.root.className = `mdzip-diff-root mdzip-diff-density-${this.density} mdzip-diff-scheme-${this.colorScheme}`;
368
+ }
217
369
  updateBuiltInControls() {
218
- this.prevChangeButton.disabled = !this.adjacentChange(-1);
219
- this.nextChangeButton.disabled = !this.adjacentChange(1);
370
+ const count = this.entryChangeCount();
371
+ this.prevChangeButton.disabled = this.changeCursor <= 0 && !this.adjacentChange(-1);
372
+ this.nextChangeButton.disabled = this.changeCursor >= count - 1 && !this.adjacentChange(1);
373
+ // Where you are among the selected entry's changes, so disabled arrows read as
374
+ // "nothing further" rather than broken.
375
+ const selected = this.selectedEntry();
376
+ this.changeCountLabel.hidden = !this.controls.changeTraversal || !selected;
377
+ this.changeCountLabel.textContent = count === 0
378
+ ? 'No changes'
379
+ : `${Math.max(1, this.changeCursor + 1)} of ${count}`;
220
380
  this.showUnchangedButton.setAttribute('aria-pressed', String(this.showUnchanged));
221
381
  this.showUnchangedButton.classList.toggle('active', this.showUnchanged);
382
+ this.sourceButton.setAttribute('aria-pressed', String(!this.rendered));
383
+ this.sourceButton.classList.toggle('active', !this.rendered);
384
+ this.renderedButton.setAttribute('aria-pressed', String(this.rendered));
385
+ this.renderedButton.classList.toggle('active', this.rendered);
386
+ // Only Markdown has a rendered form; the choice is kept for the next Markdown entry.
387
+ const entry = this.selectedEntry();
388
+ const notMarkdown = Boolean(entry) && entry?.kind !== 'markdown';
389
+ this.sourceButton.disabled = notMarkdown;
390
+ this.renderedButton.disabled = notMarkdown;
222
391
  }
223
392
  async runToolbarAction(action) {
224
393
  if (action.disabled || this.pendingToolbarAction)
@@ -237,6 +406,17 @@ export class MdzipDiffView {
237
406
  }
238
407
  }
239
408
  async openSide(input) {
409
+ if (input.markdown !== undefined) {
410
+ const bytes = new TextEncoder().encode(input.markdown);
411
+ return {
412
+ input,
413
+ archive: null,
414
+ // The entry is added by assignMarkdownEntries once both sides are open.
415
+ inventory: EMPTY_INVENTORY,
416
+ state: 'ready',
417
+ markdown: { text: input.markdown, bytes, hash: await sha256Hex(bytes) }
418
+ };
419
+ }
240
420
  if (!input.bytes)
241
421
  return { input, archive: null, inventory: EMPTY_INVENTORY, state: 'missing' };
242
422
  if (input.bytes.length === 0)
@@ -337,12 +517,20 @@ export class MdzipDiffView {
337
517
  const afterText = decodeText(afterBytes);
338
518
  if ((beforeBytes === null || beforeText !== null)
339
519
  && (afterBytes === null || afterText !== null)) {
340
- this.renderText(beforeText, afterText, entry);
520
+ if (this.rendered && entry.kind === 'markdown') {
521
+ await this.renderRendered(beforeText, afterText, entry, generation);
522
+ if (generation !== this.selectionGeneration)
523
+ return;
524
+ }
525
+ else {
526
+ this.renderText(beforeText, afterText, entry);
527
+ }
341
528
  }
342
529
  else {
343
530
  this.renderBinary(beforeBytes, afterBytes, entry);
344
531
  }
345
532
  }
533
+ this.updateBuiltInControls();
346
534
  this.options.onSelectionChanged?.({ path, entry });
347
535
  }
348
536
  catch (cause) {
@@ -355,27 +543,176 @@ export class MdzipDiffView {
355
543
  }
356
544
  renderText(before, after, entry) {
357
545
  this.body.replaceChildren();
358
- const extensions = [
359
- lineNumbers(),
360
- EditorState.readOnly.of(true),
361
- EditorView.editable.of(false),
362
- EditorView.lineWrapping
363
- ];
546
+ // Ctrl+F / Cmd+F searches the side that has focus, as in the editor's source view.
547
+ // Only the lines near the scroll position are in the page, so the browser's own
548
+ // find can't see the rest; CodeMirror's search covers the whole text.
549
+ const base = [lineNumbers(), EditorView.lineWrapping, search({ top: true }), keymap.of(searchKeymap)];
364
550
  if (entry.kind === 'markdown')
365
- extensions.push(markdown());
551
+ base.push(markdown());
552
+ const extensionsFor = (side) => {
553
+ if (side && this.isEditable(side, entry)) {
554
+ return [...base, EditorView.updateListener.of((update) => {
555
+ if (!update.docChanged)
556
+ return;
557
+ const fromHost = update.transactions.some((transaction) => transaction.annotation(hostUpdate));
558
+ if (!fromHost)
559
+ this.markdownEdited(side, update.state.doc.toString());
560
+ })];
561
+ }
562
+ return [...base, EditorState.readOnly.of(true), EditorView.editable.of(false)];
563
+ };
564
+ const beforeExtensions = extensionsFor(this.before);
565
+ const afterExtensions = extensionsFor(this.after);
366
566
  if (before === null || after === null) {
367
- this.body.append(this.createPair(this.textSide(before, extensions), this.textSide(after, extensions)));
567
+ this.body.append(this.createPair(this.textSide(before, beforeExtensions), this.textSide(after, afterExtensions)));
368
568
  return;
369
569
  }
370
570
  this.mergeView = new MergeView({
371
- a: { doc: before, extensions },
372
- b: { doc: after, extensions },
571
+ a: { doc: before, extensions: beforeExtensions },
572
+ b: { doc: after, extensions: afterExtensions },
373
573
  parent: this.body,
374
574
  root: this.root.ownerDocument,
375
575
  highlightChanges: true,
376
576
  gutter: true,
377
577
  diffConfig: { scanLimit: 2000, timeout: 100 }
378
578
  });
579
+ // Open at the first change, as the rendered view does.
580
+ if (this.entryChangeCount() > 0)
581
+ this.goToEntryChange(0);
582
+ }
583
+ /** An editable plain-Markdown side, showing its one document. */
584
+ isEditable(side, entry) {
585
+ return Boolean(side.markdown && side.input.editable && entry.path === side.inventory.entryPoint);
586
+ }
587
+ /**
588
+ * Keeps the side's text current, so the rendered view and a re-selection
589
+ * show the edits, and tells the host.
590
+ */
591
+ markdownEdited(side, text) {
592
+ if (!side.markdown)
593
+ return;
594
+ side.markdown = { ...side.markdown, text, bytes: new TextEncoder().encode(text) };
595
+ side.input.onMarkdownChange?.(text);
596
+ }
597
+ async renderRendered(before, after, entry, generation) {
598
+ if (!this.before || !this.after)
599
+ return;
600
+ const doc = this.root.ownerDocument;
601
+ injectPreviewStyles(doc);
602
+ const abort = new AbortController();
603
+ this.renderAbort = abort;
604
+ const [beforeFragment, afterFragment] = await Promise.all([
605
+ renderSideFragment(doc, this.renderedSource(this.before, before, entry.before?.path), abort.signal),
606
+ renderSideFragment(doc, this.renderedSource(this.after, after, entry.after?.path), abort.signal)
607
+ ]);
608
+ if (generation !== this.selectionGeneration)
609
+ return;
610
+ const beforePane = this.renderedPane(beforeFragment);
611
+ const afterPane = this.renderedPane(afterFragment);
612
+ const pair = this.createPair(beforePane.side, afterPane.side);
613
+ pair.classList.add('mdzip-diff-rendered-pair');
614
+ this.body.replaceChildren(pair);
615
+ if (beforePane.content && afterPane.content) {
616
+ const matched = markBlockChanges(beforePane.content, afterPane.content);
617
+ this.stopScrollSync = syncScroll(beforePane.side, afterPane.side, matched);
618
+ // The changes in reading order: what the new version added or edited,
619
+ // plus what the old one lost outright (an edit already shows on the new side).
620
+ // Changed blocks are top-level blocks, or items inside an edited list or quote.
621
+ const blocks = (pane, selector) => Array.from(pane.content?.querySelectorAll(selector) ?? [])
622
+ .map((block) => ({ side: pane.side, block, offset: offsetWithin(pane.side, block) }));
623
+ this.renderedChanges = [
624
+ ...blocks(afterPane, '.mdzip-diff-block-added'),
625
+ ...blocks(beforePane, '.mdzip-diff-block-removed:not(.mdzip-diff-block-modified)')
626
+ ].sort((a, b) => a.offset - b.offset).map(({ side, block }) => ({ side, block }));
627
+ // Open at the first change, not the top; the other side follows.
628
+ if (this.renderedChanges.length > 0)
629
+ this.goToEntryChange(0);
630
+ }
631
+ }
632
+ renderedSource(side, markdown, path) {
633
+ const createUrl = (bytes, mime) => {
634
+ const url = URL.createObjectURL(new Blob([bytes], { type: mime }));
635
+ this.objectUrls.push(url);
636
+ return url;
637
+ };
638
+ if (side.markdown) {
639
+ // Images live next to the .md file, so the host reads them. Hashes are
640
+ // taken as they're read, so a changed image marks its block.
641
+ const hashes = new Map();
642
+ const readResource = side.input.readResource;
643
+ return {
644
+ markdown,
645
+ path,
646
+ manifest: null,
647
+ colorScheme: this.colorScheme,
648
+ sourceFormat: 'markdown',
649
+ readBytes: async (linkedPath) => {
650
+ const bytes = readResource ? await readResource(linkedPath) : null;
651
+ if (bytes)
652
+ hashes.set(linkedPath, await sha256Hex(bytes));
653
+ return bytes;
654
+ },
655
+ hashOf: (linkedPath) => hashes.get(linkedPath),
656
+ createUrl
657
+ };
658
+ }
659
+ return {
660
+ markdown,
661
+ path,
662
+ manifest: side.inventory.manifest,
663
+ colorScheme: this.colorScheme,
664
+ readBytes: async (entryPath) => {
665
+ if (!side.archive || !side.inventory.entries.some((item) => item.path === entryPath))
666
+ return null;
667
+ return side.archive.readBytes(entryPath);
668
+ },
669
+ hashOf: (entryPath) => side.inventory.entries.find((item) => item.path === entryPath)?.hash,
670
+ createUrl
671
+ };
672
+ }
673
+ /**
674
+ * One side of the rendered comparison, inside the workspace preview's own
675
+ * `.mdzip-root .preview-content` scope so it's styled like the preview.
676
+ */
677
+ renderedPane(fragment) {
678
+ const doc = this.root.ownerDocument;
679
+ const side = doc.createElement('div');
680
+ side.className = 'mdzip-diff-side mdzip-diff-rendered-side';
681
+ if (!fragment) {
682
+ side.classList.add('mdzip-diff-missing');
683
+ side.textContent = 'File does not exist';
684
+ return { side, content: null };
685
+ }
686
+ const scope = doc.createElement('div');
687
+ scope.className = `mdzip-root mdzip-diff-preview-scope${this.colorScheme === 'dark' ? ' mdzip-theme-dark' : ''}`;
688
+ const content = doc.createElement('article');
689
+ content.className = 'preview-content mdzip-diff-preview';
690
+ content.append(fragment);
691
+ scope.append(content);
692
+ side.append(scope);
693
+ side.addEventListener('click', (event) => this.handleRenderedClick(event, side));
694
+ return { side, content };
695
+ }
696
+ // Links in the rendered comparison don't navigate: the page is a
697
+ // comparison, not a browser. A `#fragment` link scrolls its own side.
698
+ handleRenderedClick(event, side) {
699
+ const link = event.target?.closest?.('a[href]');
700
+ if (!link)
701
+ return;
702
+ event.preventDefault();
703
+ const href = link.getAttribute('href') ?? '';
704
+ if (!href.startsWith('#'))
705
+ return;
706
+ let id = href.slice(1);
707
+ try {
708
+ id = decodeURIComponent(id);
709
+ }
710
+ catch {
711
+ // Use the raw fragment.
712
+ }
713
+ const target = Array.from(side.querySelectorAll('[id]'))
714
+ .find((element) => element.id === id || element.id === `user-content-${id}`);
715
+ target?.scrollIntoView({ block: 'start' });
379
716
  }
380
717
  textSide(text, extensions) {
381
718
  const side = this.root.ownerDocument.createElement('div');
@@ -449,6 +786,12 @@ export class MdzipDiffView {
449
786
  this.body.innerHTML = `<div class="mdzip-diff-message${errors.length ? ' mdzip-diff-error' : ''}">${escapeHtml(errors.join('\n') || 'No archive entries to compare.')}</div>`;
450
787
  }
451
788
  disposeSelection() {
789
+ this.changeCursor = -1;
790
+ this.renderedChanges = [];
791
+ this.renderAbort?.abort();
792
+ this.renderAbort = null;
793
+ this.stopScrollSync?.();
794
+ this.stopScrollSync = null;
452
795
  this.mergeView?.destroy();
453
796
  this.mergeView = null;
454
797
  for (const editor of this.editorViews)
@@ -476,13 +819,18 @@ export class MdzipDiffView {
476
819
  target.focus();
477
820
  }
478
821
  }
479
- function resolveControls(controls) {
822
+ function resolveControls(controls, markdownOnly) {
480
823
  return {
481
- navigation: controls?.navigation ?? true,
824
+ navigation: controls?.navigation ?? !markdownOnly,
482
825
  changeTraversal: controls?.changeTraversal ?? true,
483
- showUnchanged: controls?.showUnchanged ?? true
826
+ showUnchanged: controls?.showUnchanged ?? false,
827
+ rendered: controls?.rendered ?? true
484
828
  };
485
829
  }
830
+ /** An element's offset from the top of a scrolling pane's content. */
831
+ function offsetWithin(pane, element) {
832
+ return element.getBoundingClientRect().top - pane.getBoundingClientRect().top + pane.scrollTop;
833
+ }
486
834
  function chooseInitialPath(entries, initialPath, entryPoint) {
487
835
  if (initialPath && entries.some((entry) => entry.path === initialPath))
488
836
  return initialPath;
@@ -494,7 +842,45 @@ function chooseInitialPath(entries, initialPath, entryPoint) {
494
842
  ?? null;
495
843
  }
496
844
  async function readEntry(side, path) {
497
- return path && side.archive ? side.archive.readBytes(path) : null;
845
+ if (!path)
846
+ return null;
847
+ if (side.markdown)
848
+ return path === side.inventory.entryPoint ? side.markdown.bytes : null;
849
+ return side.archive ? side.archive.readBytes(path) : null;
850
+ }
851
+ /** True when every side given is plain Markdown (a missing side counts too), and at least one is. */
852
+ function isMarkdownOnly(options) {
853
+ const sides = [options.before, options.after];
854
+ return sides.some((side) => side.markdown !== undefined)
855
+ && sides.every((side) => side.markdown !== undefined || !side.bytes);
856
+ }
857
+ /**
858
+ * Gives each plain-Markdown side its single entry. The name is shared so the
859
+ * two sides compare as one document: the archive's entry point when the other
860
+ * side is an archive (comparing `notes.md` with `notes.mdz` lines it up with
861
+ * the main document), otherwise the `.md` file name.
862
+ */
863
+ function assignMarkdownEntries(before, after) {
864
+ if (!before.markdown && !after.markdown)
865
+ return;
866
+ const archiveSide = [after, before].find((side) => side.archive && side.inventory.entryPoint);
867
+ const path = archiveSide?.inventory.entryPoint
868
+ ?? markdownFileName(after.input.fileName)
869
+ ?? markdownFileName(before.input.fileName)
870
+ ?? DEFAULT_MARKDOWN_PATH;
871
+ for (const side of [before, after]) {
872
+ if (!side.markdown)
873
+ continue;
874
+ side.inventory = {
875
+ entries: [{ path, kind: 'markdown', size: side.markdown.bytes.length, hash: side.markdown.hash }],
876
+ entryPoint: path,
877
+ manifest: null
878
+ };
879
+ }
880
+ }
881
+ function markdownFileName(fileName) {
882
+ const base = fileName?.split(/[\\/]/).pop();
883
+ return base && /\.(md|markdown)$/i.test(base) ? base : undefined;
498
884
  }
499
885
  function decodeText(bytes) {
500
886
  if (!bytes)