content-ui-editor-web.js 34 KB

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