Skip to content
Closed
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
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
"packages/react-inertia",
"packages/vue",
"packages/vue-inertia",
"packages/alpine"
"packages/alpine",
"packages/svelte",
"packages/svelte-inertia"
],
"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\" \"npm run watch --workspace=packages/svelte-inertia\" --names=core,react,react-inertia,vue,vue-inertia,alpine,svelte,svelte-inertia",
"build": "npm run build --workspaces",
"link": "npm link --workspaces",
"typeCheck": "npm run typeCheck --workspaces",
Expand Down
2 changes: 2 additions & 0 deletions packages/svelte-inertia/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/dist
/node_modules
21 changes: 21 additions & 0 deletions packages/svelte-inertia/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-inertia/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).
53 changes: 53 additions & 0 deletions packages/svelte-inertia/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "laravel-precognition-svelte-inertia",
"version": "0.0.1",
"description": "Laravel Precognition (Svelte w/ Inertia).",
"keywords": [
"laravel",
"precognition",
"svelte",
"inertia"
],
"homepage": "https://github.com/laravel/precognition",
"type": "module",
"repository": {
"type": "git",
"url": "https://github.com/laravel/precognition"
},
"license": "MIT",
"author": "Laravel",
"main": "dist/index.js",
"files": [
"dist",
"!dist/**/*.test.*",
"!dist/**/*.spec.*"
],
"svelte": "./dist/index.svelte.js",
"types": "./dist/index.svelte.d.ts",
"exports": {
".": {
"types": "./dist/index.svelte.d.ts",
"svelte": "./dist/index.svelte.js"
}
},
"scripts": {
"watch": "rm -rf dist && tsc --watch --preserveWatchOutput",
"build": "rm -rf dist && tsc",
"typeCheck": "tsc --noEmit",
"prepublishOnly": "npm run build",
"version": "npm pkg set dependencies.laravel-precognition=$npm_package_version"
},
"peerDependencies": {
"@inertiajs/svelte": "^1.0.0 || ^2.0.0",
"svelte": "^5.0.0"
},
"dependencies": {
"laravel-precognition": "0.7.2",
"laravel-precognition-svelte": "0.0.1",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"@types/lodash-es": "^4.17.12",
"typescript": "^5.0.0"
}
}
185 changes: 185 additions & 0 deletions packages/svelte-inertia/src/index.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import { FormDataConvertible, VisitOptions } from '@inertiajs/core'
import { useForm as useInertiaForm } from '@inertiajs/svelte'
import {
client,
NamedInputEvent,
RequestMethod,
resolveMethod,
resolveUrl,
SimpleValidationErrors,
toSimpleValidationErrors,
ValidationConfig,
ValidationErrors,
} from 'laravel-precognition'
import { useForm as usePrecognitiveForm } from 'laravel-precognition-svelte'
import { fromStore, get, writable, Writable } from 'svelte/store'
import { Form } from './types'

export { client }

