Skip to content

Commit 32bc47d

Browse files
authored
Merge pull request #810 from sveltejs/gh-455
optimize style attributes
2 parents 89c0b71 + 186b770 commit 32bc47d

File tree

17 files changed

+1393
-2
lines changed

17 files changed

+1393
-2
lines changed

src/generators/dom/visitors/Element/Attribute.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import attributeLookup from './lookup';
22
import deindent from '../../../../utils/deindent';
3+
import visitStyleAttribute, { optimizeStyle } from './StyleAttribute';
34
import { stringify } from '../../../../utils/stringify';
45
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
56
import { DomGenerator } from '../../index';
@@ -16,6 +17,14 @@ export default function visitAttribute(
1617
) {
1718
const name = attribute.name;
1819

20+
if (name === 'style') {
21+
const styleProps = optimizeStyle(attribute.value);
22+
if (styleProps) {
23+
visitStyleAttribute(generator, block, state, node, attribute, styleProps);
24+
return;
25+
}
26+
}
27+
1928
let metadata = state.namespace ? null : attributeLookup[name];
2029
if (metadata && metadata.appliesTo && !~metadata.appliesTo.indexOf(node.name))
2130
metadata = null;
@@ -211,4 +220,4 @@ export default function visitAttribute(
211220
block.builders.hydrate.addLine(updateValue);
212221
if (isDynamic) block.builders.update.addLine(updateValue);
213222
}
214-
}
223+
}
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import attributeLookup from './lookup';
2+
import deindent from '../../../../utils/deindent';
3+
import { stringify } from '../../../../utils/stringify';
4+
import getExpressionPrecedence from '../../../../utils/getExpressionPrecedence';
5+
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
6+
import { DomGenerator } from '../../index';
7+
import Block from '../../Block';
8+
import { Node } from '../../../../interfaces';
9+
import { State } from '../../interfaces';
10+
11+
export interface StyleProp {
12+
key: string;
13+
value: Node[];
14+
}
15+
16+
export default function visitStyleAttribute(
17+
generator: DomGenerator,
18+
block: Block,
19+
state: State,
20+
node: Node,
21+
attribute: Node,
22+
styleProps: StyleProp[]
23+
) {
24+
styleProps.forEach((prop: StyleProp) => {
25+
let value;
26+
27+
if (isDynamic(prop.value)) {
28+
const allDependencies = new Set();
29+
let shouldCache;
30+
let hasChangeableIndex;
31+
32+
value =
33+
((prop.value.length === 1 || prop.value[0].type === 'Text') ? '' : `"" + `) +
34+
prop.value
35+
.map((chunk: Node) => {
36+
if (chunk.type === 'Text') {
37+
return stringify(chunk.data);
38+
} else {
39+
const { snippet, dependencies, indexes } = block.contextualise(chunk.expression);
40+
41+
if (Array.from(indexes).some(index => block.changeableIndexes.get(index))) {
42+
hasChangeableIndex = true;
43+
}
44+
45+
dependencies.forEach(d => {
46+
allDependencies.add(d);
47+
});
48+
49+
return getExpressionPrecedence(chunk.expression) <= 13 ? `( ${snippet} )` : snippet;
50+
}
51+
})
52+
.join(' + ');
53+
54+
if (allDependencies.size || hasChangeableIndex) {
55+
const dependencies = Array.from(allDependencies);
56+
const condition = (
57+
( block.hasOutroMethod ? `#outroing || ` : '' ) +
58+
dependencies.map(dependency => `changed.${dependency}`).join(' || ')
59+
);
60+
61+
block.builders.update.addConditional(
62+
condition,
63+
`@setStyle(${node.var}, '${prop.key}', ${value});`
64+
);
65+
}
66+
} else {
67+
value = stringify(prop.value[0].data);
68+
}
69+
70+
block.builders.hydrate.addLine(
71+
`@setStyle(${node.var}, '${prop.key}', ${value});`
72+
);
73+
});
74+
}
75+
76+
export function optimizeStyle(value: Node[]) {
77+
let expectingKey = true;
78+
let i = 0;
79+
80+
const props: { key: string, value: Node[] }[] = [];
81+
let chunks = value.slice();
82+
83+
while (chunks.length) {
84+
const chunk = chunks[0];
85+
86+
if (chunk.type !== 'Text') return null;
87+
88+
const keyMatch = /^\s*([\w-]+):\s*/.exec(chunk.data);
89+
if (!keyMatch) return null;
90+
91+
const key = keyMatch[1];
92+
93+
const offset = keyMatch.index + keyMatch[0].length;
94+
const remainingData = chunk.data.slice(offset);
95+
96+
if (remainingData) {
97+
chunks[0] = {
98+
start: chunk.start + offset,
99+
end: chunk.end,
100+
type: 'Text',
101+
data: remainingData
102+
};
103+
} else {
104+
chunks.shift();
105+
}
106+
107+
const result = getStyleValue(chunks);
108+
if (!result) return null;
109+
110+
props.push({ key, value: result.value });
111+
chunks = result.chunks;
112+
}
113+
114+
return props;
115+
}
116+
117+
function getStyleValue(chunks: Node[]) {
118+
const value: Node[] = [];
119+
120+
let inUrl = false;
121+
let quoteMark = null;
122+
let escaped = false;
123+
124+
while (chunks.length) {
125+
const chunk = chunks.shift();
126+
127+
if (chunk.type === 'Text') {
128+
let c = 0;
129+
while (c < chunk.data.length) {
130+
const char = chunk.data[c];
131+
132+
if (escaped) {
133+
escaped = false;
134+
} else if (char === '\\') {
135+
escaped = true;
136+
} else if (char === quoteMark) {
137+
quoteMark === null;
138+
} else if (char === '"' || char === "'") {
139+
quoteMark = char;
140+
} else if (char === ')' && inUrl) {
141+
inUrl = false;
142+
} else if (char === 'u' && chunk.data.slice(c, c + 4) === 'url(') {
143+
inUrl = true;
144+
} else if (char === ';' && !inUrl && !quoteMark) {
145+
break;
146+
}
147+
148+
c += 1;
149+
}
150+
151+
if (c > 0) {
152+
value.push({
153+
type: 'Text',
154+
start: chunk.start,
155+
end: chunk.start + c,
156+
data: chunk.data.slice(0, c)
157+
});
158+
}
159+
160+
while (/[;\s]/.test(chunk.data[c])) c += 1;
161+
const remainingData = chunk.data.slice(c);
162+
163+
if (remainingData) {
164+
chunks.unshift({
165+
start: chunk.start + c,
166+
end: chunk.end,
167+
type: 'Text',
168+
data: remainingData
169+
});
170+
171+
break;
172+
}
173+
}
174+
175+
else {
176+
value.push(chunk);
177+
}
178+
}
179+
180+
return {
181+
chunks,
182+
value
183+
};
184+
}
185+
186+
function isDynamic(value: Node[]) {
187+
return value.length > 1 || value[0].type !== 'Text';
188+
}

