1
0

content-ui-main.js 21 KB

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