json-edit-react 1.1.0 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1078 +1 @@
1
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
2
- import { createContext, useState, useContext, useEffect, useMemo, useRef, useCallback } from 'react';
3
- import assign from 'object-property-assigner';
4
- import extract from 'object-property-extractor';
5
- import clone from 'just-clone';
6
- import { HiOutlineClipboardCopy } from 'react-icons/hi';
7
- import { BiEdit, BiPlusCircle } from 'react-icons/bi';
8
- import { MdDeleteForever } from 'react-icons/md';
9
- import { FiCheckCircle } from 'react-icons/fi';
10
- import { TiCancel } from 'react-icons/ti';
11
- import { FaChevronDown } from 'react-icons/fa';
12
-
13
- /******************************************************************************
14
- Copyright (c) Microsoft Corporation.
15
-
16
- Permission to use, copy, modify, and/or distribute this software for any
17
- purpose with or without fee is hereby granted.
18
-
19
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
- PERFORMANCE OF THIS SOFTWARE.
26
- ***************************************************************************** */
27
- /* global Reflect, Promise, SuppressedError, Symbol */
28
-
29
-
30
- function __rest(s, e) {
31
- var t = {};
32
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
33
- t[p] = s[p];
34
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
35
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
36
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
37
- t[p[i]] = s[p[i]];
38
- }
39
- return t;
40
- }
41
-
42
- function __awaiter(thisArg, _arguments, P, generator) {
43
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
44
- return new (P || (P = Promise))(function (resolve, reject) {
45
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
46
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
47
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
48
- step((generator = generator.apply(thisArg, _arguments || [])).next());
49
- });
50
- }
51
-
52
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
53
- var e = new Error(message);
54
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
55
- };
56
-
57
- var e=[],t=[];function n(n,r){if(n&&"undefined"!=typeof document){var a,s=!0===r.prepend?"prepend":"append",d=!0===r.singleTag,i="string"==typeof r.container?document.querySelector(r.container):document.getElementsByTagName("head")[0];if(d){var u=e.indexOf(i);-1===u&&(u=e.push(i)-1,t[u]={}),a=t[u]&&t[u][s]?t[u][s]:t[u][s]=c();}else a=c();65279===n.charCodeAt(0)&&(n=n.substring(1)),a.styleSheet?a.styleSheet.cssText+=n:a.appendChild(document.createTextNode(n));}function c(){var e=document.createElement("style");if(e.setAttribute("type","text/css"),r.attributes)for(var t=Object.keys(r.attributes),n=0;n<t.length;n++)e.setAttribute(t[n],r.attributes[t[n]]);var a="prepend"===s?"afterbegin":"beforeend";return i.insertAdjacentElement(a,e),e}}
58
-
59
- var css = ":root {\n --jer-select-border: #b6b6b6;\n --jer-select-focus: #777;\n --jer-select-arrow: #777;\n --jer-form-border: 1px solid #ededf0;\n --jer-form-border-focus: 1px solid #e2e2e2;\n --jer-expand-transition-time: 0.5s;\n --jer-highlight-color: #b3d8ff;\n}\n\n.jer-visible {\n opacity: 1;\n transition: var(--jer-expand-transition-time);\n}\n\n.jer-hidden {\n opacity: 0;\n transition: var(--jer-expand-transition-time);\n}\n\n/* Select styled as per:\nhttps://moderncss.dev/custom-select-styles-with-pure-css/\n*/\n\n.jer-select select {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n background-color: transparent;\n border: none;\n padding: 0 1em 0 0;\n margin: 0;\n /* width: 100%; */\n font-family: inherit;\n font-size: inherit;\n color: black;\n cursor: inherit;\n line-height: inherit;\n z-index: 1;\n outline: none;\n}\nselect::-ms-expand {\n display: none;\n}\n\n.jer-select {\n display: grid;\n grid-template-areas: 'select';\n align-items: center;\n position: relative;\n min-width: 12ch;\n max-width: 15ch;\n border: 1px solid var(--jer-select-border);\n border-radius: 0.25em;\n padding: 0.25em 0.5em;\n font-size: 1em;\n cursor: pointer;\n line-height: 1.1;\n background-color: #fff;\n background-image: linear-gradient(to top, #f9f9f9, #fff 33%);\n}\n.jer-select select,\n.jer-select::after {\n grid-area: select;\n}\n.jer-select:not(.jer-select--multiple)::after {\n content: '';\n justify-self: end;\n width: 0.8em;\n height: 0.5em;\n background-color: var(--jer-select-arrow);\n -webkit-clip-path: polygon(100% 0%, 0 0%, 50% 100%);\n clip-path: polygon(100% 0%, 0 0%, 50% 100%);\n}\n\nselect:focus + .focus {\n position: absolute;\n top: -1px;\n left: -1px;\n right: -1px;\n bottom: -1px;\n border: 1px solid var(--jer-select-focus);\n border-radius: inherit;\n}\n\n.jer-editor-container {\n font-size: 1.1em;\n /* font-size: 20px; */\n padding: 1em;\n margin-top: 1em;\n margin-bottom: 1em;\n border-radius: 0.5em;\n}\n\n.jer-editor-container textarea {\n /* width: 90%; */\n color: var(--jer-input-color);\n border: var(--jer-form-border);\n border-radius: 0.3em;\n outline: none;\n}\n\n.jer-editor-container textarea:focus {\n border: var(--jer-form-border-focus);\n}\n\n.jer-editor-container input {\n border: var(--jer-form-border);\n border-radius: 0.3em;\n outline: none;\n}\n\n.jer-editor-container input:focus {\n border: var(--jer-form-border-focus);\n}\n\n/* Input highlighted text */\n.jer-editor-container ::selection {\n background-color: var(--jer-highlight-color);\n}\n\n.jer-editor-container select {\n /* color: red; */\n}\n\n.jer-component {\n}\n\n.jer-collection-header-row,\n.jer-value-main-row {\n display: flex;\n min-height: 1.7em;\n gap: 0.3em;\n align-items: center;\n}\n\n.jer-collection-header-row {\n display: flex;\n flex-wrap: wrap;\n}\n\n.jer-brackets {\n}\n\n.jer-collection-item-count {\n}\n\n.jer-collection-inner {\n position: relative;\n}\n\n.jer-collection-text-edit {\n display: flex;\n flex-direction: column;\n gap: 0.3em;\n align-items: flex-start;\n}\n\n.jer-collection-text-area {\n resize: both;\n padding-top: 0.2em;\n padding-left: 0.5em;\n padding-right: 0.5em;\n padding-bottom: 0;\n overflow: hidden;\n max-height: 40em;\n}\n\n.jer-collection-input-button-row {\n display: flex;\n justify-content: flex-end;\n font-size: 150%;\n}\n\n.jer-collection-element {\n}\n\n.jer-collection-error-row {\n position: absolute;\n bottom: 0;\n}\n\n.jer-collection-error-row-edit {\n}\n\n.jer-error-slug {\n margin-left: 1em;\n}\n\n.jer-value-component {\n position: relative;\n}\n\n.jer-value-main-row {\n display: flex;\n gap: 0;\n}\n\n.jer-value-and-buttons {\n display: flex;\n justify-content: flex-start;\n align-items: center;\n padding-left: 0.5em;\n}\n\n.jer-value-error-row {\n position: absolute;\n}\n\n.jer-value-string {\n line-height: 1.3em;\n}\n\n.jer-input-text {\n resize: none;\n margin: 0;\n height: 1.4em;\n padding-left: 0.5em;\n padding-right: 0.5em;\n padding-bottom: 0;\n min-width: 6em;\n overflow: hidden;\n max-height: 30em;\n}\n\n.jer-value-number {\n}\n\n.jer-value-boolean {\n}\n\n.jer-input-boolean {\n transform: scale(1.5);\n margin-left: 0.3em;\n margin-right: 0.3em;\n}\n\n.jer-value-null {\n}\n\n.jer-value-object {\n}\n\n.jer-object-key {\n word-break: break-word;\n line-height: 1.1em;\n}\n\n.jer-value-array {\n}\n\n.jer-value-invalid {\n opacity: 0.5;\n font-style: italic;\n}\n\n/* .jer-input-text, */\n.jer-input-number {\n height: 1.6em;\n}\n\n.jer-input-number {\n min-width: 3em;\n}\n\n.jer-input-component {\n}\n\n.jer-edit-buttons,\n.jer-confirm-buttons {\n display: flex;\n align-items: center;\n cursor: pointer;\n}\n\n.jer-input-buttons {\n gap: 0.4em;\n}\n\n.jer-edit-buttons {\n gap: 0.4em;\n margin-left: 0.5em;\n opacity: 0;\n}\n\n.jer-confirm-buttons {\n gap: 0.2em;\n margin-left: 0.4em;\n}\n\n.jer-edit-buttons:hover {\n opacity: 1;\n position: relative;\n}\n\n.jer-collection-header-row:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-value-main-row:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-value-and-buttons:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-input-buttons {\n}\n\n.jer-copy-pulse {\n position: relative;\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-copy-pulse:hover {\n opacity: 0.85;\n transition: 0.3s;\n transform: scale(1.2);\n}\n\n.jer-copy-pulse:after {\n content: '';\n display: block;\n position: absolute;\n border-radius: 50%;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n transition: all 0.5s;\n box-shadow: 0 0 15px 5px var(--jer-icon-copy-color);\n}\n\n.jer-copy-pulse:active:after {\n box-shadow: 0 0 0 0 var(--jer-icon-copy-color);\n position: absolute;\n border-radius: 4em;\n left: 0;\n top: 0;\n opacity: 1;\n transition: 0s;\n}\n\n.jer-copy-pulse:active {\n top: 0.07em;\n}\n\n.jer-rotate-90 {\n transform: rotate(-90deg);\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-accordion-icon {\n /* font-size: '2em'; */\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-icon:hover {\n opacity: 0.85;\n transition: 0.3s;\n transform: scale(1.2);\n}\n";
60
- n(css,{});
61
-
62
- const defaultTheme$1 = {
63
- displayName: 'Default',
64
- fragments: { edit: 'rgb(42, 161, 152)' },
65
- styles: {
66
- container: {
67
- backgroundColor: '#f6f6f6',
68
- fontFamily: 'monospace',
69
- },
70
- property: '#292929',
71
- bracket: { color: 'rgb(0, 43, 54)', fontWeight: 'bold' },
72
- itemCount: { color: 'rgba(0, 0, 0, 0.3)', fontStyle: 'italic' },
73
- string: 'rgb(203, 75, 22)',
74
- number: 'rgb(38, 139, 210)',
75
- boolean: 'green',
76
- null: { color: 'rgb(220, 50, 47)', fontVariant: 'small-caps', fontWeight: 'bold' },
77
- input: ['#292929', { fontSize: '90%' }],
78
- inputHighlight: '#b3d8ff',
79
- error: { fontSize: '0.8em', color: 'red', fontWeight: 'bold' },
80
- iconCollection: 'rgb(0, 43, 54)',
81
- iconEdit: 'edit',
82
- iconDelete: 'rgb(203, 75, 22)',
83
- iconAdd: 'edit',
84
- iconCopy: 'rgb(38, 139, 210)',
85
- iconOk: 'green',
86
- iconCancel: 'rgb(203, 75, 22)',
87
- },
88
- };
89
- const themes = {
90
- default: defaultTheme$1,
91
- githubDark: {
92
- displayName: 'Github Dark',
93
- styles: {
94
- container: {
95
- backgroundColor: '#0d1117',
96
- color: 'white',
97
- },
98
- property: '#E6EDF3',
99
- bracket: '#56d364',
100
- itemCount: '#8B949E',
101
- string: '#A5D6FF',
102
- number: '#D2A8FF',
103
- boolean: { color: '#FF7B72', fontSize: '90%', fontWeight: 'bold' },
104
- null: 'green',
105
- iconCollection: '#D2A8FF',
106
- iconEdit: '#D2A8FF',
107
- iconDelete: 'rgb(203, 75, 22)',
108
- iconAdd: 'rgb(203, 75, 22)',
109
- iconCopy: '#A5D6FF',
110
- iconOk: '#56d364',
111
- iconCancel: 'rgb(203, 75, 22)',
112
- },
113
- },
114
- githubLight: {
115
- displayName: 'Github Light',
116
- styles: {
117
- container: 'white',
118
- property: '#1F2328',
119
- bracket: '#00802e',
120
- itemCount: '#8B949E',
121
- string: '#0A3069',
122
- number: '#953800',
123
- boolean: { color: '#CF222E', fontSize: '90%', fontWeight: 'bold' },
124
- null: '#FF7B72',
125
- iconCollection: '#8250DF',
126
- iconEdit: '#8250DF',
127
- iconDelete: 'rgb(203, 75, 22)',
128
- iconAdd: '#8250DF',
129
- iconCopy: '#57606A',
130
- },
131
- },
132
- monoDark: {
133
- displayName: 'Black & White',
134
- fragments: {
135
- lightText: { color: 'white' },
136
- midGrey: '#5c5c5c',
137
- },
138
- styles: {
139
- container: ['lightText', { backgroundColor: 'black' }],
140
- property: 'lightText',
141
- bracket: 'midGrey',
142
- itemCount: '#4a4a4a',
143
- string: '#a8a8a8',
144
- number: '#666666',
145
- boolean: { color: '#848484', fontStyle: 'italic' },
146
- null: '#333333',
147
- iconCollection: 'midGrey',
148
- iconEdit: 'midGrey',
149
- iconDelete: 'midGrey',
150
- iconAdd: 'midGrey',
151
- iconCopy: 'midGrey',
152
- iconOk: 'midGrey',
153
- iconCancel: 'midGrey',
154
- },
155
- },
156
- monoLight: {
157
- fragments: { midGrey: '#a3a3a3' },
158
- displayName: 'White & Black',
159
- styles: {
160
- container: 'white',
161
- property: 'black',
162
- bracket: 'midGrey',
163
- itemCount: '#b5b5b5',
164
- string: '#575757',
165
- number: '#999999',
166
- boolean: { color: '#7b7b7b', fontStyle: 'italic' },
167
- null: '#cccccc',
168
- iconCollection: 'midGrey',
169
- iconEdit: 'midGrey',
170
- iconDelete: 'midGrey',
171
- iconAdd: 'midGrey',
172
- iconCopy: 'midGrey',
173
- iconOk: 'midGrey',
174
- iconCancel: 'midGrey',
175
- },
176
- },
177
- candyWrapper: {
178
- displayName: 'Candy Wrapper',
179
- fragments: {
180
- minty: { backgroundColor: '#F1FAEE' },
181
- pale: { color: '#A8DADC' },
182
- mid: { color: '#457B9D' },
183
- dark: { color: '#1D3557' },
184
- pop: { color: '#E63946' },
185
- darkBlue: { color: '#2B2D42' },
186
- },
187
- styles: {
188
- container: 'minty',
189
- property: 'pop',
190
- bracket: 'dark',
191
- itemCount: 'pale',
192
- string: 'mid',
193
- number: ['darkBlue', { fontSize: '85%' }],
194
- boolean: ['mid', { fontStyle: 'italic', fontWeight: 'bold', fontSize: '80%' }],
195
- null: ['#cccccc', { fontWeight: 'bold' }],
196
- iconCollection: '#1D3557',
197
- iconEdit: '#457B9D',
198
- iconDelete: '#E63946',
199
- iconAdd: '#2B2D42',
200
- iconCopy: '#1D3557',
201
- iconCancel: '#E63946',
202
- },
203
- },
204
- psychedelic: {
205
- displayName: 'Psychedelic',
206
- fragments: {
207
- minty: {
208
- backgroundColor: '#F1FAEE',
209
- },
210
- pale: {
211
- color: '#A8DADC',
212
- },
213
- mid: {
214
- color: '#457B9D',
215
- },
216
- dark: {
217
- color: '#1D3557',
218
- },
219
- pop: {
220
- color: '#E63946',
221
- },
222
- fluroYellow: 'rgb(242, 228, 21)',
223
- fluroGreen: 'rgb(68, 255, 62)',
224
- hotPink: '#f7379a',
225
- },
226
- styles: {
227
- container: {
228
- backgroundColor: 'unset',
229
- background: 'linear-gradient(90deg, hsla(333, 100%, 53%, 1) 0%, hsla(33, 94%, 57%, 1) 100%)',
230
- color: 'black',
231
- },
232
- property: 'black',
233
- bracket: 'fluroYellow',
234
- itemCount: [
235
- 'pale',
236
- {
237
- opacity: 0.7,
238
- },
239
- ],
240
- string: 'white',
241
- number: [
242
- '#33d9ff',
243
- {
244
- fontSize: '90%',
245
- fontWeight: 'bold',
246
- },
247
- ],
248
- boolean: [
249
- 'fluroGreen',
250
- {
251
- fontWeight: 'bold',
252
- fontSize: '80%',
253
- },
254
- ],
255
- null: [
256
- 'black',
257
- {
258
- fontWeight: 'bold',
259
- opacity: 0.3,
260
- backgroundColor: 'rgb(255, 255, 255, 0.5)',
261
- padding: '0 0.4em',
262
- borderRadius: '0.4em',
263
- },
264
- ],
265
- iconCollection: 'fluroYellow',
266
- iconEdit: ['black'],
267
- iconDelete: [
268
- 'white',
269
- {
270
- opacity: 0.5,
271
- },
272
- ],
273
- iconAdd: [
274
- 'white',
275
- {
276
- opacity: 0.5,
277
- },
278
- ],
279
- iconCopy: 'rgb(32, 84, 242)',
280
- iconOk: 'fluroGreen',
281
- iconCancel: 'hotPink',
282
- },
283
- },
284
- };
285
- const emptyStyleObject = {
286
- container: {},
287
- property: {},
288
- bracket: {},
289
- itemCount: {},
290
- string: {},
291
- number: {},
292
- boolean: {},
293
- null: {},
294
- input: {},
295
- inputHighlight: {},
296
- error: {},
297
- iconCollection: {},
298
- iconEdit: {},
299
- iconDelete: {},
300
- iconAdd: {},
301
- iconCopy: {},
302
- iconOk: {},
303
- iconCancel: {},
304
- };
305
-
306
- const defaultTheme = themes.default;
307
- const initialContext = {
308
- styles: emptyStyleObject,
309
- setTheme: (_) => { },
310
- icons: {},
311
- setIcons: () => { },
312
- };
313
- const ThemeProviderContext = createContext(initialContext);
314
- const ThemeProvider = ({ children }) => {
315
- const [styles, setStyles] = useState(emptyStyleObject);
316
- const [icons, setIcons] = useState({});
317
- const setTheme = (theme) => setStyles(compileStyles(theme));
318
- return (jsx(ThemeProviderContext.Provider, { value: { styles, setTheme, icons, setIcons }, children: children }));
319
- };
320
- const useTheme = () => useContext(ThemeProviderContext);
321
- const compileStyles = (themeInput) => {
322
- if (typeof themeInput === 'string')
323
- return buildStyleObject(themes[themeInput]);
324
- if (Array.isArray(themeInput)) {
325
- const [name, overrides] = themeInput;
326
- return buildStyleObject(themes[name], isStyleObject(overrides) ? { styles: overrides } : overrides);
327
- }
328
- return buildStyleObject(defaultTheme, isStyleObject(themeInput) ? { styles: themeInput } : themeInput);
329
- };
330
- const buildStyleObject = (baseTheme, overrides = { styles: emptyStyleObject }) => {
331
- var _a, _b, _c, _d;
332
- const [defaultStyles, baseStyles, overrideStyles] = [defaultTheme, baseTheme, overrides].map((theme) => {
333
- const { fragments, styles } = theme;
334
- const compiledStyles = {};
335
- Object.entries(styles).forEach(([key, value]) => {
336
- const elements = Array.isArray(value) ? value : [value];
337
- const cssStyles = elements.reduce((acc, curr) => {
338
- var _a;
339
- if (typeof curr === 'string') {
340
- const style = (_a = fragments === null || fragments === void 0 ? void 0 : fragments[curr]) !== null && _a !== void 0 ? _a : curr;
341
- switch (typeof style) {
342
- case 'string':
343
- return Object.assign(Object.assign({}, acc), { [defaultStyleProperties[key]]: style });
344
- default:
345
- return Object.assign(Object.assign({}, acc), style);
346
- }
347
- }
348
- else
349
- return Object.assign(Object.assign({}, acc), curr);
350
- }, {});
351
- compiledStyles[key] = cssStyles;
352
- });
353
- return compiledStyles;
354
- });
355
- const finalStyles = {};
356
- Object.keys(defaultTheme.styles).forEach((key) => {
357
- finalStyles[key] = Object.assign(Object.assign(Object.assign({}, defaultStyles[key]), baseStyles[key]), overrideStyles[key]);
358
- });
359
- if ((_a = finalStyles === null || finalStyles === void 0 ? void 0 : finalStyles.inputHighlight) === null || _a === void 0 ? void 0 : _a.backgroundColor)
360
- document.documentElement.style.setProperty('--jer-highlight-color', (_b = finalStyles === null || finalStyles === void 0 ? void 0 : finalStyles.inputHighlight) === null || _b === void 0 ? void 0 : _b.backgroundColor);
361
- if ((_c = finalStyles === null || finalStyles === void 0 ? void 0 : finalStyles.iconCopy) === null || _c === void 0 ? void 0 : _c.color)
362
- document.documentElement.style.setProperty('--jer-icon-copy-color', (_d = finalStyles === null || finalStyles === void 0 ? void 0 : finalStyles.iconCopy) === null || _d === void 0 ? void 0 : _d.color);
363
- return finalStyles;
364
- };
365
- const isStyleObject = (overrideObject) => {
366
- return !('styles' in overrideObject);
367
- };
368
- const defaultStyleProperties = {
369
- container: 'backgroundColor',
370
- property: 'color',
371
- bracket: 'color',
372
- itemCount: 'color',
373
- string: 'color',
374
- number: 'color',
375
- boolean: 'color',
376
- null: 'color',
377
- input: 'color',
378
- inputHighlight: 'backgroundColor',
379
- error: 'color',
380
- iconCollection: 'color',
381
- iconEdit: 'color',
382
- iconDelete: 'color',
383
- iconAdd: 'color',
384
- iconCopy: 'color',
385
- iconOk: 'color',
386
- iconCancel: 'color',
387
- };
388
-
389
- const AutogrowTextArea = ({ className, name, value, setValue, handleKeyPress, }) => {
390
- const { styles } = useTheme();
391
- const dummyValue = value.slice(-1) === '\n' ? value + '.' : value;
392
- return (jsxs("div", { style: { display: 'grid' }, children: [jsx("textarea", { style: Object.assign({ height: 'auto', gridArea: '1 / 1 / 2 / 2', overflowY: 'auto' }, styles.input), rows: 1, className: className, name: name, value: value, onChange: (e) => setValue(e.target.value), autoFocus: true, onFocus: (e) => {
393
- if (value.length < 40)
394
- e.target.select();
395
- }, onKeyDown: handleKeyPress }), jsx("span", { className: className, style: Object.assign({ visibility: 'hidden', height: 'auto', gridArea: '1 / 1 / 2 / 2', color: 'red', opacity: 0.9, whiteSpace: 'pre-wrap', overflow: 'clip', border: '1px solid transparent' }, styles.input), children: dummyValue })] }));
396
- };
397
-
398
- const INVALID_FUNCTION_STRING = '**INVALID_FUNCTION**';
399
- const truncate = (string, length = 200) => string.length < length ? string : `${string.slice(0, length - 2).trim()}...`;
400
- const StringValue = ({ value, setValue, isEditing, path, setIsEditing, handleEdit, handleCancel, stringTruncate, }) => {
401
- const { styles } = useTheme();
402
- const handleKeyPress = (e) => {
403
- if (e.key === 'Enter' && !e.shiftKey)
404
- handleEdit();
405
- else if (e.key === 'Escape')
406
- handleCancel();
407
- };
408
- const breakString = (text) => text.split('\n').map((line, index, arr) => (jsxs("span", { children: [line, index < arr.length - 1 ? jsx("br", {}) : null] }, index)));
409
- return isEditing ? (jsx(AutogrowTextArea, { className: "jer-input-text", name: path.join('.'), value: value, setValue: setValue, isEditing: isEditing, handleKeyPress: handleKeyPress })) : (jsxs("div", { onDoubleClick: () => setIsEditing(true), onClick: (e) => {
410
- if (e.getModifierState('Control') || e.getModifierState('Meta'))
411
- setIsEditing(true);
412
- }, className: "jer-value-string", style: styles.string, children: ["\"", breakString(truncate(value, stringTruncate)), "\""] }));
413
- };
414
- const NumberValue = ({ value, setValue, isEditing, path, setIsEditing, handleEdit, handleCancel, }) => {
415
- const { styles } = useTheme();
416
- const handleKeyPress = (e) => {
417
- if (e.key === 'Enter')
418
- handleEdit();
419
- else if (e.key === 'Escape')
420
- handleCancel();
421
- };
422
- const validateNumber = (input) => {
423
- return input.replace(/[^0-9.-]/g, '');
424
- };
425
- return isEditing ? (jsx("input", { className: "jer-input-number", type: "text", name: path.join('.'), value: value, onChange: (e) => setValue(validateNumber(e.target.value)), autoFocus: true, onFocus: (e) => e.target.select(), onKeyDown: handleKeyPress, style: { width: `${String(value).length / 1.5 + 2}em` } })) : (jsx("span", { onDoubleClick: () => setIsEditing(true), className: "jer-value-number", style: styles.number, children: value }));
426
- };
427
- const BooleanValue = ({ value, setValue, isEditing, path, setIsEditing, handleEdit, handleCancel, }) => {
428
- const { styles } = useTheme();
429
- useEffect(() => {
430
- if (isEditing)
431
- document.addEventListener('keydown', listenForSubmit);
432
- return () => document.removeEventListener('keydown', listenForSubmit);
433
- }, [isEditing]);
434
- const listenForSubmit = (event) => {
435
- if (event.key === 'Enter') {
436
- handleEdit();
437
- }
438
- else if (event.key === 'Escape')
439
- handleCancel();
440
- };
441
- return isEditing ? (jsx("input", { className: "jer-input-boolean", type: "checkbox", name: path.join('.'), checked: value, onChange: () => setValue(!value) })) : (jsx("span", { onDoubleClick: () => setIsEditing(true), className: "jer-value-boolean", style: styles.boolean, children: String(value) }));
442
- };
443
- const NullValue = ({ value, isEditing, setIsEditing, handleEdit, handleCancel, }) => {
444
- const { styles } = useTheme();
445
- useEffect(() => {
446
- if (isEditing)
447
- document.addEventListener('keydown', listenForSubmit);
448
- return () => document.removeEventListener('keydown', listenForSubmit);
449
- }, [isEditing]);
450
- const listenForSubmit = (event) => {
451
- if (event.key === 'Enter') {
452
- handleEdit();
453
- }
454
- else if (event.key === 'Escape')
455
- handleCancel();
456
- };
457
- return isEditing ? (jsx("div", { className: "jer-input-null", children: "null" })) : (jsx("div", { onDoubleClick: () => setIsEditing(true), className: "jer-value-null", style: styles.null, children: String(value) }));
458
- };
459
- const ObjectValue = ({ value, translate, isEditing, handleEdit, handleCancel, }) => {
460
- useEffect(() => {
461
- if (isEditing)
462
- document.addEventListener('keydown', listenForSubmit);
463
- return () => document.removeEventListener('keydown', listenForSubmit);
464
- }, []);
465
- const listenForSubmit = (event) => {
466
- if (event.key === 'Enter') {
467
- handleEdit();
468
- }
469
- else if (event.key === 'Escape')
470
- handleCancel();
471
- };
472
- return (jsx("span", { className: "jer-value-object", children: `{${translate('DEFAULT_NEW_KEY')}: "${value}" }` }));
473
- };
474
- const ArrayValue = ({ value, isEditing, handleEdit, handleCancel, }) => {
475
- useEffect(() => {
476
- if (isEditing)
477
- document.addEventListener('keydown', listenForSubmit);
478
- return () => document.removeEventListener('keydown', listenForSubmit);
479
- }, []);
480
- const listenForSubmit = (event) => {
481
- if (event.key === 'Enter') {
482
- handleEdit();
483
- }
484
- else if (event.key === 'Escape')
485
- handleCancel();
486
- };
487
- return jsx("span", { className: "jer-value-array", children: `[${value === null ? '' : value}]` });
488
- };
489
- const InvalidValue = ({ value }) => {
490
- let message = 'Error!';
491
- switch (typeof value) {
492
- case 'string':
493
- if (value === INVALID_FUNCTION_STRING)
494
- message = 'Function';
495
- break;
496
- case 'undefined':
497
- message = 'Undefined';
498
- break;
499
- case 'symbol':
500
- message = 'Symbol';
501
- break;
502
- }
503
- return jsx("span", { className: "jer-value-invalid", children: message });
504
- };
505
-
506
- const Icon = ({ name, rotate }) => {
507
- var _a, _b, _c, _d, _e, _f, _g;
508
- const { styles, icons } = useTheme();
509
- const commonProps = { size: '1.4em', className: 'jer-icon' };
510
- switch (name) {
511
- case 'add':
512
- return (_a = icons === null || icons === void 0 ? void 0 : icons.add) !== null && _a !== void 0 ? _a : jsx(BiPlusCircle, Object.assign({}, commonProps, { style: styles.iconAdd }));
513
- case 'edit':
514
- return (_b = icons === null || icons === void 0 ? void 0 : icons.edit) !== null && _b !== void 0 ? _b : jsx(BiEdit, Object.assign({}, commonProps, { style: styles.iconEdit }));
515
- case 'delete':
516
- return ((_c = icons === null || icons === void 0 ? void 0 : icons.delete) !== null && _c !== void 0 ? _c : jsx(MdDeleteForever, Object.assign({}, commonProps, { style: styles.iconDelete, size: "1.5em" })));
517
- case 'copy':
518
- return (_d = icons === null || icons === void 0 ? void 0 : icons.copy) !== null && _d !== void 0 ? _d : jsx(HiOutlineClipboardCopy, Object.assign({}, commonProps, { style: styles.iconCopy }));
519
- case 'ok':
520
- return ((_e = icons === null || icons === void 0 ? void 0 : icons.ok) !== null && _e !== void 0 ? _e : (jsx(FiCheckCircle, Object.assign({}, commonProps, { style: Object.assign({ fontSize: '90%' }, styles.iconOk) }))));
521
- case 'cancel':
522
- return ((_f = icons === null || icons === void 0 ? void 0 : icons.cancel) !== null && _f !== void 0 ? _f : (jsx(TiCancel, Object.assign({}, commonProps, { style: Object.assign({ fontSize: '130%' }, styles.iconCancel) }))));
523
- case 'chevron':
524
- return ((_g = icons === null || icons === void 0 ? void 0 : icons.chevron) !== null && _g !== void 0 ? _g : (jsx(FaChevronDown, { className: `jer-accordion-icon${rotate ? ' jer-rotate-90' : ''}`, style: styles.iconCollection })));
525
- default:
526
- return jsx(Fragment, {});
527
- }
528
- };
529
-
530
- const EditButtons = ({ startEdit, handleDelete, handleAdd, enableClipboard, type, data, path, name, translate, }) => {
531
- const { styles } = useTheme();
532
- const NEW_KEY_PROMPT = translate('KEY_NEW');
533
- const [isAdding, setIsAdding] = useState(false);
534
- const [newKey, setNewKey] = useState(NEW_KEY_PROMPT);
535
- useEffect(() => {
536
- if (!isAdding)
537
- setNewKey(NEW_KEY_PROMPT);
538
- }, [isAdding]);
539
- const handleKeyPress = (e) => {
540
- if (e.key === 'Enter' && handleAdd) {
541
- setIsAdding(false);
542
- handleAdd(newKey);
543
- }
544
- else if (e.key === 'Escape')
545
- setIsAdding(false);
546
- };
547
- const handleCopy = (e) => {
548
- let copyType = 'value';
549
- let value;
550
- let stringValue = '';
551
- if (enableClipboard) {
552
- switch (e.ctrlKey || e.metaKey) {
553
- case true:
554
- value = stringifyPath(path);
555
- stringValue = value;
556
- copyType = 'path';
557
- break;
558
- default:
559
- value = data;
560
- stringValue = type ? JSON.stringify(data, null, 2) : String(value);
561
- }
562
- navigator.clipboard.writeText(stringValue);
563
- }
564
- if (typeof enableClipboard === 'function')
565
- enableClipboard({ value, stringValue, path, key: name, type: copyType });
566
- };
567
- return (jsxs("div", { className: "jer-edit-buttons", style: isAdding ? { opacity: 1 } : undefined, children: [enableClipboard && (jsx("div", { onClick: handleCopy, className: "jer-copy-pulse", children: jsx(Icon, { name: "copy" }) })), startEdit && (jsx("div", { onClick: startEdit, children: jsx(Icon, { name: "edit" }) })), handleDelete && (jsx("div", { onClick: handleDelete, children: jsx(Icon, { name: "delete" }) })), handleAdd && (jsx("div", { onClick: () => {
568
- if (type === 'object')
569
- setIsAdding(true);
570
- else
571
- handleAdd('');
572
- }, children: jsx(Icon, { name: "add" }) })), isAdding && handleAdd && type === 'object' && (jsxs(Fragment, { children: [jsx("input", { className: "jer-input-new-key", type: "text", name: "new-object-key", value: newKey, onChange: (e) => setNewKey(e.target.value), autoFocus: true, onFocus: (e) => e.target.select(), onKeyDown: handleKeyPress, style: Object.assign({}, styles.input) }), jsx(InputButtons, { onOk: () => {
573
- if (!!newKey) {
574
- setIsAdding(false);
575
- handleAdd(newKey);
576
- }
577
- }, onCancel: () => {
578
- setIsAdding(false);
579
- } })] }))] }));
580
- };
581
- const InputButtons = ({ onOk, onCancel }) => {
582
- return (jsxs("div", { className: "jer-confirm-buttons", children: [jsx("div", { onClick: onOk, children: jsx(Icon, { name: "ok" }) }), jsx("div", { onClick: onCancel, children: jsx(Icon, { name: "cancel" }) })] }));
583
- };
584
- const stringifyPath = (path) => path.reduce((str, part) => {
585
- if (typeof part === 'number')
586
- return `${str}[${part}]`;
587
- else
588
- return str === '' ? part : `${str}.${part}`;
589
- }, '');
590
-
591
- const ERROR_DISPLAY_TIME = 2500;
592
- const ValueDataTypes = ['string', 'number', 'boolean', 'null'];
593
- const CollectionDataTypes = ['object', 'array'];
594
- const DataTypes = [...ValueDataTypes, ...CollectionDataTypes];
595
-
596
- const getCustomNode = (customNodeDefinitions = [], filterProps) => {
597
- const matchingDefinitions = customNodeDefinitions.filter(({ condition }) => condition(filterProps));
598
- if (matchingDefinitions.length === 0)
599
- return {};
600
- const { element, props, hideKey = false } = matchingDefinitions[0];
601
- return { CustomNode: element, customNodeProps: props, hideKey };
602
- };
603
-
604
- const CustomNodeWrapper = ({ name, hideKey, children, indent, }) => {
605
- const { styles } = useTheme();
606
- const indentStyle = indent ? { marginLeft: `${indent / 2}em` } : {};
607
- return (jsx("div", { className: "jer-component jer-value-component", style: indentStyle, children: jsxs("div", { className: "jer-value-main-row", style: {
608
- flexWrap: name.length > 10 ? 'wrap' : 'nowrap',
609
- }, children: [!hideKey && (jsxs("label", { htmlFor: name, className: "jer-object-key", style: Object.assign(Object.assign({}, styles.property), { minWidth: `${Math.min(String(name).length + 1, 5)}ch`, flexShrink: name.length > 10 ? 1 : 0 }), children: [name, ":", ' '] })), jsx("div", { className: "jer-value-and-buttons", style: { paddingLeft: hideKey ? 0 : undefined }, children: children })] }) }));
610
- };
611
-
612
- const ValueNodeWrapper = (props) => {
613
- const { data, parentData, name, path, onEdit, onDelete, enableClipboard, restrictEditFilter, restrictDeleteFilter, restrictTypeSelection, showLabel, stringTruncate, indent, translate, customNodeDefinitions, } = props;
614
- const { styles } = useTheme();
615
- const [isEditing, setIsEditing] = useState(false);
616
- const [isEditingKey, setIsEditingKey] = useState(false);
617
- const [value, setValue] = useState(typeof data === 'function' ? INVALID_FUNCTION_STRING : data);
618
- const [error, setError] = useState(null);
619
- const [dataType, setDataType] = useState(getDataType(data));
620
- useEffect(() => {
621
- setValue(typeof data === 'function' ? INVALID_FUNCTION_STRING : data);
622
- setDataType(getDataType(data));
623
- }, [data, error]);
624
- const handleChangeDataType = (type) => {
625
- const customNode = customNodeDefinitions.find((customNode) => customNode.name === type);
626
- if (customNode) {
627
- onEdit(customNode.defaultValue, path);
628
- }
629
- else {
630
- setValue(convertValue(value, type));
631
- setDataType(type);
632
- }
633
- };
634
- const logError = (errorString) => {
635
- setError(errorString);
636
- setTimeout(() => setError(null), ERROR_DISPLAY_TIME);
637
- console.log('Error', errorString);
638
- };
639
- const handleEdit = () => {
640
- setIsEditing(false);
641
- let newValue;
642
- switch (dataType) {
643
- case 'object':
644
- newValue = { [translate('DEFAULT_NEW_KEY')]: value };
645
- break;
646
- case 'array':
647
- newValue = value !== null ? value : [];
648
- break;
649
- case 'number':
650
- const n = Number(value);
651
- if (isNaN(n))
652
- newValue = 0;
653
- else
654
- newValue = n;
655
- break;
656
- default:
657
- newValue = value;
658
- }
659
- onEdit(newValue, path).then((error) => {
660
- if (error)
661
- logError(error);
662
- });
663
- };
664
- const handleEditKey = (newKey) => {
665
- setIsEditingKey(false);
666
- if (!parentData)
667
- return;
668
- const parentPath = path.slice(0, -1);
669
- if (!newKey)
670
- return;
671
- const newData = Object.fromEntries(Object.entries(parentData).map(([key, val]) => (key === name ? [newKey, val] : [key, val])));
672
- onEdit(newData, parentPath);
673
- };
674
- const handleKeyPress = (e) => {
675
- if (e.key === 'Enter')
676
- handleEditKey(e.target.value);
677
- else if (e.key === 'Escape')
678
- handleCancel();
679
- };
680
- const handleCancel = () => {
681
- setIsEditing(false);
682
- setIsEditingKey(false);
683
- setValue(data);
684
- setDataType(getDataType(data));
685
- };
686
- const handleDelete = () => {
687
- onDelete(value, path).then((error) => {
688
- if (error)
689
- logError(error);
690
- });
691
- };
692
- const filterProps = { key: name, path, level: path.length, value: data, size: null };
693
- const canEdit = useMemo(() => !restrictEditFilter(filterProps), [filterProps]);
694
- const canDelete = useMemo(() => !restrictDeleteFilter(filterProps), [filterProps]);
695
- const isArray = typeof path.slice(-1)[0] === 'number';
696
- const canEditKey = !isArray && canEdit && canDelete;
697
- const inputProps = {
698
- value,
699
- parentData,
700
- setValue,
701
- isEditing,
702
- setIsEditing: canEdit ? () => setIsEditing(true) : () => { },
703
- handleEdit,
704
- handleCancel,
705
- path,
706
- stringTruncate,
707
- translate,
708
- };
709
- const { CustomNode, customNodeProps, hideKey } = getCustomNode(customNodeDefinitions, {
710
- key: name,
711
- path,
712
- level: path.length,
713
- value: data,
714
- size: 0,
715
- });
716
- const allDataTypes = [
717
- ...customNodeDefinitions
718
- .filter(({ showInTypesSelector = false }) => showInTypesSelector)
719
- .map(({ name }) => name),
720
- ...DataTypes,
721
- ];
722
- const allowedDataTypes = useMemo(() => {
723
- if (typeof restrictTypeSelection === 'boolean')
724
- return restrictTypeSelection ? [] : allDataTypes;
725
- if (Array.isArray(restrictTypeSelection))
726
- return restrictTypeSelection;
727
- const result = restrictTypeSelection(filterProps);
728
- if (typeof result === 'boolean')
729
- return result ? [] : allDataTypes;
730
- return result;
731
- }, [filterProps, restrictTypeSelection]);
732
- return CustomNode ? (jsx(CustomNodeWrapper, { name: name, hideKey: hideKey, indent: indent, children: jsx(CustomNode, Object.assign({ customProps: customNodeProps }, props)) })) : (jsx("div", { className: "jer-component jer-value-component", style: { marginLeft: `${indent / 2}em` }, children: jsxs("div", { className: "jer-value-main-row", style: {
733
- flexWrap: name.length > 10 ? 'wrap' : 'nowrap',
734
- }, children: [showLabel && !isEditingKey && (jsxs("label", { htmlFor: path.join('.'), className: "jer-object-key", style: Object.assign(Object.assign({}, styles.property), { minWidth: `${Math.min(String(name).length + 1, 5)}ch`, flexShrink: name.length > 10 ? 1 : 0 }), onDoubleClick: () => canEditKey && setIsEditingKey(true), children: [name, ":", ' '] })), showLabel && isEditingKey && (jsx("input", { className: "jer-object-key", type: "text", name: path.join('.'), defaultValue: name, autoFocus: true, onFocus: (e) => e.target.select(), onKeyDown: handleKeyPress, style: { width: `${String(name).length / 1.5 + 0.5}em` } })), jsxs("div", { className: "jer-value-and-buttons", children: [jsx("div", { className: "jer-input-component", children: getInputComponent(dataType, inputProps) }), isEditing ? (jsx(InputButtons, { onOk: handleEdit, onCancel: handleCancel })) : (dataType !== 'invalid' &&
735
- !error && (jsx(EditButtons, { startEdit: canEdit ? () => setIsEditing(true) : undefined, handleDelete: canDelete ? handleDelete : undefined, data: data, enableClipboard: enableClipboard, name: name, path: path, translate: translate }))), isEditing && allowedDataTypes.length > 0 && (jsxs("div", { className: "jer-select", children: [jsx("select", { name: `${name}-type-select`, className: "jer-type-select", onChange: (e) => handleChangeDataType(e.target.value), value: dataType, children: allowedDataTypes.map((type) => (jsx("option", { value: type, children: type }, type))) }), jsx("span", { className: "focus" })] })), !isEditing && error && (jsx("span", { className: "jer-error-slug", style: styles.error, children: error }))] })] }) }));
736
- };
737
- const getDataType = (value) => {
738
- if (typeof value === 'string')
739
- return 'string';
740
- if (typeof value === 'number')
741
- return 'number';
742
- if (typeof value === 'boolean')
743
- return 'boolean';
744
- if (value === null)
745
- return 'null';
746
- return 'invalid';
747
- };
748
- const getInputComponent = (dataType, inputProps) => {
749
- const value = inputProps.value;
750
- switch (dataType) {
751
- case 'string':
752
- return jsx(StringValue, Object.assign({}, inputProps, { value: value }));
753
- case 'number':
754
- return jsx(NumberValue, Object.assign({}, inputProps, { value: value }));
755
- case 'boolean':
756
- return jsx(BooleanValue, Object.assign({}, inputProps, { value: value }));
757
- case 'null':
758
- return jsx(NullValue, Object.assign({}, inputProps));
759
- case 'object':
760
- return jsx(ObjectValue, Object.assign({}, inputProps, { value: value }));
761
- case 'array':
762
- return jsx(ArrayValue, Object.assign({}, inputProps));
763
- default:
764
- return jsx(InvalidValue, Object.assign({}, inputProps));
765
- }
766
- };
767
- const convertValue = (value, type) => {
768
- switch (type) {
769
- case 'string':
770
- return String(value);
771
- case 'number':
772
- const n = Number(value);
773
- return isNaN(n) ? 0 : n;
774
- case 'boolean':
775
- return !!value;
776
- case 'null':
777
- return null;
778
- case 'object':
779
- return value;
780
- case 'array':
781
- return [value];
782
- default:
783
- return String(value);
784
- }
785
- };
786
-
787
- const isCollection = (value) => value !== null && typeof value == 'object';
788
- const CollectionNode = (_a) => {
789
- var { data, path, name, parentData, showCollectionCount } = _a, props = __rest(_a, ["data", "path", "name", "parentData", "showCollectionCount"]);
790
- const { styles } = useTheme();
791
- const { onEdit, onAdd, onDelete, restrictEditFilter, restrictDeleteFilter, restrictAddFilter, collapseFilter, enableClipboard, indent, keySort, showArrayIndices, defaultValue, translate, customNodeDefinitions, } = props;
792
- const [isEditing, setIsEditing] = useState(false);
793
- const [isEditingKey, setIsEditingKey] = useState(false);
794
- const [stringifiedValue, setStringifiedValue] = useState(JSON.stringify(data, null, 2));
795
- const [error, setError] = useState(null);
796
- const collectionSize = Object.keys(data).length;
797
- const filterProps = { key: name, path, level: path.length, value: data, size: collectionSize };
798
- const startCollapsed = collapseFilter(filterProps);
799
- const [collapsed, setCollapsed] = useState(startCollapsed);
800
- const hasBeenOpened = useRef(!startCollapsed);
801
- const [isAnimating, setIsAnimating] = useState(false);
802
- useEffect(() => {
803
- setStringifiedValue(JSON.stringify(data, null, 2));
804
- }, [data]);
805
- useEffect(() => {
806
- setCollapsed(collapseFilter(filterProps));
807
- }, [collapseFilter]);
808
- const collectionType = Array.isArray(data) ? 'array' : 'object';
809
- const brackets = collectionType === 'array' ? { open: '[', close: ']' } : { open: '{', close: '}' };
810
- const transitionTime = getComputedStyle(document.documentElement).getPropertyValue('--jer-expand-transition-time');
811
- const handleKeyPress = (e) => {
812
- if (e.key === 'Enter' && (e.metaKey || e.shiftKey || e.ctrlKey))
813
- handleEdit();
814
- else if (e.key === 'Escape')
815
- handleCancel();
816
- };
817
- const handleCollapse = () => {
818
- if (!isEditing) {
819
- setIsAnimating(true);
820
- hasBeenOpened.current = true;
821
- setCollapsed(!collapsed);
822
- setTimeout(() => setIsAnimating(false), 500);
823
- }
824
- };
825
- const showError = (errorString) => {
826
- setError(errorString);
827
- setTimeout(() => setError(null), ERROR_DISPLAY_TIME);
828
- console.log('Error', errorString);
829
- };
830
- const handleEdit = () => {
831
- try {
832
- const value = JSON.parse(stringifiedValue);
833
- setIsEditing(false);
834
- setError(null);
835
- onEdit(value, path).then((error) => {
836
- if (error)
837
- showError(error);
838
- });
839
- }
840
- catch (_a) {
841
- setError(translate('ERROR_INVALID_JSON'));
842
- setTimeout(() => setError(null), ERROR_DISPLAY_TIME);
843
- console.log('Invalid JSON');
844
- return;
845
- }
846
- };
847
- const handleEditKey = (newKey) => {
848
- setIsEditingKey(false);
849
- if (!parentData)
850
- return;
851
- const parentPath = path.slice(0, -1);
852
- if (!newKey)
853
- return;
854
- const newData = Object.fromEntries(Object.entries(parentData).map(([key, val]) => (key === name ? [newKey, val] : [key, val])));
855
- onEdit(newData, parentPath);
856
- };
857
- const handleKeyPressKeyEdit = (e) => {
858
- if (e.key === 'Enter')
859
- handleEditKey(e.target.value);
860
- else if (e.key === 'Escape')
861
- handleCancel();
862
- };
863
- const handleAdd = (key) => {
864
- setCollapsed(false);
865
- if (collectionType === 'array') {
866
- onAdd(defaultValue, [...path, data.length]).then((error) => {
867
- if (error)
868
- showError(error);
869
- });
870
- }
871
- else if (key in data) {
872
- showError(translate('ERROR_KEY_EXISTS'));
873
- return;
874
- }
875
- else
876
- onAdd(defaultValue, [...path, key]).then((error) => {
877
- if (error)
878
- showError(error);
879
- });
880
- };
881
- const handleDelete = path.length > 0
882
- ? () => {
883
- onDelete(data, path).then((result) => {
884
- if (result)
885
- showError(result);
886
- });
887
- }
888
- : undefined;
889
- const handleCancel = () => {
890
- setIsEditing(false);
891
- setError(null);
892
- setStringifiedValue(JSON.stringify(data, null, 2));
893
- };
894
- const canEdit = useMemo(() => !restrictEditFilter(filterProps), [filterProps]);
895
- const canDelete = useMemo(() => !restrictDeleteFilter(filterProps), [filterProps]);
896
- const canAdd = useMemo(() => !restrictAddFilter(filterProps), [filterProps]);
897
- const canEditKey = parentData !== null && canEdit && canAdd && canDelete;
898
- const isArray = typeof path.slice(-1)[0] === 'number';
899
- const showLabel = showArrayIndices || !isArray;
900
- const showCount = showCollectionCount === 'when-closed' ? collapsed : showCollectionCount;
901
- const keyValueArray = Object.entries(data).map(([key, value]) => [
902
- collectionType === 'array' ? Number(key) : key,
903
- value,
904
- ]);
905
- if (keySort && collectionType === 'object')
906
- keyValueArray.sort(typeof keySort === 'function' ? (a, b) => keySort(a[0], b[0]) : undefined);
907
- const numOfLines = JSON.stringify(data, null, 2).split('\n').length;
908
- const { CustomNode, customNodeProps, hideKey } = getCustomNode(customNodeDefinitions, {
909
- key: name,
910
- path,
911
- level: path.length,
912
- value: data,
913
- size: Object.keys(data).length,
914
- });
915
- return (jsx("div", { className: "jer-component fb-collection-component", style: { marginLeft: `${path.length === 0 ? 0 : indent / 2}em` }, children: CustomNode ? (jsx(CustomNodeWrapper, { name: name, hideKey: hideKey, children: jsx(CustomNode, Object.assign({ data: data, path: path, name: name, parentData: parentData, customProps: customNodeProps }, props)) })) : (jsxs(Fragment, { children: [jsxs("div", { className: "jer-collection-header-row", children: [jsx("div", { onClick: handleCollapse, children: jsx(Icon, { name: "chevron", rotate: collapsed }) }), jsxs("div", { className: "jer-collection-name", children: [!isEditingKey && (jsx("span", { style: styles.property, onDoubleClick: () => canEditKey && setIsEditingKey(true), children: showLabel && name !== '' && name !== undefined ? `${name}:` : null })), isEditingKey && (jsx("input", { className: "jer-collection-name", type: "text", name: path.join('.'), defaultValue: name, autoFocus: true, onFocus: (e) => e.target.select(), onKeyDown: handleKeyPressKeyEdit, style: { width: `${String(name).length / 1.5 + 0.5}em` } })), !isEditing && (jsx("span", { className: "jer-brackets", style: styles.bracket, children: brackets.open }))] }), !isEditing && showCollectionCount && (jsx("div", { className: `jer-collection-item-count${showCount ? ' jer-visible' : ' jer-hidden'}`, style: styles.itemCount, children: collectionSize === 1
916
- ? translate('ITEM_SINGLE', 1)
917
- : translate('ITEMS_MULTIPLE', collectionSize) })), jsx("div", { className: `jer-brackets${collapsed ? ' jer-visible' : ' jer-hidden'}`, style: styles.bracket, children: brackets.close }), !isEditing && (jsx(EditButtons, { startEdit: canEdit
918
- ? () => {
919
- setIsEditing(true);
920
- setCollapsed(false);
921
- }
922
- : undefined, handleAdd: canAdd ? handleAdd : undefined, handleDelete: canDelete ? handleDelete : undefined, enableClipboard: enableClipboard, type: collectionType, data: data, name: name, path: path, translate: translate }))] }), jsxs("div", { className: 'jer-collection-inner', style: {
923
- maxHeight: collapsed ? 0 : !isEditing ? `${numOfLines * 3}em` : undefined,
924
- overflowY: collapsed || isAnimating ? 'hidden' : 'visible',
925
- transition: `max-height ${transitionTime}`,
926
- }, children: [isEditing ? (jsx("div", { className: "jer-collection-text-edit", children: jsxs("div", { children: [jsx(AutogrowTextArea, { className: "jer-collection-text-area", name: path.join('.'), value: stringifiedValue, setValue: setStringifiedValue, isEditing: isEditing, handleKeyPress: handleKeyPress }), jsx("div", { className: "jer-collection-input-button-row", children: jsx(InputButtons, { onOk: handleEdit, onCancel: handleCancel, isCollection: true }) })] }) })) : (jsx(Fragment, { children: !hasBeenOpened.current
927
- ? null
928
- : keyValueArray.map(([key, value]) => (jsx("div", { className: "jer-collection-element", children: isCollection(value) ? (jsx(CollectionNode, Object.assign({ data: value, parentData: data, path: [...path, key], name: key, showCollectionCount: showCollectionCount }, props), key)) : (jsx(ValueNodeWrapper, Object.assign({ data: value, parentData: data, path: [...path, key], name: key }, props, { showLabel: collectionType === 'object' ? true : showArrayIndices }), key)) }, key))) })), jsx("div", { className: isEditing ? 'jer-collection-error-row' : 'jer-collection-error-row-edit', children: error && (jsx("span", { className: "jer-error-slug", style: styles.error, children: error })) }), jsx("div", { className: "jer-brackets", style: styles.bracket, children: brackets.close })] })] })) }));
929
- };
930
-
931
- const localisedStrings = {
932
- ITEM_SINGLE: '{{count}} item',
933
- ITEMS_MULTIPLE: '{{count}} items',
934
- KEY_NEW: 'Enter new key',
935
- ERROR_KEY_EXISTS: 'Key already exists',
936
- ERROR_INVALID_JSON: 'Invalid JSON',
937
- ERROR_UPDATE: 'Update unsuccessful',
938
- ERROR_DELETE: 'Delete unsuccessful',
939
- ERROR_ADD: 'Adding node unsuccessful',
940
- DEFAULT_STRING: 'New data!',
941
- DEFAULT_NEW_KEY: 'key',
942
- };
943
- const translate = (translations, key, count) => {
944
- const string = key in translations ? translations[key] : localisedStrings[key];
945
- return count === undefined ? string : string === null || string === void 0 ? void 0 : string.replace('{{count}}', String(count));
946
- };
947
- const getTranslateFunction = (translations) => (key, count) => translate(translations, key, count);
948
-
949
- const Editor = ({ data: srcData, rootName = 'root', onUpdate, onEdit: srcEdit = onUpdate, onDelete: srcDelete = onUpdate, onAdd: srcAdd = onUpdate, enableClipboard = true, theme = 'default', icons, indent = 4, collapse = false, showCollectionCount = true, restrictEdit = false, restrictDelete = false, restrictAdd = false, restrictTypeSelection = false, keySort = false, showArrayIndices = true, defaultValue = null, minWidth = 250, maxWidth = 'min(600px, 90vw)', stringTruncate = 250, translations = {}, className, customNodeDefinitions = [], }) => {
950
- const [data, setData] = useState(srcData);
951
- const { styles, setTheme, setIcons } = useTheme();
952
- const collapseFilter = useCallback(getFilterFunction(collapse), [collapse]);
953
- const translate = useCallback(getTranslateFunction(translations), [translations]);
954
- useEffect(() => {
955
- setData(srcData);
956
- }, [srcData]);
957
- useEffect(() => {
958
- if (theme)
959
- setTheme(theme);
960
- if (icons)
961
- setIcons(icons);
962
- }, [theme, icons]);
963
- const onEdit = (value, path) => __awaiter(void 0, void 0, void 0, function* () {
964
- const { currentData, newData, currentValue, newValue } = updateDataObject(data, path, value, 'update');
965
- if (srcEdit) {
966
- const result = yield srcEdit({
967
- currentData,
968
- newData,
969
- currentValue,
970
- newValue,
971
- name: path.slice(-1)[0],
972
- path,
973
- });
974
- if (result === undefined)
975
- setData(newData);
976
- if (result === false)
977
- return translate('ERROR_UPDATE');
978
- return result;
979
- }
980
- else
981
- setData(newData);
982
- });
983
- const onDelete = (value, path) => __awaiter(void 0, void 0, void 0, function* () {
984
- const { currentData, newData, currentValue, newValue } = updateDataObject(data, path, value, 'delete');
985
- if (srcDelete) {
986
- const result = yield srcDelete({
987
- currentData,
988
- newData,
989
- currentValue,
990
- newValue,
991
- name: path.slice(-1)[0],
992
- path,
993
- });
994
- if (result === undefined)
995
- setData(newData);
996
- if (result === false)
997
- return translate('ERROR_DELETE');
998
- return result;
999
- }
1000
- else
1001
- setData(newData);
1002
- });
1003
- const onAdd = (value, path) => __awaiter(void 0, void 0, void 0, function* () {
1004
- const { currentData, newData, currentValue, newValue } = updateDataObject(data, path, value, 'add');
1005
- if (srcAdd) {
1006
- const result = yield srcAdd({
1007
- currentData,
1008
- newData,
1009
- currentValue,
1010
- newValue,
1011
- name: path.slice(-1)[0],
1012
- path,
1013
- });
1014
- if (result === undefined)
1015
- setData(newData);
1016
- if (result === false)
1017
- return translate('ERROR_ADD');
1018
- return result;
1019
- }
1020
- else
1021
- setData(newData);
1022
- });
1023
- const restrictEditFilter = getFilterFunction(restrictEdit);
1024
- const restrictDeleteFilter = getFilterFunction(restrictDelete);
1025
- const restrictAddFilter = getFilterFunction(restrictAdd);
1026
- const otherProps = {
1027
- name: rootName,
1028
- onEdit,
1029
- onDelete,
1030
- onAdd,
1031
- showCollectionCount,
1032
- collapseFilter,
1033
- restrictEditFilter,
1034
- restrictDeleteFilter,
1035
- restrictAddFilter,
1036
- restrictTypeSelection,
1037
- enableClipboard,
1038
- keySort,
1039
- showArrayIndices,
1040
- indent,
1041
- defaultValue,
1042
- stringTruncate,
1043
- translate,
1044
- customNodeDefinitions,
1045
- parentData: null,
1046
- };
1047
- if (!styles)
1048
- return null;
1049
- return (jsx("div", { className: 'jer-editor-container ' + className, style: Object.assign(Object.assign({}, styles.container), { minWidth, maxWidth }), children: isCollection(data) ? (jsx(CollectionNode, Object.assign({ data: data, path: [] }, otherProps))) : (jsx(ValueNodeWrapper, Object.assign({ data: data, path: [], showLabel: true }, otherProps))) }));
1050
- };
1051
- const JsonEditor = (props) => (jsx(ThemeProvider, { children: jsx(Editor, Object.assign({}, props)) }));
1052
- const updateDataObject = (data, path, newValue, action) => {
1053
- if (path.length === 0) {
1054
- return {
1055
- currentData: data,
1056
- newData: newValue,
1057
- currentValue: data,
1058
- newValue: newValue,
1059
- };
1060
- }
1061
- const currentValue = action !== 'add' ? extract(data, path) : undefined;
1062
- const newData = assign(clone(data), path, newValue, { remove: action === 'delete' });
1063
- return {
1064
- currentData: data,
1065
- newData,
1066
- currentValue,
1067
- newValue: action === 'update' ? newValue : undefined,
1068
- };
1069
- };
1070
- const getFilterFunction = (propValue) => {
1071
- if (typeof propValue === 'boolean')
1072
- return () => propValue;
1073
- if (typeof propValue === 'number')
1074
- return ({ level }) => level >= propValue;
1075
- return propValue;
1076
- };
1077
-
1078
- export { JsonEditor, themes };
1
+ import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{createContext,useState,useContext,useEffect,useMemo,useRef,useCallback}from"react";import assign from"object-property-assigner";import extract from"object-property-extractor";import clone from"just-clone";import{HiOutlineClipboardCopy}from"react-icons/hi";import{BiEdit,BiPlusCircle}from"react-icons/bi";import{MdDeleteForever}from"react-icons/md";import{FiCheckCircle}from"react-icons/fi";import{TiCancel}from"react-icons/ti";import{FaChevronDown}from"react-icons/fa";function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var e=[],t=[];!function(n,r){if(n&&"undefined"!=typeof document){var a,s=!0===r.prepend?"prepend":"append",d=!0===r.singleTag,i="string"==typeof r.container?document.querySelector(r.container):document.getElementsByTagName("head")[0];if(d){var u=e.indexOf(i);-1===u&&(u=e.push(i)-1,t[u]={}),a=t[u]&&t[u][s]?t[u][s]:t[u][s]=c()}else a=c();65279===n.charCodeAt(0)&&(n=n.substring(1)),a.styleSheet?a.styleSheet.cssText+=n:a.appendChild(document.createTextNode(n))}function c(){var e=document.createElement("style");if(e.setAttribute("type","text/css"),r.attributes)for(var t=Object.keys(r.attributes),n=0;n<t.length;n++)e.setAttribute(t[n],r.attributes[t[n]]);var a="prepend"===s?"afterbegin":"beforeend";return i.insertAdjacentElement(a,e),e}}(":root {\n --jer-select-border: #b6b6b6;\n --jer-select-focus: #777;\n --jer-select-arrow: #777;\n --jer-form-border: 1px solid #ededf0;\n --jer-form-border-focus: 1px solid #e2e2e2;\n --jer-expand-transition-time: 0.5s;\n --jer-highlight-color: #b3d8ff;\n}\n\n.jer-visible {\n opacity: 1;\n transition: var(--jer-expand-transition-time);\n}\n\n.jer-hidden {\n opacity: 0;\n transition: var(--jer-expand-transition-time);\n}\n\n/* Select styled as per:\nhttps://moderncss.dev/custom-select-styles-with-pure-css/\n*/\n\n.jer-select select {\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n background-color: transparent;\n border: none;\n padding: 0 1em 0 0;\n margin: 0;\n /* width: 100%; */\n font-family: inherit;\n font-size: inherit;\n color: black;\n cursor: inherit;\n line-height: inherit;\n z-index: 1;\n outline: none;\n}\nselect::-ms-expand {\n display: none;\n}\n\n.jer-select {\n display: grid;\n grid-template-areas: 'select';\n align-items: center;\n position: relative;\n min-width: 12ch;\n max-width: 15ch;\n border: 1px solid var(--jer-select-border);\n border-radius: 0.25em;\n padding: 0.25em 0.5em;\n font-size: 1em;\n cursor: pointer;\n line-height: 1.1;\n background-color: #fff;\n background-image: linear-gradient(to top, #f9f9f9, #fff 33%);\n}\n.jer-select select,\n.jer-select::after {\n grid-area: select;\n}\n.jer-select:not(.jer-select--multiple)::after {\n content: '';\n justify-self: end;\n width: 0.8em;\n height: 0.5em;\n background-color: var(--jer-select-arrow);\n -webkit-clip-path: polygon(100% 0%, 0 0%, 50% 100%);\n clip-path: polygon(100% 0%, 0 0%, 50% 100%);\n}\n\nselect:focus + .focus {\n position: absolute;\n top: -1px;\n left: -1px;\n right: -1px;\n bottom: -1px;\n border: 1px solid var(--jer-select-focus);\n border-radius: inherit;\n}\n\n.jer-editor-container {\n font-size: 1.1em;\n /* font-size: 20px; */\n padding: 1em;\n margin-top: 1em;\n margin-bottom: 1em;\n border-radius: 0.5em;\n}\n\n.jer-editor-container textarea {\n /* width: 90%; */\n color: var(--jer-input-color);\n border: var(--jer-form-border);\n border-radius: 0.3em;\n outline: none;\n}\n\n.jer-editor-container textarea:focus {\n border: var(--jer-form-border-focus);\n}\n\n.jer-editor-container input {\n border: var(--jer-form-border);\n border-radius: 0.3em;\n outline: none;\n}\n\n.jer-editor-container input:focus {\n border: var(--jer-form-border-focus);\n}\n\n/* Input highlighted text */\n.jer-editor-container ::selection {\n background-color: var(--jer-highlight-color);\n}\n\n.jer-editor-container select {\n /* color: red; */\n}\n\n.jer-component {\n}\n\n.jer-collection-header-row,\n.jer-value-main-row {\n display: flex;\n min-height: 1.7em;\n gap: 0.3em;\n align-items: center;\n}\n\n.jer-collection-header-row {\n display: flex;\n flex-wrap: wrap;\n}\n\n.jer-brackets {\n}\n\n.jer-collection-item-count {\n}\n\n.jer-collection-inner {\n position: relative;\n}\n\n.jer-collection-text-edit {\n display: flex;\n flex-direction: column;\n gap: 0.3em;\n align-items: flex-start;\n}\n\n.jer-collection-text-area {\n resize: both;\n padding-top: 0.2em;\n padding-left: 0.5em;\n padding-right: 0.5em;\n padding-bottom: 0;\n overflow: hidden;\n max-height: 40em;\n}\n\n.jer-collection-input-button-row {\n display: flex;\n justify-content: flex-end;\n font-size: 150%;\n}\n\n.jer-collection-element {\n}\n\n.jer-collection-error-row {\n position: absolute;\n bottom: 0;\n}\n\n.jer-collection-error-row-edit {\n}\n\n.jer-error-slug {\n margin-left: 1em;\n}\n\n.jer-value-component {\n position: relative;\n}\n\n.jer-value-main-row {\n display: flex;\n gap: 0;\n}\n\n.jer-value-and-buttons {\n display: flex;\n justify-content: flex-start;\n align-items: center;\n padding-left: 0.5em;\n}\n\n.jer-value-error-row {\n position: absolute;\n}\n\n.jer-value-string {\n line-height: 1.3em;\n}\n\n.jer-input-text {\n resize: none;\n margin: 0;\n height: 1.4em;\n padding-left: 0.5em;\n padding-right: 0.5em;\n padding-bottom: 0;\n min-width: 6em;\n overflow: hidden;\n max-height: 30em;\n}\n\n.jer-value-number {\n}\n\n.jer-value-boolean {\n}\n\n.jer-input-boolean {\n transform: scale(1.5);\n margin-left: 0.3em;\n margin-right: 0.3em;\n}\n\n.jer-value-null {\n}\n\n.jer-value-object {\n}\n\n.jer-object-key {\n word-break: break-word;\n line-height: 1.1em;\n}\n\n.jer-value-array {\n}\n\n.jer-value-invalid {\n opacity: 0.5;\n font-style: italic;\n}\n\n/* .jer-input-text, */\n.jer-input-number {\n height: 1.6em;\n}\n\n.jer-input-number {\n min-width: 3em;\n}\n\n.jer-input-component {\n}\n\n.jer-edit-buttons,\n.jer-confirm-buttons {\n display: flex;\n align-items: center;\n cursor: pointer;\n}\n\n.jer-input-buttons {\n gap: 0.4em;\n}\n\n.jer-edit-buttons {\n gap: 0.4em;\n margin-left: 0.5em;\n opacity: 0;\n}\n\n.jer-confirm-buttons {\n gap: 0.2em;\n margin-left: 0.4em;\n}\n\n.jer-edit-buttons:hover {\n opacity: 1;\n position: relative;\n}\n\n.jer-collection-header-row:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-value-main-row:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-value-and-buttons:hover > .jer-edit-buttons {\n opacity: 1;\n}\n\n.jer-input-buttons {\n}\n\n.jer-copy-pulse {\n position: relative;\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-copy-pulse:hover {\n opacity: 0.85;\n transition: 0.3s;\n transform: scale(1.2);\n}\n\n.jer-copy-pulse:after {\n content: '';\n display: block;\n position: absolute;\n border-radius: 50%;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n transition: all 0.5s;\n box-shadow: 0 0 15px 5px var(--jer-icon-copy-color);\n}\n\n.jer-copy-pulse:active:after {\n box-shadow: 0 0 0 0 var(--jer-icon-copy-color);\n position: absolute;\n border-radius: 4em;\n left: 0;\n top: 0;\n opacity: 1;\n transition: 0s;\n}\n\n.jer-copy-pulse:active {\n top: 0.07em;\n}\n\n.jer-rotate-90 {\n transform: rotate(-90deg);\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-accordion-icon {\n /* font-size: '2em'; */\n transition: transform var(--jer-expand-transition-time);\n}\n\n.jer-icon:hover {\n opacity: 0.85;\n transition: 0.3s;\n transform: scale(1.2);\n}\n",{});const themes={default:{displayName:"Default",fragments:{edit:"rgb(42, 161, 152)"},styles:{container:{backgroundColor:"#f6f6f6",fontFamily:"monospace"},property:"#292929",bracket:{color:"rgb(0, 43, 54)",fontWeight:"bold"},itemCount:{color:"rgba(0, 0, 0, 0.3)",fontStyle:"italic"},string:"rgb(203, 75, 22)",number:"rgb(38, 139, 210)",boolean:"green",null:{color:"rgb(220, 50, 47)",fontVariant:"small-caps",fontWeight:"bold"},input:["#292929",{fontSize:"90%"}],inputHighlight:"#b3d8ff",error:{fontSize:"0.8em",color:"red",fontWeight:"bold"},iconCollection:"rgb(0, 43, 54)",iconEdit:"edit",iconDelete:"rgb(203, 75, 22)",iconAdd:"edit",iconCopy:"rgb(38, 139, 210)",iconOk:"green",iconCancel:"rgb(203, 75, 22)"}},githubDark:{displayName:"Github Dark",styles:{container:{backgroundColor:"#0d1117",color:"white"},property:"#E6EDF3",bracket:"#56d364",itemCount:"#8B949E",string:"#A5D6FF",number:"#D2A8FF",boolean:{color:"#FF7B72",fontSize:"90%",fontWeight:"bold"},null:"green",iconCollection:"#D2A8FF",iconEdit:"#D2A8FF",iconDelete:"rgb(203, 75, 22)",iconAdd:"rgb(203, 75, 22)",iconCopy:"#A5D6FF",iconOk:"#56d364",iconCancel:"rgb(203, 75, 22)"}},githubLight:{displayName:"Github Light",styles:{container:"white",property:"#1F2328",bracket:"#00802e",itemCount:"#8B949E",string:"#0A3069",number:"#953800",boolean:{color:"#CF222E",fontSize:"90%",fontWeight:"bold"},null:"#FF7B72",iconCollection:"#8250DF",iconEdit:"#8250DF",iconDelete:"rgb(203, 75, 22)",iconAdd:"#8250DF",iconCopy:"#57606A"}},monoDark:{displayName:"Black & White",fragments:{lightText:{color:"white"},midGrey:"#5c5c5c"},styles:{container:["lightText",{backgroundColor:"black"}],property:"lightText",bracket:"midGrey",itemCount:"#4a4a4a",string:"#a8a8a8",number:"#666666",boolean:{color:"#848484",fontStyle:"italic"},null:"#333333",iconCollection:"midGrey",iconEdit:"midGrey",iconDelete:"midGrey",iconAdd:"midGrey",iconCopy:"midGrey",iconOk:"midGrey",iconCancel:"midGrey"}},monoLight:{fragments:{midGrey:"#a3a3a3"},displayName:"White & Black",styles:{container:"white",property:"black",bracket:"midGrey",itemCount:"#b5b5b5",string:"#575757",number:"#999999",boolean:{color:"#7b7b7b",fontStyle:"italic"},null:"#cccccc",iconCollection:"midGrey",iconEdit:"midGrey",iconDelete:"midGrey",iconAdd:"midGrey",iconCopy:"midGrey",iconOk:"midGrey",iconCancel:"midGrey"}},candyWrapper:{displayName:"Candy Wrapper",fragments:{minty:{backgroundColor:"#F1FAEE"},pale:{color:"#A8DADC"},mid:{color:"#457B9D"},dark:{color:"#1D3557"},pop:{color:"#E63946"},darkBlue:{color:"#2B2D42"}},styles:{container:"minty",property:"pop",bracket:"dark",itemCount:"pale",string:"mid",number:["darkBlue",{fontSize:"85%"}],boolean:["mid",{fontStyle:"italic",fontWeight:"bold",fontSize:"80%"}],null:["#cccccc",{fontWeight:"bold"}],iconCollection:"#1D3557",iconEdit:"#457B9D",iconDelete:"#E63946",iconAdd:"#2B2D42",iconCopy:"#1D3557",iconCancel:"#E63946"}},psychedelic:{displayName:"Psychedelic",fragments:{minty:{backgroundColor:"#F1FAEE"},pale:{color:"#A8DADC"},mid:{color:"#457B9D"},dark:{color:"#1D3557"},pop:{color:"#E63946"},fluroYellow:"rgb(242, 228, 21)",fluroGreen:"rgb(68, 255, 62)",hotPink:"#f7379a"},styles:{container:{backgroundColor:"unset",background:"linear-gradient(90deg, hsla(333, 100%, 53%, 1) 0%, hsla(33, 94%, 57%, 1) 100%)",color:"black"},property:"black",bracket:"fluroYellow",itemCount:["pale",{opacity:.7}],string:"white",number:["#33d9ff",{fontSize:"90%",fontWeight:"bold"}],boolean:["fluroGreen",{fontWeight:"bold",fontSize:"80%"}],null:["black",{fontWeight:"bold",opacity:.3,backgroundColor:"rgb(255, 255, 255, 0.5)",padding:"0 0.4em",borderRadius:"0.4em"}],iconCollection:"fluroYellow",iconEdit:["black"],iconDelete:["white",{opacity:.5}],iconAdd:["white",{opacity:.5}],iconCopy:"rgb(32, 84, 242)",iconOk:"fluroGreen",iconCancel:"hotPink"}}},emptyStyleObject={container:{},property:{},bracket:{},itemCount:{},string:{},number:{},boolean:{},null:{},input:{},inputHighlight:{},error:{},iconCollection:{},iconEdit:{},iconDelete:{},iconAdd:{},iconCopy:{},iconOk:{},iconCancel:{}},defaultTheme=themes.default,ThemeProviderContext=createContext({styles:emptyStyleObject,setTheme:_=>{},icons:{},setIcons:()=>{}}),ThemeProvider=({children:children})=>{const[styles,setStyles]=useState(emptyStyleObject),[icons,setIcons]=useState({});return jsx(ThemeProviderContext.Provider,{value:{styles:styles,setTheme:theme=>setStyles(compileStyles(theme)),icons:icons,setIcons:setIcons},children:children})},useTheme=()=>useContext(ThemeProviderContext),compileStyles=themeInput=>{if("string"==typeof themeInput)return buildStyleObject(themes[themeInput]);if(Array.isArray(themeInput)){const[name,overrides]=themeInput;return buildStyleObject(themes[name],isStyleObject(overrides)?{styles:overrides}:overrides)}return buildStyleObject(defaultTheme,isStyleObject(themeInput)?{styles:themeInput}:themeInput)},buildStyleObject=(baseTheme,overrides={styles:emptyStyleObject})=>{var _a,_b,_c,_d;const[defaultStyles,baseStyles,overrideStyles]=[defaultTheme,baseTheme,overrides].map((theme=>{const{fragments:fragments,styles:styles}=theme,compiledStyles={};return Object.entries(styles).forEach((([key,value])=>{const cssStyles=(Array.isArray(value)?value:[value]).reduce(((acc,curr)=>{var _a;if("string"==typeof curr){const style=null!==(_a=null==fragments?void 0:fragments[curr])&&void 0!==_a?_a:curr;return"string"==typeof style?Object.assign(Object.assign({},acc),{[defaultStyleProperties[key]]:style}):Object.assign(Object.assign({},acc),style)}return Object.assign(Object.assign({},acc),curr)}),{});compiledStyles[key]=cssStyles})),compiledStyles})),finalStyles={};return Object.keys(defaultTheme.styles).forEach((key=>{finalStyles[key]=Object.assign(Object.assign(Object.assign({},defaultStyles[key]),baseStyles[key]),overrideStyles[key])})),(null===(_a=null==finalStyles?void 0:finalStyles.inputHighlight)||void 0===_a?void 0:_a.backgroundColor)&&document.documentElement.style.setProperty("--jer-highlight-color",null===(_b=null==finalStyles?void 0:finalStyles.inputHighlight)||void 0===_b?void 0:_b.backgroundColor),(null===(_c=null==finalStyles?void 0:finalStyles.iconCopy)||void 0===_c?void 0:_c.color)&&document.documentElement.style.setProperty("--jer-icon-copy-color",null===(_d=null==finalStyles?void 0:finalStyles.iconCopy)||void 0===_d?void 0:_d.color),finalStyles},isStyleObject=overrideObject=>!("styles"in overrideObject),defaultStyleProperties={container:"backgroundColor",property:"color",bracket:"color",itemCount:"color",string:"color",number:"color",boolean:"color",null:"color",input:"color",inputHighlight:"backgroundColor",error:"color",iconCollection:"color",iconEdit:"color",iconDelete:"color",iconAdd:"color",iconCopy:"color",iconOk:"color",iconCancel:"color"},AutogrowTextArea=({className:className,name:name,value:value,setValue:setValue,handleKeyPress:handleKeyPress})=>{const{styles:styles}=useTheme(),dummyValue="\n"===value.slice(-1)?value+".":value;return jsxs("div",{style:{display:"grid"},children:[jsx("textarea",{style:Object.assign({height:"auto",gridArea:"1 / 1 / 2 / 2",overflowY:"auto"},styles.input),rows:1,className:className,name:name,value:value,onChange:e=>setValue(e.target.value),autoFocus:!0,onFocus:e=>{value.length<40&&e.target.select()},onKeyDown:handleKeyPress}),jsx("span",{className:className,style:Object.assign({visibility:"hidden",height:"auto",gridArea:"1 / 1 / 2 / 2",color:"red",opacity:.9,whiteSpace:"pre-wrap",overflow:"clip",border:"1px solid transparent"},styles.input),children:dummyValue})]})},truncate=(string,length=200)=>string.length<length?string:`${string.slice(0,length-2).trim()}...`,StringValue=({value:value,setValue:setValue,isEditing:isEditing,path:path,setIsEditing:setIsEditing,handleEdit:handleEdit,handleCancel:handleCancel,stringTruncate:stringTruncate})=>{const{styles:styles}=useTheme();return isEditing?jsx(AutogrowTextArea,{className:"jer-input-text",name:path.join("."),value:value,setValue:setValue,isEditing:isEditing,handleKeyPress:e=>{"Enter"!==e.key||e.shiftKey?"Escape"===e.key&&handleCancel():handleEdit()}}):jsxs("div",{onDoubleClick:()=>setIsEditing(!0),onClick:e=>{(e.getModifierState("Control")||e.getModifierState("Meta"))&&setIsEditing(!0)},className:"jer-value-string",style:styles.string,children:['"',(text=truncate(value,stringTruncate),text.split("\n").map(((line,index,arr)=>jsxs("span",{children:[line,index<arr.length-1?jsx("br",{}):null]},index)))),'"']});var text},NumberValue=({value:value,setValue:setValue,isEditing:isEditing,path:path,setIsEditing:setIsEditing,handleEdit:handleEdit,handleCancel:handleCancel})=>{const{styles:styles}=useTheme();return isEditing?jsx("input",{className:"jer-input-number",type:"text",name:path.join("."),value:value,onChange:e=>setValue(e.target.value.replace(/[^0-9.-]/g,"")),autoFocus:!0,onFocus:e=>e.target.select(),onKeyDown:e=>{"Enter"===e.key?handleEdit():"Escape"===e.key&&handleCancel()},style:{width:String(value).length/1.5+2+"em"}}):jsx("span",{onDoubleClick:()=>setIsEditing(!0),className:"jer-value-number",style:styles.number,children:value})},BooleanValue=({value:value,setValue:setValue,isEditing:isEditing,path:path,setIsEditing:setIsEditing,handleEdit:handleEdit,handleCancel:handleCancel})=>{const{styles:styles}=useTheme();useEffect((()=>(isEditing&&document.addEventListener("keydown",listenForSubmit),()=>document.removeEventListener("keydown",listenForSubmit))),[isEditing]);const listenForSubmit=event=>{"Enter"===event.key?handleEdit():"Escape"===event.key&&handleCancel()};return isEditing?jsx("input",{className:"jer-input-boolean",type:"checkbox",name:path.join("."),checked:value,onChange:()=>setValue(!value)}):jsx("span",{onDoubleClick:()=>setIsEditing(!0),className:"jer-value-boolean",style:styles.boolean,children:String(value)})},NullValue=({value:value,isEditing:isEditing,setIsEditing:setIsEditing,handleEdit:handleEdit,handleCancel:handleCancel})=>{const{styles:styles}=useTheme();useEffect((()=>(isEditing&&document.addEventListener("keydown",listenForSubmit),()=>document.removeEventListener("keydown",listenForSubmit))),[isEditing]);const listenForSubmit=event=>{"Enter"===event.key?handleEdit():"Escape"===event.key&&handleCancel()};return jsx("div",isEditing?{className:"jer-input-null",children:"null"}:{onDoubleClick:()=>setIsEditing(!0),className:"jer-value-null",style:styles.null,children:String(value)})},ObjectValue=({value:value,translate:translate,isEditing:isEditing,handleEdit:handleEdit,handleCancel:handleCancel})=>{useEffect((()=>(isEditing&&document.addEventListener("keydown",listenForSubmit),()=>document.removeEventListener("keydown",listenForSubmit))),[]);const listenForSubmit=event=>{"Enter"===event.key?handleEdit():"Escape"===event.key&&handleCancel()};return jsx("span",{className:"jer-value-object",children:`{${translate("DEFAULT_NEW_KEY")}: "${value}" }`})},ArrayValue=({value:value,isEditing:isEditing,handleEdit:handleEdit,handleCancel:handleCancel})=>{useEffect((()=>(isEditing&&document.addEventListener("keydown",listenForSubmit),()=>document.removeEventListener("keydown",listenForSubmit))),[]);const listenForSubmit=event=>{"Enter"===event.key?handleEdit():"Escape"===event.key&&handleCancel()};return jsx("span",{className:"jer-value-array",children:`[${null===value?"":value}]`})},InvalidValue=({value:value})=>{let message="Error!";switch(typeof value){case"string":"**INVALID_FUNCTION**"===value&&(message="Function");break;case"undefined":message="Undefined";break;case"symbol":message="Symbol"}return jsx("span",{className:"jer-value-invalid",children:message})},Icon=({name:name,rotate:rotate})=>{var _a,_b,_c,_d,_e,_f,_g;const{styles:styles,icons:icons}=useTheme(),commonProps={size:"1.4em",className:"jer-icon"};switch(name){case"add":return null!==(_a=null==icons?void 0:icons.add)&&void 0!==_a?_a:jsx(BiPlusCircle,Object.assign({},commonProps,{style:styles.iconAdd}));case"edit":return null!==(_b=null==icons?void 0:icons.edit)&&void 0!==_b?_b:jsx(BiEdit,Object.assign({},commonProps,{style:styles.iconEdit}));case"delete":return null!==(_c=null==icons?void 0:icons.delete)&&void 0!==_c?_c:jsx(MdDeleteForever,Object.assign({},commonProps,{style:styles.iconDelete,size:"1.5em"}));case"copy":return null!==(_d=null==icons?void 0:icons.copy)&&void 0!==_d?_d:jsx(HiOutlineClipboardCopy,Object.assign({},commonProps,{style:styles.iconCopy}));case"ok":return null!==(_e=null==icons?void 0:icons.ok)&&void 0!==_e?_e:jsx(FiCheckCircle,Object.assign({},commonProps,{style:Object.assign({fontSize:"90%"},styles.iconOk)}));case"cancel":return null!==(_f=null==icons?void 0:icons.cancel)&&void 0!==_f?_f:jsx(TiCancel,Object.assign({},commonProps,{style:Object.assign({fontSize:"130%"},styles.iconCancel)}));case"chevron":return null!==(_g=null==icons?void 0:icons.chevron)&&void 0!==_g?_g:jsx(FaChevronDown,{className:"jer-accordion-icon"+(rotate?" jer-rotate-90":""),style:styles.iconCollection});default:return jsx(Fragment,{})}},EditButtons=({startEdit:startEdit,handleDelete:handleDelete,handleAdd:handleAdd,enableClipboard:enableClipboard,type:type,data:data,path:path,name:name,translate:translate})=>{const{styles:styles}=useTheme(),NEW_KEY_PROMPT=translate("KEY_NEW"),[isAdding,setIsAdding]=useState(!1),[newKey,setNewKey]=useState(NEW_KEY_PROMPT);useEffect((()=>{isAdding||setNewKey(NEW_KEY_PROMPT)}),[isAdding]);return jsxs("div",{className:"jer-edit-buttons",style:isAdding?{opacity:1}:void 0,children:[enableClipboard&&jsx("div",{onClick:e=>{let value,copyType="value",stringValue="";if(enableClipboard){if(!0===(e.ctrlKey||e.metaKey))value=stringifyPath(path),stringValue=value,copyType="path";else value=data,stringValue=type?JSON.stringify(data,null,2):String(value);navigator.clipboard.writeText(stringValue)}"function"==typeof enableClipboard&&enableClipboard({value:value,stringValue:stringValue,path:path,key:name,type:copyType})},className:"jer-copy-pulse",children:jsx(Icon,{name:"copy"})}),startEdit&&jsx("div",{onClick:startEdit,children:jsx(Icon,{name:"edit"})}),handleDelete&&jsx("div",{onClick:handleDelete,children:jsx(Icon,{name:"delete"})}),handleAdd&&jsx("div",{onClick:()=>{"object"===type?setIsAdding(!0):handleAdd("")},children:jsx(Icon,{name:"add"})}),isAdding&&handleAdd&&"object"===type&&jsxs(Fragment,{children:[jsx("input",{className:"jer-input-new-key",type:"text",name:"new-object-key",value:newKey,onChange:e=>setNewKey(e.target.value),autoFocus:!0,onFocus:e=>e.target.select(),onKeyDown:e=>{"Enter"===e.key&&handleAdd?(setIsAdding(!1),handleAdd(newKey)):"Escape"===e.key&&setIsAdding(!1)},style:Object.assign({},styles.input)}),jsx(InputButtons,{onOk:()=>{newKey&&(setIsAdding(!1),handleAdd(newKey))},onCancel:()=>{setIsAdding(!1)}})]})]})},InputButtons=({onOk:onOk,onCancel:onCancel})=>jsxs("div",{className:"jer-confirm-buttons",children:[jsx("div",{onClick:onOk,children:jsx(Icon,{name:"ok"})}),jsx("div",{onClick:onCancel,children:jsx(Icon,{name:"cancel"})})]}),stringifyPath=path=>path.reduce(((str,part)=>"number"==typeof part?`${str}[${part}]`:""===str?part:`${str}.${part}`),""),DataTypes=["string","number","boolean","null","object","array"],getCustomNode=(customNodeDefinitions=[],filterProps)=>{const matchingDefinitions=customNodeDefinitions.filter((({condition:condition})=>condition(filterProps)));if(0===matchingDefinitions.length)return{};const{element:element,props:props,hideKey:hideKey=!1}=matchingDefinitions[0];return{CustomNode:element,customNodeProps:props,hideKey:hideKey}},CustomNodeWrapper=({name:name,hideKey:hideKey,children:children,indent:indent})=>{const{styles:styles}=useTheme();return jsx("div",{className:"jer-component jer-value-component",style:indent?{marginLeft:indent/2+"em"}:{},children:jsxs("div",{className:"jer-value-main-row",style:{flexWrap:name.length>10?"wrap":"nowrap"},children:[!hideKey&&jsxs("label",{htmlFor:name,className:"jer-object-key",style:Object.assign(Object.assign({},styles.property),{minWidth:`${Math.min(String(name).length+1,5)}ch`,flexShrink:name.length>10?1:0}),children:[name,":"," "]}),jsx("div",{className:"jer-value-and-buttons",style:{paddingLeft:hideKey?0:void 0},children:children})]})})},ValueNodeWrapper=props=>{const{data:data,parentData:parentData,name:name,path:path,onEdit:onEdit,onDelete:onDelete,enableClipboard:enableClipboard,restrictEditFilter:restrictEditFilter,restrictDeleteFilter:restrictDeleteFilter,restrictTypeSelection:restrictTypeSelection,showLabel:showLabel,stringTruncate:stringTruncate,indent:indent,translate:translate,customNodeDefinitions:customNodeDefinitions}=props,{styles:styles}=useTheme(),[isEditing,setIsEditing]=useState(!1),[isEditingKey,setIsEditingKey]=useState(!1),[value,setValue]=useState("function"==typeof data?"**INVALID_FUNCTION**":data),[error,setError]=useState(null),[dataType,setDataType]=useState(getDataType(data));useEffect((()=>{setValue("function"==typeof data?"**INVALID_FUNCTION**":data),setDataType(getDataType(data))}),[data,error]);const logError=errorString=>{setError(errorString),setTimeout((()=>setError(null)),2500),console.log("Error",errorString)},handleEdit=()=>{let newValue;switch(setIsEditing(!1),dataType){case"object":newValue={[translate("DEFAULT_NEW_KEY")]:value};break;case"array":newValue=null!==value?value:[];break;case"number":const n=Number(value);newValue=isNaN(n)?0:n;break;default:newValue=value}onEdit(newValue,path).then((error=>{error&&logError(error)}))},handleCancel=()=>{setIsEditing(!1),setIsEditingKey(!1),setValue(data),setDataType(getDataType(data))},filterProps={key:name,path:path,level:path.length,value:data,size:null},canEdit=useMemo((()=>!restrictEditFilter(filterProps)),[filterProps]),canDelete=useMemo((()=>!restrictDeleteFilter(filterProps)),[filterProps]),canEditKey=!("number"==typeof path.slice(-1)[0])&&canEdit&&canDelete,inputProps={value:value,parentData:parentData,setValue:setValue,isEditing:isEditing,setIsEditing:canEdit?()=>setIsEditing(!0):()=>{},handleEdit:handleEdit,handleCancel:handleCancel,path:path,stringTruncate:stringTruncate,translate:translate},{CustomNode:CustomNode,customNodeProps:customNodeProps,hideKey:hideKey}=getCustomNode(customNodeDefinitions,{key:name,path:path,level:path.length,value:data,size:0}),allDataTypes=[...customNodeDefinitions.filter((({showInTypesSelector:showInTypesSelector=!1})=>showInTypesSelector)).map((({name:name})=>name)),...DataTypes],allowedDataTypes=useMemo((()=>{if("boolean"==typeof restrictTypeSelection)return restrictTypeSelection?[]:allDataTypes;if(Array.isArray(restrictTypeSelection))return restrictTypeSelection;const result=restrictTypeSelection(filterProps);return"boolean"==typeof result?result?[]:allDataTypes:result}),[filterProps,restrictTypeSelection]);return CustomNode?jsx(CustomNodeWrapper,{name:name,hideKey:hideKey,indent:indent,children:jsx(CustomNode,Object.assign({customProps:customNodeProps},props))}):jsx("div",{className:"jer-component jer-value-component",style:{marginLeft:indent/2+"em"},children:jsxs("div",{className:"jer-value-main-row",style:{flexWrap:name.length>10?"wrap":"nowrap"},children:[showLabel&&!isEditingKey&&jsxs("label",{htmlFor:path.join("."),className:"jer-object-key",style:Object.assign(Object.assign({},styles.property),{minWidth:`${Math.min(String(name).length+1,5)}ch`,flexShrink:name.length>10?1:0}),onDoubleClick:()=>canEditKey&&setIsEditingKey(!0),children:[name,":"," "]}),showLabel&&isEditingKey&&jsx("input",{className:"jer-object-key",type:"text",name:path.join("."),defaultValue:name,autoFocus:!0,onFocus:e=>e.target.select(),onKeyDown:e=>{"Enter"===e.key?(newKey=>{if(setIsEditingKey(!1),!parentData)return;const parentPath=path.slice(0,-1);if(!newKey)return;const newData=Object.fromEntries(Object.entries(parentData).map((([key,val])=>key===name?[newKey,val]:[key,val])));onEdit(newData,parentPath)})(e.target.value):"Escape"===e.key&&handleCancel()},style:{width:String(name).length/1.5+.5+"em"}}),jsxs("div",{className:"jer-value-and-buttons",children:[jsx("div",{className:"jer-input-component",children:getInputComponent(dataType,inputProps)}),isEditing?jsx(InputButtons,{onOk:handleEdit,onCancel:handleCancel}):"invalid"!==dataType&&!error&&jsx(EditButtons,{startEdit:canEdit?()=>setIsEditing(!0):void 0,handleDelete:canDelete?()=>{onDelete(value,path).then((error=>{error&&logError(error)}))}:void 0,data:data,enableClipboard:enableClipboard,name:name,path:path,translate:translate}),isEditing&&allowedDataTypes.length>0&&jsxs("div",{className:"jer-select",children:[jsx("select",{name:`${name}-type-select`,className:"jer-type-select",onChange:e=>(type=>{const customNode=customNodeDefinitions.find((customNode=>customNode.name===type));customNode?onEdit(customNode.defaultValue,path):(setValue(convertValue(value,type)),setDataType(type))})(e.target.value),value:dataType,children:allowedDataTypes.map((type=>jsx("option",{value:type,children:type},type)))}),jsx("span",{className:"focus"})]}),!isEditing&&error&&jsx("span",{className:"jer-error-slug",style:styles.error,children:error})]})]})})},getDataType=value=>"string"==typeof value?"string":"number"==typeof value?"number":"boolean"==typeof value?"boolean":null===value?"null":"invalid",getInputComponent=(dataType,inputProps)=>{const value=inputProps.value;switch(dataType){case"string":return jsx(StringValue,Object.assign({},inputProps,{value:value}));case"number":return jsx(NumberValue,Object.assign({},inputProps,{value:value}));case"boolean":return jsx(BooleanValue,Object.assign({},inputProps,{value:value}));case"null":return jsx(NullValue,Object.assign({},inputProps));case"object":return jsx(ObjectValue,Object.assign({},inputProps,{value:value}));case"array":return jsx(ArrayValue,Object.assign({},inputProps));default:return jsx(InvalidValue,Object.assign({},inputProps))}},convertValue=(value,type)=>{switch(type){case"string":default:return String(value);case"number":const n=Number(value);return isNaN(n)?0:n;case"boolean":return!!value;case"null":return null;case"object":return value;case"array":return[value]}},isCollection=value=>null!==value&&"object"==typeof value,CollectionNode=_a=>{var{data:data,path:path,name:name,parentData:parentData,showCollectionCount:showCollectionCount}=_a,props=function(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]])}return t}(_a,["data","path","name","parentData","showCollectionCount"]);const{styles:styles}=useTheme(),{onEdit:onEdit,onAdd:onAdd,onDelete:onDelete,restrictEditFilter:restrictEditFilter,restrictDeleteFilter:restrictDeleteFilter,restrictAddFilter:restrictAddFilter,collapseFilter:collapseFilter,enableClipboard:enableClipboard,indent:indent,keySort:keySort,showArrayIndices:showArrayIndices,defaultValue:defaultValue,translate:translate,customNodeDefinitions:customNodeDefinitions}=props,[isEditing,setIsEditing]=useState(!1),[isEditingKey,setIsEditingKey]=useState(!1),[stringifiedValue,setStringifiedValue]=useState(JSON.stringify(data,null,2)),[error,setError]=useState(null),collectionSize=Object.keys(data).length,filterProps={key:name,path:path,level:path.length,value:data,size:collectionSize},startCollapsed=collapseFilter(filterProps),[collapsed,setCollapsed]=useState(startCollapsed),hasBeenOpened=useRef(!startCollapsed),[isAnimating,setIsAnimating]=useState(!1);useEffect((()=>{setStringifiedValue(JSON.stringify(data,null,2))}),[data]),useEffect((()=>{setCollapsed(collapseFilter(filterProps))}),[collapseFilter]);const collectionType=Array.isArray(data)?"array":"object",brackets="array"===collectionType?{open:"[",close:"]"}:{open:"{",close:"}"},transitionTime=getComputedStyle(document.documentElement).getPropertyValue("--jer-expand-transition-time"),showError=errorString=>{setError(errorString),setTimeout((()=>setError(null)),2500),console.log("Error",errorString)},handleEdit=()=>{try{const value=JSON.parse(stringifiedValue);setIsEditing(!1),setError(null),onEdit(value,path).then((error=>{error&&showError(error)}))}catch(_a){return setError(translate("ERROR_INVALID_JSON")),setTimeout((()=>setError(null)),2500),void console.log("Invalid JSON")}},handleDelete=path.length>0?()=>{onDelete(data,path).then((result=>{result&&showError(result)}))}:void 0,handleCancel=()=>{setIsEditing(!1),setIsEditingKey(!1),setError(null),setStringifiedValue(JSON.stringify(data,null,2))},canEdit=useMemo((()=>!restrictEditFilter(filterProps)),[filterProps]),canDelete=useMemo((()=>!restrictDeleteFilter(filterProps)),[filterProps]),canAdd=useMemo((()=>!restrictAddFilter(filterProps)),[filterProps]),canEditKey=null!==parentData&&canEdit&&canAdd&&canDelete,isArray="number"==typeof path.slice(-1)[0],showLabel=showArrayIndices||!isArray,showCount="when-closed"===showCollectionCount?collapsed:showCollectionCount,keyValueArray=Object.entries(data).map((([key,value])=>["array"===collectionType?Number(key):key,value]));keySort&&"object"===collectionType&&keyValueArray.sort("function"==typeof keySort?(a,b)=>keySort(a[0],b[0]):void 0);const numOfLines=JSON.stringify(data,null,2).split("\n").length,{CustomNode:CustomNode,customNodeProps:customNodeProps,hideKey:hideKey}=getCustomNode(customNodeDefinitions,{key:name,path:path,level:path.length,value:data,size:Object.keys(data).length});return jsx("div",{className:"jer-component jer-collection-component",style:{marginLeft:(0===path.length?0:indent/2)+"em"},children:CustomNode?jsx(CustomNodeWrapper,{name:name,hideKey:hideKey,children:jsx(CustomNode,Object.assign({data:data,path:path,name:name,parentData:parentData,customProps:customNodeProps},props))}):jsxs(Fragment,{children:[jsxs("div",{className:"jer-collection-header-row",children:[jsx("div",{onClick:()=>{isEditing||(setIsAnimating(!0),hasBeenOpened.current=!0,setCollapsed(!collapsed),setTimeout((()=>setIsAnimating(!1)),500))},children:jsx(Icon,{name:"chevron",rotate:collapsed})}),jsxs("div",{className:"jer-collection-name",children:[!isEditingKey&&jsx("span",{style:styles.property,onDoubleClick:()=>canEditKey&&setIsEditingKey(!0),children:showLabel&&""!==name&&void 0!==name?`${name}:`:null}),isEditingKey&&jsx("input",{className:"jer-collection-name",type:"text",name:path.join("."),defaultValue:name,autoFocus:!0,onFocus:e=>e.target.select(),onKeyDown:e=>{"Enter"===e.key?(newKey=>{if(setIsEditingKey(!1),!parentData)return;const parentPath=path.slice(0,-1);if(!newKey)return;const newData=Object.fromEntries(Object.entries(parentData).map((([key,val])=>key===name?[newKey,val]:[key,val])));onEdit(newData,parentPath)})(e.target.value):"Escape"===e.key&&handleCancel()},style:{width:String(name).length/1.5+.5+"em"}}),!isEditing&&jsx("span",{className:"jer-brackets",style:styles.bracket,children:brackets.open})]}),!isEditing&&showCollectionCount&&jsx("div",{className:"jer-collection-item-count"+(showCount?" jer-visible":" jer-hidden"),style:styles.itemCount,children:1===collectionSize?translate("ITEM_SINGLE",1):translate("ITEMS_MULTIPLE",collectionSize)}),jsx("div",{className:"jer-brackets"+(collapsed?" jer-visible":" jer-hidden"),style:styles.bracket,children:brackets.close}),!isEditing&&jsx(EditButtons,{startEdit:canEdit?()=>{setIsEditing(!0),setCollapsed(!1)}:void 0,handleAdd:canAdd?key=>{if(setCollapsed(!1),"array"===collectionType)onAdd(defaultValue,[...path,data.length]).then((error=>{error&&showError(error)}));else{if(key in data)return void showError(translate("ERROR_KEY_EXISTS"));onAdd(defaultValue,[...path,key]).then((error=>{error&&showError(error)}))}}:void 0,handleDelete:canDelete?handleDelete:void 0,enableClipboard:enableClipboard,type:collectionType,data:data,name:name,path:path,translate:translate})]}),jsxs("div",{className:"jer-collection-inner",style:{maxHeight:collapsed?0:isEditing?void 0:3*numOfLines+"em",overflowY:collapsed||isAnimating?"hidden":"visible",transition:`max-height ${transitionTime}`},children:[isEditing?jsx("div",{className:"jer-collection-text-edit",children:jsxs("div",{children:[jsx(AutogrowTextArea,{className:"jer-collection-text-area",name:path.join("."),value:stringifiedValue,setValue:setStringifiedValue,isEditing:isEditing,handleKeyPress:e=>{"Enter"===e.key&&(e.metaKey||e.shiftKey||e.ctrlKey)?handleEdit():"Escape"===e.key&&handleCancel()}}),jsx("div",{className:"jer-collection-input-button-row",children:jsx(InputButtons,{onOk:handleEdit,onCancel:handleCancel,isCollection:!0})})]})}):jsx(Fragment,{children:hasBeenOpened.current?keyValueArray.map((([key,value])=>jsx("div",{className:"jer-collection-element",children:isCollection(value)?jsx(CollectionNode,Object.assign({data:value,parentData:data,path:[...path,key],name:key,showCollectionCount:showCollectionCount},props),key):jsx(ValueNodeWrapper,Object.assign({data:value,parentData:data,path:[...path,key],name:key},props,{showLabel:"object"===collectionType||showArrayIndices}),key)},key))):null}),jsx("div",{className:isEditing?"jer-collection-error-row":"jer-collection-error-row-edit",children:error&&jsx("span",{className:"jer-error-slug",style:styles.error,children:error})}),jsx("div",{className:"jer-brackets",style:styles.bracket,children:brackets.close})]})]})})},localisedStrings={ITEM_SINGLE:"{{count}} item",ITEMS_MULTIPLE:"{{count}} items",KEY_NEW:"Enter new key",ERROR_KEY_EXISTS:"Key already exists",ERROR_INVALID_JSON:"Invalid JSON",ERROR_UPDATE:"Update unsuccessful",ERROR_DELETE:"Delete unsuccessful",ERROR_ADD:"Adding node unsuccessful",DEFAULT_STRING:"New data!",DEFAULT_NEW_KEY:"key"},getTranslateFunction=translations=>(key,count)=>((translations,key,count)=>{const string=key in translations?translations[key]:localisedStrings[key];return void 0===count?string:null==string?void 0:string.replace("{{count}}",String(count))})(translations,key,count),Editor=({data:data,rootName:rootName="root",onUpdate:onUpdate,onEdit:srcEdit=onUpdate,onDelete:srcDelete=onUpdate,onAdd:srcAdd=onUpdate,enableClipboard:enableClipboard=!0,theme:theme="default",icons:icons,indent:indent=4,collapse:collapse=!1,showCollectionCount:showCollectionCount=!0,restrictEdit:restrictEdit=!1,restrictDelete:restrictDelete=!1,restrictAdd:restrictAdd=!1,restrictTypeSelection:restrictTypeSelection=!1,keySort:keySort=!1,showArrayIndices:showArrayIndices=!0,defaultValue:defaultValue=null,minWidth:minWidth=250,maxWidth:maxWidth="min(600px, 90vw)",stringTruncate:stringTruncate=250,translations:translations={},className:className,customNodeDefinitions:customNodeDefinitions=[]})=>{const{styles:styles,setTheme:setTheme,setIcons:setIcons}=useTheme(),collapseFilter=useCallback(getFilterFunction(collapse),[collapse]),translate=useCallback(getTranslateFunction(translations),[translations]);useEffect((()=>{theme&&setTheme(theme),icons&&setIcons(icons)}),[theme,icons]);const otherProps={name:rootName,onEdit:(value,path)=>__awaiter(void 0,void 0,void 0,(function*(){const{currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue}=updateDataObject(data,path,value,"update");if(srcEdit){const result=yield srcEdit({currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue,name:path.slice(-1)[0],path:path});return!1===result?translate("ERROR_UPDATE"):result}})),onDelete:(value,path)=>__awaiter(void 0,void 0,void 0,(function*(){const{currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue}=updateDataObject(data,path,value,"delete");if(srcDelete){const result=yield srcDelete({currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue,name:path.slice(-1)[0],path:path});return!1===result?translate("ERROR_DELETE"):result}})),onAdd:(value,path)=>__awaiter(void 0,void 0,void 0,(function*(){const{currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue}=updateDataObject(data,path,value,"add");if(srcAdd){const result=yield srcAdd({currentData:currentData,newData:newData,currentValue:currentValue,newValue:newValue,name:path.slice(-1)[0],path:path});return!1===result?translate("ERROR_ADD"):result}})),showCollectionCount:showCollectionCount,collapseFilter:collapseFilter,restrictEditFilter:getFilterFunction(restrictEdit),restrictDeleteFilter:getFilterFunction(restrictDelete),restrictAddFilter:getFilterFunction(restrictAdd),restrictTypeSelection:restrictTypeSelection,enableClipboard:enableClipboard,keySort:keySort,showArrayIndices:showArrayIndices,indent:indent,defaultValue:defaultValue,stringTruncate:stringTruncate,translate:translate,customNodeDefinitions:customNodeDefinitions,parentData:null};return styles?jsx("div",{className:"jer-editor-container "+className,style:Object.assign(Object.assign({},styles.container),{minWidth:minWidth,maxWidth:maxWidth}),children:isCollection(data)?jsx(CollectionNode,Object.assign({data:data,path:[]},otherProps)):jsx(ValueNodeWrapper,Object.assign({data:data,path:[],showLabel:!0},otherProps))}):null},JsonEditor=props=>jsx(ThemeProvider,{children:jsx(Editor,Object.assign({},props))}),updateDataObject=(data,path,newValue,action)=>{if(0===path.length)return{currentData:data,newData:newValue,currentValue:data,newValue:newValue};const currentValue="add"!==action?extract(data,path):void 0;return{currentData:data,newData:assign(clone(data),path,newValue,{remove:"delete"===action}),currentValue:currentValue,newValue:"update"===action?newValue:void 0}},getFilterFunction=propValue=>"boolean"==typeof propValue?()=>propValue:"number"==typeof propValue?({level:level})=>level>=propValue:propValue;export{JsonEditor,themes};