src/shared/dom.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,8 @@ export function setInputType(input, type) {
137137
try {
138138
input.type = type;
139139
} catch (e) {}
140+
}
141+
142+
export function setStyle(node, key, value) {
143+
node.style.setProperty(key, value);
140144
}

src/utils/getExpressionPrecedence.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { Node } from '../interfaces';
2+
3+
const binaryOperators: Record<string, number> = {
4+
'**': 15,
5+
'*': 14,
6+
'/': 14,
7+
'%': 14,
8+
'+': 13,
9+
'-': 13,
10+
'<<': 12,
11+
'>>': 12,
12+
'>>>': 12,
13+
'<': 11,
14+
'<=': 11,
15+
'>': 11,
16+
'>=': 11,
17+
'in': 11,
18+
'instanceof': 11,
19+
'==': 10,
20+
'!=': 10,
21+
'===': 10,
22+
'!==': 10,
23+
'&': 9,
24+
'^': 8,
25+
'|': 7
26+
};
27+
28+
const logicalOperators: Record<string, number> = {
29+
'&&': 6,
30+
'||': 5
31+
};
32+
33+
const precedence: Record<string, (expression?: Node) => number> = {
34+
Literal: () => 21,
35+
Identifier: () => 21,
36+
ParenthesizedExpression: () => 20,
37+
MemberExpression: () => 19,
38+
NewExpression: () => 19, // can be 18 (if no args) but makes no practical difference
39+
CallExpression: () => 19,
40+
UpdateExpression: () => 17,
41+
UnaryExpression: () => 16,
42+
BinaryExpression: (expression: Node) => binaryOperators[expression.operator],
43+
LogicalExpression: (expression: Node) => logicalOperators[expression.operator],
44+
ConditionalExpression: () => 4,
45+
AssignmentExpression: () => 3,
46+
YieldExpression: () => 2,
47+
SpreadElement: () => 1,
48+
SequenceExpression: () => 0
49+
};
50+
51+
export default function getExpressionPrecedence(expression: Node) {
52+
return expression.type in precedence ? precedence[expression.type](expression) : 0;
53+
}

test/js/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ describe("js", () => {
3939
fs.writeFileSync(`${dir}/_actual.js`, actual);
4040

4141
return rollup({
42-
entry: `${dir}/_actual.js`,
42+
input: `${dir}/_actual.js`,
4343
plugins: [
4444
{
4545
resolveId(importee, importer) {

0 commit comments

Comments
 (0)