Skip to content

Commit

Permalink
fix: handle prefixing paths that start with numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
airjp73 committed Sep 16, 2024
1 parent b4f26f5 commit 7a386db
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
46 changes: 46 additions & 0 deletions packages/core/src/form.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
7 changes: 6 additions & 1 deletion packages/core/src/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
ValidStringPaths,
ValueAtPath,
pathArrayToString,
stringToPathArray,
} from "@rvf/set-get";

type SubmitTypes<FormOutputData> =
Expand Down Expand Up @@ -143,7 +144,11 @@ const instantiateFormScope = <FormInputData extends FieldValues>(
__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);

Expand Down

0 comments on commit 7a386db

Please sign in to comment.