astro-wysiwyg 0.1.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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +84 -0
  3. package/dist/astro-transform.d.ts +8 -0
  4. package/dist/astro-transform.d.ts.map +1 -0
  5. package/dist/astro-transform.js +240 -0
  6. package/dist/astro-transform.js.map +1 -0
  7. package/dist/client.d.ts +6 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/client.js +1423 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/editable-tags.d.ts +3 -0
  12. package/dist/editable-tags.d.ts.map +1 -0
  13. package/dist/editable-tags.js +8 -0
  14. package/dist/editable-tags.js.map +1 -0
  15. package/dist/frontmatter.d.ts +18 -0
  16. package/dist/frontmatter.d.ts.map +1 -0
  17. package/dist/frontmatter.js +156 -0
  18. package/dist/frontmatter.js.map +1 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +252 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/marker.d.ts +14 -0
  24. package/dist/marker.d.ts.map +1 -0
  25. package/dist/marker.js +37 -0
  26. package/dist/marker.js.map +1 -0
  27. package/dist/persist.d.ts +26 -0
  28. package/dist/persist.d.ts.map +1 -0
  29. package/dist/persist.js +315 -0
  30. package/dist/persist.js.map +1 -0
  31. package/dist/preferences.d.ts +12 -0
  32. package/dist/preferences.d.ts.map +1 -0
  33. package/dist/preferences.js +36 -0
  34. package/dist/preferences.js.map +1 -0
  35. package/dist/project-path.d.ts +2 -0
  36. package/dist/project-path.d.ts.map +1 -0
  37. package/dist/project-path.js +5 -0
  38. package/dist/project-path.js.map +1 -0
  39. package/dist/rehype.d.ts +25 -0
  40. package/dist/rehype.d.ts.map +1 -0
  41. package/dist/rehype.js +59 -0
  42. package/dist/rehype.js.map +1 -0
  43. package/dist/source-file.d.ts +8 -0
  44. package/dist/source-file.d.ts.map +1 -0
  45. package/dist/source-file.js +42 -0
  46. package/dist/source-file.js.map +1 -0
  47. package/dist/toolbar-app.d.ts +3 -0
  48. package/dist/toolbar-app.d.ts.map +1 -0
  49. package/dist/toolbar-app.js +76 -0
  50. package/dist/toolbar-app.js.map +1 -0
  51. package/package.json +82 -0
