-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
css.tsx
789 lines (716 loc) · 20.5 KB
/
css.tsx
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
import * as React from 'react';
import { Component, useEffect, useMemo, useState } from 'react';
import type {
JsxAST,
Middleware,
Styles,
UriProps,
UriState,
XmlAST,
XmlProps,
XmlState,
} from 'react-native-svg';
import { camelCase, fetchText, parse, SvgAst } from 'react-native-svg';
import type {
Atrule,
AtrulePrelude,
CssNode,
Declaration,
DeclarationList,
ListItem,
PseudoClassSelector,
Rule,
Selector,
SelectorList,
} from 'css-tree';
import csstree, { List } from 'css-tree';
import type { Options } from 'css-select';
import cssSelect from 'css-select';
const err = console.error.bind(console);
/*
* Style element inlining experiment based on SVGO
* https://github.com/svg/svgo/blob/11f9c797411a8de966aacc4cb83dbb3e471757bc/plugins/inlineStyles.js
* */
/**
* DOMUtils API for rnsvg AST (used by css-select)
*/
// is the node a tag?
// isTag: ( node:Node ) => isTag:Boolean
function isTag(node: XmlAST | string): node is XmlAST {
return typeof node === 'object';
}
// get the parent of the node
// getParent: ( node:Node ) => parentNode:Node
// returns null when no parent exists
function getParent(node: XmlAST | string): XmlAST {
return ((typeof node === 'object' && node.parent) || null) as XmlAST;
}
// get the node's children
// getChildren: ( node:Node ) => children:[Node]
function getChildren(node: XmlAST | string): Array<XmlAST | string> {
return (typeof node === 'object' && node.children) || [];
}
// get the name of the tag'
// getName: ( elem:ElementNode ) => tagName:String
function getName(elem: XmlAST): string {
return elem.tag;
}
// get the text content of the node, and its children if it has any
// getText: ( node:Node ) => text:String
// returns empty string when there is no text
function getText(_node: XmlAST | string): string {
return '';
}
// get the attribute value
// getAttributeValue: ( elem:ElementNode, name:String ) => value:String
// returns null when attribute doesn't exist
function getAttributeValue(elem: XmlAST, name: string): string {
return (elem.props[name] || null) as string;
}
// takes an array of nodes, and removes any duplicates, as well as any nodes
// whose ancestors are also in the array
function removeSubsets(nodes: Array<XmlAST | string>): Array<XmlAST | string> {
let idx = nodes.length;
let node;
let ancestor;
let replace;
// Check if each node (or one of its ancestors) is already contained in the
// array.
while (--idx > -1) {
node = ancestor = nodes[idx];
// Temporarily remove the node under consideration
delete nodes[idx];
replace = true;
while (ancestor) {
if (nodes.includes(ancestor)) {
replace = false;
nodes.splice(idx, 1);
break;
}
ancestor = (typeof ancestor === 'object' && ancestor.parent) || null;
}
// If the node has been found to be unique, re-insert it.
if (replace) {
nodes[idx] = node;
}
}
return nodes;
}
// does at least one of passed element nodes pass the test predicate?
function existsOne(
predicate: (v: XmlAST) => boolean,
elems: Array<XmlAST | string>
): boolean {
return elems.some(
(elem) =>
typeof elem === 'object' &&
(predicate(elem) || existsOne(predicate, elem.children))
);
}
/*
get the siblings of the node. Note that unlike jQuery's `siblings` method,
this is expected to include the current node as well
*/
function getSiblings(node: XmlAST | string): Array<XmlAST | string> {
const parent = typeof node === 'object' && node.parent;
return (parent && parent.children) || [];
}
// does the element have the named attribute?
function hasAttrib(elem: XmlAST, name: string): boolean {
return Object.prototype.hasOwnProperty.call(elem.props, name);
}
// finds the first node in the array that matches the test predicate, or one
// of its children
function findOne(
predicate: (v: XmlAST) => boolean,
elems: Array<XmlAST | string>
): XmlAST | null {
let elem: XmlAST | null = null;
for (let i = 0, l = elems.length; i < l && !elem; i++) {
const node = elems[i];
if (typeof node === 'string') {
/* empty */
} else if (predicate(node)) {
elem = node;
} else {
const { children } = node;
if (children.length !== 0) {
elem = findOne(predicate, children);
}
}
}
return elem;
}
// finds all of the element nodes in the array that match the test predicate,
// as well as any of their children that match it
function findAll(
predicate: (v: XmlAST) => boolean,
nodes: Array<XmlAST | string>,
result: Array<XmlAST> = []
): Array<XmlAST> {
for (let i = 0, j = nodes.length; i < j; i++) {
const node = nodes[i];
if (typeof node !== 'object') {
continue;
}
if (predicate(node)) {
result.push(node);
}
const { children } = node;
if (children.length !== 0) {
findAll(predicate, children, result);
}
}
return result;
}
const cssSelectOpts: Options<XmlAST | string, XmlAST> = {
xmlMode: true,
adapter: {
removeSubsets,
existsOne,
getSiblings,
hasAttrib,
findOne,
findAll,
isTag,
getParent,
getChildren,
getName,
getText,
getAttributeValue,
},
};
type FlatPseudoSelector = {
item: ListItem<CssNode>;
list: List<CssNode>;
};
type FlatPseudoSelectorList = FlatPseudoSelector[];
type FlatSelector = {
item: ListItem<CssNode>;
atrule: Atrule | null;
rule: CssNode;
pseudos: FlatPseudoSelectorList;
};
type FlatSelectorList = FlatSelector[];
/**
* Flatten a CSS AST to a selectors list.
*
* @param {Object} cssAst css-tree AST to flatten
* @param {Array} selectors
*/
function flattenToSelectors(cssAst: CssNode, selectors: FlatSelectorList) {
csstree.walk(cssAst, {
visit: 'Rule',
enter(rule: CssNode) {
const { type, prelude } = rule as Rule;
if (type !== 'Rule') {
return;
}
const atrule = this.atrule;
(prelude as SelectorList).children.each((node, item) => {
const { children } = node as Selector;
const pseudos: FlatPseudoSelectorList = [];
selectors.push({
item,
atrule,
rule,
pseudos,
});
children.each(({ type: childType }, pseudoItem, list) => {
if (
childType === 'PseudoClassSelector' ||
childType === 'PseudoElementSelector'
) {
pseudos.push({
item: pseudoItem,
list,
});
}
});
});
},
});
}
/**
* Filter selectors by Media Query.
*
* @param {Array} selectors to filter
* @return {Array} Filtered selectors that match the passed media queries
*/
function filterByMqs(selectors: FlatSelectorList) {
return selectors.filter(({ atrule }) => {
if (atrule === null) {
return true;
}
const { name, prelude } = atrule;
const atPrelude = prelude as AtrulePrelude;
const first = atPrelude && atPrelude.children.first();
const mq = first && first.type === 'MediaQueryList';
const query = mq ? csstree.generate(atPrelude) : name;
return useMqs.includes(query);
});
}
// useMqs Array with strings of media queries that should pass (<name> <expression>)
const useMqs = ['', 'screen'];
/**
* Filter selectors by the pseudo-elements and/or -classes they contain.
*
* @param {Array} selectors to filter
* @return {Array} Filtered selectors that match the passed pseudo-elements and/or -classes
*/
function filterByPseudos(selectors: FlatSelectorList) {
return selectors.filter(({ pseudos }) =>
usePseudos.includes(
csstree.generate({
type: 'Selector',
children: new List<CssNode>().fromArray(
pseudos.map((pseudo) => pseudo.item.data)
),
})
)
);
}
// usePseudos Array with strings of single or sequence of pseudo-elements and/or -classes that should pass
const usePseudos = [''];
/**
* Remove pseudo-elements and/or -classes from the selectors for proper matching.
*
* @param {Array} selectors to clean
* @return {Array} Selectors without pseudo-elements and/or -classes
*/
function cleanPseudos(selectors: FlatSelectorList) {
selectors.forEach(({ pseudos }) =>
pseudos.forEach((pseudo) => pseudo.list.remove(pseudo.item))
);
}
type Specificity = [number, number, number];
function specificity(selector: Selector): Specificity {
let A = 0;
let B = 0;
let C = 0;
selector.children.each(function walk(node: CssNode) {
switch (node.type) {
case 'SelectorList':
case 'Selector':
node.children.each(walk);
break;
case 'IdSelector':
A++;
break;
case 'ClassSelector':
case 'AttributeSelector':
B++;
break;
case 'PseudoClassSelector':
switch (node.name.toLowerCase()) {
case 'not': {
const children = (node as PseudoClassSelector).children;
children && children.each(walk);
break;
}
case 'before':
case 'after':
case 'first-line':
case 'first-letter':
C++;
break;
// TODO: support for :nth-*(.. of <SelectorList>), :matches(), :has()
default:
B++;
}
break;
case 'PseudoElementSelector':
C++;
break;
case 'TypeSelector': {
// ignore universal selector
const { name } = node;
if (name.charAt(name.length - 1) !== '*') {
C++;
}
break;
}
}
});
return [A, B, C];
}
/**
* Compares two selector specificities.
* extracted from https://github.com/keeganstreet/specificity/blob/master/specificity.js#L211
*
* @param {Array} aSpecificity Specificity of selector A
* @param {Array} bSpecificity Specificity of selector B
* @return {Number} Score of selector specificity A compared to selector specificity B
*/
function compareSpecificity(
aSpecificity: Specificity,
bSpecificity: Specificity
): number {
for (let i = 0; i < 4; i += 1) {
if (aSpecificity[i] < bSpecificity[i]) {
return -1;
} else if (aSpecificity[i] > bSpecificity[i]) {
return 1;
}
}
return 0;
}
type Spec = {
selector: FlatSelector;
specificity: Specificity;
};
function selectorWithSpecificity(selector: FlatSelector): Spec {
return {
selector,
specificity: specificity(selector.item.data as Selector),
};
}
/**
* Compare two simple selectors.
*
* @param {Object} a Simple selector A
* @param {Object} b Simple selector B
* @return {Number} Score of selector A compared to selector B
*/
function bySelectorSpecificity(a: Spec, b: Spec): number {
return compareSpecificity(a.specificity, b.specificity);
}
// Run a single pass with the given chunk size.
function pass(arr: Spec[], len: number, chk: number, result: Spec[]) {
// Step size / double chunk size.
const dbl = chk * 2;
// Bounds of the left and right chunks.
let l, r, e;
// Iterators over the left and right chunk.
let li, ri;
// Iterate over pairs of chunks.
let i = 0;
for (l = 0; l < len; l += dbl) {
r = l + chk;
e = r + chk;
if (r > len) {
r = len;
}
if (e > len) {
e = len;
}
// Iterate both chunks in parallel.
li = l;
ri = r;
while (true) {
// Compare the chunks.
if (li < r && ri < e) {
// This works for a regular `sort()` compatible comparator,
// but also for a simple comparator like: `a > b`
if (bySelectorSpecificity(arr[li], arr[ri]) <= 0) {
result[i++] = arr[li++];
} else {
result[i++] = arr[ri++];
}
}
// Nothing to compare, just flush what's left.
else if (li < r) {
result[i++] = arr[li++];
} else if (ri < e) {
result[i++] = arr[ri++];
}
// Both iterators are at the chunk ends.
else {
break;
}
}
}
}
// Execute the sort using the input array and a second buffer as work space.
// Returns one of those two, containing the final result.
function exec(arr: Spec[], len: number): Spec[] {
// Rather than dividing input, simply iterate chunks of 1, 2, 4, 8, etc.
// Chunks are the size of the left or right hand in merge sort.
// Stop when the left-hand covers all of the array.
let buffer = new Array(len);
for (let chk = 1; chk < len; chk *= 2) {
pass(arr, len, chk, buffer);
const tmp = arr;
arr = buffer;
buffer = tmp;
}
return arr;
}
/**
* Sort selectors stably by their specificity.
*
* @param {Array} selectors to be sorted
* @return {Array} Stable sorted selectors
*/
function sortSelectors(selectors: FlatSelectorList) {
// Short-circuit when there's nothing to sort.
const len = selectors.length;
if (len <= 1) {
return selectors;
}
const specs = selectors.map(selectorWithSpecificity);
return exec(specs, len).map((s) => s.selector);
}
const declarationParseProps = {
context: 'declarationList',
parseValue: false,
};
function CSSStyleDeclaration(ast: XmlAST) {
const { props, styles } = ast;
if (!props.style) {
props.style = {};
}
const style = props.style as Styles;
const priority = new Map();
ast.style = style;
ast.priority = priority;
if (!styles || styles.length === 0) {
return;
}
try {
const declarations = csstree.parse(
styles,
declarationParseProps
) as DeclarationList;
declarations.children.each((node) => {
try {
const { property, value, important } = node as Declaration;
const name = property.trim();
priority.set(name, important);
style[camelCase(name)] = csstree.generate(value).trim();
} catch (styleError) {
if (
styleError instanceof Error &&
styleError.message !== 'Unknown node type: undefined'
) {
console.warn(
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
styleError
);
}
}
});
} catch (parseError) {
console.warn(
"Warning: Parse error when parsing inline styles, style properties of this element cannot be used. The raw styles can still be get/set using .attr('style').value. Error details: " +
parseError
);
}
}
interface StyledAST extends XmlAST {
style: Styles;
priority: Map<string, boolean | undefined>;
}
function initStyle(selectedEl: XmlAST): StyledAST {
if (!selectedEl.style) {
CSSStyleDeclaration(selectedEl);
}
return selectedEl as StyledAST;
}
/**
* Find the closest ancestor of the current element.
* @param node
* @param elemName
* @return {?Object}
*/
function closestElem(node: XmlAST, elemName: string) {
let elem: XmlAST | null = node;
while ((elem = elem.parent) && elem.tag !== elemName) {
/* empty */
}
return elem;
}
const parseProps = {
parseValue: false,
parseCustomProperty: false,
};
/**
* Moves + merges styles from style elements to element styles
*
* Options
* useMqs (default: ['', 'screen'])
* what media queries to be used
* empty string element for styles outside media queries
*
* usePseudos (default: [''])
* what pseudo-classes/-elements to be used
* empty string element for all non-pseudo-classes and/or -elements
*
* @param {Object} document document element
*
* @author strarsis <[email protected]>
* @author modified by: msand <[email protected]>
*/
export const inlineStyles: Middleware = function inlineStyles(
document: XmlAST
) {
// collect <style/>s
const styleElements = cssSelect('style', document, cssSelectOpts);
// no <styles/>s, nothing to do
if (styleElements.length === 0) {
return document;
}
const selectors: FlatSelectorList = [];
for (const element of styleElements) {
const { children } = element;
if (!children.length || closestElem(element, 'foreignObject')) {
// skip empty <style/>s or <foreignObject> content.
continue;
}
// collect <style/>s and their css ast
try {
const styleString = children.join('');
flattenToSelectors(csstree.parse(styleString, parseProps), selectors);
} catch (parseError) {
console.warn(
'Warning: Parse error of styles of <style/> element, skipped. Error details: ' +
parseError
);
}
}
// filter for mediaqueries to be used or without any mediaquery
const selectorsMq = filterByMqs(selectors);
// filter for pseudo elements to be used
const selectorsPseudo = filterByPseudos(selectorsMq);
// remove PseudoClass from its SimpleSelector for proper matching
cleanPseudos(selectorsPseudo);
// stable sort selectors
const sortedSelectors = sortSelectors(selectorsPseudo).reverse();
// match selectors
for (const { rule, item } of sortedSelectors) {
if (rule === null) {
continue;
}
const selectorStr = csstree.generate(item.data);
try {
// apply <style/> to matched elements
const matched = cssSelect(selectorStr, document, cssSelectOpts).map(
initStyle
);
if (matched.length === 0) {
continue;
}
csstree.walk(rule, {
visit: 'Declaration',
enter(node: CssNode) {
const { property, value, important } = node as Declaration;
// existing inline styles have higher priority
// no inline styles, external styles, external styles used
// inline styles, external styles same priority as inline styles, inline styles used
// inline styles, external styles higher priority than inline styles, external styles used
const name = property.trim();
const camel = camelCase(name);
const val = csstree.generate(value).trim();
for (const element of matched) {
const { style, priority } = element;
const current = priority.get(name);
if (current === undefined || current < important) {
priority.set(name, important as boolean);
style[camel] = val;
}
}
},
});
} catch (selectError) {
if (selectError instanceof SyntaxError) {
console.warn(
'Warning: Syntax error when trying to select \n\n' +
selectorStr +
'\n\n, skipped. Error details: ' +
selectError
);
continue;
}
throw selectError;
}
}
return document;
};
export function SvgCss(props: XmlProps) {
const { xml, override, fallback, onError = err } = props;
try {
const ast = useMemo<JsxAST | null>(
() => (xml !== null ? parse(xml, inlineStyles) : null),
[xml]
);
return <SvgAst ast={ast} override={override || props} />;
} catch (error) {
onError(error);
return fallback ?? null;
}
}
export function SvgCssUri(props: UriProps) {
const { uri, onError = err, onLoad, fallback } = props;
const [xml, setXml] = useState<string | null>(null);
const [isError, setIsError] = useState(false);
useEffect(() => {
uri
? fetchText(uri)
.then((data) => {
setXml(data);
onLoad?.();
})
.catch((e) => {
onError(e);
setIsError(true);
})
: setXml(null);
}, [onError, uri, onLoad]);
if (isError) {
return fallback ?? null;
}
return <SvgCss xml={xml} override={props} fallback={fallback} />;
}
// Extending Component is required for Animated support.
export class SvgWithCss extends Component<XmlProps, XmlState> {
state = { ast: null };
componentDidMount() {
this.parse(this.props.xml);
}
componentDidUpdate(prevProps: { xml: string | null }) {
const { xml } = this.props;
if (xml !== prevProps.xml) {
this.parse(xml);
}
}
parse(xml: string | null) {
try {
this.setState({ ast: xml ? parse(xml, inlineStyles) : null });
} catch (e) {
this.props.onError ? this.props.onError(e as Error) : console.error(e);
}
}
render() {
const {
props,
state: { ast },
} = this;
return <SvgAst ast={ast} override={props.override || props} />;
}
}
export class SvgWithCssUri extends Component<UriProps, UriState> {
state = { xml: null };
componentDidMount() {
this.fetch(this.props.uri);
}
componentDidUpdate(prevProps: { uri: string | null }) {
const { uri } = this.props;
if (uri !== prevProps.uri) {
this.fetch(uri);
}
}
async fetch(uri: string | null) {
try {
this.setState({ xml: uri ? await fetchText(uri) : null });
} catch (e) {
this.props.onError ? this.props.onError(e as Error) : console.error(e);
}
}
render() {
const {
props,
state: { xml },
} = this;
return <SvgWithCss xml={xml} override={props} />;
}
}