single-file-extension-editor.js 118 KB

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