├── .gitignore ├── .storybook ├── main.js └── preview.js ├── Development.md ├── LICENSE ├── README.md ├── example ├── .npmignore ├── index.html ├── index.tsx ├── package.json └── tsconfig.json ├── package.json ├── src ├── .prettierrc ├── ZodFormFactories.tsx ├── ZodFormInner.tsx ├── ZodFormSection.tsx ├── ZodFormikContainer.ts ├── bits.tsx ├── index.tsx └── utils.ts ├── stories ├── ZodForm.stories.tsx └── index.css ├── test └── blah.test.tsx ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | .DS_Store 3 | node_modules 4 | .cache 5 | dist 6 | storybook-static -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | stories: ['../stories/**/*.stories.@(ts|tsx|js|jsx)'], 3 | addons: ['@storybook/addon-links', '@storybook/addon-essentials'], 4 | // https://storybook.js.org/docs/react/configure/typescript#mainjs-configuration 5 | typescript: { 6 | check: true, // type-check stories during Storybook build 7 | }, 8 | }; 9 | -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | // https://storybook.js.org/docs/react/writing-stories/parameters#global-parameters 2 | export const parameters = { 3 | // https://storybook.js.org/docs/react/essentials/actions#automatically-matching-args 4 | actions: { argTypesRegex: '^on.*' }, 5 | }; 6 | -------------------------------------------------------------------------------- /Development.md: -------------------------------------------------------------------------------- 1 | # TSDX React w/ Storybook User Guide 2 | 3 | Congrats! You just saved yourself hours of work by bootstrapping this project with TSDX. Let’s get you oriented with what’s here and how to use it. 4 | 5 | > This TSDX setup is meant for developing React component libraries (not apps!) that can be published to NPM. If you’re looking to build a React-based app, you should use `create-react-app`, `razzle`, `nextjs`, `gatsby`, or `react-static`. 6 | 7 | > If you’re new to TypeScript and React, checkout [this handy cheatsheet](https://github.com/sw-yx/react-typescript-cheatsheet/) 8 | 9 | ## Commands 10 | 11 | TSDX scaffolds your new library inside `/src`, and also sets up a [Parcel-based](https://parceljs.org) playground for it inside `/example`. 12 | 13 | The recommended workflow is to run TSDX in one terminal: 14 | 15 | ```bash 16 | npm start # or yarn start 17 | ``` 18 | 19 | This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`. 20 | 21 | Then run either Storybook or the example playground: 22 | 23 | ### Storybook 24 | 25 | Run inside another terminal: 26 | 27 | ```bash 28 | yarn storybook 29 | ``` 30 | 31 | This loads the stories from `./stories`. 32 | 33 | > NOTE: Stories should reference the components as if using the library, similar to the example playground. This means importing from the root project directory. This has been aliased in the tsconfig and the storybook webpack config as a helper. 34 | 35 | ### Example 36 | 37 | Then run the example inside another: 38 | 39 | ```bash 40 | cd example 41 | npm i # or yarn to install dependencies 42 | npm start # or yarn start 43 | ``` 44 | 45 | The default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure TSDX is running in watch mode like we recommend above. **No symlinking required**, we use [Parcel's aliasing](https://parceljs.org/module_resolution.html#aliases). 46 | 47 | To do a one-off build, use `npm run build` or `yarn build`. 48 | 49 | To run tests, use `npm test` or `yarn test`. 50 | 51 | ## Configuration 52 | 53 | Code quality is set up for you with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields in `package.json` accordingly. 54 | 55 | ### Jest 56 | 57 | Jest tests are set up to run with `npm test` or `yarn test`. 58 | 59 | ### Bundle analysis 60 | 61 | Calculates the real cost of your library using [size-limit](https://github.com/ai/size-limit) with `npm run size` and visulize it with `npm run analyze`. 62 | 63 | #### Setup Files 64 | 65 | This is the folder structure we set up for you: 66 | 67 | ```txt 68 | /example 69 | index.html 70 | index.tsx # test your component here in a demo app 71 | package.json 72 | tsconfig.json 73 | /src 74 | index.tsx # EDIT THIS 75 | /test 76 | blah.test.tsx # EDIT THIS 77 | /stories 78 | Thing.stories.tsx # EDIT THIS 79 | /.storybook 80 | main.js 81 | preview.js 82 | .gitignore 83 | package.json 84 | README.md # EDIT THIS 85 | tsconfig.json 86 | ``` 87 | 88 | #### React Testing Library 89 | 90 | We do not set up `react-testing-library` for you yet, we welcome contributions and documentation on this. 91 | 92 | ### Rollup 93 | 94 | TSDX uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details. 95 | 96 | ### TypeScript 97 | 98 | `tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your needs. 99 | 100 | ## Continuous Integration 101 | 102 | ### GitHub Actions 103 | 104 | Two actions are added by default: 105 | 106 | - `main` which installs deps w/ cache, lints, tests, and builds on all pushes against a Node and OS matrix 107 | - `size` which comments cost comparison of your library on every pull request using [size-limit](https://github.com/ai/size-limit) 108 | 109 | ## Optimizations 110 | 111 | Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know that you can take advantage of development-only optimizations: 112 | 113 | ```js 114 | // ./types/index.d.ts 115 | declare var __DEV__: boolean; 116 | 117 | // inside your code... 118 | if (__DEV__) { 119 | console.log('foo'); 120 | } 121 | ``` 122 | 123 | You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant) and [warning](https://github.com/palmerhq/tsdx#warning) functions. 124 | 125 | ## Module Formats 126 | 127 | CJS, ESModules, and UMD module formats are supported. 128 | 129 | The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found. 130 | 131 | ## Deploying the Example Playground 132 | 133 | The Playground is just a simple [Parcel](https://parceljs.org) app, you can deploy it anywhere you would normally deploy that. Here are some guidelines for **manually** deploying with the Netlify CLI (`npm i -g netlify-cli`): 134 | 135 | ```bash 136 | cd example # if not already in the example folder 137 | npm run build # builds to dist 138 | netlify deploy # deploy the dist folder 139 | ``` 140 | 141 | Alternatively, if you already have a git repo connected, you can set up continuous deployment with Netlify: 142 | 143 | ```bash 144 | netlify init 145 | # build command: yarn build && cd example && yarn && yarn build 146 | # directory to deploy: example/dist 147 | # pick yes for netlify.toml 148 | ``` 149 | 150 | ## Named Exports 151 | 152 | Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library. 153 | 154 | ## Including Styles 155 | 156 | There are many ways to ship styles, including with CSS-in-JS. TSDX has no opinion on this, configure how you like. 157 | 158 | For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so that it can be imported separately by your users and run through their bundler's loader. 159 | 160 | ## Publishing to NPM 161 | 162 | We recommend using [np](https://github.com/sindresorhus/np). 163 | 164 | ## Usage with Lerna 165 | 166 | When creating a new package with TSDX within a project set up with Lerna, you might encounter a `Cannot resolve dependency` error when trying to run the `example` project. To fix that you will need to make changes to the `package.json` file _inside the `example` directory_. 167 | 168 | The problem is that due to the nature of how dependencies are installed in Lerna projects, the aliases in the example project's `package.json` might not point to the right place, as those dependencies might have been installed in the root of your Lerna project. 169 | 170 | Change the `alias` to point to where those packages are actually installed. This depends on the directory structure of your Lerna project, so the actual path might be different from the diff below. 171 | 172 | ```diff 173 | "alias": { 174 | - "react": "../node_modules/react", 175 | - "react-dom": "../node_modules/react-dom" 176 | + "react": "../../../node_modules/react", 177 | + "react-dom": "../../../node_modules/react-dom" 178 | }, 179 | ``` 180 | 181 | An alternative to fixing this problem would be to remove aliases altogether and define the dependencies referenced as aliases as dev dependencies instead. [However, that might cause other problems.](https://github.com/palmerhq/tsdx/issues/64) 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 7frank 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zod-form 2 | 3 | Generate forms from zod.js schemas 4 | 5 | Note: forms are hard - only a case study as of now 6 | 7 | see it in action at https://7frank.github.io/zod-form/?path=/docs/welcome--a-form-with-two-sections 8 | 9 | ```typescript 10 | const firstSchema = z.object({ 11 | name: z.string().min(3), 12 | category: z.enum(['freelancer', 'student', 'company']), 13 | isActive: z.boolean(), 14 | numberOfParticipants: z.number().min(1), 15 | }); 16 | 17 | const firstSchemaTranslation = dummyFormTranslation( 18 | 'name', 19 | 'category', 20 | 'isActive', 21 | 'numberOfParticipants' 22 | ); 23 | 24 | export function AFormWithTwoSections() { 25 | const [data, setData] = useState(); 26 | return ( 27 | <> 28 | 29 | ZodFormFactories}, 36 | > 37 | 38 |
 data: {JSON.stringify(data, null, '  ')}
