toolbar.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /* Copyright 2016 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import {
  16. animationStarted,
  17. DEFAULT_SCALE,
  18. DEFAULT_SCALE_VALUE,
  19. docStyle,
  20. MAX_SCALE,
  21. MIN_SCALE,
  22. noContextMenuHandler,
  23. } from "./ui_utils.js";
  24. import { AnnotationEditorType } from "pdfjs-lib";
  25. const PAGE_NUMBER_LOADING_INDICATOR = "visiblePageIsLoading";
  26. /**
  27. * @typedef {Object} ToolbarOptions
  28. * @property {HTMLDivElement} container - Container for the secondary toolbar.
  29. * @property {HTMLSpanElement} numPages - Label that contains number of pages.
  30. * @property {HTMLInputElement} pageNumber - Control for display and user input
  31. * of the current page number.
  32. * @property {HTMLSelectElement} scaleSelect - Scale selection control.
  33. * Its width is adjusted, when necessary, on UI localization.
  34. * @property {HTMLOptionElement} customScaleOption - The item used to display
  35. * a non-predefined scale.
  36. * @property {HTMLButtonElement} previous - Button to go to the previous page.
  37. * @property {HTMLButtonElement} next - Button to go to the next page.
  38. * @property {HTMLButtonElement} zoomIn - Button to zoom in the pages.
  39. * @property {HTMLButtonElement} zoomOut - Button to zoom out the pages.
  40. * @property {HTMLButtonElement} viewFind - Button to open find bar.
  41. * @property {HTMLButtonElement} openFile - Button to open a new document.
  42. * @property {HTMLButtonElement} editorFreeTextButton - Button to switch to
  43. * FreeText editing.
  44. * @property {HTMLButtonElement} download - Button to download the document.
  45. */
  46. class Toolbar {
  47. #wasLocalized = false;
  48. /**
  49. * @param {ToolbarOptions} options
  50. * @param {EventBus} eventBus
  51. * @param {IL10n} l10n - Localization service.
  52. */
  53. constructor(options, eventBus, l10n) {
  54. this.toolbar = options.container;
  55. this.eventBus = eventBus;
  56. this.l10n = l10n;
  57. this.buttons = [
  58. { element: options.previous, eventName: "previouspage" },
  59. { element: options.next, eventName: "nextpage" },
  60. { element: options.zoomIn, eventName: "zoomin" },
  61. { element: options.zoomOut, eventName: "zoomout" },
  62. { element: options.print, eventName: "print" },
  63. { element: options.download, eventName: "download" },
  64. {
  65. element: options.editorFreeTextButton,
  66. eventName: "switchannotationeditormode",
  67. eventDetails: {
  68. get mode() {
  69. const { classList } = options.editorFreeTextButton;
  70. return classList.contains("toggled")
  71. ? AnnotationEditorType.NONE
  72. : AnnotationEditorType.FREETEXT;
  73. },
  74. },
  75. },
  76. {
  77. element: options.editorInkButton,
  78. eventName: "switchannotationeditormode",
  79. eventDetails: {
  80. get mode() {
  81. const { classList } = options.editorInkButton;
  82. return classList.contains("toggled")
  83. ? AnnotationEditorType.NONE
  84. : AnnotationEditorType.INK;
  85. },
  86. },
  87. },
  88. ];
  89. if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
  90. this.buttons.push({ element: options.openFile, eventName: "openfile" });
  91. }
  92. this.items = {
  93. numPages: options.numPages,
  94. pageNumber: options.pageNumber,
  95. scaleSelect: options.scaleSelect,
  96. customScaleOption: options.customScaleOption,
  97. previous: options.previous,
  98. next: options.next,
  99. zoomIn: options.zoomIn,
  100. zoomOut: options.zoomOut,
  101. };
  102. // Bind the event listeners for click and various other actions.
  103. this.#bindListeners(options);
  104. this.reset();
  105. }
  106. setPageNumber(pageNumber, pageLabel) {
  107. this.pageNumber = pageNumber;
  108. this.pageLabel = pageLabel;
  109. this.#updateUIState(false);
  110. }
  111. setPagesCount(pagesCount, hasPageLabels) {
  112. this.pagesCount = pagesCount;
  113. this.hasPageLabels = hasPageLabels;
  114. this.#updateUIState(true);
  115. }
  116. setPageScale(pageScaleValue, pageScale) {
  117. this.pageScaleValue = (pageScaleValue || pageScale).toString();
  118. this.pageScale = pageScale;
  119. this.#updateUIState(false);
  120. }
  121. reset() {
  122. this.pageNumber = 0;
  123. this.pageLabel = null;
  124. this.hasPageLabels = false;
  125. this.pagesCount = 0;
  126. this.pageScaleValue = DEFAULT_SCALE_VALUE;
  127. this.pageScale = DEFAULT_SCALE;
  128. this.#updateUIState(true);
  129. this.updateLoadingIndicatorState();
  130. // Reset the Editor buttons too, since they're document specific.
  131. this.eventBus.dispatch("toolbarreset", { source: this });
  132. }
  133. #bindListeners(options) {
  134. const { pageNumber, scaleSelect } = this.items;
  135. const self = this;
  136. // The buttons within the toolbar.
  137. for (const { element, eventName, eventDetails } of this.buttons) {
  138. element.addEventListener("click", evt => {
  139. if (eventName !== null) {
  140. const details = { source: this };
  141. if (eventDetails) {
  142. for (const property in eventDetails) {
  143. details[property] = eventDetails[property];
  144. }
  145. }
  146. this.eventBus.dispatch(eventName, details);
  147. }
  148. });
  149. }
  150. // The non-button elements within the toolbar.
  151. pageNumber.addEventListener("click", function () {
  152. this.select();
  153. });
  154. pageNumber.addEventListener("change", function () {
  155. self.eventBus.dispatch("pagenumberchanged", {
  156. source: self,
  157. value: this.value,
  158. });
  159. });
  160. scaleSelect.addEventListener("change", function () {
  161. if (this.value === "custom") {
  162. return;
  163. }
  164. self.eventBus.dispatch("scalechanged", {
  165. source: self,
  166. value: this.value,
  167. });
  168. });
  169. // Here we depend on browsers dispatching the "click" event *after* the
  170. // "change" event, when the <select>-element changes.
  171. scaleSelect.addEventListener("click", function (evt) {
  172. const target = evt.target;
  173. // Remove focus when an <option>-element was *clicked*, to improve the UX
  174. // for mouse users (fixes bug 1300525 and issue 4923).
  175. if (
  176. this.value === self.pageScaleValue &&
  177. target.tagName.toUpperCase() === "OPTION"
  178. ) {
  179. this.blur();
  180. }
  181. });
  182. // Suppress context menus for some controls.
  183. scaleSelect.oncontextmenu = noContextMenuHandler;
  184. this.eventBus._on("localized", () => {
  185. this.#wasLocalized = true;
  186. this.#adjustScaleWidth();
  187. this.#updateUIState(true);
  188. });
  189. this.#bindEditorToolsListener(options);
  190. }
  191. #bindEditorToolsListener({
  192. editorFreeTextButton,
  193. editorFreeTextParamsToolbar,
  194. editorInkButton,
  195. editorInkParamsToolbar,
  196. }) {
  197. const editorModeChanged = (evt, disableButtons = false) => {
  198. const editorButtons = [
  199. {
  200. mode: AnnotationEditorType.FREETEXT,
  201. button: editorFreeTextButton,
  202. toolbar: editorFreeTextParamsToolbar,
  203. },
  204. {
  205. mode: AnnotationEditorType.INK,
  206. button: editorInkButton,
  207. toolbar: editorInkParamsToolbar,
  208. },
  209. ];
  210. for (const { mode, button, toolbar } of editorButtons) {
  211. const checked = mode === evt.mode;
  212. button.classList.toggle("toggled", checked);
  213. button.setAttribute("aria-checked", checked);
  214. button.disabled = disableButtons;
  215. toolbar?.classList.toggle("hidden", !checked);
  216. }
  217. };
  218. this.eventBus._on("annotationeditormodechanged", editorModeChanged);
  219. this.eventBus._on("toolbarreset", evt => {
  220. if (evt.source === this) {
  221. editorModeChanged(
  222. { mode: AnnotationEditorType.NONE },
  223. /* disableButtons = */ true
  224. );
  225. }
  226. });
  227. }
  228. #updateUIState(resetNumPages = false) {
  229. if (!this.#wasLocalized) {
  230. // Don't update the UI state until we localize the toolbar.
  231. return;
  232. }
  233. const { pageNumber, pagesCount, pageScaleValue, pageScale, items } = this;
  234. if (resetNumPages) {
  235. if (this.hasPageLabels) {
  236. items.pageNumber.type = "text";
  237. } else {
  238. items.pageNumber.type = "number";
  239. this.l10n.get("of_pages", { pagesCount }).then(msg => {
  240. items.numPages.textContent = msg;
  241. });
  242. }
  243. items.pageNumber.max = pagesCount;
  244. }
  245. if (this.hasPageLabels) {
  246. items.pageNumber.value = this.pageLabel;
  247. this.l10n.get("page_of_pages", { pageNumber, pagesCount }).then(msg => {
  248. items.numPages.textContent = msg;
  249. });
  250. } else {
  251. items.pageNumber.value = pageNumber;
  252. }
  253. items.previous.disabled = pageNumber <= 1;
  254. items.next.disabled = pageNumber >= pagesCount;
  255. items.zoomOut.disabled = pageScale <= MIN_SCALE;
  256. items.zoomIn.disabled = pageScale >= MAX_SCALE;
  257. this.l10n
  258. .get("page_scale_percent", { scale: Math.round(pageScale * 10000) / 100 })
  259. .then(msg => {
  260. let predefinedValueFound = false;
  261. for (const option of items.scaleSelect.options) {
  262. if (option.value !== pageScaleValue) {
  263. option.selected = false;
  264. continue;
  265. }
  266. option.selected = true;
  267. predefinedValueFound = true;
  268. }
  269. if (!predefinedValueFound) {
  270. items.customScaleOption.textContent = msg;
  271. items.customScaleOption.selected = true;
  272. }
  273. });
  274. }
  275. updateLoadingIndicatorState(loading = false) {
  276. const { pageNumber } = this.items;
  277. pageNumber.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading);
  278. }
  279. /**
  280. * Increase the width of the zoom dropdown DOM element if, and only if, it's
  281. * too narrow to fit the *longest* of the localized strings.
  282. */
  283. async #adjustScaleWidth() {
  284. const { items, l10n } = this;
  285. const predefinedValuesPromise = Promise.all([
  286. l10n.get("page_scale_auto"),
  287. l10n.get("page_scale_actual"),
  288. l10n.get("page_scale_fit"),
  289. l10n.get("page_scale_width"),
  290. ]);
  291. await animationStarted;
  292. const style = getComputedStyle(items.scaleSelect);
  293. const scaleSelectWidth = parseFloat(
  294. style.getPropertyValue("--scale-select-width")
  295. );
  296. // The temporary canvas is used to measure text length in the DOM.
  297. const canvas = document.createElement("canvas");
  298. const ctx = canvas.getContext("2d", { alpha: false });
  299. ctx.font = `${style.fontSize} ${style.fontFamily}`;
  300. let maxWidth = 0;
  301. for (const predefinedValue of await predefinedValuesPromise) {
  302. const { width } = ctx.measureText(predefinedValue);
  303. if (width > maxWidth) {
  304. maxWidth = width;
  305. }
  306. }
  307. // Account for the icon width, and ensure that there's always some spacing
  308. // between the text and the icon.
  309. maxWidth += 0.3 * scaleSelectWidth;
  310. if (maxWidth > scaleSelectWidth) {
  311. docStyle.setProperty("--scale-select-width", `${maxWidth}px`);
  312. }
  313. // Zeroing the width and height cause Firefox to release graphics resources
  314. // immediately, which can greatly reduce memory consumption.
  315. canvas.width = 0;
  316. canvas.height = 0;
  317. }
  318. }
  319. export { Toolbar };