This repository has been archived on 2023-10-27. You can view files and clone it, but cannot push or open issues or pull requests.
Files
scoresaber-reloaded/src/stores/container.js

61 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-10-17 23:38:18 +01:00
import { writable } from "svelte/store";
2023-10-17 21:42:37 +01:00
2023-10-17 23:38:18 +01:00
export default (
2023-10-17 23:41:42 +01:00
sizes = { phone: 0, tablet: 768, desktop: 1024, xxl: 1749 }
2023-10-17 23:38:18 +01:00
) => {
const defaultValue = { name: null, width: null, nodeWidth: null, rect: null };
const { subscribe, unsubscribe, set } = writable(defaultValue);
2023-10-17 21:42:37 +01:00
let ro = null;
let node = null;
const unobserve = () => {
if (!node) return;
2023-10-17 23:38:18 +01:00
ro.unobserve(node);
2023-10-17 21:42:37 +01:00
node = null;
2023-10-17 23:38:18 +01:00
};
2023-10-17 21:42:37 +01:00
2023-10-17 23:38:18 +01:00
const observe = (nodeToObserve) => {
2023-10-17 21:42:37 +01:00
if (!nodeToObserve) return null;
if (node) unobserve();
node = nodeToObserve;
let lastWidth = null;
ro = new ResizeObserver(() => {
const rect = node.getBoundingClientRect();
const nodeWidth = rect.width;
if (lastWidth === nodeWidth) return;
lastWidth = nodeWidth;
set(
Object.entries(sizes)
.sort((a, b) => a[1] - b[1])
2023-10-17 23:38:18 +01:00
.reduce(
(cum, item) =>
item[1] <= nodeWidth
? { name: item[0], width: item[1], nodeWidth, rect }
: cum,
2023-10-17 23:41:42 +01:00
defaultValue
)
2023-10-17 23:38:18 +01:00
);
2023-10-17 21:42:37 +01:00
});
2023-10-17 23:38:18 +01:00
ro.observe(node);
2023-10-17 21:42:37 +01:00
return node;
2023-10-17 23:38:18 +01:00
};
2023-10-17 21:42:37 +01:00
return {
subscribe,
unsubscribe,
observe,
unobserve,
2023-10-17 23:38:18 +01:00
};
2023-10-17 21:42:37 +01:00
};