single-file-extension-editor.js 117 KB

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