single-file-extension-editor.js 84 KB

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