import React, { useContext, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { xarrowPropsType } from '../types'; import useXarrowProps from './useXarrowProps'; import { XarrowContext } from '../Xwrapper'; import { getPosition } from './utils/GetPosition'; import { getTotalLength } from './utils'; const log = console.log; const Xarrow: React.FC = (props: xarrowPropsType) => { // log('xarrow update'); const mainRef = useRef({ svgRef: useRef(null), lineRef: useRef(null), headRef: useRef(null), tailRef: useRef(null), lineDrawAnimRef: useRef(null), lineDashAnimRef: useRef(null), headOpacityAnimRef: useRef(null), }); const { svgRef, lineRef, headRef, tailRef, lineDrawAnimRef, lineDashAnimRef, headOpacityAnimRef } = mainRef.current; useContext(XarrowContext); const xProps = useXarrowProps(props, mainRef.current); const [propsRefs] = xProps; const { labels, lineColor, headColor, tailColor, strokeWidth, showHead, showTail, dashness, headShape, tailShape, showXarrow, zIndex, passProps, arrowBodyProps, arrowHeadProps, arrowTailProps, SVGcanvasProps, divContainerProps, divContainerStyle, SVGcanvasStyle, _debug, shouldUpdatePosition, } = propsRefs; // read straight off props rather than the parsed refs - this one is reassigned below let animateDrawing = props.animateDrawing as number; const [drawAnimEnded, setDrawAnimEnded] = useState(!animateDrawing); const [, setRender] = useState({}); const forceRerender = () => setRender({}); // Typed from what getPosition returns rather than inferred from the literal // below, which would make the two empty arrays never[]. const [st, setSt] = useState>({ //initial state cx0: 0, //x start position of the canvas cy0: 0, //y start position of the canvas cw: 0, // the canvas width ch: 0, // the canvas height x1: 0, //the x starting point of the line inside the canvas y1: 0, //the y starting point of the line inside the canvas x2: 0, //the x ending point of the line inside the canvas y2: 0, //the y ending point of the line inside the canvas dx: 0, // the x difference between 'start' anchor to 'end' anchor dy: 0, // the y difference between 'start' anchor to 'end' anchor absDx: 0, // the x length(positive) difference absDy: 0, // the y length(positive) difference cpx1: 0, // control points - control the curviness of the line cpy1: 0, cpx2: 0, cpy2: 0, headOrient: 0, // determines to what side the arrowhead will point tailOrient: 0, // determines to what side the arrow tail will point arrowHeadOffset: { x: 0, y: 0 }, arrowTailOffset: { x: 0, y: 0 }, headOffset: 0, excRight: 0, //expand canvas to the right excLeft: 0, //expand canvas to the left excUp: 0, //expand canvas upwards excDown: 0, // expand canvas downward startPoints: [], endPoints: [], mainDivPos: { x: 0, y: 0 }, xSign: 1, ySign: 1, lineLength: 0, fHeadSize: 1, fTailSize: 1, arrowPath: ``, labelStartPos: { x: 0, y: 0 }, labelMiddlePos: { x: 0, y: 0 }, labelEndPos: { x: 0, y: 0 }, }); /** * The Main logic of path calculation for the arrow. * calculate new path, adjusting canvas, and set state based on given properties. * */ useLayoutEffect(() => { if (shouldUpdatePosition.current) { // log('xarrow getPosition'); const pos = getPosition(xProps, mainRef); // log('pos', pos); setSt(pos); shouldUpdatePosition.current = false; } }); // log('st', st); const xOffsetHead = st.x2 - st.arrowHeadOffset.x; const yOffsetHead = st.y2 - st.arrowHeadOffset.y; const xOffsetTail = st.x1 - st.arrowTailOffset.x; const yOffsetTail = st.y1 - st.arrowTailOffset.y; const dashoffset = dashness.strokeLen + dashness.nonStrokeLen; let animDirection = 1; if (dashness.animation < 0) { dashness.animation *= -1; animDirection = -1; } let dashArray, animation, animRepeatCount, animStartValue, animEndValue = 0; if (animateDrawing && drawAnimEnded == false) { if (typeof animateDrawing === 'boolean') animateDrawing = 1; animation = animateDrawing + 's'; dashArray = st.lineLength; animStartValue = st.lineLength; animRepeatCount = 1; if (animateDrawing < 0) { [animStartValue, animEndValue] = [animEndValue, animStartValue]; animation = animateDrawing * -1 + 's'; } } else { dashArray = `${dashness.strokeLen} ${dashness.nonStrokeLen}`; animation = `${1 / dashness.animation}s`; animStartValue = dashoffset * animDirection; animRepeatCount = 'indefinite'; animEndValue = 0; } // handle draw animation useLayoutEffect(() => { if (lineRef.current) setSt((prevSt) => ({ ...prevSt, lineLength: getTotalLength(lineRef.current) })); }, [lineRef.current]); // set all props on first render useEffect(() => { const monitorDOMchanges = () => { window.addEventListener('resize', forceRerender); const handleDrawAmimEnd = () => { setDrawAnimEnded(true); // @ts-ignore headOpacityAnimRef.current?.beginElement(); // @ts-ignore lineDashAnimRef.current?.beginElement(); }; // Deliberately does not depend on the arrowhead. This listener is what // ends the draw phase, and gating it on headRef left `drawAnimEnded` // false forever whenever showHead was false, so the arrow stayed stuck // mid-draw. The head is hidden through the rendered `opacity` attribute // instead, which React can actually reconcile. if (lineDrawAnimRef.current) { lineDrawAnimRef.current.addEventListener('endEvent', handleDrawAmimEnd); } return () => { window.removeEventListener('resize', forceRerender); if (lineDrawAnimRef.current) { lineDrawAnimRef.current.removeEventListener('endEvent', handleDrawAmimEnd); } }; }; const cleanMonitorDOMchanges = monitorDOMchanges(); return () => { setDrawAnimEnded(false); cleanMonitorDOMchanges(); }; }, [showXarrow]); //todo: could make some advanced generic typescript inferring. for example get type from headShape.elem:T and // tailShape.elem:K force the type for passProps,arrowHeadProps,arrowTailProps property. for now `as any` is used to // avoid typescript conflicts // so todo- fix all the `passProps as any` assertions return (
{showXarrow ? ( <> {/* body of the arrow */} <> {drawAnimEnded || !animateDrawing ? ( <> {/* moving dashed line animation */} {dashness.animation ? ( ) : null} ) : ( <> {/* the creation of the line animation */} {animateDrawing ? ( ) : null} )} {/* arrow tail */} {showTail ? ( {tailShape.svgElem} ) : null} {/* head of the arrow */} {showHead ? ( {/* No repeatCount: SMIL rejects 0 and logs "Unexpected value 0 parsing repeatCount attribute", and the default of a single run is what this fade-in wants anyway. */} {headShape.svgElem} ) : null} {/* debug elements */} {_debug ? ( <> {/* control points circles */} {/* start to end rectangle wrapper */} ) : null} {labels.start ? (
{labels.start}
) : null} {labels.middle ? (
{labels.middle}
) : null} {labels.end ? (
0 ? 'translate(-100% , -50%)' : 'translate(-0% , -50%)', width: 'max-content', position: 'absolute', left: st.cx0 + st.labelEndPos.x, top: st.cy0 + st.labelEndPos.y + strokeWidth + 5, }}> {labels.end}
) : null} {_debug ? ( <> {/* possible anchor connections */} {[...st.startPoints, ...st.endPoints].map((p, i) => { return (
); })} ) : null} ) : null}
); }; export default Xarrow;