hdoc-tools 0.63.0 → 0.64.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.
@@ -0,0 +1,977 @@
1
+ //-- LOCAL PREVIEW PATCH — hdoc-tools only, NOT part of the live-site viewer.
2
+ //-- Do not copy this file to esp-docs-service htdocs, and keep it (plus its
3
+ //-- loader entry in js/bootstrap.js) when re-syncing ui/ from the live site.
4
+ //--
5
+ //-- Inline edit mode for `hdoc serve`. Probes /_edit/mode; when the server
6
+ //-- confirms edit mode (loopback callers only — LAN viewers stay read-only),
7
+ //-- right-clicking page content offers "Edit this
8
+ //-- in the page editor" (Shift+right-click keeps the browser's own menu).
9
+ //-- The action opens a slide-over panel hosting a CodeMirror 6 editor (the
10
+ //-- same stack `hdoc edit` uses: line numbers, fold gutter, markdown
11
+ //-- highlighting — bundled as js/hdoc-edit-cm.js, lazy-loaded only in edit
12
+ //-- mode) with the page's raw markdown:
13
+ //-- - edits live-preview into the page through the server's shared render
14
+ //-- pipeline (POST /_edit/preview), so preview == published output
15
+ //-- - Save writes the file back (PUT /_edit/source) with an etag conflict
16
+ //-- check, then re-renders the page from disk
17
+ //-- - the editor follows the page viewport (heading-anchored scroll sync),
18
+ //-- and right-clicking content jumps the editor to that block
19
+ //-- Relies on viewer globals loaded before this file: contentContainer(),
20
+ //-- postProcessBookContentRender(), loadContentUrl(), view.docApp.
21
+
22
+ (() => {
23
+ "use strict";
24
+
25
+ let panel = null;
26
+ let cm = null; //-- CodeMirror EditorView
27
+ let cm_ready = null; //-- promise: bundle loaded
28
+ let ed_disabled = true;
29
+ let status_el = null;
30
+ let save_btn = null;
31
+ let open_path = "";
32
+ let etag = "";
33
+ let saved_content = "";
34
+ let preview_timer = null;
35
+ let previewed = false;
36
+ //-- the file's line-ending style: the editor buffer is LF-normalized, so
37
+ //-- Save re-applies the original EOLs or a CRLF file would come back as a
38
+ //-- whole-file line-ending diff.
39
+ let eol = "\n";
40
+ //-- CM compartments so wrap / read-only can be reconfigured live
41
+ let wrap_comp = null;
42
+ let ro_comp = null;
43
+
44
+ const logical_path = () =>
45
+ decodeURIComponent(window.location.pathname)
46
+ .replace(/^\/+/, "")
47
+ .replace(/\/+$/, "");
48
+
49
+ const api = async (method, url, body) => {
50
+ const r = await fetch(url, {
51
+ method,
52
+ headers: body ? { "content-type": "application/json" } : undefined,
53
+ body: body ? JSON.stringify(body) : undefined,
54
+ });
55
+ let json = null;
56
+ try {
57
+ json = await r.json();
58
+ } catch {
59
+ /* non-JSON response */
60
+ }
61
+ return { ok: r.ok, status: r.status, json };
62
+ };
63
+
64
+ //-- persisted prefs (word wrap, panel width). Storage can throw (blocked
65
+ //-- site data) — fall back to defaults.
66
+ const pref = (k) => {
67
+ try {
68
+ return localStorage.getItem(k);
69
+ } catch {
70
+ return null;
71
+ }
72
+ };
73
+ const set_pref = (k, v) => {
74
+ try {
75
+ localStorage.setItem(k, v);
76
+ } catch {
77
+ /* ignore */
78
+ }
79
+ };
80
+
81
+ //-- --- editor adapter ---------------------------------------------------
82
+
83
+ const ed_value = () => (cm ? cm.state.doc.toString() : "");
84
+
85
+ //-- suppress the change listener during programmatic loads, or setting the
86
+ //-- buffer would flag "Unsaved changes" and fire a pointless preview
87
+ let ed_loading = false;
88
+ const ed_set_value = (text) => {
89
+ ed_loading = true;
90
+ try {
91
+ cm.dispatch({
92
+ changes: { from: 0, to: cm.state.doc.length, insert: text },
93
+ //-- keep the load OUT of the undo history — otherwise an undo
94
+ //-- with no edits made reverts to the empty initial doc
95
+ annotations: window.HdocCM.Transaction.addToHistory.of(false),
96
+ });
97
+ } finally {
98
+ ed_loading = false;
99
+ }
100
+ };
101
+
102
+ const ed_set_disabled = (disabled) => {
103
+ ed_disabled = disabled;
104
+ if (!cm) return;
105
+ cm.dispatch({
106
+ effects: ro_comp.reconfigure([
107
+ window.HdocCM.EditorState.readOnly.of(disabled),
108
+ window.HdocCM.EditorView.editable.of(!disabled),
109
+ ]),
110
+ });
111
+ };
112
+
113
+ const ed_pos_at_line = (line) => {
114
+ const doc = cm.state.doc;
115
+ return doc.line(Math.max(1, Math.min(line + 1, doc.lines))).from;
116
+ };
117
+
118
+ const set_caret_at_line = (line, col) => {
119
+ const doc = cm.state.doc;
120
+ const l = doc.line(Math.max(1, Math.min(line + 1, doc.lines)));
121
+ cm.dispatch({
122
+ selection: { anchor: l.from + Math.min(col || 0, l.length) },
123
+ });
124
+ };
125
+
126
+ //-- --- jump flash ------------------------------------------------------
127
+ //-- Every editor jump (open-sync, right-click) flashes the target line so
128
+ //-- the eye lands on the right spot: a line decoration with a CSS fade
129
+ //-- animation, removed once the fade completes.
130
+ let hl_effect = null;
131
+ let hl_field = null;
132
+ let hl_timer = null;
133
+
134
+ const build_highlight_ext = () => {
135
+ const CM = window.HdocCM;
136
+ hl_effect = CM.StateEffect.define();
137
+ const hl_deco = CM.Decoration.line({ class: "hb-edit-hl-line" });
138
+ hl_field = CM.StateField.define({
139
+ create: () => CM.Decoration.none,
140
+ update(deco, tr) {
141
+ deco = deco.map(tr.changes);
142
+ for (const e of tr.effects) {
143
+ if (e.is(hl_effect)) {
144
+ deco =
145
+ e.value === null
146
+ ? CM.Decoration.none
147
+ : CM.Decoration.set([hl_deco.range(e.value)]);
148
+ }
149
+ }
150
+ return deco;
151
+ },
152
+ provide: (f) => CM.EditorView.decorations.from(f),
153
+ });
154
+ return hl_field;
155
+ };
156
+
157
+ const flash_line = (line) => {
158
+ if (!cm) return;
159
+ const doc = cm.state.doc;
160
+ const from = doc.line(Math.max(1, Math.min(line + 1, doc.lines))).from;
161
+ //-- retrigger cleanly if a flash is already running
162
+ if (hl_timer) clearTimeout(hl_timer);
163
+ cm.dispatch({ effects: hl_effect.of(null) });
164
+ cm.dispatch({ effects: hl_effect.of(from) });
165
+ hl_timer = setTimeout(() => {
166
+ hl_timer = null;
167
+ if (cm) cm.dispatch({ effects: hl_effect.of(null) });
168
+ }, 2600);
169
+ };
170
+
171
+ const scroll_editor_to_line = (line) => {
172
+ cm.dispatch({
173
+ effects: window.HdocCM.EditorView.scrollIntoView(
174
+ ed_pos_at_line(line),
175
+ { y: "start", yMargin: 40 },
176
+ ),
177
+ });
178
+ };
179
+
180
+ //-- --- viewport → editor scroll sync ---------------------------------
181
+ //-- The page and the markdown have no shared coordinate system (variables
182
+ //-- and includes expand, HTML wraps), but headings survive rendering
183
+ //-- almost verbatim, so they make reliable sync anchors: find the nearest
184
+ //-- heading above the viewport top, locate the same heading line in the
185
+ //-- markdown, scroll the editor to it.
186
+
187
+ const norm_text = (s) =>
188
+ String(s || "")
189
+ .toLowerCase()
190
+ .replace(/[^a-z0-9]+/g, " ")
191
+ .trim();
192
+
193
+ //-- ATX heading lines in the buffer (fenced code blocks skipped), as
194
+ //-- { line, text } with text normalized for comparison.
195
+ const md_heading_lines = () => {
196
+ const lines = ed_value().split("\n");
197
+ const out = [];
198
+ let in_fence = false;
199
+ for (let i = 0; i < lines.length; i++) {
200
+ if (/^\s*(```|~~~)/.test(lines[i])) {
201
+ in_fence = !in_fence;
202
+ continue;
203
+ }
204
+ if (in_fence) continue;
205
+ const m = lines[i].match(/^#{1,6}\s+(.*)$/);
206
+ if (m) {
207
+ out.push({ line: i, text: norm_text(m[1].replace(/\s*#+\s*$/, "")) });
208
+ }
209
+ }
210
+ return out;
211
+ };
212
+
213
+ let last_typed = 0;
214
+
215
+ //-- set_caret: also move the caret to the matched line (used on open, so
216
+ //-- focus lands on the right line instead of line 0).
217
+ const sync_editor_scroll = (set_caret) => {
218
+ if (!panel || !cm || ed_disabled) return;
219
+ //-- never fight the author: no sync within 2s of them typing
220
+ if (!set_caret && Date.now() - last_typed < 2000) return;
221
+ const root = document.querySelector(".injected-document-content");
222
+ if (!root) return;
223
+ const headings = Array.from(
224
+ root.querySelectorAll("h1,h2,h3,h4,h5,h6"),
225
+ );
226
+ //-- nearest heading at/above the viewport top, where "top" extends a
227
+ //-- band into the top third of the viewport: a heading sitting just
228
+ //-- below the toolbar (anchor scroll-margin parks them ~200px down)
229
+ //-- reads as the current section, not the previous one
230
+ const band = Math.max(120, window.innerHeight * 0.33);
231
+ let current = null;
232
+ for (const h of headings) {
233
+ if (h.getBoundingClientRect().top <= band) current = h;
234
+ else break;
235
+ }
236
+ if (!current) {
237
+ //-- above the first heading (page intro) → top of the source
238
+ if (set_caret) set_caret_at_line(0);
239
+ scroll_editor_to_line(0);
240
+ return;
241
+ }
242
+ const line = md_line_for_heading(current, headings);
243
+ if (line === null) return;
244
+ if (set_caret) {
245
+ set_caret_at_line(line);
246
+ }
247
+ scroll_editor_to_line(line);
248
+ if (set_caret) flash_line(line);
249
+ };
250
+
251
+ //-- markdown line index for a rendered heading element, or null when it
252
+ //-- can't be matched. Same heading text can repeat — match Nth occurrence.
253
+ const md_line_for_heading = (heading_el, headings) => {
254
+ const target = norm_text(heading_el.textContent);
255
+ if (!target) return null;
256
+ let occurrence = 0;
257
+ for (const h of headings) {
258
+ if (h === heading_el) break;
259
+ if (norm_text(h.textContent) === target) occurrence++;
260
+ }
261
+ const candidates = md_heading_lines().filter((h) => h.text === target);
262
+ if (!candidates.length) return null;
263
+ return candidates[Math.min(occurrence, candidates.length - 1)].line;
264
+ };
265
+
266
+ let scroll_sync_timer = null;
267
+ const on_page_scroll = (ev) => {
268
+ //-- ignore scrolls originating inside the panel (the editor's own
269
+ //-- scroller included — capture listener sees all)
270
+ if (
271
+ panel &&
272
+ ev.target instanceof Node &&
273
+ panel.contains(ev.target)
274
+ ) {
275
+ return;
276
+ }
277
+ if (scroll_sync_timer) clearTimeout(scroll_sync_timer);
278
+ scroll_sync_timer = setTimeout(sync_editor_scroll, 150);
279
+ };
280
+
281
+ //-- --- right-click → edit at this point --------------------------------
282
+ //-- Right-clicking page content offers "Edit this in the page editor":
283
+ //-- opens the panel (if closed) and places the caret at the markdown line
284
+ //-- for the clicked block. The block is located by anchoring on the
285
+ //-- nearest heading above it, then scoring the section's markdown lines
286
+ //-- by word overlap with the block's text.
287
+
288
+ let ctx_menu = null;
289
+ const close_ctx_menu = () => {
290
+ if (ctx_menu) {
291
+ ctx_menu.remove();
292
+ ctx_menu = null;
293
+ }
294
+ };
295
+
296
+ //-- The words immediately BEFORE the caret position under a point in the
297
+ //-- rendered text (up to 3). Used to place the editor cursor at the same
298
+ //-- spot within the matched markdown line, not just at its start.
299
+ const click_words_at_point = (x, y) => {
300
+ let node = null;
301
+ let offset = 0;
302
+ if (document.caretPositionFromPoint) {
303
+ const p = document.caretPositionFromPoint(x, y);
304
+ if (p) {
305
+ node = p.offsetNode;
306
+ offset = p.offset;
307
+ }
308
+ } else if (document.caretRangeFromPoint) {
309
+ //-- deprecated, but the only option on older WebKit
310
+ const r = document.caretRangeFromPoint(x, y);
311
+ if (r) {
312
+ node = r.startContainer;
313
+ offset = r.startOffset;
314
+ }
315
+ }
316
+ if (!node || node.nodeType !== Node.TEXT_NODE) return null;
317
+ const words = node.textContent
318
+ .slice(0, offset)
319
+ .toLowerCase()
320
+ .split(/[^a-z0-9]+/)
321
+ .filter(Boolean)
322
+ .slice(-3);
323
+ return words.length ? words : null;
324
+ };
325
+
326
+ //-- best-matching markdown line for a rendered block within [start, end)
327
+ const find_block_line = (block_el, start, end, lines) => {
328
+ const words = norm_text(block_el.textContent)
329
+ .split(" ")
330
+ .filter(Boolean)
331
+ .slice(0, 12);
332
+ if (!words.length) return start;
333
+ let best = start;
334
+ let best_score = 0;
335
+ for (let i = start; i < end; i++) {
336
+ const ln = norm_text(lines[i]);
337
+ if (!ln) continue;
338
+ let score = 0;
339
+ for (const w of words) {
340
+ if (ln.includes(w)) score++;
341
+ }
342
+ if (score > best_score) {
343
+ best_score = score;
344
+ best = i;
345
+ }
346
+ }
347
+ return best;
348
+ };
349
+
350
+ const edit_at_block = async (block, click_words) => {
351
+ if (!panel) await open_panel();
352
+ if (!panel || !cm || ed_disabled) return;
353
+ const root = document.querySelector(".injected-document-content");
354
+ if (!root) return;
355
+ const headings = Array.from(
356
+ root.querySelectorAll("h1,h2,h3,h4,h5,h6"),
357
+ );
358
+ //-- nearest heading at/above the clicked block, in document order
359
+ let current = null;
360
+ for (const h of headings) {
361
+ if (
362
+ h === block ||
363
+ h.compareDocumentPosition(block) & Node.DOCUMENT_POSITION_FOLLOWING
364
+ ) {
365
+ current = h;
366
+ } else break;
367
+ }
368
+ const lines = ed_value().split("\n");
369
+ let start = 0;
370
+ let end = lines.length;
371
+ const md_hs = md_heading_lines();
372
+ if (current) {
373
+ const heading_line = md_line_for_heading(current, headings);
374
+ if (heading_line !== null) {
375
+ start = heading_line;
376
+ const next = md_hs.find((h) => h.line > heading_line);
377
+ if (next) end = next.line;
378
+ }
379
+ } else if (md_hs.length) {
380
+ //-- block sits in the page intro, above the first heading
381
+ end = md_hs[0].line;
382
+ }
383
+ let line =
384
+ current && block === current
385
+ ? start
386
+ : find_block_line(block, start, end, lines);
387
+ //-- refine to the exact spot: find the words that preceded the click
388
+ //-- inside the matched line (markdown punctuation like ** or ` can sit
389
+ //-- between them), and put the caret right after them. Longest word
390
+ //-- suffix wins; the block-matched line is tried first, then the rest
391
+ //-- of the section (covers multi-line blocks like fenced code).
392
+ let col = 0;
393
+ if (click_words && click_words.length) {
394
+ const esc = (w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
395
+ const order = [line];
396
+ for (let i = start; i < end; i++) {
397
+ if (i !== line) order.push(i);
398
+ }
399
+ outer: for (let n = click_words.length; n >= 1; n--) {
400
+ const re = new RegExp(
401
+ click_words.slice(-n).map(esc).join("[^a-zA-Z0-9]+"),
402
+ "i",
403
+ );
404
+ for (const li of order) {
405
+ const m = re.exec(lines[li]);
406
+ if (m) {
407
+ line = li;
408
+ col = m.index + m[0].length;
409
+ break outer;
410
+ }
411
+ }
412
+ }
413
+ }
414
+ set_caret_at_line(line, col);
415
+ cm.focus();
416
+ scroll_editor_to_line(line);
417
+ flash_line(line);
418
+ };
419
+
420
+ const on_context_menu = (ev) => {
421
+ //-- Shift+right-click = the browser's native menu (the same convention
422
+ //-- Firefox implements natively for pages with contextmenu handlers)
423
+ if (ev.shiftKey) return;
424
+ const root = document.querySelector(".injected-document-content");
425
+ if (!root || !root.contains(ev.target)) return;
426
+ ev.preventDefault();
427
+ close_ctx_menu();
428
+ const block =
429
+ ev.target.closest(
430
+ "p,li,td,th,pre,blockquote,h1,h2,h3,h4,h5,h6",
431
+ ) || ev.target;
432
+ //-- capture NOW, before the menu is in the DOM under the pointer
433
+ const click_words = click_words_at_point(ev.clientX, ev.clientY);
434
+ ctx_menu = document.createElement("div");
435
+ ctx_menu.className = "hb-edit-ctx";
436
+ const item = document.createElement("button");
437
+ item.type = "button";
438
+ item.className = "hb-edit-ctx-item";
439
+ item.innerHTML =
440
+ '<i class="bi bi-pencil-fill" aria-hidden="true"></i> Edit this in the page editor';
441
+ item.addEventListener("click", (e) => {
442
+ e.stopPropagation();
443
+ close_ctx_menu();
444
+ edit_at_block(block, click_words);
445
+ });
446
+ ctx_menu.appendChild(item);
447
+ document.body.appendChild(ctx_menu);
448
+ ctx_menu.style.left = `${Math.min(ev.clientX, window.innerWidth - ctx_menu.offsetWidth - 8)}px`;
449
+ ctx_menu.style.top = `${Math.min(ev.clientY, window.innerHeight - ctx_menu.offsetHeight - 8)}px`;
450
+ };
451
+
452
+ //-- --- close on SPA navigation ----------------------------------------
453
+ //-- Left-nav clicks swap the page under the panel (pushState) — without
454
+ //-- this the editor stays open holding the PREVIOUS page's source. Clean
455
+ //-- buffer closes silently; a dirty buffer prompts, and if the author
456
+ //-- keeps it open the status bar flags what it still holds.
457
+ const on_nav_change = () => {
458
+ if (!panel || !cm) return;
459
+ const now = logical_path();
460
+ if (now === open_path) return;
461
+ //-- the new page is already rendered — never "restore" the old one
462
+ previewed = false;
463
+ const held = open_path;
464
+ close_panel();
465
+ if (panel) {
466
+ set_status(
467
+ `Page changed — this editor still holds ${held}. Save your changes or close.`,
468
+ true,
469
+ );
470
+ }
471
+ };
472
+
473
+ const set_status = (msg, is_err) => {
474
+ if (!status_el) return;
475
+ status_el.textContent = msg || "";
476
+ status_el.classList.toggle("hb-edit-status-err", !!is_err);
477
+ };
478
+
479
+ //-- Replacing the page body resets the window scroll to the top — brutal
480
+ //-- when previewing edits deep in long content. Capture the position
481
+ //-- BEFORE the swap; the returned restorer re-applies it immediately,
482
+ //-- again on the next frame (post-process reflow) and once more shortly
483
+ //-- after (late async layout: mermaid rendering, image loads).
484
+ const capture_page_scroll = () => {
485
+ //-- the viewer scrolls the #DocContent container, not the window
486
+ const el =
487
+ document.getElementById("DocContent") ||
488
+ document.scrollingElement ||
489
+ document.documentElement;
490
+ const y = el.scrollTop;
491
+ const x = el.scrollLeft;
492
+ return () => {
493
+ const restore = () => {
494
+ el.scrollTop = y;
495
+ el.scrollLeft = x;
496
+ };
497
+ restore();
498
+ requestAnimationFrame(restore);
499
+ setTimeout(restore, 300);
500
+ };
501
+ };
502
+
503
+ //-- Re-render the page body from a server-rendered fragment, then run the
504
+ //-- viewer's standard post-render pass (TOC, code badges, mermaid, vue
505
+ //-- components) so the preview behaves like a real page load.
506
+ const inject_fragment = (html) => {
507
+ const body = contentContainer();
508
+ if (!body) return;
509
+ const restore_scroll = capture_page_scroll();
510
+ body.innerHTML = html;
511
+ try {
512
+ //-- deep-clone to a PLAIN object: docApp.frontmatterData is a Vue
513
+ //-- reactive proxy, and postProcess postMessage()s it to any parent
514
+ //-- frame - structured clone throws DataCloneError on a proxy.
515
+ let fm = {};
516
+ try {
517
+ fm = JSON.parse(
518
+ JSON.stringify(
519
+ (window.view && view.docApp.frontmatterData) || {},
520
+ ),
521
+ );
522
+ } catch {
523
+ /* keep {} */
524
+ }
525
+ postProcessBookContentRender(open_path, fm, `_books/${open_path}`);
526
+ } catch (e) {
527
+ console.warn("[hdoc edit] preview post-process failed", e);
528
+ }
529
+ restore_scroll();
530
+ };
531
+
532
+ const render_preview = async () => {
533
+ preview_timer = null;
534
+ const r = await api("POST", "/_edit/preview", {
535
+ path: open_path,
536
+ content: ed_value(),
537
+ });
538
+ if (!r.ok || !r.json || typeof r.json.html !== "string") {
539
+ set_status((r.json && r.json.error) || "Preview failed", true);
540
+ return;
541
+ }
542
+ previewed = true;
543
+ inject_fragment(r.json.html);
544
+ };
545
+
546
+ const schedule_preview = () => {
547
+ last_typed = Date.now();
548
+ if (preview_timer) clearTimeout(preview_timer);
549
+ preview_timer = setTimeout(render_preview, 600);
550
+ set_status(ed_value() === saved_content ? "" : "Unsaved changes");
551
+ };
552
+
553
+ const save = async () => {
554
+ if (!panel || ed_disabled) return;
555
+ set_status("Saving…");
556
+ const value = ed_value();
557
+ const out = eol === "\r\n" ? value.replace(/\r?\n/g, "\r\n") : value;
558
+ const r = await api(
559
+ "PUT",
560
+ `/_edit/source?path=${encodeURIComponent(open_path)}`,
561
+ { content: out, baseEtag: etag },
562
+ );
563
+ if (r.status === 409) {
564
+ set_status(
565
+ "Conflict: this file changed on disk since it was opened. Copy your changes, close the panel and re-open it to pick up the latest version.",
566
+ true,
567
+ );
568
+ return;
569
+ }
570
+ if (!r.ok || !r.json) {
571
+ set_status((r.json && r.json.error) || "Save failed", true);
572
+ return;
573
+ }
574
+ etag = r.json.etag;
575
+ saved_content = value;
576
+ previewed = false;
577
+ set_status(`Saved ${r.json.file}`);
578
+ //-- re-render from disk so the page shows exactly what was persisted,
579
+ //-- holding the reader's scroll position through the reload
580
+ const restore_scroll = capture_page_scroll();
581
+ try {
582
+ await loadContentUrl(open_path);
583
+ restore_scroll();
584
+ } catch {
585
+ window.location.reload();
586
+ }
587
+ };
588
+
589
+ const close_panel = () => {
590
+ if (!panel) return;
591
+ if (
592
+ cm &&
593
+ !ed_disabled &&
594
+ ed_value() !== saved_content &&
595
+ !window.confirm("Discard unsaved changes?")
596
+ ) {
597
+ return;
598
+ }
599
+ if (preview_timer) clearTimeout(preview_timer);
600
+ preview_timer = null;
601
+ if (scroll_sync_timer) clearTimeout(scroll_sync_timer);
602
+ scroll_sync_timer = null;
603
+ if (hl_timer) clearTimeout(hl_timer);
604
+ hl_timer = null;
605
+ document.removeEventListener("scroll", on_page_scroll, true);
606
+ if (cm) {
607
+ cm.destroy();
608
+ cm = null;
609
+ }
610
+ panel.remove();
611
+ panel = null;
612
+ status_el = null;
613
+ save_btn = null;
614
+ ed_disabled = true;
615
+ document.body.classList.remove("hb-edit-open");
616
+ //-- if the page body is showing an unsaved preview, restore it from
617
+ //-- disk — holding the reader's scroll position through the reload
618
+ if (previewed) {
619
+ previewed = false;
620
+ const restore_scroll = capture_page_scroll();
621
+ loadContentUrl(open_path).then(restore_scroll, () => {
622
+ window.location.reload();
623
+ });
624
+ }
625
+ };
626
+
627
+ const build_panel = () => {
628
+ panel = document.createElement("aside");
629
+ panel.className = "hb-edit-panel";
630
+ panel.innerHTML = `
631
+ <div class="hb-edit-resizer" title="Drag to resize"></div>
632
+ <div class="hb-edit-head">
633
+ <span class="hb-edit-title">Edit page</span>
634
+ <span>
635
+ <button type="button" class="hb-edit-wrap" title="Toggle word wrap" aria-label="Toggle word wrap"><i class="bi bi-text-wrap" aria-hidden="true"></i></button>
636
+ <button type="button" class="hb-edit-x" title="Close (Esc)" aria-label="Close editor">&times;</button>
637
+ </span>
638
+ </div>
639
+ <div class="hb-edit-cm" aria-label="Page markdown source"></div>
640
+ <div class="hb-edit-status" role="status"></div>
641
+ <div class="hb-edit-foot">
642
+ <button type="button" class="hb-edit-save">Save</button>
643
+ <button type="button" class="hb-edit-cancel">Close</button>
644
+ </div>`;
645
+ document.body.appendChild(panel);
646
+ document.body.classList.add("hb-edit-open");
647
+
648
+ status_el = panel.querySelector(".hb-edit-status");
649
+ save_btn = panel.querySelector(".hb-edit-save");
650
+
651
+ const saved_width = Number.parseInt(pref("hdoc-edit-width"), 10);
652
+ if (saved_width) {
653
+ panel.style.width = `${Math.min(saved_width, window.innerWidth * 0.92)}px`;
654
+ }
655
+ const resizer = panel.querySelector(".hb-edit-resizer");
656
+ resizer.addEventListener("pointerdown", (ev) => {
657
+ ev.preventDefault();
658
+ resizer.setPointerCapture(ev.pointerId);
659
+ const on_move = (mv) => {
660
+ const w = Math.min(
661
+ Math.max(window.innerWidth - mv.clientX, 360),
662
+ window.innerWidth * 0.92,
663
+ );
664
+ panel.style.width = `${w}px`;
665
+ };
666
+ const on_up = () => {
667
+ resizer.removeEventListener("pointermove", on_move);
668
+ resizer.removeEventListener("pointerup", on_up);
669
+ set_pref("hdoc-edit-width", String(Math.round(panel.offsetWidth)));
670
+ };
671
+ resizer.addEventListener("pointermove", on_move);
672
+ resizer.addEventListener("pointerup", on_up);
673
+ });
674
+
675
+ save_btn.addEventListener("click", save);
676
+ panel.querySelector(".hb-edit-cancel").addEventListener("click", close_panel);
677
+ panel.querySelector(".hb-edit-x").addEventListener("click", close_panel);
678
+ panel.addEventListener("keydown", (ev) => {
679
+ if (ev.key === "Escape") {
680
+ ev.stopPropagation();
681
+ close_panel();
682
+ } else if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === "s") {
683
+ ev.preventDefault();
684
+ save();
685
+ }
686
+ });
687
+ };
688
+
689
+ //-- Create the CodeMirror view inside the panel — same stack `hdoc edit`
690
+ //-- uses (basicSetup: line numbers, fold gutter, history, search;
691
+ //-- markdown language), plus a theme matching the panel's light/dark look.
692
+ const build_editor = () => {
693
+ const CM = window.HdocCM;
694
+ wrap_comp = new CM.Compartment();
695
+ ro_comp = new CM.Compartment();
696
+
697
+ const dark = document.documentElement.classList.contains("dark");
698
+ const theme = CM.EditorView.theme(
699
+ {
700
+ "&": {
701
+ height: "100%",
702
+ fontSize: "13px",
703
+ backgroundColor: "transparent",
704
+ color: "inherit",
705
+ },
706
+ ".cm-scroller": {
707
+ fontFamily: 'Consolas, "SFMono-Regular", Menlo, monospace',
708
+ lineHeight: "1.55",
709
+ overflow: "auto",
710
+ },
711
+ ".cm-gutters": {
712
+ backgroundColor: "transparent",
713
+ borderRight: dark
714
+ ? "1px solid rgba(255,255,255,.08)"
715
+ : "1px solid rgba(0,0,0,.08)",
716
+ color: dark ? "#6c757d" : "#adb5bd",
717
+ },
718
+ ".cm-activeLine": {
719
+ backgroundColor: dark
720
+ ? "rgba(255,255,255,.04)"
721
+ : "rgba(0,0,0,.03)",
722
+ },
723
+ ".cm-activeLineGutter": {
724
+ backgroundColor: dark
725
+ ? "rgba(255,255,255,.06)"
726
+ : "rgba(0,0,0,.05)",
727
+ },
728
+ "&.cm-focused": { outline: "none" },
729
+ ".cm-cursor": { borderLeftColor: dark ? "#dee2e6" : "#212529" },
730
+ ".cm-selectionBackground, &.cm-focused .cm-selectionBackground": {
731
+ backgroundColor: dark
732
+ ? "rgba(100,150,255,.25)"
733
+ : "rgba(100,150,255,.22)",
734
+ },
735
+ },
736
+ { dark },
737
+ );
738
+
739
+ //-- CM's default syntax colors are designed for a light background —
740
+ //-- markdown link URLs in particular are near-unreadable on dark. Give
741
+ //-- dark mode its own palette (light keeps the CM defaults).
742
+ const t = CM.tags;
743
+ const dark_syntax = CM.syntaxHighlighting(
744
+ CM.HighlightStyle.define([
745
+ { tag: [t.link, t.url], color: "#6ea8fe" },
746
+ { tag: t.heading, color: "#ffd777", fontWeight: "bold" },
747
+ { tag: t.strong, fontWeight: "bold" },
748
+ { tag: t.emphasis, fontStyle: "italic" },
749
+ { tag: t.monospace, color: "#98c379" },
750
+ { tag: t.quote, color: "#8fbc8f" },
751
+ { tag: [t.meta, t.processingInstruction, t.comment], color: "#8a939c" },
752
+ { tag: t.strikethrough, textDecoration: "line-through" },
753
+ ]),
754
+ );
755
+
756
+ const wrap_on = pref("hdoc-edit-wrap") !== "0";
757
+ cm = new CM.EditorView({
758
+ state: CM.EditorState.create({
759
+ doc: "",
760
+ extensions: [
761
+ CM.basicSetup,
762
+ CM.markdown(),
763
+ theme,
764
+ ...(dark ? [dark_syntax] : []),
765
+ build_highlight_ext(),
766
+ wrap_comp.of(wrap_on ? CM.EditorView.lineWrapping : []),
767
+ ro_comp.of([
768
+ CM.EditorState.readOnly.of(true),
769
+ CM.EditorView.editable.of(false),
770
+ ]),
771
+ CM.EditorView.updateListener.of((u) => {
772
+ if (u.docChanged && !ed_loading) schedule_preview();
773
+ }),
774
+ ],
775
+ }),
776
+ parent: panel.querySelector(".hb-edit-cm"),
777
+ });
778
+
779
+ const wrap_btn = panel.querySelector(".hb-edit-wrap");
780
+ wrap_btn.classList.toggle("hb-edit-wrap-on", wrap_on);
781
+ wrap_btn.addEventListener("click", () => {
782
+ const on = !wrap_btn.classList.contains("hb-edit-wrap-on");
783
+ cm.dispatch({
784
+ effects: wrap_comp.reconfigure(
785
+ on ? CM.EditorView.lineWrapping : [],
786
+ ),
787
+ });
788
+ wrap_btn.classList.toggle("hb-edit-wrap-on", on);
789
+ set_pref("hdoc-edit-wrap", on ? "1" : "0");
790
+ cm.focus();
791
+ });
792
+ };
793
+
794
+ const open_panel = async () => {
795
+ if (panel) {
796
+ close_panel();
797
+ return;
798
+ }
799
+ open_path = logical_path();
800
+ previewed = false;
801
+ build_panel();
802
+ save_btn.disabled = true;
803
+ set_status("Loading…");
804
+ try {
805
+ await cm_ready;
806
+ } catch {
807
+ set_status(
808
+ "Editor failed to load (js/hdoc-edit-cm.js missing — rebuild it from editor/cm-standalone.mjs)",
809
+ true,
810
+ );
811
+ return;
812
+ }
813
+ if (!panel) return; //-- closed while loading
814
+ build_editor();
815
+ const r = await api(
816
+ "GET",
817
+ `/_edit/source?path=${encodeURIComponent(open_path)}`,
818
+ );
819
+ if (!panel) return; //-- closed while loading
820
+ if (!r.ok || !r.json) {
821
+ set_status(
822
+ (r.json && r.json.error) || "No markdown source found for this page",
823
+ true,
824
+ );
825
+ return;
826
+ }
827
+ eol = r.json.content.includes("\r\n") ? "\r\n" : "\n";
828
+ ed_set_disabled(false);
829
+ //-- LF-normalize for the buffer; Save re-applies the original EOLs
830
+ ed_set_value(r.json.content.replace(/\r\n/g, "\n"));
831
+ saved_content = ed_value();
832
+ etag = r.json.etag;
833
+ save_btn.disabled = false;
834
+ set_status(`Editing ${r.json.file}`);
835
+ //-- open the editor at the content the reader is currently looking at
836
+ //-- (caret placed on the matched line so focus lands there too), and
837
+ //-- keep following while the page (not the editor) scrolls
838
+ sync_editor_scroll(true);
839
+ cm.focus();
840
+ document.addEventListener("scroll", on_page_scroll, true);
841
+ };
842
+
843
+ const inject_styles = () => {
844
+ const css = `
845
+ .hb-edit-panel {
846
+ position: fixed; top: 0; right: 0; bottom: 0; z-index: 3001;
847
+ width: min(680px, 92vw); display: flex; flex-direction: column;
848
+ background: #ffffff; color: #212529;
849
+ border-left: 1px solid rgba(0,0,0,.15);
850
+ box-shadow: -8px 0 28px rgba(0,0,0,.22);
851
+ font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
852
+ }
853
+ html.dark .hb-edit-panel { background: #1b1e21; color: #dee2e6; border-left-color: rgba(255,255,255,.12); }
854
+ .hb-edit-head {
855
+ display: flex; align-items: center; justify-content: space-between;
856
+ padding: 10px 14px; border-bottom: 1px solid rgba(0,0,0,.1); font-weight: 600;
857
+ }
858
+ html.dark .hb-edit-head { border-bottom-color: rgba(255,255,255,.1); }
859
+ .hb-edit-x {
860
+ border: none; background: none; font-size: 22px; cursor: pointer;
861
+ color: inherit; padding: 0 4px; line-height: 1;
862
+ }
863
+ .hb-edit-cm { flex: 1 1 auto; overflow: hidden; }
864
+ .hb-edit-cm .cm-editor { height: 100%; }
865
+ .hb-edit-hl-line { animation: hb-edit-hl-fade 2.5s ease-out forwards; }
866
+ @keyframes hb-edit-hl-fade {
867
+ 0%, 25% { background-color: rgba(255, 190, 60, .55); }
868
+ 100% { background-color: transparent; }
869
+ }
870
+ html.dark .hb-edit-hl-line { animation-name: hb-edit-hl-fade-dark; }
871
+ @keyframes hb-edit-hl-fade-dark {
872
+ 0%, 25% { background-color: rgba(255, 190, 60, .30); }
873
+ 100% { background-color: transparent; }
874
+ }
875
+ .hb-edit-resizer {
876
+ position: absolute; left: -3px; top: 0; bottom: 0; width: 8px;
877
+ cursor: ew-resize; touch-action: none; z-index: 1;
878
+ }
879
+ .hb-edit-resizer:hover { background: rgba(128,128,128,.25); }
880
+ .hb-edit-wrap {
881
+ border: none; background: none; cursor: pointer; color: inherit;
882
+ font-size: 16px; padding: 0 8px; opacity: .45; vertical-align: 1px;
883
+ }
884
+ .hb-edit-wrap.hb-edit-wrap-on { opacity: 1; color: #b8860b; }
885
+ html.dark .hb-edit-wrap.hb-edit-wrap-on { color: #ffd777; }
886
+ .hb-edit-status {
887
+ padding: 6px 14px; font-size: 12px; min-height: 26px; opacity: .85;
888
+ border-top: 1px solid rgba(0,0,0,.08);
889
+ }
890
+ html.dark .hb-edit-status { border-top-color: rgba(255,255,255,.08); }
891
+ .hb-edit-status-err { color: #c62828; opacity: 1; }
892
+ html.dark .hb-edit-status-err { color: #ff8a80; }
893
+ .hb-edit-foot {
894
+ display: flex; gap: 8px; padding: 10px 14px 14px;
895
+ }
896
+ .hb-edit-foot button {
897
+ padding: 6px 18px; border-radius: 6px; cursor: pointer; font-size: 14px;
898
+ border: 1px solid rgba(0,0,0,.2); background: none; color: inherit;
899
+ }
900
+ html.dark .hb-edit-foot button { border-color: rgba(255,255,255,.25); }
901
+ .hb-edit-save { background: #ffd777 !important; color: #6b4400 !important; border-color: transparent !important; font-weight: 600; }
902
+ html.dark .hb-edit-save { background: #7a5200 !important; color: #ffe2a0 !important; }
903
+ .hb-edit-save:disabled { opacity: .5; cursor: default; }
904
+ .hb-edit-ctx {
905
+ position: fixed; z-index: 3002; padding: 4px;
906
+ background: #ffffff; border: 1px solid rgba(0,0,0,.15); border-radius: 8px;
907
+ box-shadow: 0 6px 20px rgba(0,0,0,.2);
908
+ font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
909
+ }
910
+ html.dark .hb-edit-ctx { background: #23272b; border-color: rgba(255,255,255,.15); }
911
+ .hb-edit-ctx-item {
912
+ display: block; width: 100%; text-align: left; white-space: nowrap;
913
+ border: none; background: none; color: #212529; cursor: pointer;
914
+ padding: 7px 12px; border-radius: 6px; font-size: 13px;
915
+ }
916
+ html.dark .hb-edit-ctx-item { color: #dee2e6; }
917
+ .hb-edit-ctx-item:hover { background: rgba(0,0,0,.06); }
918
+ html.dark .hb-edit-ctx-item:hover { background: rgba(255,255,255,.08); }
919
+ .hb-edit-ctx-item .bi { color: #b8860b; margin-right: 6px; }
920
+ html.dark .hb-edit-ctx-item .bi { color: #ffd777; }
921
+ `;
922
+ const style = document.createElement("style");
923
+ style.textContent = css;
924
+ document.head.appendChild(style);
925
+ };
926
+
927
+ //-- Lazy-load the CodeMirror bundle — only edit mode pays its weight.
928
+ const load_cm_bundle = () =>
929
+ new Promise((resolve, reject) => {
930
+ if (window.HdocCM) return resolve();
931
+ const script = document.createElement("script");
932
+ script.src = "js/hdoc-edit-cm.js";
933
+ script.onload = () =>
934
+ window.HdocCM ? resolve() : reject(new Error("bundle bad"));
935
+ script.onerror = () => reject(new Error("bundle load failed"));
936
+ document.head.appendChild(script);
937
+ });
938
+
939
+ const init = async () => {
940
+ let enabled = false;
941
+ try {
942
+ const r = await fetch("/_edit/mode", {
943
+ headers: { accept: "application/json" },
944
+ });
945
+ const ct = r.headers.get("content-type") || "";
946
+ if (r.ok && ct.includes("json")) {
947
+ enabled = (await r.json()).enabled === true;
948
+ }
949
+ } catch {
950
+ /* not in edit mode / not hdoc serve */
951
+ }
952
+ if (!enabled) return;
953
+ cm_ready = load_cm_bundle();
954
+ cm_ready.catch(() => {}); //-- surfaced in open_panel, not unhandled
955
+ inject_styles();
956
+ //-- right-click menu on page content (active whether or not the panel
957
+ //-- is open — it opens the panel on demand)
958
+ document.addEventListener("contextmenu", on_context_menu);
959
+ document.addEventListener("click", close_ctx_menu);
960
+ document.addEventListener("keydown", (ev) => {
961
+ if (ev.key === "Escape") close_ctx_menu();
962
+ });
963
+ //-- SPA navigation detection: back/forward plus the history writes the
964
+ //-- viewer makes on nav-link clicks
965
+ window.addEventListener("popstate", () => setTimeout(on_nav_change, 0));
966
+ for (const fn of ["pushState", "replaceState"]) {
967
+ const orig = history[fn].bind(history);
968
+ history[fn] = (...args) => {
969
+ const r = orig(...args);
970
+ setTimeout(on_nav_change, 0);
971
+ return r;
972
+ };
973
+ }
974
+ };
975
+
976
+ init();
977
+ })();