content-ui-editor-web.js 29 KB

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