forked from sanity-io/sanity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathUtils.ts
241 lines (196 loc) · 5.96 KB
/
pathUtils.ts
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
import getRandomValues from 'get-random-values'
import {
IndexTuple,
isIndexSegment,
isIndexTuple,
isKeySegment,
KeyedSegment,
Path,
PathSegment,
} from '@sanity/types'
const rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g
const reKeySegment = /_key\s*==\s*['"](.*)['"]/
const EMPTY_PATH: Path = []
export const FOCUS_TERMINATOR = '$'
export function get(obj: unknown, path: Path | string, defaultVal?: unknown): unknown {
const select = typeof path === 'string' ? fromString(path) : path
if (!Array.isArray(select)) {
throw new Error('Path must be an array or a string')
}
let acc = obj
for (let i = 0; i < select.length; i++) {
const segment = select[i]
if (isIndexSegment(segment)) {
if (!Array.isArray(acc)) {
return defaultVal
}
acc = acc[segment]
}
if (isKeySegment(segment)) {
if (!Array.isArray(acc)) {
return defaultVal
}
acc = acc.find((item) => item._key === segment._key)
}
if (typeof segment === 'string') {
acc = typeof acc === 'object' && acc !== null ? acc[segment] : undefined
}
if (typeof acc === 'undefined') {
return defaultVal
}
}
return acc
}
export function isEqual(path: Path, otherPath: Path): boolean {
return (
path.length === otherPath.length &&
path.every((segment, i) => isSegmentEqual(segment, otherPath[i]))
)
}
export function numEqualSegments(path: Path, otherPath: Path): number {
const length = Math.min(path.length, otherPath.length)
for (let i = 0; i < length; i++) {
if (!isSegmentEqual(path[i], otherPath[i])) {
return i
}
}
return length
}
export function isSegmentEqual(segmentA: PathSegment, segmentB: PathSegment): boolean {
if (isKeySegment(segmentA) && isKeySegment(segmentB)) {
return segmentA._key === segmentB._key
}
if (isIndexSegment(segmentA)) {
return Number(segmentA) === Number(segmentB)
}
if (isIndexTuple(segmentA) && isIndexTuple(segmentB)) {
return segmentA[0] === segmentB[0] && segmentA[1] === segmentB[1]
}
return segmentA === segmentB
}
export function hasFocus(focusPath: Path, path: Path): boolean {
const withoutTerminator =
focusPath[focusPath.length - 1] === FOCUS_TERMINATOR ? focusPath.slice(0, -1) : focusPath
return isEqual(withoutTerminator, path)
}
export function hasItemFocus(focusPath: Path, item: PathSegment): boolean {
return focusPath.length === 1 && isSegmentEqual(focusPath[0], item)
}
export function isExpanded(segment: PathSegment, focusPath: Path): boolean {
const [head, ...tail] = focusPath
return tail.length > 0 && isSegmentEqual(segment, head)
}
export function startsWith(prefix: Path, path: Path): boolean {
return prefix.every((segment, i) => isSegmentEqual(segment, path[i]))
}
export function trimLeft(prefix: Path, path: Path): Path {
if (prefix.length === 0 || path.length === 0) {
return path
}
const [prefixHead, ...prefixTail] = prefix
const [pathHead, ...pathTail] = path
if (!isSegmentEqual(prefixHead, pathHead)) {
return path
}
return trimLeft(prefixTail, pathTail)
}
export function trimRight(suffix: Path, path: Path): Path {
const sufLen = suffix.length
const pathLen = path.length
if (sufLen === 0 || pathLen === 0) {
return path
}
let i = 0
while (
i < sufLen &&
i < pathLen &&
isSegmentEqual(path[pathLen - i - 1], suffix[sufLen - i - 1])
) {
i++
}
return path.slice(0, pathLen - i)
}
export function trimChildPath(path: Path, childPath: Path): Path {
return startsWith(path, childPath) ? trimLeft(path, childPath) : EMPTY_PATH
}
export function toString(path: Path): string {
if (!Array.isArray(path)) {
throw new Error('Path is not an array')
}
return path.reduce<string>((target, segment, i) => {
const segmentType = typeof segment
if (segmentType === 'number') {
return `${target}[${segment}]`
}
if (segmentType === 'string') {
const separator = i === 0 ? '' : '.'
return `${target}${separator}${segment}`
}
if (isKeySegment(segment) && segment._key) {
return `${target}[_key=="${segment._key}"]`
}
if (Array.isArray(segment)) {
const [from, to] = segment
return `${target}[${from}:${to}]`
}
throw new Error(`Unsupported path segment \`${JSON.stringify(segment)}\``)
}, '')
}
export function fromString(path: string): Path {
if (typeof path !== 'string') {
throw new Error('Path is not a string')
}
const segments = path.match(rePropName)
if (!segments) {
throw new Error('Invalid path string')
}
return segments.map(normalizePathSegment)
}
function normalizePathSegment(segment: string): PathSegment {
if (isIndexSegment(segment)) {
return normalizeIndexSegment(segment)
}
if (isKeySegment(segment)) {
return normalizeKeySegment(segment)
}
if (isIndexTuple(segment)) {
return normalizeIndexTupleSegment(segment)
}
return segment
}
function normalizeIndexSegment(segment: string): PathSegment {
return Number(segment.replace(/[^\d]/g, ''))
}
function normalizeKeySegment(segment: string): KeyedSegment {
const segments = segment.match(reKeySegment)
return {_key: segments![1]}
}
function normalizeIndexTupleSegment(segment: string): IndexTuple {
const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))
return [from, to]
}
const getByteHexTable = (() => {
let table
return () => {
if (table) {
return table
}
table = []
for (let i = 0; i < 256; ++i) {
table[i] = (i + 0x100).toString(16).substring(1)
}
return table
}
})()
// WHATWG crypto RNG - https://w3c.github.io/webcrypto/Overview.html
function whatwgRNG(length = 16) {
const rnds8 = new Uint8Array(length)
getRandomValues(rnds8)
return rnds8
}
export function randomKey(length?: number): string {
const table = getByteHexTable()
return whatwgRNG(length)
.reduce((str, n) => str + table[n], '')
.slice(0, length)
}