@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/AGENTS.md CHANGED
@@ -47,6 +47,14 @@ A host that writes a linked image file itself (plain `.md`) can reuse the editor
47
47
 
48
48
  `onLinkActivated(event)` fires for every preview link click before built-in handling. `event.preventDefault()` must be called synchronously — calling it after an `await` is too late, and the built-in anchor scroll / document open / `onUnresolvedLinkClick` will already have run. To open new tabs for external links, use the `externalLinks` policy (or `setExternalLinks()`), not a custom renderer or DOMPurify hook: sanitization strips `target`, so the policy is applied to the mounted DOM instead. `scrollToAnchor()` is safe to call right after `open()` — it waits for the preview to mount rather than failing — so hosts don't need their own `onPreviewRendered` + retry loop. To deep-link into another file use `openPath(path, { anchor })` (resolves `false` for an unknown path or anchor). To reload an archive without sending the user back to the entry point, pass `initialPath: view.getCurrentPath()` to `open()`/`openWorkspace()`; for a rename only (Save As), call `setFileName()` instead of reopening.
49
49
 
50
+ **Rendering moved to `@mdzip/renderer` (since 2.5.0)**
51
+
52
+ The Markdown-to-HTML pipeline (marked, footnotes, highlight.js, heading ids, the DOMPurify policy) is now the `@mdzip/renderer` package, a dependency of the editor; `marked`, `marked-footnote` and `highlight.js` come in through it. Heading ids changed: a repeated heading gets `-1`, `-2` (was `-2`, `-3`), and letters in any language are kept, so stored `#anchor` links to repeated headings may need updating. To render a page the way the preview does (a static site, a server), use the renderer directly rather than mounting the editor.
53
+
54
+ **Extract and Find depend on host options (since 2.5.0)**
55
+
56
+ Without `onExtractFiles`, the contents pane offers browser downloads (Download, Download as ZIP) — wrong wording and behavior in a desktop host, which should pass `onExtractFiles` to get **Extract…** and write the files itself, asking before overwriting. Extracting never changes the archive or marks it dirty. Find in the View layout (a find bar over the preview, no source editor) is gated by the same `controls.search` flag as find/replace: a host that passes `search: false` turns both off.
57
+
50
58
  **Preview code-block chrome (since 1.3.16)**
51
59
 
52
60
  Rendered code blocks get a language header, a copy button, and (past 15 lines) a collapse toggle, gated by the `codeBlockTools` control-policy flag (default `true` everywhere, including `preview`). This is wired into `mountPreviewHtml`/`mountProgressivePreview` directly, not a `markdownExtensions` entry — don't confuse it with `formatting.codeBlock`, which is the unrelated editor-toolbar insert-code-block control.
package/README.md CHANGED
@@ -1,7 +1,4 @@
1
- [![MDZip logo][mdzip-logo]][mdzip-url]
2
-
3
- [mdzip-logo]: https://raw.githubusercontent.com/mdzip-project/mdzip-editor/main/resources/mdzip-mark.svg
4
- [mdzip-url]: https://mdzip.org
1
+ <a href="https://mdzip.org"><img src="https://mdzip.org/assets/images/mdzip-mark-square.svg" alt="MDZip logo" width="64" height="64"></a>
5
2
 
6
3
  # @mdzip/editor
7
4
 
@@ -46,6 +43,13 @@ await view.open(markdownBytes, {
46
43
  });
