content-ui-editor-web.js 32 KB

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