-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
297 lines (285 loc) · 8.53 KB
/
main.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
285
286
287
288
289
290
291
292
293
294
295
296
297
import { EditorView } from "codemirror"
import json5 from "json5"
import { UseBoundStore, create } from "zustand"
import {
PersistOptions,
createJSONStorage,
devtools,
persist,
} from "zustand/middleware"
import { JSONModes } from "@/types/editor"
import { parse, serialize } from "@/lib/json"
import { toast } from "@/components/ui/use-toast"
import {
SchemaResponse,
SchemaSelectorValue,
} from "@/components/schema/schema-selector"
import { storage } from "./idb-store"
type JsonEditorState = {
mode?: JSONModes
theme?: string
instance?: EditorView
}
export type SchemaState = {
// metadata about the selected schema, formatted for autocomplete component
selectedSchema?: SchemaSelectorValue
// the actual schema object
schema?: Record<string, unknown>
schemaString?: string
testValueString?: string
// the initial schema value on change for the editor to set
// pristineSchema?: Record<string, unknown>
schemaError?: string
// an index of available schemas from SchemaStore.org
index: SchemaSelectorValue[]
indexError?: string
// the base $schema spec for the current `schema`
schemaSpec?: Record<string, unknown>
// user settings
userSettings: {
mode: JSONModes
}
// editors state
editors: {
schema: JsonEditorState
testValue: JsonEditorState
}
schemas: Record<string, Record<string, unknown>>
}
export type SchemaActions = {
setSelectedSchema: (
selectedSchema: Partial<SchemaSelectorValue> & { value: string }
) => Promise<void>
setSelectedSchemaFromUrl: (url: string) => Promise<void>
setSchema: (schema: Record<string, unknown>) => void
setSchemaString: (schema: string) => void
clearSelectedSchema: () => void
loadIndex: () => Promise<void>
setEditorSetting: <T = string>(
editor: keyof SchemaState["editors"],
setting: keyof JsonEditorState,
value: T
) => void
setEditorMode: (editor: keyof SchemaState["editors"], mode: JSONModes) => void
setTestValueString: (testValue: string) => void
getMode: (editorKey?: keyof SchemaState["editors"]) => JSONModes
fetchSchema: (
url: string
) => Promise<{ schemaString: string; schema: Record<string, unknown> }>
}
const persistOptions: PersistOptions<SchemaState & SchemaActions> = {
name: "jsonWorkBench",
storage: createJSONStorage(() => storage),
}
const initialState = {
userSettings: {
// theme: "system",
mode: JSONModes.JSON4,
// "editor.theme": "one-dark",
// "editor.keymap": "default",
// "editor.tabSize": 2,
// "editor.indentWithTabs": false,
},
editors: {
schema: {},
testValue: {},
},
schemas: {},
}
export const useMainStore = create<SchemaState & SchemaActions>()<
[["zustand/persist", unknown], ["zustand/devtools", never]]
>(
persist(
devtools((set, get) => ({
...initialState,
index: [],
clearSelectedSchema: () => {
set({
selectedSchema: undefined,
schema: undefined,
schemaError: undefined,
})
},
getMode: (editorKey?: keyof SchemaState["editors"]) => {
if (editorKey) {
return get().editors[editorKey].mode ?? get().userSettings.mode
}
return get().userSettings.mode
},
// don't set pristine schema here to avoid triggering updates
setSchema: (schema: Record<string, unknown>) => {
set({
schema,
schemaError: undefined,
schemaString: serialize(get().getMode("schema"), schema),
})
},
setSchemaString: (schema: string) => {
set({
schema: parse(get().getMode("schema"), schema),
schemaString: schema,
schemaError: undefined,
})
},
setTestValueString: (testValue) => {
set({
testValueString: testValue,
})
},
setEditorSetting: (editor, setting, value) => {
set((state) => ({
editors: {
...state.editors,
[editor]: {
...state.editors[editor],
[setting]: value,
},
},
}))
if (setting === "mode") {
const editorString = get()[`${editor}String`] ?? "{}"
set({
[`${editor}String`]:
value === "json5"
? json5.stringify(JSON.parse(editorString), null, 2)
: JSON.stringify(json5.parse(editorString), null, 2),
})
}
},
setEditorMode: (editor, mode) => {
set((state) => ({
editors: {
...state.editors,
[editor]: {
...state.editors[editor],
mode,
},
},
}))
},
fetchSchema: async (url: string) => {
const schemas = get().schemas
// serialize them to the json4/5 the schema editor is configured for
const mode = get().getMode("schema")
if (schemas[url]) {
const schema = schemas[url]!
return {
schemaString: serialize(mode, schema),
schema,
}
}
const data = await (
await fetch(
`/api/schema?${new URLSearchParams({
url,
})}`
)
).text()
const parsed = parse(mode, data)
schemas[url] = parsed
return { schemaString: data, schema: parsed }
},
setSelectedSchema: async (selectedSchema) => {
try {
let selected = selectedSchema
const { schemaString: data, schema } = await get().fetchSchema(
selectedSchema.value
)
if (!selectedSchema.label) {
selected = {
label:
schema.title ??
schema.description ??
(selectedSchema.value as string),
value: selectedSchema.value,
description: schema.title
? (schema.description as string)
: undefined,
} as SchemaSelectorValue
}
set({
selectedSchema: selected as SchemaSelectorValue,
schemaError: undefined,
})
// though it appears we are setting schema state twice,
// pristineSchema only changes on selecting a new schema
set({
schema: schema,
schemaString: data,
schemaError: undefined,
})
toast({
title: "Schema loaded",
description: selectedSchema.label,
})
} catch (err) {
// @ts-expect-error
const errMessage = err?.message || err
set({ schemaError: errMessage })
toast({
title: "Error loading schema",
description: errMessage,
variant: "destructive",
})
}
try {
const schema = get().schema
const schemaUrl =
schema && schema["$schema"]
? (schema["$schema"] as string)
: "https://json-schema.org/draft/2020-12/schema"
const { schema: schemaSpec } = await get().fetchSchema(schemaUrl)
set({ schemaSpec })
} catch (err) {
// @ts-expect-error
const errMessage = err?.message || err
set({ schemaError: errMessage })
toast({
title: "Error loading schema spec",
description: errMessage,
variant: "destructive",
})
}
},
setSelectedSchemaFromUrl: async (url) => {
const index = get().index
if (index) {
const selectedSchema = index.find((schema) => schema?.value === url)
if (selectedSchema) {
await get().setSelectedSchema(selectedSchema)
} else {
await get().setSelectedSchema({ value: url })
}
}
},
// this should only need to be called on render
loadIndex: async () => {
try {
if (!get().index?.length) {
const indexPayload: SchemaResponse = await (
await fetch("/api/schemas")
).json()
set({
indexError: undefined,
index: indexPayload.schemas.map((schema) => ({
value: schema.url,
label: schema.name,
...schema,
})),
})
}
} catch (err) {
// @ts-expect-error
const errMessage = err?.message || err
set({ indexError: errMessage })
toast({
title: "Error loading schema index",
description: errMessage,
variant: "destructive",
})
}
},
})),
persistOptions
)
)