-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathutils.js
More file actions
77 lines (71 loc) · 2.22 KB
/
Copy pathutils.js
File metadata and controls
77 lines (71 loc) · 2.22 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
import words from 'lodash/words'
import merge from 'lodash/merge'
/**
* Removes a key and puts the children of that key in the key's parent
* e.g. remove "extended" in the path color|extended|primary-10.
* Note: This cannot merge keys where a child has the same key as the parent,
* e.g. we cannot remove the duplication of the path gradient|gradient|xyz.
*/
export function removeKeyFromObject(contents, keyToRemove, recurse = true) {
// Don't need to work on types without keys
if (typeof contents !== 'object') {
return contents
}
for (const key in contents) {
if (key === keyToRemove) {
// Put matching children in their parent
// Parent may already have same key, so recursively merge
contents = merge(contents, contents[key])
delete contents[key]
// No more recursion - we are assuming that matching values
// will not also have descendent items with matching keys.
} else {
// Recurse
if (recurse) {
contents[key] = removeKeyFromObject(contents[key], keyToRemove, true)
}
}
}
return contents
}
/**
* Applies a function to all token nodes of a type
* @param {*} root The root node
* @param {*} type The type of node to apply the function to
* @param {*} apply The applicator
*/
export function applyToTokens(root, type, apply) {
if (!root || typeof root !== 'object') return
if (root.type === type) {
apply(root)
return
}
const children = Object.values(root)
for (const child of children) {
applyToTokens(child, type, apply)
}
}
/**
* This is a tagged template literal to format variable
* definitions, like:
* @media (prefers-color-scheme: light) {
* :root {
* --leo-elevation-xl: 36px;
* --leo-elevation-l: 24px;
* ...
* }
* }
*/
export function varDefFormat(strings, vars) {
return [strings[0], vars, strings[1]].join('\n')
}
/**
* Unlike _.snakeCase, which splits on letter/digit boundaries (e.g. "background2"
* becomes "background_2"), this function treats alphanumeric sequences as single
* words. Only whitespace, hyphens, and underscores are used as word boundaries.
*/
export function snakeCaseCustom(str) {
return words(str, /[^\s_-]+/g)
.map((w) => w.toLowerCase())
.join('_')
}