vzcode 2.31.0 → 2.35.0

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.
@@ -9,21 +9,26 @@ import { VZCodeContext } from '../../VZCodeContext';
9
9
  import { VizContent, VizFileId } from '@vizhub/viz-types';
10
10
  import { VisualEditorConfigEntry } from '../../../types';
11
11
  import { EmptyState } from '../EmptyState';
12
- import { color, hcl, HCLColor, rgb } from 'd3-color';
12
+ import {
13
+ toHclChannels,
14
+ hclChannelsToHex,
15
+ } from './colorUtils';
13
16
  import { CONFIG_FILE_NAME } from './constants';
17
+ import { getVisualEditorEmptyReason } from './status';
18
+ import { updateVisualEditorProperty } from './updateConfig';
14
19
  import { SliderWidget } from './SliderWidget';
15
20
  import { CheckboxWidget } from './CheckboxWidget';
16
21
  import { TextInputWidget } from './TextInputWidget';
17
22
  import { DropdownWidget } from './DropdownWidget';
18
23
  import { ColorWidget } from './ColorWidget';
19
- import {
20
- getNestedProperty,
21
- setNestedProperty,
22
- } from './utils';
24
+ import { getNestedProperty } from './utils';
23
25
 
24
26
  export const VisualEditor = () => {
25
- const { files, submitOperation } =
26
- useContext(VZCodeContext);
27
+ const {
28
+ files,
29
+ submitOperation,
30
+ renderVisualEditorEmptyState,
31
+ } = useContext(VZCodeContext);
27
32
 
28
33
  // Local state to track widget values during user interaction
29
34
  const [localValues, setLocalValues] = useState<{
@@ -57,131 +62,61 @@ export const VisualEditor = () => {
57
62
  }
58
63
  }, [configFileId, files]);
59
64
 
65
+ // All controls share one optimistic state + ShareDB write path.
66
+ const setWidgetValue = useCallback(
67
+ (
68
+ property: string,
69
+ value: number | boolean | string,
70
+ extraLocalValues: Record<string, number> = {},
71
+ ) => {
72
+ setLocalValues((prev) => ({
73
+ ...prev,
74
+ [property]: value,
75
+ ...extraLocalValues,
76
+ }));
77
+ submitOperation((document: VizContent) =>
78
+ updateVisualEditorProperty(
79
+ document,
80
+ configFileId,
81
+ property,
82
+ value,
83
+ ),
84
+ );
85
+ },
86
+ [configFileId, submitOperation],
87
+ );
88
+
60
89
  const onSliderChange = useCallback(
61
90
  (property: string) =>
62
- (event: React.ChangeEvent<HTMLInputElement>) => {
63
- const newValue = parseFloat(
64
- event.currentTarget.value,
65
- );
66
-
67
- // Update local state immediately for responsive UI
68
- setLocalValues((prev) => ({
69
- ...prev,
70
- [property]: newValue,
71
- }));
72
-
73
- // Update config.json with support for nested properties
74
- const newConfigData = setNestedProperty(
75
- configData,
91
+ (event: React.ChangeEvent<HTMLInputElement>) =>
92
+ setWidgetValue(
76
93
  property,
77
- newValue,
78
- );
79
-
80
- submitOperation((document: VizContent) => ({
81
- ...document,
82
- files: {
83
- ...files,
84
- [configFileId]: {
85
- name: 'config.json',
86
- text: JSON.stringify(newConfigData, null, 2),
87
- },
88
- },
89
- }));
90
- },
91
- [configData, files, configFileId, submitOperation],
94
+ parseFloat(event.currentTarget.value),
95
+ ),
96
+ [setWidgetValue],
92
97
  );
93
98
 
