Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

createForm proposal #321

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/form/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @solid-primitives/form

0.0.100

First commit of the form primitive.
21 changes: 21 additions & 0 deletions packages/form/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Solid Primitives Working Group

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions packages/form/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<p>
<img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=I18n" alt="Solid Primitives I18n">
</p>

# @solid-primitives/form

[![turborepo](https://img.shields.io/badge/built%20with-turborepo-cc00ff.svg?style=for-the-badge&logo=turborepo)](https://turborepo.org/)
[![size](https://img.shields.io/bundlephobia/minzip/@solid-primitives/i18n?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/i18n)
[![size](https://img.shields.io/npm/v/@solid-primitives/i18n?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/i18n)
[![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-3.json)](https://github.com/solidjs-community/solid-primitives#contribution-process)

Creates state and helpers for managing forms.

## How to use it

Install it:

```bash
yarn add @solid-primitives/form
```

## Changelog

See [CHANGELOG.md](./CHANGELOG.md)
35 changes: 35 additions & 0 deletions packages/form/dev/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>Solid App</title>
<style>
html {
font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
}

body {
padding: 0;
margin: 0;
}

a,
button {
cursor: pointer;
}

* {
margin: 0;
}
</style>
</head>

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>

<script src="/index.tsx" type="module"></script>
</body>
</html>
59 changes: 59 additions & 0 deletions packages/form/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Component } from "solid-js";
import { render } from "solid-js/web";
import { z } from "zod";
import { createForm } from "../src";

const registerSchema = z.object({
password: z.string().min(8),
emergencyContact: z.array(z.object({ firstName: z.string() })).min(2),
favoriteNumber: z.number(),
user: z.object({
lastName: z.string(),
email: z.object({
random: z.array(
z.object({
keys: z.object({
email: z.string().email()
})
})
)
})
})
});

const App: Component = () => {
const { handleSubmit } = createForm({
schema: registerSchema,
onError(errors) {
console.log(errors);
},
onSubmit(data) {
console.log(data);
}
});
return (
<form onSubmit={handleSubmit}>
<label>1st Emergency Contact First Name</label>
<input name="emergencyContact[0].firstName" required type="text" />
<br />
<label>2nd Emergency Contact First Name</label>
<input name="emergencyContact[1].firstName" required type="text" />
<br />
<label>Your Favorite Number</label>
<input name="favoriteNumber" required type="number" />
<br />
<label>Your Last Name</label>
<input name="user.lastName" required type="text" />
<br />
<label>Crazy Set Path Email</label>
<input name="user.email.random[0].keys.email" required type="email" />
<br />
<label>Password</label>
<input name="password" required type="password" />
<br />
<button type="submit">Test</button>
</form>
);
};

render(() => <App />, document.getElementById("root")!);
2 changes: 2 additions & 0 deletions packages/form/dev/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { viteConfig } from "../../../configs/vite.config";
export default viteConfig;
57 changes: 57 additions & 0 deletions packages/form/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"name": "@solid-primitives/form",
"version": "1.1.4",
"description": "Primitive to create and compose forms",
"author": "Tanner Scadden <tanner@scaddenfamily.com>",
"license": "MIT",
"homepage": "https://github.com/solidjs-community/solid-primitives/tree/main/packages/form",
"repository": {
"type": "git",
"url": "git+https://github.com/solidjs-community/solid-primitives.git"
},
"primitive": {
"name": "form",
"stage": 3,
"list": [
"createForm"
],
"category": "Utilities"
},
"files": [
"dist"
],
"private": false,
"sideEffects": false,
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"browser": {},
"types": "./dist/index.d.ts",
"exports": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": "./dist/index.cjs"
},
"scripts": {
"dev": "vite serve dev",
"page": "vite build dev",
"start": "vite -r ./dev/ -c ./dev/vite.config.ts",
"build": "jiti ../../scripts/build.ts",
"test": "vitest -c ../../configs/vitest.config.ts",
"test:ssr": "pnpm run test --mode ssr"
},
"keywords": [
"form",
"solid",
"primitives"
],
"devDependencies": {
"zod": "3.20.6"
},
"peerDependencies": {
"solid-js": "^1.6.0"
},
"typesVersions": {}
}
92 changes: 92 additions & 0 deletions packages/form/src/getParseFn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Credit to @trpc/server
// https://github.com/trpc/trpc/blob/main/packages/server/src/core/parser.ts
// https://github.com/trpc/trpc/blob/main/packages/server/src/core/internals/getParseFn.ts

export type ParserZodEsque<TInput, TParsedInput> = {
_input: TInput;
_output: TParsedInput;
};

export type ParserMyZodEsque<TInput> = {
parse: (input: any) => TInput;
};

export type ParserSuperstructEsque<TInput> = {
create: (input: unknown) => TInput;
};

export type ParserCustomValidatorEsque<TInput> = (input: unknown) => TInput | Promise<TInput>;

export type ParserYupEsque<TInput> = {
validateSync: (input: unknown) => TInput;
};
export type ParserWithoutInput<TInput> =
| ParserYupEsque<TInput>
| ParserSuperstructEsque<TInput>
| ParserCustomValidatorEsque<TInput>
| ParserMyZodEsque<TInput>;

export type ParserWithInputOutput<TInput, TParsedInput> = ParserZodEsque<TInput, TParsedInput>;

export type Parser = ParserWithoutInput<any> | ParserWithInputOutput<any, any>;

export type inferParser<TParser extends Parser> = TParser extends ParserWithInputOutput<
infer $TIn,
infer $TOut
>
? {
in: $TIn;
out: $TOut;
}
: TParser extends ParserWithoutInput<infer $InOut>
? {
in: $InOut;
out: $InOut;
}
: never;

export type ParseFn<TType> = (value: unknown) => TType | Promise<TType>;

export function getParseFn<TType>(procedureParser: Parser): ParseFn<TType> {
const parser = procedureParser as any;

if (typeof parser === "function") {
// ProcedureParserCustomValidatorEsque
return parser;
}

if (typeof parser.parseAsync === "function") {
// ProcedureParserZodEsque
return parser.parseAsync.bind(parser);
}

if (typeof parser.parse === "function") {
// ProcedureParserZodEsque
return parser.parse.bind(parser);
}

if (typeof parser.validateSync === "function") {
// ProcedureParserYupEsque
return parser.validateSync.bind(parser);
}

if (typeof parser.create === "function") {
// ProcedureParserSuperstructEsque
return parser.create.bind(parser);
}

throw new Error("Could not find a validator fn");
}

/**
* @deprecated only for backwards compat
* @internal
*/
export function getParseFnOrPassThrough<TType>(
procedureParser: Parser | undefined
): ParseFn<TType> {
if (!procedureParser) {
return v => v as TType;
}
return getParseFn(procedureParser);
}
60 changes: 60 additions & 0 deletions packages/form/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { getParseFn, Parser } from "./getParseFn";

export type FormError<T> = {
data: T;
error: unknown;
};

export type CreateFormOptions<T> = {
schema?: Parser;
onSubmit: (data: T) => Promise<void> | void;
onError: (errors: FormError<T>) => void | Promise<void>;
castNumbers?: boolean;
};

type FormEvent = Event & {
submitter: HTMLElement;
} & {
currentTarget: HTMLFormElement;
target: Element;
};

// Taken from https://youmightnotneed.com/lodash#set
const set = <T extends object>(obj: T, path: string | string[], value: string | number) => {
// Regex explained: https://regexr.com/58j0k
const pathArray = Array.isArray(path) ? path : path.match(/([^[.\]])+/g)!;

pathArray.reduce((acc, key, i) => {
if (acc[key] === undefined) acc[key] = {};
if (i === pathArray.length - 1) acc[key] = value;
return acc[key];
}, obj as any);
};

export const createForm = <T>(options: CreateFormOptions<T>) => {
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);

let data: Partial<T> = {};

for (const [name, value] of formData.entries()) {
const v = !options.castNumbers || isNaN(value as any) ? value.toString() : Number(value);
set(data, name, v);
}

try {
if (options.schema) {
const parser = getParseFn(options.schema);
await parser(data);
}
options.onSubmit(data as T);
} catch (e) {
options.onError({ data: data as T, error: e });
}
};

return {
handleSubmit
};
};
7 changes: 7 additions & 0 deletions packages/form/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { describe, expect, it } from "vitest";

describe("createForm", () => {
it("Should create a form", () => {
expect(false).toBe(true);
});
});
7 changes: 7 additions & 0 deletions packages/form/test/server.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { describe, expect, it } from "vitest";

describe("createForm", () => {
it("Should create a form", () => {
expect(false).toBe(true);
});
});
5 changes: 5 additions & 0 deletions packages/form/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "../../tsconfig.json",
"include": ["./src", "./test", "./dev", "./demo"],
"exclude": ["node_modules", "./dist"]
}
Loading