@inertia-solid/solid 0.0.0-stage → 0.1.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.
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,278 @@
1
+ import { config, UseFormUtils, } from '@inertiajs/core';
2
+ import { cloneDeep, isEqual } from 'es-toolkit';
3
+ import { get, has, set } from 'es-toolkit/compat';
4
+ import { createValidator, resolveName, toSimpleValidationErrors, } from 'laravel-precognition';
5
+ import { createMemo, createSignal, createStore, deep, onCleanup, snapshot } from 'solid-js';
6
+ import { rememberEffect, restoreRemembered } from './useRemember';
7
+ /** `createStore` cannot prove `NoFn<T>` for a type parameter, so the generic store goes through one cast. */
8
+ const createFormStore = (initial) => createStore(initial);
9
+ const restore = (rememberKey, name) => rememberKey ? restoreRemembered(`${rememberKey}:${name}`) : undefined;
10
+ export default function useFormState(options) {
11
+ const { data: dataOption, rememberKey } = options;
12
+ const isDataFunction = typeof dataOption === 'function';
13
+ const resolveData = () => (isDataFunction ? dataOption() : dataOption);
14
+ const initialData = cloneDeep(resolveData());
15
+ // Plain closure variables, as React's refs. A component body runs once.
16
+ let recentlySuccessfulTimeout;
17
+ let transformCallback = (data) => data;
18
+ let precognitionEndpoint = options.precognitionEndpoint ?? null;
19
+ let validator = null;
20
+ let withAllErrors = null;
21
+ const allErrorsEnabled = () => withAllErrors ?? config.get('form.withAllErrors');
22
+ let excludeKeys = [];
23
+ const [data, setStoreData] = createFormStore(restore(rememberKey, 'data') ?? initialData);
24
+ const [errors, setStoreErrors] = createFormStore(restore(rememberKey, 'errors') ?? {});
25
+ const [defaults, setStoreDefaults] = createFormStore(cloneDeep(initialData));
26
+ const [processing, setProcessing] = createSignal(false);
27
+ const [progress, setProgress] = createSignal(null);
28
+ const [wasSuccessful, setWasSuccessful] = createSignal(false);
29
+ const [recentlySuccessful, setRecentlySuccessful] = createSignal(false);
30
+ const [validating, setValidating] = createSignal(false);
31
+ const [touchedFields, setTouchedFields] = createSignal([]);
32
+ const [validFields, setValidFields] = createSignal([]);
33
+ const isDirty = createMemo(() => !isEqual(deep(data), deep(defaults)));
34
+ onCleanup(() => clearTimeout(recentlySuccessfulTimeout));
35
+ if (rememberKey) {
36
+ rememberEffect(`${rememberKey}:data`, () => deep(data), () => excludeKeys);
37
+ rememberEffect(`${rememberKey}:errors`, () => deep(errors));
38
+ }
39
+ // `snapshot` sees writes that are still pending, so a read after a write in the same tick is current.
40
+ // It shares unchanged subtrees with the store, so the copy lets callers, `transform` included, change the result.
41
+ const latestData = () => cloneDeep(snapshot(data));
42
+ const latestDefaults = () => cloneDeep(snapshot(defaults));
43
+ const latestErrors = () => cloneDeep(snapshot(errors));
44
+ const commitData = (next) => setStoreData(() => next);
45
+ const commitDefaults = (next) => setStoreDefaults(() => next);
46
+ const setData = (keyOrData, value) => {
47
+ if (typeof keyOrData === 'string') {
48
+ setStoreData((draft) => {
49
+ set(draft, keyOrData, value);
50
+ });
51
+ }
52
+ else if (typeof keyOrData === 'function') {
53
+ commitData(keyOrData(latestData()));
54
+ }
55
+ else {
56
+ commitData(keyOrData);
57
+ }
58
+ };
59
+ const setDefaults = (fieldOrFields, value) => {
60
+ if (isDataFunction) {
61
+ throw new Error('You cannot call `defaults()` when using a function to define your form data.');
62
+ }
63
+ internals.defaultsCalledInOnSuccess = true;
64
+ let next;
65
+ if (typeof fieldOrFields === 'undefined') {
66
+ next = latestData();
67
+ }
68
+ else if (typeof fieldOrFields === 'string') {
69
+ next = set(latestDefaults(), fieldOrFields, value);
70
+ }
71
+ else {
72
+ next = Object.assign(latestDefaults(), fieldOrFields);
73
+ }
74
+ validator?.defaults(cloneDeep(next));
75
+ commitDefaults(next);
76
+ };
77
+ const reset = (...fields) => {
78
+ const resolved = isDataFunction ? cloneDeep(resolveData()) : latestDefaults();
79
+ if (fields.length === 0) {
80
+ if (isDataFunction) {
81
+ commitDefaults(resolved);
82
+ }
83
+ commitData(cloneDeep(resolved));
84
+ }
85
+ else {
86
+ const present = fields.filter((key) => has(resolved, key));
87
+ if (isDataFunction) {
88
+ setStoreDefaults((draft) => {
89
+ present.forEach((key) => set(draft, key, cloneDeep(get(resolved, key))));
90
+ });
91
+ }
92
+ setStoreData((draft) => {
93
+ present.forEach((key) => set(draft, key, cloneDeep(get(resolved, key))));
94
+ });
95
+ }
96
+ validator?.reset(...fields);
97
+ };
98
+ // Errors are written before the validator hears of the change, because the validator answers with its own
99
+ // `errorsChanged`, whose errors win, as they do in React.
100
+ const setError = (fieldOrFields, value) => {
101
+ const next = {
102
+ ...latestErrors(),
103
+ ...(typeof fieldOrFields === 'string' ? { [fieldOrFields]: value } : fieldOrFields),
104
+ };
105
+ setStoreErrors(() => next);
106
+ validator?.setErrors(next);
107
+ };
108
+ const clearErrors = (...fields) => {
109
+ const current = latestErrors();
110
+ const next = Object.fromEntries(Object.entries(current).filter(([field]) => fields.length > 0 && !fields.includes(field)));
111
+ setStoreErrors(() => next);
112
+ if (validator) {
113
+ if (fields.length === 0) {
114
+ validator.setErrors({});
115
+ }
116
+ else {
117
+ fields.forEach(validator.forgetError);
118
+ }
119
+ }
120
+ };
121
+ const resetAndClearErrors = (...fields) => {
122
+ reset(...fields);
123
+ clearErrors(...fields);
124
+ };
125
+ const markAsSuccessful = () => {
126
+ clearErrors();
127
+ setWasSuccessful(true);
128
+ setRecentlySuccessful(true);
129
+ recentlySuccessfulTimeout = window.setTimeout(() => setRecentlySuccessful(false), config.get('form.recentlySuccessfulDuration'));
130
+ };
131
+ const resetBeforeSubmit = () => {
132
+ setWasSuccessful(false);
133
+ setRecentlySuccessful(false);
134
+ clearTimeout(recentlySuccessfulTimeout);
135
+ };
136
+ const finishProcessing = () => {
137
+ setProcessing(false);
138
+ setProgress(null);
139
+ };
140
+ const dontRemember = (...fields) => {
141
+ excludeKeys = fields;
142
+ return form;
143
+ };
144
+ const validate = (field, validationConfig) => {
145
+ if (typeof field === 'object' && !('target' in field)) {
146
+ validationConfig = field;
147
+ field = undefined;
148
+ }
149
+ if (field === undefined) {
150
+ validator.validate(validationConfig);
151
+ }
152
+ else {
153
+ const fieldName = resolveName(field);
154
+ const transformed = transformCallback(latestData());
155
+ validator.validate(fieldName, get(transformed, fieldName), validationConfig);
156
+ }
157
+ return form;
158
+ };
159
+ const withPrecognition = (...args) => {
160
+ precognitionEndpoint = UseFormUtils.createWayfinderCallback(...args);
161
+ if (!validator) {
162
+ const created = createValidator((client) => {
163
+ const { method, url } = precognitionEndpoint();
164
+ return client[method](url, transformCallback(latestData()));
165
+ }, latestDefaults());
166
+ validator = created;
167
+ created
168
+ .on('validatingChanged', () => {
169
+ setValidating(created.validating());
170
+ })
171
+ .on('validatedChanged', () => {
172
+ setValidFields(created.valid());
173
+ })
174
+ .on('touchedChanged', () => {
175
+ setTouchedFields(created.touched());
176
+ })
177
+ .on('errorsChanged', () => {
178
+ const validationErrors = allErrorsEnabled()
179
+ ? created.errors()
180
+ : toSimpleValidationErrors(created.errors());
181
+ setStoreErrors(() => validationErrors);
182
+ setValidFields(created.valid());
183
+ });
184
+ }
185
+ const tap = (callback) => {
186
+ callback();
187
+ return form;
188
+ };
189
+ Object.defineProperty(form, 'validating', { get: validating, enumerable: true, configurable: true });
190
+ Object.assign(form, {
191
+ validator: () => validator,
192
+ valid: (field) => validFields().includes(field),
193
+ invalid: (field) => field in errors,
194
+ touched: (field) => (typeof field === 'string' ? touchedFields().includes(field) : touchedFields().length > 0),
195
+ validate,
196
+ touch: (field, ...fields) => tap(() => {
197
+ if (typeof field === 'string') {
198
+ validator?.touch([field, ...fields]);
199
+ }
200
+ else {
201
+ validator?.touch(field);
202
+ }
203
+ }),
204
+ withAllErrors: () => tap(() => {
205
+ withAllErrors = true;
206
+ }),
207
+ withoutFileValidation: () => tap(() => validator?.withoutFileValidation()),
208
+ setValidationTimeout: (duration) => tap(() => validator?.setTimeout(duration)),
209
+ validateFiles: () => tap(() => validator?.validateFiles()),
210
+ setErrors: (next) => tap(() => setError(next)),
211
+ forgetError: (field) => tap(() => clearErrors(resolveName(field))),
212
+ });
213
+ return form;
214
+ };
215
+ // The one stable form object. State members are getters over the stores and signals, methods never change.
216
+ const form = {
217
+ get data() {
218
+ return data;
219
+ },
220
+ get isDirty() {
221
+ return isDirty();
222
+ },
223
+ get errors() {
224
+ return errors;
225
+ },
226
+ get hasErrors() {
227
+ return Object.keys(errors).length > 0;
228
+ },
229
+ get processing() {
230
+ return processing();
231
+ },
232
+ get progress() {
233
+ return progress();
234
+ },
235
+ get wasSuccessful() {
236
+ return wasSuccessful();
237
+ },
238
+ get recentlySuccessful() {
239
+ return recentlySuccessful();
240
+ },
241
+ setData,
242
+ transform: (callback) => {
243
+ transformCallback = callback;
244
+ },
245
+ setDefaults,
246
+ reset,
247
+ setError,
248
+ clearErrors,
249
+ resetAndClearErrors,
250
+ dontRemember,
251
+ withPrecognition,
252
+ };
253
+ const internals = {
254
+ form,
255
+ latestData,
256
+ commitDefaults,
257
+ transformData: (current) => transformCallback(current),
258
+ precognitionEndpoint: () => precognitionEndpoint,
259
+ withAllErrors: {
260
+ enabled: allErrorsEnabled,
261
+ enable: () => {
262
+ withAllErrors = true;
263
+ },
264
+ },
265
+ defaultsCalledInOnSuccess: false,
266
+ setProcessing,
267
+ setProgress,
268
+ markAsSuccessful,
269
+ resetBeforeSubmit,
270
+ finishProcessing,
271
+ clearErrors,
272
+ setError,
273
+ };
274
+ if (precognitionEndpoint) {
275
+ form.withPrecognition(precognitionEndpoint);
276
+ }
277
+ return internals;
278
+ }
@@ -0,0 +1,10 @@
1
+ import { type FormDataType, type UseFormArguments, type UseHttpSubmitOptions } from '@inertiajs/core';
2
+ import type { FormHelper, PrecognitiveArguments, Precognition } from './formHelper';
3
+ /** A `useHttp` object: submits are plain requests that resolve to the response body, also kept as `response`. */
4
+ export interface UseHttp<TForm extends object, TResponse = unknown> extends FormHelper<TForm, UseHttpSubmitOptions<TResponse, TForm>, Promise<TResponse>> {
5
+ readonly response: TResponse | null;
6
+ optimistic(callback: (current: TForm) => Partial<TForm>): this;
7
+ withAllErrors(): this;
8
+ }
9
+ export default function useHttp<TForm extends FormDataType<TForm>, TResponse = unknown>(...args: PrecognitiveArguments<TForm>): UseHttp<TForm, TResponse> & Precognition<TForm>;
10
+ export default function useHttp<TForm extends FormDataType<TForm>, TResponse = unknown>(...args: UseFormArguments<TForm>): UseHttp<TForm, TResponse>;
@@ -0,0 +1,172 @@
1
+ import { config, hasFiles, http, HttpCancelledError, HttpResponseError, mergeDataIntoQueryString, objectToFormData, UseFormUtils, } from '@inertiajs/core';
2
+ import { cloneDeep } from 'es-toolkit';
3
+ import { toSimpleValidationErrors } from 'laravel-precognition';
4
+ import { createSignal } from 'solid-js';
5
+ import useFormState from './useFormState';
6
+ const isSuccessStatus = (status) => status >= 200 && status < 300;
7
+ const parseJson = (text) => {
8
+ try {
9
+ return { value: JSON.parse(text) };
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ };
15
+ /** A response with a failing status: validation errors when it is a 422 with a JSON body, an HTTP error otherwise. */
16
+ function fromFailedResponse(response, url, error) {
17
+ const body = response.status === 422 ? parseJson(response.data) : null;
18
+ if (body) {
19
+ return { kind: 'invalid', errors: body.value?.errors || {} };
20
+ }
21
+ return {
22
+ kind: 'http-error',
23
+ error: error ?? new HttpResponseError(`Request failed with status ${response.status}`, response, url),
24
+ };
25
+ }
26
+ /** Sends a request and reports how it ended. It never throws. */
27
+ async function send(request) {
28
+ try {
29
+ const response = await http.getClient().request(request);
30
+ if (!isSuccessStatus(response.status)) {
31
+ return fromFailedResponse(response, request.url);
32
+ }
33
+ // An empty body (204) is a success without data.
34
+ const data = (response.data ? JSON.parse(response.data) : null);
35
+ return { kind: 'success', data, response };
36
+ }
37
+ catch (error) {
38
+ if (error instanceof HttpResponseError) {
39
+ return fromFailedResponse(error.response, request.url, error);
40
+ }
41
+ if (error instanceof HttpCancelledError || (error instanceof Error && error.name === 'AbortError')) {
42
+ return { kind: 'cancelled' };
43
+ }
44
+ return { kind: 'failed', error: error instanceof Error ? error : new Error('The request failed.') };
45
+ }
46
+ }
47
+ /** GET puts the data in the query string, files make a multipart body, anything else is JSON. */
48
+ function encodeRequest(method, url, data) {
49
+ if (method === 'get') {
50
+ return { url: mergeDataIntoQueryString(method, url, data)[0], headers: {} };
51
+ }
52
+ if (hasFiles(data)) {
53
+ const indices = config.get('form.forceIndicesArrayFormatInFormData');
54
+ return { url, body: objectToFormData(data, new FormData(), null, indices ? 'indices' : 'brackets'), headers: {} };
55
+ }
56
+ return { url, body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } };
57
+ }
58
+ export default function useHttp(...args) {
59
+ const { rememberKey, data, precognitionEndpoint } = UseFormUtils.parseUseFormArguments(...args);
60
+ const state = useFormState({ data, rememberKey, precognitionEndpoint });
61
+ const [response, setResponse] = createSignal(null);
62
+ const form = state.form;
63
+ let newest = null;
64
+ let pendingOptimistic = null;
65
+ /** Shows the optimistic data, and returns what to restore if the request does not succeed. */
66
+ const showOptimistic = (options) => {
67
+ const optimistic = options.optimistic ?? pendingOptimistic;
68
+ pendingOptimistic = null;
69
+ if (!optimistic) {
70
+ return undefined;
71
+ }
72
+ const before = state.latestData();
73
+ const patch = optimistic(cloneDeep(before));
74
+ form.setData((current) => Object.assign(current, patch));
75
+ return before;
76
+ };
77
+ /** Applies an outcome to the form and the callbacks. It resolves with the data, or throws. */
78
+ const settle = (outcome, url, options, restore) => {
79
+ if (outcome.kind !== 'success' && restore) {
80
+ form.setData(restore);
81
+ }
82
+ switch (outcome.kind) {
83
+ case 'success':
84
+ state.markAsSuccessful();
85
+ setResponse(() => outcome.data);
86
+ options.onSuccess?.(outcome.data, outcome.response);
87
+ if (!state.defaultsCalledInOnSuccess) {
88
+ state.commitDefaults(state.latestData());
89
+ }
90
+ return outcome.data;
91
+ case 'invalid': {
92
+ const errors = (state.withAllErrors.enabled() ? outcome.errors : toSimpleValidationErrors(outcome.errors));
93
+ state.clearErrors();
94
+ state.setError(errors);
95
+ options.onError?.(errors);
96
+ return undefined;
97
+ }
98
+ case 'http-error':
99
+ options.onHttpException?.(outcome.error.response);
100
+ throw outcome.error;
101
+ case 'cancelled':
102
+ options.onCancel?.();
103
+ throw new HttpCancelledError(undefined, url);
104
+ case 'failed':
105
+ options.onNetworkError?.(outcome.error);
106
+ throw outcome.error;
107
+ }
108
+ };
109
+ const submit = async (method, url, options) => {
110
+ if (options.onBefore?.() === false) {
111
+ throw new Error('The request was stopped because onBefore returned false.');
112
+ }
113
+ state.defaultsCalledInOnSuccess = false;
114
+ state.resetBeforeSubmit();
115
+ const attempt = { controller: new AbortController() };
116
+ newest = attempt;
117
+ options.onCancelToken?.({ cancel: () => attempt.controller.abort() });
118
+ const restore = showOptimistic(options);
119
+ state.setProcessing(true);
120
+ options.onStart?.();
121
+ const payload = state.transformData(state.latestData());
122
+ const encoded = encodeRequest(method, url, payload);
123
+ const outcome = await send({
124
+ method,
125
+ url: encoded.url,
126
+ data: encoded.body,
127
+ headers: { Accept: 'application/json', ...encoded.headers, ...options.headers },
128
+ signal: attempt.controller.signal,
129
+ onUploadProgress: (event) => {
130
+ if (newest === attempt) {
131
+ state.setProgress(event);
132
+ }
133
+ options.onProgress?.(event);
134
+ },
135
+ });
136
+ try {
137
+ return settle(outcome, url, options, restore);
138
+ }
139
+ finally {
140
+ // An older request that ends while a newer one is in flight leaves `processing` to the newer one.
141
+ if (newest === attempt) {
142
+ state.finishProcessing();
143
+ newest = null;
144
+ }
145
+ options.onFinish?.();
146
+ }
147
+ };
148
+ Object.defineProperty(form, 'response', { get: response, enumerable: true, configurable: true });
149
+ Object.assign(form, {
150
+ get: (url, options = {}) => submit('get', url, options),
151
+ post: (url, options = {}) => submit('post', url, options),
152
+ put: (url, options = {}) => submit('put', url, options),
153
+ patch: (url, options = {}) => submit('patch', url, options),
154
+ delete: (url, options = {}) => submit('delete', url, options),
155
+ query: (url, options = {}) => submit('query', url, options),
156
+ submit: (...submitArgs) => {
157
+ // Only the callbacks differ from a form submit, and `parseSubmitArguments` just passes them on.
158
+ const parsed = UseFormUtils.parseSubmitArguments(submitArgs, state.precognitionEndpoint());
159
+ return submit(parsed.method, parsed.url, parsed.options);
160
+ },
161
+ cancel: () => newest?.controller.abort(),
162
+ optimistic: (callback) => {
163
+ pendingOptimistic = callback;
164
+ return form;
165
+ },
166
+ withAllErrors: () => {
167
+ state.withAllErrors.enable();
168
+ return form;
169
+ },
170
+ });
171
+ return form;
172
+ }
@@ -0,0 +1,6 @@
1
+ import type { Page, PageProps, SharedPageProps } from '@inertiajs/core';
2
+ /**
3
+ * Returns the current page as a reactive, store-like object. Read `page.props.x` inside JSX,
4
+ * a memo or an effect compute; never destructure it. Throws outside the Inertia app.
5
+ */
6
+ export default function usePage<TPageProps extends PageProps = PageProps>(): Page<TPageProps & SharedPageProps>;
@@ -0,0 +1,9 @@
1
+ import { useContext } from 'solid-js';
2
+ import PageContext from './PageContext';
3
+ /**
4
+ * Returns the current page as a reactive, store-like object. Read `page.props.x` inside JSX,
5
+ * a memo or an effect compute; never destructure it. Throws outside the Inertia app.
6
+ */
7
+ export default function usePage() {
8
+ return useContext(PageContext);
9
+ }
@@ -0,0 +1,12 @@
1
+ import { type PollOptions, type ReloadOptions } from '@inertiajs/core';
2
+ export interface InertiaPoll {
3
+ start: () => void;
4
+ stop: () => void;
5
+ /** Getter: read it in JSX or a memo, do not destructure the object. */
6
+ readonly polling: boolean;
7
+ }
8
+ /**
9
+ * Reloads the page every `interval` milliseconds while the component is mounted. A function `requestOptions` is
10
+ * called for each poll, so it can read the current state.
11
+ */
12
+ export default function usePoll(interval: number, requestOptions?: ReloadOptions | (() => ReloadOptions), options?: PollOptions): InertiaPoll;
@@ -0,0 +1,28 @@
1
+ import { router } from '@inertiajs/core';
2
+ import { createSignal, onSettled } from 'solid-js';
3
+ /**
4
+ * Reloads the page every `interval` milliseconds while the component is mounted. A function `requestOptions` is
5
+ * called for each poll, so it can read the current state.
6
+ */
7
+ export default function usePoll(interval, requestOptions = {}, options = { autoStart: true }) {
8
+ const autoStart = options.autoStart ?? true;
9
+ const [polling, setPolling] = createSignal(autoStart);
10
+ let poll;
11
+ onSettled(() => {
12
+ poll = router.poll(interval, requestOptions, { ...options, autoStart });
13
+ return () => poll?.destroy();
14
+ });
15
+ return {
16
+ start() {
17
+ poll?.start();
18
+ setPolling(true);
19
+ },
20
+ stop() {
21
+ poll?.stop();
22
+ setPolling(false);
23
+ },
24
+ get polling() {
25
+ return polling();
26
+ },
27
+ };
28
+ }
@@ -0,0 +1,10 @@
1
+ import { type VisitOptions } from '@inertiajs/core';
2
+ export interface InertiaPrefetch {
3
+ /** Getters: read them in JSX or a memo, do not destructure the object. */
4
+ readonly lastUpdatedAt: number | null;
5
+ readonly isPrefetching: boolean;
6
+ readonly isPrefetched: boolean;
7
+ flush: () => void;
8
+ }
9
+ /** Tracks the prefetch cache entry of the current page: when it was fetched, and whether a request is in flight. */
10
+ export default function usePrefetch(options?: VisitOptions): InertiaPrefetch;
@@ -0,0 +1,42 @@
1
+ import { router } from '@inertiajs/core';
2
+ import { createStore, merge, onSettled } from 'solid-js';
3
+ const currentPath = () => window.location.pathname;
4
+ /** What core's prefetch cache holds for the current page. A server render has no page, so it holds nothing. */
5
+ function readCache(options) {
6
+ if (typeof window === 'undefined') {
7
+ return { lastUpdatedAt: null, isPrefetching: false, isPrefetched: false };
8
+ }
9
+ const cached = router.getCached(currentPath(), options);
10
+ return {
11
+ lastUpdatedAt: cached?.staleTimestamp || null,
12
+ isPrefetching: router.getPrefetching(currentPath(), options) !== null,
13
+ isPrefetched: cached !== null,
14
+ };
15
+ }
16
+ /** Tracks the prefetch cache entry of the current page: when it was fetched, and whether a request is in flight. */
17
+ export default function usePrefetch(options = {}) {
18
+ const [state, setState] = createStore(readCache(options));
19
+ onSettled(() => {
20
+ const stopPrefetching = router.on('prefetching', ({ detail }) => {
21
+ if (detail.visit.url.pathname === currentPath()) {
22
+ setState((draft) => {
23
+ draft.isPrefetching = true;
24
+ });
25
+ }
26
+ });
27
+ const stopPrefetched = router.on('prefetched', ({ detail }) => {
28
+ if (detail.visit.url.pathname === currentPath()) {
29
+ setState((draft) => {
30
+ draft.isPrefetching = false;
31
+ draft.isPrefetched = true;
32
+ draft.lastUpdatedAt = detail.fetchedAt;
33
+ });
34
+ }
35
+ });
36
+ return () => {
37
+ stopPrefetching();
38
+ stopPrefetched();
39
+ };
40
+ });
41
+ return merge(state, { flush: () => router.flush(currentPath(), options) });
42
+ }
@@ -0,0 +1,8 @@
1
+ /** Reactive object: `value`, `loading` and `loaded` are getters, read them in JSX or a memo. */
2
+ export interface InertiaProp<T> {
3
+ readonly value: T | undefined;
4
+ readonly loading: boolean;
5
+ readonly loaded: boolean;
6
+ }
7
+ /** Reads one (dot-path) page prop. */
8
+ export default function useProp<T = unknown>(name: string): InertiaProp<T>;
@@ -0,0 +1,27 @@
1
+ import { propRefreshes } from '@inertiajs/core';
2
+ import { get } from 'es-toolkit/compat';
3
+ import { createSignal, isHydrating, onSettled } from 'solid-js';
4
+ import usePage from './usePage';
5
+ /** Reads one (dot-path) page prop. */
6
+ export default function useProp(name) {
7
+ const page = usePage();
8
+ // The server never renders a prop as loading, so hydration starts from false and onSettled catches up
9
+ const [loading, setLoading] = createSignal(isHydrating() ? false : propRefreshes.isRefreshing(name));
10
+ onSettled(() => {
11
+ const sync = () => setLoading(propRefreshes.isRefreshing(name));
12
+ const unsubscribe = propRefreshes.onChange(sync);
13
+ sync();
14
+ return unsubscribe;
15
+ });
16
+ return {
17
+ get value() {
18
+ return get(page.props, name);
19
+ },
20
+ get loading() {
21
+ return loading();
22
+ },
23
+ get loaded() {
24
+ return get(page.props, name) !== undefined;
25
+ },
26
+ };
27
+ }
@@ -0,0 +1,14 @@
1
+ import { type Signal } from 'solid-js';
2
+ /** The value saved under `key` in the history state, copied so later changes never reach the history entry. */
3
+ export declare function restoreRemembered<T>(key: string | undefined): T | undefined;
4
+ /**
5
+ * Saves `read()` under `key` each time it changes, and once at setup.
6
+ * Top-level keys listed by `excludeKeys`, read at save time, are left out when the value is an object.
7
+ */
8
+ export declare function rememberEffect<T>(key: string | undefined, read: () => T, excludeKeys?: () => readonly string[]): void;
9
+ /**
10
+ * Like `createSignal`, but the value is saved to and restored from Inertia's history state under `key`.
11
+ * `excludeKeys` is read on each save and lists object keys to leave out of the remembered copy.
12
+ * The state cannot be a function, because `createSignal` would treat it as a compute function.
13
+ */
14
+ export default function useRemember<State>(initialState: State, key?: string, excludeKeys?: () => string[]): Signal<State>;
@@ -0,0 +1,36 @@
1
+ import { router } from '@inertiajs/core';
2
+ import { cloneDeep } from 'es-toolkit';
3
+ import { createEffect, createSignal, untrack } from 'solid-js';
4
+ /** The value saved under `key` in the history state, copied so later changes never reach the history entry. */
5
+ export function restoreRemembered(key) {
6
+ const restored = router.restore(key);
7
+ return restored === undefined ? undefined : cloneDeep(restored);
8
+ }
9
+ /**
10
+ * Saves `read()` under `key` each time it changes, and once at setup.
11
+ * Top-level keys listed by `excludeKeys`, read at save time, are left out when the value is an object.
12
+ */
13
+ export function rememberEffect(key, read, excludeKeys) {
14
+ createEffect(read, (value) => {
15
+ const excluded = untrack(() => excludeKeys?.() ?? []);
16
+ if (excluded.length > 0 && typeof value === 'object' && value !== null) {
17
+ const filtered = { ...value };
18
+ excluded.forEach((name) => delete filtered[name]);
19
+ router.remember(filtered, key);
20
+ }
21
+ else {
22
+ router.remember(value, key);
23
+ }
24
+ });
25
+ }
26
+ /**
27
+ * Like `createSignal`, but the value is saved to and restored from Inertia's history state under `key`.
28
+ * `excludeKeys` is read on each save and lists object keys to leave out of the remembered copy.
29
+ * The state cannot be a function, because `createSignal` would treat it as a compute function.
30
+ */
31
+ export default function useRemember(initialState, key, excludeKeys) {
32
+ const restored = restoreRemembered(key);
33
+ const signal = createSignal((restored === undefined ? initialState : restored));
34
+ rememberEffect(key, signal[0], excludeKeys);
35
+ return signal;
36
+ }