Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ You have full control over the delimiters used for injecting locals, as well as
| **unescapeDelimiters** | `['{{{', '}}}']` | Array containing beginning and ending delimiters for unescaped locals |
| **locals** | `{}` | Object containing any local variables you want to be available inside your expressions |
| **conditionalTags** | `['if', 'elseif', 'else']` | Array containing names for tags used for `if/else if/else` statements |
| **switchTags** | `['switch', 'case', 'default']` | Array containing names for tags used for `switch/case/default` statements |
| **loopTags** | `['each']` | Array containing names for `for` loops |
| **scopeTags** | `['scope']` | Array containing names for scopes |

Expand Down Expand Up @@ -155,6 +156,34 @@ else
p Foo is probably just foo in the end.
```

### Switch statement

Switch statements act like streamline conditionals. They are useful for when you want to compare a single variable against a series of constants.

```js
locals: { foo: 'foo' }
```

```html
<switch expression="foo">
<case n="'bar'">
<p>Foo really is bar! Revolutionary!</p>
</case>
<case n="'wow'">
<p>Foo is wow, oh man.</p>
</case>
<default>
<p>Foo is probably just foo in the end.</p>
</default>
</switch>
```

```html
<p>Foo is probably just foo in the end.</p>
```

Anything in the `expression` attribute is evaluated directly as an expressions.

### Loops

You can use the `each` tag to build loops. It works with both arrays and objects. For example:
Expand Down
53 changes: 49 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const revertBackupedLocals = require('./backup').revert
const placeholders = require('./placeholders')

let delimitersSettings = []
let conditionals, loops, scopes
let conditionals, switches, loops, scopes

/**
* @description Creates a set of local variables within the loop, and evaluates all nodes within the loop, returning their contents
Expand Down Expand Up @@ -57,7 +57,7 @@ function executeScope (scope, locals, node) {

/**
* @author Jeff Escalante Denis (@jescalan),
* Malinochkin (mrmlnc),
* Denis Malinochkin (mrmlnc),
* Michael Ciniawsky (@michael-ciniawsky)
* @description Expressions Plugin for PostHTML
* @license MIT
Expand All @@ -84,6 +84,7 @@ module.exports = function postHTMLExpressions (options) {
delimiters: ['{{', '}}'],
unescapeDelimiters: ['{{{', '}}}'],
conditionalTags: ['if', 'elseif', 'else'],
switchTags: ['switch', 'case', 'default'],
loopTags: ['each'],
scopeTags: ['scope']
}, options)
Expand All @@ -92,6 +93,7 @@ module.exports = function postHTMLExpressions (options) {
loops = options.loopTags
scopes = options.scopeTags
conditionals = options.conditionalTags
switches = options.switchTags

// make a RegExp's to search for placeholders
let before = escapeRegexpString(options.delimiters[0])
Expand Down Expand Up @@ -169,7 +171,6 @@ function walk (opts, nodes) {

// сalculate the first path of condition expression
let expressionIndex = 1

let expression = `if (${node.attrs.condition}) { 0 } `

const branches = [node.content]
Expand Down Expand Up @@ -225,11 +226,55 @@ function walk (opts, nodes) {
return m
}

// switch tag
if (node.tag === switches[0]) {
// throw an error if it's missing the "expression" attribute
if (!(node.attrs && node.attrs.expression)) {
throw new Error(`the "${switches[0]}" tag must have a "expression" attribute`)
}

// сalculate the first path of condition expression
let expressionIndex = 0
let expression = `switch(${node.attrs.expression}) {`

const branches = []

for (let i = 0; i < node.content.length; i++) {
const currentNode = node.content[i]
if (typeof currentNode === 'string') {
continue
}

if (currentNode.tag === switches[1]) {
// throw an error if it's missing the "n" attribute
if (!(currentNode.attrs && currentNode.attrs.n)) {
throw new Error(`the "${switches[1]}" tag must have a "n" attribute`)
}
expression += `case ${currentNode.attrs.n}: {${expressionIndex++}}; break; `
} else if (currentNode.tag === switches[2]) {
expression += `default: {${expressionIndex++}}`
} else {
throw new Error(`the "${switches[0]}" tag can contain only "${switches[1]}" tags and one "${switches[2]}" tag`)
}
branches.push(currentNode)
}

expression += '}'

// evaluate the expression, get the winning switch branch
const branch = branches[vm.runInContext(expression, ctx)]

// recursive evaluate of branch
Array.prototype.push.apply(m, walk(opts, branch.content))

return m
}

// parse loops
if (node.tag === loops[0]) {
// handle syntax error
if (!(node.attrs && node.attrs.loop)) {
throw new Error(`the "${conditionals[1]}" tag must have a "loop" attribute`)
throw new Error(`the "${loops[0]}" tag must have a "loop" attribute`)
}

// parse the "loop" param
Expand Down
2 changes: 2 additions & 0 deletions test/expect/switch.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

<p>Hello, from Germany!</p>
2 changes: 2 additions & 0 deletions test/expect/switch_customtag.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

<p>Hello, from United States!</p>
2 changes: 2 additions & 0 deletions test/expect/switch_default.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

<p>Hello, from Earth!</p>
2 changes: 2 additions & 0 deletions test/expect/switch_nested.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

<p>Hello, from Russia!</p>
2 changes: 2 additions & 0 deletions test/expect/switch_number.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

<p>3</p>
14 changes: 14 additions & 0 deletions test/fixtures/switch.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<switch expression="country">
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<case n="'germany'">
<p>Hello, from Germany!</p>
</case>
<case n="'us'">
<p>Hello, from United States!</p>
</case>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
9 changes: 9 additions & 0 deletions test/fixtures/switch_bad_flow.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<switch expression="country">
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<p>What?</p>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
14 changes: 14 additions & 0 deletions test/fixtures/switch_customtag.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<s expression="country">
<c n="'russia'">
<p>Hello, from Russia!</p>
</c>
<c n="'germany'">
<p>Hello, from Germany!</p>
</c>
<c n="'us'">
<p>Hello, from United States!</p>
</c>
<d>
<p>Hello, from Earth!</p>
</d>
</s>
14 changes: 14 additions & 0 deletions test/fixtures/switch_default.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<switch expression="country">
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<case n="'germany'">
<p>Hello, from Germany!</p>
</case>
<case n="'us'">
<p>Hello, from United States!</p>
</case>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
27 changes: 27 additions & 0 deletions test/fixtures/switch_nested.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<switch expression="country_one">
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<case n="'germany'">
<p>Hello, from Germany!</p>
</case>
<case n="'us'">
<p>Hello, from United States!</p>
</case>
<default>
<switch expression="country_two">
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<case n="'germany'">
<p>Hello, from Germany!</p>
</case>
<case n="'us'">
<p>Hello, from United States!</p>
</case>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
</default>
</switch>
8 changes: 8 additions & 0 deletions test/fixtures/switch_no_attr.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<switch>
<case n="'russia'">
<p>Hello, from Russia!</p>
</case>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
8 changes: 8 additions & 0 deletions test/fixtures/switch_no_case_attr.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<switch expression="">
<case>
<p>Hello, from Russia!</p>
</case>
<default>
<p>Hello, from Earth!</p>
</default>
</switch>
11 changes: 11 additions & 0 deletions test/fixtures/switch_number.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<switch expression="items.length">
<case n="2">
<p>2</p>
</case>
<case n="3">
<p>3</p>
</case>
<default>
<p>default</p>
</default>
</switch>
54 changes: 54 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,60 @@ test('Conditionals - expression in else/elseif', (t) => {
})
})

test('Switch', (t) => {
return Promise.all([
process(t, 'switch', { locals: { country: 'germany' } })
])
})

test('Switch - default branch', (t) => {
return Promise.all([
process(t, 'switch_default', { locals: { country: 'venezuela' } })
])
})

test('Switch - nested', (t) => {
return Promise.all([
process(t, 'switch_nested', {
locals: {
country_one: 'venezuela',
country_two: 'russia'
}
})
])
})

test('Switch - custom tag', (t) => {
return process(t, 'switch_customtag', {
switchTags: ['s', 'c', 'd'],
locals: { country: 'us' }
})
})

test('Switch - dynamic expression', (t) => {
return Promise.all([
process(t, 'switch_number', { locals: { items: [1, 2, 3] } })
])
})

test('Switch - no switch attribute', (t) => {
return error('switch_no_attr', (err) => {
t.truthy(err.toString() === 'Error: the "switch" tag must have a "expression" attribute')
})
})

test('Switch - no case attribute', (t) => {
return error('switch_no_case_attr', (err) => {
t.truthy(err.toString() === 'Error: the "case" tag must have a "n" attribute')
})
})

test('Switch - bad flow', (t) => {
return error('switch_bad_flow', (err) => {
t.truthy(err.toString() === 'the "switch" tag can contain only "case" tags and one "default" tag')
})
})

test('Loops', (t) => {
return process(t, 'loop', { locals: { items: [1, 2, 3] } })
})
Expand Down