Skip to content

Commit 2f6a886

Browse files
author
Alfred Ringstad
committed
Add add_css_class method to DynamicElement
1 parent fe4158a commit 2f6a886

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
@@ -13,6 +13,7 @@ import Transition from './Transition';
1313
import Animation from './Animation';
1414
import Action from './Action';
1515
import { string_literal } from '../utils/stringify';
16+
import Text from './Text';
1617

1718
export default class DynamicElement extends Node {
1819
type: 'DynamicElement';
@@ -29,6 +30,7 @@ export default class DynamicElement extends Node {
2930
animation?: Animation = null;
3031
children: INode[];
3132
scope: TemplateScope;
33+
needs_manual_style_scoping: boolean;
3234

3335
constructor(component: Component, parent, scope, info) {
3436
super(component, parent, scope, info);
@@ -95,4 +97,37 @@ export default class DynamicElement extends Node {
9597

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

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

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

0 commit comments

Comments
 (0)