├── .nvmrc
├── .npmrc
├── .prettierignore
├── .eslintignore
├── .gitignore
├── commitlint.config.js
├── postcss.config.js
├── public
├── favicon.png
└── index.html
├── .prettierrc
├── src
├── main.js
├── components
│ ├── components.module.js
│ ├── Select.svelte
│ ├── Input.svelte
│ ├── Choice.svelte
│ └── Form.svelte
├── utils.js
└── App.svelte
├── CHANGELOG.md
├── svelte.config.js
├── tests
├── utils.js
├── Input
│ ├── TestApp.svelte
│ ├── __snapshots__
│ │ └── Input.spec.js.snap
│ └── Input.spec.js
└── Form
│ ├── TestApp.svelte
│ ├── __snapshots__
│ └── Form.spec.js.snap
│ └── Form.spec.js
├── babel.config.js
├── jest.config.js
├── .eslintrc.js
├── .github
├── workflows
│ ├── release.yml
│ └── CI.yml
└── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
├── LICENSE
├── rollup.config.js
├── package.json
└── README.md
/.nvmrc:
--------------------------------------------------------------------------------
1 | lts/*
2 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | scripts-prepend-node-path=true
2 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | README.md
2 | coverage
3 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | public
2 | dist
3 | coverage
4 | node_modules
5 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | dist
3 | node_modules
4 | public/bundle.*
5 | coverage
6 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = { extends: ['@commitlint/config-conventional'] };
2 |
--------------------------------------------------------------------------------
/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: [require('autoprefixer')],
3 | };
4 |
--------------------------------------------------------------------------------
/public/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mdauner/sveltejs-forms/HEAD/public/favicon.png
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "es5",
3 | "tabWidth": 2,
4 | "singleQuote": true
5 | }
6 |
--------------------------------------------------------------------------------
/src/main.js:
--------------------------------------------------------------------------------
1 | import App from './App.svelte';
2 |
3 | const app = new App({
4 | target: document.body,
5 | });
6 |
7 | export default app;
8 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # CHANGELOG
2 |
3 | The changelog is automatically updated using
4 | [semantic-release](https://github.com/semantic-release/semantic-release). You
5 | can see it on the [releases page](../../releases).
6 |
--------------------------------------------------------------------------------
/svelte.config.js:
--------------------------------------------------------------------------------
1 | const autoPreprocess = require('svelte-preprocess');
2 |
3 | module.exports = {
4 | preprocess: autoPreprocess({
5 | postcss: true,
6 | scss: { includePaths: ['src', 'node_modules'] },
7 | }),
8 | };
9 |
--------------------------------------------------------------------------------
/src/components/components.module.js:
--------------------------------------------------------------------------------
1 | export { default as Form } from './Form.svelte';
2 | export { default as Input } from './Input.svelte';
3 | export { default as Select } from './Select.svelte';
4 | export { default as Choice } from './Choice.svelte';
5 |
--------------------------------------------------------------------------------
/tests/utils.js:
--------------------------------------------------------------------------------
1 | import { render, wait } from '@testing-library/svelte';
2 |
3 | async function renderAndWait(component, options) {
4 | const renderedComponent = render(component, options);
5 | await wait();
6 | return renderedComponent;
7 | }
8 |
9 | export { renderAndWait as render };
10 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Svelte component
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | export function createObjectWithDefaultValue(defaultValue = '') {
2 | return new Proxy(
3 | {},
4 | {
5 | get: function(object, property) {
6 | return Object.prototype.hasOwnProperty.call(object, property)
7 | ? object[property]
8 | : defaultValue;
9 | },
10 | }
11 | );
12 | }
13 |
14 | export function deepCopy(src) {
15 | return JSON.parse(JSON.stringify(src));
16 | }
17 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | include: ['**/**/*.js', '**/**/*.mjs', '**/**/*.html', '**/**/*.svelte'],
3 | plugins: [
4 | '@babel/plugin-syntax-dynamic-import',
5 | [
6 | '@babel/plugin-transform-runtime',
7 | {
8 | useESModules: true,
9 | },
10 | ],
11 | ],
12 | presets: [
13 | [
14 | '@babel/preset-env',
15 | {
16 | targets: {
17 | node: 'current',
18 | },
19 | },
20 | ],
21 | ],
22 | ignore: ['node_modules/(?!lodash-es)'],
23 | };
24 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | transform: {
3 | '^.+\\.m?js$': 'babel-jest',
4 | "^.+\\.svelte$": ["svelte-jester", { "preprocess": true }]
5 | },
6 | transformIgnorePatterns: [
7 | '/node_modules/(?!(lodash-es|svelte-writable-derived)).+\\.m?js$',
8 | ],
9 | moduleFileExtensions: ['js', 'svelte', 'mjs'],
10 | roots: ['/tests'],
11 | bail: false,
12 | verbose: false,
13 | collectCoverage: true,
14 | collectCoverageFrom: ['src/components/**/*.{js,svelte}', 'src/utils.js'],
15 | setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
16 | };
17 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | browser: true,
4 | node: true,
5 | es6: true,
6 | 'jest/globals': true,
7 | },
8 | extends: ['eslint:recommended', 'plugin:jest/recommended', 'prettier'],
9 | overrides: [
10 | {
11 | files: '*.svelte',
12 | processor: 'svelte3/svelte3',
13 | },
14 | ],
15 | settings: {
16 | 'svelte3/ignore-styles': attributes =>
17 | attributes.lang && attributes.lang.includes('scss'),
18 | },
19 | rules: {
20 | 'jest/no-test-callback': 0
21 | },
22 | parserOptions: {
23 | ecmaVersion: 2019,
24 | sourceType: 'module',
25 | },
26 | plugins: ['svelte3', 'jest'],
27 | };
28 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 |
8 | jobs:
9 | release:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v1
14 | - name: Use Node.js 10.x
15 | uses: actions/setup-node@v1
16 | with:
17 | node-version: 10.x
18 | - name: yarn install, build, and release
19 | run: |
20 | yarn install
21 | yarn run build
22 | yarn run semantic-release
23 | env:
24 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
25 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
26 | GH_TOKEN: ${{ secrets.GH_TOKEN }}
27 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/tests/Input/TestApp.svelte:
--------------------------------------------------------------------------------
1 |
14 |
15 |
27 |
--------------------------------------------------------------------------------
/.github/workflows/CI.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - master
7 | push:
8 | branches:
9 | - master
10 |
11 | jobs:
12 | build:
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v1
17 | - name: Use Node.js 10.x
18 | uses: actions/setup-node@v1
19 | with:
20 | node-version: 10.x
21 | - name: yarn install, build, and test
22 | run: |
23 | yarn install
24 | yarn run build
25 | yarn run lint
26 | yarn run prettier
27 | yarn run test
28 |
29 | - name: Codecov
30 | run: bash <(curl -s https://codecov.io/bash) -t $TOKEN -B $REF
31 | env:
32 | CI: true
33 | TOKEN: "${{ secrets.CODECOV_TOKEN }}"
34 | REF: "${{ github.ref }}"
35 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/tests/Form/TestApp.svelte:
--------------------------------------------------------------------------------
1 |
26 |
27 |
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Michael Dauner
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 |
--------------------------------------------------------------------------------
/src/components/Select.svelte:
--------------------------------------------------------------------------------
1 |
24 |
25 |
26 | {#if label}
27 |
28 | {/if}
29 |
43 | {#if get($touched, name) && get($errors, name)}
44 |
{get($errors, name)}
45 | {/if}
46 |
47 |
--------------------------------------------------------------------------------
/src/components/Input.svelte:
--------------------------------------------------------------------------------
1 |
25 |
26 |
27 | {#if label}
28 |
29 | {/if}
30 | {#if multiline}
31 |
39 | {:else}
40 |
49 | {/if}
50 | {#if get($touched, name) && get($errors, name)}
51 |
{get($errors, name)}
52 | {/if}
53 |
54 |
--------------------------------------------------------------------------------
/src/components/Choice.svelte:
--------------------------------------------------------------------------------
1 |
37 |
38 |
39 | {#each options as option}
40 | {#if multiple}
41 |
50 | {:else}
51 |
60 | {/if}
61 | {#if option.title}
62 |
63 | {/if}
64 | {/each}
65 | {#if get($touched, name) && get($errors, name)}
66 |
{get($errors, name)}
67 | {/if}
68 |
69 |
--------------------------------------------------------------------------------
/tests/Input/__snapshots__/Input.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Input matches snapshot 1`] = `
4 |
28 | `;
29 |
30 | exports[`Input passes props to input 1`] = `
31 |
56 | `;
57 |
58 | exports[`Input renders label 1`] = `
59 |
88 | `;
89 |
90 | exports[`Input renders textarea when multiline parameter is set 1`] = `
91 |
114 | `;
115 |
--------------------------------------------------------------------------------
/src/App.svelte:
--------------------------------------------------------------------------------
1 |
51 |
52 |
73 |
74 |
104 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import babel from 'rollup-plugin-babel';
2 | import commonjs from 'rollup-plugin-commonjs';
3 | import livereload from 'rollup-plugin-livereload';
4 | import resolve from 'rollup-plugin-node-resolve';
5 | import svelte from 'rollup-plugin-svelte';
6 | import { terser } from 'rollup-plugin-terser';
7 | import autoPreprocess from 'svelte-preprocess';
8 | import pkg from './package.json';
9 |
10 | const production = !process.env.ROLLUP_WATCH;
11 | const name = pkg.name
12 | .replace(/^(@\S+\/)?(svelte-)?(\S+)/, '$3')
13 | .replace(/^\w/, m => m.toUpperCase())
14 | .replace(/-\w/g, m => m[1].toUpperCase());
15 |
16 | export default {
17 | input: !production ? 'src/main.js' : 'src/components/components.module.js',
18 | output: !production
19 | ? {
20 | sourcemap: true,
21 | format: 'iife',
22 | name: 'app',
23 | file: 'public/bundle.js',
24 | }
25 | : [
26 | {
27 | file: pkg.module,
28 | format: 'es',
29 | sourcemap: true,
30 | name,
31 | },
32 | {
33 | file: pkg.main,
34 | format: 'umd',
35 | sourcemap: true,
36 | name,
37 | },
38 | ],
39 | plugins: [
40 | babel({
41 | runtimeHelpers: true,
42 | }),
43 | svelte({
44 | // enable run-time checks when not in production
45 | dev: !production,
46 | // we'll extract any component CSS out into
47 | // a separate file — better for performance
48 | css: css => {
49 | css.write('public/bundle.css');
50 | },
51 |
52 | /**
53 | * Auto preprocess supported languages with
54 | * ''/'external src files' support
55 | **/
56 | preprocess: autoPreprocess({
57 | postcss: true,
58 | scss: { includePaths: ['src', 'node_modules'] },
59 | }),
60 | }),
61 |
62 | // If you have external dependencies installed from
63 | // npm, you'll most likely need these plugins. In
64 | // some cases you'll need additional configuration —
65 | // consult the documentation for details:
66 | // https://github.com/rollup/rollup-plugin-commonjs
67 | resolve({
68 | browser: true,
69 | dedupe: importee =>
70 | importee === 'svelte' || importee.startsWith('svelte/'),
71 | }),
72 | commonjs({
73 | include: ['node_modules/**'],
74 | }),
75 |
76 | // Watch the `public` directory and refresh the
77 | // browser on changes when not in production
78 | !production && livereload('public'),
79 |
80 | // If we're building for production (npm run build
81 | // instead of npm run dev), minify
82 | production && terser(),
83 | ],
84 | watch: {
85 | clearScreen: false,
86 | },
87 | };
88 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "sveltejs-forms",
3 | "description": "Declarative forms for Svelte",
4 | "homepage": "https://mdauner.github.io/sveltejs-forms/",
5 | "version": "0.0.0-semantically-released",
6 | "license": "MIT",
7 | "repository": "github:mdauner/sveltejs-forms",
8 | "svelte": "src/components/components.module.js",
9 | "module": "dist/index.min.mjs",
10 | "main": "dist/index.min.js",
11 | "devDependencies": {
12 | "@babel/core": "~7.11.6",
13 | "@babel/plugin-syntax-dynamic-import": "~7.8.3",
14 | "@babel/plugin-transform-runtime": "~7.11.5",
15 | "@babel/preset-env": "~7.11.5",
16 | "@commitlint/cli": "~8.3.5",
17 | "@commitlint/config-conventional": "~8.3.4",
18 | "@testing-library/dom": "^7.24.1",
19 | "@testing-library/jest-dom": "~5.11.4",
20 | "@testing-library/svelte": "~3.0.0",
21 | "@testing-library/user-event": "^12.1.3",
22 | "@types/jest": "~25.1.3",
23 | "autoprefixer": "~9.7.4",
24 | "babel-jest": "~26.3.0",
25 | "cz-conventional-changelog": "~3.1.0",
26 | "eslint": "~6.8.0",
27 | "eslint-config-prettier": "~6.10.00",
28 | "eslint-plugin-jest": "~23.8.1",
29 | "eslint-plugin-svelte3": "~2.7.3",
30 | "husky": "~4.2.3",
31 | "jest": "~25.1.0",
32 | "lint-staged": "~10.0.8",
33 | "node-sass": "~4.13.1",
34 | "npm-run-all": "~4.1.5",
35 | "postcss": "~7.0.27",
36 | "postcss-load-config": "~2.1.0",
37 | "prettier": "~1.19.1",
38 | "prettier-plugin-svelte": "~0.7.0",
39 | "rollup": "~1.32.0",
40 | "rollup-plugin-babel": "~4.3.3",
41 | "rollup-plugin-commonjs": "~10.1.0",
42 | "rollup-plugin-livereload": "~1.0.4",
43 | "rollup-plugin-node-resolve": "~5.2.0",
44 | "rollup-plugin-svelte": "~5.1.1",
45 | "rollup-plugin-terser": "~5.2.0",
46 | "semantic-release": "~17.0.4",
47 | "sirv-cli": "~0.4.5",
48 | "svelte": "~3.20.0",
49 | "svelte-jester": "^1.1.5",
50 | "svelte-preprocess": "~3.4.0",
51 | "yup": "~0.28.2"
52 | },
53 | "peerDependencies": {
54 | "svelte": "~3.20.0",
55 | "yup": "~0.28.2"
56 | },
57 | "dependencies": {
58 | "lodash-es": "~4.17.15",
59 | "svelte-writable-derived": "~2.0.1"
60 | },
61 | "scripts": {
62 | "prettier": "prettier --check '**/*.{svelte, html, css, scss, stylus, js, ts, json, yml, md}' --plugin-search-dir=.",
63 | "lint": "eslint --color './**/*.{js,svelte}'",
64 | "test": "jest --verbose",
65 | "autobuild": "rollup -c -w",
66 | "start:dev": "sirv public --single --dev",
67 | "dev": "run-p start:dev autobuild",
68 | "build": "rollup -c",
69 | "prepublishOnly": "npm run build",
70 | "semantic-release": "semantic-release"
71 | },
72 | "browserslist": [
73 | "defaults"
74 | ],
75 | "keywords": [
76 | "svelte",
77 | "forms",
78 | "validation",
79 | "javascript"
80 | ],
81 | "files": [
82 | "src",
83 | "dist"
84 | ],
85 | "husky": {
86 | "hooks": {
87 | "pre-commit": "lint-staged",
88 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
89 | }
90 | },
91 | "lint-staged": {
92 | "*.{svelte,js}": [
93 | "eslint --fix",
94 | "git add"
95 | ],
96 | "*.{svelte, html, css, scss, stylus, js, ts, json, yml, md}": [
97 | "prettier --write --plugin-search-dir=.",
98 | "git add"
99 | ]
100 | },
101 | "config": {
102 | "commitizen": {
103 | "path": "./node_modules/cz-conventional-changelog"
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/components/Form.svelte:
--------------------------------------------------------------------------------
1 |
4 |
5 |
126 |
127 |
142 |
--------------------------------------------------------------------------------
/tests/Input/Input.spec.js:
--------------------------------------------------------------------------------
1 | import App from './TestApp.svelte';
2 | import { fireEvent, waitFor } from '@testing-library/svelte';
3 | import userEvent from '@testing-library/user-event';
4 | import * as yup from 'yup';
5 | import { render } from '../utils';
6 |
7 | describe('Input', () => {
8 | it('renders textarea when multiline parameter is set', async () => {
9 | const { container } = await render(App, { props: { multiline: true } });
10 | expect(container.firstChild).toMatchSnapshot();
11 | });
12 |
13 | it('renders label', async () => {
14 | const { container } = await render(App, { props: { label: 'Email' } });
15 | expect(container.firstChild).toMatchSnapshot();
16 | });
17 |
18 | it('passes props to input', async () => {
19 | const { container } = await render(App, { props: { disabled: true } });
20 | expect(container.firstChild).toMatchSnapshot();
21 | });
22 |
23 | it('updates form value on change', async () => {
24 | const { component, getByPlaceholderText } = await render(App);
25 |
26 | const emailInput = getByPlaceholderText('Email');
27 |
28 | await fireEvent.change(emailInput, {
29 | target: { value: 'test@user.com' },
30 | });
31 |
32 | expect(component.form.$capture_state().$values).toMatchObject({
33 | email: 'test@user.com',
34 | });
35 | });
36 |
37 | it('validates on input if field is touched', async () => {
38 | const schema = yup.object().shape({
39 | email: yup.string().min(4),
40 | });
41 | const { component, getByPlaceholderText } = await render(App, {
42 | props: { schema },
43 | });
44 |
45 | const emailInput = getByPlaceholderText('Email');
46 |
47 | await fireEvent.change(emailInput, {
48 | target: { value: 'pas' },
49 | });
50 |
51 | await waitFor(() =>
52 | expect(component.form.$capture_state().$errors.email).toEqual(
53 | 'email must be at least 4 characters'
54 | )
55 | );
56 |
57 | userEvent.type(emailInput, 's');
58 |
59 | await waitFor(() =>
60 | expect(component.form.$capture_state().$errors).toEqual({})
61 | );
62 | });
63 |
64 | it('validates on change if validateOnChange is true', async () => {
65 | const schema = yup.object().shape({
66 | email: yup.string().email(),
67 | });
68 | const { component, getByPlaceholderText } = await render(App, {
69 | props: { schema, validateOnChange: true },
70 | });
71 |
72 | const emailInput = getByPlaceholderText('Email');
73 |
74 | await fireEvent.change(emailInput, {
75 | target: { value: 'invalid value' },
76 | });
77 |
78 | await waitFor(() =>
79 | expect(component.form.$capture_state().$errors).toEqual({
80 | email: 'email must be a valid email',
81 | })
82 | );
83 | });
84 |
85 | it('does not validate on change if validateOnChange is false', async () => {
86 | const schema = yup.object().shape({
87 | email: yup.string().email(),
88 | });
89 | const { component, getByPlaceholderText } = await render(App, {
90 | props: { schema, validateOnChange: false },
91 | });
92 |
93 | const emailInput = getByPlaceholderText('Email');
94 |
95 | await fireEvent.change(emailInput, {
96 | target: { value: 'invalid value' },
97 | });
98 |
99 | await waitFor(() =>
100 | expect(component.form.$capture_state().$errors).toEqual({})
101 | );
102 | });
103 |
104 | it('validates on blur if validateOnBlur is true', async () => {
105 | const schema = yup.object().shape({
106 | email: yup.string().email(),
107 | });
108 | const { component, getByPlaceholderText } = await render(App, {
109 | props: { schema, validateOnChange: false, validateOnBlur: true },
110 | });
111 |
112 | const emailInput = getByPlaceholderText('Email');
113 |
114 | await fireEvent.change(emailInput, {
115 | target: { value: 'invalid value' },
116 | });
117 | await fireEvent.blur(emailInput);
118 |
119 | await waitFor(() =>
120 | expect(component.form.$capture_state().$errors).toEqual({
121 | email: 'email must be a valid email',
122 | })
123 | );
124 | });
125 |
126 | it('does not validate on blur if validateOnBlur is false', async () => {
127 | const schema = yup.object().shape({
128 | email: yup.string().email(),
129 | });
130 | const { component, getByPlaceholderText } = await render(App, {
131 | props: { schema, validateOnChange: false, validateOnBlur: false },
132 | });
133 |
134 | const emailInput = getByPlaceholderText('Email');
135 |
136 | await fireEvent.change(emailInput, {
137 | target: { value: 'invalid value' },
138 | });
139 | await fireEvent.blur(emailInput);
140 |
141 | await waitFor(() =>
142 | expect(component.form.$capture_state().$errors).toEqual({})
143 | );
144 | });
145 |
146 | it('matches snapshot', async () => {
147 | const { container } = await render(App);
148 | expect(container.firstChild).toMatchSnapshot();
149 | });
150 | });
151 |
--------------------------------------------------------------------------------
/tests/Form/__snapshots__/Form.spec.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Form matches snapshot 1`] = `
4 |
103 | `;
104 |
105 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 1`] = `
106 | Object {
107 | "language": "svelte",
108 | "os": Array [],
109 | "user": Object {
110 | "email": "test@user.com",
111 | },
112 | }
113 | `;
114 |
115 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 2`] = `
116 | Object {
117 | "language": "svelte",
118 | "os": Array [],
119 | "user": Object {
120 | "email": "test@user.com",
121 | },
122 | }
123 | `;
124 |
125 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 3`] = `Object {}`;
126 |
127 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 4`] = `
128 | Object {
129 | "language": true,
130 | "os": true,
131 | "user": Object {
132 | "email": true,
133 | },
134 | }
135 | `;
136 |
137 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 5`] = `
138 | Object {
139 | "language": "",
140 | "os": Array [],
141 | "user": Object {
142 | "email": "",
143 | },
144 | }
145 | `;
146 |
147 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 6`] = `Object {}`;
148 |
149 | exports[`Form onSubmit event returns values, resetForm, setSubmitting 7`] = `
150 | Object {
151 | "language": false,
152 | "os": false,
153 | "user": Object {
154 | "email": false,
155 | },
156 | }
157 | `;
158 |
159 | exports[`Form shows error message when schema is defined 1`] = `
160 |
264 | `;
265 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sveltejs-forms
2 |
3 | 
4 | 
5 | 
6 |
7 | 
8 | 
9 | [](https://codecov.io/gh/mdauner/sveltejs-forms)
10 |
11 | Declarative forms for [Svelte](https://svelte.dev/).
12 |
13 | [DEMO](https://svelte.dev/repl/8e7deaa261364b4f8b2c0caff1982eeb?version=3.23.0)
14 |
15 | ## Features
16 |
17 | - optional schema-based validation through [Yup](https://github.com/jquense/yup)
18 | - access to nested properties using paths
19 | - supports custom components
20 | - provides `Input`, `Select`, `Choice` components to reduce boilerplate
21 |
22 | ## Install
23 |
24 | ```shell
25 | $ npm i sveltejs-forms
26 | ```
27 |
28 | or
29 |
30 | ```shell
31 | $ yarn add sveltejs-forms
32 | ```
33 |
34 | ## How to use
35 |
36 | ### With provided `Input`, `Select`, `Choice` helper components
37 |
38 | ```html
39 |
96 |
97 |
152 |
153 |
179 | ```
180 |
181 | ### With custom component:
182 |
183 | ```html
184 |
212 |
213 |
233 | ```
234 |
235 | ## Slot props
236 |
237 | | Name | Type |
238 | |------|------|
239 | | isSubmitting | `boolean`
240 | | isValid | `boolean`
241 | | setValue(path, value) | `function`
242 | | touchField(path) | `function`
243 | | validate() | `function`
244 | | values | `object`
245 | | errors | `object`
246 | | touched | `object`
247 |
248 | ## Contributions
249 |
250 | **All contributions are welcome.**
251 |
--------------------------------------------------------------------------------
/tests/Form/Form.spec.js:
--------------------------------------------------------------------------------
1 | import App from './TestApp.svelte';
2 | import { fireEvent, wait } from '@testing-library/svelte';
3 | import * as yup from 'yup';
4 | import { render } from '../utils';
5 |
6 | describe('Form', () => {
7 | it('click on submit button dispatches submit event and sets isSubmitting to true', async () => {
8 | const { component, getByText } = await render(App, {
9 | props: { onSubmit: jest.fn() },
10 | });
11 | const signInButton = getByText('Sign in');
12 |
13 | expect(component.form.$capture_state().$isSubmitting).toBe(false);
14 | expect(signInButton).not.toHaveAttribute('disabled');
15 |
16 | await fireEvent.click(signInButton);
17 | await wait();
18 | expect(component.onSubmit).toHaveBeenCalledTimes(1);
19 | expect(signInButton).toHaveAttribute('disabled');
20 | expect(component.form.$capture_state().$isSubmitting).toBe(true);
21 | });
22 |
23 | it('onSubmit event returns values, resetForm, setSubmitting', async done => {
24 | const {
25 | container,
26 | component,
27 | getByText,
28 | getByPlaceholderText,
29 | } = await render(App, {
30 | props: {
31 | onSubmit: jest.fn(
32 | ({ detail: { values, setSubmitting, resetForm } }) => {
33 | expect(values).toMatchSnapshot();
34 |
35 | expect(component.form.$capture_state().$isSubmitting).toBeTruthy();
36 |
37 | setSubmitting(false);
38 | let formState = component.form.$capture_state();
39 | expect(formState.$isSubmitting).toBeFalsy();
40 | expect(formState.$values).toMatchSnapshot();
41 | expect(formState.$errors).toMatchSnapshot();
42 | expect(formState.$touched).toMatchSnapshot();
43 |
44 | resetForm();
45 | formState = component.form.$capture_state();
46 | expect(formState.$values).toMatchSnapshot();
47 | expect(formState.$errors).toMatchSnapshot();
48 | expect(formState.$touched).toMatchSnapshot();
49 |
50 | done();
51 | }
52 | ),
53 | },
54 | });
55 |
56 | const emailInput = getByPlaceholderText('Email');
57 | await fireEvent.change(emailInput, {
58 | target: { value: 'test@user.com' },
59 | });
60 |
61 | const languageSelect = container.querySelector('select');
62 | await fireEvent.change(languageSelect, {
63 | target: { value: 'svelte' },
64 | });
65 |
66 | let osChoice = getByText('macOS');
67 | await fireEvent.click(osChoice);
68 |
69 | osChoice = getByText('Windows');
70 | await fireEvent.click(osChoice);
71 |
72 | const signInButton = getByText('Sign in');
73 |
74 | expect(component.form.$capture_state().$isSubmitting).toBe(false);
75 | expect(signInButton).not.toHaveAttribute('disabled');
76 |
77 | await fireEvent.click(signInButton);
78 | });
79 |
80 | it('resetForm resets values to initialValues', async done => {
81 | const { component, getByText, getByPlaceholderText } = await render(App, {
82 | props: {
83 | initialValues: {
84 | user: { email: 'initial@value.com' },
85 | },
86 | onSubmit: jest.fn(({ detail: { resetForm } }) => {
87 | expect(component.form.$capture_state().$values.user.email).toEqual(
88 | 'test@user.com'
89 | );
90 | resetForm();
91 | expect(component.form.$capture_state().$values.user.email).toEqual(
92 | 'initial@value.com'
93 | );
94 |
95 | done();
96 | }),
97 | },
98 | });
99 |
100 | const emailInput = getByPlaceholderText('Email');
101 | await fireEvent.change(emailInput, {
102 | target: { value: 'test@user.com' },
103 | });
104 |
105 | const signInButton = getByText('Sign in');
106 | await fireEvent.click(signInButton);
107 | });
108 |
109 | it('resetForm accepts optional new form data object', async done => {
110 | const { component, getByText, getByPlaceholderText } = await render(App, {
111 | props: {
112 | initialValues: {
113 | user: { email: 'initial@value.com' },
114 | },
115 | onSubmit: jest.fn(({ detail: { resetForm } }) => {
116 | expect(component.form.$capture_state().$values.user.email).toEqual(
117 | 'test@user.com'
118 | );
119 | resetForm({
120 | user: { email: 'after@reset.com' },
121 | });
122 | expect(component.form.$capture_state().$values.user.email).toEqual(
123 | 'after@reset.com'
124 | );
125 |
126 | done();
127 | }),
128 | },
129 | });
130 |
131 | const emailInput = getByPlaceholderText('Email');
132 | await fireEvent.change(emailInput, {
133 | target: { value: 'test@user.com' },
134 | });
135 |
136 | const signInButton = getByText('Sign in');
137 | await fireEvent.click(signInButton);
138 | });
139 |
140 | it('shows error message when schema is defined', async () => {
141 | const schema = yup.object().shape({
142 | user: yup.object().shape({
143 | email: yup
144 | .string()
145 | .required()
146 | .email(),
147 | }),
148 | });
149 | const {
150 | container,
151 | component,
152 | getByPlaceholderText,
153 | getByText,
154 | } = await render(App, {
155 | props: { schema },
156 | });
157 | const emailInput = getByPlaceholderText('Email');
158 |
159 | await fireEvent.change(emailInput, {
160 | target: { value: 'invalid value' },
161 | });
162 | await fireEvent.blur(emailInput);
163 | await wait(() => {
164 | expect(getByText('user.email must be a valid email')).toBeInTheDocument();
165 | });
166 | expect(component.form.$capture_state().$errors).toEqual({
167 | user: { email: 'user.email must be a valid email' },
168 | });
169 |
170 | expect(container.firstChild).toMatchSnapshot();
171 | });
172 |
173 | it('registers fields and sets default values', async () => {
174 | const { component } = await render(App);
175 |
176 | expect(component.form.$capture_state().$values).toMatchObject({
177 | user: { email: '' },
178 | language: '',
179 | os: [],
180 | });
181 | expect(component.form.$capture_state().$touched).toMatchObject({
182 | user: { email: false },
183 | language: false,
184 | os: false,
185 | });
186 | });
187 |
188 | it('isValid is undefined initially', async () => {
189 | const { component } = await render(App);
190 | expect(component.form.$capture_state().isValid).toBe(undefined);
191 | });
192 |
193 | it('sets initial values', async () => {
194 | const { component } = await render(App, {
195 | props: { initialValues: { user: { email: 'test@user.com' } } },
196 | });
197 |
198 | expect(component.form.$capture_state().$values).toMatchObject({
199 | user: { email: 'test@user.com' },
200 | language: '',
201 | os: [],
202 | });
203 | });
204 |
205 | it('matches snapshot', async () => {
206 | const { container } = await render(App);
207 | expect(container.firstChild).toMatchSnapshot();
208 | });
209 | });
210 |
--------------------------------------------------------------------------------