package/dist/client.js ADDED
@@ -0,0 +1,1423 @@
1
+ import { EDITABLE_BLOCK_TAGS } from "./editable-tags.js";
2
+ import { FRONTMATTER_EVENT, PREFERENCES_EVENT, readPreferences, } from "./preferences.js";
3
+ const MARKER_ATTRIBUTE = 'data-astro-wysiwyg';
4
+ const ACTIVE_ATTRIBUTE = 'data-astro-wysiwyg-active';
5
+ const NATIVE_ACTION_TAGS = new Set(['button', 'label', 'summary']);
6
+ const SOURCE_SELECTOR = EDITABLE_BLOCK_TAGS
7
+ .map((tag) => `${tag}[data-wysiwyg-source-file][data-wysiwyg-source-loc]`)
8
+ .join(',');
9
+ const ASTRO_SOURCE_SELECTOR = EDITABLE_BLOCK_TAGS
10
+ .map((tag) => `${tag}[data-astro-source-file][data-astro-source-loc]`)
11
+ .join(',');
12
+ const EDITABLE_SELECTOR = `[${MARKER_ATTRIBUTE}],${SOURCE_SELECTOR}`;
13
+ const PREPARE_SELECTOR = `${EDITABLE_SELECTOR},${ASTRO_SOURCE_SELECTOR}`;
14
+ const HOST_ID = 'astro-wysiwyg-toolbar';
15
+ const EDIT_INSTRUCTIONS_ID = 'astro-wysiwyg-edit-instructions';
16
+ const PERSIST_ATTRIBUTE = 'data-astro-transition-persist';
17
+ const STYLE_PERSIST_KEY = 'astro-wysiwyg-style';
18
+ const SAVE_REQUEST_TIMEOUT = 10_000;
19
+ const SESSION_KEY = 'astro-wysiwyg-active';
20
+ const FRONTMATTER_DRAFT_KEY = 'astro-wysiwyg-frontmatter-draft';
21
+ export function startEditor(options) {
22
+ if (document.getElementById(HOST_ID))
23
+ return;
24
+ let active = null;
25
+ let saveTimer;
26
+ const pendingSaves = [];
27
+ let saveInFlight = false;
28
+ let preferences = readPreferences();
29
+ let undoHistory = [];
30
+ let linkRange;
31
+ let editingLink;
32
+ let frontmatterContext;
33
+ let frontmatterFields = [];
34
+ let activeSaveInFlight = false;
35
+ let suppressRestoredAutosave = false;
36
+ const host = document.createElement('div');
37
+ host.id = HOST_ID;
38
+ host.setAttribute(PERSIST_ATTRIBUTE, HOST_ID);
39
+ const shadow = host.attachShadow({ mode: 'open' });
40
+ shadow.innerHTML = toolbarMarkup();
41
+ const editInstructions = document.createElement('span');
42
+ editInstructions.id = EDIT_INSTRUCTIONS_ID;
43
+ editInstructions.setAttribute(PERSIST_ATTRIBUTE, EDIT_INSTRUCTIONS_ID);
44
+ editInstructions.hidden = true;
45
+ editInstructions.textContent = 'Editable source content. Press Enter to edit. Press Alt+Up or Alt+Down to move between editable blocks.';
46
+ document.body.append(host, editInstructions);
47
+ const toolbar = shadow.querySelector('[role="toolbar"]');
48
+ const status = shadow.querySelector('[role="status"]');
49
+ const globalStyle = document.createElement('style');
50
+ globalStyle.dataset.astroWysiwygStyle = '';
51
+ globalStyle.setAttribute(PERSIST_ATTRIBUTE, STYLE_PERSIST_KEY);
52
+ globalStyle.textContent = `
53
+ html[data-astro-wysiwyg-enabled] :is(${EDITABLE_SELECTOR}) { cursor: text; }
54
+ html[data-astro-wysiwyg-highlights] :is(${EDITABLE_SELECTOR}):hover { outline: 1px dashed Highlight; outline-offset: 3px; }
55
+ html[data-astro-wysiwyg-highlights] :is(${EDITABLE_SELECTOR}):focus-visible,
56
+ [${ACTIVE_ATTRIBUTE}] { outline: 2px solid Highlight !important; outline-offset: 3px; }
57
+ `;
58
+ document.head.append(globalStyle);
59
+ applyPreferences(preferences);
60
+ prepareEditableBlocks(document);
61
+ void restorePageState();
62
+ document.addEventListener('astro:before-swap', onBeforeSwap);
63
+ document.addEventListener('astro:page-load', onPageLoad);
64
+ document.addEventListener('click', onDocumentClick, true);
65
+ document.addEventListener('keydown', onKeyDown, true);
66
+ document.addEventListener('input', onInput, true);
67
+ document.addEventListener('focusin', onDocumentFocus);
68
+ document.addEventListener('selectionchange', rememberActiveSession);
69
+ document.addEventListener(PREFERENCES_EVENT, onPreferences);
70
+ document.addEventListener(FRONTMATTER_EVENT, () => void openFrontmatterEditor());
71
+ window.addEventListener('scroll', positionToolbar, true);
72
+ window.addEventListener('resize', positionToolbar);
73
+ shadow.addEventListener('pointerdown', (event) => {
74
+ if (event.target instanceof HTMLButtonElement)
75
+ event.preventDefault();
76
+ });
77
+ shadow.addEventListener('click', onToolbarClick);
78
+ shadow.addEventListener('keydown', onToolbarKeyDown);
79
+ shadow.addEventListener('input', rememberFrontmatterDraft);
80
+ function onBeforeSwap(event) {
81
+ const newDocument = event.newDocument;
82
+ addPersistencePlaceholder(newDocument.body, 'div', HOST_ID);
83
+ addPersistencePlaceholder(newDocument.body, 'span', EDIT_INSTRUCTIONS_ID);
84
+ addPersistencePlaceholder(newDocument.head, 'style', STYLE_PERSIST_KEY);
85
+ }
86
+ function addPersistencePlaceholder(parent, tag, key) {
87
+ const placeholder = parent.ownerDocument.createElement(tag);
88
+ placeholder.setAttribute(PERSIST_ATTRIBUTE, key);
89
+ parent.append(placeholder);
90
+ }
91
+ function onPageLoad() {
92
+ if (active && !active.isConnected) {
93
+ active = null;
94
+ toolbar.hidden = true;
95
+ undoHistory = [];
96
+ }
97
+ closeFrontmatterEditor();
98
+ closeLinkEditor();
99
+ applyPreferences(preferences);
100
+ prepareEditableBlocks(document);
101
+ void restorePageState();
102
+ }
103
+ async function restorePageState() {
104
+ await restoreActiveSession();
105
+ await restoreFrontmatterDraft();
106
+ }
107
+ function onPreferences(event) {
108
+ if (!(event instanceof CustomEvent))
109
+ return;
110
+ applyPreferences(event.detail);
111
+ }
112
+ function applyPreferences(next) {
113
+ preferences = next;
114
+ document.documentElement.toggleAttribute('data-astro-wysiwyg-enabled', preferences.enabled);
115
+ document.documentElement.toggleAttribute('data-astro-wysiwyg-highlights', preferences.enabled && preferences.highlights);
116
+ if (!preferences.enabled) {
117
+ window.clearTimeout(saveTimer);
118
+ if (active)
119
+ void finishEditing();
120
+ for (const element of document.querySelectorAll('[data-wysiwyg-added-tabindex]')) {
121
+ element.removeAttribute('tabindex');
122
+ delete element.dataset.wysiwygAddedTabindex;
123
+ }
124
+ for (const element of document.querySelectorAll('[data-wysiwyg-added-description]')) {
125
+ removeEditDescription(element);
126
+ }
127
+ return;
128
+ }
129
+ prepareEditableBlocks(document);
130
+ }
131
+ function prepareEditableBlocks(root) {
132
+ const elements = [...root.querySelectorAll(PREPARE_SELECTOR)];
133
+ for (const element of elements) {
134
+ const sourceFile = element.getAttribute('data-astro-source-file');
135
+ const sourceLocation = element.getAttribute('data-astro-source-loc');
136
+ if (sourceFile && sourceLocation) {
137
+ element.dataset.wysiwygSourceFile = sourceFile;
138
+ element.dataset.wysiwygSourceLoc = sourceLocation;
139
+ }
140
+ }
141
+ if (!preferences.enabled)
142
+ return;
143
+ const managed = elements.filter((element) => (element.hasAttribute('data-wysiwyg-added-tabindex') || !element.hasAttribute('tabindex')));
144
+ const roving = managed.find((element) => element === active)
145
+ ?? managed.find((element) => element.hasAttribute('data-wysiwyg-added-tabindex') && element.tabIndex === 0)
146
+ ?? managed[0];
147
+ for (const element of managed) {
148
+ element.tabIndex = element === roving ? 0 : -1;
149
+ element.dataset.wysiwygAddedTabindex = '';
150
+ }
151
+ for (const element of elements)
152
+ addEditDescription(element);
153
+ }
154
+ function setRovingTabStop(target) {
155
+ if (!target.hasAttribute('data-wysiwyg-added-tabindex'))
156
+ return;
157
+ for (const element of document.querySelectorAll('[data-wysiwyg-added-tabindex]')) {
158
+ element.tabIndex = element === target ? 0 : -1;
159
+ }
160
+ }
161
+ function onDocumentFocus(event) {
162
+ if (event.target instanceof HTMLElement && event.target.matches(EDITABLE_SELECTOR)) {
163
+ setRovingTabStop(event.target);
164
+ }
165
+ }
166
+ function moveEditableFocus(current, direction) {
167
+ const elements = [...document.querySelectorAll(EDITABLE_SELECTOR)];
168
+ const index = elements.indexOf(current);
169
+ const target = elements[(index + direction + elements.length) % elements.length];
170
+ setRovingTabStop(target);
171
+ target.focus();
172
+ }
173
+ function addEditDescription(element) {
174
+ const descriptions = (element.getAttribute('aria-describedby') ?? '')
175
+ .split(/\s+/)
176
+ .filter(Boolean)
177
+ .filter((id) => id !== EDIT_INSTRUCTIONS_ID);
178
+ descriptions.push(EDIT_INSTRUCTIONS_ID);
179
+ element.setAttribute('aria-describedby', descriptions.join(' '));
180
+ element.dataset.wysiwygAddedDescription = '';
181
+ }
182
+ function removeEditDescription(element) {
183
+ const descriptions = (element.getAttribute('aria-describedby') ?? '')
184
+ .split(/\s+/)
185
+ .filter(Boolean)
186
+ .filter((id) => id !== EDIT_INSTRUCTIONS_ID);
187
+ if (descriptions.length)
188
+ element.setAttribute('aria-describedby', descriptions.join(' '));
189
+ else
190
+ element.removeAttribute('aria-describedby');
191
+ delete element.dataset.wysiwygAddedDescription;
192
+ }
193
+ function onDocumentClick(event) {
194
+ if (!preferences.enabled)
195
+ return;
196
+ const target = event.target;
197
+ if (!(target instanceof Element))
198
+ return;
199
+ let block = target.closest(EDITABLE_SELECTOR);
200
+ if (block?.localName === 'li') {
201
+ const list = block.parentElement?.closest('ul, ol');
202
+ /* istanbul ignore else -- Source-marked list items inherit a source-marked parent list. */
203
+ if (list?.matches(EDITABLE_SELECTOR))
204
+ block = list;
205
+ }
206
+ if (!block)
207
+ return;
208
+ setRovingTabStop(block);
209
+ const hasNativeAction = NATIVE_ACTION_TAGS.has(block.localName);
210
+ if (target.closest('a') || hasNativeAction)
211
+ event.preventDefault();
212
+ if (hasNativeAction)
213
+ event.stopPropagation();
214
+ suppressRestoredAutosave = false;
215
+ void activate(block);
216
+ }
217
+ async function activate(block) {
218
+ if (!preferences.enabled)
219
+ return undefined;
220
+ if (!block.hasAttribute(MARKER_ATTRIBUTE) && !await resolveSourceMarker(block))
221
+ return undefined;
222
+ setRovingTabStop(block);
223
+ if (active === block)
224
+ return active;
225
+ if (isFrontmatterEditorOpen())
226
+ closeFrontmatterEditor();
227
+ if (isLinkEditorOpen())
228
+ closeLinkEditor();
229
+ if (active) {
230
+ const previous = active;
231
+ if (hasUnsavedChanges(previous)) {
232
+ const saved = await queueSave(previous);
233
+ if (!saved) {
234
+ previous.focus({ preventScroll: true });
235
+ return undefined;
236
+ }
237
+ }
238
+ deactivate(previous);
239
+ }
240
+ active = block;
241
+ removeEditDescription(active);
242
+ active.setAttribute('contenteditable', 'true');
243
+ active.setAttribute(ACTIVE_ATTRIBUTE, '');
244
+ undoHistory = [snapshot(active)];
245
+ toolbar.hidden = false;
246
+ updateUndoButton();
247
+ updateStructureButtons();
248
+ setStatus('Editing');
249
+ positionToolbar();
250
+ active.focus({ preventScroll: true });
251
+ rememberActiveSession();
252
+ return active;
253
+ }
254
+ async function restoreActiveSession() {
255
+ if (active)
256
+ return;
257
+ const session = readActiveSession();
258
+ if (!session || session.pathname !== location.pathname)
259
+ return;
260
+ suppressRestoredAutosave = Boolean(session.suppressAutosave);
261
+ let block;
262
+ if (session.sourceFile && session.sourceLocation) {
263
+ block = [...document.querySelectorAll(SOURCE_SELECTOR)]
264
+ .filter((element) => element.dataset.wysiwygSourceFile === session.sourceFile
265
+ && (!session.href || element.closest('a')?.getAttribute('href') === session.href))
266
+ .sort((left, right) => sourceLocationDistance(left.dataset.wysiwygSourceLoc, session.sourceLocation)
267
+ - sourceLocationDistance(right.dataset.wysiwygSourceLoc, session.sourceLocation))[0];
268
+ }
269
+ if (!block && session.file) {
270
+ const candidates = [...document.querySelectorAll(`[${MARKER_ATTRIBUTE}]`)]
271
+ .map((element) => ({ element, marker: decodeClientMarker(element.getAttribute(MARKER_ATTRIBUTE)) }))
272
+ .filter((candidate) => candidate.marker?.file === session.file)
273
+ .sort((left, right) => Math.abs(left.marker.start - session.start)
274
+ - Math.abs(right.marker.start - session.start));
275
+ block = candidates[0]?.element;
276
+ }
277
+ if (!block)
278
+ return;
279
+ let restored = await activate(block);
280
+ if (!restored)
281
+ return;
282
+ const draftSnapshot = session.html !== undefined && session.tag !== undefined
283
+ ? { html: session.html, tag: session.tag }
284
+ : undefined;
285
+ const currentSource = decodeClientMarker(restored.getAttribute(MARKER_ATTRIBUTE))?.original;
286
+ const hasDraft = Boolean(session.dirty || session.saving || session.suppressAutosave);
287
+ const sourceChanged = session.sourceOriginal !== undefined
288
+ && currentSource !== undefined
289
+ && session.sourceOriginal !== currentSource;
290
+ let restoredDraftState = 'clean';
291
+ if (hasDraft) {
292
+ if (session.sourceOriginal !== undefined && session.sourceOriginal === currentSource) {
293
+ restoredDraftState = 'pending';
294
+ }
295
+ else if (draftSnapshot && sameSnapshot(snapshot(restored), draftSnapshot)) {
296
+ restoredDraftState = 'committed';
297
+ }
298
+ else {
299
+ restoredDraftState = 'conflict';
300
+ }
301
+ }
302
+ suppressRestoredAutosave = Boolean(session.suppressAutosave || restoredDraftState === 'committed' || restoredDraftState === 'conflict');
303
+ if (session.history?.length && !(restoredDraftState === 'clean' && sourceChanged)) {
304
+ undoHistory = session.history;
305
+ }
306
+ const shouldRestoreDraft = hasDraft && restoredDraftState !== 'committed';
307
+ let draftRestored = false;
308
+ if (shouldRestoreDraft && session.tag && restored.localName !== session.tag) {
309
+ changeBlockTag(session.tag, false, false);
310
+ /* istanbul ignore next -- Tag replacement always installs the replacement as active. */
311
+ restored = active ?? restored;
312
+ draftRestored = true;
313
+ }
314
+ if (shouldRestoreDraft && session.html !== undefined && restored.innerHTML !== session.html) {
315
+ restored.innerHTML = session.html;
316
+ draftRestored = true;
317
+ }
318
+ if (restoredDraftState === 'committed')
319
+ checkpoint(restored);
320
+ if (draftRestored && preferences.autosave && !suppressRestoredAutosave) {
321
+ window.clearTimeout(saveTimer);
322
+ saveTimer = window.setTimeout(() => queueSave(restored), options.saveDelay);
323
+ }
324
+ setCaretOffset(restored, session.caret);
325
+ rememberActiveSession();
326
+ updateUndoButton();
327
+ if (restoredDraftState === 'conflict') {
328
+ setStatus('The source changed since this draft began. Review this block before saving again.', true);
329
+ }
330
+ }
331
+ function rememberActiveSession() {
332
+ if (!active)
333
+ return;
334
+ const marker = decodeClientMarker(active.getAttribute(MARKER_ATTRIBUTE));
335
+ const session = {
336
+ pathname: location.pathname,
337
+ file: marker?.file,
338
+ start: marker?.start,
339
+ sourceFile: active.dataset.wysiwygSourceFile,
340
+ sourceLocation: active.dataset.wysiwygSourceLoc,
341
+ href: active.closest('a')?.getAttribute('href') ?? undefined,
342
+ html: active.innerHTML,
343
+ tag: active.localName,
344
+ caret: getCaretOffset(active),
345
+ history: undoHistory,
346
+ dirty: hasUnsavedChanges(active) || activeSaveInFlight,
347
+ saving: activeSaveInFlight,
348
+ suppressAutosave: suppressRestoredAutosave,
349
+ sourceOriginal: marker?.original,
350
+ };
351
+ try {
352
+ sessionStorage.setItem(SESSION_KEY, JSON.stringify(session));
353
+ }
354
+ catch {
355
+ // Editing still works when session storage is unavailable.
356
+ }
357
+ }
358
+ async function resolveSourceMarker(element) {
359
+ const sourceFile = element.dataset.wysiwygSourceFile;
360
+ const sourceLocation = element.dataset.wysiwygSourceLoc;
361
+ /* istanbul ignore next -- The editable source selector requires both attributes. */
362
+ if (!sourceFile || !sourceLocation)
363
+ return false;
364
+ try {
365
+ const contextMarker = document.querySelector(`[${MARKER_ATTRIBUTE}]`)
366
+ ?.getAttribute(MARKER_ATTRIBUTE) ?? undefined;
367
+ const response = await fetch(options.endpoint, {
368
+ method: 'POST',
369
+ headers: { 'Content-Type': 'application/json' },
370
+ body: JSON.stringify({
371
+ sourceFile,
372
+ sourceLocation,
373
+ contextMarker,
374
+ contextHref: element.closest('a')?.getAttribute('href') ?? undefined,
375
+ renderedText: element.textContent.trim(),
376
+ }),
377
+ });
378
+ const body = await response.json();
379
+ if (!response.ok || !body.marker)
380
+ return false;
381
+ element.setAttribute(MARKER_ATTRIBUTE, body.marker);
382
+ return true;
383
+ }
384
+ catch {
385
+ return false;
386
+ }
387
+ }
388
+ function deactivate(element) {
389
+ element.removeAttribute('contenteditable');
390
+ element.removeAttribute(ACTIVE_ATTRIBUTE);
391
+ if (preferences.enabled)
392
+ addEditDescription(element);
393
+ }
394
+ function onInput(event) {
395
+ if (event.target !== active || !active)
396
+ return;
397
+ window.clearTimeout(saveTimer);
398
+ suppressRestoredAutosave = false;
399
+ setStatus('Unsaved');
400
+ rememberActiveSession();
401
+ updateUndoButton();
402
+ if (preferences.autosave) {
403
+ const edited = active;
404
+ saveTimer = window.setTimeout(() => queueSave(edited), options.saveDelay);
405
+ }
406
+ positionToolbar();
407
+ }
408
+ function onKeyDown(event) {
409
+ if (!preferences.enabled)
410
+ return;
411
+ const target = event.target;
412
+ if (!active && event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')
413
+ && target instanceof HTMLElement && target.matches(EDITABLE_SELECTOR)) {
414
+ event.preventDefault();
415
+ moveEditableFocus(target, event.key === 'ArrowUp' ? -1 : 1);
416
+ return;
417
+ }
418
+ if (!active && event.key === 'Enter' && target instanceof HTMLElement && target.matches(EDITABLE_SELECTOR)) {
419
+ event.preventDefault();
420
+ void activate(target);
421
+ return;
422
+ }
423
+ if (!active || !active.contains(target))
424
+ return;
425
+ const modifier = event.ctrlKey || event.metaKey;
426
+ if (modifier && event.shiftKey && event.code === 'Digit7') {
427
+ event.preventDefault();
428
+ changeList('ol');
429
+ }
430
+ else if (modifier && event.shiftKey && event.code === 'Digit8') {
431
+ event.preventDefault();
432
+ changeList('ul');
433
+ }
434
+ else if (modifier && event.key.toLowerCase() === 'k') {
435
+ event.preventDefault();
436
+ openLinkEditor();
437
+ }
438
+ else if (modifier && event.key.toLowerCase() === 'z' && !event.shiftKey) {
439
+ event.preventDefault();
440
+ undoEdit();
441
+ }
442
+ else if (modifier && event.key.toLowerCase() === 'b') {
443
+ event.preventDefault();
444
+ runInlineCommand('bold');
445
+ }
446
+ else if (modifier && event.key.toLowerCase() === 'i') {
447
+ event.preventDefault();
448
+ runInlineCommand('italic');
449
+ }
450
+ else if (modifier && event.key.toLowerCase() === 's') {
451
+ event.preventDefault();
452
+ queueSave(active);
453
+ }
454
+ else if (event.altKey && event.key === 'F10') {
455
+ event.preventDefault();
456
+ toolbar.querySelector('button:not(:disabled)')?.focus();
457
+ }
458
+ else if (event.altKey && /^Digit[1-6]$/.test(event.code)) {
459
+ event.preventDefault();
460
+ changeBlockTag(`h${event.code.slice(-1)}`);
461
+ }
462
+ else if (event.key === 'Escape') {
463
+ event.preventDefault();
464
+ void finishEditing();
465
+ }
466
+ }
467
+ function onToolbarKeyDown(event) {
468
+ if (!(event instanceof KeyboardEvent))
469
+ return;
470
+ if (event.key === 'Enter'
471
+ && event.target instanceof HTMLInputElement
472
+ && event.target.closest('.link-editor')) {
473
+ event.preventDefault();
474
+ applyLink();
475
+ return;
476
+ }
477
+ if (event.key !== 'Escape')
478
+ return;
479
+ event.preventDefault();
480
+ if (isFrontmatterEditorOpen())
481
+ closeFrontmatterEditor(true);
482
+ else if (isLinkEditorOpen())
483
+ closeLinkEditor();
484
+ else
485
+ void finishEditing();
486
+ }
487
+ function onToolbarClick(event) {
488
+ const button = event.composedPath().find((item) => item instanceof HTMLButtonElement);
489
+ if (!button)
490
+ return;
491
+ const action = button.dataset.action;
492
+ if (action === 'save-frontmatter') {
493
+ void saveFrontmatter();
494
+ return;
495
+ }
496
+ if (action === 'cancel-frontmatter') {
497
+ closeFrontmatterEditor(true);
498
+ return;
499
+ }
500
+ if (!active)
501
+ return;
502
+ const command = button.dataset.command;
503
+ const tag = button.dataset.tag;
504
+ const list = button.dataset.list;
505
+ if (command)
506
+ runInlineCommand(command);
507
+ else if (tag)
508
+ changeBlockTag(tag);
509
+ else if (list === 'ul' || list === 'ol')
510
+ changeList(list);
511
+ else if (button.dataset.action === 'undo')
512
+ undoEdit();
513
+ else if (button.dataset.action === 'add-block')
514
+ void addBlockAfter();
515
+ else if (button.dataset.action === 'delete-block')
516
+ void deleteBlock();
517
+ else if (button.dataset.action === 'link')
518
+ openLinkEditor();
519
+ else if (button.dataset.action === 'apply-link')
520
+ applyLink();
521
+ else if (button.dataset.action === 'remove-link')
522
+ removeLink();
523
+ else if (button.dataset.action === 'cancel-link')
524
+ closeLinkEditor();
525
+ else if (button.dataset.action === 'save')
526
+ queueSave(active);
527
+ /* istanbul ignore else -- Remaining toolbar actions are inert by design. */
528
+ else if (button.dataset.action === 'done')
529
+ void finishEditing();
530
+ }
531
+ async function structuralTarget() {
532
+ /* istanbul ignore next -- Toolbar actions require an active block. */
533
+ if (!active)
534
+ return undefined;
535
+ let element = active;
536
+ if (hasUnsavedChanges(element)) {
537
+ const saved = await queueSave(element);
538
+ /* istanbul ignore else -- Both save outcomes are covered through the caller-visible status. */
539
+ if (!saved)
540
+ return undefined;
541
+ /* istanbul ignore next -- Saving an active structural target does not clear it. */
542
+ element = active ?? element;
543
+ }
544
+ const marker = element.getAttribute(MARKER_ATTRIBUTE);
545
+ const decoded = decodeClientMarker(marker);
546
+ if (!marker || !decoded || decoded.format === 'frontmatter') {
547
+ setStatus('Frontmatter fields cannot be added or deleted.', true);
548
+ return undefined;
549
+ }
550
+ return { element, marker };
551
+ }
552
+ async function addBlockAfter() {
553
+ const target = await structuralTarget();
554
+ if (!target)
555
+ return;
556
+ setStatus('Adding block...');
557
+ try {
558
+ const response = await fetch(options.endpoint, {
559
+ method: 'POST',
560
+ headers: { 'Content-Type': 'application/json' },
561
+ body: JSON.stringify({ marker: target.marker, operation: 'insert-after' }),
562
+ });
563
+ const body = await response.json();
564
+ /* istanbul ignore next -- The endpoint always supplies an error for rejected requests. */
565
+ if (!response.ok || !body.marker)
566
+ throw new Error(body.error ?? 'The block could not be added.');
567
+ const paragraph = document.createElement('p');
568
+ paragraph.textContent = 'New paragraph';
569
+ paragraph.setAttribute(MARKER_ATTRIBUTE, body.marker);
570
+ if (target.element.isConnected) {
571
+ target.element.after(paragraph);
572
+ await activate(paragraph);
573
+ }
574
+ else {
575
+ rememberInsertedBlock(body.marker);
576
+ active = null;
577
+ await restoreActiveSession();
578
+ }
579
+ setStatus('Block added');
580
+ }
581
+ catch (error) {
582
+ /* istanbul ignore next -- Fetch and response failures are Error instances in browsers. */
583
+ setStatus(error instanceof Error ? error.message : 'The block could not be added.', true);
584
+ }
585
+ }
586
+ async function deleteBlock() {
587
+ if (!active || !window.confirm('Delete this block from its source file?'))
588
+ return;
589
+ const target = await structuralTarget();
590
+ if (!target)
591
+ return;
592
+ setStatus('Deleting block...');
593
+ try {
594
+ try {
595
+ sessionStorage.removeItem(SESSION_KEY);
596
+ }
597
+ catch {
598
+ // Deletion still works when session storage is unavailable.
599
+ }
600
+ const response = await fetch(options.endpoint, {
601
+ method: 'POST',
602
+ headers: { 'Content-Type': 'application/json' },
603
+ body: JSON.stringify({ marker: target.marker, operation: 'delete' }),
604
+ });
605
+ const body = await response.json();
606
+ /* istanbul ignore next -- The endpoint always supplies an error for rejected requests. */
607
+ if (!response.ok)
608
+ throw new Error(body.error ?? 'The block could not be deleted.');
609
+ /* istanbul ignore else -- Successful writes normally retain the selected DOM node until removal. */
610
+ if (target.element.isConnected)
611
+ target.element.remove();
612
+ active = null;
613
+ undoHistory = [];
614
+ toolbar.hidden = true;
615
+ setStatus('Block deleted');
616
+ }
617
+ catch (error) {
618
+ if (target.element.isConnected) {
619
+ active = target.element;
620
+ rememberActiveSession();
621
+ }
622
+ /* istanbul ignore next -- Fetch and response failures are Error instances in browsers. */
623
+ setStatus(error instanceof Error ? error.message : 'The block could not be deleted.', true);
624
+ }
625
+ }
626
+ function rememberInsertedBlock(token) {
627
+ const marker = decodeClientMarker(token);
628
+ /* istanbul ignore next -- Successful insert responses contain a server-validated marker. */
629
+ if (!marker)
630
+ return;
631
+ const inserted = { html: 'New paragraph', tag: 'p' };
632
+ try {
633
+ sessionStorage.setItem(SESSION_KEY, JSON.stringify({
634
+ pathname: location.pathname,
635
+ file: marker.file,
636
+ start: marker.start,
637
+ html: inserted.html,
638
+ tag: inserted.tag,
639
+ history: [inserted],
640
+ suppressAutosave: true,
641
+ }));
642
+ }
643
+ catch {
644
+ // The inserted block still exists in source when session storage is unavailable.
645
+ }
646
+ }
647
+ function updateStructureButtons() {
648
+ /* istanbul ignore next -- This refresh is called after active-block guards. */
649
+ const marker = decodeClientMarker(active?.getAttribute(MARKER_ATTRIBUTE) ?? null);
650
+ const disabled = !marker || marker.format === 'frontmatter';
651
+ for (const button of toolbar.querySelectorAll('[data-action="add-block"], [data-action="delete-block"]')) {
652
+ button.disabled = disabled;
653
+ }
654
+ }
655
+ function findFrontmatterContextMarker() {
656
+ const candidates = [
657
+ active,
658
+ ...document.querySelectorAll(`[${MARKER_ATTRIBUTE}]`),
659
+ ];
660
+ for (const element of candidates) {
661
+ const token = element?.getAttribute(MARKER_ATTRIBUTE);
662
+ const marker = decodeClientMarker(token ?? null);
663
+ if (token && marker && /\.(?:md|mdx)$/i.test(marker.file))
664
+ return token;
665
+ }
666
+ return undefined;
667
+ }
668
+ function isFrontmatterEditorOpen() {
669
+ /* istanbul ignore next -- The dialog is static toolbar markup. */
670
+ return shadow.querySelector('.frontmatter-editor')?.open ?? false;
671
+ }
672
+ async function restoreFrontmatterDraft() {
673
+ const draft = readFrontmatterDraft();
674
+ if (draft)
675
+ await openFrontmatterEditor(draft);
676
+ }
677
+ function readFrontmatterDraft() {
678
+ try {
679
+ const value = JSON.parse(sessionStorage.getItem(FRONTMATTER_DRAFT_KEY) ?? 'null');
680
+ if (!value || typeof value !== 'object')
681
+ return undefined;
682
+ const draft = value;
683
+ if (draft.pathname !== location.pathname || typeof draft.contextMarker !== 'string')
684
+ return undefined;
685
+ if (!draft.changes || typeof draft.changes !== 'object' || Array.isArray(draft.changes))
686
+ return undefined;
687
+ for (const change of Object.values(draft.changes)) {
688
+ if (!change || typeof change !== 'object' || Array.isArray(change))
689
+ return undefined;
690
+ const fields = change;
691
+ if (typeof fields.original !== 'string'
692
+ || (typeof fields.value !== 'string' && typeof fields.value !== 'boolean'))
693
+ return undefined;
694
+ }
695
+ return draft;
696
+ }
697
+ catch {
698
+ return undefined;
699
+ }
700
+ }
701
+ async function openFrontmatterEditor(draft) {
702
+ if (isLinkEditorOpen())
703
+ closeLinkEditor();
704
+ const marker = draft?.contextMarker ?? findFrontmatterContextMarker();
705
+ const editor = shadow.querySelector('.frontmatter-editor');
706
+ const fields = shadow.querySelector('.frontmatter-fields');
707
+ /* istanbul ignore next -- These controls are static frontmatter-editor markup. */
708
+ if (!editor || !fields)
709
+ return;
710
+ frontmatterContext = marker;
711
+ frontmatterFields = [];
712
+ /* istanbul ignore else -- Opening an already-open editor only refreshes its context. */
713
+ if (!editor.open)
714
+ editor.showModal();
715
+ fields.replaceChildren();
716
+ setFrontmatterMessage('Loading...');
717
+ if (!marker) {
718
+ setFrontmatterMessage('Open a Markdown or MDX page with source-backed content.');
719
+ return;
720
+ }
721
+ try {
722
+ const response = await fetch(options.endpoint, {
723
+ method: 'POST',
724
+ headers: { 'Content-Type': 'application/json' },
725
+ body: JSON.stringify({ frontmatter: 'read', contextMarker: marker }),
726
+ });
727
+ const body = await response.json();
728
+ /* istanbul ignore next -- The endpoint always supplies an error for rejected requests. */
729
+ if (!response.ok || !body.fields)
730
+ throw new Error(body.error ?? 'Frontmatter could not be loaded.');
731
+ frontmatterFields = body.fields;
732
+ renderFrontmatterFields(fields, frontmatterFields);
733
+ if (draft)
734
+ restoreFrontmatterDraftFields(draft);
735
+ else {
736
+ /* istanbul ignore next -- Empty field collections are a valid endpoint fallback. */
737
+ setFrontmatterMessage(frontmatterFields.length ? '' : 'No simple frontmatter fields were found.');
738
+ }
739
+ fields.querySelector('input')?.focus();
740
+ }
741
+ catch (error) {
742
+ /* istanbul ignore next -- Fetch and response failures are Error instances in browsers. */
743
+ setFrontmatterMessage(error instanceof Error ? error.message : 'Frontmatter could not be loaded.');
744
+ }
745
+ }
746
+ function renderFrontmatterFields(container, fields) {
747
+ for (const field of fields) {
748
+ const label = document.createElement('label');
749
+ label.className = 'frontmatter-field';
750
+ const name = document.createElement('span');
751
+ name.textContent = field.name;
752
+ const input = document.createElement('input');
753
+ input.dataset.frontmatterField = field.name;
754
+ input.setAttribute('aria-label', field.name);
755
+ if (field.type === 'boolean') {
756
+ input.type = 'checkbox';
757
+ input.checked = field.value === true;
758
+ }
759
+ else {
760
+ /* istanbul ignore next -- Field-type parsing is exhaustively covered by frontmatter unit tests. */
761
+ input.type = field.type === 'date' ? 'date' : field.type === 'number' ? 'number' : 'text';
762
+ input.value = String(field.value);
763
+ }
764
+ label.append(name, input);
765
+ container.append(label);
766
+ }
767
+ }
768
+ function restoreFrontmatterDraftFields(draft) {
769
+ let restored = false;
770
+ for (const field of frontmatterFields) {
771
+ const change = draft.changes[field.name];
772
+ if (!change)
773
+ continue;
774
+ const input = shadow.querySelector(`[data-frontmatter-field="${CSS.escape(field.name)}"]`);
775
+ /* istanbul ignore next -- Inputs are rendered from this same field collection. */
776
+ if (!input)
777
+ continue;
778
+ if (field.type === 'boolean' && typeof change.value === 'boolean')
779
+ input.checked = change.value;
780
+ else if (field.type !== 'boolean' && typeof change.value === 'string')
781
+ input.value = change.value;
782
+ else
783
+ continue;
784
+ field.original = change.original;
785
+ restored = true;
786
+ }
787
+ setFrontmatterMessage(restored
788
+ ? 'Restored unsaved frontmatter changes.'
789
+ : 'The unsaved frontmatter fields are no longer available.');
790
+ }
791
+ function collectFrontmatterChanges() {
792
+ const changes = {};
793
+ for (const field of frontmatterFields) {
794
+ const input = shadow.querySelector(`[data-frontmatter-field="${CSS.escape(field.name)}"]`);
795
+ /* istanbul ignore next -- Inputs are rendered from this same field collection. */
796
+ if (!input)
797
+ continue;
798
+ const value = field.type === 'boolean' ? input.checked : input.value;
799
+ if (value !== field.value)
800
+ changes[field.name] = { value, original: field.original };
801
+ }
802
+ return changes;
803
+ }
804
+ function rememberFrontmatterDraft(event) {
805
+ if (!(event.target instanceof HTMLInputElement)
806
+ || !event.target.hasAttribute('data-frontmatter-field')
807
+ || !frontmatterContext)
808
+ return;
809
+ const changes = collectFrontmatterChanges();
810
+ try {
811
+ if (Object.keys(changes).length === 0)
812
+ sessionStorage.removeItem(FRONTMATTER_DRAFT_KEY);
813
+ else
814
+ sessionStorage.setItem(FRONTMATTER_DRAFT_KEY, JSON.stringify({
815
+ pathname: location.pathname,
816
+ contextMarker: frontmatterContext,
817
+ changes,
818
+ }));
819
+ }
820
+ catch {
821
+ // Frontmatter editing still works when session storage is unavailable.
822
+ }
823
+ }
824
+ async function saveFrontmatter() {
825
+ /* istanbul ignore next -- The save action is only rendered with a frontmatter context. */
826
+ if (!frontmatterContext)
827
+ return;
828
+ const changes = collectFrontmatterChanges();
829
+ if (Object.keys(changes).length === 0) {
830
+ closeFrontmatterEditor(true);
831
+ return;
832
+ }
833
+ setFrontmatterMessage('Saving...');
834
+ try {
835
+ const response = await fetch(options.endpoint, {
836
+ method: 'POST',
837
+ headers: { 'Content-Type': 'application/json' },
838
+ body: JSON.stringify({
839
+ frontmatter: 'update',
840
+ contextMarker: frontmatterContext,
841
+ changes,
842
+ }),
843
+ });
844
+ const body = await response.json();
845
+ /* istanbul ignore next -- The endpoint always supplies an error for rejected requests. */
846
+ if (!response.ok || !body.saved)
847
+ throw new Error(body.error ?? 'Frontmatter could not be saved.');
848
+ setStatus('Saved');
849
+ closeFrontmatterEditor(true);
850
+ }
851
+ catch (error) {
852
+ /* istanbul ignore next -- Fetch and response failures are Error instances in browsers. */
853
+ setFrontmatterMessage(error instanceof Error ? error.message : 'Frontmatter could not be saved.');
854
+ }
855
+ }
856
+ function closeFrontmatterEditor(discardDraft = false) {
857
+ const editor = shadow.querySelector('.frontmatter-editor');
858
+ /* istanbul ignore else -- Close is called for an open static dialog or as an idempotent cleanup. */
859
+ if (editor?.open)
860
+ editor.close();
861
+ frontmatterContext = undefined;
862
+ frontmatterFields = [];
863
+ if (discardDraft) {
864
+ try {
865
+ sessionStorage.removeItem(FRONTMATTER_DRAFT_KEY);
866
+ }
867
+ catch {
868
+ // The dialog still closes when session storage is unavailable.
869
+ }
870
+ }
871
+ setFrontmatterMessage('');
872
+ active?.focus({ preventScroll: true });
873
+ }
874
+ function setFrontmatterMessage(message) {
875
+ const element = shadow.querySelector('.frontmatter-message');
876
+ /* istanbul ignore else -- The message node is static frontmatter-editor markup. */
877
+ if (element)
878
+ element.textContent = message;
879
+ }
880
+ function isLinkEditorOpen() {
881
+ const editor = toolbar.querySelector('.link-editor');
882
+ return Boolean(editor && !editor.hidden);
883
+ }
884
+ function openLinkEditor() {
885
+ /* istanbul ignore next -- Link actions require an active block. */
886
+ if (!active)
887
+ return;
888
+ const selection = getSelection();
889
+ const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
890
+ if (!range || !active.contains(range.commonAncestorContainer)) {
891
+ setLinkError('Select text or place the caret inside a link.');
892
+ return;
893
+ }
894
+ linkRange = range.cloneRange();
895
+ const container = range.commonAncestorContainer instanceof Element
896
+ ? range.commonAncestorContainer
897
+ : range.commonAncestorContainer.parentElement;
898
+ editingLink = container?.closest('a') ?? undefined;
899
+ /* istanbul ignore next -- A validated range is contained by the active block. */
900
+ if (editingLink && !active.contains(editingLink))
901
+ editingLink = undefined;
902
+ const editor = toolbar.querySelector('.link-editor');
903
+ const input = toolbar.querySelector('.link-editor input');
904
+ const remove = toolbar.querySelector('[data-action="remove-link"]');
905
+ /* istanbul ignore next -- These controls are static toolbar markup. */
906
+ if (!editor || !input || !remove)
907
+ return;
908
+ editor.hidden = false;
909
+ input.value = editingLink?.getAttribute('href') ?? '';
910
+ remove.disabled = !editingLink;
911
+ setLinkError('');
912
+ positionToolbar();
913
+ input.focus();
914
+ input.select();
915
+ }
916
+ function applyLink() {
917
+ /* istanbul ignore next -- Apply is only enabled by an active link-editing session. */
918
+ if (!active || !linkRange)
919
+ return;
920
+ const input = toolbar.querySelector('.link-editor input');
921
+ /* istanbul ignore next -- The input is static link-editor markup. */
922
+ if (!input)
923
+ return;
924
+ const href = validHref(input.value);
925
+ if (!href) {
926
+ setLinkError('Enter an http, https, mail, phone, anchor, or relative URL.');
927
+ return;
928
+ }
929
+ if (!editingLink && linkRange.collapsed) {
930
+ setLinkError('Select text before adding a new link.');
931
+ return;
932
+ }
933
+ checkpoint(active);
934
+ if (editingLink?.isConnected && active.contains(editingLink)) {
935
+ editingLink.setAttribute('href', href);
936
+ }
937
+ else {
938
+ restoreLinkRange();
939
+ document.execCommand('createLink', false, href);
940
+ }
941
+ finishLinkChange();
942
+ }
943
+ function removeLink() {
944
+ /* istanbul ignore next -- Remove is only enabled for the connected link in the active block. */
945
+ if (!active || !editingLink?.isConnected || !active.contains(editingLink))
946
+ return;
947
+ checkpoint(active);
948
+ editingLink.replaceWith(...editingLink.childNodes);
949
+ finishLinkChange();
950
+ }
951
+ function finishLinkChange() {
952
+ /* istanbul ignore next -- Link changes can only finish in the active block. */
953
+ if (!active)
954
+ return;
955
+ closeLinkEditor();
956
+ setStatus('Unsaved');
957
+ rememberActiveSession();
958
+ updateUndoButton();
959
+ window.clearTimeout(saveTimer);
960
+ /* istanbul ignore else -- Manual-save link changes remain unsaved until an explicit save. */
961
+ if (preferences.autosave) {
962
+ const edited = active;
963
+ saveTimer = window.setTimeout(() => queueSave(edited), options.saveDelay);
964
+ }
965
+ }
966
+ function closeLinkEditor() {
967
+ const editor = toolbar.querySelector('.link-editor');
968
+ /* istanbul ignore else -- The link editor is static toolbar markup. */
969
+ if (editor)
970
+ editor.hidden = true;
971
+ linkRange = undefined;
972
+ editingLink = undefined;
973
+ setLinkError('');
974
+ active?.focus({ preventScroll: true });
975
+ positionToolbar();
976
+ }
977
+ function restoreLinkRange() {
978
+ /* istanbul ignore next -- This helper is called only after a link range is validated. */
979
+ if (!linkRange)
980
+ return;
981
+ const selection = getSelection();
982
+ selection?.removeAllRanges();
983
+ selection?.addRange(linkRange);
984
+ }
985
+ function setLinkError(message) {
986
+ const error = toolbar.querySelector('.link-error');
987
+ /* istanbul ignore else -- The error node is static link-editor markup. */
988
+ if (error)
989
+ error.textContent = message;
990
+ }
991
+ function validHref(value) {
992
+ const href = value.trim();
993
+ if (!href || /[\u0000-\u001f\u007f]/.test(href))
994
+ return undefined;
995
+ try {
996
+ const protocol = new URL(href, location.href).protocol;
997
+ return ['http:', 'https:', 'mailto:', 'tel:'].includes(protocol) ? href : undefined;
998
+ }
999
+ catch {
1000
+ return undefined;
1001
+ }
1002
+ }
1003
+ function snapshot(element) {
1004
+ return { html: element.innerHTML, tag: element.localName };
1005
+ }
1006
+ function sameSnapshot(left, right) {
1007
+ return left.html === right.html && left.tag === right.tag;
1008
+ }
1009
+ function checkpoint(element, value = snapshot(element)) {
1010
+ const previous = undoHistory.at(-1);
1011
+ if (!previous || !sameSnapshot(previous, value))
1012
+ undoHistory.push(value);
1013
+ rememberActiveSession();
1014
+ updateUndoButton();
1015
+ }
1016
+ function hasUnsavedChanges(element) {
1017
+ const saved = undoHistory.at(-1);
1018
+ return !saved || !sameSnapshot(saved, snapshot(element));
1019
+ }
1020
+ function updateUndoButton() {
1021
+ const button = toolbar.querySelector('[data-action="undo"]');
1022
+ /* istanbul ignore next -- Undo is static toolbar markup. */
1023
+ if (!button)
1024
+ return;
1025
+ const current = active ? snapshot(active) : undefined;
1026
+ button.disabled = !current || (undoHistory.length === 1 && sameSnapshot(undoHistory[0], current));
1027
+ }
1028
+ function undoEdit() {
1029
+ /* istanbul ignore next -- Undo is disabled without an active checkpoint. */
1030
+ if (!active || undoHistory.length === 0)
1031
+ return;
1032
+ const current = snapshot(active);
1033
+ if (undoHistory.length > 1 && sameSnapshot(undoHistory.at(-1), current))
1034
+ undoHistory.pop();
1035
+ const target = undoHistory.at(-1);
1036
+ if (!target || sameSnapshot(target, current))
1037
+ return;
1038
+ if (active.localName !== target.tag)
1039
+ changeBlockTag(target.tag, false, false);
1040
+ /* istanbul ignore next -- Tag replacement always installs the replacement as active. */
1041
+ if (!active)
1042
+ return;
1043
+ active.innerHTML = target.html;
1044
+ active.focus({ preventScroll: true });
1045
+ setCaretOffset(active);
1046
+ setStatus('Unsaved');
1047
+ rememberActiveSession();
1048
+ updateUndoButton();
1049
+ queueSave(active);
1050
+ }
1051
+ function runInlineCommand(command) {
1052
+ /* istanbul ignore next -- Formatting actions require an active block. */
1053
+ if (!active)
1054
+ return;
1055
+ checkpoint(active);
1056
+ document.execCommand('styleWithCSS', false, 'false');
1057
+ document.execCommand(command, false);
1058
+ active.focus({ preventScroll: true });
1059
+ setStatus('Unsaved');
1060
+ window.clearTimeout(saveTimer);
1061
+ rememberActiveSession();
1062
+ updateUndoButton();
1063
+ if (preferences.autosave) {
1064
+ const edited = active;
1065
+ saveTimer = window.setTimeout(() => queueSave(edited), options.saveDelay);
1066
+ }
1067
+ }
1068
+ function changeList(tag) {
1069
+ /* istanbul ignore next -- List actions require an active block. */
1070
+ if (!active)
1071
+ return;
1072
+ if (active.localName === 'ul' || active.localName === 'ol') {
1073
+ if (active.localName !== tag) {
1074
+ changeBlockTag(tag);
1075
+ return;
1076
+ }
1077
+ checkpoint(active);
1078
+ const paragraph = document.createElement('p');
1079
+ const items = [...active.children].filter((child) => child instanceof HTMLLIElement);
1080
+ items.forEach((item, index) => {
1081
+ if (index > 0)
1082
+ paragraph.append(document.createElement('br'));
1083
+ while (item.firstChild)
1084
+ paragraph.append(item.firstChild);
1085
+ });
1086
+ replaceActiveElement(paragraph);
1087
+ return;
1088
+ }
1089
+ checkpoint(active);
1090
+ const list = document.createElement(tag);
1091
+ const item = document.createElement('li');
1092
+ while (active.firstChild)
1093
+ item.append(active.firstChild);
1094
+ list.append(item);
1095
+ replaceActiveElement(list);
1096
+ }
1097
+ function changeBlockTag(tag, record = true, scheduleSave = true) {
1098
+ if (!active || active.localName === tag)
1099
+ return;
1100
+ if (record)
1101
+ checkpoint(active);
1102
+ const replacement = document.createElement(tag);
1103
+ while (active.firstChild)
1104
+ replacement.append(active.firstChild);
1105
+ replaceActiveElement(replacement, scheduleSave);
1106
+ }
1107
+ function replaceActiveElement(replacement, scheduleSave = true) {
1108
+ /* istanbul ignore next -- Replacements are created only for an active block. */
1109
+ if (!active)
1110
+ return;
1111
+ for (const attribute of active.attributes)
1112
+ replacement.setAttribute(attribute.name, attribute.value);
1113
+ active.replaceWith(replacement);
1114
+ active = replacement;
1115
+ active.setAttribute('contenteditable', 'true');
1116
+ active.focus({ preventScroll: true });
1117
+ setStatus('Unsaved');
1118
+ window.clearTimeout(saveTimer);
1119
+ rememberActiveSession();
1120
+ updateUndoButton();
1121
+ if (scheduleSave && preferences.autosave) {
1122
+ const edited = active;
1123
+ saveTimer = window.setTimeout(() => queueSave(edited), options.saveDelay);
1124
+ }
1125
+ positionToolbar();
1126
+ }
1127
+ async function finishEditing() {
1128
+ /* istanbul ignore next -- Finish is exposed only while a block is active. */
1129
+ if (!active)
1130
+ return;
1131
+ if (isFrontmatterEditorOpen())
1132
+ closeFrontmatterEditor();
1133
+ if (isLinkEditorOpen())
1134
+ closeLinkEditor();
1135
+ window.clearTimeout(saveTimer);
1136
+ const finished = active;
1137
+ if (hasUnsavedChanges(finished)) {
1138
+ const saved = await queueSave(finished);
1139
+ if (!saved || active !== finished)
1140
+ return;
1141
+ if (hasUnsavedChanges(finished)) {
1142
+ setStatus('Unsaved');
1143
+ return;
1144
+ }
1145
+ }
1146
+ deactivate(finished);
1147
+ active = null;
1148
+ undoHistory = [];
1149
+ updateUndoButton();
1150
+ try {
1151
+ sessionStorage.removeItem(SESSION_KEY);
1152
+ }
1153
+ catch {
1154
+ // Nothing needs clearing when session storage is unavailable.
1155
+ }
1156
+ toolbar.hidden = true;
1157
+ finished.focus({ preventScroll: true });
1158
+ setStatus('Saved');
1159
+ }
1160
+ function queueSave(element) {
1161
+ window.clearTimeout(saveTimer);
1162
+ /* istanbul ignore else -- Saves are queued while their source block is active. */
1163
+ if (element === active) {
1164
+ activeSaveInFlight = true;
1165
+ suppressRestoredAutosave = false;
1166
+ rememberActiveSession();
1167
+ }
1168
+ const html = element.innerHTML;
1169
+ /* istanbul ignore next -- HTMLElement textContent is present for supported blocks. */
1170
+ const text = element.textContent ?? '';
1171
+ const tag = element.localName;
1172
+ setStatus('Saving...');
1173
+ const pending = pendingSaves.find((save) => save.element === element);
1174
+ if (pending) {
1175
+ pending.html = html;
1176
+ pending.text = text;
1177
+ pending.tag = tag;
1178
+ return pending.promise;
1179
+ }
1180
+ let resolve;
1181
+ const promise = new Promise((complete) => { resolve = complete; });
1182
+ pendingSaves.push({ element, html, promise, resolve, tag, text });
1183
+ void drainSaveQueue();
1184
+ return promise;
1185
+ }
1186
+ async function drainSaveQueue() {
1187
+ if (saveInFlight)
1188
+ return;
1189
+ saveInFlight = true;
1190
+ try {
1191
+ while (pendingSaves.length) {
1192
+ const save = pendingSaves.shift();
1193
+ save.resolve(await saveSnapshot(save));
1194
+ }
1195
+ }
1196
+ finally {
1197
+ saveInFlight = false;
1198
+ }
1199
+ }
1200
+ async function saveSnapshot({ element, html, tag, text }) {
1201
+ const marker = element.getAttribute(MARKER_ATTRIBUTE);
1202
+ if (!marker) {
1203
+ /* istanbul ignore else -- Missing markers are detected on the current active block. */
1204
+ if (element === active) {
1205
+ activeSaveInFlight = hasPendingSave(element);
1206
+ rememberActiveSession();
1207
+ }
1208
+ setStatus('Missing source marker.', true);
1209
+ return false;
1210
+ }
1211
+ setStatus('Saving...');
1212
+ const controller = new AbortController();
1213
+ const requestTimeout = window.setTimeout(() => controller.abort(), SAVE_REQUEST_TIMEOUT);
1214
+ try {
1215
+ const response = await fetch(options.endpoint, {
1216
+ method: 'POST',
1217
+ headers: { 'Content-Type': 'application/json' },
1218
+ body: JSON.stringify({ marker, html, text, tag }),
1219
+ signal: controller.signal,
1220
+ });
1221
+ const body = await response.json();
1222
+ /* istanbul ignore next -- The endpoint always supplies an error for rejected requests. */
1223
+ if (!response.ok || !body.marker)
1224
+ throw new Error(body.error ?? 'The source file could not be saved.');
1225
+ /* istanbul ignore else -- Unchanged DOM markers are refreshed from successful responses. */
1226
+ if (element.getAttribute(MARKER_ATTRIBUTE) === marker) {
1227
+ element.setAttribute(MARKER_ATTRIBUTE, body.marker);
1228
+ }
1229
+ /* istanbul ignore else -- An inactive block needs no active-session update. */
1230
+ if (element === active) {
1231
+ activeSaveInFlight = hasPendingSave(element);
1232
+ suppressRestoredAutosave = !activeSaveInFlight && sameSnapshot(snapshot(element), { html, tag });
1233
+ checkpoint(element, { html, tag });
1234
+ }
1235
+ setStatus('Saved');
1236
+ return true;
1237
+ }
1238
+ catch (error) {
1239
+ /* istanbul ignore else -- An inactive block needs no active-session update. */
1240
+ if (element === active) {
1241
+ activeSaveInFlight = hasPendingSave(element);
1242
+ rememberActiveSession();
1243
+ }
1244
+ /* istanbul ignore next -- Fetch and response failures are Error instances in browsers. */
1245
+ const message = controller.signal.aborted
1246
+ ? 'Saving timed out. Try again.'
1247
+ : error instanceof Error ? error.message : 'The source file could not be saved.';
1248
+ setStatus(message, true);
1249
+ return false;
1250
+ }
1251
+ finally {
1252
+ window.clearTimeout(requestTimeout);
1253
+ }
1254
+ }
1255
+ function hasPendingSave(element) {
1256
+ return pendingSaves.some((save) => save.element === element);
1257
+ }
1258
+ function positionToolbar() {
1259
+ if (!active || toolbar.hidden)
1260
+ return;
1261
+ const rect = active.getBoundingClientRect();
1262
+ const toolbarRect = toolbar.getBoundingClientRect();
1263
+ const top = rect.top >= toolbarRect.height + 16
1264
+ ? rect.top - toolbarRect.height - 8
1265
+ : Math.min(window.innerHeight - toolbarRect.height - 8, rect.bottom + 8);
1266
+ const left = Math.max(8, Math.min(rect.left, window.innerWidth - toolbarRect.width - 8));
1267
+ toolbar.style.transform = `translate(${Math.round(left)}px, ${Math.round(Math.max(8, top))}px)`;
1268
+ }
1269
+ function setStatus(message, error = false) {
1270
+ status.textContent = message;
1271
+ status.dataset.error = String(error);
1272
+ }
1273
+ }
1274
+ function sourceLocationDistance(candidate, target) {
1275
+ /* istanbul ignore next -- The optional candidate is covered by the invalid-coordinate guard below. */
1276
+ const parse = (value) => value?.split(':').map(Number) ?? [];
1277
+ const [candidateLine, candidateColumn] = parse(candidate);
1278
+ const [targetLine, targetColumn] = parse(target);
1279
+ /* istanbul ignore next -- Source locations come from Astro's numeric compiler coordinates. */
1280
+ if (![candidateLine, candidateColumn, targetLine, targetColumn].every(Number.isFinite)) {
1281
+ return Number.MAX_SAFE_INTEGER;
1282
+ }
1283
+ return Math.abs(candidateLine - targetLine) * 10_000 + Math.abs(candidateColumn - targetColumn);
1284
+ }
1285
+ function readActiveSession() {
1286
+ try {
1287
+ const value = sessionStorage.getItem(SESSION_KEY);
1288
+ return value ? JSON.parse(value) : undefined;
1289
+ }
1290
+ catch {
1291
+ return undefined;
1292
+ }
1293
+ }
1294
+ function decodeClientMarker(token) {
1295
+ if (!token)
1296
+ return undefined;
1297
+ try {
1298
+ const base64 = token.replace(/-/g, '+').replace(/_/g, '/');
1299
+ const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
1300
+ const value = JSON.parse(new TextDecoder().decode(bytes));
1301
+ if (typeof value.file !== 'string' || typeof value.start !== 'number')
1302
+ return undefined;
1303
+ if (value.format !== 'astro' && value.format !== 'frontmatter' && value.format !== 'markdown')
1304
+ return undefined;
1305
+ return {
1306
+ file: value.file,
1307
+ start: value.start,
1308
+ format: value.format,
1309
+ original: typeof value.original === 'string' ? value.original : undefined,
1310
+ };
1311
+ }
1312
+ catch {
1313
+ return undefined;
1314
+ }
1315
+ }
1316
+ function getCaretOffset(element) {
1317
+ const selection = getSelection();
1318
+ if (!selection?.focusNode || !element.contains(selection.focusNode))
1319
+ return undefined;
1320
+ const range = document.createRange();
1321
+ range.selectNodeContents(element);
1322
+ range.setEnd(selection.focusNode, selection.focusOffset);
1323
+ return range.toString().length;
1324
+ }
1325
+ function setCaretOffset(element, offset = element.textContent.length) {
1326
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
1327
+ let remaining = offset;
1328
+ let node = walker.nextNode();
1329
+ while (node) {
1330
+ const length = node.textContent.length;
1331
+ if (remaining <= length) {
1332
+ const range = document.createRange();
1333
+ range.setStart(node, remaining);
1334
+ range.collapse(true);
1335
+ const selection = getSelection();
1336
+ selection?.removeAllRanges();
1337
+ selection?.addRange(range);
1338
+ return;
1339
+ }
1340
+ remaining -= length;
1341
+ node = walker.nextNode();
1342
+ }
1343
+ element.focus({ preventScroll: true });
1344
+ }
1345
+ function toolbarMarkup() {
1346
+ return `
1347
+ <style>
1348
+ :host { all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none; }
1349
+ [role="toolbar"] {
1350
+ position: fixed; left: 0; top: 0; display: flex; align-items: center; gap: 3px;
1351
+ max-width: calc(100vw - 16px); padding: 6px; overflow-x: auto; pointer-events: auto;
1352
+ color: #f8fafc; background: #111827; border: 1px solid #475569; border-radius: 8px;
1353
+ box-shadow: 0 6px 24px rgb(0 0 0 / 35%); font: 13px/1.2 ui-sans-serif, system-ui, sans-serif;
1354
+ }
1355
+ button { min-width: 36px; min-height: 36px; padding: 6px 9px; color: inherit; background: #1f2937; border: 1px solid #64748b; border-radius: 5px; font: inherit; cursor: pointer; }
1356
+ button:hover { background: #334155; }
1357
+ button.danger { color: #fecaca; border-color: #b91c1c; }
1358
+ button.danger:hover { background: #7f1d1d; }
1359
+ button:disabled { opacity: .45; cursor: not-allowed; }
1360
+ button:focus-visible, input:focus-visible { outline: 3px solid #7dd3fc; outline-offset: 1px; }
1361
+ .bold { font-weight: 700; } .italic { font-style: italic; }
1362
+ .link-editor { display: flex; align-items: center; gap: 4px; }
1363
+ .link-editor input { width: min(260px, 42vw); min-height: 34px; padding: 0 8px; color: #111827; background: #fff; border: 1px solid #94a3b8; border-radius: 5px; font: 14px/1.2 ui-sans-serif, system-ui, sans-serif; }
1364
+ .link-error { max-width: 220px; color: #fecaca; font-size: 12px; }
1365
+ .frontmatter-editor { width: min(420px, calc(100vw - 32px)); max-height: min(620px, calc(100vh - 32px)); padding: 16px; overflow-y: auto; color: #f8fafc; background: #111827; border: 1px solid #475569; border-radius: 8px; box-shadow: 0 8px 28px rgb(0 0 0 / 45%); pointer-events: auto; }
1366
+ .frontmatter-editor::backdrop { background: rgb(15 23 42 / 65%); }
1367
+ .frontmatter-editor h2 { margin: 0 0 12px; font: 600 17px/1.2 ui-sans-serif, system-ui, sans-serif; }
1368
+ .frontmatter-fields { display: grid; gap: 9px; }
1369
+ .frontmatter-field { display: grid; grid-template-columns: minmax(110px, .7fr) minmax(0, 1.3fr); align-items: center; gap: 10px; }
1370
+ .frontmatter-field > span { overflow-wrap: anywhere; color: #cbd5e1; }
1371
+ .frontmatter-field input:not([type="checkbox"]) { min-width: 0; min-height: 34px; padding: 0 8px; color: #111827; background: #fff; border: 1px solid #94a3b8; border-radius: 5px; font: 14px/1.2 ui-sans-serif, system-ui, sans-serif; }
1372
+ .frontmatter-field input[type="checkbox"] { width: 20px; height: 20px; }
1373
+ .frontmatter-actions { display: flex; align-items: center; gap: 6px; margin-top: 14px; padding-top: 12px; border-top: 1px solid #475569; }
1374
+ .frontmatter-message { color: #fecaca; font-size: 12px; }
1375
+ .separator { width: 1px; height: 28px; margin: 0 2px; background: #64748b; }
1376
+ [role="status"] { min-width: 54px; margin-inline: 5px; white-space: nowrap; color: #bbf7d0; }
1377
+ [role="status"][data-error="true"] { max-width: 260px; color: #fecaca; white-space: normal; }
1378
+ [hidden] { display: none; }
1379
+ @media (forced-colors: active) { [role="toolbar"], button { border: 1px solid ButtonText; } }
1380
+ </style>
1381
+ <div role="toolbar" aria-label="Edit text" hidden>
1382
+ <button type="button" data-action="undo" aria-label="Undo" title="Undo (Ctrl+Z)" disabled>↶</button>
1383
+ <span class="separator" aria-hidden="true"></span>
1384
+ <button type="button" class="bold" data-command="bold" aria-label="Bold" title="Bold (Ctrl+B)">B</button>
1385
+ <button type="button" class="italic" data-command="italic" aria-label="Italic" title="Italic (Ctrl+I)">I</button>
1386
+ <button type="button" data-action="link" aria-label="Link" title="Link (Ctrl+K)">Link</button>
1387
+ <button type="button" data-list="ul" aria-label="Bullet list" title="Bullet list (Ctrl+Shift+8)">• List</button>
1388
+ <button type="button" data-list="ol" aria-label="Numbered list" title="Numbered list (Ctrl+Shift+7)">1. List</button>
1389
+ <span class="separator" aria-hidden="true"></span>
1390
+ <button type="button" data-action="add-block" aria-label="Add block below">+ Block</button>
1391
+ <button type="button" class="danger" data-action="delete-block" aria-label="Delete block">Delete</button>
1392
+ <span class="link-editor" role="group" aria-label="Edit link" hidden>
1393
+ <label><input type="text" inputmode="url" aria-label="Link URL" placeholder="https://example.com or /page" /></label>
1394
+ <button type="button" data-action="apply-link" aria-label="Apply link">Apply</button>
1395
+ <button type="button" data-action="remove-link" aria-label="Remove link">Remove</button>
1396
+ <button type="button" data-action="cancel-link" aria-label="Cancel link">Cancel</button>
1397
+ <span class="link-error" role="alert"></span>
1398
+ </span>
1399
+ <span class="separator" aria-hidden="true"></span>
1400
+ <button type="button" data-tag="h1" aria-label="Heading 1" title="Heading 1 (Alt+1)">H1</button>
1401
+ <button type="button" data-tag="h2" aria-label="Heading 2" title="Heading 2 (Alt+2)">H2</button>
1402
+ <button type="button" data-tag="h3" aria-label="Heading 3" title="Heading 3 (Alt+3)">H3</button>
1403
+ <button type="button" data-tag="h4" aria-label="Heading 4" title="Heading 4 (Alt+4)">H4</button>
1404
+ <button type="button" data-tag="h5" aria-label="Heading 5" title="Heading 5 (Alt+5)">H5</button>
1405
+ <button type="button" data-tag="h6" aria-label="Heading 6" title="Heading 6 (Alt+6)">H6</button>
1406
+ <button type="button" data-tag="p" aria-label="Paragraph">P</button>
1407
+ <span class="separator" aria-hidden="true"></span>
1408
+ <button type="button" data-action="save">Save</button>
1409
+ <button type="button" data-action="done">Done</button>
1410
+ <span role="status" aria-live="polite">Editing</span>
1411
+ </div>
1412
+ <dialog class="frontmatter-editor" aria-label="Edit frontmatter">
1413
+ <h2>Frontmatter</h2>
1414
+ <div class="frontmatter-fields"></div>
1415
+ <div class="frontmatter-actions">
1416
+ <button type="button" data-action="save-frontmatter">Save frontmatter</button>
1417
+ <button type="button" data-action="cancel-frontmatter">Cancel</button>
1418
+ <span class="frontmatter-message" role="alert"></span>
1419
+ </div>
1420
+ </dialog>
1421
+ `;
1422
+ }
1423
+ //# sourceMappingURL=client.js.map