single-file-extension-editor.js 115 KB

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