Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #476 Smooth scrolling to new target's location #477

Merged
merged 5 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@
"react-aria": "^3.9.0",
"react-device-detect": "^1.17.0",
"react-portal": "^4.2.2",
"react-virtuoso": "^1.10.5",
"src": "^1.1.2"
"react-virtuoso": "^1.10.5"
},
"peerDependencies": {
"@react-spring/web": "^9.2.4",
Expand Down Expand Up @@ -220,5 +219,9 @@
"last 1 safari version"
]
},
"gitHead": "1310c14f2882b9431200c5968097d8df9e92878e"
"gitHead": "1310c14f2882b9431200c5968097d8df9e92878e",
"volta": {
"node": "18.18.0",
"yarn": "3.6.3"
}
}
24 changes: 23 additions & 1 deletion src/components/Spotlight/Spotlight.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ const Header = styled(Card.NoPaddingHeader)`
display: flex;
justify-content: flex-end;
`;
const Container = styled(Card.Container)`
max-width: 35rem;
margin-top: 10rem;
`;

const Annotation = styled(Spotlight.Annotation)`
display: flex;
Expand Down Expand Up @@ -57,6 +61,7 @@ export const AnimatedSpotlight: Story = (args: Partial<SpotlightProps>) => {
<>
<Card
StyledHeader={Header}
StyledContainer={Container}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - our ref types don't like getting a set state dispatch function
containerRef={setCardRef}
Expand Down Expand Up @@ -84,7 +89,24 @@ export const AnimatedSpotlight: Story = (args: Partial<SpotlightProps>) => {
</Button>
}
>
There are a few items in this card we can talk about!
<p>There are a few items in this card we can talk about!</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ultricies mi eget mauris pharetra et ultrices neque
ornare aenean. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra.
Ullamcorper dignissim cras tincidunt lobortis feugiat vivamus at. Mauris a diam maecenas
sed enim ut sem viverra aliquet. Ultrices in iaculis nunc sed augue lacus viverra. Sodales
neque sodales ut etiam. Pulvinar neque laoreet suspendisse interdum consectetur libero id
faucibus nisl. Ut placerat orci nulla pellentesque dignissim enim sit amet venenatis.
Vivamus arcu felis bibendum ut tristique. Netus et malesuada fames ac turpis egestas.
Porttitor rhoncus dolor purus non enim. Proin nibh nisl condimentum id. Aliquam ultrices
sagittis orci a scelerisque purus semper. Faucibus purus in massa tempor nec feugiat. Et
netus et malesuada fames. Cras pulvinar mattis nunc sed blandit libero. Nisi lacus sed
viverra tellus in. Tellus rutrum tellus pellentesque eu tincidunt tortor aliquam nulla. Id
porta nibh venenatis cras sed felis eget velit. Eros in cursus turpis massa tincidunt dui
ut ornare. Proin fermentum leo vel orci porta non. Quisque non tellus orci ac auctor
augue.
</p>
</Card>
{tourStarted && (
<Spotlight {...args} StyledAnnotation={Annotation} targetElement={stepOptions[currStep]}>
Expand Down
91 changes: 77 additions & 14 deletions src/components/Spotlight/Spotlight.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import React, { useEffect, useMemo } from 'react';
import React, {
MouseEvent,
ReactNode,
RefObject,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import styled from 'styled-components';
import { animated, useSpring } from '@react-spring/web';
import { Portal } from 'react-portal';

import { mergeRefs } from '../../utils/refs';
import { SubcomponentPropsType, StyledSubcomponentType } from '../commonTypes';
import { useScrollObserver, useWindowSizeObserver } from '../../utils/hooks';
import { useTheme, useAnalytics } from '../../context';
Expand Down Expand Up @@ -48,20 +57,20 @@ export enum SpotlightShapes {
export type SpotlightProps = {
StyledContainer?: StyledSubcomponentType;
containerProps?: SubcomponentPropsType;
containerRef?: React.RefObject<HTMLElement>;
containerRef?: RefObject<HTMLElement>;

StyledAnnotation?: StyledSubcomponentType;
annotationProps?: SubcomponentPropsType;
annotationRef?: React.RefObject<HTMLElement>;
annotationRef?: RefObject<HTMLElement>;

children?: React.ReactNode;
targetElement?: HTMLElement;
children?: ReactNode;
targetElement?: HTMLElement | Element;
backgroundBlur?: string;
backgroundDarkness?: number;
shape?: SpotlightShapes;
cornerRadius?: number;
padding?: number;
onClick?: (e: React.MouseEvent) => void;
onClick?: (e: MouseEvent) => void;
animateTargetChanges?: boolean;
// onAnimationEnd?: ControllerProps['onRest'];
onAnimationEnd?: () => void;
Expand Down Expand Up @@ -105,7 +114,44 @@ const Spotlight = ({
accessibilityPreferences: { prefersReducedMotion },
} = useTheme();

const rect = useMemo<Pick<DOMRect, 'x' | 'y' | 'width' | 'height' | 'bottom' | 'right'>>(() => {
const internalAnnotationRef: RefObject<HTMLElement> = useRef();

/* Scroll to new position if need-be */

const [isAutoScrolling, setIsAutoScrolling] = useState(false);

useEffect(() => {
if (targetElement) {
const newTargetTop = targetElement?.getBoundingClientRect().top ?? 0;
const annotationHeight = internalAnnotationRef?.current?.getBoundingClientRect().height;
// TODO: This assumes the annotation is above the target
// when custom above/under alignment is implemented, this logic should change
// (if the annotation is below the target, this should be an addition, not subtraction)
const offset = newTargetTop - annotationHeight;

window.scrollBy({
top: offset,
left: 0,
behavior: !animateTargetChanges || prefersReducedMotion ? 'auto' : 'smooth',
});

setIsAutoScrolling(true);
}
}, [animateTargetChanges, internalAnnotationRef, prefersReducedMotion, targetElement]);

useEffect(() => {
// check if auto scroll has completed
if (isScrolling === false && isAutoScrolling === true) {
setIsAutoScrolling(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isScrolling]);

/* Build spotlight shape */

const rect: DOMRect = useMemo<
Pick<DOMRect, 'x' | 'y' | 'width' | 'height' | 'bottom' | 'right'>
>(() => {
const defaultVal = {
x: windowWidth / 2,
y: windowHeight / 2,
Expand Down Expand Up @@ -174,6 +220,8 @@ const Spotlight = ({
`;
const finalRectangularPath = `${outerRectPath} ${innerShapePath}`;

