1
0

single-file-extension-editor.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  1. (function () {
  2. 'use strict';
  3. /*
  4. * Copyright 2010-2020 Gildas Lormeau
  5. * contact : gildas.lormeau <at> gmail.com
  6. *
  7. * This file is part of SingleFile.
  8. *
  9. * The code in this file is free software: you can redistribute it and/or
  10. * modify it under the terms of the GNU Affero General Public License
  11. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  12. * of the License, or (at your option) any later version.
  13. *
  14. * The code in this file is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  17. * General Public License for more details.
  18. *
  19. * As additional permission under GNU AGPL version 3 section 7, you may
  20. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  21. * AGPL normally required by section 4, provided you include this license
  22. * notice and a URL through which recipients can access the Corresponding
  23. * Source.
  24. */
  25. /* global globalThis, window, document, fetch, DOMParser, getComputedStyle, setTimeout, clearTimeout, NodeFilter, Readability, isProbablyReaderable, matchMedia, TextDecoder, Node, URL, MouseEvent, Blob, prompt, MutationObserver, FileReader, Worker, navigator, alert */
  26. (globalThis => {
  27. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  28. const singlefile = globalThis.singlefile;
  29. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  30. 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";
  31. 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==";
  32. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  33. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  34. const NOTE_TAGNAME = "single-file-note";
  35. const NOTE_CLASS = "note";
  36. const NOTE_MASK_CLASS = "note-mask";
  37. const NOTE_HIDDEN_CLASS = "note-hidden";
  38. const NOTE_ANCHORED_CLASS = "note-anchored";
  39. const NOTE_SELECTED_CLASS = "note-selected";
  40. const NOTE_MOVING_CLASS = "note-moving";
  41. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  42. const PAGE_MASK_CLASS = "page-mask";
  43. const MASK_CLASS = "single-file-mask";
  44. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  45. const HIGHLIGHT_CLASS = "single-file-highlight";
  46. const REMOVED_CONTENT_CLASS = "single-file-removed";
  47. const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
  48. const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
  49. const CUT_HOVER_CLASS = "single-file-cut-hover";
  50. const CUT_OUTER_HOVER_CLASS = "single-file-cut-outer-hover";
  51. const CUT_SELECTED_CLASS = "single-file-cut-selected";
  52. const CUT_OUTER_SELECTED_CLASS = "single-file-cut-outer-selected";
  53. const CUT_MODE_CLASS = "single-file-cut-mode";
  54. const NOTE_INITIAL_POSITION_X = 20;
  55. const NOTE_INITIAL_POSITION_Y = 20;
  56. const NOTE_INITIAL_WIDTH = 150;
  57. const NOTE_INITIAL_HEIGHT = 150;
  58. const NOTE_HEADER_HEIGHT = 25;
  59. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  60. const COMMENT_HEADER = "Page saved with SingleFile";
  61. const COMMENT_HEADER_LEGACY = "Archive processed by SingleFile";
  62. const STYLE_FORMATTED_PAGE = `
  63. /* This Source Code Form is subject to the terms of the Mozilla Public
  64. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  65. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  66. /* Avoid adding ID selector rules in this style sheet, since they could
  67. * inadvertently match elements in the article content. */
  68. :root {
  69. --grey-90-a10: rgba(12, 12, 13, 0.1);
  70. --grey-90-a20: rgba(12, 12, 13, 0.2);
  71. --grey-90-a30: rgba(12, 12, 13, 0.3);
  72. --grey-90-a80: rgba(12, 12, 13, 0.8);
  73. --grey-30: #d7d7db;
  74. --blue-40: #45a1ff;
  75. --blue-40-a30: rgba(69, 161, 255, 0.3);
  76. --blue-60: #0060df;
  77. --body-padding: 64px;
  78. --font-size: 12;
  79. --content-width: 70em;
  80. --line-height: 1.6em;
  81. }
  82. body {
  83. --main-background: #fff;
  84. --main-foreground: #333;
  85. --font-color: #000000;
  86. --primary-color: #0B83FF;
  87. --toolbar-border: var(--grey-90-a20);
  88. --toolbar-transparent-border: transparent;
  89. --toolbar-box-shadow: var(--grey-90-a10);
  90. --toolbar-button-background: transparent;
  91. --toolbar-button-background-hover: var(--grey-90-a10);
  92. --toolbar-button-foreground-hover: var(--font-color);
  93. --toolbar-button-background-active: var(--grey-90-a20);
  94. --toolbar-button-foreground-active: var(--primary-color);
  95. --toolbar-button-border: transparent;
  96. --toolbar-button-border-hover: transparent;
  97. --toolbar-button-border-active: transparent;
  98. --tooltip-background: var(--grey-90-a80);
  99. --tooltip-foreground: white;
  100. --tooltip-border: transparent;
  101. --popup-background: white;
  102. --popup-border: rgba(0, 0, 0, 0.12);
  103. --opaque-popup-border: #e0e0e0;
  104. --popup-line: var(--grey-30);
  105. --popup-shadow: rgba(49, 49, 49, 0.3);
  106. --popup-button-background: #edecf0;
  107. --popup-button-background-hover: hsla(0,0%,70%,.4);
  108. --popup-button-foreground-hover: var(--font-color);
  109. --popup-button-background-active: hsla(240,5%,5%,.15);
  110. --selected-background: var(--blue-40-a30);
  111. --selected-border: var(--blue-40);
  112. --font-value-border: var(--grey-30);
  113. --icon-fill: #3b3b3c;
  114. --icon-disabled-fill: #8080807F;
  115. --link-foreground: var(--blue-60);
  116. --link-selected-foreground: #333;
  117. --visited-link-foreground: #b5007f;
  118. /* light colours */
  119. }
  120. body.sepia {
  121. --main-background: #f4ecd8;
  122. --main-foreground: #5b4636;
  123. --toolbar-border: #5b4636;
  124. }
  125. body.dark {
  126. --main-background: rgb(28, 27, 34);
  127. --main-foreground: #eee;
  128. --font-color: #fff;
  129. --toolbar-border: #4a4a4b;
  130. --toolbar-box-shadow: black;
  131. --toolbar-button-background-hover: var(--grey-90-a30);
  132. --toolbar-button-background-active: var(--grey-90-a80);
  133. --tooltip-background: black;
  134. --tooltip-foreground: white;
  135. --popup-background: rgb(66,65,77);
  136. --opaque-popup-border: #434146;
  137. --popup-line: rgb(82, 82, 94);
  138. --popup-button-background: #5c5c61;
  139. --popup-button-background-active: hsla(0,0%,70%,.6);
  140. --selected-background: #3E6D9A;
  141. --font-value-border: #656468;
  142. --icon-fill: #fff;
  143. --icon-disabled-fill: #ffffff66;
  144. --link-foreground: #45a1ff;
  145. --link-selected-foreground: #fff;
  146. --visited-link-foreground: #e675fd;
  147. /* dark colours */
  148. }
  149. body.hcm {
  150. --main-background: Canvas;
  151. --main-foreground: CanvasText;
  152. --font-color: CanvasText;
  153. --primary-color: SelectedItem;
  154. --toolbar-border: CanvasText;
  155. /* We need a true transparent but in HCM this would compute to an actual color,
  156. so select the page's background color instead: */
  157. --toolbar-transparent-border: Canvas;
  158. --toolbar-box-shadow: Canvas;
  159. --toolbar-button-background: ButtonFace;
  160. --toolbar-button-background-hover: ButtonText;
  161. --toolbar-button-foreground-hover: ButtonFace;
  162. --toolbar-button-background-active: SelectedItem;
  163. --toolbar-button-foreground-active: SelectedItemText;
  164. --toolbar-button-border: ButtonText;
  165. --toolbar-button-border-hover: ButtonText;
  166. --toolbar-button-border-active: ButtonText;
  167. --tooltip-background: Canvas;
  168. --tooltip-foreground: CanvasText;
  169. --tooltip-border: CanvasText;
  170. --popup-background: Canvas;
  171. --popup-border: CanvasText;
  172. --opaque-popup-border: CanvasText;
  173. --popup-line: CanvasText;
  174. --popup-button-background: ButtonFace;
  175. --popup-button-background-hover: ButtonText;
  176. --popup-button-foreground-hover: ButtonFace;
  177. --popup-button-background-active: ButtonText;
  178. --selected-background: Canvas;
  179. --selected-border: SelectedItem;
  180. --font-value-border: CanvasText;
  181. --icon-fill: ButtonText;
  182. --icon-disabled-fill: GrayText;
  183. --link-foreground: LinkText;
  184. --link-selected-foreground: ActiveText;
  185. --visited-link-foreground: VisitedText;
  186. }
  187. body {
  188. margin: 0;
  189. padding: var(--body-padding);
  190. background-color: var(--main-background);
  191. color: var(--main-foreground);
  192. }
  193. body.loaded {
  194. transition: color 0.4s, background-color 0.4s;
  195. }
  196. body.dark *::-moz-selection {
  197. background-color: var(--selected-background);
  198. }
  199. a::-moz-selection {
  200. color: var(--link-selected-foreground);
  201. }
  202. body.sans-serif,
  203. body.sans-serif .remove-button {
  204. font-family: Helvetica, Arial, sans-serif;
  205. }
  206. body.serif,
  207. body.serif .remove-button {
  208. font-family: Georgia, "Times New Roman", serif;
  209. }
  210. /* Override some controls and content styles based on color scheme */
  211. body.light > .container > .header > .domain {
  212. border-bottom-color: #333333 !important;
  213. }
  214. body.sepia > .container > .header > .domain {
  215. border-bottom-color: #5b4636 !important;
  216. }
  217. body.dark > .container > .header > .domain {
  218. border-bottom-color: #eeeeee !important;
  219. }
  220. body.light blockquote {
  221. border-inline-start: 2px solid #333333 !important;
  222. }
  223. body.sepia blockquote {
  224. border-inline-start: 2px solid #5b4636 !important;
  225. }
  226. body.dark blockquote {
  227. border-inline-start: 2px solid #eeeeee !important;
  228. }
  229. .light-button {
  230. color: #333333;
  231. background-color: #ffffff;
  232. }
  233. .dark-button {
  234. color: #eeeeee;
  235. background-color: #1c1b22;
  236. }
  237. .sepia-button {
  238. color: #5b4636;
  239. background-color: #f4ecd8;
  240. }
  241. .auto-button {
  242. text-align: center;
  243. }
  244. @media (prefers-color-scheme: dark) {
  245. .auto-button {
  246. background-color: #1c1b22;
  247. color: #eeeeee;
  248. }
  249. }
  250. @media not (prefers-color-scheme: dark) {
  251. .auto-button {
  252. background-color: #ffffff;
  253. color: #333333;
  254. }
  255. }
  256. /* Loading/error message */
  257. .reader-message {
  258. margin-top: 40px;
  259. display: none;
  260. text-align: center;
  261. width: 100%;
  262. font-size: 0.9em;
  263. }
  264. /* Detector element to see if we're at the top of the doc or not. */
  265. .top-anchor {
  266. position: absolute;
  267. top: 0;
  268. width: 0;
  269. height: 5px;
  270. pointer-events: none;
  271. }
  272. /* Header */
  273. .header {
  274. text-align: start;
  275. display: none;
  276. }
  277. .domain {
  278. font-size: 0.9em;
  279. line-height: 1.48em;
  280. padding-bottom: 4px;
  281. font-family: Helvetica, Arial, sans-serif;
  282. text-decoration: none;
  283. border-bottom: 1px solid;
  284. color: var(--link-foreground);
  285. }
  286. .header > h1 {
  287. font-size: 1.6em;
  288. line-height: 1.25em;
  289. width: 100%;
  290. margin: 30px 0;
  291. padding: 0;
  292. }
  293. .header > .credits {
  294. font-size: 0.9em;
  295. line-height: 1.48em;
  296. margin: 0 0 10px;
  297. padding: 0;
  298. font-style: italic;
  299. }
  300. .header > .meta-data {
  301. font-size: 0.65em;
  302. margin: 0 0 15px;
  303. }
  304. .reader-estimated-time {
  305. text-align: match-parent;
  306. }
  307. /* Controls toolbar */
  308. .toolbar-container {
  309. position: sticky;
  310. z-index: 2;
  311. top: 32px;
  312. height: 0; /* take up no space, so body is at the top. */
  313. /* As a stick container, we're positioned relative to the body. Move us to
  314. * the edge of the viewport using margins, and take the width of
  315. * the body padding into account for calculating our width.
  316. */
  317. margin-inline-start: calc(-1 * var(--body-padding));
  318. width: max(var(--body-padding), calc((100% - var(--content-width)) / 2 + var(--body-padding)));
  319. font-size: var(--font-size); /* Needed to ensure 'em' units match, is reset for .reader-controls */
  320. }
  321. .toolbar {
  322. padding-block: 16px;
  323. border: 1px solid var(--toolbar-border);
  324. border-radius: 6px;
  325. box-shadow: 0 2px 8px var(--toolbar-box-shadow);
  326. width: 32px; /* basic width, without padding/border */
  327. /* padding should be 16px, except if there's not enough space for that, in
  328. * which case use half the available space for padding (=25% on each side).
  329. * The 34px here is the width + borders. We use a variable because we need
  330. * to know this size for the margin calculation.
  331. */
  332. --inline-padding: min(16px, calc(25% - 0.25 * 34px));
  333. padding-inline: var(--inline-padding);
  334. /* Keep a maximum of 96px distance to the body, but center once the margin
  335. * gets too small. We need to set the start margin, however...
  336. * To center, we'd want 50% of the container, but we'd subtract half our
  337. * own width (16px) and half the border (1px) and the inline padding.
  338. * When the other margin would be 96px, we want 100% - 96px - the complete
  339. * width of the actual toolbar (34px + 2 * padding)
  340. */
  341. margin-inline-start: max(calc(50% - 17px - var(--inline-padding)), calc(100% - 96px - 34px - 2 * var(--inline-padding)));
  342. font-family: Helvetica, Arial, sans-serif;
  343. list-style: none;
  344. user-select: none;
  345. }
  346. @media (prefers-reduced-motion: no-preference) {
  347. .toolbar {
  348. transition-property: border-color, box-shadow;
  349. transition-duration: 250ms;
  350. }
  351. .toolbar .toolbar-button {
  352. transition-property: opacity;
  353. transition-duration: 250ms;
  354. }
  355. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) {
  356. border-color: var(--toolbar-transparent-border);
  357. box-shadow: 0 2px 8px transparent;
  358. }
  359. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) .toolbar-button {
  360. opacity: 0.6;
  361. }
  362. .toolbar-container.transition-location {
  363. transition-duration: 250ms;
  364. transition-property: width;
  365. }
  366. }
  367. .toolbar-container.overlaps .toolbar-button {
  368. opacity: 0.1;
  369. }
  370. .dropdown-open .toolbar {
  371. border-color: var(--toolbar-transparent-border);
  372. box-shadow: 0 2px 8px transparent;
  373. }
  374. .reader-controls {
  375. /* We use 'em's above this node to get it to the right size. However,
  376. * the UI inside the toolbar should use a fixed, smaller size. */
  377. font-size: 11px;
  378. }
  379. button {
  380. -moz-context-properties: fill;
  381. color: var(--font-color);
  382. fill: var(--icon-fill);
  383. }
  384. button:disabled {
  385. fill: var(--icon-disabled-fill);
  386. }
  387. .toolbar button::-moz-focus-inner {
  388. border: 0;
  389. }
  390. .toolbar-button {
  391. position: relative;
  392. width: 32px;
  393. height: 32px;
  394. padding: 0;
  395. border: 1px solid var(--toolbar-button-border);
  396. border-radius: 4px;
  397. margin: 4px 0;
  398. background-color: var(--toolbar-button-background);
  399. background-size: 16px 16px;
  400. background-position: center;
  401. background-repeat: no-repeat;
  402. }
  403. .toolbar-button:hover,
  404. .toolbar-button:focus-visible {
  405. background-color: var(--toolbar-button-background-hover);
  406. border-color: var(--toolbar-button-border-hover);
  407. fill: var(--toolbar-button-foreground-hover);
  408. }
  409. .open .toolbar-button,
  410. .toolbar-button:hover:active {
  411. background-color: var(--toolbar-button-background-active);
  412. border-color: var(--toolbar-button-border-active);
  413. color: var(--toolbar-button-foreground-active);
  414. fill: var(--toolbar-button-foreground-active);
  415. }
  416. .hover-label {
  417. position: absolute;
  418. top: 4px;
  419. inset-inline-start: 36px;
  420. line-height: 16px;
  421. white-space: pre; /* make sure we don't wrap */
  422. background-color: var(--tooltip-background);
  423. color: var(--tooltip-foreground);
  424. padding: 4px 8px;
  425. border: 1px solid var(--tooltip-border);
  426. border-radius: 2px;
  427. visibility: hidden;
  428. pointer-events: none;
  429. /* Put above .dropdown .dropdown-popup, which has z-index: 1000. */
  430. z-index: 1001;
  431. }
  432. /* Show the hover tooltip on non-dropdown buttons. */
  433. .toolbar-button:not(.dropdown-toggle):hover > .hover-label,
  434. .toolbar-button:not(.dropdown-toggle):focus-visible > .hover-label,
  435. /* Show the hover tooltip for dropdown buttons unless its dropdown is open. */
  436. :not(.open) > li > .dropdown-toggle:hover > .hover-label,
  437. :not(.open) > li > .dropdown-toggle:focus-visible > .hover-label {
  438. visibility: visible;
  439. }
  440. .dropdown {
  441. text-align: center;
  442. list-style: none;
  443. margin: 0;
  444. padding: 0;
  445. position: relative;
  446. }
  447. .dropdown li {
  448. margin: 0;
  449. padding: 0;
  450. }
  451. /* Popup */
  452. .dropdown .dropdown-popup {
  453. text-align: start;
  454. position: absolute;
  455. inset-inline-start: 40px;
  456. z-index: 1000;
  457. background-color: var(--popup-background);
  458. visibility: hidden;
  459. border-radius: 4px;
  460. border: 1px solid var(--popup-border);
  461. box-shadow: 0 0 10px 0 var(--popup-shadow);
  462. top: 0;
  463. }
  464. .open > .dropdown-popup {
  465. visibility: visible;
  466. }
  467. .dropdown-arrow {
  468. position: absolute;
  469. height: 24px;
  470. width: 16px;
  471. inset-inline-start: -16px;
  472. background-image: url("chrome://global/skin/reader/RM-Type-Controls-Arrow.svg");
  473. display: block;
  474. -moz-context-properties: fill, stroke;
  475. fill: var(--popup-background);
  476. stroke: var(--opaque-popup-border);
  477. pointer-events: none;
  478. }
  479. .dropdown-arrow:dir(rtl) {
  480. transform: scaleX(-1);
  481. }
  482. /* Align the style dropdown arrow (narrate does its own) */
  483. .style-dropdown .dropdown-arrow {
  484. top: 7px;
  485. }
  486. /* Font style popup */
  487. .radio-button {
  488. /* We visually hide these, but we keep them around so they can be focused
  489. * and changed by interacting with them via the label, or the keyboard, or
  490. * assistive technology.
  491. */
  492. opacity: 0;
  493. pointer-events: none;
  494. position: absolute;
  495. }
  496. .radiorow,
  497. .buttonrow {
  498. display: flex;
  499. align-content: center;
  500. justify-content: center;
  501. }
  502. .content-width-value,
  503. .font-size-value,
  504. .line-height-value {
  505. box-sizing: border-box;
  506. width: 36px;
  507. height: 20px;
  508. line-height: 20px;
  509. display: flex;
  510. justify-content: center;
  511. align-content: center;
  512. margin: auto;
  513. border-radius: 10px;
  514. border: 1px solid var(--font-value-border);
  515. background-color: var(--popup-button-background);
  516. }
  517. .buttonrow > button {
  518. border: 0;
  519. height: 60px;
  520. width: 90px;
  521. background-color: transparent;
  522. background-repeat: no-repeat;
  523. background-position: center;
  524. }
  525. .buttonrow > button:enabled:hover,
  526. .buttonrow > button:enabled:focus-visible {
  527. background-color: var(--popup-button-background-hover);
  528. color: var(--popup-button-foreground-hover);
  529. fill: var(--popup-button-foreground-hover);
  530. }
  531. .buttonrow > button:enabled:hover:active {
  532. background-color: var(--popup-button-background-active);
  533. }
  534. .radiorow:not(:last-child),
  535. .buttonrow:not(:last-child) {
  536. border-bottom: 1px solid var(--popup-line);
  537. }
  538. body.hcm .buttonrow.line-height-buttons {
  539. /* On HCM the .color-scheme-buttons row is hidden, so remove the border from the row above it */
  540. border-bottom: none;
  541. }
  542. .radiorow > label {
  543. position: relative;
  544. box-sizing: border-box;
  545. border-radius: 2px;
  546. border: 2px solid var(--popup-border);
  547. }
  548. .radiorow > label[checked] {
  549. border-color: var(--selected-border);
  550. }
  551. /* For the hover style, we draw a line under the item by means of a
  552. * pseudo-element. Because these items are variable height, and
  553. * because their contents are variable height, position it absolutely,
  554. * and give it a width of 100% (the content width) + 4px for the 2 * 2px
  555. * border width.
  556. */
  557. .radiorow > input[type=radio]:focus-visible + label::after,
  558. .radiorow > label:hover::after {
  559. content: "";
  560. display: block;
  561. border-bottom: 2px solid var(--selected-border);
  562. width: calc(100% + 4px);
  563. position: absolute;
  564. /* to skip the 2 * 2px border + 2px spacing. */
  565. bottom: -6px;
  566. /* Match the start of the 2px border of the element: */
  567. inset-inline-start: -2px;
  568. }
  569. .font-type-buttons > label {
  570. height: 64px;
  571. width: 105px;
  572. /* Slightly more space between these items. */
  573. margin: 10px;
  574. /* Center the Sans-serif / Serif labels */
  575. text-align: center;
  576. background-size: 63px 39px;
  577. background-repeat: no-repeat;
  578. background-position: center 18px;
  579. background-color: var(--popup-button-background);
  580. fill: currentColor;
  581. -moz-context-properties: fill;
  582. /* This mostly matches baselines, but because of differences in font
  583. * baselines between serif and sans-serif, this isn't always enough. */
  584. line-height: 1;
  585. padding-top: 2px;
  586. }
  587. .font-type-buttons > label[checked] {
  588. background-color: var(--selected-background);
  589. }
  590. .sans-serif-button {
  591. font-family: Helvetica, Arial, sans-serif;
  592. background-image: url("chrome://global/skin/reader/RM-Sans-Serif.svg");
  593. }
  594. /* Tweak padding to match the baseline on mac */
  595. :root[platform=macosx] .sans-serif-button {
  596. padding-top: 3px;
  597. }
  598. .serif-button {
  599. font-family: Georgia, "Times New Roman", serif;
  600. background-image: url("chrome://global/skin/reader/RM-Serif.svg");
  601. }
  602. body.hcm .color-scheme-buttons {
  603. /* Disallow selecting themes when HCM is on. */
  604. display: none;
  605. }
  606. .color-scheme-buttons > label {
  607. padding: 12px;
  608. height: 34px;
  609. font-size: 12px;
  610. /* Center the labels horizontally as well as vertically */
  611. display: inline-flex;
  612. align-items: center;
  613. justify-content: center;
  614. /* We want 10px between items, but there's no margin collapsing in flexbox. */
  615. margin: 10px 5px;
  616. }
  617. .color-scheme-buttons > input:first-child + label {
  618. margin-inline-start: 10px;
  619. }
  620. .color-scheme-buttons > label:last-child {
  621. margin-inline-end: 10px;
  622. }
  623. /* Toolbar icons */
  624. .close-button {
  625. background-image: url("chrome://global/skin/icons/close.svg");
  626. }
  627. .style-button {
  628. background-image: url("chrome://global/skin/reader/RM-Type-Controls-24x24.svg");
  629. }
  630. .minus-button {
  631. background-size: 18px 18px;
  632. background-image: url("chrome://global/skin/reader/RM-Minus-24x24.svg");
  633. }
  634. .plus-button {
  635. background-size: 18px 18px;
  636. background-image: url("chrome://global/skin/reader/RM-Plus-24x24.svg");
  637. }
  638. .content-width-minus-button {
  639. background-size: 42px 16px;
  640. background-image: url("chrome://global/skin/reader/RM-Content-Width-Minus-42x16.svg");
  641. }
  642. .content-width-plus-button {
  643. background-size: 44px 16px;
  644. background-image: url("chrome://global/skin/reader/RM-Content-Width-Plus-44x16.svg");
  645. }
  646. .line-height-minus-button {
  647. background-size: 34px 14px;
  648. background-image: url("chrome://global/skin/reader/RM-Line-Height-Minus-38x14.svg");
  649. }
  650. .line-height-plus-button {
  651. background-size: 34px 24px;
  652. background-image: url("chrome://global/skin/reader/RM-Line-Height-Plus-38x24.svg");
  653. }
  654. /* Mirror the line height buttons if the article is RTL. */
  655. .reader-controls[articledir="rtl"] .line-height-minus-button,
  656. .reader-controls[articledir="rtl"] .line-height-plus-button {
  657. transform: scaleX(-1);
  658. }
  659. @media print {
  660. .toolbar {
  661. display: none !important;
  662. }
  663. }
  664. /* Article content */
  665. /* Note that any class names from the original article that we want to match on
  666. * must be added to CLASSES_TO_PRESERVE in ReaderMode.jsm, so that
  667. * Readability.js doesn't strip them out */
  668. .container {
  669. margin: 0 auto;
  670. font-size: var(--font-size);
  671. max-width: var(--content-width);
  672. line-height: var(--line-height);
  673. }
  674. pre {
  675. font-family: inherit;
  676. }
  677. .moz-reader-content {
  678. display: none;
  679. font-size: 1em;
  680. }
  681. @media print {
  682. .moz-reader-content p,
  683. .moz-reader-content code,
  684. .moz-reader-content pre,
  685. .moz-reader-content blockquote,
  686. .moz-reader-content ul,
  687. .moz-reader-content ol,
  688. .moz-reader-content li,
  689. .moz-reader-content figure,
  690. .moz-reader-content .wp-caption {
  691. margin: 0 0 10px !important;
  692. padding: 0 !important;
  693. }
  694. }
  695. .moz-reader-content h1,
  696. .moz-reader-content h2,
  697. .moz-reader-content h3 {
  698. font-weight: bold;
  699. }
  700. .moz-reader-content h1 {
  701. font-size: 1.6em;
  702. line-height: 1.25em;
  703. }
  704. .moz-reader-content h2 {
  705. font-size: 1.2em;
  706. line-height: 1.51em;
  707. }
  708. .moz-reader-content h3 {
  709. font-size: 1em;
  710. line-height: 1.66em;
  711. }
  712. .moz-reader-content a:link {
  713. text-decoration: underline;
  714. font-weight: normal;
  715. }
  716. .moz-reader-content a:link,
  717. .moz-reader-content a:link:hover,
  718. .moz-reader-content a:link:active {
  719. color: var(--link-foreground);
  720. }
  721. .moz-reader-content a:visited {
  722. color: var(--visited-link-foreground);
  723. }
  724. .moz-reader-content * {
  725. max-width: 100%;
  726. height: auto;
  727. }
  728. .moz-reader-content p,
  729. .moz-reader-content p,
  730. .moz-reader-content code,
  731. .moz-reader-content pre,
  732. .moz-reader-content blockquote,
  733. .moz-reader-content ul,
  734. .moz-reader-content ol,
  735. .moz-reader-content li,
  736. .moz-reader-content figure,
  737. .moz-reader-content .wp-caption {
  738. margin: -10px -10px 20px;
  739. padding: 10px;
  740. border-radius: 5px;
  741. }
  742. .moz-reader-content li {
  743. margin-bottom: 0;
  744. }
  745. .moz-reader-content li > ul,
  746. .moz-reader-content li > ol {
  747. margin-bottom: -10px;
  748. }
  749. .moz-reader-content p > img:only-child,
  750. .moz-reader-content p > a:only-child > img:only-child,
  751. .moz-reader-content .wp-caption img,
  752. .moz-reader-content figure img {
  753. display: block;
  754. }
  755. .moz-reader-content img[moz-reader-center] {
  756. margin-inline: auto;
  757. }
  758. .moz-reader-content .caption,
  759. .moz-reader-content .wp-caption-text
  760. .moz-reader-content figcaption {
  761. font-size: 0.9em;
  762. line-height: 1.48em;
  763. font-style: italic;
  764. }
  765. .moz-reader-content pre {
  766. white-space: pre-wrap;
  767. }
  768. .moz-reader-content blockquote {
  769. padding: 0;
  770. padding-inline-start: 16px;
  771. }
  772. .moz-reader-content ul,
  773. .moz-reader-content ol {
  774. padding: 0;
  775. }
  776. .moz-reader-content ul {
  777. padding-inline-start: 30px;
  778. list-style: disc;
  779. }
  780. .moz-reader-content ol {
  781. padding-inline-start: 30px;
  782. }
  783. table,
  784. th,
  785. td {
  786. border: 1px solid currentColor;
  787. border-collapse: collapse;
  788. padding: 6px;
  789. vertical-align: top;
  790. }
  791. table {
  792. margin: 5px;
  793. }
  794. /* Visually hide (but don't display: none) screen reader elements */
  795. .moz-reader-content .visually-hidden,
  796. .moz-reader-content .visuallyhidden,
  797. .moz-reader-content .sr-only {
  798. display: inline-block;
  799. width: 1px;
  800. height: 1px;
  801. margin: -1px;
  802. overflow: hidden;
  803. padding: 0;
  804. border-width: 0;
  805. }
  806. /* Hide elements with common "hidden" class names */
  807. .moz-reader-content .hidden,
  808. .moz-reader-content .invisible {
  809. display: none;
  810. }
  811. /* Enforce wordpress and similar emoji/smileys aren't sized to be full-width,
  812. * see bug 1399616 for context. */
  813. .moz-reader-content img.wp-smiley,
  814. .moz-reader-content img.emoji {
  815. display: inline-block;
  816. border-width: 0;
  817. /* height: auto is implied from '.moz-reader-content *' rule. */
  818. width: 1em;
  819. margin: 0 .07em;
  820. padding: 0;
  821. }
  822. .reader-show-element {
  823. display: initial;
  824. }
  825. /* Provide extra spacing for images that may be aided with accompanying element such as <figcaption> */
  826. .moz-reader-block-img:not(:last-child) {
  827. margin-block-end: 12px;
  828. }
  829. .moz-reader-wide-table {
  830. overflow-x: auto;
  831. display: block;
  832. }
  833. pre code {
  834. background-color: var(--main-background);
  835. border: 1px solid var(--font-color);
  836. display: block;
  837. overflow: auto;
  838. }`;
  839. let NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET;
  840. let selectedNote, anchorElement, maskNoteElement, maskPageElement, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, highlightColor, collapseNoteTimeout, cuttingOuterMode, cuttingMode, cuttingTouchTarget, cuttingPath, cuttingPathIndex, previousContent;
  841. let removedElements = [], removedElementIndex = 0, initScriptContent, pageResources, pageUrl, pageCompressContent, includeInfobar;
  842. globalThis.zip = singlefile.helper.zip;
  843. window.onmessage = async event => {
  844. const message = JSON.parse(event.data);
  845. if (message.method == "init") {
  846. await init(message);
  847. }
  848. if (message.method == "addNote") {
  849. addNote(message);
  850. }
  851. if (message.method == "displayNotes") {
  852. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  853. }
  854. if (message.method == "hideNotes") {
  855. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  856. }
  857. if (message.method == "enableHighlight") {
  858. if (highlightColor) {
  859. document.documentElement.classList.remove(highlightColor + "-mode");
  860. }
  861. highlightColor = message.color;
  862. highlightSelectionMode = true;
  863. document.documentElement.classList.add(message.color + "-mode");
  864. }
  865. if (message.method == "disableHighlight") {
  866. disableHighlight();
  867. highlightSelectionMode = false;
  868. }
  869. if (message.method == "displayHighlights") {
  870. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  871. }
  872. if (message.method == "hideHighlights") {
  873. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  874. }
  875. if (message.method == "enableRemoveHighlights") {
  876. removeHighlightMode = true;
  877. document.documentElement.classList.add("single-file-remove-highlights-mode");
  878. }
  879. if (message.method == "disableRemoveHighlights") {
  880. removeHighlightMode = false;
  881. document.documentElement.classList.remove("single-file-remove-highlights-mode");
  882. }
  883. if (message.method == "enableEditPage") {
  884. document.body.contentEditable = true;
  885. onUpdate(false);
  886. }
  887. if (message.method == "formatPage") {
  888. formatPage(!message.applySystemTheme);
  889. }
  890. if (message.method == "cancelFormatPage") {
  891. cancelFormatPage();
  892. }
  893. if (message.method == "disableEditPage") {
  894. document.body.contentEditable = false;
  895. }
  896. if (message.method == "enableCutInnerPage") {
  897. cuttingMode = true;
  898. document.documentElement.classList.add(CUT_MODE_CLASS);
  899. }
  900. if (message.method == "enableCutOuterPage") {
  901. cuttingOuterMode = true;
  902. document.documentElement.classList.add(CUT_MODE_CLASS);
  903. }
  904. if (message.method == "disableCutInnerPage" || message.method == "disableCutOuterPage") {
  905. if (message.method == "disableCutInnerPage") {
  906. cuttingMode = false;
  907. } else {
  908. cuttingOuterMode = false;
  909. }
  910. document.documentElement.classList.remove(CUT_MODE_CLASS);
  911. resetSelectedElements();
  912. if (cuttingPath) {
  913. unhighlightCutElement();
  914. cuttingPath = null;
  915. }
  916. }
  917. if (message.method == "undoCutPage") {
  918. undoCutPage();
  919. }
  920. if (message.method == "undoAllCutPage") {
  921. while (removedElementIndex) {
  922. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  923. removedElementIndex--;
  924. }
  925. }
  926. if (message.method == "redoCutPage") {
  927. redoCutPage();
  928. }
  929. if (message.method == "getContent") {
  930. onUpdate(true);
  931. includeInfobar = message.includeInfobar;
  932. let content = getContent(message.compressHTML, message.updatedResources);
  933. if (initScriptContent) {
  934. content = content.replace(/<script data-template-shadow-root src.*?<\/script>/g, initScriptContent);
  935. }
  936. if (pageCompressContent) {
  937. if (message.foregroundSave) {
  938. alert("Foreground save not supported for compressed content");
  939. } else {
  940. const viewport = document.head.querySelector("meta[name=viewport]");
  941. window.parent.postMessage(JSON.stringify({
  942. method: "setContent",
  943. content,
  944. title: document.title,
  945. doctype: singlefile.helper.getDoctypeString(document),
  946. url: pageUrl,
  947. viewport: viewport ? viewport.content : null,
  948. compressContent: true
  949. }), "*");
  950. }
  951. } else {
  952. if (message.foregroundSave) {
  953. if (message.filename && message.filename.length) {
  954. const link = document.createElement("a");
  955. link.download = message.filename;
  956. link.href = URL.createObjectURL(new Blob([content], { type: "text/html" }));
  957. link.dispatchEvent(new MouseEvent("click"));
  958. }
  959. return new Promise(resolve => setTimeout(resolve, 1));
  960. } else {
  961. window.parent.postMessage(JSON.stringify({
  962. method: "setContent",
  963. content
  964. }), "*");
  965. }
  966. }
  967. }
  968. if (message.method == "printPage") {
  969. printPage();
  970. }
  971. if (message.method == "displayInfobar") {
  972. singlefile.helper.displayIcon(document, true);
  973. }
  974. };
  975. window.onresize = reflowNotes;
  976. document.ondragover = event => event.preventDefault();
  977. document.ondrop = async event => {
  978. if (event.dataTransfer.files && event.dataTransfer.files[0]) {
  979. const file = event.dataTransfer.files[0];
  980. event.preventDefault();
  981. const content = new TextDecoder().decode(await file.arrayBuffer());
  982. const compressContent = /<html[^>]* data-sfz[^>]*>/i.test(content);
  983. if (compressContent) {
  984. await init({ content: file, compressContent }, { filename: file.name });
  985. } else {
  986. await init({ content }, { filename: file.name });
  987. }
  988. }
  989. };
  990. async function init({ content, password, compressContent }, { filename, reset } = {}) {
  991. await initConstants();
  992. if (compressContent) {
  993. const zipOptions = {
  994. workerScripts: { inflate: ["/lib/single-file-z-worker.js"] }
  995. };
  996. try {
  997. const worker = new Worker(zipOptions.workerScripts.inflate[0]);
  998. worker.terminate();
  999. } catch (error) {
  1000. delete zipOptions.workerScripts;
  1001. }
  1002. zipOptions.useWebWorkers = IS_NOT_SAFARI;
  1003. const { docContent, origDocContent, resources, url } = await singlefile.helper.extract(content, {
  1004. password,
  1005. prompt,
  1006. shadowRootScriptURL: new URL("/lib/single-file-extension-editor-init.js", document.baseURI).href,
  1007. zipOptions
  1008. });
  1009. pageResources = resources;
  1010. pageUrl = url;
  1011. pageCompressContent = true;
  1012. const contentDocument = (new DOMParser()).parseFromString(docContent, "text/html");
  1013. if (detectSavedPage(contentDocument)) {
  1014. await singlefile.helper.display(document, docContent, { disableFramePointerEvents: true });
  1015. const infobarElement = document.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1016. if (infobarElement) {
  1017. infobarElement.remove();
  1018. }
  1019. await initPage();
  1020. let icon;
  1021. const origContentDocument = (new DOMParser()).parseFromString(origDocContent, "text/html");
  1022. const iconElement = origContentDocument.querySelector("link[rel*=icon]");
  1023. if (iconElement) {
  1024. const iconResource = resources.find(resource => resource.filename == iconElement.getAttribute("href"));
  1025. if (iconResource && iconResource.blob) {
  1026. const reader = new FileReader();
  1027. reader.readAsDataURL(iconResource.blob);
  1028. icon = await new Promise((resolve, reject) => {
  1029. reader.addEventListener("load", () => resolve(reader.result), false);
  1030. reader.addEventListener("error", reject, false);
  1031. });
  1032. } else {
  1033. icon = iconElement.href;
  1034. }
  1035. }
  1036. window.parent.postMessage(JSON.stringify({
  1037. method: "onInit",
  1038. title: document.title,
  1039. icon,
  1040. filename,
  1041. reset,
  1042. formatPageEnabled: isProbablyReaderable(document)
  1043. }), "*");
  1044. }
  1045. } else {
  1046. const initScriptContentMatch = content.match(/<script data-template-shadow-root.*<\/script>/);
  1047. if (initScriptContentMatch && initScriptContentMatch[0]) {
  1048. initScriptContent = initScriptContentMatch[0];
  1049. }
  1050. content = content.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=/lib/single-file-extension-editor-init.js></script>");
  1051. const contentDocument = (new DOMParser()).parseFromString(content, "text/html");
  1052. if (detectSavedPage(contentDocument)) {
  1053. if (contentDocument.doctype) {
  1054. if (document.doctype) {
  1055. document.replaceChild(contentDocument.doctype, document.doctype);
  1056. } else {
  1057. document.insertBefore(contentDocument.doctype, document.documentElement);
  1058. }
  1059. } else if (document.doctype) {
  1060. document.doctype.remove();
  1061. }
  1062. const infobarElement = contentDocument.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1063. if (infobarElement) {
  1064. infobarElement.remove();
  1065. }
  1066. contentDocument.querySelectorAll("noscript").forEach(element => {
  1067. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  1068. element.textContent = "";
  1069. });
  1070. contentDocument.querySelectorAll("iframe").forEach(element => {
  1071. const pointerEvents = "pointer-events";
  1072. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1073. element.style.setProperty(pointerEvents, "none", "important");
  1074. });
  1075. document.replaceChild(contentDocument.documentElement, document.documentElement);
  1076. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1077. deserializeShadowRoots(document);
  1078. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1079. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  1080. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1081. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1082. document.documentElement.onmousedown = onMouseDown;
  1083. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1084. document.documentElement.onmouseover = onMouseOver;
  1085. document.documentElement.onmouseout = onMouseOut;
  1086. document.documentElement.onkeydown = onKeyDown;
  1087. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1088. window.onclick = event => event.preventDefault();
  1089. const iconElement = document.querySelector("link[rel*=icon]");
  1090. window.parent.postMessage(JSON.stringify({
  1091. method: "onInit",
  1092. title: document.title,
  1093. icon: iconElement && iconElement.href,
  1094. filename,
  1095. reset,
  1096. formatPageEnabled: isProbablyReaderable(document)
  1097. }), "*");
  1098. }
  1099. }
  1100. }
  1101. async function initPage() {
  1102. document.querySelectorAll("iframe").forEach(element => {
  1103. const pointerEvents = "pointer-events";
  1104. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1105. element.style.setProperty(pointerEvents, "none", "important");
  1106. });
  1107. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1108. deserializeShadowRoots(document);
  1109. reflowNotes();
  1110. await waitResourcesLoad();
  1111. reflowNotes();
  1112. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1113. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  1114. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1115. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1116. document.documentElement.onmousedown = onMouseDown;
  1117. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1118. document.documentElement.onmouseover = onMouseOver;
  1119. document.documentElement.onmouseout = onMouseOut;
  1120. document.documentElement.onkeydown = onKeyDown;
  1121. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1122. window.onclick = event => event.preventDefault();
  1123. }
  1124. async function initConstants() {
  1125. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  1126. minifyText(await ((await fetch("../pages/editor-note-web.css")).text())),
  1127. minifyText(await ((await fetch("../pages/editor-mask-web.css")).text())),
  1128. minifyText(await ((await fetch("../pages/editor-frame-web.css")).text()))
  1129. ]);
  1130. }
  1131. function addNote({ color }) {
  1132. const containerElement = document.createElement(NOTE_TAGNAME);
  1133. const noteElement = document.createElement("div");
  1134. const headerElement = document.createElement("header");
  1135. const blockquoteElement = document.createElement("blockquote");
  1136. const mainElement = document.createElement("textarea");
  1137. const resizeElement = document.createElement("div");
  1138. const removeNoteElement = document.createElement("img");
  1139. const anchorIconElement = document.createElement("img");
  1140. const noteShadow = containerElement.attachShadow({ mode: "open" });
  1141. headerElement.appendChild(anchorIconElement);
  1142. headerElement.appendChild(removeNoteElement);
  1143. blockquoteElement.appendChild(mainElement);
  1144. noteElement.appendChild(headerElement);
  1145. noteElement.appendChild(blockquoteElement);
  1146. noteElement.appendChild(resizeElement);
  1147. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  1148. noteShadow.appendChild(noteElement);
  1149. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  1150. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  1151. blockquoteElement.cite = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[data-single-file-note-refs~=\"" + noteId + "\"])";
  1152. noteElement.classList.add(NOTE_CLASS);
  1153. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  1154. noteElement.classList.add(color);
  1155. noteElement.dataset.color = color;
  1156. mainElement.dir = "auto";
  1157. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  1158. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  1159. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  1160. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  1161. positionX += NOTE_INITIAL_POSITION_X;
  1162. positionY += NOTE_INITIAL_POSITION_Y;
  1163. }
  1164. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  1165. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  1166. resizeElement.className = "note-resize";
  1167. resizeElement.ondragstart = event => event.preventDefault();
  1168. removeNoteElement.className = "note-remove";
  1169. removeNoteElement.src = BUTTON_CLOSE_URL;
  1170. removeNoteElement.ondragstart = event => event.preventDefault();
  1171. anchorIconElement.className = "note-anchor";
  1172. anchorIconElement.src = BUTTON_ANCHOR_URL;
  1173. anchorIconElement.ondragstart = event => event.preventDefault();
  1174. containerElement.dataset.noteId = noteId;
  1175. addNoteRef(document.documentElement, noteId);
  1176. attachNoteListeners(containerElement, true);
  1177. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1178. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1179. selectedNote = noteElement;
  1180. onUpdate(false);
  1181. }
  1182. function attachNoteListeners(containerElement, editable = false) {
  1183. const SELECT_PX_THRESHOLD = 4;
  1184. const COLLAPSING_NOTE_DELAY = 750;
  1185. const noteShadow = containerElement.shadowRoot;
  1186. const noteElement = noteShadow.childNodes[1];
  1187. const headerElement = noteShadow.querySelector("header");
  1188. const mainElement = noteShadow.querySelector("textarea");
  1189. const noteId = containerElement.dataset.noteId;
  1190. const resizeElement = noteShadow.querySelector(".note-resize");
  1191. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  1192. const removeNoteElement = noteShadow.querySelector(".note-remove");
  1193. mainElement.readOnly = !editable;
  1194. if (!editable) {
  1195. anchorIconElement.style.setProperty("display", "none", "important");
  1196. } else {
  1197. anchorIconElement.style.removeProperty("display");
  1198. }
  1199. headerElement.ontouchstart = headerElement.onmousedown = event => {
  1200. if (event.target == headerElement) {
  1201. collapseNoteTimeout = setTimeout(() => {
  1202. noteElement.classList.toggle("note-collapsed");
  1203. hideMaskNote();
  1204. }, COLLAPSING_NOTE_DELAY);
  1205. event.preventDefault();
  1206. const position = getPosition(event);
  1207. const clientX = position.clientX;
  1208. const clientY = position.clientY;
  1209. const boundingRect = noteElement.getBoundingClientRect();
  1210. const deltaX = clientX - boundingRect.left;
  1211. const deltaY = clientY - boundingRect.top;
  1212. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  1213. document.documentElement.style.setProperty("user-select", "none", "important");
  1214. anchorElement = getAnchorElement(containerElement);
  1215. displayMaskNote();
  1216. selectNote(noteElement);
  1217. moveNote(event, deltaX, deltaY);
  1218. movingNoteMode = { event, deltaX, deltaY };
  1219. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  1220. clearTimeout(collapseNoteTimeout);
  1221. if (!movingNoteMode) {
  1222. movingNoteMode = { deltaX, deltaY };
  1223. }
  1224. movingNoteMode.event = event;
  1225. moveNote(event, deltaX, deltaY);
  1226. };
  1227. }
  1228. };
  1229. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  1230. event.preventDefault();
  1231. resizingNoteMode = true;
  1232. selectNote(noteElement);
  1233. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  1234. document.documentElement.style.setProperty("user-select", "none", "important");
  1235. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  1236. event.preventDefault();
  1237. const { clientX, clientY } = getPosition(event);
  1238. const boundingRectNote = noteElement.getBoundingClientRect();
  1239. noteElement.style.width = clientX - boundingRectNote.left + "px";
  1240. noteElement.style.height = clientY - boundingRectNote.top + "px";
  1241. };
  1242. };
  1243. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  1244. event.preventDefault();
  1245. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  1246. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  1247. deleteNoteRef(containerElement, noteId);
  1248. addNoteRef(document.documentElement, noteId);
  1249. }
  1250. onUpdate(false);
  1251. };
  1252. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  1253. event.preventDefault();
  1254. deleteNoteRef(containerElement, noteId);
  1255. containerElement.remove();
  1256. };
  1257. noteElement.onmousedown = () => {
  1258. selectNote(noteElement);
  1259. };
  1260. function moveNote(event, deltaX, deltaY) {
  1261. event.preventDefault();
  1262. const { clientX, clientY } = getPosition(event);
  1263. noteElement.classList.add(NOTE_MOVING_CLASS);
  1264. if (editable) {
  1265. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  1266. deleteNoteRef(containerElement, noteId);
  1267. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  1268. addNoteRef(anchorElement, noteId);
  1269. } else {
  1270. anchorElement = document.documentElement;
  1271. }
  1272. }
  1273. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1274. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  1275. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  1276. noteElement.style.setProperty("position", "fixed");
  1277. displayMaskNote();
  1278. }
  1279. function displayMaskNote() {
  1280. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  1281. hideMaskNote();
  1282. } else {
  1283. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  1284. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  1285. if (selectedNote) {
  1286. maskNoteElement.classList.add(selectedNote.dataset.color);
  1287. }
  1288. maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
  1289. maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
  1290. maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
  1291. maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
  1292. }
  1293. }
  1294. function hideMaskNote() {
  1295. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  1296. if (selectedNote) {
  1297. maskNoteElement.classList.remove(selectedNote.dataset.color);
  1298. }
  1299. }
  1300. function selectNote(noteElement) {
  1301. if (selectedNote) {
  1302. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  1303. maskNoteElement.classList.remove(selectedNote.dataset.color);
  1304. }
  1305. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1306. noteElement.classList.add(noteElement.dataset.color);
  1307. selectedNote = noteElement;
  1308. }
  1309. function getTarget(clientX, clientY) {
  1310. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
  1311. if (!targets.includes(document.documentElement)) {
  1312. targets.push(document.documentElement);
  1313. }
  1314. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  1315. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  1316. if (newTarget == target) {
  1317. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  1318. }
  1319. if (newTarget == target) {
  1320. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  1321. }
  1322. if (newTarget == target) {
  1323. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  1324. }
  1325. target = newTarget;
  1326. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  1327. target = target.parentElement;
  1328. }
  1329. return target;
  1330. }
  1331. function getMatchedParents(target, property) {
  1332. let element = target, matchedParent, parents = [];
  1333. do {
  1334. const boundingRect = element.getBoundingClientRect();
  1335. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  1336. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  1337. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  1338. if (matchedParent) {
  1339. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  1340. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  1341. parents.push(element.parentElement);
  1342. }
  1343. element = element.parentElement;
  1344. }
  1345. } else {
  1346. matchedParent = false;
  1347. }
  1348. } while (matchedParent && element);
  1349. return parents;
  1350. }
  1351. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  1352. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  1353. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  1354. }
  1355. return target;
  1356. }
  1357. }
  1358. function onMouseDown(event) {
  1359. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  1360. event.preventDefault();
  1361. }
  1362. }
  1363. function onMouseUp(event) {
  1364. if (highlightSelectionMode) {
  1365. event.preventDefault();
  1366. highlightSelection();
  1367. onUpdate(false);
  1368. }
  1369. if (removeHighlightMode) {
  1370. event.preventDefault();
  1371. let element = event.target, done;
  1372. while (element && !done) {
  1373. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  1374. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  1375. resetHighlightedElement(highlightedElement);
  1376. onUpdate(false);
  1377. });
  1378. done = true;
  1379. }
  1380. element = element.parentElement;
  1381. }
  1382. }
  1383. if (resizingNoteMode) {
  1384. event.preventDefault();
  1385. resizingNoteMode = false;
  1386. document.documentElement.style.removeProperty("user-select");
  1387. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  1388. document.documentElement.ontouchmove = onTouchMove;
  1389. document.documentElement.onmousemove = null;
  1390. onUpdate(false);
  1391. }
  1392. if (movingNoteMode) {
  1393. event.preventDefault();
  1394. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  1395. movingNoteMode = null;
  1396. document.documentElement.ontouchmove = onTouchMove;
  1397. document.documentElement.onmousemove = null;
  1398. onUpdate(false);
  1399. }
  1400. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  1401. event.preventDefault();
  1402. if (event.ctrlKey) {
  1403. const element = cuttingPath[cuttingPathIndex];
  1404. element.classList.toggle(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  1405. } else {
  1406. validateCutElement(event.shiftKey);
  1407. }
  1408. }
  1409. if (collapseNoteTimeout) {
  1410. clearTimeout(collapseNoteTimeout);
  1411. collapseNoteTimeout = null;
  1412. }
  1413. }
  1414. function onMouseOver(event) {
  1415. if (cuttingMode || cuttingOuterMode) {
  1416. const target = event.target;
  1417. if (target.classList) {
  1418. let ancestorFound;
  1419. document.querySelectorAll("." + (cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS)).forEach(element => {
  1420. if (element == target || isAncestor(element, target) || isAncestor(target, element)) {
  1421. ancestorFound = element;
  1422. }
  1423. });
  1424. if (ancestorFound) {
  1425. cuttingPath = [ancestorFound];
  1426. } else {
  1427. cuttingPath = getParents(event.target);
  1428. }
  1429. cuttingPathIndex = 0;
  1430. highlightCutElement();
  1431. }
  1432. }
  1433. }
  1434. function onMouseOut() {
  1435. if (cuttingMode || cuttingOuterMode) {
  1436. if (cuttingPath) {
  1437. unhighlightCutElement();
  1438. cuttingPath = null;
  1439. }
  1440. }
  1441. }
  1442. function onTouchMove(event) {
  1443. if (cuttingMode || cuttingOuterMode) {
  1444. event.preventDefault();
  1445. const { clientX, clientY } = getPosition(event);
  1446. const target = document.elementFromPoint(clientX, clientY);
  1447. if (cuttingTouchTarget != target) {
  1448. onMouseOut();
  1449. if (target) {
  1450. cuttingTouchTarget = target;
  1451. onMouseOver({ target });
  1452. }
  1453. }
  1454. }
  1455. }
  1456. function onKeyDown(event) {
  1457. if (cuttingMode || cuttingOuterMode) {
  1458. if (event.code == "Tab") {
  1459. if (cuttingPath) {
  1460. const delta = event.shiftKey ? -1 : 1;
  1461. let element = cuttingPath[cuttingPathIndex];
  1462. let nextElement = cuttingPath[cuttingPathIndex + delta];
  1463. if (nextElement) {
  1464. let pathIndex = cuttingPathIndex + delta;
  1465. while (
  1466. nextElement &&
  1467. (
  1468. (delta == 1 &&
  1469. element.getBoundingClientRect().width >= nextElement.getBoundingClientRect().width &&
  1470. element.getBoundingClientRect().height >= nextElement.getBoundingClientRect().height) ||
  1471. (delta == -1 &&
  1472. element.getBoundingClientRect().width <= nextElement.getBoundingClientRect().width &&
  1473. element.getBoundingClientRect().height <= nextElement.getBoundingClientRect().height))) {
  1474. pathIndex += delta;
  1475. nextElement = cuttingPath[pathIndex];
  1476. }
  1477. if (nextElement && nextElement.classList && nextElement != document.body && nextElement != document.documentElement) {
  1478. unhighlightCutElement();
  1479. cuttingPathIndex = pathIndex;
  1480. highlightCutElement();
  1481. }
  1482. }
  1483. }
  1484. event.preventDefault();
  1485. }
  1486. if (event.code == "Space") {
  1487. if (cuttingPath) {
  1488. if (event.ctrlKey) {
  1489. const element = cuttingPath[cuttingPathIndex];
  1490. element.classList.add(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  1491. } else {
  1492. validateCutElement(event.shiftKey);
  1493. }
  1494. event.preventDefault();
  1495. }
  1496. }
  1497. if (event.code == "Escape") {
  1498. resetSelectedElements();
  1499. event.preventDefault();
  1500. }
  1501. if (event.key.toLowerCase() == "z" && event.ctrlKey) {
  1502. if (event.shiftKey) {
  1503. redoCutPage();
  1504. } else {
  1505. undoCutPage();
  1506. }
  1507. event.preventDefault();
  1508. }
  1509. }
  1510. if (event.key.toLowerCase() == "s" && event.ctrlKey) {
  1511. window.parent.postMessage(JSON.stringify({ "method": "savePage" }), "*");
  1512. event.preventDefault();
  1513. }
  1514. if (event.key.toLowerCase() == "p" && event.ctrlKey) {
  1515. printPage();
  1516. event.preventDefault();
  1517. }
  1518. }
  1519. function printPage() {
  1520. unhighlightCutElement();
  1521. resetSelectedElements();
  1522. window.print();
  1523. }
  1524. function highlightCutElement() {
  1525. const element = cuttingPath[cuttingPathIndex];
  1526. element.classList.add(cuttingMode ? CUT_HOVER_CLASS : CUT_OUTER_HOVER_CLASS);
  1527. }
  1528. function unhighlightCutElement() {
  1529. if (cuttingPath) {
  1530. const element = cuttingPath[cuttingPathIndex];
  1531. element.classList.remove(CUT_HOVER_CLASS);
  1532. element.classList.remove(CUT_OUTER_HOVER_CLASS);
  1533. }
  1534. }
  1535. function disableHighlight(doc = document) {
  1536. if (highlightColor) {
  1537. doc.documentElement.classList.remove(highlightColor + "-mode");
  1538. }
  1539. }
  1540. function undoCutPage() {
  1541. if (removedElementIndex) {
  1542. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  1543. removedElementIndex--;
  1544. }
  1545. }
  1546. function redoCutPage() {
  1547. if (removedElementIndex < removedElements.length) {
  1548. removedElements[removedElementIndex].forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  1549. removedElementIndex++;
  1550. }
  1551. }
  1552. function validateCutElement(invert) {
  1553. const selectedElement = cuttingPath[cuttingPathIndex];
  1554. if ((cuttingMode && !invert) || (cuttingOuterMode && invert)) {
  1555. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  1556. const elementsRemoved = [selectedElement].concat(...document.querySelectorAll("." + CUT_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS + " *,." + CUT_HOVER_CLASS + " *"));
  1557. resetSelectedElements();
  1558. if (elementsRemoved.length) {
  1559. elementsRemoved.forEach(element => {
  1560. unhighlightCutElement();
  1561. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  1562. resetAnchorNote(element);
  1563. } else {
  1564. element.classList.add(REMOVED_CONTENT_CLASS);
  1565. }
  1566. });
  1567. removedElements[removedElementIndex] = elementsRemoved;
  1568. removedElementIndex++;
  1569. removedElements.length = removedElementIndex;
  1570. onUpdate(false);
  1571. }
  1572. }
  1573. } else {
  1574. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  1575. const elements = [];
  1576. const searchSelector = "*:not(style):not(meta):not(." + REMOVED_CONTENT_CLASS + ")";
  1577. const elementsKept = [selectedElement].concat(...document.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS));
  1578. document.body.querySelectorAll(searchSelector).forEach(element => {
  1579. let removed = true;
  1580. elementsKept.forEach(elementKept => removed = removed && (elementKept != element && !isAncestor(elementKept, element) && !isAncestor(element, elementKept)));
  1581. if (removed) {
  1582. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  1583. resetAnchorNote(element);
  1584. } else {
  1585. elements.push(element);
  1586. }
  1587. }
  1588. });
  1589. elementsKept.forEach(elementKept => {
  1590. unhighlightCutElement();
  1591. const elementKeptRect = elementKept.getBoundingClientRect();
  1592. elementKept.querySelectorAll(searchSelector).forEach(descendant => {
  1593. const descendantRect = descendant.getBoundingClientRect();
  1594. if (descendantRect.width && descendantRect.height && (
  1595. descendantRect.left + descendantRect.width < elementKeptRect.left ||
  1596. descendantRect.right > elementKeptRect.right + elementKeptRect.width ||
  1597. descendantRect.top + descendantRect.height < elementKeptRect.top ||
  1598. descendantRect.bottom > elementKeptRect.bottom + elementKeptRect.height
  1599. )) {
  1600. elements.push(descendant);
  1601. }
  1602. });
  1603. });
  1604. resetSelectedElements();
  1605. if (elements.length) {
  1606. elements.forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  1607. removedElements[removedElementIndex] = elements;
  1608. removedElementIndex++;
  1609. removedElements.length = removedElementIndex;
  1610. onUpdate(false);
  1611. }
  1612. }
  1613. }
  1614. }
  1615. function resetSelectedElements(doc = document) {
  1616. doc.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS).forEach(element => {
  1617. element.classList.remove(CUT_OUTER_SELECTED_CLASS);
  1618. element.classList.remove(CUT_SELECTED_CLASS);
  1619. });
  1620. }
  1621. function anchorNote(event, noteElement, deltaX, deltaY) {
  1622. event.preventDefault();
  1623. const { clientX, clientY } = getPosition(event);
  1624. document.documentElement.style.removeProperty("user-select");
  1625. noteElement.classList.remove(NOTE_MOVING_CLASS);
  1626. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  1627. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  1628. maskNoteElement.classList.remove(noteElement.dataset.color);
  1629. const headerElement = noteElement.querySelector("header");
  1630. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  1631. let currentElement = anchorElement;
  1632. let positionedElement;
  1633. while (currentElement.parentElement && !positionedElement) {
  1634. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  1635. const currentElementStyle = getComputedStyle(currentElement);
  1636. if (currentElementStyle.position != "static") {
  1637. positionedElement = currentElement;
  1638. }
  1639. }
  1640. currentElement = currentElement.parentElement;
  1641. }
  1642. if (!positionedElement) {
  1643. positionedElement = document.documentElement;
  1644. }
  1645. const containerElement = noteElement.getRootNode().host;
  1646. if (positionedElement == document.documentElement) {
  1647. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  1648. firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
  1649. } else {
  1650. positionedElement.appendChild(containerElement);
  1651. }
  1652. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  1653. const stylePositionedElement = window.getComputedStyle(positionedElement);
  1654. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  1655. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  1656. noteElement.style.setProperty("position", "absolute");
  1657. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  1658. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  1659. }
  1660. function resetAnchorNote(containerElement) {
  1661. const noteId = containerElement.dataset.noteId;
  1662. const noteElement = containerElement.shadowRoot.childNodes[1];
  1663. noteElement.classList.remove(NOTE_ANCHORED_CLASS);
  1664. deleteNoteRef(containerElement, noteId);
  1665. addNoteRef(document.documentElement, noteId);
  1666. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1667. }
  1668. function getPosition(event) {
  1669. if (event.touches && event.touches.length) {
  1670. const touch = event.touches[0];
  1671. return touch;
  1672. } else {
  1673. return event;
  1674. }
  1675. }
  1676. function highlightSelection() {
  1677. let highlightId = 0;
  1678. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  1679. highlightId++;
  1680. const selection = window.getSelection();
  1681. const highlightedNodes = new Set();
  1682. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  1683. const range = selection.getRangeAt(indexRange);
  1684. if (!range.collapsed) {
  1685. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  1686. let contentText = range.startContainer.splitText(range.startOffset);
  1687. contentText = contentText.splitText(range.endOffset);
  1688. addHighLightedNode(contentText.previousSibling);
  1689. } else {
  1690. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  1691. let highlightNodes;
  1692. while (treeWalker.nextNode()) {
  1693. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  1694. addHighLightedNode(treeWalker.currentNode);
  1695. }
  1696. if (treeWalker.currentNode == range.startContainer) {
  1697. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  1698. const contentText = range.startContainer.splitText(range.startOffset);
  1699. treeWalker.nextNode();
  1700. addHighLightedNode(contentText);
  1701. } else {
  1702. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  1703. }
  1704. highlightNodes = true;
  1705. }
  1706. if (treeWalker.currentNode == range.endContainer) {
  1707. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  1708. const contentText = range.endContainer.splitText(range.endOffset);
  1709. treeWalker.nextNode();
  1710. addHighLightedNode(contentText.previousSibling);
  1711. } else {
  1712. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  1713. }
  1714. highlightNodes = false;
  1715. }
  1716. }
  1717. range.collapse();
  1718. }
  1719. }
  1720. }
  1721. highlightedNodes.forEach(node => highlightNode(node));
  1722. function addHighLightedNode(node) {
  1723. if (node && node.textContent.trim()) {
  1724. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  1725. highlightedNodes.add(node.parentElement);
  1726. } else {
  1727. highlightedNodes.add(node);
  1728. }
  1729. }
  1730. }
  1731. function highlightNode(node) {
  1732. if (node.nodeType == node.ELEMENT_NODE) {
  1733. resetHighlightedElement(node);
  1734. node.classList.add(HIGHLIGHT_CLASS);
  1735. node.classList.add(highlightColor);
  1736. node.dataset.singlefileHighlightId = highlightId;
  1737. } else if (node.parentElement) {
  1738. highlightTextNode(node);
  1739. }
  1740. }
  1741. function highlightTextNode(node) {
  1742. const spanElement = document.createElement("span");
  1743. spanElement.classList.add(HIGHLIGHT_CLASS);
  1744. spanElement.classList.add(highlightColor);
  1745. spanElement.textContent = node.textContent;
  1746. spanElement.dataset.singlefileHighlightId = highlightId;
  1747. node.parentNode.replaceChild(spanElement, node);
  1748. return spanElement;
  1749. }
  1750. }
  1751. function getParents(element) {
  1752. const path = [];
  1753. while (element) {
  1754. path.push(element);
  1755. element = element.parentElement;
  1756. }
  1757. return path;
  1758. }
  1759. function formatPage(applySystemTheme) {
  1760. if (pageCompressContent) {
  1761. serializeShadowRoots(document);
  1762. previousContent = document.documentElement.cloneNode(true);
  1763. deserializeShadowRoots(document);
  1764. } else {
  1765. previousContent = getContent(false, []);
  1766. }
  1767. const shadowRoots = {};
  1768. const classesToPreserve = ["single-file-highlight", "single-file-highlight-yellow", "single-file-highlight-green", "single-file-highlight-pink", "single-file-highlight-blue"];
  1769. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1770. shadowRoots[containerElement.dataset.noteId] = containerElement.shadowRoot;
  1771. const className = "singlefile-note-id-" + containerElement.dataset.noteId;
  1772. containerElement.classList.add(className);
  1773. classesToPreserve.push(className);
  1774. });
  1775. const article = new Readability(document, { classesToPreserve }).parse();
  1776. removedElements = [];
  1777. removedElementIndex = 0;
  1778. document.body.innerHTML = "";
  1779. const domParser = new DOMParser();
  1780. const doc = domParser.parseFromString(article.content, "text/html");
  1781. const contentEditable = document.body.contentEditable;
  1782. document.documentElement.replaceChild(doc.body, document.body);
  1783. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1784. const noteId = (Array.from(containerElement.classList).find(className => /singlefile-note-id-\d+/.test(className))).split("singlefile-note-id-")[1];
  1785. containerElement.classList.remove("singlefile-note-id-" + noteId);
  1786. containerElement.dataset.noteId = noteId;
  1787. if (!containerElement.shadowRoot) {
  1788. containerElement.attachShadow({ mode: "open" });
  1789. containerElement.shadowRoot.appendChild(shadowRoots[noteId]);
  1790. }
  1791. });
  1792. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => shadowRoots[containerElement.dataset.noteId].childNodes.forEach(node => containerElement.shadowRoot.appendChild(node)));
  1793. document.body.contentEditable = contentEditable;
  1794. document.head.querySelectorAll("style").forEach(styleElement => styleElement.remove());
  1795. const styleElement = document.createElement("style");
  1796. styleElement.textContent = STYLE_FORMATTED_PAGE;
  1797. document.head.appendChild(styleElement);
  1798. document.body.classList.add("moz-reader-content");
  1799. document.body.classList.add("content-width6");
  1800. document.body.classList.add("reader-show-element");
  1801. document.body.classList.add("sans-serif");
  1802. document.body.classList.add("container");
  1803. document.body.classList.add("line-height4");
  1804. const prefersColorSchemeDark = matchMedia("(prefers-color-scheme: dark)");
  1805. if (applySystemTheme && prefersColorSchemeDark && prefersColorSchemeDark.matches) {
  1806. document.body.classList.add("dark");
  1807. }
  1808. document.body.style.setProperty("display", "block");
  1809. document.body.style.setProperty("padding", "24px");
  1810. const titleElement = document.createElement("h1");
  1811. titleElement.classList.add("reader-title");
  1812. titleElement.textContent = article.title;
  1813. document.body.insertBefore(titleElement, document.body.firstChild);
  1814. document.querySelectorAll("a[href]").forEach(element => {
  1815. const href = element.getAttribute("href").trim();
  1816. if (href.startsWith(document.baseURI + "#")) {
  1817. element.setAttribute("href", href.substring(document.baseURI.length));
  1818. }
  1819. });
  1820. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  1821. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1822. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1823. reflowNotes();
  1824. onUpdate(false);
  1825. }
  1826. async function cancelFormatPage() {
  1827. if (previousContent) {
  1828. const contentEditable = document.body.contentEditable;
  1829. if (pageCompressContent) {
  1830. document.replaceChild(previousContent, document.documentElement);
  1831. deserializeShadowRoots(document);
  1832. await initPage();
  1833. } else {
  1834. await init({ content: previousContent }, { reset: true });
  1835. }
  1836. document.body.contentEditable = contentEditable;
  1837. onUpdate(false);
  1838. previousContent = null;
  1839. }
  1840. }
  1841. function getContent(compressHTML, updatedResources) {
  1842. unhighlightCutElement();
  1843. serializeShadowRoots(document);
  1844. const doc = document.cloneNode(true);
  1845. disableHighlight(doc);
  1846. resetSelectedElements(doc);
  1847. deserializeShadowRoots(doc);
  1848. deserializeShadowRoots(document);
  1849. doc.documentElement.classList.remove(CUT_MODE_CLASS);
  1850. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  1851. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  1852. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  1853. });
  1854. doc.querySelectorAll("." + MASK_CLASS + ", " + singlefile.helper.INFOBAR_TAGNAME + ", ." + REMOVED_CONTENT_CLASS).forEach(maskElement => maskElement.remove());
  1855. if (includeInfobar) {
  1856. singlefile.helper.appendInfobar(doc, singlefile.helper.extractInfobarData(doc));
  1857. }
  1858. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  1859. doc.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  1860. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  1861. if (noteElement) {
  1862. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  1863. }
  1864. const mainElement = templateElement.querySelector("textarea");
  1865. if (mainElement) {
  1866. mainElement.textContent = mainElement.value;
  1867. }
  1868. });
  1869. doc.querySelectorAll("iframe").forEach(element => {
  1870. const pointerEvents = "pointer-events";
  1871. element.style.setProperty(pointerEvents, element.style.getPropertyValue("-sf-" + pointerEvents), element.style.getPropertyPriority("-sf-" + pointerEvents));
  1872. element.style.removeProperty("-sf-" + pointerEvents);
  1873. });
  1874. doc.body.removeAttribute("contentEditable");
  1875. const newResources = Object.keys(updatedResources).filter(url => updatedResources[url].type == "stylesheet").map(url => updatedResources[url]);
  1876. newResources.forEach(resource => {
  1877. const element = doc.createElement("style");
  1878. doc.body.appendChild(element);
  1879. element.textContent = resource.content;
  1880. });
  1881. if (pageCompressContent) {
  1882. const pageFilename = pageResources
  1883. .filter(resource => resource.filename.endsWith("index.html"))
  1884. .sort((resourceLeft, resourceRight) => resourceLeft.filename.length - resourceRight.filename.length)[0].filename;
  1885. const resources = pageResources.filter(resource => resource.parentResources.includes(pageFilename));
  1886. doc.querySelectorAll("[src]").forEach(element => resources.forEach(resource => {
  1887. if (element.src == resource.content) {
  1888. element.src = resource.name;
  1889. }
  1890. }));
  1891. let content = singlefile.helper.serialize(doc, compressHTML);
  1892. resources.sort((resourceLeft, resourceRight) => resourceRight.content.length - resourceLeft.content.length);
  1893. resources.forEach(resource => content = content.replaceAll(resource.content, resource.name));
  1894. return content + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  1895. } else {
  1896. return singlefile.helper.serialize(doc, compressHTML) + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  1897. }
  1898. }
  1899. function onUpdate(saved) {
  1900. window.parent.postMessage(JSON.stringify({ "method": "onUpdate", saved }), "*");
  1901. }
  1902. function waitResourcesLoad() {
  1903. return new Promise(resolve => {
  1904. let counterMutations = 0;
  1905. const done = () => {
  1906. observer.disconnect();
  1907. resolve();
  1908. };
  1909. let timeoutInit = setTimeout(done, 100);
  1910. const observer = new MutationObserver(() => {
  1911. if (counterMutations < 20) {
  1912. counterMutations++;
  1913. clearTimeout(timeoutInit);
  1914. timeoutInit = setTimeout(done, 100);
  1915. } else {
  1916. done();
  1917. }
  1918. });
  1919. observer.observe(document, { subtree: true, childList: true, attributes: true });
  1920. });
  1921. }
  1922. function reflowNotes() {
  1923. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1924. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  1925. const noteBoundingRect = noteElement.getBoundingClientRect();
  1926. const anchorElement = getAnchorElement(containerElement);
  1927. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  1928. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  1929. const minX = anchorBoundingRect.x;
  1930. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  1931. const minY = anchorBoundingRect.y;
  1932. let left = parseInt(noteElement.style.getPropertyValue("left"));
  1933. let top = parseInt(noteElement.style.getPropertyValue("top"));
  1934. if (noteBoundingRect.x > maxX) {
  1935. left -= noteBoundingRect.x - maxX;
  1936. }
  1937. if (noteBoundingRect.x < minX) {
  1938. left += minX - noteBoundingRect.x;
  1939. }
  1940. if (noteBoundingRect.y > maxY) {
  1941. top -= noteBoundingRect.y - maxY;
  1942. }
  1943. if (noteBoundingRect.y < minY) {
  1944. top += minY - noteBoundingRect.y;
  1945. }
  1946. noteElement.style.setProperty("position", "absolute");
  1947. noteElement.style.setProperty("left", left + "px");
  1948. noteElement.style.setProperty("top", top + "px");
  1949. });
  1950. }
  1951. function resetHighlightedElement(element) {
  1952. element.classList.remove(HIGHLIGHT_CLASS);
  1953. element.classList.remove("single-file-highlight-yellow");
  1954. element.classList.remove("single-file-highlight-pink");
  1955. element.classList.remove("single-file-highlight-blue");
  1956. element.classList.remove("single-file-highlight-green");
  1957. delete element.dataset.singlefileHighlightId;
  1958. }
  1959. function serializeShadowRoots(node) {
  1960. node.querySelectorAll("*").forEach(element => {
  1961. const shadowRoot = getShadowRoot(element);
  1962. if (shadowRoot) {
  1963. serializeShadowRoots(shadowRoot);
  1964. const templateElement = document.createElement("template");
  1965. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  1966. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  1967. element.appendChild(templateElement);
  1968. }
  1969. });
  1970. }
  1971. function deserializeShadowRoots(node) {
  1972. node.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(element => {
  1973. if (element.parentElement) {
  1974. let shadowRoot = getShadowRoot(element.parentElement);
  1975. if (shadowRoot) {
  1976. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  1977. element.remove();
  1978. } else {
  1979. try {
  1980. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  1981. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  1982. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  1983. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  1984. } catch (error) {
  1985. // ignored
  1986. }
  1987. }
  1988. if (shadowRoot) {
  1989. deserializeShadowRoots(shadowRoot);
  1990. }
  1991. }
  1992. });
  1993. }
  1994. function getMaskElement(className, containerClassName) {
  1995. let maskElement = document.documentElement.querySelector("." + className);
  1996. if (!maskElement) {
  1997. maskElement = document.createElement("div");
  1998. const maskContainerElement = document.createElement("div");
  1999. if (containerClassName) {
  2000. maskContainerElement.classList.add(containerClassName);
  2001. }
  2002. maskContainerElement.classList.add(MASK_CLASS);
  2003. const firstNote = document.querySelector(NOTE_TAGNAME);
  2004. if (firstNote && firstNote.parentElement == document.documentElement) {
  2005. document.documentElement.insertBefore(maskContainerElement, firstNote);
  2006. } else {
  2007. document.documentElement.appendChild(maskContainerElement);
  2008. }
  2009. maskElement.classList.add(className);
  2010. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  2011. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  2012. maskShadow.appendChild(maskElement);
  2013. return maskElement;
  2014. }
  2015. }
  2016. function getEmbedScript() {
  2017. return minifyText(`(() => {
  2018. document.currentScript.remove();
  2019. const processNode = node => {
  2020. node.querySelectorAll("template[${SHADOWROOT_ATTRIBUTE_NAME}]").forEach(element=>{
  2021. let shadowRoot = getShadowRoot(element.parentElement);
  2022. if (!shadowRoot) {
  2023. try {
  2024. shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOWROOT_ATTRIBUTE_NAME}")});
  2025. shadowRoot.innerHTML = element.innerHTML;
  2026. element.remove();
  2027. } catch (error) {}
  2028. if (shadowRoot) {
  2029. processNode(shadowRoot);
  2030. }
  2031. }
  2032. })
  2033. };
  2034. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  2035. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  2036. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  2037. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  2038. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  2039. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  2040. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  2041. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  2042. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  2043. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  2044. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  2045. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  2046. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  2047. const REMOVED_CONTENT_CLASS = ${JSON.stringify(REMOVED_CONTENT_CLASS)};
  2048. const reflowNotes = ${minifyText(reflowNotes.toString())};
  2049. const addNoteRef = ${minifyText(addNoteRef.toString())};
  2050. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  2051. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  2052. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  2053. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  2054. const getMaskElement = ${minifyText(getMaskElement.toString())};
  2055. const getStyleElement = ${minifyText(getStyleElement.toString())};
  2056. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  2057. const anchorNote = ${minifyText(anchorNote.toString())};
  2058. const getPosition = ${minifyText(getPosition.toString())};
  2059. const onMouseUp = ${minifyText(onMouseUp.toString())};
  2060. const getShadowRoot = ${minifyText(getShadowRoot.toString())};
  2061. const waitResourcesLoad = ${minifyText(waitResourcesLoad.toString())};
  2062. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  2063. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  2064. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout, cuttingMode, cuttingOuterMode;
  2065. window.onresize = reflowNotes;
  2066. window.onUpdate = () => {};
  2067. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  2068. processNode(document);
  2069. reflowNotes();
  2070. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  2071. if (document.documentElement.dataset.sfz !== undefined) {
  2072. waitResourcesLoad().then(reflowNotes);
  2073. }
  2074. })()`);
  2075. }
  2076. function getStyleElement(stylesheet) {
  2077. const linkElement = document.createElement("style");
  2078. linkElement.textContent = stylesheet;
  2079. return linkElement;
  2080. }
  2081. function getAnchorElement(containerElement) {
  2082. return document.querySelector("[data-single-file-note-refs~=\"" + containerElement.dataset.noteId + "\"]") || document.documentElement;
  2083. }
  2084. function addNoteRef(anchorElement, noteId) {
  2085. const noteRefs = getNoteRefs(anchorElement);
  2086. noteRefs.push(noteId);
  2087. setNoteRefs(anchorElement, noteRefs);
  2088. }
  2089. function deleteNoteRef(containerElement, noteId) {
  2090. const anchorElement = getAnchorElement(containerElement);
  2091. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  2092. if (noteRefs.length) {
  2093. setNoteRefs(anchorElement, noteRefs);
  2094. } else {
  2095. delete anchorElement.dataset.singleFileNoteRefs;
  2096. }
  2097. }
  2098. function getNoteRefs(anchorElement) {
  2099. return anchorElement.dataset.singleFileNoteRefs ? anchorElement.dataset.singleFileNoteRefs.split(" ") : [];
  2100. }
  2101. function setNoteRefs(anchorElement, noteRefs) {
  2102. anchorElement.dataset.singleFileNoteRefs = noteRefs.join(" ");
  2103. }
  2104. function minifyText(text) {
  2105. return text.replace(/[\n\t\s]+/g, " ");
  2106. }
  2107. function isAncestor(element, otherElement) {
  2108. return otherElement.parentElement && (element == otherElement.parentElement || isAncestor(element, otherElement.parentElement));
  2109. }
  2110. function getShadowRoot(element) {
  2111. const chrome = window.chrome;
  2112. if (element.openOrClosedShadowRoot) {
  2113. return element.openOrClosedShadowRoot;
  2114. } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
  2115. try {
  2116. return chrome.dom.openOrClosedShadowRoot(element);
  2117. } catch (error) {
  2118. return element.shadowRoot;
  2119. }
  2120. } else {
  2121. return element.shadowRoot;
  2122. }
  2123. }
  2124. function detectSavedPage(document) {
  2125. const firstDocumentChild = document.documentElement.firstChild;
  2126. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  2127. (firstDocumentChild.textContent.includes(COMMENT_HEADER) || firstDocumentChild.textContent.includes(COMMENT_HEADER_LEGACY));
  2128. }
  2129. })(typeof globalThis == "object" ? globalThis : window);
  2130. })();