single-file-core 1.11.0 → 1.12.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.
package/core/constants.js CHANGED
@@ -4,6 +4,7 @@ const SINGLE_FILE_SIGNATURE = "SingleFile";
4
4
  const WAIT_FOR_USERSCRIPT_PROPERTY_NAME = "_singleFile_waitForUserScript";
5
5
  const MESSAGE_PREFIX = "__frameTree__::";
6
6
  const NO_SCRIPT_PROPERTY_NAME = "singleFileDisabledNoscript";
7
+ const NESTING_TRACK_ID_ATTRIBUTE_NAME = "data-sf-nesting-track-id";
7
8
 
8
9
  export {
9
10
  SINGLE_FILE_PREFIX,
@@ -11,5 +12,6 @@ export {
11
12
  SINGLE_FILE_SIGNATURE,
12
13
  WAIT_FOR_USERSCRIPT_PROPERTY_NAME,
13
14
  MESSAGE_PREFIX,
14
- NO_SCRIPT_PROPERTY_NAME
15
+ NO_SCRIPT_PROPERTY_NAME,
16
+ NESTING_TRACK_ID_ATTRIBUTE_NAME
15
17
  };
package/core/helper.js CHANGED
@@ -31,7 +31,8 @@ import {
31
31
  COMMENT_HEADER,
32
32
  WAIT_FOR_USERSCRIPT_PROPERTY_NAME,
33
33
  MESSAGE_PREFIX,
34
- NO_SCRIPT_PROPERTY_NAME
34
+ NO_SCRIPT_PROPERTY_NAME,
35
+ NESTING_TRACK_ID_ATTRIBUTE_NAME
35
36
  } from "./constants.js";
36
37
  import {
37
38
  getValidFilename,
@@ -135,7 +136,6 @@ const INFOBAR_TAGNAME = infobar.INFOBAR_TAGNAME;
135
136
  const EMPTY_RESOURCE = "data:,";
136
137
  const POSTER_CONTENT_TYPES = ["image/webp", "image/jpeg"];
137
138
  const POSTER_QUALITY = 0.8;
138
- const NESTING_TRACK_ID_ATTRIBUTE_NAME = "data-sf-nesting-track-id";
139
139
  const NESTING_START_MARKER = NESTING_TRACK_ID_ATTRIBUTE_NAME + "-start ";
140
140
  const NESTING_END_MARKER = NESTING_TRACK_ID_ATTRIBUTE_NAME + "-end ";
141
141
  const NESTING_RECREATED_ATTRIBUTE_NAME = NESTING_TRACK_ID_ATTRIBUTE_NAME + "-recreated";
package/core/index.js CHANGED
@@ -126,6 +126,7 @@ const STAGES = [{
126
126
  { option: "removeHiddenElements", action: "removeHiddenElements" },
127
127
  { action: "saveScrollPosition" },
128
128
  { action: "resolveHrefs" },
129
+ { option: "removeLinkQueryStrings", action: "removeLinkQueryStrings" },
129
130
  { action: "resolveStyleAttributeURLs" }
130
131
  ],
131
132
  parallel: [
@@ -1469,6 +1470,16 @@ class Processor {
1469
1470
  }));
1470
1471
  }
1471
1472
 
1473
+ removeLinkQueryStrings() {
1474
+ this.doc.querySelectorAll("a[href*=\"?\"], area[href*=\"?\"]").forEach(element => {
1475
+ const href = element.getAttribute("href").trim();
1476
+ const scheme = href.match(/^([a-z][a-z0-9+.-]*):/i);
1477
+ if (!scheme || HTTP_SCHEMES.includes(scheme[1].toLowerCase())) {
1478
+ element.setAttribute("href", href.replace(/\?[^#]*/, ""));
1479
+ }
1480
+ });
1481
+ }
1482
+
1472
1483
  resolveStyleAttributeURLs() {
1473
1484
  this.doc.querySelectorAll("[style]").forEach(element => {
1474
1485
  if (this.options.blockStylesheets) {
@@ -1992,6 +2003,7 @@ class Processor {
1992
2003
  // ----
1993
2004
  const DATA_URI_PREFIX = "data:";
1994
2005
  const ABOUT_BLANK_URI = "about:blank";
2006
+ const HTTP_SCHEMES = ["http", "https"];
1995
2007
  const BLOB_URI_PREFIX = "blob:";
1996
2008
  const HTTP_URI_PREFIX = /^https?:\/\//;
1997
2009
  const FILE_URI_PREFIX = /^file:\/\//;
@@ -434,6 +434,8 @@ class ProcessorHelperCommon {
434
434
 
435
435
  async removeAlternativeFonts(doc, stylesheets, fonts, fontTests) {
436
436
  const fontsDetails = this.createFontsDetailsInfo();
437
+ // Share parsing across sheets, but release embedded payloads when this pass finishes.
438
+ const sourceLists = new Map();
437
439
  const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
438
440
  const ruleScopes = new Map();
439
441
  getStylesheetsInCascadeOrder(stylesheets).forEach(({ stylesheetInfo, index: sheetIndex }) => {
@@ -448,9 +450,9 @@ class ProcessorHelperCommon {
448
450
  if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
449
451
  const mediaFontsDetails = this.createFontsDetailsInfo();
450
452
  fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
451
- this.getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
453
+ this.getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails, sourceLists);
452
454
  } else {
453
- this.getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
455
+ this.getFontsDetails(doc, cssRules, sheetIndex, fontsDetails, sourceLists);
454
456
  }
455
457
  }
456
458
  }
@@ -481,12 +483,20 @@ class ProcessorHelperCommon {
481
483
  if (scope && !scopeIds.has(scope)) {
482
484
  scopeIds.set(scope, scopeIds.size + 1);
483
485
  }
484
- const ruleKey = (scope ? scopeIds.get(scope) : 0) + " " + this.getFontKey(ruleData) + " " + this.getPropertyValue(ruleData, "src");
485
- const previousRuleData = lastRules.get(ruleKey);
486
+ // Keep large source strings out of compound keys without weakening exact-source equality.
487
+ const ruleKey = (scope ? scopeIds.get(scope) : 0) + " " + this.getFontKey(ruleData);
488
+ let sourceRules = lastRules.get(ruleKey);
489
+ if (!sourceRules) {
490
+ sourceRules = new Map();
491
+ lastRules.set(ruleKey, sourceRules);
492
+ }
493
+ // Preserve the old concatenated key's coercion, including an absent src.
494
+ const sourceKey = String(this.getPropertyValue(ruleData, "src"));
495
+ const previousRuleData = sourceRules.get(sourceKey);
486
496
  if (previousRuleData) {
487
497
  fontsDetails.repeatedFonts.add(previousRuleData);
488
498
  }
489
- lastRules.set(ruleKey, ruleData);
499
+ sourceRules.set(sourceKey, ruleData);
490
500
  });
491
501
  fontsDetails.medias.forEach(mediaFontsDetails => this.markRepeatedFontFaceRules(mediaFontsDetails, ruleScopes, scopeIds));
492
502
  fontsDetails.supports.forEach(supportsFontsDetails => this.markRepeatedFontFaceRules(supportsFontsDetails, ruleScopes, scopeIds));
@@ -535,7 +545,7 @@ class ProcessorHelperCommon {
535
545
  groupDuplicateImages() {
536
546
  }
537
547
 
538
- getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
548
+ getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails, sourceLists = new Map()) {
539
549
  let mediaIndex = 0, supportsIndex = 0, layerIndex = 0;
540
550
  cssRules.forEach(ruleData => {
541
551
  if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
@@ -543,35 +553,44 @@ class ProcessorHelperCommon {
543
553
  const fontsDetails = this.createFontsDetailsInfo();
544
554
  mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
545
555
  mediaIndex++;
546
- this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
556
+ this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails, sourceLists);
547
557
  } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
548
558
  const supportsText = cssTree.generate(ruleData.prelude);
549
559
  const fontsDetails = this.createFontsDetailsInfo();
550
560
  mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
551
561
  supportsIndex++;
552
- this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
562
+ this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails, sourceLists);
553
563
  } else if (ruleData.type == "Atrule" && ruleData.name == "layer" && ruleData.block && ruleData.block.children && ruleData.prelude) {
554
564
  const layerText = cssTree.generate(ruleData.prelude);
555
565
  const fontsDetails = this.createFontsDetailsInfo();
556
566
  mediaFontsDetails.layers.set("layer-" + sheetIndex + "-" + layerIndex + "-" + layerText, fontsDetails);
557
567
  layerIndex++;
558
- this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
568
+ this.getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails, sourceLists);
559
569
  } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
560
- const fontInfo = [];
561
- mediaFontsDetails.fonts.set(ruleData, fontInfo);
562
570
  const src = this.getPropertyValue(ruleData, "src");
563
- if (src) {
564
- const fontSources = src.match(REGEXP_URL_FUNCTION);
565
- if (fontSources) {
566
- fontSources.forEach(fontSource => {
567
- const source = fontSource.match(REGEXP_FONT_SRC)[1];
568
- if (fontInfo.includes(source)) {
569
- fontInfo.splice(fontInfo.indexOf(source), 1);
570
- }
571
- fontInfo.unshift(source);
572
- });
571
+ // Reuse the source list for this exact src text; otherwise split its url()/local()
572
+ // entries once, so repeated faces do not reparse the same embedded font payload.
573
+ let fontInfo = sourceLists.get(src);
574
+ if (!fontInfo) {
575
+ fontInfo = [];
576
+ if (src) {
577
+ const fontSources = src.match(REGEXP_URL_FUNCTION);
578
+ if (fontSources) {
579
+ fontSources.forEach(fontSource => {
580
+ const source = fontSource.match(REGEXP_FONT_SRC)[1];
581
+ // Keep the last occurrence of each source, in reverse CSS order,
582
+ // matching the later selector's backwards scan and final reversal.
583
+ if (fontInfo.includes(source)) {
584
+ fontInfo.splice(fontInfo.indexOf(source), 1);
585
+ }
586
+ fontInfo.unshift(source);
587
+ });
588
+ }
573
589
  }
590
+ sourceLists.set(src, fontInfo);
574
591
  }
592
+ // Selection reverses and edits these lists; rules must not mutate the cached list.
593
+ mediaFontsDetails.fonts.set(ruleData, fontInfo.slice());
575
594
  }
576
595
  });
577
596
  }
@@ -629,31 +648,35 @@ class ProcessorHelperCommon {
629
648
  }
630
649
 
631
650
  getPropertyValue(ruleData, propertyName) {
632
- let property;
651
+ let value;
633
652
  if (ruleData.block.children) {
634
- property = ruleData.block.children.filter(node => {
635
- try {
636
- return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
637
- // eslint-disable-next-line no-unused-vars
638
- } catch (error) {
639
- return node.property == propertyName;
653
+ ruleData.block.children.forEach(node => {
654
+ if (node.property == propertyName) {
655
+ try {
656
+ // Reuse the IE-hack check's serialization: src can contain megabytes of font data.
657
+ const generated = cssTree.generate(node.value);
658
+ if (!generated.match(/\\9$/)) {
659
+ value = generated;
660
+ }
661
+ } catch {
662
+ // A broken last declaration still overrides earlier ones, as before.
663
+ value = undefined;
664
+ }
640
665
  }
641
- }).tail;
642
- }
643
- if (property) {
644
- try {
645
- return cssTree.generate(property.data.value);
646
- // eslint-disable-next-line no-unused-vars
647
- } catch (error) {
648
- // ignored
649
- }
666
+ });
650
667
  }
668
+ return value;
651
669
  }
652
670
  }
653
671
 
654
- function processFontDetails(fontsDetails, fontResources) {
672
+ // Resource metadata belongs to this capture; cached records never carry a rule's mutable valid flag.
673
+ function processFontDetails(fontsDetails, fontResources, sourceDetails = new Map()) {
655
674
  fontsDetails.fonts.forEach((fontInfo, fontKey) => {
656
675
  fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
676
+ // Clone on both paths so one rule's fallback result cannot affect another rule.
677
+ if (sourceDetails.has(fontSource)) {
678
+ return { ...sourceDetails.get(fontSource) };
679
+ }
657
680
  const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
658
681
  const fontTechMatch = fontSource.match(REGEXP_FONT_TECH_VALUE);
659
682
  let fontFormat, fontTech;
@@ -686,22 +709,25 @@ function processFontDetails(fontsDetails, fontResources) {
686
709
  fontFormat = fontFormatMatch[1];
687
710
  }
688
711
  }
712
+ let sourceInfo;
689
713
  if (fontResources) {
690
714
  const fontResource = Array.from(fontResources.values()).find(info => info.name == fontUrl);
691
- return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat, tech: fontTech, contentType: fontResource && fontResource.contentType };
715
+ sourceInfo = { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat, tech: fontTech, contentType: fontResource && fontResource.contentType };
692
716
  } else {
693
- return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat, tech: fontTech };
717
+ sourceInfo = { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat, tech: fontTech };
694
718
  }
719
+ sourceDetails.set(fontSource, sourceInfo);
720
+ return { ...sourceInfo };
695
721
  }));
696
722
  });
697
723
  if (fontResources) {
698
- fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails, fontResources));
699
- fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails, fontResources));
700
- fontsDetails.layers.forEach(layerFontsDetails => processFontDetails(layerFontsDetails, fontResources));
724
+ fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails, fontResources, sourceDetails));
725
+ fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails, fontResources, sourceDetails));
726
+ fontsDetails.layers.forEach(layerFontsDetails => processFontDetails(layerFontsDetails, fontResources, sourceDetails));
701
727
  } else {
702
- fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
703
- fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
704
- fontsDetails.layers.forEach(layerFontsDetails => processFontDetails(layerFontsDetails));
728
+ fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails, undefined, sourceDetails));
729
+ fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails, undefined, sourceDetails));
730
+ fontsDetails.layers.forEach(layerFontsDetails => processFontDetails(layerFontsDetails, undefined, sourceDetails));
705
731
  }
