Skip to content

Instantly share code, notes, and snippets.

@vnphanquang
Created August 11, 2023 10:19
Show Gist options
  • Save vnphanquang/3e523057c0f6005bdf1e3f11f3d65adc to your computer and use it in GitHub Desktop.
Save vnphanquang/3e523057c0f6005bdf1e3f11f3d65adc to your computer and use it in GitHub Desktop.
batching for snapshot feature in svelte-kit
/* 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