content-ui-editor-web.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global globalThis, window, document, fetch, DOMParser, getComputedStyle, setTimeout, clearTimeout, NodeFilter, Readability, isProbablyReaderable, matchMedia, TextDecoder, Node, URL, MouseEvent, Blob, prompt, MutationObserver, FileReader, Worker, navigator */
  24. (globalThis => {
  25. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  26. const singlefile = globalThis.singlefile;
  27. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  28. 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";
  29. 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==";
  30. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  31. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  32. const SCRIPT_OPTIONS = "data-single-file-options";
  33. const NOTE_TAGNAME = "single-file-note";
  34. const NOTE_CLASS = "note";
  35. const NOTE_MASK_CLASS = "note-mask";
  36. const NOTE_HIDDEN_CLASS = "note-hidden";
  37. const NOTE_ANCHORED_CLASS = "note-anchored";
  38. const NOTE_SELECTED_CLASS = "note-selected";
  39. const NOTE_MOVING_CLASS = "note-moving";
  40. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  41. const PAGE_MASK_CLASS = "page-mask";
  42. const MASK_CLASS = "single-file-mask";
  43. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  44. const HIGHLIGHT_CLASS = "single-file-highlight";
  45. const HIGHLIGHTS_STYLESHEET_CLASS = "single-file-highlights-stylesheet";
  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. initEventListeners();
  844. new MutationObserver(initEventListeners).observe(document, { childList: true });
  845. function initEventListeners() {
  846. window.onmessage = async event => {
  847. const message = JSON.parse(event.data);
  848. if (message.method == "init") {
  849. await init(message);
  850. }
  851. if (message.method == "addNote") {
  852. addNote(message);
  853. }
  854. if (message.method == "displayNotes") {
  855. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  856. }
  857. if (message.method == "hideNotes") {
  858. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  859. }
  860. if (message.method == "enableHighlight") {
  861. if (highlightColor) {
  862. document.documentElement.classList.remove(highlightColor + "-mode");
  863. }
  864. highlightColor = message.color;
  865. highlightSelectionMode = true;
  866. document.documentElement.classList.add(message.color + "-mode");
  867. }
  868. if (message.method == "disableHighlight") {
  869. disableHighlight();
  870. highlightSelectionMode = false;
  871. }
  872. if (message.method == "displayHighlights") {
  873. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  874. }
  875. if (message.method == "hideHighlights") {
  876. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  877. }
  878. if (message.method == "enableRemoveHighlights") {
  879. removeHighlightMode = true;
  880. document.documentElement.classList.add("single-file-remove-highlights-mode");
  881. }
  882. if (message.method == "disableRemoveHighlights") {
  883. removeHighlightMode = false;
  884. document.documentElement.classList.remove("single-file-remove-highlights-mode");
  885. }
  886. if (message.method == "enableEditPage") {
  887. document.body.contentEditable = true;
  888. onUpdate(false);
  889. }
  890. if (message.method == "formatPage") {
  891. formatPage(!message.applySystemTheme);
  892. }
  893. if (message.method == "cancelFormatPage") {
  894. cancelFormatPage();
  895. }
  896. if (message.method == "disableEditPage") {
  897. document.body.contentEditable = false;
  898. }
  899. if (message.method == "enableCutInnerPage") {
  900. cuttingMode = true;
  901. document.documentElement.classList.add(CUT_MODE_CLASS);
  902. }
  903. if (message.method == "enableCutOuterPage") {
  904. cuttingOuterMode = true;
  905. document.documentElement.classList.add(CUT_MODE_CLASS);
  906. }
  907. if (message.method == "disableCutInnerPage" || message.method == "disableCutOuterPage") {
  908. if (message.method == "disableCutInnerPage") {
  909. cuttingMode = false;
  910. } else {
  911. cuttingOuterMode = false;
  912. }
  913. document.documentElement.classList.remove(CUT_MODE_CLASS);
  914. resetSelectedElements();
  915. if (cuttingPath) {
  916. unhighlightCutElement();
  917. cuttingPath = null;
  918. }
  919. }
  920. if (message.method == "undoCutPage") {
  921. undoCutPage();
  922. }
  923. if (message.method == "undoAllCutPage") {
  924. while (removedElementIndex) {
  925. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  926. removedElementIndex--;
  927. }
  928. }
  929. if (message.method == "redoCutPage") {
  930. redoCutPage();
  931. }
  932. if (message.method == "getContent") {
  933. onUpdate(true);
  934. includeInfobar = message.includeInfobar;
  935. let content = getContent(message.compressHTML, message.updatedResources);
  936. if (initScriptContent) {
  937. content = content.replace(/<script data-template-shadow-root src.*?<\/script>/g, initScriptContent);
  938. }
  939. let filename;
  940. const pageOptions = loadOptionsFromPage(document);
  941. if (pageOptions) {
  942. pageOptions.backgroundSave = message.backgroundSave;
  943. pageOptions.saveDate = new Date(pageOptions.saveDate);
  944. pageOptions.visitDate = new Date(pageOptions.visitDate);
  945. filename = await singlefile.helper.formatFilename(content, document, pageOptions);
  946. }
  947. if (pageCompressContent) {
  948. const viewport = document.head.querySelector("meta[name=viewport]");
  949. window.parent.postMessage(JSON.stringify({
  950. method: "setContent",
  951. content,
  952. filename,
  953. title: document.title,
  954. doctype: singlefile.helper.getDoctypeString(document),
  955. url: pageUrl,
  956. viewport: viewport ? viewport.content : null,
  957. compressContent: true,
  958. foregroundSave: message.foregroundSave
  959. }), "*");
  960. } else {
  961. if (message.foregroundSave) {
  962. if (filename || (message.filename && message.filename.length)) {
  963. const link = document.createElement("a");
  964. link.download = filename || message.filename;
  965. link.href = URL.createObjectURL(new Blob([content], { type: "text/html" }));
  966. link.dispatchEvent(new MouseEvent("click"));
  967. }
  968. return new Promise(resolve => setTimeout(resolve, 1));
  969. } else {
  970. window.parent.postMessage(JSON.stringify({
  971. method: "setContent",
  972. content,
  973. filename
  974. }), "*");
  975. }
  976. }
  977. }
  978. if (message.method == "printPage") {
  979. printPage();
  980. }
  981. if (message.method == "displayInfobar") {
  982. singlefile.helper.displayIcon(document, true);
  983. const infobarDoc = document.implementation.createHTMLDocument();
  984. infobarDoc.body.appendChild(document.querySelector(singlefile.helper.INFOBAR_TAGNAME));
  985. serializeShadowRoots(infobarDoc.body);
  986. const content = singlefile.helper.serialize(infobarDoc, true);
  987. window.parent.postMessage(JSON.stringify({
  988. method: "displayInfobar",
  989. content
  990. }), "*");
  991. }
  992. if (message.method == "download") {
  993. const link = document.createElement("a");
  994. link.download = message.filename;
  995. link.href = URL.createObjectURL(new Blob([new Uint8Array(message.content)], { type: "text/html" }));
  996. link.dispatchEvent(new MouseEvent("click"));
  997. }
  998. };
  999. window.onresize = reflowNotes;
  1000. document.ondragover = event => event.preventDefault();
  1001. document.ondrop = async event => {
  1002. if (event.dataTransfer.files && event.dataTransfer.files[0]) {
  1003. const file = event.dataTransfer.files[0];
  1004. event.preventDefault();
  1005. const content = new TextDecoder().decode(await file.arrayBuffer());
  1006. const compressContent = /<html[^>]* data-sfz[^>]*>/i.test(content);
  1007. if (compressContent) {
  1008. await init({ content: file, compressContent }, { filename: file.name });
  1009. } else {
  1010. await init({ content }, { filename: file.name });
  1011. }
  1012. }
  1013. };
  1014. }
  1015. async function init({ content, password, compressContent }, { filename, reset } = {}) {
  1016. await initConstants();
  1017. if (compressContent) {
  1018. const zipOptions = {
  1019. workerScripts: { inflate: ["/lib/single-file-z-worker.js"] }
  1020. };
  1021. try {
  1022. const worker = new Worker(zipOptions.workerScripts.inflate[0]);
  1023. worker.terminate();
  1024. } catch (error) {
  1025. delete zipOptions.workerScripts;
  1026. }
  1027. zipOptions.useWebWorkers = IS_NOT_SAFARI;
  1028. const { docContent, origDocContent, resources, url } = await singlefile.helper.extract(content, {
  1029. password,
  1030. prompt,
  1031. shadowRootScriptURL: new URL("/lib/single-file-extension-editor-init.js", document.baseURI).href,
  1032. zipOptions
  1033. });
  1034. pageResources = resources;
  1035. pageUrl = url;
  1036. pageCompressContent = true;
  1037. const contentDocument = (new DOMParser()).parseFromString(docContent, "text/html");
  1038. if (detectSavedPage(contentDocument)) {
  1039. await singlefile.helper.display(document, docContent, { disableFramePointerEvents: true });
  1040. const infobarElement = document.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1041. if (infobarElement) {
  1042. infobarElement.remove();
  1043. }
  1044. await initPage();
  1045. let icon;
  1046. const origContentDocument = (new DOMParser()).parseFromString(origDocContent, "text/html");
  1047. const iconElement = origContentDocument.querySelector("link[rel*=icon]");
  1048. if (iconElement) {
  1049. const iconResource = resources.find(resource => resource.filename == iconElement.getAttribute("href"));
  1050. if (iconResource && iconResource.content) {
  1051. const reader = new FileReader();
  1052. reader.readAsDataURL(await (await fetch(iconResource.content)).blob());
  1053. icon = await new Promise((resolve, reject) => {
  1054. reader.addEventListener("load", () => resolve(reader.result), false);
  1055. reader.addEventListener("error", reject, false);
  1056. });
  1057. } else {
  1058. icon = iconElement.href;
  1059. }
  1060. }
  1061. window.parent.postMessage(JSON.stringify({
  1062. method: "onInit",
  1063. title: document.title,
  1064. icon,
  1065. filename,
  1066. reset,
  1067. formatPageEnabled: isProbablyReaderable(document)
  1068. }), "*");
  1069. }
  1070. } else {
  1071. const initScriptContentMatch = content.match(/<script data-template-shadow-root.*<\/script>/);
  1072. if (initScriptContentMatch && initScriptContentMatch[0]) {
  1073. initScriptContent = initScriptContentMatch[0];
  1074. }
  1075. content = content.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=/lib/single-file-extension-editor-init.js></script>");
  1076. const contentDocument = (new DOMParser()).parseFromString(content, "text/html");
  1077. if (detectSavedPage(contentDocument)) {
  1078. if (contentDocument.doctype) {
  1079. if (document.doctype) {
  1080. document.replaceChild(contentDocument.doctype, document.doctype);
  1081. } else {
  1082. document.insertBefore(contentDocument.doctype, document.documentElement);
  1083. }
  1084. } else if (document.doctype) {
  1085. document.doctype.remove();
  1086. }
  1087. const infobarElement = contentDocument.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1088. if (infobarElement) {
  1089. infobarElement.remove();
  1090. }
  1091. contentDocument.querySelectorAll("noscript").forEach(element => {
  1092. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  1093. element.textContent = "";
  1094. });
  1095. contentDocument.querySelectorAll("iframe").forEach(element => {
  1096. const pointerEvents = "pointer-events";
  1097. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1098. element.style.setProperty(pointerEvents, "none", "important");
  1099. });
  1100. document.replaceChild(contentDocument.documentElement, document.documentElement);
  1101. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1102. deserializeShadowRoots(document);
  1103. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1104. insertHighlightStylesheet(document);
  1105. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1106. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1107. document.documentElement.onmousedown = onMouseDown;
  1108. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1109. document.documentElement.onmouseover = onMouseOver;
  1110. document.documentElement.onmouseout = onMouseOut;
  1111. document.documentElement.onkeydown = onKeyDown;
  1112. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1113. window.onclick = event => event.preventDefault();
  1114. const iconElement = document.querySelector("link[rel*=icon]");
  1115. window.parent.postMessage(JSON.stringify({
  1116. method: "onInit",
  1117. title: document.title,
  1118. icon: iconElement && iconElement.href,
  1119. filename,
  1120. reset,
  1121. formatPageEnabled: isProbablyReaderable(document)
  1122. }), "*");
  1123. }
  1124. }
  1125. }
  1126. function loadOptionsFromPage(doc) {
  1127. const optionsElement = doc.body.querySelector("script[type=\"application/json\"][" + SCRIPT_OPTIONS + "]");
  1128. if (optionsElement) {
  1129. return JSON.parse(optionsElement.textContent);
  1130. }
  1131. }
  1132. async function initPage() {
  1133. document.querySelectorAll("iframe").forEach(element => {
  1134. const pointerEvents = "pointer-events";
  1135. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1136. element.style.setProperty(pointerEvents, "none", "important");
  1137. });
  1138. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1139. deserializeShadowRoots(document);
  1140. reflowNotes();
  1141. await waitResourcesLoad();
  1142. reflowNotes();
  1143. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1144. insertHighlightStylesheet(document);
  1145. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1146. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1147. document.documentElement.onmousedown = onMouseDown;
  1148. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1149. document.documentElement.onmouseover = onMouseOver;
  1150. document.documentElement.onmouseout = onMouseOut;
  1151. document.documentElement.onkeydown = onKeyDown;
  1152. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1153. window.onclick = event => event.preventDefault();
  1154. }
  1155. async function initConstants() {
  1156. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  1157. minifyText(await ((await fetch("../pages/editor-note-web.css")).text())),
  1158. minifyText(await ((await fetch("../pages/editor-mask-web.css")).text())),
  1159. minifyText(await ((await fetch("../pages/editor-frame-web.css")).text()))
  1160. ]);
  1161. }
  1162. function addNote({ color }) {
  1163. const containerElement = document.createElement(NOTE_TAGNAME);
  1164. const noteElement = document.createElement("div");
  1165. const headerElement = document.createElement("header");
  1166. const blockquoteElement = document.createElement("blockquote");
  1167. const mainElement = document.createElement("textarea");
  1168. const resizeElement = document.createElement("div");
  1169. const removeNoteElement = document.createElement("img");
  1170. const anchorIconElement = document.createElement("img");
  1171. const noteShadow = containerElement.attachShadow({ mode: "open" });
  1172. headerElement.appendChild(anchorIconElement);
  1173. headerElement.appendChild(removeNoteElement);
  1174. blockquoteElement.appendChild(mainElement);
  1175. noteElement.appendChild(headerElement);
  1176. noteElement.appendChild(blockquoteElement);
  1177. noteElement.appendChild(resizeElement);
  1178. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  1179. noteShadow.appendChild(noteElement);
  1180. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  1181. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  1182. blockquoteElement.cite = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[data-single-file-note-refs~=\"" + noteId + "\"])";
  1183. noteElement.classList.add(NOTE_CLASS);
  1184. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  1185. noteElement.classList.add(color);
  1186. noteElement.dataset.color = color;
  1187. mainElement.dir = "auto";
  1188. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  1189. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  1190. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  1191. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  1192. positionX += NOTE_INITIAL_POSITION_X;
  1193. positionY += NOTE_INITIAL_POSITION_Y;
  1194. }
  1195. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  1196. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  1197. resizeElement.className = "note-resize";
  1198. resizeElement.ondragstart = event => event.preventDefault();
  1199. removeNoteElement.className = "note-remove";
  1200. removeNoteElement.src = BUTTON_CLOSE_URL;
  1201. removeNoteElement.ondragstart = event => event.preventDefault();
  1202. anchorIconElement.className = "note-anchor";
  1203. anchorIconElement.src = BUTTON_ANCHOR_URL;
  1204. anchorIconElement.ondragstart = event => event.preventDefault();
  1205. containerElement.dataset.noteId = noteId;
  1206. addNoteRef(document.documentElement, noteId);
  1207. attachNoteListeners(containerElement, true);
  1208. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1209. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1210. selectedNote = noteElement;
  1211. onUpdate(false);
  1212. }
  1213. function attachNoteListeners(containerElement, editable = false) {
  1214. const SELECT_PX_THRESHOLD = 4;
  1215. const COLLAPSING_NOTE_DELAY = 750;
  1216. const noteShadow = containerElement.shadowRoot;
  1217. const noteElement = noteShadow.childNodes[1];
  1218. const headerElement = noteShadow.querySelector("header");
  1219. const mainElement = noteShadow.querySelector("textarea");
  1220. const noteId = containerElement.dataset.noteId;
  1221. const resizeElement = noteShadow.querySelector(".note-resize");
  1222. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  1223. const removeNoteElement = noteShadow.querySelector(".note-remove");
  1224. mainElement.readOnly = !editable;
  1225. if (!editable) {
  1226. anchorIconElement.style.setProperty("display", "none", "important");
  1227. } else {
  1228. anchorIconElement.style.removeProperty("display");
  1229. }
  1230. headerElement.ontouchstart = headerElement.onmousedown = event => {
  1231. if (event.target == headerElement) {
  1232. collapseNoteTimeout = setTimeout(() => {
  1233. noteElement.classList.toggle("note-collapsed");
  1234. hideMaskNote();
  1235. }, COLLAPSING_NOTE_DELAY);
  1236. event.preventDefault();
  1237. const position = getPosition(event);
  1238. const clientX = position.clientX;
  1239. const clientY = position.clientY;
  1240. const boundingRect = noteElement.getBoundingClientRect();
  1241. const deltaX = clientX - boundingRect.left;
  1242. const deltaY = clientY - boundingRect.top;
  1243. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  1244. document.documentElement.style.setProperty("user-select", "none", "important");
  1245. anchorElement = getAnchorElement(containerElement);
  1246. displayMaskNote();
  1247. selectNote(noteElement);
  1248. moveNote(event, deltaX, deltaY);
  1249. movingNoteMode = { event, deltaX, deltaY };
  1250. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  1251. clearTimeout(collapseNoteTimeout);
  1252. if (!movingNoteMode) {
  1253. movingNoteMode = { deltaX, deltaY };
  1254. }
  1255. movingNoteMode.event = event;
  1256. moveNote(event, deltaX, deltaY);
  1257. };
  1258. }
  1259. };
  1260. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  1261. event.preventDefault();
  1262. resizingNoteMode = true;
  1263. selectNote(noteElement);
  1264. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  1265. document.documentElement.style.setProperty("user-select", "none", "important");
  1266. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  1267. event.preventDefault();
  1268. const { clientX, clientY } = getPosition(event);
  1269. const boundingRectNote = noteElement.getBoundingClientRect();
  1270. noteElement.style.width = clientX - boundingRectNote.left + "px";
  1271. noteElement.style.height = clientY - boundingRectNote.top + "px";
  1272. };
  1273. };
  1274. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  1275. event.preventDefault();
  1276. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  1277. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  1278. deleteNoteRef(containerElement, noteId);
  1279. addNoteRef(document.documentElement, noteId);
  1280. }
  1281. onUpdate(false);
  1282. };
  1283. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  1284. event.preventDefault();
  1285. deleteNoteRef(containerElement, noteId);
  1286. containerElement.remove();
  1287. };
  1288. noteElement.onmousedown = () => {
  1289. selectNote(noteElement);
  1290. };
  1291. function moveNote(event, deltaX, deltaY) {
  1292. event.preventDefault();
  1293. const { clientX, clientY } = getPosition(event);
  1294. noteElement.classList.add(NOTE_MOVING_CLASS);
  1295. if (editable) {
  1296. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  1297. deleteNoteRef(containerElement, noteId);
  1298. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  1299. addNoteRef(anchorElement, noteId);
  1300. } else {
  1301. anchorElement = document.documentElement;
  1302. }
  1303. }
  1304. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1305. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  1306. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  1307. noteElement.style.setProperty("position", "fixed");
  1308. displayMaskNote();
  1309. }
  1310. function displayMaskNote() {
  1311. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  1312. hideMaskNote();
  1313. } else {
  1314. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  1315. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  1316. if (selectedNote) {
  1317. maskNoteElement.classList.add(selectedNote.dataset.color);
  1318. }
  1319. maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
  1320. maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
  1321. maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
  1322. maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
  1323. }
  1324. }
  1325. function hideMaskNote() {
  1326. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  1327. if (selectedNote) {
  1328. maskNoteElement.classList.remove(selectedNote.dataset.color);
  1329. }
  1330. }
  1331. function selectNote(noteElement) {
  1332. if (selectedNote) {
  1333. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  1334. maskNoteElement.classList.remove(selectedNote.dataset.color);
  1335. }
  1336. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1337. noteElement.classList.add(noteElement.dataset.color);
  1338. selectedNote = noteElement;
  1339. }
  1340. function getTarget(clientX, clientY) {
  1341. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
  1342. if (!targets.includes(document.documentElement)) {
  1343. targets.push(document.documentElement);
  1344. }
  1345. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  1346. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  1347. if (newTarget == target) {
  1348. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  1349. }
  1350. if (newTarget == target) {
  1351. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  1352. }
  1353. if (newTarget == target) {
  1354. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  1355. }
  1356. target = newTarget;
  1357. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  1358. target = target.parentElement;
  1359. }
  1360. return target;
  1361. }
  1362. function getMatchedParents(target, property) {
  1363. let element = target, matchedParent, parents = [];
  1364. do {
  1365. const boundingRect = element.getBoundingClientRect();
  1366. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  1367. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  1368. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  1369. if (matchedParent) {
  1370. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  1371. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  1372. parents.push(element.parentElement);
  1373. }
  1374. element = element.parentElement;
  1375. }
  1376. } else {
  1377. matchedParent = false;
  1378. }
  1379. } while (matchedParent && element);
  1380. return parents;
  1381. }
  1382. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  1383. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  1384. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  1385. }
  1386. return target;
  1387. }
  1388. }
  1389. function onMouseDown(event) {
  1390. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  1391. event.preventDefault();
  1392. }
  1393. }
  1394. function onMouseUp(event) {
  1395. if (highlightSelectionMode) {
  1396. event.preventDefault();
  1397. highlightSelection();
  1398. onUpdate(false);
  1399. }
  1400. if (removeHighlightMode) {
  1401. event.preventDefault();
  1402. let element = event.target, done;
  1403. while (element && !done) {
  1404. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  1405. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  1406. resetHighlightedElement(highlightedElement);
  1407. onUpdate(false);
  1408. });
  1409. done = true;
  1410. }
  1411. element = element.parentElement;
  1412. }
  1413. }
  1414. if (resizingNoteMode) {
  1415. event.preventDefault();
  1416. resizingNoteMode = false;
  1417. document.documentElement.style.removeProperty("user-select");
  1418. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  1419. document.documentElement.ontouchmove = onTouchMove;
  1420. document.documentElement.onmousemove = null;
  1421. onUpdate(false);
  1422. }
  1423. if (movingNoteMode) {
  1424. event.preventDefault();
  1425. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  1426. movingNoteMode = null;
  1427. document.documentElement.ontouchmove = onTouchMove;
  1428. document.documentElement.onmousemove = null;
  1429. onUpdate(false);
  1430. }
  1431. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  1432. event.preventDefault();
  1433. if (event.ctrlKey) {
  1434. const element = cuttingPath[cuttingPathIndex];
  1435. element.classList.toggle(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  1436. } else {
  1437. validateCutElement(event.shiftKey);
  1438. }
  1439. }
  1440. if (collapseNoteTimeout) {
  1441. clearTimeout(collapseNoteTimeout);
  1442. collapseNoteTimeout = null;
  1443. }
  1444. }
  1445. function onMouseOver(event) {
  1446. if (cuttingMode || cuttingOuterMode) {
  1447. const target = event.target;
  1448. if (target.classList) {
  1449. let ancestorFound;
  1450. document.querySelectorAll("." + (cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS)).forEach(element => {
  1451. if (element == target || isAncestor(element, target) || isAncestor(target, element)) {
  1452. ancestorFound = element;
  1453. }
  1454. });
  1455. if (ancestorFound) {
  1456. cuttingPath = [ancestorFound];
  1457. } else {
  1458. cuttingPath = getParents(event.target);
  1459. }
  1460. cuttingPathIndex = 0;
  1461. highlightCutElement();
  1462. }
  1463. }
  1464. }
  1465. function onMouseOut() {
  1466. if (cuttingMode || cuttingOuterMode) {
  1467. if (cuttingPath) {
  1468. unhighlightCutElement();
  1469. cuttingPath = null;
  1470. }
  1471. }
  1472. }
  1473. function onTouchMove(event) {
  1474. if (cuttingMode || cuttingOuterMode) {
  1475. event.preventDefault();
  1476. const { clientX, clientY } = getPosition(event);
  1477. const target = document.elementFromPoint(clientX, clientY);
  1478. if (cuttingTouchTarget != target) {
  1479. onMouseOut();
  1480. if (target) {
  1481. cuttingTouchTarget = target;
  1482. onMouseOver({ target });
  1483. }
  1484. }
  1485. }
  1486. }
  1487. function onKeyDown(event) {
  1488. if (cuttingMode || cuttingOuterMode) {
  1489. if (event.code == "Tab") {
  1490. if (cuttingPath) {
  1491. const delta = event.shiftKey ? -1 : 1;
  1492. let element = cuttingPath[cuttingPathIndex];
  1493. let nextElement = cuttingPath[cuttingPathIndex + delta];
  1494. if (nextElement) {
  1495. let pathIndex = cuttingPathIndex + delta;
  1496. while (
  1497. nextElement &&
  1498. (
  1499. (delta == 1 &&
  1500. element.getBoundingClientRect().width >= nextElement.getBoundingClientRect().width &&
  1501. element.getBoundingClientRect().height >= nextElement.getBoundingClientRect().height) ||
  1502. (delta == -1 &&
  1503. element.getBoundingClientRect().width <= nextElement.getBoundingClientRect().width &&
  1504. element.getBoundingClientRect().height <= nextElement.getBoundingClientRect().height))) {
  1505. pathIndex += delta;
  1506. nextElement = cuttingPath[pathIndex];
  1507. }
  1508. if (nextElement && nextElement.classList && nextElement != document.body && nextElement != document.documentElement) {
  1509. unhighlightCutElement();
  1510. cuttingPathIndex = pathIndex;
  1511. highlightCutElement();
  1512. }
  1513. }
  1514. }
  1515. event.preventDefault();
  1516. }
  1517. if (event.code == "Space") {
  1518. if (cuttingPath) {
  1519. if (event.ctrlKey) {
  1520. const element = cuttingPath[cuttingPathIndex];
  1521. element.classList.add(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  1522. } else {
  1523. validateCutElement(event.shiftKey);
  1524. }
  1525. event.preventDefault();
  1526. }
  1527. }
  1528. if (event.code == "Escape") {
  1529. resetSelectedElements();
  1530. event.preventDefault();
  1531. }
  1532. if (event.key.toLowerCase() == "z" && event.ctrlKey) {
  1533. if (event.shiftKey) {
  1534. redoCutPage();
  1535. } else {
  1536. undoCutPage();
  1537. }
  1538. event.preventDefault();
  1539. }
  1540. }
  1541. if (event.key.toLowerCase() == "s" && event.ctrlKey) {
  1542. window.parent.postMessage(JSON.stringify({ "method": "savePage" }), "*");
  1543. event.preventDefault();
  1544. }
  1545. if (event.key.toLowerCase() == "p" && event.ctrlKey) {
  1546. printPage();
  1547. event.preventDefault();
  1548. }
  1549. }
  1550. function printPage() {
  1551. unhighlightCutElement();
  1552. resetSelectedElements();
  1553. window.print();
  1554. }
  1555. function highlightCutElement() {
  1556. const element = cuttingPath[cuttingPathIndex];
  1557. element.classList.add(cuttingMode ? CUT_HOVER_CLASS : CUT_OUTER_HOVER_CLASS);
  1558. }
  1559. function unhighlightCutElement() {
  1560. if (cuttingPath) {
  1561. const element = cuttingPath[cuttingPathIndex];
  1562. element.classList.remove(CUT_HOVER_CLASS);
  1563. element.classList.remove(CUT_OUTER_HOVER_CLASS);
  1564. }
  1565. }
  1566. function disableHighlight(doc = document) {
  1567. if (highlightColor) {
  1568. doc.documentElement.classList.remove(highlightColor + "-mode");
  1569. }
  1570. }
  1571. function undoCutPage() {
  1572. if (removedElementIndex) {
  1573. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  1574. removedElementIndex--;
  1575. }
  1576. }
  1577. function redoCutPage() {
  1578. if (removedElementIndex < removedElements.length) {
  1579. removedElements[removedElementIndex].forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  1580. removedElementIndex++;
  1581. }
  1582. }
  1583. function validateCutElement(invert) {
  1584. const selectedElement = cuttingPath[cuttingPathIndex];
  1585. if ((cuttingMode && !invert) || (cuttingOuterMode && invert)) {
  1586. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  1587. const elementsRemoved = [selectedElement].concat(...document.querySelectorAll("." + CUT_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS + " *,." + CUT_HOVER_CLASS + " *"));
  1588. resetSelectedElements();
  1589. if (elementsRemoved.length) {
  1590. elementsRemoved.forEach(element => {
  1591. unhighlightCutElement(element);
  1592. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  1593. resetAnchorNote(element);
  1594. } else {
  1595. element.classList.add(REMOVED_CONTENT_CLASS);
  1596. }
  1597. });
  1598. removedElements[removedElementIndex] = elementsRemoved;
  1599. removedElementIndex++;
  1600. removedElements.length = removedElementIndex;
  1601. onUpdate(false);
  1602. }
  1603. }
  1604. } else {
  1605. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  1606. const elements = [];
  1607. const searchSelector = "*:not(style):not(meta):not(." + REMOVED_CONTENT_CLASS + ")";
  1608. const elementsKept = [selectedElement].concat(...document.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS));
  1609. document.body.querySelectorAll(searchSelector).forEach(element => {
  1610. let removed = true;
  1611. elementsKept.forEach(elementKept => removed = removed && (elementKept != element && !isAncestor(elementKept, element) && !isAncestor(element, elementKept)));
  1612. if (removed) {
  1613. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  1614. resetAnchorNote(element);
  1615. } else {
  1616. elements.push(element);
  1617. }
  1618. }
  1619. });
  1620. elementsKept.forEach(elementKept => {
  1621. unhighlightCutElement(elementKept);
  1622. const elementKeptRect = elementKept.getBoundingClientRect();
  1623. elementKept.querySelectorAll(searchSelector).forEach(descendant => {
  1624. const descendantRect = descendant.getBoundingClientRect();
  1625. if (descendantRect.width && descendantRect.height && (
  1626. descendantRect.left + descendantRect.width < elementKeptRect.left ||
  1627. descendantRect.right > elementKeptRect.right + elementKeptRect.width ||
  1628. descendantRect.top + descendantRect.height < elementKeptRect.top ||
  1629. descendantRect.bottom > elementKeptRect.bottom + elementKeptRect.height
  1630. )) {
  1631. elements.push(descendant);
  1632. }
  1633. });
  1634. });
  1635. resetSelectedElements();
  1636. if (elements.length) {
  1637. elements.forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  1638. removedElements[removedElementIndex] = elements;
  1639. removedElementIndex++;
  1640. removedElements.length = removedElementIndex;
  1641. onUpdate(false);
  1642. }
  1643. }
  1644. }
  1645. }
  1646. function resetSelectedElements(doc = document) {
  1647. doc.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS).forEach(element => {
  1648. element.classList.remove(CUT_OUTER_SELECTED_CLASS);
  1649. element.classList.remove(CUT_SELECTED_CLASS);
  1650. });
  1651. }
  1652. function anchorNote(event, noteElement, deltaX, deltaY) {
  1653. event.preventDefault();
  1654. const { clientX, clientY } = getPosition(event);
  1655. document.documentElement.style.removeProperty("user-select");
  1656. noteElement.classList.remove(NOTE_MOVING_CLASS);
  1657. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  1658. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  1659. maskNoteElement.classList.remove(noteElement.dataset.color);
  1660. const headerElement = noteElement.querySelector("header");
  1661. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  1662. let currentElement = anchorElement;
  1663. let positionedElement;
  1664. while (currentElement.parentElement && !positionedElement) {
  1665. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  1666. const currentElementStyle = getComputedStyle(currentElement);
  1667. if (currentElementStyle.position != "static") {
  1668. positionedElement = currentElement;
  1669. }
  1670. }
  1671. currentElement = currentElement.parentElement;
  1672. }
  1673. if (!positionedElement) {
  1674. positionedElement = document.documentElement;
  1675. }
  1676. const containerElement = noteElement.getRootNode().host;
  1677. if (positionedElement == document.documentElement) {
  1678. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  1679. firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
  1680. } else {
  1681. positionedElement.appendChild(containerElement);
  1682. }
  1683. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  1684. const stylePositionedElement = window.getComputedStyle(positionedElement);
  1685. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  1686. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  1687. noteElement.style.setProperty("position", "absolute");
  1688. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  1689. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  1690. }
  1691. function resetAnchorNote(containerElement) {
  1692. const noteId = containerElement.dataset.noteId;
  1693. const noteElement = containerElement.shadowRoot.childNodes[1];
  1694. noteElement.classList.remove(NOTE_ANCHORED_CLASS);
  1695. deleteNoteRef(containerElement, noteId);
  1696. addNoteRef(document.documentElement, noteId);
  1697. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1698. }
  1699. function getPosition(event) {
  1700. if (event.touches && event.touches.length) {
  1701. const touch = event.touches[0];
  1702. return touch;
  1703. } else {
  1704. return event;
  1705. }
  1706. }
  1707. function highlightSelection() {
  1708. let highlightId = 0;
  1709. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  1710. highlightId++;
  1711. const selection = window.getSelection();
  1712. const highlightedNodes = new Set();
  1713. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  1714. const range = selection.getRangeAt(indexRange);
  1715. if (!range.collapsed) {
  1716. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  1717. let contentText = range.startContainer.splitText(range.startOffset);
  1718. contentText = contentText.splitText(range.endOffset);
  1719. addHighLightedNode(contentText.previousSibling);
  1720. } else {
  1721. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  1722. let highlightNodes;
  1723. while (treeWalker.nextNode()) {
  1724. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  1725. addHighLightedNode(treeWalker.currentNode);
  1726. }
  1727. if (treeWalker.currentNode == range.startContainer) {
  1728. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  1729. const contentText = range.startContainer.splitText(range.startOffset);
  1730. treeWalker.nextNode();
  1731. addHighLightedNode(contentText);
  1732. } else {
  1733. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  1734. }
  1735. highlightNodes = true;
  1736. }
  1737. if (treeWalker.currentNode == range.endContainer) {
  1738. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  1739. const contentText = range.endContainer.splitText(range.endOffset);
  1740. treeWalker.nextNode();
  1741. addHighLightedNode(contentText.previousSibling);
  1742. } else {
  1743. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  1744. }
  1745. highlightNodes = false;
  1746. }
  1747. }
  1748. range.collapse();
  1749. }
  1750. }
  1751. }
  1752. highlightedNodes.forEach(node => highlightNode(node));
  1753. function addHighLightedNode(node) {
  1754. if (node && node.textContent.trim()) {
  1755. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  1756. highlightedNodes.add(node.parentElement);
  1757. } else {
  1758. highlightedNodes.add(node);
  1759. }
  1760. }
  1761. }
  1762. function highlightNode(node) {
  1763. if (node.nodeType == node.ELEMENT_NODE) {
  1764. resetHighlightedElement(node);
  1765. node.classList.add(HIGHLIGHT_CLASS);
  1766. node.classList.add(highlightColor);
  1767. node.dataset.singlefileHighlightId = highlightId;
  1768. } else if (node.parentElement) {
  1769. highlightTextNode(node);
  1770. }
  1771. }
  1772. function highlightTextNode(node) {
  1773. const spanElement = document.createElement("span");
  1774. spanElement.classList.add(HIGHLIGHT_CLASS);
  1775. spanElement.classList.add(highlightColor);
  1776. spanElement.textContent = node.textContent;
  1777. spanElement.dataset.singlefileHighlightId = highlightId;
  1778. node.parentNode.replaceChild(spanElement, node);
  1779. return spanElement;
  1780. }
  1781. }
  1782. function getParents(element) {
  1783. const path = [];
  1784. while (element) {
  1785. path.push(element);
  1786. element = element.parentElement;
  1787. }
  1788. return path;
  1789. }
  1790. function formatPage(applySystemTheme) {
  1791. if (pageCompressContent) {
  1792. serializeShadowRoots(document);
  1793. previousContent = document.documentElement.cloneNode(true);
  1794. deserializeShadowRoots(document);
  1795. } else {
  1796. previousContent = getContent(false, []);
  1797. }
  1798. const shadowRoots = {};
  1799. const classesToPreserve = ["single-file-highlight", "single-file-highlight-yellow", "single-file-highlight-green", "single-file-highlight-pink", "single-file-highlight-blue"];
  1800. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1801. shadowRoots[containerElement.dataset.noteId] = containerElement.shadowRoot;
  1802. const className = "singlefile-note-id-" + containerElement.dataset.noteId;
  1803. containerElement.classList.add(className);
  1804. classesToPreserve.push(className);
  1805. });
  1806. const article = new Readability(document, { classesToPreserve }).parse();
  1807. removedElements = [];
  1808. removedElementIndex = 0;
  1809. document.body.innerHTML = "";
  1810. const domParser = new DOMParser();
  1811. const doc = domParser.parseFromString(article.content, "text/html");
  1812. const contentEditable = document.body.contentEditable;
  1813. document.documentElement.replaceChild(doc.body, document.body);
  1814. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1815. const noteId = (Array.from(containerElement.classList).find(className => /singlefile-note-id-\d+/.test(className))).split("singlefile-note-id-")[1];
  1816. containerElement.classList.remove("singlefile-note-id-" + noteId);
  1817. containerElement.dataset.noteId = noteId;
  1818. if (!containerElement.shadowRoot) {
  1819. containerElement.attachShadow({ mode: "open" });
  1820. containerElement.shadowRoot.appendChild(shadowRoots[noteId]);
  1821. }
  1822. });
  1823. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => shadowRoots[containerElement.dataset.noteId].childNodes.forEach(node => containerElement.shadowRoot.appendChild(node)));
  1824. document.body.contentEditable = contentEditable;
  1825. document.head.querySelectorAll("style").forEach(styleElement => styleElement.remove());
  1826. const styleElement = document.createElement("style");
  1827. styleElement.textContent = STYLE_FORMATTED_PAGE;
  1828. document.head.appendChild(styleElement);
  1829. document.body.classList.add("moz-reader-content");
  1830. document.body.classList.add("content-width6");
  1831. document.body.classList.add("reader-show-element");
  1832. document.body.classList.add("sans-serif");
  1833. document.body.classList.add("container");
  1834. document.body.classList.add("line-height4");
  1835. const prefersColorSchemeDark = matchMedia("(prefers-color-scheme: dark)");
  1836. if (applySystemTheme && prefersColorSchemeDark && prefersColorSchemeDark.matches) {
  1837. document.body.classList.add("dark");
  1838. }
  1839. document.body.style.setProperty("display", "block");
  1840. document.body.style.setProperty("padding", "24px");
  1841. const titleElement = document.createElement("h1");
  1842. titleElement.classList.add("reader-title");
  1843. titleElement.textContent = article.title;
  1844. document.body.insertBefore(titleElement, document.body.firstChild);
  1845. document.querySelectorAll("a[href]").forEach(element => {
  1846. const href = element.getAttribute("href").trim();
  1847. if (href.startsWith(document.baseURI + "#")) {
  1848. element.setAttribute("href", href.substring(document.baseURI.length));
  1849. }
  1850. });
  1851. insertHighlightStylesheet(document);
  1852. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1853. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1854. reflowNotes();
  1855. onUpdate(false);
  1856. }
  1857. async function cancelFormatPage() {
  1858. if (previousContent) {
  1859. const contentEditable = document.body.contentEditable;
  1860. if (pageCompressContent) {
  1861. document.replaceChild(previousContent, document.documentElement);
  1862. deserializeShadowRoots(document);
  1863. await initPage();
  1864. } else {
  1865. await init({ content: previousContent }, { reset: true });
  1866. }
  1867. document.body.contentEditable = contentEditable;
  1868. onUpdate(false);
  1869. previousContent = null;
  1870. }
  1871. }
  1872. function insertHighlightStylesheet(doc) {
  1873. if (!doc.querySelector("." + HIGHLIGHTS_STYLESHEET_CLASS)) {
  1874. const styleheetHighlights = getStyleElement(HIGHLIGHTS_WEB_STYLESHEET);
  1875. styleheetHighlights.classList.add(HIGHLIGHTS_STYLESHEET_CLASS);
  1876. doc.documentElement.appendChild(styleheetHighlights);
  1877. }
  1878. }
  1879. function getContent(compressHTML, updatedResources) {
  1880. unhighlightCutElement();
  1881. serializeShadowRoots(document);
  1882. const doc = document.cloneNode(true);
  1883. disableHighlight(doc);
  1884. resetSelectedElements(doc);
  1885. deserializeShadowRoots(doc);
  1886. deserializeShadowRoots(document);
  1887. doc.documentElement.classList.remove(CUT_MODE_CLASS);
  1888. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  1889. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  1890. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  1891. });
  1892. doc.querySelectorAll("." + MASK_CLASS + ", " + singlefile.helper.INFOBAR_TAGNAME + ", ." + REMOVED_CONTENT_CLASS).forEach(element => element.remove());
  1893. if (includeInfobar) {
  1894. singlefile.helper.appendInfobar(doc, singlefile.helper.extractInfobarData(doc));
  1895. }
  1896. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  1897. doc.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  1898. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  1899. if (noteElement) {
  1900. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  1901. }
  1902. const mainElement = templateElement.querySelector("textarea");
  1903. if (mainElement) {
  1904. mainElement.textContent = mainElement.value;
  1905. }
  1906. });
  1907. doc.querySelectorAll("iframe").forEach(element => {
  1908. const pointerEvents = "pointer-events";
  1909. element.style.setProperty(pointerEvents, element.style.getPropertyValue("-sf-" + pointerEvents), element.style.getPropertyPriority("-sf-" + pointerEvents));
  1910. element.style.removeProperty("-sf-" + pointerEvents);
  1911. });
  1912. doc.body.removeAttribute("contentEditable");
  1913. const newResources = Object.keys(updatedResources).filter(url => updatedResources[url].type == "stylesheet").map(url => updatedResources[url]);
  1914. newResources.forEach(resource => {
  1915. const element = doc.createElement("style");
  1916. doc.body.appendChild(element);
  1917. element.textContent = resource.content;
  1918. });
  1919. if (pageCompressContent) {
  1920. const pageFilename = pageResources
  1921. .filter(resource => resource.filename.endsWith("index.html"))
  1922. .sort((resourceLeft, resourceRight) => resourceLeft.filename.length - resourceRight.filename.length)[0].filename;
  1923. const resources = pageResources.filter(resource => resource.parentResources.includes(pageFilename));
  1924. doc.querySelectorAll("[src]").forEach(element => resources.forEach(resource => {
  1925. if (element.src == resource.content) {
  1926. element.src = resource.name;
  1927. }
  1928. }));
  1929. let content = singlefile.helper.serialize(doc, compressHTML);
  1930. resources.sort((resourceLeft, resourceRight) => resourceRight.content.length - resourceLeft.content.length);
  1931. resources.forEach(resource => content = content.replaceAll(resource.content, resource.name));
  1932. return content + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  1933. } else {
  1934. return singlefile.helper.serialize(doc, compressHTML) + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  1935. }
  1936. }
  1937. function onUpdate(saved) {
  1938. window.parent.postMessage(JSON.stringify({ "method": "onUpdate", saved }), "*");
  1939. }
  1940. function waitResourcesLoad() {
  1941. return new Promise(resolve => {
  1942. let counterMutations = 0;
  1943. const done = () => {
  1944. observer.disconnect();
  1945. resolve();
  1946. };
  1947. let timeoutInit = setTimeout(done, 100);
  1948. const observer = new MutationObserver(() => {
  1949. if (counterMutations < 20) {
  1950. counterMutations++;
  1951. clearTimeout(timeoutInit);
  1952. timeoutInit = setTimeout(done, 100);
  1953. } else {
  1954. done();
  1955. }
  1956. });
  1957. observer.observe(document, { subtree: true, childList: true, attributes: true });
  1958. });
  1959. }
  1960. function reflowNotes() {
  1961. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  1962. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  1963. const noteBoundingRect = noteElement.getBoundingClientRect();
  1964. const anchorElement = getAnchorElement(containerElement);
  1965. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  1966. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  1967. const minX = anchorBoundingRect.x;
  1968. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  1969. const minY = anchorBoundingRect.y;
  1970. let left = parseInt(noteElement.style.getPropertyValue("left"));
  1971. let top = parseInt(noteElement.style.getPropertyValue("top"));
  1972. if (noteBoundingRect.x > maxX) {
  1973. left -= noteBoundingRect.x - maxX;
  1974. }
  1975. if (noteBoundingRect.x < minX) {
  1976. left += minX - noteBoundingRect.x;
  1977. }
  1978. if (noteBoundingRect.y > maxY) {
  1979. top -= noteBoundingRect.y - maxY;
  1980. }
  1981. if (noteBoundingRect.y < minY) {
  1982. top += minY - noteBoundingRect.y;
  1983. }
  1984. noteElement.style.setProperty("position", "absolute");
  1985. noteElement.style.setProperty("left", left + "px");
  1986. noteElement.style.setProperty("top", top + "px");
  1987. });
  1988. }
  1989. function resetHighlightedElement(element) {
  1990. element.classList.remove(HIGHLIGHT_CLASS);
  1991. element.classList.remove("single-file-highlight-yellow");
  1992. element.classList.remove("single-file-highlight-pink");
  1993. element.classList.remove("single-file-highlight-blue");
  1994. element.classList.remove("single-file-highlight-green");
  1995. delete element.dataset.singlefileHighlightId;
  1996. }
  1997. function serializeShadowRoots(node) {
  1998. node.querySelectorAll("*").forEach(element => {
  1999. const shadowRoot = getShadowRoot(element);
  2000. if (shadowRoot) {
  2001. serializeShadowRoots(shadowRoot);
  2002. const templateElement = document.createElement("template");
  2003. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  2004. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  2005. element.appendChild(templateElement);
  2006. }
  2007. });
  2008. }
  2009. function deserializeShadowRoots(node) {
  2010. node.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(element => {
  2011. if (element.parentElement) {
  2012. let shadowRoot = getShadowRoot(element.parentElement);
  2013. if (shadowRoot) {
  2014. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  2015. element.remove();
  2016. } else {
  2017. try {
  2018. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  2019. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  2020. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  2021. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  2022. } catch (error) {
  2023. // ignored
  2024. }
  2025. }
  2026. if (shadowRoot) {
  2027. deserializeShadowRoots(shadowRoot);
  2028. }
  2029. }
  2030. });
  2031. }
  2032. function getMaskElement(className, containerClassName) {
  2033. let maskElement = document.documentElement.querySelector("." + className);
  2034. if (!maskElement) {
  2035. maskElement = document.createElement("div");
  2036. const maskContainerElement = document.createElement("div");
  2037. if (containerClassName) {
  2038. maskContainerElement.classList.add(containerClassName);
  2039. }
  2040. maskContainerElement.classList.add(MASK_CLASS);
  2041. const firstNote = document.querySelector(NOTE_TAGNAME);
  2042. if (firstNote && firstNote.parentElement == document.documentElement) {
  2043. document.documentElement.insertBefore(maskContainerElement, firstNote);
  2044. } else {
  2045. document.documentElement.appendChild(maskContainerElement);
  2046. }
  2047. maskElement.classList.add(className);
  2048. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  2049. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  2050. maskShadow.appendChild(maskElement);
  2051. return maskElement;
  2052. }
  2053. }
  2054. function getEmbedScript() {
  2055. return minifyText(`(() => {
  2056. document.currentScript.remove();
  2057. const processNode = node => {
  2058. node.querySelectorAll("template[${SHADOWROOT_ATTRIBUTE_NAME}]").forEach(element=>{
  2059. let shadowRoot = getShadowRoot(element.parentElement);
  2060. if (!shadowRoot) {
  2061. try {
  2062. shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOWROOT_ATTRIBUTE_NAME}")});
  2063. shadowRoot.innerHTML = element.innerHTML;
  2064. element.remove();
  2065. } catch (error) {}
  2066. if (shadowRoot) {
  2067. processNode(shadowRoot);
  2068. }
  2069. }
  2070. })
  2071. };
  2072. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  2073. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  2074. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  2075. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  2076. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  2077. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  2078. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  2079. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  2080. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  2081. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  2082. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  2083. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  2084. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  2085. const REMOVED_CONTENT_CLASS = ${JSON.stringify(REMOVED_CONTENT_CLASS)};
  2086. const reflowNotes = ${minifyText(reflowNotes.toString())};
  2087. const addNoteRef = ${minifyText(addNoteRef.toString())};
  2088. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  2089. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  2090. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  2091. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  2092. const getMaskElement = ${minifyText(getMaskElement.toString())};
  2093. const getStyleElement = ${minifyText(getStyleElement.toString())};
  2094. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  2095. const anchorNote = ${minifyText(anchorNote.toString())};
  2096. const getPosition = ${minifyText(getPosition.toString())};
  2097. const onMouseUp = ${minifyText(onMouseUp.toString())};
  2098. const getShadowRoot = ${minifyText(getShadowRoot.toString())};
  2099. const waitResourcesLoad = ${minifyText(waitResourcesLoad.toString())};
  2100. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  2101. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  2102. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout, cuttingMode, cuttingOuterMode;
  2103. window.onresize = reflowNotes;
  2104. window.onUpdate = () => {};
  2105. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  2106. processNode(document);
  2107. reflowNotes();
  2108. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  2109. if (document.documentElement.dataset.sfz !== undefined) {
  2110. waitResourcesLoad().then(reflowNotes);
  2111. }
  2112. })()`);
  2113. }
  2114. function getStyleElement(stylesheet) {
  2115. const linkElement = document.createElement("style");
  2116. linkElement.textContent = stylesheet;
  2117. return linkElement;
  2118. }
  2119. function getAnchorElement(containerElement) {
  2120. return document.querySelector("[data-single-file-note-refs~=\"" + containerElement.dataset.noteId + "\"]") || document.documentElement;
  2121. }
  2122. function addNoteRef(anchorElement, noteId) {
  2123. const noteRefs = getNoteRefs(anchorElement);
  2124. noteRefs.push(noteId);
  2125. setNoteRefs(anchorElement, noteRefs);
  2126. }
  2127. function deleteNoteRef(containerElement, noteId) {
  2128. const anchorElement = getAnchorElement(containerElement);
  2129. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  2130. if (noteRefs.length) {
  2131. setNoteRefs(anchorElement, noteRefs);
  2132. } else {
  2133. delete anchorElement.dataset.singleFileNoteRefs;
  2134. }
  2135. }
  2136. function getNoteRefs(anchorElement) {
  2137. return anchorElement.dataset.singleFileNoteRefs ? anchorElement.dataset.singleFileNoteRefs.split(" ") : [];
  2138. }
  2139. function setNoteRefs(anchorElement, noteRefs) {
  2140. anchorElement.dataset.singleFileNoteRefs = noteRefs.join(" ");
  2141. }
  2142. function minifyText(text) {
  2143. return text.replace(/[\n\t\s]+/g, " ");
  2144. }
  2145. function isAncestor(element, otherElement) {
  2146. return otherElement.parentElement && (element == otherElement.parentElement || isAncestor(element, otherElement.parentElement));
  2147. }
  2148. function getShadowRoot(element) {
  2149. const chrome = window.chrome;
  2150. if (element.openOrClosedShadowRoot) {
  2151. return element.openOrClosedShadowRoot;
  2152. } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
  2153. try {
  2154. return chrome.dom.openOrClosedShadowRoot(element);
  2155. } catch (error) {
  2156. return element.shadowRoot;
  2157. }
  2158. } else {
  2159. return element.shadowRoot;
  2160. }
  2161. }
  2162. function detectSavedPage(document) {
  2163. const firstDocumentChild = document.documentElement.firstChild;
  2164. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  2165. (firstDocumentChild.textContent.includes(COMMENT_HEADER) || firstDocumentChild.textContent.includes(COMMENT_HEADER_LEGACY));
  2166. }
  2167. })(typeof globalThis == "object" ? globalThis : window);