UNPKG

sveltekit-flash-message

Version:

Send temporary data to the next request after redirect. Works with both SSR and client.

48 lines (47 loc) 1.67 kB
/* eslint-disable @typescript-eslint/no-non-null-assertion */ import { writable } from 'svelte/store'; import { FlashMessage } from './flashMessage.js'; import { mergeOptions } from './options.js'; import { onDestroy } from 'svelte'; export class FlashRouter { routes = new Map(); messageStore; constructor() { this.messageStore = writable(); this.routes.set('', new FlashMessage(this.messageStore)); onDestroy(() => { for (const route of this.routes.values()) { clearTimeout(route.flashTimeout); } }); } get defaultRoute() { return this.routes.get(''); } has(routeId) { return this.routes.has(routeId); } getFlashMessage(routeId) { if (!routeId) return this.defaultRoute; if (this.routes.has(routeId)) return this.routes.get(routeId); return this.getClosestRoute(routeId); } getClosestRoute(routeId) { const matchingRoutes = Array.from(this.routes.keys()).filter((key) => routeId.includes(key)); if (!matchingRoutes.length) { return this.defaultRoute; } const longestRoute = matchingRoutes.reduce((prev, curr) => curr.length > prev.length ? curr : prev); return this.routes.get(longestRoute); } createRoute(routeId, data, options) { const closest = this.getClosestRoute(routeId); const newRoute = new FlashMessage(this.messageStore, mergeOptions(closest.options, options)); // Update flash data newRoute.message.set(data); this.routes.set(routeId, newRoute); return newRoute; } }