content-ui-editor-web.js 29 KB

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