editor-web.js 71 KB

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