single-file-extension-editor.js 116 KB

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