remix-validated-form 0.0.3 → 1.1.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.eslintcache +1 -0
  2. package/.prettierignore +2 -0
  3. package/README.md +228 -1
  4. package/browser/ValidatedForm.js +1 -1
  5. package/browser/flatten.d.ts +5 -0
  6. package/browser/flatten.js +41 -0
  7. package/browser/hooks.js +5 -1
  8. package/browser/index.d.ts +1 -0
  9. package/browser/index.js +1 -0
  10. package/browser/server.d.ts +1 -1
  11. package/browser/server.js +1 -1
  12. package/browser/validation/createValidator.d.ts +3 -0
  13. package/browser/validation/createValidator.js +8 -0
  14. package/browser/validation/types.d.ts +5 -2
  15. package/browser/validation/validation.test.js +156 -8
  16. package/browser/validation/withYup.js +28 -25
  17. package/browser/validation/withZod.d.ts +3 -0
  18. package/browser/validation/withZod.js +47 -0
  19. package/build/ValidatedForm.js +1 -1
  20. package/build/flatten.d.ts +5 -0
  21. package/build/flatten.js +49 -0
  22. package/build/hooks.js +8 -1
  23. package/build/index.d.ts +1 -0
  24. package/build/index.js +1 -0
  25. package/build/server.d.ts +1 -1
  26. package/build/server.js +3 -3
  27. package/build/validation/createValidator.d.ts +3 -0
  28. package/build/validation/createValidator.js +12 -0
  29. package/build/validation/types.d.ts +5 -2
  30. package/build/validation/validation.test.js +156 -8
  31. package/build/validation/withYup.js +28 -25
  32. package/build/validation/withZod.d.ts +3 -0
  33. package/build/validation/withZod.js +54 -0
  34. package/package.json +20 -14
  35. package/sample-app/.env +7 -0
  36. package/sample-app/README.md +53 -0
  37. package/sample-app/app/components/ErrorBox.tsx +34 -0
  38. package/sample-app/app/components/FormInput.tsx +40 -0
  39. package/sample-app/app/components/FormSelect.tsx +37 -0
  40. package/sample-app/app/components/SubjectForm.tsx +150 -0
  41. package/sample-app/app/entry.client.tsx +4 -0
  42. package/sample-app/app/entry.server.tsx +21 -0
  43. package/sample-app/app/root.tsx +92 -0
  44. package/sample-app/app/routes/index.tsx +5 -0
  45. package/sample-app/app/routes/subjects/$id.edit.tsx +100 -0
  46. package/sample-app/app/routes/subjects/index.tsx +112 -0
  47. package/sample-app/app/routes/subjects/new.tsx +48 -0
  48. package/sample-app/app/services/db.server.ts +23 -0
  49. package/sample-app/app/types.ts +6 -0
  50. package/sample-app/package-lock.json +4617 -0
  51. package/sample-app/package.json +36 -0
  52. package/sample-app/prisma/dev.db +0 -0
  53. package/sample-app/prisma/schema.prisma +34 -0
  54. package/sample-app/public/favicon.ico +0 -0
  55. package/sample-app/remix.config.js +10 -0
  56. package/sample-app/remix.env.d.ts +2 -0