706
732
  }
707
733
 
package/core/notes.js ADDED
@@ -0,0 +1,943 @@
1
+ /*
2
+ * Copyright 2010-2025 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ import { NESTING_TRACK_ID_ATTRIBUTE_NAME } from "./constants.js";
25
+
26
+ const NOTE_TAGNAME = "single-file-note";
27
+ const NOTE_CLASS = "note";
28
+ const NOTE_MASK_CLASS = "note-mask";
29
+ const NOTE_HIDDEN_CLASS = "note-hidden";
30
+ const NOTE_ANCHORED_CLASS = "note-anchored";
31
+ const NOTE_SELECTED_CLASS = "note-selected";
32
+ const NOTE_MOVING_CLASS = "note-moving";
33
+ const NOTE_COLLAPSED_CLASS = "note-collapsed";
34
+ const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
35
+ const NOTE_RESIZE_CLASS = "note-resize";
36
+ const NOTE_REMOVE_CLASS = "note-remove";
37
+ const NOTE_ANCHOR_CLASS = "note-anchor";
38
+ const NOTE_REFS_ATTRIBUTE_NAME = "data-single-file-note-refs";
39
+ const PAGE_MASK_CLASS = "page-mask";
40
+ const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
41
+ const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
42
+ const MASK_CLASS = "single-file-mask";
43
+ const HIGHLIGHT_CLASS = "single-file-highlight";
44
+ const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
45
+ const HIGHLIGHTS_STYLESHEET_CLASS = "single-file-highlights-stylesheet";
46
+ const REMOVED_CONTENT_CLASS = "single-file-removed";
47
+ const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
48
+ const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
49
+ const NOTE_SELECTOR_URL_PREFIX = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[" + NOTE_REFS_ATTRIBUTE_NAME + "~=\"";
50
+ const NOTE_SELECTOR_URL_SUFFIX = "\"])";
51
+ const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
52
+ const NOTE_INITIAL_POSITION_X = 20;
53
+ const NOTE_INITIAL_POSITION_Y = 20;
54
+ const NOTE_INITIAL_WIDTH = 150;
55
+ const NOTE_INITIAL_HEIGHT = 150;
56
+ const NOTE_HEADER_HEIGHT = 25;
57
+ const SELECT_PX_THRESHOLD = 4;
58
+ const COLLAPSING_NOTE_DELAY = 750;
59
+ const RESOURCES_LOAD_DELAY = 100;
60
+ const RESOURCES_LOAD_MAX_MUTATIONS = 20;
61
+ const BUTTON_ANCHOR_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAgMAAAAOFJJnAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVETuIOASsThZERRylikWwUNoKrTqYXPohNGlIUlwcBdeCgx+LVQcXZ10dXAVB8APEydFJ0UVK/F9SaBHjwXE/3t173L0DhFqJqWbbOKBqlpGMRcVMdkUMvKIbfQCG0SExU4+nFtLwHF/38PH1LsKzvM/9OXqUnMkAn0g8y3TDIl4nnt60dM77xCFWlBTic+Ixgy5I/Mh12eU3zgWHBZ4ZMtLJOeIQsVhoYbmFWdFQiaeIw4qqUb6QcVnhvMVZLVVY4578hcGctpziOs0hxLCIOBIQIaOCDZRgIUKrRoqJJO1HPfyDjj9BLplcG2DkmEcZKiTHD/4Hv7s185MTblIwCrS/2PbHCBDYBepV2/4+tu36CeB/Bq60pr9cA2Y+Sa82tfAR0LsNXFw3NXkPuNwBBp50yZAcyU9TyOeB9zP6pizQfwt0rbq9NfZx+gCkqaulG+DgEBgtUPaax7s7W3v790yjvx825XKP2aKCdAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+QLEQA4M3Y7LzIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAACVBMVEUAAAAAAACKioqjwG1pAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAABkSURBVBjThc47CsNADIThWfD0bnSfbdIroP/+V0mhsN5gTNToK0YPaSvnF9B9wGykG54j/2GF1/hauE4E1AOuNxrBdA5KUXIqdiCnqC1zIZ2mFJQzKJ3wesOhcwDM4+fo7cOuD9C4HTQ9HAAQAAAAAElFTkSuQmCC";
62
+ const BUTTON_CLOSE_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAgMAAAAOFJJnAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TtaIVETuIOASsThZERRylikWwUNoKrTqYXPohNGlIUlwcBdeCgx+LVQcXZ10dXAVB8APEydFJ0UVK/F9SaBHjwXE/3t173L0DhFqJqWbbOKBqlpGMRcVMdkUMvKIbfQCG0SExU4+nFtLwHF/38PH1LsKzvM/9OXqUnMkAn0g8y3TDIl4nnt60dM77xCFWlBTic+Ixgy5I/Mh12eU3zgWHBZ4ZMtLJOeIQsVhoYbmFWdFQiaeIw4qqUb6QcVnhvMVZLVVY4578hcGctpziOs0hxLCIOBIQIaOCDZRgIUKrRoqJJO1HPfyDjj9BLplcG2DkmEcZKiTHD/4Hv7s185MTblIwCrS/2PbHCBDYBepV2/4+tu36CeB/Bq60pr9cA2Y+Sa82tfAR0LsNXFw3NXkPuNwBBp50yZAcyU9TyOeB9zP6pizQfwt0rbq9NfZx+gCkqaulG+DgEBgtUPaax7s7W3v790yjvx825XKP2aKCdAAAAAlwSFlzAAAuIwAALiMBeKU/dgAAAAd0SU1FB+QLEQA6Na1u6IUAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAACVBMVEUAAAAAAACKioqjwG1pAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAABlSURBVBhXTc/BEUQhCAPQ58ES6McSPED/rfwDI7vOMCoJIeGd6CvFgZXiwk47Ia5VUKdrVXcb39kfqxqmTg+I2xJ2tqhVTaGaQjTl7/GgIc/4CL4Vs3RsjLFndcxPnAn4iww8A3yQjRZjti1t6AAAAABJRU5ErkJggg==";
63
+ const NOTES_STYLESHEET = minifyText(`
64
+ .note {
65
+ all: initial;
66
+ display: flex;
67
+ flex-direction: column;
68
+ height: 150px;
69
+ width: 150px;
70
+ position: absolute;
71
+ top: 10px;
72
+ left: 10px;
73
+ border: 1px solid rgb(191, 191, 191);
74
+ z-index: 2147483646;
75
+ box-shadow: 3px 3px 3px rgba(33, 33, 33, .7);
76
+ min-height: 100px;
77
+ min-width: 100px;
78
+ }
79
+
80
+ .note-selected {
81
+ z-index: 2147483647;
82
+ }
83
+
84
+ .note-hidden {
85
+ display: none;
86
+ }
87
+
88
+ .note-collapsed {
89
+ min-height: 30px;
90
+ max-height: 30px;
91
+ overflow: hidden;
92
+ }
93
+
94
+ .note blockquote {
95
+ all: initial;
96
+ padding: 1px;
97
+ height: 100%;
98
+ }
99
+
100
+ .note textarea {
101
+ all: initial;
102
+ white-space: break-spaces;
103
+ font-family: Arial, Helvetica, sans-serif;
104
+ font-size: 14px;
105
+ height: 100%;
106
+ width: 100%;
107
+ padding: 2px;
108
+ border: 1px solid transparent;
109
+ resize: none;
110
+ color: black;
111
+ }
112
+
113
+ .note textarea:focus {
114
+ border: 1px dotted rgb(160, 160, 160);
115
+ }
116
+
117
+ .note header {
118
+ all: initial;
119
+ min-height: 30px;
120
+ cursor: grab;
121
+ user-select: none;
122
+ }
123
+
124
+ .note .note-remove {
125
+ all: initial;
126
+ position: absolute;
127
+ right: 0px;
128
+ top: 2px;
129
+ padding: 5px;
130
+ opacity: .5;
131
+ cursor: pointer;
132
+ user-select: none;
133
+ width: 16px;
134
+ height: 16px;
135
+ }
136
+
137
+ .note .note-anchor {
138
+ all: initial;
139
+ position: absolute;
140
+ left: 0px;
141
+ top: 2px;
142
+ padding: 5px;
143
+ opacity: .25;
144
+ cursor: pointer;
145
+ width: 16px;
146
+ height: 16px;
147
+ }
148
+
149
+ .note .note-resize {
150
+ all: initial;
151
+ position: absolute;
152
+ bottom: -5px;
153
+ right: -5px;
154
+ height: 15px;
155
+ width: 15px;
156
+ cursor: nwse-resize;
157
+ user-select: none;
158
+ }
159
+
160
+ .note .note-remove:hover {
161
+ opacity: 1;
162
+ }
163
+
164
+ .note .note-anchor:hover {
165
+ opacity: .5;
166
+ }
167
+
168
+ .note-anchored .note-anchor {
169
+ opacity: .5;
170
+ }
171
+
172
+ .note-anchored .note-anchor:hover {
173
+ opacity: 1;
174
+ }
175
+
176
+ .note-moving {
177
+ opacity: .75;
178
+ box-shadow: 6px 6px 3px rgba(33, 33, 33, .7);
179
+ }
180
+
181
+ .note-moving * {
182
+ cursor: grabbing;
183
+ }
184
+
185
+ .note-yellow header {
186
+ background-color: #f5f545;
187
+ }
188
+
189
+ .note-yellow blockquote {
190
+ background-color: #ffff7c;
191
+ }
192
+
193
+ .note-pink header {
194
+ background-color: #ffa59f;
195
+ }
196
+
197
+ .note-pink blockquote {
198
+ background-color: #ffbbb6;
199
+ }
200
+
201
+ .note-blue header {
202
+ background-color: #84c8ff;
203
+ }
204
+
205
+ .note-blue blockquote {
206
+ background-color: #95d0ff;
207
+ }
208
+
209
+ .note-green header {
210
+ background-color: #93ef8d;
211
+ }
212
+
213
+ .note-green blockquote {
214
+ background-color: #9cff95;
215
+ }
216
+ `);
217
+ const MASK_STYLESHEET = minifyText(`
218
+ .note-mask {
219
+ all: initial;
220
+ position: fixed;
221
+ z-index: 2147483645;
222
+ pointer-events: none;
223
+ background-color: transparent;
224
+ transition: background-color 125ms;
225
+ }
226
+
227
+ .note-mask-moving.note-yellow {
228
+ background-color: rgba(255, 255, 124, .3);
229
+ }
230
+
231
+ .note-mask-moving.note-pink {
232
+ background-color: rgba(255, 187, 182, .3);
233
+ }
234
+
235
+ .note-mask-moving.note-blue {
236
+ background-color: rgba(149, 208, 255, .3);
237
+ }
238
+
239
+ .note-mask-moving.note-green {
240
+ background-color: rgba(156, 255, 149, .3);
241
+ }
242
+
243
+ .page-mask {
244
+ all: initial;
245
+ position: fixed;
246
+ top: 0;
247
+ left: 0;
248
+ width: 0;
249
+ height: 0;
250
+ z-index: 2147483646;
251
+ }
252
+
253
+ .page-mask-active {
254
+ width: 100vw;
255
+ height: 100vh;
256
+ }
257
+ `);
258
+ const HIGHLIGHTS_STYLESHEET = minifyText(`
259
+ .single-file-highlight-yellow, .single-file-highlight-yellow-mode ::selection {
260
+ background-color: #ffff7c !important;
261
+ color: black !important;
262
+ }
263
+
264
+ .single-file-highlight-pink, .single-file-highlight-pink-mode ::selection {
265
+ background-color: #ffbbb6 !important;
266
+ color: black !important;
267
+ }
268
+
269
+ .single-file-highlight-blue, .single-file-highlight-blue-mode ::selection {
270
+ background-color: #95d0ff !important;
271
+ color: black !important;
272
+ }
273
+
274
+ .single-file-highlight-green, .single-file-highlight-green-mode ::selection {
275
+ background-color: #93ef8d !important;
276
+ color: black !important;
277
+ }
278
+
279
+ span.single-file-highlight-yellow, span.single-file-highlight-pink, span.single-file-highlight-blue, span.single-file-highlight-green {
280
+ display: inline !important;
281
+ }
282
+
283
+ .single-file-highlight-hidden {
284
+ background-color: inherit !important;
285
+ color: inherit !important;
286
+ }
287
+
288
+ .single-file-mask {
289
+ all: initial;
290
+ display: contents !important;
291
+ }
292
+
293
+ .single-file-mask.single-file-page-mask {
294
+ opacity: .99 !important;
295
+ }
296
+
297
+ single-file-note {
298
+ all: initial !important;
299
+ display: contents !important;
300
+ }
301
+
302
+ .single-file-cut-hover, .single-file-cut-outer-hover, .single-file-cut-selected, .single-file-cut-outer-selected {
303
+ transition: outline-width 125ms !important;
304
+ outline-offset: -4px !important;
305
+ outline-width: 4px !important;
306
+ }
307
+
308
+ .single-file-cut-hover, .single-file-cut-outer-hover {
309
+ outline-style: dotted !important;
310
+ }
311
+
312
+ .single-file-cut-selected, .single-file-cut-outer-selected {
313
+ outline-style: dashed !important;
314
+ }
315
+
316
+ .single-file-cut-hover, .single-file-cut-selected {
317
+ outline-color: red !important;
318
+ }
319
+
320
+ .single-file-cut-outer-hover, .single-file-cut-outer-selected {
321
+ outline-color: green !important;
322
+ }
323
+
324
+ .single-file-cut-mode, .single-file-cut-mode * {
325
+ pointer-events: auto !important;
326
+ touch-action: none !important;
327
+ }
328
+
329
+ .single-file-cut-hover, .single-file-cut-outer-hover, .single-file-remove-highlights-mode .single-file-highlight:hover {
330
+ cursor: crosshair !important;
331
+ }
332
+
333
+ .single-file-removed {
334
+ display: none !important;
335
+ float: none !important;
336
+ position: static !important;
337
+ visibility: collapse !important;
338
+ }
339
+
340
+ a[href], img {
341
+ -webkit-touch-callout: none;
342
+ }
343
+ `);
344
+
345
+ export {
346
+ init,
347
+ restoreShadowRoots,
348
+ repairNesting,
349
+ serializeNotes,
350
+ insertHighlightsStylesheet,
351
+ getShadowRoot,
352
+ getPosition,
353
+ NOTE_TAGNAME,
354
+ MASK_CLASS,
355
+ HIGHLIGHT_CLASS,
356
+ HIGHLIGHT_HIDDEN_CLASS,
357
+ REMOVED_CONTENT_CLASS,
358
+ SHADOWROOT_ATTRIBUTE_NAME,
359
+ SCRIPT_TEMPLATE_SHADOW_ROOT
360
+ };
361
+
362
+ function init(doc, { editable = false, onUpdate = () => { } } = {}) {
363
+ const win = doc.defaultView;
364
+ const maskPageElement = getMaskElement(doc, PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
365
+ const maskNoteElement = getMaskElement(doc, NOTE_MASK_CLASS);
366
+ let selectedNote, anchorElement, resizingNoteMode, movingNoteMode, collapseNoteTimeout, previousMoveHandlers;
367
+ return {
368
+ addNote,
369
+ attachNoteListeners,
370
+ anchorNote,
371
+ resetAnchorNote,
372
+ onMouseUp,
373
+ reflowNotes,
374
+ watchNotesLayout,
375
+ waitResourcesLoad,
376
+ saveNoteOffset,
377
+ saveNoteOffsets,
378
+ displayNotes,
379
+ hideNotes
380
+ };
381
+
382
+ function addNote({ color }) {
383
+ const containerElement = doc.createElement(NOTE_TAGNAME);
384
+ const noteElement = doc.createElement("div");
385
+ const headerElement = doc.createElement("header");
386
+ const blockquoteElement = doc.createElement("blockquote");
387
+ const mainElement = doc.createElement("textarea");
388
+ const resizeElement = doc.createElement("div");
389
+ const removeNoteElement = doc.createElement("img");
390
+ const anchorIconElement = doc.createElement("img");
391
+ const noteShadow = containerElement.attachShadow({ mode: "open" });
392
+ headerElement.appendChild(anchorIconElement);
393
+ headerElement.appendChild(removeNoteElement);
394
+ blockquoteElement.appendChild(mainElement);
395
+ noteElement.appendChild(headerElement);
396
+ noteElement.appendChild(blockquoteElement);
397
+ noteElement.appendChild(resizeElement);
398
+ noteShadow.appendChild(getStyleElement(doc, NOTES_STYLESHEET));
399
+ noteShadow.appendChild(noteElement);
400
+ const notesElements = Array.from(doc.querySelectorAll(NOTE_TAGNAME));
401
+ const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
402
+ blockquoteElement.cite = NOTE_SELECTOR_URL_PREFIX + noteId + NOTE_SELECTOR_URL_SUFFIX;
403
+ noteElement.classList.add(NOTE_CLASS);
404
+ noteElement.classList.add(NOTE_ANCHORED_CLASS);
405
+ noteElement.classList.add(color);
406
+ noteElement.dataset.color = color;
407
+ mainElement.dir = "auto";
408
+ const boundingRectDocument = doc.documentElement.getBoundingClientRect();
409
+ let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
410
+ let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
411
+ while (Array.from(doc.elementsFromPoint(positionX - win.scrollX, positionY - win.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
412
+ positionX += NOTE_INITIAL_POSITION_X;
413
+ positionY += NOTE_INITIAL_POSITION_Y;
414
+ }
415
+ noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
416
+ noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
417
+ resizeElement.className = NOTE_RESIZE_CLASS;
418
+ resizeElement.ondragstart = event => event.preventDefault();
419
+ removeNoteElement.className = NOTE_REMOVE_CLASS;
420
+ removeNoteElement.src = BUTTON_CLOSE_URL;
421
+ removeNoteElement.ondragstart = event => event.preventDefault();
422
+ anchorIconElement.className = NOTE_ANCHOR_CLASS;
423
+ anchorIconElement.src = BUTTON_ANCHOR_URL;
424
+ anchorIconElement.ondragstart = event => event.preventDefault();
425
+ containerElement.dataset.noteId = noteId;
426
+ addNoteRef(doc.documentElement, noteId);
427
+ attachNoteListeners(containerElement, true);
428
+ doc.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
429
+ selectNote(noteElement);
430
+ saveNoteOffset(containerElement);
431
+ onUpdate(false);
432
+ return containerElement;
433
+ }
434
+
435
+ function attachNoteListeners(containerElement, editableNote = editable) {
436
+ const noteShadow = containerElement.shadowRoot;
437
+ const noteElement = noteShadow.childNodes[1];
438
+ const headerElement = noteShadow.querySelector("header");
439
+ const mainElement = noteShadow.querySelector("textarea");
440
+ const noteId = containerElement.dataset.noteId;
441
+ const resizeElement = noteShadow.querySelector("." + NOTE_RESIZE_CLASS);
442
+ const anchorIconElement = noteShadow.querySelector("." + NOTE_ANCHOR_CLASS);
443
+ const removeNoteElement = noteShadow.querySelector("." + NOTE_REMOVE_CLASS);
444
+ mainElement.readOnly = !editableNote;
445
+ if (!editableNote) {
446
+ anchorIconElement.style.setProperty("display", "none", "important");
447
+ } else {
448
+ anchorIconElement.style.removeProperty("display");
449
+ }
450
+ headerElement.ontouchstart = headerElement.onmousedown = event => {
451
+ if (event.target == headerElement) {
452
+ collapseNoteTimeout = win.setTimeout(() => {
453
+ noteElement.classList.toggle(NOTE_COLLAPSED_CLASS);
454
+ hideMaskNote();
455
+ }, COLLAPSING_NOTE_DELAY);
456
+ event.preventDefault();
457
+ const position = getPosition(event);
458
+ const clientX = position.clientX;
459
+ const clientY = position.clientY;
460
+ const boundingRect = noteElement.getBoundingClientRect();
461
+ const deltaX = clientX - boundingRect.left;
462
+ const deltaY = clientY - boundingRect.top;
463
+ maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
464
+ doc.documentElement.style.setProperty("user-select", "none", "important");
465
+ anchorElement = getAnchorElement(containerElement);
466
+ displayMaskNote();
467
+ selectNote(noteElement);
468
+ moveNote(event, deltaX, deltaY);
469
+ movingNoteMode = { event, deltaX, deltaY };
470
+ saveMoveHandlers();
471
+ doc.documentElement.ontouchmove = doc.documentElement.onmousemove = event => {
472
+ win.clearTimeout(collapseNoteTimeout);
473
+ if (!movingNoteMode) {
474
+ movingNoteMode = { deltaX, deltaY };
475
+ }
476
+ movingNoteMode.event = event;
477
+ moveNote(event, deltaX, deltaY);
478
+ };
479
+ }
480
+ };
481
+ resizeElement.ontouchstart = resizeElement.onmousedown = event => {
482
+ event.preventDefault();
483
+ resizingNoteMode = true;
484
+ selectNote(noteElement);
485
+ maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
486
+ doc.documentElement.style.setProperty("user-select", "none", "important");
487
+ saveMoveHandlers();
488
+ doc.documentElement.ontouchmove = doc.documentElement.onmousemove = event => {
489
+ event.preventDefault();
490
+ const { clientX, clientY } = getPosition(event);
491
+ const boundingRectNote = noteElement.getBoundingClientRect();
492
+ noteElement.style.width = clientX - boundingRectNote.left + "px";
493
+ noteElement.style.height = clientY - boundingRectNote.top + "px";
494
+ };
495
+ };
496
+ anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
497
+ event.preventDefault();
498
+ noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
499
+ if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
500
+ deleteNoteRef(containerElement, noteId);
501
+ addNoteRef(doc.documentElement, noteId);
502
+ }
503
+ saveNoteOffset(containerElement);
504
+ onUpdate(false);
505
+ };
506
+ removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
507
+ event.preventDefault();
508
+ deleteNoteRef(containerElement, noteId);
509
+ containerElement.remove();
510
+ if (selectedNote == noteElement) {
511
+ selectedNote = null;
512
+ }
513
+ onUpdate(false);
514
+ };
515
+ noteElement.onmousedown = () => {
516
+ selectNote(noteElement);
517
+ };
518
+
519
+ function moveNote(event, deltaX, deltaY) {
520
+ event.preventDefault();
521
+ const { clientX, clientY } = getPosition(event);
522
+ noteElement.classList.add(NOTE_MOVING_CLASS);
523
+ if (editableNote) {
524
+ if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
525
+ deleteNoteRef(containerElement, noteId);
526
+ anchorElement = getTarget(clientX, clientY) || doc.documentElement;
527
+ addNoteRef(anchorElement, noteId);
528
+ } else {
529
+ anchorElement = doc.documentElement;
530
+ }
531
+ }
532
+ doc.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
533
+ noteElement.style.setProperty("left", (clientX - deltaX) + "px");
534
+ noteElement.style.setProperty("top", (clientY - deltaY) + "px");
535
+ noteElement.style.setProperty("position", "fixed");
536
+ displayMaskNote();
537
+ }
538
+
539
+ function displayMaskNote() {
540
+ if (anchorElement == doc.documentElement) {
541
+ hideMaskNote();
542
+ } else {
543
+ const boundingRectAnchor = anchorElement.getBoundingClientRect();
544
+ maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
545
+ if (selectedNote) {
546
+ maskNoteElement.classList.add(selectedNote.dataset.color);
547
+ }
548
+ maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
549
+ maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
550
+ maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
551
+ maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
552
+ }
553
+ }
554
+
555
+ function hideMaskNote() {
556
+ maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
557
+ if (selectedNote) {
558
+ maskNoteElement.classList.remove(selectedNote.dataset.color);
559
+ }
560
+ }
561
+
562
+ function getTarget(clientX, clientY) {
563
+ const targets = Array.from(doc.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
564
+ if (!targets.includes(doc.documentElement)) {
565
+ targets.push(doc.documentElement);
566
+ }
567
+ let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
568
+ newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
569
+ if (newTarget == target) {
570
+ newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
571
+ }
572
+ if (newTarget == target) {
573
+ newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
574
+ }
575
+ if (newTarget == target) {
576
+ newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
577
+ }
578
+ target = newTarget;
579
+ while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
580
+ target = target.parentElement;
581
+ }
582
+ return target;
583
+ }
584
+
585
+ function getMatchedParents(target, property) {
586
+ let element = target, matchedParent, parents = [];
587
+ do {
588
+ const boundingRect = element.getBoundingClientRect();
589
+ if (element.parentElement && element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
590
+ const parentBoundingRect = element.parentElement.getBoundingClientRect();
591
+ matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
592
+ if (matchedParent) {
593
+ if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
594
+ ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
595
+ parents.push(element.parentElement);
596
+ }
597
+ element = element.parentElement;
598
+ }
599
+ } else {
600
+ matchedParent = false;
601
+ }
602
+ } while (matchedParent && element);
603
+ return parents;
604
+ }
605
+
606
+ function determineTargetElement(roundingMethod, target, widthDistance, parents) {
607
+ if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
608
+ target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
609
+ }
610
+ return target;
611
+ }
612
+ }
613
+
614
+ function selectNote(noteElement) {
615
+ if (selectedNote) {
616
+ selectedNote.classList.remove(NOTE_SELECTED_CLASS);
617
+ maskNoteElement.classList.remove(selectedNote.dataset.color);
618
+ }
619
+ noteElement.classList.add(NOTE_SELECTED_CLASS);
620
+ noteElement.classList.add(noteElement.dataset.color);
621
+ selectedNote = noteElement;
622
+ }
623
+
624
+ function saveMoveHandlers() {
625
+ if (!previousMoveHandlers) {
626
+ previousMoveHandlers = { ontouchmove: doc.documentElement.ontouchmove, onmousemove: doc.documentElement.onmousemove };
627
+ }
628
+ }
629
+
630
+ function restoreMoveHandlers() {
631
+ if (previousMoveHandlers) {
632
+ doc.documentElement.ontouchmove = previousMoveHandlers.ontouchmove;
633
+ doc.documentElement.onmousemove = previousMoveHandlers.onmousemove;
634
+ previousMoveHandlers = null;
635
+ }
636
+ }
637
+
638
+ function onMouseUp(event) {
639
+ if (resizingNoteMode) {
640
+ event.preventDefault();
641
+ resizingNoteMode = false;
642
+ doc.documentElement.style.removeProperty("user-select");
643
+ maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
644
+ restoreMoveHandlers();
645
+ onUpdate(false);
646
+ }
647
+ if (movingNoteMode) {
648
+ event.preventDefault();
649
+ anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
650
+ movingNoteMode = null;
651
+ restoreMoveHandlers();
652
+ onUpdate(false);
653
+ }
654
+ if (collapseNoteTimeout) {
655
+ win.clearTimeout(collapseNoteTimeout);
656
+ collapseNoteTimeout = null;
657
+ }
658
+ }
659
+
660
+ function anchorNote(event, noteElement, deltaX, deltaY) {
661
+ event.preventDefault();
662
+ const { clientX, clientY } = getPosition(event);
663
+ doc.documentElement.style.removeProperty("user-select");
664
+ noteElement.classList.remove(NOTE_MOVING_CLASS);
665
+ maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
666
+ maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
667
+ maskNoteElement.classList.remove(noteElement.dataset.color);
668
+ const headerElement = noteElement.querySelector("header");
669
+ headerElement.ontouchmove = doc.documentElement.onmousemove = null;
670
+ let currentElement = anchorElement;
671
+ let positionedElement;
672
+ while (currentElement.parentElement && !positionedElement) {
673
+ if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
674
+ const currentElementStyle = win.getComputedStyle(currentElement);
675
+ if (currentElementStyle.position != "static") {
676
+ positionedElement = currentElement;
677
+ }
678
+ }
679
+ currentElement = currentElement.parentElement;
680
+ }
681
+ if (!positionedElement) {
682
+ positionedElement = doc.documentElement;
683
+ }
684
+ const containerElement = noteElement.getRootNode().host;
685
+ if (positionedElement == doc.documentElement) {
686
+ const firstMaskElement = doc.querySelector("." + MASK_CLASS);
687
+ firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
688
+ } else {
689
+ positionedElement.appendChild(containerElement);
690
+ }
691
+ const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
692
+ const stylePositionedElement = win.getComputedStyle(positionedElement);
693
+ const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
694
+ const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
695
+ noteElement.style.setProperty("position", "absolute");
696
+ noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
697
+ noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
698
+ saveNoteOffset(containerElement);
699
+ }
700
+
701
+ function resetAnchorNote(containerElement) {
702
+ const noteId = containerElement.dataset.noteId;
703
+ const noteElement = containerElement.shadowRoot.childNodes[1];
704
+ noteElement.classList.remove(NOTE_ANCHORED_CLASS);
705
+ deleteNoteRef(containerElement, noteId);
706
+ addNoteRef(doc.documentElement, noteId);
707
+ doc.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
708
+ saveNoteOffset(containerElement);
709
+ }
710
+
711
+ function reflowNotes() {
712
+ doc.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
713
+ const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
714
+ const noteBoundingRect = noteElement.getBoundingClientRect();
715
+ if ((noteBoundingRect.width || noteBoundingRect.height) && !noteElement.classList.contains(NOTE_MOVING_CLASS)) {
716
+ const anchorElement = getAnchorElement(containerElement);
717
+ const anchorBoundingRect = anchorElement.getBoundingClientRect();
718
+ const offsetX = Number(containerElement.dataset.noteOffsetX);
719
+ const offsetY = Number(containerElement.dataset.noteOffsetY);
720
+ const savedOffset = anchorElement != doc.documentElement && !isNaN(offsetX) && !isNaN(offsetY);
721
+ const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
722
+ const minX = anchorBoundingRect.x;
723
+ const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
724
+ const minY = anchorBoundingRect.y;
725
+ const positionX = Math.min(maxX, Math.max(minX, savedOffset ? anchorBoundingRect.x + offsetX : noteBoundingRect.x));
726
+ const positionY = Math.min(maxY, Math.max(minY, savedOffset ? anchorBoundingRect.y + offsetY : noteBoundingRect.y));
727
+ const left = parseFloat(noteElement.style.getPropertyValue("left"));
728
+ const top = parseFloat(noteElement.style.getPropertyValue("top"));
729
+ noteElement.style.setProperty("position", "absolute");
730
+ if (Math.abs(positionX - noteBoundingRect.x) > 0.5) {
731
+ noteElement.style.setProperty("left", (left + positionX - noteBoundingRect.x) + "px");
732
+ }
733
+ if (Math.abs(positionY - noteBoundingRect.y) > 0.5) {
734
+ noteElement.style.setProperty("top", (top + positionY - noteBoundingRect.y) + "px");
735
+ }
736
+ }
737
+ });
738
+ }
739
+
740
+ function watchNotesLayout() {
741
+ if (win.ResizeObserver) {
742
+ let reflowPending;
743
+ new win.ResizeObserver(() => {
744
+ if (!reflowPending) {
745
+ reflowPending = win.requestAnimationFrame(() => {
746
+ reflowPending = null;
747
+ reflowNotes();
748
+ });
749
+ }
750
+ }).observe(doc.documentElement);
751
+ }
752
+ if (doc.fonts) {
753
+ doc.fonts.ready.then(() => reflowNotes());
754
+ }
755
+ }
756
+
757
+ function waitResourcesLoad() {
758
+ return new Promise(resolve => {
759
+ let counterMutations = 0;
760
+ const done = () => {
761
+ observer.disconnect();
762
+ resolve();
763
+ };
764
+ let timeoutInit = win.setTimeout(done, RESOURCES_LOAD_DELAY);
765
+ const observer = new win.MutationObserver(() => {
766
+ if (counterMutations < RESOURCES_LOAD_MAX_MUTATIONS) {
767
+ counterMutations++;
768
+ win.clearTimeout(timeoutInit);
769
+ timeoutInit = win.setTimeout(done, RESOURCES_LOAD_DELAY);
770
+ } else {
771
+ done();
772
+ }
773
+ });
774
+ observer.observe(doc, { subtree: true, childList: true, attributes: true });
775
+ });
776
+ }
777
+
778
+ function saveNoteOffset(containerElement) {
779
+ const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
780
+ if (noteElement) {
781
+ const anchorElement = getAnchorElement(containerElement);
782
+ const noteBoundingRect = noteElement.getBoundingClientRect();
783
+ if (anchorElement == doc.documentElement) {
784
+ delete containerElement.dataset.noteOffsetX;
785
+ delete containerElement.dataset.noteOffsetY;
786
+ } else if (noteBoundingRect.width || noteBoundingRect.height) {
787
+ const anchorBoundingRect = anchorElement.getBoundingClientRect();
788
+ containerElement.dataset.noteOffsetX = Math.round(noteBoundingRect.x - anchorBoundingRect.x);
789
+ containerElement.dataset.noteOffsetY = Math.round(noteBoundingRect.y - anchorBoundingRect.y);
790
+ }
791
+ }
792
+ }
793
+
794
+ function saveNoteOffsets() {
795
+ doc.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => saveNoteOffset(containerElement));
796
+ }
797
+
798
+ function displayNotes() {
799
+ doc.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => containerElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
800
+ reflowNotes();
801
+ }
802
+
803
+ function hideNotes() {
804
+ doc.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => containerElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
805
+ }
806
+
807
+ function getAnchorElement(containerElement) {
808
+ return doc.querySelector("[" + NOTE_REFS_ATTRIBUTE_NAME + "~=\"" + containerElement.dataset.noteId + "\"]") || doc.documentElement;
809
+ }
810
+ }
811
+
812
+ function addNoteRef(anchorElement, noteId) {
813
+ const noteRefs = getNoteRefs(anchorElement);
814
+ noteRefs.push(noteId);
815
+ setNoteRefs(anchorElement, noteRefs);
816
+ }
817
+
818
+ function deleteNoteRef(containerElement, noteId) {
819
+ const anchorElement = containerElement.ownerDocument.querySelector("[" + NOTE_REFS_ATTRIBUTE_NAME + "~=\"" + noteId + "\"]") || containerElement.ownerDocument.documentElement;
820
+ const noteRefs = getNoteRefs(anchorElement).filter(noteRef => noteRef != noteId);
821
+ if (noteRefs.length) {
822
+ setNoteRefs(anchorElement, noteRefs);
823
+ } else {
824
+ anchorElement.removeAttribute(NOTE_REFS_ATTRIBUTE_NAME);
825
+ }
826
+ }
827
+
828
+ function getNoteRefs(anchorElement) {
829
+ const noteRefs = anchorElement.getAttribute(NOTE_REFS_ATTRIBUTE_NAME);
830
+ return noteRefs ? noteRefs.split(" ") : [];
831
+ }
832
+
833
+ function setNoteRefs(anchorElement, noteRefs) {
834
+ anchorElement.setAttribute(NOTE_REFS_ATTRIBUTE_NAME, noteRefs.join(" "));
835
+ }
836
+
837
+ function getMaskElement(doc, className, containerClassName) {
838
+ const maskContainerElement = doc.createElement("div");
839
+ const maskElement = doc.createElement("div");
840
+ if (containerClassName) {
841
+ maskContainerElement.classList.add(containerClassName);
842
+ }
843
+ maskContainerElement.classList.add(MASK_CLASS);
844
+ const firstNote = doc.querySelector(NOTE_TAGNAME);
845
+ if (firstNote && firstNote.parentElement == doc.documentElement) {
846
+ doc.documentElement.insertBefore(maskContainerElement, firstNote);
847
+ } else {
848
+ doc.documentElement.appendChild(maskContainerElement);
849
+ }
850
+ maskElement.classList.add(className);
851
+ const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
852
+ maskShadow.appendChild(getStyleElement(doc, MASK_STYLESHEET));
853
+ maskShadow.appendChild(maskElement);
854
+ return maskElement;
855
+ }
856
+
857
+ function getStyleElement(doc, stylesheet) {
858
+ const styleElement = doc.createElement("style");
859
+ styleElement.textContent = stylesheet;
860
+ return styleElement;
861
+ }
862
+
863
+ function insertHighlightsStylesheet(doc) {
864
+ if (!doc.querySelector("." + HIGHLIGHTS_STYLESHEET_CLASS)) {
865
+ const styleElement = getStyleElement(doc, HIGHLIGHTS_STYLESHEET);
866
+ styleElement.classList.add(HIGHLIGHTS_STYLESHEET_CLASS);
867
+ doc.documentElement.appendChild(styleElement);
868
+ }
869
+ }
870
+
871
+ function serializeNotes(doc) {
872
+ doc.querySelectorAll("template[" + SHADOWROOT_ATTRIBUTE_NAME + "]").forEach(templateElement => {
873
+ const noteElement = templateElement.querySelector("." + NOTE_CLASS);
874
+ if (noteElement) {
875
+ noteElement.classList.remove(NOTE_HIDDEN_CLASS);
876
+ }
877
+ const mainElement = templateElement.querySelector("textarea");
878
+ if (mainElement) {
879
+ mainElement.textContent = mainElement.value;
880
+ }
881
+ });
882
+ }
883
+
884
+ function restoreShadowRoots(node) {
885
+ node.querySelectorAll("template[" + SHADOWROOT_ATTRIBUTE_NAME + "]").forEach(templateElement => {
886
+ const hostElement = templateElement.parentElement;
887
+ if (hostElement && !getShadowRoot(hostElement)) {
888
+ let shadowRoot;
889
+ try {
890
+ shadowRoot = hostElement.attachShadow({ mode: templateElement.getAttribute(SHADOWROOT_ATTRIBUTE_NAME) });
891
+ shadowRoot.innerHTML = templateElement.innerHTML;
892
+ templateElement.remove();
893
+ } catch {
894
+ // ignored
895
+ }
896
+ if (shadowRoot) {
897
+ restoreShadowRoots(shadowRoot);
898
+ }
899
+ }
900
+ });
901
+ }
902
+
903
+ function repairNesting(doc) {
904
+ const trackedElements = new Map();
905
+ doc.querySelectorAll("[" + NESTING_TRACK_ID_ATTRIBUTE_NAME + "]").forEach(element => trackedElements.set(element.getAttribute(NESTING_TRACK_ID_ATTRIBUTE_NAME), element));
906
+ trackedElements.forEach((element, trackId) => {
907
+ const trackIdParts = trackId.split(".");
908
+ if (trackIdParts.length > 1) {
909
+ const expectedParent = trackedElements.get(trackIdParts.slice(0, -1).join("."));
910
+ if (expectedParent && element.parentElement !== expectedParent) {
911
+ expectedParent.appendChild(element);
912
+ }
913
+ }
914
+ });
915
+ trackedElements.forEach(element => element.removeAttribute(NESTING_TRACK_ID_ATTRIBUTE_NAME));
916
+ }
917
+
918
+ function getShadowRoot(element) {
919
+ const chrome = globalThis.chrome;
920
+ if (element.openOrClosedShadowRoot) {
921
+ return element.openOrClosedShadowRoot;
922
+ } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
923
+ try {
924
+ return chrome.dom.openOrClosedShadowRoot(element);
925
+ } catch {
926
+ return element.shadowRoot;
927
+ }
928
+ } else {
929
+ return element.shadowRoot;
930
+ }
931
+ }
932
+
933
+ function getPosition(event) {
934
+ if (event.touches && event.touches.length) {
935
+ return event.touches[0];
936
+ } else {
937
+ return event;
938
+ }
939
+ }
940
+
941
+ function minifyText(text) {
942
+ return text.replace(/[\n\t\s]+/g, " ").trim();
943
+ }
@@ -17024,6 +17024,11 @@ async function evalTemplate(template = "", options, content, doc, context = {})
17024
17024
  "if-not-equals": (value, otherValue, trueValue, falseValue) => value != otherValue ? trueValue : falseValue,
17025
17025
  "if-contains": (value, otherValue, trueValue, falseValue) => otherValue && value.includes(otherValue) ? trueValue : falseValue,
17026
17026
  "if-not-contains": (value, otherValue, trueValue, falseValue) => otherValue && !value.includes(otherValue) ? trueValue : falseValue,
17027
+ "switch": (value, ...cases) => {
17028
+ const defaultValue = cases.length % 2 ? cases.pop() : undefined;
17029
+ const index = cases.findIndex((caseValue, caseIndex) => caseIndex % 2 == 0 && caseValue == value);
17030
+ return index == -1 ? defaultValue : cases[index + 1];
17031
+ },
17027
17032
  "substring": (value, start, end) => value.substring(start, end),
17028
17033
  "lowercase": value => value.toLowerCase(),
17029
17034
  "uppercase": value => value.toUpperCase(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "single-file-core",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "SingleFile Core",
5
5
  "author": "Gildas Lormeau",
6
6
  "license": "AGPL-3.0-or-later",
@@ -92,6 +92,7 @@
92
92
  const MutationObserver = globalThis.MutationObserver;
93
93
  const URL = globalThis.URL;
94
94
  const CSSStyleSheet = globalThis.CSSStyleSheet;
95
+ const DOMRect = globalThis.DOMRect;
95
96
 
96
97
  const observers = new Map();
97
98
  const observedElements = new Map();
@@ -188,6 +189,10 @@
188
189
  document.documentElement.style.removeProperty("-sf-transform");
189
190
  document.documentElement.style.removeProperty("-sf-transform-origin");
190
191
  document.documentElement.style.removeProperty("-sf-min-height");
192
+ if (globalThis._singleFile_getBoundingClientRect) {
193
+ Element.prototype.getBoundingClientRect = globalThis._singleFile_getBoundingClientRect;
194
+ delete globalThis._singleFile_getBoundingClientRect;
195
+ }
191
196
  resetScreenSize();
192
197
  }
193
198
 
@@ -351,6 +356,20 @@
351
356
  document.documentElement.style.setProperty("transform-origin", horizontalOrigin + " 0 0", "important");
352
357
  document.documentElement.style.setProperty("transform", translation + "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
353
358
  document.documentElement.style.setProperty("min-height", (100 / zoomFactor) + "vh", "important");
359
+ if (keepZoomLevel && !globalThis._singleFile_getBoundingClientRect) {
360
+ const originX = horizontalOrigin == "0" ? 0 : document.documentElement.offsetWidth / 2;
361
+ const translationX = horizontalOrigin == "0" ? scrollPosition.x : 0;
362
+ const translationY = scrollPosition.y;
363
+ globalThis._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
364
+ Element.prototype.getBoundingClientRect = function () {
365
+ const boundingRect = globalThis._singleFile_getBoundingClientRect.call(this);
366
+ const x = originX + (boundingRect.x + globalThis.scrollX - originX - translationX) / zoomFactor - globalThis.scrollX;
367
+ const y = (boundingRect.y + globalThis.scrollY - translationY) / zoomFactor - globalThis.scrollY;
368
+ return new DOMRect(x, y, boundingRect.width / zoomFactor, boundingRect.height / zoomFactor);
369
+ };
370
+ Element.prototype.getBoundingClientRect.toString = function () { return "function getBoundingClientRect() { [native code] }"; };
371
+ setFunctionName(Element.prototype.getBoundingClientRect, "getBoundingClientRect");
372
+ }
354
373
  dispatchResizeEvent();
355
374
  if (keepZoomLevel || keepEmulatedScreenSize) {
356
375
  document.documentElement.style.setProperty("-sf-transform", transform, transformPriority);
@@ -28,6 +28,7 @@ import { getInstance } from "./core/util.js";
28
28
  import * as zip from "./vendor/zip/zip.js";
29
29
  import { extract } from "./processors/compression/compression-extract.js";
30
30
  import { display } from "./processors/compression/compression-display.js";
31
+ import * as notes from "./core/notes.js";
31
32
 
32
33
  const util = getInstance();
33
34
  const helper = {
@@ -56,6 +57,7 @@ const helper = {
56
57
  extract,
57
58
  display,
58
59
  formatFilename,
60
+ notes,
59
61
  INFOBAR_TAGNAME: infobar.INFOBAR_TAGNAME,
60
62
  NESTING_TRACK_ID_ATTRIBUTE_NAME: util.NESTING_TRACK_ID_ATTRIBUTE_NAME
61
63
  };
@@ -0,0 +1,43 @@
1
+ /*
2
+ * Copyright 2010-2025 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ /* global document */
25
+
26
+ import { init, restoreShadowRoots, repairNesting, NOTE_TAGNAME } from "./core/notes.js";
27
+
28
+ (() => {
29
+
30
+ if (document.currentScript) {
31
+ document.currentScript.remove();
32
+ }
33
+ const notes = init(document);
34
+ globalThis.onresize = notes.reflowNotes;
35
+ document.documentElement.onmouseup = document.documentElement.ontouchend = notes.onMouseUp;
36
+ restoreShadowRoots(document);
37
+ notes.reflowNotes();
38
+ document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => notes.attachNoteListeners(containerElement));
39
+ notes.waitResourcesLoad().then(notes.reflowNotes);
40
+ notes.watchNotesLayout();
41
+ repairNesting(document);
42
+
43
+ })();