content-ui-editor-web.js 29 KB

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