sveltekit-flash-message
Version:
Send temporary data to the next request after redirect. Works with both SSR and client.
47 lines (46 loc) • 1.78 kB
JavaScript
import { browser } from '$app/environment';
import { defaultOptions } from './options.js';
export class FlashMessage {
options;
_message;
get message() {
return this._message;
}
_flashTimeout = 0;
get flashTimeout() {
return this._flashTimeout;
}
constructor(message, options) {
this.options = options ?? defaultOptions;
this._message = {
subscribe: message.subscribe,
set: (value, options) => message.update(($message) => this.update($message, value, options?.concatenateArray ?? false)),
update: (updater, options) => message.update(($message) => this.update($message, updater($message), options?.concatenateArray ?? false))
};
}
update(current, newData, concatenateArray = false) {
if (this._flashTimeout)
clearTimeout(this.flashTimeout);
// Need to do a per-element comparison here, since update will be called
// when going to the same route, while keeping the old flash message,
// making it display multiple times.
if (concatenateArray && Array.isArray(newData)) {
if (Array.isArray(current)) {
if (current.length > 0 &&
newData.length > 0 &&
current[current.length - 1] === newData[newData.length - 1]) {
return current;
}
else {
return current.concat(newData);
}
}
}
if (browser && newData !== undefined && this.options.clearAfterMs) {
this._flashTimeout = setTimeout(() => {
this.message.set(undefined);
}, this.options.clearAfterMs);
}
return newData;
}
}