ui_utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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.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.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. function getOutputScale(ctx) {
  75. var devicePixelRatio = window.devicePixelRatio || 1;
  76. var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  77. var pixelRatio = devicePixelRatio / backingStoreRatio;
  78. return {
  79. sx: pixelRatio,
  80. sy: pixelRatio,
  81. scaled: pixelRatio !== 1
  82. };
  83. }
  84. function scrollIntoView(element, spot) {
  85. var skipOverflowHiddenElements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  86. var parent = element.offsetParent;
  87. if (!parent) {
  88. console.error('offsetParent is not set -- cannot scroll');
  89. return;
  90. }
  91. var offsetY = element.offsetTop + element.clientTop;
  92. var offsetX = element.offsetLeft + element.clientLeft;
  93. while (parent.clientHeight === parent.scrollHeight || skipOverflowHiddenElements && getComputedStyle(parent).overflow === 'hidden') {
  94. if (parent.dataset._scaleY) {
  95. offsetY /= parent.dataset._scaleY;
  96. offsetX /= parent.dataset._scaleX;
  97. }
  98. offsetY += parent.offsetTop;
  99. offsetX += parent.offsetLeft;
  100. parent = parent.offsetParent;
  101. if (!parent) {
  102. return;
  103. }
  104. }
  105. if (spot) {
  106. if (spot.top !== undefined) {
  107. offsetY += spot.top;
  108. }
  109. if (spot.left !== undefined) {
  110. offsetX += spot.left;
  111. parent.scrollLeft = offsetX;
  112. }
  113. }
  114. parent.scrollTop = offsetY;
  115. }
  116. function watchScroll(viewAreaElement, callback) {
  117. var debounceScroll = function debounceScroll(evt) {
  118. if (rAF) {
  119. return;
  120. }
  121. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  122. rAF = null;
  123. var currentY = viewAreaElement.scrollTop;
  124. var lastY = state.lastY;
  125. if (currentY !== lastY) {
  126. state.down = currentY > lastY;
  127. }
  128. state.lastY = currentY;
  129. callback(state);
  130. });
  131. };
  132. var state = {
  133. down: true,
  134. lastY: viewAreaElement.scrollTop,
  135. _eventHandler: debounceScroll
  136. };
  137. var rAF = null;
  138. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  139. return state;
  140. }
  141. function parseQueryString(query) {
  142. var parts = query.split('&');
  143. var params = Object.create(null);
  144. for (var i = 0, ii = parts.length; i < ii; ++i) {
  145. var param = parts[i].split('=');
  146. var key = param[0].toLowerCase();
  147. var value = param.length > 1 ? param[1] : null;
  148. params[decodeURIComponent(key)] = decodeURIComponent(value);
  149. }
  150. return params;
  151. }
  152. function binarySearchFirstItem(items, condition) {
  153. var minIndex = 0;
  154. var maxIndex = items.length - 1;
  155. if (items.length === 0 || !condition(items[maxIndex])) {
  156. return items.length;
  157. }
  158. if (condition(items[minIndex])) {
  159. return minIndex;
  160. }
  161. while (minIndex < maxIndex) {
  162. var currentIndex = minIndex + maxIndex >> 1;
  163. var currentItem = items[currentIndex];
  164. if (condition(currentItem)) {
  165. maxIndex = currentIndex;
  166. } else {
  167. minIndex = currentIndex + 1;
  168. }
  169. }
  170. return minIndex;
  171. }
  172. function approximateFraction(x) {
  173. if (Math.floor(x) === x) {
  174. return [x, 1];
  175. }
  176. var xinv = 1 / x;
  177. var limit = 8;
  178. if (xinv > limit) {
  179. return [1, limit];
  180. } else if (Math.floor(xinv) === xinv) {
  181. return [1, xinv];
  182. }
  183. var x_ = x > 1 ? xinv : x;
  184. var a = 0,
  185. b = 1,
  186. c = 1,
  187. d = 1;
  188. while (true) {
  189. var p = a + c,
  190. q = b + d;
  191. if (q > limit) {
  192. break;
  193. }
  194. if (x_ <= p / q) {
  195. c = p;
  196. d = q;
  197. } else {
  198. a = p;
  199. b = q;
  200. }
  201. }
  202. var result = void 0;
  203. if (x_ - a / b < c / d - x_) {
  204. result = x_ === x ? [a, b] : [b, a];
  205. } else {
  206. result = x_ === x ? [c, d] : [d, c];
  207. }
  208. return result;
  209. }
  210. function roundToDivide(x, div) {
  211. var r = x % div;
  212. return r === 0 ? x : Math.round(x - r + div);
  213. }
  214. function getVisibleElements(scrollEl, views) {
  215. var sortByVisibility = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  216. var top = scrollEl.scrollTop,
  217. bottom = top + scrollEl.clientHeight;
  218. var left = scrollEl.scrollLeft,
  219. right = left + scrollEl.clientWidth;
  220. function isElementBottomBelowViewTop(view) {
  221. var element = view.div;
  222. var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  223. return elementBottom > top;
  224. }
  225. var visible = [],
  226. view = void 0,
  227. element = void 0;
  228. var currentHeight = void 0,
  229. viewHeight = void 0,
  230. hiddenHeight = void 0,
  231. percentHeight = void 0;
  232. var currentWidth = void 0,
  233. viewWidth = void 0;
  234. var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
  235. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  236. view = views[i];
  237. element = view.div;
  238. currentHeight = element.offsetTop + element.clientTop;
  239. viewHeight = element.clientHeight;
  240. if (currentHeight > bottom) {
  241. break;
  242. }
  243. currentWidth = element.offsetLeft + element.clientLeft;
  244. viewWidth = element.clientWidth;
  245. if (currentWidth + viewWidth < left || currentWidth > right) {
  246. continue;
  247. }
  248. hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
  249. percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
  250. visible.push({
  251. id: view.id,
  252. x: currentWidth,
  253. y: currentHeight,
  254. view: view,
  255. percent: percentHeight
  256. });
  257. }
  258. var first = visible[0];
  259. var last = visible[visible.length - 1];
  260. if (sortByVisibility) {
  261. visible.sort(function (a, b) {
  262. var pc = a.percent - b.percent;
  263. if (Math.abs(pc) > 0.001) {
  264. return -pc;
  265. }
  266. return a.id - b.id;
  267. });
  268. }
  269. return {
  270. first: first,
  271. last: last,
  272. views: visible
  273. };
  274. }
  275. function noContextMenuHandler(evt) {
  276. evt.preventDefault();
  277. }
  278. function isFileSchema(url) {
  279. var i = 0,
  280. ii = url.length;
  281. while (i < ii && url[i].trim() === '') {
  282. i++;
  283. }
  284. return url.substr(i, 7).toLowerCase() === 'file://';
  285. }
  286. function isDataSchema(url) {
  287. var i = 0,
  288. ii = url.length;
  289. while (i < ii && url[i].trim() === '') {
  290. i++;
  291. }
  292. return url.substr(i, 5).toLowerCase() === 'data:';
  293. }
  294. function getPDFFileNameFromURL(url) {
  295. var defaultFilename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'document.pdf';
  296. if (isDataSchema(url)) {
  297. console.warn('getPDFFileNameFromURL: ' + 'ignoring "data:" URL for performance reasons.');
  298. return defaultFilename;
  299. }
  300. var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  301. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  302. var splitURI = reURI.exec(url);
  303. var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  304. if (suggestedFilename) {
  305. suggestedFilename = suggestedFilename[0];
  306. if (suggestedFilename.includes('%')) {
  307. try {
  308. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  309. } catch (ex) {}
  310. }
  311. }
  312. return suggestedFilename || defaultFilename;
  313. }
  314. function normalizeWheelEventDelta(evt) {
  315. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  316. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  317. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  318. delta = -delta;
  319. }
  320. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  321. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  322. var MOUSE_PIXELS_PER_LINE = 30;
  323. var MOUSE_LINES_PER_PAGE = 30;
  324. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  325. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  326. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  327. delta /= MOUSE_LINES_PER_PAGE;
  328. }
  329. return delta;
  330. }
  331. function isValidRotation(angle) {
  332. return Number.isInteger(angle) && angle % 90 === 0;
  333. }
  334. function cloneObj(obj) {
  335. var result = Object.create(null);
  336. for (var i in obj) {
  337. if (Object.prototype.hasOwnProperty.call(obj, i)) {
  338. result[i] = obj[i];
  339. }
  340. }
  341. return result;
  342. }
  343. var WaitOnType = {
  344. EVENT: 'event',
  345. TIMEOUT: 'timeout'
  346. };
  347. function waitOnEventOrTimeout(_ref) {
  348. var target = _ref.target,
  349. name = _ref.name,
  350. _ref$delay = _ref.delay,
  351. delay = _ref$delay === undefined ? 0 : _ref$delay;
  352. if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object' || !(name && typeof name === 'string') || !(Number.isInteger(delay) && delay >= 0)) {
  353. return Promise.reject(new Error('waitOnEventOrTimeout - invalid paramaters.'));
  354. }
  355. var capability = (0, _pdf.createPromiseCapability)();
  356. function handler(type) {
  357. if (target instanceof EventBus) {
  358. target.off(name, eventHandler);
  359. } else {
  360. target.removeEventListener(name, eventHandler);
  361. }
  362. if (timeout) {
  363. clearTimeout(timeout);
  364. }
  365. capability.resolve(type);
  366. }
  367. var eventHandler = handler.bind(null, WaitOnType.EVENT);
  368. if (target instanceof EventBus) {
  369. target.on(name, eventHandler);
  370. } else {
  371. target.addEventListener(name, eventHandler);
  372. }
  373. var timeoutHandler = handler.bind(null, WaitOnType.TIMEOUT);
  374. var timeout = setTimeout(timeoutHandler, delay);
  375. return capability.promise;
  376. }
  377. var animationStarted = new Promise(function (resolve) {
  378. window.requestAnimationFrame(resolve);
  379. });
  380. var EventBus = function () {
  381. function EventBus() {
  382. _classCallCheck(this, EventBus);
  383. this._listeners = Object.create(null);
  384. }
  385. _createClass(EventBus, [{
  386. key: 'on',
  387. value: function on(eventName, listener) {
  388. var eventListeners = this._listeners[eventName];
  389. if (!eventListeners) {
  390. eventListeners = [];
  391. this._listeners[eventName] = eventListeners;
  392. }
  393. eventListeners.push(listener);
  394. }
  395. }, {
  396. key: 'off',
  397. value: function off(eventName, listener) {
  398. var eventListeners = this._listeners[eventName];
  399. var i = void 0;
  400. if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
  401. return;
  402. }
  403. eventListeners.splice(i, 1);
  404. }
  405. }, {
  406. key: 'dispatch',
  407. value: function dispatch(eventName) {
  408. var eventListeners = this._listeners[eventName];
  409. if (!eventListeners || eventListeners.length === 0) {
  410. return;
  411. }
  412. var args = Array.prototype.slice.call(arguments, 1);
  413. eventListeners.slice(0).forEach(function (listener) {
  414. listener.apply(null, args);
  415. });
  416. }
  417. }]);
  418. return EventBus;
  419. }();
  420. function clamp(v, min, max) {
  421. return Math.min(Math.max(v, min), max);
  422. }
  423. var ProgressBar = function () {
  424. function ProgressBar(id) {
  425. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  426. height = _ref2.height,
  427. width = _ref2.width,
  428. units = _ref2.units;
  429. _classCallCheck(this, ProgressBar);
  430. this.visible = true;
  431. this.div = document.querySelector(id + ' .progress');
  432. this.bar = this.div.parentNode;
  433. this.height = height || 100;
  434. this.width = width || 100;
  435. this.units = units || '%';
  436. this.div.style.height = this.height + this.units;
  437. this.percent = 0;
  438. }
  439. _createClass(ProgressBar, [{
  440. key: '_updateBar',
  441. value: function _updateBar() {
  442. if (this._indeterminate) {
  443. this.div.classList.add('indeterminate');
  444. this.div.style.width = this.width + this.units;
  445. return;
  446. }
  447. this.div.classList.remove('indeterminate');
  448. var progressSize = this.width * this._percent / 100;
  449. this.div.style.width = progressSize + this.units;
  450. }
  451. }, {
  452. key: 'setWidth',
  453. value: function setWidth(viewer) {
  454. if (!viewer) {
  455. return;
  456. }
  457. var container = viewer.parentNode;
  458. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  459. if (scrollbarWidth > 0) {
  460. this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
  461. }
  462. }
  463. }, {
  464. key: 'hide',
  465. value: function hide() {
  466. if (!this.visible) {
  467. return;
  468. }
  469. this.visible = false;
  470. this.bar.classList.add('hidden');
  471. document.body.classList.remove('loadingInProgress');
  472. }
  473. }, {
  474. key: 'show',
  475. value: function show() {
  476. if (this.visible) {
  477. return;
  478. }
  479. this.visible = true;
  480. document.body.classList.add('loadingInProgress');
  481. this.bar.classList.remove('hidden');
  482. }
  483. }, {
  484. key: 'percent',
  485. get: function get() {
  486. return this._percent;
  487. },
  488. set: function set(val) {
  489. this._indeterminate = isNaN(val);
  490. this._percent = clamp(val, 0, 100);
  491. this._updateBar();
  492. }
  493. }]);
  494. return ProgressBar;
  495. }();
  496. exports.CSS_UNITS = CSS_UNITS;
  497. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  498. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  499. exports.MIN_SCALE = MIN_SCALE;
  500. exports.MAX_SCALE = MAX_SCALE;
  501. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  502. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  503. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  504. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  505. exports.isValidRotation = isValidRotation;
  506. exports.isFileSchema = isFileSchema;
  507. exports.cloneObj = cloneObj;
  508. exports.PresentationModeState = PresentationModeState;
  509. exports.RendererType = RendererType;
  510. exports.TextLayerMode = TextLayerMode;
  511. exports.NullL10n = NullL10n;
  512. exports.EventBus = EventBus;
  513. exports.ProgressBar = ProgressBar;
  514. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  515. exports.noContextMenuHandler = noContextMenuHandler;
  516. exports.parseQueryString = parseQueryString;
  517. exports.getVisibleElements = getVisibleElements;
  518. exports.roundToDivide = roundToDivide;
  519. exports.approximateFraction = approximateFraction;
  520. exports.getOutputScale = getOutputScale;
  521. exports.scrollIntoView = scrollIntoView;
  522. exports.watchScroll = watchScroll;
  523. exports.binarySearchFirstItem = binarySearchFirstItem;
  524. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  525. exports.animationStarted = animationStarted;
  526. exports.WaitOnType = WaitOnType;
  527. exports.waitOnEventOrTimeout = waitOnEventOrTimeout;