all files / liquidjs/src/ whitespace-ctrl.js

100% Statements 38/38
100% Branches 44/44
100% Functions 5/5
100% Lines 28/28
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   332× 332×   332× 991× 69×     991× 991×   991× 71×         991× 975× 563×     991× 971× 563×     69×   65× 65×     71×   65× 65×      
const _ = require('./util/underscore.js')
 
function whiteSpaceCtrl (tokens, options) {
  options = _.assign({ greedy: true }, options)
  var inRaw = false
 
  tokens.forEach((token, i) => {
    if (shouldTrimLeft(token, inRaw, options)) {
      trimLeft(tokens[i - 1], options.greedy)
    }
 
    if (token.type === 'tag' && token.name === 'raw') inRaw = true
    if (token.type === 'tag' && token.name === 'endraw') inRaw = false
 
    if (shouldTrimRight(token, inRaw, options)) {
      trimRight(tokens[i + 1], options.greedy)
    }
  })
}
 
function shouldTrimLeft (token, inRaw, options) {
  if (inRaw) return false
  if (token.type === 'tag') return token.trim_left || options.trim_tag_left
  if (token.type === 'value') return token.trim_left || options.trim_value_left
}
 
function shouldTrimRight (token, inRaw, options) {
  if (inRaw) return false
  if (token.type === 'tag') return token.trim_right || options.trim_tag_right
  if (token.type === 'value') return token.trim_right || options.trim_value_right
}
 
function trimLeft (token, greedy) {
  if (!token || token.type !== 'html') return
 
  var rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
  token.value = token.value.replace(rLeft, '')
}
 
function trimRight (token, greedy) {
  if (!token || token.type !== 'html') return
 
  var rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
  token.value = token.value.replace(rRight, '')
}
 
module.exports = whiteSpaceCtrl