react-easy-loading 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.
package/.editorconfig ADDED
@@ -0,0 +1,17 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 4
6
+ max_line_length = 100
7
+ insert_final_newline = true
8
+ charset = utf-8
9
+
10
+ [*.md]
11
+ indent_size = 2
12
+
13
+ [*.yml]
14
+ indent_size = 2
15
+
16
+ [*.json]
17
+ indent_size = 2
@@ -0,0 +1,128 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ hichem.taboukouyout@hichemtab-tech.me.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.0, available at
119
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120
+
121
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct
122
+ enforcement ladder](https://github.com/mozilla/diversity).
123
+
124
+ [homepage]: https://www.contributor-covenant.org
125
+
126
+ For answers to common questions about this code of conduct, see the FAQ at
127
+ https://www.contributor-covenant.org/faq. Translations are available at
128
+ https://www.contributor-covenant.org/translations.
@@ -0,0 +1,112 @@
1
+ # 👥 Contributing to React Easy Loading
2
+
3
+ Thank you for your interest in contributing to this project! Open source contributions help improve projects, introduce new ideas, and build a better community.
4
+
5
+ ---
6
+
7
+ ## 🚨 Before You Start
8
+
9
+ Before contributing, please:
10
+
11
+ - Browse [existing issues](https://github.com/HichemTab-tech/react-easy-loading/issues) to see if your issue or feature idea has already been raised.
12
+ - If your idea or issue hasn't been addressed, feel free to [create a new issue](https://github.com/HichemTab-tech/react-easy-loading/issues/new).
13
+
14
+ ---
15
+
16
+ ## 📄 Code of Conduct
17
+
18
+ Please ensure your contributions follow these general guidelines:
19
+
20
+ - Be respectful and professional at all times.
21
+ - Treat everyone in the community with kindness.
22
+ - Discuss constructively and respectfully.
23
+
24
+ Any harassment or inappropriate behavior is strictly prohibited.
25
+
26
+ ---
27
+
28
+ ## ⚙️ Setting Up Your Environment
29
+
30
+ To start contributing to the project, follow these steps:
31
+
32
+ 1. Fork this repository on GitHub.
33
+ 2. Clone your forked repository:
34
+
35
+ ```sh
36
+ git clone https://github.com/YOUR_GITHUB_USERNAME/react-easy-loading
37
+ cd react-easy-loading
38
+ ```
39
+
40
+ 3. Install dependencies with your preferred package manager:
41
+
42
+ - npm:
43
+ ```sh
44
+ npm install
45
+ ```
46
+
47
+ - pnpm:
48
+ ```sh
49
+ pnpm install
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 🔨 Making Changes
55
+
56
+ To submit a feature or bug fix, please:
57
+
58
+ 1. Create a branch from the `main` branch. Name the branch according to your feature or bug fix:
59
+
60
+ ```sh
61
+ git checkout -b feature/CoolNewFeature
62
+ ```
63
+
64
+ or for bug fixes:
65
+
66
+ ```sh
67
+ git checkout -b fix/bug-description
68
+ ```
69
+
70
+ 2. After making your necessary changes, run relevant checks and tests to ensure everything works correctly:
71
+
72
+ ```sh
73
+ npm test
74
+ ```
75
+
76
+ or with pnpm:
77
+
78
+ ```sh
79
+ pnpm test
80
+ ```
81
+
82
+ 3. Stage and commit your changes clearly describing what has been changed:
83
+
84
+ ```sh
85
+ git add .
86
+ git commit -m 'feat: Add CoolNewFeature to improve performance'
87
+ ```
88
+
89
+ 4. Push your branch to your forked repo:
90
+
91
+ ```sh
92
+ git push origin feature/CoolNewFeature
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 📝 Submitting a Pull Request
98
+
99
+ When your changes are ready:
100
+
101
+ 1. Open GitHub and navigate to your forked repository.
102
+ 2. Click `Compare & pull request`.
103
+ 3. Clearly explain the following in your pull request description:
104
+ - **What changes you made and why they are needed.**
105
+ - **Any linked relevant issues (e.g., "**Closes #number**").**
106
+ 4. Wait for project maintainers review to suggest changes or to merge your PR.
107
+
108
+ ---
109
+
110
+ ## 📌 Commit Message Guidelines
111
+
112
+ Write clear commit messages, formatted this way:
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Hichem Taboukouyout
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/README.md ADDED
@@ -0,0 +1,299 @@
1
+ # React Easy Loading
2
+
3
+ Simplify loading states across your React app with built-in status tracking and fallbacks.
4
+ This package provides a simple but powerful way to manage `idle`, `loading`, `success`,
5
+ and `error` states, removing boilerplate and making your code cleaner and more readable.
6
+
7
+ ![react-easy-loading banner](assets/banner.png)
8
+
9
+ ## Getting Started
10
+
11
+ Start by installing the package via your preferred package manager:
12
+
13
+ ```sh
14
+ npm install react-easy-loading
15
+ ```
16
+
17
+ or, if using pnpm:
18
+
19
+ ```sh
20
+ pnpm add react-easy-loading
21
+ ```
22
+
23
+ ## ☕ 60-Second TL;DR
24
+
25
+ At its core, `react-easy-loading` lets you create a `loading` object that tracks the state of an operation. You can then use its components to conditionally render content.
26
+
27
+ Here's the simplest example:
28
+
29
+ ```javascript
30
+ import { createLoading } from 'react-easy-loading';
31
+ import React, {useEffect} from 'react';
32
+
33
+ // 1. Create a loading instance
34
+ const userLoading = createLoading();
35
+
36
+ // 2. A function that returns a promise
37
+ const fetchUser = () => fetch('https://api.github.com/users/HichemTab-tech').then(res => res.json());
38
+
39
+ export default function Demo() {
40
+ const [user, setUser] = React.useState(null);
41
+
42
+ // 3. Set the loading state manually
43
+ useEffect(() => {
44
+ userLoading.set('loading');
45
+ fetchUser()
46
+ .then(user => {
47
+ setUser(user);
48
+ userLoading.set('success');
49
+ })
50
+ .catch(() => userLoading.set('error'));
51
+ }, []);
52
+
53
+ return (
54
+ <div>
55
+ {/* 4. Show content based on loading state */}
56
+ <userLoading.ShowWhenLoaded fallback={<p>Loading user...</p>}>
57
+ <h1>{user?.name}</h1>
58
+ </userLoading.ShowWhenLoaded>
59
+ </div>
60
+ );
61
+ }
62
+ ```
63
+
64
+ ## Cross-Component State Tracking
65
+
66
+ Because `loading` instances are just exported objects,
67
+ you can share a single loading state across completely different parts of your application without prop-drilling.
68
+
69
+ **`src/loadings.js`**
70
+
71
+ ```javascript
72
+ import { createLoading } from 'react-easy-loading';
73
+
74
+ // Create and export a loading instance
75
+ export const userProfileLoading = createLoading({ initialState: 'idle' });
76
+ ```
77
+
78
+ **`src/components/ProfileHeader.js`**
79
+
80
+ ```javascript
81
+ import { userProfileLoading } from '../loadings';
82
+
83
+ function ProfileHeader() {
84
+ // Use a hook to reactively track the loading state
85
+ const isLoading = userProfileLoading.useIsLoading();
86
+
87
+ if (isLoading) {
88
+ return <p>Updating header...</p>;
89
+ }
90
+ // ... render header
91
+ }
92
+ ```
93
+
94
+ **`src/components/Avatar.js`**
95
+
96
+ ```javascript
97
+ import { userProfileLoading } from '../loadings';
98
+
99
+ function Avatar() {
100
+ // Use a component from the same instance to show a fallback
101
+ return (
102
+ <userProfileLoading.ShowWhenLoaded fallback={<AvatarSkeleton />}>
103
+ <img src="..." alt="User Avatar" />
104
+ </userProfileLoading.ShowWhenLoaded>
105
+ );
106
+ }
107
+ ```
108
+
109
+ ## ✨ Automatic State Management with `wrap`
110
+
111
+ The `wrap` function automates state management.
112
+ It takes an async function, sets the state to `loading` immediately,
113
+ and updates it to `success` or `error` when the promise settles.
114
+ It also automatically implements a `retry` function.
115
+
116
+ ```javascript
117
+ const loadUser = () => {
118
+ // This handles set('loading'), set('success'), set('error'), and setRetry()
119
+ userLoading.wrap(fetchUser).then(setUser);
120
+ };
121
+ ```
122
+
123
+ ### Finer Control with `wrapWithControl`
124
+
125
+ For more complex scenarios, `wrapWithControl` lets you chain `.then()`, `.catch()`, and `.finally()` handlers *before* the async operation starts. The operation is only executed when you call `.start()`.
126
+
127
+ ```javascript
128
+ const { then, catch_, start } = userLoading.wrapWithControl(fetchUser);
129
+
130
+ // Define extra custom handlers
131
+ then(user => console.log('User loaded:', user));
132
+ catch_(error => console.error('Failed to load user:', error));
133
+
134
+ // Later, in your event handler
135
+ const loadUser = () => {
136
+ start().then(setUser); // The promise starts here
137
+ };
138
+ ```
139
+
140
+ ## Fallbacks and The Registry
141
+
142
+ A key benefit of `react-easy-loading` is its powerful fallback system.
143
+ You can define a library of reusable loading and error components and use them by name.
144
+
145
+ ### How to Use the Registry
146
+
147
+ 1. **Register a named fallback**: Use `registerFallback` or `registerErrorFallback`.
148
+ 2. **Use it by name**: Pass the name to `createLoading` or the `fallback`/`errorFallback` prop.
149
+
150
+ This allows you to maintain a consistent look and feel for common UI states like inline spinners,
151
+ card loaders, or error modals.
152
+
153
+ **`src/fallbacks.js`**
154
+
155
+ ```javascript
156
+ import { registerFallback, registerErrorFallback } from 'react-easy-loading';
157
+
158
+ const InlineSpinner = () => <span className="spinner-inline"></span>;
159
+ const CardLoader = () => <div className="card-skeleton"></div>;
160
+ const ErrorCard = ({ errors, retry }) => (
161
+ <div className="error-card">
162
+ <h4>Oops! Something went wrong.</h4>
163
+ <p>{errors[0]?.message}</p>
164
+ <button onClick={retry}>Try Again</button>
165
+ </div>
166
+ );
167
+
168
+ // Register your components
169
+ registerFallback('inline', <InlineSpinner />);
170
+ registerFallback('card', <CardLoader />);
171
+ registerErrorFallback('defaultError', ErrorCard);
172
+ ```
173
+
174
+ **`src/MyComponent.js`**
175
+
176
+ ```javascript
177
+ // Use the 'card' fallback for this instance
178
+ const postsLoading = createLoading({ defaultFallback: 'card' });
179
+
180
+ function MyComponent() {
181
+ return (
182
+ <div>
183
+ {/* But use the 'inline' fallback for this specific case */}
184
+ <postsLoading.ShowWhenLoaded fallback="inline">
185
+ <span>Post loaded!</span>
186
+ </postsLoading.ShowWhenLoaded>
187
+ </div>
188
+ );
189
+ }
190
+ ```
191
+
192
+ ### Error Fallbacks and Retry Logic
193
+
194
+ When you use `wrap` or `wrapWithControl`,
195
+ the `retry` function is automatically implemented to re-run the original async operation.
196
+
197
+ ```javascript
198
+ import { createLoading, registerDefaultErrorFallback } from 'react-easy-loading';
199
+
200
+ // A beautiful, reusable error component with a retry button
201
+ const ErrorCard = ({ errors, retry }) => (
202
+ <div style={{ border: '1px solid red', padding: '1rem' }}>
203
+ <h4>Oops! Something went wrong.</h4>
204
+ <ul>
205
+ {errors.map((e, i) => <li key={i}>{e.message || String(e)}</li>)}
206
+ </ul>
207
+ {retry && <button onClick={retry}>Try Again</button>}
208
+ </div>
209
+ );
210
+
211
+ // Register it as the global default error fallback
212
+ registerDefaultErrorFallback(ErrorCard);
213
+
214
+ const dataLoading = createLoading();
215
+
216
+ function App() {
217
+ const fetchData = () => {
218
+ // This promise will reject
219
+ return Promise.reject(new Error('Network connection failed'));
220
+ };
221
+
222
+ const load = () => dataLoading.wrap(fetchData);
223
+
224
+ return (
225
+ <div>
226
+ <button onClick={load}>Load Data</button>
227
+ <dataLoading.ShowWhenLoaded errorFallback>
228
+ <p>Data loaded successfully!</p>
229
+ </dataLoading.ShowWhenLoaded>
230
+ </div>
231
+ );
232
+ }
233
+ ```
234
+
235
+ When `fetchData` fails, `ShowWhenLoaded` will automatically render the `ErrorCard` because `errorFallback` is set to `true`, which tells it to use the default. Clicking "Try Again" will call `dataLoading.retry()`, re-triggering the `fetchData` call.
236
+
237
+
238
+ ---
239
+
240
+ ## The `loading` Object: API Deep Dive
241
+
242
+ The object returned by `createLoading` is your command center.
243
+ It provides both **reactive hooks** for use in components and **non-reactive getters/setters** for use in event handlers or external logic.
244
+
245
+ ### Reactive Hooks
246
+
247
+ Use these inside your React components to trigger re-renders when the state changes.
248
+
249
+ | Hook | Description |
250
+ |------------------|-------------------------------------------------------------------|
251
+ | `use()` | Returns the current `LoadingState` (`'idle'`, `'loading'`, etc.). |
252
+ | `useIsLoading()` | Returns `true` if the state is `'loading'`. |
253
+ | `useErrors()` | Returns the array of errors, or `undefined`. |
254
+ | `useContext()` | Returns the shared context object. |
255
+
256
+ ### Getters (Non-Reactive)
257
+
258
+ Use these to get the current value without subscribing to updates.
259
+
260
+ | Getter | Description |
261
+ |---------------|-----------------------------------------|
262
+ | `get()` | Returns the current `LoadingState`. |
263
+ | `getErrors()` | Returns the current array of errors. |
264
+ | `isLoading()` | Returns `true` if state is `'loading'`. |
265
+ | `isSuccess()` | Returns `true` if state is `'success'`. |
266
+ | `isError()` | Returns `true` if state is `'error'`. |
267
+
268
+ ### Setters and Methods
269
+
270
+ Use these to control the state from anywhere.
271
+
272
+ | Method | Description |
273
+ |---------------------|--------------------------------------------|
274
+ | `set(state)` | Manually sets the loading state. |
275
+ | `reset()` | Resets the state to its initial value. |
276
+ | `retry()` | Re-runs the last wrapped async function. |
277
+ | `setRetry(fn)` | Manually provides a custom retry function. |
278
+ | `setErrors(errors)` | Overwrites the errors array. |
279
+ | `addError(error)` | Adds an error to the errors array. |
280
+
281
+ ---
282
+
283
+ ## 🤝 Contributions
284
+
285
+ Contributions are welcome! Please follow the standard fork-and-pull-request workflow.
286
+
287
+ ## Issues
288
+
289
+ If you encounter any issue, please open an issue [here](https://github.com/HichemTab-tech/react-easy-loading/issues).
290
+
291
+ ## License
292
+
293
+ Distributed under the MIT License. See [`LICENSE`](LICENSE) file for more details.
294
+
295
+ &copy; 2025 [Hichem Taboukouyout](mailto:hichem.taboukouyout@hichemtab-tech.me)
296
+
297
+ ---
298
+
299
+ _If you found this package helpful, consider leaving a star! ⭐️_
@@ -0,0 +1,10 @@
1
+ import { Loading, ReactNodeOrFunction } from '../create-loading';
2
+ import { default as React, PropsWithChildren } from 'react';
3
+ interface AllLoadedProps {
4
+ of: Loading[];
5
+ fallback?: React.ReactNode;
6
+ errorFallback?: ReactNodeOrFunction<[errors: any[] | undefined, retry: (() => void) | undefined]>;
7
+ }
8
+ export declare const AllLoaded: ({ of, fallback, errorFallback, children }: PropsWithChildren<AllLoadedProps>) => string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element | null | undefined;
9
+ export {};
10
+ //# sourceMappingURL=AllLoaded.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AllLoaded.d.ts","sourceRoot":"","sources":["../../src/components/AllLoaded.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,OAAO,EAAE,mBAAmB,EAAC,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,EAAC,KAAK,iBAAiB,EAAiB,MAAM,OAAO,CAAC;AAOpE,UAAU,cAAc;IACpB,EAAE,EAAE,OAAO,EAAE,CAAC;IACd,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAC3B,aAAa,CAAC,EAAE,mBAAmB,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,SAAS,EAAE,KAAK,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;CACrG;AAGD,eAAO,MAAM,SAAS,GAAI,2CAAyC,iBAAiB,CAAC,cAAc,CAAC,0TA+BnG,CAAA"}
@@ -0,0 +1,2 @@
1
+ export * from './AllLoaded';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC"}
@@ -0,0 +1,68 @@
1
+ import { default as React, PropsWithChildren, ReactNode } from 'react';
2
+ export type LoadingState = "idle" | "loading" | "success" | "error";
3
+ export type LoadingSharedState<Errors extends unknown[] = string[], Context extends Record<string, unknown> = any> = {
4
+ state: LoadingState;
5
+ errors?: Errors;
6
+ context?: Context;
7
+ retry?: () => void;
8
+ };
9
+ export type WrappedPromiseReturn<T> = {
10
+ then: WrappedPromise<Promise<T>['then']>;
11
+ catch_: WrappedPromise<Promise<T>['catch']>;
12
+ finally_: WrappedPromise<Promise<T>['finally']>;
13
+ start: () => Promise<T>;
14
+ };
15
+ export type ReactNodeOrFunction<T extends unknown[]> = ReactNode | ((...args: T) => ReactNode);
16
+ export type ExtractPromiseParameters<T> = T extends (...args: infer P) => Promise<unknown> ? P : never;
17
+ export type PromiseFunctionWithCustomReturn<T, R> = (...args: ExtractPromiseParameters<T>) => R;
18
+ export type WrappedPromise<T> = PromiseFunctionWithCustomReturn<T, WrappedPromiseReturn<T>>;
19
+ export type Loading<Errors extends unknown[] = string[], Context extends Record<string, unknown> = any> = {
20
+ use: () => LoadingState;
21
+ useIsLoading: () => boolean;
22
+ useErrors: () => Errors | undefined;
23
+ useContext: () => Context | undefined;
24
+ isLoading: () => boolean;
25
+ isIdle: () => boolean;
26
+ isSuccess: () => boolean;
27
+ isError: () => boolean;
28
+ isFinished: () => boolean;
29
+ is: (s: LoadingState | LoadingState[]) => boolean;
30
+ hasErrors: () => boolean;
31
+ get: () => LoadingState;
32
+ getErrors: () => Errors | undefined;
33
+ getContext: () => Context | undefined;
34
+ set(state: LoadingState): void;
35
+ retry: () => void;
36
+ reset: () => void;
37
+ addError: (error: Errors[number]) => void;
38
+ setContext: (context: Context) => void;
39
+ setErrors: (errors: Errors) => void;
40
+ clearErrors: () => void;
41
+ setRetry: (retry: () => void) => void;
42
+ whenLoaded: () => Promise<void>;
43
+ whenFinished: () => Promise<void>;
44
+ wrap: <T>(asyncFn: () => Promise<T>) => Promise<T>;
45
+ wrapWithControl: <T>(asyncFn: () => Promise<T>) => WrappedPromiseReturn<T>;
46
+ ShowWhenLoaded: React.FC<PropsWithChildren<{
47
+ fallback?: React.ReactNode;
48
+ errorFallback?: ReactNodeOrFunction<[errors: Errors, retry: () => void]>;
49
+ }>>;
50
+ ShowWhileLoading: React.FC<PropsWithChildren>;
51
+ ShowWhenError: React.FC<{
52
+ children?: ReactNodeOrFunction<[errors: Errors, retry: () => void]> | undefined;
53
+ }>;
54
+ ShowWhenFinish: React.FC<{
55
+ children?: ReactNodeOrFunction<[errors: Errors | undefined, retry: (() => void) | undefined]> | undefined;
56
+ }>;
57
+ ShowWhen: React.FC<PropsWithChildren<{
58
+ state: LoadingState;
59
+ }>>;
60
+ };
61
+ export type CreateLoadingOptions = {
62
+ initialState?: LoadingState;
63
+ defaultFallback?: React.ReactNode;
64
+ defaultErrorFallback?: React.ReactNode;
65
+ defaultRetry?: () => void;
66
+ };
67
+ export declare const createLoading: <Errors extends unknown[] = string[], Context extends Record<string, unknown> = any>({ initialState, defaultFallback, defaultErrorFallback, defaultRetry }?: CreateLoadingOptions) => Loading<Errors, Context>;
68
+ //# sourceMappingURL=create-loading.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-loading.d.ts","sourceRoot":"","sources":["../src/create-loading.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,EAAC,KAAK,iBAAiB,EAAE,KAAK,SAAS,EAAC,MAAM,OAAO,CAAC;AAIpE,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC;AACpE,MAAM,MAAM,kBAAkB,CAAC,MAAM,SAAS,OAAO,EAAE,GAAG,MAAM,EAAE,EAAE,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,GAAG,IAAI;IACjH,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB,CAAA;AAED,MAAM,MAAM,oBAAoB,CAAC,CAA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