Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Collection improvements (#5571)

Oleg Isonenb0fe05611b16
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 41156f0e8d..ea147b2ce1 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -15,8 +15,13 @@
- Never alias the same type or variable to different names (e.g., `type AliasName = OriginalName`) - always use the original name consistently throughout the codebase
- Spreading `undefined` works fine in JavaScript/TypeScript - the spread operator skips it. Never return empty objects `{}` when you can just `return` (or omit return for `undefined`). Example: `return { ...obj, ...maybeUndefined }` works correctly.
-## Running Checks
+## Running Commands
+- For global workspace commands (e.g., "update fixtures", "run checks"), always check the root `package.json` scripts first
+- The root package.json at `/workspaces/webstudio/package.json` contains commands like:
+ - `pnpm fixtures` - updates all fixtures (link, sync, build)
+ - `pnpm checks` - runs all checks (tests, typecheck, lint, fixtures)
+ - `pnpm build` - builds all packages
- Before running any commands, always check `get_errors` tool first to see TypeScript and ESLint errors in the VS Code editor
- Only run `pnpm typecheck` and `pnpm eslint` when user explicitly says "run checks" or after completing substantial changes
- `pnpm typecheck` is slow - avoid running it unnecessarily during development
diff --git a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
index a2086c92ac..336bdb9cc1 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/boolean.tsx
@@ -3,6 +3,7 @@ import { Grid, Switch, theme } from "@webstudio-is/design-system";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import {
type ControlProps,
@@ -54,11 +55,7 @@ export const BooleanControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "boolean") {
- return `${label} expects a boolean value`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, label)}
variant={variant}
value={expression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/code.tsx b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
index fe389a32af..7e2c8078f0 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/code.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/code.tsx
@@ -18,6 +18,7 @@ import { CodeEditor } from "~/shared/code-editor";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import {
useLocalValue,
@@ -224,11 +225,7 @@ export const CodeControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `${label} expects a string value`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, label)}
variant={variant}
value={expression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/file.tsx b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
index 4f8bc109d2..af01813b14 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/file.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/file.tsx
@@ -4,6 +4,7 @@ import { Flex, InputField, theme } from "@webstudio-is/design-system";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import {
type ControlProps,
@@ -88,11 +89,7 @@ export const FileControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `${label} expects a string value or file`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, label)}
variant={variant}
value={expression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
index aaf1cab21a..e596be45a5 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx
@@ -23,6 +23,7 @@ import { isLiteralExpression, Resource, type Prop } from "@webstudio-is/sdk";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
type BindingVariant,
} from "~/builder/shared/binding-popover";
import {
@@ -320,11 +321,7 @@ export const ResourceControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `Expected URL string value`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, "URL")}
variant={variant}
value={urlExpression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
index 2fa42f1535..44ab9a2b6c 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx
@@ -16,6 +16,7 @@ import { $instances } from "~/shared/sync/data-stores";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import { updateWebstudioData } from "~/shared/instance-utils";
import { CodeEditor } from "~/shared/code-editor";
@@ -138,11 +139,7 @@ export const TextContent = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `Text Content expects a string value`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, "Text Content")}
variant={variant}
value={expression}
onChange={(newExpression) => {
diff --git a/apps/builder/app/builder/features/settings-panel/controls/text.tsx b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
index 7fe11f8a80..240c4c4fc0 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/text.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/text.tsx
@@ -4,6 +4,7 @@ import { TextArea } from "@webstudio-is/design-system";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import {
type ControlProps,
@@ -57,11 +58,7 @@ export const TextControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `${label} expects a string value`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, label)}
variant={variant}
value={expression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/features/settings-panel/controls/url.tsx b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
index 39e285a5bc..3337544f8b 100644
--- a/apps/builder/app/builder/features/settings-panel/controls/url.tsx
+++ b/apps/builder/app/builder/features/settings-panel/controls/url.tsx
@@ -29,6 +29,7 @@ import { $instances, $pages, $props } from "~/shared/sync/data-stores";
import {
BindingControl,
BindingPopover,
+ validatePrimitiveValue,
} from "~/builder/shared/binding-popover";
import {
type ControlProps,
@@ -521,11 +522,7 @@ export const UrlControl = ({
<BindingPopover
scope={scope}
aliases={aliases}
- validate={(value) => {
- if (value !== undefined && typeof value !== "string") {
- return `${label} expects a string value, page or file`;
- }
- }}
+ validate={(value) => validatePrimitiveValue(value, label)}
variant={variant}
value={expression}
onChange={(newExpression) =>
diff --git a/apps/builder/app/builder/shared/binding-popover.tsx b/apps/builder/app/builder/shared/binding-popover.tsx
index 9636aec9f2..9b3fe35d4e 100644
--- a/apps/builder/app/builder/shared/binding-popover.tsx
+++ b/apps/builder/app/builder/shared/binding-popover.tsx
@@ -47,6 +47,33 @@ import {
type EditorApi,
} from "./expression-editor";
+/**
+ * Check if a value is a primitive that can be safely stringified.
+ * Allows: string, number, boolean, null, undefined
+ * Rejects: object, array, function, symbol
+ */
+export const isPrimitiveValue = (value: unknown): boolean => {
+ if (value === null || value === undefined) {
+ return true;
+ }
+ const type = typeof value;
+ return type === "string" || type === "number" || type === "boolean";
+};
+
+/**
+ * Generate a validation error message for non-primitive values.
+ * @param label - The control label (e.g., "Title", "URL")
+ * @returns Error message or undefined if value is valid
+ */
+export const validatePrimitiveValue = (
+ value: unknown,
+ label: string
+): string | undefined => {
+ if (!isPrimitiveValue(value)) {
+ return `${label} expects a primitive value (string, number, boolean, null, or undefined), not an object, array, or function`;
+ }
+};
+
export const evaluateExpressionWithinScope = (
expression: string,
scope: Record<string, unknown>
diff --git a/apps/builder/app/builder/shared/expression-editor.test.ts b/apps/builder/app/builder/shared/expression-editor.test.ts
new file mode 100644
index 0000000000..97dc2eaea0
--- /dev/null
+++ b/apps/builder/app/builder/shared/expression-editor.test.ts
@@ -0,0 +1,265 @@
+import { describe, test, expect } from "vitest";
+import { generateCompletionOptions } from "./expression-editor";
+
+describe("generateCompletionOptions", () => {
+ describe("object properties", () => {
+ test("returns object properties with preview values", () => {
+ const target = { name: "John", age: 30, email: "[email protected]" };
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expect(options).toEqual([
+ { label: "name", detail: `"John"` },
+ { label: "age", detail: "30" },
+ { label: "email", detail: `"[email protected]"` },
+ ]);
+ });
+
+ test("returns all properties regardless of pathName (filtering happens in CodeMirror layer)", () => {
+ const target = { name: "John", age: 30, email: "[email protected]" };
+ const options = generateCompletionOptions({
+ target,
+ pathName: "na",
+ pathLength: 1,
+ });
+
+ // generateCompletionOptions doesn't filter - that's done by matchSorter in scopeCompletionSource
+ expect(options).toEqual([
+ { label: "name", detail: `"John"` },
+ { label: "age", detail: "30" },
+ { label: "email", detail: `"[email protected]"` },
+ ]);
+ });
+
+ test("handles properties with special characters", () => {
+ const target = { "prop with spaces": "value", "123": "numeric key" };
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ // Object.entries order for number-like keys may vary
+ const labels = options.map((o) => o.label);
+ expect(labels).toContain("prop with spaces");
+ expect(labels).toContain("123");
+ });
+ });
+
+ describe("array properties and methods", () => {
+ test("returns array indices, length property, and methods", () => {
+ const target = ["apple", "banana", "cherry"];
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ // Should include indices, length, and all array methods
+ const labels = options.map((o) => o.label);
+ expect(labels).toContain("0");
+ expect(labels).toContain("1");
+ expect(labels).toContain("2");
+ expect(labels).toContain("length");
+ expect(labels).toContain("filter()");
+ expect(labels).toContain("slice()");
+
+ // Check specific values
+ const lengthOption = options.find((o) => o.label === "length");
+ expect(lengthOption).toEqual({
+ label: "length",
+ detail: "3",
+ type: "property",
+ });
+ });
+
+ test("includes array methods when searching", () => {
+ const target = [1, 2, 3];
+ const options = generateCompletionOptions({
+ target,
+ pathName: "fil",
+ pathLength: 1,
+ });
+
+ const methodOptions = options.filter((o) => o.type === "method");
+ expect(methodOptions).toContainEqual({
+ label: "filter()",
+ detail: "array method",
+ type: "method",
+ });
+ });
+
+ test("filters length property by pathName", () => {
+ const target = [1, 2, 3, 4, 5];
+ const options = generateCompletionOptions({
+ target,
+ pathName: "len",
+ pathLength: 1,
+ });
+
+ expect(options).toContainEqual({
+ label: "length",
+ detail: "5",
+ type: "property",
+ });
+ });
+ });
+
+ describe("string methods", () => {
+ test("returns string methods when target is a string", () => {
+ const target = "hello world";
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ const methodLabels = options.map((o) => o.label);
+ expect(methodLabels).toContain("toUpperCase()");
+ expect(methodLabels).toContain("toLowerCase()");
+ expect(methodLabels).toContain("replace()");
+ });
+
+ test("filters string methods by pathName", () => {
+ const target = "test string";
+ const options = generateCompletionOptions({
+ target,
+ pathName: "upper",
+ pathLength: 1,
+ });
+
+ // Should include both toUpperCase and toLocaleUpperCase
+ const labels = options.map((o) => o.label);
+ expect(labels).toContain("toUpperCase()");
+ expect(labels).toContain("toLocaleUpperCase()");
+ });
+
+ test("does not return string methods for non-string targets", () => {
+ const target = { name: "test" };
+ const options = generateCompletionOptions({
+ target,
+ pathName: "upper",
+ pathLength: 1,
+ });
+
+ // Should only return object properties, no string methods
+ const methodOptions = options.filter((o) => o.type === "method");
+ expect(methodOptions).toEqual([]);
+ });
+ });
+
+ describe("pathLength === 0 (top-level variables)", () => {
+ test("does not include methods for top-level variables", () => {
+ const target = "hello";
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 0,
+ });
+
+ expect(options).toEqual([]);
+ });
+
+ test("returns array indices for top-level arrays (but no methods)", () => {
+ const target = [1, 2, 3];
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 0,
+ });
+
+ // At pathLength === 0, we get array indices but no length/methods
+ expect(options).toEqual([
+ { label: "0", detail: "1" },
+ { label: "1", detail: "2" },
+ { label: "2", detail: "3" },
+ ]);
+ });
+ });
+
+ describe("non-object targets", () => {
+ test("returns empty array for null", () => {
+ const options = generateCompletionOptions({
+ target: null,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expect(options).toEqual([]);
+ });
+
+ test("returns empty array for undefined", () => {
+ const options = generateCompletionOptions({
+ target: undefined,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expect(options).toEqual([]);
+ });
+
+ test("returns empty array for primitive numbers", () => {
+ const options = generateCompletionOptions({
+ target: 42,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expect(options).toEqual([]);
+ });
+ });
+
+ describe("edge cases", () => {
+ test("handles empty object", () => {
+ const options = generateCompletionOptions({
+ target: {},
+ pathName: "",
+ pathLength: 1,
+ });
+
+ expect(options).toEqual([]);
+ });
+
+ test("handles empty array", () => {
+ const options = generateCompletionOptions({
+ target: [],
+ pathName: "",
+ pathLength: 1,
+ });
+
+ // Empty array has length and all array methods
+ const labels = options.map((o) => o.label);
+ expect(labels).toContain("length");
+ expect(labels).toContain("filter()");
+ expect(labels).toContain("slice()");
+
+ const lengthOption = options.find((o) => o.label === "length");
+ expect(lengthOption).toEqual({
+ label: "length",
+ detail: "0",
+ type: "property",
+ });
+ });
+
+ test("handles nested values in preview", () => {
+ const target = {
+ nested: { inner: "value" },
+ arr: [1, 2, 3],
+ };
+ const options = generateCompletionOptions({
+ target,
+ pathName: "",
+ pathLength: 1,
+ });
+
+ // formatValuePreview returns "JSON" for complex objects
+ expect(options).toEqual([
+ { label: "nested", detail: "JSON" },
+ { label: "arr", detail: "JSON" },
+ ]);
+ });
+ });
+});
diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsx
index 8b6a42187e..fdb84a0b51 100644
--- a/apps/builder/app/builder/shared/expression-editor.tsx
+++ b/apps/builder/app/builder/shared/expression-editor.tsx
@@ -183,6 +183,73 @@ const completionPath = (
return;
};
+/**
+ * Generate completion options for object properties and array/string methods.
+ * Exported for testing.
+ */
+export const generateCompletionOptions = ({
+ target,
+ pathName,
+ pathLength,
+}: {
+ target: unknown;
+ pathName: string;
+ pathLength: number;
+}): Array<{ label: string; detail: string; type?: string }> => {
+ const options: Array<{ label: string; detail: string; type?: string }> = [];
+
+ // Add object properties
+ if (typeof target === "object" && target !== null) {
+ for (const [name, value] of Object.entries(target)) {
+ options.push({
+ label: name,
+ detail: formatValuePreview(value),
+ });
+ }
+ }
+
+ // Add string/array methods and properties for nested paths
+ if (pathLength > 0) {
+ const isString = typeof target === "string";
+ const isArray = Array.isArray(target);
+
+ if (isString) {
+ for (const method of allowedStringMethods) {
+ if (method.toLowerCase().includes(pathName.toLowerCase())) {
+ options.push({
+ label: `${method}()`,
+ detail: "string method",
+ type: "method",
+ });
+ }
+ }
+ }
+
+ if (isArray) {
+ // Add length property
+ if ("length".toLowerCase().includes(pathName.toLowerCase())) {
+ options.push({
+ label: "length",
+ detail: `${target.length}`,
+ type: "property",
+ });
+ }
+
+ for (const method of allowedArrayMethods) {
+ if (method.toLowerCase().includes(pathName.toLowerCase())) {
+ options.push({
+ label: `${method}()`,
+ detail: "array method",
+ type: "method",
+ });
+ }
+ }
+ }
+ }
+
+ return options;
+};
+
// Defines a completion source that completes from the given scope
// object (for example `globalThis`). Will enter properties
// of the object when completing properties on a directly-named path.
@@ -200,18 +267,29 @@ const scopeCompletionSource: CompletionSource = (context) => {
return null;
}
}
- let options: Completion[] = [];
- if (typeof target === "object" && target !== null) {
- options = Object.entries(target).map(([name, value]) => ({
+
+ // Generate base completion options using exported function
+ const baseOptions = generateCompletionOptions({
+ target,
+ pathName: path.name,
+ pathLength: path.path.length,
+ });
+
+ // Convert to CodeMirror Completion format with apply functions
+ let options: Completion[] = baseOptions.map((option) => {
+ const name = option.label;
+ return {
label: name,
displayLabel: decodeDataVariableName(name),
- detail: formatValuePreview(value),
+ detail: option.detail,
+ type: option.type,
apply: (view, completion, from, to) => {
+ const textToInsert = name;
// complete valid js identifier or top level variable without quotes
- if (Identifier.test(name) || path.path.length === 0) {
+ if (Identifier.test(textToInsert) || path.path.length === 0) {
// complete with dot
view.dispatch({
- ...insertCompletionText(view.state, name, from, to),
+ ...insertCompletionText(view.state, textToInsert, from, to),
annotations: pickedCompletion.of(completion),
});
} else {
@@ -221,7 +299,7 @@ const scopeCompletionSource: CompletionSource = (context) => {
view.state,
// `param with spaces` -> ["param with spaces"]
// `0` -> [0]
- `[${/^\d+$/.test(name) ? name : JSON.stringify(name)}]`,
+ `[${/^\d+$/.test(textToInsert) ? textToInsert : JSON.stringify(textToInsert)}]`,
// remove dot when autocomplete computed member expression
// variable.
// variable["name"]
@@ -232,7 +310,11 @@ const scopeCompletionSource: CompletionSource = (context) => {
});
}
},
- }));
+ };
+ });
+
+ // Sort options if target is an object
+ if (typeof target === "object" && target !== null) {
options = matchSorter(options, path.name, {
keys: [(option) => option.displayLabel ?? option.label],
baseSort: (left, right) => {
@@ -250,55 +332,6 @@ const scopeCompletionSource: CompletionSource = (context) => {
});
}
- // Add safe string and array method completions
- if (path.path.length > 0) {
- const methodOptions: Completion[] = [];
-
- // Determine if target is likely a string or array based on its value
- const isString = typeof target === "string";
- const isArray = Array.isArray(target);
-
- // Add string methods only if target is a string
- if (isString) {
- for (const method of allowedStringMethods) {
- if (method.toLowerCase().includes(path.name.toLowerCase())) {
- methodOptions.push({
- label: `${method}()`,
- detail: "string method",
- type: "method",
- apply: (view, completion, from, to) => {
- view.dispatch({
- ...insertCompletionText(view.state, `${method}()`, from, to),
- annotations: pickedCompletion.of(completion),
- });
- },
- });
- }
- }
- }
-
- // Add array methods if target is an array
- if (isArray) {
- for (const method of allowedArrayMethods) {
- if (method.toLowerCase().includes(path.name.toLowerCase())) {
- methodOptions.push({
- label: `${method}()`,
- detail: "array method",
- type: "method",
- apply: (view, completion, from, to) => {
- view.dispatch({
- ...insertCompletionText(view.state, `${method}()`, from, to),
- annotations: pickedCompletion.of(completion),
- });
- },
- });
- }
- }
- }
-
- options = [...options, ...methodOptions];
- }
-
return {
from: context.pos - path.name.length,
filter: false,
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index 06022730a3..a70aa9e01f 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -321,9 +321,13 @@ export const $propValuesByInstanceSelector = computed(
if (instance.component === collectionComponent) {
const originalData = propValues.get("data");
const itemVariableId = parameters.get("item");
+ const itemKeyVariableId = parameters.get("itemKey");
if (itemVariableId !== undefined && originalData) {
for (const [key, value] of getCollectionEntries(originalData)) {
variableValues.set(itemVariableId, value);
+ if (itemKeyVariableId !== undefined) {
+ variableValues.set(itemKeyVariableId, key);
+ }
for (const child of instance.children) {
if (child.type === "id") {
const indexId = getIndexedInstanceId(instanceId, key);
@@ -521,15 +525,22 @@ export const $variableValuesByInstanceSelector = computed(
if (instance.component === collectionComponent) {
const originalData = propValues.get("data");
const itemVariableId = parameters.get("item");
+ const itemKeyVariableId = parameters.get("itemKey");
if (itemVariableId === undefined) {
return;
}
// prevent accessing item from collection
variableValues.delete(itemVariableId);
+ if (itemKeyVariableId !== undefined) {
+ variableValues.delete(itemKeyVariableId);
+ }
if (originalData) {
for (const [key, value] of getCollectionEntries(originalData)) {
const itemVariableValues = new Map(variableValues);
itemVariableValues.set(itemVariableId, value);
+ if (itemKeyVariableId !== undefined) {
+ itemVariableValues.set(itemKeyVariableId, key);
+ }
for (const child of instance.children) {
if (child.type === "id") {
const indexId = getIndexedInstanceId(instanceId, key);
diff --git a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
index 36d64ee640..1e84b99fc0 100644
--- a/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[resources]._index.tsx
@@ -36,13 +36,19 @@ const Page = (_props: { system: any }) => {
{Object.entries(
// @ts-ignore
list?.data ?? {}
- ).map(([index, collectionItem]: any) => (
- <Fragment key={index}>
- <Box className={`w-box`}>
- <HtmlEmbed code={collectionItem?.name} className={`w-html-embed`} />
- </Box>
- </Fragment>
- ))}
+ ).map(([_key, collectionItem]: any) => {
+ const index = Array.isArray(list?.data) ? Number(_key) : _key;
+ return (
+ <Fragment key={index}>
+ <Box className={`w-box`}>
+ <HtmlEmbed
+ code={collectionItem?.name}
+ className={`w-html-embed`}
+ />
+ </Box>
+ </Fragment>
+ );
+ })}
</Body>
);
};
diff --git a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
index dc0cc8f357..20b416a9a7 100644
--- a/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
+++ b/fixtures/webstudio-features/app/__generated__/[sitemap.xml]._index.tsx
@@ -48,22 +48,36 @@ const Page = (_props: { system: any }) => {
lastModified: "2024-05-07",
},
] ?? {}
- ).map(([index, url]: any) => (
- <Fragment key={index}>
- <XmlNode tag={"url"}>
- <XmlNode tag={"loc"}>
- {`${system?.origin ?? "${ORIGIN}"}${url?.path}`}
+ ).map(([_key, url]: any) => {
+ const index = Array.isArray([
+ {
+ path: "/",
+ lastModified: "2024-05-07",
+ },
+ {
+ path: "/olegs-test",
+ lastModified: "2024-05-07",
+ },
+ ])
+ ? Number(_key)
+ : _key;
+ return (
+ <Fragment key={index}>
+ <XmlNode tag={"url"}>
+ <XmlNode tag={"loc"}>
+ {`${system?.origin ?? "${ORIGIN}"}${url?.path}`}
+ </XmlNode>
+ <XmlNode tag={"lastmod"}>{url?.lastModified}</XmlNode>
+ <XmlNode
+ tag={"xhtml:link"}
+ rel={"alternate"}
+ hreflang={"en"}
+ href={`${system?.origin ?? "${ORIGIN}"}${url?.path}en`}
+ />
</XmlNode>
- <XmlNode tag={"lastmod"}>{url?.lastModified}</XmlNode>
- <XmlNode
- tag={"xhtml:link"}
- rel={"alternate"}
- hreflang={"en"}
- href={`${system?.origin ?? "${ORIGIN}"}${url?.path}en`}
- />
- </XmlNode>
- </Fragment>
- ))}
+ </Fragment>
+ );
+ })}
<XmlNode tag={"url"}>
<XmlNode tag={"loc"}>{"custom-hand-made-location"}</XmlNode>
<XmlNode tag={"lastmod"}>
diff --git a/packages/react-sdk/src/collection-utils.test.ts b/packages/react-sdk/src/collection-utils.test.ts
index 2a52872d2e..3e72371f66 100644
--- a/packages/react-sdk/src/collection-utils.test.ts
+++ b/packages/react-sdk/src/collection-utils.test.ts
@@ -6,9 +6,9 @@ import {
test("getCollectionEntries handles arrays", () => {
expect(getCollectionEntries(["a", "b", "c"])).toEqual([
- ["0", "a"],
- ["1", "b"],
- ["2", "c"],
+ [0, "a"],
+ [1, "b"],
+ [2, "c"],
]);
});
@@ -40,7 +40,9 @@ test("generateCollectionIterationCode produces correct template", () => {
expect(code).toBe(`Object.entries(
// @ts-ignore
myData ?? {}
-).map(([index, item]: any)`);
+).map(([_key, item]: any) => {
+ const index = Array.isArray(myData) ? Number(_key) : _key;
+ return`);
});
test("generated code works with arrays at runtime", () => {
diff --git a/packages/react-sdk/src/collection-utils.ts b/packages/react-sdk/src/collection-utils.ts
index f853c170e0..75effb601d 100644
--- a/packages/react-sdk/src/collection-utils.ts
+++ b/packages/react-sdk/src/collection-utils.ts
@@ -11,17 +11,23 @@
/**
* Normalize collection data to entries format [key, value][].
* Returns empty array if data is not iterable.
+ * For arrays, keys are converted to numbers.
*/
export const getCollectionEntries = (
data: unknown
-): Array<[string, unknown]> => {
+): Array<[string | number, unknown]> => {
if (data === null || data === undefined) {
return [];
}
if (typeof data !== "object") {
return [];
}
- return Object.entries(data);
+ const entries = Object.entries(data);
+ // Convert string indices to numbers for arrays
+ if (Array.isArray(data)) {
+ return entries.map(([key, value]) => [Number(key), value]);
+ }
+ return entries;
};
/**
@@ -40,5 +46,7 @@ export const generateCollectionIterationCode = ({
return `Object.entries(
// @ts-ignore
${dataExpression} ?? {}
-).map(([${keyVariable}, ${itemVariable}]: any)`;
+).map(([_key, ${itemVariable}]: any) => {
+ const ${keyVariable} = Array.isArray(${dataExpression}) ? Number(_key) : _key;
+ return`;
};
diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsx
index 1443d1b9e6..268da7004a 100644
--- a/packages/react-sdk/src/component-generator.test.tsx
+++ b/packages/react-sdk/src/component-generator.test.tsx
@@ -465,13 +465,64 @@ test("generate collection component as map", () => {
{Object.entries(
// @ts-ignore
data ?? {}
- ).map(([index, element]: any) =>
+ ).map(([_key, element]: any) => {
+ const index = Array.isArray(data) ? Number(_key) : _key;
+ return (
<Fragment key={index}>
<Label />
<Button
aria-label={element} />
</Fragment>
- )}
+ )
+ })
+ }
+ `)
+ )
+ );
+});
+
+test("generate collection component with itemKey", () => {
+ const data = new Variable("data", { a: "apple", b: "orange" });
+ const element = new Parameter("element");
+ const key = new Parameter("key");
+ expect(
+ generateJsxChildren({
+ scope: createScope(),
+ metas: new Map(),
+ children: [{ type: "id", value: "list" }],
+ usedDataSources: new Map(),
+ indexesWithinAncestors: new Map(),
+ ...renderData(
+ <ws.collection
+ ws:id="list"
+ data={expression`${data}`}
+ item={element}
+ itemKey={key}
+ >
+ <$.Label>{expression`${key}`}</$.Label>
+ <$.Button aria-label={expression`${element}`}></$.Button>
+ </ws.collection>
+ ),
+ })
+ ).toEqual(
+ validateJSX(
+ clear(`
+ {Object.entries(
+ // @ts-ignore
+ data ?? {}
+ ).map(([_key, element]: any) => {
+ const key = Array.isArray(data) ? Number(_key) : _key;
+ return (
+ <Fragment key={key}>
+ <Label>
+ {key}
+ </Label>
+ <Button
+ aria-label={element} />
+ </Fragment>
+ )
+ })
+ }
`)
)
);
@@ -646,10 +697,14 @@ test("avoid generating collection parameter variable as state", () => {
{Object.entries(
// @ts-ignore
data ?? {}
- ).map(([index, element]: any) =>
+ ).map(([_key, element]: any) => {
+ const index = Array.isArray(data) ? Number(_key) : _key;
+ return (
<Fragment key={index}>
</Fragment>
- )}
+ )
+ })
+ }
</Body>
}
`)
@@ -853,10 +908,14 @@ test("generate conditional collection", () => {
{Object.entries(
// @ts-ignore
[] ?? {}
- ).map(([index, collectionItem]: any) =>
+ ).map(([_key, collectionItem]: any) => {
+ const index = Array.isArray([]) ? Number(_key) : _key;
+ return (
<Fragment key={index}>
</Fragment>
- )}
+ )
+ })
+ }
</>
}
</Body>
diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.ts
index d3bd9ad1bc..7bb30798b0 100644
--- a/packages/react-sdk/src/component-generator.ts
+++ b/packages/react-sdk/src/component-generator.ts
@@ -192,6 +192,7 @@ export const generateJsxElement = ({
let conditionValue: undefined | string;
let collectionDataValue: undefined | string;
let collectionItemValue: undefined | string;
+ let collectionItemKeyValue: undefined | string;
let classNameValue: undefined | string;
for (const prop of props.values()) {
@@ -237,6 +238,9 @@ export const generateJsxElement = ({
if (prop.name === "item") {
collectionItemValue = propValue;
}
+ if (prop.name === "itemKey") {
+ collectionItemKeyValue = propValue;
+ }
continue;
}
// We need to merge atomic classes with user-defined className prop.
@@ -277,18 +281,22 @@ export const generateJsxElement = ({
return "";
}
const indexVariable = scope.getName(`${instance.id}-index`, "index");
+ // use itemKey prop if provided, otherwise use generated index variable
+ const keyVariable = collectionItemKeyValue ?? indexVariable;
// collection can be nullable or invalid type
// fix implicitly on published sites
// support both arrays and objects with Object.entries
generatedElement += `{${generateCollectionIterationCode({
dataExpression: collectionDataValue,
- keyVariable: indexVariable,
+ keyVariable,
itemVariable: collectionItemValue,
- })} =>\n`;
- generatedElement += `<Fragment key={${indexVariable}}>\n`;
+ })} (\n`;
+ generatedElement += `<Fragment key={${keyVariable}}>\n`;
generatedElement += children;
generatedElement += `</Fragment>\n`;
- generatedElement += `)}\n`;
+ generatedElement += `)\n`;
+ generatedElement += `})\n`;
+ generatedElement += `}\n`;
} else if (instance.component === blockComponent) {
generatedElement += children;
} else {
diff --git a/packages/sdk/src/core-metas.ts b/packages/sdk/src/core-metas.ts
index 7b6cd7b430..a45d763172 100644
--- a/packages/sdk/src/core-metas.ts
+++ b/packages/sdk/src/core-metas.ts
@@ -57,6 +57,16 @@ const collectionMeta: WsComponentMeta = {
control: "json",
type: "json",
},
+ item: {
+ required: false,
+ control: "text",
+ type: "string",
+ },
+ itemKey: {
+ required: false,
+ control: "text",
+ type: "string",
+ },
},
};
diff --git a/packages/sdk/src/core-templates.tsx b/packages/sdk/src/core-templates.tsx
index a59f4ee747..0727bc632a 100644
--- a/packages/sdk/src/core-templates.tsx
+++ b/packages/sdk/src/core-templates.tsx
@@ -43,6 +43,7 @@ const linkMeta: TemplateMeta = {
};
const collectionItem = new Parameter("collectionItem");
+const collectionItemKey = new Parameter("collectionItemKey");
const collectionMeta: TemplateMeta = {
category: "data",
@@ -51,6 +52,7 @@ const collectionMeta: TemplateMeta = {
<ws.collection
data={["Collection Item 1", "Collection Item 2", "Collection Item 3"]}
item={collectionItem}
+ itemKey={collectionItemKey}
>
<ws.element ws:tag="div">
<ws.element ws:tag="div">{expression`${collectionItem}`}</ws.element>