-
Notifications
You must be signed in to change notification settings - Fork 411
/
gradientPatchAdapter.ts
114 lines (106 loc) · 3.15 KB
/
gradientPatchAdapter.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
import {arrayToJSONMatchPath} from '@sanity/mutator'
import assert from 'assert'
import {flatten} from 'lodash'
import {Origin, Patch} from '../../typedefs/patch'
import * as convertPath from './convertPath'
type GradientPatch = Record<string, any>
export function toGradient(patches: Patch[]): GradientPatch[] {
return patches.map(toGradientPatch)
}
export function toFormBuilder(origin: Origin, patches: GradientPatch[]): Patch[] {
return flatten(patches.map(patch => toFormBuilderPatches(origin, patch)))
}
const notIn = values => value => !values.includes(value)
function toFormBuilderPatches(origin: Origin, patch: GradientPatch): Patch[] {
return flatten(
Object.keys(patch)
.filter(notIn(['id', 'ifRevisionID', 'query']))
.map(type => {
if (type === 'unset') {
return patch.unset.map(path => {
return {
type: 'unset',
path: convertPath.toFormBuilder(path),
origin
}
})
}
if (type === 'insert') {
const position = 'before' in patch.insert ? 'before' : 'after'
return {
type: 'insert',
position: position,
path: convertPath.toFormBuilder(patch.insert[position]),
items: patch.insert.items,
origin
}
}
return Object.keys(patch[type])
.map(gradientPath => {
if (type === 'set') {
return {
type: 'set',
path: convertPath.toFormBuilder(gradientPath),
value: patch[type][gradientPath],
origin
}
}
if (type === 'inc' || type === 'dec') {
return {
type: type,
path: convertPath.toFormBuilder(gradientPath),
value: patch[type][gradientPath],
origin
}
}
if (type === 'setIfMissing') {
return {
type: 'setIfMissing',
path: convertPath.toFormBuilder(gradientPath),
value: patch[type][gradientPath],
origin
}
}
if (type === 'diffMatchPatch') {
return {
type: 'diffMatchPatch',
path: convertPath.toFormBuilder(gradientPath),
value: patch[type][gradientPath],
origin
}
}
console.warn(new Error(`Unsupported patch type: ${type}`))
return null
})
.filter(Boolean)
})
)
}
function toGradientPatch(patch: Patch): GradientPatch {
const matchPath = arrayToJSONMatchPath(patch.path || [])
if (patch.type === 'insert') {
const {position, items} = patch
return {
insert: {
[position]: matchPath,
items: items
}
}
}
if (patch.type === 'unset') {
return {
unset: [matchPath]
}
}
assert(patch.type, `Missing patch type in patch ${JSON.stringify(patch)}`)
if (matchPath) {
return {
[patch.type]: {
[matchPath]: patch.value
}
}
}
return {
[patch.type]: patch.value
}
}