Skip to content

Commit 3c22ed9

Browse files
committed
feat(async-stack): implement StackItem.progress
1 parent 64e5b0f commit 3c22ed9

4 files changed

Lines changed: 27 additions & 3 deletions

File tree

.changeset/healthy-cows-matter.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@svelte-put/async-stack': minor
3+
---
4+
5+
expose `StackItem['progress']` as a number from 0 to 1, indicating how far until the timeout is reached, if any

packages/async-stack/src/stack-item.svelte.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ export class StackItem<
1919

2020
constructor(config: StackItemInstanceConfig<string, UserComponent>);
2121

22+
/**
23+
* progress of the timeout, from 0 to 1
24+
* or null if item has no timeout.
25+
* This property is not reactive!
26+
*/
27+
readonly progress: number | null;
2228
/** resume the stack item, if it has been paused */
2329
resume: () => void;
2430
/** pause the stack item, if it has a timeout */

packages/async-stack/src/stack-item.svelte.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,19 @@ export class StackItem {
3737
});
3838
}
3939

40+
/**
41+
* @returns {number | null}
42+
*/
43+
get progress() {
44+
if (this.config.timeout === 0) return null;
45+
if (this.state === 'elapsing') {
46+
const elapsedMs = Date.now() - this.#internals.lastStartedTime;
47+
const actualMsToTimeout = this.#internals.msToTimeout - elapsedMs;
48+
return (this.config.timeout - actualMsToTimeout) / this.config.timeout;
49+
}
50+
return (this.config.timeout - this.#internals.msToTimeout) / this.config.timeout;
51+
}
52+
4053
resume = () => {
4154
if (this.#internals.msToTimeout <= 0 || this.state === 'elapsing') return;
4255
clearTimeout(this.#internals.timeoutId);

packages/async-stack/src/stack.svelte.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,17 +124,17 @@ export class Stack {
124124
instanceConfig.id = idResolver(instanceConfig);
125125
}
126126

127-
// STEP 4: preparing the `StackItem` instance
127+
// STEP 3: preparing the `StackItem` instance
128128
/** @type {StackItem<any>} */
129129
let pushed = new StackItem(instanceConfig);
130130
pushed.resolution.then(() => {
131131
this.items = this.items.filter((n) => n.config.id !== pushed.config.id);
132132
});
133133

134-
// STEP 5: push to store
134+
// STEP 4: push to store
135135
this.items.push(pushed);
136136

137-
// STEP 6: start timer if any
137+
// STEP 5: start timer if any
138138
pushed.resume();
139139

140140
return pushed;

0 commit comments

Comments
 (0)