94
99
  const onCheckboxChange = useCallback(
95
100
  (property: string) =>
96
- (event: React.ChangeEvent<HTMLInputElement>) => {
97
- const newValue = event.currentTarget.checked;
98
-
99
- // Update local state immediately for responsive UI
100
- setLocalValues((prev) => ({
101
- ...prev,
102
- [property]: newValue,
103
- }));
104
-
105
- // Update config.json with support for nested properties
106
- const newConfigData = setNestedProperty(
107
- configData,
101
+ (event: React.ChangeEvent<HTMLInputElement>) =>
102
+ setWidgetValue(
108
103
  property,
109
- newValue,
110
- );
111
-
112
- submitOperation((document: VizContent) => ({
113
- ...document,
114
- files: {
115
- ...files,
116
- [configFileId]: {
117
- name: 'config.json',
118
- text: JSON.stringify(newConfigData, null, 2),
119
- },
120
- },
121
- }));
122
- },
123
- [configData, files, configFileId, submitOperation],
104
+ event.currentTarget.checked,
105
+ ),
106
+ [setWidgetValue],
124
107
  );
125
108
 
126
109
  const onTextInputChange = useCallback(
127
110
  (property: string) =>
128
- (event: React.ChangeEvent<HTMLInputElement>) => {
129
- const newValue = event.currentTarget.value;
130
-
131
- // Update local state immediately for responsive UI
132
- setLocalValues((prev) => ({
133
- ...prev,
134
- [property]: newValue,
135
- }));
136
-
137
- // Update config.json with support for nested properties
138
- const newConfigData = setNestedProperty(
139
- configData,
140
- property,
141
- newValue,
142
- );
143
-
144
- submitOperation((document: VizContent) => ({
145
- ...document,
146
- files: {
147
- ...files,
148
- [configFileId]: {
149
- name: 'config.json',
150
- text: JSON.stringify(newConfigData, null, 2),
151
- },
152
- },
153
- }));
154
- },
155
- [configData, files, configFileId, submitOperation],
111
+ (event: React.ChangeEvent<HTMLInputElement>) =>
112
+ setWidgetValue(property, event.currentTarget.value),
113
+ [setWidgetValue],
156
114
  );
157
115
 
158
116
  const onDropdownChange = useCallback(
159
- (property: string, newValue: string) => {
160
- // Update local state immediately for responsive UI
161
- setLocalValues((prev) => ({
162
- ...prev,
163
- [property]: newValue,
164
- }));
165
-
166
- // Update config.json with support for nested properties
167
- const newConfigData = setNestedProperty(
168
- configData,
169
- property,
170
- newValue,
171
- );
172
-
173
- submitOperation((document: VizContent) => ({
174
- ...document,
175
- files: {
176
- ...files,
177
- [configFileId]: {
178
- name: 'config.json',
179
- text: JSON.stringify(newConfigData, null, 2),
180
- },
181
- },
182
- }));
183
- },
184
- [configData, files, configFileId, submitOperation],
117
+ (property: string, value: string) =>
118
+ setWidgetValue(property, value),
119
+ [setWidgetValue],
185
120
  );
186
121
 
187
122
  // Custom dropdown handlers
