Skip to content

Commit 4fcc681

Browse files
author
Alfred Ringstad
committed
Add add_css_class method to DynamicElement
1 parent f001107 commit 4fcc681

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

src/compiler/compile/nodes/DynamicElement.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import Animation from './Animation';
1414
import Action from './Action';
1515
import { string_literal } from '../utils/stringify';
1616
import { Literal } from 'estree';
17+
import Text from './Text';
1718

1819
export default class DynamicElement extends Node {
1920
type: 'DynamicElement';
@@ -30,6 +31,7 @@ export default class DynamicElement extends Node {
3031
animation?: Animation = null;
3132
children: INode[];
3233
scope: TemplateScope;
34+
needs_manual_style_scoping: boolean;
3335

3436
constructor(component: Component, parent, scope, info) {
3537
super(component, parent, scope, info);
@@ -96,4 +98,37 @@ export default class DynamicElement extends Node {
9698

9799
this.children = map_children(component, this, this.scope, info.children);
98100
}
101+
102+
add_css_class() {
103+
if (this.attributes.some(attr => attr.is_spread)) {
104+
this.needs_manual_style_scoping = true;
105+
return;
106+
}
107+
108+
const { id } = this.component.stylesheet;
109+
110+
const class_attribute = this.attributes.find(a => a.name === 'class');
111+
112+
if (class_attribute && !class_attribute.is_true) {
113+
if (class_attribute.chunks.length === 1 && class_attribute.chunks[0].type === 'Text') {
114+
(class_attribute.chunks[0] as Text).data += ` ${id}`;
115+
} else {
116+
(class_attribute.chunks as Node[]).push(
117+
new Text(this.component, this, this.scope, {
118+
type: 'Text',
119+
data: ` ${id}`,
120+
synthetic: true
121+
} as any)
122+
);
123+
}
124+
} else {
125+
this.attributes.push(
126+
new Attribute(this.component, this, this.scope, {
127+
type: 'Attribute',
128+
name: 'class',
129+
value: [{ type: 'Text', data: id, synthetic: true }]
130+
} as any)
131+
);
132+
}
133+
}
99134
}

src/compiler/compile/render_ssr/handlers/DynamicElement.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ export default function (
5050
const snippet = expression ? expression.node : x`#ctx.${name}`; // TODO is this right?
5151
return x`${snippet} ? "${name}" : ""`;
5252
});
53-
// if (node.needs_manual_style_scoping) {
54-
// class_expression_list.push(x`"${node.component.stylesheet.id}"`);
55-
// }
53+
if (node.needs_manual_style_scoping) {
54+
class_expression_list.push(x`"${node.component.stylesheet.id}"`);
55+
}
5656
const class_expression =
5757
class_expression_list.length > 0 &&
5858
class_expression_list.reduce((lhs, rhs) => x`${lhs} + ' ' + ${rhs}`);

0 commit comments

Comments
 (0)