single-file-extension-editor.js 83 KB

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