@inertiajs/svelte 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Jonathan Reinink <jonathan@reinink.ca>
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.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@inertiajs/svelte",
3
+ "version": "1.0.0-beta.1",
4
+ "license": "MIT",
5
+ "description": "The Svelte adapter for Inertia.js",
6
+ "contributors": [
7
+ "Jonathan Reinink <jonathan@reinink.ca>",
8
+ "Pedro Borges <oi@pedroborg.es>"
9
+ ],
10
+ "homepage": "https://inertiajs.com/",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/inertiajs/inertia.git",
14
+ "directory": "packages/svelte"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/inertiajs/inertia/issues"
18
+ },
19
+ "keywords": [
20
+ "svelte"
21
+ ],
22
+ "main": "src/index.js",
23
+ "peerDependencies": {
24
+ "svelte": "^3.20.0"
25
+ },
26
+ "dependencies": {
27
+ "@inertiajs/core": "1.0.0-beta.1",
28
+ "lodash.isequal": "^4.5.0"
29
+ }
30
+ }
package/readme.md ADDED
@@ -0,0 +1,3 @@
1
+ # Inertia.js Svelte Adapter
2
+
3
+ Visit [inertiajs.com](https://inertiajs.com/) to learn more.
package/src/App.svelte ADDED
@@ -0,0 +1,32 @@
1
+ <script>
2
+ import { router } from '@inertiajs/core'
3
+ import Render, { h } from './Render.svelte'
4
+ import store from './store'
5
+
6
+ export let initialPage, resolveComponent
7
+
8
+ router.init({
9
+ initialPage,
10
+ resolveComponent,
11
+ swapComponent: async ({ component, page, preserveState }) => {
12
+ store.update((current) => ({
13
+ component,
14
+ page,
15
+ key: preserveState ? current.key : Date.now()
16
+ }))
17
+ }
18
+ })
19
+
20
+ $: child = $store.component && h($store.component.default, $store.page.props)
21
+ $: layout = $store.component && $store.component.layout
22
+ $: components = layout
23
+ ? Array.isArray(layout)
24
+ ? layout
25
+ .concat(child)
26
+ .reverse()
27
+ .reduce((child, layout) => h(layout, $store.page.props, [child]))
28
+ : h(layout, $store.page.props, [child])
29
+ : child
30
+ </script>
31
+
32
+ <Render {...components} />
@@ -0,0 +1,49 @@
1
+ <script>
2
+ import { mergeDataIntoQueryString, router, shouldIntercept } from '@inertiajs/core'
3
+ import { beforeUpdate, createEventDispatcher } from 'svelte'
4
+
5
+ const dispatch = createEventDispatcher()
6
+
7
+ export let
8
+ data = {},
9
+ href,
10
+ method = 'get',
11
+ replace = false,
12
+ preserveScroll = false,
13
+ preserveState = null,
14
+ only = [],
15
+ headers = {}
16
+
17
+ beforeUpdate(() => {
18
+ method = method.toLowerCase()
19
+ const [_href, _data] = mergeDataIntoQueryString(method, href, data)
20
+ href = _href
21
+ data = _data
22
+
23
+ if (method !== 'get') {
24
+ console.warn(`Creating POST/PUT/PATCH/DELETE <a> links is discouraged as it causes "Open Link in New Tab/Window" accessibility issues.\n\nPlease specify a more appropriate element using the "inertia" directive. For example:\n\n<button use:inertia={{ method: 'post', href: '${href}' }}>...</button>`)
25
+ }
26
+ })
27
+
28
+ function visit(event) {
29
+ dispatch('click', event)
30
+
31
+ if (shouldIntercept(event)) {
32
+ event.preventDefault()
33
+
34
+ router.visit(href, {
35
+ data,
36
+ method,
37
+ preserveScroll,
38
+ preserveState: preserveState !== null ? preserveState : (method !== 'get'),
39
+ replace,
40
+ only,
41
+ headers,
42
+ })
43
+ }
44
+ }
45
+ </script>
46
+
47
+ <a {...$$restProps} {href} on:click={visit}>
48
+ <slot />
49
+ </a>
@@ -0,0 +1,25 @@
1
+ <script context="module">
2
+ export const h = (component, props, children) => {
3
+ return {
4
+ component,
5
+ ...(props ? { props } : {}),
6
+ ...(children ? { children } : {})
7
+ }
8
+ }
9
+ </script>
10
+
11
+ <script>
12
+ import store from './store'
13
+
14
+ export let component
15
+ export let props = {}
16
+ export let children = []
17
+ </script>
18
+
19
+ {#if $store.component}
20
+ <svelte:component this={component} {...props}>
21
+ {#each children as child, index (component && component.length === index ? $store.key : null)}
22
+ <svelte:self {...child} />
23
+ {/each}
24
+ </svelte:component>
25
+ {/if}
@@ -0,0 +1,32 @@
1
+ import { setupProgress } from '@inertiajs/core'
2
+ import App from './App.svelte'
3
+
4
+ export default async function createInertiaApp({ id = 'app', resolve, setup, progress = {}, page, render }) {
5
+ const isServer = typeof window === 'undefined'
6
+ const el = isServer ? null : document.getElementById(id)
7
+ const initialPage = page || JSON.parse(el.dataset.page)
8
+ const resolveComponent = (name) => Promise.resolve(resolve(name))
9
+
10
+ let head = []
11
+
12
+ const svelteApp = await resolveComponent(initialPage.component).then((initialComponent) => {
13
+ return setup({
14
+ el,
15
+ App,
16
+ props: {
17
+ initialPage,
18
+ initialComponent,
19
+ resolveComponent,
20
+ onHeadUpdate: isServer ? (elements) => (head = elements) : null,
21
+ },
22
+ })
23
+ })
24
+
25
+ if (!isServer && progress) {
26
+ setupProgress(progress)
27
+ }
28
+
29
+ if (isServer) {
30
+ // TODO
31
+ }
32
+ }
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { router } from '@inertiajs/core'
2
+ export { default as createInertiaApp } from './createInertiaApp'
3
+ export { default as inertia } from './link'
4
+ export { default as Link } from './Link.svelte'
5
+ export { default as page } from './page'
6
+ export { default as remember } from './remember'
7
+ export { default as useForm } from './useForm'
package/src/link.js ADDED
@@ -0,0 +1,49 @@
1
+ import { mergeDataIntoQueryString, router, shouldIntercept } from '@inertiajs/core'
2
+ import { createEventDispatcher } from 'svelte'
3
+
4
+ export default (node, options = {}) => {
5
+ const [href, data] = mergeDataIntoQueryString(
6
+ options.method || 'get',
7
+ node.href || options.href || '',
8
+ options.data || {},
9
+ options.queryStringArrayFormat || 'brackets',
10
+ )
11
+ node.href = href
12
+ options.data = data
13
+
14
+ const dispatch = createEventDispatcher()
15
+
16
+ function visit(event) {
17
+ dispatch('click', event)
18
+
19
+ const href = node.href || options.href
20
+
21
+ if (!href) {
22
+ throw new Error('Option "href" is required')
23
+ }
24
+
25
+ if (shouldIntercept(event)) {
26
+ event.preventDefault()
27
+ router.visit(href, options)
28
+ }
29
+ }
30
+
31
+ node.addEventListener('click', visit)
32
+
33
+ return {
34
+ update(newOptions) {
35
+ const [href, data] = mergeDataIntoQueryString(
36
+ newOptions.method || 'get',
37
+ node.href || newOptions.href,
38
+ newOptions.data || {},
39
+ newOptions.queryStringArrayFormat || 'brackets',
40
+ )
41
+ node.href = href
42
+ newOptions.data = data
43
+ options = newOptions
44
+ },
45
+ destroy() {
46
+ node.removeEventListener('click', visit)
47
+ },
48
+ }
49
+ }
package/src/page.js ADDED
@@ -0,0 +1,6 @@
1
+ import { derived } from 'svelte/store'
2
+ import store from './store'
3
+
4
+ const page = derived(store, ($store) => $store.page)
5
+
6
+ export default page
@@ -0,0 +1,15 @@
1
+ import { router } from '@inertiajs/core'
2
+ import { onDestroy } from 'svelte'
3
+ import { writable } from 'svelte/store'
4
+
5
+ function useRemember(initialState, key) {
6
+ const restored = router.restore(key)
7
+ const store = writable(restored !== undefined ? restored : initialState)
8
+ const unsubscribe = store.subscribe((state) => router.remember(state, key))
9
+
10
+ onDestroy(unsubscribe)
11
+
12
+ return store
13
+ }
14
+
15
+ export default useRemember
package/src/store.js ADDED
@@ -0,0 +1,10 @@
1
+ import { writable } from 'svelte/store'
2
+
3
+ const store = writable({
4
+ component: null,
5
+ layout: [],
6
+ page: {},
7
+ key: null,
8
+ })
9
+
10
+ export default store
package/src/useForm.js ADDED
@@ -0,0 +1,208 @@
1
+ import { router } from '@inertiajs/core'
2
+ import isEqual from 'lodash.isequal'
3
+ import { writable } from 'svelte/store'
4
+
5
+ function useForm(...args) {
6
+ const rememberKey = typeof args[0] === 'string' ? args[0] : null
7
+ const data = (typeof args[0] === 'string' ? args[1] : args[0]) || {}
8
+ const restored = rememberKey ? router.restore(rememberKey) : null
9
+ let defaults = data
10
+ let cancelToken = null
11
+ let recentlySuccessfulTimeoutId = null
12
+ let transform = (data) => data
13
+
14
+ const store = writable({
15
+ ...(restored ? restored.data : data),
16
+ isDirty: false,
17
+ errors: restored ? restored.errors : {},
18
+ hasErrors: false,
19
+ progress: null,
20
+ wasSuccessful: false,
21
+ recentlySuccessful: false,
22
+ processing: false,
23
+ setStore(key, value) {
24
+ store.update((store) => {
25
+ return Object.assign({}, store, typeof key === 'string' ? { [key]: value } : key)
26
+ })
27
+ },
28
+ data() {
29
+ return Object.keys(data).reduce((carry, key) => {
30
+ carry[key] = this[key]
31
+ return carry
32
+ }, {})
33
+ },
34
+ transform(callback) {
35
+ transform = callback
36
+
37
+ return this
38
+ },
39
+ defaults(key, value) {
40
+ if (typeof key === 'undefined') {
41
+ defaults = Object.assign(defaults, this.data())
42
+
43
+ return this
44
+ }
45
+
46
+ defaults = Object.assign(defaults, value ? { [key]: value } : key)
47
+
48
+ return this
49
+ },
50
+ reset(...fields) {
51
+ if (fields.length === 0) {
52
+ this.setStore(defaults)
53
+ } else {
54
+ this.setStore(
55
+ Object.keys(defaults)
56
+ .filter((key) => fields.includes(key))
57
+ .reduce((carry, key) => {
58
+ carry[key] = defaults[key]
59
+ return carry
60
+ }, {}),
61
+ )
62
+ }
63
+
64
+ return this
65
+ },
66
+ setError(key, value) {
67
+ this.setStore('errors', {
68
+ ...this.errors,
69
+ ...(value ? { [key]: value } : key),
70
+ })
71
+
72
+ return this
73
+ },
74
+ clearErrors(...fields) {
75
+ this.setStore(
76
+ 'errors',
77
+ Object.keys(this.errors).reduce(
78
+ (carry, field) => ({
79
+ ...carry,
80
+ ...(fields.length > 0 && !fields.includes(field) ? { [field]: this.errors[field] } : {}),
81
+ }),
82
+ {},
83
+ ),
84
+ )
85
+
86
+ return this
87
+ },
88
+ submit(method, url, options = {}) {
89
+ const data = transform(this.data())
90
+ const _options = {
91
+ ...options,
92
+ onCancelToken: (token) => {
93
+ cancelToken = token
94
+
95
+ if (options.onCancelToken) {
96
+ return options.onCancelToken(token)
97
+ }
98
+ },
99
+ onBefore: (visit) => {
100
+ this.setStore('wasSuccessful', false)
101
+ this.setStore('recentlySuccessful', false)
102
+ clearTimeout(recentlySuccessfulTimeoutId)
103
+
104
+ if (options.onBefore) {
105
+ return options.onBefore(visit)
106
+ }
107
+ },
108
+ onStart: (visit) => {
109
+ this.setStore('processing', true)
110
+
111
+ if (options.onStart) {
112
+ return options.onStart(visit)
113
+ }
114
+ },
115
+ onProgress: (event) => {
116
+ this.setStore('progress', event)
117
+
118
+ if (options.onProgress) {
119
+ return options.onProgress(event)
120
+ }
121
+ },
122
+ onSuccess: async (page) => {
123
+ this.setStore('processing', false)
124
+ this.setStore('progress', null)
125
+ this.clearErrors()
126
+ this.setStore('wasSuccessful', true)
127
+ this.setStore('recentlySuccessful', true)
128
+ recentlySuccessfulTimeoutId = setTimeout(() => this.setStore('recentlySuccessful', false), 2000)
129
+
130
+ if (options.onSuccess) {
131
+ return options.onSuccess(page)
132
+ }
133
+ },
134
+ onError: (errors) => {
135
+ this.setStore('processing', false)
136
+ this.setStore('progress', null)
137
+ this.clearErrors().setError(errors)
138
+
139
+ if (options.onError) {
140
+ return options.onError(errors)
141
+ }
142
+ },
143
+ onCancel: () => {
144
+ this.setStore('processing', false)
145
+ this.setStore('progress', null)
146
+
147
+ if (options.onCancel) {
148
+ return options.onCancel()
149
+ }
150
+ },
151
+ onFinish: () => {
152
+ this.setStore('processing', false)
153
+ this.setStore('progress', null)
154
+ cancelToken = null
155
+
156
+ if (options.onFinish) {
157
+ return options.onFinish()
158
+ }
159
+ },
160
+ }
161
+
162
+ if (method === 'delete') {
163
+ router.delete(url, { ..._options, data })
164
+ } else {
165
+ router[method](url, data, _options)
166
+ }
167
+ },
168
+ get(url, options) {
169
+ this.submit('get', url, options)
170
+ },
171
+ post(url, options) {
172
+ this.submit('post', url, options)
173
+ },
174
+ put(url, options) {
175
+ this.submit('put', url, options)
176
+ },
177
+ patch(url, options) {
178
+ this.submit('patch', url, options)
179
+ },
180
+ delete(url, options) {
181
+ this.submit('delete', url, options)
182
+ },
183
+ cancel() {
184
+ if (cancelToken) {
185
+ cancelToken.cancel()
186
+ }
187
+ },
188
+ })
189
+
190
+ store.subscribe((form) => {
191
+ if (form.isDirty === isEqual(form.data(), defaults)) {
192
+ form.setStore('isDirty', !form.isDirty)
193
+ }
194
+
195
+ const hasErrors = Object.keys(form.errors).length > 0
196
+ if (form.hasErrors !== hasErrors) {
197
+ form.setStore('hasErrors', !form.hasErrors)
198
+ }
199
+
200
+ if (rememberKey) {
201
+ router.remember({ data: form.data(), errors: form.errors }, rememberKey)
202
+ }
203
+ })
204
+
205
+ return store
206
+ }
207
+
208
+ export default useForm