@@ -0,0 +1,53 @@
1
+ # Welcome to Remix!
2
+
3
+ - [Remix Docs](https://remix.run/docs)
4
+
5
+ ## Development
6
+
7
+ From your terminal:
8
+
9
+ ```sh
10
+ npm run dev
11
+ ```
12
+
13
+ This starts your app in development mode, rebuilding assets on file changes.
14
+
15
+ ## Deployment
16
+
17
+ First, build your app for production:
18
+
19
+ ```sh
20
+ npm run build
21
+ ```
22
+
23
+ Then run the app in production mode:
24
+
25
+ ```sh
26
+ npm start
27
+ ```
28
+
29
+ Now you'll need to pick a host to deploy it to.
30
+
31
+ ### DIY
32
+
33
+ If you're familiar with deploying node applications, the built-in Remix app server is production-ready.
34
+
35
+ Make sure to deploy the output of `remix build`
36
+
37
+ - `build/`
38
+ - `public/build/`
39
+
40
+ ### Using a Template
41
+
42
+ When you ran `npx create-remix@latest` there were a few choices for hosting. You can run that again to create a new project, then copy over your `app/` folder to the new project that's pre-configured for your target server.
43
+
44
+ ```sh
45
+ cd ..
46
+ # create a new project, and pick a pre-configured host
47
+ npx create-remix@latest
48
+ cd my-new-remix-app
49
+ # remove the new project's app (not the old one!)
50
+ rm -rf app
51
+ # copy your app over
52
+ cp -R ../my-old-remix-app/app app
53
+ ```
@@ -0,0 +1,34 @@
1
+ import {
2
+ Alert,
3
+ AlertDescription,
4
+ AlertIcon,
5
+ AlertTitle,
6
+ } from "@chakra-ui/react";
7
+
8
+ type ErrorProps = {
9
+ title?: React.ReactNode;
10
+ description?: React.ReactNode;
11
+ };
12
+ export function ErrorBox({ title, description }: ErrorProps) {
13
+ return (
14
+ <Alert
15
+ status="error"
16
+ variant="subtle"
17
+ flexDirection="column"
18
+ alignItems="center"
19
+ justifyContent="center"
20
+ textAlign="center"
21
+ height="200px"
22
+ >
23
+ <AlertIcon boxSize="40px" mr={0} />
24
+ {title && (
25
+ <AlertTitle mt={4} mb={1} fontSize="lg">
26
+ {title}
27
+ </AlertTitle>
28
+ )}
29
+ {description && (
30
+ <AlertDescription maxWidth="sm">{description}</AlertDescription>
31
+ )}
32
+ </Alert>
33
+ );
34
+ }
@@ -0,0 +1,40 @@
1
+ import {
2
+ FormControl,
3
+ FormErrorMessage,
4
+ FormLabel,
5
+ Input,
6
+ InputProps,
7
+ } from "@chakra-ui/react";
8
+ import { useField } from "../../remix-validated-form";
9
+
10
+ type FormInputProps = {
11
+ name: string;
12
+ label: string;
13
+ isRequired?: boolean;
14
+ };
15
+
16
+ export const FormInput = ({
17
+ name,
18
+ label,
19
+ isRequired,
20
+ ...rest
21
+ }: FormInputProps & InputProps) => {
22
+ const { validate, clearError, defaultValue, error } = useField(name);
23
+
24
+ return (
25
+ <>
26
+ <FormControl isInvalid={!!error} isRequired={isRequired}>
27
+ <FormLabel htmlFor={name}>{label}</FormLabel>
28
+ <Input
29
+ id={name}
30
+ name={name}
31
+ onBlur={validate}
32
+ onChange={clearError}
33
+ defaultValue={defaultValue}
34
+ {...rest}
35
+ />
36
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
37
+ </FormControl>
38
+ </>
39
+ );
40
+ };
@@ -0,0 +1,37 @@
1
+ import {
2
+ FormControl,
3
+ FormErrorMessage,
4
+ FormLabel,
5
+ Select,
6
+ SelectProps,
7
+ } from "@chakra-ui/react";
8
+ import { useField } from "../../remix-validated-form";
9
+
10
+ type FormSelectProps = {
11
+ name: string;
12
+ label: string;
13
+ isRequired?: boolean;
14
+ };
15
+
16
+ export const FormSelect = ({
17
+ name,
18
+ label,
19
+ isRequired,
20
+ ...rest
21
+ }: FormSelectProps & SelectProps) => {
22
+ const { validate, clearError, defaultValue, error } = useField(name);
23
+ return (
24
+ <FormControl isInvalid={!!error} isRequired={isRequired}>
25
+ <FormLabel htmlFor={name}>{label}</FormLabel>
26
+ <Select
27
+ id={name}
28
+ name={name}
29
+ onBlur={validate}
30
+ onChange={clearError}
31
+ defaultValue={defaultValue}
32
+ {...rest}
33
+ />
34
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
35
+ </FormControl>
36
+ );
37
+ };
@@ -0,0 +1,150 @@
1
+ import {
2
+ Box,
3
+ Button,
4
+ Stack,
5
+ HStack,
6
+ Container,
7
+ VStack,
8
+ } from "@chakra-ui/react";
9
+ import { useState } from "react";
10
+ import { useNavigate } from "remix";
11
+ import * as z from "zod";
12
+ import {
13
+ ValidatedForm,
14
+ withZod,
15
+ useIsSubmitting,
16
+ } from "../../remix-validated-form";
17
+ import { FormInput } from "./FormInput";
18
+ import { FormSelect } from "./FormSelect";
19
+
20
+ const subjectSchema = z.object({
21
+ name: z.string().nonempty("Subject Name can't be empty"),
22
+ description: z.string().nonempty("Subject Description can't be empty"),
23
+ teacher: z.object({
24
+ name: z.string().nonempty("Teacher Name can't be empty"),
25
+ email: z
26
+ .string()
27
+ .email("Teacher Email is invalid")
28
+ .nonempty("Teacher Email can't be empty"),
29
+ }),
30
+ subjectDays: z
31
+ .object({
32
+ day: z.string().nonempty("Day can't be empty"),
33
+ })
34
+ .array(),
35
+ });
36
+
37
+ export const subjectFormValidator = withZod(subjectSchema);
38
+
39
+ export function SubjectForm({
40
+ defaultValues,
41
+ }: {
42
+ defaultValues?: Partial<z.infer<typeof subjectSchema>>;
43
+ }) {
44
+ let navigate = useNavigate();
45
+ const isSubmitting = useIsSubmitting();
46
+ const [daysKeys, setDaysKeys] = useState(
47
+ defaultValues?.subjectDays && defaultValues.subjectDays.length > 0
48
+ ? Array.from(Array(defaultValues.subjectDays.length).keys())
49
+ : [0]
50
+ );
51
+
52
+ return (
53
+ <Box as="main" py="8" flex="1">
54
+ <Container maxW="7xl" id="xxx">
55
+ <Box bg="white" p="6" rounded="lg" shadow="base">
56
+ <Box px="10" maxWidth="7xl">
57
+ <ValidatedForm
58
+ validator={subjectFormValidator}
59
+ defaultValues={defaultValues}
60
+ method="post"
61
+ noValidate
62
+ >
63
+ <Stack spacing="6" direction="column">
64
+ <Stack direction="row" spacing="6" align="center" width="full">
65
+ <FormInput name="name" label="Name" isRequired />
66
+ <FormInput
67
+ name="description"
68
+ label="Description"
69
+ isRequired
70
+ />
71
+ </Stack>
72
+ <Stack direction="row" spacing="6" align="center" width="full">
73
+ <FormInput
74
+ name="teacher.name"
75
+ label="Teacher Name"
76
+ isRequired
77
+ />
78
+ <FormInput
79
+ name="teacher.email"
80
+ label="Teacher Email"
81
+ isRequired
82
+ />
83
+ </Stack>
84
+ <VStack width="full" spacing="6" alignItems="flex-start">
85
+ {daysKeys.map((key, index) => (
86
+ <Stack direction="row" width="full" key={key}>
87
+ <FormSelect
88
+ name={`subjectDays[${index}].day`}
89
+ label="Subject Day"
90
+ isRequired
91
+ placeholder="Select Day"
92
+ >
93
+ <option value="Monday">Monday</option>
94
+ <option value="Tuesday">Tuesday</option>
95
+ <option value="Wednesday">Wednesday</option>
96
+ <option value="Thursday">Thursday</option>
97
+ <option value="Friday">Friday</option>
98
+ <option value="Saturday">Saturday</option>
99
+ <option value="Sunday">Sunday</option>
100
+ </FormSelect>
101
+ {daysKeys.length > 1 && (
102
+ <Box pt="8">
103
+ <Button
104
+ colorScheme="red"
105
+ onClick={() =>
106
+ setDaysKeys(
107
+ daysKeys.filter(
108
+ (key2, index2) => index !== index2
109
+ )
110
+ )
111
+ }
112
+ >
113
+ Delete
114
+ </Button>
115
+ </Box>
116
+ )}
117
+ </Stack>
118
+ ))}
119
+ <Button
120
+ colorScheme="blue"
121
+ size="xs"
122
+ onClick={() =>
123
+ setDaysKeys([...daysKeys, Math.max(...daysKeys) + 1])
124
+ }
125
+ >
126
+ Add Day
127
+ </Button>
128
+ </VStack>
129
+
130
+ <HStack width="full" justifyContent="center" mt="8">
131
+ <Button
132
+ type="submit"
133
+ colorScheme="blue"
134
+ disabled={isSubmitting}
135
+ isLoading={isSubmitting}
136
+ >
137
+ {isSubmitting ? "Sending..." : "Send"}
138
+ </Button>
139
+ <Button variant="outline" onClick={() => navigate(-1)}>
140
+ Cancel
141
+ </Button>
142
+ </HStack>
143
+ </Stack>
144
+ </ValidatedForm>
145
+ </Box>
146
+ </Box>
147
+ </Container>
148
+ </Box>
149
+ );
150
+ }
@@ -0,0 +1,4 @@
1
+ import { hydrate } from "react-dom";
2
+ import { RemixBrowser } from "remix";
3
+
4
+ hydrate(<RemixBrowser />, document);
@@ -0,0 +1,21 @@
1
+ import { renderToString } from "react-dom/server";
2
+ import { RemixServer } from "remix";
3
+ import type { EntryContext } from "remix";
4
+
5
+ export default function handleRequest(
6
+ request: Request,
7
+ responseStatusCode: number,
8
+ responseHeaders: Headers,
9
+ remixContext: EntryContext
10
+ ) {
11
+ let markup = renderToString(
12
+ <RemixServer context={remixContext} url={request.url} />
13
+ );
14
+
15
+ responseHeaders.set("Content-Type", "text/html");
16
+
17
+ return new Response("<!DOCTYPE html>" + markup, {
18
+ status: responseStatusCode,
19
+ headers: responseHeaders,
20
+ });
21
+ }
@@ -0,0 +1,92 @@
1
+ import { ChakraProvider } from "@chakra-ui/react";
2
+ import {
3
+ Links,
4
+ LiveReload,
5
+ Meta,
6
+ Outlet,
7
+ Scripts,
8
+ ScrollRestoration,
9
+ useCatch,
10
+ } from "remix";
11
+ import { ErrorBox } from "./components/ErrorBox";
12
+
13
+ // https://remix.run/api/conventions#default-export
14
+ // https://remix.run/api/conventions#route-filenames
15
+ export default function App() {
16
+ return (
17
+ <Document>
18
+ <Outlet />
19
+ </Document>
20
+ );
21
+ }
22
+
23
+ // https://remix.run/docs/en/v1/api/conventions#errorboundary
24
+ export function ErrorBoundary({ error }: { error: Error }) {
25
+ console.error(error);
26
+ return (
27
+ <Document title="Error!">
28
+ <ErrorBox title={`There was an error`} description={error.message} />
29
+ </Document>
30
+ );
31
+ }
32
+
33
+ // https://remix.run/docs/en/v1/api/conventions#catchboundary
34
+ export function CatchBoundary() {
35
+ let caught = useCatch();
36
+
37
+ let message;
38
+ switch (caught.status) {
39
+ case 401:
40
+ message = (
41
+ <p>
42
+ Oops! Looks like you tried to visit a page that you do not have access
43
+ to.
44
+ </p>
45
+ );
46
+ break;
47
+ case 404:
48
+ message = (
49
+ <p>Oops! Looks like you tried to visit a page that does not exist.</p>
50
+ );
51
+ break;
52
+
53
+ default:
54
+ throw new Error(caught.data || caught.statusText);
55
+ }
56
+
57
+ return (
58
+ <Document title={`${caught.status} ${caught.statusText}`}>
59
+ <ErrorBox
60
+ title={`${caught.status}: ${caught.statusText}`}
61
+ description={message}
62
+ />
63
+ </Document>
64
+ );
65
+ }
66
+
67
+ function Document({
68
+ children,
69
+ title,
70
+ }: {
71
+ children: React.ReactNode;
72
+ title?: string;
73
+ }) {
74
+ return (
75
+ <html lang="en">
76
+ <head>
77
+ <meta charSet="utf-8" />
78
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
79
+ {title ? <title>{title}</title> : null}
80
+ <Meta />
81
+ <Links />
82
+ </head>
83
+ <body>
84
+ <ChakraProvider>{children}</ChakraProvider>
85
+
86
+ <ScrollRestoration />
87
+ <Scripts />
88
+ {process.env.NODE_ENV === "development" && <LiveReload />}
89
+ </body>
90
+ </html>
91
+ );
92
+ }
@@ -0,0 +1,5 @@
1
+ import { LoaderFunction, redirect } from "remix";
2
+
3
+ export let loader: LoaderFunction = () => {
4
+ return redirect("/subjects");
5
+ };
@@ -0,0 +1,100 @@
1
+ import { Box, Container, Heading } from "@chakra-ui/react";
2
+ import {
3
+ ActionFunction,
4
+ json,
5
+ LoaderFunction,
6
+ redirect,
7
+ useCatch,
8
+ useLoaderData,
9
+ useParams,
10
+ } from "remix";
11
+ import { z } from "zod";
12
+ import { ErrorBox } from "~/components/ErrorBox";
13
+ import { SubjectForm, subjectFormValidator } from "~/components/SubjectForm";
14
+ import { db } from "~/services/db.server";
15
+ import { SubjectComplete } from "~/types";
16
+ import { validationError } from "../../../remix-validated-form";
17
+
18
+ export const loader: LoaderFunction = async ({ params }) => {
19
+ const { id } = z.object({ id: z.string() }).parse(params);
20
+
21
+ const subject = await db.subject.findUnique({
22
+ where: { id: +id },
23
+ include: {
24
+ teacher: true,
25
+ subjectDays: { orderBy: { day: "asc" } },
26
+ },
27
+ });
28
+
29
+ if (!subject) {
30
+ throw new Response(`Subject ${id} doesn't exist`, {
31
+ status: 404,
32
+ });
33
+ }
34
+
35
+ return json(subject);
36
+ };
37
+
38
+ export const action: ActionFunction = async ({ request, params }) => {
39
+ const { id } = z.object({ id: z.string() }).parse(params);
40
+
41
+ const fieldValues = subjectFormValidator.validate(
42
+ Object.fromEntries(await request.formData())
43
+ );
44
+ if (fieldValues.error) return validationError(fieldValues.error);
45
+
46
+ const { teacher, subjectDays, ...updatedSubject } = fieldValues.data;
47
+
48
+ await db.subject.update({
49
+ where: { id: +id },
50
+ data: {
51
+ ...updatedSubject,
52
+ teacher: {
53
+ update: teacher,
54
+ },
55
+ subjectDays: {
56
+ deleteMany: {},
57
+ create: subjectDays,
58
+ },
59
+ },
60
+ });
61
+
62
+ return redirect("/subjects");
63
+ };
64
+
65
+ export default function NewSubject() {
66
+ const subject = useLoaderData<SubjectComplete | null>();
67
+ return (
68
+ <>
69
+ <Box bg="white" pt="4" pb="4" shadow="sm">
70
+ <Container maxW="7xl">
71
+ <Heading size="lg" mb="0">
72
+ Create Subject
73
+ </Heading>
74
+ </Container>
75
+ </Box>
76
+
77
+ <Box as="main" py="8" flex="1">
78
+ <Container maxW="7xl">
79
+ <SubjectForm defaultValues={subject ?? undefined} />
80
+ </Container>
81
+ </Box>
82
+ </>
83
+ );
84
+ }
85
+
86
+ export function CatchBoundary() {
87
+ const caught = useCatch();
88
+ const params = useParams();
89
+ if (caught.status === 404) {
90
+ return <ErrorBox title={`Subject ${params.id} doesn't exist`} />;
91
+ }
92
+ throw new Error(`Unhandled error: ${caught.status}`);
93
+ }
94
+
95
+ export function ErrorBoundary() {
96
+ const { id } = useParams();
97
+ return (
98
+ <ErrorBox title={`There was an error subject by the id ${id}. Sorry.`} />
99
+ );
100
+ }
@@ -0,0 +1,112 @@
1
+ import {
2
+ Box,
3
+ Button,
4
+ Container,
5
+ Flex,
6
+ Heading,
7
+ Spacer,
8
+ Table,
9
+ Tbody,
10
+ Td,
11
+ Th,
12
+ Thead,
13
+ Tr,
14
+ } from "@chakra-ui/react";
15
+ import { Subject, SubjectDays, Teacher } from "@prisma/client";
16
+ import {
17
+ json,
18
+ Link,
19
+ LoaderFunction,
20
+ useCatch,
21
+ useLoaderData,
22
+ useParams,
23
+ } from "remix";
24
+ import { db } from "~/services/db.server";
25
+
26
+ export const loader: LoaderFunction = async () => {
27
+ const subjects = await db.subject.findMany({
28
+ include: { teacher: true, subjectDays: true },
29
+ });
30
+ return json(subjects);
31
+ };
32
+
33
+ export default function Subjects() {
34
+ const subjects =
35
+ useLoaderData<
36
+ (Subject & { teacher: Teacher; subjectDays: SubjectDays[] })[]
37
+ >();
38
+ return (
39
+ <>
40
+ <Box bg="white" pt="4" pb="4" shadow="sm">
41
+ <Container maxW="7xl">
42
+ <Flex>
43
+ <Heading size="lg" mb="0">
44
+ Subjects
45
+ </Heading>
46
+ <Spacer />
47
+ <Link to="new">
48
+ <Button colorScheme="blue">New</Button>
49
+ </Link>
50
+ </Flex>
51
+ </Container>
52
+ </Box>
53
+
54
+ <Box as="main" py="8" flex="1">
55
+ <Container maxW="7xl">
56
+ <Box bg="white" p="6" rounded="lg" shadow="base" overflowX="auto">
57
+ <Table borderWidth="1px" fontSize="sm">
58
+ <Thead bg="white">
59
+ <Tr>
60
+ <Th whiteSpace="nowrap" scope="col">
61
+ Subject
62
+ </Th>
63
+ <Th whiteSpace="nowrap" scope="col">
64
+ Teacher
65
+ </Th>
66
+ <Th whiteSpace="nowrap" scope="col"></Th>
67
+ </Tr>
68
+ </Thead>
69
+ <Tbody>
70
+ {subjects.map((subject) => (
71
+ <Tr key={subject.id}>
72
+ <Td whiteSpace="nowrap">{subject.name}</Td>
73
+ <Td>
74
+ {subject.teacher.name} ({subject.teacher.email})
75
+ </Td>
76
+ <Td textAlign="right">
77
+ <Link to={`${subject.id}/edit`}>
78
+ <Button variant="link" colorScheme="blue">
79
+ Edit
80
+ </Button>
81
+ </Link>
82
+ </Td>
83
+ </Tr>
84
+ ))}
85
+ </Tbody>
86
+ </Table>
87
+ </Box>
88
+ </Container>
89
+ </Box>
90
+ </>
91
+ );
92
+ }
93
+
94
+ export function CatchBoundary() {
95
+ const caught = useCatch();
96
+ const params = useParams();
97
+ if (caught.status === 404) {
98
+ return (
99
+ <div className="error-container">
100
+ Huh? What the heck is "{params.id}"?
101
+ </div>
102
+ );
103
+ }
104
+ throw new Error(`Unhandled error: ${caught.status}`);
105
+ }
106
+
107
+ export function ErrorBoundary() {
108
+ const { jokeId } = useParams();
109
+ return (
110
+ <div className="error-container">{`There was an error loading joke by the id ${jokeId}. Sorry.`}</div>
111
+ );
112
+ }