-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathApp.tsx
748 lines (720 loc) · 26.3 KB
/
App.tsx
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import React, { useEffect, useRef, lazy, Suspense } from 'react'
import { useSearch, useLocation } from 'wouter'
import JSON5 from 'json5'
import 'react-datepicker/dist/react-datepicker.css'
import {
JsonEditor,
Theme,
FilterFunction,
JsonData,
OnErrorFunction,
defaultTheme,
// Additional Themes
githubDarkTheme,
githubLightTheme,
monoLightTheme,
monoDarkTheme,
candyWrapperTheme,
psychedelicTheme,
} from './_imports'
import { FaNpm, FaExternalLinkAlt, FaGithub } from 'react-icons/fa'
import { BiReset } from 'react-icons/bi'
import { AiOutlineCloudUpload } from 'react-icons/ai'
import { useState } from 'react'
import useUndo from 'use-undo'
import {
Box,
Flex,
Heading,
Text,
Button,
Checkbox,
Select,
HStack,
VStack,
Link,
Icon,
CheckboxGroup,
Spacer,
FormControl,
FormLabel,
Input,
NumberInput,
NumberInputField,
NumberInputStepper,
NumberIncrementStepper,
NumberDecrementStepper,
useToast,
Tooltip,
} from '@chakra-ui/react'
import logo from './image/logo_400.png'
import { ArrowBackIcon, ArrowForwardIcon, InfoIcon } from '@chakra-ui/icons'
import { demoDataDefinitions } from './demoData'
import { useDatabase } from './useDatabase'
import './style.css'
import { version } from './version'
const CodeEditor = lazy(() => import('./CodeEditor'))
interface AppState {
rootName: string
indent: number
collapseLevel: number
collapseTime: number
showCount: 'Yes' | 'No' | 'When closed'
theme: Theme
allowEdit: boolean
allowDelete: boolean
allowAdd: boolean
allowCopy: boolean
sortKeys: boolean
showIndices: boolean
showStringQuotes: boolean
defaultNewValue: string
searchText: string
customTextEditor: boolean
}
const themes = [
defaultTheme,
githubDarkTheme,
githubLightTheme,
monoLightTheme,
monoDarkTheme,
candyWrapperTheme,
psychedelicTheme,
]
function App() {
const navigate = useLocation()[1]
const searchString = useSearch()
const queryParams = new URLSearchParams(searchString)
const selectedDataSet = queryParams.get('data') ?? 'intro'
const dataDefinition = demoDataDefinitions[selectedDataSet]
const [state, setState] = useState<AppState>({
rootName: dataDefinition.rootName ?? 'data',
indent: 2,
collapseLevel: dataDefinition.collapse ?? 2,
collapseTime: 300,
showCount: 'When closed',
theme: defaultTheme,
allowEdit: true,
allowDelete: true,
allowAdd: true,
allowCopy: true,
sortKeys: false,
showIndices: true,
showStringQuotes: true,
defaultNewValue: 'New data!',
searchText: '',
customTextEditor: false,
})
const [isSaving, setIsSaving] = useState(false)
const previousTheme = useRef<Theme>() // Used when resetting after theme editing
const toast = useToast()
const { liveData, loading, updateLiveData } = useDatabase()
const [
{ present: data, past, future },
{ set: setData, reset, undo: undoData, redo: redoData, canUndo, canRedo },
] = useUndo(selectedDataSet === 'editTheme' ? defaultTheme : dataDefinition.data)
// Provides a named version of these methods (i.e undo.name = "undo")
const undo = () => undoData()
const redo = () => redoData()
useEffect(() => {
if (selectedDataSet === 'liveData' && !loading && liveData) reset(liveData)
}, [loading, liveData, reset, selectedDataSet])
const updateState = (patch: Partial<AppState>) => setState({ ...state, ...patch })
const toggleState = (field: keyof AppState) => updateState({ [field]: !state[field] })
const {
searchText,
rootName,
theme,
indent,
collapseLevel,
collapseTime,
showCount,
showIndices,
sortKeys,
showStringQuotes,
allowCopy,
defaultNewValue,
allowEdit,
allowDelete,
allowAdd,
customTextEditor,
} = state
const restrictEdit: FilterFunction | boolean = (() => {
const customRestrictor = dataDefinition?.restrictEdit
if (typeof customRestrictor === 'function')
return (input) => !allowEdit || customRestrictor(input)
if (customRestrictor !== undefined) return customRestrictor
return !allowEdit
})()
const restrictDelete: FilterFunction | boolean = (() => {
const customRestrictor = dataDefinition?.restrictDelete
if (typeof customRestrictor === 'function')
return (input) => !allowDelete || customRestrictor(input)
if (customRestrictor !== undefined) return customRestrictor
return !allowDelete
})()
const restrictAdd: FilterFunction | boolean = (() => {
const customRestrictor = dataDefinition?.restrictAdd
if (typeof customRestrictor === 'function')
return (input) => !allowAdd || customRestrictor(input)
if (customRestrictor !== undefined) return customRestrictor
return !allowAdd
})()
const handleChangeData = (selected: string) => {
const newDataDefinition = demoDataDefinitions[selected]
setState({
...state,
searchText: '',
collapseLevel: newDataDefinition.collapse ?? state.collapseLevel,
rootName: newDataDefinition.rootName ?? 'data',
customTextEditor: false,
})
switch (selected) {
case 'editTheme':
previousTheme.current = theme
reset(theme)
break
case 'liveData':
if (!liveData) reset({ 'Oops!': "We couldn't load this data, sorry " })
else reset(liveData)
break
default:
reset(newDataDefinition.data)
}
if (selected === 'intro') navigate('./')
else navigate(`./?data=${selected}`)
}
const handleThemeChange = (e) => {
const theme = themes.find((th) => th.displayName === e.target.value)
if (!theme) return
updateState({ theme })
if (selectedDataSet === 'editTheme') {
setData(theme)
previousTheme.current = theme
}
}
const handleHistory = (method: () => void) => {
if (selectedDataSet === 'editTheme') {
const theme = (method.name === 'undo' ? past.slice(-1)[0] : future[0]) as Theme
updateState({ theme })
}
method()
}
const handleReset = async () => {
const newState = { ...state }
newState.searchText = ''
switch (selectedDataSet) {
case 'editTheme':
reset(previousTheme.current ?? defaultTheme)
newState.theme = previousTheme.current ?? defaultTheme
break
case 'liveData':
setIsSaving(true)
await updateLiveData(data)
setIsSaving(false)
toast({
title: 'Whoosh!',
description: 'Data saved!',
status: 'success',
duration: 5000,
isClosable: true,
})
reset(data)
break
default:
reset(dataDefinition.data)
}
setState(newState)
}
return (
<div className="App">
<Flex
px={8}
pt={4}
mb={-50}
align="flex-start"
justify="space-evenly"
wrap="wrap"
gap={4}
minH="100%"
>
<HStack w="100%" justify="space-between" align="flex-start">
<VStack align="flex-start" gap={3}>
<HStack align="flex-end" mt={2} gap={4} flexWrap="wrap">
<Flex gap={4} align="center">
<img src={logo} alt="logo" style={{ maxHeight: '3.5em' }} />
<Heading as="h1" size="3xl" variant="other">
json-edit-<span style={{ color: '#EA3788' }}>react</span>
</Heading>
</Flex>
<Text pb={0.5} variant="primary">
by{' '}
<Link href="https://github.com/CarlosNZ" isExternal>
<strong>@CarlosNZ</strong>
</Link>
</Text>
</HStack>
<Heading variant="sub">
A <span style={{ color: '#011C27' }}>React</span> component for editing or viewing
JSON/object data •{' '}
<Link
href="https://github.com/CarlosNZ/json-edit-react#readme"
isExternal
color="accent"
>
Docs <Icon boxSize={4} as={FaExternalLinkAlt} />
</Link>
</Heading>
</VStack>
<Flex align="center" gap={5}>
<a href="https://github.com/CarlosNZ/json-edit-react" target="_blank" rel="noreferrer">
<Icon boxSize="2em" as={FaGithub} color="secondary" />
</a>
<a
href="https://www.npmjs.com/package/json-edit-react"
target="_blank"
rel="noreferrer"
>
<Icon boxSize="3em" as={FaNpm} color="secondary" />
</a>
</Flex>
</HStack>
<VStack minW={400}>
<Heading size="lg" variant="accent">
Demo
</Heading>
<Box position="relative">
<Input
id="searchTextInput"
placeholder={dataDefinition.searchPlaceholder ?? 'Search values'}
bgColor={'#f6f6f6'}
borderColor="gainsboro"
borderRadius={50}
size="sm"
w={60}
value={searchText}
onChange={(e) => updateState({ searchText: e.target.value })}
position="absolute"
right={2}
top={2}
zIndex={100}
/>
<JsonEditor
data={data}
setData={setData as (data: JsonData) => void}
rootName={rootName}
theme={[theme, dataDefinition?.styles ?? {}, { container: { paddingTop: '1em' } }]}
indent={indent}
onUpdate={async (nodeData) => {
const demoOnUpdate = dataDefinition?.onUpdate ?? (() => undefined)
const result = await demoOnUpdate(nodeData, toast as (options: unknown) => void)
if (result) return result
else {
const { newData } = nodeData
if (selectedDataSet === 'editTheme') updateState({ theme: newData as Theme })
}
}}
onEdit={dataDefinition?.onEdit ?? undefined}
onAdd={dataDefinition?.onAdd ?? undefined}
onError={
dataDefinition.onError
? (errorData) => {
const error = (dataDefinition.onError as OnErrorFunction)(errorData)
toast({
title: 'ERROR 😢',
description: error as any,
status: 'error',
duration: 5000,
isClosable: true,
})
}
: undefined
}
showErrorMessages={dataDefinition.showErrorMessages}
collapse={collapseLevel}
collapseAnimationTime={collapseTime}
showCollectionCount={
showCount === 'Yes' ? true : showCount === 'When closed' ? 'when-closed' : false
}
enableClipboard={
allowCopy
? ({ stringValue, type, success, errorMessage }) => {
success
? toast({
title: `${type === 'value' ? 'Value' : 'Path'} copied to clipboard:`,
description: truncate(String(stringValue)),
status: 'success',
duration: 5000,
isClosable: true,
})
: toast({
title: 'Problem copying to clipboard',
description: errorMessage,
status: 'error',
duration: 5000,
isClosable: true,
})
}
: false
}
restrictEdit={restrictEdit}
// restrictEdit={(nodeData) => !(typeof nodeData.value === 'string')}
restrictDelete={restrictDelete}
restrictAdd={restrictAdd}
restrictTypeSelection={dataDefinition?.restrictTypeSelection}
restrictDrag={false}
searchFilter={dataDefinition?.searchFilter}
searchText={searchText}
keySort={sortKeys}
// keySort={
// sortKeys
// ? (a, b) => {
// const nameRev1 = String(a[0]).length
// const nameRev2 = String(b[0]).length
// if (nameRev1 < nameRev2) {
// return -1
// }
// if (nameRev1 > nameRev2) {
// return 1
// }
// return 0
// }
// : false
// }
defaultValue={dataDefinition?.defaultValue ?? defaultNewValue}
showArrayIndices={showIndices}
showStringQuotes={showStringQuotes}
minWidth={'min(500px, 95vw)'}
maxWidth="min(670px, 90vw)"
className="block-shadow"
stringTruncate={90}
customNodeDefinitions={dataDefinition?.customNodeDefinitions}
customText={dataDefinition?.customTextDefinitions}
// icons={{ chevron: <IconCancel size="1.2em" /> }}
// customButtons={[
// {
// Element: () => (
// <svg fill="none" viewBox="0 0 24 24" height="1em" width="1em">
// <path
// fill="currentColor"
// fillRule="evenodd"
// d="M12 21a9 9 0 100-18 9 9 0 000 18zm0 2c6.075 0 11-4.925 11-11S18.075 1 12 1 1 5.925 1 12s4.925 11 11 11z"
// clipRule="evenodd"
// />
// <path fill="currentColor" d="M16 12l-6 4.33V7.67L16 12z" />
// </svg>
// ),
// onClick: (nodeData, e) => console.log(nodeData),
// },
// ]}
onChange={dataDefinition?.onChange ?? undefined}
jsonParse={JSON5.parse}
// keyboardControls={{
// cancel: 'Tab',
// confirm: { key: 'Enter', modifier: 'Meta' },
// objectConfirm: { key: 'Enter', modifier: 'Shift' },
// stringLineBreak: { key: 'Enter' },
// stringConfirm: { key: 'Enter', modifier: 'Meta' },
// clipboardModifier: ['Alt', 'Shift'],
// collapseModifier: 'Control',
// booleanConfirm: 'Enter',
// booleanToggle: 'r',
// }}
// insertAtBeginning="object"
// rootFontSize={20}
TextEditor={
customTextEditor
? (props) => (
<Suspense
fallback={
<div className="loading" style={{ height: `${getLineHeight(data)}lh` }}>
Loading code editor...
</div>
}
>
<CodeEditor {...props} theme={theme?.displayName ?? ''} />
</Suspense>
)
: undefined
}
/>
</Box>
<VStack w="100%" align="flex-end" gap={4}>
<HStack w="100%" justify="space-between" mt={4}>
<Button
colorScheme="primaryScheme"
leftIcon={<ArrowBackIcon />}
onClick={() => handleHistory(undo)}
isDisabled={!canUndo}
>
Undo
</Button>
<Spacer />
<Button
colorScheme="primaryScheme"
rightIcon={<ArrowForwardIcon />}
onClick={() => handleHistory(redo)}
isDisabled={!canRedo}
>
Redo
</Button>
</HStack>
<HStack justify="space-between" w="100%">
<Text maxW={400} fontSize="md">
Undo/Redo functionality can be incorporated by using an additional hook, such as{' '}
<Link href="https://github.com/homerchen19/use-undo" isExternal>
use-undo
</Link>
</Text>
<Button
colorScheme="accentScheme"
leftIcon={selectedDataSet === 'liveData' ? <AiOutlineCloudUpload /> : <BiReset />}
variant="outline"
onClick={handleReset}
visibility={canUndo ? 'visible' : 'hidden'}
isLoading={isSaving}
>
{selectedDataSet === 'liveData' ? 'Push to the cloud' : 'Reset'}
</Button>
</HStack>
</VStack>
</VStack>
<VStack flexBasis={500}>
<Heading size="lg" variant="accent">
Options
</Heading>
<VStack backgroundColor="#f6f6f6" borderRadius={10} className="block-shadow">
<FormControl>
<VStack align="flex-start" m={4}>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Demo data
</FormLabel>
<div className="inputWidth" style={{ flexGrow: 1 }}>
<Select
id="dataSelect"
onChange={(e) => handleChangeData(e.target.value)}
value={selectedDataSet}
>
{Object.entries(demoDataDefinitions).map(([key, { name }]) => (
<option value={key} key={key}>
{name}
</option>
))}
</Select>
</div>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Theme
</FormLabel>
<div className="inputWidth" style={{ flexGrow: 1 }}>
<Select id="themeSelect" onChange={handleThemeChange} value={theme.displayName}>
{themes.map((theme) => (
<option value={theme.displayName} key={theme.displayName}>
{theme.displayName}
</option>
))}
</Select>
</div>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Data root name
</FormLabel>
<Input
id="dataNameInput"
className="inputWidth"
type="text"
value={rootName}
onChange={(e) => updateState({ rootName: e.target.value })}
/>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Collapse level
</FormLabel>
<NumberInput
id="collapseInput"
className="inputWidth"
min={0}
value={collapseLevel}
onChange={(value) => updateState({ collapseLevel: Number(value) })}
>
<NumberInputField />
<NumberInputStepper>
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Collapse animation time
</FormLabel>
<NumberInput
id="collapseTime"
className="inputWidth"
min={0}
value={collapseTime}
onChange={(value) => updateState({ collapseTime: Number(value) })}
>
<NumberInputField />
</NumberInput>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Indent level
</FormLabel>
<NumberInput
id="indentInput"
className="inputWidth"
max={12}
min={0}
value={indent}
onChange={(value) => updateState({ indent: Number(value) })}
>
<NumberInputField />
<NumberInputStepper>
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
</HStack>
<HStack className="inputRow">
<FormLabel className="labelWidth" textAlign="right">
Show counts
</FormLabel>
<div className="inputWidth" style={{ flexGrow: 1 }}>
<Select
id="showCountSelect"
onChange={(e) =>
updateState({ showCount: e.target.value as 'Yes' | 'No' | 'When closed' })
}
value={showCount}
>
<option value="Yes" key={0}>
Yes
</option>
<option value="No" key={1}>
No
</option>
<option value="When closed" key={2}>
When closed
</option>
</Select>
</div>
</HStack>
<CheckboxGroup colorScheme="primaryScheme">
<Flex w="100%" justify="flex-start">
<Checkbox
id="allowEditCheckbox"
isChecked={allowEdit}
disabled={dataDefinition.restrictEdit !== undefined}
onChange={() => toggleState('allowEdit')}
w="50%"
>
Allow Edit
</Checkbox>
<Checkbox
id="allowDeleteCheckbox"
isChecked={allowDelete}
disabled={dataDefinition.restrictDelete !== undefined}
onChange={() => toggleState('allowDelete')}
w="50%"
>
Allow Delete
</Checkbox>
</Flex>
<Flex w="100%" justify="flex-start">
<Checkbox
id="allowAddCheckbox"
isChecked={allowAdd}
disabled={dataDefinition.restrictAdd !== undefined}
onChange={() => toggleState('allowAdd')}
w="50%"
>
Allow Add
</Checkbox>
<Checkbox
id="allowCopyCheckbox"
isChecked={allowCopy}
onChange={() => toggleState('allowCopy')}
w="50%"
>
Enable clipboard
</Checkbox>
</Flex>
<Flex w="100%" justify="flex-start">
<Checkbox
id="showStringQuotesCheckbox"
isChecked={showStringQuotes}
onChange={() => toggleState('showStringQuotes')}
w="50%"
>
Show String quotes
</Checkbox>
<Checkbox
id="showIndicesCheckbox"
isChecked={showIndices}
onChange={() => toggleState('showIndices')}
w="50%"
>
Show Array indices
</Checkbox>
</Flex>
<Flex w="100%" justify="flex-start">
<Checkbox
id="sortKeysCheckbox"
isChecked={sortKeys}
onChange={() => toggleState('sortKeys')}
w="50%"
>
Sort Object keys
</Checkbox>
<HStack>
<Checkbox
id="customEditorCheckbox"
isChecked={customTextEditor}
onChange={() => toggleState('customTextEditor')}
disabled={!dataDefinition.customTextEditorAvailable}
>
Custom Text Editor
</Checkbox>
<Tooltip label="When in full JSON object edit">
<InfoIcon color="primaryScheme.500" />
</Tooltip>
</HStack>
</Flex>
<HStack className="inputRow" pt={2}>
<FormLabel className="labelWidth" textAlign="right">
Default new value
</FormLabel>
<Input
className="inputWidth"
disabled={dataDefinition.defaultValue !== undefined}
type="text"
value={defaultNewValue}
onChange={(e) => updateState({ defaultNewValue: e.target.value })}
/>
</HStack>
</CheckboxGroup>
</VStack>
</FormControl>
</VStack>
<Box maxW={350} pt={4}>
{dataDefinition.description}
</Box>
</VStack>
</Flex>
<Box h={50} />
<footer>
<Text fontSize="sm">{`json-edit-react v${version}`}</Text>
</footer>
</div>
)
}
export default App
export const truncate = (string: string, length = 200) =>
string.length < length ? string : `${string.slice(0, length - 2).trim()}...`
const getLineHeight = (data: JsonData) => JSON.stringify(data, null, 2).split('\n').length