-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathget_attribute_value.ts
35 lines (30 loc) · 1.36 KB
/
get_attribute_value.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
import Attribute from '../../../nodes/Attribute';
import { string_literal } from '../../../utils/stringify';
import Text from '../../../nodes/Text';
import { x } from 'code-red';
import Expression from '../../../nodes/shared/Expression';
import { Expression as ESTreeExpression } from 'estree';
export function get_class_attribute_value(attribute: Attribute): ESTreeExpression {
// handle special case — `class={possiblyUndefined}` with scoped CSS
if (attribute.chunks.length === 2 && (attribute.chunks[1] as Text).synthetic) {
const value = (attribute.chunks[0] as Expression).node;
return x`@escape(@null_to_empty(${value}), true) + "${(attribute.chunks[1] as Text).data}"`;
}
return get_attribute_value(attribute);
}
export function get_attribute_value(attribute: Attribute): ESTreeExpression {
if (attribute.chunks.length === 0) return x`""`;
return attribute.chunks
.map((chunk) => {
return chunk.type === 'Text'
? string_literal(chunk.data.replace(/"/g, '"')) as ESTreeExpression
: x`@escape(${chunk.node}, true)`;
})
.reduce((lhs, rhs) => x`${lhs} + ${rhs}`);
}
export function get_attribute_expression(attribute: Attribute): ESTreeExpression {
if (attribute.chunks.length === 1 && attribute.chunks[0].type === 'Expression') {
return (attribute.chunks[0] as Expression).node as ESTreeExpression;
}
return get_attribute_value(attribute);
}