Skip to content

Commit

Permalink
feat: add svelte 5 package
Browse files Browse the repository at this point in the history
  • Loading branch information
renatomoor committed Oct 28, 2024
1 parent cd07692 commit 9436206
Show file tree
Hide file tree
Showing 8 changed files with 356 additions and 2 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
"packages/react-inertia",
"packages/vue",
"packages/vue-inertia",
"packages/alpine"
"packages/alpine",
"packages/svelte"
],
"scripts": {
"watch": "npx concurrently \"npm run watch --workspace=packages/core\" \"npm run watch --workspace=packages/react\" \"npm run watch --workspace=packages/react-inertia\" \"npm run watch --workspace=packages/vue\" \"npm run watch --workspace=packages/vue-inertia\" \"npm run watch --workspace=packages/alpine\" --names=core,react,react-inertia,vue,vue-inertia,alpine",
"watch": "npx concurrently \"npm run watch --workspace=packages/core\" \"npm run watch --workspace=packages/react\" \"npm run watch --workspace=packages/react-inertia\" \"npm run watch --workspace=packages/vue\" \"npm run watch --workspace=packages/vue-inertia\" \"npm run watch --workspace=packages/alpine\" \"npm run watch --workspace=packages/svelte\" --names=core,react,react-inertia,vue,vue-inertia,alpine,svelte",
"build": "npm run build --workspaces",
"link": "npm link --workspaces",
"typeCheck": "npm run typeCheck --workspaces",
Expand Down
24 changes: 24 additions & 0 deletions packages/svelte/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
node_modules

# Output
.output
.vercel
/.svelte-kit
/build
/dist

# OS
.DS_Store
Thumbs.db

# Env
.env
.env.*
!.env.example
!.env.test

# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

pnpm-lock.yaml
21 changes: 21 additions & 0 deletions packages/svelte/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Taylor Otwell

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.
31 changes: 31 additions & 0 deletions packages/svelte/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Laravel Precognition

<a href="https://github.com/laravel/precognition/actions"><img src="https://github.com/laravel/precognition/workflows/tests/badge.svg" alt="Test Status"></a>
<a href="https://github.com/laravel/precognition/actions"><img src="https://github.com/laravel/precognition/workflows/build/badge.svg" alt="Build Status"></a>
<a href="https://www.npmjs.com/package/laravel-precognition"><img src="https://img.shields.io/npm/dt/laravel-precognition" alt="Total Downloads"></a>
<a href="https://www.npmjs.com/package/laravel-precognition"><img src="https://img.shields.io/npm/v/laravel-precognition" alt="Latest Stable Version"></a>
<a href="https://www.npmjs.com/package/laravel-precognition"><img src="https://img.shields.io/npm/l/laravel-precognition" alt="License"></a>

## Introduction

Laravel Precognition allows you to anticipate the outcome of a future HTTP request. One of the primary use cases of Precognition is the ability to provide "live" validation in your frontend application.

## Official Documentation

Documentation for Laravel Precognition can be found on the [Laravel website](https://laravel.com/docs/precognition).

## Contributing

Thank you for considering contributing to Laravel Precognition! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).

## Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).

## Security Vulnerabilities

Please review [our security policy](https://github.com/laravel/precognition/security/policy) on how to report security vulnerabilities.

## License

Laravel Precognition is open-sourced software licensed under the [MIT license](LICENSE.md).
40 changes: 40 additions & 0 deletions packages/svelte/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"name": "laravel-precognition-svelte",
"version": "0.0.1",
"description": "Laravel Precognition (Svelte).",
"keywords": [
"laravel",
"precognition",
"svelte"
],
"homepage": "https://github.com/laravel/precognition",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/laravel/precognition"
},
"license": "MIT",
"author": "Laravel",
"main": "dist/index.svelte.js",
"files": [
"/dist"
],
"scripts": {
"watch": "rm -rf dist && tsc --watch",
"build": "rm -rf dist && tsc",
"typeCheck": "tsc --noEmit",
"prepublishOnly": "npm run build",
"version": "npm pkg set dependencies.laravel-precognition=$npm_package_version"
},
"peerDependencies": {
"svelte": "^5.0.0"
},
"dependencies": {
"laravel-precognition": "0.5.11",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"@types/lodash-es": "^4.17.12",
"typescript": "^5.0.0"
}
}
198 changes: 198 additions & 0 deletions packages/svelte/src/index.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import { get, cloneDeep, set } from 'lodash-es'

import {
client,
createValidator,
type RequestMethod,
resolveName,
toSimpleValidationErrors,
type ValidationConfig,
resolveUrl,
resolveMethod,
} from 'laravel-precognition'

import { Form } from './types.js'

