content-ui-editor-web.js 33 KB

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