ui_utils.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /* Copyright 2017 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. 'use strict';
  16. var pdfjsLib = require('./pdfjs.js');
  17. var CSS_UNITS = 96.0 / 72.0;
  18. var DEFAULT_SCALE_VALUE = 'auto';
  19. var DEFAULT_SCALE = 1.0;
  20. var MIN_SCALE = 0.25;
  21. var MAX_SCALE = 10.0;
  22. var UNKNOWN_SCALE = 0;
  23. var MAX_AUTO_SCALE = 1.25;
  24. var SCROLLBAR_PADDING = 40;
  25. var VERTICAL_PADDING = 5;
  26. var RendererType = {
  27. CANVAS: 'canvas',
  28. SVG: 'svg'
  29. };
  30. var mozL10n = document.mozL10n || document.webL10n;
  31. var PDFJS = pdfjsLib.PDFJS;
  32. PDFJS.disableFullscreen = PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen;
  33. PDFJS.useOnlyCssZoom = PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom;
  34. PDFJS.maxCanvasPixels = PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels;
  35. PDFJS.disableHistory = PDFJS.disableHistory === undefined ? false : PDFJS.disableHistory;
  36. PDFJS.disableTextLayer = PDFJS.disableTextLayer === undefined ? false : PDFJS.disableTextLayer;
  37. PDFJS.ignoreCurrentPositionOnZoom = PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : PDFJS.ignoreCurrentPositionOnZoom;
  38. PDFJS.locale = PDFJS.locale === undefined ? navigator.language : PDFJS.locale;
  39. function getOutputScale(ctx) {
  40. var devicePixelRatio = window.devicePixelRatio || 1;
  41. var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  42. var pixelRatio = devicePixelRatio / backingStoreRatio;
  43. return {
  44. sx: pixelRatio,
  45. sy: pixelRatio,
  46. scaled: pixelRatio !== 1
  47. };
  48. }
  49. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  50. var parent = element.offsetParent;
  51. if (!parent) {
  52. console.error('offsetParent is not set -- cannot scroll');
  53. return;
  54. }
  55. var checkOverflow = skipOverflowHiddenElements || false;
  56. var offsetY = element.offsetTop + element.clientTop;
  57. var offsetX = element.offsetLeft + element.clientLeft;
  58. while (parent.clientHeight === parent.scrollHeight || checkOverflow && getComputedStyle(parent).overflow === 'hidden') {
  59. if (parent.dataset._scaleY) {
  60. offsetY /= parent.dataset._scaleY;
  61. offsetX /= parent.dataset._scaleX;
  62. }
  63. offsetY += parent.offsetTop;
  64. offsetX += parent.offsetLeft;
  65. parent = parent.offsetParent;
  66. if (!parent) {
  67. return;
  68. }
  69. }
  70. if (spot) {
  71. if (spot.top !== undefined) {
  72. offsetY += spot.top;
  73. }
  74. if (spot.left !== undefined) {
  75. offsetX += spot.left;
  76. parent.scrollLeft = offsetX;
  77. }
  78. }
  79. parent.scrollTop = offsetY;
  80. }
  81. function watchScroll(viewAreaElement, callback) {
  82. var debounceScroll = function debounceScroll(evt) {
  83. if (rAF) {
  84. return;
  85. }
  86. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  87. rAF = null;
  88. var currentY = viewAreaElement.scrollTop;
  89. var lastY = state.lastY;
  90. if (currentY !== lastY) {
  91. state.down = currentY > lastY;
  92. }
  93. state.lastY = currentY;
  94. callback(state);
  95. });
  96. };
  97. var state = {
  98. down: true,
  99. lastY: viewAreaElement.scrollTop,
  100. _eventHandler: debounceScroll
  101. };
  102. var rAF = null;
  103. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  104. return state;
  105. }
  106. function parseQueryString(query) {
  107. var parts = query.split('&');
  108. var params = {};
  109. for (var i = 0, ii = parts.length; i < ii; ++i) {
  110. var param = parts[i].split('=');
  111. var key = param[0].toLowerCase();
  112. var value = param.length > 1 ? param[1] : null;
  113. params[decodeURIComponent(key)] = decodeURIComponent(value);
  114. }
  115. return params;
  116. }
  117. function binarySearchFirstItem(items, condition) {
  118. var minIndex = 0;
  119. var maxIndex = items.length - 1;
  120. if (items.length === 0 || !condition(items[maxIndex])) {
  121. return items.length;
  122. }
  123. if (condition(items[minIndex])) {
  124. return minIndex;
  125. }
  126. while (minIndex < maxIndex) {
  127. var currentIndex = minIndex + maxIndex >> 1;
  128. var currentItem = items[currentIndex];
  129. if (condition(currentItem)) {
  130. maxIndex = currentIndex;
  131. } else {
  132. minIndex = currentIndex + 1;
  133. }
  134. }
  135. return minIndex;
  136. }
  137. function approximateFraction(x) {
  138. if (Math.floor(x) === x) {
  139. return [x, 1];
  140. }
  141. var xinv = 1 / x;
  142. var limit = 8;
  143. if (xinv > limit) {
  144. return [1, limit];
  145. } else if (Math.floor(xinv) === xinv) {
  146. return [1, xinv];
  147. }
  148. var x_ = x > 1 ? xinv : x;
  149. var a = 0,
  150. b = 1,
  151. c = 1,
  152. d = 1;
  153. while (true) {
  154. var p = a + c,
  155. q = b + d;
  156. if (q > limit) {
  157. break;
  158. }
  159. if (x_ <= p / q) {
  160. c = p;
  161. d = q;
  162. } else {
  163. a = p;
  164. b = q;
  165. }
  166. }
  167. var result;
  168. if (x_ - a / b < c / d - x_) {
  169. result = x_ === x ? [a, b] : [b, a];
  170. } else {
  171. result = x_ === x ? [c, d] : [d, c];
  172. }
  173. return result;
  174. }
  175. function roundToDivide(x, div) {
  176. var r = x % div;
  177. return r === 0 ? x : Math.round(x - r + div);
  178. }
  179. function getVisibleElements(scrollEl, views, sortByVisibility) {
  180. var top = scrollEl.scrollTop,
  181. bottom = top + scrollEl.clientHeight;
  182. var left = scrollEl.scrollLeft,
  183. right = left + scrollEl.clientWidth;
  184. function isElementBottomBelowViewTop(view) {
  185. var element = view.div;
  186. var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
  187. return elementBottom > top;
  188. }
  189. var visible = [],
  190. view,
  191. element;
  192. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  193. var currentWidth, viewWidth;
  194. var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
  195. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  196. view = views[i];
  197. element = view.div;
  198. currentHeight = element.offsetTop + element.clientTop;
  199. viewHeight = element.clientHeight;
  200. if (currentHeight > bottom) {
  201. break;
  202. }
  203. currentWidth = element.offsetLeft + element.clientLeft;
  204. viewWidth = element.clientWidth;
  205. if (currentWidth + viewWidth < left || currentWidth > right) {
  206. continue;
  207. }
  208. hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
  209. percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
  210. visible.push({
  211. id: view.id,
  212. x: currentWidth,
  213. y: currentHeight,
  214. view: view,
  215. percent: percentHeight
  216. });
  217. }
  218. var first = visible[0];
  219. var last = visible[visible.length - 1];
  220. if (sortByVisibility) {
  221. visible.sort(function (a, b) {
  222. var pc = a.percent - b.percent;
  223. if (Math.abs(pc) > 0.001) {
  224. return -pc;
  225. }
  226. return a.id - b.id;
  227. });
  228. }
  229. return {
  230. first: first,
  231. last: last,
  232. views: visible
  233. };
  234. }
  235. function noContextMenuHandler(e) {
  236. e.preventDefault();
  237. }
  238. function getPDFFileNameFromURL(url, defaultFilename) {
  239. if (typeof defaultFilename === 'undefined') {
  240. defaultFilename = 'document.pdf';
  241. }
  242. var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  243. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  244. var splitURI = reURI.exec(url);
  245. var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
  246. if (suggestedFilename) {
  247. suggestedFilename = suggestedFilename[0];
  248. if (suggestedFilename.indexOf('%') !== -1) {
  249. try {
  250. suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  251. } catch (e) {}
  252. }
  253. }
  254. return suggestedFilename || defaultFilename;
  255. }
  256. function normalizeWheelEventDelta(evt) {
  257. var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
  258. var angle = Math.atan2(evt.deltaY, evt.deltaX);
  259. if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
  260. delta = -delta;
  261. }
  262. var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
  263. var MOUSE_DOM_DELTA_LINE_MODE = 1;
  264. var MOUSE_PIXELS_PER_LINE = 30;
  265. var MOUSE_LINES_PER_PAGE = 30;
  266. if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
  267. delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
  268. } else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
  269. delta /= MOUSE_LINES_PER_PAGE;
  270. }
  271. return delta;
  272. }
  273. var animationStarted = new Promise(function (resolve) {
  274. window.requestAnimationFrame(resolve);
  275. });
  276. var localized = new Promise(function (resolve, reject) {
  277. if (!mozL10n) {
  278. resolve();
  279. return;
  280. }
  281. if (mozL10n.getReadyState() !== 'loading') {
  282. resolve();
  283. return;
  284. }
  285. window.addEventListener('localized', function localized(evt) {
  286. resolve();
  287. });
  288. });
  289. var EventBus = function EventBusClosure() {
  290. function EventBus() {
  291. this._listeners = Object.create(null);
  292. }
  293. EventBus.prototype = {
  294. on: function EventBus_on(eventName, listener) {
  295. var eventListeners = this._listeners[eventName];
  296. if (!eventListeners) {
  297. eventListeners = [];
  298. this._listeners[eventName] = eventListeners;
  299. }
  300. eventListeners.push(listener);
  301. },
  302. off: function EventBus_on(eventName, listener) {
  303. var eventListeners = this._listeners[eventName];
  304. var i;
  305. if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
  306. return;
  307. }
  308. eventListeners.splice(i, 1);
  309. },
  310. dispatch: function EventBus_dispath(eventName) {
  311. var eventListeners = this._listeners[eventName];
  312. if (!eventListeners || eventListeners.length === 0) {
  313. return;
  314. }
  315. var args = Array.prototype.slice.call(arguments, 1);
  316. eventListeners.slice(0).forEach(function (listener) {
  317. listener.apply(null, args);
  318. });
  319. }
  320. };
  321. return EventBus;
  322. }();
  323. var ProgressBar = function ProgressBarClosure() {
  324. function clamp(v, min, max) {
  325. return Math.min(Math.max(v, min), max);
  326. }
  327. function ProgressBar(id, opts) {
  328. this.visible = true;
  329. this.div = document.querySelector(id + ' .progress');
  330. this.bar = this.div.parentNode;
  331. this.height = opts.height || 100;
  332. this.width = opts.width || 100;
  333. this.units = opts.units || '%';
  334. this.div.style.height = this.height + this.units;
  335. this.percent = 0;
  336. }
  337. ProgressBar.prototype = {
  338. updateBar: function ProgressBar_updateBar() {
  339. if (this._indeterminate) {
  340. this.div.classList.add('indeterminate');
  341. this.div.style.width = this.width + this.units;
  342. return;
  343. }
  344. this.div.classList.remove('indeterminate');
  345. var progressSize = this.width * this._percent / 100;
  346. this.div.style.width = progressSize + this.units;
  347. },
  348. get percent() {
  349. return this._percent;
  350. },
  351. set percent(val) {
  352. this._indeterminate = isNaN(val);
  353. this._percent = clamp(val, 0, 100);
  354. this.updateBar();
  355. },
  356. setWidth: function ProgressBar_setWidth(viewer) {
  357. if (viewer) {
  358. var container = viewer.parentNode;
  359. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  360. if (scrollbarWidth > 0) {
  361. this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
  362. }
  363. }
  364. },
  365. hide: function ProgressBar_hide() {
  366. if (!this.visible) {
  367. return;
  368. }
  369. this.visible = false;
  370. this.bar.classList.add('hidden');
  371. document.body.classList.remove('loadingInProgress');
  372. },
  373. show: function ProgressBar_show() {
  374. if (this.visible) {
  375. return;
  376. }
  377. this.visible = true;
  378. document.body.classList.add('loadingInProgress');
  379. this.bar.classList.remove('hidden');
  380. }
  381. };
  382. return ProgressBar;
  383. }();
  384. exports.CSS_UNITS = CSS_UNITS;
  385. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  386. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  387. exports.MIN_SCALE = MIN_SCALE;
  388. exports.MAX_SCALE = MAX_SCALE;
  389. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  390. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  391. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  392. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  393. exports.RendererType = RendererType;
  394. exports.mozL10n = mozL10n;
  395. exports.EventBus = EventBus;
  396. exports.ProgressBar = ProgressBar;
  397. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  398. exports.noContextMenuHandler = noContextMenuHandler;
  399. exports.parseQueryString = parseQueryString;
  400. exports.getVisibleElements = getVisibleElements;
  401. exports.roundToDivide = roundToDivide;
  402. exports.approximateFraction = approximateFraction;
  403. exports.getOutputScale = getOutputScale;
  404. exports.scrollIntoView = scrollIntoView;
  405. exports.watchScroll = watchScroll;
  406. exports.binarySearchFirstItem = binarySearchFirstItem;
  407. exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
  408. exports.animationStarted = animationStarted;
  409. exports.localized = localized;