content-ui-main.js 21 KB

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