vzcode 2.34.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,7 +9,10 @@ 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';
14
17
  import { getVisualEditorEmptyReason } from './status';
15
18
  import { updateVisualEditorProperty } from './updateConfig';
@@ -59,95 +62,61 @@ export const VisualEditor = () => {
59
62
  }
60
63
  }, [configFileId, files]);
61
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
+
62
89
  const onSliderChange = useCallback(
63
90
  (property: string) =>
64
- (event: React.ChangeEvent<HTMLInputElement>) => {
65
- const newValue = parseFloat(
66
- event.currentTarget.value,
67
- );
68
-
69
- // Update local state immediately for responsive UI
70
- setLocalValues((prev) => ({
71
- ...prev,
72
- [property]: newValue,
73
- }));
74
-
75
- submitOperation((document: VizContent) =>
76
- updateVisualEditorProperty(
77
- document,
78
- configFileId,
79
- property,
80
- newValue,
81
- ),
82
- );
83
- },
84
- [configFileId, submitOperation],
91
+ (event: React.ChangeEvent<HTMLInputElement>) =>
92
+ setWidgetValue(
93
+ property,
94
+ parseFloat(event.currentTarget.value),
95
+ ),
96
+ [setWidgetValue],
85
97
  );
86
98
 
87
99
  const onCheckboxChange = useCallback(
88
100
  (property: string) =>
89
- (event: React.ChangeEvent<HTMLInputElement>) => {
90
- const newValue = event.currentTarget.checked;
91
-
92
- // Update local state immediately for responsive UI
93
- setLocalValues((prev) => ({
94
- ...prev,
95
- [property]: newValue,
96
- }));
97
-
98
- submitOperation((document: VizContent) =>
99
- updateVisualEditorProperty(
100
- document,
101
- configFileId,
102
- property,
103
- newValue,
104
- ),
105
- );
106
- },
107
- [configFileId, submitOperation],
101
+ (event: React.ChangeEvent<HTMLInputElement>) =>
102
+ setWidgetValue(
103
+ property,
104
+ event.currentTarget.checked,
105
+ ),
106
+ [setWidgetValue],
108
107
  );
109
108
 
110
109
  const onTextInputChange = useCallback(
111
110
  (property: string) =>
112
- (event: React.ChangeEvent<HTMLInputElement>) => {
113
- const newValue = event.currentTarget.value;
114
-
115
- // Update local state immediately for responsive UI
116
- setLocalValues((prev) => ({
117
- ...prev,
118
- [property]: newValue,
119
- }));
120
-
121
- submitOperation((document: VizContent) =>
122
- updateVisualEditorProperty(
123
- document,
124
- configFileId,
125
- property,
126
- newValue,
127
- ),
128
- );
129
- },
130
- [configFileId, submitOperation],
111
+ (event: React.ChangeEvent<HTMLInputElement>) =>
112
+ setWidgetValue(property, event.currentTarget.value),
113
+ [setWidgetValue],
131
114
  );
132
115
 
133
116
  const onDropdownChange = useCallback(
134
- (property: string, newValue: string) => {
135
- // Update local state immediately for responsive UI
136
- setLocalValues((prev) => ({
137
- ...prev,
138
- [property]: newValue,
139
- }));
140
-
141
- submitOperation((document: VizContent) =>
142
- updateVisualEditorProperty(
143
- document,
144
- configFileId,
145
- property,
146
- newValue,
147
- ),
148
- );
149
- },
150
- [configFileId, submitOperation],
117
+ (property: string, value: string) =>
118
+ setWidgetValue(property, value),
119
+ [setWidgetValue],
151
120
  );
152
121
 
153
122
  // Custom dropdown handlers
