mytril
Version:
Mytril Svelte library component for rapidly building modern websites based on Svelte and Sveltekit
46 lines (45 loc) • 1.5 kB
JavaScript
import { displayOnLaptop, displayOnMobile, displayOnTablet } from '../stores/screen.js';
import { innerWidth } from 'svelte/reactivity/window';
export function hasDisplayScreen() {
// state
let width = $state(0);
$effect(() => {
width = innerWidth.current;
});
function convertToPixels(size) {
if (typeof size === 'number') {
return size;
}
const match = size.match(/^(\d+(?:\.\d+)?)(px|rem|em|pt)$/);
if (!match) {
throw new Error(`Value not supported : ${size}`);
}
const value = parseFloat(match[1]);
const unit = match[2];
let pixels;
switch (unit) {
case 'px':
pixels = value;
break;
case 'rem':
pixels = value * 16; // 1rem = 16px default
break;
case 'em':
pixels = value * 16; // 1em = 16px default
break;
case 'pt':
pixels = value * 1.333; // 1pt = 1.333px
break;
default:
throw new Error(`has not support : ${unit}`);
}
return pixels;
}
return {
display({ mobile, tablet, laptop }) {
displayOnMobile.set(width < convertToPixels(mobile));
displayOnTablet.set(width > convertToPixels(mobile) && width < convertToPixels(tablet));
displayOnLaptop.set(width > convertToPixels(laptop));
}
};
}