@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
@@ -0,0 +1,44 @@
1
+ import type { FormComponentMethods, FormComponentState, FormDataKeys, FormDataValues, Method, UrlMethodPair, UseFormTransformCallback, UseFormWithPrecognitionArguments } from '@inertiajs/core';
2
+ import type { NamedInputEvent, PrecognitionPath, ValidationConfig } from 'laravel-precognition';
3
+ /** Arguments that make `useForm` / `useHttp` precognitive from the start: an endpoint, then the data. */
4
+ export type PrecognitiveArguments<TForm> = [...UseFormWithPrecognitionArguments, TForm | (() => TForm)];
5
+ export type SetDataByObject<TForm> = (data: Partial<TForm>) => void;
6
+ export type SetDataByMethod<TForm> = (data: (previousData: TForm) => TForm) => void;
7
+ export type SetDataByKeyValuePair<TForm> = <K extends FormDataKeys<TForm>>(key: K, value: FormDataValues<TForm, K>) => void;
8
+ export type SetDataAction<TForm extends object> = SetDataByObject<TForm> & SetDataByMethod<TForm> & SetDataByKeyValuePair<TForm>;
9
+ /**
10
+ * What `useForm` and `useHttp` share. The object is reactive: state members are getters, read them as
11
+ * `form.data.name` inside JSX, a memo or an effect compute, and never destructure the object.
12
+ */
13
+ export interface FormState<TForm extends object> extends Readonly<Omit<FormComponentState<TForm>, 'validating'>>, Pick<FormComponentMethods<TForm>, 'reset' | 'clearErrors' | 'resetAndClearErrors' | 'setError'> {
14
+ readonly data: TForm;
15
+ setData: SetDataAction<TForm>;
16
+ setDefaults: {
17
+ (): void;
18
+ <K extends FormDataKeys<TForm>>(field: K, value: FormDataValues<TForm, K>): void;
19
+ (fields: Partial<TForm>): void;
20
+ };
21
+ transform(callback: UseFormTransformCallback<TForm>): void;
22
+ dontRemember<K extends FormDataKeys<TForm>>(...fields: K[]): this;
23
+ withPrecognition(...endpoint: UseFormWithPrecognitionArguments): this & Precognition<TForm>;
24
+ }
25
+ /** `TOptions` and `TResult` are what a submit takes and gives back. */
26
+ export interface FormHelper<TForm extends object, TOptions, TResult> extends FormState<TForm>, Pick<FormComponentMethods<TForm>, 'cancel'>, Record<Method, (url: string, options?: TOptions) => TResult> {
27
+ submit(...args: [Method, string, TOptions?] | [UrlMethodPair, TOptions?] | [TOptions?]): TResult;
28
+ }
29
+ type ValidatedPath<TForm> = FormDataKeys<TForm> | PrecognitionPath<TForm>;
30
+ type ValidateOptions<TPath> = ValidationConfig & {
31
+ only?: Iterable<TPath> | ArrayLike<TPath>;
32
+ };
33
+ /** The members a form gains once it validates through Precognition. */
34
+ export interface Precognition<TForm extends object> extends Readonly<Pick<FormComponentState<TForm>, 'validating'>>, Pick<FormComponentMethods<TForm>, 'valid' | 'invalid' | 'touched' | 'validator'> {
35
+ validate<P extends ValidatedPath<TForm>>(target?: P | NamedInputEvent | ValidateOptions<P>, options?: ValidateOptions<P>): this;
36
+ touch<K extends FormDataKeys<TForm>>(target: K | K[] | NamedInputEvent, ...targets: K[]): this;
37
+ withAllErrors(): this;
38
+ setValidationTimeout(ms: number): this;
39
+ validateFiles(): this;
40
+ withoutFileValidation(): this;
41
+ setErrors(errors: FormComponentState<TForm>['errors']): this;
42
+ forgetError<K extends FormDataKeys<TForm> | NamedInputEvent>(target: K): this;
43
+ }
44
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ export { config, http, progress, router, socketId } from '@inertiajs/core';
2
+ export { default as App } from './App';
3
+ export type { InertiaAppProps } from './App';
4
+ export { default as createInertiaApp } from './createInertiaApp';
5
+ export { default as Deferred } from './Deferred';
6
+ export type { DeferredProps, DeferredSlotProps } from './Deferred';
7
+ export { default as Form, useFormContext } from './Form';
8
+ export type { FormProps } from './Form';
9
+ export { default as Head } from './Head';
10
+ export type { InertiaHeadProps } from './Head';
11
+ export { default as InfiniteScroll } from './InfiniteScroll';
12
+ export type { InfiniteScrollElement, InfiniteScrollProps } from './InfiniteScroll';
13
+ export { resetLayoutProps, setLayoutProps } from './layoutProps';
14
+ export { default as Link } from './Link';
15
+ export type { InertiaLinkProps } from './Link';
16
+ export type { LayoutCallback, LayoutResolver, RenderFunction, RenderNode, ResolvedComponent } from './types';
17
+ export { default as useForm } from './useForm';
18
+ export type { InertiaForm, InertiaFormProps, InertiaPrecognitiveFormProps, SetDataAction, SetDataByKeyValuePair, SetDataByMethod, SetDataByObject, } from './useForm';
19
+ export { default as useHttp } from './useHttp';
20
+ export type { UseHttp } from './useHttp';
21
+ export { default as usePage } from './usePage';
22
+ export { default as usePoll } from './usePoll';
23
+ export type { InertiaPoll } from './usePoll';
24
+ export { default as usePrefetch } from './usePrefetch';
25
+ export type { InertiaPrefetch } from './usePrefetch';
26
+ export { default as useProp } from './useProp';
27
+ export type { InertiaProp } from './useProp';
28
+ export { default as useRemember } from './useRemember';
29
+ export { default as WhenMounted } from './WhenMounted';
30
+ export type { WhenMountedProps } from './WhenMounted';
31
+ export { default as WhenVisible } from './WhenVisible';
32
+ export type { WhenVisibleProps, WhenVisibleSlotProps } from './WhenVisible';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ export { config, http, progress, router, socketId } from '@inertiajs/core';
2
+ export { default as App } from './App';
3
+ export { default as createInertiaApp } from './createInertiaApp';
4
+ export { default as Deferred } from './Deferred';
5
+ export { default as Form, useFormContext } from './Form';
6
+ export { default as Head } from './Head';
7
+ export { default as InfiniteScroll } from './InfiniteScroll';
8
+ export { resetLayoutProps, setLayoutProps } from './layoutProps';
9
+ export { default as Link } from './Link';
10
+ export { default as useForm } from './useForm';
11
+ export { default as useHttp } from './useHttp';
12
+ export { default as usePage } from './usePage';
13
+ export { default as usePoll } from './usePoll';
14
+ export { default as usePrefetch } from './usePrefetch';
15
+ export { default as useProp } from './useProp';
16
+ export { default as useRemember } from './useRemember';
17
+ export { default as WhenMounted } from './WhenMounted';
18
+ export { default as WhenVisible } from './WhenVisible';
@@ -0,0 +1,11 @@
1
+ import { type LayoutProps, type NamedLayoutProps } from '@inertiajs/core';
2
+ /** What `setLayoutProps` writes. `App` subscribes to it. */
3
+ export declare const layoutPropsStore: import("@inertiajs/core").LayoutPropsStore;
4
+ /** Without a type argument the props are checked against the app's configured (named) layout props. */
5
+ type LayoutPropsUpdate<Custom> = [Custom] extends [never] ? [Partial<LayoutProps>] | {
6
+ [Name in keyof NamedLayoutProps]: [Name, Partial<NamedLayoutProps[Name]>];
7
+ }[keyof NamedLayoutProps] : [Partial<Custom>] | [string, Partial<Custom>];
8
+ /** Merges props into the default layout's, or into the named layout's when a name comes first. */
9
+ export declare function setLayoutProps<Custom = never>(...update: LayoutPropsUpdate<NoInfer<Custom>>): void;
10
+ export declare function resetLayoutProps(): void;
11
+ export {};
@@ -0,0 +1,16 @@
1
+ import { createLayoutPropsStore } from '@inertiajs/core';
2
+ /** What `setLayoutProps` writes. `App` subscribes to it. */
3
+ export const layoutPropsStore = createLayoutPropsStore();
4
+ /** Merges props into the default layout's, or into the named layout's when a name comes first. */
5
+ export function setLayoutProps(...update) {
6
+ const [nameOrProps, props] = update;
7
+ if (typeof nameOrProps === 'string') {
8
+ layoutPropsStore.setFor(nameOrProps, props);
9
+ }
10
+ else {
11
+ layoutPropsStore.set(nameOrProps);
12
+ }
13
+ }
14
+ export function resetLayoutProps() {
15
+ layoutPropsStore.reset();
16
+ }
@@ -0,0 +1,21 @@
1
+ import { type Page } from '@inertiajs/core';
2
+ import type { RenderFunction, RenderNode, ResolvedComponent } from './types';
3
+ export declare const h: RenderFunction;
4
+ /** The layouts' props that `setLayoutProps` set: for every layout, and for the layout of that name. */
5
+ export type DynamicLayoutProps = {
6
+ shared: Record<string, unknown>;
7
+ named: Record<string, Record<string, unknown>>;
8
+ };
9
+ /**
10
+ * Describes what to render: each layout, outermost first, with the page as the innermost child.
11
+ * Pure, apart from the arrow-layout warning. The renderer keeps a level mounted while its component is the same function.
12
+ * Layout props merge the page props, the layout's own, `setLayoutProps` for all layouts,
13
+ * and `setLayoutProps` for the layout of that name, later ones winning.
14
+ */
15
+ export declare function buildRenderTree(options: {
16
+ component: ResolvedComponent;
17
+ page: Page;
18
+ key: number | null;
19
+ defaultLayout?: (name: string, page: Page) => unknown;
20
+ dynamicLayoutProps: DynamicLayoutProps;
21
+ }): RenderNode;
@@ -0,0 +1,72 @@
1
+ import { isPropsObject, isPropsObjectOrCallback, normalizeLayouts } from '@inertiajs/core';
2
+ import { merge } from 'solid-js';
3
+ export const h = (component, second, third, fourth) => {
4
+ if (second === undefined || Array.isArray(second)) {
5
+ return { component, props: {}, children: second ?? [], key: typeof third === 'number' ? third : null };
6
+ }
7
+ return { component, props: second, children: Array.isArray(third) ? third : [], key: fourth ?? null };
8
+ };
9
+ const isComponent = (value) => typeof value === 'function';
10
+ const isArrowFunction = (value) => typeof value === 'function' && value.prototype === undefined;
11
+ const isRenderFunction = (value) => isArrowFunction(value) && value.length === 2;
12
+ const isLayoutCallback = (value) => isArrowFunction(value) && value.length <= 1;
13
+ /** A layout callback's result that an arrow component rendered. Only the browser can see it: server JSX is markup. */
14
+ const isRenderedElement = (value) => typeof Node !== 'undefined' &&
15
+ (value instanceof Node || (Array.isArray(value) && value.some((item) => item instanceof Node)));
16
+ /**
17
+ * Describes what to render: each layout, outermost first, with the page as the innermost child.
18
+ * Pure, apart from the arrow-layout warning. The renderer keeps a level mounted while its component is the same function.
19
+ * Layout props merge the page props, the layout's own, `setLayoutProps` for all layouts,
20
+ * and `setLayoutProps` for the layout of that name, later ones winning.
21
+ */
22
+ export function buildRenderTree(options) {
23
+ const { component, page, key, defaultLayout, dynamicLayoutProps } = options;
24
+ const child = { component, props: page.props, children: [], key };
25
+ const layoutValue = component.layout;
26
+ if (isRenderFunction(layoutValue)) {
27
+ return layoutValue(h, child);
28
+ }
29
+ let effectiveLayout;
30
+ let callbackProps = null;
31
+ if (isLayoutCallback(layoutValue)) {
32
+ const result = layoutValue(page.props);
33
+ if (isRenderedElement(result)) {
34
+ console.warn(`[Inertia] The layout of page "${page.component}" is an arrow function with at most one parameter, so it ran as a ` +
35
+ 'layout callback and returned elements. The page renders without it. To use an arrow function component as ' +
36
+ 'a layout, put it in an array (`Page.layout = [ArrowLayout]`), write it as a function declaration, or use ' +
37
+ '`(h, page) => h(ArrowLayout, [page])`.');
38
+ return child;
39
+ }
40
+ if (isPropsObjectOrCallback(result, isComponent)) {
41
+ effectiveLayout = defaultLayout?.(page.component, page);
42
+ callbackProps = result;
43
+ }
44
+ else {
45
+ effectiveLayout = result;
46
+ }
47
+ }
48
+ else if (isPropsObject(layoutValue, isComponent)) {
49
+ effectiveLayout = defaultLayout?.(page.component, page);
50
+ callbackProps = layoutValue;
51
+ }
52
+ else {
53
+ effectiveLayout = layoutValue ?? defaultLayout?.(page.component, page);
54
+ }
55
+ if (!effectiveLayout) {
56
+ return child;
57
+ }
58
+ const isFromPage = !!layoutValue && !callbackProps;
59
+ if (isFromPage && isRenderFunction(effectiveLayout)) {
60
+ return effectiveLayout(h, child);
61
+ }
62
+ let layouts = normalizeLayouts(effectiveLayout, isComponent, isFromPage ? isRenderFunction : undefined);
63
+ if (callbackProps) {
64
+ layouts = layouts.map((layout) => ({ ...layout, props: { ...layout.props, ...callbackProps } }));
65
+ }
66
+ return layouts.reduceRight((node, layout) => ({
67
+ component: layout.component,
68
+ props: merge(page.props, layout.props, dynamicLayoutProps.shared, layout.name ? (dynamicLayoutProps.named[layout.name] ?? {}) : {}),
69
+ children: [node],
70
+ name: layout.name,
71
+ }), child);
72
+ }
@@ -0,0 +1 @@
1
+ export { default } from '@inertiajs/core/server';
package/dist/server.js ADDED
@@ -0,0 +1 @@
1
+ export { default } from '@inertiajs/core/server';
package/dist/slot.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { JSX } from '@solidjs/web';
2
+ /** JSX, or a render function that receives the slot props. */
3
+ export type Slot<P> = JSX.Element | ((slot: P) => JSX.Element);
4
+ /**
5
+ * Renders a slot. A render function that takes a parameter is called once, untracked, so its body is not a tracking
6
+ * scope. A function with no parameters, such as the accessor a lone `<For>` or `<Show>` child compiles to, passes
7
+ * through uncalled so the surrounding boundary keeps tracking it. This is the test Solid's own `Show` applies
8
+ * (`typeof child === 'function' && child.length > 0`).
9
+ */
10
+ export declare function renderSlot<P>(content: Slot<P> | undefined, slot: P): JSX.Element;
package/dist/slot.js ADDED
@@ -0,0 +1,13 @@
1
+ import { untrack } from 'solid-js';
2
+ /**
3
+ * Renders a slot. A render function that takes a parameter is called once, untracked, so its body is not a tracking
4
+ * scope. A function with no parameters, such as the accessor a lone `<For>` or `<Show>` child compiles to, passes
5
+ * through uncalled so the surrounding boundary keeps tracking it. This is the test Solid's own `Show` applies
6
+ * (`typeof child === 'function' && child.length > 0`).
7
+ */
8
+ export function renderSlot(content, slot) {
9
+ if (typeof content !== 'function') {
10
+ return content;
11
+ }
12
+ return content.length > 0 ? untrack(() => content(slot)) : content;
13
+ }
@@ -0,0 +1,31 @@
1
+ import type { LayoutCallbackReturn, SharedPageProps } from '@inertiajs/core';
2
+ import type { JSX } from '@solidjs/web';
3
+ import type { Component } from 'solid-js';
4
+ /** Any component. A layout takes `children`; a page takes its props. */
5
+ export type RenderComponent = Component<never>;
6
+ /** One level of the page tree: a layout with the next level as its child, or the page as the leaf. */
7
+ export type RenderNode = {
8
+ component: RenderComponent;
9
+ props: Record<string, unknown>;
10
+ children: RenderNode[];
11
+ /** Only the leaf, the page, uses it. A new key re-creates the page. */
12
+ key?: number | null;
13
+ name?: string;
14
+ };
15
+ /** The `h` that a render-function layout receives: `(h, page) => h(Layout, [page])`. */
16
+ export type RenderFunction = {
17
+ (component: RenderComponent, props?: Record<string, unknown>, children?: RenderNode[], key?: number | null): RenderNode;
18
+ (component: RenderComponent, children?: RenderNode[], key?: number | null): RenderNode;
19
+ };
20
+ type Layout = Component<{
21
+ children: JSX.Element;
22
+ }>;
23
+ /** Picks persistent layouts from the shared page props. */
24
+ export type LayoutCallback = (props: SharedPageProps) => LayoutCallbackReturn<Layout>;
25
+ /** `(h, page) => h(Layout, [page])`. Nest with `h(Outer, [h(Inner, [page])])`. */
26
+ export type LayoutResolver = (h: RenderFunction, page: RenderNode) => RenderNode;
27
+ /** A page component. Its static `layout` is a layout, a list or map of them, a callback, or `(h, page) => h(Layout, [page])`. */
28
+ export type ResolvedComponent = Component<never> & {
29
+ layout?: LayoutCallbackReturn<Layout> | LayoutCallback | LayoutResolver;
30
+ };
31
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { type FormDataType, type OptimisticCallback, type UseFormArguments, type UseFormSubmitOptions } from '@inertiajs/core';
2
+ import type { FormHelper, PrecognitiveArguments, Precognition } from './formHelper';
3
+ export type { FormState, Precognition, SetDataAction, SetDataByKeyValuePair, SetDataByMethod, SetDataByObject, } from './formHelper';
4
+ /** A `useForm` object: submits are router visits. */
5
+ export interface InertiaFormProps<TForm extends object> extends FormHelper<TForm, UseFormSubmitOptions, void> {
6
+ optimistic<TProps>(callback: OptimisticCallback<TProps>): this;
7
+ }
8
+ export type InertiaForm<TForm extends object> = InertiaFormProps<TForm>;
9
+ export type InertiaPrecognitiveFormProps<TForm extends object> = InertiaFormProps<TForm> & Precognition<TForm>;
10
+ export default function useForm<TForm extends FormDataType<TForm>>(...args: PrecognitiveArguments<TForm>): InertiaPrecognitiveFormProps<TForm>;
11
+ export default function useForm<TForm extends FormDataType<TForm>>(...args: UseFormArguments<TForm>): InertiaFormProps<TForm>;
@@ -0,0 +1,106 @@
1
+ import { router, UseFormUtils, } from '@inertiajs/core';
2
+ import { createRoot, runWithOwner } from 'solid-js';
3
+ import useFormState from './useFormState';
4
+ /** Every verb is `submit(verb, url, options)`. */
5
+ const verbs = ['get', 'post', 'put', 'patch', 'delete', 'query'];
6
+ let reservedFormKeys = null;
7
+ let bootstrapping = false;
8
+ /** Logs an error for data keys that name a form member, as the Vue and Svelte adapters do. */
9
+ function validateFormDataKeys(data) {
10
+ if (bootstrapping) {
11
+ return;
12
+ }
13
+ if (reservedFormKeys === null) {
14
+ bootstrapping = true;
15
+ try {
16
+ // A detached root takes no hydration id, so the one-off probe cannot shift the ids of the component that runs it
17
+ reservedFormKeys = runWithOwner(null, () => createRoot((dispose) => {
18
+ const keys = new Set(Object.keys(useForm({})));
19
+ dispose();
20
+ return keys;
21
+ }));
22
+ }
23
+ catch {
24
+ // Solid dev can throw when the first useForm runs inside a computation; skip validation for this call and retry on the next
25
+ }
26
+ finally {
27
+ bootstrapping = false;
28
+ }
29
+ if (reservedFormKeys === null) {
30
+ return;
31
+ }
32
+ }
33
+ const conflicts = Object.keys(data).filter((key) => reservedFormKeys.has(key));
34
+ if (conflicts.length > 0) {
35
+ console.error(`[Inertia] useForm() data contains field(s) that conflict with form properties: ${conflicts.map((k) => `"${k}"`).join(', ')}. ` +
36
+ `These fields will be overwritten by form methods/properties. Please rename these fields.`);
37
+ }
38
+ }
39
+ export default function useForm(...args) {
40
+ const { rememberKey, data, precognitionEndpoint } = UseFormUtils.parseUseFormArguments(...args);
41
+ validateFormDataKeys(typeof data === 'function' ? data() : data);
42
+ const state = useFormState({ data, rememberKey, precognitionEndpoint });
43
+ let cancelToken = null;
44
+ let pendingOptimistic = null;
45
+ const submit = (...submitArgs) => {
46
+ const { method, url, options } = UseFormUtils.parseSubmitArguments(submitArgs, state.precognitionEndpoint());
47
+ state.defaultsCalledInOnSuccess = false;
48
+ const visitOptions = {
49
+ ...options,
50
+ onCancelToken: (token) => {
51
+ cancelToken = token;
52
+ return options.onCancelToken?.(token);
53
+ },
54
+ onBefore: (visit) => {
55
+ state.resetBeforeSubmit();
56
+ return options.onBefore?.(visit);
57
+ },
58
+ onStart: (visit) => {
59
+ state.setProcessing(true);
60
+ return options.onStart?.(visit);
61
+ },
62
+ onProgress: (event) => {
63
+ state.setProgress(event || null);
64
+ return options.onProgress?.(event);
65
+ },
66
+ onSuccess: async (page) => {
67
+ state.markAsSuccessful();
68
+ const result = options.onSuccess ? await options.onSuccess(page) : null;
69
+ if (!state.defaultsCalledInOnSuccess) {
70
+ state.commitDefaults(state.latestData());
71
+ }
72
+ return result;
73
+ },
74
+ onError: (errors) => {
75
+ state.clearErrors();
76
+ state.setError(errors);
77
+ return options.onError?.(errors);
78
+ },
79
+ onCancel: () => options.onCancel?.(),
80
+ onFinish: (visit) => {
81
+ state.finishProcessing();
82
+ cancelToken = null;
83
+ return options.onFinish?.(visit);
84
+ },
85
+ };
86
+ visitOptions.optimistic = visitOptions.optimistic ?? pendingOptimistic ?? undefined;
87
+ pendingOptimistic = null;
88
+ const transformed = state.transformData(state.latestData());
89
+ if (method === 'delete') {
90
+ router.delete(url, { ...visitOptions, data: transformed });
91
+ }
92
+ else {
93
+ router[method](url, transformed, visitOptions);
94
+ }
95
+ };
96
+ const form = state.form;
97
+ Object.assign(form, Object.fromEntries(verbs.map((verb) => [verb, (url, options = {}) => submit(verb, url, options)])), {
98
+ submit,
99
+ cancel: () => cancelToken?.cancel(),
100
+ optimistic: (callback) => {
101
+ pendingOptimistic = callback;
102
+ return form;
103
+ },
104
+ });
105
+ return form;
106
+ }
@@ -0,0 +1,33 @@
1
+ import { type ErrorValue, type FormDataErrors, type Progress, type UrlMethodPair } from '@inertiajs/core';
2
+ import type { FormState } from './formHelper';
3
+ export interface UseFormStateOptions<TForm extends object> {
4
+ data: TForm | (() => TForm);
5
+ /** Saves and restores the data and the errors in the history state under `${rememberKey}:data` and `:errors`. */
6
+ rememberKey?: string | null;
7
+ precognitionEndpoint?: (() => UrlMethodPair) | null;
8
+ }
9
+ /** What `useForm` and `useHttp` need besides the form object. In React these are refs and state setters. */
10
+ export interface FormStateInternals<TForm extends object> {
11
+ form: FormState<TForm>;
12
+ /** The data including a `setData` made in the same tick. A store read lags its writes until the next flush. */
13
+ latestData(): TForm;
14
+ commitDefaults(next: TForm): void;
15
+ /** Runs the callback given to `transform`. */
16
+ transformData(data: TForm): object;
17
+ precognitionEndpoint(): (() => UrlMethodPair) | null;
18
+ /** Whether validation errors keep every message per field (`withAllErrors()`, else `form.withAllErrors` config). */
19
+ withAllErrors: {
20
+ enabled(): boolean;
21
+ enable(): void;
22
+ };
23
+ /** `setDefaults` was called since the last submit, so a successful submit must not overwrite the defaults. */
24
+ defaultsCalledInOnSuccess: boolean;
25
+ setProcessing(value: boolean): void;
26
+ setProgress(value: Progress | null): void;
27
+ markAsSuccessful(): void;
28
+ resetBeforeSubmit(): void;
29
+ finishProcessing(): void;
30
+ clearErrors(...fields: string[]): void;
31
+ setError(fieldOrFields: string | FormDataErrors<TForm>, value?: ErrorValue): void;
32
+ }
33
+ export default function useFormState<TForm extends object>(options: UseFormStateOptions<TForm>): FormStateInternals<TForm>;