feat: produceAsync
This commit is contained in:
@@ -2,12 +2,39 @@ import {Signal, signal, SignalOptions} from '@preact/signals-core';
|
||||
import {create} from 'mutative';
|
||||
|
||||
export class MutableSignal<T> extends Signal<T> {
|
||||
private _interruptions: Promise<void>[] = [];
|
||||
|
||||
public constructor(t?: T, options?: SignalOptions<T>) {
|
||||
super(t, options);
|
||||
}
|
||||
produce(fn: (draft: T) => void) {
|
||||
this.value = create(this.value, fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个中断 Promise,`produceAsync` 会等待它完成后再更新状态。
|
||||
* 通常用于传入动画 Promise,让状态更新等待动画播放完毕。
|
||||
*/
|
||||
addInterruption(promise: Promise<void>): void {
|
||||
this._interruptions.push(promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有未完成的中断 Promise。
|
||||
*/
|
||||
clearInterruptions(): void {
|
||||
this._interruptions = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步版本的 produce。会先等待所有通过 `addInterruption` 添加的 Promise 完成,
|
||||
* 然后再更新状态。适用于需要在状态更新前播放动画的场景。
|
||||
*/
|
||||
async produceAsync(fn: (draft: T) => void): Promise<void> {
|
||||
await Promise.allSettled(this._interruptions);
|
||||
this._interruptions = [];
|
||||
this.produce(fn);
|
||||
}
|
||||
}
|
||||
|
||||
export function mutableSignal<T>(initial?: T, options?: SignalOptions<T>): MutableSignal<T> {
|
||||
|
||||
Reference in New Issue
Block a user