UNPKG

@dschz/solid-auto-sizer

Version:

SolidJS component that automatically measures and provides the width and height of its parent — useful for virtualized lists, grids, and charts.

68 lines (65 loc) 1.85 kB
import { template, use, insert, effect, className, style } from 'solid-js/web'; import { mergeProps, createSignal, onMount, onCleanup } from 'solid-js'; // src/AutoSizer.tsx var _tmpl$ = /* @__PURE__ */ template(`<div>`); var AutoSizer = (props) => { let container; const _props = mergeProps({ initialWidth: 0, initialHeight: 0 }, props); const [size, setSize] = createSignal({ width: _props.initialWidth, height: _props.initialHeight }); onMount(() => { const containerRect = container.getBoundingClientRect(); const containerSize = { width: Math.floor(containerRect.width), height: Math.floor(containerRect.height) }; if (containerSize.width !== size().width || containerSize.height !== size().height) { setSize(containerSize); _props.onResize?.(containerSize); } const resizeObserver = new ResizeObserver((entries) => { const entry = entries[0]; if (!entry) return; const { width, height } = entry.contentRect; const newSize = { width: Math.floor(width), height: Math.floor(height) }; setSize(newSize); _props.onResize?.(newSize); }); resizeObserver.observe(container); onCleanup(() => { resizeObserver.disconnect(); }); }); return (() => { var _el$ = _tmpl$(); var _ref$ = container; typeof _ref$ === "function" ? use(_ref$, _el$) : container = _el$; insert(_el$, () => _props.children(size())); effect((_p$) => { var _v$ = _props.class, _v$2 = { width: "100%", height: "100%", ..._props.style }; _v$ !== _p$.e && className(_el$, _p$.e = _v$); _p$.t = style(_el$, _v$2, _p$.t); return _p$; }, { e: void 0, t: void 0 }); return _el$; })(); }; export { AutoSizer };