@inertia-solid/solid 0.0.0-stage → 0.1.0

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.
Files changed (59) hide show
  1. package/LICENSE +47 -0
  2. package/README.md +10 -2
  3. package/dist/App.d.ts +13 -0
  4. package/dist/App.jsx +90 -0
  5. package/dist/Deferred.d.ts +17 -0
  6. package/dist/Deferred.jsx +70 -0
  7. package/dist/Form.d.ts +13 -0
  8. package/dist/Form.jsx +237 -0
  9. package/dist/Head.d.ts +6 -0
  10. package/dist/Head.js +117 -0
  11. package/dist/HeadContext.d.ts +4 -0
  12. package/dist/HeadContext.js +3 -0
  13. package/dist/InfiniteScroll.d.ts +23 -0
  14. package/dist/InfiniteScroll.jsx +186 -0
  15. package/dist/Link.d.ts +16 -0
  16. package/dist/Link.jsx +155 -0
  17. package/dist/PageContext.d.ts +4 -0
  18. package/dist/PageContext.js +3 -0
  19. package/dist/Render.d.ts +8 -0
  20. package/dist/Render.jsx +27 -0
  21. package/dist/WhenMounted.d.ts +8 -0
  22. package/dist/WhenMounted.jsx +12 -0
  23. package/dist/WhenVisible.d.ts +22 -0
  24. package/dist/WhenVisible.jsx +67 -0
  25. package/dist/createInertiaApp.d.ts +40 -0
  26. package/dist/createInertiaApp.js +77 -0
  27. package/dist/echo.d.ts +6 -0
  28. package/dist/echo.js +3 -0
  29. package/dist/formHelper.d.ts +44 -0
  30. package/dist/formHelper.js +1 -0
  31. package/dist/index.d.ts +32 -0
  32. package/dist/index.js +18 -0
  33. package/dist/layoutProps.d.ts +11 -0
  34. package/dist/layoutProps.js +16 -0
  35. package/dist/renderTree.d.ts +21 -0
  36. package/dist/renderTree.js +72 -0
  37. package/dist/server.d.ts +1 -0
  38. package/dist/server.js +1 -0
  39. package/dist/slot.d.ts +10 -0
  40. package/dist/slot.js +13 -0
  41. package/dist/types.d.ts +31 -0
  42. package/dist/types.js +1 -0
  43. package/dist/useForm.d.ts +11 -0
  44. package/dist/useForm.js +106 -0
  45. package/dist/useFormState.d.ts +33 -0
  46. package/dist/useFormState.js +278 -0
  47. package/dist/useHttp.d.ts +10 -0
  48. package/dist/useHttp.js +172 -0
  49. package/dist/usePage.d.ts +6 -0
  50. package/dist/usePage.js +9 -0
  51. package/dist/usePoll.d.ts +12 -0
  52. package/dist/usePoll.js +28 -0
  53. package/dist/usePrefetch.d.ts +10 -0
  54. package/dist/usePrefetch.js +42 -0
  55. package/dist/useProp.d.ts +8 -0
  56. package/dist/useProp.js +27 -0
  57. package/dist/useRemember.d.ts +14 -0
  58. package/dist/useRemember.js +36 -0
  59. package/package.json +62 -3