@@ -237,89 +172,38 @@ export const VisualEditor = () => {
237
172
  getNestedProperty<string>(configData, property) ??
238
173
  '#000000';
239
174
 
240
- // Convert current hex to LCH
241
- let hclFromRGB: HCLColor;
242
- try {
243
- const rgbColor = rgb(currentHex);
244
- hclFromRGB = hcl(rgbColor);
245
- } catch {
246
- // Fallback to black if conversion fails
247
- hclFromRGB = hcl('black');
248
- }
249
-
250
- const hclArray: number[] = [
251
- (localValues[`${property}_h`] as number) ??
252
- hclFromRGB.h,
253
- (localValues[`${property}_c`] as number) ??
254
- hclFromRGB.c,
255
- (localValues[`${property}_l`] as number) ??
256
- hclFromRGB.l,
257
- ];
258
-
259
- // Update the specific LCH component
260
- const newhcl = [...hclArray];
261
- if (lchComponent === 'h') newhcl[0] = newValue;
262
- else if (lchComponent === 'c') newhcl[1] = newValue;
263
- else if (lchComponent === 'l') newhcl[2] = newValue;
264
-
265
- // Convert back to hex
266
- let newHex;
267
- try {
268
- const newColor = hcl(
269
- newhcl[0],
270
- newhcl[1],
271
- newhcl[2],
272
- );
273
-
274
- if (newColor.displayable()) {
275
- newHex = newColor.formatHex();
276
- } else {
277
- newHex = currentHex;
278
- }
279
- } catch {
280
- // Fallback to current color if conversion fails
281
- newHex = currentHex;
282
- }
283
-
284
- // Update local state for responsive UI
285
- setLocalValues((prev) => ({
286
- ...prev,
287
- [property]: newHex,
288
- [`${property}_h`]: newhcl[0],
289
- [`${property}_c`]: newhcl[1],
290
- [`${property}_l`]: newhcl[2],
291
- }));
292
-
293
- // Update config.json with hex value using nested property access
294
- const newConfigData = setNestedProperty(
295
- configData,
296
- property,
297
- newHex,
175
+ const base = toHclChannels(currentHex);
176
+ const channels = {
177
+ h:
178
+ (localValues[`${property}_h`] as number) ??
179
+ base.h,
180
+ c:
181
+ (localValues[`${property}_c`] as number) ??
182
+ base.c,
183
+ l:
184
+ (localValues[`${property}_l`] as number) ??
185
+ base.l,
186
+ };
187
+ channels[lchComponent] = newValue;
188
+ const newHex = hclChannelsToHex(
189
+ channels,
190
+ currentHex,
298
191
  );
299
-
300
- submitOperation((document: VizContent) => ({
301
- ...document,
302
- files: {
303
- ...files,
304
- [configFileId]: {
305
- name: 'config.json',
306
- text: JSON.stringify(newConfigData, null, 2),
307
- },
308
- },
309
- }));
192
+ setWidgetValue(property, newHex, {
193
+ [`${property}_h`]: channels.h,
194
+ [`${property}_c`]: channels.c,
195
+ [`${property}_l`]: channels.l,
196
+ });
310
197
  },
311
- [
312
- configData,
313
- files,
314
- configFileId,
315
- submitOperation,
316
- localValues,
317
- ],
198
+ [configData, setWidgetValue, localValues],
318
199
  );
319
200
 
320
201
  const visualEditorWidgets: VisualEditorConfigEntry[] =
321
202
  useMemo(
322
- () => configData?.visualEditorWidgets ?? [],
203
+ () =>
204
+ Array.isArray(configData?.visualEditorWidgets)
205
+ ? configData.visualEditorWidgets
206
+ : [],
323
207
  [configData],
324
208
  );
325
209
 
@@ -329,106 +213,46 @@ export const VisualEditor = () => {
329
213
  [key: string]: number | boolean | string;
330
214
  } = {};
