@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/view.js CHANGED
@@ -1,11 +1,14 @@
1
+ import { closeBrackets, closeBracketsKeymap } from '@codemirror/autocomplete';
1
2
  import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
3
+ import { json } from '@codemirror/lang-json';
2
4
  import { markdown } from '@codemirror/lang-markdown';
3
- import { HighlightStyle, syntaxHighlighting, syntaxTree } from '@codemirror/language';
5
+ import { linter } from '@codemirror/lint';
6
+ import { HighlightStyle, bracketMatching, foldGutter, foldKeymap, syntaxHighlighting, syntaxTree } from '@codemirror/language';
4
7
  import { closeSearchPanel, openSearchPanel, search, searchKeymap } from '@codemirror/search';
5
- import { Compartment, EditorState, RangeSetBuilder, StateEffect, StateField } from '@codemirror/state';
6
- import { Decoration, EditorView, MatchDecorator, ViewPlugin, WidgetType, dropCursor, keymap, lineNumbers } from '@codemirror/view';
8
+ import { Compartment, EditorState, Prec, RangeSetBuilder, StateEffect, StateField } from '@codemirror/state';
9
+ import { Decoration, EditorView, MatchDecorator, ViewPlugin, WidgetType, dropCursor, keymap, highlightWhitespace, lineNumbers } from '@codemirror/view';
7
10
  import { tags } from '@lezer/highlight';
8
- import { Bold, Check, ChevronDown, ChevronRight, ClipboardPaste, ClipboardType, Code, Columns2, Copy, Eraser, Eye, File, FileBraces, FileImage, Folder, FolderOpen, Hash, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, Highlighter, ImagePlus, Info, Italic, Link2Off, Link, List, ListOrdered, CornerDownLeft, Monitor, Moon, PackagePlus, PanelLeft, Pilcrow, Quote, Save, Scissors, Search, SpellCheck, SquareCode, SquarePen, Strikethrough, Sun, TextSelect, ZoomIn } from 'lucide';
11
+ import { Bold, CaseSensitive, Check, ChevronDown, ChevronRight, ChevronUp, ClipboardPaste, ClipboardType, Code, Columns2, Copy, Eraser, Eye, File, FileBraces, FileImage, Folder, FolderOpen, Hash, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, Highlighter, ImagePlus, Info, Italic, Link2Off, Link, List, ListOrdered, CornerDownLeft, Monitor, Moon, PackagePlus, PanelLeft, Pilcrow, Quote, Save, Scissors, Search, SpellCheck, SquareCode, SquarePen, Strikethrough, Braces, Text, TableOfContents, Sun, TextSelect, X, ZoomIn } from 'lucide';
9
12
  import { samePath } from '@mdzip/core-js';
10
13
  import { browserClipboardHasImage, readBrowserClipboardImage } from './browser.js';
11
14
  import { buildPackedArchiveBytes, isMarkdownArchivePath, resolveMarkdownEntryPoint } from './archive-utils.js';
@@ -13,8 +16,16 @@ import { MdzipAssetSession, mdzipArchiveSourceId, sniffImageSize } from './asset
13
16
  import { MD_MARKDOWN_ICON } from './icons/md-markdown.js';
14
17
  import { PAGE_WIDTH_DEFAULT_ICON, PAGE_WIDTH_FULL_ICON, PAGE_WIDTH_NARROW_ICON, PAGE_WIDTH_WIDE_ICON } from './icons/page-width.js';
15
18
  import { MDZIP_RUNTIME_LIBRARIES } from './library-info.js';
16
- import { MdzipWorkspaceService, extensionForMime, normalizeArchivePath, relativeArchivePath } from './workspace.js';
19
+ import { MdzipManifestInvalidError, MdzipWorkspaceService, extensionForMime, normalizeArchivePath, relativeArchivePath } from './workspace.js';
17
20
  import { buildMdzipNavTree, canEditMdzipPath, escapeHtml, isOrphanedMdzipAsset, mdzipEntryIconKind, isMdzipManifestPath, isMdzipDefaultPolicyExternalLink, isMdzipExternalLink, isMdzipWorkspaceRelativeLink, parseMdzipLink, renderMdzipPreviewHtml } from './workspace-view.js';
21
+ import { collectMdzipHeadings } from '@mdzip/renderer';
22
+ import { describeMdzipJsonValidity, formatMdzipJsonText, isMdzipJsonPath, isMdzipRootManifestPath, setMdzipJsonMember } from './json-validation.js';
23
+ import { MdzipManifestForm } from './manifest-form.js';
24
+ import { mapScrollPosition } from './scroll-anchors.js';
25
+ import { zipSync } from 'fflate';
26
+ import { collectFindText, findMatches, findPattern, findRange, setFindHighlights } from './preview-find.js';
27
+ import { MDZIP_BLOCK_ATTRIBUTE, stripMdzipBlockMarks } from '@mdzip/renderer';
28
+ import { createMdzipHeadingOutline } from './heading-outline.js';
18
29
  import { escapeMarkdownImageAlt, findImageReferenceAtOffset, formatImageEditMarkdown } from './image-edit.js';
19
30
  import { MdzipRenderingService, defaultSafeMarkdownRenderer, groupTokensIntoChunks, chunkSourceKey, collectMdzipHeadingIds, MDZIP_HEADING_ID_PREFIX, tokenEmbedsImage, tokenIsHeading } from './rendering.js';
20
31
  import { mdzipFrontMatterExtension } from './front-matter-extension.js';
@@ -53,6 +64,28 @@ const PREVIEW_ICON_HTML = lucideIcon(Eye, TOOLBAR_ICON_CLASS);
53
64
  const SPLIT_ICON_HTML = lucideIcon(Columns2, TOOLBAR_ICON_CLASS);
54
65
  const SAVE_ICON_HTML = lucideIcon(Save, TOOLBAR_ICON_CLASS);
55
66
  const SEARCH_ICON_HTML = lucideIcon(Search, TOOLBAR_ICON_CLASS);
67
+ const FIND_ICON_CLASS = 'preview-find-icon';
68
+ const FIND_PREVIOUS_ICON_HTML = lucideIcon(ChevronUp, FIND_ICON_CLASS);
69
+ const FIND_NEXT_ICON_HTML = lucideIcon(ChevronDown, FIND_ICON_CLASS);
70
+ const FIND_CASE_ICON_HTML = lucideIcon(CaseSensitive, FIND_ICON_CLASS);
71
+ const FIND_CLOSE_ICON_HTML = lucideIcon(X, FIND_ICON_CLASS);
72
+ const OUTLINE_ICON_HTML = lucideIcon(TableOfContents, TOOLBAR_ICON_CLASS);
73
+ // The outline button while the panel shows: a page with the outline's column,
74
+ // and its lines, on the side the panel is on. (Not Lucide's panel-left: that's
75
+ // the contents pane's button.)
76
+ const OUTLINE_SIDE_ICON = (side) => {
77
+ const divider = side === 'left' ? 11 : 13;
78
+ const [from, to] = side === 'left' ? [5.5, 8.5] : [15.5, 18.5];
79
+ return [
80
+ ['rect', { x: 3, y: 3, width: 18, height: 18, rx: 2 }],
81
+ ['path', { d: `M${divider} 3v18` }],
82
+ ...[8, 12, 16].map((y) => ['path', { d: `M${from} ${y}h${to - from}` }])
83
+ ];
84
+ };
85
+ const OUTLINE_LEFT_ICON_HTML = lucideIcon(OUTLINE_SIDE_ICON('left'), `${TOOLBAR_ICON_CLASS} outline-side-icon`);
86
+ const OUTLINE_RIGHT_ICON_HTML = lucideIcon(OUTLINE_SIDE_ICON('right'), `${TOOLBAR_ICON_CLASS} outline-side-icon`);
87
+ const WHITESPACE_ICON_HTML = lucideIcon(Pilcrow, TOOLBAR_ICON_CLASS);
88
+ const FORMAT_JSON_ICON_HTML = lucideIcon(Braces, TOOLBAR_ICON_CLASS);
56
89
  const ZOOM_ICON_HTML = lucideIcon(ZoomIn, TOOLBAR_ICON_CLASS);
57
90
  const DARK_THEME_ICON_HTML = lucideIcon(Moon, TOOLBAR_ICON_CLASS);
58
91
  const LIGHT_THEME_ICON_HTML = lucideIcon(Sun, TOOLBAR_ICON_CLASS);
@@ -107,7 +140,8 @@ const MENU_IMAGE_ICON_HTML = lucideIcon(ImagePlus, MENU_ICON_CLASS);
107
140
  const MENU_LINK_ICON_HTML = lucideIcon(Link, MENU_ICON_CLASS);
108
141
  const MENU_CLEAR_FORMAT_ICON_HTML = lucideIcon(Eraser, MENU_ICON_CLASS);
109
142
  const MENU_HEADING_PARENT_ICON_HTML = lucideIcon(Heading1, MENU_ICON_CLASS);
110
- const MENU_PARAGRAPH_ICON_HTML = lucideIcon(Pilcrow, MENU_ICON_CLASS);
143
+ // Lines of plain text: ¶ is the Show whitespace button's icon.
144
+ const MENU_PARAGRAPH_ICON_HTML = lucideIcon(Text, MENU_ICON_CLASS);
111
145
  const MENU_CHEVRON_ICON_HTML = lucideIcon(ChevronRight, 'nav-menu-chevron');
112
146
  const MENU_HEADING_ICON_HTML = {
113
147
  1: lucideIcon(Heading1, MENU_ICON_CLASS),
@@ -218,6 +252,31 @@ function fileActionTarget(target) {
218
252
  isEntryPoint: target.isEntryPoint
219
253
  };
220
254
  }
255
+ /** A host file action's text for a file. */
256
+ function fileActionLabel(action, file) {
257
+ return typeof action.label === 'function' ? action.label(file) : action.label;
258
+ }
259
+ // What a file the preview can't show is, by extension, for its card.
260
+ const FILE_KIND_NAMES = {
261
+ docx: 'Word document', doc: 'Word document', dotx: 'Word template', dot: 'Word template',
262
+ xlsx: 'Excel workbook', xls: 'Excel workbook', pptx: 'PowerPoint presentation', ppt: 'PowerPoint presentation',
263
+ odt: 'OpenDocument text', ods: 'OpenDocument spreadsheet', odp: 'OpenDocument presentation',
264
+ pdf: 'PDF document', rtf: 'Rich Text document', epub: 'EPUB book', zip: 'ZIP archive',
265
+ drawio: 'draw.io diagram', dio: 'draw.io diagram', psd: 'Photoshop image', ai: 'Illustrator file',
266
+ mp3: 'Audio', wav: 'Audio', mp4: 'Video', mov: 'Video', webm: 'Video',
267
+ ttf: 'Font', otf: 'Font', woff: 'Font', woff2: 'Font'
268
+ };
269
+ function fileKindName(path) {
270
+ const name = path.split('/').pop() ?? path;
271
+ const dot = name.lastIndexOf('.');
272
+ if (dot <= 0)
273
+ return 'File';
274
+ const extension = name.slice(dot + 1).toLowerCase();
275
+ return FILE_KIND_NAMES[extension] ?? `${extension.toUpperCase()} file`;
276
+ }
277
+ // hydrateImages' onSettled for image batches that don't drive onAssetsHydrated
278
+ // (later lazy chunks, Copy All's drain): no progress reported for them.
279
+ const NO_SETTLE = () => { };
221
280
  const ALL_HEADINGS = [1, 2, 3, 4, 5, 6];
