content-ui-editor-web.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global singlefile, window, document, fetch, DOMParser, getComputedStyle, setTimeout, clearTimeout, NodeFilter */
  24. (async () => {
  25. const FORBIDDEN_TAG_NAMES = ["a", "area", "audio", "base", "br", "col", "command", "embed", "hr", "img", "iframe", "input", "keygen", "link", "meta", "param", "source", "track", "video", "wbr"];
  26. const BUTTON_ANCHOR_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAHdElNRQfjCh0VAjZTpsLvAAAA1klEQVQoz3XQMS8EURQF4O9txN9QSCjoNYRiy01EomDb3UbnR+j8BpSKrbaaQvwAyTZ2Qyg0WiwJiZjmKmasmWTnvObe8849971DFSe+/TjVgL6wpyMczxcMXYIzV/9kqyIY27Vsyb5J05KREMa1sQoS3r2W1Vxkcrms6Tph6q3usFARBJJUVjPBgZ6Je49u5ELCog0r1qy7YFMI4RxMfZRZFOxOa/bn28oi8rK7K6hrITw48uVT37MQBn9vOcS2l9K0OE9W0atHsqWtIwxlRk1ZdHXrxC+ueUcydrdI6QAAAABJRU5ErkJggg==";
  27. const BUTTON_CLOSE_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4wodFQUaLj84ywAAANxJREFUOMuN08tKAzEUgOGPSrU6fTL3PpuuperCSr22OFX0hQSXYkfHzRkIcW4Hskg4/5/kJAf2cIZ77BuOORa4aBZOUcfYDEjmuIncXSO5SwQ11h2SIoFrVHgRyU8Dkjb4GdMmoU9SYJnBZQqnknUmKXE1Bu6T1EnRtn1wKikz+AfvbfCkRTDFR7ZW47Mj/99TLbOdq2T+iNlYeBfHvs2u89AmKXCdVbsp2EHsnEsO0+/ZBTcx65OcD8Bdkl+sJtGNVRTsDcdx/zy+cBL/BL5DBC7xOrKdj6L1V/AHRf5yO+i79cQAAAAASUVORK5CYII=";
  28. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  29. const SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME = "delegatesfocus";
  30. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  31. const NOTE_TAGNAME = "single-file-note";
  32. const NOTE_CLASS = "note";
  33. const NOTE_MASK_CLASS = "note-mask";
  34. const NOTE_HIDDEN_CLASS = "note-hidden";
  35. const NOTE_ANCHORED_CLASS = "note-anchored";
  36. const NOTE_SELECTED_CLASS = "note-selected";
  37. const NOTE_MOVING_CLASS = "note-moving";
  38. const NOTE_MASK_MOVING_CLASS = "note-mask-moving";
  39. const PAGE_MASK_CLASS = "page-mask";
  40. const MASK_CLASS = "single-file-mask";
  41. const PAGE_MASK_CONTAINER_CLASS = "single-file-page-mask";
  42. const HIGHLIGHT_CLASS = "single-file-highlight";
  43. const HIGHLIGHT_HIDDEN_CLASS = "single-file-highlight-hidden";
  44. const PAGE_MASK_ACTIVE_CLASS = "page-mask-active";
  45. const NOTE_INITIAL_POSITION_X = 20;
  46. const NOTE_INITIAL_POSITION_Y = 20;
  47. const NOTE_INITIAL_WIDTH = 150;
  48. const NOTE_INITIAL_HEIGHT = 150;
  49. const NOTE_HEADER_HEIGHT = 25;
  50. const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-single-file-disabled-noscript";
  51. let NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET;
  52. let selectedNote, anchorElement, maskNoteElement, maskPageElement, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, highlightColor, collapseNoteTimeout;
  53. window.onmessage = async event => {
  54. const message = JSON.parse(event.data);
  55. if (message.method == "init") {
  56. await initConstants();
  57. const contentDocument = (new DOMParser()).parseFromString(message.content, "text/html");
  58. if (contentDocument.doctype) {
  59. if (document.doctype) {
  60. document.replaceChild(contentDocument.doctype, document.doctype);
  61. } else {
  62. document.insertBefore(contentDocument.doctype, document.documentElement);
  63. }
  64. } else {
  65. document.doctype.remove();
  66. }
  67. contentDocument.querySelectorAll("noscript").forEach(element => {
  68. element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.innerHTML);
  69. element.textContent = "";
  70. });
  71. document.replaceChild(contentDocument.documentElement, document.documentElement);
  72. deserializeShadowRoots(document);
  73. window.parent.postMessage(JSON.stringify({ "method": "setMetadata", title: document.title, icon: document.querySelector("link[rel*=icon]").href }), "*");
  74. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => attachNoteListeners(containerElement, true));
  75. document.documentElement.appendChild(getStyleElement(HIGHLIGHTS_WEB_STYLESHEET));
  76. maskPageElement = getMaskElement(PAGE_MASK_CLASS, PAGE_MASK_CONTAINER_CLASS);
  77. maskNoteElement = getMaskElement(NOTE_MASK_CLASS);
  78. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  79. window.onclick = event => event.preventDefault();
  80. }
  81. if (message.method == "addNote") {
  82. addNote(message);
  83. }
  84. if (message.method == "displayNotes") {
  85. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.remove(NOTE_HIDDEN_CLASS));
  86. }
  87. if (message.method == "hideNotes") {
  88. document.querySelectorAll(NOTE_TAGNAME).forEach(noteElement => noteElement.shadowRoot.querySelector("." + NOTE_CLASS).classList.add(NOTE_HIDDEN_CLASS));
  89. }
  90. if (message.method == "enableHighlight") {
  91. highlightColor = message.color;
  92. highlightSelectionMode = true;
  93. }
  94. if (message.method == "disableHighlight") {
  95. highlightSelectionMode = false;
  96. }
  97. if (message.method == "displayHighlights") {
  98. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  99. }
  100. if (message.method == "hideHighlights") {
  101. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.add(HIGHLIGHT_HIDDEN_CLASS));
  102. }
  103. if (message.method == "enableRemoveHighlights") {
  104. removeHighlightMode = true;
  105. }
  106. if (message.method == "disableRemoveHighlights") {
  107. removeHighlightMode = false;
  108. }
  109. if (message.method == "enableEditPage") {
  110. document.body.contentEditable = true;
  111. }
  112. if (message.method == "disableEditPage") {
  113. document.body.contentEditable = false;
  114. }
  115. if (message.method == "getContent") {
  116. serializeShadowRoots(document);
  117. const doc = document.cloneNode(true);
  118. deserializeShadowRoots(document);
  119. doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
  120. element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  121. element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
  122. });
  123. doc.querySelectorAll("." + MASK_CLASS).forEach(maskElement => maskElement.remove());
  124. doc.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(noteElement => noteElement.classList.remove(HIGHLIGHT_HIDDEN_CLASS));
  125. doc.querySelectorAll(`template[${SHADOW_MODE_ATTRIBUTE_NAME}]`).forEach(templateElement => {
  126. const noteElement = templateElement.querySelector("." + NOTE_CLASS);
  127. if (noteElement) {
  128. noteElement.classList.remove(NOTE_HIDDEN_CLASS);
  129. }
  130. const mainElement = templateElement.querySelector("textarea");
  131. if (mainElement) {
  132. mainElement.textContent = mainElement.value;
  133. }
  134. });
  135. delete doc.body.contentEditable;
  136. const scriptElement = doc.createElement("script");
  137. scriptElement.setAttribute(SCRIPT_TEMPLATE_SHADOW_ROOT, "");
  138. scriptElement.textContent = getEmbedScript();
  139. doc.body.appendChild(scriptElement);
  140. window.parent.postMessage(JSON.stringify({ "method": "setContent", content: singlefile.lib.modules.serializer.process(doc, message.compressHTML) }), "*");
  141. }
  142. };
  143. window.onresize = reflowNotes;
  144. async function initConstants() {
  145. [NOTES_WEB_STYLESHEET, MASK_WEB_STYLESHEET, HIGHLIGHTS_WEB_STYLESHEET] = await Promise.all([
  146. minifyText(await ((await fetch("editor-note-web.css")).text())),
  147. minifyText(await ((await fetch("editor-mask-web.css")).text())),
  148. minifyText(await ((await fetch("editor-frame-web.css")).text()))
  149. ]);
  150. }
  151. function addNote({ color }) {
  152. const containerElement = document.createElement(NOTE_TAGNAME);
  153. const noteElement = document.createElement("div");
  154. const headerElement = document.createElement("header");
  155. const mainElement = document.createElement("textarea");
  156. const resizeElement = document.createElement("div");
  157. const removeNoteElement = document.createElement("img");
  158. const anchorIconElement = document.createElement("img");
  159. const noteShadow = containerElement.attachShadow({ mode: "open" });
  160. headerElement.appendChild(anchorIconElement);
  161. headerElement.appendChild(removeNoteElement);
  162. noteElement.appendChild(headerElement);
  163. noteElement.appendChild(mainElement);
  164. noteElement.appendChild(resizeElement);
  165. noteShadow.appendChild(getStyleElement(NOTES_WEB_STYLESHEET));
  166. noteShadow.appendChild(noteElement);
  167. const notesElements = Array.from(document.querySelectorAll(NOTE_TAGNAME));
  168. const noteId = Math.max.call(Math, 0, ...notesElements.map(noteElement => Number(noteElement.dataset.noteId))) + 1;
  169. noteElement.classList.add(NOTE_CLASS);
  170. noteElement.classList.add(NOTE_ANCHORED_CLASS);
  171. noteElement.classList.add(color);
  172. const boundingRectDocument = document.documentElement.getBoundingClientRect();
  173. let positionX = NOTE_INITIAL_WIDTH + NOTE_INITIAL_POSITION_X - 1 - boundingRectDocument.x;
  174. let positionY = NOTE_INITIAL_HEIGHT + NOTE_INITIAL_POSITION_Y - 1 - boundingRectDocument.y;
  175. while (Array.from(document.elementsFromPoint(positionX - window.scrollX, positionY - window.scrollY)).find(element => element.tagName.toLowerCase() == NOTE_TAGNAME)) {
  176. positionX += NOTE_INITIAL_POSITION_X;
  177. positionY += NOTE_INITIAL_POSITION_Y;
  178. }
  179. noteElement.style.setProperty("left", (positionX - NOTE_INITIAL_WIDTH - 1) + "px");
  180. noteElement.style.setProperty("top", (positionY - NOTE_INITIAL_HEIGHT - 1) + "px");
  181. resizeElement.className = "note-resize";
  182. resizeElement.ondragstart = event => event.preventDefault();
  183. removeNoteElement.className = "note-remove";
  184. removeNoteElement.src = BUTTON_CLOSE_URL;
  185. removeNoteElement.ondragstart = event => event.preventDefault();
  186. anchorIconElement.className = "note-anchor";
  187. anchorIconElement.src = BUTTON_ANCHOR_URL;
  188. anchorIconElement.ondragstart = event => event.preventDefault();
  189. containerElement.dataset.noteId = noteId;
  190. addNoteRef(document.documentElement, noteId);
  191. attachNoteListeners(containerElement, true);
  192. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  193. noteElement.classList.add(NOTE_SELECTED_CLASS);
  194. selectedNote = noteElement;
  195. }
  196. function attachNoteListeners(containerElement, editable = false) {
  197. const SELECT_PX_THRESHOLD = 4;
  198. const COLLAPSING_NOTE_DELAY = 750;
  199. const noteShadow = containerElement.shadowRoot;
  200. const noteElement = noteShadow.childNodes[1];
  201. const headerElement = noteShadow.querySelector("header");
  202. const mainElement = noteShadow.querySelector("textarea");
  203. const noteId = containerElement.dataset.noteId;
  204. const resizeElement = noteShadow.querySelector(".note-resize");
  205. const anchorIconElement = noteShadow.querySelector(".note-anchor");
  206. const removeNoteElement = noteShadow.querySelector(".note-remove");
  207. mainElement.readOnly = !editable;
  208. if (!editable) {
  209. anchorIconElement.style.setProperty("display", "none", "important");
  210. } else {
  211. anchorIconElement.style.removeProperty("display");
  212. }
  213. headerElement.ontouchstart = headerElement.onmousedown = event => {
  214. if (event.target == headerElement) {
  215. collapseNoteTimeout = setTimeout(() => noteElement.classList.toggle("note-collapsed"), COLLAPSING_NOTE_DELAY);
  216. event.preventDefault();
  217. const position = getPosition(event);
  218. const clientX = position.clientX;
  219. const clientY = position.clientY;
  220. const boundingRect = noteElement.getBoundingClientRect();
  221. const deltaX = clientX - boundingRect.left;
  222. const deltaY = clientY - boundingRect.top;
  223. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  224. document.documentElement.style.setProperty("user-select", "none", "important");
  225. anchorElement = getAnchorElement(containerElement);
  226. displayMaskNote();
  227. selectNote(noteElement);
  228. moveNote(event, deltaX, deltaY);
  229. movingNoteMode = { event, deltaX, deltaY };
  230. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  231. clearTimeout(collapseNoteTimeout);
  232. if (!movingNoteMode) {
  233. movingNoteMode = { deltaX, deltaY };
  234. }
  235. movingNoteMode.event = event;
  236. moveNote(event, deltaX, deltaY);
  237. };
  238. }
  239. };
  240. resizeElement.ontouchstart = resizeElement.onmousedown = event => {
  241. event.preventDefault();
  242. resizingNoteMode = true;
  243. selectNote(noteElement);
  244. maskPageElement.classList.add(PAGE_MASK_ACTIVE_CLASS);
  245. document.documentElement.style.setProperty("user-select", "none", "important");
  246. document.documentElement.ontouchmove = document.documentElement.onmousemove = event => {
  247. event.preventDefault();
  248. const { clientX, clientY } = getPosition(event);
  249. const boundingRectNote = noteElement.getBoundingClientRect();
  250. noteElement.style.width = clientX - boundingRectNote.left + "px";
  251. noteElement.style.height = clientY - boundingRectNote.top + "px";
  252. };
  253. };
  254. anchorIconElement.ontouchend = anchorIconElement.onclick = event => {
  255. event.preventDefault();
  256. noteElement.classList.toggle(NOTE_ANCHORED_CLASS);
  257. if (!noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  258. deleteNoteRef(containerElement, noteId);
  259. addNoteRef(document.documentElement, noteId);
  260. }
  261. };
  262. removeNoteElement.ontouchend = removeNoteElement.onclick = event => {
  263. event.preventDefault();
  264. deleteNoteRef(containerElement, noteId);
  265. containerElement.remove();
  266. };
  267. noteElement.onmousedown = () => {
  268. selectNote(noteElement);
  269. };
  270. function moveNote(event, deltaX, deltaY) {
  271. event.preventDefault();
  272. const { clientX, clientY } = getPosition(event);
  273. noteElement.classList.add(NOTE_MOVING_CLASS);
  274. if (editable) {
  275. if (noteElement.classList.contains(NOTE_ANCHORED_CLASS)) {
  276. deleteNoteRef(containerElement, noteId);
  277. anchorElement = getTarget(clientX, clientY) || document.documentElement;
  278. addNoteRef(anchorElement, noteId);
  279. } else {
  280. anchorElement = document.documentElement;
  281. }
  282. }
  283. document.documentElement.insertBefore(containerElement, maskPageElement.getRootNode().host);
  284. noteElement.style.setProperty("left", (clientX - deltaX) + "px");
  285. noteElement.style.setProperty("top", (clientY - deltaY) + "px");
  286. noteElement.style.setProperty("position", "fixed");
  287. displayMaskNote();
  288. }
  289. function displayMaskNote() {
  290. if (anchorElement == document.documentElement || anchorElement == document.documentElement) {
  291. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  292. } else {
  293. const boundingRectAnchor = anchorElement.getBoundingClientRect();
  294. maskNoteElement.classList.add(NOTE_MASK_MOVING_CLASS);
  295. maskNoteElement.style.setProperty("top", boundingRectAnchor.y + "px");
  296. maskNoteElement.style.setProperty("left", boundingRectAnchor.x + "px");
  297. maskNoteElement.style.setProperty("width", boundingRectAnchor.width + "px");
  298. maskNoteElement.style.setProperty("height", boundingRectAnchor.height + "px");
  299. }
  300. }
  301. function selectNote(noteElement) {
  302. if (selectedNote) {
  303. selectedNote.classList.remove(NOTE_SELECTED_CLASS);
  304. }
  305. noteElement.classList.add(NOTE_SELECTED_CLASS);
  306. selectedNote = noteElement;
  307. }
  308. function getTarget(clientX, clientY) {
  309. const targets = Array.from(document.elementsFromPoint(clientX, clientY)).filter(element => element.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS));
  310. if (!targets.includes(document.documentElement)) {
  311. targets.push(document.documentElement);
  312. }
  313. let newTarget, target = targets[0], boundingRect = target.getBoundingClientRect();
  314. newTarget = determineTargetElement("floor", target, clientX - boundingRect.left, getMatchedParents(target, "left"));
  315. if (newTarget == target) {
  316. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - clientX, getMatchedParents(target, "right"));
  317. }
  318. if (newTarget == target) {
  319. newTarget = determineTargetElement("floor", target, clientY - boundingRect.top, getMatchedParents(target, "top"));
  320. }
  321. if (newTarget == target) {
  322. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - clientY, getMatchedParents(target, "bottom"));
  323. }
  324. target = newTarget;
  325. while (boundingRect = target && target.getBoundingClientRect(), boundingRect && boundingRect.width <= SELECT_PX_THRESHOLD && boundingRect.height <= SELECT_PX_THRESHOLD) {
  326. target = target.parentElement;
  327. }
  328. return target;
  329. }
  330. function getMatchedParents(target, property) {
  331. let element = target, matchedParent, parents = [];
  332. do {
  333. const boundingRect = element.getBoundingClientRect();
  334. if (element.parentElement && !element.parentElement.tagName.toLowerCase() != NOTE_TAGNAME && !element.classList.contains(MASK_CLASS)) {
  335. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  336. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  337. if (matchedParent) {
  338. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  339. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  340. parents.push(element.parentElement);
  341. }
  342. element = element.parentElement;
  343. }
  344. } else {
  345. matchedParent = false;
  346. }
  347. } while (matchedParent && element);
  348. return parents;
  349. }
  350. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  351. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  352. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  353. }
  354. return target;
  355. }
  356. }
  357. function onMouseUp(event) {
  358. if (highlightSelectionMode) {
  359. highlightSelection();
  360. }
  361. if (removeHighlightMode) {
  362. let element = event.target, done;
  363. while (element && !done) {
  364. if (element.classList.contains(HIGHLIGHT_CLASS)) {
  365. document.querySelectorAll("." + HIGHLIGHT_CLASS + "[data-singlefile-highlight-id=" + JSON.stringify(element.dataset.singlefileHighlightId) + "]").forEach(highlightedElement => {
  366. resetHighlightedElement(highlightedElement);
  367. });
  368. done = true;
  369. }
  370. element = element.parentElement;
  371. }
  372. }
  373. if (resizingNoteMode) {
  374. resizingNoteMode = false;
  375. document.documentElement.style.removeProperty("user-select");
  376. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  377. document.documentElement.ontouchmove = document.documentElement.onmousemove = null;
  378. }
  379. if (movingNoteMode) {
  380. anchorNote(movingNoteMode.event || event, selectedNote, movingNoteMode.deltaX, movingNoteMode.deltaY);
  381. movingNoteMode = null;
  382. document.documentElement.ontouchmove = document.documentElement.onmousemove = null;
  383. }
  384. if (collapseNoteTimeout) {
  385. clearTimeout(collapseNoteTimeout);
  386. collapseNoteTimeout = null;
  387. }
  388. }
  389. function anchorNote(event, noteElement, deltaX, deltaY) {
  390. event.preventDefault();
  391. const { clientX, clientY } = getPosition(event);
  392. document.documentElement.style.removeProperty("user-select");
  393. noteElement.classList.remove(NOTE_MOVING_CLASS);
  394. maskNoteElement.classList.remove(NOTE_MASK_MOVING_CLASS);
  395. maskPageElement.classList.remove(PAGE_MASK_ACTIVE_CLASS);
  396. const headerElement = noteElement.querySelector("header");
  397. headerElement.ontouchmove = document.documentElement.onmousemove = null;
  398. let currentElement = anchorElement;
  399. let positionedElement;
  400. while (currentElement.parentElement && !positionedElement) {
  401. if (!FORBIDDEN_TAG_NAMES.includes(currentElement.tagName.toLowerCase())) {
  402. const currentElementStyle = getComputedStyle(currentElement);
  403. if (currentElementStyle.position != "static") {
  404. positionedElement = currentElement;
  405. }
  406. }
  407. currentElement = currentElement.parentElement;
  408. }
  409. if (!positionedElement) {
  410. positionedElement = document.documentElement;
  411. }
  412. const containerElement = noteElement.getRootNode().host;
  413. if (positionedElement == document.documentElement) {
  414. const firstMaskElement = document.querySelector("." + MASK_CLASS);
  415. document.documentElement.insertBefore(containerElement, firstMaskElement);
  416. } else {
  417. positionedElement.appendChild(containerElement);
  418. }
  419. const boundingRectPositionedElement = positionedElement.getBoundingClientRect();
  420. const stylePositionedElement = window.getComputedStyle(positionedElement);
  421. const borderX = parseInt(stylePositionedElement.getPropertyValue("border-left-width"));
  422. const borderY = parseInt(stylePositionedElement.getPropertyValue("border-top-width"));
  423. noteElement.style.setProperty("position", "absolute");
  424. noteElement.style.setProperty("left", (clientX - boundingRectPositionedElement.x - deltaX - borderX) + "px");
  425. noteElement.style.setProperty("top", (clientY - boundingRectPositionedElement.y - deltaY - borderY) + "px");
  426. }
  427. function getPosition(event) {
  428. if (event.touches && event.touches.length) {
  429. const touch = event.touches[0];
  430. return touch;
  431. } else {
  432. return event;
  433. }
  434. }
  435. function highlightSelection() {
  436. let highlightId = 0;
  437. document.querySelectorAll("." + HIGHLIGHT_CLASS).forEach(highlightedElement => highlightId = Math.max(highlightId, highlightedElement.dataset.singlefileHighlightId));
  438. highlightId++;
  439. const selection = window.getSelection();
  440. const highlightedNodes = new Set();
  441. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  442. const range = selection.getRangeAt(indexRange);
  443. if (!range.collapsed) {
  444. if (range.commonAncestorContainer.nodeType == range.commonAncestorContainer.TEXT_NODE) {
  445. let contentText = range.startContainer.splitText(range.startOffset);
  446. contentText = contentText.splitText(range.endOffset);
  447. addHighLightedNode(contentText.previousSibling);
  448. } else {
  449. const treeWalker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
  450. let highlightNodes;
  451. while (treeWalker.nextNode()) {
  452. if (highlightNodes && !treeWalker.currentNode.contains(range.endContainer)) {
  453. addHighLightedNode(treeWalker.currentNode);
  454. }
  455. if (treeWalker.currentNode == range.startContainer) {
  456. if (range.startContainer.nodeType == range.startContainer.TEXT_NODE) {
  457. const contentText = range.startContainer.splitText(range.startOffset);
  458. treeWalker.nextNode();
  459. addHighLightedNode(contentText);
  460. } else {
  461. addHighLightedNode(range.startContainer.childNodes[range.startOffset]);
  462. }
  463. highlightNodes = true;
  464. }
  465. if (treeWalker.currentNode == range.endContainer) {
  466. if (range.endContainer.nodeType == range.endContainer.TEXT_NODE) {
  467. const contentText = range.endContainer.splitText(range.endOffset);
  468. treeWalker.nextNode();
  469. addHighLightedNode(contentText.previousSibling);
  470. } else {
  471. addHighLightedNode(range.endContainer.childNodes[range.endOffset]);
  472. }
  473. highlightNodes = false;
  474. }
  475. }
  476. range.collapse();
  477. }
  478. }
  479. }
  480. highlightedNodes.forEach(node => highlightNode(node));
  481. function addHighLightedNode(node) {
  482. if (node && node.textContent.trim()) {
  483. if (node.nodeType == node.TEXT_NODE && node.parentElement.childNodes.length == 1 && node.parentElement.classList.contains(HIGHLIGHT_CLASS)) {
  484. highlightedNodes.add(node.parentElement);
  485. } else {
  486. highlightedNodes.add(node);
  487. }
  488. }
  489. }
  490. function highlightNode(node) {
  491. if (node.nodeType == node.ELEMENT_NODE) {
  492. resetHighlightedElement(node);
  493. node.classList.add(HIGHLIGHT_CLASS);
  494. node.classList.add(highlightColor);
  495. node.dataset.singlefileHighlightId = highlightId;
  496. } else if (node.parentElement) {
  497. highlightTextNode(node);
  498. }
  499. }
  500. function highlightTextNode(node) {
  501. const spanElement = document.createElement("span");
  502. spanElement.classList.add(HIGHLIGHT_CLASS);
  503. spanElement.classList.add(highlightColor);
  504. spanElement.textContent = node.textContent;
  505. spanElement.dataset.singlefileHighlightId = highlightId;
  506. node.parentNode.replaceChild(spanElement, node);
  507. return spanElement;
  508. }
  509. }
  510. function reflowNotes() {
  511. document.querySelectorAll(NOTE_TAGNAME).forEach(containerElement => {
  512. const noteElement = containerElement.shadowRoot.querySelector("." + NOTE_CLASS);
  513. const noteBoundingRect = noteElement.getBoundingClientRect();
  514. const anchorElement = getAnchorElement(containerElement);
  515. const anchorBoundingRect = anchorElement.getBoundingClientRect();
  516. const maxX = anchorBoundingRect.x + Math.max(0, anchorBoundingRect.width - noteBoundingRect.width);
  517. const minX = anchorBoundingRect.x;
  518. const maxY = anchorBoundingRect.y + Math.max(0, anchorBoundingRect.height - NOTE_HEADER_HEIGHT);
  519. const minY = anchorBoundingRect.y;
  520. let left = parseInt(noteElement.style.getPropertyValue("left"));
  521. let top = parseInt(noteElement.style.getPropertyValue("top"));
  522. if (noteBoundingRect.x > maxX) {
  523. left -= noteBoundingRect.x - maxX;
  524. }
  525. if (noteBoundingRect.x < minX) {
  526. left += minX - noteBoundingRect.x;
  527. }
  528. if (noteBoundingRect.y > maxY) {
  529. top -= noteBoundingRect.y - maxY;
  530. }
  531. if (noteBoundingRect.y < minY) {
  532. top += minY - noteBoundingRect.y;
  533. }
  534. noteElement.style.setProperty("position", "absolute");
  535. noteElement.style.setProperty("left", left + "px");
  536. noteElement.style.setProperty("top", top + "px");
  537. });
  538. }
  539. function resetHighlightedElement(element) {
  540. element.classList.remove(HIGHLIGHT_CLASS);
  541. element.classList.remove("single-file-highlight-yellow");
  542. element.classList.remove("single-file-highlight-pink");
  543. element.classList.remove("single-file-highlight-blue");
  544. element.classList.remove("single-file-highlight-green");
  545. delete element.dataset.singlefileHighlightId;
  546. }
  547. function serializeShadowRoots(node) {
  548. node.querySelectorAll("*").forEach(element => {
  549. if (element.shadowRoot) {
  550. serializeShadowRoots(element.shadowRoot);
  551. const templateElement = document.createElement("template");
  552. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, "open");
  553. templateElement.appendChild(element.shadowRoot);
  554. element.appendChild(templateElement);
  555. }
  556. });
  557. }
  558. function deserializeShadowRoots(node) {
  559. node.querySelectorAll(`template[${SHADOW_MODE_ATTRIBUTE_NAME}]`).forEach(element => {
  560. let shadowRoot = element.parentElement.shadowRoot;
  561. if (shadowRoot) {
  562. Array.from(element.childNodes).forEach(node => shadowRoot.appendChild(node));
  563. element.remove();
  564. } else {
  565. shadowRoot = element.parentElement.attachShadow({ mode: "open" });
  566. const contentDocument = (new DOMParser()).parseFromString(element.innerHTML, "text/html");
  567. Array.from(contentDocument.head.childNodes).forEach(node => shadowRoot.appendChild(node));
  568. Array.from(contentDocument.body.childNodes).forEach(node => shadowRoot.appendChild(node));
  569. }
  570. deserializeShadowRoots(shadowRoot);
  571. });
  572. }
  573. function getMaskElement(className, containerClassName) {
  574. let maskElement = document.documentElement.querySelector("." + className);
  575. if (!maskElement) {
  576. maskElement = document.createElement("div");
  577. const maskContainerElement = document.createElement("div");
  578. if (containerClassName) {
  579. maskContainerElement.classList.add(containerClassName);
  580. }
  581. maskContainerElement.classList.add(MASK_CLASS);
  582. const firstNote = document.querySelector(NOTE_TAGNAME);
  583. if (firstNote && firstNote.parentElement == document.documentElement) {
  584. document.documentElement.insertBefore(maskContainerElement, firstNote);
  585. } else {
  586. document.documentElement.appendChild(maskContainerElement);
  587. }
  588. maskElement.classList.add(className);
  589. const maskShadow = maskContainerElement.attachShadow({ mode: "open" });
  590. maskShadow.appendChild(getStyleElement(MASK_WEB_STYLESHEET));
  591. maskShadow.appendChild(maskElement);
  592. return maskElement;
  593. }
  594. }
  595. function getEmbedScript() {
  596. return minifyText(`(() => {
  597. document.currentScript.remove();
  598. const processNode = node => {
  599. node.querySelectorAll("template[${SHADOW_MODE_ATTRIBUTE_NAME}]").forEach(element=>{
  600. if (!element.parentElement.shadowRoot) {
  601. const shadowRoot = element.parentElement.attachShadow({mode:element.getAttribute("${SHADOW_MODE_ATTRIBUTE_NAME}"),delegatesFocus:Boolean(element.getAttribute("${SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME}"))});
  602. shadowRoot.innerHTML = element.innerHTML;
  603. element.remove();
  604. processNode(shadowRoot);
  605. }
  606. })
  607. };
  608. const FORBIDDEN_TAG_NAMES = ${JSON.stringify(FORBIDDEN_TAG_NAMES)};
  609. const NOTE_TAGNAME = ${JSON.stringify(NOTE_TAGNAME)};
  610. const NOTE_CLASS = ${JSON.stringify(NOTE_CLASS)};
  611. const NOTE_ANCHORED_CLASS = ${JSON.stringify(NOTE_ANCHORED_CLASS)};
  612. const NOTE_SELECTED_CLASS = ${JSON.stringify(NOTE_SELECTED_CLASS)};
  613. const NOTE_MOVING_CLASS = ${JSON.stringify(NOTE_MOVING_CLASS)};
  614. const NOTE_MASK_MOVING_CLASS = ${JSON.stringify(NOTE_MASK_MOVING_CLASS)};
  615. const MASK_CLASS = ${JSON.stringify(MASK_CLASS)};
  616. const HIGHLIGHT_CLASS = ${JSON.stringify(HIGHLIGHT_CLASS)};
  617. const NOTES_WEB_STYLESHEET = ${JSON.stringify(NOTES_WEB_STYLESHEET)};
  618. const MASK_WEB_STYLESHEET = ${JSON.stringify(MASK_WEB_STYLESHEET)};
  619. const NOTE_HEADER_HEIGHT = ${JSON.stringify(NOTE_HEADER_HEIGHT)};
  620. const PAGE_MASK_ACTIVE_CLASS = ${JSON.stringify(PAGE_MASK_ACTIVE_CLASS)};
  621. const reflowNotes = ${minifyText(reflowNotes.toString())};
  622. const addNoteRef = ${minifyText(addNoteRef.toString())};
  623. const deleteNoteRef = ${minifyText(deleteNoteRef.toString())};
  624. const getNoteRefs = ${minifyText(getNoteRefs.toString())};
  625. const setNoteRefs = ${minifyText(setNoteRefs.toString())};
  626. const getAnchorElement = ${minifyText(getAnchorElement.toString())};
  627. const getMaskElement = ${minifyText(getMaskElement.toString())};
  628. const getStyleElement = ${minifyText(getStyleElement.toString())};
  629. const attachNoteListeners = ${minifyText(attachNoteListeners.toString())};
  630. const anchorNote = ${minifyText(anchorNote.toString())};
  631. const getPosition = ${minifyText(getPosition.toString())};
  632. const onMouseUp = ${minifyText(onMouseUp.toString())};
  633. const maskNoteElement = getMaskElement(${JSON.stringify(NOTE_MASK_CLASS)});
  634. const maskPageElement = getMaskElement(${JSON.stringify(PAGE_MASK_CLASS)}, ${JSON.stringify(PAGE_MASK_CONTAINER_CLASS)});
  635. let selectedNote, highlightSelectionMode, removeHighlightMode, resizingNoteMode, movingNoteMode, collapseNoteTimeout;
  636. window.onresize = reflowNotes;
  637. document.documentElement.onmouseup = document.documentElement.ontouchend = onMouseUp;
  638. window.addEventListener("DOMContentLoaded", () => {
  639. processNode(document);
  640. reflowNotes();
  641. document.querySelectorAll(${JSON.stringify(NOTE_TAGNAME)}).forEach(noteElement => attachNoteListeners(noteElement));
  642. });
  643. })()`);
  644. }
  645. function getStyleElement(stylesheet) {
  646. const linkElement = document.createElement("style");
  647. linkElement.textContent = stylesheet;
  648. return linkElement;
  649. }
  650. function getAnchorElement(containerElement) {
  651. return document.querySelector("[data-single-file-note-refs^=" + JSON.stringify(containerElement.dataset.noteId) + "], [data-single-file-note-refs$=" + JSON.stringify(containerElement.dataset.noteId) + "], [data-single-file-note-refs*=" + JSON.stringify("," + containerElement.dataset.noteId + ",") + "]");
  652. }
  653. function addNoteRef(anchorElement, noteId) {
  654. const noteRefs = getNoteRefs(anchorElement);
  655. noteRefs.push(noteId);
  656. setNoteRefs(anchorElement, noteRefs);
  657. }
  658. function deleteNoteRef(containerElement, noteId) {
  659. const anchorElement = getAnchorElement(containerElement);
  660. const noteRefs = getNoteRefs(anchorElement).filter(noteRefs => noteRefs != noteId);
  661. if (noteRefs.length) {
  662. setNoteRefs(anchorElement, noteRefs);
  663. } else {
  664. delete anchorElement.dataset.singleFileNoteRefs;
  665. }
  666. }
  667. function getNoteRefs(anchorElement) {
  668. return JSON.parse("[" + (anchorElement.dataset.singleFileNoteRefs || "") + "]");
  669. }
  670. function setNoteRefs(anchorElement, noteRefs) {
  671. anchorElement.dataset.singleFileNoteRefs = noteRefs.toString();
  672. }
  673. function minifyText(text) {
  674. return text.replace(/[\n\t\s]+/g, " ");
  675. }
  676. })();