useViewbox

PHOTO EMBED

Wed Sep 15 2021 07:22:26 GMT+0000 (Coordinated Universal Time)

Saved by @cxgarcia #typescript

export interface IViewBoxProps {
  x: number;
  y: number;
  zoom: number;
  width: number;
  height: number;
  activeNodeId?: string;
}

type TViewBoxReturn = [
  { viewBox: string; viewBoxProps: IViewBoxProps },
  (arg0: Partial<IViewBoxProps>) => void
];

export default function useViewBox(
  defaultState: IViewBoxProps
): TViewBoxReturn {
  const [viewBoxProps, _configsDispatch] = useLocalStorage(
    "_viewboxConfigs",
    defaultState
  );

  const viewBox = getViewBox(viewBoxProps);
  const updateViewBox = _updateStorage(_configsDispatch);

  return [{ viewBox, viewBoxProps }, updateViewBox];
}

function getViewBox(viewBoxProps: IViewBoxProps) {
  const { x, y, width, height, zoom } = viewBoxProps;

  const xyOffset = 2 ** -zoom;
  const _x = x - (width / 2) * xyOffset;
  const _y = y - (height / 2) * xyOffset;

  const whOffset = 2 ** zoom;
  const _w = width / whOffset;
  const _h = height / whOffset;

  return [_x, _y, _w, _h].join(" ");
}
content_copyCOPY