diff --git a/editor.planx.uk/src/hooks/useScrollOnPreviousURLMatch.ts b/editor.planx.uk/src/hooks/useScrollOnPreviousURLMatch.ts new file mode 100644 index 0000000000..c01391d67e --- /dev/null +++ b/editor.planx.uk/src/hooks/useScrollOnPreviousURLMatch.ts @@ -0,0 +1,41 @@ +import { useTheme } from "@mui/material/styles"; +import { useStore } from "pages/FlowEditor/lib/store"; +import { useEffect, useRef } from "react"; + +const useScrollOnPreviousURLMatch = ( + urlMatcher: string, +) => { + const previousURL = useStore((state) => state.previousURL); + const ref = useRef(null); + const theme = useTheme(); + + useEffect(() => { + if (!ref.current) return; + + const isReturningFromPortal = previousURL?.endsWith(urlMatcher); + if (!isReturningFromPortal) return; + + // Center node + ref.current.scrollIntoView({ + block: "center", + inline: "center", + }); + + // Visually highlight node + const keyframes: Keyframe[] = [ + { outline: `4px solid ${theme.palette.action.focus}`, outlineOffset: 0 }, + { outline: `4px solid transparent`, outlineOffset: 0 }, + ]; + + const animationOptions: KeyframeAnimationOptions = { + duration: 1500, + easing: "ease-in", + }; + + ref.current.animate(keyframes, animationOptions); + }, [previousURL, urlMatcher, theme]); + + return ref; +}; + +export default useScrollOnPreviousURLMatch; diff --git a/editor.planx.uk/src/pages/FlowEditor/components/Flow/components/Portal.tsx b/editor.planx.uk/src/pages/FlowEditor/components/Flow/components/Portal.tsx index f1d0a95f72..b750a47885 100644 --- a/editor.planx.uk/src/pages/FlowEditor/components/Flow/components/Portal.tsx +++ b/editor.planx.uk/src/pages/FlowEditor/components/Flow/components/Portal.tsx @@ -4,6 +4,7 @@ import { ComponentType } from "@opensystemslab/planx-core/types"; import { ICONS } from "@planx/components/shared/icons"; import classNames from "classnames"; import gql from "graphql-tag"; +import useScrollOnPreviousURLMatch from "hooks/useScrollOnPreviousURLMatch"; import { useStore } from "pages/FlowEditor/lib/store"; import React, { useState } from "react"; import { useDrag } from "react-dnd"; @@ -17,6 +18,8 @@ import Question from "./Question"; const ExternalPortal: React.FC = (props) => { const [href, setHref] = useState("Loading..."); + const ref = useScrollOnPreviousURLMatch(href); + const addExternalPortal = useStore.getState().addExternalPortal; const { data, loading } = useQuery( @@ -84,7 +87,7 @@ const ExternalPortal: React.FC = (props) => { return ( <>