export { client }
export const useForm = <Data extends Record<string, unknown>>(method: RequestMethod | (() => RequestMethod), url: string | (() => string), inputs: Data, config: ValidationConfig = {}): Data & Form<Data> => {
/**
* The original data.
*/
const originalData = cloneDeep(inputs)

/**
* The original input names.
*/
const originalInputs: (keyof Data)[] = Object.keys(originalData)

/**
* Reactive valid state.
*/
// @ts-ignore
let valid = $state<string[]>([])

/**
* Reactive touched state.
*/
// @ts-ignore
let touched = $state<string[]>([])

/**
* Reactive errors.
*/
// @ts-ignore
let errors = $state<Record<string, any>>({})

/**
* Reactive hasErrors.
*/
// @ts-ignore
let hasErrors = $state<boolean>(false)

/**
* Reactive Validating.
*/
// @ts-ignore
let validating = $state<boolean>(false)

/**
* Reactive Processing.
*/
// @ts-ignore
let processing = $state<boolean>(false)

/**
* Reactive Data state
*/
// @ts-ignore
const data = $state<Data>(cloneDeep(originalData))

/**
* The validator instance.
*/
const validator = createValidator((client) => client[resolveMethod(method)](resolveUrl(url), form.getData(), config), originalData)
.on('validatingChanged', () => {
validating = validator.validating()
})
.on('validatedChanged', () => {
valid = validator.valid()
})
.on('touchedChanged', () => {
touched = validator.touched()
})
.on('errorsChanged', () => {
hasErrors = validator.hasErrors()
errors = toSimpleValidationErrors(validator.errors())
valid = validator.valid()
})

/**
* Resolve the config for a form submission.
*/
const resolveSubmitConfig = (config: any) => ({
...config,
precognitive: false,
onStart: () => {
processing = true
config.onStart?.()
},
onFinish: () => {
processing = false
config.onFinish?.()
},
onValidationError: (response: any, error: any) => {
validator.setErrors(response.data.errors)
return config.onValidationError
? config.onValidationError(response)
// @ts-ignore
: Promise.reject(error)
},
})

/**
* Create a new form instance.
*/
const form: Record<string, any> = {
data,
setData(newData: Record<string, unknown>) {
Object.keys(newData).forEach((input) => {
// @ts-ignore
data[input] = newData[input]
})
return form
},
touched(name: string) {
return touched.includes(resolveName(name))
},
touch(name: string) {
validator.touch(name)
return form
},
validate(name: string | undefined, config: any) {
if (name === undefined) {
validator.validate(config)
} else {
validator.validate(name, get(data, name), config)
}
return form
},
valid(name: string) {
return valid.includes(resolveName(name))
},
invalid(name: string) {
return typeof form.errors[name] !== 'undefined'
},
setErrors(newErrors: any) {
validator.setErrors(newErrors)
return form
},
forgetError(name: string) {
validator.forgetError(name)
return form
},
reset(...names: string[]) {
const original = cloneDeep(originalData)

if (names.length === 0) {
originalInputs.forEach((name) => (data[name] = original[name]))
} else {
names.forEach((name : string) => set(data, name, get(original, name)))
}

validator.reset(...names)

return form
},
setValidationTimeout(duration: number) {
validator.setTimeout(duration)
return form
},
submit(config = {}) {
return client[resolveMethod(method)](resolveUrl(url), form.getData(), resolveSubmitConfig(config))
},
validateFiles() {
validator.validateFiles()
return form
},
validator() {
return validator
},
get validating() {
return validating
},
get processing() {
return processing
},
get errors() {
return errors
},
get hasErrors() {
return hasErrors
},
getData() {
return cloneDeep(data)
},
}

return form as Data & Form<Data>
}
24 changes: 24 additions & 0 deletions packages/svelte/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { client, type RequestMethod, type ValidationConfig, type Config, type NamedInputEvent, type Validator } from 'laravel-precognition'
export { client }
export interface Form<Data extends Record<string, unknown>> {
processing: boolean;
validating: boolean;
errors: Partial<Record<keyof Data, string>>;
hasErrors: boolean;
touched(name: keyof Data): boolean;
touch(name: string | NamedInputEvent | Array<string>): Data & Form<Data>;
data: Data;
setData(data: Record<string, unknown>): Data & Form<Data>;
valid(name: keyof Data): boolean;
invalid(name: keyof Data): boolean;
validate(name?: (keyof Data | NamedInputEvent) | ValidationConfig, config?: ValidationConfig): Data & Form<Data>;
setErrors(errors: Partial<Record<keyof Data, string | string[]>>): Data & Form<Data>;
forgetError(string: keyof Data | NamedInputEvent): Data & Form<Data>;
setValidationTimeout(duration: number): Data & Form<Data>;
submit(config?: Config): Promise<unknown>;
reset(...keys: (keyof Partial<Data>)[]): Data & Form<Data>;
validateFiles(): Data & Form<Data>;
validator(): Validator;
getData(): Data;
}
export declare const useForm: <Data extends Record<string, unknown>>(method: RequestMethod | (() => RequestMethod), url: string | (() => string), inputs: Data, config?: ValidationConfig) => Data & Form<Data>
15 changes: 15 additions & 0 deletions packages/svelte/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"outDir": "./dist",
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"resolveJsonModule": true,
"strict": true,
"declaration": true,
"esModuleInterop": true
},
"include": [
"./src/index.svelte.ts"
]
}

0 comments on commit 9436206

Please sign in to comment.