This repository was archived by the owner on Feb 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 248
/
Copy pathcss_shim.dart
430 lines (355 loc) · 11.5 KB
/
css_shim.dart
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
library css_shim;
import 'package:angular/core/parser/characters.dart';
String shimCssText(String css, String tag) =>
new _CssShim(tag).shimCssText(css);
/**
* This is a shim for ShadowDOM css styling. It adds an attribute selector suffix
* to each simple selector.
*
* So:
*
* one, two {color: red;}
*
* Becomes:
*
* one[tag], two[tag] {color: red;}
*
* It can handle the following selectors:
* * `one::before`
* * `one two`
* * `one>two`
* * `one+two`
* * `one~two`
* * `.one.two`
* * `one[attr="value"]`
* * `one[attr^="value"]`
* * `one[attr$="value"]`
* * `one[attr*="value"]`
* * `one[attr|="value"]`
* * `one[attr]`
* * `[is=one]`
*
* It can handle :host:
* * `:host`
* * `:host(.x)`
*
* When the shim is not powerful enough, you can fall back on the polyfill-next-selector,
* polyfill-unscoped-next-selector, and polyfill-non-strict directives.
*
* * `polyfill-next-selector {content: 'x > y'}` z {} becomes `x[tag] > y[tag] {}`
* * `polyfill-unscoped-next-selector {content: 'x > y'} z {}` becomes `x > y {}`
* * `polyfill-non-strict {} z {}` becomes `tag z {}`
*
* See http://www.polymer-project.org/docs/polymer/styling.html#at-polyfill
*
* This implementation is a simplified version of the shim provided by platform.js:
* https://github.com/Polymer/platform-dev/blob/master/src/ShadowCSS.js
*/
class _CssShim {
static final List SELECTOR_SPLITS = const [' ', '>', '+', '~'];
static final RegExp COMMENTS = new RegExp(
// Taken from http://www.w3.org/TR/CSS2/grammar.html#scanner.
r"\/\*[^*]*\*+([^/*][^*]*\*+)*\/");
static final RegExp CONTENT = new RegExp(
r"[^}]*"
r"content:\s*"
"('|\")([^\\1]*)\\1"
r"[^}]*}",
caseSensitive: false,
multiLine: true
);
static final String HOST_TOKEN = '-host-element';
static final RegExp COLON_SELECTORS = new RegExp(r'(' + HOST_TOKEN + r')(\(.*\))?(.*)',
caseSensitive: false);
static final RegExp SIMPLE_SELECTORS = new RegExp(r'([^:]*)(:*)(.*)', caseSensitive: false);
static final RegExp IS_SELECTORS = new RegExp(r'\[is="([^\]]*)"\]', caseSensitive: false);
// See https://github.com/Polymer/platform-dev/blob/master/src/ShadowCSS.js#L561
static final String PAREN_SUFFIX = r')(?:\(('
r'(?:\([^)(]*\)|[^)(]*)+?'
r')\))?([^,{]*)';
static final RegExp COLON_HOST = new RegExp('($HOST_TOKEN$PAREN_SUFFIX',
caseSensitive: false, multiLine: true);
static final String POLYFILL_NON_STRICT = "polyfill-non-strict";
static final String POLYFILL_UNSCOPED_NEXT_SELECTOR = "polyfill-unscoped-next-selector";
static final String POLYFILL_NEXT_SELECTOR = "polyfill-next-selector";
static final List<RegExp> COMBINATORS = [
new RegExp(r'/shadow/', caseSensitive: false),
new RegExp(r'/shadow-deep/', caseSensitive: false),
new RegExp(r'::shadow', caseSensitive: false),
new RegExp(r'/deep/', caseSensitive: false)
];
final String tag;
final String attr;
_CssShim(String tag)
: tag = tag, attr = "[$tag]";
String shimCssText(String css) {
final preprocessed = convertColonHost(stripComments(css));
final rules = cssToRules(preprocessed);
return scopeRules(rules);
}
String stripComments(String css) =>
css.replaceAll(COMMENTS, "");
String convertColonHost(String css) {
css = css.replaceAll(":host", HOST_TOKEN);
String partReplacer(host, part, suffix) =>
"$host${part.replaceAll(HOST_TOKEN, '')}$suffix";
return css.replaceAllMapped(COLON_HOST, (m) {
final base = HOST_TOKEN;
final inParens = m.group(2);
final rest = m.group(3);
if (inParens != null && inParens.isNotEmpty) {
return inParens.split(',')
.map((p) => p.trim())
.where((_) => _.isNotEmpty)
.map((p) => partReplacer(base, p, rest))
.join(",");
} else {
return "$base$rest";
}
});
}
List<_Rule> cssToRules(String css) =>
new _Parser(css).parse();
String scopeRules(List<_Rule> rules, {bool emitMode: false}) {
if (emitMode) {
return rules.map(ruleToString).join("\n");
}
final scopedRules = [];
var prevRule;
rules.forEach((rule) {
if (prevRule != null && prevRule.selectorText == POLYFILL_NON_STRICT) {
scopedRules.add(scopeNonStrictMode(rule, emitMode));
} else if (prevRule != null && prevRule.selectorText == POLYFILL_UNSCOPED_NEXT_SELECTOR) {
final content = extractContent(prevRule);
scopedRules.add(ruleToString(new _Rule(content, body: rule.body)));
} else if (prevRule != null && prevRule.selectorText == POLYFILL_NEXT_SELECTOR) {
final content = extractContent(prevRule);
scopedRules.add(scopeStrictMode(new _Rule(content, body: rule.body), false));
} else if (rule.selectorText != POLYFILL_NON_STRICT &&
rule.selectorText != POLYFILL_UNSCOPED_NEXT_SELECTOR &&
rule.selectorText != POLYFILL_NEXT_SELECTOR) {
scopedRules.add(scopeStrictMode(rule, false));
}
prevRule = rule;
});
return scopedRules.join("\n");
}
String extractContent(_Rule rule) {
return CONTENT.firstMatch(rule.body)[2];
}
String ruleToString(_Rule rule) {
return "${rule.selectorText} ${rule.body}";
}
String scopeStrictMode(_Rule rule, bool emitMode) {
if (rule.hasNestedRules) {
final rules = scopeRules(rule.rules, emitMode: rule.selectorText.contains("keyframes"));
return "${rule.selectorText} {\n$rules\n}";
} else {
final scopedSelector = scopeSelector(rule.selectorText, strict: true);
final scopedBody = cssText(rule);
return "$scopedSelector $scopedBody";
}
}
String scopeNonStrictMode(_Rule rule, bool emitMode) {
if (rule.hasNestedRules && rule.selectorText == "keyframes") {
final rules = scopeRules(rule.rules, emitMode: true);
return '${rule.selectorText} {\n$rules\n}';
}
final scopedBody = cssText(rule);
final scopedSelector = scopeSelector(rule.selectorText, strict: false);
return "${scopedSelector} $scopedBody";
}
String scopeSelector(String selector, {bool strict}) {
final parts = replaceCombinators(selector).split(",");
final scopedParts = parts.fold([], (res, p) {
res.add(scopeSimpleSelector(p.trim(), strict: strict));
return res;
});
return scopedParts.join(", ");
}
String replaceCombinators(String selector) {
return COMBINATORS.fold(selector, (sel, combinator) {
return sel.replaceAll(combinator, ' ');
});
}
String scopeSimpleSelector(String selector, {bool strict}) {
if (selector.contains(HOST_TOKEN)) {
return replaceColonSelectors(selector);
} else if (strict) {
return insertTagToEverySelectorPart(selector);
} else {
return "$tag $selector";
}
}
String cssText(_Rule rule) => rule.body;
String replaceColonSelectors(String css) {
return css.replaceAllMapped(COLON_SELECTORS, (m) {
final selectorInParens = m[2] == null ? "" : m[2].substring(1, m[2].length - 1);
final rest = m[3];
return "$tag$selectorInParens$rest";
});
}
String insertTagToEverySelectorPart(String selector) {
selector = handleIsSelector(selector);
SELECTOR_SPLITS.forEach((split) {
final parts = selector.split(split).map((p) => p.trim());
selector = parts.map(insertAttrSuffixIntoSelectorPart).join(split);
});
return selector;
}
String insertAttrSuffixIntoSelectorPart(String p) {
final shouldInsert = p.isNotEmpty && !SELECTOR_SPLITS.contains(p) && !p.contains(attr);
return shouldInsert ? insertAttr(p) : p;
}
String insertAttr(String selector) {
return selector.replaceAllMapped(SIMPLE_SELECTORS, (m) {
final basePart = m[1];
final colonPart = m[2];
final rest = m[3];
return m[0].isNotEmpty ? "$basePart$attr$colonPart$rest" : "";
});
}
String handleIsSelector(String selector) =>
selector.replaceAllMapped(IS_SELECTORS, (m) => m[1]);
}
class _Token {
static final _Token EOF = new _Token(null);
final String string;
final String type;
_Token(this.string, [this.type]);
String toString() => "TOKEN[$string, $type]";
}
class _Lexer {
int peek = 0;
int index = -1;
final String input;
final int length;
_Lexer(String input)
: input = input, length = input.length {
advance();
}
List<_Token> parse() {
final res = [];
var t = scanToken();
while (t != _Token.EOF) {
res.add(t);
t = scanToken();
}
return res;
}
_Token scanToken() {
skipWhitespace();
if (peek == $EOF) return _Token.EOF;
if (isBodyEnd(peek)) {
advance();
return new _Token("}", "rparen");
}
if (isDeclaration(peek)) return scanDeclaration();
if (isSelector(peek)) return scanSelector();
if (isBodyStart(peek)) return scanBody();
return _Token.EOF;
}
bool isSelector(int v) => !isBodyStart(v) && v != $EOF;
bool isBodyStart(int v) => v == $LBRACE;
bool isBodyEnd(int v) => v == $RBRACE;
bool isDeclaration(int v) => v == 64; //@ = 64
void skipWhitespace() {
while (isWhitespace(peek)) {
if (++index >= length) {
peek = $EOF;
return null;
} else {
peek = input.codeUnitAt(index);
}
}
}
_Token scanSelector() {
int start = index;
advance();
while (isSelector(peek)) advance();
String string = input.substring(start, index).trim();
return new _Token(string, "selector");
}
_Token scanBody() {
int start = index;
advance();
while (!isBodyEnd(peek)) advance();
advance();
String string = input.substring(start, index);
return new _Token(string, "body");
}
_Token scanDeclaration() {
int start = index;
advance();
while (!isBodyStart(peek)) advance();
String string = input.substring(start, index);
advance(); //skip {
// we assume that declaration cannot start with media and contain keyframes.
String type = string.contains("keyframes") ? "keyframes" :
(string.startsWith("@media") ? "media" : string);
return new _Token(string, type);
}
void advance() {
peek = ++index >= length ? $EOF : input.codeUnitAt(index);
}
}
class _Rule {
final String selectorText;
final String body;
final List<_Rule> rules;
_Rule(this.selectorText, {this.body, this.rules});
bool get hasNestedRules => rules != null;
String toString() => "Rule[$selectorText $body]";
}
class _Parser {
List<_Token> tokens;
int currentIndex;
_Parser(String input) {
tokens = new _Lexer(input).parse();
currentIndex = -1;
}
List<_Rule> parse() {
final res = [];
var rule;
while ((rule = parseRule()) != null) {
res.add(rule);
}
return res;
}
_Rule parseRule() {
try {
if (next.type == "media" || next.type == "keyframes") {
return parseMedia(next.type);
} else {
return parseCssRule();
}
} catch (e) {
return null;
}
}
_Rule parseMedia(type) {
advance(type);
final media = current.string;
final rules = [];
while (next.type != "rparen") {
rules.add(parseCssRule());
}
advance("rparen");
return new _Rule(media.trim(), rules: rules);
}
_Rule parseCssRule() {
advance("selector");
final selector = current.string;
advance("body");
final body = current.string;
return new _Rule(selector, body: body);
}
void advance(String expectedType) {
currentIndex += 1;
if (current.type != expectedType) {
throw "Unexpected token ${current.type}. Expected $expectedType";
}
}
_Token get current => tokens[currentIndex];
_Token get next => tokens[currentIndex + 1];
}