Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add helper of getValibotConstraint #16

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ $ npm install @conform-to/react valibot conform-to-valibot
## API Reference

- [parseWithValibot](#parseWithValibot)
- [getValibotConstraint](#getValibotConstraint)

<!-- /aside -->

Expand Down Expand Up @@ -73,3 +74,26 @@ export async function action({ request }) {
// ...
}
```

### getValibotConstraint

A helper that returns an object containing the validation attributes for each field by introspecting the valibot schema.

```tsx
import { getValibotConstraint } from "conform-to-valibot";
import { useForm } from "@conform-to/react";
import { object, string, minLength, maxLength, optional } from "valibot";

const schema = object({
title: string([minLength(10), maxLength(100)]),
description: optional(string([minLength(100), maxLength(1000)])),
});

function Example() {
const [form, fields] = useForm({
constraint: getValibotConstraint(schema),
});

// ...
}
```
62 changes: 3 additions & 59 deletions coercion.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,5 @@
import type {
NullSchema,
NullableSchema,
OptionalSchema,
NullishSchema,
NonNullableSchema,
NonOptionalSchema,
NonNullishSchema,
ObjectSchema,
ObjectEntries,
UnionSchema,
UnionOptions,
BaseSchema,
ArraySchema,
BigintSchema,
BooleanSchema,
DateSchema,
EnumSchema,
Enum,
LiteralSchema,
Literal,
NumberSchema,
PicklistSchema,
PicklistOptions,
StringSchema,
UndefinedSchema,
} from "valibot";
import type { WrapSchema, AllSchema, ObjectSchema } from "./types/schema";

import { coerce } from "valibot";

/**
Expand Down Expand Up @@ -67,37 +42,6 @@ export function coerceFile(file: unknown) {
return file;
}

type WrapWithDefaultSchema =
| NullSchema<BaseSchema>
| OptionalSchema<BaseSchema>
| NullableSchema<BaseSchema>
| NullishSchema<BaseSchema>;
type WrapWithoutDefaultSchema =
| NonNullableSchema<BaseSchema>
| NonOptionalSchema<BaseSchema>
| NonNullableSchema<BaseSchema>
| NonNullishSchema<BaseSchema>;
type WrapSchema = WrapWithDefaultSchema | WrapWithoutDefaultSchema;

type ValibotSchema =
| ObjectSchema<ObjectEntries>
| StringSchema
| ArraySchema<BaseSchema>
| BigintSchema
| BooleanSchema
| DateSchema
| EnumSchema<Enum>
| LiteralSchema<Literal>
| NumberSchema
| PicklistSchema<PicklistOptions>
| UndefinedSchema;

type AllSchema =
| ValibotSchema
| WrapSchema
| UnionSchema<UnionOptions>
| BaseSchema;

type WrapOption = {
wrap?: WrapSchema;
cache?: Map<AllSchema, AllSchema>;
Expand Down Expand Up @@ -316,7 +260,7 @@ export function enableTypeCoercion<Type extends AllSchema,>(
enableTypeCoercion(def, { cache }),
]),
),
} as ObjectSchema<ObjectEntries>;
} as ObjectSchema;
schema = options?.wrap
? {
...options.wrap,
Expand Down
153 changes: 153 additions & 0 deletions constraint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import type { Constraint } from "@conform-to/dom";
import type { WrapSchema, AllSchema, ObjectSchema } from "./types/schema";

const keys: Array<keyof Constraint> = [
"required",
"minLength",
"maxLength",
"min",
"max",
"step",
"multiple",
"pattern",
];

export function getValibotConstraint(
schema: AllSchema,
): Record<string, Constraint> {
function updateConstraint(
schema: AllSchema,
data: Record<string, Constraint>,
name = "",
): void {
if (name !== "" && !data[name]) {
data[name] = { required: true };
}
const constraint = name !== "" ? data[name] : {};

if (!("type" in schema)) {
return;
}

if (schema.type === "object") {
for (const key in schema.entries) {
updateConstraint(
schema.entries[key],
data,
name ? `${name}.${key}` : key,
);
}
} else if (schema.type === "intersect") {
for (const option of schema.options) {
const result: Record<string, Constraint> = {};
updateConstraint(option, result, name);

Object.assign(data, result);
}
} else if (schema.type === "union" || schema.type === "variant") {
Object.assign(
data,
schema.options
.map((option) => {
const result: Record<string, Constraint> = {};

updateConstraint(option, result, name);

return result;
})
.reduce((prev, next) => {
const list = new Set([...Object.keys(prev), ...Object.keys(next)]);
const result: Record<string, Constraint> = {};

for (const name of list) {
const prevConstraint = prev[name];
const nextConstraint = next[name];

if (prevConstraint && nextConstraint) {
const constraint: Constraint = {};

result[name] = constraint;

for (const key of keys) {
if (
typeof prevConstraint[key] !== "undefined" &&
typeof nextConstraint[key] !== "undefined" &&
prevConstraint[key] === nextConstraint[key]
) {
// @ts-expect-error Both are on the same type
constraint[key] = prevConstraint[key];
}
}
} else {
result[name] = {
...prevConstraint,
...nextConstraint,
required: false,
};
}
}

return result;
}),
);
} else if (name === "") {
// All the cases below are not allowed on root
throw new Error("Unsupported schema");
} else if (schema.type === "array") {
constraint.multiple = true;
updateConstraint(schema.item, data, `${name}[]`);
} else if (schema.type === "string") {
const minLength = schema.pipe?.find(
(v) => "type" in v && v.type === "min_length",
);
if (minLength && "requirement" in minLength) {
constraint.minLength = minLength.requirement as number;
}
const maxLength = schema.pipe?.find(
(v) => "type" in v && v.type === "max_length",
);
if (maxLength && "requirement" in maxLength) {
constraint.maxLength = maxLength.requirement as number;
}
} else if (schema.type === "optional") {
constraint.required = false;
updateConstraint(schema.wrapped, data, name);
} else if (schema.type === "number") {
const minValue = schema.pipe?.find(
(v) => "type" in v && v.type === "min_value",
);
if (minValue && "requirement" in minValue) {
constraint.min = minValue.requirement as number;
}
const maxValue = schema.pipe?.find(
(v) => "type" in v && v.type === "max_value",
);
if (maxValue && "requirement" in maxValue) {
constraint.max = maxValue.requirement as number;
}
} else if (schema.type === "enum") {
constraint.pattern = Object.entries(schema.enum)
.map(([_, option]) =>
// To escape unsafe characters on regex
typeof option === "string"
? option
.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&")
.replace(/-/g, "\\x2d")
: option,
)
.join("|");
} else if (schema.type === "tuple") {
for (let i = 0; i < schema.items.length; i++) {
updateConstraint(schema.items[i], data, `${name}[${i}]`);
}
} else {
// FIXME: If you are interested in this, feel free to create a PR
}
}

const result: Record<string, Constraint> = {};

updateConstraint(schema, result);

return result;
}
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { getValibotConstraint } from "./constraint";
export { parseWithValibot } from "./parse";
Loading
Loading