import { useState , useLayoutEffect } from 'react' ; export const GRID_SIZE = 20 ; export interface Position { x : number ; y : number ; } export interface Dimension { width : number ; height : number ; } export const gridOffset = ( { x , y } , i ) => { return { x : x + i * ( GRID_SIZE * 2 ) , y : y + i * ( GRID_SIZE * 2 ) } ; } ; export const gridCellsToPixels = ( i ) : number => { return i * GRID_SIZE ; } ; export const snapToGrid = ( num ) => { const resto = num % GRID_SIZE ; if ( resto <= GRID_SIZE / 2 ) { return num - resto ; } return num + GRID_SIZE - resto ; } ; export const snapPositionToGrid = ( { x , y } ) : Position => ( { x : snapToGrid ( x ) , y : snapToGrid ( y ) } ) ; export const snapDimensionToGrid = ( { width , height } ) : Dimension => ( { width : width ? snapToGrid ( width ) + 1 : width , height : height ? snapToGrid ( height ) + 1 : height } ) ; /**
 * measure the distance from a start point over time
 */ export function useDistance ( ) { const [ measuring , setMeasuring ] = useState < boolean > ( false ) ; const [ start , setStart ] = useState < Position > ( { x : 0 , y : 0 } ) ; const [ current , setCurrent ] = useState < Position > ( { x : 0 , y : 0 } ) ; const startMeasure = ( position ) => { setMeasuring ( true ) ; setStart ( position ) ; setCurrent ( position ) ; } ; const endMeasure = ( ) => { setMeasuring ( false ) ; setStart ( current ) ; } ; const [ distance , setDistance ] = useState < Position > ( { x : 0 , y : 0 } ) ; useLayoutEffect ( ( ) => { setDistance ( { x : current . x - start . x , y : current . y - start . y } ) ; } , [ start , current ] ) ; return { measuring , distance , startMeasure , setCurrent , endMeasure } ; }