single-file-extension-editor.js 83 KB

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