content-ui-editor-web.js 85 KB

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