content-ui-editor-web.js 29 KB

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