_includes/shortcodes/pdf-link.js

/**
* @file Defines a shortcode for linking to PDF copies of pages
* @author Reuben L. Lillie <reubenlillie@gmail.com>
*/



import {statSync} from 'fs'
import prettyBytes from 'pretty-bytes'

// Filters
import fileExists from '../filters/file-exists.js'
import fileToString from '../filters/file-to-string.js'

/**
* Defines markup for links to PDF versions of a page
* @param {string} fileSlug Page file slug from Eleventy’s `data` object
* @param {sting} dir Directory to search for a PDF
* @return {string} Relative file path for the PDF
* @see _Chicago Manual of Style_ 17th ed. 10.49
*/

export default (fileSlug, dir = 'pdf') => {
var icon = 'img/icons/pdf.svg'
var path = `${dir}/${fileSlug}.pdf`

/**
* Get the file size in bytes
* @param {string} path File path to check
* @return {number} Bytes
*/

function getFileSize(path) {
var stats = statSync(path)
var sizeInBytes = stats.size
return sizeInBytes
}

if(fileExists(path)) {
var size = prettyBytes(getFileSize(path))
return `<!--_includes/shortcodes/pdf-link-->
<p class="show-on-screen-only text-inline-end">
<a href="/
${path}" data-link-type="pdf">${fileExists(icon)
? `<span class="icon">${fileToString(icon)}</span>`
: ''}
PDF version</a>
${size ? `<span class="small"><code>(${size.toUpperCase()})</code></span>` : ''}
</p>
`

}

return `<!--no pdf found for ${path} by _includes/shortcodes/pdf-link.js-->`
}