export const useForm = <Data extends Record<string, FormDataConvertible>>(
method: RequestMethod | (() => RequestMethod),
url: string | (() => string),
inputs: Data,
config: ValidationConfig = {},
): Writable<Form<Data>> => {
/**
* The Inertia form.
*/
const inertiaForm = useInertiaForm(inputs)

/**
* The React form.
*/
const precognitiveForm = usePrecognitiveForm(method, url, inputs, config)

/**
* The transform function.
*/
let transformer: (data: Data) => Data = (data) => data

/**
* Patch the form.
*/
const form = writable({
...fromStore(inertiaForm).current,
validating: false,
touched: precognitiveForm.touched,
touch(name: Array<string> | string | NamedInputEvent) {
precognitiveForm.touch(name)

return get(form)
},
valid: precognitiveForm.valid,
invalid: precognitiveForm.invalid,
errors: precognitiveForm.errors,
clearErrors(...names: string[]) {
form.update((prev) => {
names.forEach((name) => delete prev.errors[name])

return prev
})

if (names.length === 0) {
precognitiveForm.setErrors({})
} else {
names.forEach(precognitiveForm.forgetError)
}

return get(form)
},
reset(...names: string[]) {
// inertiaReset(...names)

precognitiveForm.reset(...names)
},
setErrors(errors: SimpleValidationErrors | ValidationErrors) {
// @ts-ignore
precognitiveForm.setErrors(errors)

return get(form)
},
setError(key: any, value?: any) {
// @ts-ignore
form.update((prev) => ({
...prev,
errors: { ...prev.errors, ...(typeof value === 'undefined' ? key : { [key]: value }) },
}))

return get(form)
},
forgetError(name: string | NamedInputEvent) {
precognitiveForm.forgetError(name)

return get(form)
},
transform(callback: (data: Data) => Data) {
form.update((prev) => {
prev.transform(callback)

return prev
})

transformer = callback

return get(form)
},
validate(name?: keyof Data | NamedInputEvent | ValidationConfig, config?: ValidationConfig) {
precognitiveForm.setData(transformer(get(form).data()))

if (typeof name === 'object' && !('target' in name)) {
config = name
name = undefined
}

if (typeof name === 'undefined') {
precognitiveForm.validate(config)
} else {
precognitiveForm.validate(name, config)
}

return get(form)
},
setValidationTimeout(duration: number) {
precognitiveForm.setValidationTimeout(duration)

return get(form)
},
validateFiles() {
precognitiveForm.validateFiles()

return get(form)
},
submit(
submitMethod: RequestMethod | Partial<VisitOptions> = {},
submitUrl?: string,
submitOptions?: Partial<VisitOptions>,
): void {
if (typeof submitMethod !== 'string') {
submitOptions = submitMethod
submitUrl = resolveUrl(url)
submitMethod = resolveMethod(method)
}

inertiaForm.update((prev) => ({
...prev,
...get(form).data(),
}))

get(inertiaForm).submit(submitMethod, submitUrl!, {
...submitOptions,
onError: (errors: SimpleValidationErrors): any => {
precognitiveForm.validator().setErrors(errors)

if (submitOptions?.onError) {
return submitOptions.onError(errors)
}
},
})
},
validator: precognitiveForm.validator,
})

/**
* Setup event listeners.
*/
form.subscribe((value) => precognitiveForm.setData(value.data()))

precognitiveForm
.validator()
.on('errorsChanged', () => {
// @ts-ignore
form.update((prev) => ({
...prev,
errors: toSimpleValidationErrors(precognitiveForm.validator().errors()),
}))
})
.on('validatingChanged', () => {
form.update((prev) => ({
...prev,
validating: precognitiveForm.validating,
}))
})

return form
}
49 changes: 49 additions & 0 deletions packages/svelte-inertia/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { VisitOptions } from '@inertiajs/core'
import { InertiaForm } from '@inertiajs/svelte'
import {
client,
RequestMethod,
SimpleValidationErrors,
ValidationErrors,
type NamedInputEvent,
type ValidationConfig,
} from 'laravel-precognition'
import { Form as PrecognitiveForm } from 'laravel-precognition-svelte/dist/types'
export { client }

type RedefinedProperties =
| 'setErrors'
| 'touch'
| 'forgetError'
| 'setValidationTimeout'
| 'submit'
| 'reset'
| 'validateFiles'
| 'setData'
| 'validate'

export type Form<Data extends Record<string, FormDataConvertible>> = Omit<PrecognitiveForm<Data>, RedefinedProperties> &
Omit<InertiaForm<Data>, RedefinedProperties> & {
setErrors(errors: SimpleValidationErrors | ValidationErrors): Form<Data>
touch(name: Array<string> | string | NamedInputEvent): Form<Data>
forgetError(string: keyof Data | NamedInputEvent): Form<Data>
setValidationTimeout(duration: number): Form<Data>
submit(config?: Partial<VisitOptions>): void
submit(method: RequestMethod, url: string, options?: Omit<VisitOptions, 'data'>): void
reset(...keys: (keyof Partial<Data>)[]): void
validateFiles(): Form<Data>
validate(name?: (keyof Data | NamedInputEvent) | ValidationConfig, config?: ValidationConfig): Form<Data>
valid: (name: keyof Data) => boolean
invalid: (name: keyof Data) => boolean
}

export type FormDataConvertible =
| Array<FormDataConvertible>
| { [key: string]: FormDataConvertible }
| Blob
| FormDataEntryValue
| Date
| boolean
| number
| null
| undefined
15 changes: 15 additions & 0 deletions packages/svelte-inertia/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"
]
}
2 changes: 2 additions & 0 deletions packages/svelte/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/dist
/node_modules
Loading