content-ui.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 SingleFileBrowser, browser, document, prompt, getComputedStyle, addEventListener, removeEventListener, requestAnimationFrame, setTimeout, getSelection, Node */
  24. this.singlefile.ui = this.singlefile.ui || (() => {
  25. const SingleFile = SingleFileBrowser.getClass();
  26. const MASK_TAGNAME = "singlefile-mask";
  27. const PROGRESS_BAR_TAGNAME = "singlefile-progress-bar";
  28. const PROGRESS_CURSOR_TAGNAME = "singlefile-progress-cursor";
  29. const SELECTION_ZONE_TAGNAME = "single-file-selection-zone";
  30. const LOGS_WINDOW_TAGNAME = "singlefile-logs-window";
  31. const LOGS_LINE_TAGNAME = "singlefile-logs-line";
  32. const LOGS_LINE_ELEMENT_TAGNAME = "singlefile-logs-element";
  33. const SINGLE_FILE_UI_ELEMENT_CLASS = "single-file-ui-element";
  34. const SELECT_PX_THRESHOLD = 8;
  35. const LOG_PANEL_DEFERRED_IMAGES_MESSAGE = browser.i18n.getMessage("logPanelDeferredImages");
  36. const LOG_PANEL_FRAME_CONTENTS_MESSAGE = browser.i18n.getMessage("logPanelFrameContents");
  37. const LOG_PANEL_STEP_MESSAGE = browser.i18n.getMessage("logPanelStep");
  38. const LOG_PANEL_WIDTH = browser.i18n.getMessage("logPanelWidth");
  39. let selectedAreaElement;
  40. let logsWindowElement = createLogsWindowElement();
  41. const allProperties = new Set();
  42. Array.from(getComputedStyle(document.body)).forEach(property => allProperties.add(property));
  43. return {
  44. markSelection,
  45. unmarkSelection,
  46. prompt(message, defaultValue) {
  47. return prompt(message, defaultValue);
  48. },
  49. onStartPage() {
  50. let maskElement = document.querySelector(MASK_TAGNAME);
  51. if (!maskElement) {
  52. const maskElement = createMaskElement();
  53. createProgressBarElement(maskElement);
  54. document.body.appendChild(logsWindowElement);
  55. setLogsWindowStyle();
  56. maskElement.offsetWidth;
  57. maskElement.style.setProperty("background-color", "black", "important");
  58. maskElement.style.setProperty("opacity", .3, "important");
  59. document.body.offsetWidth;
  60. }
  61. },
  62. onEndPage() {
  63. const maskElement = document.querySelector(MASK_TAGNAME);
  64. logsWindowElement.remove();
  65. clearLogs();
  66. if (maskElement) {
  67. maskElement.remove();
  68. }
  69. },
  70. onLoadResource(index, maxIndex) {
  71. const progressBarElement = document.querySelector(PROGRESS_BAR_TAGNAME);
  72. if (progressBarElement && maxIndex) {
  73. const width = Math.floor((index / maxIndex) * 100) + "%";
  74. if (progressBarElement.style.getPropertyValue("width") != width) {
  75. requestAnimationFrame(() => progressBarElement.style.setProperty("width", Math.floor((index / maxIndex) * 100) + "%", "important"));
  76. }
  77. }
  78. },
  79. onLoadingDeferResources() {
  80. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "…");
  81. },
  82. onLoadDeferResources() {
  83. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "✓");
  84. },
  85. onLoadingFrames() {
  86. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "…");
  87. },
  88. onLoadFrames() {
  89. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "✓");
  90. },
  91. onStartStage(step) {
  92. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "…");
  93. },
  94. onEndStage(step) {
  95. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "✓");
  96. },
  97. onPageLoading() { },
  98. onLoadPage() { },
  99. onStartStageTask() { },
  100. onEndStageTask() { }
  101. };
  102. async function markSelection() {
  103. let selectionFound = markSelectedContent();
  104. if (selectionFound) {
  105. return selectionFound;
  106. } else {
  107. selectionFound = await selectArea();
  108. if (selectionFound) {
  109. return markSelectedContent();
  110. }
  111. }
  112. }
  113. function markSelectedContent() {
  114. const selection = getSelection();
  115. let selectionFound;
  116. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  117. let range = selection.getRangeAt(indexRange);
  118. if (range && range.commonAncestorContainer) {
  119. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  120. let rangeSelectionFound = false;
  121. let finished = false;
  122. while (!finished) {
  123. if (rangeSelectionFound || treeWalker.currentNode == range.startContainer || treeWalker.currentNode == range.endContainer) {
  124. rangeSelectionFound = true;
  125. if (range.startContainer != range.endContainer || range.startOffset != range.endOffset) {
  126. selectionFound = true;
  127. markSelectedNode(treeWalker.currentNode);
  128. }
  129. }
  130. if (selectionFound && treeWalker.currentNode == range.startContainer) {
  131. markSelectedParents(treeWalker.currentNode);
  132. }
  133. if (treeWalker.currentNode == range.endContainer) {
  134. finished = true;
  135. } else {
  136. treeWalker.nextNode();
  137. }
  138. }
  139. if (selectionFound && treeWalker.currentNode == range.endContainer && treeWalker.currentNode.querySelectorAll) {
  140. treeWalker.currentNode.querySelectorAll("*").forEach(descendantElement => markSelectedNode(descendantElement));
  141. }
  142. }
  143. }
  144. return selectionFound;
  145. }
  146. function markSelectedNode(node) {
  147. const element = node.nodeType == Node.ELEMENT_NODE ? node : node.parentElement;
  148. element.setAttribute(SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  149. }
  150. function markSelectedParents(node) {
  151. if (node.parentElement) {
  152. markSelectedNode(node);
  153. markSelectedParents(node.parentElement);
  154. }
  155. }
  156. function unmarkSelection() {
  157. document.querySelectorAll("[" + SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME));
  158. }
  159. function selectArea() {
  160. return new Promise(resolve => {
  161. let selectedRanges = [];
  162. addEventListener("mousemove", mousemoveListener, true);
  163. addEventListener("click", clickListener, true);
  164. addEventListener("keyup", keypressListener, true);
  165. document.addEventListener("contextmenu", contextmenuListener, true);
  166. getSelection().removeAllRanges();
  167. function contextmenuListener(event) {
  168. selectedRanges = [];
  169. select();
  170. event.preventDefault();
  171. }
  172. function mousemoveListener(event) {
  173. const targetElement = getTarget(event);
  174. if (targetElement) {
  175. selectedAreaElement = targetElement;
  176. moveAreaSelector(targetElement);
  177. }
  178. }
  179. function clickListener(event) {
  180. event.preventDefault();
  181. event.stopPropagation();
  182. if (event.button == 0) {
  183. select(selectedAreaElement, event.ctrlKey);
  184. } else {
  185. cancel();
  186. }
  187. }
  188. function keypressListener(event) {
  189. if (event.key == "Escape") {
  190. cancel();
  191. }
  192. }
  193. function cancel() {
  194. if (selectedRanges.length) {
  195. getSelection().removeAllRanges();
  196. }
  197. selectedRanges = [];
  198. cleanupAndResolve();
  199. }
  200. function select(selectedElement, multiSelect) {
  201. if (selectedElement) {
  202. if (!multiSelect) {
  203. restoreSelectedRanges();
  204. }
  205. const range = document.createRange();
  206. range.selectNodeContents(selectedElement);
  207. cleanupSelectionRanges();
  208. getSelection().addRange(range);
  209. saveSelectedRanges();
  210. if (!multiSelect) {
  211. cleanupAndResolve();
  212. }
  213. } else {
  214. cleanupAndResolve();
  215. }
  216. }
  217. function cleanupSelectionRanges() {
  218. const selection = getSelection();
  219. for (let indexRange = selection.rangeCount - 1; indexRange >= 0; indexRange--) {
  220. const range = selection.getRangeAt(indexRange);
  221. if (range.startOffset == range.endOffset) {
  222. selection.removeRange(range);
  223. indexRange--;
  224. }
  225. }
  226. }
  227. function cleanupAndResolve() {
  228. getAreaSelector().remove();
  229. removeEventListener("mousemove", mousemoveListener, true);
  230. removeEventListener("click", clickListener, true);
  231. removeEventListener("keyup", keypressListener, true);
  232. selectedAreaElement = null;
  233. resolve(Boolean(selectedRanges.length));
  234. setTimeout(() => document.removeEventListener("contextmenu", contextmenuListener, true), 0);
  235. }
  236. function restoreSelectedRanges() {
  237. getSelection().removeAllRanges();
  238. selectedRanges.forEach(range => getSelection().addRange(range));
  239. }
  240. function saveSelectedRanges() {
  241. selectedRanges = [];
  242. for (let indexRange = 0; indexRange < getSelection().rangeCount; indexRange++) {
  243. const range = getSelection().getRangeAt(indexRange);
  244. selectedRanges.push(range);
  245. }
  246. }
  247. });
  248. }
  249. function getTarget(event) {
  250. let newTarget, target = event.target, boundingRect = target.getBoundingClientRect();
  251. newTarget = determineTargetElement("floor", target, event.clientX - boundingRect.left, getMatchedParents(target, "left"));
  252. if (newTarget == target) {
  253. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - event.clientX, getMatchedParents(target, "right"));
  254. }
  255. if (newTarget == target) {
  256. newTarget = determineTargetElement("floor", target, event.clientY - boundingRect.top, getMatchedParents(target, "top"));
  257. }
  258. if (newTarget == target) {
  259. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - event.clientY, getMatchedParents(target, "bottom"));
  260. }
  261. target = newTarget;
  262. while (target && target.clientWidth <= SELECT_PX_THRESHOLD && target.clientHeight <= SELECT_PX_THRESHOLD) {
  263. target = target.parentElement;
  264. }
  265. return target;
  266. }
  267. function moveAreaSelector(target) {
  268. requestAnimationFrame(() => {
  269. const selectorElement = getAreaSelector();
  270. const boundingRect = target.getBoundingClientRect();
  271. selectorElement.style.setProperty("top", (document.documentElement.scrollTop + boundingRect.top - 10) + "px");
  272. selectorElement.style.setProperty("left", (document.documentElement.scrollLeft + boundingRect.left - 10) + "px");
  273. selectorElement.style.setProperty("width", (boundingRect.width + 20) + "px");
  274. selectorElement.style.setProperty("height", (boundingRect.height + 20) + "px");
  275. });
  276. }
  277. function getAreaSelector() {
  278. let selectorElement = document.querySelector(SELECTION_ZONE_TAGNAME);
  279. if (!selectorElement) {
  280. selectorElement = createElement(SELECTION_ZONE_TAGNAME, document.body);
  281. selectorElement.style.setProperty("box-sizing", "border-box", "important");
  282. selectorElement.style.setProperty("background-color", "#3ea9d7", "important");
  283. selectorElement.style.setProperty("border", "10px solid #0b4892", "important");
  284. selectorElement.style.setProperty("border-radius", "2px", "important");
  285. selectorElement.style.setProperty("opacity", ".25", "important");
  286. selectorElement.style.setProperty("pointer-events", "none", "important");
  287. selectorElement.style.setProperty("position", "absolute", "important");
  288. selectorElement.style.setProperty("transition", "all 100ms", "important");
  289. selectorElement.style.setProperty("cursor", "pointer", "important");
  290. selectorElement.style.setProperty("z-index", "2147483647", "important");
  291. selectorElement.style.removeProperty("border-inline-end");
  292. selectorElement.style.removeProperty("border-inline-start");
  293. selectorElement.style.removeProperty("inline-size");
  294. selectorElement.style.removeProperty("block-size");
  295. selectorElement.style.removeProperty("inset-block-start");
  296. selectorElement.style.removeProperty("inset-inline-end");
  297. selectorElement.style.removeProperty("inset-block-end");
  298. selectorElement.style.removeProperty("inset-inline-start");
  299. }
  300. return selectorElement;
  301. }
  302. function createMaskElement() {
  303. let maskElement = document.querySelector(MASK_TAGNAME);
  304. if (!maskElement) {
  305. maskElement = createElement(MASK_TAGNAME, document.body);
  306. maskElement.style.setProperty("opacity", 0, "important");
  307. maskElement.style.setProperty("background-color", "transparent", "important");
  308. maskElement.offsetWidth;
  309. maskElement.style.setProperty("position", "fixed", "important");
  310. maskElement.style.setProperty("top", "0", "important");
  311. maskElement.style.setProperty("left", "0", "important");
  312. maskElement.style.setProperty("width", "100%", "important");
  313. maskElement.style.setProperty("height", "100%", "important");
  314. maskElement.style.setProperty("z-index", 2147483646, "important");
  315. maskElement.style.setProperty("transition", "opacity 250ms", "important");
  316. }
  317. return maskElement;
  318. }
  319. function createProgressBarElement(maskElement) {
  320. let progressBarElementContainer = document.querySelector(PROGRESS_BAR_TAGNAME);
  321. if (!progressBarElementContainer) {
  322. progressBarElementContainer = createElement(PROGRESS_BAR_TAGNAME, maskElement);
  323. const styleElement = document.createElement("style");
  324. styleElement.textContent = "@keyframes single-file-progress { 0% { left: -50px } 100% { left: 0 }";
  325. maskElement.appendChild(styleElement);
  326. progressBarElementContainer.style.setProperty("position", "fixed", "important");
  327. progressBarElementContainer.style.setProperty("top", "0", "important");
  328. progressBarElementContainer.style.setProperty("left", "0", "important");
  329. progressBarElementContainer.style.setProperty("width", "0", "important");
  330. progressBarElementContainer.style.setProperty("height", "8px", "important");
  331. progressBarElementContainer.style.setProperty("overflow", "hidden", "important");
  332. progressBarElementContainer.style.setProperty("transition", "width 200ms", "important");
  333. progressBarElementContainer.style.setProperty("will-change", "width", "important");
  334. const progressBarElement = createElement(PROGRESS_CURSOR_TAGNAME, progressBarElementContainer);
  335. progressBarElement.style.setProperty("position", "absolute", "important");
  336. progressBarElement.style.setProperty("left", "0");
  337. progressBarElement.style.setProperty("animation", "single-file-progress 5s linear infinite reverse", "important");
  338. progressBarElement.style.setProperty("background", "white linear-gradient(-45deg, rgba(0, 0, 0, 0.1) 25%, transparent 25%, transparent 50%, rgba(0, 0, 0, 0.1) 50%, rgba(0, 0, 0, 0.1) 75%, transparent 75%, transparent) repeat scroll 0% 0% / 50px 50px padding-box border-box", "important");
  339. progressBarElement.style.setProperty("width", "calc(100% + 50px)", "important");
  340. progressBarElement.style.setProperty("height", "100%", "important");
  341. progressBarElement.style.setProperty("inset-inline-start", "auto");
  342. }
  343. return progressBarElementContainer;
  344. }
  345. function createLogsWindowElement() {
  346. let logsWindowElement = document.querySelector(LOGS_WINDOW_TAGNAME);
  347. if (!logsWindowElement) {
  348. logsWindowElement = document.createElement(LOGS_WINDOW_TAGNAME);
  349. logsWindowElement.className = SINGLE_FILE_UI_ELEMENT_CLASS;
  350. }
  351. const styleElement = document.createElement("style");
  352. logsWindowElement.appendChild(styleElement);
  353. styleElement.textContent = "@keyframes single-file-pulse { 0% { opacity: .5 } 100% { opacity: 1 }";
  354. return logsWindowElement;
  355. }
  356. function setLogsWindowStyle() {
  357. initStyle(logsWindowElement);
  358. logsWindowElement.style.setProperty("opacity", "0.9", "important");
  359. logsWindowElement.style.setProperty("padding", "4px", "important");
  360. logsWindowElement.style.setProperty("position", "fixed", "important");
  361. logsWindowElement.style.setProperty("bottom", "24px", "important");
  362. logsWindowElement.style.setProperty("left", "8px", "important");
  363. logsWindowElement.style.setProperty("z-index", 2147483647, "important");
  364. logsWindowElement.style.setProperty("background-color", "white", "important");
  365. logsWindowElement.style.setProperty("min-width", LOG_PANEL_WIDTH + "px", "important");
  366. logsWindowElement.style.setProperty("min-height", "16px", "important");
  367. logsWindowElement.style.setProperty("transition", "height 100ms", "important");
  368. logsWindowElement.style.setProperty("will-change", "height", "important");
  369. }
  370. function updateLog(id, textContent, textStatus) {
  371. let lineElement = logsWindowElement.querySelector("[data-id='" + id + "']");
  372. if (!lineElement) {
  373. lineElement = createElement(LOGS_LINE_TAGNAME, logsWindowElement);
  374. lineElement.setAttribute("data-id", id);
  375. lineElement.style.setProperty("display", "flex");
  376. lineElement.style.setProperty("justify-content", "space-between");
  377. const textElement = createElement(LOGS_LINE_ELEMENT_TAGNAME, lineElement);
  378. textElement.style.setProperty("font-size", "13px", "important");
  379. textElement.style.setProperty("font-family", "arial, sans-serif", "important");
  380. textElement.style.setProperty("color", "black", "important");
  381. textElement.style.setProperty("background-color", "white", "important");
  382. textElement.style.setProperty("opacity", "1", "important");
  383. textElement.style.setProperty("transition", "opacity 200ms", "important");
  384. textElement.textContent = textContent;
  385. const statusElement = createElement(LOGS_LINE_ELEMENT_TAGNAME, lineElement);
  386. statusElement.style.setProperty("font-size", "11px", "important");
  387. statusElement.style.setProperty("font-family", "arial, sans-serif", "important");
  388. statusElement.style.setProperty("color", "black", "important");
  389. statusElement.style.setProperty("background-color", "white", "important");
  390. statusElement.style.setProperty("min-width", "15px", "important");
  391. statusElement.style.setProperty("text-align", "center", "important");
  392. statusElement.style.setProperty("will-change", "opacity", "important");
  393. }
  394. updateLogLine(lineElement, textContent, textStatus);
  395. }
  396. function updateLogLine(lineElement, textContent, textStatus) {
  397. const textElement = lineElement.childNodes[0];
  398. const statusElement = lineElement.childNodes[1];
  399. textElement.textContent = textContent;
  400. statusElement.style.setProperty("color", textStatus == "✓" ? "#055000" : "black", "important");
  401. if (textStatus == "✓") {
  402. textElement.style.setProperty("opacity", ".5", "important");
  403. statusElement.style.setProperty("animation", "none", "important");
  404. } else {
  405. statusElement.style.setProperty("opacity", ".5", "important");
  406. statusElement.style.setProperty("animation", "single-file-pulse 1s linear infinite alternate", "important");
  407. }
  408. statusElement.textContent = textStatus;
  409. }
  410. function clearLogs() {
  411. logsWindowElement = createLogsWindowElement();
  412. }
  413. function getMatchedParents(target, property) {
  414. let element = target, matchedParent, parents = [];
  415. do {
  416. const boundingRect = element.getBoundingClientRect();
  417. if (element.parentElement) {
  418. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  419. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  420. if (matchedParent) {
  421. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  422. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  423. parents.push(element.parentElement);
  424. }
  425. element = element.parentElement;
  426. }
  427. } else {
  428. matchedParent = false;
  429. }
  430. } while (matchedParent && element);
  431. return parents;
  432. }
  433. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  434. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  435. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  436. }
  437. return target;
  438. }
  439. function createElement(tagName, parentElement) {
  440. const element = document.createElement(tagName);
  441. element.className = SINGLE_FILE_UI_ELEMENT_CLASS;
  442. parentElement.appendChild(element);
  443. initStyle(element);
  444. return element;
  445. }
  446. function initStyle(element) {
  447. allProperties.forEach(property => element.style.setProperty(property, "initial", "important"));
  448. }
  449. })();