-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtemplate.js
More file actions
71 lines (61 loc) · 1.97 KB
/
template.js
File metadata and controls
71 lines (61 loc) · 1.97 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const { indentLines } = require('../utils/template');
const templateRecast = require('ember-template-recast');
const b = templateRecast.builders;
const PLACEHOLDER = '@@@PLACEHOLDER@@@';
module.exports = function transformTemplate(
template,
{ tagName, elementId, classNames, classNameBindings, attributeBindings, ariaRole, eventHandlers },
options
) {
// wrap existing template with root element
let classNodes = [];
if (options.hasComponentCSS) {
classNodes.push(b.mustache('this.styleNamespace'));
}
for (let className of classNames) {
classNodes.push(b.text(className));
}
classNameBindings.forEach(([truthy, falsy], property) => {
if (!truthy) {
classNodes.push(b.mustache(`unless this.${property} "${falsy}"`));
} else {
classNodes.push(b.mustache(`if this.${property} "${truthy}"${falsy ? ` "${falsy}"` : ''}`));
}
});
let attrs = [];
if (elementId) {
attrs.push(b.attr('id', b.text(elementId)));
}
if (ariaRole) {
attrs.push(b.attr('role', b.text(ariaRole)));
}
attributeBindings.forEach((value, key) => {
attrs.push(b.attr(key, b.mustache(`this.${value}`)));
});
if (classNodes.length === 1) {
attrs.push(b.attr('class', classNodes[0]));
} else if (classNodes.length !== 0) {
let parts = [];
classNodes.forEach((node, i) => {
if (i !== 0) parts.push(b.text(' '));
parts.push(node);
});
attrs.push(b.attr('class', b.concat(parts)));
}
attrs.push(b.attr('...attributes', b.text('')));
let modifiers = [];
if (eventHandlers) {
eventHandlers.forEach((methodName, eventName) => {
modifiers.push(b.elementModifier('on', [b.string(eventName), b.path(`this.${methodName}`)]));
});
}
let templateAST = templateRecast.parse(template);
templateAST.body = [
b.element(tagName, {
attrs,
modifiers,
children: [b.text(`\n${PLACEHOLDER}\n`)],
}),
];
return templateRecast.print(templateAST).replace(PLACEHOLDER, indentLines(template));
};