svelte-infinite 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Nico Domino
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,124 @@
1
+ <img align="right" src="https://raw.githubusercontent.com/ndom91/svelte-infinite/51683d459ae954a99e7c5c25817ed667678a0840/src/assets/SvelteLogo.svg" alt="Svelte Logo" width="128px" />
2
+
3
+ # Svelte Infinite
4
+
5
+ Svelte Infinite Scroller designed for use in **Svelte 5** with runes
6
+
7
+ - ⏰ Infinite Loop Detection
8
+ - πŸ“£ Control Loader State
9
+ - πŸ”Ž IntersectionObservor based
10
+ - ✨ Flexible
11
+
12
+ > [!NOTE]
13
+ > Initially inspired by [jonasgeiler/svelte-infinite-loading](https://github.com/jonasgeiler/svelte-infinite-loading)
14
+
15
+ ## πŸ—οΈ Getting Started
16
+
17
+ 1. Install `svelte-infinite`
18
+
19
+ ```bash
20
+ pnpm install svelte-infinite
21
+ ```
22
+
23
+ 2. Import both `InfiniteLoader` and `stateChanger` from `svelte-infinite`
24
+
25
+ 3. The component should wrap your list of items, and `stateChanger` should be used in your `triggerLoad` function to interact with the internal state of the component, telling it whether you're out of data, ran into an error, etc. See the example below and [in this repository](https://github.com/ndom91/svelte-infinite/blob/main/src/routes/%2Bpage.svelte#L12-L50) for more details.
26
+
27
+ ## 🍍 Example
28
+
29
+ ```svelte
30
+ <script lang="ts">
31
+ import { InfiniteLoader, stateChanger } from "svelte-infinite"
32
+
33
+ const LOAD_LIMIT = 20
34
+ const allItems = $state<number[]>($page.data.items)
35
+ let pageNumber = $state(1)
36
+
37
+ // 1. You'll have to pass the InfiniteLoader component a load function
38
+ // to its `triggerLoad` prop.
39
+ const loadMore = async () => {
40
+ try {
41
+ pageNumber += 1
42
+ const limit = LOAD_LIMIT
43
+ const skip = LOAD_LIMIT * (pageNumber - 1)
44
+
45
+ // If there are less results on the first page than the limit,
46
+ // don't keep trying to fetch more. We're done.
47
+ if (allItems.length < LOAD_LIMIT) {
48
+ stateChanger.complete()
49
+ return
50
+ }
51
+
52
+ const searchParams = new URLSearchParams({ limit, skip })
53
+
54
+ const dataResponse = await fetch(`/api/data?${searchParams}`)
55
+
56
+ if (!dataResponse.ok) {
57
+ stateChanger.error()
58
+ return
59
+ }
60
+ const data = await dataResponse.json()
61
+
62
+ if (data.items.length) {
63
+ allItems.push(...data.items)
64
+ }
65
+
66
+ // There are less items available than fit on one page,
67
+ // don't keep trying to fetch more. We're done.
68
+ if (allItems.length >= data.totalCount) {
69
+ stateChanger.complete()
70
+ } else {
71
+ stateChanger.loaded()
72
+ }
73
+ } catch (error) {
74
+ console.error(error)
75
+ stateChanger.error()
76
+ }
77
+ }
78
+ </script>
79
+
80
+ <main class="container">
81
+
82
+ <!-- 2. Here you wrap your items with the InfiniteLoader component -->
83
+
84
+ <InfiniteLoader triggerLoad={loadMore}>
85
+ {#each allItems as user (user.id)}
86
+ <UserCard {user} />
87
+ {/each}
88
+ </InfiniteLoader>
89
+ </main>
90
+
91
+ </script>
92
+ ```
93
+
94
+ ## ♾️ Usage
95
+
96
+ The `InfiniteLoader` component is a wrapper around your items, which will trigger the `triggerLoad` function when the user scrolls to the bottom of the list.
97
+
98
+ However, there is also a `stateChanger` export which you should use to interact with the internal state of the loader. For example, if your `fetch` call errored, or you've reached the maximum number of items, etc. See the `loadMore` function above or the example application in `/src/routes` in this repository.
99
+
100
+ ### stateChanger
101
+
102
+ The `stateChanger` import is an object with 4 methods on it:
103
+
104
+ 1. `stateChanger.loaded()` - Designed to be called after a successful fetch.
105
+ 2. `stateChanger.error()` - Designed to be called after a failed fetch or any other error. This will cause the `InfiniteLoader` to render a "Retry" button.
106
+ 3. `stateChanger.complete()` - Designed to be called when you've reached the end of your list and there are no more items to fetch.
107
+ 4. `stateChanger.reset()` - Designed to be called when you want to reset the state of the `InfiniteLoader` to its initial state, for example if there is a search input tied to your infinite list and the user enters a new query.
108
+
109
+ ### Props
110
+
111
+ - `triggerLoad: () => Promise<void>` - **required** - The function to call when the user scrolls to the bottom of the list.
112
+ - `loopTimeout: number = 1000` - optional - If the `loopMaxCalls` is reached within this duration (in milliseconds), a cool down period is triggered.
113
+ - `loopMaxCalls: number = 5` - optional - The number of calls to the `triggerLoad` function within timeout which should trigger cool down period.
114
+
115
+ ### Slots
116
+
117
+ - `loading` - Shown while calling `triggerLoad` and waiting on a response.
118
+ - `no-results` - Shown when there are no results to display.
119
+ - `no-data` - Shown when `stateChanger.complete()` is called, indicating the end of scroll.
120
+ - `error` - Shown when there is an error. Slot has an `attemptLoad` prop passed to it which is the `triggerLoad` function, designed for a "Retry" button or similar.
121
+
122
+ ## πŸ“ License
123
+
124
+ MIT
@@ -0,0 +1,171 @@
1
+ <script context="module">const STATUS = {
2
+ READY: "READY",
3
+ LOADING: "LOADING",
4
+ COMPLETE: "COMPLETE",
5
+ ERROR: "ERROR"
6
+ };
7
+ let isFirstLoad = $state(true);
8
+ let status = $state(STATUS.READY);
9
+ export const stateChanger = {
10
+ loaded: () => {
11
+ isFirstLoad = false;
12
+ status = STATUS.READY;
13
+ },
14
+ complete: () => {
15
+ isFirstLoad = false;
16
+ status = STATUS.COMPLETE;
17
+ },
18
+ reset: () => {
19
+ status = STATUS.READY;
20
+ isFirstLoad = true;
21
+ },
22
+ error: () => {
23
+ status = STATUS.ERROR;
24
+ }
25
+ };
26
+ </script>
27
+
28
+ <script>const { triggerLoad, loopTimeout = 1e3, loopMaxCalls = 5 } = $props();
29
+ const ERROR_INFINITE_LOOP = `Executed load function ${loopMaxCalls} or more times within a short period. Cooling off..`;
30
+ class LoopTracker {
31
+ coolingOff = false;
32
+ timer = null;
33
+ count = 0;
34
+ track() {
35
+ this.count += 1;
36
+ if (this.count >= loopMaxCalls) {
37
+ console.error(ERROR_INFINITE_LOOP);
38
+ this.coolingOff = true;
39
+ this.timer = setTimeout(() => {
40
+ this.coolingOff = false;
41
+ this.count = 0;
42
+ }, loopTimeout);
43
+ }
44
+ }
45
+ }
46
+ const loopTracker = new LoopTracker();
47
+ let intersectionTarget = $state();
48
+ let observer = $state();
49
+ let showLoading = $derived(status === STATUS.LOADING);
50
+ let showError = $derived(status === STATUS.ERROR);
51
+ let showNoResults = $derived(status === STATUS.COMPLETE && isFirstLoad);
52
+ let showNoMore = $derived(status === STATUS.COMPLETE && !isFirstLoad);
53
+ async function attemptLoad() {
54
+ if (status === STATUS.COMPLETE || status !== STATUS.READY && status !== STATUS.ERROR) {
55
+ return;
56
+ }
57
+ status = STATUS.LOADING;
58
+ if (!loopTracker.coolingOff) {
59
+ await triggerLoad();
60
+ loopTracker.track();
61
+ }
62
+ if (status !== STATUS.ERROR && status !== STATUS.COMPLETE) {
63
+ if (status === STATUS.LOADING) {
64
+ status = STATUS.READY;
65
+ isFirstLoad = false;
66
+ }
67
+ }
68
+ }
69
+ $effect(() => {
70
+ if (!observer) {
71
+ if (intersectionTarget) {
72
+ observer = new IntersectionObserver(
73
+ (entries) => {
74
+ if (entries[0]?.isIntersecting) {
75
+ attemptLoad();
76
+ }
77
+ },
78
+ { rootMargin: "100px 0px 0px 0px" }
79
+ );
80
+ observer.observe(intersectionTarget);
81
+ return observer;
82
+ }
83
+ }
84
+ return () => observer?.disconnect();
85
+ });
86
+ </script>
87
+
88
+ <div class="loader-wrapper">
89
+ <slot />
90
+
91
+ {#if showLoading}
92
+ <slot name="loading">
93
+ <div class="loading">Loading...</div>
94
+ </slot>
95
+ {/if}
96
+
97
+ {#if showNoResults}
98
+ <slot name="no-results">
99
+ <div class="no-results">No results</div>
100
+ </slot>
101
+ {/if}
102
+
103
+ {#if showNoMore}
104
+ <slot name="no-data">
105
+ <div class="no-data">No more data</div>
106
+ </slot>
107
+ {/if}
108
+
109
+ {#if showError}
110
+ <slot name="error" {attemptLoad}>
111
+ <div class="error">
112
+ <div class="label">Oops, something went wrong</div>
113
+ <button class="btn" on:click={attemptLoad}> Retry </button>
114
+ </div>
115
+ </slot>
116
+ {/if}
117
+
118
+ <div class="target" bind:this={intersectionTarget} />
119
+ </div>
120
+
121
+ <style>
122
+ .loader-wrapper {
123
+ display: grid;
124
+ width: 100%;
125
+ place-items: center;
126
+ margin-block: 2rem;
127
+
128
+ .loading {
129
+ margin-top: 1rem;
130
+ font-size: 1.5rem;
131
+ }
132
+
133
+ .no-results {
134
+ margin-top: 1rem;
135
+ font-size: 1.5rem;
136
+ }
137
+
138
+ .no-data {
139
+ margin-top: 1rem;
140
+ font-size: 1.5rem;
141
+ }
142
+
143
+ .error {
144
+ display: flex;
145
+ flex-direction: column;
146
+ gap: 1rem;
147
+ font-size: 1.5rem;
148
+ margin-block: 1rem;
149
+
150
+ .label {
151
+ color: firebrick;
152
+ }
153
+
154
+ .btn {
155
+ color: white;
156
+ background-color: #333;
157
+ padding-inline: 1.5rem;
158
+ padding-block: 0.75rem;
159
+ border-radius: 0.25rem;
160
+ border: none;
161
+ }
162
+ .btn:hover {
163
+ cursor: pointer;
164
+ }
165
+ }
166
+
167
+ .target {
168
+ height: 4rem;
169
+ }
170
+ }
171
+ </style>
@@ -0,0 +1,36 @@
1
+ import { SvelteComponent } from "svelte";
2
+ export declare const stateChanger: {
3
+ loaded: () => void;
4
+ complete: () => void;
5
+ reset: () => void;
6
+ error: () => void;
7
+ };
8
+ declare const __propDef: {
9
+ props: {
10
+ triggerLoad: () => Promise<void>;
11
+ loopTimeout?: number | undefined;
12
+ loopMaxCalls?: number | undefined;
13
+ } & {
14
+ children?: ((this: void) => typeof import("svelte").SnippetReturn & {
15
+ _: "functions passed to {@render ...} tags must use the `Snippet` type imported from \"svelte\"";
16
+ }) | undefined;
17
+ };
18
+ events: {
19
+ [evt: string]: CustomEvent<any>;
20
+ };
21
+ slots: {
22
+ default: {};
23
+ loading: {};
24
+ 'no-results': {};
25
+ 'no-data': {};
26
+ error: {
27
+ attemptLoad: () => Promise<void>;
28
+ };
29
+ };
30
+ };
31
+ type InfiniteLoaderProps_ = typeof __propDef.props;
32
+ export { InfiniteLoaderProps_ as InfiniteLoaderProps };
33
+ export type InfiniteLoaderEvents = typeof __propDef.events;
34
+ export type InfiniteLoaderSlots = typeof __propDef.slots;
35
+ export default class InfiniteLoader extends SvelteComponent<InfiniteLoaderProps_, InfiniteLoaderEvents, InfiniteLoaderSlots> {
36
+ }
@@ -0,0 +1,2 @@
1
+ import InfiniteLoader, { stateChanger } from './InfiniteLoader.svelte';
2
+ export { InfiniteLoader, stateChanger };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import InfiniteLoader, { stateChanger } from './InfiniteLoader.svelte';
2
+ export { InfiniteLoader, stateChanger };
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "svelte-infinite",
3
+ "description": "Infinite scroll for Svelte 5 with Runes",
4
+ "author": "ndom91 <yo@ndo.dev>",
5
+ "version": "0.1.0",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/ndom91/svelte-infinite",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ndom91/svelte-infinite.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ndom91/svelte-infinite/issues"
14
+ },
15
+ "scripts": {
16
+ "dev": "vite dev",
17
+ "build": "vite build && npm run package",
18
+ "preview": "vite preview",
19
+ "package": "svelte-kit sync && svelte-package && publint",
20
+ "prepublishOnly": "npm run package",
21
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
22
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
23
+ "test": "vitest",
24
+ "lint": "prettier --check . && eslint .",
25
+ "format": "prettier --write ."
26
+ },
27
+ "keywords": [
28
+ "infinite-loader",
29
+ "svelte",
30
+ "svelte5",
31
+ "sveltekit"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "svelte": "./dist/index.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "!dist/**/*.test.*",
42
+ "!dist/**/*.spec.*"
43
+ ],
44
+ "peerDependencies": {
45
+ "svelte": "^5.0.0"
46
+ },
47
+ "devDependencies": {
48
+ "@sveltejs/adapter-auto": "^3.0.0",
49
+ "@sveltejs/kit": "^2.0.0",
50
+ "@sveltejs/package": "^2.0.0",
51
+ "@sveltejs/vite-plugin-svelte": "^3.0.0",
52
+ "@types/eslint": "^8.56.0",
53
+ "@typescript-eslint/eslint-plugin": "^7.0.0",
54
+ "@typescript-eslint/parser": "^7.0.0",
55
+ "eslint": "^8.56.0",
56
+ "eslint-config-prettier": "^9.1.0",
57
+ "eslint-plugin-svelte": "^2.36.0-next.4",
58
+ "prettier": "^3.1.1",
59
+ "prettier-plugin-svelte": "^3.1.2",
60
+ "publint": "^0.1.9",
61
+ "svelte": "^5.0.0-beta.70",
62
+ "svelte-check": "^3.6.0",
63
+ "tslib": "^2.4.1",
64
+ "typescript": "^5.0.0",
65
+ "vite": "^5.0.11",
66
+ "vitest": "^1.2.0"
67
+ },
68
+ "svelte": "./dist/index.js",
69
+ "types": "./dist/index.d.ts",
70
+ "type": "module"
71
+ }