pdfViewer.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. import _ from 'lodash'
  2. /* eslint-disable
  3. handle-callback-err,
  4. max-len,
  5. new-cap,
  6. no-return-assign,
  7. no-sequences,
  8. no-unused-vars,
  9. */
  10. // TODO: This file was created by bulk-decaffeinate.
  11. // Fix any style issues and re-enable lint.
  12. /*
  13. * decaffeinate suggestions:
  14. * DS101: Remove unnecessary use of Array.from
  15. * DS102: Remove unnecessary code created because of implicit returns
  16. * DS103: Rewrite code to no longer use __guard__
  17. * DS104: Avoid inline assignments
  18. * DS207: Consider shorter variations of null checks
  19. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  20. */
  21. import App from '../../../base'
  22. import pdfTextLayer from './pdfTextLayer'
  23. import pdfAnnotations from './pdfAnnotations'
  24. import pdfHighlights from './pdfHighlights'
  25. import pdfRenderer from './pdfRenderer'
  26. import pdfPage from './pdfPage'
  27. import pdfSpinner from './pdfSpinner'
  28. App.controller('pdfViewerController', function(
  29. $scope,
  30. $q,
  31. $timeout,
  32. PDFRenderer,
  33. $element,
  34. pdfHighlights,
  35. pdfSpinner
  36. ) {
  37. this.load = function() {
  38. // $scope.pages = []
  39. // Ensure previous document is torn down before loading the next one (to
  40. // prevent race conditions)
  41. const documentTearDown =
  42. $scope.document != null ? $scope.document.destroy() : Promise.resolve()
  43. return documentTearDown.then(() => {
  44. $scope.loadCount = $scope.loadCount != null ? $scope.loadCount + 1 : 1
  45. // TODO need a proper url manipulation library to add to query string
  46. let url = $scope.pdfSrc
  47. // add 'pdfng=true' to show that we are using the angular pdfjs viewer
  48. const queryStringExists = /\?/.test(url)
  49. url = url + (!queryStringExists ? '?' : '&') + 'pdfng=true'
  50. // for isolated compiles, load the pdf on-demand because nobody will overwrite it
  51. const onDemandLoading = true
  52. $scope.document = new PDFRenderer(url, {
  53. scale: 1,
  54. disableAutoFetch: onDemandLoading ? true : undefined,
  55. navigateFn(ref) {
  56. // this function captures clicks on the annotation links
  57. $scope.navigateTo = ref
  58. return $scope.$apply()
  59. },
  60. progressCallback(progress) {
  61. return $scope.$emit('progress', progress)
  62. },
  63. loadedCallback() {
  64. return $scope.$emit('loaded')
  65. },
  66. errorCallback(error) {
  67. if (window.Raven) {
  68. // MissingPDFException is "expected" as the pdf file can be on a
  69. // CLSI server that has been cycled out.
  70. // Currently, there is NO error handling to handle this situation,
  71. // but we plan to add this in the future
  72. // (https://github.com/overleaf/issues/issues/2985) and this error
  73. // is causing noise in Sentry so ignore it
  74. if (!error.name === 'MissingPDFException') {
  75. window.Raven.captureMessage(`pdfng error ${error}`)
  76. }
  77. }
  78. return $scope.$emit('pdf:error', error)
  79. },
  80. pageSizeChangeCallback(pageNum, deltaH) {
  81. return $scope.$broadcast('pdf:page:size-change', pageNum, deltaH)
  82. }
  83. })
  84. // we will have all the main information needed to start display
  85. // after the following promise is resolved
  86. $scope.loaded = $q
  87. .all({
  88. numPages: $scope.document.getNumPages(),
  89. // get size of first page as default @ scale 1
  90. pdfViewport: $scope.document.getPdfViewport(1, 1)
  91. })
  92. .then(function(result) {
  93. $scope.pdfViewport = result.pdfViewport
  94. $scope.pdfPageSize = [
  95. result.pdfViewport.height,
  96. result.pdfViewport.width
  97. ]
  98. // console.log 'resolved q.all, page size is', result
  99. $scope.$emit('loaded')
  100. return ($scope.numPages = result.numPages)
  101. })
  102. .catch(function(error) {
  103. $scope.$emit('pdf:error', error)
  104. return $q.reject(error)
  105. })
  106. return $scope.loaded
  107. })
  108. }
  109. this.setScale = (scale, containerHeight, containerWidth) =>
  110. $scope.loaded
  111. .then(function() {
  112. let numScale
  113. if (scale == null) {
  114. scale = {}
  115. }
  116. if (containerHeight === 0 || containerWidth === 0) {
  117. numScale = 1
  118. } else if (scale.scaleMode === 'scale_mode_fit_width') {
  119. // TODO make this dynamic
  120. numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
  121. } else if (scale.scaleMode === 'scale_mode_fit_height') {
  122. // TODO magic numbers for jquery ui layout
  123. numScale = (containerHeight - 20) / $scope.pdfPageSize[0]
  124. } else if (scale.scaleMode === 'scale_mode_value') {
  125. numScale = scale.scale
  126. } else if (scale.scaleMode === 'scale_mode_auto') {
  127. // TODO
  128. } else {
  129. scale.scaleMode = 'scale_mode_fit_width'
  130. numScale = (containerWidth - 40) / $scope.pdfPageSize[1]
  131. }
  132. // TODO
  133. $scope.scale.scale = numScale
  134. $scope.document.setScale(numScale)
  135. return ($scope.defaultPageSize = [
  136. numScale * $scope.pdfPageSize[0],
  137. numScale * $scope.pdfPageSize[1]
  138. ])
  139. })
  140. // console.log 'in setScale result', $scope.scale.scale, $scope.defaultPageSize
  141. .catch(function(error) {
  142. $scope.$emit('pdf:error', error)
  143. return $q.reject(error)
  144. })
  145. this.redraw = function(position) {
  146. // console.log 'in redraw'
  147. // console.log 'reseting pages array for', $scope.numPages
  148. $scope.pages = __range__(0, $scope.numPages - 1, true).map(i => ({
  149. pageNum: i + 1
  150. }))
  151. if (position != null && position.page != null) {
  152. // console.log 'position is', position.page, position.offset
  153. // console.log 'setting current page', position.page
  154. let pagenum = position.page
  155. if (pagenum > $scope.numPages - 1) {
  156. pagenum = $scope.numPages - 1
  157. }
  158. $scope.pages[pagenum].current = true
  159. return ($scope.pages[pagenum].position = position)
  160. }
  161. }
  162. this.zoomIn = function() {
  163. // console.log 'zoom in'
  164. const newScale = $scope.scale.scale * 1.2
  165. return ($scope.forceScale = {
  166. scaleMode: 'scale_mode_value',
  167. scale: newScale
  168. })
  169. }
  170. this.zoomOut = function() {
  171. // console.log 'zoom out'
  172. const newScale = $scope.scale.scale / 1.2
  173. return ($scope.forceScale = {
  174. scaleMode: 'scale_mode_value',
  175. scale: newScale
  176. })
  177. }
  178. this.fitWidth = () =>
  179. // console.log 'fit width'
  180. ($scope.forceScale = { scaleMode: 'scale_mode_fit_width' })
  181. this.fitHeight = () =>
  182. // console.log 'fit height'
  183. ($scope.forceScale = { scaleMode: 'scale_mode_fit_height' })
  184. this.checkPosition = () =>
  185. // console.log 'check position'
  186. ($scope.forceCheck = ($scope.forceCheck || 0) + 1)
  187. this.showRandomHighlights = () =>
  188. // console.log 'show highlights'
  189. ($scope.highlights = [
  190. {
  191. page: 3,
  192. h: 100,
  193. v: 100,
  194. height: 30,
  195. width: 200
  196. }
  197. ])
  198. // we work with (pagenumber, % of height down page from top)
  199. // pdfListView works with (pagenumber, vertical position up page from
  200. // bottom measured in pts)
  201. this.getPdfPosition = function() {
  202. // console.log 'in getPdfPosition'
  203. let canvasOffset, pdfOffset, viewport
  204. let topPageIdx = 0
  205. let topPage = $scope.pages[0]
  206. // find first visible page
  207. const visible = $scope.pages.some(function(page, i) {
  208. if (page.visible) {
  209. let ref
  210. return ([topPageIdx, topPage] = Array.from((ref = [i, page]))), ref
  211. }
  212. })
  213. if (visible && topPage.element != null) {
  214. // console.log 'found it', topPageIdx
  215. } else {
  216. // console.log 'CANNOT FIND TOP PAGE'
  217. return
  218. }
  219. // console.log 'top page is', topPage.pageNum, topPage.elemTop, topPage.elemBottom, topPage
  220. const { top } = topPage.element.offset()
  221. const bottom = top + topPage.element.innerHeight()
  222. const viewportTop = $element.offset().top
  223. const viewportBottom = viewportTop + $element.height()
  224. const topVisible = top >= viewportTop && top < viewportBottom
  225. const someContentVisible = top < viewportTop && bottom > viewportTop
  226. // console.log 'in PdfListView', top, topVisible, someContentVisible, viewportTop
  227. if (topVisible) {
  228. canvasOffset = 0
  229. } else if (someContentVisible) {
  230. canvasOffset = viewportTop - top
  231. } else {
  232. canvasOffset = null
  233. }
  234. // console.log 'pdfListview position = ', canvasOffset
  235. // instead of using promise, check if size is known and revert to
  236. // default otherwise
  237. // console.log 'looking up viewport', topPage.viewport, $scope.pdfViewport
  238. if (topPage.viewport) {
  239. ;({ viewport } = topPage)
  240. pdfOffset = viewport.convertToPdfPoint(0, canvasOffset)
  241. } else {
  242. // console.log 'WARNING: had to default to global page size'
  243. viewport = $scope.pdfViewport
  244. const scaledOffset = canvasOffset / $scope.scale.scale
  245. pdfOffset = viewport.convertToPdfPoint(0, scaledOffset)
  246. }
  247. // console.log 'converted to offset = ', pdfOffset
  248. const newPosition = {
  249. page: topPageIdx,
  250. offset: { top: pdfOffset[1], left: 0 },
  251. pageSize: { height: viewport.viewBox[3], width: viewport.viewBox[2] }
  252. }
  253. return newPosition
  254. }
  255. this.computeOffset = function(page, position) {
  256. // console.log 'computing offset for', page, position
  257. const { element } = page
  258. // console.log 'element =', $(element), 'parent =', $(element).parent()
  259. const t1 = __guard__($(element).offset(), x => x.top)
  260. const t2 = __guard__(
  261. $(element)
  262. .parent()
  263. .offset(),
  264. x1 => x1.top
  265. )
  266. if (!(t1 != null && t2 != null)) {
  267. return $q((resolve, reject) => reject('elements destroyed'))
  268. }
  269. const pageTop =
  270. $(element).offset().top -
  271. $(element)
  272. .parent()
  273. .offset().top
  274. // console.log('top of page scroll is', pageTop, 'vs', page.elemTop)
  275. // console.log('inner height is', $(element).innerHeight())
  276. const currentScroll = $(element)
  277. .parent()
  278. .scrollTop()
  279. const { offset } = position
  280. // convert offset to pixels
  281. return $scope.document
  282. .getPdfViewport(page.pageNum)
  283. .then(function(viewport) {
  284. page.viewport = viewport
  285. const pageOffset = viewport.convertToViewportPoint(
  286. offset.left,
  287. offset.top
  288. )
  289. // if the passed-in position doesn't have the page height/width add them now
  290. if (position.pageSize == null) {
  291. position.pageSize = {
  292. height: viewport.viewBox[3],
  293. width: viewport.viewBox[2]
  294. }
  295. }
  296. // console.log 'addition offset =', pageOffset
  297. // console.log 'total', pageTop + pageOffset[1]
  298. return Math.round(pageTop + pageOffset[1] + currentScroll)
  299. }) // # 10 is margin
  300. }
  301. this.setPdfPosition = function(page, position) {
  302. // console.log 'required pdf Position is', position
  303. return this.computeOffset(page, position).then(function(offset) {
  304. return $scope.$apply(() => {
  305. $scope.pleaseScrollTo = offset
  306. $scope.position = position
  307. })
  308. })
  309. }
  310. return this
  311. })
  312. export default App.directive('pdfViewer', ($q, $timeout, pdfSpinner) => ({
  313. controller: 'pdfViewerController',
  314. controllerAs: 'ctrl',
  315. scope: {
  316. pdfSrc: '=',
  317. highlights: '=',
  318. position: '=',
  319. scale: '=',
  320. pleaseJumpTo: '='
  321. },
  322. template: `\
  323. <div data-pdf-page class='pdf-page-container page-container' ng-repeat='page in pages'></div>\
  324. `,
  325. link(scope, element, attrs, ctrl) {
  326. // console.log 'in pdfViewer element is', element
  327. // console.log 'attrs', attrs
  328. const spinner = new pdfSpinner()
  329. let layoutReady = $q.defer()
  330. layoutReady.notify('waiting for layout')
  331. layoutReady.promise.then(function() {})
  332. // console.log 'layoutReady was resolved'
  333. const renderVisiblePages = function() {
  334. const visiblePages = getVisiblePages()
  335. const pages = getExtraPages(visiblePages)
  336. return scope.document.renderPages(pages)
  337. }
  338. var getVisiblePages = function() {
  339. const top = element[0].scrollTop
  340. const bottom = top + element[0].clientHeight
  341. const visiblePages = _.filter(scope.pages, function(page) {
  342. if (page.element == null) {
  343. return false
  344. }
  345. const pageElement = page.element[0]
  346. const pageTop = pageElement.offsetTop
  347. const pageBottom = pageTop + pageElement.clientHeight
  348. page.visible = pageTop < bottom && pageBottom > top
  349. return page.visible
  350. })
  351. return visiblePages
  352. }
  353. var getExtraPages = function(visiblePages) {
  354. const extra = []
  355. if (visiblePages.length > 0) {
  356. const firstVisiblePage = visiblePages[0].pageNum
  357. const firstVisiblePageIdx = firstVisiblePage - 1
  358. const len = visiblePages.length
  359. const lastVisiblePage = visiblePages[len - 1].pageNum
  360. const lastVisiblePageIdx = lastVisiblePage - 1
  361. // first page after
  362. if (lastVisiblePageIdx + 1 < scope.pages.length) {
  363. extra.push(scope.pages[lastVisiblePageIdx + 1])
  364. }
  365. // page before
  366. if (firstVisiblePageIdx > 0) {
  367. extra.push(scope.pages[firstVisiblePageIdx - 1])
  368. }
  369. // second page after
  370. if (lastVisiblePageIdx + 2 < scope.pages.length) {
  371. extra.push(scope.pages[lastVisiblePageIdx + 2])
  372. }
  373. }
  374. return visiblePages.concat(extra)
  375. }
  376. let rescaleTimer = null
  377. const queueRescale = function(scale) {
  378. // console.log 'call to queueRescale'
  379. if (rescaleTimer != null || layoutTimer != null || elementTimer != null) {
  380. return
  381. }
  382. // console.log 'adding to rescale queue'
  383. return (rescaleTimer = setTimeout(function() {
  384. doRescale(scale)
  385. return (rescaleTimer = null)
  386. }, 0))
  387. }
  388. let spinnerTimer = null
  389. var doRescale = function(scale) {
  390. // console.log 'doRescale', scale
  391. if (scale == null) {
  392. return
  393. }
  394. const origposition = angular.copy(scope.position)
  395. // console.log 'origposition', origposition
  396. if (spinnerTimer == null) {
  397. spinnerTimer = setTimeout(function() {
  398. spinner.add(element)
  399. return (spinnerTimer = null)
  400. }, 100)
  401. }
  402. return layoutReady.promise.then(function(parentSize) {
  403. const [h, w] = Array.from(parentSize)
  404. // console.log 'in promise', h, w
  405. return ctrl
  406. .setScale(scale, h, w)
  407. .then(() =>
  408. // console.log 'in setscale then', scale, h, w
  409. scope.$evalAsync(function() {
  410. if (spinnerTimer) {
  411. clearTimeout(spinnerTimer)
  412. } else {
  413. spinner.remove(element)
  414. }
  415. // stop displaying the text layer
  416. element.removeClass('pdfjs-viewer-show-text')
  417. ctrl.redraw(origposition)
  418. $timeout(renderVisiblePages)
  419. return (scope.loadSuccess = true)
  420. })
  421. )
  422. .catch(error => scope.$emit('pdf:error', error))
  423. })
  424. }
  425. var elementTimer = null
  426. var updateLayout = function() {
  427. // if element is zero-sized keep checking until it is ready
  428. // console.log 'checking element ready', element.height(), element.width()
  429. if (element.height() === 0 || element.width() === 0) {
  430. if (elementTimer != null) {
  431. return
  432. }
  433. return (elementTimer = setTimeout(function() {
  434. elementTimer = null
  435. return updateLayout()
  436. }, 1000))
  437. } else {
  438. scope.parentSize = [element.innerHeight(), element.innerWidth()]
  439. // console.log 'resolving layoutReady with', scope.parentSize
  440. return $timeout(function() {
  441. layoutReady.resolve(scope.parentSize)
  442. return scope.$emit('flash-controls')
  443. })
  444. }
  445. }
  446. var layoutTimer = null
  447. const queueLayout = function() {
  448. // console.log 'call to queue layout'
  449. if (layoutTimer != null) {
  450. return
  451. }
  452. // console.log 'added to queue layoyt'
  453. layoutReady = $q.defer()
  454. return (layoutTimer = setTimeout(function() {
  455. // console.log 'calling update layout'
  456. updateLayout()
  457. // console.log 'setting layout timer to null'
  458. return (layoutTimer = null)
  459. }, 0))
  460. }
  461. queueLayout()
  462. // scope.$on 'layout:pdf:view', (e, args) ->
  463. // console.log 'pdf view change', element, e, args
  464. // queueLayout()
  465. scope.$on('layout:main:resize', () =>
  466. // console.log 'GOT LAYOUT-MAIN-RESIZE EVENT'
  467. queueLayout()
  468. )
  469. scope.$on('layout:pdf:resize', () =>
  470. // FIXME we get this event twice
  471. // also we need to start a new layout when we get it
  472. // console.log 'GOT LAYOUT-PDF-RESIZE EVENT'
  473. queueLayout()
  474. )
  475. scope.$on('pdf:error', function(event, error) {
  476. if (error.name === 'RenderingCancelledException') {
  477. return
  478. }
  479. // check if too many retries or file is missing
  480. const message = (error != null ? error.message : undefined) || error
  481. if (
  482. scope.loadCount > 3 ||
  483. /^Missing PDF/i.test(message) ||
  484. /^loading/i.test(message)
  485. ) {
  486. scope.$emit('pdf:error:display')
  487. return
  488. }
  489. if (scope.loadSuccess) {
  490. return ctrl
  491. .load()
  492. .then(
  493. () =>
  494. // trigger a redraw
  495. (scope.scale = angular.copy(scope.scale))
  496. )
  497. .catch(error => scope.$emit('pdf:error:display'))
  498. } else {
  499. scope.$emit('pdf:error:display')
  500. }
  501. })
  502. scope.$on('pdf:page:size-change', function(event, pageNum, delta) {
  503. // console.log 'page size change event', pageNum, delta
  504. const origposition = angular.copy(scope.position)
  505. // console.log 'orig position', JSON.stringify(origposition)
  506. if (
  507. origposition != null &&
  508. pageNum - 1 < origposition.page &&
  509. delta !== 0
  510. ) {
  511. const currentScrollTop = element.scrollTop()
  512. // console.log 'adjusting scroll from', currentScrollTop, 'by', delta
  513. scope.adjustingScroll = true
  514. return element.scrollTop(currentScrollTop + delta)
  515. }
  516. })
  517. element.on('mousedown', function(e) {
  518. // We're checking that the event target isn't the directive root element
  519. // to make sure that the click was within a PDF page - no point in showing
  520. // the text layer when the click is outside.
  521. // If the user clicks a PDF page, the mousedown target will be the canvas
  522. // element (or the text layer one). Alternatively, if the event target is
  523. // the root element, we can assume that the user has clicked either the
  524. // grey background area or the scrollbars.
  525. if (e.target !== element[0] && !_hasSelection()) {
  526. element.addClass('pdfjs-viewer-show-text')
  527. return _setMouseUpHandler()
  528. }
  529. })
  530. let mouseUpHandler = null // keep track of the handler to avoid adding multiple times
  531. var _setMouseUpHandler = function() {
  532. if (mouseUpHandler == null) {
  533. return (mouseUpHandler = $(document.body).one(
  534. 'mouseup',
  535. _handleSelectionMouseUp
  536. ))
  537. }
  538. }
  539. var _handleSelectionMouseUp = function() {
  540. mouseUpHandler = null // reset handler, has now fired
  541. window.setTimeout(function() {
  542. const removedClass = _removeClassIfNoSelection()
  543. // if we still have a selection we need to keep the handler going
  544. if (!removedClass) {
  545. return _setMouseUpHandler()
  546. }
  547. }, 10)
  548. return true
  549. }
  550. var _removeClassIfNoSelection = function() {
  551. if (_hasSelection()) {
  552. return false // didn't remove the text layer
  553. } else {
  554. element.removeClass('pdfjs-viewer-show-text')
  555. return true
  556. }
  557. }
  558. var _hasSelection = function() {
  559. const selection =
  560. typeof window.getSelection === 'function'
  561. ? window.getSelection()
  562. : undefined
  563. // check the selection collapsed state in preference to
  564. // using selection.toString() as the latter is "" when
  565. // the selection is hidden (e.g. while viewing logs)
  566. return (
  567. selection != null &&
  568. _isSelectionWithinPDF(selection) &&
  569. !selection.isCollapsed
  570. )
  571. }
  572. var _isSelectionWithinPDF = function(selection) {
  573. if (selection.rangeCount === 0) {
  574. return false
  575. }
  576. const selectionAncestorNode = selection.getRangeAt(0)
  577. .commonAncestorContainer
  578. return (
  579. element.find(selectionAncestorNode).length > 0 ||
  580. element.is(selectionAncestorNode)
  581. )
  582. }
  583. element.on('scroll', function() {
  584. // console.log 'scroll event', element.scrollTop(), 'adjusting?', scope.adjustingScroll
  585. // scope.scrollPosition = element.scrollTop()
  586. if (scope.adjustingScroll) {
  587. renderVisiblePages()
  588. scope.adjustingScroll = false
  589. return
  590. }
  591. if (scope.scrollHandlerTimeout) {
  592. clearTimeout(scope.scrollHandlerTimeout)
  593. }
  594. return (scope.scrollHandlerTimeout = setTimeout(scrollHandler, 25))
  595. })
  596. var scrollHandler = function() {
  597. renderVisiblePages()
  598. const newPosition = ctrl.getPdfPosition()
  599. if (newPosition != null) {
  600. scope.position = newPosition
  601. }
  602. return (scope.scrollHandlerTimeout = null)
  603. }
  604. scope.$watch('pdfSrc', function(newVal, oldVal) {
  605. // console.log 'loading pdf', newVal, oldVal
  606. if (newVal == null) {
  607. return
  608. }
  609. scope.loadCount = 0 // new pdf, so reset load count
  610. scope.loadSuccess = false
  611. return ctrl
  612. .load()
  613. .then(
  614. () =>
  615. // trigger a redraw
  616. (scope.scale = angular.copy(scope.scale))
  617. )
  618. .catch(error => scope.$emit('pdf:error', error))
  619. })
  620. scope.$watch('scale', function(newVal, oldVal) {
  621. // no need to set scale when initialising, done in pdfSrc
  622. if (newVal === oldVal) {
  623. return
  624. }
  625. // console.log 'XXX calling Setscale in scale watch'
  626. return queueRescale(newVal)
  627. })
  628. scope.$watch('forceScale', function(newVal, oldVal) {
  629. // console.log 'got change in numscale watcher', newVal, oldVal
  630. if (newVal == null) {
  631. return
  632. }
  633. return queueRescale(newVal)
  634. })
  635. // scope.$watch 'position', (newVal, oldVal) ->
  636. // console.log 'got change in position watcher', newVal, oldVal
  637. scope.$watch('forceCheck', function(newVal, oldVal) {
  638. // console.log 'forceCheck', newVal, oldVal
  639. if (newVal == null) {
  640. return
  641. }
  642. scope.adjustingScroll = true // temporarily disable scroll
  643. return queueRescale(scope.scale)
  644. })
  645. scope.$watch(
  646. 'parentSize',
  647. function(newVal, oldVal) {
  648. // console.log 'XXX in parentSize watch', newVal, oldVal
  649. // if newVal == oldVal
  650. // console.log 'returning because old and new are the same'
  651. // return
  652. // return unless oldVal?
  653. // console.log 'XXX calling setScale in parentSize watcher'
  654. if (newVal == null) {
  655. return
  656. }
  657. return queueRescale(scope.scale)
  658. },
  659. true
  660. )
  661. // scope.$watch 'elementWidth', (newVal, oldVal) ->
  662. // console.log '*** watch INTERVAL element width is', newVal, oldVal
  663. scope.$watch('pleaseScrollTo', function(newVal, oldVal) {
  664. // console.log 'got request to ScrollTo', newVal, 'oldVal', oldVal
  665. if (newVal == null) {
  666. return
  667. }
  668. scope.adjustingScroll = true // temporarily disable scroll
  669. // handler while we reposition
  670. $(element).scrollTop(newVal)
  671. return (scope.pleaseScrollTo = undefined)
  672. })
  673. scope.$watch('pleaseJumpTo', function(newPosition, oldPosition) {
  674. // console.log 'in pleaseJumpTo', newPosition, oldPosition
  675. if (newPosition == null) {
  676. return
  677. }
  678. return ctrl.setPdfPosition(scope.pages[newPosition.page - 1], newPosition)
  679. })
  680. scope.$watch('navigateTo', function(newVal, oldVal) {
  681. if (newVal == null) {
  682. return
  683. }
  684. // console.log 'got request to navigate to', newVal, 'oldVal', oldVal
  685. scope.navigateTo = undefined
  686. // console.log 'navigate to', newVal
  687. // console.log 'look up page num'
  688. return scope.document.getDestination(newVal.dest).then(r =>
  689. // console.log 'need to go to', r
  690. // console.log 'page ref is', r[0]
  691. scope.document.getPageIndex(r[0]).then(function(pidx) {
  692. // console.log 'page num is', pidx
  693. const page = scope.pages[pidx]
  694. return scope.document
  695. .getPdfViewport(page.pageNum)
  696. .then(function(viewport) {
  697. // console.log 'got viewport', viewport
  698. const coords = viewport.convertToViewportPoint(r[2], r[3])
  699. // console.log 'viewport position', coords
  700. // console.log 'r is', r, 'r[1]', r[1], 'r[1].name', r[1].name
  701. if (r[1].name === 'XYZ') {
  702. // console.log 'XYZ:', r[2], r[3]
  703. const newPosition = {
  704. page: pidx,
  705. offset: { top: r[3], left: r[2] }
  706. }
  707. return ctrl.setPdfPosition(scope.pages[pidx], newPosition)
  708. }
  709. })
  710. })
  711. )
  712. }) // XXX?
  713. scope.$watch('highlights', function(areas) {
  714. // console.log 'got HIGHLIGHTS in pdfViewer', areas
  715. if (areas == null) {
  716. return
  717. }
  718. // console.log 'areas are', areas
  719. const highlights = Array.from(areas || []).map(area => ({
  720. page: area.page - 1,
  721. highlight: {
  722. left: area.h,
  723. top: area.v,
  724. height: area.height,
  725. width: area.width
  726. }
  727. }))
  728. // console.log 'highlights', highlights
  729. if (!highlights.length) {
  730. return
  731. }
  732. scope.$broadcast('pdf:highlights', areas)
  733. const first = highlights[0]
  734. // switching between split and full pdf views can cause
  735. // highlights to appear before rendering
  736. if (!scope.pages) {
  737. return // ignore highlight scroll if still rendering
  738. }
  739. const pageNum =
  740. scope.pages[first.page] != null
  741. ? scope.pages[first.page].pageNum
  742. : undefined
  743. if (pageNum == null) {
  744. return // ignore highlight scroll if page not found
  745. }
  746. // use a visual offset of 72pt to match the offset in PdfController syncToCode
  747. return scope.document.getPdfViewport(pageNum).then(function(viewport) {
  748. const position = {
  749. page: first.page,
  750. offset: {
  751. left: first.highlight.left,
  752. top:
  753. viewport.viewBox[3] -
  754. first.highlight.top +
  755. first.highlight.height +
  756. 72
  757. }
  758. }
  759. return ctrl.setPdfPosition(scope.pages[first.page], position)
  760. })
  761. })
  762. return scope.$on('$destroy', function() {
  763. // console.log 'handle pdfng directive destroy'
  764. if (elementTimer != null) {
  765. clearTimeout(elementTimer)
  766. }
  767. if (layoutTimer != null) {
  768. clearTimeout(layoutTimer)
  769. }
  770. if (rescaleTimer != null) {
  771. clearTimeout(rescaleTimer)
  772. }
  773. if (spinnerTimer != null) {
  774. return clearTimeout(spinnerTimer)
  775. }
  776. })
  777. }
  778. }))
  779. function __range__(left, right, inclusive) {
  780. let range = []
  781. let ascending = left < right
  782. let end = !inclusive ? right : ascending ? right + 1 : right - 1
  783. for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
  784. range.push(i)
  785. }
  786. return range
  787. }
  788. function __guard__(value, transform) {
  789. return typeof value !== 'undefined' && value !== null
  790. ? transform(value)
  791. : undefined
  792. }