content-ui-editor-web.js 34 KB

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