-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.ts
284 lines (263 loc) · 8.8 KB
/
index.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
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
import type { JSONContent, JSONEditorPropsOptional, TextContent } from 'vanilla-jsoneditor'
import type { App, Plugin, PropType } from 'vue-demi'
import { destr, safeDestr } from 'destr'
import { debounce } from 'lodash-es'
import { createJSONEditor, Mode } from 'vanilla-jsoneditor'
import { computed, defineComponent, getCurrentInstance, h, isVue3, onMounted, onUnmounted, ref, unref, watch, watchEffect } from 'vue-demi'
import { conclude, resolveConfig } from 'vue-global-config'
import { PascalCasedName as name } from '../package.json'
import { BOOL_ATTRS } from './constants'
type SFCWithInstall<T> = T & Plugin
type UpdatedContent = JSONContent & Partial<TextContent>
interface Parser { parse: typeof destr, stringify: typeof JSON.stringify }
const propsGlobal: Record<string, any> = {}
const attrsGlobal: Record<string, any> = {}
enum ModelValueProp {
vue3 = 'modelValue',
vue2 = 'value',
}
const modelValueProp: ModelValueProp = isVue3 ? ModelValueProp.vue3 : ModelValueProp.vue2
enum UpdateModelValueEvent {
vue3 = 'update:modelValue',
vue2 = 'input',
}
const updateModelValueEvent = isVue3 ? UpdateModelValueEvent.vue3 : UpdateModelValueEvent.vue2
const props = {
[modelValueProp]: {},
mode: {
type: String as PropType<Mode>,
},
debounce: {
type: Number as PropType<number>,
},
stringified: {
type: Boolean as PropType<boolean>,
default: undefined,
},
...Object.fromEntries(
BOOL_ATTRS.map(boolAttr => [
boolAttr,
{
type: Boolean as PropType<boolean>,
default: undefined,
},
]),
),
} as {
[key in ModelValueProp]: object
} & {
mode: { type: PropType<Mode> }
debounce: { type: PropType<number> }
stringified: { type: PropType<boolean>, default: undefined }
} & {
[key in typeof BOOL_ATTRS[number]]: {
type: PropType<boolean>
default: undefined
}
}
const JsonEditorVue = defineComponent({
name,
install(app: App, options?: typeof props): void {
const optionsGlobal = resolveConfig(options || {}, { props })
Object.assign(propsGlobal, optionsGlobal.props)
Object.assign(attrsGlobal, optionsGlobal.attrs)
app.component(name, this)
},
props,
emits: {
[updateModelValueEvent](_payload: any) {
return true
},
'update:mode': function (_payload: Mode) {
return true
},
},
setup(props, { attrs, emit, expose }) {
const currentInstance = getCurrentInstance()?.proxy
const jsonEditor = ref()
const preventUpdatingContent = ref(false)
const modeComputed = ref()
watchEffect(() => {
modeComputed.value = conclude([props.mode, propsGlobal.mode], {
type: String,
})
jsonEditor.value?.updateProps({
mode: modeComputed.value || Mode.tree,
})
})
const onChangeMode = (mode: Mode) => {
emit('update:mode', mode)
}
// Synchronize the local `mode` with the global one
if (propsGlobal.mode !== undefined && props.mode === undefined) {
onChangeMode(propsGlobal.mode)
}
const debounceComputed = computed(() => {
return conclude([props.debounce, propsGlobal.debounce, 300], {
type: Number,
})
})
const stringifiedComputed = computed(() => conclude([props.stringified, propsGlobal.stringified, true], {
type: Boolean,
}))
let parse = destr
const updateModelValue = (updatedContent: UpdatedContent) => {
preventUpdatingContent.value = true
if (!stringifiedComputed.value && updatedContent.text) {
if (jsonEditor.value && !jsonEditor.value.validate()) {
updatedContent.json = parse(updatedContent.text)
}
updatedContent.text = undefined
}
emit(
updateModelValueEvent,
updatedContent.text === undefined
? updatedContent.json
: updatedContent.text,
)
}
const updateModelValueDebounced = debounce(updateModelValue, debounceComputed.value)
const onChange = (updatedContent: UpdatedContent) => {
if (modeComputed.value === 'text') {
updateModelValueDebounced(updatedContent)
}
else {
updateModelValue(updatedContent)
}
}
const mergeFunction = (accumulator: (...args: any) => unknown, currentValue: (...args: any) => unknown) => (...args: any) => {
accumulator(...args)
currentValue(...args)
}
expose?.({ jsonEditor })
onUnmounted(() => {
jsonEditor.value?.destroy()
})
onMounted(() => {
const initialValue = conclude([props[modelValueProp], propsGlobal[modelValueProp]])
const initialBoolAttrs = Object.fromEntries(
Array.from(BOOL_ATTRS, boolAttr => [boolAttr, conclude([props[boolAttr], propsGlobal[boolAttr]])]).filter(
([, v]) => v !== undefined,
),
)
const initialAttrs = conclude(
[
initialBoolAttrs,
attrs,
attrsGlobal,
],
{
camelizeObjectKeys: true,
defaultIsDynamic: true,
default: (userProp: JSONEditorPropsOptional) => {
parse = (userProp.parser as Parser)?.parse || destr
return {
onChange,
onChangeMode,
mode: modeComputed.value,
// Can not just pass one of parse and stringify
parser: {
// SafeDestr is used by default so that it will not affect the result of jsonEditor.value.validate()
// When stringified is disabled, destr is used by default for better performance (destr is only called when JSON is valid)
parse: safeDestr,
stringify: JSON.stringify,
},
...(initialValue !== undefined && {
content: {
[(typeof initialValue === 'string' && modeComputed.value === 'text' && stringifiedComputed.value)
? 'text'
: 'json']: initialValue,
},
}),
}
},
mergeFunction,
mergeObject: 'shallow',
type: Object,
},
)
jsonEditor.value = createJSONEditor({
target: currentInstance?.$refs.jsonEditorRef as HTMLDivElement,
props: initialAttrs,
})
watch(
() => props[modelValueProp],
(newModelValue: any) => {
if (preventUpdatingContent.value) {
preventUpdatingContent.value = false
return
}
if (jsonEditor.value) {
// jsonEditor.value.update cannot render new props in json
// `undefined` is not accepted by vanilla-jsoneditor
// The default value is `{ text: '' }`
// Only default value can clear the editor
jsonEditor.value.set(
[undefined, ''].includes(newModelValue)
? {
text: '',
}
: {
[(typeof newModelValue === 'string' && modeComputed.value === 'text' && stringifiedComputed.value)
? 'text'
: 'json']: newModelValue,
},
)
}
},
{
deep: true,
},
)
watch(
() => Array.from(BOOL_ATTRS, boolAttr => props[boolAttr]),
(values) => {
jsonEditor.value?.updateProps(
Object.fromEntries(Array.from(values, (v, i) => [BOOL_ATTRS[i], v]).filter(([, v]) => v !== undefined)),
)
},
)
watch(
() => attrs,
(newAttrs) => {
// Functions need to be merged again
const defaultFunctionAttrs: {
onChange?: (...args: any) => unknown
onChangeMode?: (...args: any) => unknown
} = {}
if (newAttrs.onChange || newAttrs['on-change']) {
defaultFunctionAttrs.onChange = onChange
}
if (newAttrs.onChangeMode || newAttrs['on-change-mode']) {
defaultFunctionAttrs.onChangeMode = onChangeMode
}
parse = (newAttrs.parser as Parser)?.parse || destr
jsonEditor.value?.updateProps(
Object.getOwnPropertyNames(defaultFunctionAttrs).length > 0
? conclude([newAttrs, defaultFunctionAttrs], {
camelizeObjectKeys: true,
mergeFunction,
mergeObject: 'shallow',
type: Object,
})
: newAttrs,
)
},
{
deep: true,
},
)
// There's no `expose` in @vue/composition-api
if (!expose) {
expose = (exposed: Record<string, any> | undefined): void => {
for (const k in exposed) {
(currentInstance as any)[k] = unref(exposed[k])
}
}
expose({ jsonEditor })
}
})
return () => h('div', { ref: 'jsonEditorRef' })
},
})
export default JsonEditorVue as SFCWithInstall<typeof JsonEditorVue>