package/LICENSE ADDED
@@ -0,0 +1,47 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 inertia-solid contributors
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
+
23
+ ---
24
+
25
+ Parts of src/ are adapted from the official adapters in inertiajs/inertia v3.11.0 (commit f3125577a9e5a5a8bcdecffefc2e6577282f7868): packages/react/src, packages/vue3/src and packages/svelte/src. Those parts are also under the notice below.
26
+
27
+ MIT License
28
+
29
+ Copyright (c) Jonathan Reinink <jonathan@reinink.ca>
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy
32
+ of this software and associated documentation files (the "Software"), to deal
33
+ in the Software without restriction, including without limitation the rights
34
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
35
+ copies of the Software, and to permit persons to whom the Software is
36
+ furnished to do so, subject to the following conditions:
37
+
38
+ The above copyright notice and this permission notice shall be included in all
39
+ copies or substantial portions of the Software.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
46
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
47
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @inertia-solid/solid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Inertia.js](https://inertiajs.com) v3 client adapter for [Solid](https://www.solidjs.com) 2.0.
4
+
5
+ ```sh
6
+ npm install @inertia-solid/solid solid-js @solidjs/web
7
+ ```
8
+
9
+ Compile Solid with `@solidjs/vite-plugin` ^3.0.1. The package ships JSX under a `solid` export condition, which the plugin compiles for your client and SSR builds.
10
+
11
+ See the [project README](https://github.com/mboisvertdupras/inertia-solid#readme) for setup, Vite configuration and usage.
package/dist/App.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type HeadManagerOnUpdateCallback, type HeadManagerTitleCallback, type Page, type PageProps, type ServerHeadOption } from '@inertiajs/core';
2
+ import type { JSX } from '@solidjs/web';
3
+ import type { ResolvedComponent } from './types';
4
+ export interface InertiaAppProps<SharedProps extends PageProps = PageProps> {
5
+ initialPage: Page<SharedProps>;
6
+ initialComponent: ResolvedComponent;
7
+ resolveComponent: (name: string, page?: Page) => ResolvedComponent | Promise<ResolvedComponent>;
8
+ titleCallback?: HeadManagerTitleCallback;
9
+ onHeadUpdate?: HeadManagerOnUpdateCallback;
10
+ defaultLayout?: (name: string, page: Page) => unknown;
11
+ serverHead?: ServerHeadOption;
12
+ }
13
+ export default function App<SharedProps extends PageProps = PageProps>(props: InertiaAppProps<SharedProps>): JSX.Element;
package/dist/App.jsx ADDED
@@ -0,0 +1,90 @@
1
+ import { createHeadManager, resolveServerHead, router, } from '@inertiajs/core';
2
+ import { createMemo, createSignal, createStore, flush, onSettled, untrack } from 'solid-js';
3
+ import HeadContext from './HeadContext';
4
+ import { layoutPropsStore, resetLayoutProps } from './layoutProps';
5
+ import PageContext from './PageContext';
6
+ import Render from './Render';
7
+ import { buildRenderTree } from './renderTree';
8
+ const noLayoutProps = { shared: {}, named: {} };
9
+ /** Writes `source`'s keys into `target`, deleting the ones it lacks. A value that is the same object leaves its readers alone. */
10
+ function assignKeys(target, source, skip) {
11
+ for (const key of Object.keys(target)) {
12
+ if (key !== skip && !Reflect.has(source, key)) {
13
+ Reflect.deleteProperty(target, key);
14
+ }
15
+ }
16
+ for (const key of Object.keys(source)) {
17
+ if (key !== skip) {
18
+ Reflect.set(target, key, Reflect.get(source, key));
19
+ }
20
+ }
21
+ }
22
+ export default function App(props) {
23
+ const isServer = typeof window === 'undefined';
24
+ const [page, setPage] = createStore({
25
+ ...props.initialPage,
26
+ props: { ...props.initialPage.props },
27
+ flash: props.initialPage.flash ?? {},
28
+ });
29
+ const [current, setCurrent] = createSignal({ component: props.initialComponent, key: null });
30
+ const [dynamicLayoutProps, setDynamicLayoutProps] = createSignal(isServer ? noLayoutProps : layoutPropsStore.get());
31
+ const headManager = createHeadManager(isServer,
32
+ // Core runs this inside Head's effect callbacks, where a tracked store read only warns
33
+ (title) => untrack(() => (props.titleCallback ? props.titleCallback(title, page) : title)), props.onHeadUpdate ?? (() => { }), resolveServerHead(props.initialPage, props.serverHead));
34
+ const tree = createMemo(() => buildRenderTree({
35
+ component: current().component,
36
+ page,
37
+ key: current().key,
38
+ defaultLayout: props.defaultLayout,
39
+ dynamicLayoutProps: dynamicLayoutProps(),
40
+ }));
41
+ if (!isServer) {
42
+ let swaps = 0;
43
+ router.init({
44
+ initialPage: props.initialPage,
45
+ resolveComponent: props.resolveComponent,
46
+ swapComponent: async ({ component, page: nextPage, preserveState }) => {
47
+ if (!preserveState) {
48
+ resetLayoutProps();
49
+ // Core notifies subscribers in a microtask, so read the reset store now
50
+ setDynamicLayoutProps(layoutPropsStore.get());
51
+ }
52
+ setPage((draft) => {
53
+ assignKeys(draft.props, nextPage.props);
54
+ assignKeys(draft, nextPage, 'props');
55
+ });
56
+ setCurrent((previous) => ({ component, key: preserveState ? previous.key : ++swaps }));
57
+ flush();
58
+ // The title callback reads the page store, so rerun it after the swap
59
+ headManager.forceUpdate();
60
+ },
61
+ onFlash: (flash) => {
62
+ setPage((draft) => {
63
+ draft.flash = flash;
64
+ });
65
+ flush();
66
+ },
67
+ });
68
+ }
69
+ // Called on the server too, where it never runs: it takes the same hydration id slot as on the client
70
+ onSettled(() => {
71
+ const syncServerHead = (event) => {
72
+ headManager.updateServerHead(resolveServerHead(event.detail.page, props.serverHead));
73
+ };
74
+ const removeNavigateListener = router.on('navigate', syncServerHead);
75
+ const removeClientVisitListener = router.on('clientVisit', syncServerHead);
76
+ const unsubscribeLayoutProps = layoutPropsStore.subscribe(() => setDynamicLayoutProps(layoutPropsStore.get()));
77
+ // A page can call setLayoutProps while it mounts, before this runs
78
+ setDynamicLayoutProps(layoutPropsStore.get());
79
+ return () => {
80
+ removeNavigateListener();
81
+ removeClientVisitListener();
82
+ unsubscribeLayoutProps();
83
+ };
84
+ });
85
+ return (<HeadContext value={headManager}>
86
+ <PageContext value={page}>
87
+ <Render node={tree}/>
88
+ </PageContext>
89
+ </HeadContext>);
90
+ }
@@ -0,0 +1,17 @@
1
+ import type { JSX } from '@solidjs/web';
2
+ import { type Slot } from './slot';
3
+ export interface DeferredSlotProps {
4
+ readonly reloading: boolean;
5
+ }
6
+ export interface DeferredProps {
7
+ /** Plain children, or a render function receiving `{ reloading }`. */
8
+ children: Slot<DeferredSlotProps>;
9
+ rescue?: Slot<DeferredSlotProps>;
10
+ fallback: JSX.Element | (() => JSX.Element);
11
+ data: string | string[];
12
+ }
13
+ /**
14
+ * Renders `fallback` until every prop in `data` is defined, then its children. A prop the server could not resolve
15
+ * renders `rescue`, or `fallback` without one. `reloading` is true while a partial reload of those props is in flight.
16
+ */
17
+ export default function Deferred(props: DeferredProps): JSX.Element;
@@ -0,0 +1,70 @@
1
+ import { isSameUrlWithoutQueryOrHash, partialReloadRequestsSomeProps, router } from '@inertiajs/core';
2
+ import { get } from 'es-toolkit/compat';
3
+ import { createMemo, createSignal, Match, onSettled, Switch, untrack } from 'solid-js';
4
+ import { renderSlot } from './slot';
5
+ import usePage from './usePage';
6
+ /**
7
+ * Renders `fallback` until every prop in `data` is defined, then its children. A prop the server could not resolve
8
+ * renders `rescue`, or `fallback` without one. `reloading` is true while a partial reload of those props is in flight.
9
+ */
10
+ export default function Deferred(props) {
11
+ untrack(() => {
12
+ if (!props.data) {
13
+ throw new Error('`<Deferred>` requires a `data` prop to be a string or array of strings');
14
+ }
15
+ if (!('fallback' in props)) {
16
+ throw new Error('`<Deferred>` requires a `fallback` prop');
17
+ }
18
+ });
19
+ const page = usePage();
20
+ const [activeReloads, setActiveReloads] = createSignal(new Set());
21
+ const keys = createMemo(() => (Array.isArray(props.data) ? props.data : [props.data]));
22
+ const reloading = createMemo(() => activeReloads().size > 0);
23
+ const state = createMemo(() => {
24
+ const rescued = keys().some((key) => page.rescuedProps?.includes(key));
25
+ if (!rescued && keys().every((key) => get(page.props, key) !== undefined)) {
26
+ return 'children';
27
+ }
28
+ return rescued ? 'rescued' : 'fallback';
29
+ });
30
+ onSettled(() => {
31
+ const removeStartListener = router.on('start', (event) => {
32
+ const visit = event.detail.visit;
33
+ if (visit.preserveState === true &&
34
+ isSameUrlWithoutQueryOrHash(visit.url, window.location) &&
35
+ partialReloadRequestsSomeProps(visit, keys())) {
36
+ setActiveReloads((reloads) => new Set(reloads).add(visit));
37
+ }
38
+ });
39
+ const removeFinishListener = router.on('finish', (event) => {
40
+ const visit = event.detail.visit;
41
+ setActiveReloads((reloads) => {
42
+ if (!reloads.has(visit)) {
43
+ return reloads;
44
+ }
45
+ const remaining = new Set(reloads);
46
+ remaining.delete(visit);
47
+ return remaining;
48
+ });
49
+ });
50
+ return () => {
51
+ removeStartListener();
52
+ removeFinishListener();
53
+ };
54
+ });
55
+ const slot = {
56
+ get reloading() {
57
+ return reloading();
58
+ },
59
+ };
60
+ const render = (content) => renderSlot(content, slot);
61
+ const renderRescued = () => {
62
+ const rescue = props.rescue;
63
+ return rescue ? render(rescue) : render(props.fallback);
64
+ };
65
+ return (<Switch>
66
+ <Match when={state() === 'children'}>{render(props.children)}</Match>
67
+ <Match when={state() === 'rescued'}>{renderRescued()}</Match>
68
+ <Match when={state() === 'fallback'}>{render(props.fallback)}</Match>
69
+ </Switch>);
70
+ }
package/dist/Form.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type FormComponentProps, type FormComponentRef, type FormComponentSlotProps, type FormDataConvertible } from '@inertiajs/core';
2
+ import type { JSX } from '@solidjs/web';
3
+ export type FormProps<TForm extends object = Record<string, FormDataConvertible>> = FormComponentProps<TForm> & Omit<JSX.FormHTMLAttributes<HTMLFormElement>, keyof FormComponentProps | 'children' | 'ref'> & {
4
+ /** Plain children, or a render function receiving the reactive slot props (members are getters and methods). */
5
+ children?: JSX.Element | ((slot: FormComponentSlotProps<TForm>) => JSX.Element);
6
+ /** Receives the same object as the slot props once the form is created. */
7
+ ref?: (form: FormComponentRef<TForm>) => void;
8
+ };
9
+ type FormValues = Record<string, FormDataConvertible>;
10
+ declare const _default: <TForm extends object = FormValues>(props: FormProps<TForm>) => JSX.Element;
11
+ export default _default;
12
+ /** The nearest `<Form>`'s ref object, or `undefined` outside a form. */
13
+ export declare function useFormContext<TForm extends object = FormValues>(): FormComponentRef<TForm> | undefined;
package/dist/Form.jsx ADDED
@@ -0,0 +1,237 @@
1
+ import { config, FormComponentResetSymbol, formDataToObject, isUrlMethodPair, mergeDataIntoQueryString, resetFormFields, resolveUrlMethodPairComponent, UseFormUtils, } from '@inertiajs/core';
2
+ import { isEqual } from 'es-toolkit';
3
+ import { createContext, createEffect, createMemo, createSignal, omit, onSettled, useContext } from 'solid-js';
4
+ import { renderSlot } from './slot';
5
+ import useForm, {} from './useForm';
6
+ /** A `null` default, because a context without one throws outside its provider. `useFormContext` maps it to `undefined`. */
7
+ const FormContext = createContext(null);
8
+ /** Props of the form component that must not reach the `form` element. */
9
+ const formOnlyProps = new Set([
10
+ 'action', 'method', 'headers', 'queryStringArrayFormat', 'errorBag', 'showProgress', 'transform', 'optimistic',
11
+ 'options', 'onStart', 'onProgress', 'onFinish', 'onBefore', 'onCancel', 'onSuccess', 'onError', 'onHttpException',
12
+ 'onNetworkError', 'onFlash', 'onCancelToken', 'onSubmitComplete', 'disableWhileProcessing', 'cancelOnUnmount',
13
+ 'resetOnError', 'resetOnSuccess', 'setDefaultsOnSuccess', 'invalidateCacheTags', 'validateFiles',
14
+ 'validationTimeout', 'withAllErrors', 'component', 'instant', 'children', 'ref',
15
+ ]);
16
+ const fieldEvents = ['input', 'change', 'reset'];
17
+ /**
18
+ * The fields a `resetOnSuccess` or `resetOnError` option resets: `[]` is every field, a list is those fields, and
19
+ * `null` is none.
20
+ */
21
+ function resetTargets(option) {
22
+ if (option === true) {
23
+ return [];
24
+ }
25
+ return Array.isArray(option) && option.length > 0 ? option : null;
26
+ }
27
+ /**
28
+ * A form that collects its fields from the DOM and submits them through the router. It sits on a `useForm({})`
29
+ * made precognitive, which keeps the errors, processing state and validator. Props are read where they are used,
30
+ * so a prop that changes after mount affects the next submit.
31
+ */
32
+ function FormImpl(props) {
33
+ let formElement;
34
+ // The baseline for DOM operations (`reset`). `defaultValues` is the same baseline as an object, for `isDirty`.
35
+ let defaultFormData = new FormData();
36
+ // The data of the submit being handed to `useForm`, which `transform` and the request prefer over the DOM.
37
+ let submission = null;
38
+ const [fields, setFields] = createSignal({});
39
+ const [defaultValues, setDefaultValues] = createSignal({});
40
+ const isDirty = createMemo(() => !isEqual(fields(), defaultValues()));
41
+ const endpoint = createMemo(() => {
42
+ const target = props.action;
43
+ return isUrlMethodPair(target)
44
+ ? { method: target.method, action: target.url }
45
+ : { method: (props.method ?? 'get').toLowerCase(), action: target ?? '' };
46
+ });
47
+ const pageComponent = createMemo(() => {
48
+ if (props.component) {
49
+ return props.component;
50
+ }
51
+ return props.instant && isUrlMethodPair(props.action) ? resolveUrlMethodPairComponent(props.action) : null;
52
+ });
53
+ const domFormData = (submitter) => formElement ? new FormData(formElement, submitter) : new FormData();
54
+ const domValues = (submitter) => formDataToObject(domFormData(submitter));
55
+ const request = (submitter) => {
56
+ const [url, data] = mergeDataIntoQueryString(endpoint().method, endpoint().action, domValues(submitter), props.queryStringArrayFormat ?? 'brackets');
57
+ return { url, data };
58
+ };
59
+ // `useForm({})` is typed with no field names. The form collects its fields from the DOM, so any name is valid.
60
+ const form = useForm({}).withPrecognition(() => endpoint().method, () => request().url);
61
+ form.transform(() => {
62
+ const data = submission ?? request().data;
63
+ return props.transform?.(data) ?? data;
64
+ });
65
+ const adoptDefaults = (formData) => {
66
+ const values = formDataToObject(formData);
67
+ defaultFormData = formData;
68
+ setDefaultValues(values);
69
+ setFields(values);
70
+ };
71
+ const clearErrors = (...names) => {
72
+ form.clearErrors(...names);
73
+ return form;
74
+ };
75
+ const reset = (...names) => {
76
+ if (formElement) {
77
+ resetFormFields(formElement, defaultFormData, names);
78
+ }
79
+ form.reset(...names);
80
+ };
81
+ const resetAndClearErrors = (...names) => {
82
+ clearErrors(...names);
83
+ reset(...names);
84
+ };
85
+ const resetBy = (option) => {
86
+ const targets = resetTargets(option);
87
+ if (targets) {
88
+ reset(...targets);
89
+ }
90
+ };
91
+ const defaults = () => adoptDefaults(domFormData());
92
+ const visitOptions = (data) => ({
93
+ headers: props.headers,
94
+ queryStringArrayFormat: props.queryStringArrayFormat,
95
+ errorBag: props.errorBag,
96
+ showProgress: props.showProgress ?? true,
97
+ invalidateCacheTags: props.invalidateCacheTags,
98
+ component: pageComponent(),
99
+ optimistic: props.optimistic ? (pageProps) => props.optimistic?.(pageProps, data) : undefined,
100
+ onCancelToken: props.onCancelToken,
101
+ onBefore: props.onBefore,
102
+ onStart: props.onStart,
103
+ onProgress: props.onProgress,
104
+ onFinish: props.onFinish,
105
+ onCancel: props.onCancel,
106
+ onSuccess: async (...args) => {
107
+ const result = await props.onSuccess?.(...args);
108
+ props.onSubmitComplete?.({ reset, defaults });
109
+ resetBy(props.resetOnSuccess);
110
+ if (props.setDefaultsOnSuccess === true) {
111
+ defaults();
112
+ }
113
+ return result;
114
+ },
115
+ onError: (...args) => {
116
+ props.onError?.(...args);
117
+ resetBy(props.resetOnError);
118
+ },
119
+ onHttpException: props.onHttpException,
120
+ onNetworkError: props.onNetworkError,
121
+ onFlash: props.onFlash,
122
+ ...props.options,
123
+ });
124
+ const submit = (submitter) => {
125
+ const { url, data } = request(submitter);
126
+ const { method } = endpoint();
127
+ if (method === 'get' && submitter?.getAttribute('formtarget') === '_blank') {
128
+ window.open(url, '_blank');
129
+ return;
130
+ }
131
+ submission = data;
132
+ try {
133
+ form.submit(method, url, visitOptions(data));
134
+ }
135
+ finally {
136
+ submission = null;
137
+ }
138
+ };
139
+ const slot = {
140
+ get errors() {
141
+ return form.errors;
142
+ },
143
+ get hasErrors() {
144
+ return form.hasErrors;
145
+ },
146
+ get processing() {
147
+ return form.processing;
148
+ },
149
+ get progress() {
150
+ return form.progress;
151
+ },
152
+ get wasSuccessful() {
153
+ return form.wasSuccessful;
154
+ },
155
+ get recentlySuccessful() {
156
+ return form.recentlySuccessful;
157
+ },
158
+ get isDirty() {
159
+ return isDirty();
160
+ },
161
+ get validating() {
162
+ return form.validating;
163
+ },
164
+ clearErrors,
165
+ resetAndClearErrors,
166
+ setError: form.setError,
167
+ reset,
168
+ submit,
169
+ cancel: form.cancel,
170
+ defaults,
171
+ getData: (submitter) => domValues(submitter),
172
+ getFormData: (submitter) => domFormData(submitter),
173
+ valid: form.valid,
174
+ invalid: form.invalid,
175
+ validate: (field, validationConfig) => form.validate(...UseFormUtils.mergeHeadersForValidation(field, validationConfig, props.headers ?? {})),
176
+ touch: form.touch,
177
+ touched: form.touched,
178
+ validator: () => form.validator(),
179
+ };
180
+ props.ref?.(slot);
181
+ const followFields = (event) => {
182
+ if (event.type !== 'reset') {
183
+ setFields(domValues());
184
+ return;
185
+ }
186
+ if (event.detail?.[FormComponentResetSymbol]) {
187
+ // A programmatic reset restores the fields itself, so the native reset must not run.
188
+ event.preventDefault();
189
+ }
190
+ setFields(formDataToObject(defaultFormData));
191
+ };
192
+ onSettled(() => {
193
+ const element = formElement;
194
+ adoptDefaults(domFormData());
195
+ form.setDefaults(domValues());
196
+ fieldEvents.forEach((type) => element?.addEventListener(type, followFields));
197
+ return () => {
198
+ fieldEvents.forEach((type) => element?.removeEventListener(type, followFields));
199
+ if (props.cancelOnUnmount) {
200
+ form.cancel();
201
+ }
202
+ };
203
+ });
204
+ createEffect(() => props.validationTimeout ?? 1500, (timeout) => {
205
+ form.setValidationTimeout(timeout);
206
+ });
207
+ createEffect(() => props.validateFiles ?? false, (validateFiles) => {
208
+ if (validateFiles) {
209
+ form.validateFiles();
210
+ }
211
+ else {
212
+ form.withoutFileValidation();
213
+ }
214
+ });
215
+ createEffect(() => props.withAllErrors ?? config.get('form.withAllErrors'), (withAllErrors) => {
216
+ if (withAllErrors) {
217
+ form.withAllErrors();
218
+ }
219
+ });
220
+ // Called where the children are inserted, under the provider, so a child sees `useFormContext()`.
221
+ const renderChildren = () => renderSlot(props.children, slot);
222
+ return (<FormContext value={slot}>
223
+ <form {...omit(props, (key) => formOnlyProps.has(key))} ref={(element) => {
224
+ formElement = element;
225
+ }} action={endpoint().action} method={endpoint().method} inert={props.disableWhileProcessing && form.processing ? true : undefined} onSubmit={(event) => {
226
+ event.preventDefault();
227
+ submit(event.submitter);
228
+ }}>
229
+ {renderChildren()}
230
+ </form>
231
+ </FormContext>);
232
+ }
233
+ export default FormImpl;
234
+ /** The nearest `<Form>`'s ref object, or `undefined` outside a form. */
235
+ export function useFormContext() {
236
+ return (useContext(FormContext) ?? undefined);
237
+ }
package/dist/Head.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { type JSX } from '@solidjs/web';
2
+ export type InertiaHeadProps = {
3
+ title?: string;
4
+ children?: JSX.Element;
5
+ };
6
+ export default function Head(props: InertiaHeadProps): JSX.Element;
package/dist/Head.js ADDED
@@ -0,0 +1,117 @@
1
+ import { insert, resolveSSRNode } from '@solidjs/web';
2
+ import { escape } from 'es-toolkit/compat';
3
+ import { createEffect, createRoot, createSignal, getOwner, isHydrating, onSettled, runWithOwner, useContext, } from 'solid-js';
4
+ import HeadContext from './HeadContext';
5
+ const titleTag = (title) => `<title data-inertia="">${escape(title)}</title>`;
6
+ /** Each element child as the tag string core's head manager diffs, keyed by `head-key`. */
7
+ function serialize(container, title) {
8
+ const elements = Array.from(container.children, (child) => {
9
+ const tag = child.cloneNode(true);
10
+ tag.setAttribute('data-inertia', tag.getAttribute('head-key') ?? '');
11
+ tag.removeAttribute('head-key');
12
+ return tag.outerHTML;
13
+ });
14
+ if (title && !elements.some((tag) => tag.startsWith('<title'))) {
15
+ elements.push(titleTag(title));
16
+ }
17
+ return elements;
18
+ }
19
+ const flatten = (node) => (Array.isArray(node) ? node.flatMap(flatten) : [node]);
20
+ const openingTag = /^<([a-z][^\s/>]*)((?:\s+[^\s=>/]+(?:=(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*\/?>/i;
21
+ const attribute = /\s+([^\s=>/]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
22
+ const hydrationMarker = /<!--(?:\$|\/|!\$)-->/g;
23
+ /**
24
+ * Splits markup the server rendered into its top-level elements, a void tag or `<tag …>…</tag>` as head content is
25
+ * flat. Each one loses its hydration key, and its `head-key` becomes `data-inertia`.
26
+ */
27
+ function serverTags(html) {
28
+ const tags = [];
29
+ let rest = html.replace(hydrationMarker, '').trim();
30
+ while (rest) {
31
+ const opening = openingTag.exec(rest);
32
+ if (!opening) {
33
+ tags.push(rest);
34
+ break;
35
+ }
36
+ const closing = `</${opening[1]}>`;
37
+ const end = rest.indexOf(closing, opening[0].length);
38
+ const length = end === -1 ? opening[0].length : end + closing.length;
39
+ let headKey = '';
40
+ let attributes = '';
41
+ for (const [whole, name, double, single, bare] of opening[2].matchAll(attribute)) {
42
+ if (name === 'head-key') {
43
+ headKey = double ?? single ?? bare ?? '';
44
+ }
45
+ else if (name !== '_hk') {
46
+ attributes += whole;
47
+ }
48
+ }
49
+ tags.push(`<${opening[1]}${attributes} data-inertia="${headKey}">${rest.slice(opening[0].length, length)}`);
50
+ rest = rest.slice(length).trimStart();
51
+ }
52
+ return tags;
53
+ }
54
+ /** The server cannot read a DOM, so it resolves the children to markup and the title to a tag. */
55
+ function serializeOnServer(props) {
56
+ // A root with its own id keeps the children's hydration keys out of the page's id sequence
57
+ const markup = createRoot((dispose) => {
58
+ const nodes = flatten(props.children).map((node) => resolveSSRNode(node).t.join(''));
59
+ dispose();
60
+ return nodes;
61
+ }, { id: 'inertia-head' });
62
+ const elements = markup.flatMap(serverTags);
63
+ if (props.title && !elements.some((tag) => tag.startsWith('<title'))) {
64
+ elements.push(titleTag(props.title));
65
+ }
66
+ return elements;
67
+ }
68
+ export default function Head(props) {
69
+ const provider = useContext(HeadContext).createProvider();
70
+ if (typeof window === 'undefined') {
71
+ provider.update(serializeOnServer(props));
72
+ }
73
+ // The children render into a detached element once Head settles. A settle inside the root hydration pass mounts
74
+ // in a microtask, after hydrate() returns, as the server rendered no children under Head's path for their
75
+ // templates to claim. Waiting for the whole hydration phase would let core's head manager remove the server's
76
+ // head tags while Loading boundaries resolve. Owner-backed
77
+ // onSettled forbids child owners, so the root is created under Head's owner. The server calls onSettled too,
78
+ // where it never runs, to take the same hydration id slot as the client.
79
+ const owner = getOwner();
80
+ const mountClient = () => runWithOwner(owner, () => createRoot((dispose) => {
81
+ const container = document.createElement('div');
82
+ const [revision, setRevision] = createSignal(0);
83
+ insert(container, () => props.children);
84
+ const observer = new MutationObserver(() => setRevision((value) => value + 1));
85
+ observer.observe(container, { childList: true, attributes: true, characterData: true, subtree: true });
86
+ createEffect(() => {
87
+ revision();
88
+ return serialize(container, props.title);
89
+ }, (elements) => {
90
+ provider.update(elements);
91
+ });
92
+ return () => {
93
+ observer.disconnect();
94
+ provider.disconnect();
95
+ dispose();
96
+ };
97
+ }));
98
+ onSettled(() => {
99
+ let cleanup;
100
+ let disposed = false;
101
+ const mount = () => {
102
+ if (!disposed)
103
+ cleanup = mountClient();
104
+ };
105
+ if (isHydrating()) {
106
+ queueMicrotask(mount);
107
+ }
108
+ else {
109
+ mount();
110
+ }
111
+ return () => {
112
+ disposed = true;
113
+ cleanup?.();
114
+ };
115
+ });
116
+ return null;
117
+ }
@@ -0,0 +1,4 @@
1
+ import type { HeadManager } from '@inertiajs/core';
2
+ /** Core's head manager, created by `App`. `Head` reads it to create its provider. */
3
+ declare const _default: import("solid-js").Context<HeadManager>;
4
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import { createContext } from 'solid-js';
2
+ /** Core's head manager, created by `App`. `Head` reads it to create its provider. */
3
+ export default createContext(undefined, { name: 'InertiaHeadContext' });
@@ -0,0 +1,23 @@
1
+ import { type InfiniteScrollActionSlotProps, type InfiniteScrollComponentBaseProps, type InfiniteScrollRef, type InfiniteScrollSlotProps, type ReloadOptions } from '@inertiajs/core';
2
+ import { type JSX } from '@solidjs/web';
3
+ import { type Slot } from './slot';
4
+ /** A CSS selector, or a getter for an element captured through a `ref` callback (read lazily, after mount). */
5
+ export type InfiniteScrollElement = string | (() => HTMLElement | null | undefined);
6
+ export interface InfiniteScrollProps extends InfiniteScrollComponentBaseProps, Omit<JSX.HTMLAttributes<HTMLElement>, keyof InfiniteScrollComponentBaseProps | 'children' | 'ref'> {
7
+ children?: Slot<InfiniteScrollSlotProps>;
8
+ startElement?: InfiniteScrollElement;
9
+ endElement?: InfiniteScrollElement;
10
+ itemsElement?: InfiniteScrollElement;
11
+ previous?: Slot<InfiniteScrollActionSlotProps>;
12
+ next?: Slot<InfiniteScrollActionSlotProps>;
13
+ loading?: Slot<InfiniteScrollActionSlotProps>;
14
+ params?: ReloadOptions;
15
+ /** Receives the controls each time the scroll instance is created, once the items element exists. */
16
+ ref?: (ref: InfiniteScrollRef) => void;
17
+ }
18
+ /**
19
+ * Loads the previous and next pages of a paginated prop as the start and end triggers scroll into view. Core's
20
+ * `useInfiniteScroll` owns the requests, the observers, the URL and the scroll position. This component owns the
21
+ * state the slots read: one `{ loading, hasMore }` record per side and the request count.
22
+ */
23
+ export default function InfiniteScroll(props: InfiniteScrollProps): JSX.Element;