Created
August 11, 2023 10:19
-
-
Save vnphanquang/3e523057c0f6005bdf1e3f11f3d65adc to your computer and use it in GitHub Desktop.
batching for snapshot feature in svelte-kit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
import { getContext, setContext } from 'svelte'; | |
type Snapshot<T = any> = { | |
capture: () => T; | |
restore: (value: T) => void; | |
}; | |
export function provideSnapshot() { | |
const snapshots: Record<string, Snapshot> = {}; | |
function snap<T>(key: string, snapshot: Snapshot<T>) { | |
snapshots[key] = snapshot; | |
} | |
setContext('snapshot', snap); | |
const registry = { | |
capture() { | |
return Object.entries(snapshots).reduce((acc, [key, snapshot]) => { | |
acc[key] = snapshot.capture(); | |
return acc; | |
}, {} as Record<string, any>); | |
}, | |
restore(value: Record<string, any>) { | |
Object.entries(snapshots).forEach(([key, snapshot]) => { | |
snapshot.restore(value[key]); | |
}); | |
}, | |
}; | |
return { registry, snap }; | |
} | |
export type SnapshotContext = ReturnType<typeof provideSnapshot>['snap']; | |
export function useSnapshot() { | |
return getContext<SnapshotContext>('snapshot'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment