All files index.js

97.5% Statements 39/40
80% Branches 12/15
87.5% Functions 7/8
97.22% Lines 35/36

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 831x 1x   1x 1x 1x 1x 1x 1x   1x                       1x 3x 3x     1x 5x   4x   2x     1x 5x   5x   5x   5x 3x 6x 3x 3x 4x 3x 3x   3x               3x   3x       1x 1x             3x 3x                
const postcss = require('postcss')
const { env } = require('process')
 
const MakeDirectories = require('./make_dir')
const MakeWebp = require('./make_webp')
const GetImagePath = require('./get_image_path')
const CreateNewPath = require('./create_new_path')
const CheckAttribute = require('./check_attribute')
const CreateAttribute = require('./create_attribute')
 
const DEFAULT_OPTS = {
  env,
  environments: 'all',
  imageFolder: /~images/,
  quality: 60,
  replaceFrom: /\.(jpe?g|png)/,
  resolvePath: 'app/javascript/images',
  webpClass: '.webp',
  webpFolder: 'tmp/webp',
  webpPath: '~webp'
}
 
const makeAssets = async (options, { folder, url }) => {
  await MakeDirectories(options, folder)
  await MakeWebp(options, url)
}
 
const checkEnvironment = ({ environments, env: e }) => {
  if (environments === 'all') return true
 
  if (Array.isArray(environments)) return environments.includes(e)
 
  return environments === e
}
 
module.exports = postcss.plugin('postcss-webp-processing', (opts = {}) => {
  let options = { ...DEFAULT_OPTS, ...opts }
  /* eslint-disable */
  let tester = new RegExp(`^${ options.webpClass }`)
  /* eslint-enable */
  return function (root) {
    // Transform CSS AST here
    if (!checkEnvironment(options)) return
    root.walkRules(rule => {
      if (tester.test(rule.selector)) return
      let decs = []
      rule.walkDecls(/^background-?|border-image/, decl => {
        if (CheckAttribute(options, decl)) {
          let paths = GetImagePath(decl)
          let webpPath = CreateNewPath(options, paths)
 
          makeAssets(options, paths)
            .then(() => {
              // console.log("Asset webp create");
            })
            .catch(e => {
              console.error(e)
            })
 
          let v = CreateAttribute(decl.value, webpPath)
 
          decs.push(postcss.decl({
            prop: decl.prop,
            value: v
          }))
        } else Eif (decl.prop === 'background-size') {
          decs.push(postcss.decl({
            prop: decl.prop,
            value: decl.value
          }))
        }
      })
 
      Eif (decs.length > 0) {
        root.append({
          selector: `${ options.webpClass } ${ rule.selector }`,
          nodes: decs
        })
      }
    })
  }
})