47
44
  ```
48
45
 
46
+ In the split layout the editor and preview scroll together, block by block:
47
+ each heading, paragraph, list, code block, table or image in the preview stays
48
+ level with its Markdown, so a tall image or table doesn't pull the two apart.
49
+ The preview marks its blocks with `data-mdzip-block` for this; copies of the
50
+ preview leave the marks out. With a custom `markdownRenderer` the panes scroll
51
+ in proportion instead.
52
+
49
53
  CodeMirror is not initialized until a source or split layout is used. Consumers
50
54
  that only need archive, rendering, and preview helpers can import from
51
55
  `@mdzip/editor/preview`; that entry point excludes `MdzipWorkspaceView` and its
@@ -103,6 +107,11 @@ in the browser. When `onSaved` is provided, the host owns persistence and must
103
107
  call `markPersisted()` after a successful write. Failed writes should leave the
104
108
  workspace dirty.
105
109
 
110
+ A document opens in `initialLayout` (Edit is `'source'`, then `'split'` and
111
+ View is `'preview'`). `await view.setLayout('preview')` switches layout later,
112
+ as the toolbar's buttons do, and `view.layoutMode` says which is showing. A
113
+ file that can't be shown that way gets the nearest layout it can.
114
+
106
115
  ## Control Presets
107
116
 
108
117
  - `preview`: clean document preview with no toolbar or package navigation.
@@ -114,6 +123,14 @@ Call `setControls(nextControls)` to update the policy after construction
114
123
  without rebuilding the workspace view. `lineNumbers` changes are applied to the
115
124
  existing CodeMirror editor, preserving the current document and selection.
116
125
 
126
+ The **Show whitespace** button (¶, at the end of the formatting buttons;
127
+ `controls.whitespace`, on except
128
+ in `preview`) shows spaces as faint dots and tabs as arrows in the source
129
+ editor; it appears while the editor is visible. The marks start hidden unless
130
+ `showWhitespace: true` is passed; `setWhitespaceVisible()` and
131
+ `isWhitespaceVisible` switch and read them, and `onWhitespaceVisibilityChanged`
132
+ lets a host remember the reader's choice.
133
+
117
134
  ## Density and Spacing
118
135
 
119
136
  Hosts can opt into smaller built-in UI without targeting private classes:
@@ -177,6 +194,97 @@ Unset is the same as `'default'`. A pixel number is used exactly as given and
177
194
  doesn't scale with zoom, and leaves no menu item checked; so does setting the
178
195
  `--mdzip-preview-content-max-width` CSS variable directly.
179
196
 
197
+ ## Find
198
+
199
+ `view.openSearch()`, the toolbar's Find button and Ctrl+F (Cmd+F on a Mac)
200
+ with focus in the editor open find for the current Markdown document:
201
+
202
+ - **In View**, a find bar over the preview searches the rendered text, what
203
+ the reader sees rather than the Markdown, and the layout stays View. It
204
+ counts matches in the whole document ("3 of 12"), including parts the
205
+ progressive preview hasn't drawn yet; going to one of those draws it first.
206
+ Matches are highlighted with the CSS Custom Highlight API, so the preview's
207
+ DOM isn't changed. Enter and Shift+Enter (or F3 and Shift+F3, or the arrow
208
+ buttons) move between them, **Aa** matches case, and Escape closes the bar
209
+ and clears the highlights. Spaces in the query match any whitespace, and a
210
+ match doesn't run from one paragraph into the next. Diagrams, code-block
211
+ headers and other editor chrome aren't searched.
212
+ - **In Edit and Split**, it's the source editor's find and replace panel, as
213
+ before.
214
+
215
+ `closeSearch()` closes either; `isFindOpen` says whether the bar is open.
216
+ `controls.search: false` turns both off. Find works in read-only documents
217
+ too.
218
+
219
+ ## Outline Panel
220
+
221
+ The outline panel is a table of contents built from the document's headings,
222
+ beside the preview. It marks the section being read, and a click scrolls
223
+ smoothly to that section (it jumps instead when the system asks for reduced
224
+ motion). The toolbar's outline button (next to Find) shows it on the left,
225
+ moves it to the right, then hides it, sliding it out and in rather than
226
+ jumping (unless the system asks for reduced motion); its tooltip says which
227
+ comes next. It
228
+ appears while the preview of a Markdown document is visible, in View or Split
229
+ layout. Under progressive rendering it lists every heading, including ones in
230
+ chunks that haven't been drawn yet, and a click draws the chunks up to the
231
+ heading first, as `scrollToAnchor()` does.
232
+
233
+ The panel is closed at start. `outline` opens it and configures it, and
234
+ `onOutlineVisibilityChanged(visible)` and `onOutlinePositionChanged(position)`
235
+ report the button so a host can remember the choice:
236
+
237
+ ```ts
238
+ const view = new MdzipWorkspaceView(container, {
239
+ controls: 'hosted-editor',
240
+ outline: { visible: savedOutline ?? false, levels: [1, 2, 3], collapse: true, label: 'Outline' },
241
+ onOutlineVisibilityChanged: (visible) => saveOutline(visible),
242
+ onOutlinePositionChanged: (position) => saveOutlineSide(position)
243
+ });
244
+
245
+ view.setOutlineVisible(true);
246
+ view.isOutlineVisible; // true
247
+ ```
248
+
249
+ `levels` defaults to `[1, 2, 3]`. With `collapse` (the default), deeper levels
250
+ show only under the section being read. `controls: { outline: false }` hides
251
+ the button; `outline: true` still opens the panel, for hosts with their own
252
+ toggle. The panel is 240px wide (`--mdzip-outline-pane-width`, or the
253
+ `width` option), and the reader can drag its edge to resize it;
254
+ `onOutlineWidthChanged(width)` reports the new width when they let go, so a
255
+ host can pass it back as `width` next time. It goes on the right of the
256
+ document; `position: 'left'` puts it on the left instead, between the
257
+ contents pane and the document, and `setOutlinePosition('left' | 'right')`
258
+ moves it later (`outlineSide` says where it is). Below 760px it floats over
259
+ the preview, on its side. Its links use the `.mdz-outline*` classes and take
260
+ their colors from `--mdz-outline-text`, `--mdz-outline-muted`,
261
+ `--mdz-outline-rule` and `--mdz-outline-current`.
262
+
263
+ The outline also works on its own, on any page that shows rendered Markdown
264
+ (`@mdzip/editor/outline`, no other editor code):
265
+
266
+ ```ts
267
+ import { createMdzipHeadingOutline, collectMdzipOutlineHeadings } from '@mdzip/editor/outline';
268
+
269
+ const outline = createMdzipHeadingOutline({
270
+ content: document.querySelector('article')!,
271
+ container: document.querySelector('#toc')!,
272
+ levels: [2, 3], // default
273
+ label: 'On this page', // default
274
+ scrollContainer: null // the window; or the element that scrolls the content
275
+ });
276
+ outline.refresh(); // after the content changes
277
+ outline.destroy();
278
+
279
+ // Or just the headings, to draw your own: [{ id, text, level, element }]
280
+ const headings = collectMdzipOutlineHeadings(document.querySelector('article')!, { levels: [2, 3] });
281
+ ```
282
+
283
+ Headings without an id get one. `onNavigate(heading, event)` runs on click
284
+ (call `event.preventDefault()` to scroll some other way), `offset` sets where a
285
+ heading counts as reached (default 96px from the top), and `headings` /
286
+ `findElement` supply headings that aren't in the DOM yet.
287
+
180
288
  ## Host Persistence
181
289
 
182
290
  Desktop hosts can flush pending editor content, persist the returned bytes, and
@@ -197,6 +305,74 @@ Structured callbacks are available for workspace, document, asset, manifest,
197
305
  selection, dirty, validation, and snapshot changes. Asset hosts can also call
198
306
  `addAsset()`, `replaceAsset()`, `removeAsset()`, and `listAssets()`.
199
307
 
308
+ ## Editing JSON and the Manifest
309
+
310
+ `.json` files open in the editor with JSON highlighting, and are checked as
311
+ you type: a syntax error is underlined where it is, with what's wrong ("Remove
312
+ the comma before }: JSON has no trailing commas."), and a status line under
313
+ the editor sums it up. Other JSON files are saved exactly as typed, even when
314
+ they don't parse.
315
+
316
+ The archive's `manifest.json` opens as a form, **Document properties**, in
317
+ the View layout: Title, Description, Author, Keywords, Language, License and
318
+ Document version, with the entry point and mode under **Advanced** and the
319
+ dates, spec version and producer as read-only details. Where a label isn't
320
+ the JSON key itself, the key follows it in parentheses, such as "Opens with
321
+ (`entryPoint`)" and "Kind of archive (`mode`)". Edit shows the JSON,
322
+ and Split shows both, each following the other as you type. The JSON text is
323
+ the one source of truth: a change in the form sets only that value in the
324
+ text (`setMdzipJsonMember()`), so key order, formatting and fields the form
325
+ doesn't show are kept, and Ctrl+Z in the JSON editor undoes it. Clearing a
326
+ field removes the property. A field's problem shows under it; while the text
327
+ isn't valid JSON, the form shows a notice with **Fix in JSON** instead. The
328
+ manifest remembers its own layout, so opening it doesn't change how your
329
+ documents are shown. `manifestView: 'json'` opens it in the JSON editor
330
+ instead of the form.
331
+
332
+ `manifest.json` is checked against the spec in both views:
333
+
334
+ | Problem | |
335
+ | --- | --- |
336
+ | Not JSON, not an object, or a property name used twice | error |
337
+ | `spec`, `spec.version`, `mode` or `entryPoint` invalid, or `entryPoint` not a Markdown file in the archive | error |
338
+ | A descriptive field with a wrong type or format (`title: 42`, `created: "yesterday"`) | error |
339
+ | `cover` names no file in the archive | warning |
340
+ | `producer` or `spec.version` edited (tools normally set these) | warning |
341
+ | Fields the spec doesn't define | fine: listed as custom fields and kept |
342
+
343
+ While the manifest has an error, saving is blocked: `flush()`, `saveToBytes()`,
344
+ `exportBytes()`, `serialize()` and `getCurrentSnapshot()` throw
345
+ `MdzipManifestInvalidError` (`code: 'ERR_MANIFEST_INVALID'`, with the problems
346
+ in `validity`), and the toolbar's save button opens the manifest to show them.
347
+ The broken text is kept while you look at other files. A valid manifest is
348
+ saved as core-js writes every manifest: the same values, in the same order,
349
+ custom fields included, with `modified` refreshed and 2-space indentation.
350
+
351
+ ```ts
352
+ const view = new MdzipWorkspaceView(container, {
353
+ jsonStatus: true, // the status line under the editor (default)
354
+ onJsonValidityChanged: (validity, path) => {
355
+ // validity: { kind, status: 'valid' | 'warnings' | 'invalid', problems, canSave, customFields }
356
+ // null when the open file isn't JSON
357
+ }
358
+ });
359
+
360
+ view.getManifestValidity(); // the manifest's problems that block saving, or null
361
+ ```
362
+
363
+ JSON files also get the usual editing aids: matching brackets are highlighted,
364
+ `{`, `[` and `"` close themselves as you type, and arrows in the gutter fold
365
+ objects and arrays (Ctrl+Shift+[ and Ctrl+Shift+] too). **Format JSON** (the
366
+ `{}` button in the editing toolbar, or Shift+Alt+F) re-indents the file with
367
+ 2 spaces in one undo step. It only changes whitespace: keys stay in their
368
+ order, and numbers (`1.0`, `1e3`, very long integers) and strings stay exactly
369
+ as typed. It's disabled while the text isn't valid JSON. `view.formatJson()`
370
+ does the same, and `formatMdzipJsonText(text)` formats any JSON text.
371
+
372
+ The checks are also available on their own: `validateMdzipManifestText(text, {
373
+ archivePaths, stored })` and `validateMdzipJsonText(text)` return the same
374
+ `MdzipJsonValidity`, with each problem's position in the text.
375
+
200
376
  ## File Management (navigation pane)
201
377
 
202
378
  With `controls: 'standalone-editor'` or `'hosted-editor'` (or `fileActions: true`
@@ -234,6 +410,68 @@ new MdzipWorkspaceView(container, {
234
410
  The items show in read-only workspaces too; the host decides what each one
235
411
  allows. The Angular, React and Vue wrappers take the same `hostFileActions`.
236
412
 
413
+ **Files the preview can't show.** A Word document, a ZIP or any other file
414
+ that isn't Markdown, text or a picture shows as a card: its name, what kind of
415
+ file it is, and buttons for the `hostFileActions` that apply to it, then
416
+ **Extract…** (or **Download**) and, in an editable document, **Replace…**. A
417
+ desktop host can offer to open the file in the app the system opens it with,
418
+ and put the changes back with `replaceAsset()` when it's saved there:
419
+
420
+ ```ts
421
+ new MdzipWorkspaceView(container, {
422
+ hostFileActions: [{
423
+ id: 'open',
424
+ primary: true, // its button comes first and stands out
425
+ label: (file) => `Open in ${appFor(file.path) ?? 'Default App'}`,
426
+ appliesTo: (file) => !file.isMarkdown,
427
+ description: 'Opens it in that app. Each time you save there, the changes come back here.',
428
+ run: (file) => openInApp(file.path)
429
+ }],
430
+ // A link at the bottom of the card.
431
+ fileCardHelp: { label: 'More about files in a document', run: () => showHelp('files') },
432
+ // A line on the card, or null for none.
433
+ fileNote: (file) => isOpenElsewhere(file.path) ? 'Open in Word: changes come back each time you save there.' : null
434
+ });
435
+
436
+ // When a label or the note would now be different:
437
+ view.refreshFileActions();
438
+ ```
439
+
440
+ The menu on the file in the contents pane uses the same labels.
441
+
442
+ **Selecting and extracting files.** Ctrl+click (Cmd+click on a Mac) adds a
443
+ row of the tree to the selection or takes it off, Shift+click selects the rows
444
+ in between, and Ctrl+A / Cmd+A with focus in the tree selects every row
445
+ (Escape clears it). Right-clicking a row outside the selection selects just
446
+ that row; inside a selection of several, the menu offers only taking them out
447
+ of the archive. Folders take all their files, and `manifest.json` comes only
448
+ when it's selected itself. Paths below the folder are kept and bytes are
449
+ copied as stored. The archive isn't changed, so this works in read-only
450
+ workspaces too.
451
+
452
+ - **On the web** (no `onExtractFiles`), one file is **Download**, and a folder
453
+ or several rows are **Download as ZIP** (the folder's name, or the
454
+ archive's, `.zip`), plus **Extract to Folder…** in browsers that can write
455
+ to a folder (`showDirectoryPicker`). That asks in the editor before
456
+ replacing files already there.
457
+ - **In a desktop host**, `onExtractFiles` replaces all of these with
458
+ **Extract…** (**Extract All…** on the empty part of the pane). It's called
459
+ with `{ files: [{ path, bytes }], selection: { files, folders } }`; the host
460
+ picks where they go, keeps the paths below it and asks before replacing.
461
+
462
+ ```ts
463
+ new MdzipWorkspaceView(container, {
464
+ onExtractFiles: async ({ files }) => {
465
+ const folder = await pickFolder(); // the host's own dialog
466
+ await writeFiles(folder, files); // ask first if any exist
467
+ }
468
+ });
469
+ ```
470
+
471
+ `view.extractFiles(paths, { includeFolders })` returns the same
472
+ `{ path, bytes }[]` for files and folders named by path (`''` is the whole
473
+ archive), for hosts with their own commands.
474
+
237
475
  The same operations are available programmatically: `removeFile()`,
238
476
  `renameFile()` (rewrites markdown references, including a moved document's own
239
477
  relative links), `setEntryPoint()`, and `setCoverImage()`.
@@ -554,6 +792,65 @@ states, image previews with metadata, and binary metadata. Entry content is
554
792
  loaded only when selected. Call `destroy()` to release editors, listeners, and
555
793
  image object URLs.
556
794
 
795
+ ### Plain Markdown files
796
+
797
+ A side can be a plain `.md` document instead of an archive. Pass its text as
798
+ `markdown`, and, for images in the rendered view, a `readResource` function
799
+ that reads the files it links to:
800
+
801
+ ```ts
802
+ const diff = new MdzipDiffView(container, {
803
+ before: { markdown: headText, label: 'HEAD', readResource: readImageAtHead },
804
+ after: { markdown: workingText, label: 'Working tree', fileName: 'notes.md', readResource: readImageOnDisk },
805
+ rendered: true
806
+ });
807
+ ```
808
+
809
+ `readResource` receives the image source normalized relative to the
810
+ document's folder (`images/a.png`, `../shared/a.png`; a root-relative source
811
+ keeps its leading `/`) and resolves the bytes, or `null` when there's no such
812
+ file. Give each side its own reader, so a comparison with an older version
813
+ shows that version's images. Without one, images show as missing.
814
+
815
+ Set `editable: true` on a Markdown side (typically the working copy) to let
816
+ the user edit it in the source view; `onMarkdownChange(text)` receives the
817
+ full text after each edit, and the comparison updates as they type. The
818
+ rendered view stays read-only but shows the edited text. Saving is up to the
819
+ host.
820
+
821
+ The comparison has a single entry, named after `fileName` (or `document.md`),
822
+ and the navigation pane starts hidden unless `navigationVisible` says
823
+ otherwise. One side may be plain Markdown and the other an archive: the
824
+ document then lines up with the archive's main document.
825
+
826
+ ## Resolving Merge Conflicts
827
+
828
+ When two branches change the same part of a document, a Git merge leaves conflict markers in its text. For an `.mdz`, the `mdz merge` driver ([mdzip-cli](https://github.com/mdzip-project/mdzip-cli)) merges the archive file by file: it puts the markers inside the documents, keeps both versions of an image both sides replaced (`chart.png` and `chart.theirs.png`), and decides a few things itself (a file one side deleted and the other changed is kept; a manifest field both changed keeps the current value). `MdzipMergeView` resolves what it left, in the layout of the Visual Studio and VS Code merge editors:
829
+
830
+ ```ts
831
+ import { MdzipMergeView } from '@mdzip/editor/merge-view';
832
+
833
+ const view = new MdzipMergeView(container, {
834
+ bytes: mergedArchiveBytes, // or { markdown: text, fileName: 'notes.md', readResource }
835
+ // Optional: the versions Git holds during the merge (index stages 1, 2, 3).
836
+ versions: { base: { bytes: baseBytes }, ours: { bytes: oursBytes }, theirs: { bytes: theirsBytes } },
837
+ oursLabel: 'main', // branch names, shown under Current and Incoming
838
+ theirsLabel: 'topic',
839
+ colorScheme: 'dark',
840
+ toolbarDensity: 'dense',
841
+ onChange: ({ path, text, bytes, remaining }) => save(bytes ?? text),
842
+ onComplete: ({ remaining }) => markResolved() // shows a Complete Merge button
843
+ });
844
+ ```
845
+
846
+ - **A tree of the archive's files** with a marker on each: ● text conflicts (with a count), ◐ a choice to make (an image both sides replaced), ↺ a choice the merge made that's worth reviewing, ✓ merged. Unchanged files are hidden unless you ask for them. A plain Markdown document has no tree.
847
+ - **A text file** shows Incoming (theirs) on the left and Current (ours) on the right, each with its changes from the original marked, over the result. Each change has a checkbox: one-sided changes start ticked, conflicts unticked. Ticking a side takes its text into the result; ticking both sides of a conflict keeps both, in the order you ticked them, and unticking both brings the conflict back. **Take All Incoming** / **Take All Current** in each pane's heading tick every change on that side. In the source view the result is editable (the boxes follow what you type), and each conflict has **Accept Incoming**, **Accept Current**, **Accept Both** and **Use Original** links above it. The three panes scroll together; in the source view they're lined up line for line (blank filler where one pane has fewer lines for a change, a dashed line where it has none), with word wrap off so the lines stay level. In the rendered view, matching headings stay level and the stretches between them scroll in step. The result's heading counts the conflicts remaining in the file, and the toolbar counts those left overall ("2 of 5 conflicts") and steps through them across files. The rendered view shows all three as the preview, with unresolved conflicts in the result showing the current version, marked, and a bar that accepts the current conflict.
848
+ - **An image both sides replaced** shows incoming, current and the original, with **Take Incoming** (which removes the `.theirs` copy) and **Keep Current**. **A file one side deleted** has **Keep it** and **Delete it**. **Manifest fields** both sides changed are listed with **Take Incoming** / **Take Current**.
849
+ - With `versions`, the tree shows every change (added, deleted, changed in current, incoming or both) and spots renames, as `mdz merge` does, and each text file shows its one-sided changes with checkboxes too; without them, the view works from the conflict markers and `.theirs` copies alone.
850
+ - `onChange` fires after each change with the entry's new text and, for an archive, the whole archive's new bytes (typing in the result is reported once it pauses). `onResolved` fires when nothing is left, and **Complete Merge** (shown when you pass `onComplete`) reports every pending change, then calls `onComplete` with what's still unresolved, so the host can ask before completing anyway. `files` lists each file's state and summary, `conflicts` what's left; `resolve(index, resolution)`, `chooseChange(path, index, sides)` (a file's changes, as the checkboxes set them), `resolveFile(path, 'keep' | 'delete')` and `chooseManifestField(key, side)` resolve from code; `getText(path)` and `getArchiveBytes()` return the current result.
851
+
852
+ The parsing is also available on its own from the main entry: `findMergeConflicts(text)` returns each block (with `ours`, `base` or null, `theirs`, labels and position), and `resolveMergeConflict(text, index, 'ours' | 'theirs' | 'both' | 'base' | { text })` returns the text with that block replaced. Markers longer than seven characters (Git's `conflict-marker-size`) and CRLF line endings are handled; an unfinished block is left alone.
853
+
557
854
  ## Preview Lifecycle Signals
558
855
 
559
856
  To reveal or animate read-only preview content without scraping internal DOM,
@@ -588,6 +885,24 @@ In live-editing hosts where the preview re-renders frequently, pass
588
885
  images open on same-document edits. Use `'off'` to disable the loading pulse
589
886
  and slide-open animation entirely.
590
887
 
888
+ Images load as they come near the visible part of the preview, so a long
889
+ document doesn't decode every picture up front. A preview nobody scrolls,
890
+ such as an off-screen copy rendered for printing or a PDF, would then never
891
+ load the images further down, and `onAssetsHydrated` would never fire: pass
892
+ `eagerImages: true` (with `progressiveTextRendering: false`, so all the text
893
+ mounts too) to load them all as soon as the preview mounts. `onAssetsProgress`
894
+ reports `{ loaded, total }` as they load, for a progress bar:
895
+
896
+ ```ts
897
+ const printCopy = new MdzipWorkspaceView(offscreen, {
898
+ controls: 'preview',
899
+ progressiveTextRendering: false,
900
+ eagerImages: true,
901
+ onAssetsProgress: ({ loaded, total }) => showProgress(loaded / total),
902
+ onAssetsHydrated: () => print()
903
+ });
904
+ ```
905
+
591
906
  ## Links and anchors
592
907
 
593
908
  Hosts that embed the preview as a doc browser can route links, set an
@@ -660,7 +975,9 @@ does. You can call it at any time, including straight after `open()` or from
660
975
  `onPreviewRendered`. It waits for the current document to mount and, under
661
976
  progressive rendering, mounts the chunks up to the target first. It resolves
662
977
  `true` when it scrolled and `false` when nothing matched. `''` and `'top'`
663
- scroll to the top. `getAvailableAnchors()` lists the reachable anchors in
978
+ scroll to the top. `{ smooth: true }` glides there over a fraction of a second,
979
+ as an outline click does, instead of jumping (except under
980
+ `prefers-reduced-motion`). `getAvailableAnchors()` lists the reachable anchors in
664
981
  document order, including headings in chunks that haven't mounted yet.
665
982
 
666
983
  ```ts
@@ -0,0 +1,54 @@
1
+ import type { MdzManifest } from '@mdzip/core-js';
2
+ /** Attribute recording an image's archive path and content hash, used to match blocks. */
3
+ export declare const DIFF_ASSET_ATTRIBUTE = "data-mdzip-diff-asset";
4
+ export interface RenderedSideSource {
5
+ /** The document's Markdown, or null when the entry doesn't exist on this side. */
6
+ markdown: string | null;
7
+ /** Archive path of the document, for resolving relative image paths. */
8
+ path: string | undefined;
9
+ manifest: MdzManifest | null;
10
+ colorScheme: 'light' | 'dark';
11
+ /** Reads an archive entry; resolves null when it doesn't exist. */
12
+ readBytes(path: string): Promise<Uint8Array | null>;
13
+ /** The content hash of an archive entry, when known. */
14
+ hashOf(path: string): string | undefined;
15
+ /** Turns image bytes into a URL the page can load (an object URL). */
16
+ createUrl(bytes: Uint8Array, mime: string): string;
17
+ /**
18
+ * `'markdown'` for a plain `.md` document: images are files next to it
19
+ * (resolved with {@link resolveLinkedPath}), not archive entries.
20
+ * Default `'mdz'`.
21
+ */
22
+ sourceFormat?: 'mdz' | 'markdown';
23
+ }
24
+ /**
25
+ * Renders one side to an inert fragment: archive images are loaded from the
26
+ * archive and tagged with their path and hash; nothing is fetched from the
27
+ * host page's location.
28
+ */
29
+ export declare function renderSideFragment(doc: Document, source: RenderedSideSource, signal: AbortSignal): Promise<DocumentFragment | null>;
30
+ /**
31
+ * Marks the top-level blocks that only one side has: `mdzip-diff-block-removed`
32
+ * on the before side, `mdzip-diff-block-added` on the after side. A changed
33
+ * paragraph shows as both. Returns the pairs of blocks that match, in order,
34
+ * for {@link syncScroll}.
35
+ */
36
+ export declare function markBlockChanges(before: Element, after: Element): Array<[HTMLElement, HTMLElement]>;
37
+ /**
38
+ * Keeps two scrolling panes in step: the matched block at the top of the
39
+ * pane being scrolled is lined up with its partner in the other pane, so
40
+ * blocks added on one side don't push the two out of line. Returns a function
41
+ * that removes the listeners.
42
+ */
43
+ export declare function syncScroll(left: HTMLElement, right: HTMLElement, pairs: ReadonlyArray<readonly [HTMLElement, HTMLElement]>): () => void;
44
+ /** Resolves an image source against the document's folder; null if it leaves the archive. */
45
+ export declare function resolveArchivePath(documentPath: string, source: string): string | null;
46
+ /**
47
+ * Normalizes an image source in a plain `.md` document, relative to the
48
+ * document's own folder. Unlike {@link resolveArchivePath} it may leave that
49
+ * folder: leading `../` segments are kept, and a root-relative source keeps
50
+ * its leading `/`, so the host can resolve it against its own root.
51
+ * Returns null for an empty source.
52
+ */
53
+ export declare function resolveLinkedPath(source: string): string | null;
54
+ //# sourceMappingURL=diff-rendered.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff-rendered.d.ts","sourceRoot":"","sources":["../src/diff-rendered.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAOlD,0FAA0F;AAC1F,eAAO,MAAM,oBAAoB,0BAA0B,CAAC;AAO5D,MAAM,WAAW,kBAAkB;IACjC,kFAAkF;IAClF,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,wEAAwE;IACxE,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,QAAQ,EAAE,WAAW,GAAG,IAAI,CAAC;IAC7B,WAAW,EAAE,OAAO,GAAG,MAAM,CAAC;IAC9B,mEAAmE;IACnE,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IACpD,wDAAwD;IACxD,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACzC,sEAAsE;IACtE,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACnD;;;;OAIG;IACH,YAAY,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC;CACnC;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,QAAQ,EACb,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAuClC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,KAAK,CAAC,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,CA4DnG;AAuMD;;;;;GAKG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,aAAa,CAAC,SAAS,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,GACxD,MAAM,IAAI,CAwCZ;AAED,6FAA6F;AAC7F,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAmBtF;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqB/D"}