From 7a386dbb49ade788daa320feed058aa57b9abe2c Mon Sep 17 00:00:00 2001 From: Aaron Pettengill Date: Mon, 16 Sep 2024 16:24:20 -0400 Subject: [PATCH] fix: handle prefixing paths that start with numbers --- packages/core/src/form.test.ts | 46 ++++++++++++++++++++++++++++++++++ packages/core/src/form.ts | 7 +++++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/core/src/form.test.ts b/packages/core/src/form.test.ts index a09e1c71..5ac54c43 100644 --- a/packages/core/src/form.test.ts +++ b/packages/core/src/form.test.ts @@ -38,3 +38,49 @@ it("should be able to nest scopes arbitrarily deep", () => { const baz = bar.scope("baz"); expect(baz.__field_prefix__).toBe("foo.bar.baz"); }); + +it("should be able to nest scopes with arrays", () => { + const form = createFormScope({ + defaultValues: { + foo: { + bar: [ + { + baz: "baz", + }, + ], + }, + }, + serverValidationErrors: {}, + validator: createValidator({ + validate: (data) => Promise.resolve({ data, error: undefined }), + }), + submitSource: "state", + onSubmit: vi.fn(), + onSubmitSuccess: vi.fn(), + onSubmitFailure: vi.fn(), + onBeforeSubmit: vi.fn(), + onInvalidSubmit: vi.fn(), + flags: { + disableFocusOnError: false, + reloadDocument: false, + }, + formProps: { id: "test-form" }, + }); + + expect(form.__field_prefix__).toBe(""); + + const foo = form.scope("foo"); + expect(foo.__field_prefix__).toBe("foo"); + + const bar = foo.scope("bar"); + expect(bar.__field_prefix__).toBe("foo.bar"); + + const item = bar.scope("0"); + expect(item.__field_prefix__).toBe("foo.bar[0]"); + + const baz = item.scope("baz"); + expect(baz.__field_prefix__).toBe("foo.bar[0].baz"); + + const itemBaz = bar.scope("0.baz"); + expect(itemBaz.__field_prefix__).toBe("foo.bar[0].baz"); +}); diff --git a/packages/core/src/form.ts b/packages/core/src/form.ts index d060f5e5..ae1ff247 100644 --- a/packages/core/src/form.ts +++ b/packages/core/src/form.ts @@ -25,6 +25,7 @@ import { ValidStringPaths, ValueAtPath, pathArrayToString, + stringToPathArray, } from "@rvf/set-get"; type SubmitTypes = @@ -143,7 +144,11 @@ const instantiateFormScope = ( __field_prefix__: prefix, __store__: store, scope(field) { - const newPrefix = pathArrayToString([prefix, field].filter(Boolean)); + const newPrefix = pathArrayToString( + [...stringToPathArray(prefix), ...stringToPathArray(field)].filter( + (segment) => segment !== "", + ), + ); if (store.subformCache.has(newPrefix)) return store.subformCache.get(newPrefix);