331
215
  visualEditorWidgets.forEach((widget) => {
332
- if (widget.type === 'slider') {
333
- newLocalValues[widget.property] = getNestedProperty(
334
- configData,
335
- widget.property,
336
- );
337
- } else if (widget.type === 'checkbox') {
338
- newLocalValues[widget.property] = getNestedProperty(
339
- configData,
340
- widget.property,
341
- );
342
- } else if (widget.type === 'textInput') {
343
- newLocalValues[widget.property] = getNestedProperty(
344
- configData,
345
- widget.property,
346
- );
347
- } else if (widget.type === 'dropdown') {
348
- newLocalValues[widget.property] = getNestedProperty(
349
- configData,
350
- widget.property,
351
- );
352
- } else if (widget.type === 'color') {
353
- newLocalValues[widget.property] = getNestedProperty(
354
- configData,
355
- widget.property,
356
- );
357
-
358
- // Convert hex to LCH for internal state
359
- const hexColor = getNestedProperty<string>(
360
- configData,
361
- widget.property,
362
- );
363
-
364
- if (localValues[widget.property] !== hexColor) {
365
- if (hexColor) {
366
- try {
367
- const rgbColor = color(hexColor);
368
- const lch = hcl(rgbColor);
369
- newLocalValues[`${widget.property}_h`] =
370
- lch.h;
371
- newLocalValues[`${widget.property}_c`] =
372
- lch.c;
373
- newLocalValues[`${widget.property}_l`] =
374
- lch.l;
375
- } catch {
376
- // Fallback values if conversion fails
377
- newLocalValues[`${widget.property}_l`] = 0;
378
- newLocalValues[`${widget.property}_c`] = 0;
379
- newLocalValues[`${widget.property}_h`] = 0;
380
- }
381
- }
382
- }
216
+ const value = getNestedProperty<
217
+ string | number | boolean
218
+ >(configData, widget.property);
219
+ if (value !== undefined)
220
+ newLocalValues[widget.property] = value;
221
+ if (
222
+ widget.type === 'color' &&
223
+ typeof value === 'string'
224
+ ) {
225
+ const channels = toHclChannels(value);
226
+ newLocalValues[`${widget.property}_h`] = channels.h;
227
+ newLocalValues[`${widget.property}_c`] = channels.c;
228
+ newLocalValues[`${widget.property}_l`] = channels.l;
383
229
  }
384
230
  });
385
231
  setLocalValues(newLocalValues);
386
- }, [configData, localValues, visualEditorWidgets]);
387
-
388
- if (configFileId === null) {
389
- return (
390
- <EmptyState>
391
- To begin using the visual editor, create a
392
- config.json.
393
- </EmptyState>
394
- );
395
- }
396
-
397
- if (!configData) {
398
- return (
399
- <EmptyState>
400
- Your config.json file is not valid json.
401
- </EmptyState>
402
- );
403
- }
404
-
405
- if (
406
- configData &&
407
- !('visualEditorWidgets' in configData)
408
- ) {
409
- return (
410
- <EmptyState>
411
- To begin using the visual editor, make sure your
412
- config.json has a key called
413
- &quot;visualEditorWidgets&quot;, whose value is the
414
- config for the visual editor.
415
- </EmptyState>
416
- );
417
- }
232
+ }, [configData, visualEditorWidgets]);
418
233
 
