-
-
Notifications
You must be signed in to change notification settings - Fork 231
/
whitespace-ctrl.ts
48 lines (38 loc) · 1.73 KB
/
whitespace-ctrl.ts
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
import DelimitedToken from '../parser/delimited-token'
import Token from '../parser/token'
import TagToken from '../parser/tag-token'
import { NormalizedFullOptions } from '../liquid-options'
export default function whiteSpaceCtrl (tokens: Token[], options: NormalizedFullOptions) {
options = { greedy: true, ...options }
let inRaw = false
tokens.forEach((token: Token, i: number) => {
if (shouldTrimLeft(token as DelimitedToken, inRaw, options)) {
trimLeft(tokens[i - 1], options.greedy)
}
if (token.type === 'tag' && (token as TagToken).name === 'raw') inRaw = true
if (token.type === 'tag' && (token as TagToken).name === 'endraw') inRaw = false
if (shouldTrimRight(token as DelimitedToken, inRaw, options)) {
trimRight(tokens[i + 1], options.greedy)
}
})
}
function shouldTrimLeft (token: DelimitedToken, inRaw: boolean, options: NormalizedFullOptions) {
if (inRaw) return false
if (token.type === 'tag') return token.trimLeft || options.trimTagLeft
if (token.type === 'output') return token.trimLeft || options.trimOutputLeft
}
function shouldTrimRight (token: DelimitedToken, inRaw: boolean, options: NormalizedFullOptions) {
if (inRaw) return false
if (token.type === 'tag') return token.trimRight || options.trimTagRight
if (token.type === 'output') return token.trimRight || options.trimOutputRight
}
function trimLeft (token: Token, greedy: boolean) {
if (!token || token.type !== 'html') return
const rLeft = greedy ? /\s+$/g : /[\t\r ]*$/g
token.value = token.value.replace(rLeft, '')
}
function trimRight (token: Token, greedy: boolean) {
if (!token || token.type !== 'html') return
const rRight = greedy ? /^\s+/g : /^[\t\r ]*\n?/g
token.value = token.value.replace(rRight, '')
}