39 | 40 | ); 41 | } 42 | ``` 43 | 44 | override the default cell factories with your own implementation via 45 | 46 | ``` 47 | ... 48 | factories={() => ZodFormFactories}, 49 | ... 50 | ``` 51 | 52 | # Development 53 | 54 | [Development](./Development.md) 55 | -------------------------------------------------------------------------------- /example/.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .cache 3 | dist -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Playground 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /example/index.tsx: -------------------------------------------------------------------------------- 1 | import 'react-app-polyfill/ie11'; 2 | import * as React from 'react'; 3 | import * as ReactDOM from 'react-dom'; 4 | import { Thing } from '../.'; 5 | 6 | const App = () => { 7 | return ( 8 |
9 | 10 |
11 | ); 12 | }; 13 | 14 | ReactDOM.render(, document.getElementById('root')); 15 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "license": "MIT", 6 | "scripts": { 7 | "start": "parcel index.html", 8 | "build": "parcel build index.html" 9 | }, 10 | "dependencies": { 11 | "react-app-polyfill": "^1.0.0" 12 | }, 13 | "alias": { 14 | "react": "../node_modules/react", 15 | "react-dom": "../node_modules/react-dom/profiling", 16 | "scheduler/tracing": "../node_modules/scheduler/tracing-profiling" 17 | }, 18 | "devDependencies": { 19 | "@types/react": "^16.9.11", 20 | "@types/react-dom": "^16.8.4", 21 | "parcel": "^1.12.3", 22 | "typescript": "^3.4.5" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": false, 4 | "target": "es5", 5 | "module": "commonjs", 6 | "jsx": "react", 7 | "moduleResolution": "node", 8 | "noImplicitAny": false, 9 | "noUnusedLocals": false, 10 | "noUnusedParameters": false, 11 | "removeComments": true, 12 | "strictNullChecks": true, 13 | "preserveConstEnums": true, 14 | "sourceMap": true, 15 | "lib": ["es2015", "es2016", "dom"], 16 | "types": ["node"] 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.1.0", 3 | "license": "MIT", 4 | "main": "dist/index.js", 5 | "typings": "dist/index.d.ts", 6 | "homepage": "http://7frank.github.io/zod-form", 7 | "files": [ 8 | "dist", 9 | "src" 10 | ], 11 | "engines": { 12 | "node": ">=10" 13 | }, 14 | "scripts": { 15 | "start": "tsdx watch", 16 | "build": "tsdx build", 17 | "format": "prettier --write .", 18 | "test": "tsdx test --passWithNoTests", 19 | "lint": "tsdx lint", 20 | "prepare": "tsdx build", 21 | "size": "size-limit", 22 | "analyze": "size-limit --why", 23 | "storybook": "start-storybook -p 6006", 24 | "build-storybook": "build-storybook", 25 | "predeploy": "npm run build-storybook", 26 | "deploy-storybook": "gh-pages -d storybook-static" 27 | }, 28 | "peerDependencies": { 29 | "react": ">=16" 30 | }, 31 | "husky": { 32 | "hooks": { 33 | "pre-commit": "tsdx lint" 34 | } 35 | }, 36 | "prettier": { 37 | "printWidth": 80, 38 | "semi": true, 39 | "singleQuote": true, 40 | "trailingComma": "es5" 41 | }, 42 | "name": "zod-form", 43 | "author": "7frank", 44 | "module": "dist/zod-form.esm.js", 45 | "size-limit": [ 46 | { 47 | "path": "dist/zod-form.cjs.production.min.js", 48 | "limit": "10 KB" 49 | }, 50 | { 51 | "path": "dist/zod-form.esm.js", 52 | "limit": "10 KB" 53 | } 54 | ], 55 | "devDependencies": { 56 | "@babel/core": "^7.17.5", 57 | "@size-limit/preset-small-lib": "^7.0.8", 58 | "@storybook/addon-essentials": "^6.4.19", 59 | "@storybook/addon-info": "^5.3.21", 60 | "@storybook/addon-links": "^6.4.19", 61 | "@storybook/addons": "^6.4.19", 62 | "@storybook/react": "^6.4.19", 63 | "@types/react": "^17.0.40", 64 | "@types/react-dom": "^17.0.13", 65 | "babel-loader": "^8.2.3", 66 | "classnames": "^2.3.1", 67 | "focus-formik-error": "^1.1.0", 68 | "formik": "^2.2.9", 69 | "gh-pages": "^3.2.3", 70 | "husky": "^7.0.4", 71 | "react": "^17.0.2", 72 | "react-dom": "^17.0.2", 73 | "react-is": "^17.0.2", 74 | "size-limit": "^7.0.8", 75 | "tsdx": "^0.14.1", 76 | "tslib": "^2.3.1", 77 | "typescript": "^4.6.2", 78 | "unstated-next": "^1.1.0", 79 | "zod": "^3.13.4", 80 | "zod-formik-adapter": "^1.0.2" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /src/ZodFormFactories.tsx: -------------------------------------------------------------------------------- 1 | import classnames from 'classnames'; 2 | import { FormikProps } from 'formik'; 3 | import React from 'react'; 4 | import { ReactNode } from 'react'; 5 | import { ZodFirstPartyTypeKind } from 'zod'; 6 | import { computeFormElementState } from './utils'; 7 | 8 | export type FactoryType = { 9 | index: number; 10 | disabled?: boolean; 11 | label: ReactNode; 12 | placeholder?: string; 13 | formikValues: FormikProps; 14 | name: keyof T; 15 | /** 16 | * Potential values. For now only string | number are supported. 17 | */ 18 | values?: (string | number)[]; 19 | type: ZodFirstPartyTypeKind; 20 | }; 21 | 22 | export type FactoriesRecord = Partial< 23 | Record< 24 | ZodFirstPartyTypeKind | 'DEFAULT', 25 | (props: FactoryType) => ReactNode 26 | > 27 | >; 28 | 29 | export const ZodFormFactories = { 30 | DEFAULT: defaultCellFactory, 31 | ZodEnum: enumCellFactory, 32 | ZodBoolean: booleanCellFactory, 33 | }; 34 | 35 | export function enumCellFactory({ 36 | formikValues, 37 | index, 38 | label, 39 | name, 40 | type, 41 | disabled, 42 | placeholder, 43 | values, 44 | }: FactoryType) { 45 | const { indicateError, indicateSuccess } = computeFormElementState( 46 | formikValues, 47 | name, 48 | disabled, 49 | true 50 | ); 51 | return ( 52 |
53 | 62 | 75 |
{indicateError && <>{formikValues.errors[name]}}
76 |
77 | ); 78 | } 79 | 80 | export function booleanCellFactory({ 81 | formikValues, 82 | index, 83 | label, 84 | name, 85 | type, 86 | disabled, 87 | placeholder, 88 | values, 89 | }: FactoryType) { 90 | const { indicateError, indicateSuccess } = computeFormElementState( 91 | formikValues, 92 | name, 93 | disabled, 94 | true 95 | ); 96 | return ( 97 |
98 | 107 | { 112 | formikValues.setFieldValue(name.toString(), e.target?.checked); 113 | }} 114 | checked={Boolean(formikValues.values[name] as any)} 115 | /> 116 |
{indicateError && <>{formikValues.errors[name]}}
117 |
118 | ); 119 | } 120 | 121 | /** 122 | * This is our default form element factory, which is used when no other factory is specified. 123 | */ 124 | export function defaultCellFactory({ 125 | formikValues, 126 | index, 127 | label, 128 | name, 129 | type, 130 | disabled, 131 | placeholder, 132 | values, 133 | }: FactoryType) { 134 | const { indicateError, indicateSuccess } = computeFormElementState( 135 | formikValues, 136 | name, 137 | disabled, 138 | true 139 | ); 140 | 141 | return ( 142 |
143 | 152 | { 156 | const val = e.target?.value; 157 | formikValues.setFieldValue( 158 | name.toString(), 159 | type == 'ZodNumber' ? Number(val) : val 160 | ); 161 | }} 162 | placeholder={placeholder} 163 | type={type == 'ZodNumber' ? 'number' : 'text'} 164 | value={formikValues.values[name] as any} 165 | /> 166 |
{indicateError && <>{formikValues.errors[name]}}
167 |
168 | ); 169 | } 170 | -------------------------------------------------------------------------------- /src/ZodFormInner.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | 3 | import { ZodFormikContainer } from './ZodFormikContainer'; 4 | 5 | export interface ZodFormProps { 6 | children: ReactNode; 7 | onSubmit?: (values: any) => void; 8 | disabled?: boolean; 9 | } 10 | 11 | export function ZodFormInner({ 12 | children, 13 | onSubmit, 14 | disabled = false, 15 | }: ZodFormProps) { 16 | const { sections, submitForm } = ZodFormikContainer.useContainer(); 17 | 18 | return ( 19 | <> 20 | {children} 21 | {!disabled && ( 22 |
23 | 24 | {' '} 33 | Connected forms: {Object.keys(sections).join(',')} 34 |
35 | )} 36 | 37 | ); 38 | } 39 | -------------------------------------------------------------------------------- /src/ZodFormSection.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useMemo, useState } from 'react'; 2 | import { FocusError } from 'focus-formik-error'; 3 | import { useFormik } from 'formik'; 4 | import { ZodArray, ZodObject, ZodObjectDef, ZodRawShape } from 'zod'; 5 | import { 6 | FactoriesRecord, 7 | FactoryType, 8 | ZodFormFactories, 9 | } from './ZodFormFactories'; 10 | import { toFormikValidationSchema } from 'zod-formik-adapter'; 11 | import { Missing } from './bits'; 12 | import { ZodFormikContainer } from './ZodFormikContainer'; 13 | 14 | export type GenericFormTranslation = Record< 15 | keyof T, 16 | { label: string; description: string } 17 | >; 18 | 19 | export interface ZodFormSectionProps { 20 | disabled?: boolean; 21 | 22 | initialValues: Partial; 23 | translation: GenericFormTranslation; 24 | onValidate?: (isValid: boolean, values: T) => void; 25 | schema: ZodObject | ZodArray>; 26 | factories?: (defaults: FactoriesRecord) => FactoriesRecord; 27 | className?: string; 28 | sectionName: string; 29 | } 30 | 31 | /** 32 | * This form uses the translations to create one input field per translation element. You need to make sure that your translations match your zod-schema. 33 | * Note: This is no jack of all trades frm implementation. If any it is sufficient for nrarrow scenarios where flat objects contains enums, numbers, text, or boolean. 34 | * 35 | * This form should only provide input fields for top level schema keys. 36 | * Nested data is currently out-of-scope and should be created handled separately. 37 | * 38 | * TODO we could unify the S,T generic type parameters by either using a factory and infering the type as below or possibly other means 39 | e.g. type TestType = z.infer; 40 | * TODO add sections = Record 41 | */ 42 | export function ZodFormSection({ 43 | disabled = false, 44 | schema, 45 | initialValues = {}, 46 | onValidate, 47 | translation, 48 | factories = () => ZodFormFactories, 49 | className, 50 | sectionName, 51 | }: ZodFormSectionProps) { 52 | const { registerSection } = ZodFormikContainer.useContainer(); 53 | 54 | const formikValues = useFormik({ 55 | validationSchema: toFormikValidationSchema(schema), 56 | initialValues: initialValues as T, 57 | onSubmit: (v) => { 58 | // Note: will not be used 59 | }, 60 | }); 61 | 62 | useEffect(() => { 63 | if (formikValues) registerSection(sectionName, { formik: formikValues }); 64 | }, [formikValues]); 65 | 66 | // we currently only support forms that have an object shape as top level as other less complex forms are out of scope 67 | const canBeInitialized = schema._def.typeName == 'ZodObject'; 68 | 69 | if (!canBeInitialized) 70 | return ( 71 | <>Form cannot be initialized. Schema root node must be a zod-object 72 | ); 73 | 74 | const _factories = factories({}); 75 | // select a factory to render form elements 76 | function pickFromFactory(props: FactoryType) { 77 | const f = _factories[props.type] ?? _factories['DEFAULT']; 78 | return f ? f(props) : <>; 79 | } 80 | 81 | return ( 82 |
83 |
84 | 85 | {Object.keys(translation).map((key, index) => { 86 | const name = key as keyof T; 87 | 88 | const shape = (schema._def as any)?.shape(); 89 | 90 | // TODO leverage error rendering to options 91 | if (!shape[name]) { 92 | return ; 93 | } 94 | const _def = shape[name]._def; 95 | const type = (_def as ZodObjectDef).typeName; 96 | const otherPotentialValues = _def.values; 97 | 98 | // TODO try to leverage this functionality to only occur when status changes onValidationStatusChange instead 99 | onValidate?.(formikValues.isValid, formikValues.values); 100 | 101 | return pickFromFactory({ 102 | index, 103 | values: otherPotentialValues, 104 | type, 105 | disabled, 106 | label: translation[name].label, 107 | formikValues, 108 | name: name as any, 109 | placeholder: translation[name].description, 110 | }); 111 | })} 112 |
113 |
114 | ); 115 | } 116 | -------------------------------------------------------------------------------- /src/ZodFormikContainer.ts: -------------------------------------------------------------------------------- 1 | import { FormikValues } from 'formik'; 2 | import { useState } from 'react'; 3 | 4 | import { createContainer } from 'unstated-next'; 5 | 6 | export type Section = { 7 | formik: FormikValues; 8 | }; 9 | 10 | async function submitForm(sections: Record) { 11 | return Promise.all( 12 | Object.entries(sections).map(([name, section]) => 13 | section.formik.submitForm().then(() => { 14 | return { section: name, values: section.formik.values }; 15 | }) 16 | ) 17 | ); 18 | } 19 | 20 | function useZodFormik() { 21 | let [sections, setSections] = useState>({}); 22 | const registerSection = (key: string, section: Section) => 23 | (sections[key] = section); 24 | // setSections((s) => ({ ...s, [key]: section })); 25 | 26 | return { sections, registerSection, submitForm: () => submitForm(sections) }; 27 | } 28 | 29 | export const ZodFormikContainer = createContainer(useZodFormik); 30 | -------------------------------------------------------------------------------- /src/bits.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export function Missing({ name }: { name: string | number | symbol }) { 4 | return ( 5 | <> 6 | {process.env.NODE_ENV == 'development' && ( 7 | 8 | could not create form element for name:{name} (are your "validators" 9 | missing keys that are defined in "translations") 10 | 11 | )} 12 | 13 | ); 14 | } 15 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import { ZodFormInner, ZodFormProps } from './ZodFormInner'; 4 | import { ZodFormikContainer } from './ZodFormikContainer'; 5 | 6 | export function ZodForm(props: ZodFormProps) { 7 | return ( 8 | 9 | 10 | 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { FormikValues } from 'formik'; 2 | 3 | type Severity = 'success' | 'danger' | undefined; 4 | 5 | export function computeFormElementState( 6 | { touched, submitCount, errors }: FormikValues, 7 | name: keyof T, 8 | disabled?: boolean, 9 | strictType: boolean = false 10 | ): { 11 | severity: Severity; 12 | indicateSuccess: boolean; 13 | indicateError: boolean; 14 | } { 15 | const shouldValidate = touched[name] || submitCount > 0; 16 | 17 | const hasError = strictType 18 | ? errors[name] !== undefined 19 | : errors[name] != undefined; 20 | 21 | function isValid() { 22 | return !disabled ? shouldValidate && !hasError : false; 23 | } 24 | 25 | function isInvalid() { 26 | return !disabled ? shouldValidate && hasError : false; 27 | } 28 | 29 | return { 30 | severity: !shouldValidate ? undefined : isValid() ? 'success' : 'danger', 31 | indicateSuccess: isValid(), 32 | indicateError: isInvalid(), 33 | }; 34 | } 35 | 36 | export function dummyFormTranslation( 37 | ...keys: (keyof T)[] 38 | ): Record { 39 | const res: any = {}; 40 | 41 | keys.forEach((k) => { 42 | res[k] = { 43 | label: k, 44 | description: 'enter a ' + k, 45 | }; 46 | }); 47 | 48 | return res; 49 | } 50 | -------------------------------------------------------------------------------- /stories/ZodForm.stories.tsx: -------------------------------------------------------------------------------- 1 | import React, { Props, useState } from 'react'; 2 | import { Meta, Story } from '@storybook/react'; 3 | import { ZodForm } from '../src'; 4 | import { ZodFormSection } from '../src/ZodFormSection'; 5 | import { z } from 'zod'; 6 | import { dummyFormTranslation } from '../src/utils'; 7 | import './index.css'; 8 | 9 | const meta: Meta = { 10 | title: 'Welcome', 11 | component: ZodFormSection, 12 | parameters: {}, 13 | }; 14 | 15 | export default meta; 16 | 17 | const Template: Story = (args) =>
; 18 | 19 | // By passing using the Args format for exported stories, you can control the props for a component for reuse in a test 20 | // https://storybook.js.org/docs/react/workflows/unit-testing 21 | export const Default = Template.bind({}); 22 | 23 | Default.args = {}; 24 | 25 | const firstSchema = z.object({ 26 | name: z.string().min(3), 27 | category: z.enum(['freelancer', 'student', 'company']), 28 | isActive: z.boolean(), 29 | numberOfParticipants: z.number().min(1), 30 | }); 31 | 32 | const secondSchema = z.object({ 33 | isCookieConsent: z.boolean(), 34 | }); 35 | 36 | const firstSchemaTranslation = dummyFormTranslation( 37 | 'name', 38 | 'category', 39 | 'isActive', 40 | 'numberOfParticipants' 41 | ); 42 | 43 | const secondSchemaTranslation = dummyFormTranslation('isCookieConsent'); 44 | 45 | export function AFormWithTwoSections() { 46 | const [data, setData] = useState(); 47 | 48 | return ( 49 | <> 50 | { 52 | console.log('submitting'); 53 | setData(values); 54 | }} 55 | > 56 | console.log('validating section1', ...args)} 68 | schema={firstSchema} 69 | > 70 | console.log('validating section2', ...args)} 77 | schema={secondSchema} 78 | > 79 | 80 |
{JSON.stringify(data, null, '  ')}
81 | 82 | ); 83 | } 84 | -------------------------------------------------------------------------------- /stories/index.css: -------------------------------------------------------------------------------- 1 | label { 2 | font-weight: bold; 3 | display: block; 4 | } 5 | 6 | .grid { 7 | display: grid; 8 | grid-template-columns: 1fr 1fr 1fr; 9 | } 10 | 11 | .grid > div { 12 | margin: 1em; 13 | } 14 | 15 | .danger { 16 | color: red; 17 | } 18 | 19 | .success { 20 | color: lightgreen; 21 | } 22 | 23 | .neutral { 24 | color: lightgreen; 25 | } 26 | -------------------------------------------------------------------------------- /test/blah.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import * as ReactDOM from 'react-dom'; 3 | import { Default as Thing } from '../stories/Thing.stories'; 4 | 5 | describe('Thing', () => { 6 | it('renders without crashing', () => { 7 | const div = document.createElement('div'); 8 | ReactDOM.render(, div); 9 | ReactDOM.unmountComponentAtNode(div); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": ["src", "types"], 4 | "compilerOptions": { 5 | "module": "esnext", 6 | "lib": ["dom", "esnext"], 7 | "importHelpers": true, 8 | // output .d.ts declaration files for consumers 9 | "declaration": true, 10 | // output .js.map sourcemap files for consumers 11 | "sourceMap": true, 12 | // match output dir to input dir. e.g. dist/index instead of dist/src/index 13 | "rootDir": "./src", 14 | // stricter type-checking for stronger correctness. Recommended by TS 15 | "strict": true, 16 | // linter checks for common issues 17 | "noImplicitReturns": true, 18 | "noFallthroughCasesInSwitch": true, 19 | // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative 20 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | // use Node's module resolution algorithm, instead of the legacy TS one 23 | "moduleResolution": "node", 24 | // transpile JSX to React.createElement 25 | "jsx": "react", 26 | // interop between ESM and CJS modules. Recommended by TS 27 | "esModuleInterop": true, 28 | // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS 29 | "skipLibCheck": true, 30 | // error out if import and file system have a casing mismatch. Recommended by TS 31 | "forceConsistentCasingInFileNames": true, 32 | // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` 33 | "noEmit": true 34 | } 35 | } 36 | --------------------------------------------------------------------------------