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 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. if (options.logsEnabled) {
  53. document.body.appendChild(logsWindowElement);
  54. setLogsWindowStyle();
  55. }
  56. if (options.shadowEnabled) {
  57. const maskElement = createMaskElement();
  58. createProgressBarElement(maskElement);
  59. maskElement.offsetWidth;
  60. maskElement.style.setProperty("background-color", "black", "important");
  61. maskElement.style.setProperty("opacity", .3, "important");
  62. document.body.offsetWidth;
  63. }
  64. }
  65. },
  66. onEndPage(options) {
  67. if (options.shadowEnabled) {
  68. const maskElement = document.querySelector(MASK_TAGNAME);
  69. if (maskElement) {
  70. maskElement.remove();
  71. }
  72. }
  73. if (options.logsEnabled) {
  74. logsWindowElement.remove();
  75. clearLogs();
  76. }
  77. },
  78. onLoadResource(index, maxIndex, options) {
  79. if (options.shadowEnabled) {
  80. const progressBarElement = document.querySelector(PROGRESS_BAR_TAGNAME);
  81. if (progressBarElement && maxIndex) {
  82. const width = Math.floor((index / maxIndex) * 100) + "%";
  83. if (progressBarElement.style.getPropertyValue("width") != width) {
  84. requestAnimationFrame(() => progressBarElement.style.setProperty("width", Math.floor((index / maxIndex) * 100) + "%", "important"));
  85. }
  86. }
  87. }
  88. },
  89. onLoadingDeferResources(options) {
  90. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "…", options);
  91. },
  92. onLoadDeferResources(options) {
  93. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "✓", options);
  94. },
  95. onLoadingFrames(options) {
  96. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "…", options);
  97. },
  98. onLoadFrames(options) {
  99. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "✓", options);
  100. },
  101. onStartStage(step, options) {
  102. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "…", options);
  103. },
  104. onEndStage(step, options) {
  105. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "✓", options);
  106. },
  107. onPageLoading() { },
  108. onLoadPage() { },
  109. onStartStageTask() { },
  110. onEndStageTask() { }
  111. };
  112. async function markSelection() {
  113. let selectionFound = markSelectedContent();
  114. if (selectionFound) {
  115. return selectionFound;
  116. } else {
  117. selectionFound = await selectArea();
  118. if (selectionFound) {
  119. return markSelectedContent();
  120. }
  121. }
  122. }
  123. function markSelectedContent() {
  124. const selection = getSelection();
  125. let selectionFound;
  126. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  127. let range = selection.getRangeAt(indexRange);
  128. if (range && range.commonAncestorContainer) {
  129. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  130. let rangeSelectionFound = false;
  131. let finished = false;
  132. while (!finished) {
  133. if (rangeSelectionFound || treeWalker.currentNode == range.startContainer || treeWalker.currentNode == range.endContainer) {
  134. rangeSelectionFound = true;
  135. if (range.startContainer != range.endContainer || range.startOffset != range.endOffset) {
  136. selectionFound = true;
  137. markSelectedNode(treeWalker.currentNode);
  138. }
  139. }
  140. if (selectionFound && treeWalker.currentNode == range.startContainer) {
  141. markSelectedParents(treeWalker.currentNode);
  142. }
  143. if (treeWalker.currentNode == range.endContainer) {
  144. finished = true;
  145. } else {
  146. treeWalker.nextNode();
  147. }
  148. }
  149. if (selectionFound && treeWalker.currentNode == range.endContainer && treeWalker.currentNode.querySelectorAll) {
  150. treeWalker.currentNode.querySelectorAll("*").forEach(descendantElement => markSelectedNode(descendantElement));
  151. }
  152. }
  153. }
  154. return selectionFound;
  155. }
  156. function markSelectedNode(node) {
  157. const element = node.nodeType == Node.ELEMENT_NODE ? node : node.parentElement;
  158. element.setAttribute(SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  159. }
  160. function markSelectedParents(node) {
  161. if (node.parentElement) {
  162. markSelectedNode(node);
  163. markSelectedParents(node.parentElement);
  164. }
  165. }
  166. function unmarkSelection() {
  167. document.querySelectorAll("[" + SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SingleFile.SELECTED_CONTENT_ATTRIBUTE_NAME));
  168. }
  169. function selectArea() {
  170. return new Promise(resolve => {
  171. let selectedRanges = [];
  172. addEventListener("mousemove", mousemoveListener, true);
  173. addEventListener("click", clickListener, true);
  174. addEventListener("keyup", keypressListener, true);
  175. document.addEventListener("contextmenu", contextmenuListener, true);
  176. getSelection().removeAllRanges();
  177. function contextmenuListener(event) {
  178. selectedRanges = [];
  179. select();
  180. event.preventDefault();
  181. }
  182. function mousemoveListener(event) {
  183. const targetElement = getTarget(event);
  184. if (targetElement) {
  185. selectedAreaElement = targetElement;
  186. moveAreaSelector(targetElement);
  187. }
  188. }
  189. function clickListener(event) {
  190. event.preventDefault();
  191. event.stopPropagation();
  192. if (event.button == 0) {
  193. select(selectedAreaElement, event.ctrlKey);
  194. } else {
  195. cancel();
  196. }
  197. }
  198. function keypressListener(event) {
  199. if (event.key == "Escape") {
  200. cancel();
  201. }
  202. }
  203. function cancel() {
  204. if (selectedRanges.length) {
  205. getSelection().removeAllRanges();
  206. }
  207. selectedRanges = [];
  208. cleanupAndResolve();
  209. }
  210. function select(selectedElement, multiSelect) {
  211. if (selectedElement) {
  212. if (!multiSelect) {
  213. restoreSelectedRanges();
  214. }
  215. const range = document.createRange();
  216. range.selectNodeContents(selectedElement);
  217. cleanupSelectionRanges();
  218. getSelection().addRange(range);
  219. saveSelectedRanges();
  220. if (!multiSelect) {
  221. cleanupAndResolve();
  222. }
  223. } else {
  224. cleanupAndResolve();
  225. }
  226. }
  227. function cleanupSelectionRanges() {
  228. const selection = getSelection();
  229. for (let indexRange = selection.rangeCount - 1; indexRange >= 0; indexRange--) {
  230. const range = selection.getRangeAt(indexRange);
  231. if (range.startOffset == range.endOffset) {
  232. selection.removeRange(range);
  233. indexRange--;
  234. }
  235. }
  236. }
  237. function cleanupAndResolve() {
  238. getAreaSelector().remove();
  239. removeEventListener("mousemove", mousemoveListener, true);
  240. removeEventListener("click", clickListener, true);
  241. removeEventListener("keyup", keypressListener, true);
  242. selectedAreaElement = null;
  243. resolve(Boolean(selectedRanges.length));
  244. setTimeout(() => document.removeEventListener("contextmenu", contextmenuListener, true), 0);
  245. }
  246. function restoreSelectedRanges() {
  247. getSelection().removeAllRanges();
  248. selectedRanges.forEach(range => getSelection().addRange(range));
  249. }
  250. function saveSelectedRanges() {
  251. selectedRanges = [];
  252. for (let indexRange = 0; indexRange < getSelection().rangeCount; indexRange++) {
  253. const range = getSelection().getRangeAt(indexRange);
  254. selectedRanges.push(range);
  255. }
  256. }
  257. });
  258. }
  259. function getTarget(event) {
  260. let newTarget, target = event.target, boundingRect = target.getBoundingClientRect();
  261. newTarget = determineTargetElement("floor", target, event.clientX - boundingRect.left, getMatchedParents(target, "left"));
  262. if (newTarget == target) {
  263. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - event.clientX, getMatchedParents(target, "right"));
  264. }
  265. if (newTarget == target) {
  266. newTarget = determineTargetElement("floor", target, event.clientY - boundingRect.top, getMatchedParents(target, "top"));
  267. }
  268. if (newTarget == target) {
  269. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - event.clientY, getMatchedParents(target, "bottom"));
  270. }
  271. target = newTarget;
  272. while (target && target.clientWidth <= SELECT_PX_THRESHOLD && target.clientHeight <= SELECT_PX_THRESHOLD) {
  273. target = target.parentElement;
  274. }
  275. return target;
  276. }
  277. function moveAreaSelector(target) {
  278. requestAnimationFrame(() => {
  279. const selectorElement = getAreaSelector();
  280. const boundingRect = target.getBoundingClientRect();
  281. selectorElement.style.setProperty("top", (document.documentElement.scrollTop + boundingRect.top - 10) + "px");
  282. selectorElement.style.setProperty("left", (document.documentElement.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. })();