├── .gitignore ├── LICENSE ├── README.md ├── index.ts ├── package.json ├── packages └── example │ ├── app │ ├── bouncer.ts │ ├── root.tsx │ └── routes │ │ ├── _index.tsx │ │ └── api.ts │ ├── package.json │ ├── public │ └── favicon.ico │ ├── remix.config.js │ ├── remix.env.d.ts │ └── tsconfig.json ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── src ├── hooks │ ├── use-action.tsx │ └── use-on-resolve.ts ├── server │ ├── api-responses.server.ts │ ├── data-function-helpers.server.ts │ └── helpers.server.ts ├── unstyled-components │ └── input-helper.tsx └── utils │ ├── from-promise.ts │ ├── get-rem-fetcher-state.ts │ └── options-from-zod-shape-def.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | 4 | packages/example/.cache 5 | packages/example/build 6 | packages/example/public/build 7 | 8 | .env 9 | .DS_Store 10 | 11 | yarn.lock 12 | package-lock.json -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Sam Cook 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Remix Easy Mode 2 | 3 | Simple, typesafe toolkit for developing highly interactive Remix apps 4 | 5 | ## Features 6 | 7 | - 100% typesafe 8 | - Built on zod 9 | - Inspired by TRPC 10 | - Designed for building highly interactive apps 11 | - Bone-simple client form validations 12 | - Server-side input validations _a la_ TRPC 13 | - Session middleware via "bouncer" pattern 14 | - `onSuccess`, `onError`, and `onSettled` mutation callbacks _a la_ react-query 15 | - Input helpers are unstyled (and polymorphic, if you want to supply your own input components) 16 | - Optional custom serializers (_e.g._, `superjson`) 17 | - MIT licensed 18 | 19 | ## Installation 20 | 21 | ```bash 22 | npm i remix-easy-mode zod 23 | ``` 24 | 25 | ## Usage 26 | 27 | ### Resource Route 28 | 29 | ```tsx 30 | import type { DataFunctionArgs } from "@remix-run/server-runtime" 31 | import { dataFunctionHelper, useAction } from "remix-easy-mode" 32 | import { z } from "zod" 33 | 34 | const schema = z.object({ 35 | someUserInput: z.string(), 36 | }) 37 | 38 | // this is like a TRPC procedure 39 | export const action = (ctx: DataFunctionArgs) => { 40 | return dataFunctionHelper({ 41 | ctx, 42 | schema, 43 | bouncer: async ({ ctx, csrfToken }) => { 44 | // (1) throw error or (2) return user session 45 | }, 46 | fn: async ({ input, session }) => console.log({ input, session }), // typesafe!, 47 | }) 48 | } 49 | 50 | // return hook from your resource route to use on client 51 | export function useExample() { 52 | return useAction({ 53 | path: "/resource-route", 54 | schema, 55 | onSuccess: (res) => console.log(res), // typesafe!, 56 | }) 57 | } 58 | ``` 59 | 60 | ### Client-side Form 61 | 62 | ```tsx 63 | import { InputHelper } from "remix-easy-mode" 64 | import { useExample } from "./resource-route" 65 | import { StyledInput } from "./your-custom-input-component" 66 | 67 | export default function Index() { 68 | const { Form, fields } = useExample() 69 | 70 | return ( 71 |
72 |
console.log(res)} // typesafe! 75 | > 76 | 77 | 78 | 79 | 80 |
81 | ) 82 | } 83 | ``` 84 | 85 | ## Example App 86 | 87 | To run the example app: 88 | 89 | ```bash 90 | pnpm install 91 | cd packages/example 92 | pnpm run dev 93 | ``` 94 | 95 | Then visit `localhost:3000`. 96 | 97 | ## Peer Dependencies 98 | 99 | `react`, `@remix-run/react`, `@remix-run/server-runtime`, `zod` 100 | 101 | ## Disclaimer 102 | 103 | This is a work in progress. It's not yet battle-tested, and the pre-1.0.0 API will change without notice. If you want to use this in production, be careful, and set your dependency to a specific version. 104 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | // utils 2 | export * from "./src/utils/get-rem-fetcher-state" 3 | 4 | // hooks 5 | export * from "./src/hooks/use-action" 6 | export * from "./src/hooks/use-on-resolve" 7 | 8 | // server 9 | export * from "./src/server/data-function-helpers.server" 10 | 11 | // unstyled-components 12 | export * from "./src/unstyled-components/input-helper" 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "remix-easy-mode", 3 | "version": "0.2.2", 4 | "author": { 5 | "name": "Sam Cook", 6 | "email": "email@samcook.cc", 7 | "url": "https://samcook.cc" 8 | }, 9 | "license": "MIT", 10 | "description": "Opinionated toolkit for developing highly interactive, typesafe Remix apps. Built with zod, and inspired by the TRPC / React Query DX. Provides automatic client and server-side form validations, typesafe form input fields, automatic error handling and easy-to-display error messages, typesafe session middleware support, typesafe session and input values in server-side functions, and typesafe form input values and fetcher responses in client-side hooks and components.", 11 | "main": "dist/index.js", 12 | "module": "dist/index.mjs", 13 | "types": "dist/index.d.ts", 14 | "files": [ 15 | "dist" 16 | ], 17 | "dependencies": { 18 | "@kiruna/form-data": "0.0.0-alpha.31" 19 | }, 20 | "devDependencies": { 21 | "@remix-run/eslint-config": "^2.2.0", 22 | "@remix-run/react": "^2.2.0", 23 | "@remix-run/server-runtime": "^2.2.0", 24 | "@types/react": "^18.2.33", 25 | "eslint": "^8.52.0", 26 | "react": "^18.2.0", 27 | "rimraf": "^5.0.5", 28 | "tsup": "^7.2.0", 29 | "typescript": "^5.2.2", 30 | "zod": "^3.22.4" 31 | }, 32 | "peerDependencies": { 33 | "@remix-run/react": ">=2.0.0", 34 | "@remix-run/server-runtime": ">=2.0.0", 35 | "react": ">=18", 36 | "zod": ">=3" 37 | }, 38 | "scripts": { 39 | "dev": "rimraf dist && tsup index.ts --format cjs,esm --dts --watch", 40 | "build": "rimraf dist && tsup index.ts --format cjs,esm --dts", 41 | "lint": "tsc", 42 | "publish-beta": "npm publish --tag beta" 43 | }, 44 | "repository": { 45 | "type": "git", 46 | "url": "git+https://github.com/sjc5/remix-easy-mode.git" 47 | }, 48 | "homepage": "https://github.com/sjc5/remix-easy-mode", 49 | "bugs": "https://github.com/sjc5/remix-easy-mode/issues", 50 | "keywords": [ 51 | "remix", 52 | "typescript", 53 | "typesafe", 54 | "zod", 55 | "api", 56 | "react", 57 | "query", 58 | "mutation", 59 | "action", 60 | "loader", 61 | "forms", 62 | "validation", 63 | "form validation", 64 | "trpc", 65 | "bouncer", 66 | "session", 67 | "middleware" 68 | ], 69 | "sideEffects": false 70 | } 71 | -------------------------------------------------------------------------------- /packages/example/app/bouncer.ts: -------------------------------------------------------------------------------- 1 | import { DataFunctionArgs } from "@remix-run/node" 2 | import { BouncerProps } from "../../../index" 3 | // import { BouncerProps } from "remix-easy-mode" 4 | 5 | export const bouncer = async ({ ctx, csrfToken }: BouncerProps) => { 6 | const session = getSessionFromCtx(ctx) 7 | const csrfTokenIsValid = csrfToken === "5" 8 | 9 | if (session && csrfTokenIsValid) { 10 | return session 11 | } 12 | 13 | throw new Error("Unauthorized") 14 | } 15 | 16 | const getSessionFromCtx = (ctx: DataFunctionArgs) => { 17 | return { 18 | user: { 19 | id: 490, 20 | name: "Bob", 21 | }, 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /packages/example/app/root.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Links, 3 | LiveReload, 4 | Meta, 5 | Outlet, 6 | Scripts, 7 | ScrollRestoration, 8 | } from "@remix-run/react" 9 | 10 | export default function App() { 11 | return ( 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | ) 27 | } 28 | -------------------------------------------------------------------------------- /packages/example/app/routes/_index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import { InputHelper } from "../../../../src/unstyled-components/input-helper" 3 | import { useExampleHook } from "./api" 4 | import { TextInput, MantineProvider } from "@mantine/core" 5 | 6 | const Comp = React.forwardRef< 7 | HTMLInputElement, 8 | React.InputHTMLAttributes 9 | >((props, ref) => { 10 | return 11 | }) 12 | 13 | export default function Index() { 14 | const { Form, fields, result } = useExampleHook() 15 | 16 | const { Form: Form2, fields: fields2, result: result2 } = useExampleHook() 17 | 18 | return ( 19 |
20 | 21 |
console.log("form onSuccess", successRes)} 24 | style={{ display: "flex", flexDirection: "column", gap: "1rem" }} 25 | > 26 | 37 | 38 | 45 | 46 | {/* ZOD UNION OF STRING LITERALS */} 47 | {fields.letters.options?.map((option) => { 48 | return ( 49 | 58 | ) 59 | })} 60 | 61 | {/* ZOD ENUM */} 62 | {fields.letters2.options?.map((option) => { 63 | return ( 64 | 73 | ) 74 | })} 75 | 76 | 81 | 82 | 83 | 84 | 85 |
{JSON.stringify(result, null, 2)}
86 | 87 | console.log("form onSuccess", successRes)} 90 | style={{ display: "flex", flexDirection: "column", gap: "1rem" }} 91 | > 92 | 103 | 104 | 111 | 112 | {/* ZOD UNION OF STRING LITERALS */} 113 | {fields2.letters.options?.map((option) => { 114 | return ( 115 | 124 | ) 125 | })} 126 | 127 | {/* ZOD ENUM */} 128 | {fields2.letters2.options?.map((option) => { 129 | return ( 130 | 139 | ) 140 | })} 141 | 142 | 147 | 148 | 149 | 150 | 151 |
{JSON.stringify(result2, null, 2)}
152 |
153 |
154 | ) 155 | } 156 | -------------------------------------------------------------------------------- /packages/example/app/routes/api.ts: -------------------------------------------------------------------------------- 1 | import type { DataFunctionArgs } from "@remix-run/node" 2 | import { z } from "zod" 3 | import { dataFunctionHelper, useAction } from "../../../../index" 4 | // import { dataFunctionHelper, useAction } from "remix-easy-mode" 5 | 6 | import { bouncer } from "../bouncer" 7 | 8 | const schema = z.object({ 9 | anyString: z.string().refine((val) => val !== "bad message", { 10 | message: `Oops, you weren't supposed to write that!`, 11 | }), 12 | helloWorld: z.literal("hello world"), 13 | 14 | // any of these work for radio inputs 15 | letters: z.union([z.literal(1), z.literal(2), z.literal(3)]), 16 | letters2: z.enum(["1", "2", "3"]), 17 | 18 | someNumber: z.number().refine((val) => val > 0, { 19 | message: "Must be greater than 0", 20 | }), 21 | }) 22 | 23 | export const action = (ctx: DataFunctionArgs) => { 24 | return dataFunctionHelper({ 25 | ctx, 26 | schema, 27 | bouncer, 28 | fn: async ({ input, session }) => { 29 | const statusText = session.user 30 | ? `logged in as user ${session.user.id}` 31 | : "not logged in" 32 | 33 | return `You are ${statusText}. You typed: ${input.anyString}.` as const 34 | }, 35 | }) 36 | } 37 | 38 | export const useExampleHook = () => { 39 | return useAction({ 40 | path: "/api", 41 | schema, 42 | onSuccess: (successRes) => { 43 | console.log("from useAction onSuccess!", successRes) 44 | }, 45 | }) 46 | } 47 | -------------------------------------------------------------------------------- /packages/example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "remix-easy-mode-example-app", 3 | "type": "module", 4 | "private": true, 5 | "dependencies": { 6 | "@mantine/core": "^7.1.7", 7 | "@remix-run/node": "^2.2.0", 8 | "@remix-run/react": "^2.2.0", 9 | "isbot": "^3.7.0", 10 | "react": "^18.2.0", 11 | "react-dom": "^18.2.0", 12 | "remix-easy-mode": "0.2.2" 13 | }, 14 | "devDependencies": { 15 | "@remix-run/dev": "^2.2.0", 16 | "@remix-run/serve": "^2.2.0", 17 | "@types/node": "^20.8.10", 18 | "@types/react": "^18.2.33", 19 | "@types/react-dom": "^18.2.14", 20 | "isbot": "^3.6.5", 21 | "superjson": "^2.2.0", 22 | "typescript": "^5.2.2", 23 | "zod": "^3.22.4" 24 | }, 25 | "engines": { 26 | "node": ">=18" 27 | }, 28 | "scripts": { 29 | "dev": "remix dev -p 1234" 30 | }, 31 | "sideEffects": false 32 | } 33 | -------------------------------------------------------------------------------- /packages/example/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sjc5/remix-easy-mode/92ca3d68002b4350060fe98ecc8b853e5f2b3051/packages/example/public/favicon.ico -------------------------------------------------------------------------------- /packages/example/remix.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('@remix-run/dev').AppConfig} */ 2 | export default { 3 | ignoredRouteFiles: ["**/.*"], 4 | // appDirectory: "app", 5 | // assetsBuildDirectory: "public/build", 6 | // serverBuildPath: "build/index.js", 7 | // publicPath: "/build/", 8 | future: { 9 | v2_errorBoundary: true, 10 | v2_meta: true, 11 | v2_normalizeFormMethod: true, 12 | v2_routeConvention: true, 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /packages/example/remix.env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /packages/example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"], 3 | "compilerOptions": { 4 | "lib": ["DOM", "DOM.Iterable", "ES2019"], 5 | "isolatedModules": true, 6 | "esModuleInterop": true, 7 | "jsx": "react-jsx", 8 | "moduleResolution": "node", 9 | "resolveJsonModule": true, 10 | "target": "ES2019", 11 | "strict": true, 12 | "allowJs": true, 13 | "forceConsistentCasingInFileNames": true, 14 | "baseUrl": ".", 15 | "paths": { 16 | "~/*": ["./app/*"] 17 | }, 18 | "skipLibCheck": true, 19 | 20 | // Remix takes care of building everything in `remix build`. 21 | "noEmit": true 22 | }, 23 | "exclude": ["node_modules"] 24 | } 25 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - packages/* 3 | -------------------------------------------------------------------------------- /src/hooks/use-action.tsx: -------------------------------------------------------------------------------- 1 | import type { FetcherWithComponents } from "@remix-run/react" 2 | import { useFetcher } from "@remix-run/react" 3 | import type { ActionFunction } from "@remix-run/server-runtime" 4 | import { useState, useCallback, useMemo } from "react" 5 | import type { SomeZodObject, ZodError, ZodIssue, ZodTypeDef } from "zod" 6 | import { z } from "zod" 7 | import type { OnResolveProps } from "./use-on-resolve" 8 | import { useOnResolve } from "./use-on-resolve" 9 | import { getRemFetcherState } from "../utils/get-rem-fetcher-state" 10 | import { obj_from_fd as objectFromFormData } from "@kiruna/form-data" 11 | import { optionsFromZodShapeDef } from "../utils/options-from-zod-shape-def" 12 | import { FromPromise } from "../utils/from-promise" 13 | 14 | export type ClientOptions = { 15 | skipClientValidation?: boolean 16 | } 17 | 18 | export function useAction< 19 | Action extends ActionFunction, 20 | InputSchema extends SomeZodObject 21 | >({ 22 | path, 23 | schema, 24 | options, 25 | serializationHandlers, 26 | ...initialProps 27 | }: { 28 | path: string 29 | schema: InputSchema | null | undefined 30 | options?: ClientOptions 31 | serializationHandlers?: SerializationHandlers 32 | } & OnResolveProps< 33 | NonNullable< 34 | // @ts-ignore 35 | FromPromise["data"] 36 | > 37 | >) { 38 | const key = useMemo(() => String(Math.random()), []) 39 | const fetcher = useFetcher({ key }) 40 | const fetcherState = getRemFetcherState(fetcher) 41 | 42 | type LocalInferred = z.infer 43 | type Keys = keyof LocalInferred 44 | 45 | const keys = Object.keys(schema?.shape ?? {}) as Keys[] 46 | 47 | const [validationErrors, setValidationErrors] = useState< 48 | ZodError | undefined 49 | >(undefined) 50 | 51 | const fields: { 52 | [k in Keys]: { 53 | errors: ZodIssue[] | undefined 54 | options: Parameters[0]["input"][k][] | undefined 55 | props: { 56 | schema: typeof schema 57 | stringifyFn: SerializationHandlers["stringify"] | undefined 58 | name: k 59 | } 60 | } 61 | } = useMemo(() => { 62 | return Object.fromEntries( 63 | keys.map((key) => { 64 | const shapeDef = (schema?.shape as any)?.[key]?._def as 65 | | ZodTypeDef 66 | | undefined 67 | 68 | return [ 69 | key, 70 | { 71 | errors: validationErrors?.issues.filter( 72 | (issue) => issue.path[0] === key 73 | ), 74 | options: optionsFromZodShapeDef(shapeDef), 75 | props: { 76 | schema, 77 | stringifyFn: serializationHandlers?.stringify, 78 | name: key, 79 | }, 80 | }, 81 | ] 82 | }) 83 | ) as any 84 | }, [validationErrors, keys]) 85 | 86 | const [onResolve, setOnResolve] = useState< 87 | OnResolveProps< 88 | NonNullable< 89 | // @ts-ignore 90 | FromPromise["data"] 91 | > 92 | > 93 | >({ 94 | onSuccess: initialProps.onSuccess, 95 | onError: initialProps.onError, 96 | onSettled: initialProps.onSettled, 97 | }) 98 | 99 | useOnResolve({ 100 | fetcher, 101 | ...onResolve, 102 | }) 103 | 104 | type OnResolvePropsLocal = OnResolveProps< 105 | NonNullable< 106 | // @ts-ignore 107 | FromPromise["data"] 108 | > 109 | > 110 | 111 | const mutate = useCallback( 112 | async ( 113 | props: { input: LocalInferred } & OnResolvePropsLocal & { 114 | csrfToken?: string 115 | } & { 116 | options?: ClientOptions 117 | } 118 | ) => { 119 | const mergedOptions = { 120 | ...options, 121 | ...props.options, 122 | } 123 | 124 | setOnResolve({ 125 | onSuccess: async (result) => { 126 | props.onSuccess?.(result) 127 | initialProps.onSuccess?.(result) 128 | }, 129 | onError: async (result) => { 130 | props.onError?.(result) 131 | initialProps.onError?.(result) 132 | }, 133 | onSettled: async (result) => { 134 | props.onSettled?.(result) 135 | initialProps.onSettled?.(result) 136 | }, 137 | }) 138 | 139 | const parsedInput = 140 | mergedOptions?.skipClientValidation || !schema 141 | ? z.any().safeParse(props.input) 142 | : schema.safeParse(props.input) 143 | 144 | if (!parsedInput.success) { 145 | if (process.env.NODE_ENV === "development") { 146 | console.error("parse error", { 147 | errors: parsedInput.error, 148 | attemptedInput: props.input, 149 | }) 150 | } 151 | 152 | setValidationErrors(parsedInput.error) 153 | 154 | // stop the onResolve from running again 155 | setOnResolve({}) 156 | return 157 | } else { 158 | setValidationErrors(undefined) 159 | } 160 | 161 | const stringifier = serializationHandlers?.stringify ?? JSON.stringify 162 | 163 | fetcher.submit( 164 | stringifier({ 165 | csrfToken: props.csrfToken, 166 | input: parsedInput.data, 167 | }), 168 | { 169 | method: "post", 170 | action: path, 171 | encType: "application/json", 172 | } 173 | ) 174 | }, 175 | [schema, path, fetcher, initialProps, options] 176 | ) 177 | 178 | const Form = useMemo(() => { 179 | return function Form({ 180 | onSubmit, 181 | csrfToken, 182 | onSuccess, 183 | onError, 184 | onSettled, 185 | ...props 186 | }: { 187 | onSubmit?: ({ 188 | input, 189 | e, 190 | onResolveProps, 191 | }: { 192 | input: LocalInferred 193 | e: React.FormEvent 194 | onResolveProps: OnResolvePropsLocal 195 | }) => void 196 | csrfToken?: string 197 | } & OnResolvePropsLocal & 198 | Omit, "onSubmit">) { 199 | return ( 200 |
{ 202 | e.preventDefault() 203 | const formData = new FormData(e.target as HTMLFormElement) 204 | 205 | const input = objectFromFormData( 206 | formData, 207 | serializationHandlers?.parse 208 | ) as LocalInferred 209 | 210 | const onResolveProps = { onError, onSuccess, onSettled } 211 | 212 | if (onSubmit) { 213 | return onSubmit({ input, e, onResolveProps }) 214 | } 215 | 216 | return mutate({ 217 | input, 218 | csrfToken, 219 | ...onResolveProps, 220 | }) 221 | }} 222 | {...props} 223 | > 224 | {props.children} 225 |
226 | ) 227 | } 228 | }, []) 229 | 230 | return { 231 | ...fetcherState, 232 | fetcher: fetcher as FetcherWithComponents, 233 | result: fetcher.data as FromPromise | undefined, 234 | mutate, 235 | Form, 236 | fields, 237 | } 238 | } 239 | 240 | export type SerializationHandlers = { 241 | stringify: (input: unknown) => string 242 | parse: (input: string) => unknown 243 | } 244 | -------------------------------------------------------------------------------- /src/hooks/use-on-resolve.ts: -------------------------------------------------------------------------------- 1 | import type { Fetcher } from "@remix-run/react" 2 | import { useEffect } from "react" 3 | import type { 4 | handleApiError, 5 | handleApiSuccess, 6 | } from "../server/api-responses.server" 7 | import { getRemFetcherState } from "../utils/get-rem-fetcher-state" 8 | import { FromPromise } from "../utils/from-promise" 9 | 10 | export const useOnResolve = ({ 11 | fetcher, 12 | onSuccess, 13 | onError, 14 | onSettled, 15 | }: { 16 | fetcher: Fetcher 17 | } & OnResolveProps) => { 18 | const { isError, isSuccess } = getRemFetcherState(fetcher) 19 | 20 | const isSettled = isError || isSuccess 21 | 22 | useEffect(() => { 23 | if (isSuccess && onSuccess) { 24 | onSuccess(fetcher.data) 25 | } 26 | if (isError && onError) { 27 | onError(fetcher.data) 28 | } 29 | if (isSettled && onSettled) { 30 | onSettled(fetcher.data) 31 | } 32 | }, [ 33 | fetcher.data, 34 | isError, 35 | isSettled, 36 | isSuccess, 37 | onError, 38 | onSettled, 39 | onSuccess, 40 | ]) 41 | } 42 | 43 | export type OnResolveProps = { 44 | onSuccess?: (data: FromPromise>) => void 45 | onError?: (data: FromPromise) => void 46 | onSettled?: ( 47 | data: 48 | | FromPromise> 49 | | FromPromise 50 | ) => void 51 | } 52 | -------------------------------------------------------------------------------- /src/server/api-responses.server.ts: -------------------------------------------------------------------------------- 1 | import { json } from "@remix-run/server-runtime" 2 | 3 | async function handleApiSuccess({ 4 | result, 5 | responseInit, 6 | }: { 7 | result: RawResult 8 | responseInit?: ResponseInit 9 | }) { 10 | const payload = { 11 | success: true as const, 12 | data: result, 13 | error: undefined, 14 | at: Date.now(), 15 | } 16 | 17 | return json(payload, responseInit) as unknown as typeof payload 18 | } 19 | 20 | async function handleApiError({ 21 | error, 22 | errorMessage, 23 | responseInit, 24 | }: { 25 | error: unknown 26 | errorMessage: string 27 | responseInit?: ResponseInit 28 | }) { 29 | console.error(error) 30 | 31 | const payload = { 32 | success: false as const, 33 | data: undefined, 34 | error: errorMessage || "Something went wrong.", 35 | at: Date.now(), 36 | } 37 | 38 | const responseInitToUse = { 39 | ...responseInit, 40 | status: responseInit?.status || 500, 41 | } 42 | 43 | return json(payload, responseInitToUse) as unknown as typeof payload 44 | } 45 | 46 | export { handleApiSuccess, handleApiError } 47 | -------------------------------------------------------------------------------- /src/server/data-function-helpers.server.ts: -------------------------------------------------------------------------------- 1 | import type { DataFunctionArgs } from "@remix-run/server-runtime" 2 | import { objFromCtx } from "./helpers.server" 3 | import { handleApiError, handleApiSuccess } from "./api-responses.server" 4 | import type { ZodSchema } from "zod" 5 | import { z } from "zod" 6 | import { SerializationHandlers } from "../hooks/use-action" 7 | import { FromPromise } from "../utils/from-promise" 8 | 9 | export type BouncerProps = { 10 | ctx: DataFunctionArgs 11 | csrfToken: string | undefined 12 | } 13 | 14 | type NarrowBouncer = (props: BouncerProps) => Promise 15 | type BroadBouncer = NarrowBouncer | null | undefined 16 | 17 | const parseInput = async ({ 18 | ctx, 19 | schema, 20 | parseFn, 21 | }: { 22 | ctx: DataFunctionArgs 23 | schema: ZodSchema 24 | parseFn: ((input: string) => unknown) | undefined 25 | }) => { 26 | const obj = await objFromCtx(ctx, parseFn) 27 | 28 | return { 29 | parsedInput: schema.parse(obj.input), 30 | csrfToken: (obj.csrfToken as string) || undefined, 31 | } 32 | } 33 | 34 | const runBouncer = async ({ 35 | ctx, 36 | bouncer, 37 | csrfToken, 38 | parsedInput, 39 | }: { 40 | ctx: DataFunctionArgs 41 | bouncer: NarrowBouncer 42 | } & FromPromise>) => { 43 | const session = await bouncer({ 44 | ctx, 45 | csrfToken, 46 | }) 47 | 48 | return { session, input: parsedInput } 49 | } 50 | 51 | type DataFunctionHelperOptions = { 52 | sendRawErrors?: boolean 53 | throwOnError?: boolean 54 | } 55 | 56 | async function dataFunctionHelper< 57 | InputSchema extends ZodSchema, 58 | FnRes, 59 | Bouncer 60 | >({ 61 | ctx, 62 | schema, 63 | fn, 64 | bouncer, 65 | headers, 66 | options, 67 | serializationHandlers, 68 | }: { 69 | ctx: DataFunctionArgs 70 | schema: InputSchema | null | undefined 71 | fn: ( 72 | props: FromPromise, Bouncer>> 73 | ) => Promise 74 | bouncer: BroadBouncer 75 | headers?: Headers 76 | options?: DataFunctionHelperOptions 77 | serializationHandlers?: SerializationHandlers 78 | }) { 79 | const sendRawErrors = options?.sendRawErrors ?? false 80 | const throwOnError = options?.throwOnError ?? false 81 | 82 | try { 83 | let parseInputRes: 84 | | FromPromise>> 85 | | undefined 86 | try { 87 | parseInputRes = await parseInput({ 88 | ctx, 89 | schema: 90 | schema ?? (z.any() as unknown as ZodSchema>), 91 | parseFn: serializationHandlers?.parse, 92 | }) 93 | } catch (thrownRes) { 94 | if (thrownRes instanceof Error) { 95 | if (throwOnError) { 96 | throw thrownRes 97 | } 98 | 99 | return handleApiError({ 100 | error: thrownRes, 101 | errorMessage: sendRawErrors ? thrownRes.message : "Invalid input.", 102 | responseInit: { 103 | status: 400, 104 | }, 105 | }) 106 | } 107 | 108 | throw thrownRes 109 | } 110 | 111 | try { 112 | const bouncerRes = await runBouncer({ 113 | ctx, 114 | bouncer: bouncer ?? (() => Promise.resolve(undefined as Bouncer)), 115 | ...parseInputRes, 116 | }) 117 | 118 | return handleApiSuccess({ 119 | result: await fn(bouncerRes), 120 | responseInit: { 121 | headers, 122 | }, 123 | }) 124 | } catch (thrownRes) { 125 | if (throwOnError) { 126 | throw thrownRes 127 | } 128 | 129 | if (thrownRes instanceof Error) { 130 | return handleApiError({ 131 | error: thrownRes, 132 | errorMessage: sendRawErrors ? thrownRes.message : "Unauthorized.", 133 | responseInit: { 134 | status: 401, 135 | }, 136 | }) 137 | } 138 | 139 | throw thrownRes 140 | } 141 | } catch (thrownRes) { 142 | if (throwOnError) { 143 | throw thrownRes 144 | } 145 | 146 | if (thrownRes instanceof Error) { 147 | return handleApiError({ 148 | error: thrownRes, 149 | errorMessage: sendRawErrors 150 | ? thrownRes.message 151 | : "Something went wrong.", 152 | responseInit: { 153 | status: 500, 154 | }, 155 | }) 156 | } 157 | 158 | throw thrownRes 159 | } 160 | } 161 | 162 | export { dataFunctionHelper } 163 | -------------------------------------------------------------------------------- /src/server/helpers.server.ts: -------------------------------------------------------------------------------- 1 | import type { DataFunctionArgs } from "@remix-run/server-runtime" 2 | import { obj_from_fd as objectFromFormData } from "@kiruna/form-data" 3 | 4 | async function objFromCtx( 5 | ctx: DataFunctionArgs, 6 | parseFn?: (input: string) => unknown 7 | ) { 8 | if (ctx.request.method === "GET") { 9 | return ctx.params 10 | } 11 | try { 12 | const json = await ctx.request.json() 13 | if (parseFn) return parseFn(json) 14 | return json 15 | } catch (e) { 16 | const formData = await ctx.request.formData() 17 | return objectFromFormData(formData, parseFn) 18 | } 19 | } 20 | 21 | export { objFromCtx } 22 | -------------------------------------------------------------------------------- /src/unstyled-components/input-helper.tsx: -------------------------------------------------------------------------------- 1 | import React, { useMemo, useRef, useState } from "react" 2 | import { ZodObject, ZodRawShape, z } from "zod" 3 | import { SerializationHandlers } from "../hooks/use-action" 4 | 5 | function InputHelper< 6 | T, 7 | N extends keyof Inferred, 8 | C extends React.ForwardRefExoticComponent 9 | >({ 10 | name, 11 | component: Component, 12 | schema, 13 | stringifyFn, 14 | ...props 15 | }: { 16 | component?: C 17 | } & React.ComponentPropsWithoutRef & 18 | InputHelperProps) { 19 | const ref = useRef(null) 20 | const isCheckedOrSelected = ref.current?.checked ?? false 21 | const isCheckbox = props.type === "checkbox" 22 | 23 | const [valueState, setValueState] = useState( 24 | isCheckbox 25 | ? props.defaultChecked ?? props.checked ?? false 26 | : props.defaultValue ?? props.value ?? "" 27 | ) 28 | 29 | const stringifyToUse = useMemo(() => { 30 | return stringifyFn ?? JSON.stringify 31 | }, [stringifyFn]) 32 | 33 | const inputValue = useMemo(() => { 34 | const toBeStringified = isCheckbox ? isCheckedOrSelected : valueState 35 | 36 | return stringifyToUse( 37 | props.type === "number" ? Number(toBeStringified) : toBeStringified 38 | ) 39 | }, [stringifyFn, valueState, props.type]) 40 | 41 | const Comp = useMemo(() => Component ?? "input", [Component]) 42 | 43 | return ( 44 | <> 45 | {} 46 | 47 | { 50 | setValueState(isCheckbox ? e.target.checked : e.target.value) 51 | props.onChange?.(e) 52 | }} 53 | ref={ref} 54 | /> 55 | 56 | ) 57 | } 58 | 59 | function TextAreaHelper< 60 | T, 61 | N extends keyof Inferred, 62 | C extends React.ForwardRefExoticComponent 63 | >({ 64 | name, 65 | component: Component, 66 | schema, 67 | stringifyFn, 68 | ...props 69 | }: { 70 | component?: C 71 | } & React.ComponentPropsWithoutRef & 72 | TextAreaHelperProps) { 73 | const [valueState, setValueState] = useState(props.defaultValue ?? "") 74 | 75 | const inputValue = useMemo(() => { 76 | return stringifyFn ? stringifyFn(valueState) : JSON.stringify(valueState) 77 | }, [stringifyFn, valueState]) 78 | 79 | const Comp = useMemo(() => Component ?? "input", [Component]) 80 | 81 | return ( 82 | <> 83 | 84 | 85 | { 88 | setValueState(e.target.value) 89 | props.onChange?.(e) 90 | }} 91 | /> 92 | 93 | ) 94 | } 95 | 96 | type ZodObjectFromRawShape = ZodObject 97 | 98 | type NarrowedForForm = T extends ZodObject 99 | ? ZodObjectFromRawShape 100 | : never 101 | 102 | type Inferred = NarrowedForForm["_output"] 103 | 104 | type InputHelperBaseProps> = { 105 | name: N 106 | value?: Inferred[N] 107 | defaultValue?: Inferred[N] 108 | } & FormProps 109 | 110 | type InputHelperProps> = InputHelperBaseProps< 111 | T, 112 | N 113 | > & 114 | Omit, "value" | "defaultValue"> 115 | 116 | type TextAreaHelperProps> = InputHelperBaseProps< 117 | T, 118 | N 119 | > & 120 | Omit< 121 | React.TextareaHTMLAttributes, 122 | "value" | "defaultValue" 123 | > 124 | 125 | type FormProps = { 126 | schema: T extends NarrowedForForm ? T : never | null | undefined 127 | stringifyFn?: SerializationHandlers["stringify"] 128 | } 129 | 130 | export { InputHelper, TextAreaHelper } 131 | -------------------------------------------------------------------------------- /src/utils/from-promise.ts: -------------------------------------------------------------------------------- 1 | type FromPromise any> = Awaited> 2 | 3 | export type { FromPromise } 4 | -------------------------------------------------------------------------------- /src/utils/get-rem-fetcher-state.ts: -------------------------------------------------------------------------------- 1 | import type { Fetcher } from "@remix-run/react" 2 | 3 | function getRemFetcherState(fetcher: Fetcher) { 4 | const isLoading = fetcher.state !== "idle" 5 | 6 | return { 7 | isLoading, 8 | isSuccess: Boolean(!isLoading && fetcher.data?.success), 9 | isError: Boolean(fetcher.data && !fetcher.data?.success), 10 | } 11 | } 12 | 13 | export { getRemFetcherState } 14 | -------------------------------------------------------------------------------- /src/utils/options-from-zod-shape-def.ts: -------------------------------------------------------------------------------- 1 | import type { ZodEnumDef, ZodTypeDef, ZodUnionDef } from "zod" 2 | 3 | type TargetRadioZodDefs = ZodUnionDef | ZodEnumDef 4 | 5 | function optionsFromZodShapeDef(zodTypeDef: ZodTypeDef | undefined) { 6 | try { 7 | if ( 8 | typeof zodTypeDef !== "object" || 9 | !zodTypeDefHasTypeNameProp(zodTypeDef) 10 | ) { 11 | return 12 | } 13 | 14 | if (isZodUnionDef(zodTypeDef)) { 15 | return zodTypeDef.options.map((x) => x._def.value) 16 | } 17 | 18 | if (isZodEnumDef(zodTypeDef)) { 19 | return zodTypeDef.values 20 | } 21 | } catch (ignore) { 22 | console.error("Error in optionsFromZodShapeDef.") 23 | } 24 | } 25 | 26 | export { optionsFromZodShapeDef } 27 | 28 | function zodTypeDefHasTypeNameProp( 29 | x: ZodTypeDef & { 30 | typeName?: string 31 | } 32 | ): x is TargetRadioZodDefs { 33 | return !!x?.typeName 34 | } 35 | 36 | function isZodUnionDef(x: TargetRadioZodDefs): x is ZodUnionDef { 37 | return x.typeName === "ZodUnion" 38 | } 39 | 40 | function isZodEnumDef(x: TargetRadioZodDefs): x is ZodEnumDef { 41 | return x.typeName === "ZodEnum" 42 | } 43 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "commonjs", 5 | "esModuleInterop": true, 6 | "forceConsistentCasingInFileNames": true, 7 | "strict": true, 8 | "skipLibCheck": true, 9 | "noUncheckedIndexedAccess": true, 10 | "noEmit": true, 11 | "jsx": "react-jsx" 12 | }, 13 | "include": ["src", "index.ts"] 14 | } 15 | --------------------------------------------------------------------------------