curran / d3-rosetta

Maximize framework interoperability for interactive graphics
MIT License
7 stars 0 forks source link

Observe Resize Utility #15

Closed curran closed 2 months ago

curran commented 2 months ago

Observing the dimensions of a container is such a common need. It would be great to provide a utility that does this well.

Prior work:

https://vizhub.com/curran/responsive-axes?edit=files&file=observeResize.js

export const observeResize = ({
  state,
  setState,
  container,
}) => {
  if (state.width === undefined) {
    // Set up a ResizeObserver on `container`
    const resizeObserver = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect;
      setState((state) => ({ ...state, width, height }));
    });
    resizeObserver.observe(container);
    return null;
  }
  return { width: state.width, height: state.height };
};

We may want to make the field custom, and leverage the StateProperty utility as well.

curran commented 2 months ago

idea:

export const main = (container, options) => {
  const stateProperty = StateProperty(options);
  const [dimensions, setDimensions] = stateProperty('dimensions');
  if(!dimensions){
    observeResize(container, { setDimensions });
    return;
  }
  const { width, height } = dimensions;
export const observeResize = (container, { setDimensions }) => {
  new ResizeObserver((entries) => {
    const { width, height } = entries[0].contentRect;
    setDimensions({ width, height });
  }).observe(container);
};
curran commented 2 months ago
  const dimensions = observeResize(container, options);
  if (!dimensions) return;
  const { width, height } = dimensions;
import { StateField } from 'd3-rosetta';
export const observeResize = (container, options) => {
  const [dimensions, setDimensions] =
    StateField(options)('dimensions');
  if (!dimensions) {
    const resizeObserver = new ResizeObserver((entries) => {
      setDimensions(entries[0].contentRect);
    });
    resizeObserver.observe(container);
  }
  return dimensions;
};