AboutReader.jsm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. var Ci = Components.interfaces, Cc = Components.classes, Cu = Components.utils;
  6. this.EXPORTED_SYMBOLS = [ "AboutReader" ];
  7. Cu.import("resource://gre/modules/ReaderMode.jsm");
  8. Cu.import("resource://gre/modules/Services.jsm");
  9. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  10. XPCOMUtils.defineLazyModuleGetter(this, "AsyncPrefs", "resource://gre/modules/AsyncPrefs.jsm");
  11. XPCOMUtils.defineLazyModuleGetter(this, "NarrateControls", "resource://gre/modules/narrate/NarrateControls.jsm");
  12. XPCOMUtils.defineLazyModuleGetter(this, "PluralForm", "resource://gre/modules/PluralForm.jsm");
  13. XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", "resource://gre/modules/PlacesUtils.jsm");
  14. var gStrings = Services.strings.createBundle("chrome://global/locale/aboutReader.properties");
  15. var AboutReader = function(win, articlePromise) {
  16. let url = this._getOriginalUrl(win);
  17. if (!(url.startsWith("http://") || url.startsWith("https://"))) {
  18. let errorMsg = "Only http:// and https:// URLs can be loaded in about:reader.";
  19. if (Services.prefs.getBoolPref("reader.errors.includeURLs"))
  20. errorMsg += " Tried to load: " + url + ".";
  21. Cu.reportError(errorMsg);
  22. win.location.href = "about:blank";
  23. return;
  24. }
  25. let doc = win.document;
  26. this._docRef = Cu.getWeakReference(doc);
  27. this._winRef = Cu.getWeakReference(win);
  28. this._innerWindowId = win.QueryInterface(Ci.nsIInterfaceRequestor)
  29. .getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
  30. this._article = null;
  31. this._languagePromise = new Promise(resolve => {
  32. this._foundLanguage = resolve;
  33. });
  34. if (articlePromise) {
  35. this._articlePromise = articlePromise;
  36. }
  37. this._headerElementRef = Cu.getWeakReference(doc.querySelector(".reader-header"));
  38. this._domainElementRef = Cu.getWeakReference(doc.querySelector(".reader-domain"));
  39. this._titleElementRef = Cu.getWeakReference(doc.querySelector(".reader-title"));
  40. this._readTimeElementRef = Cu.getWeakReference(doc.querySelector(".reader-estimated-time"));
  41. this._creditsElementRef = Cu.getWeakReference(doc.querySelector(".reader-credits"));
  42. this._contentElementRef = Cu.getWeakReference(doc.querySelector(".moz-reader-content"));
  43. this._toolbarElementRef = Cu.getWeakReference(doc.querySelector(".reader-toolbar"));
  44. this._messageElementRef = Cu.getWeakReference(doc.querySelector(".reader-message"));
  45. this._containerElementRef = Cu.getWeakReference(doc.querySelector(".container"));
  46. this._scrollOffset = win.pageYOffset;
  47. doc.addEventListener("mousedown", this);
  48. doc.addEventListener("click", this);
  49. win.addEventListener("pagehide", this);
  50. win.addEventListener("scroll", this);
  51. win.addEventListener("resize", this);
  52. win.addEventListener("AboutReaderAddButton", this, false, true);
  53. win.addEventListener("AboutReaderRemoveButton", this, false, true);
  54. Services.obs.addObserver(this, "inner-window-destroyed", false);
  55. this._setupStyleDropdown();
  56. this._setupButton("close-button", this._onReaderClose.bind(this), "aboutReader.toolbar.close");
  57. // we're ready for any external setup, send a signal for that.
  58. doc.dispatchEvent(
  59. new win.CustomEvent("AboutReaderOnSetup", { bubbles: true, cancelable: false }));
  60. let colorSchemeValues = JSON.parse(Services.prefs.getCharPref("reader.color_scheme.values"));
  61. let colorSchemeOptions = colorSchemeValues.map((value) => {
  62. return {
  63. name: gStrings.GetStringFromName("aboutReader.colorScheme." + value),
  64. value,
  65. itemClass: value + "-button"
  66. };
  67. });
  68. let colorScheme = Services.prefs.getCharPref("reader.color_scheme");
  69. this._setupSegmentedButton("color-scheme-buttons", colorSchemeOptions, colorScheme, this._setColorSchemePref.bind(this));
  70. this._setColorSchemePref(colorScheme);
  71. let fontTypeSample = gStrings.GetStringFromName("aboutReader.fontTypeSample");
  72. let fontTypeOptions = [
  73. { name: fontTypeSample,
  74. description: gStrings.GetStringFromName("aboutReader.fontType.sans-serif"),
  75. value: "sans-serif",
  76. itemClass: "sans-serif-button"
  77. },
  78. { name: fontTypeSample,
  79. description: gStrings.GetStringFromName("aboutReader.fontType.serif"),
  80. value: "serif",
  81. itemClass: "serif-button" },
  82. ];
  83. let fontType = Services.prefs.getCharPref("reader.font_type");
  84. this._setupSegmentedButton("font-type-buttons", fontTypeOptions, fontType, this._setFontType.bind(this));
  85. this._setFontType(fontType);
  86. this._setupFontSizeButtons();
  87. this._setupContentWidthButtons();
  88. this._setupLineHeightButtons();
  89. if (win.speechSynthesis && Services.prefs.getBoolPref("narrate.enabled")) {
  90. new NarrateControls(win, this._languagePromise);
  91. }
  92. this._loadArticle();
  93. let dropdown = this._toolbarElement;
  94. let elemL10nMap = {
  95. ".minus-button": "minus",
  96. ".plus-button": "plus",
  97. ".content-width-minus-button": "contentwidthminus",
  98. ".content-width-plus-button": "contentwidthplus",
  99. ".line-height-minus-button": "lineheightminus",
  100. ".line-height-plus-button": "lineheightplus",
  101. ".light-button": "colorschemelight",
  102. ".dark-button": "colorschemedark",
  103. ".sepia-button": "colorschemesepia",
  104. };
  105. for (let [selector, stringID] of Object.entries(elemL10nMap)) {
  106. dropdown.querySelector(selector).setAttribute("title",
  107. gStrings.GetStringFromName("aboutReader.toolbar." + stringID));
  108. }
  109. };
  110. AboutReader.prototype = {
  111. _BLOCK_IMAGES_SELECTOR: ".content p > img:only-child, " +
  112. ".content p > a:only-child > img:only-child, " +
  113. ".content .wp-caption img, " +
  114. ".content figure img",
  115. get _doc() {
  116. return this._docRef.get();
  117. },
  118. get _win() {
  119. return this._winRef.get();
  120. },
  121. get _headerElement() {
  122. return this._headerElementRef.get();
  123. },
  124. get _domainElement() {
  125. return this._domainElementRef.get();
  126. },
  127. get _titleElement() {
  128. return this._titleElementRef.get();
  129. },
  130. get _readTimeElement() {
  131. return this._readTimeElementRef.get();
  132. },
  133. get _creditsElement() {
  134. return this._creditsElementRef.get();
  135. },
  136. get _contentElement() {
  137. return this._contentElementRef.get();
  138. },
  139. get _toolbarElement() {
  140. return this._toolbarElementRef.get();
  141. },
  142. get _messageElement() {
  143. return this._messageElementRef.get();
  144. },
  145. get _containerElement() {
  146. return this._containerElementRef.get();
  147. },
  148. get _isToolbarVertical() {
  149. if (this._toolbarVertical !== undefined) {
  150. return this._toolbarVertical;
  151. }
  152. return this._toolbarVertical = Services.prefs.getBoolPref("reader.toolbar.vertical");
  153. },
  154. // Provides unique view Id.
  155. get viewId() {
  156. let _viewId = Cc["@mozilla.org/uuid-generator;1"].
  157. getService(Ci.nsIUUIDGenerator).generateUUID().toString();
  158. Object.defineProperty(this, "viewId", { value: _viewId });
  159. return _viewId;
  160. },
  161. handleEvent(aEvent) {
  162. if (!aEvent.isTrusted)
  163. return;
  164. let target = aEvent.target;
  165. switch (aEvent.type) {
  166. case "mousedown":
  167. if (!target.closest(".dropdown-popup")) {
  168. this._closeDropdowns();
  169. }
  170. break;
  171. case "click":
  172. if (target.classList.contains("dropdown-toggle")) {
  173. this._toggleDropdownClicked(aEvent);
  174. }
  175. break;
  176. case "scroll":
  177. this._closeDropdowns(true);
  178. this._scrollOffset = aEvent.pageY;
  179. break;
  180. case "resize":
  181. this._updateImageMargins();
  182. if (this._isToolbarVertical) {
  183. this._win.setTimeout(() => {
  184. for (let dropdown of this._doc.querySelectorAll(".dropdown.open")) {
  185. this._updatePopupPosition(dropdown);
  186. }
  187. }, 0);
  188. }
  189. break;
  190. case "pagehide":
  191. // Close the Banners Font-dropdown, cleanup Android BackPressListener.
  192. this._closeDropdowns();
  193. this._windowUnloaded = true;
  194. break;
  195. case "AboutReaderAddButton": {
  196. if (aEvent.detail.id && aEvent.detail.image &&
  197. !this._doc.getElementById(aEvent.detail.id)) {
  198. let btn = this._doc.createElement("button");
  199. btn.setAttribute("class", "button " + aEvent.detail.id);
  200. btn.setAttribute("style", "background-image: url('" + aEvent.detail.image + "')");
  201. btn.setAttribute("id", aEvent.detail.id);
  202. if (aEvent.detail.title)
  203. btn.setAttribute("title", aEvent.detail.title);
  204. if (aEvent.detail.text)
  205. btn.textContent = aEvent.detail.text;
  206. let tb = this._toolbarElement;
  207. tb.appendChild(btn);
  208. this._setupButton(aEvent.detail.id, button => {
  209. var data = { article: this._article };
  210. this._doc.dispatchEvent(
  211. new this._win.CustomEvent("AboutReaderButtonClicked-" + button.getAttribute("id"), {detail: data, bubbles: true, cancelable: false}));
  212. });
  213. }
  214. break;
  215. }
  216. case "AboutReaderRemoveButton": {
  217. if (aEvent.detail.id) {
  218. let btn = this._doc.getElementById(aEvent.detail.id);
  219. if (btn)
  220. btn.remove();
  221. }
  222. break;
  223. }
  224. }
  225. },
  226. observe(subject, topic, data) {
  227. if (subject.QueryInterface(Ci.nsISupportsPRUint64).data != this._innerWindowId) {
  228. return;
  229. }
  230. Services.obs.removeObserver(this, "inner-window-destroyed");
  231. this._windowUnloaded = true;
  232. },
  233. _onReaderClose() {
  234. ReaderMode.leaveReaderMode(this._win.document.docShell, this._win);
  235. },
  236. _setFontSize(newFontSize) {
  237. this._fontSize = newFontSize;
  238. let size = (10 + 2 * this._fontSize) + "px";
  239. this._containerElement.style.setProperty("--font-size", size);
  240. return AsyncPrefs.set("reader.font_size", this._fontSize);
  241. },
  242. _setupFontSizeButtons() {
  243. const FONT_SIZE_MIN = 1;
  244. const FONT_SIZE_MAX = 9;
  245. let currentSize = Services.prefs.getIntPref("reader.font_size");
  246. currentSize = Math.max(FONT_SIZE_MIN, Math.min(FONT_SIZE_MAX, currentSize));
  247. let plusButton = this._doc.querySelector(".plus-button");
  248. let minusButton = this._doc.querySelector(".minus-button");
  249. function updateControls() {
  250. if (currentSize === FONT_SIZE_MIN) {
  251. minusButton.setAttribute("disabled", true);
  252. } else {
  253. minusButton.removeAttribute("disabled");
  254. }
  255. if (currentSize === FONT_SIZE_MAX) {
  256. plusButton.setAttribute("disabled", true);
  257. } else {
  258. plusButton.removeAttribute("disabled");
  259. }
  260. }
  261. updateControls();
  262. this._setFontSize(currentSize);
  263. plusButton.addEventListener("click", (event) => {
  264. if (!event.isTrusted) {
  265. return;
  266. }
  267. event.stopPropagation();
  268. if (currentSize >= FONT_SIZE_MAX) {
  269. return;
  270. }
  271. currentSize++;
  272. updateControls();
  273. this._setFontSize(currentSize);
  274. }, true);
  275. minusButton.addEventListener("click", (event) => {
  276. if (!event.isTrusted) {
  277. return;
  278. }
  279. event.stopPropagation();
  280. if (currentSize <= FONT_SIZE_MIN) {
  281. return;
  282. }
  283. currentSize--;
  284. updateControls();
  285. this._setFontSize(currentSize);
  286. }, true);
  287. },
  288. _setContentWidth(newContentWidth) {
  289. let containerClasses = this._containerElement.classList;
  290. if (this._contentWidth > 0)
  291. containerClasses.remove("content-width" + this._contentWidth);
  292. this._contentWidth = newContentWidth;
  293. containerClasses.add("content-width" + this._contentWidth);
  294. return AsyncPrefs.set("reader.content_width", this._contentWidth);
  295. },
  296. _setupContentWidthButtons() {
  297. const CONTENT_WIDTH_MIN = 1;
  298. const CONTENT_WIDTH_MAX = 9;
  299. let currentContentWidth = Services.prefs.getIntPref("reader.content_width");
  300. currentContentWidth = Math.max(CONTENT_WIDTH_MIN, Math.min(CONTENT_WIDTH_MAX, currentContentWidth));
  301. let plusButton = this._doc.querySelector(".content-width-plus-button");
  302. let minusButton = this._doc.querySelector(".content-width-minus-button");
  303. function updateControls() {
  304. if (currentContentWidth === CONTENT_WIDTH_MIN) {
  305. minusButton.setAttribute("disabled", true);
  306. } else {
  307. minusButton.removeAttribute("disabled");
  308. }
  309. if (currentContentWidth === CONTENT_WIDTH_MAX) {
  310. plusButton.setAttribute("disabled", true);
  311. } else {
  312. plusButton.removeAttribute("disabled");
  313. }
  314. }
  315. updateControls();
  316. this._setContentWidth(currentContentWidth);
  317. plusButton.addEventListener("click", (event) => {
  318. if (!event.isTrusted) {
  319. return;
  320. }
  321. event.stopPropagation();
  322. if (currentContentWidth >= CONTENT_WIDTH_MAX) {
  323. return;
  324. }
  325. currentContentWidth++;
  326. updateControls();
  327. this._setContentWidth(currentContentWidth);
  328. }, true);
  329. minusButton.addEventListener("click", (event) => {
  330. if (!event.isTrusted) {
  331. return;
  332. }
  333. event.stopPropagation();
  334. if (currentContentWidth <= CONTENT_WIDTH_MIN) {
  335. return;
  336. }
  337. currentContentWidth--;
  338. updateControls();
  339. this._setContentWidth(currentContentWidth);
  340. }, true);
  341. },
  342. _setLineHeight(newLineHeight) {
  343. let contentClasses = this._contentElement.classList;
  344. if (this._lineHeight > 0)
  345. contentClasses.remove("line-height" + this._lineHeight);
  346. this._lineHeight = newLineHeight;
  347. contentClasses.add("line-height" + this._lineHeight);
  348. return AsyncPrefs.set("reader.line_height", this._lineHeight);
  349. },
  350. _setupLineHeightButtons() {
  351. const LINE_HEIGHT_MIN = 1;
  352. const LINE_HEIGHT_MAX = 9;
  353. let currentLineHeight = Services.prefs.getIntPref("reader.line_height");
  354. currentLineHeight = Math.max(LINE_HEIGHT_MIN, Math.min(LINE_HEIGHT_MAX, currentLineHeight));
  355. let plusButton = this._doc.querySelector(".line-height-plus-button");
  356. let minusButton = this._doc.querySelector(".line-height-minus-button");
  357. function updateControls() {
  358. if (currentLineHeight === LINE_HEIGHT_MIN) {
  359. minusButton.setAttribute("disabled", true);
  360. } else {
  361. minusButton.removeAttribute("disabled");
  362. }
  363. if (currentLineHeight === LINE_HEIGHT_MAX) {
  364. plusButton.setAttribute("disabled", true);
  365. } else {
  366. plusButton.removeAttribute("disabled");
  367. }
  368. }
  369. updateControls();
  370. this._setLineHeight(currentLineHeight);
  371. plusButton.addEventListener("click", (event) => {
  372. if (!event.isTrusted) {
  373. return;
  374. }
  375. event.stopPropagation();
  376. if (currentLineHeight >= LINE_HEIGHT_MAX) {
  377. return;
  378. }
  379. currentLineHeight++;
  380. updateControls();
  381. this._setLineHeight(currentLineHeight);
  382. }, true);
  383. minusButton.addEventListener("click", (event) => {
  384. if (!event.isTrusted) {
  385. return;
  386. }
  387. event.stopPropagation();
  388. if (currentLineHeight <= LINE_HEIGHT_MIN) {
  389. return;
  390. }
  391. currentLineHeight--;
  392. updateControls();
  393. this._setLineHeight(currentLineHeight);
  394. }, true);
  395. },
  396. _setColorScheme(newColorScheme) {
  397. if (this._colorScheme === newColorScheme)
  398. return;
  399. let bodyClasses = this._doc.body.classList;
  400. if (this._colorScheme)
  401. bodyClasses.remove(this._colorScheme);
  402. this._colorScheme = newColorScheme;
  403. bodyClasses.add(this._colorScheme);
  404. },
  405. // Pref values include "dark", "light", and "sepia".
  406. _setColorSchemePref(colorSchemePref) {
  407. this._setColorScheme(colorSchemePref);
  408. AsyncPrefs.set("reader.color_scheme", colorSchemePref);
  409. },
  410. _setFontType(newFontType) {
  411. if (this._fontType === newFontType)
  412. return;
  413. let bodyClasses = this._doc.body.classList;
  414. if (this._fontType)
  415. bodyClasses.remove(this._fontType);
  416. this._fontType = newFontType;
  417. bodyClasses.add(this._fontType);
  418. AsyncPrefs.set("reader.font_type", this._fontType);
  419. },
  420. _setToolbarVisibility(visible) {
  421. let tb = this._toolbarElement;
  422. if (visible) {
  423. if (tb.style.opacity != "1") {
  424. tb.removeAttribute("hidden");
  425. tb.style.opacity = "1";
  426. }
  427. } else if (tb.style.opacity != "0") {
  428. tb.addEventListener("transitionend", evt => {
  429. if (tb.style.opacity == "0") {
  430. tb.setAttribute("hidden", "");
  431. }
  432. }, { once: true });
  433. tb.style.opacity = "0";
  434. }
  435. },
  436. async _loadArticle() {
  437. let url = this._getOriginalUrl();
  438. this._showProgressDelayed();
  439. let article;
  440. if (this._articlePromise) {
  441. article = await this._articlePromise;
  442. } else {
  443. try {
  444. article = await this._getArticle(url);
  445. } catch (e) {
  446. if (e && e.newURL) {
  447. let readerURL = "about:reader?url=" + encodeURIComponent(e.newURL);
  448. this._win.location.replace(readerURL);
  449. return;
  450. }
  451. }
  452. }
  453. if (this._windowUnloaded) {
  454. return;
  455. }
  456. // Replace the loading message with an error message if there's a failure.
  457. // Users are supposed to navigate away by themselves (because we cannot
  458. // remove ourselves from session history.)
  459. if (!article) {
  460. this._showError();
  461. return;
  462. }
  463. this._showContent(article);
  464. },
  465. _getArticle(url) {
  466. return ReaderMode.downloadAndParseDocument(url);
  467. },
  468. _requestFavicon() {
  469. let faviconUrl = PlacesUtils.promiseFaviconLinkUrl(this._article.url);
  470. var self = this;
  471. faviconUrl.then(function onResolution(favicon) {
  472. self._loadFavicon(self._article.url, favicon.path.replace(/^favicon:/, ""));
  473. },
  474. function onRejection(reason) {
  475. Cu.reportError("Error requesting favicon URL for about:reader content: " + reason);
  476. }).catch(Cu.reportError);
  477. },
  478. _loadFavicon(url, faviconUrl) {
  479. if (this._article.url !== url)
  480. return;
  481. let doc = this._doc;
  482. let link = doc.createElement("link");
  483. link.rel = "shortcut icon";
  484. link.href = faviconUrl;
  485. doc.getElementsByTagName("head")[0].appendChild(link);
  486. },
  487. _updateImageMargins() {
  488. let windowWidth = this._win.innerWidth;
  489. let bodyWidth = this._doc.body.clientWidth;
  490. let setImageMargins = function(img) {
  491. // If the image is at least as wide as the window, make it fill edge-to-edge on mobile.
  492. if (img.naturalWidth >= windowWidth) {
  493. img.setAttribute("moz-reader-full-width", true);
  494. } else {
  495. img.removeAttribute("moz-reader-full-width");
  496. }
  497. // If the image is at least half as wide as the body, center it on desktop.
  498. if (img.naturalWidth >= bodyWidth / 2) {
  499. img.setAttribute("moz-reader-center", true);
  500. } else {
  501. img.removeAttribute("moz-reader-center");
  502. }
  503. };
  504. let imgs = this._doc.querySelectorAll(this._BLOCK_IMAGES_SELECTOR);
  505. for (let i = imgs.length; --i >= 0;) {
  506. let img = imgs[i];
  507. if (img.naturalWidth > 0) {
  508. setImageMargins(img);
  509. } else {
  510. img.onload = function() {
  511. setImageMargins(img);
  512. };
  513. }
  514. }
  515. },
  516. _maybeSetTextDirection: function Read_maybeSetTextDirection(article) {
  517. if (article.dir) {
  518. // Set "dir" attribute on content
  519. this._contentElement.setAttribute("dir", article.dir);
  520. this._headerElement.setAttribute("dir", article.dir);
  521. // The native locale could be set differently than the article's text direction.
  522. var localeDirection = Services.locale.isAppLocaleRTL ? "rtl" : "ltr";
  523. this._readTimeElement.setAttribute("dir", localeDirection);
  524. this._readTimeElement.style.textAlign = article.dir == "rtl" ? "right" : "left";
  525. }
  526. },
  527. _fixLocalLinks() {
  528. // We need to do this because preprocessing the content through nsIParserUtils
  529. // gives back a DOM with a <base> element. That influences how these URLs get
  530. // resolved, making them no longer match the document URI (which is
  531. // about:reader?url=...). To fix this, make all the hash URIs absolute. This
  532. // is hacky, but the alternative of removing the base element has potential
  533. // security implications if Readability has not successfully made all the URLs
  534. // absolute, so we pick just fixing these in-document links explicitly.
  535. let localLinks = this._contentElement.querySelectorAll("a[href^='#']");
  536. for (let localLink of localLinks) {
  537. // Have to get the attribute because .href provides an absolute URI.
  538. localLink.href = this._doc.documentURI + localLink.getAttribute("href");
  539. }
  540. },
  541. _formatReadTime(slowEstimate, fastEstimate) {
  542. let displayStringKey = "aboutReader.estimatedReadTimeRange1";
  543. // only show one reading estimate when they are the same value
  544. if (slowEstimate == fastEstimate) {
  545. displayStringKey = "aboutReader.estimatedReadTimeValue1";
  546. }
  547. return PluralForm.get(slowEstimate, gStrings.GetStringFromName(displayStringKey))
  548. .replace("#1", fastEstimate)
  549. .replace("#2", slowEstimate);
  550. },
  551. _showError() {
  552. this._headerElement.style.display = "none";
  553. this._contentElement.style.display = "none";
  554. let errorMessage = gStrings.GetStringFromName("aboutReader.loadError");
  555. this._messageElement.textContent = errorMessage;
  556. this._messageElement.style.display = "block";
  557. this._doc.title = errorMessage;
  558. this._doc.documentElement.dataset.isError = true;
  559. this._error = true;
  560. this._doc.dispatchEvent(
  561. new this._win.CustomEvent("AboutReaderContentError", { bubbles: true, cancelable: false }));
  562. },
  563. // This function is the JS version of Java's StringUtils.stripCommonSubdomains.
  564. _stripHost(host) {
  565. if (!host)
  566. return host;
  567. let start = 0;
  568. if (host.startsWith("www."))
  569. start = 4;
  570. else if (host.startsWith("m."))
  571. start = 2;
  572. else if (host.startsWith("mobile."))
  573. start = 7;
  574. return host.substring(start);
  575. },
  576. _showContent(article) {
  577. this._messageElement.style.display = "none";
  578. this._article = article;
  579. this._domainElement.href = article.url;
  580. let articleUri = Services.io.newURI(article.url);
  581. this._domainElement.textContent = this._stripHost(articleUri.host);
  582. this._creditsElement.textContent = article.byline;
  583. this._titleElement.textContent = article.title;
  584. this._readTimeElement.textContent = this._formatReadTime(article.readingTimeMinsSlow, article.readingTimeMinsFast);
  585. this._doc.title = article.title;
  586. this._headerElement.style.display = "block";
  587. let parserUtils = Cc["@mozilla.org/parserutils;1"].getService(Ci.nsIParserUtils);
  588. let contentFragment = parserUtils.parseFragment(article.content,
  589. Ci.nsIParserUtils.SanitizerDropForms | Ci.nsIParserUtils.SanitizerAllowStyle,
  590. false, articleUri, this._contentElement);
  591. this._contentElement.innerHTML = "";
  592. this._contentElement.appendChild(contentFragment);
  593. this._fixLocalLinks();
  594. this._maybeSetTextDirection(article);
  595. this._foundLanguage(article.language);
  596. this._contentElement.style.display = "block";
  597. this._updateImageMargins();
  598. this._requestFavicon();
  599. this._doc.body.classList.add("loaded");
  600. this._goToReference(articleUri.ref);
  601. Services.obs.notifyObservers(this._win, "AboutReader:Ready", "");
  602. this._doc.dispatchEvent(
  603. new this._win.CustomEvent("AboutReaderContentReady", { bubbles: true, cancelable: false }));
  604. },
  605. _hideContent() {
  606. this._headerElement.style.display = "none";
  607. this._contentElement.style.display = "none";
  608. },
  609. _showProgressDelayed() {
  610. this._win.setTimeout(() => {
  611. // No need to show progress if the article has been loaded,
  612. // if the window has been unloaded, or if there was an error
  613. // trying to load the article.
  614. if (this._article || this._windowUnloaded || this._error) {
  615. return;
  616. }
  617. this._headerElement.style.display = "none";
  618. this._contentElement.style.display = "none";
  619. this._messageElement.textContent = gStrings.GetStringFromName("aboutReader.loading2");
  620. this._messageElement.style.display = "block";
  621. }, 300);
  622. },
  623. /**
  624. * Returns the original article URL for this about:reader view.
  625. */
  626. _getOriginalUrl(win) {
  627. let url = win ? win.location.href : this._win.location.href;
  628. return ReaderMode.getOriginalUrl(url) || url;
  629. },
  630. _setupSegmentedButton(id, options, initialValue, callback) {
  631. let doc = this._doc;
  632. let segmentedButton = doc.getElementsByClassName(id)[0];
  633. for (let i = 0; i < options.length; i++) {
  634. let option = options[i];
  635. let item = doc.createElement("button");
  636. // Put the name in a div so that Android can hide it.
  637. let div = doc.createElement("div");
  638. div.textContent = option.name;
  639. div.classList.add("name");
  640. item.appendChild(div);
  641. if (option.itemClass !== undefined)
  642. item.classList.add(option.itemClass);
  643. if (option.description !== undefined) {
  644. let description = doc.createElement("div");
  645. description.textContent = option.description;
  646. description.classList.add("description");
  647. item.appendChild(description);
  648. }
  649. segmentedButton.appendChild(item);
  650. item.addEventListener("click", function(aEvent) {
  651. if (!aEvent.isTrusted)
  652. return;
  653. aEvent.stopPropagation();
  654. let items = segmentedButton.children;
  655. for (let j = items.length - 1; j >= 0; j--) {
  656. items[j].classList.remove("selected");
  657. }
  658. item.classList.add("selected");
  659. callback(option.value);
  660. }, true);
  661. if (option.value === initialValue)
  662. item.classList.add("selected");
  663. }
  664. },
  665. _setupButton(id, callback, titleEntity, textEntity) {
  666. if (titleEntity) {
  667. this._setButtonTip(id, titleEntity);
  668. }
  669. let button = this._doc.getElementsByClassName(id)[0];
  670. if (textEntity) {
  671. button.textContent = gStrings.GetStringFromName(textEntity);
  672. }
  673. button.removeAttribute("hidden");
  674. button.addEventListener("click", function(aEvent) {
  675. if (!aEvent.isTrusted)
  676. return;
  677. aEvent.stopPropagation();
  678. let btn = aEvent.target;
  679. callback(btn);
  680. }, true);
  681. },
  682. /**
  683. * Sets a toolTip for a button. Performed at initial button setup
  684. * and dynamically as button state changes.
  685. * @param Localizable string providing UI element usage tip.
  686. */
  687. _setButtonTip(id, titleEntity) {
  688. let button = this._doc.getElementsByClassName(id)[0];
  689. button.setAttribute("title", gStrings.GetStringFromName(titleEntity));
  690. },
  691. _setupStyleDropdown() {
  692. let dropdownToggle = this._doc.querySelector(".style-dropdown .dropdown-toggle");
  693. dropdownToggle.setAttribute("title", gStrings.GetStringFromName("aboutReader.toolbar.typeControls"));
  694. },
  695. _updatePopupPosition(dropdown) {
  696. let dropdownToggle = dropdown.querySelector(".dropdown-toggle");
  697. let dropdownPopup = dropdown.querySelector(".dropdown-popup");
  698. let toggleHeight = dropdownToggle.offsetHeight;
  699. let toggleTop = dropdownToggle.offsetTop;
  700. let popupTop = toggleTop - toggleHeight / 2;
  701. dropdownPopup.style.top = popupTop + "px";
  702. },
  703. _toggleDropdownClicked(event) {
  704. let dropdown = event.target.closest(".dropdown");
  705. if (!dropdown)
  706. return;
  707. event.stopPropagation();
  708. if (dropdown.classList.contains("open")) {
  709. this._closeDropdowns();
  710. } else {
  711. this._openDropdown(dropdown);
  712. if (this._isToolbarVertical) {
  713. this._updatePopupPosition(dropdown);
  714. }
  715. }
  716. },
  717. /*
  718. * If the ReaderView banner font-dropdown is closed, open it.
  719. */
  720. _openDropdown(dropdown) {
  721. if (dropdown.classList.contains("open")) {
  722. return;
  723. }
  724. this._closeDropdowns();
  725. dropdown.classList.add("open");
  726. },
  727. /*
  728. * If the ReaderView has open dropdowns, close them. If we are closing the
  729. * dropdowns because the page is scrolling, allow popups to stay open with
  730. * the keep-open class.
  731. */
  732. _closeDropdowns(scrolling) {
  733. let selector = ".dropdown.open";
  734. if (scrolling) {
  735. selector += ":not(.keep-open)";
  736. }
  737. let openDropdowns = this._doc.querySelectorAll(selector);
  738. for (let dropdown of openDropdowns) {
  739. dropdown.classList.remove("open");
  740. }
  741. },
  742. /*
  743. * Scroll reader view to a reference
  744. */
  745. _goToReference(ref) {
  746. if (ref) {
  747. this._win.location.hash = ref;
  748. }
  749. }
  750. };