-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (95 loc) · 2.56 KB
/
index.js
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
import css from 'css'
import locations from 'vfile-location'
import {vendors} from 'vendors'
/**
* @typedef CssDeclarationsOptions
* @property {(reason: string, offset: number) => void} [warning] Function called on errors
*/
/**
* Parse CSS declarations to an object.
*
* @param {string} [value]
* @param {CssDeclarationsOptions} [options]
* @returns {Record.<string, string>} Declarations
*/
export function parse(value, options) {
var source = String(value || '')
var rule = 'i{' + source + '}'
var location = locations(rule)
var sheet = css.parse(rule, {silent: true}).stylesheet
// @ts-ignore to loose `css` types.
var results = sheet.rules[0].declarations || []
var index = -1
var declarations = {}
var offset
while (++index < results.length) {
if (results[index].type === 'declaration') {
declarations[toJsName(results[index].property)] = String(
results[index].value
)
}
}
if (options && options.warning) {
index = -1
while (++index < sheet.parsingErrors.length) {
offset = Math.min(
source.length,
location.toOffset({
line: sheet.parsingErrors[index].line,
column: sheet.parsingErrors[index].column
}) - 2 // `'i{'.length`
)
options.warning(sheet.parsingErrors[index].reason, offset)
}
}
// @ts-ignore to loose `css` types.
return declarations
}
/**
* Serialize declarations.
*
* @param {Record.<string, string>} declarations
* @returns {string}
*/
export function stringify(declarations) {
var results = []
var result
var key
for (key in declarations) {
if (declarations[key] !== null && declarations[key] !== undefined) {
results.push([toCssName(key), declarations[key]].join(': '))
}
}
result = results.join('; ')
return result ? result + ';' : ''
}
// Transform `cssName` to `jsName`.
function toJsName(cssName) {
var head = cssName.charCodeAt(0)
return camel(
head === 45 /* `-` */ || head === 95 /* `_` */ ? cssName.slice(1) : cssName
)
}
// Transform `jsName` to `cssName`.
function toCssName(jsName) {
var cssName = parameter(jsName)
var index = cssName.indexOf('-')
var subvalue
if (index > -1) {
subvalue = cssName.slice(0, index)
if (vendors.indexOf(subvalue) > -1) cssName = '-' + cssName
}
return cssName
}
function camel(value) {
return value.replace(/-./g, replacer)
function replacer($0) {
return $0.charAt(1).toUpperCase()
}
}
function parameter(value) {
return value.replace(/[A-Z]/g, replacer)
function replacer($0) {
return '-' + $0.toLowerCase()
}
}