@@ -203,74 +172,30 @@ export const VisualEditor = () => {
203
172
  getNestedProperty<string>(configData, property) ??
204
173
  '#000000';
205
174
 
206
- // Convert current hex to LCH
207
- let hclFromRGB: HCLColor;
208
- try {
209
- const rgbColor = rgb(currentHex);
210
- hclFromRGB = hcl(rgbColor);
211
- } catch {
212
- // Fallback to black if conversion fails
213
- hclFromRGB = hcl('black');
214
- }
215
-
216
- const hclArray: number[] = [
217
- (localValues[`${property}_h`] as number) ??
218
- hclFromRGB.h,
219
- (localValues[`${property}_c`] as number) ??
220
- hclFromRGB.c,
221
- (localValues[`${property}_l`] as number) ??
222
- hclFromRGB.l,
223
- ];
224
-
225
- // Update the specific LCH component
226
- const newhcl = [...hclArray];
227
- if (lchComponent === 'h') newhcl[0] = newValue;
228
- else if (lchComponent === 'c') newhcl[1] = newValue;
229
- else if (lchComponent === 'l') newhcl[2] = newValue;
230
-
231
- // Convert back to hex
232
- let newHex;
233
- try {
234
- const newColor = hcl(
235
- newhcl[0],
236
- newhcl[1],
237
- newhcl[2],
238
- );
239
-
240
- if (newColor.displayable()) {
241
- newHex = newColor.formatHex();
242
- } else {
243
- newHex = currentHex;
244
- }
245
- } catch {
246
- // Fallback to current color if conversion fails
247
- newHex = currentHex;
248
- }
249
-
250
- // Update local state for responsive UI
251
- setLocalValues((prev) => ({
252
- ...prev,
253
- [property]: newHex,
254
- [`${property}_h`]: newhcl[0],
255
- [`${property}_c`]: newhcl[1],
256
- [`${property}_l`]: newhcl[2],
257
- }));
258
-
259
- submitOperation((document: VizContent) =>
260
- updateVisualEditorProperty(
261
- document,
262
- configFileId,
263
- property,
264
- newHex,
265
- ),
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,
266
191
  );
192
+ setWidgetValue(property, newHex, {
193
+ [`${property}_h`]: channels.h,
194
+ [`${property}_c`]: channels.c,
195
+ [`${property}_l`]: channels.l,
196
+ });
267
197
  },
268
- [
269
- configData,
270
- configFileId,
271
- submitOperation,
272
- localValues,
273
- ],
198
+ [configData, setWidgetValue, localValues],
274
199
  );
275
200
 
276
201
  const visualEditorWidgets: VisualEditorConfigEntry[] =
@@ -288,52 +213,19 @@ export const VisualEditor = () => {
288
213
  [key: string]: number | boolean | string;
289
214
  } = {};
290
215
  visualEditorWidgets.forEach((widget) => {
291
- if (widget.type === 'slider') {
292
- newLocalValues[widget.property] = getNestedProperty(
293
- configData,
294
- widget.property,
295
- );
296
- } else if (widget.type === 'checkbox') {
297
- newLocalValues[widget.property] = getNestedProperty(
298
- configData,
299
- widget.property,
300
- );
301
- } else if (widget.type === 'textInput') {
302
- newLocalValues[widget.property] = getNestedProperty(
303
- configData,
304
- widget.property,
305
- );
306
- } else if (widget.type === 'dropdown') {
307
- newLocalValues[widget.property] = getNestedProperty(
308
- configData,
309
- widget.property,
310
- );
311
- } else if (widget.type === 'color') {
312
- newLocalValues[widget.property] = getNestedProperty(
313
- configData,
314
- widget.property,
315
- );
316
-
317
- // Convert hex to LCH for internal state
318
- const hexColor = getNestedProperty<string>(
319
- configData,
320
- widget.property,
321
- );
322
-
323
- if (hexColor) {
324
- try {
325
- const rgbColor = color(hexColor);
326
- const lch = hcl(rgbColor);
327
- newLocalValues[`${widget.property}_h`] = lch.h;
328
- newLocalValues[`${widget.property}_c`] = lch.c;
329
- newLocalValues[`${widget.property}_l`] = lch.l;
330
- } catch {
331
- // Fallback values if conversion fails
332
- newLocalValues[`${widget.property}_l`] = 0;
333
- newLocalValues[`${widget.property}_c`] = 0;
334
- newLocalValues[`${widget.property}_h`] = 0;
335
- }
336
- }
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;
337
229
  }
338
230
  });
339
231
  setLocalValues(newLocalValues);
@@ -484,25 +376,16 @@ export const VisualEditor = () => {
484
376
  ) ??
485
377
  '#000000';
486
378
 
487
- // Convert hex to LCH for slider values
488
- let hclColor;
489
- try {
490
- const rgbColor = color(currentHex);
491
- hclColor = hcl(rgbColor);
492
- } catch {
493
- hclColor = hcl('black');
494
- }
495
-
496
- // Use local LCH values if available, otherwise convert from hex
379
+ const channels = toHclChannels(currentHex);
497
380
  const currentH =
498
381
  localValues[`${widgetConfig.property}_h`] ??
499
- hclColor.h;
382
+ channels.h;
500
383
  const currentC =
501
384
  localValues[`${widgetConfig.property}_c`] ??
502
- hclColor.c;
385
+ channels.c;
503
386
  const currentL =
504
387
  localValues[`${widgetConfig.property}_l`] ??
505
- hclColor.l;
388
+ channels.l;
506
389
 
507
390
  return (
508
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
+ }
@@ -1,11 +1,6 @@
1
1
  import { color } from 'd3-color';
2
2
  import type { VisualEditorEmptyReason } from '../../../types';