419
- if (
420
- configData &&
421
- !Array.isArray(configData.visualEditorWidgets)
422
- ) {
423
- return (
424
- <EmptyState>
425
- Your config.json file has
426
- &quot;visualEditorWidgets&quot; but it is not an
427
- array. Please make sure
428
- &quot;visualEditorWidgets&quot; is an array of
429
- widget configurations.
430
- </EmptyState>
431
- );
234
+ const emptyReason = getVisualEditorEmptyReason(
235
+ configFileId === null
236
+ ? null
237
+ : (files?.[configFileId]?.text ?? null),
238
+ );
239
+ if (emptyReason) {
240
+ const hostUI =
241
+ renderVisualEditorEmptyState?.(emptyReason);
242
+ if (hostUI != null) return <>{hostUI}</>;
243
+ const messages = {
244
+ 'missing-config':
245
+ 'To begin using the visual editor, create a config.json.',
246
+ 'invalid-config':
247
+ 'Your config.json file is not valid JSON.',
248
+ 'missing-widgets':
249
+ 'Add a visualEditorWidgets array to config.json.',
250
+ 'invalid-widgets':
251
+ 'Your visualEditorWidgets configuration is invalid.',
252
+ 'empty-widgets':
253
+ 'Add at least one widget to visualEditorWidgets.',
254
+ };
255
+ return <EmptyState>{messages[emptyReason]}</EmptyState>;
432
256
  }
433
257
 
434
258
  return (
@@ -552,25 +376,16 @@ export const VisualEditor = () => {
552
376
  ) ??
553
377
  '#000000';
554
378
 
555
- // Convert hex to LCH for slider values
556
- let hclColor;
557
- try {
558
- const rgbColor = color(currentHex);
559
- hclColor = hcl(rgbColor);
560
- } catch {
561
- hclColor = hcl('black');
562
- }
563
-
564
- // Use local LCH values if available, otherwise convert from hex
379
+ const channels = toHclChannels(currentHex);
565
380
  const currentH =
566
381
  localValues[`${widgetConfig.property}_h`] ??
567
- hclColor.h;
382
+ channels.h;
568
383
  const currentC =
569
384
  localValues[`${widgetConfig.property}_c`] ??
570
- hclColor.c;
385
+ channels.c;
571
386
  const currentL =
572
387
  localValues[`${widgetConfig.property}_l`] ??
573
- hclColor.l;
388
+ channels.l;
574
389
 
575
390
  return (
576
391
  <ColorWidget
@@ -0,0 +1,25 @@
1
+ import { color, hcl } from 'd3-color';
2
+
3
+ export type HclChannels = {
4
+ h: number;
5
+ c: number;
6
+ l: number;
7
+ };
8
+
9
+ export function toHclChannels(value: string): HclChannels {
10
+ const parsed = color(value);
11
+ const result = parsed ? hcl(parsed) : hcl('black');
12
+ return {
13
+ h: Number.isFinite(result.h) ? result.h : 0,
14
+ c: Number.isFinite(result.c) ? result.c : 0,
15
+ l: Number.isFinite(result.l) ? result.l : 0,
16
+ };
17
+ }
18
+
19
+ export function hclChannelsToHex(
20
+ channels: HclChannels,
21
+ fallback: string,
22
+ ): string {
23
+ const next = hcl(channels.h, channels.c, channels.l);
24
+ return next.displayable() ? next.formatHex() : fallback;
25
+ }
@@ -0,0 +1,112 @@
1
+ import { color } from 'd3-color';
2
+ import type { VisualEditorEmptyReason } from '../../../types';
3
+ import { getEditablePropertyValue } from './utils';
4
+
5
+ const isRecord = (
6
+ value: unknown,
7
+ ): value is Record<string, unknown> =>
8
+ value !== null &&
9
+ typeof value === 'object' &&
10
+ !Array.isArray(value);
11
+
12
+ /** Pure classifier shared by the visual editor and host integration tests. */
13
+ export function getVisualEditorEmptyReason(
14
+ configText: string | null,
15
+ ): VisualEditorEmptyReason | null {
16
+ if (configText === null) return 'missing-config';
17
+ let config: unknown;
18
+ try {
19
+ config = JSON.parse(configText);
20
+ } catch {
21
+ return 'invalid-config';
22
+ }
23
+ if (!isRecord(config)) return 'invalid-config';
24
+ if (
25
+ !Object.prototype.hasOwnProperty.call(
26
+ config,
27
+ 'visualEditorWidgets',
28
+ )
29
+ )
30
+ return 'missing-widgets';
31
+
32
+ const widgets = config.visualEditorWidgets;
33
+ if (!Array.isArray(widgets)) return 'invalid-widgets';
34
+ if (!widgets.length) return 'empty-widgets';
35
+
36
+ for (const widget of widgets) {
37
+ if (
38
+ !isRecord(widget) ||
39
+ typeof widget.property !== 'string' ||
40
+ !widget.property ||
41
+ typeof widget.label !== 'string' ||
42
+ !widget.label.trim()
43
+ ) {
44
+ return 'invalid-widgets';
45
+ }
46
+
47
+ const { found, value } = getEditablePropertyValue(
48
+ config,
49
+ widget.property,
50
+ );
51
+ if (!found) return 'invalid-widgets';
52
+
53
+ switch (widget.type) {
54
+ case 'slider':
55
+ if (
56
+ !Number.isFinite(value) ||
57
+ !Number.isFinite(widget.min) ||
58
+ !Number.isFinite(widget.max) ||
59
+ (widget.min as number) >=
60
+ (widget.max as number) ||
61
+ (widget.step !== undefined &&
62
+ (!Number.isFinite(widget.step) ||
63
+ (widget.step as number) <= 0))
64
+ ) {
65
+ return 'invalid-widgets';
66
+ }
67
+ break;
68
+ case 'checkbox':
69
+ if (typeof value !== 'boolean')
70
+ return 'invalid-widgets';
71
+ break;
72
+ case 'textInput':
73
+ if (typeof value !== 'string')
74
+ return 'invalid-widgets';
75
+ break;
76
+ case 'dropdown':
77
+ if (
78
+ typeof value !== 'string' ||
79
+ !Array.isArray(widget.options) ||
80
+ widget.options.length === 0 ||
81
+ !widget.options.every(
82
+ (option: unknown) => typeof option === 'string',
83
+ ) ||
84
+ !widget.options.includes(value)
85
+ ) {
86
+ return 'invalid-widgets';
87
+ }
88
+ break;
89
+ case 'color': {
90
+ if (typeof value !== 'string')
91
+ return 'invalid-widgets';
92
+ // A color widget converts through RGB/HCL. A mere string (or the
93
+ // special transparent color with NaN RGB channels) is not usable.
94
+ const rgb = color(value)?.rgb();
95
+ if (
96
+ !rgb ||
97
+ !Number.isFinite(rgb.r) ||
98
+ !Number.isFinite(rgb.g) ||
99
+ !Number.isFinite(rgb.b) ||
100
+ rgb.opacity !== 1
101
+ ) {
102
+ return 'invalid-widgets';
103
+ }
104
+ break;
105
+ }
106
+ default:
107
+ return 'invalid-widgets';
108
+ }
109
+ }
110
+
111
+ return null;
112
+ }
@@ -0,0 +1,61 @@
1
+ import type {
2
+ VizContent,
3
+ VizFileId,
4
+ } from '@vizhub/viz-types';
5
+ import {
6
+ setNestedProperty,
7
+ getEditablePropertyValue,
8
+ } from './utils';
9
+
10
+ /**
11
+ * Apply a widget edit against the LATEST ShareDB document, not a stale React
12
+ * closure. Preserve unrelated files and concurrent edits to other properties.
13
+ */
14
+ export function updateVisualEditorProperty(
15
+ document: VizContent,
16
+ configFileId: VizFileId | null,
17
+ property: string,
18
+ value: string | number | boolean,
19
+ ): VizContent {
20
+ if (!configFileId) return document;
21
+ const original = document.files[configFileId];
22
+ if (!original) return document;
23
+ let currentConfig: unknown;
24
+ try {
25
+ currentConfig = JSON.parse(original.text);
26
+ } catch {
27
+ return document;
28
+ }
29
+ if (
30
+ !currentConfig ||
31
+ typeof currentConfig !== 'object' ||
32
+ Array.isArray(currentConfig)
33
+ )
34
+ return document;
35
+ // A widget may become stale after a concurrent config edit. Never recreate
36
+ // a removed property or change the structure of its parent object.
37
+ if (
38
+ !getEditablePropertyValue(currentConfig, property).found
39
+ )
40
+ return document;
41
+ let updated: Record<string, unknown>;
42
+ try {
43
+ updated = setNestedProperty(
44
+ currentConfig as Record<string, unknown>,
45
+ property,
46
+ value,
47
+ );
48
+ } catch {
49
+ return document;
50
+ }
51
+ return {
52
+ ...document,
53
+ files: {
54
+ ...document.files,
55
+ [configFileId]: {
56
+ ...original,
57
+ text: JSON.stringify(updated, null, 2),
58
+ },
59
+ },
60
+ };
61
+ }