UNPKG

@smkit/ui

Version:

UI Kit of SberMarketing

58 lines (57 loc) 1.61 kB
import { isBrowser } from '../utils'; import { nanoid } from 'nanoid'; import { getContext, setContext } from 'svelte'; import { writable } from 'svelte/store'; export class Modal { fullScreenStore; ctxKey; constructor(fullScreen, ctxKey) { this.fullScreenStore = writable(fullScreen); this.ctxKey = ctxKey ?? nanoid(10); setContext(this.ctxKey, this); } static get self() { const ctxKey = getContext('ctxKey'); if (!ctxKey) throw Error('ctxKey must be set inside component'); return getContext(ctxKey); } } export class HashPath { name; path; timeout; constructor(name) { this.name = name; this.path = `/${name}`; this.timeout = null; } isIn(url) { if (!isBrowser) return false; if (!url) url = new URL(window.location.href); return url.hash.includes(this.name); } update(show) { if (!isBrowser || show === undefined) return; const url = new URL(window.location.href); const active = this.isIn(url); if (show && !active) { url.hash += this.path; } else if (!show && active) { const index = url.hash.indexOf(this.path); url.hash = url.hash.slice(0, index); } else { return; } if (this.timeout) clearTimeout(this.timeout); this.timeout = setTimeout(() => { history.replaceState(null, '', url.hash.length > 0 ? url.hash : ' '); }, 100); } }