content-ui-main.js 20 KB

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