single-file-extension-editor.js 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275
  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 document, globalThis, getComputedStyle, FileReader, Image, OffscreenCanvas, createImageBitmap */
  26. const singlefile = globalThis.singlefile;
  27. const CLOSE_ICON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABhmlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AYht+mSlUqHewg4hChOogFURFHqWIRLJS2QqsOJpf+CE0akhQXR8G14ODPYtXBxVlXB1dBEPwBcXNzUnSREr9LCi1ivOO4h/e+9+XuO0Col5lqdowDqmYZqXhMzOZWxMAruhGiOYohiZl6Ir2Qgef4uoeP73dRnuVd9+foVfImA3wi8SzTDYt4nXh609I57xOHWUlSiM+Jxwy6IPEj12WX3zgXHRZ4ZtjIpOaIw8RisY3lNmYlQyWeIo4oqkb5QtZlhfMWZ7VcZc178hcG89pymuu0BhHHIhJIQoSMKjZQhoUo7RopJlJ0HvPwDzj+JLlkcm2AkWMeFaiQHD/4H/zurVmYnHCTgjGg88W2P4aBwC7QqNn297FtN04A/zNwpbX8lTow80l6raVFjoDQNnBx3dLkPeByB+h/0iVDciQ/LaFQAN7P6JtyQN8t0LPq9q15jtMHIEO9WroBDg6BkSJlr3m8u6u9b//WNPv3A6mTcr3f/E/sAAAABmJLR0QAigCKAIrj2uckAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QkPDysvCdPVuwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAELSURBVHja7ZpLFsIwDAPj3v/OsGHDe1BIa8tKO7Mnlkw+dpoxAAAAAGCfx4ur6Yx/B337UUS4mp/VuWUEcjSfOgO+BXCZCWe0hSqQo/npBLglIUNLdAV2MH84Ad1JyIwdLkK6YoabIHWscBWmihHuAqvHtv+XqmdXOK9TxdKy3axUm2vZkXXGgPJksTuz1bVFeeU2Y6ijsLIpXbtKa1kDs2ews69o7+A+ihJ2lvI+/lcS1G21zUVG18XKNm4OS4BNkGOQQohSmGaIdpgLESvzyiRwKepsXjE2H0ZWMF8Zi4+jK5mviM0DiRXNZ2rhkdTK5jO0xermz2o8dCnq+FS2XNNVH0sDAAAA3JYnre9cH8BZmhEAAAAASUVORK5CYII=";
  28. const SINGLE_FILE_UI_ELEMENT_CLASS = singlefile.helper.SINGLE_FILE_UI_ELEMENT_CLASS;
  29. const SHARE_PAGE_BAR_TAGNAME = "singlefile-share-page-bar";
  30. let EMBEDDED_IMAGE_BUTTON_MESSAGE$1, SHARE_PAGE_BUTTON_MESSAGE$1, SHARE_SELECTION_BUTTON_MESSAGE$1, ERROR_TITLE_MESSAGE$1;
  31. const CSS_PROPERTIES = new Set(Array.from(getComputedStyle(document.documentElement)));
  32. function setLabels(labels) {
  33. ({ EMBEDDED_IMAGE_BUTTON_MESSAGE: EMBEDDED_IMAGE_BUTTON_MESSAGE$1, SHARE_PAGE_BUTTON_MESSAGE: SHARE_PAGE_BUTTON_MESSAGE$1, SHARE_SELECTION_BUTTON_MESSAGE: SHARE_SELECTION_BUTTON_MESSAGE$1, ERROR_TITLE_MESSAGE: ERROR_TITLE_MESSAGE$1 } = labels);
  34. }
  35. function getSharePageBar() {
  36. let resolvePromise;
  37. return {
  38. display: async function (selectedContent) {
  39. return new Promise(resolve => {
  40. resolvePromise = resolve;
  41. displayBar(SHARE_PAGE_BAR_TAGNAME, "", {
  42. buttonLabel: selectedContent ? SHARE_SELECTION_BUTTON_MESSAGE$1 : SHARE_PAGE_BUTTON_MESSAGE$1,
  43. buttonOnclick: resolve
  44. });
  45. });
  46. },
  47. hide: function () {
  48. const barElement = document.querySelector(SHARE_PAGE_BAR_TAGNAME);
  49. if (barElement) {
  50. barElement.remove();
  51. }
  52. },
  53. cancel: function () {
  54. this.hide();
  55. if (resolvePromise) {
  56. resolvePromise(true);
  57. }
  58. }
  59. };
  60. }
  61. function displayBar(tagName, message, { link, buttonLabel, buttonOnclick } = {}) {
  62. try {
  63. const barElement = document.querySelector(tagName);
  64. if (!barElement) {
  65. const barElement = createElement(tagName);
  66. const shadowRoot = barElement.attachShadow({ mode: "open" });
  67. const styleElement = document.createElement("style");
  68. styleElement.textContent = `
  69. .container {
  70. background-color: #ff6c00;
  71. color: white;
  72. display: flex;
  73. position: fixed;
  74. top: 0px;
  75. left: 0px;
  76. right: 0px;
  77. height: auto;
  78. width: auto;
  79. min-height: 24px;
  80. min-width: 24px;
  81. z-index: 2147483647;
  82. margin: 0;
  83. padding: 2px;
  84. font-family: Arial;
  85. }
  86. .singlefile-open-file-bar.container, .singlefile-share-page-bar.container {
  87. background-color: gainsboro;
  88. border-block-end: gray 1px solid;
  89. }
  90. .text {
  91. flex: 1;
  92. padding-top: 4px;
  93. padding-bottom: 4px;
  94. padding-left: 8px;
  95. }
  96. button {
  97. background-color: grey;
  98. color: white;
  99. border: 1px solid darkgrey;
  100. padding: 3px;
  101. padding-left: 8px;
  102. padding-right: 8px;
  103. border-radius: 4px;
  104. cursor: pointer;
  105. }
  106. .close-button {
  107. opacity: .7;
  108. padding-left: 8px;
  109. padding-right: 8px;
  110. cursor: pointer;
  111. transition: opacity 250ms;
  112. height: 16px;
  113. font-size: .8rem;
  114. align-self: center;
  115. }
  116. .singlefile-open-file-bar button, .singlefile-share-page-bar button{
  117. background-color: dimgrey;
  118. }
  119. .singlefile-open-file-bar .close-button, .singlefile-share-page-bar .close-button{
  120. filter: invert(1);
  121. }
  122. a {
  123. color: #303036;
  124. }
  125. .close-button:hover {
  126. opacity: 1;
  127. }
  128. `;
  129. shadowRoot.appendChild(styleElement);
  130. const containerElement = document.createElement("div");
  131. containerElement.classList.add(tagName);
  132. containerElement.classList.add("container");
  133. const textElement = document.createElement("span");
  134. textElement.classList.add("text");
  135. const content = message.split("__DOC_LINK__");
  136. textElement.textContent = content[0];
  137. if (link && content.length == 2) {
  138. const linkElement = document.createElement("a");
  139. linkElement.textContent = link;
  140. linkElement.href = link;
  141. linkElement.target = "_blank";
  142. textElement.appendChild(linkElement);
  143. textElement.appendChild(document.createTextNode(content[1]));
  144. }
  145. if (buttonLabel && buttonOnclick) {
  146. const buttonElement = document.createElement("button");
  147. buttonElement.textContent = buttonLabel;
  148. buttonElement.onclick = () => buttonOnclick();
  149. textElement.appendChild(buttonElement);
  150. }
  151. containerElement.appendChild(textElement);
  152. const closeElement = document.createElement("img");
  153. closeElement.classList.add("close-button");
  154. containerElement.appendChild(closeElement);
  155. shadowRoot.appendChild(containerElement);
  156. closeElement.src = CLOSE_ICON;
  157. closeElement.onclick = event => {
  158. if (event.button === 0) {
  159. if (buttonOnclick) {
  160. buttonOnclick(true);
  161. }
  162. barElement.remove();
  163. }
  164. };
  165. document.documentElement.appendChild(barElement);
  166. }
  167. } catch (error) {
  168. // iignored
  169. }
  170. }
  171. function createElement(tagName, parentElement) {
  172. const element = document.createElement(tagName);
  173. element.className = SINGLE_FILE_UI_ELEMENT_CLASS;
  174. if (parentElement) {
  175. parentElement.appendChild(element);
  176. }
  177. CSS_PROPERTIES.forEach(property => element.style.setProperty(property, "initial", "important"));
  178. return element;
  179. }
  180. /* global TextEncoder, TextDecoder */
  181. const TYPE_REFERENCE = 0;
  182. const SPECIAL_TYPES = [TYPE_REFERENCE];
  183. const EMPTY_SLOT_VALUE = Symbol();
  184. const textEncoder = new TextEncoder();
  185. const textDecoder = new TextDecoder();
  186. const types = new Array(256);
  187. let typeIndex = 0;
  188. registerType(serializeCircularReference, parseCircularReference, testCircularReference, TYPE_REFERENCE);
  189. registerType(null, parseObject, testObject);
  190. registerType(serializeArray, parseArray, testArray);
  191. registerType(serializeString, parseString, testString);
  192. registerType(serializeTypedArray, parseFloat64Array, testFloat64Array);
  193. registerType(serializeTypedArray, parseFloat32Array, testFloat32Array);
  194. registerType(serializeTypedArray, parseUint32Array, testUint32Array);
  195. registerType(serializeTypedArray, parseInt32Array, testInt32Array);
  196. registerType(serializeTypedArray, parseUint16Array, testUint16Array);
  197. registerType(serializeTypedArray, parseInt16Array, testInt16Array);
  198. registerType(serializeTypedArray, parseUint8ClampedArray, testUint8ClampedArray);
  199. registerType(serializeTypedArray, parseUint8Array, testUint8Array);
  200. registerType(serializeTypedArray, parseInt8Array, testInt8Array);
  201. registerType(serializeArrayBuffer, parseArrayBuffer, testArrayBuffer);
  202. registerType(serializeNumber, parseNumber, testNumber);
  203. registerType(serializeUint32, parseUint32, testUint32);
  204. registerType(serializeInt32, parseInt32, testInt32);
  205. registerType(serializeUint16, parseUint16, testUint16);
  206. registerType(serializeInt16, parseInt16, testInt16);
  207. registerType(serializeUint8, parseUint8, testUint8);
  208. registerType(serializeInt8, parseInt8, testInt8);
  209. registerType(null, parseUndefined, testUndefined);
  210. registerType(null, parseNull, testNull);
  211. registerType(null, parseNaN, testNaN);
  212. registerType(serializeBoolean, parseBoolean, testBoolean);
  213. registerType(serializeSymbol, parseSymbol, testSymbol);
  214. registerType(null, parseEmptySlot, testEmptySlot);
  215. registerType(serializeMap, parseMap, testMap);
  216. registerType(serializeSet, parseSet, testSet);
  217. registerType(serializeDate, parseDate, testDate);
  218. registerType(serializeError, parseError, testError);
  219. registerType(serializeRegExp, parseRegExp, testRegExp);
  220. registerType(serializeStringObject, parseStringObject, testStringObject);
  221. registerType(serializeNumberObject, parseNumberObject, testNumberObject);
  222. registerType(serializeBooleanObject, parseBooleanObject, testBooleanObject);
  223. function registerType(serialize, parse, test, type) {
  224. if (type === undefined) {
  225. typeIndex++;
  226. if (types.length - typeIndex >= SPECIAL_TYPES.length) {
  227. types[types.length - typeIndex] = { serialize, parse, test };
  228. } else {
  229. throw new Error("Reached maximum number of custom types");
  230. }
  231. } else {
  232. types[type] = { serialize, parse, test };
  233. }
  234. }
  235. async function serializeValue(data, value) {
  236. const type = types.findIndex(({ test } = {}) => test && test(value, data));
  237. data.addObject(value);
  238. await data.append(new Uint8Array([type]));
  239. const serialize = types[type].serialize;
  240. if (serialize) {
  241. await serialize(data, value);
  242. }
  243. if (type != TYPE_REFERENCE && testObject(value)) {
  244. await serializeSymbols(data, value);
  245. await serializeOwnProperties(data, value);
  246. }
  247. }
  248. async function serializeSymbols(data, value) {
  249. const ownPropertySymbols = Object.getOwnPropertySymbols(value);
  250. const symbols = ownPropertySymbols.map(propertySymbol => [propertySymbol, value[propertySymbol]]);
  251. await serializeArray(data, symbols);
  252. }
  253. async function serializeOwnProperties(data, value) {
  254. if (!ArrayBuffer.isView(value)) {
  255. let entries = Object.entries(value);
  256. if (testArray(value)) {
  257. entries = entries.filter(([key]) => !testInteger(Number(key)));
  258. }
  259. await serializeValue(data, entries.length);
  260. for (const [key, value] of entries) {
  261. await serializeString(data, key);
  262. await serializeValue(data, value);
  263. }
  264. } else {
  265. await serializeValue(data, 0);
  266. }
  267. }
  268. async function serializeCircularReference(data, value) {
  269. const index = data.objects.indexOf(value);
  270. await serializeValue(data, index);
  271. }
  272. async function serializeArray(data, array) {
  273. await serializeValue(data, array.length);
  274. const notEmptyIndexes = Object.keys(array).filter(key => testInteger(Number(key))).map(key => Number(key));
  275. let indexNotEmptyIndexes = 0, currentNotEmptyIndex = notEmptyIndexes[indexNotEmptyIndexes];
  276. for (const [indexArray, value] of array.entries()) {
  277. if (currentNotEmptyIndex == indexArray) {
  278. currentNotEmptyIndex = notEmptyIndexes[++indexNotEmptyIndexes];
  279. await serializeValue(data, value);
  280. } else {
  281. await serializeValue(data, EMPTY_SLOT_VALUE);
  282. }
  283. }
  284. }
  285. async function serializeString(data, string) {
  286. const encodedString = textEncoder.encode(string);
  287. await serializeValue(data, encodedString.length);
  288. await data.append(encodedString);
  289. }
  290. async function serializeTypedArray(data, array) {
  291. await serializeValue(data, array.length);
  292. await data.append(array.constructor.name == "Uint8Array" ? array : new Uint8Array(array.buffer));
  293. }
  294. async function serializeArrayBuffer(data, arrayBuffer) {
  295. await serializeValue(data, arrayBuffer.byteLength);
  296. await data.append(new Uint8Array(arrayBuffer));
  297. }
  298. async function serializeNumber(data, number) {
  299. const serializedNumber = new Uint8Array(new Float64Array([number]).buffer);
  300. await data.append(serializedNumber);
  301. }
  302. async function serializeUint32(data, number) {
  303. const serializedNumber = new Uint8Array(new Uint32Array([number]).buffer);
  304. await data.append(serializedNumber);
  305. }
  306. async function serializeInt32(data, number) {
  307. const serializedNumber = new Uint8Array(new Int32Array([number]).buffer);
  308. await data.append(serializedNumber);
  309. }
  310. async function serializeUint16(data, number) {
  311. const serializedNumber = new Uint8Array(new Uint16Array([number]).buffer);
  312. await data.append(serializedNumber);
  313. }
  314. async function serializeInt16(data, number) {
  315. const serializedNumber = new Uint8Array(new Int16Array([number]).buffer);
  316. await data.append(serializedNumber);
  317. }
  318. async function serializeUint8(data, number) {
  319. const serializedNumber = new Uint8Array([number]);
  320. await data.append(serializedNumber);
  321. }
  322. async function serializeInt8(data, number) {
  323. const serializedNumber = new Uint8Array(new Int8Array([number]).buffer);
  324. await data.append(serializedNumber);
  325. }
  326. async function serializeBoolean(data, boolean) {
  327. const serializedBoolean = new Uint8Array([Number(boolean)]);
  328. await data.append(serializedBoolean);
  329. }
  330. async function serializeMap(data, map) {
  331. const entries = map.entries();
  332. await serializeValue(data, map.size);
  333. for (const [key, value] of entries) {
  334. await serializeValue(data, key);
  335. await serializeValue(data, value);
  336. }
  337. }
  338. async function serializeSet(data, set) {
  339. await serializeValue(data, set.size);
  340. for (const value of set) {
  341. await serializeValue(data, value);
  342. }
  343. }
  344. async function serializeDate(data, date) {
  345. await serializeNumber(data, date.getTime());
  346. }
  347. async function serializeError(data, error) {
  348. await serializeString(data, error.message);
  349. await serializeString(data, error.stack);
  350. }
  351. async function serializeRegExp(data, regExp) {
  352. await serializeString(data, regExp.source);
  353. await serializeString(data, regExp.flags);
  354. }
  355. async function serializeStringObject(data, string) {
  356. await serializeString(data, string.valueOf());
  357. }
  358. async function serializeNumberObject(data, number) {
  359. await serializeNumber(data, number.valueOf());
  360. }
  361. async function serializeBooleanObject(data, boolean) {
  362. await serializeBoolean(data, boolean.valueOf());
  363. }
  364. async function serializeSymbol(data, symbol) {
  365. await serializeString(data, symbol.description);
  366. }
  367. class Reference {
  368. constructor(index, data) {
  369. this.index = index;
  370. this.data = data;
  371. }
  372. getObject() {
  373. return this.data.objects[this.index];
  374. }
  375. }
  376. async function parseValue(data) {
  377. const array = await data.consume(1);
  378. const parserType = array[0];
  379. const parse = types[parserType].parse;
  380. const valueId = data.getObjectId();
  381. const result = await parse(data);
  382. if (parserType != TYPE_REFERENCE && testObject(result)) {
  383. await parseSymbols(data, result);
  384. await parseOwnProperties(data, result);
  385. }
  386. data.resolveObject(valueId, result);
  387. return result;
  388. }
  389. async function parseSymbols(data, value) {
  390. const symbols = await parseArray(data);
  391. data.setObject([symbols], symbols => symbols.forEach(([symbol, propertyValue]) => value[symbol] = propertyValue));
  392. }
  393. async function parseOwnProperties(data, object) {
  394. const size = await parseValue(data);
  395. if (size) {
  396. await parseNextProperty();
  397. }
  398. async function parseNextProperty(indexKey = 0) {
  399. const key = await parseString(data);
  400. const value = await parseValue(data);
  401. data.setObject([value], value => object[key] = value);
  402. if (indexKey < size - 1) {
  403. await parseNextProperty(indexKey + 1);
  404. }
  405. }
  406. }
  407. async function parseCircularReference(data) {
  408. const index = await parseValue(data);
  409. const result = new Reference(index, data);
  410. return result;
  411. }
  412. function parseObject() {
  413. return {};
  414. }
  415. async function parseArray(data) {
  416. const length = await parseValue(data);
  417. const array = new Array(length);
  418. if (length) {
  419. await parseNextSlot();
  420. }
  421. return array;
  422. async function parseNextSlot(indexArray = 0) {
  423. const value = await parseValue(data);
  424. if (!testEmptySlot(value)) {
  425. data.setObject([value], value => array[indexArray] = value);
  426. }
  427. if (indexArray < length - 1) {
  428. await parseNextSlot(indexArray + 1);
  429. }
  430. }
  431. }
  432. function parseEmptySlot() {
  433. return EMPTY_SLOT_VALUE;
  434. }
  435. async function parseString(data) {
  436. const size = await parseValue(data);
  437. const array = await data.consume(size);
  438. return textDecoder.decode(array);
  439. }
  440. async function parseFloat64Array(data) {
  441. const length = await parseValue(data);
  442. const array = await data.consume(length * 8);
  443. return new Float64Array(array.buffer);
  444. }
  445. async function parseFloat32Array(data) {
  446. const length = await parseValue(data);
  447. const array = await data.consume(length * 4);
  448. return new Float32Array(array.buffer);
  449. }
  450. async function parseUint32Array(data) {
  451. const length = await parseValue(data);
  452. const array = await data.consume(length * 4);
  453. return new Uint32Array(array.buffer);
  454. }
  455. async function parseInt32Array(data) {
  456. const length = await parseValue(data);
  457. const array = await data.consume(length * 4);
  458. return new Int32Array(array.buffer);
  459. }
  460. async function parseUint16Array(data) {
  461. const length = await parseValue(data);
  462. const array = await data.consume(length * 2);
  463. return new Uint16Array(array.buffer);
  464. }
  465. async function parseInt16Array(data) {
  466. const length = await parseValue(data);
  467. const array = await data.consume(length * 2);
  468. return new Int16Array(array.buffer);
  469. }
  470. async function parseUint8ClampedArray(data) {
  471. const length = await parseValue(data);
  472. const array = await data.consume(length);
  473. return new Uint8ClampedArray(array.buffer);
  474. }
  475. async function parseUint8Array(data) {
  476. const length = await parseValue(data);
  477. const array = await data.consume(length);
  478. return array;
  479. }
  480. async function parseInt8Array(data) {
  481. const length = await parseValue(data);
  482. const array = await data.consume(length);
  483. return new Int8Array(array.buffer);
  484. }
  485. async function parseArrayBuffer(data) {
  486. const length = await parseValue(data);
  487. const array = await data.consume(length);
  488. return array.buffer;
  489. }
  490. async function parseNumber(data) {
  491. const array = await data.consume(8);
  492. return new Float64Array(array.buffer)[0];
  493. }
  494. async function parseUint32(data) {
  495. const array = await data.consume(4);
  496. return new Uint32Array(array.buffer)[0];
  497. }
  498. async function parseInt32(data) {
  499. const array = await data.consume(4);
  500. return new Int32Array(array.buffer)[0];
  501. }
  502. async function parseUint16(data) {
  503. const array = await data.consume(2);
  504. return new Uint16Array(array.buffer)[0];
  505. }
  506. async function parseInt16(data) {
  507. const array = await data.consume(2);
  508. return new Int16Array(array.buffer)[0];
  509. }
  510. async function parseUint8(data) {
  511. const array = await data.consume(1);
  512. return new Uint8Array(array.buffer)[0];
  513. }
  514. async function parseInt8(data) {
  515. const array = await data.consume(1);
  516. return new Int8Array(array.buffer)[0];
  517. }
  518. function parseUndefined() {
  519. return undefined;
  520. }
  521. function parseNull() {
  522. return null;
  523. }
  524. function parseNaN() {
  525. return NaN;
  526. }
  527. async function parseBoolean(data) {
  528. const array = await data.consume(1);
  529. return Boolean(array[0]);
  530. }
  531. async function parseMap(data) {
  532. const size = await parseValue(data);
  533. const map = new Map();
  534. if (size) {
  535. await parseNextEntry();
  536. }
  537. return map;
  538. async function parseNextEntry(indexKey = 0) {
  539. const key = await parseValue(data);
  540. const value = await parseValue(data);
  541. data.setObject([key, value], (key, value) => map.set(key, value));
  542. if (indexKey < size - 1) {
  543. await parseNextEntry(indexKey + 1);
  544. }
  545. }
  546. }
  547. async function parseSet(data) {
  548. const size = await parseValue(data);
  549. const set = new Set();
  550. if (size) {
  551. await parseNextEntry();
  552. }
  553. return set;
  554. async function parseNextEntry(indexKey = 0) {
  555. const value = await parseValue(data);
  556. data.setObject([value], value => set.add(value));
  557. if (indexKey < size - 1) {
  558. await parseNextEntry(indexKey + 1);
  559. }
  560. }
  561. }
  562. async function parseDate(data) {
  563. const milliseconds = await parseNumber(data);
  564. return new Date(milliseconds);
  565. }
  566. async function parseError(data) {
  567. const message = await parseString(data);
  568. const stack = await parseString(data);
  569. const error = new Error(message);
  570. error.stack = stack;
  571. return error;
  572. }
  573. async function parseRegExp(data) {
  574. const source = await parseString(data);
  575. const flags = await parseString(data);
  576. return new RegExp(source, flags);
  577. }
  578. async function parseStringObject(data) {
  579. return new String(await parseString(data));
  580. }
  581. async function parseNumberObject(data) {
  582. return new Number(await parseNumber(data));
  583. }
  584. async function parseBooleanObject(data) {
  585. return new Boolean(await parseBoolean(data));
  586. }
  587. async function parseSymbol(data) {
  588. const description = await parseString(data);
  589. return Symbol(description);
  590. }
  591. function testCircularReference(value, data) {
  592. return testObject(value) && data.objects.includes(value);
  593. }
  594. function testObject(value) {
  595. return value === Object(value);
  596. }
  597. function testArray(value) {
  598. return typeof value.length == "number";
  599. }
  600. function testEmptySlot(value) {
  601. return value === EMPTY_SLOT_VALUE;
  602. }
  603. function testString(value) {
  604. return typeof value == "string";
  605. }
  606. function testFloat64Array(value) {
  607. return value.constructor.name == "Float64Array";
  608. }
  609. function testUint32Array(value) {
  610. return value.constructor.name == "Uint32Array";
  611. }
  612. function testInt32Array(value) {
  613. return value.constructor.name == "Int32Array";
  614. }
  615. function testUint16Array(value) {
  616. return value.constructor.name == "Uint16Array";
  617. }
  618. function testFloat32Array(value) {
  619. return value.constructor.name == "Float32Array";
  620. }
  621. function testInt16Array(value) {
  622. return value.constructor.name == "Int16Array";
  623. }
  624. function testUint8ClampedArray(value) {
  625. return value.constructor.name == "Uint8ClampedArray";
  626. }
  627. function testUint8Array(value) {
  628. return value.constructor.name == "Uint8Array";
  629. }
  630. function testInt8Array(value) {
  631. return value.constructor.name == "Int8Array";
  632. }
  633. function testArrayBuffer(value) {
  634. return value.constructor.name == "ArrayBuffer";
  635. }
  636. function testNumber(value) {
  637. return typeof value == "number";
  638. }
  639. function testUint32(value) {
  640. return testInteger(value) && value >= 0 && value <= 4294967295;
  641. }
  642. function testInt32(value) {
  643. return testInteger(value) && value >= -2147483648 && value <= 2147483647;
  644. }
  645. function testUint16(value) {
  646. return testInteger(value) && value >= 0 && value <= 65535;
  647. }
  648. function testInt16(value) {
  649. return testInteger(value) && value >= -32768 && value <= 32767;
  650. }
  651. function testUint8(value) {
  652. return testInteger(value) && value >= 0 && value <= 255;
  653. }
  654. function testInt8(value) {
  655. return testInteger(value) && value >= -128 && value <= 127;
  656. }
  657. function testInteger(value) {
  658. return testNumber(value) && Number.isInteger(value);
  659. }
  660. function testUndefined(value) {
  661. return value === undefined;
  662. }
  663. function testNull(value) {
  664. return value === null;
  665. }
  666. function testNaN(value) {
  667. return Number.isNaN(value);
  668. }
  669. function testBoolean(value) {
  670. return typeof value == "boolean";
  671. }
  672. function testMap(value) {
  673. return value instanceof Map;
  674. }
  675. function testSet(value) {
  676. return value instanceof Set;
  677. }
  678. function testDate(value) {
  679. return value instanceof Date;
  680. }
  681. function testError(value) {
  682. return value instanceof Error;
  683. }
  684. function testRegExp(value) {
  685. return value instanceof RegExp;
  686. }
  687. function testStringObject(value) {
  688. return value instanceof String;
  689. }
  690. function testNumberObject(value) {
  691. return value instanceof Number;
  692. }
  693. function testBooleanObject(value) {
  694. return value instanceof Boolean;
  695. }
  696. function testSymbol(value) {
  697. return typeof value == "symbol";
  698. }
  699. /*
  700. * Copyright 2010-2020 Gildas Lormeau
  701. * contact : gildas.lormeau <at> gmail.com
  702. *
  703. * This file is part of SingleFile.
  704. *
  705. * The code in this file is free software: you can redistribute it and/or
  706. * modify it under the terms of the GNU Affero General Public License
  707. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  708. * of the License, or (at your option) any later version.
  709. *
  710. * The code in this file is distributed in the hope that it will be useful,
  711. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  712. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  713. * General Public License for more details.
  714. *
  715. * As additional permission under GNU AGPL version 3 section 7, you may
  716. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  717. * AGPL normally required by section 4, provided you include this license
  718. * notice and a URL through which recipients can access the Corresponding
  719. * Source.
  720. */
  721. let EMBEDDED_IMAGE_BUTTON_MESSAGE, SHARE_PAGE_BUTTON_MESSAGE, SHARE_SELECTION_BUTTON_MESSAGE, ERROR_TITLE_MESSAGE;
  722. try {
  723. EMBEDDED_IMAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelEmbeddedImageButton");
  724. SHARE_PAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelSharePageButton");
  725. SHARE_SELECTION_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelShareSelectionButton");
  726. ERROR_TITLE_MESSAGE = browser.i18n.getMessage("topPanelError");
  727. } catch (error) {
  728. // ignored
  729. }
  730. let sharePageBar;
  731. setLabels({
  732. EMBEDDED_IMAGE_BUTTON_MESSAGE,
  733. SHARE_PAGE_BUTTON_MESSAGE,
  734. SHARE_SELECTION_BUTTON_MESSAGE,
  735. ERROR_TITLE_MESSAGE
  736. });
  737. async function downloadPageForeground(pageData, options) {
  738. if (options.sharePage && navigator.share) {
  739. await sharePage(pageData, options);
  740. } else {
  741. if (pageData.filename && pageData.filename.length) {
  742. const link = document.createElement("a");
  743. link.download = pageData.filename;
  744. link.href = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  745. link.dispatchEvent(new MouseEvent("click"));
  746. return new Promise(resolve => setTimeout(() => { URL.revokeObjectURL(link.href); resolve(); }, 1000));
  747. }
  748. }
  749. }
  750. async function sharePage(pageData, options) {
  751. sharePageBar = getSharePageBar();
  752. debugger;
  753. const cancelled = await sharePageBar.display(options.selected);
  754. if (!cancelled) {
  755. const data = { files: [new File([pageData.content], pageData.filename, { type: pageData.mimeType })] };
  756. try {
  757. await navigator.share(data);
  758. sharePageBar.hide();
  759. } catch (error) {
  760. sharePageBar.hide();
  761. if (error.name === "AbortError") {
  762. await sharePage(pageData, options);
  763. } else {
  764. throw error;
  765. }
  766. }
  767. }
  768. }
  769. /*
  770. * Copyright 2010-2020 Gildas Lormeau
  771. * contact : gildas.lormeau <at> gmail.com
  772. *
  773. * This file is part of SingleFile.
  774. *
  775. * The code in this file is free software: you can redistribute it and/or
  776. * modify it under the terms of the GNU Affero General Public License
  777. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  778. * of the License, or (at your option) any later version.
  779. *
  780. * The code in this file is distributed in the hope that it will be useful,
  781. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  782. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  783. * General Public License for more details.
  784. *
  785. * As additional permission under GNU AGPL version 3 section 7, you may
  786. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  787. * AGPL normally required by section 4, provided you include this license
  788. * notice and a URL through which recipients can access the Corresponding
  789. * Source.
  790. */
  791. (globalThis => {
  792. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  793. const singlefile = globalThis.singlefile;
  794. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  795. 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";
  796. 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==";
  797. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  798. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  799. const SCRIPT_OPTIONS = "data-single-file-options";
  800. const NOTE_TAGNAME = "single-file-note";
  801. const NOTE_CLASS = "note";
  802. const NOTE_MASK_CLASS = "note-mask";
  803. const NOTE_HIDDEN_CLASS = "note-hidden";
  804. const NOTE_ANCHORED_CLASS = "note-anchored";
  805. const NOTE_SELECTED_CLASS = "note-selected";
  806. const NOTE_MOVING_CLASS = "note-moving";
  807. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  808. const PAGE_MASK_CLASS = "page-mask";
  809. const MASK_CLASS = "single-file-mask";
  810. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  811. const HIGHLIGHT_CLASS = "single-file-highlight";
  812. const HIGHLIGHTS_STYLESHEET_CLASS = "single-file-highlights-stylesheet";
  813. const REMOVED_CONTENT_CLASS = "single-file-removed";
  814. const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
  815. const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
  816. const CUT_HOVER_CLASS = "single-file-cut-hover";
  817. const CUT_OUTER_HOVER_CLASS = "single-file-cut-outer-hover";
  818. const CUT_SELECTED_CLASS = "single-file-cut-selected";
  819. const CUT_OUTER_SELECTED_CLASS = "single-file-cut-outer-selected";
  820. const CUT_MODE_CLASS = "single-file-cut-mode";
  821. const NOTE_INITIAL_POSITION_X = 20;
  822. const NOTE_INITIAL_POSITION_Y = 20;
  823. const NOTE_INITIAL_WIDTH = 150;
  824. const NOTE_INITIAL_HEIGHT = 150;
  825. const NOTE_HEADER_HEIGHT = 25;
  826. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  827. const COMMENT_HEADER = "Page saved with SingleFile";
  828. const COMMENT_HEADER_LEGACY = "Archive processed by SingleFile";
  829. const STYLE_FORMATTED_PAGE = `
  830. /* This Source Code Form is subject to the terms of the Mozilla Public
  831. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  832. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  833. /* Avoid adding ID selector rules in this style sheet, since they could
  834. * inadvertently match elements in the article content. */
  835. :root {
  836. --grey-90-a10: rgba(12, 12, 13, 0.1);
  837. --grey-90-a20: rgba(12, 12, 13, 0.2);
  838. --grey-90-a30: rgba(12, 12, 13, 0.3);
  839. --grey-90-a80: rgba(12, 12, 13, 0.8);
  840. --grey-30: #d7d7db;
  841. --blue-40: #45a1ff;
  842. --blue-40-a30: rgba(69, 161, 255, 0.3);
  843. --blue-60: #0060df;
  844. --body-padding: 64px;
  845. --font-size: 12;
  846. --content-width: 70em;
  847. --line-height: 1.6em;
  848. }
  849. body {
  850. --main-background: #fff;
  851. --main-foreground: #333;
  852. --font-color: #000000;
  853. --primary-color: #0B83FF;
  854. --toolbar-border: var(--grey-90-a20);
  855. --toolbar-transparent-border: transparent;
  856. --toolbar-box-shadow: var(--grey-90-a10);
  857. --toolbar-button-background: transparent;
  858. --toolbar-button-background-hover: var(--grey-90-a10);
  859. --toolbar-button-foreground-hover: var(--font-color);
  860. --toolbar-button-background-active: var(--grey-90-a20);
  861. --toolbar-button-foreground-active: var(--primary-color);
  862. --toolbar-button-border: transparent;
  863. --toolbar-button-border-hover: transparent;
  864. --toolbar-button-border-active: transparent;
  865. --tooltip-background: var(--grey-90-a80);
  866. --tooltip-foreground: white;
  867. --tooltip-border: transparent;
  868. --popup-background: white;
  869. --popup-border: rgba(0, 0, 0, 0.12);
  870. --opaque-popup-border: #e0e0e0;
  871. --popup-line: var(--grey-30);
  872. --popup-shadow: rgba(49, 49, 49, 0.3);
  873. --popup-button-background: #edecf0;
  874. --popup-button-background-hover: hsla(0,0%,70%,.4);
  875. --popup-button-foreground-hover: var(--font-color);
  876. --popup-button-background-active: hsla(240,5%,5%,.15);
  877. --selected-background: var(--blue-40-a30);
  878. --selected-border: var(--blue-40);
  879. --font-value-border: var(--grey-30);
  880. --icon-fill: #3b3b3c;
  881. --icon-disabled-fill: #8080807F;
  882. --link-foreground: var(--blue-60);
  883. --link-selected-foreground: #333;
  884. --visited-link-foreground: #b5007f;
  885. /* light colours */
  886. }
  887. body.sepia {
  888. --main-background: #f4ecd8;
  889. --main-foreground: #5b4636;
  890. --toolbar-border: #5b4636;
  891. }
  892. body.dark {
  893. --main-background: rgb(28, 27, 34);
  894. --main-foreground: #eee;
  895. --font-color: #fff;
  896. --toolbar-border: #4a4a4b;
  897. --toolbar-box-shadow: black;
  898. --toolbar-button-background-hover: var(--grey-90-a30);
  899. --toolbar-button-background-active: var(--grey-90-a80);
  900. --tooltip-background: black;
  901. --tooltip-foreground: white;
  902. --popup-background: rgb(66,65,77);
  903. --opaque-popup-border: #434146;
  904. --popup-line: rgb(82, 82, 94);
  905. --popup-button-background: #5c5c61;
  906. --popup-button-background-active: hsla(0,0%,70%,.6);
  907. --selected-background: #3E6D9A;
  908. --font-value-border: #656468;
  909. --icon-fill: #fff;
  910. --icon-disabled-fill: #ffffff66;
  911. --link-foreground: #45a1ff;
  912. --link-selected-foreground: #fff;
  913. --visited-link-foreground: #e675fd;
  914. /* dark colours */
  915. }
  916. body.hcm {
  917. --main-background: Canvas;
  918. --main-foreground: CanvasText;
  919. --font-color: CanvasText;
  920. --primary-color: SelectedItem;
  921. --toolbar-border: CanvasText;
  922. /* We need a true transparent but in HCM this would compute to an actual color,
  923. so select the page's background color instead: */
  924. --toolbar-transparent-border: Canvas;
  925. --toolbar-box-shadow: Canvas;
  926. --toolbar-button-background: ButtonFace;
  927. --toolbar-button-background-hover: ButtonText;
  928. --toolbar-button-foreground-hover: ButtonFace;
  929. --toolbar-button-background-active: SelectedItem;
  930. --toolbar-button-foreground-active: SelectedItemText;
  931. --toolbar-button-border: ButtonText;
  932. --toolbar-button-border-hover: ButtonText;
  933. --toolbar-button-border-active: ButtonText;
  934. --tooltip-background: Canvas;
  935. --tooltip-foreground: CanvasText;
  936. --tooltip-border: CanvasText;
  937. --popup-background: Canvas;
  938. --popup-border: CanvasText;
  939. --opaque-popup-border: CanvasText;
  940. --popup-line: CanvasText;
  941. --popup-button-background: ButtonFace;
  942. --popup-button-background-hover: ButtonText;
  943. --popup-button-foreground-hover: ButtonFace;
  944. --popup-button-background-active: ButtonText;
  945. --selected-background: Canvas;
  946. --selected-border: SelectedItem;
  947. --font-value-border: CanvasText;
  948. --icon-fill: ButtonText;
  949. --icon-disabled-fill: GrayText;
  950. --link-foreground: LinkText;
  951. --link-selected-foreground: ActiveText;
  952. --visited-link-foreground: VisitedText;
  953. }
  954. body {
  955. margin: 0;
  956. padding: var(--body-padding);
  957. background-color: var(--main-background);
  958. color: var(--main-foreground);
  959. }
  960. body.loaded {
  961. transition: color 0.4s, background-color 0.4s;
  962. }
  963. body.dark *::-moz-selection {
  964. background-color: var(--selected-background);
  965. }
  966. a::-moz-selection {
  967. color: var(--link-selected-foreground);
  968. }
  969. body.sans-serif,
  970. body.sans-serif .remove-button {
  971. font-family: Helvetica, Arial, sans-serif;
  972. }
  973. body.serif,
  974. body.serif .remove-button {
  975. font-family: Georgia, "Times New Roman", serif;
  976. }
  977. /* Override some controls and content styles based on color scheme */
  978. body.light > .container > .header > .domain {
  979. border-bottom-color: #333333 !important;
  980. }
  981. body.sepia > .container > .header > .domain {
  982. border-bottom-color: #5b4636 !important;
  983. }
  984. body.dark > .container > .header > .domain {
  985. border-bottom-color: #eeeeee !important;
  986. }
  987. body.light blockquote {
  988. border-inline-start: 2px solid #333333 !important;
  989. }
  990. body.sepia blockquote {
  991. border-inline-start: 2px solid #5b4636 !important;
  992. }
  993. body.dark blockquote {
  994. border-inline-start: 2px solid #eeeeee !important;
  995. }
  996. .light-button {
  997. color: #333333;
  998. background-color: #ffffff;
  999. }
  1000. .dark-button {
  1001. color: #eeeeee;
  1002. background-color: #1c1b22;
  1003. }
  1004. .sepia-button {
  1005. color: #5b4636;
  1006. background-color: #f4ecd8;
  1007. }
  1008. .auto-button {
  1009. text-align: center;
  1010. }
  1011. @media (prefers-color-scheme: dark) {
  1012. .auto-button {
  1013. background-color: #1c1b22;
  1014. color: #eeeeee;
  1015. }
  1016. }
  1017. @media not (prefers-color-scheme: dark) {
  1018. .auto-button {
  1019. background-color: #ffffff;
  1020. color: #333333;
  1021. }
  1022. }
  1023. /* Loading/error message */
  1024. .reader-message {
  1025. margin-top: 40px;
  1026. display: none;
  1027. text-align: center;
  1028. width: 100%;
  1029. font-size: 0.9em;
  1030. }
  1031. /* Detector element to see if we're at the top of the doc or not. */
  1032. .top-anchor {
  1033. position: absolute;
  1034. top: 0;
  1035. width: 0;
  1036. height: 5px;
  1037. pointer-events: none;
  1038. }
  1039. /* Header */
  1040. .header {
  1041. text-align: start;
  1042. display: none;
  1043. }
  1044. .domain {
  1045. font-size: 0.9em;
  1046. line-height: 1.48em;
  1047. padding-bottom: 4px;
  1048. font-family: Helvetica, Arial, sans-serif;
  1049. text-decoration: none;
  1050. border-bottom: 1px solid;
  1051. color: var(--link-foreground);
  1052. }
  1053. .header > h1 {
  1054. font-size: 1.6em;
  1055. line-height: 1.25em;
  1056. width: 100%;
  1057. margin: 30px 0;
  1058. padding: 0;
  1059. }
  1060. .header > .credits {
  1061. font-size: 0.9em;
  1062. line-height: 1.48em;
  1063. margin: 0 0 10px;
  1064. padding: 0;
  1065. font-style: italic;
  1066. }
  1067. .header > .meta-data {
  1068. font-size: 0.65em;
  1069. margin: 0 0 15px;
  1070. }
  1071. .reader-estimated-time {
  1072. text-align: match-parent;
  1073. }
  1074. /* Controls toolbar */
  1075. .toolbar-container {
  1076. position: sticky;
  1077. z-index: 2;
  1078. top: 32px;
  1079. height: 0; /* take up no space, so body is at the top. */
  1080. /* As a stick container, we're positioned relative to the body. Move us to
  1081. * the edge of the viewport using margins, and take the width of
  1082. * the body padding into account for calculating our width.
  1083. */
  1084. margin-inline-start: calc(-1 * var(--body-padding));
  1085. width: max(var(--body-padding), calc((100% - var(--content-width)) / 2 + var(--body-padding)));
  1086. font-size: var(--font-size); /* Needed to ensure 'em' units match, is reset for .reader-controls */
  1087. }
  1088. .toolbar {
  1089. padding-block: 16px;
  1090. border: 1px solid var(--toolbar-border);
  1091. border-radius: 6px;
  1092. box-shadow: 0 2px 8px var(--toolbar-box-shadow);
  1093. width: 32px; /* basic width, without padding/border */
  1094. /* padding should be 16px, except if there's not enough space for that, in
  1095. * which case use half the available space for padding (=25% on each side).
  1096. * The 34px here is the width + borders. We use a variable because we need
  1097. * to know this size for the margin calculation.
  1098. */
  1099. --inline-padding: min(16px, calc(25% - 0.25 * 34px));
  1100. padding-inline: var(--inline-padding);
  1101. /* Keep a maximum of 96px distance to the body, but center once the margin
  1102. * gets too small. We need to set the start margin, however...
  1103. * To center, we'd want 50% of the container, but we'd subtract half our
  1104. * own width (16px) and half the border (1px) and the inline padding.
  1105. * When the other margin would be 96px, we want 100% - 96px - the complete
  1106. * width of the actual toolbar (34px + 2 * padding)
  1107. */
  1108. margin-inline-start: max(calc(50% - 17px - var(--inline-padding)), calc(100% - 96px - 34px - 2 * var(--inline-padding)));
  1109. font-family: Helvetica, Arial, sans-serif;
  1110. list-style: none;
  1111. user-select: none;
  1112. }
  1113. @media (prefers-reduced-motion: no-preference) {
  1114. .toolbar {
  1115. transition-property: border-color, box-shadow;
  1116. transition-duration: 250ms;
  1117. }
  1118. .toolbar .toolbar-button {
  1119. transition-property: opacity;
  1120. transition-duration: 250ms;
  1121. }
  1122. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) {
  1123. border-color: var(--toolbar-transparent-border);
  1124. box-shadow: 0 2px 8px transparent;
  1125. }
  1126. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) .toolbar-button {
  1127. opacity: 0.6;
  1128. }
  1129. .toolbar-container.transition-location {
  1130. transition-duration: 250ms;
  1131. transition-property: width;
  1132. }
  1133. }
  1134. .toolbar-container.overlaps .toolbar-button {
  1135. opacity: 0.1;
  1136. }
  1137. .dropdown-open .toolbar {
  1138. border-color: var(--toolbar-transparent-border);
  1139. box-shadow: 0 2px 8px transparent;
  1140. }
  1141. .reader-controls {
  1142. /* We use 'em's above this node to get it to the right size. However,
  1143. * the UI inside the toolbar should use a fixed, smaller size. */
  1144. font-size: 11px;
  1145. }
  1146. button {
  1147. -moz-context-properties: fill;
  1148. color: var(--font-color);
  1149. fill: var(--icon-fill);
  1150. }
  1151. button:disabled {
  1152. fill: var(--icon-disabled-fill);
  1153. }
  1154. .toolbar button::-moz-focus-inner {
  1155. border: 0;
  1156. }
  1157. .toolbar-button {
  1158. position: relative;
  1159. width: 32px;
  1160. height: 32px;
  1161. padding: 0;
  1162. border: 1px solid var(--toolbar-button-border);
  1163. border-radius: 4px;
  1164. margin: 4px 0;
  1165. background-color: var(--toolbar-button-background);
  1166. background-size: 16px 16px;
  1167. background-position: center;
  1168. background-repeat: no-repeat;
  1169. }
  1170. .toolbar-button:hover,
  1171. .toolbar-button:focus-visible {
  1172. background-color: var(--toolbar-button-background-hover);
  1173. border-color: var(--toolbar-button-border-hover);
  1174. fill: var(--toolbar-button-foreground-hover);
  1175. }
  1176. .open .toolbar-button,
  1177. .toolbar-button:hover:active {
  1178. background-color: var(--toolbar-button-background-active);
  1179. border-color: var(--toolbar-button-border-active);
  1180. color: var(--toolbar-button-foreground-active);
  1181. fill: var(--toolbar-button-foreground-active);
  1182. }
  1183. .hover-label {
  1184. position: absolute;
  1185. top: 4px;
  1186. inset-inline-start: 36px;
  1187. line-height: 16px;
  1188. white-space: pre; /* make sure we don't wrap */
  1189. background-color: var(--tooltip-background);
  1190. color: var(--tooltip-foreground);
  1191. padding: 4px 8px;
  1192. border: 1px solid var(--tooltip-border);
  1193. border-radius: 2px;
  1194. visibility: hidden;
  1195. pointer-events: none;
  1196. /* Put above .dropdown .dropdown-popup, which has z-index: 1000. */
  1197. z-index: 1001;
  1198. }
  1199. /* Show the hover tooltip on non-dropdown buttons. */
  1200. .toolbar-button:not(.dropdown-toggle):hover > .hover-label,
  1201. .toolbar-button:not(.dropdown-toggle):focus-visible > .hover-label,
  1202. /* Show the hover tooltip for dropdown buttons unless its dropdown is open. */
  1203. :not(.open) > li > .dropdown-toggle:hover > .hover-label,
  1204. :not(.open) > li > .dropdown-toggle:focus-visible > .hover-label {
  1205. visibility: visible;
  1206. }
  1207. .dropdown {
  1208. text-align: center;
  1209. list-style: none;
  1210. margin: 0;
  1211. padding: 0;
  1212. position: relative;
  1213. }
  1214. .dropdown li {
  1215. margin: 0;
  1216. padding: 0;
  1217. }
  1218. /* Popup */
  1219. .dropdown .dropdown-popup {
  1220. text-align: start;
  1221. position: absolute;
  1222. inset-inline-start: 40px;
  1223. z-index: 1000;
  1224. background-color: var(--popup-background);
  1225. visibility: hidden;
  1226. border-radius: 4px;
  1227. border: 1px solid var(--popup-border);
  1228. box-shadow: 0 0 10px 0 var(--popup-shadow);
  1229. top: 0;
  1230. }
  1231. .open > .dropdown-popup {
  1232. visibility: visible;
  1233. }
  1234. .dropdown-arrow {
  1235. position: absolute;
  1236. height: 24px;
  1237. width: 16px;
  1238. inset-inline-start: -16px;
  1239. background-image: url("chrome://global/skin/reader/RM-Type-Controls-Arrow.svg");
  1240. display: block;
  1241. -moz-context-properties: fill, stroke;
  1242. fill: var(--popup-background);
  1243. stroke: var(--opaque-popup-border);
  1244. pointer-events: none;
  1245. }
  1246. .dropdown-arrow:dir(rtl) {
  1247. transform: scaleX(-1);
  1248. }
  1249. /* Align the style dropdown arrow (narrate does its own) */
  1250. .style-dropdown .dropdown-arrow {
  1251. top: 7px;
  1252. }
  1253. /* Font style popup */
  1254. .radio-button {
  1255. /* We visually hide these, but we keep them around so they can be focused
  1256. * and changed by interacting with them via the label, or the keyboard, or
  1257. * assistive technology.
  1258. */
  1259. opacity: 0;
  1260. pointer-events: none;
  1261. position: absolute;
  1262. }
  1263. .radiorow,
  1264. .buttonrow {
  1265. display: flex;
  1266. align-content: center;
  1267. justify-content: center;
  1268. }
  1269. .content-width-value,
  1270. .font-size-value,
  1271. .line-height-value {
  1272. box-sizing: border-box;
  1273. width: 36px;
  1274. height: 20px;
  1275. line-height: 20px;
  1276. display: flex;
  1277. justify-content: center;
  1278. align-content: center;
  1279. margin: auto;
  1280. border-radius: 10px;
  1281. border: 1px solid var(--font-value-border);
  1282. background-color: var(--popup-button-background);
  1283. }
  1284. .buttonrow > button {
  1285. border: 0;
  1286. height: 60px;
  1287. width: 90px;
  1288. background-color: transparent;
  1289. background-repeat: no-repeat;
  1290. background-position: center;
  1291. }
  1292. .buttonrow > button:enabled:hover,
  1293. .buttonrow > button:enabled:focus-visible {
  1294. background-color: var(--popup-button-background-hover);
  1295. color: var(--popup-button-foreground-hover);
  1296. fill: var(--popup-button-foreground-hover);
  1297. }
  1298. .buttonrow > button:enabled:hover:active {
  1299. background-color: var(--popup-button-background-active);
  1300. }
  1301. .radiorow:not(:last-child),
  1302. .buttonrow:not(:last-child) {
  1303. border-bottom: 1px solid var(--popup-line);
  1304. }
  1305. body.hcm .buttonrow.line-height-buttons {
  1306. /* On HCM the .color-scheme-buttons row is hidden, so remove the border from the row above it */
  1307. border-bottom: none;
  1308. }
  1309. .radiorow > label {
  1310. position: relative;
  1311. box-sizing: border-box;
  1312. border-radius: 2px;
  1313. border: 2px solid var(--popup-border);
  1314. }
  1315. .radiorow > label[checked] {
  1316. border-color: var(--selected-border);
  1317. }
  1318. /* For the hover style, we draw a line under the item by means of a
  1319. * pseudo-element. Because these items are variable height, and
  1320. * because their contents are variable height, position it absolutely,
  1321. * and give it a width of 100% (the content width) + 4px for the 2 * 2px
  1322. * border width.
  1323. */
  1324. .radiorow > input[type=radio]:focus-visible + label::after,
  1325. .radiorow > label:hover::after {
  1326. content: "";
  1327. display: block;
  1328. border-bottom: 2px solid var(--selected-border);
  1329. width: calc(100% + 4px);
  1330. position: absolute;
  1331. /* to skip the 2 * 2px border + 2px spacing. */
  1332. bottom: -6px;
  1333. /* Match the start of the 2px border of the element: */
  1334. inset-inline-start: -2px;
  1335. }
  1336. .font-type-buttons > label {
  1337. height: 64px;
  1338. width: 105px;
  1339. /* Slightly more space between these items. */
  1340. margin: 10px;
  1341. /* Center the Sans-serif / Serif labels */
  1342. text-align: center;
  1343. background-size: 63px 39px;
  1344. background-repeat: no-repeat;
  1345. background-position: center 18px;
  1346. background-color: var(--popup-button-background);
  1347. fill: currentColor;
  1348. -moz-context-properties: fill;
  1349. /* This mostly matches baselines, but because of differences in font
  1350. * baselines between serif and sans-serif, this isn't always enough. */
  1351. line-height: 1;
  1352. padding-top: 2px;
  1353. }
  1354. .font-type-buttons > label[checked] {
  1355. background-color: var(--selected-background);
  1356. }
  1357. .sans-serif-button {
  1358. font-family: Helvetica, Arial, sans-serif;
  1359. background-image: url("chrome://global/skin/reader/RM-Sans-Serif.svg");
  1360. }
  1361. /* Tweak padding to match the baseline on mac */
  1362. :root[platform=macosx] .sans-serif-button {
  1363. padding-top: 3px;
  1364. }
  1365. .serif-button {
  1366. font-family: Georgia, "Times New Roman", serif;
  1367. background-image: url("chrome://global/skin/reader/RM-Serif.svg");
  1368. }
  1369. body.hcm .color-scheme-buttons {
  1370. /* Disallow selecting themes when HCM is on. */
  1371. display: none;
  1372. }
  1373. .color-scheme-buttons > label {
  1374. padding: 12px;
  1375. height: 34px;
  1376. font-size: 12px;
  1377. /* Center the labels horizontally as well as vertically */
  1378. display: inline-flex;
  1379. align-items: center;
  1380. justify-content: center;
  1381. /* We want 10px between items, but there's no margin collapsing in flexbox. */
  1382. margin: 10px 5px;
  1383. }
  1384. .color-scheme-buttons > input:first-child + label {
  1385. margin-inline-start: 10px;
  1386. }
  1387. .color-scheme-buttons > label:last-child {
  1388. margin-inline-end: 10px;
  1389. }
  1390. /* Toolbar icons */
  1391. .close-button {
  1392. background-image: url("chrome://global/skin/icons/close.svg");
  1393. }
  1394. .style-button {
  1395. background-image: url("chrome://global/skin/reader/RM-Type-Controls-24x24.svg");
  1396. }
  1397. .minus-button {
  1398. background-size: 18px 18px;
  1399. background-image: url("chrome://global/skin/reader/RM-Minus-24x24.svg");
  1400. }
  1401. .plus-button {
  1402. background-size: 18px 18px;
  1403. background-image: url("chrome://global/skin/reader/RM-Plus-24x24.svg");
  1404. }
  1405. .content-width-minus-button {
  1406. background-size: 42px 16px;
  1407. background-image: url("chrome://global/skin/reader/RM-Content-Width-Minus-42x16.svg");
  1408. }
  1409. .content-width-plus-button {
  1410. background-size: 44px 16px;
  1411. background-image: url("chrome://global/skin/reader/RM-Content-Width-Plus-44x16.svg");
  1412. }
  1413. .line-height-minus-button {
  1414. background-size: 34px 14px;
  1415. background-image: url("chrome://global/skin/reader/RM-Line-Height-Minus-38x14.svg");
  1416. }
  1417. .line-height-plus-button {
  1418. background-size: 34px 24px;
  1419. background-image: url("chrome://global/skin/reader/RM-Line-Height-Plus-38x24.svg");
  1420. }
  1421. /* Mirror the line height buttons if the article is RTL. */
  1422. .reader-controls[articledir="rtl"] .line-height-minus-button,
  1423. .reader-controls[articledir="rtl"] .line-height-plus-button {
  1424. transform: scaleX(-1);
  1425. }
  1426. @media print {
  1427. .toolbar {
  1428. display: none !important;
  1429. }
  1430. }
  1431. /* Article content */
  1432. /* Note that any class names from the original article that we want to match on
  1433. * must be added to CLASSES_TO_PRESERVE in ReaderMode.jsm, so that
  1434. * Readability.js doesn't strip them out */
  1435. .container {
  1436. margin: 0 auto;
  1437. font-size: var(--font-size);
  1438. max-width: var(--content-width);
  1439. line-height: var(--line-height);
  1440. }
  1441. pre {
  1442. font-family: inherit;
  1443. }
  1444. .moz-reader-content {
  1445. display: none;
  1446. font-size: 1em;
  1447. }
  1448. @media print {
  1449. .moz-reader-content p,
  1450. .moz-reader-content code,
  1451. .moz-reader-content pre,
  1452. .moz-reader-content blockquote,
  1453. .moz-reader-content ul,
  1454. .moz-reader-content ol,
  1455. .moz-reader-content li,
  1456. .moz-reader-content figure,
  1457. .moz-reader-content .wp-caption {
  1458. margin: 0 0 10px !important;
  1459. padding: 0 !important;
  1460. }
  1461. }
  1462. .moz-reader-content h1,
  1463. .moz-reader-content h2,
  1464. .moz-reader-content h3 {
  1465. font-weight: bold;
  1466. }
  1467. .moz-reader-content h1 {
  1468. font-size: 1.6em;
  1469. line-height: 1.25em;
  1470. }
  1471. .moz-reader-content h2 {
  1472. font-size: 1.2em;
  1473. line-height: 1.51em;
  1474. }
  1475. .moz-reader-content h3 {
  1476. font-size: 1em;
  1477. line-height: 1.66em;
  1478. }
  1479. .moz-reader-content a:link {
  1480. text-decoration: underline;
  1481. font-weight: normal;
  1482. }
  1483. .moz-reader-content a:link,
  1484. .moz-reader-content a:link:hover,
  1485. .moz-reader-content a:link:active {
  1486. color: var(--link-foreground);
  1487. }
  1488. .moz-reader-content a:visited {
  1489. color: var(--visited-link-foreground);
  1490. }
  1491. .moz-reader-content * {
  1492. max-width: 100%;
  1493. height: auto;
  1494. }
  1495. .moz-reader-content p,
  1496. .moz-reader-content p,
  1497. .moz-reader-content code,
  1498. .moz-reader-content pre,
  1499. .moz-reader-content blockquote,
  1500. .moz-reader-content ul,
  1501. .moz-reader-content ol,
  1502. .moz-reader-content li,
  1503. .moz-reader-content figure,
  1504. .moz-reader-content .wp-caption {
  1505. margin: -10px -10px 20px;
  1506. padding: 10px;
  1507. border-radius: 5px;
  1508. }
  1509. .moz-reader-content li {
  1510. margin-bottom: 0;
  1511. }
  1512. .moz-reader-content li > ul,
  1513. .moz-reader-content li > ol {
  1514. margin-bottom: -10px;
  1515. }
  1516. .moz-reader-content p > img:only-child,
  1517. .moz-reader-content p > a:only-child > img:only-child,
  1518. .moz-reader-content .wp-caption img,
  1519. .moz-reader-content figure img {
  1520. display: block;
  1521. }
  1522. .moz-reader-content img[moz-reader-center] {
  1523. margin-inline: auto;
  1524. }
  1525. .moz-reader-content .caption,
  1526. .moz-reader-content .wp-caption-text
  1527. .moz-reader-content figcaption {
  1528. font-size: 0.9em;
  1529. line-height: 1.48em;
  1530. font-style: italic;
  1531. }
  1532. .moz-reader-content pre {
  1533. white-space: pre-wrap;
  1534. }
  1535. .moz-reader-content blockquote {
  1536. padding: 0;
  1537. padding-inline-start: 16px;
  1538. }
  1539. .moz-reader-content ul,
  1540. .moz-reader-content ol {
  1541. padding: 0;
  1542. }
  1543. .moz-reader-content ul {
  1544. padding-inline-start: 30px;
  1545. list-style: disc;
  1546. }
  1547. .moz-reader-content ol {
  1548. padding-inline-start: 30px;
  1549. }
  1550. table,
  1551. th,
  1552. td {
  1553. border: 1px solid currentColor;
  1554. border-collapse: collapse;
  1555. padding: 6px;
  1556. vertical-align: top;
  1557. }
  1558. table {
  1559. margin: 5px;
  1560. }
  1561. /* Visually hide (but don't display: none) screen reader elements */
  1562. .moz-reader-content .visually-hidden,
  1563. .moz-reader-content .visuallyhidden,
  1564. .moz-reader-content .sr-only {
  1565. display: inline-block;
  1566. width: 1px;
  1567. height: 1px;
  1568. margin: -1px;
  1569. overflow: hidden;
  1570. padding: 0;
  1571. border-width: 0;
  1572. }
  1573. /* Hide elements with common "hidden" class names */
  1574. .moz-reader-content .hidden,
  1575. .moz-reader-content .invisible {
  1576. display: none;
  1577. }
  1578. /* Enforce wordpress and similar emoji/smileys aren't sized to be full-width,
  1579. * see bug 1399616 for context. */
  1580. .moz-reader-content img.wp-smiley,
  1581. .moz-reader-content img.emoji {
  1582. display: inline-block;
  1583. border-width: 0;
  1584. /* height: auto is implied from '.moz-reader-content *' rule. */
  1585. width: 1em;
  1586. margin: 0 .07em;
  1587. padding: 0;
  1588. }
  1589. .reader-show-element {
  1590. display: initial;
  1591. }
  1592. /* Provide extra spacing for images that may be aided with accompanying element such as <figcaption> */
  1593. .moz-reader-block-img:not(:last-child) {
  1594. margin-block-end: 12px;
  1595. }
  1596. .moz-reader-wide-table {
  1597. overflow-x: auto;
  1598. display: block;
  1599. }
  1600. pre code {
  1601. background-color: var(--main-background);
  1602. border: 1px solid var(--font-color);
  1603. display: block;
  1604. overflow: auto;
  1605. }`;
  1606. let NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET;
  1607. let selectedNote, anchorElement, maskNoteElement, maskPageElement, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, highlightColor, collapseNoteTimeout, cuttingOuterMode, cuttingMode, cuttingTouchTarget, cuttingPath, cuttingPathIndex, previousContent;
  1608. let removedElements = [], removedElementIndex = 0, initScriptContent, pageResources, pageUrl, pageCompressContent, includeInfobar;
  1609. globalThis.zip = singlefile.helper.zip;
  1610. initEventListeners();
  1611. new MutationObserver(initEventListeners).observe(document, { childList: true });
  1612. function initEventListeners() {
  1613. window.onmessage = async event => {
  1614. const message = JSON.parse(event.data);
  1615. if (message.method == "init") {
  1616. await init(message);
  1617. }
  1618. if (message.method == "addNote") {
  1619. addNote(message);
  1620. }
  1621. if (message.method == "displayNotes") {
  1622. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  1623. }
  1624. if (message.method == "hideNotes") {
  1625. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  1626. }
  1627. if (message.method == "enableHighlight") {
  1628. if (highlightColor) {
  1629. document.documentElement.classList.remove(highlightColor + "-mode");
  1630. }
  1631. highlightColor = message.color;
  1632. highlightSelectionMode = true;
  1633. document.documentElement.classList.add(message.color + "-mode");
  1634. }
  1635. if (message.method == "disableHighlight") {
  1636. disableHighlight();
  1637. highlightSelectionMode = false;
  1638. }
  1639. if (message.method == "displayHighlights") {
  1640. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  1641. }
  1642. if (message.method == "hideHighlights") {
  1643. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  1644. }
  1645. if (message.method == "enableRemoveHighlights") {
  1646. removeHighlightMode = true;
  1647. document.documentElement.classList.add("single-file-remove-highlights-mode");
  1648. }
  1649. if (message.method == "disableRemoveHighlights") {
  1650. removeHighlightMode = false;
  1651. document.documentElement.classList.remove("single-file-remove-highlights-mode");
  1652. }
  1653. if (message.method == "enableEditPage") {
  1654. document.body.contentEditable = true;
  1655. onUpdate(false);
  1656. }
  1657. if (message.method == "formatPage") {
  1658. formatPage(!message.applySystemTheme);
  1659. }
  1660. if (message.method == "cancelFormatPage") {
  1661. cancelFormatPage();
  1662. }
  1663. if (message.method == "disableEditPage") {
  1664. document.body.contentEditable = false;
  1665. }
  1666. if (message.method == "enableCutInnerPage") {
  1667. cuttingMode = true;
  1668. document.documentElement.classList.add(CUT_MODE_CLASS);
  1669. }
  1670. if (message.method == "enableCutOuterPage") {
  1671. cuttingOuterMode = true;
  1672. document.documentElement.classList.add(CUT_MODE_CLASS);
  1673. }
  1674. if (message.method == "disableCutInnerPage" || message.method == "disableCutOuterPage") {
  1675. if (message.method == "disableCutInnerPage") {
  1676. cuttingMode = false;
  1677. } else {
  1678. cuttingOuterMode = false;
  1679. }
  1680. document.documentElement.classList.remove(CUT_MODE_CLASS);
  1681. resetSelectedElements();
  1682. if (cuttingPath) {
  1683. unhighlightCutElement();
  1684. cuttingPath = null;
  1685. }
  1686. }
  1687. if (message.method == "undoCutPage") {
  1688. undoCutPage();
  1689. }
  1690. if (message.method == "undoAllCutPage") {
  1691. while (removedElementIndex) {
  1692. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  1693. removedElementIndex--;
  1694. }
  1695. }
  1696. if (message.method == "redoCutPage") {
  1697. redoCutPage();
  1698. }
  1699. if (message.method == "getContent") {
  1700. onUpdate(true);
  1701. includeInfobar = message.includeInfobar;
  1702. let content = getContent(message.compressHTML, message.updatedResources);
  1703. if (initScriptContent) {
  1704. content = content.replace(/<script data-template-shadow-root src.*?<\/script>/g, initScriptContent);
  1705. }
  1706. let filename;
  1707. const pageOptions = loadOptionsFromPage(document);
  1708. if (pageOptions) {
  1709. pageOptions.backgroundSave = message.backgroundSave;
  1710. pageOptions.saveDate = new Date(pageOptions.saveDate);
  1711. pageOptions.visitDate = new Date(pageOptions.visitDate);
  1712. filename = await singlefile.helper.formatFilename(content, document, pageOptions);
  1713. }
  1714. if (message.sharePage) {
  1715. setLabels(message.labels);
  1716. }
  1717. if (pageCompressContent) {
  1718. const viewport = document.head.querySelector("meta[name=viewport]");
  1719. window.parent.postMessage(JSON.stringify({
  1720. method: "setContent",
  1721. content,
  1722. filename,
  1723. title: document.title,
  1724. doctype: singlefile.helper.getDoctypeString(document),
  1725. url: pageUrl,
  1726. viewport: viewport ? viewport.content : null,
  1727. compressContent: true,
  1728. foregroundSave: message.foregroundSave,
  1729. sharePage: message.sharePage
  1730. }), "*");
  1731. } else {
  1732. if (message.foregroundSave || message.sharePage) {
  1733. try {
  1734. await downloadPageForeground({
  1735. content,
  1736. filename: filename || message.filename,
  1737. mimeType: "text/html"
  1738. }, { sharePage: message.sharePage });
  1739. } catch (error) {
  1740. console.log(error); // eslint-disable-line no-console
  1741. window.parent.postMessage(JSON.stringify({ method: "onError", error: error.message }), "*");
  1742. }
  1743. } else {
  1744. window.parent.postMessage(JSON.stringify({
  1745. method: "setContent",
  1746. content,
  1747. filename
  1748. }), "*");
  1749. }
  1750. }
  1751. }
  1752. if (message.method == "printPage") {
  1753. printPage();
  1754. }
  1755. if (message.method == "displayInfobar") {
  1756. singlefile.helper.displayIcon(document, true);
  1757. const infobarDoc = document.implementation.createHTMLDocument();
  1758. infobarDoc.body.appendChild(document.querySelector(singlefile.helper.INFOBAR_TAGNAME));
  1759. serializeShadowRoots(infobarDoc.body);
  1760. const content = singlefile.helper.serialize(infobarDoc, true);
  1761. window.parent.postMessage(JSON.stringify({
  1762. method: "displayInfobar",
  1763. content
  1764. }), "*");
  1765. }
  1766. if (message.method == "download") {
  1767. debugger;
  1768. try {
  1769. await downloadPageForeground({
  1770. content: message.content,
  1771. filename: message.filename,
  1772. mimeType: message.mimeType
  1773. }, { sharePage: message.sharePage });
  1774. } catch (error) {
  1775. console.log(error); // eslint-disable-line no-console
  1776. window.parent.postMessage(JSON.stringify({ method: "onError", error: error.message }), "*");
  1777. }
  1778. }
  1779. };
  1780. window.onresize = reflowNotes;
  1781. document.ondragover = event => event.preventDefault();
  1782. document.ondrop = async event => {
  1783. if (event.dataTransfer.files && event.dataTransfer.files[0]) {
  1784. const file = event.dataTransfer.files[0];
  1785. event.preventDefault();
  1786. const content = new TextDecoder().decode(await file.arrayBuffer());
  1787. const compressContent = /<html[^>]* data-sfz[^>]*>/i.test(content);
  1788. if (compressContent) {
  1789. await init({ content: file, compressContent }, { filename: file.name });
  1790. } else {
  1791. await init({ content }, { filename: file.name });
  1792. }
  1793. }
  1794. };
  1795. }
  1796. async function init({ content, password, compressContent }, { filename, reset } = {}) {
  1797. await initConstants();
  1798. if (compressContent) {
  1799. const zipOptions = {
  1800. workerScripts: { inflate: ["/lib/single-file-z-worker.js"] }
  1801. };
  1802. try {
  1803. const worker = new Worker(zipOptions.workerScripts.inflate[0]);
  1804. worker.terminate();
  1805. } catch (error) {
  1806. delete zipOptions.workerScripts;
  1807. }
  1808. zipOptions.useWebWorkers = IS_NOT_SAFARI;
  1809. const { docContent, origDocContent, resources, url } = await singlefile.helper.extract(content, {
  1810. password,
  1811. prompt,
  1812. shadowRootScriptURL: new URL("/lib/single-file-extension-editor-init.js", document.baseURI).href,
  1813. zipOptions
  1814. });
  1815. pageResources = resources;
  1816. pageUrl = url;
  1817. pageCompressContent = true;
  1818. const contentDocument = (new DOMParser()).parseFromString(docContent, "text/html");
  1819. if (detectSavedPage(contentDocument)) {
  1820. await singlefile.helper.display(document, docContent, { disableFramePointerEvents: true });
  1821. const infobarElement = document.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1822. if (infobarElement) {
  1823. infobarElement.remove();
  1824. }
  1825. await initPage();
  1826. let icon;
  1827. const origContentDocument = (new DOMParser()).parseFromString(origDocContent, "text/html");
  1828. const iconElement = origContentDocument.querySelector("link[rel*=icon]");
  1829. if (iconElement) {
  1830. const iconResource = resources.find(resource => resource.filename == iconElement.getAttribute("href"));
  1831. if (iconResource && iconResource.content) {
  1832. const reader = new FileReader();
  1833. reader.readAsDataURL(await (await fetch(iconResource.content)).blob());
  1834. icon = await new Promise((resolve, reject) => {
  1835. reader.addEventListener("load", () => resolve(reader.result), false);
  1836. reader.addEventListener("error", reject, false);
  1837. });
  1838. } else {
  1839. icon = iconElement.href;
  1840. }
  1841. }
  1842. window.parent.postMessage(JSON.stringify({
  1843. method: "onInit",
  1844. title: document.title,
  1845. icon,
  1846. filename,
  1847. reset,
  1848. formatPageEnabled: isProbablyReaderable(document)
  1849. }), "*");
  1850. }
  1851. } else {
  1852. const initScriptContentMatch = content.match(/<script data-template-shadow-root.*<\/script>/);
  1853. if (initScriptContentMatch && initScriptContentMatch[0]) {
  1854. initScriptContent = initScriptContentMatch[0];
  1855. }
  1856. content = content.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=/lib/single-file-extension-editor-init.js></script>");
  1857. const contentDocument = (new DOMParser()).parseFromString(content, "text/html");
  1858. if (detectSavedPage(contentDocument)) {
  1859. if (contentDocument.doctype) {
  1860. if (document.doctype) {
  1861. document.replaceChild(contentDocument.doctype, document.doctype);
  1862. } else {
  1863. document.insertBefore(contentDocument.doctype, document.documentElement);
  1864. }
  1865. } else if (document.doctype) {
  1866. document.doctype.remove();
  1867. }
  1868. const infobarElement = contentDocument.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1869. if (infobarElement) {
  1870. infobarElement.remove();
  1871. }
  1872. contentDocument.querySelectorAll("noscript").forEach(element => {
  1873. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  1874. element.textContent = "";
  1875. });
  1876. contentDocument.querySelectorAll("iframe").forEach(element => {
  1877. const pointerEvents = "pointer-events";
  1878. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1879. element.style.setProperty(pointerEvents, "none", "important");
  1880. });
  1881. document.replaceChild(contentDocument.documentElement, document.documentElement);
  1882. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1883. deserializeShadowRoots(document);
  1884. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1885. insertHighlightStylesheet(document);
  1886. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1887. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1888. document.documentElement.onmousedown = onMouseDown;
  1889. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1890. document.documentElement.onmouseover = onMouseOver;
  1891. document.documentElement.onmouseout = onMouseOut;
  1892. document.documentElement.onkeydown = onKeyDown;
  1893. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1894. window.onclick = event => event.preventDefault();
  1895. const iconElement = document.querySelector("link[rel*=icon]");
  1896. window.parent.postMessage(JSON.stringify({
  1897. method: "onInit",
  1898. title: document.title,
  1899. icon: iconElement && iconElement.href,
  1900. filename,
  1901. reset,
  1902. formatPageEnabled: isProbablyReaderable(document)
  1903. }), "*");
  1904. }
  1905. }
  1906. }
  1907. function loadOptionsFromPage(doc) {
  1908. const optionsElement = doc.body.querySelector("script[type=\"application/json\"][" + SCRIPT_OPTIONS + "]");
  1909. if (optionsElement) {
  1910. return JSON.parse(optionsElement.textContent);
  1911. }
  1912. }
  1913. async function initPage() {
  1914. document.querySelectorAll("iframe").forEach(element => {
  1915. const pointerEvents = "pointer-events";
  1916. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1917. element.style.setProperty(pointerEvents, "none", "important");
  1918. });
  1919. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1920. deserializeShadowRoots(document);
  1921. reflowNotes();
  1922. await waitResourcesLoad();
  1923. reflowNotes();
  1924. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1925. insertHighlightStylesheet(document);
  1926. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1927. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1928. document.documentElement.onmousedown = onMouseDown;
  1929. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1930. document.documentElement.onmouseover = onMouseOver;
  1931. document.documentElement.onmouseout = onMouseOut;
  1932. document.documentElement.onkeydown = onKeyDown;
  1933. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1934. window.onclick = event => event.preventDefault();
  1935. }
  1936. async function initConstants() {
  1937. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  1938. minifyText(await ((await fetch("../pages/editor-note-web.css")).text())),
  1939. minifyText(await ((await fetch("../pages/editor-mask-web.css")).text())),
  1940. minifyText(await ((await fetch("../pages/editor-frame-web.css")).text()))
  1941. ]);
  1942. }
  1943. function addNote({ color }) {
  1944. const containerElement = document.createElement(NOTE_TAGNAME);
  1945. const noteElement = document.createElement("div");
  1946. const headerElement = document.createElement("header");
  1947. const blockquoteElement = document.createElement("blockquote");
  1948. const mainElement = document.createElement("textarea");
  1949. const resizeElement = document.createElement("div");
  1950. const removeNoteElement = document.createElement("img");
  1951. const anchorIconElement = document.createElement("img");
  1952. const noteShadow = containerElement.attachShadow({ mode: "open" });
  1953. headerElement.appendChild(anchorIconElement);
  1954. headerElement.appendChild(removeNoteElement);
  1955. blockquoteElement.appendChild(mainElement);
  1956. noteElement.appendChild(headerElement);
  1957. noteElement.appendChild(blockquoteElement);
  1958. noteElement.appendChild(resizeElement);
  1959. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  1960. noteShadow.appendChild(noteElement);
  1961. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  1962. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  1963. blockquoteElement.cite = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[data-single-file-note-refs~=\"" + noteId + "\"])";
  1964. noteElement.classList.add(NOTE_CLASS);
  1965. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  1966. noteElement.classList.add(color);
  1967. noteElement.dataset.color = color;
  1968. mainElement.dir = "auto";
  1969. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  1970. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  1971. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  1972. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  1973. positionX += NOTE_INITIAL_POSITION_X;
  1974. positionY += NOTE_INITIAL_POSITION_Y;
  1975. }
  1976. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  1977. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  1978. resizeElement.className = "note-resize";
  1979. resizeElement.ondragstart = event => event.preventDefault();
  1980. removeNoteElement.className = "note-remove";
  1981. removeNoteElement.src = BUTTON_CLOSE_URL;
  1982. removeNoteElement.ondragstart = event => event.preventDefault();
  1983. anchorIconElement.className = "note-anchor";
  1984. anchorIconElement.src = BUTTON_ANCHOR_URL;
  1985. anchorIconElement.ondragstart = event => event.preventDefault();
  1986. containerElement.dataset.noteId = noteId;
  1987. addNoteRef(document.documentElement, noteId);
  1988. attachNoteListeners(containerElement, true);
  1989. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1990. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1991. selectedNote = noteElement;
  1992. onUpdate(false);
  1993. }
  1994. function attachNoteListeners(containerElement, editable = false) {
  1995. const SELECT_PX_THRESHOLD = 4;
  1996. const COLLAPSING_NOTE_DELAY = 750;
  1997. const noteShadow = containerElement.shadowRoot;
  1998. const noteElement = noteShadow.childNodes[1];
  1999. const headerElement = noteShadow.querySelector("header");
  2000. const mainElement = noteShadow.querySelector("textarea");
  2001. const noteId = containerElement.dataset.noteId;
  2002. const resizeElement = noteShadow.querySelector(".note-resize");
  2003. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  2004. const removeNoteElement = noteShadow.querySelector(".note-remove");
  2005. mainElement.readOnly = !editable;
  2006. if (!editable) {
  2007. anchorIconElement.style.setProperty("display", "none", "important");
  2008. } else {
  2009. anchorIconElement.style.removeProperty("display");
  2010. }
  2011. headerElement.ontouchstart = headerElement.onmousedown = event => {
  2012. if (event.target == headerElement) {
  2013. collapseNoteTimeout = setTimeout(() => {
  2014. noteElement.classList.toggle("note-collapsed");
  2015. hideMaskNote();
  2016. }, COLLAPSING_NOTE_DELAY);
  2017. event.preventDefault();
  2018. const position = getPosition(event);
  2019. const clientX = position.clientX;
  2020. const clientY = position.clientY;
  2021. const boundingRect = noteElement.getBoundingClientRect();
  2022. const deltaX = clientX - boundingRect.left;
  2023. const deltaY = clientY - boundingRect.top;
  2024. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  2025. document.documentElement.style.setProperty("user-select", "none", "important");
  2026. anchorElement = getAnchorElement(containerElement);
  2027. displayMaskNote();
  2028. selectNote(noteElement);
  2029. moveNote(event, deltaX, deltaY);
  2030. movingNoteMode = { event, deltaX, deltaY };
  2031. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  2032. clearTimeout(collapseNoteTimeout);
  2033. if (!movingNoteMode) {
  2034. movingNoteMode = { deltaX, deltaY };
  2035. }
  2036. movingNoteMode.event = event;
  2037. moveNote(event, deltaX, deltaY);
  2038. };
  2039. }
  2040. };
  2041. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  2042. event.preventDefault();
  2043. resizingNoteMode = true;
  2044. selectNote(noteElement);
  2045. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  2046. document.documentElement.style.setProperty("user-select", "none", "important");
  2047. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  2048. event.preventDefault();
  2049. const { clientX, clientY } = getPosition(event);
  2050. const boundingRectNote = noteElement.getBoundingClientRect();
  2051. noteElement.style.width = clientX - boundingRectNote.left + "px";
  2052. noteElement.style.height = clientY - boundingRectNote.top + "px";
  2053. };
  2054. };
  2055. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  2056. event.preventDefault();
  2057. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  2058. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  2059. deleteNoteRef(containerElement, noteId);
  2060. addNoteRef(document.documentElement, noteId);
  2061. }
  2062. onUpdate(false);
  2063. };
  2064. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  2065. event.preventDefault();
  2066. deleteNoteRef(containerElement, noteId);
  2067. containerElement.remove();
  2068. };
  2069. noteElement.onmousedown = () => {
  2070. selectNote(noteElement);
  2071. };
  2072. function moveNote(event, deltaX, deltaY) {
  2073. event.preventDefault();
  2074. const { clientX, clientY } = getPosition(event);
  2075. noteElement.classList.add(NOTE_MOVING_CLASS);
  2076. if (editable) {
  2077. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  2078. deleteNoteRef(containerElement, noteId);
  2079. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  2080. addNoteRef(anchorElement, noteId);
  2081. } else {
  2082. anchorElement = document.documentElement;
  2083. }
  2084. }
  2085. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  2086. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  2087. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  2088. noteElement.style.setProperty("position", "fixed");
  2089. displayMaskNote();
  2090. }
  2091. function displayMaskNote() {
  2092. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  2093. hideMaskNote();
  2094. } else {
  2095. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  2096. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  2097. if (selectedNote) {
  2098. maskNoteElement.classList.add(selectedNote.dataset.color);
  2099. }
  2100. maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
  2101. maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
  2102. maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
  2103. maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
  2104. }
  2105. }
  2106. function hideMaskNote() {
  2107. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  2108. if (selectedNote) {
  2109. maskNoteElement.classList.remove(selectedNote.dataset.color);
  2110. }
  2111. }
  2112. function selectNote(noteElement) {
  2113. if (selectedNote) {
  2114. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  2115. maskNoteElement.classList.remove(selectedNote.dataset.color);
  2116. }
  2117. noteElement.classList.add(NOTE_SELECTED_CLASS);
  2118. noteElement.classList.add(noteElement.dataset.color);
  2119. selectedNote = noteElement;
  2120. }
  2121. function getTarget(clientX, clientY) {
  2122. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
  2123. if (!targets.includes(document.documentElement)) {
  2124. targets.push(document.documentElement);
  2125. }
  2126. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  2127. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  2128. if (newTarget == target) {
  2129. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  2130. }
  2131. if (newTarget == target) {
  2132. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  2133. }
  2134. if (newTarget == target) {
  2135. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  2136. }
  2137. target = newTarget;
  2138. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  2139. target = target.parentElement;
  2140. }
  2141. return target;
  2142. }
  2143. function getMatchedParents(target, property) {
  2144. let element = target, matchedParent, parents = [];
  2145. do {
  2146. const boundingRect = element.getBoundingClientRect();
  2147. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  2148. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  2149. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  2150. if (matchedParent) {
  2151. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  2152. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  2153. parents.push(element.parentElement);
  2154. }
  2155. element = element.parentElement;
  2156. }
  2157. } else {
  2158. matchedParent = false;
  2159. }
  2160. } while (matchedParent && element);
  2161. return parents;
  2162. }
  2163. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  2164. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  2165. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  2166. }
  2167. return target;
  2168. }
  2169. }
  2170. function onMouseDown(event) {
  2171. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  2172. event.preventDefault();
  2173. }
  2174. }
  2175. function onMouseUp(event) {
  2176. if (highlightSelectionMode) {
  2177. event.preventDefault();
  2178. highlightSelection();
  2179. onUpdate(false);
  2180. }
  2181. if (removeHighlightMode) {
  2182. event.preventDefault();
  2183. let element = event.target, done;
  2184. while (element && !done) {
  2185. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  2186. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  2187. resetHighlightedElement(highlightedElement);
  2188. onUpdate(false);
  2189. });
  2190. done = true;
  2191. }
  2192. element = element.parentElement;
  2193. }
  2194. }
  2195. if (resizingNoteMode) {
  2196. event.preventDefault();
  2197. resizingNoteMode = false;
  2198. document.documentElement.style.removeProperty("user-select");
  2199. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  2200. document.documentElement.ontouchmove = onTouchMove;
  2201. document.documentElement.onmousemove = null;
  2202. onUpdate(false);
  2203. }
  2204. if (movingNoteMode) {
  2205. event.preventDefault();
  2206. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  2207. movingNoteMode = null;
  2208. document.documentElement.ontouchmove = onTouchMove;
  2209. document.documentElement.onmousemove = null;
  2210. onUpdate(false);
  2211. }
  2212. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  2213. event.preventDefault();
  2214. if (event.ctrlKey) {
  2215. const element = cuttingPath[cuttingPathIndex];
  2216. element.classList.toggle(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  2217. } else {
  2218. validateCutElement(event.shiftKey);
  2219. }
  2220. }
  2221. if (collapseNoteTimeout) {
  2222. clearTimeout(collapseNoteTimeout);
  2223. collapseNoteTimeout = null;
  2224. }
  2225. }
  2226. function onMouseOver(event) {
  2227. if (cuttingMode || cuttingOuterMode) {
  2228. const target = event.target;
  2229. if (target.classList) {
  2230. let ancestorFound;
  2231. document.querySelectorAll("." + (cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS)).forEach(element => {
  2232. if (element == target || isAncestor(element, target) || isAncestor(target, element)) {
  2233. ancestorFound = element;
  2234. }
  2235. });
  2236. if (ancestorFound) {
  2237. cuttingPath = [ancestorFound];
  2238. } else {
  2239. cuttingPath = getParents(event.target);
  2240. }
  2241. cuttingPathIndex = 0;
  2242. highlightCutElement();
  2243. }
  2244. }
  2245. }
  2246. function onMouseOut() {
  2247. if (cuttingMode || cuttingOuterMode) {
  2248. if (cuttingPath) {
  2249. unhighlightCutElement();
  2250. cuttingPath = null;
  2251. }
  2252. }
  2253. }
  2254. function onTouchMove(event) {
  2255. if (cuttingMode || cuttingOuterMode) {
  2256. event.preventDefault();
  2257. const { clientX, clientY } = getPosition(event);
  2258. const target = document.elementFromPoint(clientX, clientY);
  2259. if (cuttingTouchTarget != target) {
  2260. onMouseOut();
  2261. if (target) {
  2262. cuttingTouchTarget = target;
  2263. onMouseOver({ target });
  2264. }
  2265. }
  2266. }
  2267. }
  2268. function onKeyDown(event) {
  2269. if (cuttingMode || cuttingOuterMode) {
  2270. if (event.code == "Tab") {
  2271. if (cuttingPath) {
  2272. const delta = event.shiftKey ? -1 : 1;
  2273. let element = cuttingPath[cuttingPathIndex];
  2274. let nextElement = cuttingPath[cuttingPathIndex + delta];
  2275. if (nextElement) {
  2276. let pathIndex = cuttingPathIndex + delta;
  2277. while (
  2278. nextElement &&
  2279. (
  2280. (delta == 1 &&
  2281. element.getBoundingClientRect().width >= nextElement.getBoundingClientRect().width &&
  2282. element.getBoundingClientRect().height >= nextElement.getBoundingClientRect().height) ||
  2283. (delta == -1 &&
  2284. element.getBoundingClientRect().width <= nextElement.getBoundingClientRect().width &&
  2285. element.getBoundingClientRect().height <= nextElement.getBoundingClientRect().height))) {
  2286. pathIndex += delta;
  2287. nextElement = cuttingPath[pathIndex];
  2288. }
  2289. if (nextElement && nextElement.classList && nextElement != document.body && nextElement != document.documentElement) {
  2290. unhighlightCutElement();
  2291. cuttingPathIndex = pathIndex;
  2292. highlightCutElement();
  2293. }
  2294. }
  2295. }
  2296. event.preventDefault();
  2297. }
  2298. if (event.code == "Space") {
  2299. if (cuttingPath) {
  2300. if (event.ctrlKey) {
  2301. const element = cuttingPath[cuttingPathIndex];
  2302. element.classList.add(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  2303. } else {
  2304. validateCutElement(event.shiftKey);
  2305. }
  2306. event.preventDefault();
  2307. }
  2308. }
  2309. if (event.code == "Escape") {
  2310. resetSelectedElements();
  2311. event.preventDefault();
  2312. }
  2313. if (event.key.toLowerCase() == "z" && event.ctrlKey) {
  2314. if (event.shiftKey) {
  2315. redoCutPage();
  2316. } else {
  2317. undoCutPage();
  2318. }
  2319. event.preventDefault();
  2320. }
  2321. }
  2322. if (event.key.toLowerCase() == "s" && event.ctrlKey) {
  2323. window.parent.postMessage(JSON.stringify({ "method": "savePage" }), "*");
  2324. event.preventDefault();
  2325. }
  2326. if (event.key.toLowerCase() == "p" && event.ctrlKey) {
  2327. printPage();
  2328. event.preventDefault();
  2329. }
  2330. }
  2331. function printPage() {
  2332. unhighlightCutElement();
  2333. resetSelectedElements();
  2334. window.print();
  2335. }
  2336. function highlightCutElement() {
  2337. const element = cuttingPath[cuttingPathIndex];
  2338. element.classList.add(cuttingMode ? CUT_HOVER_CLASS : CUT_OUTER_HOVER_CLASS);
  2339. }
  2340. function unhighlightCutElement() {
  2341. if (cuttingPath) {
  2342. const element = cuttingPath[cuttingPathIndex];
  2343. element.classList.remove(CUT_HOVER_CLASS);
  2344. element.classList.remove(CUT_OUTER_HOVER_CLASS);
  2345. }
  2346. }
  2347. function disableHighlight(doc = document) {
  2348. if (highlightColor) {
  2349. doc.documentElement.classList.remove(highlightColor + "-mode");
  2350. }
  2351. }
  2352. function undoCutPage() {
  2353. if (removedElementIndex) {
  2354. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  2355. removedElementIndex--;
  2356. }
  2357. }
  2358. function redoCutPage() {
  2359. if (removedElementIndex < removedElements.length) {
  2360. removedElements[removedElementIndex].forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  2361. removedElementIndex++;
  2362. }
  2363. }
  2364. function validateCutElement(invert) {
  2365. const selectedElement = cuttingPath[cuttingPathIndex];
  2366. if ((cuttingMode && !invert) || (cuttingOuterMode && invert)) {
  2367. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  2368. const elementsRemoved = [selectedElement].concat(...document.querySelectorAll("." + CUT_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS + " *,." + CUT_HOVER_CLASS + " *"));
  2369. resetSelectedElements();
  2370. if (elementsRemoved.length) {
  2371. elementsRemoved.forEach(element => {
  2372. unhighlightCutElement();
  2373. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  2374. resetAnchorNote(element);
  2375. } else {
  2376. element.classList.add(REMOVED_CONTENT_CLASS);
  2377. }
  2378. });
  2379. removedElements[removedElementIndex] = elementsRemoved;
  2380. removedElementIndex++;
  2381. removedElements.length = removedElementIndex;
  2382. onUpdate(false);
  2383. }
  2384. }
  2385. } else {
  2386. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  2387. const elements = [];
  2388. const searchSelector = "*:not(style):not(meta):not(." + REMOVED_CONTENT_CLASS + ")";
  2389. const elementsKept = [selectedElement].concat(...document.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS));
  2390. document.body.querySelectorAll(searchSelector).forEach(element => {
  2391. let removed = true;
  2392. elementsKept.forEach(elementKept => removed = removed && (elementKept != element && !isAncestor(elementKept, element) && !isAncestor(element, elementKept)));
  2393. if (removed) {
  2394. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  2395. resetAnchorNote(element);
  2396. } else {
  2397. elements.push(element);
  2398. }
  2399. }
  2400. });
  2401. elementsKept.forEach(elementKept => {
  2402. unhighlightCutElement();
  2403. const elementKeptRect = elementKept.getBoundingClientRect();
  2404. elementKept.querySelectorAll(searchSelector).forEach(descendant => {
  2405. const descendantRect = descendant.getBoundingClientRect();
  2406. if (descendantRect.width && descendantRect.height && (
  2407. descendantRect.left + descendantRect.width < elementKeptRect.left ||
  2408. descendantRect.right > elementKeptRect.right + elementKeptRect.width ||
  2409. descendantRect.top + descendantRect.height < elementKeptRect.top ||
  2410. descendantRect.bottom > elementKeptRect.bottom + elementKeptRect.height
  2411. )) {
  2412. elements.push(descendant);
  2413. }
  2414. });
  2415. });
  2416. resetSelectedElements();
  2417. if (elements.length) {
  2418. elements.forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  2419. removedElements[removedElementIndex] = elements;
  2420. removedElementIndex++;
  2421. removedElements.length = removedElementIndex;
  2422. onUpdate(false);
  2423. }
  2424. }
  2425. }
  2426. }
  2427. function resetSelectedElements(doc = document) {
  2428. doc.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS).forEach(element => {
  2429. element.classList.remove(CUT_OUTER_SELECTED_CLASS);
  2430. element.classList.remove(CUT_SELECTED_CLASS);
  2431. });
  2432. }
  2433. function anchorNote(event, noteElement, deltaX, deltaY) {
  2434. event.preventDefault();
  2435. const { clientX, clientY } = getPosition(event);
  2436. document.documentElement.style.removeProperty("user-select");
  2437. noteElement.classList.remove(NOTE_MOVING_CLASS);
  2438. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  2439. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  2440. maskNoteElement.classList.remove(noteElement.dataset.color);
  2441. const headerElement = noteElement.querySelector("header");
  2442. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  2443. let currentElement = anchorElement;
  2444. let positionedElement;
  2445. while (currentElement.parentElement && !positionedElement) {
  2446. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  2447. const currentElementStyle = getComputedStyle(currentElement);
  2448. if (currentElementStyle.position != "static") {
  2449. positionedElement = currentElement;
  2450. }
  2451. }
  2452. currentElement = currentElement.parentElement;
  2453. }
  2454. if (!positionedElement) {
  2455. positionedElement = document.documentElement;
  2456. }
  2457. const containerElement = noteElement.getRootNode().host;
  2458. if (positionedElement == document.documentElement) {
  2459. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  2460. firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
  2461. } else {
  2462. positionedElement.appendChild(containerElement);
  2463. }
  2464. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  2465. const stylePositionedElement = window.getComputedStyle(positionedElement);
  2466. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  2467. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  2468. noteElement.style.setProperty("position", "absolute");
  2469. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  2470. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  2471. }
  2472. function resetAnchorNote(containerElement) {
  2473. const noteId = containerElement.dataset.noteId;
  2474. const noteElement = containerElement.shadowRoot.childNodes[1];
  2475. noteElement.classList.remove(NOTE_ANCHORED_CLASS);
  2476. deleteNoteRef(containerElement, noteId);
  2477. addNoteRef(document.documentElement, noteId);
  2478. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  2479. }
  2480. function getPosition(event) {
  2481. if (event.touches && event.touches.length) {
  2482. const touch = event.touches[0];
  2483. return touch;
  2484. } else {
  2485. return event;
  2486. }
  2487. }
  2488. function highlightSelection() {
  2489. let highlightId = 0;
  2490. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  2491. highlightId++;
  2492. const selection = window.getSelection();
  2493. const highlightedNodes = new Set();
  2494. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  2495. const range = selection.getRangeAt(indexRange);
  2496. if (!range.collapsed) {
  2497. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  2498. let contentText = range.startContainer.splitText(range.startOffset);
  2499. contentText = contentText.splitText(range.endOffset);
  2500. addHighLightedNode(contentText.previousSibling);
  2501. } else {
  2502. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  2503. let highlightNodes;
  2504. while (treeWalker.nextNode()) {
  2505. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  2506. addHighLightedNode(treeWalker.currentNode);
  2507. }
  2508. if (treeWalker.currentNode == range.startContainer) {
  2509. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  2510. const contentText = range.startContainer.splitText(range.startOffset);
  2511. treeWalker.nextNode();
  2512. addHighLightedNode(contentText);
  2513. } else {
  2514. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  2515. }
  2516. highlightNodes = true;
  2517. }
  2518. if (treeWalker.currentNode == range.endContainer) {
  2519. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  2520. const contentText = range.endContainer.splitText(range.endOffset);
  2521. treeWalker.nextNode();
  2522. addHighLightedNode(contentText.previousSibling);
  2523. } else {
  2524. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  2525. }
  2526. highlightNodes = false;
  2527. }
  2528. }
  2529. range.collapse();
  2530. }
  2531. }
  2532. }
  2533. highlightedNodes.forEach(node => highlightNode(node));
  2534. function addHighLightedNode(node) {
  2535. if (node && node.textContent.trim()) {
  2536. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  2537. highlightedNodes.add(node.parentElement);
  2538. } else {
  2539. highlightedNodes.add(node);
  2540. }
  2541. }
  2542. }
  2543. function highlightNode(node) {
  2544. if (node.nodeType == node.ELEMENT_NODE) {
  2545. resetHighlightedElement(node);
  2546. node.classList.add(HIGHLIGHT_CLASS);
  2547. node.classList.add(highlightColor);
  2548. node.dataset.singlefileHighlightId = highlightId;
  2549. } else if (node.parentElement) {
  2550. highlightTextNode(node);
  2551. }
  2552. }
  2553. function highlightTextNode(node) {
  2554. const spanElement = document.createElement("span");
  2555. spanElement.classList.add(HIGHLIGHT_CLASS);
  2556. spanElement.classList.add(highlightColor);
  2557. spanElement.textContent = node.textContent;
  2558. spanElement.dataset.singlefileHighlightId = highlightId;
  2559. node.parentNode.replaceChild(spanElement, node);
  2560. return spanElement;
  2561. }
  2562. }
  2563. function getParents(element) {
  2564. const path = [];
  2565. while (element) {
  2566. path.push(element);
  2567. element = element.parentElement;
  2568. }
  2569. return path;
  2570. }
  2571. function formatPage(applySystemTheme) {
  2572. if (pageCompressContent) {
  2573. serializeShadowRoots(document);
  2574. previousContent = document.documentElement.cloneNode(true);
  2575. deserializeShadowRoots(document);
  2576. } else {
  2577. previousContent = getContent(false, []);
  2578. }
  2579. const shadowRoots = {};
  2580. const classesToPreserve = ["single-file-highlight", "single-file-highlight-yellow", "single-file-highlight-green", "single-file-highlight-pink", "single-file-highlight-blue"];
  2581. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2582. shadowRoots[containerElement.dataset.noteId] = containerElement.shadowRoot;
  2583. const className = "singlefile-note-id-" + containerElement.dataset.noteId;
  2584. containerElement.classList.add(className);
  2585. classesToPreserve.push(className);
  2586. });
  2587. const article = new Readability(document, { classesToPreserve }).parse();
  2588. removedElements = [];
  2589. removedElementIndex = 0;
  2590. document.body.innerHTML = "";
  2591. const domParser = new DOMParser();
  2592. const doc = domParser.parseFromString(article.content, "text/html");
  2593. const contentEditable = document.body.contentEditable;
  2594. document.documentElement.replaceChild(doc.body, document.body);
  2595. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2596. const noteId = (Array.from(containerElement.classList).find(className => /singlefile-note-id-\d+/.test(className))).split("singlefile-note-id-")[1];
  2597. containerElement.classList.remove("singlefile-note-id-" + noteId);
  2598. containerElement.dataset.noteId = noteId;
  2599. if (!containerElement.shadowRoot) {
  2600. containerElement.attachShadow({ mode: "open" });
  2601. containerElement.shadowRoot.appendChild(shadowRoots[noteId]);
  2602. }
  2603. });
  2604. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => shadowRoots[containerElement.dataset.noteId].childNodes.forEach(node => containerElement.shadowRoot.appendChild(node)));
  2605. document.body.contentEditable = contentEditable;
  2606. document.head.querySelectorAll("style").forEach(styleElement => styleElement.remove());
  2607. const styleElement = document.createElement("style");
  2608. styleElement.textContent = STYLE_FORMATTED_PAGE;
  2609. document.head.appendChild(styleElement);
  2610. document.body.classList.add("moz-reader-content");
  2611. document.body.classList.add("content-width6");
  2612. document.body.classList.add("reader-show-element");
  2613. document.body.classList.add("sans-serif");
  2614. document.body.classList.add("container");
  2615. document.body.classList.add("line-height4");
  2616. const prefersColorSchemeDark = matchMedia("(prefers-color-scheme: dark)");
  2617. if (applySystemTheme && prefersColorSchemeDark && prefersColorSchemeDark.matches) {
  2618. document.body.classList.add("dark");
  2619. }
  2620. document.body.style.setProperty("display", "block");
  2621. document.body.style.setProperty("padding", "24px");
  2622. const titleElement = document.createElement("h1");
  2623. titleElement.classList.add("reader-title");
  2624. titleElement.textContent = article.title;
  2625. document.body.insertBefore(titleElement, document.body.firstChild);
  2626. document.querySelectorAll("a[href]").forEach(element => {
  2627. const href = element.getAttribute("href").trim();
  2628. if (href.startsWith(document.baseURI + "#")) {
  2629. element.setAttribute("href", href.substring(document.baseURI.length));
  2630. }
  2631. });
  2632. insertHighlightStylesheet(document);
  2633. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  2634. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  2635. reflowNotes();
  2636. onUpdate(false);
  2637. }
  2638. async function cancelFormatPage() {
  2639. if (previousContent) {
  2640. const contentEditable = document.body.contentEditable;
  2641. if (pageCompressContent) {
  2642. document.replaceChild(previousContent, document.documentElement);
  2643. deserializeShadowRoots(document);
  2644. await initPage();
  2645. } else {
  2646. await init({ content: previousContent }, { reset: true });
  2647. }
  2648. document.body.contentEditable = contentEditable;
  2649. onUpdate(false);
  2650. previousContent = null;
  2651. }
  2652. }
  2653. function insertHighlightStylesheet(doc) {
  2654. if (!doc.querySelector("." + HIGHLIGHTS_STYLESHEET_CLASS)) {
  2655. const styleheetHighlights = getStyleElement(HIGHLIGHTS_WEB_STYLESHEET);
  2656. styleheetHighlights.classList.add(HIGHLIGHTS_STYLESHEET_CLASS);
  2657. doc.documentElement.appendChild(styleheetHighlights);
  2658. }
  2659. }
  2660. function getContent(compressHTML, updatedResources) {
  2661. unhighlightCutElement();
  2662. serializeShadowRoots(document);
  2663. const doc = document.cloneNode(true);
  2664. disableHighlight(doc);
  2665. resetSelectedElements(doc);
  2666. deserializeShadowRoots(doc);
  2667. deserializeShadowRoots(document);
  2668. doc.documentElement.classList.remove(CUT_MODE_CLASS);
  2669. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  2670. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  2671. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  2672. });
  2673. doc.querySelectorAll("." + MASK_CLASS + ", " + singlefile.helper.INFOBAR_TAGNAME + ", ." + REMOVED_CONTENT_CLASS).forEach(element => element.remove());
  2674. if (includeInfobar) {
  2675. singlefile.helper.appendInfobar(doc, singlefile.helper.extractInfobarData(doc));
  2676. }
  2677. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  2678. doc.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  2679. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  2680. if (noteElement) {
  2681. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  2682. }
  2683. const mainElement = templateElement.querySelector("textarea");
  2684. if (mainElement) {
  2685. mainElement.textContent = mainElement.value;
  2686. }
  2687. });
  2688. doc.querySelectorAll("iframe").forEach(element => {
  2689. const pointerEvents = "pointer-events";
  2690. element.style.setProperty(pointerEvents, element.style.getPropertyValue("-sf-" + pointerEvents), element.style.getPropertyPriority("-sf-" + pointerEvents));
  2691. element.style.removeProperty("-sf-" + pointerEvents);
  2692. });
  2693. doc.body.removeAttribute("contentEditable");
  2694. const newResources = Object.keys(updatedResources).filter(url => updatedResources[url].type == "stylesheet").map(url => updatedResources[url]);
  2695. newResources.forEach(resource => {
  2696. const element = doc.createElement("style");
  2697. doc.body.appendChild(element);
  2698. element.textContent = resource.content;
  2699. });
  2700. if (pageCompressContent) {
  2701. const pageFilename = pageResources
  2702. .filter(resource => resource.filename.endsWith("index.html"))
  2703. .sort((resourceLeft, resourceRight) => resourceLeft.filename.length - resourceRight.filename.length)[0].filename;
  2704. const resources = pageResources.filter(resource => resource.parentResources.includes(pageFilename));
  2705. doc.querySelectorAll("[src]").forEach(element => resources.forEach(resource => {
  2706. if (element.src == resource.content) {
  2707. element.src = resource.name;
  2708. }
  2709. }));
  2710. let content = singlefile.helper.serialize(doc, compressHTML);
  2711. resources.sort((resourceLeft, resourceRight) => resourceRight.content.length - resourceLeft.content.length);
  2712. resources.forEach(resource => content = content.replaceAll(resource.content, resource.name));
  2713. return content + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  2714. } else {
  2715. return singlefile.helper.serialize(doc, compressHTML) + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  2716. }
  2717. }
  2718. function onUpdate(saved) {
  2719. window.parent.postMessage(JSON.stringify({ "method": "onUpdate", saved }), "*");
  2720. }
  2721. function waitResourcesLoad() {
  2722. return new Promise(resolve => {
  2723. let counterMutations = 0;
  2724. const done = () => {
  2725. observer.disconnect();
  2726. resolve();
  2727. };
  2728. let timeoutInit = setTimeout(done, 100);
  2729. const observer = new MutationObserver(() => {
  2730. if (counterMutations < 20) {
  2731. counterMutations++;
  2732. clearTimeout(timeoutInit);
  2733. timeoutInit = setTimeout(done, 100);
  2734. } else {
  2735. done();
  2736. }
  2737. });
  2738. observer.observe(document, { subtree: true, childList: true, attributes: true });
  2739. });
  2740. }
  2741. function reflowNotes() {
  2742. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2743. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  2744. const noteBoundingRect = noteElement.getBoundingClientRect();
  2745. const anchorElement = getAnchorElement(containerElement);
  2746. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  2747. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  2748. const minX = anchorBoundingRect.x;
  2749. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  2750. const minY = anchorBoundingRect.y;
  2751. let left = parseInt(noteElement.style.getPropertyValue("left"));
  2752. let top = parseInt(noteElement.style.getPropertyValue("top"));
  2753. if (noteBoundingRect.x > maxX) {
  2754. left -= noteBoundingRect.x - maxX;
  2755. }
  2756. if (noteBoundingRect.x < minX) {
  2757. left += minX - noteBoundingRect.x;
  2758. }
  2759. if (noteBoundingRect.y > maxY) {
  2760. top -= noteBoundingRect.y - maxY;
  2761. }
  2762. if (noteBoundingRect.y < minY) {
  2763. top += minY - noteBoundingRect.y;
  2764. }
  2765. noteElement.style.setProperty("position", "absolute");
  2766. noteElement.style.setProperty("left", left + "px");
  2767. noteElement.style.setProperty("top", top + "px");
  2768. });
  2769. }
  2770. function resetHighlightedElement(element) {
  2771. element.classList.remove(HIGHLIGHT_CLASS);
  2772. element.classList.remove("single-file-highlight-yellow");
  2773. element.classList.remove("single-file-highlight-pink");
  2774. element.classList.remove("single-file-highlight-blue");
  2775. element.classList.remove("single-file-highlight-green");
  2776. delete element.dataset.singlefileHighlightId;
  2777. }
  2778. function serializeShadowRoots(node) {
  2779. node.querySelectorAll("*").forEach(element => {
  2780. const shadowRoot = getShadowRoot(element);
  2781. if (shadowRoot) {
  2782. serializeShadowRoots(shadowRoot);
  2783. const templateElement = document.createElement("template");
  2784. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  2785. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  2786. element.appendChild(templateElement);
  2787. }
  2788. });
  2789. }
  2790. function deserializeShadowRoots(node) {
  2791. node.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(element => {
  2792. if (element.parentElement) {
  2793. let shadowRoot = getShadowRoot(element.parentElement);
  2794. if (shadowRoot) {
  2795. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  2796. element.remove();
  2797. } else {
  2798. try {
  2799. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  2800. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  2801. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  2802. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  2803. } catch (error) {
  2804. // ignored
  2805. }
  2806. }
  2807. if (shadowRoot) {
  2808. deserializeShadowRoots(shadowRoot);
  2809. }
  2810. }
  2811. });
  2812. }
  2813. function getMaskElement(className, containerClassName) {
  2814. let maskElement = document.documentElement.querySelector("." + className);
  2815. if (!maskElement) {
  2816. maskElement = document.createElement("div");
  2817. const maskContainerElement = document.createElement("div");
  2818. if (containerClassName) {
  2819. maskContainerElement.classList.add(containerClassName);
  2820. }
  2821. maskContainerElement.classList.add(MASK_CLASS);
  2822. const firstNote = document.querySelector(NOTE_TAGNAME);
  2823. if (firstNote && firstNote.parentElement == document.documentElement) {
  2824. document.documentElement.insertBefore(maskContainerElement, firstNote);
  2825. } else {
  2826. document.documentElement.appendChild(maskContainerElement);
  2827. }
  2828. maskElement.classList.add(className);
  2829. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  2830. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  2831. maskShadow.appendChild(maskElement);
  2832. return maskElement;
  2833. }
  2834. }
  2835. function getEmbedScript() {
  2836. return minifyText(`(() => {
  2837. document.currentScript.remove();
  2838. const processNode = node => {
  2839. node.querySelectorAll("template[${SHADOWROOT_ATTRIBUTE_NAME}]").forEach(element=>{
  2840. let shadowRoot = getShadowRoot(element.parentElement);
  2841. if (!shadowRoot) {
  2842. try {
  2843. shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOWROOT_ATTRIBUTE_NAME}")});
  2844. shadowRoot.innerHTML = element.innerHTML;
  2845. element.remove();
  2846. } catch (error) {}
  2847. if (shadowRoot) {
  2848. processNode(shadowRoot);
  2849. }
  2850. }
  2851. })
  2852. };
  2853. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  2854. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  2855. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  2856. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  2857. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  2858. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  2859. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  2860. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  2861. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  2862. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  2863. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  2864. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  2865. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  2866. const REMOVED_CONTENT_CLASS = ${JSON.stringify(REMOVED_CONTENT_CLASS)};
  2867. const reflowNotes = ${minifyText(reflowNotes.toString())};
  2868. const addNoteRef = ${minifyText(addNoteRef.toString())};
  2869. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  2870. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  2871. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  2872. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  2873. const getMaskElement = ${minifyText(getMaskElement.toString())};
  2874. const getStyleElement = ${minifyText(getStyleElement.toString())};
  2875. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  2876. const anchorNote = ${minifyText(anchorNote.toString())};
  2877. const getPosition = ${minifyText(getPosition.toString())};
  2878. const onMouseUp = ${minifyText(onMouseUp.toString())};
  2879. const getShadowRoot = ${minifyText(getShadowRoot.toString())};
  2880. const waitResourcesLoad = ${minifyText(waitResourcesLoad.toString())};
  2881. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  2882. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  2883. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout, cuttingMode, cuttingOuterMode;
  2884. window.onresize = reflowNotes;
  2885. window.onUpdate = () => {};
  2886. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  2887. processNode(document);
  2888. reflowNotes();
  2889. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  2890. if (document.documentElement.dataset.sfz !== undefined) {
  2891. waitResourcesLoad().then(reflowNotes);
  2892. }
  2893. })()`);
  2894. }
  2895. function getStyleElement(stylesheet) {
  2896. const linkElement = document.createElement("style");
  2897. linkElement.textContent = stylesheet;
  2898. return linkElement;
  2899. }
  2900. function getAnchorElement(containerElement) {
  2901. return document.querySelector("[data-single-file-note-refs~=\"" + containerElement.dataset.noteId + "\"]") || document.documentElement;
  2902. }
  2903. function addNoteRef(anchorElement, noteId) {
  2904. const noteRefs = getNoteRefs(anchorElement);
  2905. noteRefs.push(noteId);
  2906. setNoteRefs(anchorElement, noteRefs);
  2907. }
  2908. function deleteNoteRef(containerElement, noteId) {
  2909. const anchorElement = getAnchorElement(containerElement);
  2910. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  2911. if (noteRefs.length) {
  2912. setNoteRefs(anchorElement, noteRefs);
  2913. } else {
  2914. delete anchorElement.dataset.singleFileNoteRefs;
  2915. }
  2916. }
  2917. function getNoteRefs(anchorElement) {
  2918. return anchorElement.dataset.singleFileNoteRefs ? anchorElement.dataset.singleFileNoteRefs.split(" ") : [];
  2919. }
  2920. function setNoteRefs(anchorElement, noteRefs) {
  2921. anchorElement.dataset.singleFileNoteRefs = noteRefs.join(" ");
  2922. }
  2923. function minifyText(text) {
  2924. return text.replace(/[\n\t\s]+/g, " ");
  2925. }
  2926. function isAncestor(element, otherElement) {
  2927. return otherElement.parentElement && (element == otherElement.parentElement || isAncestor(element, otherElement.parentElement));
  2928. }
  2929. function getShadowRoot(element) {
  2930. const chrome = window.chrome;
  2931. if (element.openOrClosedShadowRoot) {
  2932. return element.openOrClosedShadowRoot;
  2933. } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
  2934. try {
  2935. return chrome.dom.openOrClosedShadowRoot(element);
  2936. } catch (error) {
  2937. return element.shadowRoot;
  2938. }
  2939. } else {
  2940. return element.shadowRoot;
  2941. }
  2942. }
  2943. function detectSavedPage(document) {
  2944. const firstDocumentChild = document.documentElement.firstChild;
  2945. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  2946. (firstDocumentChild.textContent.includes(COMMENT_HEADER) || firstDocumentChild.textContent.includes(COMMENT_HEADER_LEGACY));
  2947. }
  2948. })(typeof globalThis == "object" ? globalThis : window);
  2949. })();