Skip to content

Commit 2ddfff2

Browse files
authored
[CSP] Add support for nested properties to CSP build (#4238)
1 parent 5664930 commit 2ddfff2

File tree

3 files changed

+58
-5
lines changed

3 files changed

+58
-5
lines changed

packages/csp/src/evaluator.js

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,18 @@ function generateEvaluator(el, expression, dataStack) {
2828
return (receiver = () => {}, { scope = {}, params = [] } = {}) => {
2929
let completeScope = mergeProxies([scope, ...dataStack])
3030

31-
if (completeScope[expression] === undefined) {
32-
throwExpressionError(el, expression)
33-
}
34-
35-
runIfTypeOfFunction(receiver, completeScope[expression], completeScope, params)
31+
let evaluatedExpression = expression.split('.').reduce(
32+
(currentScope, currentExpression) => {
33+
if (currentScope[currentExpression] === undefined) {
34+
throwExpressionError(el, expression)
35+
}
36+
37+
return currentScope[currentExpression]
38+
},
39+
completeScope,
40+
);
41+
42+
runIfTypeOfFunction(receiver, evaluatedExpression, completeScope, params)
3643
}
3744
}
3845

packages/docs/src/en/advanced/csp.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,26 @@ Alpine.data('counter', () => ({
118118
},
119119
}))
120120
```
121+
122+
The CSP build supports accessing nested properties (property accessors) using the dot notation.
123+
124+
```alpine
125+
<!-- This works too -->
126+
<div x-data="counter">
127+
<button @click="foo.increment">Increment</button>
128+
129+
<span x-text="foo.count"></span>
130+
</div>
131+
```
132+
133+
```js
134+
Alpine.data('counter', () => ({
135+
foo: {
136+
count: 1,
137+
138+
increment() {
139+
this.count++
140+
},
141+
},
142+
}))
143+
```

tests/cypress/integration/plugins/csp-compatibility.spec.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,26 @@ test.csp('Can use components and basic expressions with CSP-compatible build',
2020
get('span').should(haveText('baz'))
2121
}
2222
)
23+
24+
test.csp('Supports nested properties',
25+
[html`
26+
<div x-data="test">
27+
<span x-text="foo.bar"></span>
28+
29+
<button @click="foo.change">Change Foo</button>
30+
</div>
31+
`,
32+
`
33+
Alpine.data('test', () => ({
34+
foo: {
35+
bar: 'baz',
36+
change() { this.foo.bar = 'qux' },
37+
}
38+
}))
39+
`],
40+
({ get }) => {
41+
get('span').should(haveText('baz'))
42+
get('button').click()
43+
get('span').should(haveText('qux'))
44+
}
45+
)

0 commit comments

Comments
 (0)