@sv-use/core
Version:
A collection of Svelte 5 utilities.
36 lines (35 loc) • 1.29 kB
JavaScript
import { onDestroy } from 'svelte';
import { handleEventListener } from '../handle-event-listener/index.svelte.js';
import { noop } from '../__internal__/utils.svelte.js';
import { isSupported } from '../__internal__/is.svelte.js';
/**
* Returns the ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device.
* @see https://svelte-librarian.github.io/sv-use/docs/core/get-device-pixel-ratio
*/
export function getDevicePixelRatio(options = {}) {
const { autoCleanup = true } = options;
let cleanup = noop;
const _isSupported = isSupported(() => window && 'devicePixelRatio' in window);
let _current = $state(1);
if (_isSupported.current) {
updatePixelRatio();
}
if (autoCleanup) {
onDestroy(() => cleanup());
}
function updatePixelRatio() {
_current = window.devicePixelRatio;
cleanup();
const media = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
cleanup = handleEventListener(media, 'change', updatePixelRatio, { autoCleanup, once: true });
}
return {
get isSupported() {
return _isSupported.current;
},
get current() {
return _current;
},
cleanup
};
}