-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_web_annotator.js
More file actions
818 lines (740 loc) · 29.3 KB
/
simple_web_annotator.js
File metadata and controls
818 lines (740 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
// ==UserScript==
// @name Simple Web Annotator v1.0
// @namespace vardwyn-swa
// @version 9.0
// @description In-page color highlights with toggleable activation, margin notes, and import/export.
// @match *://*/*
// @grant none
// ==/UserScript==
(function () {
'use strict';
/** ---------- Config ---------- */
const HIGHLIGHT_CLASS = 'user-highlight';
const COLOR_STYLES = {
yellow: '#fffa70',
green: '#90ff90',
red: '#ff8f8f'
};
// Main toggle key <---------- CONFIGURE HERE ------------>
const KEYBOARD_SHORTCUT = { key: 'c', ctrlKey: true, shiftKey: true, altKey: false, metaKey: false };
const FILE_VERSION = 1;
const UI_ROOT_ID = 'vardwyn-swa-ui-root';
const GUTTER_WIDTH = 280;
/** ---------- State ---------- */
let isActive = false;
let currentColor = 'yellow';
// UI Root (shadow) + elements
let uiHost = null;
let shadow = null;
let toolbarEl = null;
let gutterEl = null; // margin comments
let modalEl = null; // note editor modal
let toastsEl = null; // mini notifications
let importInputEl = null;
let styleElement = null;
// In-memory cache of page annotations (kept synced to localStorage)
let annotations = []; // [{id,color,anchors:[{xpath,start,end}],note,createdAt}]
const PAGE_KEY = (() => {
try { return 'vardwyn_swa:' + location.href.split('#')[0]; }
catch { return 'vardwyn_swa:' + location.pathname; }
})();
/** ---------- Utilities ---------- */
const uid = () => 'a_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
const saveToLocal = () => {
try {
localStorage.setItem(PAGE_KEY, JSON.stringify({ v: FILE_VERSION, url: location.href.split('#')[0], annotations }));
} catch (e) {
console.warn('[Simple Web Annotator] Failed saving to localStorage:', e);
toast('Could not save to localStorage.');
}
};
const loadFromLocal = () => {
try {
const raw = localStorage.getItem(PAGE_KEY);
if (!raw) return [];
const data = JSON.parse(raw);
if (Array.isArray(data)) return data; // legacy
return Array.isArray(data.annotations) ? data.annotations : [];
} catch {
return [];
}
};
const normalizeSelection = () => {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || !sel.rangeCount) return null;
// Normalize to a single Range clone (avoid live range side-effects)
const range = sel.getRangeAt(0).cloneRange();
try {
while (range.startContainer.nodeType === Node.TEXT_NODE &&
/^\s*$/.test(range.startContainer.nodeValue.slice(range.startOffset))) {
if (range.startOffset < range.startContainer.nodeValue.length) break;
// move forward (rare)
range.setStartAfter(range.startContainer);
}
while (range.endContainer.nodeType === Node.TEXT_NODE &&
/^\s*$/.test(range.endContainer.nodeValue.slice(0, range.endOffset))) {
if (range.endOffset > 0) break;
range.setEndBefore(range.endContainer);
}
} catch {}
return range;
};
const inHighlight = (node) => {
try {
return !!(node.parentElement && node.parentElement.closest('.' + HIGHLIGHT_CLASS));
} catch { return false; }
};
// Build a robust list of text segments intersecting the range (skips nodes already highlighted)
const getTextSegments = (range) => {
const segments = [];
const filter = {
acceptNode: (node) => {
if (!range || !range.intersectsNode(node)) return NodeFilter.FILTER_REJECT;
if (!node.nodeValue || !node.nodeValue.length || /^\s*$/.test(node.nodeValue)) return NodeFilter.FILTER_REJECT;
if (inHighlight(node)) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
}
};
const iterator = document.createNodeIterator(
range.commonAncestorContainer,
NodeFilter.SHOW_TEXT,
filter
);
let node;
while ((node = iterator.nextNode())) {
const start = (node === range.startContainer) ? range.startOffset : 0;
const end = (node === range.endContainer) ? range.endOffset : node.nodeValue.length;
if (end > start) segments.push({ node, start, end });
}
return segments;
};
// element steps and text() steps with 1-based indexes
const getXPath = (node) => {
const parts = [];
let curr = node;
while (curr && curr !== document) {
if (curr.nodeType === Node.TEXT_NODE) {
const parent = curr.parentNode;
if (!parent) break;
const texts = Array.from(parent.childNodes).filter(n => n.nodeType === Node.TEXT_NODE);
const idx = texts.indexOf(curr) + 1;
parts.unshift(`text()[${idx}]`);
curr = parent;
} else if (curr.nodeType === Node.ELEMENT_NODE) {
const tag = curr.tagName.toLowerCase();
let idx = 1;
let sib = curr;
while ((sib = sib.previousElementSibling)) {
if (sib.tagName.toLowerCase() === tag) idx++;
}
parts.unshift(`${tag}[${idx}]`);
curr = curr.parentNode;
} else {
break;
}
}
return '//' + parts.join('/');
};
const resolveXPath = (xpath) => {
try {
const result = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue || null;
} catch {
return null;
}
};
const toast = (msg, ms = 1800) => {
if (!toastsEl) return;
const item = document.createElement('div');
item.className = 'vh-toast';
item.textContent = msg;
toastsEl.appendChild(item);
setTimeout(() => item.classList.add('show'), 10);
setTimeout(() => {
item.classList.remove('show');
setTimeout(() => item.remove(), 250);
}, ms);
};
/** ---------- Apply / Remove highlights in DOM ---------- */
const highlightOneSegment = (node, start, end, color, annId) => {
const parent = node.parentNode;
const mid = node.splitText(start);
const after = mid.splitText(end - start);
if (mid.textContent.trim() === '') {
parent.normalize();
return null;
}
const span = document.createElement('span');
span.className = HIGHLIGHT_CLASS;
span.style.setProperty('--hl-color', COLOR_STYLES[color] || color);
span.textContent = mid.textContent;
span.setAttribute('data-ann-id', annId);
span.setAttribute('data-ann-color', color);
parent.replaceChild(span, mid);
parent.insertBefore(after, span.nextSibling);
parent.normalize();
return span;
};
// Create an annotation from current selection
const createAnnotationFromSelection = async ({ color, note = '' }) => {
const range = normalizeSelection();
if (!range) {
toast('Select text first.');
return null;
}
const segments = getTextSegments(range);
if (!segments.length) return null;
const annId = uid();
const anchors = segments.map(({ node, start, end }) => ({
xpath: getXPath(node),
start, end
}));
// Apply to DOM
const createdSpans = [];
segments.forEach(({ node, start, end }) => {
const span = highlightOneSegment(node, start, end, color, annId);
if (span) createdSpans.push(span);
});
// Save
const annotation = {
id: annId,
color,
anchors,
note,
createdAt: Date.now()
};
annotations.push(annotation);
saveToLocal();
// Clear selection
try { window.getSelection().removeAllRanges(); } catch {}
// Update UI
renderGutter();
renderSidebarList();
return annotation;
};
// Re-apply existing annotations from storage
const restoreAnnotations = () => {
// Guard: don't double-apply
// if a span for an id already exists, skip
const appliedIds = new Set(Array.from(document.querySelectorAll('.' + HIGHLIGHT_CLASS))
.map(s => s.getAttribute('data-ann-id'))
.filter(Boolean)
);
annotations.forEach(ann => {
if (appliedIds.has(ann.id)) return;
(ann.anchors || []).forEach(a => {
const node = resolveXPath(a.xpath);
if (!node || node.nodeType !== Node.TEXT_NODE) return;
const len = node.nodeValue.length;
const start = Math.max(0, Math.min(a.start, len));
const end = Math.max(start, Math.min(a.end, len));
if (end <= start) return;
highlightOneSegment(node, start, end, ann.color, ann.id);
});
});
renderGutter();
renderSidebarList();
};
// Remove annotations whose spans intersect a given range
const removeHighlightsInSelection = () => {
const sel = window.getSelection();
if (!sel || sel.isCollapsed || !sel.rangeCount) return;
const range = sel.getRangeAt(0);
const iter = document.createNodeIterator(
range.commonAncestorContainer,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: (node) => {
if (!(node instanceof Element)) return NodeFilter.FILTER_REJECT;
if (!node.classList || !node.classList.contains(HIGHLIGHT_CLASS)) return NodeFilter.FILTER_REJECT;
return range.intersectsNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
}
);
const idsToRemove = new Set();
let el;
while ((el = iter.nextNode())) {
const id = el.getAttribute('data-ann-id');
if (id) idsToRemove.add(id);
}
if (idsToRemove.size === 0) return;
idsToRemove.forEach(id => removeAnnotationById(id));
try { sel.removeAllRanges(); } catch {}
toast(`Removed ${idsToRemove.size} annotation(s).`);
};
const removeAnnotationById = (annId) => {
// Remove spans
const spans = Array.from(document.querySelectorAll(`.${HIGHLIGHT_CLASS}[data-ann-id="${annId}"]`));
spans.forEach(span => {
const parent = span.parentNode;
const text = document.createTextNode(span.textContent);
parent.replaceChild(text, span);
parent.normalize();
});
// Remove from storage
annotations = annotations.filter(a => a.id !== annId);
saveToLocal();
renderGutter();
renderSidebarList();
};
/** ---------- UI (Shadow DOM) ---------- */
const ensureHighlightStyle = () => {
if (styleElement) return;
styleElement = document.createElement('style');
styleElement.textContent = `
.${HIGHLIGHT_CLASS} {
background-color: var(--hl-color) !important;
padding: 0.1em 0.2em !important;
margin: -0.1em 0 !important;
border-radius: 2px !important;
display: inline !important;
box-decoration-break: clone !important;
-webkit-box-decoration-break: clone !important;
cursor: pointer !important;
}
`;
document.head.appendChild(styleElement);
};
const buildUI = () => {
if (uiHost) return;
uiHost = document.createElement('div');
uiHost.id = UI_ROOT_ID;
uiHost.style.position = 'fixed';
uiHost.style.top = '0';
uiHost.style.right = '0';
uiHost.style.zIndex = '2147483647'; // on top
uiHost.style.width = '0'; // no visual footprint
uiHost.style.height = '0';
document.body.appendChild(uiHost);
shadow = uiHost.attachShadow({ mode: 'open' });
const style = document.createElement('style');
style.textContent = `
:host { all: initial; }
*, *::before, *::after { box-sizing: border-box; font: inherit; }
.vh-toolbar {
position: fixed; top: 10px; right: ${GUTTER_WIDTH + 10}px;
display: flex; gap: 6px; padding: 8px;
background: #ffffff; border: 1px solid #dadde1; border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,.08);
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, "Helvetica Neue", Arial, "Noto Sans", "Apple Color Emoji", "Segoe UI Emoji";
color: #111;
}
.vh-btn {
appearance: none; border: 1px solid #c7c7c7; padding: 6px 10px; border-radius: 6px;
background: #f8f8f8; cursor: pointer; user-select: none; line-height: 1; white-space: nowrap;
}
.vh-btn:hover { filter: brightness(0.97); }
.vh-btn:active { transform: translateY(1px); }
.vh-color { width: 26px; height: 26px; border-radius: 50%; padding: 0; border: 2px solid #888; }
.vh-sep { width: 1px; background: #ddd; margin: 0 4px; }
.vh-gutter {
position: fixed; top: 0; right: 0; height: 100vh; width: ${GUTTER_WIDTH}px;
pointer-events: none; /* note cards enable pointer events individually */
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, "Helvetica Neue", Arial, "Noto Sans";
}
.vh-note-card {
position: absolute; right: 10px; max-width: ${GUTTER_WIDTH - 20}px; min-width: 180px;
background: #fff; border: 1px solid #e3e3e3; border-radius: 8px; padding: 8px 10px;
box-shadow: 0 2px 8px rgba(0,0,0,.07);
pointer-events: auto;
}
.vh-note-card .vh-meta { font-size: 11px; color: #666; margin-bottom: 6px; display:flex; gap:8px; align-items:center; }
.vh-dot { width: 10px; height: 10px; border-radius: 50%; display:inline-block; }
.vh-note-card .vh-body { font-size: 13px; white-space: pre-wrap; color: #222; }
.vh-note-card .vh-actions { margin-top: 6px; display:flex; gap:6px; }
.vh-note-card .vh-mini { font-size: 12px; padding: 4px 6px; }
.vh-modal-backdrop {
position: fixed; inset: 0; background: rgba(0,0,0,.25);
display: none; align-items: center; justify-content: center;
}
.vh-modal {
background: #fff; width: min(520px, 90vw); border: 1px solid #ddd; border-radius: 10px; padding: 14px;
box-shadow: 0 6px 22px rgba(0,0,0,.2);
}
.vh-modal h3 { margin: 0 0 8px 0; font-size: 16px; }
.vh-modal textarea {
width: 100%; min-height: 120px; border: 1px solid #ccc; border-radius: 8px; padding: 10px;
font-family: inherit; font-size: 14px; outline: none;
}
.vh-modal .vh-row { display: flex; gap: 8px; justify-content: flex-end; margin-top: 10px; }
.vh-modal .vh-btn { padding: 8px 12px; }
.vh-toasts { position: fixed; bottom: 16px; right: ${GUTTER_WIDTH + 16}px; display:flex; flex-direction:column; gap:8px; }
.vh-toast {
opacity: 0; transform: translateY(6px);
background: #111; color: #fff; padding: 8px 12px; border-radius: 8px; font-size: 12px;
}
.vh-toast.show { opacity: 1; transform: translateY(0); transition: all .18s ease; }
.vh-list {
position: fixed; bottom: 10px; right: ${GUTTER_WIDTH + 10}px;
background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:8px; max-width: 340px;
max-height: 36vh; overflow:auto; display:none; gap:6px; flex-direction:column;
}
.vh-list-item { font-size: 13px; display:flex; gap:6px; align-items:flex-start; border-bottom:1px dashed #eee; padding-bottom:6px; }
.vh-list-item:last-child { border-bottom:0; padding-bottom:0; }
.vh-list .vh-note-text { color:#222; white-space:pre-wrap; }
.vh-link { color:#0d6efd; cursor:pointer; text-decoration: underline; }
`;
shadow.appendChild(style);
// Toolbar
toolbarEl = document.createElement('div');
toolbarEl.className = 'vh-toolbar';
toolbarEl.innerHTML = `
<button class="vh-btn vh-color" data-color="yellow" title="Highlight yellow" style="background:${COLOR_STYLES.yellow}"></button>
<button class="vh-btn vh-color" data-color="green" title="Highlight green" style="background:${COLOR_STYLES.green}"></button>
<button class="vh-btn vh-color" data-color="red" title="Highlight red" style="background:${COLOR_STYLES.red}"></button>
<div class="vh-sep"></div>
<button class="vh-btn" data-action="note">Note</button>
<button class="vh-btn" data-action="remove">Remove</button>
<div class="vh-sep"></div>
<button class="vh-btn" data-action="export">Export</button>
<button class="vh-btn" data-action="import">Import</button>
<div class="vh-sep"></div>
<button class="vh-btn" data-action="list">Notes</button>
<button class="vh-btn" data-action="close" title="Deactivate (Ctrl+Shift+C)">✕</button>
`;
shadow.appendChild(toolbarEl);
// Gutter (margin comments)
gutterEl = document.createElement('div');
gutterEl.className = 'vh-gutter';
shadow.appendChild(gutterEl);
// Notes list popup
const listEl = document.createElement('div');
listEl.className = 'vh-list';
listEl.setAttribute('id', 'vh-list');
shadow.appendChild(listEl);
// Modal (note editor)
const backdrop = document.createElement('div');
backdrop.className = 'vh-modal-backdrop';
backdrop.innerHTML = `
<div class="vh-modal">
<h3 id="vh-modal-title">Add note</h3>
<textarea id="vh-note-text" placeholder="Write your note..."></textarea>
<div class="vh-row">
<button class="vh-btn" data-modal="cancel">Cancel</button>
<button class="vh-btn" data-modal="save">Save</button>
</div>
</div>
`;
modalEl = backdrop;
shadow.appendChild(backdrop);
// Toasts
toastsEl = document.createElement('div');
toastsEl.className = 'vh-toasts';
shadow.appendChild(toastsEl);
// Hidden import input
importInputEl = document.createElement('input');
importInputEl.type = 'file';
importInputEl.accept = 'application/json';
importInputEl.style.display = 'none';
shadow.appendChild(importInputEl);
// Toolbar events
toolbarEl.addEventListener('click', async (e) => {
const t = e.target;
if (!(t instanceof Element)) return;
if (t.matches('.vh-color')) {
currentColor = t.getAttribute('data-color') || currentColor;
await createAnnotationFromSelection({ color: currentColor, note: '' });
} else if (t.matches('[data-action="note"]')) {
const range = normalizeSelection();
if (!range) { toast('Select text first.'); return; }
openNoteEditor({
title: 'Add note',
initial: '',
onSave: async (text) => {
await createAnnotationFromSelection({ color: currentColor, note: text.trim() });
}
});
} else if (t.matches('[data-action="remove"]')) {
removeHighlightsInSelection();
} else if (t.matches('[data-action="export"]')) {
doExport();
} else if (t.matches('[data-action="import"]')) {
importInputEl.click();
} else if (t.matches('[data-action="list"]')) {
const list = shadow.getElementById('vh-list');
list.style.display = (list.style.display === 'none' || !list.style.display) ? 'flex' : 'none';
renderSidebarList();
} else if (t.matches('[data-action="close"]')) {
toggleActive(false);
}
});
// Import handler
importInputEl.addEventListener('change', async () => {
const file = importInputEl.files && importInputEl.files[0];
importInputEl.value = '';
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
let incoming = Array.isArray(data) ? data : (data.annotations || []);
if (!Array.isArray(incoming)) throw new Error('Invalid file');
let added = 0;
incoming.forEach(obj => {
// Shallow validation
if (!obj || !Array.isArray(obj.anchors) || !obj.anchors.length) return;
const copy = {
id: uid(), // avoid id collisions across pages
color: obj.color && (COLOR_STYLES[obj.color] || /^#|rgb/.test(obj.color)) ? obj.color : 'yellow',
anchors: obj.anchors.filter(a => a && typeof a.xpath === 'string' && typeof a.start === 'number' && typeof a.end === 'number'),
note: obj.note || '',
createdAt: obj.createdAt || Date.now()
};
if (!copy.anchors.length) return;
annotations.push(copy);
added++;
});
saveToLocal();
restoreAnnotations();
toast(`Imported ${added} annotation(s).`);
} catch (err) {
console.error('[Vard Highlighter] Import failed', err);
toast('⚠️ Import failed.');
}
});
// Modal handlers
modalEl.addEventListener('click', (e) => {
const t = e.target;
if (!(t instanceof Element)) return;
if (t === modalEl) closeNoteEditor();
if (t.matches('[data-modal="cancel"]')) closeNoteEditor();
if (t.matches('[data-modal="save"]')) {
const textarea = shadow.getElementById('vh-note-text');
modalEl.__onSave && modalEl.__onSave(textarea.value || '');
closeNoteEditor();
}
});
// Click on highlight and edit note (if any)
document.addEventListener('click', (evt) => {
if (!isActive) return;
// Ignore clicks inside the UI shadow tree
const path = evt.composedPath ? evt.composedPath() : [];
if (path.includes(shadow)) return;
const target = evt.target;
if (!(target instanceof Element)) return;
const span = target.closest('.' + HIGHLIGHT_CLASS);
if (!span) return;
const id = span.getAttribute('data-ann-id');
const ann = annotations.find(a => a.id === id);
if (!ann) return;
openNoteEditor({
title: 'Edit note',
initial: ann.note || '',
onSave: (text) => {
ann.note = (text || '').trim();
saveToLocal();
renderGutter();
renderSidebarList();
},
extraActions: [
{ label: 'Delete', onClick: () => removeAnnotationById(ann.id) }
]
});
}, true);
// Reposition gutter notes on scroll / resize
window.addEventListener('scroll', throttled(renderGutter, 60), { passive: true });
window.addEventListener('resize', throttled(renderGutter, 60));
};
const openNoteEditor = ({ title, initial, onSave, extraActions = [] }) => {
const titleEl = modalEl.querySelector('#vh-modal-title');
const textarea = modalEl.querySelector('#vh-note-text');
titleEl.textContent = title || 'Note';
textarea.value = initial || '';
modalEl.style.display = 'flex';
modalEl.__onSave = onSave;
// Add extra actions as needed
const btnRow = modalEl.querySelector('.vh-row');
// Remove existing extra buttons except Save/Cancel
btnRow.querySelectorAll('[data-extra]').forEach(el => el.remove());
extraActions.forEach(action => {
const b = document.createElement('button');
b.className = 'vh-btn';
b.textContent = action.label;
b.setAttribute('data-extra', '1');
b.addEventListener('click', () => {
action.onClick && action.onClick();
closeNoteEditor();
}, { once: true });
btnRow.insertBefore(b, btnRow.firstChild);
});
setTimeout(() => textarea.focus(), 0);
};
const closeNoteEditor = () => {
modalEl.style.display = 'none';
modalEl.__onSave = null;
};
const throttled = (fn, wait) => {
let last = 0, timer = null;
return (...args) => {
const now = Date.now();
if (now - last >= wait) {
last = now; fn(...args);
} else {
clearTimeout(timer);
timer = setTimeout(() => { last = Date.now(); fn(...args); }, wait - (now - last));
}
};
};
// Build sidebar list (compact)
const renderSidebarList = () => {
const list = shadow && shadow.getElementById('vh-list');
if (!list) return;
list.innerHTML = '';
const withNotes = annotations.filter(a => (a.note || '').trim().length > 0)
.sort((a, b) => a.createdAt - b.createdAt);
if (!withNotes.length) {
const empty = document.createElement('div');
empty.style.fontSize = '12px';
empty.style.color = '#666';
empty.textContent = 'No notes yet.';
list.appendChild(empty);
return;
}
withNotes.forEach(a => {
const item = document.createElement('div');
item.className = 'vh-list-item';
const dot = document.createElement('span');
dot.className = 'vh-dot'; dot.style.background = COLOR_STYLES[a.color] || a.color;
const text = document.createElement('div');
text.className = 'vh-note-text';
text.textContent = a.note;
const jump = document.createElement('span');
jump.className = 'vh-link';
jump.textContent = 'Jump';
jump.addEventListener('click', () => scrollToAnnotation(a.id));
item.appendChild(dot);
item.appendChild(text);
item.appendChild(jump);
list.appendChild(item);
});
};
// Margin gutter renderer — align note cards to top of first rect of their highlight spans
const renderGutter = () => {
if (!gutterEl) return;
gutterEl.innerHTML = '';
const notes = annotations.filter(a => (a.note || '').trim().length > 0);
if (!notes.length) return;
// Compute positions relative to viewport (top in px)
const cards = [];
notes.forEach(a => {
const spans = Array.from(document.querySelectorAll(`.${HIGHLIGHT_CLASS}[data-ann-id="${a.id}"]`));
if (!spans.length) return;
// Use first visible rect
let rect = null;
for (const s of spans) {
const r = s.getBoundingClientRect();
if (r.width > 0 && r.height > 0) { rect = r; break; }
}
if (!rect) rect = spans[0].getBoundingClientRect();
const top = Math.max(8, rect.top + window.scrollY - window.scrollY); // viewport top
cards.push({ ann: a, top });
});
// Prevent overlap by stacking with minimal spacing
cards.sort((a,b) => a.top - b.top);
const minGap = 10;
for (let i=1;i<cards.length;i++){
if (cards[i].top - cards[i-1].top < 80) {
cards[i].top = cards[i-1].top + 80 + minGap;
}
}
// Render
cards.forEach(({ ann, top }) => {
const card = document.createElement('div');
card.className = 'vh-note-card';
card.style.top = `${top}px`;
card.innerHTML = `
<div class="vh-meta">
<span class="vh-dot" style="background:${COLOR_STYLES[ann.color] || ann.color}"></span>
<span>${new Date(ann.createdAt).toLocaleString()}</span>
</div>
<div class="vh-body">${escapeHtml(ann.note).replace(/\n/g,'<br>')}</div>
<div class="vh-actions">
<button class="vh-btn vh-mini" data-act="jump">Jump</button>
<button class="vh-btn vh-mini" data-act="edit">Edit</button>
<button class="vh-btn vh-mini" data-act="del">Delete</button>
</div>
`;
card.querySelector('[data-act="jump"]').addEventListener('click', () => scrollToAnnotation(ann.id));
card.querySelector('[data-act="edit"]').addEventListener('click', () => {
openNoteEditor({
title: 'Edit note',
initial: ann.note || '',
onSave: (txt) => { ann.note = (txt||'').trim(); saveToLocal(); renderGutter(); renderSidebarList(); }
});
});
card.querySelector('[data-act="del"]').addEventListener('click', () => removeAnnotationById(ann.id));
gutterEl.appendChild(card);
});
};
const escapeHtml = (s) => (s || '').replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));
const scrollToAnnotation = (annId) => {
const spans = Array.from(document.querySelectorAll(`.${HIGHLIGHT_CLASS}[data-ann-id="${annId}"]`));
if (!spans.length) return;
const target = spans[0];
const r = target.getBoundingClientRect();
const y = r.top + window.scrollY - 80;
window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
// brief flash
target.style.transition = 'box-shadow .3s';
target.style.boxShadow = '0 0 0 3px rgba(13,110,253,.45)';
setTimeout(() => { target.style.boxShadow = 'none'; }, 800);
};
/** ---------- Export / Import ---------- */
const doExport = () => {
const payload = {
meta: {
version: FILE_VERSION,
url: location.href.split('#')[0],
title: document.title,
exportedAt: new Date().toISOString()
},
annotations
};
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
const safeTitle = (document.title || location.hostname).replace(/[^\w\s-]+/g, '').slice(0,60).trim().replace(/\s+/g,'_');
a.href = url;
a.download = `annotations_${safeTitle}.json`;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 0);
toast('Exported annotations.');
};
/** ---------- Activation lifecycle ---------- */
const initialize = () => {
ensureHighlightStyle();
buildUI();
annotations = loadFromLocal();
restoreAnnotations();
};
const deactivate = () => {
// Remove UI but keep highlight spans unstyled
if (uiHost) {
uiHost.remove();
uiHost = null; shadow = null; toolbarEl = null; gutterEl = null; modalEl = null; toastsEl = null; importInputEl = null;
}
if (styleElement) { styleElement.remove(); styleElement = null; }
};
const toggleActive = (forceState = null) => {
const next = (forceState === null) ? !isActive : !!forceState;
isActive = next;
if (isActive) initialize();
else deactivate();
};
const onKeyDown = (e) => {
if (e.key.toLowerCase() !== KEYBOARD_SHORTCUT.key.toLowerCase()) return;
if (!!e.ctrlKey !== KEYBOARD_SHORTCUT.ctrlKey) return;
if (!!e.shiftKey !== KEYBOARD_SHORTCUT.shiftKey) return;
if (!!e.altKey !== KEYBOARD_SHORTCUT.altKey) return;
if (!!e.metaKey !== KEYBOARD_SHORTCUT.metaKey) return;
e.preventDefault();
e.stopPropagation();
toggleActive();
};
document.addEventListener('keydown', onKeyDown);
// auto-activate by default
// toggleActive(true);
})();