single-file-extension-editor.js 110 KB

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