All files / src/UI/Canvas CanvasContext.tsx

71.13% Statements 69/97
35% Branches 7/20
47.62% Functions 10/21
76.56% Lines 49/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228                                7x 7x                 7x 7x                                                                   7x                   7x 11x 11x 11x 11x 11x 11x 11x   11x           11x 11x     11x             11x 11x 11x 14x   11x 62x     11x 5x 3x   3x 13x     5x 5x       11x       11x   11x             11x 11x 11x 11x                                       11x                                                           7x 138x 138x       138x   276x   138x   34x         138x   34x           138x                     7x            
/*
    Copyright (C) 2017 Red Hat, Inc.
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
 
            http://www.apache.org/licenses/LICENSE-2.0
 
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
import { Coords, RectWithId, Rects } from './models';
import { FunctionComponent, createContext, useContext } from 'react';
import React, {
  ReactElement,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
 
import { scaleLinear } from 'd3-scale';
import { useGesture } from 'react-use-gesture';
 
type RedrawCallback = () => unknown;
type RedrawCallbacks = Array<RedrawCallback>;
 
export interface ICanvasDimension {
  width: number;
  height: number;
  offsetTop: number;
  offsetLeft: number;
}
 
export interface ICanvasContext {
  initialWidth?: number;
  initialHeight?: number;
  dimensions: ICanvasDimension;
  setDimension: (dimension: ICanvasDimension) => void;
  panX: number;
  panY: number;
  addRedrawListener: (callback: RedrawCallback) => void;
  removeRedrawListener: (callback: RedrawCallback) => void;
  addRect: (rect: RectWithId) => void;
  removeRect: (id: string) => void;
  getRects: () => Rects;
  zoom: number;
  updateZoom: (tick: number) => void;
  resetZoom: () => void;
  pan: Coords;
  setPan: (pan: Coords) => void;
  resetPan: () => void;
  allowPanning: boolean;
  isPanning: boolean;
  bindCanvas: ReturnType<typeof useGesture>;
}
const CanvasContext = createContext<ICanvasContext | null>(null);
 
export interface ICanvasProviderProps {
  allowPanning?: boolean;
  initialWidth?: number;
  initialHeight?: number;
  initialZoom?: number;
  initialPanX?: number;
  initialPanY?: number;
}
export const CanvasProvider: FunctionComponent<ICanvasProviderProps> = ({
  children,
  allowPanning = false,
  initialWidth = 0,
  initialHeight = 0,
  initialZoom = 1,
  initialPanX = 0,
  initialPanY = 0,
}) => {
  const [canvasDimension, setCanvasDimension] = useState<ICanvasDimension>({
    width: 0,
    height: 0,
    offsetLeft: 0,
    offsetTop: 0,
  });
  const rects = useRef<Rects>([]);
  const removeRect = useCallback((id: string) => {
    rects.current = rects.current.filter((r) => r.id !== id);
  }, []);
  const addRect = useCallback(
    (rect: RectWithId) => {
      removeRect(rect.id);
      rects.current = [...rects.current, rect];
    },
    [removeRect],
  );
  const getRects = useCallback(() => rects.current, []);
  const redrawCallbacks = useRef<RedrawCallbacks>([]);
  const addRedrawListener = useCallback((cb: RedrawCallback) => {
    redrawCallbacks.current = [...redrawCallbacks.current, cb];
  }, []);
  const removeRedrawListener = useCallback((cb: RedrawCallback) => {
    redrawCallbacks.current = redrawCallbacks.current.filter((c) => c !== cb);
  }, []);
 
  useEffect(function effectLoop() {
    let frame = requestAnimationFrame(function loop() {
      frame = requestAnimationFrame(loop);
 
      for (let i = 0, len = redrawCallbacks.current.length; i < len; i++) {
        redrawCallbacks.current[i]();
      }
    });
    return function cancelEffectLoop() {
      cancelAnimationFrame(frame);
    };
  }, []);
 
  const [{ x: panX, y: panY }, setPan] = useState<Coords>({
    x: initialPanX,
    y: initialPanY,
  });
  const [zoom, setZoom] = useState(initialZoom);
 
  const updateZoom = useCallback(
    (tick: number) => {
      setZoom((currentZoom) => Math.max(0.2, Math.min(2, currentZoom + tick)));
    },
    [setZoom],
  );
 
  const resetZoom = useCallback(() => setZoom(1), [setZoom]);
  const resetPan = useCallback(() => setPan({ x: 0, y: 0 }), [setPan]);
  const [isPanning, setIsPanning] = useState(false);
  const bindCanvas = useGesture(
    {
      onDrag: ({ movement: [x, y], first, last, memo = [panX, panY] }) => {
        if (first) setIsPanning(true);
        if (last) setIsPanning(false);
        setPan({ x: x + memo[0], y: y + memo[1] });
        return memo;
      },
      onWheel: ({ delta }) => {
        updateZoom(delta[1] * -0.001);
      },
    },
    {
      drag: {
        delay: true,
      },
      enabled: allowPanning,
    },
  );
 
  return (
    <CanvasContext.Provider
      value={{
        initialWidth,
        initialHeight,
        dimensions: canvasDimension,
        setDimension: setCanvasDimension,
        panX,
        panY,
        addRedrawListener,
        removeRedrawListener,
        addRect,
        removeRect,
        getRects,
        zoom,
        updateZoom,
        resetZoom,
        pan: { x: panX, y: panY },
        setPan,
        resetPan,
        allowPanning,
        isPanning,
        bindCanvas,
      }}
    >
      {children}
    </CanvasContext.Provider>
  );
};
 
export function useCanvas() {
  const context = useContext(CanvasContext);
  Iif (!context) {
    throw new Error('A CanvasProvider wrapper is required to use this hook.');
  }
  const {
    dimensions: { width, height },
    zoom,
  } = context;
 
  const xDomain = useMemo(
    () =>
      scaleLinear()
        .range([0, width])
        .domain([0, width * zoom]),
    [width, zoom],
  );
  const yDomain = useMemo(
    () =>
      scaleLinear()
        .range([height, 0])
        .domain([height * zoom, 0]),
    [height, zoom],
  );
 
  return {
    ...context,
    xDomain,
    yDomain,
  };
}
 
export interface IWithCanvasProps {
  children: (props: ICanvasContext) => ReactElement;
}
 
export const WithCanvas: FunctionComponent<IWithCanvasProps> = ({
  children,
}) => {
  const context = useCanvas();
  return children(context);
};