Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Refactor forms with tanstack-form (#276)

Hakan Shehu6a89303e7eb3
diff --git a/package-lock.json b/package-lock.json
index edaf95b5..dab10bdf 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12334,6 +12334,44 @@
"typescript": ">=4.7"
}
},
+ "node_modules/@tanstack/devtools-event-client": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/@tanstack/devtools-event-client/-/devtools-event-client-0.4.0.tgz",
+ "integrity": "sha512-RPfGuk2bDZgcu9bAJodvO2lnZeHuz4/71HjZ0bGb/SPg8+lyTA+RLSKQvo7fSmPSi8/vcH3aKQ8EM9ywf1olaw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
+ "node_modules/@tanstack/form-core": {
+ "version": "1.27.7",
+ "resolved": "https://registry.npmjs.org/@tanstack/form-core/-/form-core-1.27.7.tgz",
+ "integrity": "sha512-nvogpyE98fhb0NDw1Bf2YaCH+L7ZIUgEpqO9TkHucDn6zg3ni521boUpv0i8HKIrmmFwDYjWZoCnrgY4HYWTkw==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/devtools-event-client": "^0.4.0",
+ "@tanstack/pacer-lite": "^0.1.1",
+ "@tanstack/store": "^0.7.7"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
+ "node_modules/@tanstack/form-core/node_modules/@tanstack/store": {
+ "version": "0.7.7",
+ "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.7.7.tgz",
+ "integrity": "sha512-xa6pTan1bcaqYDS9BDpSiS63qa6EoDkPN9RsRaxHuDdVDNntzq3xNwR5YKTU/V3SkSyC9T4YVOPh2zRQN0nhIQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
"node_modules/@tanstack/history": {
"version": "1.139.0",
"resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.139.0.tgz",
@@ -12383,6 +12421,28 @@
"react": ">=16.8.0"
}
},
+ "node_modules/@tanstack/react-form": {
+ "version": "1.27.7",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-form/-/react-form-1.27.7.tgz",
+ "integrity": "sha512-xTg4qrUY0fuLaSnkATLZcK3BWlnwLp7IuAb6UTbZKngiDEvvDCNTvVvHgPlgef1O2qN4klZxInRyRY6oEkXZ2A==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/form-core": "1.27.7",
+ "@tanstack/react-store": "^0.8.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "peerDependencies": {
+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@tanstack/react-start": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@tanstack/react-query": {
"version": "5.90.11",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.11.tgz",
@@ -32365,6 +32425,7 @@
"@radix-ui/react-tooltip": "^1.2.8",
"@react-oauth/google": "^0.12.2",
"@tanstack/react-db": "^0.1.60",
+ "@tanstack/react-form": "^1.27.7",
"@tanstack/react-query": "^5.90.11",
"@tanstack/react-router": "^1.139.14",
"@tanstack/react-virtual": "^3.13.12",
@@ -32401,7 +32462,6 @@
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^19.2.0",
- "react-hook-form": "^7.66.1",
"react-intersection-observer": "^10.0.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 418496f6..2c6cd0e4 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -45,6 +45,7 @@
"@radix-ui/react-tooltip": "^1.2.8",
"@react-oauth/google": "^0.12.2",
"@tanstack/react-db": "^0.1.60",
+ "@tanstack/react-form": "^1.27.7",
"@tanstack/react-query": "^5.90.11",
"@tanstack/react-router": "^1.139.14",
"@tanstack/react-virtual": "^3.13.12",
@@ -81,7 +82,6 @@
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^19.2.0",
- "react-hook-form": "^7.66.1",
"react-intersection-observer": "^10.0.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
diff --git a/packages/ui/src/components/accounts/account-update.tsx b/packages/ui/src/components/accounts/account-update.tsx
index d8fbab42..6cfb1436 100644
--- a/packages/ui/src/components/accounts/account-update.tsx
+++ b/packages/ui/src/components/accounts/account-update.tsx
@@ -1,7 +1,6 @@
-import { zodResolver } from '@hookform/resolvers/zod';
import { eq, useLiveQuery } from '@tanstack/react-db';
+import { useForm } from '@tanstack/react-form';
import { Upload } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod/v4';
@@ -9,13 +8,11 @@ import { collections } from '@colanode/ui/collections';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { useWorkspace } from '@colanode/ui/contexts/workspace';
@@ -26,7 +23,7 @@ import { cn } from '@colanode/ui/lib/utils';
const formSchema = z.object({
name: z.string().min(3, 'Name must be at least 3 characters long.'),
- avatar: z.string().optional().nullable(),
+ avatar: z.string().nullable(),
email: z.email('Invalid email address'),
});
@@ -51,36 +48,69 @@ export const AccountUpdate = () => {
const accountData = accountQuery.data?.[0];
const form = useForm({
- resolver: zodResolver(formSchema),
defaultValues: {
- name: accountData?.name,
- avatar: accountData?.avatar,
- email: accountData?.email,
+ name: accountData?.name ?? '',
+ email: accountData?.email ?? '',
+ avatar: accountData?.avatar ?? null,
},
- });
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ if (isUpdatingAccount) {
+ return;
+ }
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ updateAccount({
+ input: {
+ type: 'account.update',
+ id: workspace.accountId,
+ name: value.name,
+ avatar: value.avatar,
+ },
+ onSuccess() {
+ toast.success('Account updated');
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
+ },
+ });
- const onSubmit = (values: z.output<typeof formSchema>) => {
- if (isUpdatingAccount) {
+ const handleAvatarClick = async () => {
+ if (isUpdatingAccount || isUploadingAvatar) {
return;
}
- updateAccount({
- input: {
- type: 'account.update',
- id: workspace.accountId,
- name: values.name,
- avatar: values.avatar,
- },
- onSuccess() {
- toast.success('Account updated');
- },
- onError(error) {
- toast.error(error.message);
- },
+ const result = await openFileDialog({
+ accept: 'image/jpeg, image/jpg, image/png, image/webp',
});
+
+ if (result.type === 'success') {
+ const file = result.files[0];
+ if (!file) {
+ return;
+ }
+
+ uploadAvatar({
+ input: {
+ type: 'avatar.upload',
+ accountId: workspace.accountId,
+ file,
+ },
+ onSuccess(output) {
+ if (output.id) {
+ form.setFieldValue('avatar', output.id);
+ }
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
+ } else if (result.type === 'error') {
+ toast.error(result.error);
+ }
};
if (!accountData) {
@@ -88,116 +118,121 @@ export const AccountUpdate = () => {
}
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
+ <div
+ className={cn(
+ 'pt-3',
+ isMobile ? 'flex justify-center pb-4' : 'size-40'
+ )}
+ >
<div
- className={cn(
- 'pt-3',
- isMobile ? 'flex justify-center pb-4' : 'size-40'
- )}
+ className="group relative cursor-pointer"
+ onClick={handleAvatarClick}
>
+ <form.Subscribe
+ selector={(state) => ({
+ avatar: state.values.avatar,
+ name: state.values.name,
+ })}
+ children={({ avatar, name }) => (
+ <Avatar
+ id={workspace.accountId}
+ name={name}
+ avatar={avatar}
+ className={isMobile ? 'size-24' : 'size-32'}
+ />
+ )}
+ />
<div
- className="group relative cursor-pointer"
- onClick={async () => {
- if (isUpdatingAccount || isUploadingAvatar) {
- return;
- }
-
- const result = await openFileDialog({
- accept: 'image/jpeg, image/jpg, image/png, image/webp',
- });
-
- if (result.type === 'success') {
- const file = result.files[0];
- if (!file) {
- return;
- }
-
- uploadAvatar({
- input: {
- type: 'avatar.upload',
- accountId: workspace.accountId,
- file,
- },
- onSuccess(output) {
- if (output.id) {
- form.setValue('avatar', output.id);
- }
- },
- onError(error) {
- toast.error(error.message);
- },
- });
- } else if (result.type === 'error') {
- toast.error(result.error);
- }
- }}
+ className={cn(
+ `absolute left-0 top-0 hidden items-center justify-center overflow-hidden bg-accent/50 group-hover:inline-flex`,
+ isMobile ? 'size-24' : 'size-32',
+ isUploadingAvatar ? 'inline-flex' : 'hidden'
+ )}
>
- <Avatar
- id={workspace.accountId}
- name={name}
- avatar={avatar}
- className={isMobile ? 'size-24' : 'size-32'}
- />
- <div
- className={cn(
- `absolute left-0 top-0 hidden items-center justify-center overflow-hidden bg-accent/50 group-hover:inline-flex`,
- isMobile ? 'size-24' : 'size-32',
- isUploadingAvatar ? 'inline-flex' : 'hidden'
- )}
- >
- {isUploadingAvatar ? (
- <Spinner className="size-5" />
- ) : (
- <Upload className="size-5 text-foreground" />
- )}
- </div>
+ {isUploadingAvatar ? (
+ <Spinner className="size-5" />
+ ) : (
+ <Upload className="size-5 text-foreground" />
+ )}
</div>
</div>
- <div
- className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
- >
- <FormField
- control={form.control}
+ </div>
+ <div
+ className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
+ >
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Name *</FormLabel>
- <FormControl>
- <Input placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <FieldLabel htmlFor={field.name}>Name *</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="Name"
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="email"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Email</FormLabel>
- <FormControl>
- <Input readOnly placeholder="Email" {...field} disabled />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <FieldLabel htmlFor={field.name}>Email</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly
+ placeholder="Email"
+ disabled
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- </div>
+ </FieldGroup>
</div>
+ </div>
- <div className="flex flex-row justify-end gap-2">
- <Button
- type="submit"
- disabled={isUpdatingAccount || isUploadingAvatar}
- className="w-20"
- >
- {isUpdatingAccount && <Spinner className="mr-1" />}
- Save
- </Button>
- </div>
- </form>
- </Form>
+ <div className="flex flex-row justify-end gap-2">
+ <Button
+ type="submit"
+ disabled={isUpdatingAccount || isUploadingAvatar}
+ className="w-20"
+ >
+ {isUpdatingAccount && <Spinner className="mr-1" />}
+ Save
+ </Button>
+ </div>
+ </form>
);
};
diff --git a/packages/ui/src/components/auth/email-login-form.tsx b/packages/ui/src/components/auth/email-login-form.tsx
index 349961c6..d377cfdc 100644
--- a/packages/ui/src/components/auth/email-login-form.tsx
+++ b/packages/ui/src/components/auth/email-login-form.tsx
@@ -1,19 +1,16 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { useNavigate } from '@tanstack/react-router';
import { Mail } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
-import { Label } from '@colanode/ui/components/ui/label';
import { Spinner } from '@colanode/ui/components/ui/spinner';
const formSchema = z.object({
@@ -28,76 +25,99 @@ interface LoginFormProps {
export const LoginForm = ({ isPending, onSubmit }: LoginFormProps) => {
const navigate = useNavigate();
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
email: '',
password: '',
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
- <FormField
- control={form.control}
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ className="space-y-4"
+ >
+ <FieldGroup>
+ <form.Field
name="email"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="email">Email</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
placeholder="[email protected]"
- {...field}
autoComplete="email"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="password"
- render={({ field }) => (
- <FormItem>
- <div className="flex flex-row gap-2 items-center">
- <Label htmlFor="password">Password</Label>
- <p
- className="text-xs text-muted-foreground cursor-pointer hover:underline w-full text-right"
- onClick={() => {
- navigate({ to: '/auth/reset' });
- }}
- >
- Forgot password?
- </p>
- </div>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <div className="flex flex-row gap-2 items-center">
+ <FieldLabel htmlFor={field.name}>Password</FieldLabel>
+ <p
+ className="text-xs text-muted-foreground cursor-pointer hover:underline w-full text-right"
+ onClick={() => {
+ navigate({ to: '/auth/reset' });
+ }}
+ >
+ Forgot password?
+ </p>
+ </div>
<Input
+ id={field.name}
+ name={field.name}
type="password"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
autoComplete="current-password"
placeholder="********"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <Button
- type="submit"
- variant="outline"
- className="w-full"
- disabled={isPending}
- >
- {isPending ? (
- <Spinner className="mr-1 size-4" />
- ) : (
- <Mail className="mr-1 size-4" />
- )}
- Login
- </Button>
- </form>
- </Form>
+ </FieldGroup>
+ <Button
+ type="submit"
+ variant="outline"
+ className="w-full"
+ disabled={isPending}
+ >
+ {isPending ? (
+ <Spinner className="mr-1 size-4" />
+ ) : (
+ <Mail className="mr-1 size-4" />
+ )}
+ Login
+ </Button>
+ </form>
);
};
diff --git a/packages/ui/src/components/auth/email-password-reset-complete-form.tsx b/packages/ui/src/components/auth/email-password-reset-complete-form.tsx
index 13c0856c..af97e37e 100644
--- a/packages/ui/src/components/auth/email-password-reset-complete-form.tsx
+++ b/packages/ui/src/components/auth/email-password-reset-complete-form.tsx
@@ -1,18 +1,15 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { Lock } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
-import { Label } from '@colanode/ui/components/ui/label';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { useCountdown } from '@colanode/ui/hooks/use-countdown';
@@ -46,86 +43,120 @@ export const PasswordResetCompleteForm = ({
isPending,
onSubmit,
}: PasswordResetCompleteFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
otp: '',
password: '',
confirmPassword: '',
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
const [remainingSeconds, formattedTime] = useCountdown(expiresAt);
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
- <FormField
- control={form.control}
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ className="space-y-3"
+ >
+ <FieldGroup>
+ <form.Field
name="password"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="password">New Password</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>New Password</FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
type="password"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
autoComplete="new-password"
placeholder="********"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="confirmPassword"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="confirmPassword">Confirm New Password</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>
+ Confirm New Password
+ </FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
type="password"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
autoComplete="new-password"
placeholder="********"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="otp"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="otp">Code</Label>
- <FormControl>
- <Input placeholder="123456" {...field} />
- </FormControl>
- <FormMessage />
- <p className="text-xs text-muted-foreground w-full text-center">
- {formattedTime}
- </p>
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Code</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="123456"
+ />
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ <p className="text-xs text-muted-foreground w-full text-center">
+ {formattedTime}
+ </p>
+ </Field>
+ );
+ }}
/>
- <Button
- type="submit"
- variant="outline"
- className="w-full"
- disabled={isPending || remainingSeconds <= 0}
- >
- {isPending ? (
- <Spinner className="mr-1 size-4" />
- ) : (
- <Lock className="mr-1 size-4" />
- )}
- Reset password
- </Button>
- </form>
- </Form>
+ </FieldGroup>
+ <Button
+ type="submit"
+ variant="outline"
+ className="w-full"
+ disabled={isPending || remainingSeconds <= 0}
+ >
+ {isPending ? (
+ <Spinner className="mr-1 size-4" />
+ ) : (
+ <Lock className="mr-1 size-4" />
+ )}
+ Reset password
+ </Button>
+ </form>
);
};
diff --git a/packages/ui/src/components/auth/email-password-reset-init-form.tsx b/packages/ui/src/components/auth/email-password-reset-init-form.tsx
index 25c4b06e..4bc46121 100644
--- a/packages/ui/src/components/auth/email-password-reset-init-form.tsx
+++ b/packages/ui/src/components/auth/email-password-reset-init-form.tsx
@@ -1,18 +1,15 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { Mail } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
-import { Label } from '@colanode/ui/components/ui/label';
import { Spinner } from '@colanode/ui/components/ui/spinner';
const formSchema = z.object({
@@ -28,43 +25,63 @@ export const PasswordResetInitForm = ({
isPending,
onSubmit,
}: PasswordResetInitFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
email: '',
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
- <FormField
- control={form.control}
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ className="space-y-3"
+ >
+ <FieldGroup>
+ <form.Field
name="email"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="email">Email</Label>
- <FormControl>
- <Input placeholder="[email protected]" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Email</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="[email protected]"
+ />
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <Button
- type="submit"
- variant="outline"
- className="w-full"
- disabled={isPending}
- >
- {isPending ? (
- <Spinner className="mr-1 size-4" />
- ) : (
- <Mail className="mr-1 size-4" />
- )}
- Reset password
- </Button>
- </form>
- </Form>
+ </FieldGroup>
+ <Button
+ type="submit"
+ variant="outline"
+ className="w-full"
+ disabled={isPending}
+ >
+ {isPending ? (
+ <Spinner className="mr-1 size-4" />
+ ) : (
+ <Mail className="mr-1 size-4" />
+ )}
+ Reset password
+ </Button>
+ </form>
);
};
diff --git a/packages/ui/src/components/auth/email-register-form.tsx b/packages/ui/src/components/auth/email-register-form.tsx
index 8a573f08..f1cc012e 100644
--- a/packages/ui/src/components/auth/email-register-form.tsx
+++ b/packages/ui/src/components/auth/email-register-form.tsx
@@ -1,18 +1,15 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { Mail } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
-import { Label } from '@colanode/ui/components/ui/label';
import { Spinner } from '@colanode/ui/components/ui/spinner';
const formSchema = z
@@ -41,99 +38,138 @@ interface RegisterFormProps {
}
export const RegisterForm = ({ isPending, onSubmit }: RegisterFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
name: '',
email: '',
password: '',
confirmPassword: '',
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
- <FormField
- control={form.control}
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ className="space-y-4"
+ >
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="name">Name</Label>
- <FormControl>
- <Input placeholder="John Doe" {...field} autoComplete="name" />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Name</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="John Doe"
+ autoComplete="name"
+ />
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="email"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="email">Email</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
placeholder="[email protected]"
- {...field}
autoComplete="email"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="password"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="password">Password</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Password</FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
type="password"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
autoComplete="new-password"
placeholder="********"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="confirmPassword"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="confirmPassword">Confirm Password</Label>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Confirm Password</FieldLabel>
<Input
+ id={field.name}
+ name={field.name}
type="password"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
autoComplete="new-password"
placeholder="********"
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
/>
- <Button
- type="submit"
- variant="outline"
- className="w-full"
- disabled={isPending}
- >
- {isPending ? (
- <Spinner className="mr-1 size-4" />
- ) : (
- <Mail className="mr-1 size-4" />
- )}
- Register
- </Button>
- </form>
- </Form>
+ </FieldGroup>
+ <Button
+ type="submit"
+ variant="outline"
+ className="w-full"
+ disabled={isPending}
+ >
+ {isPending ? (
+ <Spinner className="mr-1 size-4" />
+ ) : (
+ <Mail className="mr-1 size-4" />
+ )}
+ Register
+ </Button>
+ </form>
);
};
diff --git a/packages/ui/src/components/auth/email-verify-form.tsx b/packages/ui/src/components/auth/email-verify-form.tsx
index 4be5b855..b8ba3929 100644
--- a/packages/ui/src/components/auth/email-verify-form.tsx
+++ b/packages/ui/src/components/auth/email-verify-form.tsx
@@ -1,18 +1,15 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { Mail } from 'lucide-react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
-import { Label } from '@colanode/ui/components/ui/label';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { useCountdown } from '@colanode/ui/hooks/use-countdown';
@@ -31,53 +28,73 @@ export const EmailVerifyForm = ({
isPending,
onSubmit,
}: EmailVerifyFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
otp: '',
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
const [remainingSeconds, formattedTime] = useCountdown(expiresAt);
return (
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
- <FormField
- control={form.control}
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ className="space-y-4"
+ >
+ <FieldGroup>
+ <form.Field
name="otp"
- render={({ field }) => (
- <FormItem>
- <Label htmlFor="otp">Code</Label>
- <FormControl>
- <Input placeholder="123456" {...field} />
- </FormControl>
- <FormMessage />
- <div className="flex flex-col items-center gap-1">
- <p className="text-sm text-muted-foreground w-full text-center">
- We sent a verification code to your email.
- </p>
- <p className="text-xs text-muted-foreground w-full text-center">
- {formattedTime}
- </p>
- </div>
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Code</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="123456"
+ />
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ <div className="flex flex-col items-center gap-1">
+ <p className="text-sm text-muted-foreground w-full text-center">
+ We sent a verification code to your email.
+ </p>
+ <p className="text-xs text-muted-foreground w-full text-center">
+ {formattedTime}
+ </p>
+ </div>
+ </Field>
+ );
+ }}
/>
- <Button
- type="submit"
- variant="outline"
- className="w-full"
- disabled={isPending || remainingSeconds <= 0}
- >
- {isPending ? (
- <Spinner className="mr-1 size-4" />
- ) : (
- <Mail className="mr-1 size-4" />
- )}
- Confirm
- </Button>
- </form>
- </Form>
+ </FieldGroup>
+ <Button
+ type="submit"
+ variant="outline"
+ className="w-full"
+ disabled={isPending || remainingSeconds <= 0}
+ >
+ {isPending ? (
+ <Spinner className="mr-1 size-4" />
+ ) : (
+ <Mail className="mr-1 size-4" />
+ )}
+ Confirm
+ </Button>
+ </form>
);
};
diff --git a/packages/ui/src/components/channels/channel-form.tsx b/packages/ui/src/components/channels/channel-form.tsx
index a192f10d..f772f5e7 100644
--- a/packages/ui/src/components/channels/channel-form.tsx
+++ b/packages/ui/src/components/channels/channel-form.tsx
@@ -1,18 +1,11 @@
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useEffect } from 'react';
-import { useForm } from 'react-hook-form';
+import { useForm, useStore } from '@tanstack/react-form';
+import { useEffect, useRef } from 'react';
import { z } from 'zod/v4';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { AvatarPopover } from '@colanode/ui/components/avatars/avatar-popover';
import { Button } from '@colanode/ui/components/ui/button';
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+import { Field, FieldError } from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
const formSchema = z.object({
@@ -39,72 +32,89 @@ export const ChannelForm = ({
onSubmit,
readOnly = false,
}: ChannelFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const nameInputRef = useRef<HTMLInputElement>(null);
+
+ const form = useForm({
defaultValues: values,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const name = useStore(form.store, (state) => state.values.name);
+ const avatar = useStore(form.store, (state) => state.values.avatar);
useEffect(() => {
if (readOnly) return;
const timeoutId = setTimeout(() => {
- form.setFocus('name');
+ nameInputRef.current?.focus();
}, 0);
return () => clearTimeout(timeoutId);
}, [readOnly]);
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
- {readOnly ? (
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
+ {readOnly ? (
+ <Button type="button" variant="outline" size="icon">
+ <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ </Button>
+ ) : (
+ <AvatarPopover
+ onPick={(newAvatar) => {
+ if (newAvatar === values.avatar) return;
+
+ form.setFieldValue('avatar', newAvatar);
+ }}
+ >
<Button type="button" variant="outline" size="icon">
- <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ <Avatar id={id} name={name} avatar={avatar} className="size-6" />
</Button>
- ) : (
- <AvatarPopover
- onPick={(avatar) => {
- if (avatar === values.avatar) return;
-
- form.setValue('avatar', avatar);
- }}
- >
- <Button type="button" variant="outline" size="icon">
- <Avatar
- id={id}
- name={name}
- avatar={avatar}
- className="size-6"
+ </AvatarPopover>
+ )}
+ <form.Field
+ name="name"
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <Input
+ ref={nameInputRef}
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
/>
- </Button>
- </AvatarPopover>
- )}
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={readOnly}>
- {submitText}
- </Button>
- </div>
- </form>
- </Form>
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={readOnly}>
+ {submitText}
+ </Button>
+ </div>
+ </form>
);
};
diff --git a/packages/ui/src/components/databases/database-form.tsx b/packages/ui/src/components/databases/database-form.tsx
index aca43fa6..ca9a37b2 100644
--- a/packages/ui/src/components/databases/database-form.tsx
+++ b/packages/ui/src/components/databases/database-form.tsx
@@ -1,18 +1,11 @@
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useEffect } from 'react';
-import { useForm } from 'react-hook-form';
+import { useForm, useStore } from '@tanstack/react-form';
+import { useEffect, useRef } from 'react';
import { z } from 'zod/v4';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { AvatarPopover } from '@colanode/ui/components/avatars/avatar-popover';
import { Button } from '@colanode/ui/components/ui/button';
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+import { Field, FieldError } from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
const formSchema = z.object({
@@ -39,72 +32,89 @@ export const DatabaseForm = ({
onSubmit,
readOnly = false,
}: DatabaseFormProps) => {
- const form = useForm<DatabaseFormValues>({
- resolver: zodResolver(formSchema),
+ const nameInputRef = useRef<HTMLInputElement>(null);
+
+ const form = useForm({
defaultValues: values,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const name = useStore(form.store, (state) => state.values.name);
+ const avatar = useStore(form.store, (state) => state.values.avatar);
useEffect(() => {
if (readOnly) return;
const timeoutId = setTimeout(() => {
- form.setFocus('name');
+ nameInputRef.current?.focus();
}, 0);
return () => clearTimeout(timeoutId);
}, [readOnly]);
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
- {readOnly ? (
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
+ {readOnly ? (
+ <Button type="button" variant="outline" size="icon">
+ <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ </Button>
+ ) : (
+ <AvatarPopover
+ onPick={(newAvatar) => {
+ if (newAvatar === values.avatar) return;
+
+ form.setFieldValue('avatar', newAvatar);
+ }}
+ >
<Button type="button" variant="outline" size="icon">
- <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ <Avatar id={id} name={name} avatar={avatar} className="size-6" />
</Button>
- ) : (
- <AvatarPopover
- onPick={(avatar) => {
- if (avatar === values.avatar) return;
-
- form.setValue('avatar', avatar);
- }}
- >
- <Button type="button" variant="outline" size="icon">
- <Avatar
- id={id}
- name={name}
- avatar={avatar}
- className="size-6"
+ </AvatarPopover>
+ )}
+ <form.Field
+ name="name"
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <Input
+ ref={nameInputRef}
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
/>
- </Button>
- </AvatarPopover>
- )}
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={readOnly}>
- {submitText}
- </Button>
- </div>
- </form>
- </Form>
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={readOnly}>
+ {submitText}
+ </Button>
+ </div>
+ </form>
);
};
diff --git a/packages/ui/src/components/databases/fields/field-create-popover.tsx b/packages/ui/src/components/databases/fields/field-create-popover.tsx
index e15ea108..e017ff21 100644
--- a/packages/ui/src/components/databases/fields/field-create-popover.tsx
+++ b/packages/ui/src/components/databases/fields/field-create-popover.tsx
@@ -1,7 +1,6 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm, useStore } from '@tanstack/react-form';
import { useMutation } from '@tanstack/react-query';
import { useState } from 'react';
-import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod/v4';
@@ -18,13 +17,11 @@ import { DatabaseSelect } from '@colanode/ui/components/databases/database-selec
import { FieldTypeSelect } from '@colanode/ui/components/databases/fields/field-type-select';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import {
Popover,
@@ -58,6 +55,12 @@ const formSchema = z.object({
relationDatabaseId: z.string().optional().nullable(),
});
+const defaultValues: FieldCreateFormValues = {
+ name: '',
+ type: 'text',
+ relationDatabaseId: null,
+};
+
type FieldCreateFormValues = z.infer<typeof formSchema>;
interface FieldCreatePopoverProps {
@@ -75,15 +78,17 @@ export const FieldCreatePopover = ({
const workspace = useWorkspace();
const database = useDatabase();
- const form = useForm<FieldCreateFormValues>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- name: '',
- type: 'text',
+ const form = useForm({
+ defaultValues,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ mutate(value);
},
});
- const type = form.watch('type');
+ const type = useStore(form.store, (state) => state.values.type);
const handleCancelClick = () => {
setOpen(false);
@@ -164,75 +169,87 @@ export const FieldCreatePopover = ({
<Popover open={open} onOpenChange={setOpen} modal={true}>
<PopoverTrigger asChild>{button}</PopoverTrigger>
<PopoverContent className="mr-5 w-lg" side="bottom">
- <Form {...form}>
- <form
- className="flex flex-col gap-2"
- onSubmit={form.handleSubmit((values) => mutate(values))}
- >
- <div className="grow space-y-4 py-2 pb-4">
- <FormField
- control={form.control}
+ <form
+ className="flex flex-col gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow space-y-4 py-2 pb-4">
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field, formState }) => (
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input id="name" placeholder="Field name" {...field} />
- </FormControl>
- <FormMessage>{formState.errors.name?.message}</FormMessage>
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Name</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="Field name"
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="type"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Field type</FormLabel>
- <FormControl>
- <FieldTypeSelect
- value={field.value}
- onChange={field.onChange}
- types={types}
- />
- </FormControl>
- </FormItem>
+ children={(field) => (
+ <Field>
+ <FieldLabel htmlFor={field.name}>Field type</FieldLabel>
+ <FieldTypeSelect
+ value={field.state.value}
+ onChange={(value) =>
+ field.handleChange(
+ value as FieldCreateFormValues['type']
+ )
+ }
+ types={types}
+ />
+ </Field>
)}
/>
{type === 'relation' && (
- <FormField
- control={form.control}
+ <form.Field
name="relationDatabaseId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Database</FormLabel>
- <FormControl>
- <DatabaseSelect
- id={field.value}
- onChange={field.onChange}
- />
- </FormControl>
- </FormItem>
+ children={(field) => (
+ <Field>
+ <FieldLabel htmlFor={field.name}>Database</FieldLabel>
+ <DatabaseSelect
+ id={field.state.value}
+ onChange={(value) => field.handleChange(value)}
+ />
+ </Field>
)}
/>
)}
- </div>
- <div className="mt-2 flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={handleCancelClick}
- >
- Cancel
- </Button>
- <Button type="submit" size="sm" disabled={isPending}>
- {isPending && <Spinner className="mr-1" />}
- Create
- </Button>
- </div>
- </form>
- </Form>
+ </FieldGroup>
+ </div>
+ <div className="mt-2 flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={handleCancelClick}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={isPending}>
+ {isPending && <Spinner className="mr-1" />}
+ Create
+ </Button>
+ </div>
+ </form>
</PopoverContent>
</Popover>
);
diff --git a/packages/ui/src/components/databases/view-create-dialog.tsx b/packages/ui/src/components/databases/view-create-dialog.tsx
index b89740b7..e77fd653 100644
--- a/packages/ui/src/components/databases/view-create-dialog.tsx
+++ b/packages/ui/src/components/databases/view-create-dialog.tsx
@@ -1,8 +1,7 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { useMutation } from '@tanstack/react-query';
import { Calendar, Columns, Table } from 'lucide-react';
import { FC } from 'react';
-import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod/v4';
@@ -23,13 +22,11 @@ import {
DialogTitle,
} from '@colanode/ui/components/ui/dialog';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { useDatabase } from '@colanode/ui/contexts/database';
@@ -43,6 +40,11 @@ const formSchema = z.object({
type ViewCreateFormValues = z.infer<typeof formSchema>;
+const defaultValues: ViewCreateFormValues = {
+ name: '',
+ type: 'table',
+};
+
interface ViewTypeOption {
name: string;
icon: FC;
@@ -79,11 +81,13 @@ export const ViewCreateDialog = ({
const workspace = useWorkspace();
const database = useDatabase();
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- name: '',
- type: 'table',
+ const form = useForm({
+ defaultValues,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ mutate(value);
},
});
@@ -156,29 +160,42 @@ export const ViewCreateDialog = ({
Create a new view to display your database records
</DialogDescription>
</DialogHeader>
- <Form {...form}>
- <form
- className="flex flex-col"
- onSubmit={form.handleSubmit((values) => mutate(values))}
- >
- <div className="grow space-y-4 py-2 pb-4">
- <FormField
- control={form.control}
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow space-y-4 py-2 pb-4">
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Name *</FormLabel>
- <FormControl>
- <Input placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <FieldLabel htmlFor={field.name}>Name *</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ placeholder="Name"
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="type"
- render={({ field }) => (
+ children={(field) => (
<div className="grid grid-cols-3 gap-4">
{viewTypes.map((viewType) => (
<div
@@ -187,12 +204,12 @@ export const ViewCreateDialog = ({
className={cn(
'flex cursor-pointer flex-col items-center gap-2 rounded-md border p-3 text-muted-foreground',
'hover:bg-accent cursor-pointer',
- viewType.type === field.value
+ viewType.type === field.state.value
? 'border-foreground text-foreground'
: ''
)}
onClick={() => {
- field.onChange(viewType.type);
+ field.handleChange(viewType.type);
}}
>
<viewType.icon />
@@ -202,18 +219,18 @@ export const ViewCreateDialog = ({
</div>
)}
/>
- </div>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={handleCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={isPending}>
- {isPending && <Spinner className="mr-1" />}
- Create
- </Button>
- </DialogFooter>
- </form>
- </Form>
+ </FieldGroup>
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isPending}>
+ {isPending && <Spinner className="mr-1" />}
+ Create
+ </Button>
+ </DialogFooter>
+ </form>
</DialogContent>
</Dialog>
);
diff --git a/packages/ui/src/components/folders/folder-form.tsx b/packages/ui/src/components/folders/folder-form.tsx
index aa6104dd..cc59467c 100644
--- a/packages/ui/src/components/folders/folder-form.tsx
+++ b/packages/ui/src/components/folders/folder-form.tsx
@@ -1,18 +1,11 @@
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useEffect } from 'react';
-import { useForm } from 'react-hook-form';
+import { useForm, useStore } from '@tanstack/react-form';
+import { useEffect, useRef } from 'react';
import { z } from 'zod/v4';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { AvatarPopover } from '@colanode/ui/components/avatars/avatar-popover';
import { Button } from '@colanode/ui/components/ui/button';
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+import { Field, FieldError } from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
const formSchema = z.object({
@@ -39,72 +32,89 @@ export const FolderForm = ({
onSubmit,
readOnly = false,
}: FolderFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const nameInputRef = useRef<HTMLInputElement>(null);
+
+ const form = useForm({
defaultValues: values,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const name = useStore(form.store, (state) => state.values.name);
+ const avatar = useStore(form.store, (state) => state.values.avatar);
useEffect(() => {
if (readOnly) return;
const timeoutId = setTimeout(() => {
- form.setFocus('name');
+ nameInputRef.current?.focus();
}, 0);
return () => clearTimeout(timeoutId);
}, [readOnly]);
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
- {readOnly ? (
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
+ {readOnly ? (
+ <Button type="button" variant="outline" size="icon">
+ <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ </Button>
+ ) : (
+ <AvatarPopover
+ onPick={(newAvatar) => {
+ if (newAvatar === values.avatar) return;
+
+ form.setFieldValue('avatar', newAvatar);
+ }}
+ >
<Button type="button" variant="outline" size="icon">
- <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ <Avatar id={id} name={name} avatar={avatar} className="size-6" />
</Button>
- ) : (
- <AvatarPopover
- onPick={(avatar) => {
- if (avatar === values.avatar) return;
-
- form.setValue('avatar', avatar);
- }}
- >
- <Button type="button" variant="outline" size="icon">
- <Avatar
- id={id}
- name={name}
- avatar={avatar}
- className="size-6"
+ </AvatarPopover>
+ )}
+ <form.Field
+ name="name"
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <Input
+ ref={nameInputRef}
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
/>
- </Button>
- </AvatarPopover>
- )}
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={readOnly}>
- {submitText}
- </Button>
- </div>
- </form>
- </Form>
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={readOnly}>
+ {submitText}
+ </Button>
+ </div>
+ </form>
);
};
diff --git a/packages/ui/src/components/pages/page-form.tsx b/packages/ui/src/components/pages/page-form.tsx
index cf11c7bc..46297b69 100644
--- a/packages/ui/src/components/pages/page-form.tsx
+++ b/packages/ui/src/components/pages/page-form.tsx
@@ -1,18 +1,11 @@
-import { zodResolver } from '@hookform/resolvers/zod';
-import { useEffect } from 'react';
-import { useForm } from 'react-hook-form';
+import { useForm, useStore } from '@tanstack/react-form';
+import { useEffect, useRef } from 'react';
import { z } from 'zod/v4';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { AvatarPopover } from '@colanode/ui/components/avatars/avatar-popover';
import { Button } from '@colanode/ui/components/ui/button';
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+import { Field, FieldError } from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
const formSchema = z.object({
@@ -39,72 +32,89 @@ export const PageForm = ({
onSubmit,
readOnly = false,
}: PageFormProps) => {
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const nameInputRef = useRef<HTMLInputElement>(null);
+
+ const form = useForm({
defaultValues: values,
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
+ },
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const name = useStore(form.store, (state) => state.values.name);
+ const avatar = useStore(form.store, (state) => state.values.avatar);
useEffect(() => {
if (readOnly) return;
const timeoutId = setTimeout(() => {
- form.setFocus('name');
+ nameInputRef.current?.focus();
}, 0);
return () => clearTimeout(timeoutId);
}, [readOnly]);
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
- {readOnly ? (
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow flex flex-row items-end gap-2 py-2 pb-4">
+ {readOnly ? (
+ <Button type="button" variant="outline" size="icon">
+ <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ </Button>
+ ) : (
+ <AvatarPopover
+ onPick={(newAvatar) => {
+ if (newAvatar === values.avatar) return;
+
+ form.setFieldValue('avatar', newAvatar);
+ }}
+ >
<Button type="button" variant="outline" size="icon">
- <Avatar id={id} name={name} avatar={avatar} className="h-6 w-6" />
+ <Avatar id={id} name={name} avatar={avatar} className="size-6" />
</Button>
- ) : (
- <AvatarPopover
- onPick={(avatar) => {
- if (avatar === values.avatar) return;
-
- form.setValue('avatar', avatar);
- }}
- >
- <Button type="button" variant="outline" size="icon">
- <Avatar
- id={id}
- name={name}
- avatar={avatar}
- className="size-6"
+ </AvatarPopover>
+ )}
+ <form.Field
+ name="name"
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <Input
+ ref={nameInputRef}
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
/>
- </Button>
- </AvatarPopover>
- )}
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" onClick={onCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={readOnly}>
- {submitText}
- </Button>
- </div>
- </form>
- </Form>
+ {isInvalid && <FieldError errors={field.state.meta.errors} />}
+ </Field>
+ );
+ }}
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="outline" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={readOnly}>
+ {submitText}
+ </Button>
+ </div>
+ </form>
);
};
diff --git a/packages/ui/src/components/spaces/space-form.tsx b/packages/ui/src/components/spaces/space-form.tsx
index ca9707ce..95c28291 100644
--- a/packages/ui/src/components/spaces/space-form.tsx
+++ b/packages/ui/src/components/spaces/space-form.tsx
@@ -1,7 +1,6 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm, useStore } from '@tanstack/react-form';
import { Edit } from 'lucide-react';
import { useRef } from 'react';
-import { useForm } from 'react-hook-form';
import { z } from 'zod/v4';
import { generateId, IdType } from '@colanode/core';
@@ -9,13 +8,11 @@ import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { AvatarPopover } from '@colanode/ui/components/avatars/avatar-popover';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import { Textarea } from '@colanode/ui/components/ui/textarea';
import { useIsMobile } from '@colanode/ui/hooks/use-is-mobile';
@@ -29,6 +26,12 @@ const formSchema = z.object({
export type SpaceFormValues = z.infer<typeof formSchema>;
+const defaultValues: SpaceFormValues = {
+ name: '',
+ description: '',
+ avatar: null,
+};
+
interface SpaceFormProps {
values?: SpaceFormValues;
onSubmit: (values: SpaceFormValues) => void;
@@ -47,107 +50,137 @@ export const SpaceForm = ({
const id = useRef(generateId(IdType.Space));
const isMobile = useIsMobile();
- const form = useForm<SpaceFormValues>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
- name: values?.name ?? '',
- description: values?.description ?? '',
- avatar: values?.avatar,
+ ...defaultValues,
+ ...values,
+ },
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
},
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const name = useStore(form.store, (state) => state.values.name);
+ const avatar = useStore(form.store, (state) => state.values.avatar);
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
- <AvatarPopover
- onPick={(avatar) => {
- form.setValue('avatar', avatar);
- }}
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
+ <AvatarPopover
+ onPick={(newAvatar) => {
+ form.setFieldValue('avatar', newAvatar);
+ }}
+ >
+ <div
+ className={cn(
+ 'pt-3',
+ isMobile ? 'flex justify-center pb-4' : 'size-40'
+ )}
>
- <div
- className={cn(
- 'pt-3',
- isMobile ? 'flex justify-center pb-4' : 'size-40'
- )}
- >
- <div className="group relative cursor-pointer">
- <Avatar
- id={id.current}
- name={name.length > 0 ? name : 'New space'}
- avatar={avatar}
- className={isMobile ? 'size-24' : 'size-32'}
- />
- <div
- className={cn(
- `absolute left-0 top-0 hidden h-32 w-32 items-center justify-center overflow-hidden bg-accent/70 group-hover:inline-flex`,
- readOnly && 'hidden group-hover:hidden'
- )}
- >
- <Edit className="size-5 text-foreground" />
- </div>
+ <div className="group relative cursor-pointer">
+ <Avatar
+ id={id.current}
+ name={name.length > 0 ? name : 'New space'}
+ avatar={avatar}
+ className={isMobile ? 'size-24' : 'size-32'}
+ />
+ <div
+ className={cn(
+ `absolute left-0 top-0 hidden h-32 w-32 items-center justify-center overflow-hidden bg-accent/70 group-hover:inline-flex`,
+ readOnly && 'hidden group-hover:hidden'
+ )}
+ >
+ <Edit className="size-5 text-foreground" />
</div>
</div>
- </AvatarPopover>
+ </div>
+ </AvatarPopover>
- <div
- className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
- >
- <FormField
- control={form.control}
+ <div
+ className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
+ >
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Name *</FormLabel>
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <FieldLabel htmlFor={field.name}>Name *</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description</FormLabel>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Description</FieldLabel>
<Textarea
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
readOnly={readOnly}
placeholder="Write a short description about the space"
- {...field}
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- </div>
+ </FieldGroup>
</div>
- {!readOnly && (
- <div className="flex flex-row justify-end gap-2">
- {onCancel && (
- <Button
- type="button"
- variant="outline"
- onClick={() => {
- onCancel();
- }}
- >
- Cancel
- </Button>
- )}
-
- <Button type="submit" disabled={readOnly} className="w-20">
- {submitText}
+ </div>
+ {!readOnly && (
+ <div className="flex flex-row justify-end gap-2">
+ {onCancel && (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ onCancel();
+ }}
+ >
+ Cancel
</Button>
- </div>
- )}
- </form>
- </Form>
+ )}
+
+ <Button type="submit" disabled={readOnly} className="w-20">
+ {submitText}
+ </Button>
+ </div>
+ )}
+ </form>
);
};
diff --git a/packages/ui/src/components/ui/field.tsx b/packages/ui/src/components/ui/field.tsx
new file mode 100644
index 00000000..30bf40e9
--- /dev/null
+++ b/packages/ui/src/components/ui/field.tsx
@@ -0,0 +1,246 @@
+import { cva, type VariantProps } from 'class-variance-authority';
+import { useMemo } from 'react';
+
+import { Label } from '@colanode/ui/components/ui/label';
+import { Separator } from '@colanode/ui/components/ui/separator';
+import { cn } from '@colanode/ui/lib/utils';
+
+function FieldSet({ className, ...props }: React.ComponentProps<'fieldset'>) {
+ return (
+ <fieldset
+ data-slot="field-set"
+ className={cn(
+ 'flex flex-col gap-6',
+ 'has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldLegend({
+ className,
+ variant = 'legend',
+ ...props
+}: React.ComponentProps<'legend'> & { variant?: 'legend' | 'label' }) {
+ return (
+ <legend
+ data-slot="field-legend"
+ data-variant={variant}
+ className={cn(
+ 'mb-3 font-medium',
+ 'data-[variant=legend]:text-base',
+ 'data-[variant=label]:text-sm',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldGroup({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="field-group"
+ className={cn(
+ 'group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+const fieldVariants = cva(
+ 'group/field flex w-full gap-3 data-[invalid=true]:text-destructive',
+ {
+ variants: {
+ orientation: {
+ vertical: ['flex-col [&>*]:w-full [&>.sr-only]:w-auto'],
+ horizontal: [
+ 'flex-row items-center',
+ '[&>[data-slot=field-label]]:flex-auto',
+ 'has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
+ ],
+ responsive: [
+ 'flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto',
+ '@md/field-group:[&>[data-slot=field-label]]:flex-auto',
+ '@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
+ ],
+ },
+ },
+ defaultVariants: {
+ orientation: 'vertical',
+ },
+ }
+);
+
+function Field({
+ className,
+ orientation = 'vertical',
+ ...props
+}: React.ComponentProps<'div'> & VariantProps<typeof fieldVariants>) {
+ return (
+ <div
+ role="group"
+ data-slot="field"
+ data-orientation={orientation}
+ className={cn(fieldVariants({ orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+function FieldContent({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="field-content"
+ className={cn(
+ 'group/field-content flex flex-1 flex-col gap-1.5 leading-snug',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof Label>) {
+ return (
+ <Label
+ data-slot="field-label"
+ className={cn(
+ 'group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50',
+ 'has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4',
+ 'has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldTitle({ className, ...props }: React.ComponentProps<'div'>) {
+ return (
+ <div
+ data-slot="field-label"
+ className={cn(
+ 'flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldDescription({ className, ...props }: React.ComponentProps<'p'>) {
+ return (
+ <p
+ data-slot="field-description"
+ className={cn(
+ 'text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance',
+ 'last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5',
+ '[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4',
+ className
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<'div'> & {
+ children?: React.ReactNode;
+}) {
+ return (
+ <div
+ data-slot="field-separator"
+ data-content={!!children}
+ className={cn(
+ 'relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2',
+ className
+ )}
+ {...props}
+ >
+ <Separator className="absolute inset-0 top-1/2" />
+ {children && (
+ <span
+ className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
+ data-slot="field-separator-content"
+ >
+ {children}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function FieldError({
+ className,
+ children,
+ errors,
+ ...props
+}: React.ComponentProps<'div'> & {
+ errors?: Array<{ message?: string } | undefined>;
+}) {
+ const content = useMemo(() => {
+ if (children) {
+ return children;
+ }
+
+ if (!errors?.length) {
+ return null;
+ }
+
+ const uniqueErrors = [
+ ...new Map(errors.map((error) => [error?.message, error])).values(),
+ ];
+
+ if (uniqueErrors?.length == 1) {
+ return uniqueErrors[0]?.message;
+ }
+
+ return (
+ <ul className="ml-4 flex list-disc flex-col gap-1">
+ {uniqueErrors.map(
+ (error, index) =>
+ error?.message && <li key={index}>{error.message}</li>
+ )}
+ </ul>
+ );
+ }, [children, errors]);
+
+ if (!content) {
+ return null;
+ }
+
+ return (
+ <div
+ role="alert"
+ data-slot="field-error"
+ className={cn('text-destructive text-sm font-normal', className)}
+ {...props}
+ >
+ {content}
+ </div>
+ );
+}
+
+export {
+ Field,
+ FieldLabel,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldContent,
+ FieldTitle,
+};
diff --git a/packages/ui/src/components/ui/form.tsx b/packages/ui/src/components/ui/form.tsx
deleted file mode 100644
index bb494d3d..00000000
--- a/packages/ui/src/components/ui/form.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import * as LabelPrimitive from '@radix-ui/react-label';
-import { Slot } from '@radix-ui/react-slot';
-import * as React from 'react';
-import {
- Controller,
- FormProvider,
- useFormContext,
- useFormState,
- type ControllerProps,
- type FieldPath,
- type FieldValues,
-} from 'react-hook-form';
-
-import { Label } from '@colanode/ui/components/ui/label';
-import { cn } from '@colanode/ui/lib/utils';
-
-const Form = FormProvider;
-
-type FormFieldContextValue<
- TFieldValues extends FieldValues = FieldValues,
- TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
-> = {
- name: TName;
-};
-
-const FormFieldContext = React.createContext<FormFieldContextValue>(
- {} as FormFieldContextValue
-);
-
-const FormField = <
- TFieldValues extends FieldValues = FieldValues,
- TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
->({
- ...props
-}: ControllerProps<TFieldValues, TName>) => {
- return (
- <FormFieldContext.Provider value={{ name: props.name }}>
- <Controller {...props} />
- </FormFieldContext.Provider>
- );
-};
-
-const useFormField = () => {
- const fieldContext = React.useContext(FormFieldContext);
- const itemContext = React.useContext(FormItemContext);
- const { getFieldState } = useFormContext();
- const formState = useFormState({ name: fieldContext.name });
- const fieldState = getFieldState(fieldContext.name, formState);
-
- if (!fieldContext) {
- throw new Error('useFormField should be used within <FormField>');
- }
-
- const { id } = itemContext;
-
- return {
- id,
- name: fieldContext.name,
- formItemId: `${id}-form-item`,
- formDescriptionId: `${id}-form-item-description`,
- formMessageId: `${id}-form-item-message`,
- ...fieldState,
- };
-};
-
-type FormItemContextValue = {
- id: string;
-};
-
-const FormItemContext = React.createContext<FormItemContextValue>(
- {} as FormItemContextValue
-);
-
-function FormItem({ className, ...props }: React.ComponentProps<'div'>) {
- const id = React.useId();
-
- return (
- <FormItemContext.Provider value={{ id }}>
- <div
- data-slot="form-item"
- className={cn('grid gap-2', className)}
- {...props}
- />
- </FormItemContext.Provider>
- );
-}
-
-function FormLabel({
- className,
- ...props
-}: React.ComponentProps<typeof LabelPrimitive.Root>) {
- const { error, formItemId } = useFormField();
-
- return (
- <Label
- data-slot="form-label"
- data-error={!!error}
- className={cn('data-[error=true]:text-destructive', className)}
- htmlFor={formItemId}
- {...props}
- />
- );
-}
-
-function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
- const { error, formItemId, formDescriptionId, formMessageId } =
- useFormField();
-
- return (
- <Slot
- data-slot="form-control"
- id={formItemId}
- aria-describedby={
- !error
- ? `${formDescriptionId}`
- : `${formDescriptionId} ${formMessageId}`
- }
- aria-invalid={!!error}
- {...props}
- />
- );
-}
-
-function FormDescription({ className, ...props }: React.ComponentProps<'p'>) {
- const { formDescriptionId } = useFormField();
-
- return (
- <p
- data-slot="form-description"
- id={formDescriptionId}
- className={cn('text-muted-foreground text-sm', className)}
- {...props}
- />
- );
-}
-
-function FormMessage({ className, ...props }: React.ComponentProps<'p'>) {
- const { error, formMessageId } = useFormField();
- const body = error ? String(error?.message ?? '') : props.children;
-
- if (!body) {
- return null;
- }
-
- return (
- <p
- data-slot="form-message"
- id={formMessageId}
- className={cn('text-destructive text-sm', className)}
- {...props}
- >
- {body}
- </p>
- );
-}
-
-export {
- useFormField,
- Form,
- FormItem,
- FormLabel,
- FormControl,
- FormDescription,
- FormMessage,
- FormField,
-};
diff --git a/packages/ui/src/components/workspaces/storage/workspace-storage-user-update-dialog.tsx b/packages/ui/src/components/workspaces/storage/workspace-storage-user-update-dialog.tsx
index 51b3952d..b3dbcaf2 100644
--- a/packages/ui/src/components/workspaces/storage/workspace-storage-user-update-dialog.tsx
+++ b/packages/ui/src/components/workspaces/storage/workspace-storage-user-update-dialog.tsx
@@ -1,8 +1,7 @@
-import { zodResolver } from '@hookform/resolvers/zod';
import { eq, useLiveQuery } from '@tanstack/react-db';
+import { useForm } from '@tanstack/react-form';
import { Check, ChevronDown } from 'lucide-react';
import { useState } from 'react';
-import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod/v4';
@@ -24,13 +23,11 @@ import {
DropdownMenuTrigger,
} from '@colanode/ui/components/ui/dropdown-menu';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { useWorkspace } from '@colanode/ui/contexts/workspace';
@@ -125,12 +122,48 @@ export const WorkspaceStorageUserUpdateDialog = ({
const email = userQuery.data?.email ?? '';
const avatar = userQuery.data?.avatar ?? null;
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
storageLimit: initialStorageLimit.value,
maxFileSize: initialMaxFileSize.value,
},
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ if (isPending) {
+ return;
+ }
+
+ const apiValues = {
+ storageLimit: convertUnitToBytes(value.storageLimit, storageLimitUnit),
+ maxFileSize: convertUnitToBytes(value.maxFileSize, maxFileSizeUnit),
+ };
+
+ if (BigInt(apiValues.maxFileSize) > BigInt(apiValues.storageLimit)) {
+ toast.error('Max file size cannot be larger than storage limit');
+ return;
+ }
+
+ mutate({
+ input: {
+ type: 'user.storage.update',
+ accountId: workspace.accountId,
+ workspaceId: workspace.workspaceId,
+ userId: user.id,
+ storageLimit: apiValues.storageLimit,
+ maxFileSize: apiValues.maxFileSize,
+ },
+ onSuccess: () => {
+ toast.success('User storage settings updated');
+ form.reset();
+ onUpdate();
+ },
+ onError: (error) => {
+ toast.error(error.message);
+ },
+ });
+ },
});
const handleCancel = () => {
@@ -140,41 +173,6 @@ export const WorkspaceStorageUserUpdateDialog = ({
onOpenChange(false);
};
- const handleSubmit = async (values: z.infer<typeof formSchema>) => {
- if (isPending) {
- return;
- }
-
- const apiValues = {
- storageLimit: convertUnitToBytes(values.storageLimit, storageLimitUnit),
- maxFileSize: convertUnitToBytes(values.maxFileSize, maxFileSizeUnit),
- };
-
- if (BigInt(apiValues.maxFileSize) > BigInt(apiValues.storageLimit)) {
- toast.error('Max file size cannot be larger than storage limit');
- return;
- }
-
- mutate({
- input: {
- type: 'user.storage.update',
- accountId: workspace.accountId,
- workspaceId: workspace.workspaceId,
- userId: user.id,
- storageLimit: apiValues.storageLimit,
- maxFileSize: apiValues.maxFileSize,
- },
- onSuccess: () => {
- toast.success('User storage settings updated');
- form.reset();
- onUpdate();
- },
- onError: (error) => {
- toast.error(error.message);
- },
- });
- };
-
const storageLimitUnitData = UNITS.find((u) => u.value === storageLimitUnit);
const storageLimitUnitLabel = storageLimitUnitData?.label ?? 'bytes';
const maxFileSizeUnitData = UNITS.find((u) => u.value === maxFileSizeUnit);
@@ -196,24 +194,35 @@ export const WorkspaceStorageUserUpdateDialog = ({
<p className="text-sm text-muted-foreground truncate">{email}</p>
</div>
</div>
- <Form {...form}>
- <form
- className="flex flex-col"
- onSubmit={form.handleSubmit(handleSubmit)}
- >
- <div className="grow space-y-6 py-2 pb-4">
- <FormField
- control={form.control}
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className="grow space-y-6 py-2 pb-4">
+ <FieldGroup>
+ <form.Field
name="storageLimit"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Storage Limit</FormLabel>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>
+ Storage Limit
+ </FieldLabel>
<div className="flex space-x-2">
<Input
+ id={field.name}
+ name={field.name}
type="number"
placeholder="5"
- {...field}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
className="flex-1"
min="1"
step="1"
@@ -244,31 +253,43 @@ export const WorkspaceStorageUserUpdateDialog = ({
</DropdownMenuContent>
</DropdownMenu>
</div>
- </FormControl>
- <div className="text-xs text-muted-foreground">
- ={' '}
- {formatBytes(
- convertUnitToBytes(field.value || '0', storageLimitUnit)
- )}{' '}
- bytes
- </div>
- <FormMessage />
- </FormItem>
- )}
+ <div className="text-xs text-muted-foreground">
+ ={' '}
+ {formatBytes(
+ convertUnitToBytes(
+ field.state.value || '0',
+ storageLimitUnit
+ )
+ )}{' '}
+ bytes
+ </div>
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="maxFileSize"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Max File Size</FormLabel>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>
+ Max File Size
+ </FieldLabel>
<div className="flex space-x-2">
<Input
+ id={field.name}
+ name={field.name}
type="number"
placeholder="10"
- {...field}
- value={field.value || ''}
+ value={field.state.value || ''}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
className="flex-1"
min="1"
step="1"
@@ -299,30 +320,35 @@ export const WorkspaceStorageUserUpdateDialog = ({
</DropdownMenuContent>
</DropdownMenu>
</div>
- </FormControl>
- <div className="text-xs text-muted-foreground">
- ={' '}
- {formatBytes(
- convertUnitToBytes(field.value || '0', maxFileSizeUnit)
- )}{' '}
- bytes
- </div>
- <FormMessage />
- </FormItem>
- )}
+ <div className="text-xs text-muted-foreground">
+ ={' '}
+ {formatBytes(
+ convertUnitToBytes(
+ field.state.value || '0',
+ maxFileSizeUnit
+ )
+ )}{' '}
+ bytes
+ </div>
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- </div>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={handleCancel}>
- Cancel
- </Button>
- <Button type="submit" disabled={isPending}>
- {isPending && <Spinner className="mr-1" />}
- Update
- </Button>
- </DialogFooter>
- </form>
- </Form>
+ </FieldGroup>
+ </div>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={isPending}>
+ {isPending && <Spinner className="mr-1" />}
+ Update
+ </Button>
+ </DialogFooter>
+ </form>
</DialogContent>
</Dialog>
);
diff --git a/packages/ui/src/components/workspaces/workspace-form.tsx b/packages/ui/src/components/workspaces/workspace-form.tsx
index 4126c961..94a426af 100644
--- a/packages/ui/src/components/workspaces/workspace-form.tsx
+++ b/packages/ui/src/components/workspaces/workspace-form.tsx
@@ -1,7 +1,6 @@
-import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from '@tanstack/react-form';
import { Upload } from 'lucide-react';
import { useRef } from 'react';
-import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod/v4';
@@ -9,13 +8,11 @@ import { generateId, IdType } from '@colanode/core';
import { Avatar } from '@colanode/ui/components/avatars/avatar';
import { Button } from '@colanode/ui/components/ui/button';
import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@colanode/ui/components/ui/form';
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from '@colanode/ui/components/ui/field';
import { Input } from '@colanode/ui/components/ui/input';
import { Spinner } from '@colanode/ui/components/ui/spinner';
import { Textarea } from '@colanode/ui/components/ui/textarea';
@@ -31,11 +28,17 @@ const formSchema = z.object({
avatar: z.string().optional().nullable(),
});
-type formSchemaType = z.infer<typeof formSchema>;
+type WorkspaceFormValues = z.infer<typeof formSchema>;
+
+const defaultValues: WorkspaceFormValues = {
+ name: '',
+ description: '',
+ avatar: null,
+};
interface WorkspaceFormProps {
- values?: formSchemaType;
- onSubmit: (values: formSchemaType) => void;
+ values?: WorkspaceFormValues;
+ onSubmit: (values: WorkspaceFormValues) => void;
isSaving: boolean;
onCancel?: () => void;
saveText: string;
@@ -56,146 +59,183 @@ export const WorkspaceForm = ({
const id = useRef(generateId(IdType.Workspace));
const { mutate, isPending } = useMutation();
- const form = useForm<formSchemaType>({
- resolver: zodResolver(formSchema),
+ const form = useForm({
defaultValues: {
- name: values?.name ?? '',
- description: values?.description ?? '',
- avatar: values?.avatar,
+ ...defaultValues,
+ ...values,
+ },
+ validators: {
+ onSubmit: formSchema,
+ },
+ onSubmit: async ({ value }) => {
+ onSubmit(value);
},
});
- const name = form.watch('name');
- const avatar = form.watch('avatar');
+ const handleAvatarClick = async () => {
+ if (isPending || readOnly) {
+ return;
+ }
+
+ const result = await openFileDialog({
+ accept: 'image/jpeg, image/jpg, image/png, image/webp',
+ });
+
+ if (result.type === 'success') {
+ const file = result.files[0];
+ if (!file) {
+ return;
+ }
+
+ mutate({
+ input: {
+ type: 'avatar.upload',
+ accountId: workspace.accountId,
+ file,
+ },
+ onSuccess(output) {
+ form.setFieldValue('avatar', output.id);
+ },
+ onError(error) {
+ toast.error(error.message);
+ },
+ });
+ } else if (result.type === 'error') {
+ toast.error(result.error);
+ }
+ };
return (
- <Form {...form}>
- <form className="flex flex-col" onSubmit={form.handleSubmit(onSubmit)}>
- <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
+ <form
+ className="flex flex-col"
+ onSubmit={(e) => {
+ e.preventDefault();
+ form.handleSubmit();
+ }}
+ >
+ <div className={cn('flex gap-1', isMobile ? 'flex-col' : 'flex-row')}>
+ <div
+ className={cn(
+ 'pt-3',
+ isMobile ? 'flex justify-center pb-4' : 'size-40'
+ )}
+ >
<div
- className={cn(
- 'pt-3',
- isMobile ? 'flex justify-center pb-4' : 'size-40'
- )}
+ className="group relative cursor-pointer"
+ onClick={handleAvatarClick}
>
+ <form.Subscribe
+ selector={(state) => ({
+ avatar: state.values.avatar,
+ name: state.values.name,
+ })}
+ children={({ avatar, name }) => (
+ <Avatar
+ id={id.current}
+ name={name.length > 0 ? name : 'New workspace'}
+ avatar={avatar}
+ className={isMobile ? 'size-24' : 'size-32'}
+ />
+ )}
+ />
<div
- className="group relative cursor-pointer"
- onClick={async () => {
- if (isPending || readOnly) {
- return;
- }
-
- const result = await openFileDialog({
- accept: 'image/jpeg, image/jpg, image/png, image/webp',
- });
-
- if (result.type === 'success') {
- const file = result.files[0];
- if (!file) {
- return;
- }
-
- mutate({
- input: {
- type: 'avatar.upload',
- accountId: workspace.accountId,
- file,
- },
- onSuccess(output) {
- form.setValue('avatar', output.id);
- },
- onError(error) {
- toast.error(error.message);
- },
- });
- } else if (result.type === 'error') {
- toast.error(result.error);
- }
- }}
+ className={cn(
+ `absolute left-0 top-0 hidden items-center justify-center overflow-hidden bg-accent/70 group-hover:inline-flex`,
+ isMobile ? 'size-24' : 'size-32',
+ isPending ? 'inline-flex' : 'hidden',
+ readOnly && 'hidden group-hover:hidden'
+ )}
>
- <Avatar
- id={id.current}
- name={name.length > 0 ? name : 'New workspace'}
- avatar={avatar}
- className={isMobile ? 'size-24' : 'size-32'}
- />
- <div
- className={cn(
- `absolute left-0 top-0 hidden items-center justify-center overflow-hidden bg-accent/70 group-hover:inline-flex`,
- isMobile ? 'size-24' : 'size-32',
- isPending ? 'inline-flex' : 'hidden',
- readOnly && 'hidden group-hover:hidden'
- )}
- >
- {isPending ? (
- <Spinner className="size-5" />
- ) : (
- <Upload className="size-5 text-foreground" />
- )}
- </div>
+ {isPending ? (
+ <Spinner className="size-5" />
+ ) : (
+ <Upload className="size-5 text-foreground" />
+ )}
</div>
</div>
- <div
- className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
- >
- <FormField
- control={form.control}
+ </div>
+ <div
+ className={cn('space-y-4 py-2 pb-4', isMobile ? 'w-full' : 'grow')}
+ >
+ <FieldGroup>
+ <form.Field
name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Name *</FormLabel>
- <FormControl>
- <Input readOnly={readOnly} placeholder="Name" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid} className="flex-1">
+ <FieldLabel htmlFor={field.name}>Name *</FieldLabel>
+ <Input
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
+ readOnly={readOnly}
+ placeholder="Name"
+ />
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- <FormField
- control={form.control}
+ <form.Field
name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description</FormLabel>
- <FormControl>
+ children={(field) => {
+ const isInvalid =
+ field.state.meta.isTouched && !field.state.meta.isValid;
+ return (
+ <Field data-invalid={isInvalid}>
+ <FieldLabel htmlFor={field.name}>Description</FieldLabel>
<Textarea
+ id={field.name}
+ name={field.name}
+ value={field.state.value}
+ onBlur={field.handleBlur}
+ onChange={(e) => field.handleChange(e.target.value)}
+ aria-invalid={isInvalid}
readOnly={readOnly}
placeholder="Write a short description about the workspace"
- {...field}
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {isInvalid && (
+ <FieldError errors={field.state.meta.errors} />
+ )}
+ </Field>
+ );
+ }}
/>
- </div>
+ </FieldGroup>
</div>
- {!readOnly && (
- <div className="flex flex-row justify-end gap-2">
- {onCancel && (
- <Button
- type="button"
- disabled={isPending || isSaving}
- variant="outline"
- onClick={() => {
- onCancel();
- }}
- >
- Cancel
- </Button>
- )}
-
+ </div>
+ {!readOnly && (
+ <div className="flex flex-row justify-end gap-2">
+ {onCancel && (
<Button
- type="submit"
+ type="button"
disabled={isPending || isSaving}
- className="w-20"
+ variant="outline"
+ onClick={() => {
+ onCancel();
+ }}
>
- {isSaving && <Spinner className="mr-1" />}
- {saveText}
+ Cancel
</Button>
- </div>
- )}
- </form>
- </Form>
+ )}
+
+ <Button
+ type="submit"
+ disabled={isPending || isSaving}
+ className="w-20"
+ >
+ {isSaving && <Spinner className="mr-1" />}
+ {saveText}
+ </Button>
+ </div>
+ )}
+ </form>
);
};