single-file-extension-editor.js 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276
  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 (Array.isArray(pageData.content)) {
  739. pageData.content = new Uint8Array(pageData.content);
  740. }
  741. if (options.sharePage && navigator.share) {
  742. await sharePage(pageData, options);
  743. } else {
  744. if (pageData.filename && pageData.filename.length) {
  745. const link = document.createElement("a");
  746. link.download = pageData.filename;
  747. link.href = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  748. link.dispatchEvent(new MouseEvent("click"));
  749. return new Promise(resolve => setTimeout(() => { URL.revokeObjectURL(link.href); resolve(); }, 1000));
  750. }
  751. }
  752. }
  753. async function sharePage(pageData, options) {
  754. sharePageBar = getSharePageBar();
  755. const cancelled = await sharePageBar.display(options.selected);
  756. if (!cancelled) {
  757. const data = { files: [new File([pageData.content], pageData.filename, { type: pageData.mimeType })] };
  758. try {
  759. await navigator.share(data);
  760. sharePageBar.hide();
  761. } catch (error) {
  762. sharePageBar.hide();
  763. if (error.name === "AbortError") {
  764. await sharePage(pageData, options);
  765. } else {
  766. throw error;
  767. }
  768. }
  769. }
  770. }
  771. /*
  772. * Copyright 2010-2020 Gildas Lormeau
  773. * contact : gildas.lormeau <at> gmail.com
  774. *
  775. * This file is part of SingleFile.
  776. *
  777. * The code in this file is free software: you can redistribute it and/or
  778. * modify it under the terms of the GNU Affero General Public License
  779. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  780. * of the License, or (at your option) any later version.
  781. *
  782. * The code in this file is distributed in the hope that it will be useful,
  783. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  784. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  785. * General Public License for more details.
  786. *
  787. * As additional permission under GNU AGPL version 3 section 7, you may
  788. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  789. * AGPL normally required by section 4, provided you include this license
  790. * notice and a URL through which recipients can access the Corresponding
  791. * Source.
  792. */
  793. (globalThis => {
  794. const IS_NOT_SAFARI = !/Safari/.test(navigator.userAgent) || /Chrome/.test(navigator.userAgent) || /Vivaldi/.test(navigator.userAgent) || /OPR/.test(navigator.userAgent);
  795. const singlefile = globalThis.singlefile;
  796. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  797. 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";
  798. 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==";
  799. const SHADOWROOT_ATTRIBUTE_NAME = "shadowrootmode";
  800. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  801. const SCRIPT_OPTIONS = "data-single-file-options";
  802. const NOTE_TAGNAME = "single-file-note";
  803. const NOTE_CLASS = "note";
  804. const NOTE_MASK_CLASS = "note-mask";
  805. const NOTE_HIDDEN_CLASS = "note-hidden";
  806. const NOTE_ANCHORED_CLASS = "note-anchored";
  807. const NOTE_SELECTED_CLASS = "note-selected";
  808. const NOTE_MOVING_CLASS = "note-moving";
  809. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  810. const PAGE_MASK_CLASS = "page-mask";
  811. const MASK_CLASS = "single-file-mask";
  812. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  813. const HIGHLIGHT_CLASS = "single-file-highlight";
  814. const HIGHLIGHTS_STYLESHEET_CLASS = "single-file-highlights-stylesheet";
  815. const REMOVED_CONTENT_CLASS = "single-file-removed";
  816. const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
  817. const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
  818. const CUT_HOVER_CLASS = "single-file-cut-hover";
  819. const CUT_OUTER_HOVER_CLASS = "single-file-cut-outer-hover";
  820. const CUT_SELECTED_CLASS = "single-file-cut-selected";
  821. const CUT_OUTER_SELECTED_CLASS = "single-file-cut-outer-selected";
  822. const CUT_MODE_CLASS = "single-file-cut-mode";
  823. const NOTE_INITIAL_POSITION_X = 20;
  824. const NOTE_INITIAL_POSITION_Y = 20;
  825. const NOTE_INITIAL_WIDTH = 150;
  826. const NOTE_INITIAL_HEIGHT = 150;
  827. const NOTE_HEADER_HEIGHT = 25;
  828. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  829. const COMMENT_HEADER = "Page saved with SingleFile";
  830. const COMMENT_HEADER_LEGACY = "Archive processed by SingleFile";
  831. const STYLE_FORMATTED_PAGE = `
  832. /* This Source Code Form is subject to the terms of the Mozilla Public
  833. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  834. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  835. /* Avoid adding ID selector rules in this style sheet, since they could
  836. * inadvertently match elements in the article content. */
  837. :root {
  838. --grey-90-a10: rgba(12, 12, 13, 0.1);
  839. --grey-90-a20: rgba(12, 12, 13, 0.2);
  840. --grey-90-a30: rgba(12, 12, 13, 0.3);
  841. --grey-90-a80: rgba(12, 12, 13, 0.8);
  842. --grey-30: #d7d7db;
  843. --blue-40: #45a1ff;
  844. --blue-40-a30: rgba(69, 161, 255, 0.3);
  845. --blue-60: #0060df;
  846. --body-padding: 64px;
  847. --font-size: 12;
  848. --content-width: 70em;
  849. --line-height: 1.6em;
  850. }
  851. body {
  852. --main-background: #fff;
  853. --main-foreground: #333;
  854. --font-color: #000000;
  855. --primary-color: #0B83FF;
  856. --toolbar-border: var(--grey-90-a20);
  857. --toolbar-transparent-border: transparent;
  858. --toolbar-box-shadow: var(--grey-90-a10);
  859. --toolbar-button-background: transparent;
  860. --toolbar-button-background-hover: var(--grey-90-a10);
  861. --toolbar-button-foreground-hover: var(--font-color);
  862. --toolbar-button-background-active: var(--grey-90-a20);
  863. --toolbar-button-foreground-active: var(--primary-color);
  864. --toolbar-button-border: transparent;
  865. --toolbar-button-border-hover: transparent;
  866. --toolbar-button-border-active: transparent;
  867. --tooltip-background: var(--grey-90-a80);
  868. --tooltip-foreground: white;
  869. --tooltip-border: transparent;
  870. --popup-background: white;
  871. --popup-border: rgba(0, 0, 0, 0.12);
  872. --opaque-popup-border: #e0e0e0;
  873. --popup-line: var(--grey-30);
  874. --popup-shadow: rgba(49, 49, 49, 0.3);
  875. --popup-button-background: #edecf0;
  876. --popup-button-background-hover: hsla(0,0%,70%,.4);
  877. --popup-button-foreground-hover: var(--font-color);
  878. --popup-button-background-active: hsla(240,5%,5%,.15);
  879. --selected-background: var(--blue-40-a30);
  880. --selected-border: var(--blue-40);
  881. --font-value-border: var(--grey-30);
  882. --icon-fill: #3b3b3c;
  883. --icon-disabled-fill: #8080807F;
  884. --link-foreground: var(--blue-60);
  885. --link-selected-foreground: #333;
  886. --visited-link-foreground: #b5007f;
  887. /* light colours */
  888. }
  889. body.sepia {
  890. --main-background: #f4ecd8;
  891. --main-foreground: #5b4636;
  892. --toolbar-border: #5b4636;
  893. }
  894. body.dark {
  895. --main-background: rgb(28, 27, 34);
  896. --main-foreground: #eee;
  897. --font-color: #fff;
  898. --toolbar-border: #4a4a4b;
  899. --toolbar-box-shadow: black;
  900. --toolbar-button-background-hover: var(--grey-90-a30);
  901. --toolbar-button-background-active: var(--grey-90-a80);
  902. --tooltip-background: black;
  903. --tooltip-foreground: white;
  904. --popup-background: rgb(66,65,77);
  905. --opaque-popup-border: #434146;
  906. --popup-line: rgb(82, 82, 94);
  907. --popup-button-background: #5c5c61;
  908. --popup-button-background-active: hsla(0,0%,70%,.6);
  909. --selected-background: #3E6D9A;
  910. --font-value-border: #656468;
  911. --icon-fill: #fff;
  912. --icon-disabled-fill: #ffffff66;
  913. --link-foreground: #45a1ff;
  914. --link-selected-foreground: #fff;
  915. --visited-link-foreground: #e675fd;
  916. /* dark colours */
  917. }
  918. body.hcm {
  919. --main-background: Canvas;
  920. --main-foreground: CanvasText;
  921. --font-color: CanvasText;
  922. --primary-color: SelectedItem;
  923. --toolbar-border: CanvasText;
  924. /* We need a true transparent but in HCM this would compute to an actual color,
  925. so select the page's background color instead: */
  926. --toolbar-transparent-border: Canvas;
  927. --toolbar-box-shadow: Canvas;
  928. --toolbar-button-background: ButtonFace;
  929. --toolbar-button-background-hover: ButtonText;
  930. --toolbar-button-foreground-hover: ButtonFace;
  931. --toolbar-button-background-active: SelectedItem;
  932. --toolbar-button-foreground-active: SelectedItemText;
  933. --toolbar-button-border: ButtonText;
  934. --toolbar-button-border-hover: ButtonText;
  935. --toolbar-button-border-active: ButtonText;
  936. --tooltip-background: Canvas;
  937. --tooltip-foreground: CanvasText;
  938. --tooltip-border: CanvasText;
  939. --popup-background: Canvas;
  940. --popup-border: CanvasText;
  941. --opaque-popup-border: CanvasText;
  942. --popup-line: CanvasText;
  943. --popup-button-background: ButtonFace;
  944. --popup-button-background-hover: ButtonText;
  945. --popup-button-foreground-hover: ButtonFace;
  946. --popup-button-background-active: ButtonText;
  947. --selected-background: Canvas;
  948. --selected-border: SelectedItem;
  949. --font-value-border: CanvasText;
  950. --icon-fill: ButtonText;
  951. --icon-disabled-fill: GrayText;
  952. --link-foreground: LinkText;
  953. --link-selected-foreground: ActiveText;
  954. --visited-link-foreground: VisitedText;
  955. }
  956. body {
  957. margin: 0;
  958. padding: var(--body-padding);
  959. background-color: var(--main-background);
  960. color: var(--main-foreground);
  961. }
  962. body.loaded {
  963. transition: color 0.4s, background-color 0.4s;
  964. }
  965. body.dark *::-moz-selection {
  966. background-color: var(--selected-background);
  967. }
  968. a::-moz-selection {
  969. color: var(--link-selected-foreground);
  970. }
  971. body.sans-serif,
  972. body.sans-serif .remove-button {
  973. font-family: Helvetica, Arial, sans-serif;
  974. }
  975. body.serif,
  976. body.serif .remove-button {
  977. font-family: Georgia, "Times New Roman", serif;
  978. }
  979. /* Override some controls and content styles based on color scheme */
  980. body.light > .container > .header > .domain {
  981. border-bottom-color: #333333 !important;
  982. }
  983. body.sepia > .container > .header > .domain {
  984. border-bottom-color: #5b4636 !important;
  985. }
  986. body.dark > .container > .header > .domain {
  987. border-bottom-color: #eeeeee !important;
  988. }
  989. body.light blockquote {
  990. border-inline-start: 2px solid #333333 !important;
  991. }
  992. body.sepia blockquote {
  993. border-inline-start: 2px solid #5b4636 !important;
  994. }
  995. body.dark blockquote {
  996. border-inline-start: 2px solid #eeeeee !important;
  997. }
  998. .light-button {
  999. color: #333333;
  1000. background-color: #ffffff;
  1001. }
  1002. .dark-button {
  1003. color: #eeeeee;
  1004. background-color: #1c1b22;
  1005. }
  1006. .sepia-button {
  1007. color: #5b4636;
  1008. background-color: #f4ecd8;
  1009. }
  1010. .auto-button {
  1011. text-align: center;
  1012. }
  1013. @media (prefers-color-scheme: dark) {
  1014. .auto-button {
  1015. background-color: #1c1b22;
  1016. color: #eeeeee;
  1017. }
  1018. }
  1019. @media not (prefers-color-scheme: dark) {
  1020. .auto-button {
  1021. background-color: #ffffff;
  1022. color: #333333;
  1023. }
  1024. }
  1025. /* Loading/error message */
  1026. .reader-message {
  1027. margin-top: 40px;
  1028. display: none;
  1029. text-align: center;
  1030. width: 100%;
  1031. font-size: 0.9em;
  1032. }
  1033. /* Detector element to see if we're at the top of the doc or not. */
  1034. .top-anchor {
  1035. position: absolute;
  1036. top: 0;
  1037. width: 0;
  1038. height: 5px;
  1039. pointer-events: none;
  1040. }
  1041. /* Header */
  1042. .header {
  1043. text-align: start;
  1044. display: none;
  1045. }
  1046. .domain {
  1047. font-size: 0.9em;
  1048. line-height: 1.48em;
  1049. padding-bottom: 4px;
  1050. font-family: Helvetica, Arial, sans-serif;
  1051. text-decoration: none;
  1052. border-bottom: 1px solid;
  1053. color: var(--link-foreground);
  1054. }
  1055. .header > h1 {
  1056. font-size: 1.6em;
  1057. line-height: 1.25em;
  1058. width: 100%;
  1059. margin: 30px 0;
  1060. padding: 0;
  1061. }
  1062. .header > .credits {
  1063. font-size: 0.9em;
  1064. line-height: 1.48em;
  1065. margin: 0 0 10px;
  1066. padding: 0;
  1067. font-style: italic;
  1068. }
  1069. .header > .meta-data {
  1070. font-size: 0.65em;
  1071. margin: 0 0 15px;
  1072. }
  1073. .reader-estimated-time {
  1074. text-align: match-parent;
  1075. }
  1076. /* Controls toolbar */
  1077. .toolbar-container {
  1078. position: sticky;
  1079. z-index: 2;
  1080. top: 32px;
  1081. height: 0; /* take up no space, so body is at the top. */
  1082. /* As a stick container, we're positioned relative to the body. Move us to
  1083. * the edge of the viewport using margins, and take the width of
  1084. * the body padding into account for calculating our width.
  1085. */
  1086. margin-inline-start: calc(-1 * var(--body-padding));
  1087. width: max(var(--body-padding), calc((100% - var(--content-width)) / 2 + var(--body-padding)));
  1088. font-size: var(--font-size); /* Needed to ensure 'em' units match, is reset for .reader-controls */
  1089. }
  1090. .toolbar {
  1091. padding-block: 16px;
  1092. border: 1px solid var(--toolbar-border);
  1093. border-radius: 6px;
  1094. box-shadow: 0 2px 8px var(--toolbar-box-shadow);
  1095. width: 32px; /* basic width, without padding/border */
  1096. /* padding should be 16px, except if there's not enough space for that, in
  1097. * which case use half the available space for padding (=25% on each side).
  1098. * The 34px here is the width + borders. We use a variable because we need
  1099. * to know this size for the margin calculation.
  1100. */
  1101. --inline-padding: min(16px, calc(25% - 0.25 * 34px));
  1102. padding-inline: var(--inline-padding);
  1103. /* Keep a maximum of 96px distance to the body, but center once the margin
  1104. * gets too small. We need to set the start margin, however...
  1105. * To center, we'd want 50% of the container, but we'd subtract half our
  1106. * own width (16px) and half the border (1px) and the inline padding.
  1107. * When the other margin would be 96px, we want 100% - 96px - the complete
  1108. * width of the actual toolbar (34px + 2 * padding)
  1109. */
  1110. margin-inline-start: max(calc(50% - 17px - var(--inline-padding)), calc(100% - 96px - 34px - 2 * var(--inline-padding)));
  1111. font-family: Helvetica, Arial, sans-serif;
  1112. list-style: none;
  1113. user-select: none;
  1114. }
  1115. @media (prefers-reduced-motion: no-preference) {
  1116. .toolbar {
  1117. transition-property: border-color, box-shadow;
  1118. transition-duration: 250ms;
  1119. }
  1120. .toolbar .toolbar-button {
  1121. transition-property: opacity;
  1122. transition-duration: 250ms;
  1123. }
  1124. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) {
  1125. border-color: var(--toolbar-transparent-border);
  1126. box-shadow: 0 2px 8px transparent;
  1127. }
  1128. .toolbar-container.scrolled .toolbar:not(:hover, :focus-within) .toolbar-button {
  1129. opacity: 0.6;
  1130. }
  1131. .toolbar-container.transition-location {
  1132. transition-duration: 250ms;
  1133. transition-property: width;
  1134. }
  1135. }
  1136. .toolbar-container.overlaps .toolbar-button {
  1137. opacity: 0.1;
  1138. }
  1139. .dropdown-open .toolbar {
  1140. border-color: var(--toolbar-transparent-border);
  1141. box-shadow: 0 2px 8px transparent;
  1142. }
  1143. .reader-controls {
  1144. /* We use 'em's above this node to get it to the right size. However,
  1145. * the UI inside the toolbar should use a fixed, smaller size. */
  1146. font-size: 11px;
  1147. }
  1148. button {
  1149. -moz-context-properties: fill;
  1150. color: var(--font-color);
  1151. fill: var(--icon-fill);
  1152. }
  1153. button:disabled {
  1154. fill: var(--icon-disabled-fill);
  1155. }
  1156. .toolbar button::-moz-focus-inner {
  1157. border: 0;
  1158. }
  1159. .toolbar-button {
  1160. position: relative;
  1161. width: 32px;
  1162. height: 32px;
  1163. padding: 0;
  1164. border: 1px solid var(--toolbar-button-border);
  1165. border-radius: 4px;
  1166. margin: 4px 0;
  1167. background-color: var(--toolbar-button-background);
  1168. background-size: 16px 16px;
  1169. background-position: center;
  1170. background-repeat: no-repeat;
  1171. }
  1172. .toolbar-button:hover,
  1173. .toolbar-button:focus-visible {
  1174. background-color: var(--toolbar-button-background-hover);
  1175. border-color: var(--toolbar-button-border-hover);
  1176. fill: var(--toolbar-button-foreground-hover);
  1177. }
  1178. .open .toolbar-button,
  1179. .toolbar-button:hover:active {
  1180. background-color: var(--toolbar-button-background-active);
  1181. border-color: var(--toolbar-button-border-active);
  1182. color: var(--toolbar-button-foreground-active);
  1183. fill: var(--toolbar-button-foreground-active);
  1184. }
  1185. .hover-label {
  1186. position: absolute;
  1187. top: 4px;
  1188. inset-inline-start: 36px;
  1189. line-height: 16px;
  1190. white-space: pre; /* make sure we don't wrap */
  1191. background-color: var(--tooltip-background);
  1192. color: var(--tooltip-foreground);
  1193. padding: 4px 8px;
  1194. border: 1px solid var(--tooltip-border);
  1195. border-radius: 2px;
  1196. visibility: hidden;
  1197. pointer-events: none;
  1198. /* Put above .dropdown .dropdown-popup, which has z-index: 1000. */
  1199. z-index: 1001;
  1200. }
  1201. /* Show the hover tooltip on non-dropdown buttons. */
  1202. .toolbar-button:not(.dropdown-toggle):hover > .hover-label,
  1203. .toolbar-button:not(.dropdown-toggle):focus-visible > .hover-label,
  1204. /* Show the hover tooltip for dropdown buttons unless its dropdown is open. */
  1205. :not(.open) > li > .dropdown-toggle:hover > .hover-label,
  1206. :not(.open) > li > .dropdown-toggle:focus-visible > .hover-label {
  1207. visibility: visible;
  1208. }
  1209. .dropdown {
  1210. text-align: center;
  1211. list-style: none;
  1212. margin: 0;
  1213. padding: 0;
  1214. position: relative;
  1215. }
  1216. .dropdown li {
  1217. margin: 0;
  1218. padding: 0;
  1219. }
  1220. /* Popup */
  1221. .dropdown .dropdown-popup {
  1222. text-align: start;
  1223. position: absolute;
  1224. inset-inline-start: 40px;
  1225. z-index: 1000;
  1226. background-color: var(--popup-background);
  1227. visibility: hidden;
  1228. border-radius: 4px;
  1229. border: 1px solid var(--popup-border);
  1230. box-shadow: 0 0 10px 0 var(--popup-shadow);
  1231. top: 0;
  1232. }
  1233. .open > .dropdown-popup {
  1234. visibility: visible;
  1235. }
  1236. .dropdown-arrow {
  1237. position: absolute;
  1238. height: 24px;
  1239. width: 16px;
  1240. inset-inline-start: -16px;
  1241. background-image: url("chrome://global/skin/reader/RM-Type-Controls-Arrow.svg");
  1242. display: block;
  1243. -moz-context-properties: fill, stroke;
  1244. fill: var(--popup-background);
  1245. stroke: var(--opaque-popup-border);
  1246. pointer-events: none;
  1247. }
  1248. .dropdown-arrow:dir(rtl) {
  1249. transform: scaleX(-1);
  1250. }
  1251. /* Align the style dropdown arrow (narrate does its own) */
  1252. .style-dropdown .dropdown-arrow {
  1253. top: 7px;
  1254. }
  1255. /* Font style popup */
  1256. .radio-button {
  1257. /* We visually hide these, but we keep them around so they can be focused
  1258. * and changed by interacting with them via the label, or the keyboard, or
  1259. * assistive technology.
  1260. */
  1261. opacity: 0;
  1262. pointer-events: none;
  1263. position: absolute;
  1264. }
  1265. .radiorow,
  1266. .buttonrow {
  1267. display: flex;
  1268. align-content: center;
  1269. justify-content: center;
  1270. }
  1271. .content-width-value,
  1272. .font-size-value,
  1273. .line-height-value {
  1274. box-sizing: border-box;
  1275. width: 36px;
  1276. height: 20px;
  1277. line-height: 20px;
  1278. display: flex;
  1279. justify-content: center;
  1280. align-content: center;
  1281. margin: auto;
  1282. border-radius: 10px;
  1283. border: 1px solid var(--font-value-border);
  1284. background-color: var(--popup-button-background);
  1285. }
  1286. .buttonrow > button {
  1287. border: 0;
  1288. height: 60px;
  1289. width: 90px;
  1290. background-color: transparent;
  1291. background-repeat: no-repeat;
  1292. background-position: center;
  1293. }
  1294. .buttonrow > button:enabled:hover,
  1295. .buttonrow > button:enabled:focus-visible {
  1296. background-color: var(--popup-button-background-hover);
  1297. color: var(--popup-button-foreground-hover);
  1298. fill: var(--popup-button-foreground-hover);
  1299. }
  1300. .buttonrow > button:enabled:hover:active {
  1301. background-color: var(--popup-button-background-active);
  1302. }
  1303. .radiorow:not(:last-child),
  1304. .buttonrow:not(:last-child) {
  1305. border-bottom: 1px solid var(--popup-line);
  1306. }
  1307. body.hcm .buttonrow.line-height-buttons {
  1308. /* On HCM the .color-scheme-buttons row is hidden, so remove the border from the row above it */
  1309. border-bottom: none;
  1310. }
  1311. .radiorow > label {
  1312. position: relative;
  1313. box-sizing: border-box;
  1314. border-radius: 2px;
  1315. border: 2px solid var(--popup-border);
  1316. }
  1317. .radiorow > label[checked] {
  1318. border-color: var(--selected-border);
  1319. }
  1320. /* For the hover style, we draw a line under the item by means of a
  1321. * pseudo-element. Because these items are variable height, and
  1322. * because their contents are variable height, position it absolutely,
  1323. * and give it a width of 100% (the content width) + 4px for the 2 * 2px
  1324. * border width.
  1325. */
  1326. .radiorow > input[type=radio]:focus-visible + label::after,
  1327. .radiorow > label:hover::after {
  1328. content: "";
  1329. display: block;
  1330. border-bottom: 2px solid var(--selected-border);
  1331. width: calc(100% + 4px);
  1332. position: absolute;
  1333. /* to skip the 2 * 2px border + 2px spacing. */
  1334. bottom: -6px;
  1335. /* Match the start of the 2px border of the element: */
  1336. inset-inline-start: -2px;
  1337. }
  1338. .font-type-buttons > label {
  1339. height: 64px;
  1340. width: 105px;
  1341. /* Slightly more space between these items. */
  1342. margin: 10px;
  1343. /* Center the Sans-serif / Serif labels */
  1344. text-align: center;
  1345. background-size: 63px 39px;
  1346. background-repeat: no-repeat;
  1347. background-position: center 18px;
  1348. background-color: var(--popup-button-background);
  1349. fill: currentColor;
  1350. -moz-context-properties: fill;
  1351. /* This mostly matches baselines, but because of differences in font
  1352. * baselines between serif and sans-serif, this isn't always enough. */
  1353. line-height: 1;
  1354. padding-top: 2px;
  1355. }
  1356. .font-type-buttons > label[checked] {
  1357. background-color: var(--selected-background);
  1358. }
  1359. .sans-serif-button {
  1360. font-family: Helvetica, Arial, sans-serif;
  1361. background-image: url("chrome://global/skin/reader/RM-Sans-Serif.svg");
  1362. }
  1363. /* Tweak padding to match the baseline on mac */
  1364. :root[platform=macosx] .sans-serif-button {
  1365. padding-top: 3px;
  1366. }
  1367. .serif-button {
  1368. font-family: Georgia, "Times New Roman", serif;
  1369. background-image: url("chrome://global/skin/reader/RM-Serif.svg");
  1370. }
  1371. body.hcm .color-scheme-buttons {
  1372. /* Disallow selecting themes when HCM is on. */
  1373. display: none;
  1374. }
  1375. .color-scheme-buttons > label {
  1376. padding: 12px;
  1377. height: 34px;
  1378. font-size: 12px;
  1379. /* Center the labels horizontally as well as vertically */
  1380. display: inline-flex;
  1381. align-items: center;
  1382. justify-content: center;
  1383. /* We want 10px between items, but there's no margin collapsing in flexbox. */
  1384. margin: 10px 5px;
  1385. }
  1386. .color-scheme-buttons > input:first-child + label {
  1387. margin-inline-start: 10px;
  1388. }
  1389. .color-scheme-buttons > label:last-child {
  1390. margin-inline-end: 10px;
  1391. }
  1392. /* Toolbar icons */
  1393. .close-button {
  1394. background-image: url("chrome://global/skin/icons/close.svg");
  1395. }
  1396. .style-button {
  1397. background-image: url("chrome://global/skin/reader/RM-Type-Controls-24x24.svg");
  1398. }
  1399. .minus-button {
  1400. background-size: 18px 18px;
  1401. background-image: url("chrome://global/skin/reader/RM-Minus-24x24.svg");
  1402. }
  1403. .plus-button {
  1404. background-size: 18px 18px;
  1405. background-image: url("chrome://global/skin/reader/RM-Plus-24x24.svg");
  1406. }
  1407. .content-width-minus-button {
  1408. background-size: 42px 16px;
  1409. background-image: url("chrome://global/skin/reader/RM-Content-Width-Minus-42x16.svg");
  1410. }
  1411. .content-width-plus-button {
  1412. background-size: 44px 16px;
  1413. background-image: url("chrome://global/skin/reader/RM-Content-Width-Plus-44x16.svg");
  1414. }
  1415. .line-height-minus-button {
  1416. background-size: 34px 14px;
  1417. background-image: url("chrome://global/skin/reader/RM-Line-Height-Minus-38x14.svg");
  1418. }
  1419. .line-height-plus-button {
  1420. background-size: 34px 24px;
  1421. background-image: url("chrome://global/skin/reader/RM-Line-Height-Plus-38x24.svg");
  1422. }
  1423. /* Mirror the line height buttons if the article is RTL. */
  1424. .reader-controls[articledir="rtl"] .line-height-minus-button,
  1425. .reader-controls[articledir="rtl"] .line-height-plus-button {
  1426. transform: scaleX(-1);
  1427. }
  1428. @media print {
  1429. .toolbar {
  1430. display: none !important;
  1431. }
  1432. }
  1433. /* Article content */
  1434. /* Note that any class names from the original article that we want to match on
  1435. * must be added to CLASSES_TO_PRESERVE in ReaderMode.jsm, so that
  1436. * Readability.js doesn't strip them out */
  1437. .container {
  1438. margin: 0 auto;
  1439. font-size: var(--font-size);
  1440. max-width: var(--content-width);
  1441. line-height: var(--line-height);
  1442. }
  1443. pre {
  1444. font-family: inherit;
  1445. }
  1446. .moz-reader-content {
  1447. display: none;
  1448. font-size: 1em;
  1449. }
  1450. @media print {
  1451. .moz-reader-content p,
  1452. .moz-reader-content code,
  1453. .moz-reader-content pre,
  1454. .moz-reader-content blockquote,
  1455. .moz-reader-content ul,
  1456. .moz-reader-content ol,
  1457. .moz-reader-content li,
  1458. .moz-reader-content figure,
  1459. .moz-reader-content .wp-caption {
  1460. margin: 0 0 10px !important;
  1461. padding: 0 !important;
  1462. }
  1463. }
  1464. .moz-reader-content h1,
  1465. .moz-reader-content h2,
  1466. .moz-reader-content h3 {
  1467. font-weight: bold;
  1468. }
  1469. .moz-reader-content h1 {
  1470. font-size: 1.6em;
  1471. line-height: 1.25em;
  1472. }
  1473. .moz-reader-content h2 {
  1474. font-size: 1.2em;
  1475. line-height: 1.51em;
  1476. }
  1477. .moz-reader-content h3 {
  1478. font-size: 1em;
  1479. line-height: 1.66em;
  1480. }
  1481. .moz-reader-content a:link {
  1482. text-decoration: underline;
  1483. font-weight: normal;
  1484. }
  1485. .moz-reader-content a:link,
  1486. .moz-reader-content a:link:hover,
  1487. .moz-reader-content a:link:active {
  1488. color: var(--link-foreground);
  1489. }
  1490. .moz-reader-content a:visited {
  1491. color: var(--visited-link-foreground);
  1492. }
  1493. .moz-reader-content * {
  1494. max-width: 100%;
  1495. height: auto;
  1496. }
  1497. .moz-reader-content p,
  1498. .moz-reader-content p,
  1499. .moz-reader-content code,
  1500. .moz-reader-content pre,
  1501. .moz-reader-content blockquote,
  1502. .moz-reader-content ul,
  1503. .moz-reader-content ol,
  1504. .moz-reader-content li,
  1505. .moz-reader-content figure,
  1506. .moz-reader-content .wp-caption {
  1507. margin: -10px -10px 20px;
  1508. padding: 10px;
  1509. border-radius: 5px;
  1510. }
  1511. .moz-reader-content li {
  1512. margin-bottom: 0;
  1513. }
  1514. .moz-reader-content li > ul,
  1515. .moz-reader-content li > ol {
  1516. margin-bottom: -10px;
  1517. }
  1518. .moz-reader-content p > img:only-child,
  1519. .moz-reader-content p > a:only-child > img:only-child,
  1520. .moz-reader-content .wp-caption img,
  1521. .moz-reader-content figure img {
  1522. display: block;
  1523. }
  1524. .moz-reader-content img[moz-reader-center] {
  1525. margin-inline: auto;
  1526. }
  1527. .moz-reader-content .caption,
  1528. .moz-reader-content .wp-caption-text
  1529. .moz-reader-content figcaption {
  1530. font-size: 0.9em;
  1531. line-height: 1.48em;
  1532. font-style: italic;
  1533. }
  1534. .moz-reader-content pre {
  1535. white-space: pre-wrap;
  1536. }
  1537. .moz-reader-content blockquote {
  1538. padding: 0;
  1539. padding-inline-start: 16px;
  1540. }
  1541. .moz-reader-content ul,
  1542. .moz-reader-content ol {
  1543. padding: 0;
  1544. }
  1545. .moz-reader-content ul {
  1546. padding-inline-start: 30px;
  1547. list-style: disc;
  1548. }
  1549. .moz-reader-content ol {
  1550. padding-inline-start: 30px;
  1551. }
  1552. table,
  1553. th,
  1554. td {
  1555. border: 1px solid currentColor;
  1556. border-collapse: collapse;
  1557. padding: 6px;
  1558. vertical-align: top;
  1559. }
  1560. table {
  1561. margin: 5px;
  1562. }
  1563. /* Visually hide (but don't display: none) screen reader elements */
  1564. .moz-reader-content .visually-hidden,
  1565. .moz-reader-content .visuallyhidden,
  1566. .moz-reader-content .sr-only {
  1567. display: inline-block;
  1568. width: 1px;
  1569. height: 1px;
  1570. margin: -1px;
  1571. overflow: hidden;
  1572. padding: 0;
  1573. border-width: 0;
  1574. }
  1575. /* Hide elements with common "hidden" class names */
  1576. .moz-reader-content .hidden,
  1577. .moz-reader-content .invisible {
  1578. display: none;
  1579. }
  1580. /* Enforce wordpress and similar emoji/smileys aren't sized to be full-width,
  1581. * see bug 1399616 for context. */
  1582. .moz-reader-content img.wp-smiley,
  1583. .moz-reader-content img.emoji {
  1584. display: inline-block;
  1585. border-width: 0;
  1586. /* height: auto is implied from '.moz-reader-content *' rule. */
  1587. width: 1em;
  1588. margin: 0 .07em;
  1589. padding: 0;
  1590. }
  1591. .reader-show-element {
  1592. display: initial;
  1593. }
  1594. /* Provide extra spacing for images that may be aided with accompanying element such as <figcaption> */
  1595. .moz-reader-block-img:not(:last-child) {
  1596. margin-block-end: 12px;
  1597. }
  1598. .moz-reader-wide-table {
  1599. overflow-x: auto;
  1600. display: block;
  1601. }
  1602. pre code {
  1603. background-color: var(--main-background);
  1604. border: 1px solid var(--font-color);
  1605. display: block;
  1606. overflow: auto;
  1607. }`;
  1608. let NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET;
  1609. let selectedNote, anchorElement, maskNoteElement, maskPageElement, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, highlightColor, collapseNoteTimeout, cuttingOuterMode, cuttingMode, cuttingTouchTarget, cuttingPath, cuttingPathIndex, previousContent;
  1610. let removedElements = [], removedElementIndex = 0, initScriptContent, pageResources, pageUrl, pageCompressContent, includeInfobar;
  1611. globalThis.zip = singlefile.helper.zip;
  1612. initEventListeners();
  1613. new MutationObserver(initEventListeners).observe(document, { childList: true });
  1614. function initEventListeners() {
  1615. window.onmessage = async event => {
  1616. const message = JSON.parse(event.data);
  1617. if (message.method == "init") {
  1618. await init(message);
  1619. }
  1620. if (message.method == "addNote") {
  1621. addNote(message);
  1622. }
  1623. if (message.method == "displayNotes") {
  1624. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  1625. }
  1626. if (message.method == "hideNotes") {
  1627. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  1628. }
  1629. if (message.method == "enableHighlight") {
  1630. if (highlightColor) {
  1631. document.documentElement.classList.remove(highlightColor + "-mode");
  1632. }
  1633. highlightColor = message.color;
  1634. highlightSelectionMode = true;
  1635. document.documentElement.classList.add(message.color + "-mode");
  1636. }
  1637. if (message.method == "disableHighlight") {
  1638. disableHighlight();
  1639. highlightSelectionMode = false;
  1640. }
  1641. if (message.method == "displayHighlights") {
  1642. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  1643. }
  1644. if (message.method == "hideHighlights") {
  1645. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  1646. }
  1647. if (message.method == "enableRemoveHighlights") {
  1648. removeHighlightMode = true;
  1649. document.documentElement.classList.add("single-file-remove-highlights-mode");
  1650. }
  1651. if (message.method == "disableRemoveHighlights") {
  1652. removeHighlightMode = false;
  1653. document.documentElement.classList.remove("single-file-remove-highlights-mode");
  1654. }
  1655. if (message.method == "enableEditPage") {
  1656. document.body.contentEditable = true;
  1657. onUpdate(false);
  1658. }
  1659. if (message.method == "formatPage") {
  1660. formatPage(!message.applySystemTheme);
  1661. }
  1662. if (message.method == "cancelFormatPage") {
  1663. cancelFormatPage();
  1664. }
  1665. if (message.method == "disableEditPage") {
  1666. document.body.contentEditable = false;
  1667. }
  1668. if (message.method == "enableCutInnerPage") {
  1669. cuttingMode = true;
  1670. document.documentElement.classList.add(CUT_MODE_CLASS);
  1671. }
  1672. if (message.method == "enableCutOuterPage") {
  1673. cuttingOuterMode = true;
  1674. document.documentElement.classList.add(CUT_MODE_CLASS);
  1675. }
  1676. if (message.method == "disableCutInnerPage" || message.method == "disableCutOuterPage") {
  1677. if (message.method == "disableCutInnerPage") {
  1678. cuttingMode = false;
  1679. } else {
  1680. cuttingOuterMode = false;
  1681. }
  1682. document.documentElement.classList.remove(CUT_MODE_CLASS);
  1683. resetSelectedElements();
  1684. if (cuttingPath) {
  1685. unhighlightCutElement();
  1686. cuttingPath = null;
  1687. }
  1688. }
  1689. if (message.method == "undoCutPage") {
  1690. undoCutPage();
  1691. }
  1692. if (message.method == "undoAllCutPage") {
  1693. while (removedElementIndex) {
  1694. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  1695. removedElementIndex--;
  1696. }
  1697. }
  1698. if (message.method == "redoCutPage") {
  1699. redoCutPage();
  1700. }
  1701. if (message.method == "getContent") {
  1702. onUpdate(true);
  1703. includeInfobar = message.includeInfobar;
  1704. let content = getContent(message.compressHTML, message.updatedResources);
  1705. if (initScriptContent) {
  1706. content = content.replace(/<script data-template-shadow-root src.*?<\/script>/g, initScriptContent);
  1707. }
  1708. let filename;
  1709. const pageOptions = loadOptionsFromPage(document);
  1710. if (pageOptions) {
  1711. pageOptions.backgroundSave = message.backgroundSave;
  1712. pageOptions.saveDate = new Date(pageOptions.saveDate);
  1713. pageOptions.visitDate = new Date(pageOptions.visitDate);
  1714. filename = await singlefile.helper.formatFilename(content, document, pageOptions);
  1715. }
  1716. if (message.sharePage) {
  1717. setLabels(message.labels);
  1718. }
  1719. if (pageCompressContent) {
  1720. const viewport = document.head.querySelector("meta[name=viewport]");
  1721. window.parent.postMessage(JSON.stringify({
  1722. method: "setContent",
  1723. content,
  1724. filename,
  1725. title: document.title,
  1726. doctype: singlefile.helper.getDoctypeString(document),
  1727. url: pageUrl,
  1728. viewport: viewport ? viewport.content : null,
  1729. compressContent: true,
  1730. foregroundSave: message.foregroundSave,
  1731. sharePage: message.sharePage
  1732. }), "*");
  1733. } else {
  1734. if (message.foregroundSave || message.sharePage) {
  1735. try {
  1736. await downloadPageForeground({
  1737. content,
  1738. filename: filename || message.filename,
  1739. mimeType: "text/html"
  1740. }, { sharePage: message.sharePage });
  1741. } catch (error) {
  1742. console.log(error); // eslint-disable-line no-console
  1743. window.parent.postMessage(JSON.stringify({ method: "onError", error: error.message }), "*");
  1744. }
  1745. } else {
  1746. window.parent.postMessage(JSON.stringify({
  1747. method: "setContent",
  1748. content,
  1749. filename
  1750. }), "*");
  1751. }
  1752. }
  1753. }
  1754. if (message.method == "printPage") {
  1755. printPage();
  1756. }
  1757. if (message.method == "displayInfobar") {
  1758. singlefile.helper.displayIcon(document, true);
  1759. const infobarDoc = document.implementation.createHTMLDocument();
  1760. infobarDoc.body.appendChild(document.querySelector(singlefile.helper.INFOBAR_TAGNAME));
  1761. serializeShadowRoots(infobarDoc.body);
  1762. const content = singlefile.helper.serialize(infobarDoc, true);
  1763. window.parent.postMessage(JSON.stringify({
  1764. method: "displayInfobar",
  1765. content
  1766. }), "*");
  1767. }
  1768. if (message.method == "download") {
  1769. try {
  1770. await downloadPageForeground({
  1771. content: message.content,
  1772. filename: message.filename,
  1773. mimeType: message.mimeType
  1774. }, { sharePage: message.sharePage });
  1775. } catch (error) {
  1776. console.log(error); // eslint-disable-line no-console
  1777. window.parent.postMessage(JSON.stringify({ method: "onError", error: error.message }), "*");
  1778. }
  1779. }
  1780. };
  1781. window.onresize = reflowNotes;
  1782. document.ondragover = event => event.preventDefault();
  1783. document.ondrop = async event => {
  1784. if (event.dataTransfer.files && event.dataTransfer.files[0]) {
  1785. const file = event.dataTransfer.files[0];
  1786. event.preventDefault();
  1787. const content = new TextDecoder().decode(await file.arrayBuffer());
  1788. const compressContent = /<html[^>]* data-sfz[^>]*>/i.test(content);
  1789. if (compressContent) {
  1790. await init({ content: file, compressContent }, { filename: file.name });
  1791. } else {
  1792. await init({ content }, { filename: file.name });
  1793. }
  1794. }
  1795. };
  1796. }
  1797. async function init({ content, password, compressContent }, { filename, reset } = {}) {
  1798. await initConstants();
  1799. if (compressContent) {
  1800. const zipOptions = {
  1801. workerScripts: { inflate: ["/lib/single-file-z-worker.js"] }
  1802. };
  1803. try {
  1804. const worker = new Worker(zipOptions.workerScripts.inflate[0]);
  1805. worker.terminate();
  1806. } catch (error) {
  1807. delete zipOptions.workerScripts;
  1808. }
  1809. zipOptions.useWebWorkers = IS_NOT_SAFARI;
  1810. const { docContent, origDocContent, resources, url } = await singlefile.helper.extract(content, {
  1811. password,
  1812. prompt,
  1813. shadowRootScriptURL: new URL("/lib/single-file-extension-editor-init.js", document.baseURI).href,
  1814. zipOptions
  1815. });
  1816. pageResources = resources;
  1817. pageUrl = url;
  1818. pageCompressContent = true;
  1819. const contentDocument = (new DOMParser()).parseFromString(docContent, "text/html");
  1820. if (detectSavedPage(contentDocument)) {
  1821. await singlefile.helper.display(document, docContent, { disableFramePointerEvents: true });
  1822. const infobarElement = document.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1823. if (infobarElement) {
  1824. infobarElement.remove();
  1825. }
  1826. await initPage();
  1827. let icon;
  1828. const origContentDocument = (new DOMParser()).parseFromString(origDocContent, "text/html");
  1829. const iconElement = origContentDocument.querySelector("link[rel*=icon]");
  1830. if (iconElement) {
  1831. const iconResource = resources.find(resource => resource.filename == iconElement.getAttribute("href"));
  1832. if (iconResource && iconResource.content) {
  1833. const reader = new FileReader();
  1834. reader.readAsDataURL(await (await fetch(iconResource.content)).blob());
  1835. icon = await new Promise((resolve, reject) => {
  1836. reader.addEventListener("load", () => resolve(reader.result), false);
  1837. reader.addEventListener("error", reject, false);
  1838. });
  1839. } else {
  1840. icon = iconElement.href;
  1841. }
  1842. }
  1843. window.parent.postMessage(JSON.stringify({
  1844. method: "onInit",
  1845. title: document.title,
  1846. icon,
  1847. filename,
  1848. reset,
  1849. formatPageEnabled: isProbablyReaderable(document)
  1850. }), "*");
  1851. }
  1852. } else {
  1853. const initScriptContentMatch = content.match(/<script data-template-shadow-root.*<\/script>/);
  1854. if (initScriptContentMatch && initScriptContentMatch[0]) {
  1855. initScriptContent = initScriptContentMatch[0];
  1856. }
  1857. content = content.replace(/<script data-template-shadow-root.*<\/script>/g, "<script data-template-shadow-root src=/lib/single-file-extension-editor-init.js></script>");
  1858. const contentDocument = (new DOMParser()).parseFromString(content, "text/html");
  1859. if (detectSavedPage(contentDocument)) {
  1860. if (contentDocument.doctype) {
  1861. if (document.doctype) {
  1862. document.replaceChild(contentDocument.doctype, document.doctype);
  1863. } else {
  1864. document.insertBefore(contentDocument.doctype, document.documentElement);
  1865. }
  1866. } else if (document.doctype) {
  1867. document.doctype.remove();
  1868. }
  1869. const infobarElement = contentDocument.querySelector(singlefile.helper.INFOBAR_TAGNAME);
  1870. if (infobarElement) {
  1871. infobarElement.remove();
  1872. }
  1873. contentDocument.querySelectorAll("noscript").forEach(element => {
  1874. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  1875. element.textContent = "";
  1876. });
  1877. contentDocument.querySelectorAll("iframe").forEach(element => {
  1878. const pointerEvents = "pointer-events";
  1879. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1880. element.style.setProperty(pointerEvents, "none", "important");
  1881. });
  1882. document.replaceChild(contentDocument.documentElement, document.documentElement);
  1883. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1884. deserializeShadowRoots(document);
  1885. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1886. insertHighlightStylesheet(document);
  1887. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1888. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1889. document.documentElement.onmousedown = onMouseDown;
  1890. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1891. document.documentElement.onmouseover = onMouseOver;
  1892. document.documentElement.onmouseout = onMouseOut;
  1893. document.documentElement.onkeydown = onKeyDown;
  1894. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1895. window.onclick = event => event.preventDefault();
  1896. const iconElement = document.querySelector("link[rel*=icon]");
  1897. window.parent.postMessage(JSON.stringify({
  1898. method: "onInit",
  1899. title: document.title,
  1900. icon: iconElement && iconElement.href,
  1901. filename,
  1902. reset,
  1903. formatPageEnabled: isProbablyReaderable(document)
  1904. }), "*");
  1905. }
  1906. }
  1907. }
  1908. function loadOptionsFromPage(doc) {
  1909. const optionsElement = doc.body.querySelector("script[type=\"application/json\"][" + SCRIPT_OPTIONS + "]");
  1910. if (optionsElement) {
  1911. return JSON.parse(optionsElement.textContent);
  1912. }
  1913. }
  1914. async function initPage() {
  1915. document.querySelectorAll("iframe").forEach(element => {
  1916. const pointerEvents = "pointer-events";
  1917. element.style.setProperty("-sf-" + pointerEvents, element.style.getPropertyValue(pointerEvents), element.style.getPropertyPriority(pointerEvents));
  1918. element.style.setProperty(pointerEvents, "none", "important");
  1919. });
  1920. document.querySelectorAll("[data-single-file-note-refs]").forEach(noteRefElement => noteRefElement.dataset.singleFileNoteRefs = noteRefElement.dataset.singleFileNoteRefs.replace(/,/g, " "));
  1921. deserializeShadowRoots(document);
  1922. reflowNotes();
  1923. await waitResourcesLoad();
  1924. reflowNotes();
  1925. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  1926. insertHighlightStylesheet(document);
  1927. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  1928. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  1929. document.documentElement.onmousedown = onMouseDown;
  1930. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  1931. document.documentElement.onmouseover = onMouseOver;
  1932. document.documentElement.onmouseout = onMouseOut;
  1933. document.documentElement.onkeydown = onKeyDown;
  1934. document.documentElement.ontouchstart = document.documentElement.ontouchmove = onTouchMove;
  1935. window.onclick = event => event.preventDefault();
  1936. }
  1937. async function initConstants() {
  1938. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  1939. minifyText(await ((await fetch("../pages/editor-note-web.css")).text())),
  1940. minifyText(await ((await fetch("../pages/editor-mask-web.css")).text())),
  1941. minifyText(await ((await fetch("../pages/editor-frame-web.css")).text()))
  1942. ]);
  1943. }
  1944. function addNote({ color }) {
  1945. const containerElement = document.createElement(NOTE_TAGNAME);
  1946. const noteElement = document.createElement("div");
  1947. const headerElement = document.createElement("header");
  1948. const blockquoteElement = document.createElement("blockquote");
  1949. const mainElement = document.createElement("textarea");
  1950. const resizeElement = document.createElement("div");
  1951. const removeNoteElement = document.createElement("img");
  1952. const anchorIconElement = document.createElement("img");
  1953. const noteShadow = containerElement.attachShadow({ mode: "open" });
  1954. headerElement.appendChild(anchorIconElement);
  1955. headerElement.appendChild(removeNoteElement);
  1956. blockquoteElement.appendChild(mainElement);
  1957. noteElement.appendChild(headerElement);
  1958. noteElement.appendChild(blockquoteElement);
  1959. noteElement.appendChild(resizeElement);
  1960. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  1961. noteShadow.appendChild(noteElement);
  1962. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  1963. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  1964. blockquoteElement.cite = "https://www.w3.org/TR/annotation-model/#selector(type=CssSelector,value=[data-single-file-note-refs~=\"" + noteId + "\"])";
  1965. noteElement.classList.add(NOTE_CLASS);
  1966. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  1967. noteElement.classList.add(color);
  1968. noteElement.dataset.color = color;
  1969. mainElement.dir = "auto";
  1970. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  1971. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  1972. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  1973. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  1974. positionX += NOTE_INITIAL_POSITION_X;
  1975. positionY += NOTE_INITIAL_POSITION_Y;
  1976. }
  1977. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  1978. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  1979. resizeElement.className = "note-resize";
  1980. resizeElement.ondragstart = event => event.preventDefault();
  1981. removeNoteElement.className = "note-remove";
  1982. removeNoteElement.src = BUTTON_CLOSE_URL;
  1983. removeNoteElement.ondragstart = event => event.preventDefault();
  1984. anchorIconElement.className = "note-anchor";
  1985. anchorIconElement.src = BUTTON_ANCHOR_URL;
  1986. anchorIconElement.ondragstart = event => event.preventDefault();
  1987. containerElement.dataset.noteId = noteId;
  1988. addNoteRef(document.documentElement, noteId);
  1989. attachNoteListeners(containerElement, true);
  1990. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  1991. noteElement.classList.add(NOTE_SELECTED_CLASS);
  1992. selectedNote = noteElement;
  1993. onUpdate(false);
  1994. }
  1995. function attachNoteListeners(containerElement, editable = false) {
  1996. const SELECT_PX_THRESHOLD = 4;
  1997. const COLLAPSING_NOTE_DELAY = 750;
  1998. const noteShadow = containerElement.shadowRoot;
  1999. const noteElement = noteShadow.childNodes[1];
  2000. const headerElement = noteShadow.querySelector("header");
  2001. const mainElement = noteShadow.querySelector("textarea");
  2002. const noteId = containerElement.dataset.noteId;
  2003. const resizeElement = noteShadow.querySelector(".note-resize");
  2004. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  2005. const removeNoteElement = noteShadow.querySelector(".note-remove");
  2006. mainElement.readOnly = !editable;
  2007. if (!editable) {
  2008. anchorIconElement.style.setProperty("display", "none", "important");
  2009. } else {
  2010. anchorIconElement.style.removeProperty("display");
  2011. }
  2012. headerElement.ontouchstart = headerElement.onmousedown = event => {
  2013. if (event.target == headerElement) {
  2014. collapseNoteTimeout = setTimeout(() => {
  2015. noteElement.classList.toggle("note-collapsed");
  2016. hideMaskNote();
  2017. }, COLLAPSING_NOTE_DELAY);
  2018. event.preventDefault();
  2019. const position = getPosition(event);
  2020. const clientX = position.clientX;
  2021. const clientY = position.clientY;
  2022. const boundingRect = noteElement.getBoundingClientRect();
  2023. const deltaX = clientX - boundingRect.left;
  2024. const deltaY = clientY - boundingRect.top;
  2025. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  2026. document.documentElement.style.setProperty("user-select", "none", "important");
  2027. anchorElement = getAnchorElement(containerElement);
  2028. displayMaskNote();
  2029. selectNote(noteElement);
  2030. moveNote(event, deltaX, deltaY);
  2031. movingNoteMode = { event, deltaX, deltaY };
  2032. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  2033. clearTimeout(collapseNoteTimeout);
  2034. if (!movingNoteMode) {
  2035. movingNoteMode = { deltaX, deltaY };
  2036. }
  2037. movingNoteMode.event = event;
  2038. moveNote(event, deltaX, deltaY);
  2039. };
  2040. }
  2041. };
  2042. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  2043. event.preventDefault();
  2044. resizingNoteMode = true;
  2045. selectNote(noteElement);
  2046. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  2047. document.documentElement.style.setProperty("user-select", "none", "important");
  2048. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  2049. event.preventDefault();
  2050. const { clientX, clientY } = getPosition(event);
  2051. const boundingRectNote = noteElement.getBoundingClientRect();
  2052. noteElement.style.width = clientX - boundingRectNote.left + "px";
  2053. noteElement.style.height = clientY - boundingRectNote.top + "px";
  2054. };
  2055. };
  2056. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  2057. event.preventDefault();
  2058. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  2059. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  2060. deleteNoteRef(containerElement, noteId);
  2061. addNoteRef(document.documentElement, noteId);
  2062. }
  2063. onUpdate(false);
  2064. };
  2065. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  2066. event.preventDefault();
  2067. deleteNoteRef(containerElement, noteId);
  2068. containerElement.remove();
  2069. };
  2070. noteElement.onmousedown = () => {
  2071. selectNote(noteElement);
  2072. };
  2073. function moveNote(event, deltaX, deltaY) {
  2074. event.preventDefault();
  2075. const { clientX, clientY } = getPosition(event);
  2076. noteElement.classList.add(NOTE_MOVING_CLASS);
  2077. if (editable) {
  2078. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  2079. deleteNoteRef(containerElement, noteId);
  2080. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  2081. addNoteRef(anchorElement, noteId);
  2082. } else {
  2083. anchorElement = document.documentElement;
  2084. }
  2085. }
  2086. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  2087. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  2088. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  2089. noteElement.style.setProperty("position", "fixed");
  2090. displayMaskNote();
  2091. }
  2092. function displayMaskNote() {
  2093. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  2094. hideMaskNote();
  2095. } else {
  2096. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  2097. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  2098. if (selectedNote) {
  2099. maskNoteElement.classList.add(selectedNote.dataset.color);
  2100. }
  2101. maskNoteElement.style.setProperty("top", (boundingRectAnchor.y - 3) + "px");
  2102. maskNoteElement.style.setProperty("left", (boundingRectAnchor.x - 3) + "px");
  2103. maskNoteElement.style.setProperty("width", (boundingRectAnchor.width + 3) + "px");
  2104. maskNoteElement.style.setProperty("height", (boundingRectAnchor.height + 3) + "px");
  2105. }
  2106. }
  2107. function hideMaskNote() {
  2108. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  2109. if (selectedNote) {
  2110. maskNoteElement.classList.remove(selectedNote.dataset.color);
  2111. }
  2112. }
  2113. function selectNote(noteElement) {
  2114. if (selectedNote) {
  2115. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  2116. maskNoteElement.classList.remove(selectedNote.dataset.color);
  2117. }
  2118. noteElement.classList.add(NOTE_SELECTED_CLASS);
  2119. noteElement.classList.add(noteElement.dataset.color);
  2120. selectedNote = noteElement;
  2121. }
  2122. function getTarget(clientX, clientY) {
  2123. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.matches("html *:not(" + NOTE_TAGNAME + "):not(." + MASK_CLASS + ")"));
  2124. if (!targets.includes(document.documentElement)) {
  2125. targets.push(document.documentElement);
  2126. }
  2127. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  2128. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  2129. if (newTarget == target) {
  2130. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  2131. }
  2132. if (newTarget == target) {
  2133. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  2134. }
  2135. if (newTarget == target) {
  2136. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  2137. }
  2138. target = newTarget;
  2139. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  2140. target = target.parentElement;
  2141. }
  2142. return target;
  2143. }
  2144. function getMatchedParents(target, property) {
  2145. let element = target, matchedParent, parents = [];
  2146. do {
  2147. const boundingRect = element.getBoundingClientRect();
  2148. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  2149. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  2150. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  2151. if (matchedParent) {
  2152. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  2153. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  2154. parents.push(element.parentElement);
  2155. }
  2156. element = element.parentElement;
  2157. }
  2158. } else {
  2159. matchedParent = false;
  2160. }
  2161. } while (matchedParent && element);
  2162. return parents;
  2163. }
  2164. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  2165. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  2166. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  2167. }
  2168. return target;
  2169. }
  2170. }
  2171. function onMouseDown(event) {
  2172. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  2173. event.preventDefault();
  2174. }
  2175. }
  2176. function onMouseUp(event) {
  2177. if (highlightSelectionMode) {
  2178. event.preventDefault();
  2179. highlightSelection();
  2180. onUpdate(false);
  2181. }
  2182. if (removeHighlightMode) {
  2183. event.preventDefault();
  2184. let element = event.target, done;
  2185. while (element && !done) {
  2186. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  2187. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  2188. resetHighlightedElement(highlightedElement);
  2189. onUpdate(false);
  2190. });
  2191. done = true;
  2192. }
  2193. element = element.parentElement;
  2194. }
  2195. }
  2196. if (resizingNoteMode) {
  2197. event.preventDefault();
  2198. resizingNoteMode = false;
  2199. document.documentElement.style.removeProperty("user-select");
  2200. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  2201. document.documentElement.ontouchmove = onTouchMove;
  2202. document.documentElement.onmousemove = null;
  2203. onUpdate(false);
  2204. }
  2205. if (movingNoteMode) {
  2206. event.preventDefault();
  2207. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  2208. movingNoteMode = null;
  2209. document.documentElement.ontouchmove = onTouchMove;
  2210. document.documentElement.onmousemove = null;
  2211. onUpdate(false);
  2212. }
  2213. if ((cuttingMode || cuttingOuterMode) && cuttingPath) {
  2214. event.preventDefault();
  2215. if (event.ctrlKey) {
  2216. const element = cuttingPath[cuttingPathIndex];
  2217. element.classList.toggle(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  2218. } else {
  2219. validateCutElement(event.shiftKey);
  2220. }
  2221. }
  2222. if (collapseNoteTimeout) {
  2223. clearTimeout(collapseNoteTimeout);
  2224. collapseNoteTimeout = null;
  2225. }
  2226. }
  2227. function onMouseOver(event) {
  2228. if (cuttingMode || cuttingOuterMode) {
  2229. const target = event.target;
  2230. if (target.classList) {
  2231. let ancestorFound;
  2232. document.querySelectorAll("." + (cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS)).forEach(element => {
  2233. if (element == target || isAncestor(element, target) || isAncestor(target, element)) {
  2234. ancestorFound = element;
  2235. }
  2236. });
  2237. if (ancestorFound) {
  2238. cuttingPath = [ancestorFound];
  2239. } else {
  2240. cuttingPath = getParents(event.target);
  2241. }
  2242. cuttingPathIndex = 0;
  2243. highlightCutElement();
  2244. }
  2245. }
  2246. }
  2247. function onMouseOut() {
  2248. if (cuttingMode || cuttingOuterMode) {
  2249. if (cuttingPath) {
  2250. unhighlightCutElement();
  2251. cuttingPath = null;
  2252. }
  2253. }
  2254. }
  2255. function onTouchMove(event) {
  2256. if (cuttingMode || cuttingOuterMode) {
  2257. event.preventDefault();
  2258. const { clientX, clientY } = getPosition(event);
  2259. const target = document.elementFromPoint(clientX, clientY);
  2260. if (cuttingTouchTarget != target) {
  2261. onMouseOut();
  2262. if (target) {
  2263. cuttingTouchTarget = target;
  2264. onMouseOver({ target });
  2265. }
  2266. }
  2267. }
  2268. }
  2269. function onKeyDown(event) {
  2270. if (cuttingMode || cuttingOuterMode) {
  2271. if (event.code == "Tab") {
  2272. if (cuttingPath) {
  2273. const delta = event.shiftKey ? -1 : 1;
  2274. let element = cuttingPath[cuttingPathIndex];
  2275. let nextElement = cuttingPath[cuttingPathIndex + delta];
  2276. if (nextElement) {
  2277. let pathIndex = cuttingPathIndex + delta;
  2278. while (
  2279. nextElement &&
  2280. (
  2281. (delta == 1 &&
  2282. element.getBoundingClientRect().width >= nextElement.getBoundingClientRect().width &&
  2283. element.getBoundingClientRect().height >= nextElement.getBoundingClientRect().height) ||
  2284. (delta == -1 &&
  2285. element.getBoundingClientRect().width <= nextElement.getBoundingClientRect().width &&
  2286. element.getBoundingClientRect().height <= nextElement.getBoundingClientRect().height))) {
  2287. pathIndex += delta;
  2288. nextElement = cuttingPath[pathIndex];
  2289. }
  2290. if (nextElement && nextElement.classList && nextElement != document.body && nextElement != document.documentElement) {
  2291. unhighlightCutElement();
  2292. cuttingPathIndex = pathIndex;
  2293. highlightCutElement();
  2294. }
  2295. }
  2296. }
  2297. event.preventDefault();
  2298. }
  2299. if (event.code == "Space") {
  2300. if (cuttingPath) {
  2301. if (event.ctrlKey) {
  2302. const element = cuttingPath[cuttingPathIndex];
  2303. element.classList.add(cuttingMode ? CUT_SELECTED_CLASS : CUT_OUTER_SELECTED_CLASS);
  2304. } else {
  2305. validateCutElement(event.shiftKey);
  2306. }
  2307. event.preventDefault();
  2308. }
  2309. }
  2310. if (event.code == "Escape") {
  2311. resetSelectedElements();
  2312. event.preventDefault();
  2313. }
  2314. if (event.key.toLowerCase() == "z" && event.ctrlKey) {
  2315. if (event.shiftKey) {
  2316. redoCutPage();
  2317. } else {
  2318. undoCutPage();
  2319. }
  2320. event.preventDefault();
  2321. }
  2322. }
  2323. if (event.key.toLowerCase() == "s" && event.ctrlKey) {
  2324. window.parent.postMessage(JSON.stringify({ "method": "savePage" }), "*");
  2325. event.preventDefault();
  2326. }
  2327. if (event.key.toLowerCase() == "p" && event.ctrlKey) {
  2328. printPage();
  2329. event.preventDefault();
  2330. }
  2331. }
  2332. function printPage() {
  2333. unhighlightCutElement();
  2334. resetSelectedElements();
  2335. window.print();
  2336. }
  2337. function highlightCutElement() {
  2338. const element = cuttingPath[cuttingPathIndex];
  2339. element.classList.add(cuttingMode ? CUT_HOVER_CLASS : CUT_OUTER_HOVER_CLASS);
  2340. }
  2341. function unhighlightCutElement() {
  2342. if (cuttingPath) {
  2343. const element = cuttingPath[cuttingPathIndex];
  2344. element.classList.remove(CUT_HOVER_CLASS);
  2345. element.classList.remove(CUT_OUTER_HOVER_CLASS);
  2346. }
  2347. }
  2348. function disableHighlight(doc = document) {
  2349. if (highlightColor) {
  2350. doc.documentElement.classList.remove(highlightColor + "-mode");
  2351. }
  2352. }
  2353. function undoCutPage() {
  2354. if (removedElementIndex) {
  2355. removedElements[removedElementIndex - 1].forEach(element => element.classList.remove(REMOVED_CONTENT_CLASS));
  2356. removedElementIndex--;
  2357. }
  2358. }
  2359. function redoCutPage() {
  2360. if (removedElementIndex < removedElements.length) {
  2361. removedElements[removedElementIndex].forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  2362. removedElementIndex++;
  2363. }
  2364. }
  2365. function validateCutElement(invert) {
  2366. const selectedElement = cuttingPath[cuttingPathIndex];
  2367. if ((cuttingMode && !invert) || (cuttingOuterMode && invert)) {
  2368. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  2369. const elementsRemoved = [selectedElement].concat(...document.querySelectorAll("." + CUT_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS + " *,." + CUT_HOVER_CLASS + " *"));
  2370. resetSelectedElements();
  2371. if (elementsRemoved.length) {
  2372. elementsRemoved.forEach(element => {
  2373. unhighlightCutElement();
  2374. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  2375. resetAnchorNote(element);
  2376. } else {
  2377. element.classList.add(REMOVED_CONTENT_CLASS);
  2378. }
  2379. });
  2380. removedElements[removedElementIndex] = elementsRemoved;
  2381. removedElementIndex++;
  2382. removedElements.length = removedElementIndex;
  2383. onUpdate(false);
  2384. }
  2385. }
  2386. } else {
  2387. if (document.documentElement != selectedElement && selectedElement.tagName.toLowerCase() != NOTE_TAGNAME) {
  2388. const elements = [];
  2389. const searchSelector = "*:not(style):not(meta):not(." + REMOVED_CONTENT_CLASS + ")";
  2390. const elementsKept = [selectedElement].concat(...document.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS));
  2391. document.body.querySelectorAll(searchSelector).forEach(element => {
  2392. let removed = true;
  2393. elementsKept.forEach(elementKept => removed = removed && (elementKept != element && !isAncestor(elementKept, element) && !isAncestor(element, elementKept)));
  2394. if (removed) {
  2395. if (element.tagName.toLowerCase() == NOTE_TAGNAME) {
  2396. resetAnchorNote(element);
  2397. } else {
  2398. elements.push(element);
  2399. }
  2400. }
  2401. });
  2402. elementsKept.forEach(elementKept => {
  2403. unhighlightCutElement();
  2404. const elementKeptRect = elementKept.getBoundingClientRect();
  2405. elementKept.querySelectorAll(searchSelector).forEach(descendant => {
  2406. const descendantRect = descendant.getBoundingClientRect();
  2407. if (descendantRect.width && descendantRect.height && (
  2408. descendantRect.left + descendantRect.width < elementKeptRect.left ||
  2409. descendantRect.right > elementKeptRect.right + elementKeptRect.width ||
  2410. descendantRect.top + descendantRect.height < elementKeptRect.top ||
  2411. descendantRect.bottom > elementKeptRect.bottom + elementKeptRect.height
  2412. )) {
  2413. elements.push(descendant);
  2414. }
  2415. });
  2416. });
  2417. resetSelectedElements();
  2418. if (elements.length) {
  2419. elements.forEach(element => element.classList.add(REMOVED_CONTENT_CLASS));
  2420. removedElements[removedElementIndex] = elements;
  2421. removedElementIndex++;
  2422. removedElements.length = removedElementIndex;
  2423. onUpdate(false);
  2424. }
  2425. }
  2426. }
  2427. }
  2428. function resetSelectedElements(doc = document) {
  2429. doc.querySelectorAll("." + CUT_OUTER_SELECTED_CLASS + ",." + CUT_SELECTED_CLASS).forEach(element => {
  2430. element.classList.remove(CUT_OUTER_SELECTED_CLASS);
  2431. element.classList.remove(CUT_SELECTED_CLASS);
  2432. });
  2433. }
  2434. function anchorNote(event, noteElement, deltaX, deltaY) {
  2435. event.preventDefault();
  2436. const { clientX, clientY } = getPosition(event);
  2437. document.documentElement.style.removeProperty("user-select");
  2438. noteElement.classList.remove(NOTE_MOVING_CLASS);
  2439. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  2440. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  2441. maskNoteElement.classList.remove(noteElement.dataset.color);
  2442. const headerElement = noteElement.querySelector("header");
  2443. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  2444. let currentElement = anchorElement;
  2445. let positionedElement;
  2446. while (currentElement.parentElement && !positionedElement) {
  2447. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  2448. const currentElementStyle = getComputedStyle(currentElement);
  2449. if (currentElementStyle.position != "static") {
  2450. positionedElement = currentElement;
  2451. }
  2452. }
  2453. currentElement = currentElement.parentElement;
  2454. }
  2455. if (!positionedElement) {
  2456. positionedElement = document.documentElement;
  2457. }
  2458. const containerElement = noteElement.getRootNode().host;
  2459. if (positionedElement == document.documentElement) {
  2460. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  2461. firstMaskElement.parentElement.insertBefore(containerElement, firstMaskElement);
  2462. } else {
  2463. positionedElement.appendChild(containerElement);
  2464. }
  2465. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  2466. const stylePositionedElement = window.getComputedStyle(positionedElement);
  2467. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  2468. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  2469. noteElement.style.setProperty("position", "absolute");
  2470. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  2471. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  2472. }
  2473. function resetAnchorNote(containerElement) {
  2474. const noteId = containerElement.dataset.noteId;
  2475. const noteElement = containerElement.shadowRoot.childNodes[1];
  2476. noteElement.classList.remove(NOTE_ANCHORED_CLASS);
  2477. deleteNoteRef(containerElement, noteId);
  2478. addNoteRef(document.documentElement, noteId);
  2479. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  2480. }
  2481. function getPosition(event) {
  2482. if (event.touches && event.touches.length) {
  2483. const touch = event.touches[0];
  2484. return touch;
  2485. } else {
  2486. return event;
  2487. }
  2488. }
  2489. function highlightSelection() {
  2490. let highlightId = 0;
  2491. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  2492. highlightId++;
  2493. const selection = window.getSelection();
  2494. const highlightedNodes = new Set();
  2495. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  2496. const range = selection.getRangeAt(indexRange);
  2497. if (!range.collapsed) {
  2498. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  2499. let contentText = range.startContainer.splitText(range.startOffset);
  2500. contentText = contentText.splitText(range.endOffset);
  2501. addHighLightedNode(contentText.previousSibling);
  2502. } else {
  2503. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  2504. let highlightNodes;
  2505. while (treeWalker.nextNode()) {
  2506. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  2507. addHighLightedNode(treeWalker.currentNode);
  2508. }
  2509. if (treeWalker.currentNode == range.startContainer) {
  2510. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  2511. const contentText = range.startContainer.splitText(range.startOffset);
  2512. treeWalker.nextNode();
  2513. addHighLightedNode(contentText);
  2514. } else {
  2515. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  2516. }
  2517. highlightNodes = true;
  2518. }
  2519. if (treeWalker.currentNode == range.endContainer) {
  2520. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  2521. const contentText = range.endContainer.splitText(range.endOffset);
  2522. treeWalker.nextNode();
  2523. addHighLightedNode(contentText.previousSibling);
  2524. } else {
  2525. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  2526. }
  2527. highlightNodes = false;
  2528. }
  2529. }
  2530. range.collapse();
  2531. }
  2532. }
  2533. }
  2534. highlightedNodes.forEach(node => highlightNode(node));
  2535. function addHighLightedNode(node) {
  2536. if (node && node.textContent.trim()) {
  2537. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  2538. highlightedNodes.add(node.parentElement);
  2539. } else {
  2540. highlightedNodes.add(node);
  2541. }
  2542. }
  2543. }
  2544. function highlightNode(node) {
  2545. if (node.nodeType == node.ELEMENT_NODE) {
  2546. resetHighlightedElement(node);
  2547. node.classList.add(HIGHLIGHT_CLASS);
  2548. node.classList.add(highlightColor);
  2549. node.dataset.singlefileHighlightId = highlightId;
  2550. } else if (node.parentElement) {
  2551. highlightTextNode(node);
  2552. }
  2553. }
  2554. function highlightTextNode(node) {
  2555. const spanElement = document.createElement("span");
  2556. spanElement.classList.add(HIGHLIGHT_CLASS);
  2557. spanElement.classList.add(highlightColor);
  2558. spanElement.textContent = node.textContent;
  2559. spanElement.dataset.singlefileHighlightId = highlightId;
  2560. node.parentNode.replaceChild(spanElement, node);
  2561. return spanElement;
  2562. }
  2563. }
  2564. function getParents(element) {
  2565. const path = [];
  2566. while (element) {
  2567. path.push(element);
  2568. element = element.parentElement;
  2569. }
  2570. return path;
  2571. }
  2572. function formatPage(applySystemTheme) {
  2573. if (pageCompressContent) {
  2574. serializeShadowRoots(document);
  2575. previousContent = document.documentElement.cloneNode(true);
  2576. deserializeShadowRoots(document);
  2577. } else {
  2578. previousContent = getContent(false, []);
  2579. }
  2580. const shadowRoots = {};
  2581. const classesToPreserve = ["single-file-highlight", "single-file-highlight-yellow", "single-file-highlight-green", "single-file-highlight-pink", "single-file-highlight-blue"];
  2582. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2583. shadowRoots[containerElement.dataset.noteId] = containerElement.shadowRoot;
  2584. const className = "singlefile-note-id-" + containerElement.dataset.noteId;
  2585. containerElement.classList.add(className);
  2586. classesToPreserve.push(className);
  2587. });
  2588. const article = new Readability(document, { classesToPreserve }).parse();
  2589. removedElements = [];
  2590. removedElementIndex = 0;
  2591. document.body.innerHTML = "";
  2592. const domParser = new DOMParser();
  2593. const doc = domParser.parseFromString(article.content, "text/html");
  2594. const contentEditable = document.body.contentEditable;
  2595. document.documentElement.replaceChild(doc.body, document.body);
  2596. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2597. const noteId = (Array.from(containerElement.classList).find(className => /singlefile-note-id-\d+/.test(className))).split("singlefile-note-id-")[1];
  2598. containerElement.classList.remove("singlefile-note-id-" + noteId);
  2599. containerElement.dataset.noteId = noteId;
  2600. if (!containerElement.shadowRoot) {
  2601. containerElement.attachShadow({ mode: "open" });
  2602. containerElement.shadowRoot.appendChild(shadowRoots[noteId]);
  2603. }
  2604. });
  2605. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => shadowRoots[containerElement.dataset.noteId].childNodes.forEach(node => containerElement.shadowRoot.appendChild(node)));
  2606. document.body.contentEditable = contentEditable;
  2607. document.head.querySelectorAll("style").forEach(styleElement => styleElement.remove());
  2608. const styleElement = document.createElement("style");
  2609. styleElement.textContent = STYLE_FORMATTED_PAGE;
  2610. document.head.appendChild(styleElement);
  2611. document.body.classList.add("moz-reader-content");
  2612. document.body.classList.add("content-width6");
  2613. document.body.classList.add("reader-show-element");
  2614. document.body.classList.add("sans-serif");
  2615. document.body.classList.add("container");
  2616. document.body.classList.add("line-height4");
  2617. const prefersColorSchemeDark = matchMedia("(prefers-color-scheme: dark)");
  2618. if (applySystemTheme && prefersColorSchemeDark && prefersColorSchemeDark.matches) {
  2619. document.body.classList.add("dark");
  2620. }
  2621. document.body.style.setProperty("display", "block");
  2622. document.body.style.setProperty("padding", "24px");
  2623. const titleElement = document.createElement("h1");
  2624. titleElement.classList.add("reader-title");
  2625. titleElement.textContent = article.title;
  2626. document.body.insertBefore(titleElement, document.body.firstChild);
  2627. document.querySelectorAll("a[href]").forEach(element => {
  2628. const href = element.getAttribute("href").trim();
  2629. if (href.startsWith(document.baseURI + "#")) {
  2630. element.setAttribute("href", href.substring(document.baseURI.length));
  2631. }
  2632. });
  2633. insertHighlightStylesheet(document);
  2634. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  2635. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  2636. reflowNotes();
  2637. onUpdate(false);
  2638. }
  2639. async function cancelFormatPage() {
  2640. if (previousContent) {
  2641. const contentEditable = document.body.contentEditable;
  2642. if (pageCompressContent) {
  2643. document.replaceChild(previousContent, document.documentElement);
  2644. deserializeShadowRoots(document);
  2645. await initPage();
  2646. } else {
  2647. await init({ content: previousContent }, { reset: true });
  2648. }
  2649. document.body.contentEditable = contentEditable;
  2650. onUpdate(false);
  2651. previousContent = null;
  2652. }
  2653. }
  2654. function insertHighlightStylesheet(doc) {
  2655. if (!doc.querySelector("." + HIGHLIGHTS_STYLESHEET_CLASS)) {
  2656. const styleheetHighlights = getStyleElement(HIGHLIGHTS_WEB_STYLESHEET);
  2657. styleheetHighlights.classList.add(HIGHLIGHTS_STYLESHEET_CLASS);
  2658. doc.documentElement.appendChild(styleheetHighlights);
  2659. }
  2660. }
  2661. function getContent(compressHTML, updatedResources) {
  2662. unhighlightCutElement();
  2663. serializeShadowRoots(document);
  2664. const doc = document.cloneNode(true);
  2665. disableHighlight(doc);
  2666. resetSelectedElements(doc);
  2667. deserializeShadowRoots(doc);
  2668. deserializeShadowRoots(document);
  2669. doc.documentElement.classList.remove(CUT_MODE_CLASS);
  2670. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  2671. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  2672. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  2673. });
  2674. doc.querySelectorAll("." + MASK_CLASS + ", " + singlefile.helper.INFOBAR_TAGNAME + ", ." + REMOVED_CONTENT_CLASS).forEach(element => element.remove());
  2675. if (includeInfobar) {
  2676. singlefile.helper.appendInfobar(doc, singlefile.helper.extractInfobarData(doc));
  2677. }
  2678. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  2679. doc.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  2680. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  2681. if (noteElement) {
  2682. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  2683. }
  2684. const mainElement = templateElement.querySelector("textarea");
  2685. if (mainElement) {
  2686. mainElement.textContent = mainElement.value;
  2687. }
  2688. });
  2689. doc.querySelectorAll("iframe").forEach(element => {
  2690. const pointerEvents = "pointer-events";
  2691. element.style.setProperty(pointerEvents, element.style.getPropertyValue("-sf-" + pointerEvents), element.style.getPropertyPriority("-sf-" + pointerEvents));
  2692. element.style.removeProperty("-sf-" + pointerEvents);
  2693. });
  2694. doc.body.removeAttribute("contentEditable");
  2695. const newResources = Object.keys(updatedResources).filter(url => updatedResources[url].type == "stylesheet").map(url => updatedResources[url]);
  2696. newResources.forEach(resource => {
  2697. const element = doc.createElement("style");
  2698. doc.body.appendChild(element);
  2699. element.textContent = resource.content;
  2700. });
  2701. if (pageCompressContent) {
  2702. const pageFilename = pageResources
  2703. .filter(resource => resource.filename.endsWith("index.html"))
  2704. .sort((resourceLeft, resourceRight) => resourceLeft.filename.length - resourceRight.filename.length)[0].filename;
  2705. const resources = pageResources.filter(resource => resource.parentResources.includes(pageFilename));
  2706. doc.querySelectorAll("[src]").forEach(element => resources.forEach(resource => {
  2707. if (element.src == resource.content) {
  2708. element.src = resource.name;
  2709. }
  2710. }));
  2711. let content = singlefile.helper.serialize(doc, compressHTML);
  2712. resources.sort((resourceLeft, resourceRight) => resourceRight.content.length - resourceLeft.content.length);
  2713. resources.forEach(resource => content = content.replaceAll(resource.content, resource.name));
  2714. return content + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  2715. } else {
  2716. return singlefile.helper.serialize(doc, compressHTML) + "<script " + SCRIPT_TEMPLATE_SHADOW_ROOT + ">" + getEmbedScript() + "</script>";
  2717. }
  2718. }
  2719. function onUpdate(saved) {
  2720. window.parent.postMessage(JSON.stringify({ "method": "onUpdate", saved }), "*");
  2721. }
  2722. function waitResourcesLoad() {
  2723. return new Promise(resolve => {
  2724. let counterMutations = 0;
  2725. const done = () => {
  2726. observer.disconnect();
  2727. resolve();
  2728. };
  2729. let timeoutInit = setTimeout(done, 100);
  2730. const observer = new MutationObserver(() => {
  2731. if (counterMutations < 20) {
  2732. counterMutations++;
  2733. clearTimeout(timeoutInit);
  2734. timeoutInit = setTimeout(done, 100);
  2735. } else {
  2736. done();
  2737. }
  2738. });
  2739. observer.observe(document, { subtree: true, childList: true, attributes: true });
  2740. });
  2741. }
  2742. function reflowNotes() {
  2743. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  2744. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  2745. const noteBoundingRect = noteElement.getBoundingClientRect();
  2746. const anchorElement = getAnchorElement(containerElement);
  2747. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  2748. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  2749. const minX = anchorBoundingRect.x;
  2750. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  2751. const minY = anchorBoundingRect.y;
  2752. let left = parseInt(noteElement.style.getPropertyValue("left"));
  2753. let top = parseInt(noteElement.style.getPropertyValue("top"));
  2754. if (noteBoundingRect.x > maxX) {
  2755. left -= noteBoundingRect.x - maxX;
  2756. }
  2757. if (noteBoundingRect.x < minX) {
  2758. left += minX - noteBoundingRect.x;
  2759. }
  2760. if (noteBoundingRect.y > maxY) {
  2761. top -= noteBoundingRect.y - maxY;
  2762. }
  2763. if (noteBoundingRect.y < minY) {
  2764. top += minY - noteBoundingRect.y;
  2765. }
  2766. noteElement.style.setProperty("position", "absolute");
  2767. noteElement.style.setProperty("left", left + "px");
  2768. noteElement.style.setProperty("top", top + "px");
  2769. });
  2770. }
  2771. function resetHighlightedElement(element) {
  2772. element.classList.remove(HIGHLIGHT_CLASS);
  2773. element.classList.remove("single-file-highlight-yellow");
  2774. element.classList.remove("single-file-highlight-pink");
  2775. element.classList.remove("single-file-highlight-blue");
  2776. element.classList.remove("single-file-highlight-green");
  2777. delete element.dataset.singlefileHighlightId;
  2778. }
  2779. function serializeShadowRoots(node) {
  2780. node.querySelectorAll("*").forEach(element => {
  2781. const shadowRoot = getShadowRoot(element);
  2782. if (shadowRoot) {
  2783. serializeShadowRoots(shadowRoot);
  2784. const templateElement = document.createElement("template");
  2785. templateElement.setAttribute(SHADOWROOT_ATTRIBUTE_NAME, "open");
  2786. Array.from(shadowRoot.childNodes).forEach(childNode => templateElement.appendChild(childNode));
  2787. element.appendChild(templateElement);
  2788. }
  2789. });
  2790. }
  2791. function deserializeShadowRoots(node) {
  2792. node.querySelectorAll(`template[${SHADOWROOT_ATTRIBUTE_NAME}]`).forEach(element => {
  2793. if (element.parentElement) {
  2794. let shadowRoot = getShadowRoot(element.parentElement);
  2795. if (shadowRoot) {
  2796. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  2797. element.remove();
  2798. } else {
  2799. try {
  2800. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  2801. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  2802. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  2803. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  2804. } catch (error) {
  2805. // ignored
  2806. }
  2807. }
  2808. if (shadowRoot) {
  2809. deserializeShadowRoots(shadowRoot);
  2810. }
  2811. }
  2812. });
  2813. }
  2814. function getMaskElement(className, containerClassName) {
  2815. let maskElement = document.documentElement.querySelector("." + className);
  2816. if (!maskElement) {
  2817. maskElement = document.createElement("div");
  2818. const maskContainerElement = document.createElement("div");
  2819. if (containerClassName) {
  2820. maskContainerElement.classList.add(containerClassName);
  2821. }
  2822. maskContainerElement.classList.add(MASK_CLASS);
  2823. const firstNote = document.querySelector(NOTE_TAGNAME);
  2824. if (firstNote && firstNote.parentElement == document.documentElement) {
  2825. document.documentElement.insertBefore(maskContainerElement, firstNote);
  2826. } else {
  2827. document.documentElement.appendChild(maskContainerElement);
  2828. }
  2829. maskElement.classList.add(className);
  2830. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  2831. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  2832. maskShadow.appendChild(maskElement);
  2833. return maskElement;
  2834. }
  2835. }
  2836. function getEmbedScript() {
  2837. return minifyText(`(() => {
  2838. document.currentScript.remove();
  2839. const processNode = node => {
  2840. node.querySelectorAll("template[${SHADOWROOT_ATTRIBUTE_NAME}]").forEach(element=>{
  2841. let shadowRoot = getShadowRoot(element.parentElement);
  2842. if (!shadowRoot) {
  2843. try {
  2844. shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOWROOT_ATTRIBUTE_NAME}")});
  2845. shadowRoot.innerHTML = element.innerHTML;
  2846. element.remove();
  2847. } catch (error) {}
  2848. if (shadowRoot) {
  2849. processNode(shadowRoot);
  2850. }
  2851. }
  2852. })
  2853. };
  2854. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  2855. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  2856. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  2857. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  2858. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  2859. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  2860. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  2861. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  2862. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  2863. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  2864. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  2865. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  2866. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  2867. const REMOVED_CONTENT_CLASS = ${JSON.stringify(REMOVED_CONTENT_CLASS)};
  2868. const reflowNotes = ${minifyText(reflowNotes.toString())};
  2869. const addNoteRef = ${minifyText(addNoteRef.toString())};
  2870. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  2871. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  2872. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  2873. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  2874. const getMaskElement = ${minifyText(getMaskElement.toString())};
  2875. const getStyleElement = ${minifyText(getStyleElement.toString())};
  2876. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  2877. const anchorNote = ${minifyText(anchorNote.toString())};
  2878. const getPosition = ${minifyText(getPosition.toString())};
  2879. const onMouseUp = ${minifyText(onMouseUp.toString())};
  2880. const getShadowRoot = ${minifyText(getShadowRoot.toString())};
  2881. const waitResourcesLoad = ${minifyText(waitResourcesLoad.toString())};
  2882. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  2883. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  2884. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout, cuttingMode, cuttingOuterMode;
  2885. window.onresize = reflowNotes;
  2886. window.onUpdate = () => {};
  2887. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  2888. processNode(document);
  2889. reflowNotes();
  2890. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  2891. if (document.documentElement.dataset.sfz !== undefined) {
  2892. waitResourcesLoad().then(reflowNotes);
  2893. }
  2894. })()`);
  2895. }
  2896. function getStyleElement(stylesheet) {
  2897. const linkElement = document.createElement("style");
  2898. linkElement.textContent = stylesheet;
  2899. return linkElement;
  2900. }
  2901. function getAnchorElement(containerElement) {
  2902. return document.querySelector("[data-single-file-note-refs~=\"" + containerElement.dataset.noteId + "\"]") || document.documentElement;
  2903. }
  2904. function addNoteRef(anchorElement, noteId) {
  2905. const noteRefs = getNoteRefs(anchorElement);
  2906. noteRefs.push(noteId);
  2907. setNoteRefs(anchorElement, noteRefs);
  2908. }
  2909. function deleteNoteRef(containerElement, noteId) {
  2910. const anchorElement = getAnchorElement(containerElement);
  2911. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  2912. if (noteRefs.length) {
  2913. setNoteRefs(anchorElement, noteRefs);
  2914. } else {
  2915. delete anchorElement.dataset.singleFileNoteRefs;
  2916. }
  2917. }
  2918. function getNoteRefs(anchorElement) {
  2919. return anchorElement.dataset.singleFileNoteRefs ? anchorElement.dataset.singleFileNoteRefs.split(" ") : [];
  2920. }
  2921. function setNoteRefs(anchorElement, noteRefs) {
  2922. anchorElement.dataset.singleFileNoteRefs = noteRefs.join(" ");
  2923. }
  2924. function minifyText(text) {
  2925. return text.replace(/[\n\t\s]+/g, " ");
  2926. }
  2927. function isAncestor(element, otherElement) {
  2928. return otherElement.parentElement && (element == otherElement.parentElement || isAncestor(element, otherElement.parentElement));
  2929. }
  2930. function getShadowRoot(element) {
  2931. const chrome = window.chrome;
  2932. if (element.openOrClosedShadowRoot) {
  2933. return element.openOrClosedShadowRoot;
  2934. } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
  2935. try {
  2936. return chrome.dom.openOrClosedShadowRoot(element);
  2937. } catch (error) {
  2938. return element.shadowRoot;
  2939. }
  2940. } else {
  2941. return element.shadowRoot;
  2942. }
  2943. }
  2944. function detectSavedPage(document) {
  2945. const firstDocumentChild = document.documentElement.firstChild;
  2946. return firstDocumentChild.nodeType == Node.COMMENT_NODE &&
  2947. (firstDocumentChild.textContent.includes(COMMENT_HEADER) || firstDocumentChild.textContent.includes(COMMENT_HEADER_LEGACY));
  2948. }
  2949. })(typeof globalThis == "object" ? globalThis : window);
  2950. })();