2
0

ui_utils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2017 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. 'use strict';
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.waitOnEventOrTimeout = exports.WaitOnType = exports.localized = exports.animationStarted = exports.normalizeWheelEventDelta = exports.binarySearchFirstItem = exports.watchScroll = exports.scrollIntoView = exports.getOutputScale = exports.approximateFraction = exports.roundToDivide = exports.getVisibleElements = exports.parseQueryString = exports.noContextMenuHandler = exports.getPDFFileNameFromURL = exports.ProgressBar = exports.EventBus = exports.NullL10n = exports.mozL10n = exports.TextLayerMode = exports.RendererType = exports.PresentationModeState = exports.cloneObj = exports.isFileSchema = exports.isValidRotation = exports.VERTICAL_PADDING = exports.SCROLLBAR_PADDING = exports.MAX_AUTO_SCALE = exports.UNKNOWN_SCALE = exports.MAX_SCALE = exports.MIN_SCALE = exports.DEFAULT_SCALE = exports.DEFAULT_SCALE_VALUE = exports.CSS_UNITS = undefined;
  27. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  28. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  29. var _pdf = require('../pdf');
  30. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31. var CSS_UNITS = 96.0 / 72.0;
  32. var DEFAULT_SCALE_VALUE = 'auto';
  33. var DEFAULT_SCALE = 1.0;
  34. var MIN_SCALE = 0.10;
  35. var MAX_SCALE = 10.0;
  36. var UNKNOWN_SCALE = 0;
  37. var MAX_AUTO_SCALE = 1.25;
  38. var SCROLLBAR_PADDING = 40;
  39. var VERTICAL_PADDING = 5;
  40. var PresentationModeState = {
  41. UNKNOWN: 0,
  42. NORMAL: 1,
  43. CHANGING: 2,
  44. FULLSCREEN: 3
  45. };
  46. var RendererType = {
  47. CANVAS: 'canvas',
  48. SVG: 'svg'
  49. };
  50. var TextLayerMode = {
  51. DISABLE: 0,
  52. ENABLE: 1,
  53. ENABLE_ENHANCE: 2
  54. };
  55. function formatL10nValue(text, args) {
  56. if (!args) {
  57. return text;
  58. }
  59. return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function (all, name) {
  60. return name in args ? args[name] : '{{' + name + '}}';
  61. });
  62. }
  63. var NullL10n = {
  64. getDirection: function getDirection() {
  65. return Promise.resolve('ltr');
  66. },
  67. get: function get(property, args, fallback) {
  68. return Promise.resolve(formatL10nValue(fallback, args));
  69. },
  70. translate: function translate(element) {
  71. return Promise.resolve();
  72. }
  73. };
  74. _pdf.PDFJS.useOnlyCssZoom = _pdf.PDFJS.useOnlyCssZoom === undefined ? false : _pdf.PDFJS.useOnlyCssZoom;
  75. _pdf.PDFJS.maxCanvasPixels = _pdf.PDFJS.maxCanvasPixels === undefined ? 16777216 : _pdf.PDFJS.maxCanvasPixels;
  76. _pdf.PDFJS.disableHistory = _pdf.PDFJS.disableHistory === undefined ? false : _pdf.PDFJS.disableHistory;
  77. {
  78. _pdf.PDFJS.locale = (_pdf.PDFJS.locale === undefined && typeof navigator !== 'undefined' ? navigator.language : _pdf.PDFJS.locale) || 'en-US';
  79. }
  80. function getOutputScale(ctx) {
  81. var devicePixelRatio = window.devicePixelRatio || 1;
  82. var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  83. var pixelRatio = devicePixelRatio / backingStoreRatio;
  84. return {
  85. sx: pixelRatio,
  86. sy: pixelRatio,
  87. scaled: pixelRatio !== 1
  88. };
  89. }
  90. function scrollIntoView(element, spot) {
  91. var skipOverflowHiddenElements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  92. var parent = element.offsetParent;
  93. if (!parent) {
  94. console.error('offsetParent is not set -- cannot scroll');
  95. return;
  96. }
  97. var offsetY = element.offsetTop + element.clientTop;
  98. var offsetX = element.offsetLeft + element.clientLeft;
  99. while (parent.clientHeight === parent.scrollHeight || skipOverflowHiddenElements && getComputedStyle(parent).overflow === 'hidden') {
  100. if (parent.dataset._scaleY) {
  101. offsetY /= parent.dataset._scaleY;
  102. offsetX /= parent.dataset._scaleX;
  103. }
  104. offsetY += parent.offsetTop;
  105. offsetX += parent.offsetLeft;
  106. parent = parent.offsetParent;
  107. if (!parent) {
  108. return;
  109. }
  110. }
  111. if (spot) {
  112. if (spot.top !== undefined) {
  113. offsetY += spot.top;
  114. }
  115. if (spot.left !== undefined) {
  116. offsetX += spot.left;
  117. parent.scrollLeft = offsetX;
  118. }
  119. }
  120. parent.scrollTop = offsetY;
  121. }
  122. function watchScroll(viewAreaElement, callback) {
  123. var debounceScroll = function debounceScroll(evt) {
  124. if (rAF) {
  125. return;
  126. }
  127. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  128. rAF = null;
  129. var currentY = viewAreaElement.scrollTop;
  130. var lastY = state.lastY;
  131. if (currentY !== lastY) {
  132. state.down = currentY > lastY;
  133. }
  134. state.lastY = currentY;
  135. callback(state);
  136. });
  137. };
  138. var state = {
  139. down: true,
  140. lastY: viewAreaElement.scrollTop,
  141. _eventHandler: debounceScroll
  142. };
  143. var rAF = null;
  144. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  145. return state;
  146. }
  147. function parseQueryString(query) {
  148. var parts = query.split('&');
  149. var params = Object.create(null);
  150. for (var i = 0, ii = parts.length; i < ii; ++i) {
  151. var param = parts[i].split('=');
  152. var key = param[0].toLowerCase();
  153. var value = param.length > 1 ? param[1] : null;
  154. params[decodeURIComponent(key)] = decodeURIComponent(value);
  155. }
  156. return params;
  157. }
  158. function binarySearchFirstItem(items, condition) {
  159. var minIndex = 0;
  160. var maxIndex = items.length - 1;
  161. if (items.length === 0 || !condition(items[maxIndex])) {
  162. return items.length;
  163. }
  164. if (condition(items[minIndex])) {
  165. return minIndex;
  166. }
  167. while (minIndex < maxIndex) {
  168. var currentIndex = minIndex + maxIndex >> 1;
  169. var currentItem = items[currentIndex];
  170. if (condition(currentItem)) {
  171. maxIndex = currentIndex;
  172. } else {
  173. minIndex = currentIndex + 1;
  174. }
  175. }
  176. return minIndex;
  177. }
  178. function approximateFraction(x) {
  179. if (Math.floor(x) === x) {
  180. return [x, 1];
  181. }
  182. var xinv = 1 / x;
  183. var limit = 8;
  184. if (xinv > limit) {
  185. return [1, limit];
  186. } else if (Math.floor(xinv) === xinv) {
  187. return [1, xinv];
  188. }
  189. var x_ = x > 1 ? xinv : x;
  190. var a = 0,
  191. b = 1,
  192. c = 1,
  193. d = 1;
  194. while (true) {
  195. var p = a + c,
  196. q = b + d;
  197. if (q > limit) {
  198. break;
  199. }
  200. if (x_ <= p / q) {
  201. c = p;
  202. d = q;
  203. } else {
  204. a = p;
  205. b = q;
  206. }
  207. }
  208. var result = void 0;
  209. if (x_ - a / b < c / d - x_) {
  210. result = x_ === x ? [a, b] : [b, a];
  211. } else {
  212. result = x_ === x ? [c, d] : [d, c];
  213. }
  214. return result;
  215. }
  216. function roundToDivide(x, div) {
  217. var r = x % div;
  218. return r === 0 ? x : Math.round(x - r + div);
  219. }
  220. function getVisibleElements(scrollEl, views) {
  221. var sortByVisibility = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  222. var top = scrollEl.scrollTop,
  223. bottom = top + scrollEl.clientHeight;
  224. var left = scrollEl.scrollLeft,
  225. right = left + scrollEl.clientWidth;
  226. function isElementBottomBelowViewTop(view) {
  227. var element = view.div;
  228. var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  229. return elementBottom > top;
  230. }
  231. var visible = [],
  232. view = void 0,
  233. element = void 0;
  234. var currentHeight = void 0,
  235. viewHeight = void 0,
  236. hiddenHeight = void 0,
  237. percentHeight = void 0;
  238. var currentWidth = void 0,
  239. viewWidth = void 0;
  240. var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
  241. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  242. view = views[i];
  243. element = view.div;
  244. currentHeight = element.offsetTop + element.clientTop;
  245. viewHeight = element.clientHeight;
  246. if (currentHeight > bottom) {
  247. break;
  248. }
  249. currentWidth = element.offsetLeft + element.clientLeft;
  250. viewWidth = element.clientWidth;
  251. if (currentWidth + viewWidth < left || currentWidth > right) {
  252. continue;
  253. }
  254. hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
  255. percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
  256. visible.push({
  257. id: view.id,
  258. x: currentWidth,
  259. y: currentHeight,
  260. view: view,
  261. percent: percentHeight
  262. });
  263. }
  264. var first = visible[0];
  265. var last = visible[visible.length - 1];
  266. if (sortByVisibility) {
  267. visible.sort(function (a, b) {
  268. var pc = a.percent - b.percent;
  269. if (Math.abs(pc) > 0.001) {
  270. return -pc;
  271. }
  272. return a.id - b.id;
  273. });
  274. }
  275. return {
  276. first: first,
  277. last: last,
  278. views: visible
  279. };
  280. }
  281. function noContextMenuHandler(evt) {
  282. evt.preventDefault();
  283. }
  284. function isFileSchema(url) {
  285. var i = 0,
  286. ii = url.length;
  287. while (i < ii && url[i].trim() === '') {
  288. i++;
  289. }
  290. return url.substr(i, 7).toLowerCase() === 'file://';
  291. }
  292. function isDataSchema(url) {
  293. var i = 0,
  294. ii = url.length;
  295. while (i < ii && url[i].trim() === '') {
  296. i++;
  297. }
  298. return url.substr(i, 5).toLowerCase() === 'data:';
  299. }
  300. function getPDFFileNameFromURL(url) {
  301. var defaultFilename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'document.pdf';
  302. if (isDataSchema(url)) {
  303. console.warn('getPDFFileNameFromURL: ' + 'ignoring "data:" URL for performance reasons.');
  304. return defaultFilename;
  305. }
  306. var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  307. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  308. var splitURI = reURI.exec(url);
  309. var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  310. if (suggestedFilename) {
  311. suggestedFilename = suggestedFilename[0];
  312. if (suggestedFilename.includes('%')) {
  313. try {
  314. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  315. } catch (ex) {}
  316. }
  317. }
  318. return suggestedFilename || defaultFilename;
  319. }
  320. function normalizeWheelEventDelta(evt) {
  321. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  322. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  323. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  324. delta = -delta;
  325. }
  326. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  327. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  328. var MOUSE_PIXELS_PER_LINE = 30;
  329. var MOUSE_LINES_PER_PAGE = 30;
  330. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  331. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  332. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  333. delta /= MOUSE_LINES_PER_PAGE;
  334. }
  335. return delta;
  336. }
  337. function isValidRotation(angle) {
  338. return Number.isInteger(angle) && angle % 90 === 0;
  339. }
  340. function cloneObj(obj) {
  341. var result = Object.create(null);
  342. for (var i in obj) {
  343. if (Object.prototype.hasOwnProperty.call(obj, i)) {
  344. result[i] = obj[i];
  345. }
  346. }
  347. return result;
  348. }
  349. var WaitOnType = {
  350. EVENT: 'event',
  351. TIMEOUT: 'timeout'
  352. };
  353. function waitOnEventOrTimeout(_ref) {
  354. var target = _ref.target,
  355. name = _ref.name,
  356. _ref$delay = _ref.delay,
  357. delay = _ref$delay === undefined ? 0 : _ref$delay;
  358. if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object' || !(name && typeof name === 'string') || !(Number.isInteger(delay) && delay >= 0)) {
  359. return Promise.reject(new Error('waitOnEventOrTimeout - invalid paramaters.'));
  360. }
  361. var capability = (0, _pdf.createPromiseCapability)();
  362. function handler(type) {
  363. if (target instanceof EventBus) {
  364. target.off(name, eventHandler);
  365. } else {
  366. target.removeEventListener(name, eventHandler);
  367. }
  368. if (timeout) {
  369. clearTimeout(timeout);
  370. }
  371. capability.resolve(type);
  372. }
  373. var eventHandler = handler.bind(null, WaitOnType.EVENT);
  374. if (target instanceof EventBus) {
  375. target.on(name, eventHandler);
  376. } else {
  377. target.addEventListener(name, eventHandler);
  378. }
  379. var timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT);
  380. var timeout = setTimeout(timeoutHandler, delay);
  381. return capability.promise;
  382. }
  383. var animationStarted = new Promise(function (resolve) {
  384. window.requestAnimationFrame(resolve);
  385. });
  386. var mozL10n = void 0;
  387. var localized = Promise.resolve();
  388. var EventBus = function () {
  389. function EventBus() {
  390. _classCallCheck(this, EventBus);
  391. this._listeners = Object.create(null);
  392. }
  393. _createClass(EventBus, [{
  394. key: 'on',
  395. value: function on(eventName, listener) {
  396. var eventListeners = this._listeners[eventName];
  397. if (!eventListeners) {
  398. eventListeners = [];
  399. this._listeners[eventName] = eventListeners;
  400. }
  401. eventListeners.push(listener);
  402. }
  403. }, {
  404. key: 'off',
  405. value: function off(eventName, listener) {
  406. var eventListeners = this._listeners[eventName];
  407. var i = void 0;
  408. if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
  409. return;
  410. }
  411. eventListeners.splice(i, 1);
  412. }
  413. }, {
  414. key: 'dispatch',
  415. value: function dispatch(eventName) {
  416. var eventListeners = this._listeners[eventName];
  417. if (!eventListeners || eventListeners.length === 0) {
  418. return;
  419. }
  420. var args = Array.prototype.slice.call(arguments, 1);
  421. eventListeners.slice(0).forEach(function (listener) {
  422. listener.apply(null, args);
  423. });
  424. }
  425. }]);
  426. return EventBus;
  427. }();
  428. function clamp(v, min, max) {
  429. return Math.min(Math.max(v, min), max);
  430. }
  431. var ProgressBar = function () {
  432. function ProgressBar(id) {
  433. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  434. height = _ref2.height,
  435. width = _ref2.width,
  436. units = _ref2.units;
  437. _classCallCheck(this, ProgressBar);
  438. this.visible = true;
  439. this.div = document.querySelector(id + ' .progress');
  440. this.bar = this.div.parentNode;
  441. this.height = height || 100;
  442. this.width = width || 100;
  443. this.units = units || '%';
  444. this.div.style.height = this.height + this.units;
  445. this.percent = 0;
  446. }
  447. _createClass(ProgressBar, [{
  448. key: '_updateBar',
  449. value: function _updateBar() {
  450. if (this._indeterminate) {
  451. this.div.classList.add('indeterminate');
  452. this.div.style.width = this.width + this.units;
  453. return;
  454. }
  455. this.div.classList.remove('indeterminate');
  456. var progressSize = this.width * this._percent / 100;
  457. this.div.style.width = progressSize + this.units;
  458. }
  459. }, {
  460. key: 'setWidth',
  461. value: function setWidth(viewer) {
  462. if (!viewer) {
  463. return;
  464. }
  465. var container = viewer.parentNode;
  466. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  467. if (scrollbarWidth > 0) {
  468. this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
  469. }
  470. }
  471. }, {
  472. key: 'hide',
  473. value: function hide() {
  474. if (!this.visible) {
  475. return;
  476. }
  477. this.visible = false;
  478. this.bar.classList.add('hidden');
  479. document.body.classList.remove('loadingInProgress');
  480. }
  481. }, {
  482. key: 'show',
  483. value: function show() {
  484. if (this.visible) {
  485. return;
  486. }
  487. this.visible = true;
  488. document.body.classList.add('loadingInProgress');
  489. this.bar.classList.remove('hidden');
  490. }
  491. }, {
  492. key: 'percent',
  493. get: function get() {
  494. return this._percent;
  495. },
  496. set: function set(val) {
  497. this._indeterminate = isNaN(val);
  498. this._percent = clamp(val, 0, 100);
  499. this._updateBar();
  500. }
  501. }]);
  502. return ProgressBar;
  503. }();
  504. exports.CSS_UNITS = CSS_UNITS;
  505. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  506. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  507. exports.MIN_SCALE = MIN_SCALE;
  508. exports.MAX_SCALE = MAX_SCALE;
  509. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  510. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  511. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  512. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  513. exports.isValidRotation = isValidRotation;
  514. exports.isFileSchema = isFileSchema;
  515. exports.cloneObj = cloneObj;
  516. exports.PresentationModeState = PresentationModeState;
  517. exports.RendererType = RendererType;
  518. exports.TextLayerMode = TextLayerMode;
  519. exports.mozL10n = mozL10n;
  520. exports.NullL10n = NullL10n;
  521. exports.EventBus = EventBus;
  522. exports.ProgressBar = ProgressBar;
  523. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  524. exports.noContextMenuHandler = noContextMenuHandler;
  525. exports.parseQueryString = parseQueryString;
  526. exports.getVisibleElements = getVisibleElements;
  527. exports.roundToDivide = roundToDivide;
  528. exports.approximateFraction = approximateFraction;
  529. exports.getOutputScale = getOutputScale;
  530. exports.scrollIntoView = scrollIntoView;
  531. exports.watchScroll = watchScroll;
  532. exports.binarySearchFirstItem = binarySearchFirstItem;
  533. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  534. exports.animationStarted = animationStarted;
  535. exports.localized = localized;
  536. exports.WaitOnType = WaitOnType;
  537. exports.waitOnEventOrTimeout = waitOnEventOrTimeout;