3
-
4
- const UNSAFE_PATH_SEGMENTS = new Set([
5
- '__proto__',
6
- 'constructor',
7
- 'prototype',
8
- ]);
3
+ import { getEditablePropertyValue } from './utils';
9
4
 
10
5
  const isRecord = (
11
6
  value: unknown,
@@ -14,39 +9,6 @@ const isRecord = (
14
9
  typeof value === 'object' &&
15
10
  !Array.isArray(value);
16
11
 
17
- /**
18
- * Resolve only own properties of plain JSON objects, using the same dot-path
19
- * semantics as setNestedProperty. Missing values, arrays in the path and
20
- * dangerous keys are not editable targets.
21
- */
22
- function editableValueAt(
23
- config: Record<string, unknown>,
24
- path: string,
25
- ): { found: boolean; value: unknown } {
26
- const segments = path.split('.');
27
- if (
28
- segments.some(
29
- (segment) =>
30
- !segment || UNSAFE_PATH_SEGMENTS.has(segment),
31
- )
32
- ) {
33
- return { found: false, value: undefined };
34
- }
35
-
36
- let value: unknown = config;
37
- for (const segment of segments) {
38
- if (
39
- !isRecord(value) ||
40
- !Object.prototype.hasOwnProperty.call(value, segment)
41
- ) {
42
- return { found: false, value: undefined };
43
- }
44
- value = value[segment];
45
- }
46
-
47
- return { found: true, value };
48
- }
49
-
50
12
  /** Pure classifier shared by the visual editor and host integration tests. */
51
13
  export function getVisualEditorEmptyReason(
52
14
  configText: string | null,
@@ -82,7 +44,7 @@ export function getVisualEditorEmptyReason(
82
44
  return 'invalid-widgets';
83
45
  }
84
46
 
85
- const { found, value } = editableValueAt(
47
+ const { found, value } = getEditablePropertyValue(
86
48
  config,
87
49
  widget.property,
88
50
  );
@@ -2,7 +2,10 @@ import type {
2
2
  VizContent,
3
3
  VizFileId,
4
4
  } from '@vizhub/viz-types';
5
- import { setNestedProperty } from './utils';
5
+ import {
6
+ setNestedProperty,
7
+ getEditablePropertyValue,
8
+ } from './utils';
6
9
 
7
10
  /**
8
11
  * Apply a widget edit against the LATEST ShareDB document, not a stale React
@@ -29,6 +32,12 @@ export function updateVisualEditorProperty(
29
32
  Array.isArray(currentConfig)
30
33
  )
31
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;
32
41
  let updated: Record<string, unknown>;
33
42
  try {
34
43
  updated = setNestedProperty(
@@ -101,38 +101,57 @@ export const renderSliderBackground = (
101
101
  ctx.putImageData(imageData, 0, 0);
102
102
  };
103
103
 
104
- // Helper function to get nested property value using dot notation
105
- export const getNestedProperty = <T = unknown>(
106
- obj: Record<string, unknown>,
104
+ /**
105
+ * Widget paths are own-property paths through JSON objects. This parser is
106
+ * shared by reads, validation and writes to avoid accidental prototype access.
107
+ */
108
+ export const splitEditablePropertyPath = (
107
109
  path: string,
108
- ): T | undefined => {
109
- // Validate path to prevent empty strings, consecutive dots, or leading/trailing dots
110
- if (
111
- !path ||
112
- path.includes('..') ||
113
- path.startsWith('.') ||
114
- path.endsWith('.')
115
- ) {
116
- return undefined;
117
- }
110
+ ): string[] | null => {
111
+ if (typeof path !== 'string' || !path) return null;
112
+ const segments = path.split('.');
113
+ return segments.every(
114
+ (key) =>
115
+ key.length > 0 &&
116
+ key !== '__proto__' &&
117
+ key !== 'constructor' &&
118
+ key !== 'prototype',
119
+ )
120
+ ? segments
121
+ : null;
122
+ };
118
123
 
119
- const keys = path.split('.');
120
- let value: unknown = obj;
124
+ export const getEditablePropertyValue = (
125
+ obj: unknown,
126
+ path: string,
127
+ ): { found: boolean; value: unknown } => {
128
+ const keys = splitEditablePropertyPath(path);
129
+ if (!keys) return { found: false, value: undefined };
130
+ let current: unknown = obj;
121
131
  for (const key of keys) {
122
- // Skip empty keys that might result from splitting
123
- if (!key) {
124
- return undefined;
125
- }
126
- if (value === null || value === undefined) {
127
- return undefined;
128
- }
129
- // Type guard to ensure value is an object before accessing property
130
- if (typeof value !== 'object') {
131
- return undefined;
132
+ if (
133
+ current === null ||
134
+ typeof current !== 'object' ||
135
+ Array.isArray(current) ||
136
+ !Object.prototype.hasOwnProperty.call(current, key)
137
+ ) {
138
+ return { found: false, value: undefined };
132
139
  }
133
- value = (value as Record<string, unknown>)[key];
140
+ current = (current as Record<string, unknown>)[key];
134
141
  }
135
- return value as T | undefined;
142
+ return { found: true, value: current };
143
+ };
144
+
145
+ // Read widget values using exactly the same safe path semantics as writes.
146
+ export const getNestedProperty = <T = unknown>(
147
+ obj: Record<string, unknown>,
148
+ path: string,
149
+ ): T | undefined => {
150
+ const { found, value } = getEditablePropertyValue(
151
+ obj,
152
+ path,
153
+ );
154
+ return found ? (value as T) : undefined;
136
155
  };
137
156
 
138
157
  // Helper function to set nested property value using dot notation
@@ -143,47 +162,18 @@ export const setNestedProperty = <
143
162
  path: string,
144
163
  value: unknown,
145
164
  ): T => {
146
- // Validate path to prevent empty strings, consecutive dots, or leading/trailing dots
147
- if (
148
- !path ||
149
- path.includes('..') ||
150
- path.startsWith('.') ||
151
- path.endsWith('.')
152
- ) {
153
- throw new Error(
154
- `Invalid property path "${path}" - path cannot be empty, contain consecutive dots, or have leading/trailing dots`,
155
- );
156
- }
157
-
158
- const keys = path.split('.');
159
-
160
- // Check for empty keys
161
- if (keys.some((key) => !key)) {
165
+ const keys = splitEditablePropertyPath(path);
166
+ if (!keys)
162
167
  throw new Error(
163
- `Invalid property path "${path}" - path contains empty segments`,
168
+ 'Invalid or unsafe property path: ' + path,
164
169
  );
165
- }
166
170
 
167
171
  const newObj = { ...obj };
168
172
  let current: Record<string, unknown> = newObj;
169
173
 
170
- // List of dangerous keys that could lead to prototype pollution
171
- const dangerousKeys = [
172
- '__proto__',
173
- 'constructor',
174
- 'prototype',
175
- ];
176
-
177
174
  for (let i = 0; i < keys.length - 1; i++) {
178
175
  const key = keys[i];
179
176
 
180
- // Guard against prototype pollution
181
- if (dangerousKeys.includes(key)) {
182
- throw new Error(
183
- `Cannot set property "${key}" - potential prototype pollution`,
184
- );
185
- }
186
-
187
177
  // Create nested object if it doesn't exist or isn't a plain object
188
178
  if (
189
179
  current[key] == null ||
@@ -200,13 +190,7 @@ export const setNestedProperty = <
200
190
  current = current[key] as Record<string, unknown>;
201
191
  }
202
192
 
203
- // Guard against prototype pollution for the final key
204
193
  const finalKey = keys[keys.length - 1];
205
- if (dangerousKeys.includes(finalKey)) {
206
- throw new Error(
207
- `Cannot set property "${finalKey}" - potential prototype pollution`,
208
- );
209
- }
210
194
 
211
195
  // Set the final value
212
196
  current[finalKey] = value;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * An editor owns the temporary Ctrl-hover and Ctrl-click listeners.
3
+ * Keeping their lifecycle together prevents stale DOM handlers when panes
4
+ * switch or VZCode is unmounted.
5
+ */
6
+ export function createDefinitionJumpListeners(
7
+ target: EventTarget,
8
+ onHover: (event: MouseEvent) => void,
9
+ onClick: (event: MouseEvent) => void,
10
+ ) {
11
+ let hovering = false;
12
+ let armed = false;
13
+
14
+ const hoverListener: EventListener = (event) => {
15
+ onHover(event as MouseEvent);
16
+ };
17
+ const clickListener: EventListener = (event) => {
18
+ armed = false;
19
+ target.removeEventListener('mousedown', clickListener);
20
+ onClick(event as MouseEvent);
21
+ };
22
+
23
+ return {
24
+ start() {
25
+ if (hovering) return;
26
+ hovering = true;
27
+ target.addEventListener('mouseover', hoverListener);
28
+ },
29
+ armClick() {
30
+ if (armed) return;
31
+ armed = true;
32
+ target.addEventListener('mousedown', clickListener);
33
+ },
34
+ stop() {
35
+ hovering = false;
36
+ armed = false;
37
+ target.removeEventListener(
38
+ 'mouseover',
39
+ hoverListener,
40
+ );
41
+ target.removeEventListener(
42
+ 'mousedown',
43
+ clickListener,
44
+ );
45
+ },
46
+ };
47
+ }