single-file-extension-editor.js 118 KB

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