/* Setup animation */

const [
{
containerFilter,
Expand Down Expand Up @@ -218,10 +266,14 @@ const Spotlight = ({
leftBlurHeight: rect.height + 2,

rightBlurY: rect.y,
rightBlurWidth: windowWidth - rect.right,
rightBlurWidth: windowWidth - rect.right - padding - 4,
rightBlurHeight: rect.height + 2,
immediate:
!animateTargetChanges ||
prefersReducedMotion ||
(isScrolling && !isAutoScrolling) ||
isResizing,
config: {
immediate: !animateTargetChanges || prefersReducedMotion || isScrolling || isResizing,
round: gpuTier < 2 ? 1 : undefined,
...animationSpringConfig,
},
Expand All @@ -237,10 +289,10 @@ const Spotlight = ({
lightPath: finalRectangularPath,
circularLightPath: circularPath,

annotationTransform: `translate(${rect.x}px, ${rect.y}px) translate(0%, -100%)`,
annotationTransform: `translate(${rect.x}px, ${rect.y}px) translate(0%, -100%)`, // TODO: change second translate to make different attach positions

aVileBroker marked this conversation as resolved.
Show resolved Hide resolved
topBlurWidth: windowWidth,
topBlurHeight: rect.y - 1,
topBlurHeight: Math.max(rect.y - 1, 0),

bottomBlurY: rect.bottom,
bottomBlurWidth: windowWidth,
Expand All @@ -251,10 +303,15 @@ const Spotlight = ({
leftBlurHeight: rect.height + 2,

rightBlurY: rect.y,
rightBlurWidth: windowWidth - rect.right,
rightBlurWidth: windowWidth - rect.right - padding - 4,
rightBlurHeight: rect.height + 2,

onRest: onAnimationEnd,
immediate:
!animateTargetChanges ||
prefersReducedMotion ||
(isScrolling && !isAutoScrolling) ||
isResizing,
}));
}, [
targetElement,
Expand All @@ -266,6 +323,8 @@ const Spotlight = ({
windowWidth,
windowHeight,
isScrolling,
scrollY,
isAutoScrolling,
isResizing,
spring,
finalRectangularPath,
Expand All @@ -278,9 +337,13 @@ const Spotlight = ({
animateTargetChanges,
onAnimationEnd,
gpuTier,
prefersReducedMotion,
]);

const handleClick = (evt: React.MouseEvent) => {
/* Click */

const handleClick = (evt: MouseEvent) => {
// TODO: Rename to onClickOutside?
handleEventWithAnalytics('Spotlight', onClick, 'onClick', evt, containerProps);
};

Expand Down Expand Up @@ -348,7 +411,7 @@ const Spotlight = ({
</svg>
<StyledAnnotation
style={{ transform: annotationTransform }}
ref={annotationRef}
ref={mergeRefs<HTMLElement>([annotationRef, internalAnnotationRef])}
{...annotationProps}
>
{children}
Expand Down
Loading
Loading