All files / hummus-toc/src writeLinks.js

100% Statements 32/32
100% Branches 10/10
100% Functions 6/6
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 591x 1x 1x   33x   1x 1x 1x 80x 80x 80x 80x 2x     80x 33x 33x   80x           1x 1x 1x         1x   1x 1x   1x     2x 1x 1x       1x 1x   33x   1x            
const {verticalMax, verticalMargin, lineSpacing, leftMarginEnd} = require('../config')
const createLink = require('./createLink')
const annotationArrayKey = 'Annots'
 
const isFirstLineOnSubsequentPage = (pageSize, pageIndex, idx) => pageIndex > 0 && (idx + 1) % pageSize == 0
 
const getLinks = (objCtx, parser, tocText, pageIndex, howManyPages, pageSize) => {
  let myPage = 0
  return tocText.reduce((acc, {page}, idx) => {
    const verticalTextStart = verticalMax - verticalMargin
    const verticalOffset = lineSpacing * (idx % pageSize)
    const verticalLineStart = verticalTextStart - (verticalOffset + lineSpacing)
    if (verticalLineStart <= verticalMargin) {
      myPage++
    }
    // only for page of links (calculated by height) currently being worked on
    if (pageIndex === myPage) {
      const vertStart = isFirstLineOnSubsequentPage(pageSize, pageIndex, idx) ? verticalTextStart: verticalLineStart
      acc.push(createLink(objCtx, parser.getPageObjectID(page+howManyPages), [leftMarginEnd, vertStart, 505, vertStart+lineSpacing]))
    }
    return acc
  }, [])
}
 
 
 
module.exports = (objCtx, copyCtx, parser, pageIndex, tocText, howManyPages, pageSize) => {
  const pageId = parser.getPageObjectID(pageIndex)
  const pageObject = parser
    .parsePage(pageIndex)
    .getDictionary()
    .toJSObject()
 
  const links = getLinks(objCtx, parser, tocText, pageIndex, howManyPages, pageSize)
 
  objCtx.startModifiedIndirectObject(pageId)
  const modifiedPageObject = objCtx.startDictionary()
 
  Object.getOwnPropertyNames(pageObject).forEach(element => {
    // leave everything besides annotations on TOC pages in tact
    // bookmark annotations are at doc level, so won't be affected
    if (element !== annotationArrayKey) {
      modifiedPageObject.writeKey(element)
      copyCtx.copyDirectObjectAsIs(pageObject[element])
    }
  })
 
  modifiedPageObject.writeKey(annotationArrayKey)
  objCtx.startArray()
 
  links.forEach(link => objCtx.writeIndirectObjectReference(link))
 
  objCtx
    .endArray()
    .endLine()
    .endDictionary(modifiedPageObject)
    .endIndirectObject()
}