222
281
  const ALL_LAYOUT_CONTROLS = {
223
282
  source: true,
@@ -266,6 +325,7 @@ const CONTROL_PRESETS = {
266
325
  formatting: { ...NO_FORMATTING_CONTROLS },
267
326
  contextMenu: { ...ALL_CONTEXT_MENU_CONTROLS },
268
327
  lineNumbers: false,
328
+ whitespace: false,
269
329
  save: false,
270
330
  zoom: false,
271
331
  previewWidth: false,
@@ -273,6 +333,7 @@ const CONTROL_PRESETS = {
273
333
  orphanActions: false,
274
334
  fileActions: false,
275
335
  search: false,
336
+ outline: false,
276
337
  codeBlockTools: true
277
338
  },
278
339
  viewer: {
@@ -284,6 +345,7 @@ const CONTROL_PRESETS = {
284
345
  formatting: { ...NO_FORMATTING_CONTROLS },
285
346
  contextMenu: { ...ALL_CONTEXT_MENU_CONTROLS },
286
347
  lineNumbers: true,
348
+ whitespace: true,
287
349
  save: false,
288
350
  zoom: true,
289
351
  previewWidth: true,
@@ -291,6 +353,7 @@ const CONTROL_PRESETS = {
291
353
  orphanActions: false,
292
354
  fileActions: false,
293
355
  search: true,
356
+ outline: true,
294
357
  codeBlockTools: true
295
358
  },
296
359
  'standalone-editor': {
@@ -302,6 +365,7 @@ const CONTROL_PRESETS = {
302
365
  formatting: { ...ALL_FORMATTING_CONTROLS },
303
366
  contextMenu: { ...ALL_CONTEXT_MENU_CONTROLS },
304
367
  lineNumbers: true,
368
+ whitespace: true,
305
369
  save: true,
306
370
  zoom: true,
307
371
  previewWidth: true,
@@ -309,6 +373,7 @@ const CONTROL_PRESETS = {
309
373
  orphanActions: true,
310
374
  fileActions: true,
311
375
  search: true,
376
+ outline: true,
312
377
  codeBlockTools: true
313
378
  },
314
379
  'hosted-editor': {
@@ -320,6 +385,7 @@ const CONTROL_PRESETS = {
320
385
  formatting: { ...ALL_FORMATTING_CONTROLS },
321
386
  contextMenu: { ...ALL_CONTEXT_MENU_CONTROLS },
322
387
  lineNumbers: true,
388
+ whitespace: true,
323
389
  save: false,
324
390
  zoom: true,
325
391
  previewWidth: true,
@@ -327,6 +393,7 @@ const CONTROL_PRESETS = {
327
393
  orphanActions: true,
328
394
  fileActions: true,
329
395
  search: true,
396
+ outline: true,
330
397
  codeBlockTools: true
331
398
  }
332
399
  };
@@ -442,6 +509,24 @@ function normalizeContentDensity(value) {
442
509
  return value === 'compact' ? value : 'comfortable';
443
510
  }
444
511
  const mdzipEditorTheme = EditorView.theme({
512
+ // Shown whitespace (controls.whitespace): small dots and arrows in the
513
+ // muted text color, so they stay in the background in light and dark.
514
+ '.cm-highlightSpace': {
515
+ backgroundImage: 'radial-gradient(circle at 50% 55%, var(--mdzip-muted-foreground-color, #999) 11%, transparent 13%)',
516
+ opacity: '0.7'
517
+ },
518
+ '.cm-highlightTab': {
519
+ backgroundImage: 'none',
520
+ position: 'relative',
521
+ opacity: '0.7'
522
+ },
523
+ '.cm-highlightTab::before': {
524
+ content: '"→"',
525
+ position: 'absolute',
526
+ left: '0',
527
+ color: 'var(--mdzip-muted-foreground-color, #999)',
528
+ pointerEvents: 'none'
529
+ },
445
530
  '&': {
446
531
  height: '100%',
447
532
  fontSize: 'calc(16px * var(--mdz-zoom, 1))',
@@ -603,6 +688,13 @@ const mdzipMarkdownHighlight = HighlightStyle.define([
603
688
  { tag: tags.contentSeparator, color: '#6a9955' },
604
689
  { tag: tags.atom, color: '#d100d1' },
605
690
  ]);
691
+ // JSON entries (#68), in the same palette as the Markdown style above.
692
+ const mdzipJsonHighlight = HighlightStyle.define([
693
+ { tag: tags.propertyName, color: '#008b8b' },
694
+ { tag: tags.string, color: '#c36f00' },
695
+ { tag: tags.number, color: '#6a9955' },
696
+ { tag: [tags.bool, tags.null], color: '#d100d1' },
697
+ ]);
606
698
  const hardBreakMarkerMatcher = new MatchDecorator({
607
699
  regexp: /<br\s*\/?>/gi,
608
700
  decoration: Decoration.mark({ class: 'mdzip-hard-break-marker' })
@@ -698,6 +790,8 @@ const NON_ARCHIVE_IMAGE_SOURCE_RE = /^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i;
698
790
  // image. `.drawio.svg` and `.drawio.png` end in .svg/.png and stay images.
699
791
  const DRAWIO_PATH_RE = /\.(?:drawio|dio)$/i;
700
792
  const DRAWIO_PLACEHOLDER_CLASS = 'mdzip-drawio-placeholder';
793
+ // In place of a file the preview can't show (mountFileCard).
794
+ const FILE_CARD_CLASS = 'mdzip-file-card';
701
795
  // Preview chrome the editor adds around rendered content: removed, or
702
796
  // unwrapped (children kept), when the selection is copied as HTML.
703
797
  const PREVIEW_CHROME_REMOVE_SELECTOR = [
@@ -819,6 +913,22 @@ function attributesToHtml(attrs) {
819
913
  .map(([key, value]) => ` ${key}="${escapeHtml(String(value))}"`)
820
914
  .join('');
821
915
  }
916
+ // The selection key of the tree row at or around `element`: `f:<path>` for
917
+ // a file, `d:<path>` for a folder's own row (its summary), else null.
918
+ function navRowKey(element) {
919
+ if (!element) {
920
+ return null;
921
+ }
922
+ const file = element.closest('[data-nav-path]');
923
+ if (file) {
924
+ return `f:${file.getAttribute('data-nav-path') ?? ''}`;
925
+ }
926
+ const summary = element.closest('details[data-nav-dir] > summary');
927
+ if (summary) {
928
+ return `d:${summary.parentElement?.getAttribute('data-nav-dir') ?? ''}`;
929
+ }
930
+ return null;
931
+ }
822
932
  // Renders the per-row indent/guide cells: one fixed-width cell per ancestor
823
933
  // depth. An ancestor column draws a continuous vertical rail when that folder
824
934
  // still has siblings below it (so the spine keeps going), otherwise it is
@@ -855,6 +965,7 @@ depth = 0) {
855
965
  : safePath;
856
966
  const classes = [
857
967
  'nav-file',
968
+ options.selected.has(`f:${node.entry.path}`) ? 'nav-selected' : '',
858
969
  isCurrent ? 'current-entry' : '',
859
970
  isOrphaned ? 'orphaned-asset' : '',
860
971
  isEntryPoint ? 'entry-point' : ''
@@ -866,19 +977,19 @@ depth = 0) {
866
977
  : isImageFile(node.entry.path)
867
978
  ? IMAGE_ICON_HTML
868
979
  : FILE_ICON_HTML;
869
- const orphanBtnHtml = isOrphaned && options.allowOrphanActions ? `
870
- <span class="nav-orphan-button" role="button" tabindex="0"
871
- title="Orphaned asset" aria-label="Orphaned asset actions"
872
- data-orphan-path="${safePath}">
873
- ${ORPHAN_ICON_HTML}
980
+ const orphanBtnHtml = isOrphaned && options.allowOrphanActions ? `
981
+ <span class="nav-orphan-button" role="button" tabindex="0"
982
+ title="Orphaned asset" aria-label="Orphaned asset actions"
983
+ data-orphan-path="${safePath}">
984
+ ${ORPHAN_ICON_HTML}
874
985
  </span>` : '';
875
986
  const draggable = options.allowDrag && !isManifest;
876
- return `<button type="button" class="${classes}" title="${title}"
877
- data-nav-path="${safePath}" data-orphan="${isOrphaned ? 'true' : ''}"${draggable ? ' draggable="true"' : ''}>
878
- ${guides}<span class="nav-caret"></span>
879
- <span class="nav-file-icon ${iconKind}">${iconHtml}</span>
880
- ${orphanBtnHtml}
881
- <span class="nav-label">${safeName}</span>
987
+ return `<button type="button" class="${classes}" title="${title}"
988
+ data-nav-path="${safePath}" data-orphan="${isOrphaned ? 'true' : ''}"${draggable ? ' draggable="true"' : ''}>
989
+ ${guides}<span class="nav-caret"></span>
990
+ <span class="nav-file-icon ${iconKind}">${iconHtml}</span>
991
+ ${orphanBtnHtml}
992
+ <span class="nav-label">${safeName}</span>
882
993
  </button>`;
883
994
  }
884
995
  const childTrail = depth === 0 ? [] : [...trail, !isLast];
@@ -886,14 +997,16 @@ depth = 0) {
886
997
  .map((child, index) => renderNavNode(child, state, options, childTrail, index === node.children.length - 1, depth + 1))
887
998
  .join('');
888
999
  const pending = options.pendingFolders.has(node.path);
889
- return `<details class="nav-directory${pending ? ' pending-folder' : ''}" open data-nav-dir="${escapeHtml(node.path)}">
890
- <summary${pending ? ` title="${escapeHtml(node.path)} — not saved until it contains a file"` : ''}>
891
- ${guides}<span class="nav-caret" aria-hidden="true"></span>
892
- <span class="nav-folder-icon closed">${FOLDER_CLOSED_ICON_HTML}</span>
893
- <span class="nav-folder-icon open">${FOLDER_OPEN_ICON_HTML}</span>
894
- <span class="nav-label">${escapeHtml(node.name)}</span>
895
- </summary>
896
- <div class="nav-directory-children">${children}</div>
1000
+ const open = options.collapsed.has(node.path) ? '' : ' open';
1001
+ const selected = options.selected.has(`d:${node.path}`) ? ' class="nav-selected"' : '';
1002
+ return `<details class="nav-directory${pending ? ' pending-folder' : ''}"${open} data-nav-dir="${escapeHtml(node.path)}">
1003
+ <summary${selected}${pending ? ` title="${escapeHtml(node.path)} — not saved until it contains a file"` : ''}>
1004
+ ${guides}<span class="nav-caret" aria-hidden="true"></span>
1005
+ <span class="nav-folder-icon closed">${FOLDER_CLOSED_ICON_HTML}</span>
1006
+ <span class="nav-folder-icon open">${FOLDER_OPEN_ICON_HTML}</span>
1007
+ <span class="nav-label">${escapeHtml(node.name)}</span>
1008
+ </summary>
1009
+ <div class="nav-directory-children">${children}</div>
897
1010
  </details>`;
898
1011
  }
899
1012
  // Inserts view-local pending (not yet saved) folders into the nav tree so they
@@ -1068,6 +1181,14 @@ export class MdzipWorkspaceView {
1068
1181
  this.contextMenuState = null;
1069
1182
  this.nameDialogState = null;
1070
1183
  this.deleteDialogState = null;
1184
+ // Selected rows of the file tree (#69): `f:<path>` / `d:<path>`, in the
1185
+ // order picked, and the row a Shift+click range starts from.
1186
+ this.navSelection = [];
1187
+ this.navSelectionAnchor = null;
1188
+ // Folders the reader closed, kept across the tree's redraws.
1189
+ this.navCollapsed = new Set();
1190
+ // A yes/no question in the editor's own dialog (see askConfirm()).
1191
+ this.confirmDialogState = null;
1071
1192
  this.pendingNewFolders = new Set();
1072
1193
  this.pendingReplacePath = null;
1073
1194
  this.conversionHookPending = false;
@@ -1091,7 +1212,12 @@ export class MdzipWorkspaceView {
1091
1212
  this.cmEditor = null;
1092
1213
  this.readOnlyCompartment = new Compartment();
1093
1214
  this.lineNumbersCompartment = new Compartment();
1215
+ this.whitespaceCompartment = new Compartment();
1094
1216
  this.searchCompartment = new Compartment();
1217
+ this.languageCompartment = new Compartment();
1218
+ this.cmLanguage = 'markdown';
1219
+ this.jsonValidity = null;
1220
+ this.jsonValidityPath = null;
1095
1221
  this.updatingCm = false;
1096
1222
  this.syncing = false;
1097
1223
  // Last value this class itself wrote to each pane's scrollTop, used to
@@ -1099,6 +1225,8 @@ export class MdzipWorkspaceView {
1099
1225
  // syncScrollFromPreview/syncScrollToPreview).
1100
1226
  this.lastSyncedEditorScrollTop = null;
1101
1227
  this.lastSyncedPreviewScrollTop = null;
1228
+ // See splitScrollBlocks().
1229
+ this.splitBlockCache = null;
1102
1230
  // Timestamp of the most recent updatePreview() call (edit-driven or
1103
1231
  // otherwise). A content change that alters a mounted element's rendered
1104
1232
  // height (a chunk reconcile re-rendering a mermaid diagram, an image
@@ -1164,6 +1292,8 @@ export class MdzipWorkspaceView {
1164
1292
  // (images loading or easing open, a diagram rendering) and push it out of
1165
1293
  // view. This holds the target at the pane's top edge until the user
1166
1294
  // scrolls either pane or the preview re-renders.
1295
+ // requestAnimationFrame handle of a smooth scroll to an anchor (see glidePreviewTo).
1296
+ this.previewGlide = null;
1167
1297
  this.anchorPin = null;
1168
1298
  // Each link's own target/rel from before the external-link policy touched
1169
1299
  // it, so a policy change can restore them before re-applying.
@@ -1200,6 +1330,39 @@ export class MdzipWorkspaceView {
1200
1330
  // matches() does not re-run on every snapshot render of the same entry.
1201
1331
  this.entryMatchMissKey = null;
1202
1332
  this.entryGeneration = 0;
1333
+ this.findOpen = false;
1334
+ this.findMatchCase = false;
1335
+ this.findState = null;
1336
+ // Each drawn chunk's text with its nodes, until something in it changes.
1337
+ this.findDomTexts = new WeakMap();
1338
+ // Every chunk's text by its source key, drawn or not, for counting.
1339
+ this.findTextCache = new Map();
1340
+ this.findObserver = null;
1341
+ this.findRefreshQueued = false;
1342
+ this.findIndexing = false;
1343
+ // Goes to the first match once typing pauses, when it isn't drawn yet.
1344
+ this.findRevealTimer = null;
1345
+ this.outlinePosition = 'right';
1346
+ // Null until set by the option or a drag: the style sheet's width applies.
1347
+ this.outlineWidth = null;
1348
+ this.outlineVisible = false;
1349
+ // The outline button's clicks, one after another (see animateOutlineChange).
1350
+ this.outlineButtonTurn = Promise.resolve();
1351
+ this.outlineButtonPending = 0;
1352
+ this.whitespaceVisible = false;
1353
+ // Which parts of the edit toolbar the last render showed (renderFormattingControls).
1354
+ this.formattingShown = false;
1355
+ // The manifest keeps its own layout (form by default); the other files'
1356
+ // layout waits in documentLayout while it's open.
1357
+ this.manifestLayout = 'preview';
1358
+ this.documentLayout = 'preview';
1359
+ this.layoutIsManifest = false;
1360
+ this.manifestForm = null;
1361
+ this.whitespaceControlShown = false;
1362
+ this.formatJsonShown = false;
1363
+ this.outlineOptions = {};
1364
+ this.outline = null;
1365
+ this.outlineGeneration = -1;
1203
1366
  this.pendingAddFilesDir = null;
1204
1367
  this.options = options;
1205
1368
  this.controlPolicy = resolveMdzipControlPolicy(options.controls);
@@ -1216,6 +1379,14 @@ export class MdzipWorkspaceView {
1216
1379
  this.colorSchemePreference = options.initialColorScheme ?? 'system';
1217
1380
  this.colorScheme = this.resolveColorScheme(this.colorSchemePreference);
1218
1381
  this.navVisible = options.navigationButtonActive ?? this.navVisible;
1382
+ this.outlineOptions = typeof options.outline === 'object' ? options.outline : {};
1383
+ this.outlineVisible = typeof options.outline === 'object' ? options.outline.visible ?? false : options.outline ?? false;
1384
+ this.outlinePosition = this.outlineOptions.position === 'left' ? 'left' : 'right';
1385
+ this.outlineWidth = typeof this.outlineOptions.width === 'number' && this.outlineOptions.width > 0
1386
+ ? Math.round(this.outlineOptions.width)
1387
+ : null;
1388
+ this.whitespaceVisible = options.showWhitespace ?? false;
1389
+ this.manifestLayout = options.manifestView === 'json' ? 'source' : 'preview';
1219
1390
  this.markdownRenderer = options.markdownRenderer;
1220
1391
  this.markdownExtensions = options.markdownExtensions ?? [];
1221
1392
  this.frontMatterOptions = options.frontMatter ?? {};
@@ -1241,6 +1412,18 @@ export class MdzipWorkspaceView {
1241
1412
  this.elSourceIcon = q('[data-ref="source-icon"]');
1242
1413
  this.elSaveBtn = q('[data-ref="save-btn"]');
1243
1414
  this.elSearchBtn = q('[data-ref="search-btn"]');
1415
+ this.elFind = q('[data-ref="preview-find"]');
1416
+ this.elFindInput = q('[data-ref="preview-find-input"]');
1417
+ this.elFindCount = q('[data-ref="preview-find-count"]');
1418
+ this.elFindCase = q('[data-ref="preview-find-case"]');
1419
+ this.elFindPrevious = q('[data-ref="preview-find-previous"]');
1420
+ this.elFindNext = q('[data-ref="preview-find-next"]');
1421
+ this.elFindClose = q('[data-ref="preview-find-close"]');
1422
+ this.elOutlineBtn = q('[data-ref="outline-btn"]');
1423
+ this.elWhitespaceBtn = q('[data-ref="whitespace-btn"]');
1424
+ this.elFormatJsonBtn = q('[data-ref="format-json-btn"]');
1425
+ this.elOutlinePane = q('[data-ref="outline-pane"]');
1426
+ this.elOutlineResizer = q('[data-ref="outline-resizer"]');
1244
1427
  this.elZoomBtn = q('[data-ref="zoom-btn"]');
1245
1428
  this.elWidthControls = q('[data-ref="width-controls"]');
1246
1429
  this.elWidthMenuBtn = q('[data-ref="width-menu-btn"]');
@@ -1264,6 +1447,7 @@ export class MdzipWorkspaceView {
1264
1447
  this.elEditToolbar = q('[data-ref="edit-toolbar"]');
1265
1448
  this.elImageInput = q('[data-ref="image-input"]');
1266
1449
  this.elEditorHost = q('[data-ref="editor-host"]');
1450
+ this.elJsonStatus = q('[data-ref="json-status"]');
1267
1451
  this.elSplitResizer = q('[data-ref="split-resizer"]');
1268
1452
  this.elPreviewPane = q('[data-ref="preview-pane"]');
1269
1453
  this.elPreviewContent = q('[data-ref="preview-content"]');
@@ -1309,6 +1493,10 @@ export class MdzipWorkspaceView {
1309
1493
  this.elNameValidation = q('[data-ref="name-validation"]');
1310
1494
  this.elNameConfirmBtn = q('[data-ref="name-confirm-btn"]');
1311
1495
  this.elDeleteDialog = q('[data-ref="delete-dialog"]');
1496
+ this.elConfirmDialog = q('[data-ref="confirm-dialog"]');
1497
+ this.elConfirmDialogTitle = q('[data-ref="confirm-dialog-title"]');
1498
+ this.elConfirmDialogText = q('[data-ref="confirm-dialog-text"]');
1499
+ this.elConfirmDialogOk = q('[data-ref="confirm-dialog-ok"]');
1312
1500
  this.elDeleteDialogText = q('[data-ref="delete-dialog-text"]');
1313
1501
  this.elDeleteConfirmBtn = q('[data-ref="delete-confirm-btn"]');
1314
1502
  this.elReplaceInput = q('[data-ref="replace-input"]');
@@ -1552,11 +1740,12 @@ export class MdzipWorkspaceView {
1552
1740
  return true;
1553
1741
  }
1554
1742
  /**
1555
- * Opens CodeMirror's find/replace panel for the current document. Unlike
1556
- * {@link executeCommand}, this works in read-only (Viewer) hosts too —
1557
- * searching doesn't require edit access, only a visible source pane. If
1558
- * the current layout is preview-only, switches to split/source first so
1559
- * the panel has somewhere to render.
1743
+ * Opens find for the current document. In the View layout it's a find
1744
+ * bar over the preview that searches the rendered text, the whole
1745
+ * document including parts not drawn yet, and leaves the layout as it is.
1746
+ * In Edit and Split it's CodeMirror's find/replace panel. Works in
1747
+ * read-only (Viewer) hosts too. When the preview belongs to an entry
1748
+ * renderer, switches to split/source for the panel.
1560
1749
  */
1561
1750
  async openSearch() {
1562
1751
  if (!this.controlPolicy.search) {
@@ -1566,6 +1755,10 @@ export class MdzipWorkspaceView {
1566
1755
  if (!snapshot || snapshot.currentPathType !== 'markdown') {
1567
1756
  return false;
1568
1757
  }
1758
+ if (this.findApplies(snapshot)) {
1759
+ this.openFind();
1760
+ return true;
1761
+ }
1569
1762
  if (this.layout === 'preview') {
1570
1763
  const nextLayout = this.controlPolicy.layout.split
1571
1764
  ? 'split'
@@ -1583,8 +1776,357 @@ export class MdzipWorkspaceView {
1583
1776
  return openSearchPanel(editor);
1584
1777
  }
1585
1778
  closeSearch() {
1779
+ if (this.findOpen) {
1780
+ return this.closeFind();
1781
+ }
1586
1782
  return this.cmEditor ? closeSearchPanel(this.cmEditor) : false;
1587
1783
  }
1784
+ /** Whether the find bar is open over the preview. */
1785
+ get isFindOpen() {
1786
+ return this.findOpen;
1787
+ }
1788
+ // --- Find in the preview (#62) ---------------------------------------------------
1789
+ findApplies(snapshot = this.workspace?.snapshot()) {
1790
+ return !!snapshot && this.controlPolicy.search && this.layout === 'preview'
1791
+ && snapshot.currentPathType === 'markdown' && !this.entryState;
1792
+ }
1793
+ openFind() {
1794
+ const doc = this.elRoot.ownerDocument;
1795
+ // Like a browser: a short selection in the document becomes the query.
1796
+ const selection = doc.getSelection?.();
1797
+ if (selection && selection.rangeCount && selection.anchorNode && this.elPreviewContent.contains(selection.anchorNode)) {
1798
+ const selected = selection.toString().trim();
1799
+ if (selected && selected.length <= 200 && !/\n/.test(selected)) {
1800
+ this.elFindInput.value = selected;
1801
+ }
1802
+ }
1803
+ this.findOpen = true;
1804
+ this.elFind.hidden = false;
1805
+ this.elSearchBtn.classList.add('active');
1806
+ this.elFindInput.focus();
1807
+ this.elFindInput.select();
1808
+ if (!this.findObserver && typeof MutationObserver !== 'undefined') {
1809
+ this.findObserver = new MutationObserver((records) => {
1810
+ for (const record of records) {
1811
+ const target = record.target.nodeType === 1 ? record.target : record.target.parentElement;
1812
+ const root = target?.closest('.mdzip-chunk') ?? this.elPreviewContent;
1813
+ this.findDomTexts.delete(root);
1814
+ }
1815
+ this.scheduleFindRefresh();
1816
+ });
1817
+ this.findObserver.observe(this.elPreviewContent, { childList: true, subtree: true, characterData: true });
1818
+ }
1819
+ this.refreshFind('viewport');
1820
+ this.revealFindMatchSoon();
1821
+ }
1822
+ // When the current match is in a chunk not drawn yet, draws it and goes
1823
+ // there once typing pauses (the next keystroke starts the wait again).
1824
+ revealFindMatchSoon() {
1825
+ if (this.findRevealTimer !== null) {
1826
+ clearTimeout(this.findRevealTimer);
1827
+ }
1828
+ this.findRevealTimer = setTimeout(() => {
1829
+ this.findRevealTimer = null;
1830
+ void this.moveFind(0);
1831
+ }, 300);
1832
+ }
1833
+ closeFind(restoreFocus = true) {
1834
+ if (!this.findOpen) {
1835
+ return false;
1836
+ }
1837
+ const doc = this.elRoot.ownerDocument;
1838
+ const hadFocus = this.elFind.contains(doc.activeElement);
1839
+ this.findOpen = false;
1840
+ if (this.findRevealTimer !== null) {
1841
+ clearTimeout(this.findRevealTimer);
1842
+ this.findRevealTimer = null;
1843
+ }
1844
+ this.elFind.hidden = true;
1845
+ this.elSearchBtn.classList.remove('active');
1846
+ this.findState = null;
1847
+ this.findObserver?.disconnect();
1848
+ this.findObserver = null;
1849
+ this.findDomTexts = new WeakMap();
1850
+ setFindHighlights(doc, this, [], null);
1851
+ if (restoreFocus && hadFocus) {
1852
+ this.elPreviewPane.focus({ preventScroll: true });
1853
+ }
1854
+ return true;
1855
+ }
1856
+ scheduleFindRefresh() {
1857
+ if (this.findRefreshQueued) {
1858
+ return;
1859
+ }
1860
+ this.findRefreshQueued = true;
1861
+ requestAnimationFrame(() => {
1862
+ this.findRefreshQueued = false;
1863
+ this.refreshFind('keep');
1864
+ });
1865
+ }
1866
+ // The chunks of the document, drawn or not. Without chunks (a custom
1867
+ // renderer), the whole preview is one.
1868
+ findChunks() {
1869
+ const state = this.chunkedRenderState;
1870
+ if (!state) {
1871
+ return [{ key: null, root: this.elPreviewContent, index: 0 }];
1872
+ }
1873
+ return state.records.map((record, index) => ({
1874
+ key: record.key,
1875
+ root: record.root && record.root.isConnected ? record.root : null,
1876
+ index
1877
+ }));
1878
+ }
1879
+ /**
1880
+ * Matches the query against every chunk's text and repaints. `viewport`
1881
+ * (a new query) makes the first match at or below the top of the pane
1882
+ * current and scrolls to it; `keep` (the document changed under the bar)
1883
+ * keeps the current match.
1884
+ */
1885
+ refreshFind(mode, scroll = mode === 'viewport') {
1886
+ if (!this.findOpen || this.destroyed) {
1887
+ return;
1888
+ }
1889
+ const previous = this.findState;
1890
+ const pattern = findPattern(this.elFindInput.value, this.findMatchCase);
1891
+ const matches = [];
1892
+ const texts = [];
1893
+ let pending = false;
1894
+ const chunks = this.findChunks();
1895
+ if (pattern) {
1896
+ for (const chunk of chunks) {
1897
+ let dom = null;
1898
+ let text;
1899
+ if (chunk.root) {
1900
+ dom = this.findDomTexts.get(chunk.root) ?? null;
1901
+ if (!dom) {
1902
+ dom = collectFindText(chunk.root);
1903
+ this.findDomTexts.set(chunk.root, dom);
1904
+ }
1905
+ text = dom.text;
1906
+ if (chunk.key !== null) {
1907
+ this.findTextCache.set(chunk.key, text);
1908
+ }
1909
+ }
1910
+ else if (chunk.key !== null) {
1911
+ text = this.findTextCache.get(chunk.key);
1912
+ }
1913
+ texts.push(dom);
1914
+ if (text === undefined) {
1915
+ pending = true;
1916
+ continue;
1917
+ }
1918
+ let ordinal = 0;
1919
+ for (const [start, end] of findMatches(text, pattern)) {
1920
+ matches.push({ chunk: chunk.index, ordinal: ordinal++, start, end });
1921
+ }
1922
+ }
1923
+ }
1924
+ let current = -1;
1925
+ if (matches.length) {
1926
+ const was = mode === 'keep' && previous && previous.current >= 0 ? previous.matches[previous.current] : null;
1927
+ if (was) {
1928
+ current = matches.findIndex((match) => match.chunk === was.chunk && match.ordinal === was.ordinal);
1929
+ if (current < 0) {
1930
+ current = Math.min(previous.current, matches.length - 1);
1931
+ }
1932
+ }
1933
+ else {
1934
+ current = this.firstFindMatchInView(matches, chunks, texts);
1935
+ // A first match (perhaps found by the background count): show it,
1936
+ // drawing its chunk first when it isn't yet.
1937
+ scroll = true;
1938
+ if (!texts[matches[current].chunk]) {
1939
+ this.revealFindMatchSoon();
1940
+ }
1941
+ }
1942
+ }
1943
+ this.findState = { matches, current, pending, texts };
1944
+ this.paintFind(scroll);
1945
+ if (pending) {
1946
+ this.indexFindChunks();
1947
+ }
1948
+ }
1949
+ // The first match at or below the top of the preview pane, or the first.
1950
+ firstFindMatchInView(matches, chunks, texts) {
1951
+ const paneTop = this.elPreviewPane.getBoundingClientRect().top;
1952
+ let skipped = -1;
1953
+ for (let i = 0; i < matches.length; i += 1) {
1954
+ const match = matches[i];
1955
+ const root = chunks[match.chunk]?.root;
1956
+ const dom = texts[match.chunk];
1957
+ if (!root || !dom) {
1958
+ // Not drawn yet: below what is.
1959
+ return i;
1960
+ }
1961
+ if (match.chunk === skipped) {
1962
+ continue;
1963
+ }
1964
+ if (root.getBoundingClientRect().bottom < paneTop) {
1965
+ skipped = match.chunk;
1966
+ continue;
1967
+ }
1968
+ const range = findRange(dom, match.start, match.end);
1969
+ if (!range || typeof range.getBoundingClientRect !== 'function' || range.getBoundingClientRect().top >= paneTop - 1) {
1970
+ return i;
1971
+ }
1972
+ }
1973
+ return 0;
1974
+ }
1975
+ // Highlights the matches near the current one (all of them, up to a
1976
+ // thousand) and the current one, and updates the count.
1977
+ paintFind(scroll) {
1978
+ const state = this.findState;
1979
+ const all = [];
1980
+ let currentRange = null;
1981
+ if (state && state.current >= 0) {
1982
+ const from = Math.max(0, state.current - 500);
1983
+ const to = Math.min(state.matches.length, state.current + 500);
1984
+ for (let i = from; i < to; i += 1) {
1985
+ const match = state.matches[i];
1986
+ const dom = state.texts[match.chunk];
1987
+ const range = dom ? findRange(dom, match.start, match.end) : null;
1988
+ if (!range) {
1989
+ continue;
1990
+ }
1991
+ if (i === state.current) {
1992
+ currentRange = range;
1993
+ }
1994
+ else {
1995
+ all.push(range);
1996
+ }
1997
+ }
1998
+ }
1999
+ setFindHighlights(this.elRoot.ownerDocument, this, all, currentRange);
2000
+ const query = this.elFindInput.value.trim();
2001
+ const total = state?.matches.length ?? 0;
2002
+ let label = '';
2003
+ if (query && state) {
2004
+ if (!total) {
2005
+ label = state.pending ? 'Searching…' : 'No results';
2006
+ }
2007
+ else {
2008
+ label = `${state.current + 1} of ${total}${state.pending ? '+' : ''}`;
2009
+ }
2010
+ }
2011
+ this.elFindCount.textContent = label;
2012
+ this.elFind.classList.toggle('no-results', !!query && !!state && !total && !state.pending);
2013
+ this.elFindPrevious.disabled = total === 0;
2014
+ this.elFindNext.disabled = total === 0;
2015
+ if (scroll && currentRange) {
2016
+ this.scrollFindRangeIntoView(currentRange);
2017
+ }
2018
+ }
2019
+ scrollFindRangeIntoView(range) {
2020
+ if (typeof range.getBoundingClientRect !== 'function') {
2021
+ return;
2022
+ }
2023
+ const pane = this.elPreviewPane;
2024
+ const rect = range.getBoundingClientRect();
2025
+ const paneRect = pane.getBoundingClientRect();
2026
+ // Below the find bar, above the bottom edge.
2027
+ if (rect.top >= paneRect.top + this.elFind.offsetHeight + 16 && rect.bottom <= paneRect.bottom - 16) {
2028
+ return;
2029
+ }
2030
+ this.releaseAnchorPin();
2031
+ pane.scrollTop += rect.top - paneRect.top - pane.clientHeight / 3;
2032
+ }
2033
+ /**
2034
+ * Goes to the next (1) or previous (-1) match, drawing its chunk first
2035
+ * when it isn't yet. A current match that hasn't been shown (its chunk
2036
+ * isn't drawn) is gone to first, not skipped; 0 only does that.
2037
+ */
2038
+ async moveFind(delta) {
2039
+ const state = this.findState;
2040
+ if (!this.findOpen || !state || !state.matches.length) {
2041
+ return;
2042
+ }
2043
+ const total = state.matches.length;
2044
+ const unseen = state.current >= 0 && !state.texts[state.matches[state.current].chunk];
2045
+ if (!unseen) {
2046
+ if (delta === 0) {
2047
+ return;
2048
+ }
2049
+ const from = state.current < 0 ? (delta > 0 ? -1 : 0) : state.current;
2050
+ state.current = (from + delta + total) % total;
2051
+ }
2052
+ const match = state.matches[state.current];
2053
+ if (!state.texts[match.chunk]) {
2054
+ await this.mountChunksThrough(match.chunk);
2055
+ this.findDomTexts = new WeakMap();
2056
+ this.refreshFind('keep', true);
2057
+ return;
2058
+ }
2059
+ this.paintFind(true);
2060
+ }
2061
+ // Draws the chunks up to and including `index`, as scrollToAnchor() does.
2062
+ async mountChunksThrough(index) {
2063
+ const pending = this.chunkedRenderState;
2064
+ if (!pending || pending.cursor > index) {
2065
+ return;
2066
+ }
2067
+ await this.drainRemainingChunks(pending, () => { }, new AbortController().signal, index);
2068
+ const remaining = this.chunkedRenderState;
2069
+ if (remaining && remaining.generation === pending.generation && !remaining.sentinelHandle
2070
+ && remaining.cursor < remaining.records.length) {
2071
+ this.armChunkSentinel(remaining.records, remaining.cursor, remaining.context, remaining.generation, remaining.animateImageHydration);
2072
+ }
2073
+ }
2074
+ /**
2075
+ * Finds the text of chunks not drawn yet, a few at a time between frames,
2076
+ * so the count covers the whole document: each chunk's HTML (cached, or
2077
+ * rendered) in a detached fragment, read the same way as the preview.
2078
+ */
2079
+ indexFindChunks() {
2080
+ const state = this.chunkedRenderState;
2081
+ if (this.findIndexing || !state) {
2082
+ return;
2083
+ }
2084
+ this.findIndexing = true;
2085
+ const records = state.records;
2086
+ const generation = state.generation;
2087
+ const live = new Set(records.map((record) => record.key));
2088
+ for (const key of Array.from(this.findTextCache.keys())) {
2089
+ if (!live.has(key)) {
2090
+ this.findTextCache.delete(key);
2091
+ }
2092
+ }
2093
+ const run = async () => {
2094
+ let batchStart = performance.now();
2095
+ for (let i = 0; i < records.length; i += 1) {
2096
+ if (!this.findOpen || this.destroyed || this.chunkedRenderState?.records !== records) {
2097
+ return;
2098
+ }
2099
+ const record = records[i];
2100
+ if ((record.root && record.root.isConnected) || this.findTextCache.has(record.key)) {
2101
+ continue;
2102
+ }
2103
+ let html = record.html
2104
+ ?? (this.chunkHtmlCache?.generation === generation ? this.chunkHtmlCache.html.get(i) : undefined);
2105
+ if (html === undefined) {
2106
+ const result = this.renderingService.renderChunk(record.tokens, state.context, { index: i, markBlocks: true });
2107
+ html = typeof result === 'string' ? result : await result;
2108
+ }
2109
+ this.findTextCache.set(record.key, collectFindText(this.inertPreviewFragment(html)).text);
2110
+ if (performance.now() - batchStart > 12) {
2111
+ this.refreshFind('keep', false);
2112
+ await new Promise((resolve) => requestAnimationFrame(() => resolve()));
2113
+ batchStart = performance.now();
2114
+ }
2115
+ }
2116
+ };
2117
+ void run()
2118
+ .catch((error) => {
2119
+ if (error?.name !== 'AbortError') {
2120
+ this.options.onFailed?.(error);
2121
+ }
2122
+ })
2123
+ .finally(() => {
2124
+ this.findIndexing = false;
2125
+ if (this.findOpen && !this.destroyed && this.chunkedRenderState?.records === records) {
2126
+ this.refreshFind('keep', false);
2127
+ }
2128
+ });
2129
+ }
1588
2130
  async convertToMdz() {
1589
2131
  if (!this.workspace || this.workspace.mode === 'read-only') {
1590
2132
  return false;
@@ -1603,6 +2145,7 @@ export class MdzipWorkspaceView {
1603
2145
  this.cmEditor?.focus();
1604
2146
  }
1605
2147
  destroy() {
2148
+ this.closeFind(false);
1606
2149
  this.systemColorSchemeQuery?.removeEventListener?.('change', this.onSystemColorSchemeChange);
1607
2150
  this.conversionDocumentGeneration += 1;
1608
2151
  this.resolveImageInsertDialog(null);
@@ -1616,6 +2159,8 @@ export class MdzipWorkspaceView {
1616
2159
  this.resetPreviewState();
1617
2160
  this.replaceAssetSession(null);
1618
2161
  this.teardownEntryRenderer();
2162
+ this.outline?.destroy();
2163
+ this.outline = null;
1619
2164
  // Release any whenRendered() waiters so their promises do not hang.
1620
2165
  this.flushRenderedWaiters();
1621
2166
  this.destroyed = true;
@@ -2039,7 +2584,19 @@ export class MdzipWorkspaceView {
2039
2584
  this.fireAssetsHydrated(snapshot, generation);
2040
2585
  }).catch((error) => this.options.onFailed?.(error));
2041
2586
  }
2587
+ else if (this.isManifestFormPath(snapshot)) {
2588
+ this.mountManifestForm(snapshot);
2589
+ this.firePreviewRendered(snapshot, generation);
2590
+ this.fireAssetsHydrated(snapshot, generation);
2591
+ }
2592
+ else if (snapshot.currentPathType === 'binary') {
2593
+ this.manifestForm = null;
2594
+ this.mountFileCard(snapshot);
2595
+ this.firePreviewRendered(snapshot, generation);
2596
+ this.fireAssetsHydrated(snapshot, generation);
2597
+ }
2042
2598
  else {
2599
+ this.manifestForm = null;
2043
2600
  this.elPreviewContent.innerHTML = renderMdzipPreviewHtml(snapshot);
2044
2601
  this.firePreviewRendered(snapshot, generation);
2045
2602
  this.fireAssetsHydrated(snapshot, generation);
@@ -2230,6 +2787,115 @@ export class MdzipWorkspaceView {
2230
2787
  image.replaceWith(host);
2231
2788
  return host;
2232
2789
  }
2790
+ /**
2791
+ * In place of a file the preview can't show (a Word document, a ZIP): a
2792
+ * card naming it and what it is, with a button for each host file action
2793
+ * that applies to it (the `primary` one first, such as "Open in Word"),
2794
+ * then Extract… (or Download) and, in an editable document, Replace….
2795
+ */
2796
+ mountFileCard(snapshot) {
2797
+ const doc = this.elPreviewContent.ownerDocument;
2798
+ const el = (tag, className, text) => {
2799
+ const node = doc.createElement(tag);
2800
+ if (className)
2801
+ node.className = className;
2802
+ if (text !== undefined)
2803
+ node.textContent = text;
2804
+ return node;
2805
+ };
2806
+ const path = snapshot.currentPath;
2807
+ const fileName = path.split('/').pop() ?? path;
2808
+ const target = { path, isMarkdown: false, isImage: false, isManifest: false, isEntryPoint: false };
2809
+ const card = el('div', FILE_CARD_CLASS);
2810
+ card.setAttribute('role', 'group');
2811
+ card.setAttribute('aria-label', fileName);
2812
+ const icon = el('span', `${FILE_CARD_CLASS}-icon`);
2813
+ icon.setAttribute('aria-hidden', 'true');
2814
+ icon.innerHTML = '<svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round">'
2815
+ + '<path d="M14 2.5H6.5a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V8z"/><path d="M14 2.5V8h5.5"/></svg>';
2816
+ const body = el('div', `${FILE_CARD_CLASS}-body`);
2817
+ body.append(el('strong', `${FILE_CARD_CLASS}-title`, fileName), el('span', `${FILE_CARD_CLASS}-file`, `${fileKindName(path)} · ${path}`), el('span', `${FILE_CARD_CLASS}-text`, "The preview can't show this kind of file."));
2818
+ const note = this.options.fileNote?.(target) ?? null;
2819
+ if (note) {
2820
+ const noteEl = el('span', `${FILE_CARD_CLASS}-note`, note);
2821
+ noteEl.setAttribute('role', 'status');
2822
+ body.append(noteEl);
2823
+ }
2824
+ const row = el('div', `${FILE_CARD_CLASS}-actions`);
2825
+ // What each button does, listed under them in the same order.
2826
+ const explained = [];
2827
+ const addButton = (label, run, primary = false, action = '', description = '') => {
2828
+ if (description)
2829
+ explained.push([label, description]);
2830
+ const button = el('button', `${FILE_CARD_CLASS}-action${primary ? ` ${FILE_CARD_CLASS}-primary` : ''}`, label);
2831
+ button.type = 'button';
2832
+ if (action)
2833
+ button.dataset['fileCardAction'] = action;
2834
+ button.addEventListener('click', () => {
2835
+ void Promise.resolve()
2836
+ .then(run)
2837
+ .catch((error) => this.options.onFailed?.(error));
2838
+ });
2839
+ row.append(button);
2840
+ };
2841
+ const hostActions = (this.options.hostFileActions ?? [])
2842
+ .filter((item) => item.appliesTo?.(target) ?? true)
2843
+ .sort((a, b) => Number(!!b.primary) - Number(!!a.primary));
2844
+ for (const action of hostActions) {
2845
+ const description = typeof action.description === 'function' ? action.description(target) : (action.description ?? '');
2846
+ addButton(fileActionLabel(action, target), () => action.run(target), !!action.primary, `${HOST_FILE_ACTION_PREFIX}${action.id}`, description);
2847
+ }
2848
+ const navTarget = { kind: 'file', orphaned: false, ...target };
2849
+ for (const item of this.extractMenuItems('one', false)) {
2850
+ addButton(item.label, () => item.action === 'download'
2851
+ ? this.downloadArchiveFile(path)
2852
+ : this.extractNavTarget(navTarget, item.action), false, item.action, item.action === 'download'
2853
+ ? "Downloads a copy of the file. The document isn't changed."
2854
+ : "Saves a copy of the file outside the document, to open or change in another app. The document isn't changed.");
2855
+ }
2856
+ if (this.allowFileActions(snapshot)) {
2857
+ addButton('Replace…', () => {
2858
+ this.pendingReplacePath = path;
2859
+ this.elReplaceInput.click();
2860
+ }, false, 'replace', `Puts a file you choose in its place, still named ${fileName}. Save the document to keep it.`);
2861
+ }
2862
+ body.append(row);
2863
+ if (explained.length) {
2864
+ const list = el('ul', `${FILE_CARD_CLASS}-explain`);
2865
+ for (const [label, description] of explained) {
2866
+ const item = el('li', '');
2867
+ item.append(el('strong', '', label), doc.createTextNode(` ${description}`));
2868
+ list.append(item);
2869
+ }
2870
+ body.append(list);
2871
+ }
2872
+ const help = this.options.fileCardHelp;
2873
+ if (help) {
2874
+ const link = el('button', `${FILE_CARD_CLASS}-help`, help.label);
2875
+ link.type = 'button';
2876
+ link.addEventListener('click', () => {
2877
+ void Promise.resolve()
2878
+ .then(() => help.run(target))
2879
+ .catch((error) => this.options.onFailed?.(error));
2880
+ });
2881
+ body.append(link);
2882
+ }
2883
+ card.append(icon, body);
2884
+ this.elPreviewContent.replaceChildren(card);
2885
+ }
2886
+ /**
2887
+ * Asks the host's file actions and {@link MdzipWorkspaceViewOptions.fileNote}
2888
+ * again, for the card of a file the preview can't show: call it when a
2889
+ * label or note would now be different (the file was opened in another
2890
+ * app, or the app that opens it is now known). The contents pane's menu
2891
+ * asks each time it opens.
2892
+ */
2893
+ refreshFileActions() {
2894
+ const snapshot = this.workspace?.snapshot();
2895
+ if (snapshot?.currentPathType === 'binary' && this.elPreviewContent.querySelector(`.${FILE_CARD_CLASS}`)) {
2896
+ this.mountFileCard(snapshot);
2897
+ }
2898
+ }
2233
2899
  /**
2234
2900
  * Replaces an image of a raw draw.io diagram (`.drawio`, `.dio`) with a card
2235
2901
  * saying what it is, why the preview can't draw it yet (#59) and how to show
@@ -2269,7 +2935,7 @@ export class MdzipWorkspaceView {
2269
2935
  if (actions.length) {
2270
2936
  const row = el('span', `${DRAWIO_PLACEHOLDER_CLASS}-actions`);
2271
2937
  for (const action of actions) {
2272
- const button = el('button', `${DRAWIO_PLACEHOLDER_CLASS}-action`, action.label);
2938
+ const button = el('button', `${DRAWIO_PLACEHOLDER_CLASS}-action`, fileActionLabel(action, target));
2273
2939
  button.type = 'button';
2274
2940
  button.addEventListener('click', () => {
2275
2941
  void Promise.resolve()
@@ -2372,12 +3038,27 @@ export class MdzipWorkspaceView {
2372
3038
  }
2373
3039
  const document = this.elPreviewContent.ownerDocument;
2374
3040
  let remaining = pending.length;
3041
+ // Progress only for the batch that drives onAssetsHydrated (a later lazy
3042
+ // chunk's images pass a no-op onSettled; see the doc comment above).
3043
+ const reportsProgress = onSettled !== NO_SETTLE;
3044
+ const progress = () => {
3045
+ if (!reportsProgress || generation !== this.previewGeneration)
3046
+ return;
3047
+ try {
3048
+ this.options.onAssetsProgress?.({ loaded: pending.length - remaining, total: pending.length });
3049
+ }
3050
+ catch (error) {
3051
+ this.options.onFailed?.(error);
3052
+ }
3053
+ };
2375
3054
  const settle = () => {
2376
3055
  remaining -= 1;
3056
+ progress();
2377
3057
  if (remaining === 0) {
2378
3058
  onSettled();
2379
3059
  }
2380
3060
  };
3061
+ progress();
2381
3062
  const createImageSlot = (image) => {
2382
3063
  const slot = document.createElement('span');
2383
3064
  slot.className = animateImageHydration
@@ -2454,6 +3135,26 @@ export class MdzipWorkspaceView {
2454
3135
  }
2455
3136
  return;
2456
3137
  }
3138
+ // eagerImages: every image now, not as it nears the visible area; still
3139
+ // a few at a time per frame, as below, so a long document stays responsive.
3140
+ if (this.options.eagerImages === true) {
3141
+ let next = 0;
3142
+ const hydrateChunk = () => {
3143
+ if (generation !== this.previewGeneration || context.signal.aborted)
3144
+ return;
3145
+ const chunkStart = observerWindow.performance.now();
3146
+ while (next < pending.length && observerWindow.performance.now() - chunkStart < 8) {
3147
+ const item = pending[next];
3148
+ next += 1;
3149
+ hydrate(item.image, createImageSlot(item.image), item.source);
3150
+ }
3151
+ if (next < pending.length) {
3152
+ observerWindow.requestAnimationFrame(hydrateChunk);
3153
+ }
3154
+ };
3155
+ hydrateChunk();
3156
+ return;
3157
+ }
2457
3158
  const bySlot = new Map();
2458
3159
  const observer = new observerWindow.IntersectionObserver((entries) => {
2459
3160
  for (const entry of entries) {
@@ -2909,7 +3610,7 @@ export class MdzipWorkspaceView {
2909
3610
  html = cacheHit;
2910
3611
  }
2911
3612
  else {
2912
- const result = this.renderingService.renderChunk(chunkTokens, context, { index: chunkIndex });
3613
+ const result = this.renderingService.renderChunk(chunkTokens, context, { index: chunkIndex, markBlocks: true });
2913
3614
  html = typeof result === 'string' ? result : await result;
2914
3615
  }
2915
3616
  }
@@ -3007,7 +3708,7 @@ export class MdzipWorkspaceView {
3007
3708
  this.chunkedRenderState.mounting = true;
3008
3709
  liveContext = this.chunkedRenderState.context;
3009
3710
  }
3010
- void this.mountChunkBatch(records, nextCursor, liveContext, generation, animateImageHydration, () => { })
3711
+ void this.mountChunkBatch(records, nextCursor, liveContext, generation, animateImageHydration, NO_SETTLE)
3011
3712
  .then((newCursor) => {
3012
3713
  // Record whatever this batch actually mounted regardless of
3013
3714
  // whether a newer edit has since landed — recordChunkProgress's
@@ -3298,6 +3999,7 @@ export class MdzipWorkspaceView {
3298
3999
  this.restorePendingPreviewScroll(generation);
3299
4000
  this.flushPendingAnchorSoon();
3300
4001
  this.markPreviewMounted();
4002
+ this.refreshOutline();
3301
4003
  this.firingPreviewRendered = true;
3302
4004
  try {
3303
4005
  this.options.onPreviewRendered?.(snapshot);
@@ -3542,6 +4244,7 @@ export class MdzipWorkspaceView {
3542
4244
  doc: initialText,
3543
4245
  extensions: [
3544
4246
  this.lineNumbersCompartment.of(this.controlPolicy.lineNumbers ? lineNumbers() : []),
4247
+ this.whitespaceCompartment.of(this.whitespaceVisible ? highlightWhitespace() : []),
3545
4248
  this.searchCompartment.of(this.controlPolicy.search ? [search({ top: true }), keymap.of(searchKeymap)] : []),
3546
4249
  history(),
3547
4250
  keymap.of([
@@ -3550,7 +4253,7 @@ export class MdzipWorkspaceView {
3550
4253
  { key: 'Mod-k', run: () => self.runFormatShortcut('link') }
3551
4254
  ]),
3552
4255
  keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
3553
- markdown(),
4256
+ this.languageCompartment.of(markdown()),
3554
4257
  syntaxHighlighting(mdzipMarkdownHighlight),
3555
4258
  hardBreakMarkerHighlight,
3556
4259
  htmlTagMarkerHighlight,
@@ -3666,7 +4369,10 @@ export class MdzipWorkspaceView {
3666
4369
  || !canShowSourceLayout(snapshot)) {
3667
4370
  return this.cmEditor;
3668
4371
  }
4372
+ this.cmLanguage = 'markdown';
4373
+ this.jsonValidityPath = null;
3669
4374
  this.cmEditor = this.createCmEditor(this.elEditorHost, snapshot.currentText, snapshot.mode);
4375
+ this.syncEditorLanguage(snapshot);
3670
4376
  return this.cmEditor;
3671
4377
  }
3672
4378
  render() {
@@ -3695,6 +4401,7 @@ export class MdzipWorkspaceView {
3695
4401
  this.elToolbar.hidden = true;
3696
4402
  return;
3697
4403
  }
4404
+ this.swapManifestLayout(snapshot);
3698
4405
  this.layout = this.validLayoutForSnapshot(this.layout, snapshot);
3699
4406
  const entryClaimed = this.syncEntryRenderer(snapshot);
3700
4407
  const canEdit = !entryClaimed
@@ -3713,29 +4420,48 @@ export class MdzipWorkspaceView {
3713
4420
  if (!showWidthControl) {
3714
4421
  this.widthMenuOpen = false;
3715
4422
  }
3716
- const showSearchControl = this.controlPolicy.search
3717
- && canShowSource && snapshot.currentPathType === 'markdown';
4423
+ // Only where the source editor shows: Edit or Split, for a file it can edit.
4424
+ const showWhitespaceControl = this.controlPolicy.whitespace && !entryClaimed
4425
+ && canShowSource && this.shownLayout(snapshot) !== 'preview';
4426
+ const showSearchControl = this.controlPolicy.search && snapshot.currentPathType === 'markdown'
4427
+ && (canShowSource || this.findApplies(snapshot));
4428
+ if (this.findOpen && !this.findApplies(snapshot)) {
4429
+ this.closeFind(false);
4430
+ }
4431
+ const showOutlineControl = this.controlPolicy.outline && !entryClaimed
4432
+ && snapshot.currentPathType === 'markdown' && this.layout !== 'source';
3718
4433
  const showEditControls = canEdit
3719
4434
  && snapshot.currentPathType === 'markdown'
3720
4435
  && this.layout !== 'preview'
3721
4436
  && hasFormattingControls(this.controlPolicy.formatting);
3722
4437
  const showToolbar = this.controlPolicy.toolbar
3723
4438
  && (showNavigationControl || showLayoutControls || showSaveControl
3724
- || showZoomControl || showWidthControl || showColorSchemeControl || showSearchControl
3725
- || showEditControls);
4439
+ || showZoomControl || showWidthControl || showColorSchemeControl || showSearchControl || showWhitespaceControl
4440
+ || showOutlineControl || showEditControls);
3726
4441
  this.elDocumentStrip.hidden = !showTitleControl;
3727
4442
  this.elToolbar.hidden = !showToolbar;
3728
4443
  this.elToolbarLeft.hidden = !showNavigationControl;
3729
- this.elEditToolbar.hidden = !showEditControls;
4444
+ const showFormatJsonControl = canEdit && isMdzipJsonPath(snapshot.currentPath)
4445
+ && this.shownLayout(snapshot) !== 'preview';
4446
+ this.elEditToolbar.hidden = !showEditControls && !showWhitespaceControl && !showFormatJsonControl;
4447
+ this.formattingShown = showEditControls;
4448
+ this.whitespaceControlShown = showWhitespaceControl;
4449
+ this.formatJsonShown = showFormatJsonControl;
3730
4450
  this.elLayoutControls.hidden = !showLayoutControls;
3731
4451
  this.elToolbarControls.hidden = !showSaveControl && !showZoomControl
3732
- && !showWidthControl && !showColorSchemeControl && !showSearchControl;
4452
+ && !showWidthControl && !showColorSchemeControl && !showSearchControl && !showOutlineControl;
3733
4453
  this.elNavBtn.hidden = !showNavigationControl;
3734
4454
  this.elPreviewBtn.hidden = !this.controlPolicy.layout.preview;
3735
4455
  this.elSplitBtn.hidden = !this.controlPolicy.layout.split;
3736
4456
  this.elSourceBtn.hidden = !this.controlPolicy.layout.source;
3737
4457
  this.elSaveBtn.hidden = !showSaveControl;
3738
4458
  this.elSearchBtn.hidden = !showSearchControl;
4459
+ const findLabel = this.findApplies(snapshot) ? 'Find' : 'Find/replace';
4460
+ this.elSearchBtn.title = `${findLabel} (Mod-F)`;
4461
+ this.elSearchBtn.setAttribute('aria-label', findLabel);
4462
+ this.elWhitespaceBtn.setAttribute('aria-pressed', String(this.whitespaceVisible));
4463
+ this.elOutlineBtn.hidden = !showOutlineControl;
4464
+ this.syncOutlineButton();
3739
4465
  this.elZoomBtn.hidden = !showZoomControl;
3740
4466
  this.elWidthControls.hidden = !showWidthControl;
3741
4467
  this.elThemeControls.hidden = !showColorSchemeControl;
@@ -3768,7 +4494,10 @@ export class MdzipWorkspaceView {
3768
4494
  || !this.controlPolicy.title.editable;
3769
4495
  this.renderMetadata(snapshot);
3770
4496
  this.elSaveBtn.disabled = snapshot.mode === 'read-only' || !snapshot.dirty;
3771
- this.elSplitBtn.disabled = !this.controlPolicy.layout.split || !canShowSource;
4497
+ // Split only means something for Markdown: for JSON and other text the
4498
+ // preview would repeat the editor's text (see shownLayout).
4499
+ this.elSplitBtn.disabled = !this.controlPolicy.layout.split || !canShowSource
4500
+ || (snapshot.currentPathType !== 'markdown' && !this.isManifestFormPath(snapshot));
3772
4501
  this.elSourceBtn.disabled = !this.controlPolicy.layout.source || !canShowSource;
3773
4502
  this.renderFormattingControls();
3774
4503
  // Update button labels based on mode
@@ -3783,11 +4512,12 @@ export class MdzipWorkspaceView {
3783
4512
  this.elSourceIcon.innerHTML = SOURCE_EDIT_ICON_HTML;
3784
4513
  }
3785
4514
  this.elPreviewBtn.classList.toggle('active', this.layout === 'preview');
3786
- this.elSplitBtn.classList.toggle('active', this.layout === 'split');
3787
- this.elSourceBtn.classList.toggle('active', this.layout === 'source');
4515
+ const shownLayout = this.shownLayout(snapshot);
4516
+ this.elSplitBtn.classList.toggle('active', shownLayout === 'split');
4517
+ this.elSourceBtn.classList.toggle('active', shownLayout === 'source');
3788
4518
  this.elPreviewBtn.setAttribute('aria-pressed', String(this.layout === 'preview'));
3789
- this.elSplitBtn.setAttribute('aria-pressed', String(this.layout === 'split'));
3790
- this.elSourceBtn.setAttribute('aria-pressed', String(this.layout === 'source'));
4519
+ this.elSplitBtn.setAttribute('aria-pressed', String(shownLayout === 'split'));
4520
+ this.elSourceBtn.setAttribute('aria-pressed', String(shownLayout === 'source'));
3791
4521
  if (snapshot.sourceFormat === 'markdown') {
3792
4522
  this.elNavBtn.innerHTML = CONVERT_TO_MDZ_ICON_HTML;
3793
4523
  this.elNavBtn.classList.remove('active');
@@ -3873,11 +4603,14 @@ export class MdzipWorkspaceView {
3873
4603
  allowOrphanActions,
3874
4604
  allowFileActions,
3875
4605
  allowDrag: snapshot.mode !== 'read-only' && snapshot.sourceFormat === 'mdz',
3876
- pendingFolders: new Set(this.pendingNewFolders)
4606
+ pendingFolders: new Set(this.pendingNewFolders),
4607
+ selected: new Set(this.navSelection),
4608
+ collapsed: this.navCollapsed
3877
4609
  };
3878
4610
  this.elNavTree.innerHTML = navTree
3879
4611
  .map((n, i) => renderNavNode(n, snapshot, navRenderOptions, [], i === navTree.length - 1, 0))
3880
4612
  .join('');
4613
+ this.syncNavSelection();
3881
4614
  this.prepareTooltips();
3882
4615
  if (this.cmEditor) {
3883
4616
  this.updatingCm = true;
@@ -3891,17 +4624,21 @@ export class MdzipWorkspaceView {
3891
4624
  this.cmEditor.dispatch({
3892
4625
  effects: this.readOnlyCompartment.reconfigure(EditorState.readOnly.of(snapshot.mode === 'read-only'))
3893
4626
  });
4627
+ this.syncEditorLanguage(snapshot);
3894
4628
  }
3895
4629
  this.updatePreview(snapshot, entryClaimed);
3896
4630
  const pt = snapshot.currentPathType;
3897
- const showEdit = !entryClaimed && (pt === 'markdown' || pt === 'text') && this.layout !== 'preview';
3898
- const showPreview = !entryClaimed && (pt === 'image' || pt === 'binary' || pt === 'text'
3899
- || (pt === 'markdown' && this.layout !== 'source'));
4631
+ const shown = this.shownLayout(snapshot);
4632
+ const showEdit = !entryClaimed && (pt === 'markdown' || pt === 'text') && shown !== 'preview';
4633
+ // A text file's preview is its text as-is: shown in View, not beside the editor.
4634
+ const showPreview = !entryClaimed && (pt === 'image' || pt === 'binary'
4635
+ || ((pt === 'markdown' || pt === 'text') && shown !== 'source'));
3900
4636
  this.elEditPane.classList.toggle('active', showEdit);
3901
4637
  this.elPreviewPane.classList.toggle('active', showPreview);
3902
4638
  this.elEntryPane.classList.toggle('active', entryClaimed);
3903
- this.elPaneStack.classList.toggle('split-mode', this.layout === 'split' && !entryClaimed);
4639
+ this.elPaneStack.classList.toggle('split-mode', shown === 'split' && !entryClaimed);
3904
4640
  this.elPaneStack.classList.toggle('entry-claimed', entryClaimed);
4641
+ this.syncOutlinePane(this.outlineVisible && !entryClaimed && pt === 'markdown' && this.layout !== 'source');
3905
4642
  if (!showTitleControl) {
3906
4643
  this.titleDialogOpen = false;
3907
4644
  this.metadataDialogOpen = false;
@@ -3992,6 +4729,12 @@ export class MdzipWorkspaceView {
3992
4729
  this.elNameValidation.textContent = this.nameDialogState.error;
3993
4730
  this.elNameConfirmBtn.disabled = Boolean(this.nameDialogState.error);
3994
4731
  }
4732
+ this.elConfirmDialog.hidden = this.confirmDialogState === null;
4733
+ if (this.confirmDialogState) {
4734
+ this.elConfirmDialogTitle.textContent = this.confirmDialogState.title;
4735
+ this.elConfirmDialogText.textContent = this.confirmDialogState.text;
4736
+ this.elConfirmDialogOk.textContent = this.confirmDialogState.confirm;
4737
+ }
3995
4738
  this.elDeleteDialog.hidden = this.deleteDialogState === null;
3996
4739
  if (this.deleteDialogState) {
3997
4740
  this.elDeleteDialogText.textContent =
@@ -4039,6 +4782,9 @@ export class MdzipWorkspaceView {
4039
4782
  if (this.widthMenuOpen) {
4040
4783
  this.closeWidthMenu(true);
4041
4784
  }
4785
+ if (this.confirmDialogState) {
4786
+ this.answerConfirm(false);
4787
+ }
4042
4788
  if (this.contextMenuState || this.deleteDialogState || this.nameDialogState) {
4043
4789
  this.contextMenuState = null;
4044
4790
  this.deleteDialogState = null;
@@ -4121,7 +4867,97 @@ export class MdzipWorkspaceView {
4121
4867
  }
4122
4868
  });
4123
4869
  this.elSearchBtn.addEventListener('click', () => {
4124
- void this.openSearch();
4870
+ if (this.findOpen) {
4871
+ this.closeFind();
4872
+ }
4873
+ else {
4874
+ void this.openSearch();
4875
+ }
4876
+ });
4877
+ this.elFindInput.addEventListener('input', () => {
4878
+ this.refreshFind('viewport');
4879
+ this.revealFindMatchSoon();
4880
+ });
4881
+ this.elFindInput.addEventListener('keydown', (event) => {
4882
+ if (event.key === 'Enter') {
4883
+ event.preventDefault();
4884
+ void this.moveFind(event.shiftKey ? -1 : 1);
4885
+ }
4886
+ else if (event.key === 'Escape') {
4887
+ event.preventDefault();
4888
+ event.stopPropagation();
4889
+ this.closeFind();
4890
+ }
4891
+ });
4892
+ this.elFindCase.addEventListener('click', () => {
4893
+ this.findMatchCase = !this.findMatchCase;
4894
+ this.elFindCase.setAttribute('aria-pressed', String(this.findMatchCase));
4895
+ this.refreshFind('viewport');
4896
+ this.revealFindMatchSoon();
4897
+ this.elFindInput.focus();
4898
+ });
4899
+ this.elFindPrevious.addEventListener('click', () => { void this.moveFind(-1); });
4900
+ this.elFindNext.addEventListener('click', () => { void this.moveFind(1); });
4901
+ this.elFindClose.addEventListener('click', () => { this.closeFind(); });
4902
+ // Ctrl/Cmd+F in the View layout opens the find bar instead of the
4903
+ // browser's, which can't see chunks not drawn yet; F3 / Shift+F3 move
4904
+ // and Escape closes while it's open.
4905
+ doc.addEventListener('keydown', (e) => {
4906
+ if (this.destroyed) {
4907
+ return;
4908
+ }
4909
+ const focused = doc.activeElement;
4910
+ const inView = !!focused && this.elRoot.contains(focused);
4911
+ const key = e.key.toLowerCase();
4912
+ if (key === 'f' && (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) {
4913
+ if (inView && this.findApplies()) {
4914
+ e.preventDefault();
4915
+ this.openFind();
4916
+ }
4917
+ }
4918
+ else if (e.key === 'F3' && this.findOpen && inView) {
4919
+ e.preventDefault();
4920
+ void this.moveFind(e.shiftKey ? -1 : 1);
4921
+ }
4922
+ else if (e.key === 'Escape' && this.findOpen && !!focused && this.elPreviewPane.contains(focused)) {
4923
+ e.preventDefault();
4924
+ this.closeFind();
4925
+ }
4926
+ });
4927
+ // Off, then on the left, then on the right, then off again. Clicks in
4928
+ // quick succession each take their turn, so none is lost mid-animation.
4929
+ // (Without animation the change is done when the click returns.)
4930
+ this.elOutlineBtn.addEventListener('click', () => {
4931
+ const change = () => {
4932
+ if (!this.outlineVisible) {
4933
+ this.setOutlineSideFromButton('left');
4934
+ this.setOutlineVisible(true);
4935
+ this.options.onOutlineVisibilityChanged?.(true);
4936
+ }
4937
+ else if (this.outlinePosition === 'left') {
4938
+ this.setOutlineSideFromButton('right');
4939
+ }
4940
+ else {
4941
+ this.setOutlineVisible(false);
4942
+ this.options.onOutlineVisibilityChanged?.(false);
4943
+ }
4944
+ };
4945
+ if (this.outlineButtonPending === 0 && !this.canAnimateOutline()) {
4946
+ change();
4947
+ return;
4948
+ }
4949
+ const turn = () => this.animateOutlineChange(change).catch(() => { });
4950
+ this.outlineButtonPending += 1;
4951
+ const started = this.outlineButtonPending > 1 ? this.outlineButtonTurn.then(turn) : turn();
4952
+ this.outlineButtonTurn = started.finally(() => { this.outlineButtonPending -= 1; });
4953
+ });
4954
+ this.elFormatJsonBtn.addEventListener('click', () => {
4955
+ this.formatJson();
4956
+ this.cmEditor?.focus();
4957
+ });
4958
+ this.elWhitespaceBtn.addEventListener('click', () => {
4959
+ this.setWhitespaceVisible(!this.whitespaceVisible);
4960
+ this.options.onWhitespaceVisibilityChanged?.(this.whitespaceVisible);
4125
4961
  });
4126
4962
  this.elZoomBtn.addEventListener('click', (e) => {
4127
4963
  if (!this.controlPolicy.zoom) {
@@ -4247,21 +5083,85 @@ export class MdzipWorkspaceView {
4247
5083
  this.showNavMenuForPath(orphanBtn.getAttribute('data-orphan-path'), e);
4248
5084
  return;
4249
5085
  }
5086
+ const key = navRowKey(target);
5087
+ if (key && (e.ctrlKey || e.metaKey || e.shiftKey)) {
5088
+ // Selecting, not opening (or, on a folder, not opening or closing it).
5089
+ e.preventDefault();
5090
+ if (e.shiftKey) {
5091
+ this.selectNavRange(key, e.ctrlKey || e.metaKey);
5092
+ }
5093
+ else {
5094
+ this.navSelection = this.navSelection.includes(key)
5095
+ ? this.navSelection.filter((item) => item !== key)
5096
+ : [...this.navSelection, key];
5097
+ this.navSelectionAnchor = key;
5098
+ }
5099
+ this.syncNavSelection();
5100
+ return;
5101
+ }
5102
+ if (key) {
5103
+ this.navSelection = [key];
5104
+ this.navSelectionAnchor = key;
5105
+ this.syncNavSelection();
5106
+ }
4250
5107
  const navFile = target.closest('[data-nav-path]');
4251
5108
  if (navFile) {
4252
5109
  void this.openPath(navFile.getAttribute('data-nav-path'));
4253
5110
  }
4254
5111
  });
5112
+ // Remember closed folders: the tree is redrawn on every change.
5113
+ this.elNavTree.addEventListener('toggle', (e) => {
5114
+ const details = e.target;
5115
+ if (!(details instanceof HTMLElement) || !details.matches('details[data-nav-dir]')) {
5116
+ return;
5117
+ }
5118
+ const path = details.getAttribute('data-nav-dir') ?? '';
5119
+ if (details.open) {
5120
+ this.navCollapsed.delete(path);
5121
+ }
5122
+ else {
5123
+ this.navCollapsed.add(path);
5124
+ }
5125
+ }, true);
4255
5126
  this.elNavPane.addEventListener('contextmenu', (e) => {
4256
- const target = this.navMenuTargetFromElement(e.target);
5127
+ let target = this.navMenuTargetFromElement(e.target);
4257
5128
  if (!target) {
4258
5129
  return;
4259
5130
  }
4260
5131
  e.preventDefault();
4261
5132
  e.stopPropagation();
5133
+ // Right-clicking a row outside the selection selects just that row, as
5134
+ // file managers do; inside a selection of several, the menu is for all.
5135
+ const key = navRowKey(e.target);
5136
+ if (key && !this.navSelection.includes(key)) {
5137
+ this.navSelection = [key];
5138
+ this.navSelectionAnchor = key;
5139
+ this.syncNavSelection();
5140
+ }
5141
+ else if (key && this.navSelection.length > 1) {
5142
+ target = {
5143
+ kind: 'selection',
5144
+ files: this.navSelection.filter((item) => item.startsWith('f:')).map((item) => item.slice(2)),
5145
+ folders: this.navSelection.filter((item) => item.startsWith('d:')).map((item) => item.slice(2))
5146
+ };
5147
+ }
4262
5148
  this.showNavMenu(target, e);
4263
5149
  });
4264
5150
  this.elNavTree.addEventListener('keydown', (e) => {
5151
+ if (e.key.toLowerCase() === 'a' && (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) {
5152
+ e.preventDefault();
5153
+ this.navSelection = this.navRowKeys();
5154
+ this.navSelectionAnchor = this.navSelection[0] ?? null;
5155
+ this.syncNavSelection();
5156
+ return;
5157
+ }
5158
+ if (e.key === 'Escape' && this.navSelection.length > 1) {
5159
+ e.preventDefault();
5160
+ this.navSelection = [];
5161
+ this.navSelectionAnchor = null;
5162
+ this.syncNavSelection();
5163
+ return;
5164
+ }
4265
5165
  if (e.key === 'Enter') {
4266
5166
  const orphanBtn = e.target.closest('[data-orphan-path]');
4267
5167
  if (this.controlPolicy.orphanActions && orphanBtn) {
@@ -4292,6 +5192,35 @@ export class MdzipWorkspaceView {
4292
5192
  window.addEventListener('pointermove', onMove);
4293
5193
  window.addEventListener('pointerup', onUp, { once: true });
4294
5194
  });
5195
+ // The outline's edge: it's on the document side of the panel, so dragging
5196
+ // toward the document widens it on either side.
5197
+ this.elOutlineResizer.addEventListener('pointerdown', (e) => {
5198
+ if (e.button !== 0) {
5199
+ return;
5200
+ }
5201
+ e.preventDefault();
5202
+ this.resizing = true;
5203
+ this.elRoot.classList.add('resizing');
5204
+ const start = this.outlineWidth;
5205
+ const onMove = (me) => {
5206
+ const shell = this.elWorkspaceShell.getBoundingClientRect();
5207
+ const pane = this.elOutlinePane.getBoundingClientRect();
5208
+ const raw = this.outlinePosition === 'left' ? me.clientX - pane.left : pane.right - me.clientX;
5209
+ const max = Math.max(200, Math.floor(shell.width * 0.5));
5210
+ this.outlineWidth = Math.max(160, Math.min(max, Math.round(raw)));
5211
+ this.syncOutlineGeometry();
5212
+ };
5213
+ const onUp = () => {
5214
+ this.resizing = false;
5215
+ this.elRoot.classList.remove('resizing');
5216
+ window.removeEventListener('pointermove', onMove);
5217
+ if (this.outlineWidth !== null && this.outlineWidth !== start) {
5218
+ this.options.onOutlineWidthChanged?.(this.outlineWidth);
5219
+ }
5220
+ };
5221
+ window.addEventListener('pointermove', onMove);
5222
+ window.addEventListener('pointerup', onUp, { once: true });
5223
+ });
4295
5224
  this.elSplitResizer.addEventListener('pointerdown', (e) => {
4296
5225
  if (e.button !== 0 || this.layout !== 'split') {
4297
5226
  return;
@@ -4562,6 +5491,9 @@ export class MdzipWorkspaceView {
4562
5491
  this.elNameConfirmBtn.addEventListener('click', () => {
4563
5492
  void this.confirmNameDialog();
4564
5493
  });
5494
+ this.elConfirmDialog.querySelector('[data-action="cancel-confirm"]')
5495
+ .addEventListener('click', () => this.answerConfirm(false));
5496
+ this.elConfirmDialogOk.addEventListener('click', () => this.answerConfirm(true));
4565
5497
  this.elDeleteDialog.querySelector('[data-action="cancel-delete"]')
4566
5498
  .addEventListener('click', () => {
4567
5499
  this.deleteDialogState = null;
@@ -4732,8 +5664,11 @@ export class MdzipWorkspaceView {
4732
5664
  * anchor (`''` and `'top'` scroll to the top and resolve `true`), and
4733
5665
  * `false` when nothing matches, an entry renderer owns the pane, or the
4734
5666
  * view is destroyed first.
5667
+ *
5668
+ * `{ smooth: true }` glides there instead of jumping, as an outline click
5669
+ * does; it jumps anyway when the user asked for reduced motion.
4735
5670
  */
4736
- async scrollToAnchor(anchor) {
5671
+ async scrollToAnchor(anchor, options = {}) {
4737
5672
  const fragment = anchor.startsWith('#') ? anchor.slice(1) : anchor;
4738
5673
  // onPreviewRendered runs inside the first chunk batch's completion,
4739
5674
  // before the lazy-continuation sentinel is armed — same race as
@@ -4754,19 +5689,206 @@ export class MdzipWorkspaceView {
4754
5689
  return false;
4755
5690
  }
4756
5691
  if (generation !== this.previewGeneration) {
4757
- return this.scrollToAnchor(anchor);
5692
+ return this.scrollToAnchor(anchor, options);
4758
5693
  }
4759
5694
  }
4760
5695
  if (this.entryState) {
4761
5696
  return false;
4762
5697
  }
4763
- const found = await this.scrollPreviewToAnchor(fragment);
5698
+ const found = await this.scrollPreviewToAnchor(fragment, options.smooth === true && !this.prefersReducedMotion());
4764
5699
  return found || !fragment || fragment.toLowerCase() === 'top';
4765
5700
  }
4766
- /**
4767
- * The anchors {@link scrollToAnchor} can reach in the current preview, in
4768
- * document order: every heading id (without the `user-content-` prefix),
4769
- * including headings in chunks progressive rendering hasn't mounted yet,
5701
+ /** Whether the outline panel is switched on (it shows while a Markdown preview is visible). */
5702
+ get isOutlineVisible() {
5703
+ return this.outlineVisible;
5704
+ }
5705
+ /** Whether spaces and tabs are shown in the source editor. */
5706
+ get isWhitespaceVisible() {
5707
+ return this.whitespaceVisible;
5708
+ }
5709
+ /** Shows or hides spaces and tabs in the source editor, as the ¶ toolbar button does (without calling `onWhitespaceVisibilityChanged`). */
5710
+ setWhitespaceVisible(visible) {
5711
+ if (this.whitespaceVisible === visible) {
5712
+ return;
5713
+ }
5714
+ this.whitespaceVisible = visible;
5715
+ this.cmEditor?.dispatch({
5716
+ effects: this.whitespaceCompartment.reconfigure(visible ? highlightWhitespace() : [])
5717
+ });
5718
+ this.render();
5719
+ }
5720
+ /** Shows or hides the outline panel, as its toolbar button does (without calling `onOutlineVisibilityChanged`). */
5721
+ setOutlineVisible(visible) {
5722
+ if (this.outlineVisible === visible) {
5723
+ return;
5724
+ }
5725
+ this.outlineVisible = visible;
5726
+ this.render();
5727
+ }
5728
+ /** Which side of the document the outline panel is on. */
5729
+ get outlineSide() {
5730
+ return this.outlinePosition;
5731
+ }
5732
+ /** Puts the outline panel on the left or the right of the document (without calling `onOutlinePositionChanged`). */
5733
+ setOutlinePosition(position) {
5734
+ this.outlinePosition = position === 'left' ? 'left' : 'right';
5735
+ this.syncOutlineGeometry();
5736
+ this.syncOutlineButton();
5737
+ }
5738
+ setOutlineSideFromButton(position) {
5739
+ if (this.outlinePosition === position) {
5740
+ return;
5741
+ }
5742
+ this.setOutlinePosition(position);
5743
+ this.options.onOutlinePositionChanged?.(position);
5744
+ }
5745
+ /**
5746
+ * Runs `change` (which shows, hides or moves the outline panel) with
5747
+ * movement instead of a jump: the panel slides out toward its side and
5748
+ * fades, the document glides to where it now sits, and the panel slides in
5749
+ * on its new side. The layout changes once, in the middle, so a long
5750
+ * document isn't laid out again on every frame. Instant when the system
5751
+ * asks for reduced motion, or where elements can't animate.
5752
+ */
5753
+ canAnimateOutline() {
5754
+ return typeof this.elOutlinePane.animate === 'function' && !this.prefersReducedMotion();
5755
+ }
5756
+ async animateOutlineChange(change) {
5757
+ const pane = this.elOutlinePane;
5758
+ const stack = this.elPaneStack;
5759
+ if (!this.canAnimateOutline()) {
5760
+ change();
5761
+ return;
5762
+ }
5763
+ const away = () => (this.outlinePosition === 'left' ? -16 : 16);
5764
+ // The slide-out holds its last frame until the change is made, so the
5765
+ // panel can't flash back in between.
5766
+ let out = null;
5767
+ if (!pane.hidden) {
5768
+ out = pane.animate([{ opacity: 1, transform: 'translateX(0)' }, { opacity: 0, transform: `translateX(${away()}px)` }], { duration: 120, easing: 'ease-in', fill: 'forwards' });
5769
+ await out.finished;
5770
+ }
5771
+ const before = stack.getBoundingClientRect().left;
5772
+ change();
5773
+ const dx = before - stack.getBoundingClientRect().left;
5774
+ const moves = [];
5775
+ if (Math.abs(dx) >= 1) {
5776
+ moves.push(stack.animate([{ transform: `translateX(${dx}px)` }, { transform: 'translateX(0)' }], { duration: 220, easing: 'cubic-bezier(0.2, 0.8, 0.2, 1)' }).finished);
5777
+ }
5778
+ if (!pane.hidden) {
5779
+ moves.push(pane.animate([{ opacity: 0, transform: `translateX(${away()}px)` }, { opacity: 1, transform: 'translateX(0)' }], { duration: 200, delay: 40, easing: 'ease-out', fill: 'backwards' }).finished);
5780
+ }
5781
+ out?.cancel();
5782
+ await Promise.all(moves);
5783
+ }
5784
+ // The button cycles off, left, right; its icon shows where the panel is, and
5785
+ // its tooltip says what a click does next.
5786
+ syncOutlineButton() {
5787
+ const state = !this.outlineVisible ? 'off' : this.outlinePosition;
5788
+ if (this.elOutlineBtn.dataset['outlineState'] !== state) {
5789
+ this.elOutlineBtn.dataset['outlineState'] = state;
5790
+ this.elOutlineBtn.innerHTML = state === 'off' ? OUTLINE_ICON_HTML : state === 'left' ? OUTLINE_LEFT_ICON_HTML : OUTLINE_RIGHT_ICON_HTML;
5791
+ }
5792
+ const next = !this.outlineVisible ? 'show on the left' : this.outlinePosition === 'left' ? 'move to the right' : 'hide';
5793
+ this.elOutlineBtn.classList.toggle('active', this.outlineVisible);
5794
+ this.elOutlineBtn.setAttribute('aria-pressed', String(this.outlineVisible));
5795
+ setTooltip(this.elOutlineBtn, `Outline: ${next}`);
5796
+ }
5797
+ /** The outline panel's width in pixels, as last set or dragged; null while the style sheet's width applies. */
5798
+ get outlinePaneWidth() {
5799
+ return this.outlineWidth;
5800
+ }
5801
+ syncOutlineGeometry() {
5802
+ this.elRoot.classList.toggle('outline-left', this.outlinePosition === 'left');
5803
+ if (this.outlineWidth === null) {
5804
+ this.elRoot.style.removeProperty('--mdzip-outline-pane-width');
5805
+ }
5806
+ else {
5807
+ this.elRoot.style.setProperty('--mdzip-outline-pane-width', `${this.outlineWidth}px`);
5808
+ }
5809
+ }
5810
+ syncOutlinePane(show) {
5811
+ this.elRoot.classList.toggle('outline-pane-visible', show);
5812
+ this.syncOutlineGeometry();
5813
+ if (!show) {
5814
+ this.elOutlinePane.hidden = true;
5815
+ this.outline?.destroy();
5816
+ this.outline = null;
5817
+ return;
5818
+ }
5819
+ if (!this.outline) {
5820
+ // The outline hides its container while the document has no headings.
5821
+ this.outline = createMdzipHeadingOutline({
5822
+ content: this.elPreviewContent,
5823
+ container: this.elOutlinePane,
5824
+ scrollContainer: this.elPreviewPane,
5825
+ label: this.outlineOptions.label ?? 'Outline',
5826
+ collapse: this.outlineOptions.collapse,
5827
+ offset: 64,
5828
+ headings: () => this.outlineHeadings(),
5829
+ findElement: (heading) => this.findOutlineElement(heading),
5830
+ onNavigate: (heading, event) => {
5831
+ event.preventDefault();
5832
+ void this.scrollToAnchor(heading.id, { smooth: true });
5833
+ }
5834
+ });
5835
+ this.outlineGeneration = this.previewMountedGeneration;
5836
+ }
5837
+ else if (this.outlineGeneration !== this.previewMountedGeneration) {
5838
+ this.refreshOutline();
5839
+ }
5840
+ }
5841
+ /** Rebuilds the outline after the preview renders a new version of the document. */
5842
+ refreshOutline() {
5843
+ if (!this.outline) {
5844
+ return;
5845
+ }
5846
+ this.outlineGeneration = this.previewMountedGeneration;
5847
+ this.outline.refresh();
5848
+ }
5849
+ /**
5850
+ * The document's headings for the outline, ids without the
5851
+ * `user-content-` prefix. Under progressive rendering they come from the
5852
+ * chunks' tokens, so headings in chunks that aren't mounted yet are listed
5853
+ * too (without an element until they mount).
5854
+ */
5855
+ outlineHeadings() {
5856
+ if (this.entryState) {
5857
+ return [];
5858
+ }
5859
+ const levels = new Set(this.outlineOptions.levels ?? [1, 2, 3]);
5860
+ const state = this.chunkedRenderState;
5861
+ if (state && state.generation === this.previewGeneration) {
5862
+ return state.records
5863
+ .flatMap((record) => collectMdzipHeadings(record.tokens))
5864
+ .filter((heading) => levels.has(heading.level))
5865
+ .map((heading) => ({ ...heading, element: null }));
5866
+ }
5867
+ const headings = [];
5868
+ for (const element of Array.from(this.elPreviewContent.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id],h6[id]'))) {
5869
+ const level = Number(element.tagName[1]);
5870
+ // Only the document's own headings: not the footnotes section's label, say.
5871
+ if (!levels.has(level) || !element.id.startsWith(MDZIP_HEADING_ID_PREFIX))
5872
+ continue;
5873
+ const text = (element.textContent ?? '').replace(/\s+/g, ' ').trim();
5874
+ if (text) {
5875
+ headings.push({ id: element.id.slice(MDZIP_HEADING_ID_PREFIX.length), text, level, element });
5876
+ }
5877
+ }
5878
+ return headings;
5879
+ }
5880
+ findOutlineElement(heading) {
5881
+ const id = MDZIP_HEADING_ID_PREFIX + heading.id;
5882
+ for (const element of Array.from(this.elPreviewContent.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id],h6[id]'))) {
5883
+ if (element.id === id)
5884
+ return element;
5885
+ }
5886
+ return null;
5887
+ }
5888
+ /**
5889
+ * The anchors {@link scrollToAnchor} can reach in the current preview, in
5890
+ * document order: every heading id (without the `user-content-` prefix),
5891
+ * including headings in chunks progressive rendering hasn't mounted yet,
4770
5892
  * plus explicit `id`/`name` anchors on links in the mounted preview.
4771
5893
  * Empty before the preview first mounts.
4772
5894
  */
@@ -4860,7 +5982,15 @@ export class MdzipWorkspaceView {
4860
5982
  * a chunk that hasn't been mounted yet, so this mounts everything up to and
4861
5983
  * including that chunk first. Returns whether an anchor was found.
4862
5984
  */
4863
- async scrollPreviewToAnchor(rawFragment) {
5985
+ prefersReducedMotion() {
5986
+ try {
5987
+ return this.elRoot.ownerDocument.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
5988
+ }
5989
+ catch {
5990
+ return false;
5991
+ }
5992
+ }
5993
+ async scrollPreviewToAnchor(rawFragment, smooth = false) {
4864
5994
  let fragment = rawFragment;
4865
5995
  try {
4866
5996
  fragment = decodeURIComponent(rawFragment);
@@ -4886,17 +6016,81 @@ export class MdzipWorkspaceView {
4886
6016
  if (!target) {
4887
6017
  // `#` and `#top` mean the top of the document, as in a browser.
4888
6018
  if (!fragment || fragment.toLowerCase() === 'top') {
4889
- pane.scrollTop = 0;
6019
+ this.releaseAnchorPin();
6020
+ if (smooth) {
6021
+ this.glidePreviewTo(() => 0);
6022
+ }
6023
+ else {
6024
+ pane.scrollTop = 0;
6025
+ }
4890
6026
  }
4891
6027
  return false;
4892
6028
  }
4893
- this.scrollPaneToElement(target);
6029
+ // Pin first: pinning releases any earlier pin, and with it a glide.
4894
6030
  this.pinPreviewAnchor(target);
6031
+ if (smooth) {
6032
+ this.glidePreviewTo(() => this.paneTopOf(target));
6033
+ }
6034
+ else {
6035
+ this.scrollPaneToElement(target);
6036
+ }
4895
6037
  return true;
4896
6038
  }
6039
+ // The pane's scrollTop that puts `target` at the top, less its
6040
+ // scroll-margin-top (preview headings have one), so a heading gone to stops
6041
+ // a little below the top, as scrollIntoView() would leave it.
6042
+ paneTopOf(target) {
6043
+ const pane = this.elPreviewPane;
6044
+ const style = target.ownerDocument.defaultView?.getComputedStyle(target);
6045
+ const margin = Number.parseFloat(style?.scrollMarginTop ?? '') || 0;
6046
+ return Math.max(0, pane.scrollTop + target.getBoundingClientRect().top - pane.getBoundingClientRect().top - margin);
6047
+ }
4897
6048
  scrollPaneToElement(target) {
6049
+ this.elPreviewPane.scrollTop = this.paneTopOf(target);
6050
+ this.syncScrollFromPreview(true);
6051
+ }
6052
+ /**
6053
+ * Scrolls the preview to `targetTop()` over a few hundred milliseconds.
6054
+ * The target is measured again every frame, so images loading above it
6055
+ * while it moves bend the path instead of restarting it (the browser's
6056
+ * own smooth scroll restarts on every change and stutters). A wheel,
6057
+ * touch or click in the pane stops it, as it releases the anchor pin.
6058
+ */
6059
+ glidePreviewTo(targetTop) {
6060
+ this.cancelPreviewGlide();
4898
6061
  const pane = this.elPreviewPane;
4899
- pane.scrollTop += target.getBoundingClientRect().top - pane.getBoundingClientRect().top;
6062
+ const start = pane.scrollTop;
6063
+ const distance = Math.abs(targetTop() - start);
6064
+ if (distance < 2) {
6065
+ pane.scrollTop = targetTop();
6066
+ this.syncScrollFromPreview(true);
6067
+ return;
6068
+ }
6069
+ // Longer for longer trips, within limits that still feel quick.
6070
+ const duration = Math.min(700, 250 + distance * 0.12);
6071
+ const startTime = performance.now();
6072
+ // performance.now(), not the frame's timestamp: the two can count from
6073
+ // different origins (another window's requestAnimationFrame, jsdom).
6074
+ const step = () => {
6075
+ const now = performance.now();
6076
+ if (this.destroyed) {
6077
+ this.previewGlide = null;
6078
+ return;
6079
+ }
6080
+ const t = Math.min(1, Math.max(0, (now - startTime) / duration));
6081
+ const eased = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
6082
+ pane.scrollTop = start + (targetTop() - start) * eased;
6083
+ // In Split, the source follows along.
6084
+ this.syncScrollFromPreview(true);
6085
+ this.previewGlide = t < 1 ? requestAnimationFrame(step) : null;
6086
+ };
6087
+ this.previewGlide = requestAnimationFrame(step);
6088
+ }
6089
+ cancelPreviewGlide() {
6090
+ if (this.previewGlide !== null) {
6091
+ cancelAnimationFrame(this.previewGlide);
6092
+ this.previewGlide = null;
6093
+ }
4900
6094
  }
4901
6095
  /** See `anchorPin`. */
4902
6096
  pinPreviewAnchor(target) {
@@ -4910,12 +6104,16 @@ export class MdzipWorkspaceView {
4910
6104
  this.releaseAnchorPin();
4911
6105
  return;
4912
6106
  }
4913
- this.scrollPaneToElement(target);
6107
+ if (this.previewGlide === null) {
6108
+ // While gliding, each frame measures the target again anyway.
6109
+ this.scrollPaneToElement(target);
6110
+ }
4914
6111
  });
4915
6112
  observer.observe(this.elPreviewContent);
4916
6113
  this.anchorPin = observer;
4917
6114
  }
4918
6115
  releaseAnchorPin() {
6116
+ this.cancelPreviewGlide();
4919
6117
  this.anchorPin?.disconnect();
4920
6118
  this.anchorPin = null;
4921
6119
  }
@@ -5099,9 +6297,160 @@ export class MdzipWorkspaceView {
5099
6297
  this.render();
5100
6298
  }
5101
6299
  catch (error) {
6300
+ if (error instanceof MdzipManifestInvalidError) {
6301
+ await this.showManifestProblems(error.validity);
6302
+ }
5102
6303
  this.options.onFailed?.(error);
5103
6304
  }
5104
6305
  }
6306
+ // Saving is blocked by an invalid manifest: show it, with its problems,
6307
+ // wherever the user is, so they can see what to fix.
6308
+ async showManifestProblems(validity) {
6309
+ const snapshot = this.workspace?.snapshot();
6310
+ if (snapshot && !isMdzipRootManifestPath(snapshot.currentPath)) {
6311
+ await this.openPath('manifest.json');
6312
+ }
6313
+ this.setJsonValidity(validity, 'manifest.json');
6314
+ if (this.layout !== 'source' && this.manifestForm) {
6315
+ // The form shows each problem under its field.
6316
+ this.manifestForm.flash();
6317
+ return;
6318
+ }
6319
+ this.elJsonStatus.classList.remove('flash');
6320
+ void this.elJsonStatus.offsetWidth;
6321
+ this.elJsonStatus.classList.add('flash');
6322
+ }
6323
+ /**
6324
+ * Re-indents the open JSON file (2 spaces), changing only whitespace, as
6325
+ * the toolbar's Format JSON button and Shift+Alt+F do. One undo step.
6326
+ * Returns `false` when no JSON file is open in an editable editor or its
6327
+ * text isn't valid JSON.
6328
+ */
6329
+ formatJson() {
6330
+ const editor = this.cmEditor;
6331
+ const snapshot = this.workspace?.snapshot();
6332
+ if (!editor || !snapshot || snapshot.mode === 'read-only' || !isMdzipJsonPath(snapshot.currentPath)) {
6333
+ return false;
6334
+ }
6335
+ const text = editor.state.doc.toString();
6336
+ const formatted = formatMdzipJsonText(text);
6337
+ if (formatted === null) {
6338
+ return false;
6339
+ }
6340
+ if (formatted !== text) {
6341
+ // Replace only what differs, so the cursor keeps its place where it can.
6342
+ let start = 0;
6343
+ while (start < text.length && start < formatted.length && text[start] === formatted[start])
6344
+ start += 1;
6345
+ let end = 0;
6346
+ while (end < text.length - start && end < formatted.length - start
6347
+ && text[text.length - 1 - end] === formatted[formatted.length - 1 - end])
6348
+ end += 1;
6349
+ editor.dispatch({
6350
+ changes: { from: start, to: text.length - end, insert: formatted.slice(start, formatted.length - end) },
6351
+ userEvent: 'input.format',
6352
+ scrollIntoView: true
6353
+ });
6354
+ }
6355
+ return true;
6356
+ }
6357
+ /**
6358
+ * The problems of the edited `manifest.json` that block saving, or `null`
6359
+ * when the archive can be saved.
6360
+ */
6361
+ getManifestValidity() {
6362
+ return this.workspace?.manifestValidity() ?? null;
6363
+ }
6364
+ // JSON files get JSON highlighting and live validation; everything else
6365
+ // keeps the Markdown language, as before.
6366
+ syncEditorLanguage(snapshot) {
6367
+ const isJson = (snapshot.currentPathType === 'text' || snapshot.currentPathType === 'markdown')
6368
+ && isMdzipJsonPath(snapshot.currentPath);
6369
+ const language = isJson ? 'json' : 'markdown';
6370
+ if (language !== this.cmLanguage && this.cmEditor) {
6371
+ this.cmLanguage = language;
6372
+ this.cmEditor.dispatch({
6373
+ effects: this.languageCompartment.reconfigure(isJson
6374
+ // No spellcheck in JSON: keys like "someNewProp" aren't words.
6375
+ ? [
6376
+ json(),
6377
+ syntaxHighlighting(mdzipJsonHighlight),
6378
+ this.jsonLinter(),
6379
+ bracketMatching(),
6380
+ closeBrackets(),
6381
+ foldGutter(),
6382
+ Prec.high(keymap.of([
6383
+ ...closeBracketsKeymap,
6384
+ ...foldKeymap,
6385
+ { key: 'Shift-Alt-f', run: () => this.formatJson() }
6386
+ ])),
6387
+ Prec.highest(EditorView.contentAttributes.of({ spellcheck: 'false' }))
6388
+ ]
6389
+ : markdown())
6390
+ });
6391
+ }
6392
+ if (!isJson) {
6393
+ this.setJsonValidity(null, null);
6394
+ }
6395
+ else if (this.jsonValidityPath !== snapshot.currentPath && this.workspace) {
6396
+ this.setJsonValidity(this.workspace.validateJsonText(snapshot.currentPath, snapshot.currentText), snapshot.currentPath);
6397
+ }
6398
+ }
6399
+ jsonLinter() {
6400
+ return linter((view) => {
6401
+ const workspace = this.workspace;
6402
+ if (!workspace) {
6403
+ return [];
6404
+ }
6405
+ const path = workspace.snapshot().currentPath;
6406
+ const validity = workspace.validateJsonText(path, view.state.doc.toString());
6407
+ this.setJsonValidity(validity, path);
6408
+ const length = view.state.doc.length;
6409
+ return validity.problems.map((problem) => {
6410
+ const from = Math.min(problem.from, length);
6411
+ return {
6412
+ from,
6413
+ to: Math.max(from, Math.min(problem.to, length)),
6414
+ severity: problem.severity,
6415
+ message: problem.message
6416
+ };
6417
+ });
6418
+ }, { delay: 300 });
6419
+ }
6420
+ setJsonValidity(validity, path) {
6421
+ const changed = this.jsonValidityPath !== path
6422
+ || JSON.stringify(this.jsonValidity?.problems ?? null) !== JSON.stringify(validity?.problems ?? null);
6423
+ this.jsonValidity = validity;
6424
+ this.jsonValidityPath = path;
6425
+ const status = this.elJsonStatus;
6426
+ status.hidden = validity === null || this.options.jsonStatus === false;
6427
+ // Format needs valid JSON; a manifest error that isn't about syntax is fine.
6428
+ this.elFormatJsonBtn.disabled = validity !== null && validity.value === undefined;
6429
+ this.elFormatJsonBtn.title = this.elFormatJsonBtn.disabled
6430
+ ? 'Format JSON: fix the syntax error first'
6431
+ : 'Format JSON (Shift+Alt+F)';
6432
+ if (validity) {
6433
+ status.dataset.status = validity.status;
6434
+ status.textContent = validity.canSave
6435
+ ? describeMdzipJsonValidity(validity)
6436
+ : `${describeMdzipJsonValidity(validity)} Saving is blocked until it's fixed.`;
6437
+ const custom = validity.customFields.length
6438
+ ? `Custom fields, kept as they are: ${validity.customFields.join(', ')}.`
6439
+ : '';
6440
+ status.title = [
6441
+ ...validity.problems.map((problem) => `${problem.severity}: ${problem.message}`),
6442
+ custom
6443
+ ].filter(Boolean).join('\n');
6444
+ }
6445
+ else {
6446
+ delete status.dataset.status;
6447
+ status.textContent = '';
6448
+ status.title = '';
6449
+ }
6450
+ if (changed) {
6451
+ this.options.onJsonValidityChanged?.(validity, path);
6452
+ }
6453
+ }
5105
6454
  downloadSavedBlob(blob, fileName) {
5106
6455
  const doc = this.elRoot.ownerDocument;
5107
6456
  const urlApi = doc.defaultView?.URL;
@@ -6037,6 +7386,9 @@ export class MdzipWorkspaceView {
6037
7386
  card.replaceWith(image);
6038
7387
  }
6039
7388
  const text = previewPlainText(container);
7389
+ for (const element of Array.from(container.querySelectorAll(`[${MDZIP_BLOCK_ATTRIBUTE}]`))) {
7390
+ element.removeAttribute(MDZIP_BLOCK_ATTRIBUTE);
7391
+ }
6040
7392
  for (const element of Array.from(container.querySelectorAll(PREVIEW_CHROME_REMOVE_SELECTOR))) {
6041
7393
  element.remove();
6042
7394
  }
@@ -6351,7 +7703,8 @@ export class MdzipWorkspaceView {
6351
7703
  chunkHtml = cacheHit;
6352
7704
  }
6353
7705
  else {
6354
- const result = this.renderingService.renderChunk(chunks[chunkIndex], context, { index: chunkIndex });
7706
+ // Marked like the preview's chunks: the two share chunkHtmlCache.
7707
+ const result = this.renderingService.renderChunk(chunks[chunkIndex], context, { index: chunkIndex, markBlocks: true });
6355
7708
  chunkHtml = typeof result === 'string' ? result : await result;
6356
7709
  // Only populate the shared cache if this generation is *still*
6357
7710
  // the live one at the moment this (possibly async) render
@@ -6387,7 +7740,8 @@ export class MdzipWorkspaceView {
6387
7740
  setTimeout(resolve, 0);
6388
7741
  });
6389
7742
  }
6390
- return html;
7743
+ // The split view's block marks are for this page only.
7744
+ return stripMdzipBlockMarks(html);
6391
7745
  }
6392
7746
  /**
6393
7747
  * Like `copyAllPreviewContent`, but writes a rich `text/html` clipboard
@@ -6580,7 +7934,7 @@ export class MdzipWorkspaceView {
6580
7934
  this.chunkedRenderState.mounting = false;
6581
7935
  }
6582
7936
  if (generation === this.previewGeneration && !context.signal.aborted) {
6583
- this.hydrateImages(allPending, context, generation, animateImageHydration, () => { });
7937
+ this.hydrateImages(allPending, context, generation, animateImageHydration, NO_SETTLE);
6584
7938
  }
6585
7939
  }
6586
7940
  }
@@ -6771,6 +8125,12 @@ export class MdzipWorkspaceView {
6771
8125
  link: formatting.link,
6772
8126
  image: formatting.image
6773
8127
  };
8128
+ // Formatting only applies to Markdown; the whitespace toggle to any text the editor shows.
8129
+ for (const key of Object.keys(visibility)) {
8130
+ visibility[key] = visibility[key] && this.formattingShown;
8131
+ }
8132
+ visibility['whitespace'] = this.whitespaceControlShown;
8133
+ visibility['formatJson'] = this.formatJsonShown;
6774
8134
  this.elEditToolbar.querySelectorAll('[data-format-control]').forEach((element) => {
6775
8135
  element.hidden = !visibility[element.dataset['formatControl'] ?? ''];
6776
8136
  });
@@ -7136,6 +8496,15 @@ export class MdzipWorkspaceView {
7136
8496
  this.options.onColorSchemeChanged?.(this.colorScheme);
7137
8497
  }
7138
8498
  }
8499
+ /** The layout showing: `'source'` (Edit), `'split'` or `'preview'` (View). */
8500
+ get layoutMode() {
8501
+ return this.layout;
8502
+ }
8503
+ /**
8504
+ * Switches to Edit (`'source'`), Split or View (`'preview'`), as the
8505
+ * toolbar's buttons do, for example to show an imported document in View.
8506
+ * A file that can't be shown that way gets the nearest layout it can.
8507
+ */
7139
8508
  async setLayout(requested) {
7140
8509
  const snapshot = this.workspace?.snapshot();
7141
8510
  this.layout = snapshot ? this.validLayoutForSnapshot(requested, snapshot) : requested;
@@ -7194,20 +8563,26 @@ export class MdzipWorkspaceView {
7194
8563
  // Items for the nav context menu; null entries render as separators.
7195
8564
  navMenuItems(target, snapshot) {
7196
8565
  const canMutate = this.allowFileActions(snapshot);
8566
+ if (target.kind === 'selection') {
8567
+ return this.extractMenuItems('many', false);
8568
+ }
7197
8569
  if (target.kind === 'directory') {
8570
+ const hasFiles = this.collectExtractPaths({ files: [], folders: [target.path] }, snapshot).length > 0;
8571
+ const extract = hasFiles ? this.extractMenuItems('many', target.path === '') : [];
7198
8572
  if (!canMutate) {
7199
- return [];
8573
+ return extract;
7200
8574
  }
7201
8575
  return [
7202
8576
  { action: 'new-file', label: 'New .md File' },
7203
8577
  { action: 'new-folder', label: 'New Folder' },
7204
8578
  null,
7205
- { action: 'add-files', label: 'Add Files…' }
8579
+ { action: 'add-files', label: 'Add Files…' },
8580
+ ...(extract.length ? [null, ...extract] : [])
7206
8581
  ];
7207
8582
  }
7208
8583
  const hostItems = this.fileActionItems(target);
7209
8584
  if (target.isManifest) {
7210
- return [...hostItems, ...(hostItems.length ? [null] : []), { action: 'download', label: 'Download' }];
8585
+ return [...hostItems, ...(hostItems.length ? [null] : []), ...this.extractMenuItems('one', false)];
7211
8586
  }
7212
8587
  const groups = [];
7213
8588
  if (canMutate) {
@@ -7242,7 +8617,7 @@ export class MdzipWorkspaceView {
7242
8617
  if (hostItems.length > 0) {
7243
8618
  groups.push(hostItems);
7244
8619
  }
7245
- groups.push([{ action: 'download', label: 'Download' }]);
8620
+ groups.push(this.extractMenuItems('one', false));
7246
8621
  if (canMutate && !target.isEntryPoint) {
7247
8622
  groups.push([{
7248
8623
  action: 'delete',
@@ -7251,12 +8626,32 @@ export class MdzipWorkspaceView {
7251
8626
  }
7252
8627
  return groups.flatMap((group, index) => index === 0 ? group : [null, ...group]);
7253
8628
  }
8629
+ /**
8630
+ * Taking files out of the archive: **Extract…** where the host writes
8631
+ * them (`onExtractFiles`), else **Download** for one file, and for several
8632
+ * **Download as ZIP** plus **Extract to Folder…** where the browser can
8633
+ * write to a folder.
8634
+ */
8635
+ extractMenuItems(count, all) {
8636
+ if (this.options.onExtractFiles) {
8637
+ return [{ action: 'extract', label: all ? 'Extract All…' : 'Extract…' }];
8638
+ }
8639
+ if (count === 'one') {
8640
+ return [{ action: 'download', label: 'Download' }];
8641
+ }
8642
+ const items = [{ action: 'download-zip', label: all ? 'Download All as ZIP' : 'Download as ZIP' }];
8643
+ const win = this.elRoot.ownerDocument.defaultView;
8644
+ if (typeof win?.showDirectoryPicker === 'function') {
8645
+ items.push({ action: 'extract-folder', label: all ? 'Extract All to Folder…' : 'Extract to Folder…' });
8646
+ }
8647
+ return items;
8648
+ }
7254
8649
  /** Menu items for the host's {@link MdzipFileAction}s that apply to this file. */
7255
8650
  fileActionItems(target) {
7256
8651
  const file = fileActionTarget(target);
7257
8652
  return (this.options.hostFileActions ?? [])
7258
8653
  .filter((item) => item.appliesTo?.(file) ?? true)
7259
- .map((item) => ({ action: `${HOST_FILE_ACTION_PREFIX}${item.id}`, label: item.label }));
8654
+ .map((item) => ({ action: `${HOST_FILE_ACTION_PREFIX}${item.id}`, label: fileActionLabel(item, file) }));
7260
8655
  }
7261
8656
  async handleNavMenuAction(action) {
7262
8657
  const state = this.contextMenuState;
@@ -7326,6 +8721,11 @@ export class MdzipWorkspaceView {
7326
8721
  await this.downloadArchiveFile(target.path);
7327
8722
  }
7328
8723
  break;
8724
+ case 'extract':
8725
+ case 'download-zip':
8726
+ case 'extract-folder':
8727
+ await this.extractNavTarget(target, action);
8728
+ break;
7329
8729
  case 'duplicate':
7330
8730
  if (target.kind === 'file') {
7331
8731
  await this.duplicateFile(target.path);
@@ -7534,6 +8934,189 @@ export class MdzipWorkspaceView {
7534
8934
  const fileName = path.slice(path.lastIndexOf('/') + 1);
7535
8935
  this.downloadSavedBlob(new Blob([buffer]), fileName);
7536
8936
  }
8937
+ /**
8938
+ * The files of the archive as `{ path, bytes }`, for a host or a test to
8939
+ * write elsewhere (#69). Each path names a file, or a folder (with or
8940
+ * without a trailing `/`; `''` is the whole archive) whose files are all
8941
+ * included when `includeFolders` isn't false. `manifest.json` comes only
8942
+ * when named. In archive order, each file once; paths that match nothing
8943
+ * are skipped. Bytes are the file's current content, as Download gives.
8944
+ */
8945
+ async extractFiles(paths, options = {}) {
8946
+ const snapshot = this.workspace?.snapshot();
8947
+ if (!snapshot) {
8948
+ return [];
8949
+ }
8950
+ const files = [];
8951
+ const folders = [];
8952
+ for (const path of paths) {
8953
+ if (snapshot.content.paths.some((entry) => samePath(entry.path, path))) {
8954
+ files.push(path);
8955
+ }
8956
+ else if (options.includeFolders !== false) {
8957
+ folders.push(path.replace(/\/+$/, ''));
8958
+ }
8959
+ }
8960
+ return this.readExtractFiles(this.collectExtractPaths({ files, folders }, snapshot));
8961
+ }
8962
+ // The archive paths a selection covers, in archive order.
8963
+ collectExtractPaths(selection, snapshot) {
8964
+ return snapshot.content.paths
8965
+ .map((entry) => entry.path)
8966
+ .filter((path) => selection.files.some((file) => samePath(file, path))
8967
+ || (!isMdzipManifestPath(path) && selection.folders.some((folder) => folder === '' || path.startsWith(`${folder}/`))));
8968
+ }
8969
+ async readExtractFiles(paths) {
8970
+ const workspace = this.workspace;
8971
+ const files = [];
8972
+ for (const path of paths) {
8973
+ const bytes = await workspace?.readPathBytes(path);
8974
+ if (bytes) {
8975
+ files.push({ path, bytes });
8976
+ }
8977
+ }
8978
+ return files;
8979
+ }
8980
+ async extractNavTarget(target, action) {
8981
+ const snapshot = this.workspace?.snapshot();
8982
+ if (!snapshot) {
8983
+ return;
8984
+ }
8985
+ const selection = target.kind === 'selection'
8986
+ ? { files: target.files, folders: target.folders }
8987
+ : target.kind === 'directory'
8988
+ ? { files: [], folders: [target.path] }
8989
+ : { files: [target.path], folders: [] };
8990
+ if (action === 'extract-folder') {
8991
+ // Ask for the folder first: the picker needs the click's user activation.
8992
+ await this.extractToPickedFolder(selection, snapshot);
8993
+ return;
8994
+ }
8995
+ const files = await this.readExtractFiles(this.collectExtractPaths(selection, snapshot));
8996
+ if (!files.length) {
8997
+ return;
8998
+ }
8999
+ if (action === 'extract') {
9000
+ await this.options.onExtractFiles?.({ files, selection });
9001
+ return;
9002
+ }
9003
+ const zippable = {};
9004
+ for (const file of files) {
9005
+ // Pictures are compressed already.
9006
+ zippable[file.path] = [file.bytes, { level: /\.(png|jpe?g|gif|webp|avif|mp4|webm|zip|mdz)$/i.test(file.path) ? 0 : 6 }];
9007
+ }
9008
+ const zipped = zipSync(zippable);
9009
+ const buffer = zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength);
9010
+ const base = snapshot.fileName.replace(/\.[^.]+$/, '') || 'archive';
9011
+ const onlyFolder = selection.files.length === 0 && selection.folders.length === 1 && selection.folders[0] !== ''
9012
+ ? selection.folders[0].slice(selection.folders[0].lastIndexOf('/') + 1)
9013
+ : null;
9014
+ this.downloadSavedBlob(new Blob([buffer], { type: 'application/zip' }), `${onlyFolder ?? base}.zip`);
9015
+ }
9016
+ // Extract to Folder… in a browser that can write to one: keeps the archive
9017
+ // paths below the folder picked, and asks before replacing files.
9018
+ async extractToPickedFolder(selection, snapshot) {
9019
+ const win = this.elRoot.ownerDocument.defaultView;
9020
+ if (!win?.showDirectoryPicker) {
9021
+ return;
9022
+ }
9023
+ let root;
9024
+ try {
9025
+ root = await win.showDirectoryPicker({ mode: 'readwrite', id: 'mdzip-extract' });
9026
+ }
9027
+ catch (error) {
9028
+ if (error?.name === 'AbortError') {
9029
+ return;
9030
+ }
9031
+ throw error;
9032
+ }
9033
+ const files = await this.readExtractFiles(this.collectExtractPaths(selection, snapshot));
9034
+ const folderOf = async (path, create) => {
9035
+ let dir = root;
9036
+ for (const part of path.split('/').slice(0, -1)) {
9037
+ try {
9038
+ dir = await dir.getDirectoryHandle(part, { create });
9039
+ }
9040
+ catch {
9041
+ return null;
9042
+ }
9043
+ }
9044
+ return dir;
9045
+ };
9046
+ const nameOf = (path) => path.slice(path.lastIndexOf('/') + 1);
9047
+ let existing = 0;
9048
+ for (const file of files) {
9049
+ const dir = await folderOf(file.path, false);
9050
+ if (dir && await dir.getFileHandle(nameOf(file.path)).then(() => true, () => false)) {
9051
+ existing += 1;
9052
+ }
9053
+ }
9054
+ if (existing > 0) {
9055
+ const ok = await this.askConfirm('Replace Existing Files?', `${existing === 1 ? 'One file' : `${existing} files`} of the ${files.length} already ${existing === 1 ? 'exists' : 'exist'} in "${root.name}". Replace ${existing === 1 ? 'it' : 'them'}?`, 'Replace');
9056
+ if (!ok) {
9057
+ return;
9058
+ }
9059
+ }
9060
+ for (const file of files) {
9061
+ const dir = await folderOf(file.path, true);
9062
+ if (!dir) {
9063
+ throw new Error(`Could not create the folder for ${file.path}.`);
9064
+ }
9065
+ const writable = await (await dir.getFileHandle(nameOf(file.path), { create: true })).createWritable();
9066
+ await writable.write(file.bytes);
9067
+ await writable.close();
9068
+ }
9069
+ this.showCopyToast(`Extracted ${files.length === 1 ? 'one file' : `${files.length} files`} to "${root.name}"`);
9070
+ }
9071
+ /** Asks a yes/no question in the editor's own dialog (no browser confirm(), which some hosts block). */
9072
+ askConfirm(title, text, confirm) {
9073
+ this.confirmDialogState?.resolve(false);
9074
+ return new Promise((resolve) => {
9075
+ this.confirmDialogState = { title, text, confirm, resolve };
9076
+ this.render();
9077
+ this.elConfirmDialogOk.focus();
9078
+ });
9079
+ }
9080
+ answerConfirm(ok) {
9081
+ const state = this.confirmDialogState;
9082
+ this.confirmDialogState = null;
9083
+ this.render();
9084
+ state?.resolve(ok);
9085
+ }
9086
+ // The tree's rows in order, as selection keys.
9087
+ navRowKeys() {
9088
+ return Array.from(this.elNavTree.querySelectorAll('[data-nav-path], details[data-nav-dir] > summary'))
9089
+ // Hidden in a closed folder? (A folder's own row shows while it's closed.)
9090
+ .filter((row) => !(row.matches('summary') ? row.parentElement?.parentElement : row)?.closest('details:not([open])'))
9091
+ .map((row) => navRowKey(row))
9092
+ .filter((key) => key !== null);
9093
+ }
9094
+ // Shift+click: the rows from the anchor to this one (added to the
9095
+ // selection with Ctrl/Cmd).
9096
+ selectNavRange(key, add) {
9097
+ const rows = this.navRowKeys();
9098
+ const anchor = this.navSelectionAnchor && rows.includes(this.navSelectionAnchor) ? this.navSelectionAnchor : key;
9099
+ const [from, to] = [rows.indexOf(anchor), rows.indexOf(key)].sort((a, b) => a - b);
9100
+ const range = rows.slice(from, to + 1);
9101
+ this.navSelection = add ? [...new Set([...this.navSelection, ...range])] : range;
9102
+ this.navSelectionAnchor = anchor;
9103
+ }
9104
+ // Marks the selected rows, dropping any no longer in the tree.
9105
+ syncNavSelection() {
9106
+ const present = new Set(this.navRowKeysAll());
9107
+ this.navSelection = this.navSelection.filter((key) => present.has(key));
9108
+ const selected = new Set(this.navSelection);
9109
+ for (const row of Array.from(this.elNavTree.querySelectorAll('[data-nav-path], details[data-nav-dir] > summary'))) {
9110
+ const key = navRowKey(row);
9111
+ row.classList.toggle('nav-selected', !!key && selected.has(key));
9112
+ }
9113
+ this.elNavTree.classList.toggle('has-selection', this.navSelection.length > 1);
9114
+ }
9115
+ navRowKeysAll() {
9116
+ return Array.from(this.elNavTree.querySelectorAll('[data-nav-path], details[data-nav-dir] > summary'))
9117
+ .map((row) => navRowKey(row))
9118
+ .filter((key) => key !== null);
9119
+ }
7537
9120
  async duplicateFile(path) {
7538
9121
  const workspace = this.workspace;
7539
9122
  const snapshot = workspace?.snapshot();
@@ -7708,17 +9291,110 @@ export class MdzipWorkspaceView {
7708
9291
  this.options.onFailed?.(error);
7709
9292
  }
7710
9293
  }
9294
+ // The layout as drawn for the open file. Split shows the editor alone for
9295
+ // non-Markdown text (JSON, CSS, …), whose preview would only repeat the
9296
+ // text; this.layout keeps the choice, so Markdown files open split again.
9297
+ shownLayout(snapshot) {
9298
+ return this.layout === 'split' && snapshot.currentPathType === 'text' && !this.isManifestFormPath(snapshot)
9299
+ ? 'source'
9300
+ : this.layout;
9301
+ }
9302
+ // The archive's own manifest.json, which View shows as a form.
9303
+ isManifestFormPath(snapshot) {
9304
+ return snapshot.sourceFormat === 'mdz'
9305
+ && snapshot.currentPathType === 'text'
9306
+ && isMdzipRootManifestPath(snapshot.currentPath);
9307
+ }
9308
+ // Moving into or out of manifest.json swaps in that side's remembered
9309
+ // layout, so the form (View) and a document's Split don't override each other.
9310
+ swapManifestLayout(snapshot) {
9311
+ const isManifest = this.isManifestFormPath(snapshot);
9312
+ if (isManifest === this.layoutIsManifest) {
9313
+ return;
9314
+ }
9315
+ this.layoutIsManifest = isManifest;
9316
+ if (isManifest) {
9317
+ this.documentLayout = this.layout;
9318
+ this.layout = this.manifestLayout;
9319
+ }
9320
+ else {
9321
+ this.manifestLayout = this.layout;
9322
+ this.layout = this.documentLayout;
9323
+ }
9324
+ if (this.layout !== 'preview' && !this.cmEditor) {
9325
+ // The editor is created on demand; draw again once it exists.
9326
+ void this.ensureCmEditor().then(() => this.render());
9327
+ }
9328
+ }
9329
+ mountManifestForm(snapshot) {
9330
+ const workspace = this.workspace;
9331
+ if (!workspace) {
9332
+ return;
9333
+ }
9334
+ if (!this.manifestForm || !this.elPreviewContent.contains(this.manifestForm.root)) {
9335
+ this.manifestForm = new MdzipManifestForm(this.elRoot.ownerDocument, {
9336
+ editable: snapshot.mode !== 'read-only',
9337
+ markdownPaths: snapshot.content.paths.filter((entry) => entry.isMarkdown).map((entry) => entry.path),
9338
+ onChange: (path, value) => this.setManifestValue(path, value),
9339
+ onEditJson: () => {
9340
+ // In Split the JSON is already beside the form: just go to it.
9341
+ const show = this.layout === 'split' ? Promise.resolve() : this.setLayout('source');
9342
+ void show.then(() => this.cmEditor?.focus());
9343
+ }
9344
+ });
9345
+ this.elPreviewContent.replaceChildren(this.manifestForm.root);
9346
+ }
9347
+ // Edit as JSON only with a way back to the form: the toolbar's View button.
9348
+ // (In Split, where the JSON is beside the form, the CSS hides it anyway.)
9349
+ this.manifestForm.setEditJsonAvailable(this.controlPolicy.layout.preview);
9350
+ const validity = workspace.validateJsonText(snapshot.currentPath, snapshot.currentText);
9351
+ this.manifestForm.update(validity);
9352
+ this.setJsonValidity(validity, snapshot.currentPath);
9353
+ }
9354
+ // A change made in the form: one value set in the JSON text, through the
9355
+ // editor when there is one (so Ctrl+Z undoes it), else the workspace.
9356
+ setManifestValue(path, value) {
9357
+ const workspace = this.workspace;
9358
+ if (!workspace) {
9359
+ return;
9360
+ }
9361
+ const current = this.cmEditor && this.layout !== 'preview'
9362
+ ? this.cmEditor.state.doc.toString()
9363
+ : workspace.snapshot().currentText;
9364
+ const next = setMdzipJsonMember(current, path, value);
9365
+ if (next === null || next === current) {
9366
+ return;
9367
+ }
9368
+ const editor = this.cmEditor;
9369
+ if (editor && editor.state.doc.toString() === current) {
9370
+ editor.dispatch({ changes: { from: 0, to: current.length, insert: next }, userEvent: 'input.form' });
9371
+ }
9372
+ else {
9373
+ try {
9374
+ workspace.editText(next);
9375
+ }
9376
+ catch (error) {
9377
+ this.options.onFailed?.(error);
9378
+ }
9379
+ }
9380
+ }
7711
9381
  validLayoutForSnapshot(requested, snapshot) {
7712
9382
  if (requested === 'source' || requested === 'split') {
7713
9383
  return canShowSourceLayout(snapshot) ? requested : 'preview';
7714
9384
  }
7715
9385
  return requested;
7716
9386
  }
7717
- syncScrollFromPreview() {
7718
- if (this.syncing || !this.cmEditor || this.layout !== 'split') {
9387
+ /**
9388
+ * In Split, scrolls the source to match the preview. Normally only after
9389
+ * the reader scrolled the preview themselves; `driven` is for the editor's
9390
+ * own moves (going to a heading from the outline or a link), which no
9391
+ * gesture precedes.
9392
+ */
9393
+ syncScrollFromPreview(driven = false) {
9394
+ if (this.syncing || !this.cmEditor || this.layout !== 'split' || this.layoutIsManifest) {
7719
9395
  return;
7720
9396
  }
7721
- if (performance.now() - this.lastPreviewGestureTime > MdzipWorkspaceView.SCROLL_SYNC_GESTURE_WINDOW_MS) {
9397
+ if (!driven && performance.now() - this.lastPreviewGestureTime > MdzipWorkspaceView.SCROLL_SYNC_GESTURE_WINDOW_MS) {
7722
9398
  return;
7723
9399
  }
7724
9400
  if (performance.now() - this.lastContentChangeTime < MdzipWorkspaceView.SCROLL_SYNC_SETTLE_MS) {
@@ -7739,19 +9415,25 @@ export class MdzipWorkspaceView {
7739
9415
  return;
7740
9416
  }
7741
9417
  this.syncing = true;
7742
- const previewHeight = this.elPreviewPane.scrollHeight - this.elPreviewPane.clientHeight;
7743
- const scrollRatio = previewHeight > 0 ? currentTop / previewHeight : 0;
7744
9418
  const cmScroller = this.cmEditor.dom.querySelector('.cm-scroller');
7745
9419
  if (cmScroller) {
7746
- const editorHeight = cmScroller.scrollHeight - cmScroller.clientHeight;
7747
- const target = scrollRatio * editorHeight;
9420
+ const anchors = this.splitScrollAnchors('preview', currentTop);
9421
+ let target;
9422
+ if (anchors) {
9423
+ target = mapScrollPosition(currentTop, anchors.map(([editor, preview]) => [preview, editor]), this.elPreviewPane, cmScroller);
9424
+ }
9425
+ else {
9426
+ const previewHeight = this.elPreviewPane.scrollHeight - this.elPreviewPane.clientHeight;
9427
+ const scrollRatio = previewHeight > 0 ? currentTop / previewHeight : 0;
9428
+ target = scrollRatio * (cmScroller.scrollHeight - cmScroller.clientHeight);
9429
+ }
7748
9430
  this.lastSyncedEditorScrollTop = target;
7749
9431
  cmScroller.scrollTop = target;
7750
9432
  }
7751
9433
  this.syncing = false;
7752
9434
  }
7753
9435
  syncScrollToPreview() {
7754
- if (this.syncing || !this.cmEditor || this.layout !== 'split') {
9436
+ if (this.syncing || !this.cmEditor || this.layout !== 'split' || this.layoutIsManifest) {
7755
9437
  return;
7756
9438
  }
7757
9439
  if (performance.now() - this.lastEditorGestureTime > MdzipWorkspaceView.SCROLL_SYNC_GESTURE_WINDOW_MS) {
@@ -7807,13 +9489,141 @@ export class MdzipWorkspaceView {
7807
9489
  return;
7808
9490
  }
7809
9491
  this.syncing = true;
7810
- const scrollRatio = editorHeight > 0 ? currentTop / editorHeight : 0;
7811
- const previewHeight = this.elPreviewPane.scrollHeight - this.elPreviewPane.clientHeight;
7812
- const target = scrollRatio * previewHeight;
9492
+ const anchors = this.splitScrollAnchors('editor', currentTop);
9493
+ let target;
9494
+ if (anchors) {
9495
+ target = mapScrollPosition(currentTop, anchors, cmScroller, this.elPreviewPane);
9496
+ }
9497
+ else {
9498
+ const scrollRatio = editorHeight > 0 ? currentTop / editorHeight : 0;
9499
+ target = scrollRatio * (this.elPreviewPane.scrollHeight - this.elPreviewPane.clientHeight);
9500
+ }
7813
9501
  this.lastSyncedPreviewScrollTop = target;
7814
9502
  this.elPreviewPane.scrollTop = target;
7815
9503
  this.syncing = false;
7816
9504
  }
9505
+ /**
9506
+ * The two pairs of [offset in the editor, offset in the preview] for the
9507
+ * same content around `scrollTop` of one pane (#13), for
9508
+ * `mapScrollPosition` to interpolate between: the mounted top-level
9509
+ * blocks the renderer marked (`data-mdzip-block`), each at its token's
9510
+ * first source line. The panes stay together past a tall image, table or
9511
+ * code block, where one ratio for the whole document drifts. Null when
9512
+ * nothing is marked (a custom renderer) or the preview isn't laid out:
9513
+ * the sync falls back to that ratio.
9514
+ *
9515
+ * Only the two blocks around the position are measured, found by binary
9516
+ * search (both panes keep blocks in document order), so a scroll costs
9517
+ * the same in a document of any length.
9518
+ */
9519
+ splitScrollAnchors(from, scrollTop) {
9520
+ const editor = this.cmEditor;
9521
+ const blocks = this.splitScrollBlocks();
9522
+ if (!editor || !blocks || !this.elPreviewContent.offsetHeight) {
9523
+ return null;
9524
+ }
9525
+ const scroller = editor.scrollDOM;
9526
+ const pane = this.elPreviewPane;
9527
+ const previewOrigin = pane.scrollTop - pane.getBoundingClientRect().top;
9528
+ const editorOrigin = editor.documentTop - scroller.getBoundingClientRect().top + scroller.scrollTop;
9529
+ const editorTop = (i) => editor.lineBlockAt(Math.min(blocks.offsets[i], editor.state.doc.length)).top + editorOrigin;
9530
+ const previewTop = (i) => blocks.elements[i].getBoundingClientRect().top + previewOrigin;
9531
+ const top = from === 'editor' ? editorTop : previewTop;
9532
+ // The last block at or above scrollTop (-1: above the first).
9533
+ let low = 0;
9534
+ let high = blocks.offsets.length - 1;
9535
+ let at = -1;
9536
+ while (low <= high) {
9537
+ const mid = (low + high) >> 1;
9538
+ if (top(mid) <= scrollTop) {
9539
+ at = mid;
9540
+ low = mid + 1;
9541
+ }
9542
+ else {
9543
+ high = mid - 1;
9544
+ }
9545
+ }
9546
+ const anchors = [];
9547
+ for (const i of [at, at + 1]) {
9548
+ if (i >= 0 && i < blocks.offsets.length) {
9549
+ anchors.push([editorTop(i), previewTop(i)]);
9550
+ }
9551
+ }
9552
+ return anchors;
9553
+ }
9554
+ /**
9555
+ * The preview's mounted, marked blocks in order, each with its token's
9556
+ * offset in the editor's text. Offsets come from each token's `raw` text,
9557
+ * found in order in the editor's current text rather than counted from
9558
+ * the tokens: front matter is stripped before tokenizing, and the preview
9559
+ * can be a render behind the editor while typing (a block not found is
9560
+ * left out). Kept until the text or the mounted chunks change; no layout
9561
+ * is read here.
9562
+ */
9563
+ splitScrollBlocks() {
9564
+ const editor = this.cmEditor;
9565
+ const state = this.chunkedRenderState;
9566
+ if (!editor || !state) {
9567
+ return null;
9568
+ }
9569
+ const cached = this.splitBlockCache;
9570
+ if (cached && cached.doc === editor.state.doc && cached.records === state.records && cached.cursor === state.cursor) {
9571
+ return cached.blocks;
9572
+ }
9573
+ const text = editor.state.doc.toString();
9574
+ const offsets = [];
9575
+ const elements = [];
9576
+ let cursor = 0;
9577
+ let located = false;
9578
+ for (const record of state.records) {
9579
+ const tokenOffsets = [];
9580
+ for (const token of record.tokens) {
9581
+ const raw = token.raw;
9582
+ let at = -1;
9583
+ if (raw) {
9584
+ if (text.startsWith(raw, cursor)) {
9585
+ at = cursor;
9586
+ }
9587
+ else if (!located) {
9588
+ // The first block can come after front matter of any length.
9589
+ at = text.indexOf(raw, cursor);
9590
+ }
9591
+ else {
9592
+ // Later, only look a little ahead: a block edited since the
9593
+ // preview rendered isn't in the text, and mustn't cost a scan
9594
+ // of the rest of the document.
9595
+ const found = text.slice(cursor, cursor + raw.length + 4096).indexOf(raw);
9596
+ at = found < 0 ? -1 : cursor + found;
9597
+ }
9598
+ }
9599
+ tokenOffsets.push(at);
9600
+ if (at >= 0) {
9601
+ located = true;
9602
+ cursor = at + raw.length;
9603
+ }
9604
+ }
9605
+ if (!record.root) {
9606
+ continue;
9607
+ }
9608
+ // At any depth: the preview wraps some blocks after mounting (a code
9609
+ // block in its header box). Not inside another block, though: only
9610
+ // raw HTML written that way could put one there.
9611
+ for (const element of Array.from(record.root.querySelectorAll(`[${MDZIP_BLOCK_ATTRIBUTE}]`))) {
9612
+ if (element.parentElement?.closest(`[${MDZIP_BLOCK_ATTRIBUTE}]`)) {
9613
+ continue;
9614
+ }
9615
+ const index = Number(element.getAttribute(MDZIP_BLOCK_ATTRIBUTE) ?? NaN);
9616
+ const offset = Number.isInteger(index) ? tokenOffsets[index] ?? -1 : -1;
9617
+ if (offset >= 0) {
9618
+ offsets.push(offset);
9619
+ elements.push(element);
9620
+ }
9621
+ }
9622
+ }
9623
+ const blocks = offsets.length ? { offsets, elements } : null;
9624
+ this.splitBlockCache = { doc: editor.state.doc, records: state.records, cursor: state.cursor, blocks };
9625
+ return blocks;
9626
+ }
7817
9627
  /**
7818
9628
  * Handles syncScrollToPreview's bottom edge when the preview still has
7819
9629
  * unmounted chunks: force-mounts the rest (same drain Copy All uses) so
@@ -8045,349 +9855,388 @@ function formatMetadataValue(value) {
8045
9855
  }
8046
9856
  return 'Not available';
8047
9857
  }
8048
- const SHELL_HTML = `
8049
- <section class="mdzip-root">
8050
- <div class="document-strip" data-ref="document-strip" hidden>
8051
- <button type="button" class="title-button" data-ref="title-btn"></button>
8052
- <button type="button" class="document-info-button" data-ref="document-info-btn"
8053
- title="Document information" aria-label="Document information">
8054
- ${INFO_ICON_HTML}
8055
- </button>
8056
- </div>
8057
-
8058
- <header class="toolbar" data-ref="toolbar" hidden>
8059
- <div class="toolbar-start">
8060
- <div class="toolbar-left">
8061
- <button type="button" class="icon-toggle nav-toggle" data-ref="nav-btn" title="Toggle contents" aria-label="Toggle contents">
8062
- ${NAV_TOGGLE_ICON_HTML}
8063
- </button>
8064
- </div>
8065
-
8066
- <div class="edit-toolbar" data-ref="edit-toolbar" role="toolbar" aria-label="Markdown formatting">
8067
- <div class="edit-toolbar-group">
8068
- <button type="button" data-format="bold" data-format-control="bold" title="Bold" aria-label="Bold">${BOLD_ICON_HTML}</button>
8069
- <button type="button" data-format="italic" data-format-control="italic" title="Italic" aria-label="Italic">${ITALIC_ICON_HTML}</button>
8070
- <button type="button" data-format="strike" data-format-control="strikethrough" title="Strikethrough" aria-label="Strikethrough">${STRIKE_ICON_HTML}</button>
8071
- <div class="format-menu" data-format-control="headings">
8072
- <button type="button" class="format-menu-toggle" data-format-menu-toggle
8073
- aria-label="Heading" aria-haspopup="menu" aria-expanded="false">
8074
- ${HEADING_ICON_HTML}${CHEVRON_ICON_HTML}
8075
- </button>
8076
- <div class="format-menu-popover" data-format-menu role="menu" aria-label="Heading level" hidden>
8077
- <button type="button" role="menuitem" data-format="paragraph">Paragraph</button>
8078
- <button type="button" role="menuitem" data-format="heading-1" data-heading-level="1"><strong>H1</strong> Heading 1</button>
8079
- <button type="button" role="menuitem" data-format="heading-2" data-heading-level="2"><strong>H2</strong> Heading 2</button>
8080
- <button type="button" role="menuitem" data-format="heading-3" data-heading-level="3"><strong>H3</strong> Heading 3</button>
8081
- <button type="button" role="menuitem" data-format="heading-4" data-heading-level="4"><strong>H4</strong> Heading 4</button>
8082
- <button type="button" role="menuitem" data-format="heading-5" data-heading-level="5"><strong>H5</strong> Heading 5</button>
8083
- <button type="button" role="menuitem" data-format="heading-6" data-heading-level="6"><strong>H6</strong> Heading 6</button>
8084
- </div>
8085
- </div>
8086
- </div>
8087
- <span class="edit-toolbar-divider" aria-hidden="true"></span>
8088
- <div class="edit-toolbar-group">
8089
- <button type="button" data-format="bullet-list" data-format-control="bulletList" title="Bulleted list" aria-label="Bulleted list">${BULLET_LIST_ICON_HTML}</button>
8090
- <button type="button" data-format="ordered-list" data-format-control="orderedList" title="Numbered list" aria-label="Numbered list">${ORDERED_LIST_ICON_HTML}</button>
8091
- <div class="format-menu" data-format-control="code">
8092
- <button type="button" class="format-menu-toggle" data-format-menu-toggle
8093
- aria-label="Code" aria-haspopup="menu" aria-expanded="false">
8094
- ${CODE_ICON_HTML}${CHEVRON_ICON_HTML}
8095
- </button>
8096
- <div class="format-menu-popover" data-format-menu role="menu" aria-label="Code format" hidden>
8097
- <button type="button" role="menuitem" data-format="code" data-code-kind="inline">Inline code</button>
8098
- <button type="button" role="menuitem" data-format="code-block" data-code-kind="block">Code block</button>
8099
- </div>
8100
- </div>
8101
- <button type="button" data-format="quote" data-format-control="blockquote" title="Blockquote" aria-label="Blockquote">${QUOTE_ICON_HTML}</button>
8102
- <button type="button" data-format="line-break" data-format-control="lineBreak" title="Line break" aria-label="Line break">${LINE_BREAK_ICON_HTML}</button>
8103
- </div>
8104
- <span class="edit-toolbar-divider" aria-hidden="true"></span>
8105
- <div class="edit-toolbar-group">
8106
- <button type="button" data-format="link" data-format-control="link" title="Link" aria-label="Link">${LINK_ICON_HTML}</button>
8107
- <button type="button" data-format="image" data-format-control="image" title="Image" aria-label="Image">${IMAGE_FORMAT_ICON_HTML}</button>
8108
- <input type="file" data-ref="image-input" accept="image/*" hidden />
8109
- </div>
8110
- </div>
8111
- </div>
8112
-
8113
- <div class="toolbar-buttons view-mode-toggle-group" data-ref="layout-controls" role="group" aria-label="Editor layout">
8114
- <button type="button" class="icon-toggle view-mode-toggle" data-ref="source-btn" title="Edit" aria-label="Edit" aria-pressed="false">
8115
- <span class="commandbar-flex-container" data-ref="source-icon">${SOURCE_EDIT_ICON_HTML}</span>
8116
- </button>
8117
- <button type="button" class="icon-toggle view-mode-toggle" data-ref="split-btn" title="Split" aria-label="Split" aria-pressed="false">
8118
- <span class="commandbar-flex-container">
8119
- ${SPLIT_ICON_HTML}
8120
- </span>
8121
- </button>
8122
- <button type="button" class="icon-toggle view-mode-toggle" data-ref="preview-btn" title="View" aria-label="View" aria-pressed="false">
8123
- <span class="commandbar-flex-container">
8124
- ${PREVIEW_ICON_HTML}
8125
- </span>
8126
- </button>
8127
- </div>
8128
-
8129
- <div class="toolbar-controls" data-ref="toolbar-controls">
8130
- <button type="button" class="icon-toggle" data-ref="search-btn" title="Find/replace (Mod-F)" aria-label="Find/replace">
8131
- ${SEARCH_ICON_HTML}
8132
- </button>
8133
- <button type="button" class="icon-toggle" data-ref="save-btn" title="Save" aria-label="Save">
8134
- ${SAVE_ICON_HTML}
8135
- </button>
8136
- <button type="button" class="icon-toggle zoom-toggle" data-ref="zoom-btn" title="Zoom controls" aria-label="Zoom controls">
8137
- ${ZOOM_ICON_HTML}
8138
- </button>
8139
- <div class="toolbar-menu width-menu" data-ref="width-controls">
8140
- <button type="button" class="icon-toggle toolbar-menu-toggle" data-ref="width-menu-btn"
8141
- title="Page width" aria-label="Page width" aria-haspopup="menu" aria-expanded="false">
8142
- <span class="toolbar-menu-icon" data-ref="width-menu-icon">${PAGE_WIDTH_DEFAULT_ICON_HTML}</span>
8143
- </button>
8144
- <div class="toolbar-popover" data-ref="width-popover" role="menu" aria-label="Page width" hidden>
8145
- ${['narrow', 'default', 'wide', 'full'].map((choice) => `
8146
- <button type="button" role="menuitemradio" class="icon-toggle toolbar-menu-item" data-width="${choice}"
8147
- title="${PREVIEW_WIDTH_LABELS[choice]}" aria-label="${PREVIEW_WIDTH_LABELS[choice]}" aria-checked="false">
8148
- ${PREVIEW_WIDTH_ICONS_HTML[choice]}
8149
- </button>`).join('')}
8150
- </div>
8151
- </div>
8152
- <div class="theme-menu" data-ref="theme-controls">
8153
- <button type="button" class="icon-toggle theme-menu-toggle" data-ref="theme-menu-btn"
8154
- title="Color scheme" aria-label="Color scheme" aria-haspopup="menu" aria-expanded="false">
8155
- <span class="theme-menu-icon" data-ref="theme-menu-icon">${SYSTEM_THEME_ICON_HTML}</span>
8156
- </button>
8157
- <div class="theme-popover" data-ref="theme-popover" role="menu" aria-label="Color scheme" hidden>
8158
- <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="light-theme-btn"
8159
- title="Light mode" aria-label="Light mode" aria-checked="false">
8160
- ${LIGHT_THEME_ICON_HTML}
8161
- </button>
8162
- <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="dark-theme-btn"
8163
- title="Dark mode" aria-label="Dark mode" aria-checked="false">
8164
- ${DARK_THEME_ICON_HTML}
8165
- </button>
8166
- <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="system-theme-btn"
8167
- title="System setting" aria-label="System setting" aria-checked="false">
8168
- ${SYSTEM_THEME_ICON_HTML}
8169
- </button>
8170
- </div>
8171
- </div>
8172
- <div class="zoom-popover" data-ref="zoom-popover" hidden role="group" aria-label="Zoom">
8173
- <span class="zoom-level" data-ref="zoom-level">100%</span>
8174
- <span class="zoom-stepper">
8175
- <button type="button" data-action="zoom-out" title="Zoom out" aria-label="Zoom out">-</button>
8176
- <button type="button" data-action="zoom-in" title="Zoom in" aria-label="Zoom in">+</button>
8177
- </span>
8178
- <button type="button" class="zoom-reset" data-action="zoom-reset" title="Reset zoom">Reset</button>
8179
- </div>
8180
- </div>
8181
- </header>
8182
-
8183
- <div class="workspace-shell" data-ref="workspace-shell" hidden>
8184
- <aside class="nav-pane" data-ref="nav-pane" aria-label="Package contents">
8185
- <div class="nav-tree" data-ref="nav-tree"></div>
8186
- </aside>
8187
- <div class="nav-resizer" data-ref="nav-resizer"
8188
- role="separator" aria-orientation="vertical" aria-label="Resize contents pane"></div>
8189
-
8190
- <div class="pane-stack" data-ref="pane-stack">
8191
- <section class="pane edit-pane" data-ref="edit-pane">
8192
- <div class="editor-host" data-ref="editor-host"></div>
8193
- </section>
8194
- <div class="split-resizer" data-ref="split-resizer"
8195
- role="separator" aria-orientation="vertical" aria-label="Resize split panes"></div>
8196
- <section class="pane preview-pane" data-ref="preview-pane" tabindex="-1">
8197
- <article class="preview-content" data-ref="preview-content"></article>
8198
- </section>
8199
- <section class="pane entry-pane" data-ref="entry-pane"></section>
8200
- </div>
8201
- </div>
8202
-
8203
- <div class="title-dialog-backdrop" data-ref="title-dialog" hidden
8204
- role="dialog" aria-modal="true" aria-labelledby="mdzip-title-dialog-heading">
8205
- <div class="title-dialog">
8206
- <h3 id="mdzip-title-dialog-heading">Set Document Title</h3>
8207
- <p>This is the package-level title stored in manifest.json.</p>
8208
- <input type="text" maxlength="120" data-ref="title-input" aria-label="Document title" />
8209
- <p class="title-dialog-validation" data-ref="title-validation" hidden>Title cannot be empty.</p>
8210
- <p>If unset, consumers may fall back to entry point, filename, or first heading.</p>
8211
- <div class="title-dialog-actions">
8212
- <button type="button" class="reset-title" data-ref="title-reset-btn">Reset</button>
8213
- <button type="button" data-action="cancel-title">Cancel</button>
8214
- <button type="button" class="save-title" data-ref="title-save-btn">Save</button>
8215
- </div>
8216
- </div>
8217
- </div>
8218
-
8219
- <div class="title-dialog-backdrop" data-ref="conversion-dialog" hidden
8220
- role="dialog" aria-modal="true" aria-labelledby="mdzip-conversion-dialog-heading">
8221
- <div class="title-dialog">
8222
- <h3 id="mdzip-conversion-dialog-heading">Convert to MDZ?</h3>
8223
- <p>
8224
- Regular Markdown files contain only text. Convert this document to an
8225
- MDZ package to add images, package navigation, and document metadata.
8226
- </p>
8227
- <p>The next save will produce an .mdz file.</p>
8228
- <div class="title-dialog-actions">
8229
- <button type="button" data-action="cancel-conversion">Cancel</button>
8230
- <button type="button" class="save-title" data-ref="conversion-confirm-btn">Convert</button>
8231
- </div>
8232
- </div>
8233
- </div>
8234
-
8235
- <div class="title-dialog-backdrop" data-ref="image-insert-dialog" hidden
8236
- role="dialog" aria-modal="true" aria-labelledby="mdzip-image-insert-dialog-heading">
8237
- <div class="title-dialog image-insert-dialog">
8238
- <h3 id="mdzip-image-insert-dialog-heading">Insert Image</h3>
8239
- <p>Choose the Markdown inserted for this image.</p>
8240
- <fieldset class="image-insert-options">
8241
- <legend>Output</legend>
8242
- <label>
8243
- <input type="radio" name="mdzip-image-insert-mode" value="markdown"
8244
- data-ref="image-insert-mode-markdown" checked />
8245
- Markdown image
8246
- </label>
8247
- <label>
8248
- <input type="radio" name="mdzip-image-insert-mode" value="html"
8249
- data-ref="image-insert-mode-html" />
8250
- HTML &lt;img&gt; with sizing
8251
- </label>
8252
- </fieldset>
8253
- <label class="image-insert-field">
8254
- <span>Alt text</span>
8255
- <input type="text" data-ref="image-insert-alt" />
8256
- </label>
8257
- <div class="image-insert-grid">
8258
- <label class="image-insert-field">
8259
- <span>Size by</span>
8260
- <select data-ref="image-insert-size-mode">
8261
- <option value="original">Original size</option>
8262
- <option value="width" selected>Width</option>
8263
- <option value="height">Height</option>
8264
- <option value="percent">Percent</option>
8265
- </select>
8266
- </label>
8267
- <label class="image-insert-field">
8268
- <span>Value</span>
8269
- <input type="number" min="1" step="1" data-ref="image-insert-size-value" />
8270
- </label>
8271
- </div>
8272
- <label class="image-insert-field">
8273
- <span>Position</span>
8274
- <select data-ref="image-insert-position">
8275
- <option value="inline">Inline/default</option>
8276
- <option value="left">Left</option>
8277
- <option value="center">Center</option>
8278
- <option value="right">Right</option>
8279
- <option value="wrap-left">Wrap left</option>
8280
- <option value="wrap-right">Wrap right</option>
8281
- </select>
8282
- </label>
8283
- <div class="title-dialog-actions">
8284
- <button type="button" data-action="cancel-image-insert">Cancel</button>
8285
- <button type="button" class="save-title" data-ref="image-insert-confirm-btn">Insert</button>
8286
- </div>
8287
- </div>
8288
- </div>
8289
-
8290
- <div class="title-dialog-backdrop" data-ref="pack-files-dialog" hidden
8291
- role="dialog" aria-modal="true" aria-labelledby="mdzip-pack-files-dialog-heading">
8292
- <div class="title-dialog pack-files-dialog">
8293
- <h3 id="mdzip-pack-files-dialog-heading">Package Markdown Files</h3>
8294
- <p>These files contain more than one Markdown document. Choose how to package them.</p>
8295
- <fieldset class="pack-files-options">
8296
- <legend>Mode</legend>
8297
- <label>
8298
- <input type="radio" name="mdzip-pack-files-mode" value="document"
8299
- data-ref="pack-files-mode-document" checked />
8300
- Document — one primary page; the rest are attached
8301
- </label>
8302
- <label>
8303
- <input type="radio" name="mdzip-pack-files-mode" value="project"
8304
- data-ref="pack-files-mode-project" />
8305
- Project — a set of related documents
8306
- </label>
8307
- </fieldset>
8308
- <label class="pack-files-field">
8309
- <span>Entry point</span>
8310
- <select data-ref="pack-files-entry"></select>
8311
- </label>
8312
- <div class="title-dialog-actions">
8313
- <button type="button" data-action="cancel-pack-files">Cancel</button>
8314
- <button type="button" class="save-title" data-ref="pack-files-confirm-btn">Package</button>
8315
- </div>
8316
- </div>
8317
- </div>
8318
-
8319
- <div class="title-dialog-backdrop" data-ref="copy-render-dialog" hidden
8320
- role="dialog" aria-modal="true" aria-labelledby="mdzip-copy-render-dialog-heading">
8321
- <div class="title-dialog copy-render-dialog">
8322
- <h3 id="mdzip-copy-render-dialog-heading" data-ref="copy-render-heading">Copying document...</h3>
8323
- <div data-ref="copy-render-progress-section">
8324
- <p data-ref="copy-render-progress-text">Rendering the full document...</p>
8325
- <div class="copy-render-progress-track">
8326
- <div class="copy-render-progress-bar" data-ref="copy-render-progress-bar"></div>
8327
- </div>
8328
- </div>
8329
- <p data-ref="copy-render-ready-text" hidden>
8330
- The document is ready. Browsers only allow a clipboard write right after a click, so this needs one more —
8331
- click Copy to finish.
8332
- </p>
8333
- <p data-ref="copy-render-done-text" hidden></p>
8334
- <div class="title-dialog-actions">
8335
- <button type="button" data-action="cancel-copy-render" data-ref="copy-render-cancel-btn">Cancel</button>
8336
- <button type="button" data-action="cancel-copy-ready" data-ref="copy-render-ready-cancel-btn" hidden>Cancel</button>
8337
- <button type="button" class="save-title" data-action="confirm-copy-ready" data-ref="copy-render-confirm-btn" hidden>Copy</button>
8338
- <button type="button" class="save-title" data-action="dismiss-copy-render" data-ref="copy-render-dismiss-btn" hidden>Dismiss</button>
8339
- </div>
8340
- </div>
8341
- </div>
8342
-
8343
- <div class="title-dialog-backdrop" data-ref="metadata-dialog" hidden
8344
- role="dialog" aria-modal="true" aria-labelledby="mdzip-metadata-dialog-heading">
8345
- <div class="title-dialog metadata-dialog">
8346
- <h3 id="mdzip-metadata-dialog-heading">Document Information</h3>
8347
- <dl data-ref="metadata-list"></dl>
8348
- <h4>Libraries</h4>
8349
- <dl data-ref="library-list"></dl>
8350
- <div class="title-dialog-actions">
8351
- <button type="button" class="save-title" data-action="close-metadata">Close</button>
8352
- </div>
8353
- </div>
8354
- </div>
8355
-
8356
- <div class="title-dialog-backdrop" data-ref="name-dialog" hidden
8357
- role="dialog" aria-modal="true" aria-labelledby="mdzip-name-dialog-heading">
8358
- <div class="title-dialog">
8359
- <h3 id="mdzip-name-dialog-heading" data-ref="name-dialog-heading">New Markdown File</h3>
8360
- <input type="text" maxlength="260" data-ref="name-input" aria-label="File name" />
8361
- <p class="title-dialog-validation" data-ref="name-validation" hidden></p>
8362
- <div class="title-dialog-actions">
8363
- <button type="button" data-action="cancel-name">Cancel</button>
8364
- <button type="button" class="save-title" data-ref="name-confirm-btn">Create</button>
8365
- </div>
8366
- </div>
8367
- </div>
8368
-
8369
- <div class="title-dialog-backdrop" data-ref="delete-dialog" hidden
8370
- role="dialog" aria-modal="true" aria-labelledby="mdzip-delete-dialog-heading">
8371
- <div class="title-dialog">
8372
- <h3 id="mdzip-delete-dialog-heading">Delete File?</h3>
8373
- <p data-ref="delete-dialog-text"></p>
8374
- <div class="title-dialog-actions">
8375
- <button type="button" data-action="cancel-delete">Cancel</button>
8376
- <button type="button" class="danger-action" data-ref="delete-confirm-btn">Delete</button>
8377
- </div>
8378
- </div>
8379
- </div>
8380
-
8381
- <input type="file" data-ref="replace-input" hidden />
8382
- <input type="file" data-ref="add-files-input" multiple hidden />
8383
-
8384
- <div class="nav-context-menu" data-ref="nav-menu" hidden role="menu"></div>
8385
-
8386
- <div class="mdzip-tooltip" data-ref="tooltip" role="tooltip" hidden></div>
8387
-
8388
- <div class="mdzip-copy-toast" data-ref="copy-toast" role="status" aria-live="polite" hidden></div>
8389
-
8390
- <p class="mdzip-empty" data-ref="empty-state">No MDZip workspace loaded.</p>
8391
- </section>
9858
+ const SHELL_HTML = `
9859
+ <section class="mdzip-root">
9860
+ <div class="document-strip" data-ref="document-strip" hidden>
9861
+ <button type="button" class="title-button" data-ref="title-btn"></button>
9862
+ <button type="button" class="document-info-button" data-ref="document-info-btn"
9863
+ title="Document information" aria-label="Document information">
9864
+ ${INFO_ICON_HTML}
9865
+ </button>
9866
+ </div>
9867
+
9868
+ <header class="toolbar" data-ref="toolbar" hidden>
9869
+ <div class="toolbar-start">
9870
+ <div class="toolbar-left">
9871
+ <button type="button" class="icon-toggle nav-toggle" data-ref="nav-btn" title="Toggle contents" aria-label="Toggle contents">
9872
+ ${NAV_TOGGLE_ICON_HTML}
9873
+ </button>
9874
+ </div>
9875
+
9876
+ <div class="edit-toolbar" data-ref="edit-toolbar" role="toolbar" aria-label="Editing">
9877
+ <div class="edit-toolbar-group">
9878
+ <button type="button" data-format="bold" data-format-control="bold" title="Bold" aria-label="Bold">${BOLD_ICON_HTML}</button>
9879
+ <button type="button" data-format="italic" data-format-control="italic" title="Italic" aria-label="Italic">${ITALIC_ICON_HTML}</button>
9880
+ <button type="button" data-format="strike" data-format-control="strikethrough" title="Strikethrough" aria-label="Strikethrough">${STRIKE_ICON_HTML}</button>
9881
+ <div class="format-menu" data-format-control="headings">
9882
+ <button type="button" class="format-menu-toggle" data-format-menu-toggle
9883
+ aria-label="Heading" aria-haspopup="menu" aria-expanded="false">
9884
+ ${HEADING_ICON_HTML}${CHEVRON_ICON_HTML}
9885
+ </button>
9886
+ <div class="format-menu-popover" data-format-menu role="menu" aria-label="Heading level" hidden>
9887
+ <button type="button" role="menuitem" data-format="paragraph">Paragraph</button>
9888
+ <button type="button" role="menuitem" data-format="heading-1" data-heading-level="1"><strong>H1</strong> Heading 1</button>
9889
+ <button type="button" role="menuitem" data-format="heading-2" data-heading-level="2"><strong>H2</strong> Heading 2</button>
9890
+ <button type="button" role="menuitem" data-format="heading-3" data-heading-level="3"><strong>H3</strong> Heading 3</button>
9891
+ <button type="button" role="menuitem" data-format="heading-4" data-heading-level="4"><strong>H4</strong> Heading 4</button>
9892
+ <button type="button" role="menuitem" data-format="heading-5" data-heading-level="5"><strong>H5</strong> Heading 5</button>
9893
+ <button type="button" role="menuitem" data-format="heading-6" data-heading-level="6"><strong>H6</strong> Heading 6</button>
9894
+ </div>
9895
+ </div>
9896
+ </div>
9897
+ <span class="edit-toolbar-divider" aria-hidden="true"></span>
9898
+ <div class="edit-toolbar-group">
9899
+ <button type="button" data-format="bullet-list" data-format-control="bulletList" title="Bulleted list" aria-label="Bulleted list">${BULLET_LIST_ICON_HTML}</button>
9900
+ <button type="button" data-format="ordered-list" data-format-control="orderedList" title="Numbered list" aria-label="Numbered list">${ORDERED_LIST_ICON_HTML}</button>
9901
+ <div class="format-menu" data-format-control="code">
9902
+ <button type="button" class="format-menu-toggle" data-format-menu-toggle
9903
+ aria-label="Code" aria-haspopup="menu" aria-expanded="false">
9904
+ ${CODE_ICON_HTML}${CHEVRON_ICON_HTML}
9905
+ </button>
9906
+ <div class="format-menu-popover" data-format-menu role="menu" aria-label="Code format" hidden>
9907
+ <button type="button" role="menuitem" data-format="code" data-code-kind="inline">Inline code</button>
9908
+ <button type="button" role="menuitem" data-format="code-block" data-code-kind="block">Code block</button>
9909
+ </div>
9910
+ </div>
9911
+ <button type="button" data-format="quote" data-format-control="blockquote" title="Blockquote" aria-label="Blockquote">${QUOTE_ICON_HTML}</button>
9912
+ <button type="button" data-format="line-break" data-format-control="lineBreak" title="Line break" aria-label="Line break">${LINE_BREAK_ICON_HTML}</button>
9913
+ </div>
9914
+ <span class="edit-toolbar-divider" aria-hidden="true"></span>
9915
+ <div class="edit-toolbar-group">
9916
+ <button type="button" data-format="link" data-format-control="link" title="Link" aria-label="Link">${LINK_ICON_HTML}</button>
9917
+ <button type="button" data-format="image" data-format-control="image" title="Image" aria-label="Image">${IMAGE_FORMAT_ICON_HTML}</button>
9918
+ <input type="file" data-ref="image-input" accept="image/*" hidden />
9919
+ </div>
9920
+ <span class="edit-toolbar-divider" aria-hidden="true"></span>
9921
+ <div class="edit-toolbar-group">
9922
+ <button type="button" data-ref="format-json-btn" data-format-control="formatJson"
9923
+ title="Format JSON (Shift+Alt+F)" aria-label="Format JSON">${FORMAT_JSON_ICON_HTML}</button>
9924
+ <button type="button" class="edit-toolbar-toggle" data-ref="whitespace-btn" data-format-control="whitespace"
9925
+ title="Show whitespace" aria-label="Show whitespace" aria-pressed="false">${WHITESPACE_ICON_HTML}</button>
9926
+ </div>
9927
+ </div>
9928
+ </div>
9929
+
9930
+ <div class="toolbar-buttons view-mode-toggle-group" data-ref="layout-controls" role="group" aria-label="Editor layout">
9931
+ <button type="button" class="icon-toggle view-mode-toggle" data-ref="source-btn" title="Edit" aria-label="Edit" aria-pressed="false">
9932
+ <span class="commandbar-flex-container" data-ref="source-icon">${SOURCE_EDIT_ICON_HTML}</span>
9933
+ </button>
9934
+ <button type="button" class="icon-toggle view-mode-toggle" data-ref="split-btn" title="Split" aria-label="Split" aria-pressed="false">
9935
+ <span class="commandbar-flex-container">
9936
+ ${SPLIT_ICON_HTML}
9937
+ </span>
9938
+ </button>
9939
+ <button type="button" class="icon-toggle view-mode-toggle" data-ref="preview-btn" title="View" aria-label="View" aria-pressed="false">
9940
+ <span class="commandbar-flex-container">
9941
+ ${PREVIEW_ICON_HTML}
9942
+ </span>
9943
+ </button>
9944
+ </div>
9945
+
9946
+ <div class="toolbar-controls" data-ref="toolbar-controls">
9947
+ <button type="button" class="icon-toggle outline-toggle" data-ref="outline-btn" title="Outline" aria-label="Outline" aria-pressed="false">
9948
+ ${OUTLINE_ICON_HTML}
9949
+ </button>
9950
+ <button type="button" class="icon-toggle" data-ref="search-btn" title="Find/replace (Mod-F)" aria-label="Find/replace">
9951
+ ${SEARCH_ICON_HTML}
9952
+ </button>
9953
+ <button type="button" class="icon-toggle" data-ref="save-btn" title="Save" aria-label="Save">
9954
+ ${SAVE_ICON_HTML}
9955
+ </button>
9956
+ <button type="button" class="icon-toggle zoom-toggle" data-ref="zoom-btn" title="Zoom controls" aria-label="Zoom controls">
9957
+ ${ZOOM_ICON_HTML}
9958
+ </button>
9959
+ <div class="toolbar-menu width-menu" data-ref="width-controls">
9960
+ <button type="button" class="icon-toggle toolbar-menu-toggle" data-ref="width-menu-btn"
9961
+ title="Page width" aria-label="Page width" aria-haspopup="menu" aria-expanded="false">
9962
+ <span class="toolbar-menu-icon" data-ref="width-menu-icon">${PAGE_WIDTH_DEFAULT_ICON_HTML}</span>
9963
+ </button>
9964
+ <div class="toolbar-popover" data-ref="width-popover" role="menu" aria-label="Page width" hidden>
9965
+ ${['narrow', 'default', 'wide', 'full'].map((choice) => `
9966
+ <button type="button" role="menuitemradio" class="icon-toggle toolbar-menu-item" data-width="${choice}"
9967
+ title="${PREVIEW_WIDTH_LABELS[choice]}" aria-label="${PREVIEW_WIDTH_LABELS[choice]}" aria-checked="false">
9968
+ ${PREVIEW_WIDTH_ICONS_HTML[choice]}
9969
+ </button>`).join('')}
9970
+ </div>
9971
+ </div>
9972
+ <div class="theme-menu" data-ref="theme-controls">
9973
+ <button type="button" class="icon-toggle theme-menu-toggle" data-ref="theme-menu-btn"
9974
+ title="Color scheme" aria-label="Color scheme" aria-haspopup="menu" aria-expanded="false">
9975
+ <span class="theme-menu-icon" data-ref="theme-menu-icon">${SYSTEM_THEME_ICON_HTML}</span>
9976
+ </button>
9977
+ <div class="theme-popover" data-ref="theme-popover" role="menu" aria-label="Color scheme" hidden>
9978
+ <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="light-theme-btn"
9979
+ title="Light mode" aria-label="Light mode" aria-checked="false">
9980
+ ${LIGHT_THEME_ICON_HTML}
9981
+ </button>
9982
+ <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="dark-theme-btn"
9983
+ title="Dark mode" aria-label="Dark mode" aria-checked="false">
9984
+ ${DARK_THEME_ICON_HTML}
9985
+ </button>
9986
+ <button type="button" role="menuitemradio" class="icon-toggle theme-toggle" data-ref="system-theme-btn"
9987
+ title="System setting" aria-label="System setting" aria-checked="false">
9988
+ ${SYSTEM_THEME_ICON_HTML}
9989
+ </button>
9990
+ </div>
9991
+ </div>
9992
+ <div class="zoom-popover" data-ref="zoom-popover" hidden role="group" aria-label="Zoom">
9993
+ <span class="zoom-level" data-ref="zoom-level">100%</span>
9994
+ <span class="zoom-stepper">
9995
+ <button type="button" data-action="zoom-out" title="Zoom out" aria-label="Zoom out">-</button>
9996
+ <button type="button" data-action="zoom-in" title="Zoom in" aria-label="Zoom in">+</button>
9997
+ </span>
9998
+ <button type="button" class="zoom-reset" data-action="zoom-reset" title="Reset zoom">Reset</button>
9999
+ </div>
10000
+ </div>
10001
+ </header>
10002
+
10003
+ <div class="workspace-shell" data-ref="workspace-shell" hidden>
10004
+ <aside class="nav-pane" data-ref="nav-pane" aria-label="Package contents">
10005
+ <div class="nav-tree" data-ref="nav-tree"></div>
10006
+ </aside>
10007
+ <div class="nav-resizer" data-ref="nav-resizer"
10008
+ role="separator" aria-orientation="vertical" aria-label="Resize contents pane"></div>
10009
+
10010
+ <div class="pane-stack" data-ref="pane-stack">
10011
+ <section class="pane edit-pane" data-ref="edit-pane">
10012
+ <div class="editor-host" data-ref="editor-host"></div>
10013
+ <div class="json-status" data-ref="json-status" role="status" aria-live="polite" hidden></div>
10014
+ </section>
10015
+ <div class="split-resizer" data-ref="split-resizer"
10016
+ role="separator" aria-orientation="vertical" aria-label="Resize split panes"></div>
10017
+ <section class="pane preview-pane" data-ref="preview-pane" tabindex="-1">
10018
+ <article class="preview-content" data-ref="preview-content"></article>
10019
+ </section>
10020
+ <div class="preview-find" data-ref="preview-find" role="search" aria-label="Find in document" hidden>
10021
+ <input type="text" class="preview-find-input" data-ref="preview-find-input"
10022
+ placeholder="Find" aria-label="Find in document" spellcheck="false" autocomplete="off" />
10023
+ <span class="preview-find-count" data-ref="preview-find-count" aria-live="polite"></span>
10024
+ <button type="button" class="preview-find-button" data-ref="preview-find-case"
10025
+ aria-pressed="false" title="Match case" aria-label="Match case">${FIND_CASE_ICON_HTML}</button>
10026
+ <button type="button" class="preview-find-button" data-ref="preview-find-previous"
10027
+ title="Previous match (Shift+Enter)" aria-label="Previous match">${FIND_PREVIOUS_ICON_HTML}</button>
10028
+ <button type="button" class="preview-find-button" data-ref="preview-find-next"
10029
+ title="Next match (Enter)" aria-label="Next match">${FIND_NEXT_ICON_HTML}</button>
10030
+ <button type="button" class="preview-find-button" data-ref="preview-find-close"
10031
+ title="Close (Escape)" aria-label="Close find">${FIND_CLOSE_ICON_HTML}</button>
10032
+ </div>
10033
+ <section class="pane entry-pane" data-ref="entry-pane"></section>
10034
+ </div>
10035
+ <aside class="outline-pane" data-ref="outline-pane" hidden></aside>
10036
+ <div class="outline-resizer" data-ref="outline-resizer"
10037
+ role="separator" aria-orientation="vertical" aria-label="Resize outline"></div>
10038
+ </div>
10039
+
10040
+ <div class="title-dialog-backdrop" data-ref="title-dialog" hidden
10041
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-title-dialog-heading">
10042
+ <div class="title-dialog">
10043
+ <h3 id="mdzip-title-dialog-heading">Set Document Title</h3>
10044
+ <p>This is the package-level title stored in manifest.json.</p>
10045
+ <input type="text" maxlength="120" data-ref="title-input" aria-label="Document title" />
10046
+ <p class="title-dialog-validation" data-ref="title-validation" hidden>Title cannot be empty.</p>
10047
+ <p>If unset, consumers may fall back to entry point, filename, or first heading.</p>
10048
+ <div class="title-dialog-actions">
10049
+ <button type="button" class="reset-title" data-ref="title-reset-btn">Reset</button>
10050
+ <button type="button" data-action="cancel-title">Cancel</button>
10051
+ <button type="button" class="save-title" data-ref="title-save-btn">Save</button>
10052
+ </div>
10053
+ </div>
10054
+ </div>
10055
+
10056
+ <div class="title-dialog-backdrop" data-ref="conversion-dialog" hidden
10057
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-conversion-dialog-heading">
10058
+ <div class="title-dialog">
10059
+ <h3 id="mdzip-conversion-dialog-heading">Convert to MDZ?</h3>
10060
+ <p>
10061
+ Regular Markdown files contain only text. Convert this document to an
10062
+ MDZ package to add images, package navigation, and document metadata.
10063
+ </p>
10064
+ <p>The next save will produce an .mdz file.</p>
10065
+ <div class="title-dialog-actions">
10066
+ <button type="button" data-action="cancel-conversion">Cancel</button>
10067
+ <button type="button" class="save-title" data-ref="conversion-confirm-btn">Convert</button>
10068
+ </div>
10069
+ </div>
10070
+ </div>
10071
+
10072
+ <div class="title-dialog-backdrop" data-ref="image-insert-dialog" hidden
10073
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-image-insert-dialog-heading">
10074
+ <div class="title-dialog image-insert-dialog">
10075
+ <h3 id="mdzip-image-insert-dialog-heading">Insert Image</h3>
10076
+ <p>Choose the Markdown inserted for this image.</p>
10077
+ <fieldset class="image-insert-options">
10078
+ <legend>Output</legend>
10079
+ <label>
10080
+ <input type="radio" name="mdzip-image-insert-mode" value="markdown"
10081
+ data-ref="image-insert-mode-markdown" checked />
10082
+ Markdown image
10083
+ </label>
10084
+ <label>
10085
+ <input type="radio" name="mdzip-image-insert-mode" value="html"
10086
+ data-ref="image-insert-mode-html" />
10087
+ HTML &lt;img&gt; with sizing
10088
+ </label>
10089
+ </fieldset>
10090
+ <label class="image-insert-field">
10091
+ <span>Alt text</span>
10092
+ <input type="text" data-ref="image-insert-alt" />
10093
+ </label>
10094
+ <div class="image-insert-grid">
10095
+ <label class="image-insert-field">
10096
+ <span>Size by</span>
10097
+ <select data-ref="image-insert-size-mode">
10098
+ <option value="original">Original size</option>
10099
+ <option value="width" selected>Width</option>
10100
+ <option value="height">Height</option>
10101
+ <option value="percent">Percent</option>
10102
+ </select>
10103
+ </label>
10104
+ <label class="image-insert-field">
10105
+ <span>Value</span>
10106
+ <input type="number" min="1" step="1" data-ref="image-insert-size-value" />
10107
+ </label>
10108
+ </div>
10109
+ <label class="image-insert-field">
10110
+ <span>Position</span>
10111
+ <select data-ref="image-insert-position">
10112
+ <option value="inline">Inline/default</option>
10113
+ <option value="left">Left</option>
10114
+ <option value="center">Center</option>
10115
+ <option value="right">Right</option>
10116
+ <option value="wrap-left">Wrap left</option>
10117
+ <option value="wrap-right">Wrap right</option>
10118
+ </select>
10119
+ </label>
10120
+ <div class="title-dialog-actions">
10121
+ <button type="button" data-action="cancel-image-insert">Cancel</button>
10122
+ <button type="button" class="save-title" data-ref="image-insert-confirm-btn">Insert</button>
10123
+ </div>
10124
+ </div>
10125
+ </div>
10126
+
10127
+ <div class="title-dialog-backdrop" data-ref="pack-files-dialog" hidden
10128
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-pack-files-dialog-heading">
10129
+ <div class="title-dialog pack-files-dialog">
10130
+ <h3 id="mdzip-pack-files-dialog-heading">Package Markdown Files</h3>
10131
+ <p>These files contain more than one Markdown document. Choose how to package them.</p>
10132
+ <fieldset class="pack-files-options">
10133
+ <legend>Mode</legend>
10134
+ <label>
10135
+ <input type="radio" name="mdzip-pack-files-mode" value="document"
10136
+ data-ref="pack-files-mode-document" checked />
10137
+ Document — one primary page; the rest are attached
10138
+ </label>
10139
+ <label>
10140
+ <input type="radio" name="mdzip-pack-files-mode" value="project"
10141
+ data-ref="pack-files-mode-project" />
10142
+ Project — a set of related documents
10143
+ </label>
10144
+ </fieldset>
10145
+ <label class="pack-files-field">
10146
+ <span>Entry point</span>
10147
+ <select data-ref="pack-files-entry"></select>
10148
+ </label>
10149
+ <div class="title-dialog-actions">
10150
+ <button type="button" data-action="cancel-pack-files">Cancel</button>
10151
+ <button type="button" class="save-title" data-ref="pack-files-confirm-btn">Package</button>
10152
+ </div>
10153
+ </div>
10154
+ </div>
10155
+
10156
+ <div class="title-dialog-backdrop" data-ref="copy-render-dialog" hidden
10157
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-copy-render-dialog-heading">
10158
+ <div class="title-dialog copy-render-dialog">
10159
+ <h3 id="mdzip-copy-render-dialog-heading" data-ref="copy-render-heading">Copying document...</h3>
10160
+ <div data-ref="copy-render-progress-section">
10161
+ <p data-ref="copy-render-progress-text">Rendering the full document...</p>
10162
+ <div class="copy-render-progress-track">
10163
+ <div class="copy-render-progress-bar" data-ref="copy-render-progress-bar"></div>
10164
+ </div>
10165
+ </div>
10166
+ <p data-ref="copy-render-ready-text" hidden>
10167
+ The document is ready. Browsers only allow a clipboard write right after a click, so this needs one more —
10168
+ click Copy to finish.
10169
+ </p>
10170
+ <p data-ref="copy-render-done-text" hidden></p>
10171
+ <div class="title-dialog-actions">
10172
+ <button type="button" data-action="cancel-copy-render" data-ref="copy-render-cancel-btn">Cancel</button>
10173
+ <button type="button" data-action="cancel-copy-ready" data-ref="copy-render-ready-cancel-btn" hidden>Cancel</button>
10174
+ <button type="button" class="save-title" data-action="confirm-copy-ready" data-ref="copy-render-confirm-btn" hidden>Copy</button>
10175
+ <button type="button" class="save-title" data-action="dismiss-copy-render" data-ref="copy-render-dismiss-btn" hidden>Dismiss</button>
10176
+ </div>
10177
+ </div>
10178
+ </div>
10179
+
10180
+ <div class="title-dialog-backdrop" data-ref="metadata-dialog" hidden
10181
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-metadata-dialog-heading">
10182
+ <div class="title-dialog metadata-dialog">
10183
+ <h3 id="mdzip-metadata-dialog-heading">Document Information</h3>
10184
+ <dl data-ref="metadata-list"></dl>
10185
+ <h4>Libraries</h4>
10186
+ <dl data-ref="library-list"></dl>
10187
+ <div class="title-dialog-actions">
10188
+ <button type="button" class="save-title" data-action="close-metadata">Close</button>
10189
+ </div>
10190
+ </div>
10191
+ </div>
10192
+
10193
+ <div class="title-dialog-backdrop" data-ref="name-dialog" hidden
10194
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-name-dialog-heading">
10195
+ <div class="title-dialog">
10196
+ <h3 id="mdzip-name-dialog-heading" data-ref="name-dialog-heading">New Markdown File</h3>
10197
+ <input type="text" maxlength="260" data-ref="name-input" aria-label="File name" />
10198
+ <p class="title-dialog-validation" data-ref="name-validation" hidden></p>
10199
+ <div class="title-dialog-actions">
10200
+ <button type="button" data-action="cancel-name">Cancel</button>
10201
+ <button type="button" class="save-title" data-ref="name-confirm-btn">Create</button>
10202
+ </div>
10203
+ </div>
10204
+ </div>
10205
+
10206
+ <div class="title-dialog-backdrop" data-ref="delete-dialog" hidden
10207
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-delete-dialog-heading">
10208
+ <div class="title-dialog">
10209
+ <h3 id="mdzip-delete-dialog-heading">Delete File?</h3>
10210
+ <p data-ref="delete-dialog-text"></p>
10211
+ <div class="title-dialog-actions">
10212
+ <button type="button" data-action="cancel-delete">Cancel</button>
10213
+ <button type="button" class="danger-action" data-ref="delete-confirm-btn">Delete</button>
10214
+ </div>
10215
+ </div>
10216
+ </div>
10217
+
10218
+ <div class="title-dialog-backdrop" data-ref="confirm-dialog" hidden
10219
+ role="dialog" aria-modal="true" aria-labelledby="mdzip-confirm-dialog-heading">
10220
+ <div class="title-dialog">
10221
+ <h3 id="mdzip-confirm-dialog-heading" data-ref="confirm-dialog-title"></h3>
10222
+ <p data-ref="confirm-dialog-text"></p>
10223
+ <div class="title-dialog-actions">
10224
+ <button type="button" data-action="cancel-confirm">Cancel</button>
10225
+ <button type="button" class="danger-action" data-ref="confirm-dialog-ok"></button>
10226
+ </div>
10227
+ </div>
10228
+ </div>
10229
+
10230
+ <input type="file" data-ref="replace-input" hidden />
10231
+ <input type="file" data-ref="add-files-input" multiple hidden />
10232
+
10233
+ <div class="nav-context-menu" data-ref="nav-menu" hidden role="menu"></div>
10234
+
10235
+ <div class="mdzip-tooltip" data-ref="tooltip" role="tooltip" hidden></div>
10236
+
10237
+ <div class="mdzip-copy-toast" data-ref="copy-toast" role="status" aria-live="polite" hidden></div>
10238
+
10239
+ <p class="mdzip-empty" data-ref="empty-state">No MDZip workspace loaded.</p>
10240
+ </section>
8392
10241
  `;
8393
10242
  //# sourceMappingURL=view.js.map