content-ui-main.js 21 KB

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