content-ui.js 19 KB

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