xtreme-ui
Version:
Collection of reusable components that can be used in web projects
29 lines (28 loc) • 1.05 kB
JavaScript
"use client";
import { useState as h, useEffect as y } from "react";
const d = {
mobile: 640,
tablet: 1024
}, l = (n) => n.charAt(0).toUpperCase() + n.slice(1);
function g(n) {
const i = n ?? d, p = Object.keys(i), r = p.map((e) => [e, i[e]]).sort((e, s) => e[1] - s[1]), a = r.map(([e, s], t) => t === 0 ? { key: e, query: `(max-width: ${s - 1}px)` } : { key: e, query: `(min-width: ${r[t - 1][1]}px) and (max-width: ${s - 1}px)` }), u = r[r.length - 1][1], c = "largest";
a.push({ key: c, query: `(min-width: ${u}px)` });
const [o, m] = h(c);
return y(() => {
const e = a.map((t) => window.matchMedia(t.query)), s = () => {
for (let t = 0; t < e.length; t++)
if (e[t].matches) {
m(a[t].key);
break;
}
};
return s(), e.forEach((t) => t.addEventListener("change", s)), () => e.forEach((t) => t.removeEventListener("change", s));
}, [a]), {
screenType: o,
...Object.fromEntries(p.map((e) => [`is${l(e)}`, o === e])),
isLargest: o === c
};
}
export {
g as useScreenType
};