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

Add Arktype Validator #912

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
11 changes: 11 additions & 0 deletions examples/react/arktype/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// @ts-check

/** @type {import('eslint').Linter.Config} */
const config = {
extends: ['plugin:react/recommended', 'plugin:react-hooks/recommended'],
rules: {
'react/no-children-prop': 'off',
},
}

module.exports = config
27 changes: 27 additions & 0 deletions examples/react/arktype/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

pnpm-lock.yaml
yarn.lock
package-lock.json

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
6 changes: 6 additions & 0 deletions examples/react/arktype/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Example

To run this example:

- `npm install`
- `npm run dev`
16 changes: 16 additions & 0 deletions examples/react/arktype/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/emblem-light.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />

<title>TanStack Form React Valibot Example App</title>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<title>TanStack Form React Valibot Example App</title>
<title>TanStack Form React Arktype Example App</title>

</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
37 changes: 37 additions & 0 deletions examples/react/arktype/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@tanstack/form-example-react-arktype",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port=3001",
"build": "vite build",
"preview": "vite preview",
"test:types": "tsc"
},
"dependencies": {
"@tanstack/arktype-form-adapter": "^0.28.0",
"@tanstack/react-form": "^0.29.1",
"arktype": "2.0.0-beta.5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"valibot": "^0.37.0"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "valibot" dependency should not be needed here

},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"vite": "^5.4.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
13 changes: 13 additions & 0 deletions examples/react/arktype/public/emblem-light.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
104 changes: 104 additions & 0 deletions examples/react/arktype/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import * as React from 'react'
import { createRoot } from 'react-dom/client'
import { useForm } from '@tanstack/react-form'
import { arktype, arktypeValidator } from '@tanstack/arktype-form-adapter'
import type { FieldApi } from '@tanstack/react-form'

function FieldInfo({ field }: { field: FieldApi<any, any, any, any> }) {
return (
<>
{field.state.meta.isTouched && field.state.meta.errors.length ? (
<em>{field.state.meta.errors.join(',')}</em>
) : null}
{field.state.meta.isValidating ? 'Validating...' : null}
</>
)
}

export default function App() {
const form = useForm({
defaultValues: {
firstName: '',
lastName: '',
},
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
// Add a validator to support Arktype usage in Form and Field
validatorAdapter: arktypeValidator(),
})

return (
<div>
<h1>Valibot Form Example</h1>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<h1>Valibot Form Example</h1>
<h1>Arktype Form Example</h1>

<form
onSubmit={(e) => {
e.preventDefault()
e.stopPropagation()
form.handleSubmit()
}}
>
<div>
{/* A type-safe field component*/}
<form.Field
name="firstName"
validators={{
onChange: arktype('string > 2'),
}}
children={(field) => {
// Avoid hasty abstractions. Render props are great!
return (
<>
<label htmlFor={field.name}>First Name:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
<FieldInfo field={field} />
</>
)
}}
/>
</div>
<div>
<form.Field
name="lastName"
children={(field) => (
<>
<label htmlFor={field.name}>Last Name:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
<FieldInfo field={field} />
</>
)}
/>
</div>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
children={([canSubmit, isSubmitting]) => (
<button type="submit" disabled={!canSubmit}>
{isSubmitting ? '...' : 'Submit'}
</button>
)}
/>
</form>
</div>
)
}

const rootElement = document.getElementById('root')!

createRoot(rootElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
23 changes: 23 additions & 0 deletions examples/react/arktype/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"module": "ESNext",
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
5 changes: 5 additions & 0 deletions packages/arktype-form-adapter/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// @ts-check

import rootConfig from '../../eslint.config.js'

export default [...rootConfig]
63 changes: 63 additions & 0 deletions packages/arktype-form-adapter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"name": "@tanstack/arktype-form-adapter",
"version": "0.28.0",
"description": "The Arktype adapter for TanStack Form.",
"author": "tannerlinsley",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/TanStack/form.git",
"directory": "packages/zod-form-adapter"
},
"homepage": "https://tanstack.com/form",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"scripts": {
"clean": "rimraf ./dist && rimraf ./coverage",
"test:eslint": "eslint ./src ./tests",
"test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"",
"test:types:ts49": "node ../../node_modules/typescript49/lib/tsc.js -p tsconfig.legacy.json",
"test:types:ts50": "node ../../node_modules/typescript50/lib/tsc.js",
"test:types:ts51": "node ../../node_modules/typescript51/lib/tsc.js",
"test:types:ts52": "node ../../node_modules/typescript52/lib/tsc.js",
"test:types:ts53": "node ../../node_modules/typescript53/lib/tsc.js",
"test:types:ts54": "tsc",
"test:lib": "vitest",
"test:lib:dev": "pnpm run test:lib --watch",
"test:build": "publint --strict",
"build": "vite build"
},
"type": "module",
"types": "dist/esm/index.d.ts",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.js",
"exports": {
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
}
},
"./package.json": "./package.json"
},
"sideEffects": false,
"files": [
"dist",
"src"
],
"dependencies": {
"@tanstack/form-core": "workspace:*"
},
"devDependencies": {
"arktype": "2.0.0-beta.5"
},
"peerDependencies": {
"arktype": "^2.x"
}
}
1 change: 1 addition & 0 deletions packages/arktype-form-adapter/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './validator'
59 changes: 59 additions & 0 deletions packages/arktype-form-adapter/src/validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { type } from 'arktype'
import type { TypeParser } from 'arktype/internal/type.js'
import type { ValidationError, Validator } from '@tanstack/form-core'
import type { ArkErrors, Type, inferAmbient, validateAmbient } from 'arktype'
import type { inferred } from 'arktype/internal/ast.js'

type Params = {
transformErrors?: (errors: ArkErrors) => ValidationError
}

export const arktypeValidator = (params: Params = {}) =>
(() => {
return {
validate({ value }, fn) {
console.log(fn, 'XD')
// Call Arktype on the value here and return the error message
const result = fn.type(value)

console.log(result)

if (result instanceof type.errors) {
if (params.transformErrors) {
return params.transformErrors(result)
}

return result.summary
}

return
},
async validateAsync({ value }, fn): Promise<ValidationError> {
console.log(fn, 'XD')

// Call Arktype on the value here and return the error message
const result = fn.type(value)

if (result instanceof type.errors) {
if (params.transformErrors) {
return params.transformErrors(result)
}

return result.summary
}

return
},
}
}) as Validator<unknown, { type: Type }>

export type cast<t> = {
[inferred]?: t
wow: TypeParser<{}>
}

export type ParseType = <const def>(def: validateAmbient<def>) => {
type: Type<inferAmbient<def>>
}

export const arktype: ParseType = (v) => ({ type: type(v) })
Loading
Loading