-
Notifications
You must be signed in to change notification settings - Fork 357
Expand file tree
/
Copy pathexpand.ts
More file actions
639 lines (554 loc) · 16.9 KB
/
Copy pathexpand.ts
File metadata and controls
639 lines (554 loc) · 16.9 KB
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
/**
* This module expands the CSS properties to get rid of shorthands, as well as
* cleaning up some properties.
*/
import { getPropertyName, getStylesForProperty } from 'css-to-react-native'
import { parseElementStyle } from 'css-background-parser'
import { parse as parseBoxShadow } from 'css-box-shadow'
import cssColorParse from 'parse-css-color'
import CssDimension from '../vendor/parse-css-dimension/index.js'
import parseTransformOrigin, {
ParsedTransformOrigin,
} from '../transform-origin.js'
import { isString, lengthToNumber, v, splitEffects } from '../utils.js'
import { MaskProperty, parseMask } from '../parser/mask.js'
import { splitCornerShapeValues } from '../parser/corner-shape.js'
import { parseBackdropFilter } from '../parser/backdrop-filter.js'
import { FontWeight, FontStyle } from '../font.js'
import {
extractCustomProperties,
mergeVariables,
resolveVariables,
CSSVariables,
} from './variables.js'
// https://react-cn.github.io/react/tips/style-props-value-px.html
const optOutPx = new Set([
'flex',
'flexGrow',
'flexShrink',
'flexBasis',
'fontWeight',
'lineHeight',
'opacity',
'scale',
'scaleX',
'scaleY',
])
const keepNumber = new Set(['lineHeight'])
function handleFallbackColor(
prop: string,
parsed: Record<string, string>,
rawInput: string,
currentColor: string
) {
if (
prop === 'textDecoration' &&
!rawInput.includes(parsed.textDecorationColor)
) {
parsed.textDecorationColor = currentColor
}
return parsed
}
function purify(name: string, value?: string | number) {
const num = Number(value)
if (isNaN(num)) return value
if (!optOutPx.has(name)) return num + 'px'
if (keepNumber.has(name)) return num
return String(value)
}
function handleSpecialCase(
name: string,
value: string | number,
currentColor: string,
inheritedStyle: SerializedStyle
) {
if (name === 'zIndex') {
console.warn('`z-index` is currently not supported.')
return { [name]: value }
}
if (name === 'lineHeight') {
return { lineHeight: purify(name, value) }
}
if (name === 'fontFamily') {
return {
fontFamily: (value as string).split(',').map((_v) => {
return _v
.trim()
.replace(/(^['"])|(['"]$)/g, '')
.toLocaleLowerCase()
}),
}
}
if (name === 'borderRadius') {
if (typeof value !== 'string' || !value.includes('/')) {
// Regular border radius
return
}
// Support the `border-radius: 10px / 20px` syntax.
const [horizontal, vertical] = value.split('/')
const vh = getStylesForProperty(name, horizontal, true)
const vv = getStylesForProperty(name, vertical, true)
for (const k in vh) {
vv[k] = purify(name, vh[k]) + ' ' + purify(name, vv[k])
}
return vv
}
if (name === 'cornerShape') {
if (typeof value !== 'string') {
throw new Error('Invalid `cornerShape` value: "' + value + '".')
}
const values = splitCornerShapeValues(value)
const topLeft = values[0]
const topRight = values[1] || topLeft
const bottomRight = values[2] || topLeft
const bottomLeft = values[3] || topRight
return {
cornerTopLeftShape: topLeft,
cornerTopRightShape: topRight,
cornerBottomRightShape: bottomRight,
cornerBottomLeftShape: bottomLeft,
}
}
if (/^corner(TopLeft|TopRight|BottomRight|BottomLeft)Shape$/.test(name)) {
if (
typeof value !== 'string' ||
splitCornerShapeValues(value, 1).length !== 1
) {
throw new Error('Invalid `' + name + '` value: "' + value + '".')
}
return { [name]: value }
}
const cornerSide = name.match(/^corner(Top|Right|Bottom|Left)Shape$/)
if (cornerSide) {
if (typeof value !== 'string') {
throw new Error('Invalid `' + name + '` value: "' + value + '".')
}
const values = splitCornerShapeValues(value, 2)
const first = values[0]
const second = values[1] || first
const properties = {
Top: ['cornerTopLeftShape', 'cornerTopRightShape'],
Right: ['cornerTopRightShape', 'cornerBottomRightShape'],
Bottom: ['cornerBottomLeftShape', 'cornerBottomRightShape'],
Left: ['cornerTopLeftShape', 'cornerBottomLeftShape'],
}[cornerSide[1]]
return { [properties[0]]: first, [properties[1]]: second }
}
if (/^border(Top|Right|Bottom|Left)?$/.test(name)) {
const resolved = getStylesForProperty('border', value, true)
// Border width should be default to 3px (medium) instead of 1px:
// https://w3c.github.io/csswg-drafts/css-backgrounds-3/#border-width
// Although on Chrome it will be displayed as 1.5px but let's stick to the
// spec.
if (resolved.borderWidth === 1 && !String(value).includes('1px')) {
resolved.borderWidth = 3
}
// A trick to fix `border: 1px solid` to not use `black` but the inherited
// `color` value. This is necessary because css-to-react-native automatically
// fallbacks to default color values.
if (resolved.borderColor === 'black' && !String(value).includes('black')) {
resolved.borderColor = currentColor
}
const purified = {
Width: purify(name + 'Width', resolved.borderWidth),
Style: v(
resolved.borderStyle,
{
solid: 'solid',
dashed: 'dashed',
},
'solid',
name + 'Style'
),
Color: resolved.borderColor,
}
const full = {}
for (const k of name === 'border'
? ['Top', 'Right', 'Bottom', 'Left']
: [name.slice(6)]) {
for (const p in purified) {
full['border' + k + p] = purified[p]
}
}
return full
}
if (name === 'boxShadow') {
if (!value) {
throw new Error('Invalid `boxShadow` value: "' + value + '".')
}
return {
[name]: typeof value === 'string' ? parseBoxShadow(value) : value,
}
}
if (name === 'backdropFilter' || name === 'WebkitBackdropFilter') {
return {
_backdropFilters: parseBackdropFilter(
value,
inheritedStyle,
currentColor
),
}
}
if (name === 'transform') {
if (typeof value !== 'string') throw new Error('Invalid `transform` value.')
// To support percentages in transform (which is not supported in RN), we
// replace them with random symbols and then replace them back after parsing.
const symbols = {}
const replaced = value.replace(/(-?[\d.]+%)/g, (_, _v) => {
const symbol = ~~(Math.random() * 1e9)
symbols[symbol] = _v
return symbol + 'px'
})
const parsed = getStylesForProperty('transform', replaced, true)
for (const t of parsed.transform) {
for (const k in t) {
if (symbols[t[k]]) {
t[k] = symbols[t[k]]
}
}
}
return parsed
}
if (name === 'background') {
value = value.toString().trim()
if (
/^(linear-gradient|radial-gradient|url|repeating-linear-gradient|repeating-radial-gradient)\(/.test(
value
)
) {
return getStylesForProperty('backgroundImage', value, true)
}
return getStylesForProperty('background', value, true)
}
if (name === 'textShadow') {
// Handle multiple text shadows if provided.
value = value.toString().trim()
const result = {}
const shadows = splitEffects(value)
for (const shadow of shadows) {
const styles = getStylesForProperty('textShadow', shadow, true)
for (const k in styles) {
if (!result[k]) {
result[k] = [styles[k]]
} else {
result[k].push(styles[k])
}
}
}
return result
}
if (name === 'WebkitTextStroke') {
value = value.toString().trim()
const values = value.split(' ')
if (values.length !== 2) {
throw new Error('Invalid `WebkitTextStroke` value.')
}
return {
WebkitTextStrokeWidth: purify(name, values[0]),
WebkitTextStrokeColor: purify(name, values[1]),
}
}
if (name === 'textDecorationSkipInk') {
const normalized = value.toString().trim().toLowerCase()
if (!['auto', 'none', 'all'].includes(normalized)) {
throw new Error('Invalid `textDecorationSkipInk` value.')
}
return { textDecorationSkipInk: normalized }
}
return
}
function getErrorHint(name: string) {
if (name === 'transform') {
return ' Only absolute lengths such as `10px` are supported.'
}
return ''
}
const RGB_SLASH = /rgb\((\d+)\s+(\d+)\s+(\d+)\s*\/\s*([\.\d]+)\)/
function normalizeColor(value: string | object) {
if (typeof value === 'string') {
if (RGB_SLASH.test(value.trim())) {
// rgb(255 122 127 / .2) -> rgba(255, 122, 127, .2)
return value.trim().replace(RGB_SLASH, (_, r, g, b, a) => {
return `rgba(${r}, ${g}, ${b}, ${a})`
})
}
}
// Recursively normalize colors in arrays and objects.
if (typeof value === 'object' && value !== null) {
for (const k in value) {
value[k] = normalizeColor(value[k])
}
return value
}
return value
}
type MainStyle = {
color: string
fontSize: number
transformOrigin: ParsedTransformOrigin
maskImage: MaskProperty[]
opacity: number
textTransform: string
whiteSpace: string
wordBreak: string
textAlign: string
textIndent: number | string
lineHeight: number | string
letterSpacing: number
fontFamily: string | string[]
fontWeight: FontWeight
fontStyle: FontStyle
borderTopWidth: number
borderLeftWidth: number
borderRightWidth: number
borderBottomWidth: number
paddingTop: number
paddingLeft: number
paddingRight: number
paddingBottom: number
flexGrow: number
flexShrink: number
gap: number
rowGap: number
columnGap: number
textShadowOffset: {
width: number
height: number
}[]
textShadowColor: string[]
textShadowRadius: number[]
WebkitTextStrokeWidth: number
WebkitTextStrokeColor: string
textDecorationSkipInk: 'auto' | 'none' | 'all'
}
type OtherStyle = Exclude<Record<PropertyKey, string | number>, keyof MainStyle>
export type SerializedStyle = Partial<MainStyle & OtherStyle>
export default function expand(
style: Record<string, string | number> | undefined,
inheritedStyle: SerializedStyle
): SerializedStyle {
const serializedStyle: SerializedStyle = {}
// Extract inherited CSS variables
const inheritedVariables: CSSVariables = {}
for (const prop in inheritedStyle) {
if (prop.startsWith('--')) {
inheritedVariables[prop] = String(inheritedStyle[prop])
}
}
// Extract and resolve CSS variables from current style
let currentVariables: CSSVariables = {}
let processableStyle = style
if (style) {
const { variables, remainingStyle } = extractCustomProperties(style)
currentVariables = variables
processableStyle = remainingStyle
}
// Merge variables (current overrides inherited)
const mergedVariables = mergeVariables(inheritedVariables, currentVariables)
// Store merged variables in the serialized style for inheritance
for (const varName in mergedVariables) {
serializedStyle[varName] = mergedVariables[varName]
}
if (processableStyle) {
// Resolve CSS variables in color property before processing
const resolvedColor = processableStyle.color
? resolveVariables(processableStyle.color, mergedVariables)
: undefined
const currentColor = getCurrentColor(
resolvedColor as string,
inheritedStyle.color
)
serializedStyle.color = currentColor
for (const prop in processableStyle) {
// Internal properties.
if (prop.startsWith('_')) {
serializedStyle[prop] = processableStyle[prop]
continue
}
if (prop === 'color') {
continue
}
const name = getPropertyName(prop)
// Resolve CSS variables before preprocessing
const resolvedValue = resolveVariables(
processableStyle[prop],
mergedVariables
)
const value = preprocess(resolvedValue, currentColor)
try {
const resolvedStyle =
handleSpecialCase(name, value, currentColor, inheritedStyle) ||
handleFallbackColor(
name,
getStylesForProperty(name, purify(name, value), true),
value as string,
currentColor
)
Object.assign(serializedStyle, resolvedStyle)
} catch (err) {
throw new Error(
err.message +
// Attach the extra information of the rule itself if it's not included in
// the error message.
(err.message.includes(value)
? '\n ' + getErrorHint(name)
: `\n in CSS rule \`${name}: ${value}\`.${getErrorHint(name)}`)
)
}
}
}
// Parse background images.
if (serializedStyle.backgroundImage) {
const { backgrounds } = parseElementStyle(serializedStyle)
serializedStyle.backgroundImage = backgrounds
}
if (serializedStyle.maskImage || serializedStyle['WebkitMaskImage']) {
serializedStyle.maskImage = parseMask(serializedStyle)
}
// Calculate the base font size.
const baseFontSize = calcBaseFontSize(
serializedStyle.fontSize,
inheritedStyle.fontSize
)
if (typeof serializedStyle.fontSize !== 'undefined') {
serializedStyle.fontSize = baseFontSize
}
if (serializedStyle.transformOrigin) {
serializedStyle.transformOrigin = parseTransformOrigin(
serializedStyle.transformOrigin as any,
baseFontSize
)
}
for (const prop in serializedStyle) {
let value = serializedStyle[prop]
// Line height needs to be relative.
if (prop === 'lineHeight') {
if (typeof value === 'string' && value !== 'normal') {
value = serializedStyle[prop] =
lengthToNumber(
value,
baseFontSize,
baseFontSize,
inheritedStyle,
true
) / baseFontSize
}
} else {
// Convert em and rem values to px (number).
if (typeof value === 'string') {
const len = lengthToNumber(
value,
baseFontSize,
baseFontSize,
inheritedStyle
)
if (typeof len !== 'undefined') serializedStyle[prop] = len
value = serializedStyle[prop]
}
if (typeof value === 'string' || typeof value === 'object') {
const color = normalizeColor(value)
if (color) {
serializedStyle[prop] = color as any
}
value = serializedStyle[prop]
}
}
// Inherit the opacity.
if (prop === 'opacity' && typeof value === 'number') {
serializedStyle.opacity = value * inheritedStyle.opacity
}
if (prop === 'transform') {
const transforms = value as any as { [type: string]: number | string }[]
for (const transform of transforms) {
const type = Object.keys(transform)[0]
const _v = transform[type]
// Convert em, rem, vw, vh values to px (number), but keep % values.
const len =
typeof _v === 'string'
? lengthToNumber(_v, baseFontSize, baseFontSize, inheritedStyle) ??
_v
: _v
transform[type] = len
}
}
if (prop === 'textShadowRadius') {
const textShadowRadius = value as unknown as Array<number | string>
serializedStyle.textShadowRadius = textShadowRadius.map((_v) =>
lengthToNumber(_v, baseFontSize, 0, inheritedStyle, false)
)
}
if (prop === 'textShadowOffset') {
const textShadowOffset = value as unknown as Array<{
width: number | string
height: number | string
}>
serializedStyle.textShadowOffset = textShadowOffset.map(
({ height, width }) => ({
height: lengthToNumber(
height,
baseFontSize,
0,
inheritedStyle,
false
),
width: lengthToNumber(width, baseFontSize, 0, inheritedStyle, false),
})
)
}
}
return serializedStyle
}
function calcBaseFontSize(
size: number | string,
inheritedSize: number
): number {
if (typeof size === 'number') return size
try {
const parsed = new CssDimension(size)
switch (parsed.unit) {
case 'em':
return parsed.value * inheritedSize
case 'rem':
return parsed.value * 16
}
} catch (err) {
return inheritedSize
}
}
/**
* @see https://github.com/RazrFalcon/resvg/issues/579
*/
function refineHSL(color: string) {
if (color.startsWith('hsl')) {
const t = cssColorParse(color)
const [h, s, l] = t.values
return `hsl(${[h, `${s}%`, `${l}%`]
.concat(t.alpha === 1 ? [] : [t.alpha])
.join(',')})`
}
return color
}
function getCurrentColor(
color: string | undefined,
inheritedColor: string
): string {
if (color && color.toLowerCase() !== 'currentcolor') {
return refineHSL(color)
}
return refineHSL(inheritedColor)
}
function convertCurrentColorToActualValue(
value: string,
currentColor: string
): string {
return value.replace(/currentcolor/gi, currentColor)
}
function preprocess(
value: string | number,
currentColor: string
): string | number {
if (isString(value)) {
value = convertCurrentColorToActualValue(value, currentColor)
}
return value
}