UNPKG

platina-core

Version:

UI Kit of SberMarketing

28 lines (27 loc) 864 B
export function media({ queries, getter, cookie }) { const subscribers = new Set(); const matches = {}; if (typeof window === 'object') { for (const query in queries) { const media = window.matchMedia(queries[query]); set(media, query); media.onchange = (e) => set(e, query); } } function set(media, query) { matches[query] = media.matches; update(matches); getter && getter(matches); cookie && (document.cookie = `media=${JSON.stringify(matches)}`); } function update(matches) { subscribers.forEach((fn) => fn(matches)); } function subscribe(fn) { fn(matches); subscribers.add(fn); return () => unsubscribe(fn); } const unsubscribe = (fn) => subscribers.delete(fn); return { matches, subscribe }; }