Skip to content

Commit

Permalink
wip: draggable progress indicator #2
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobsfletch committed Apr 1, 2022
1 parent df4843b commit d19e904
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion demo/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const App: React.FC = () => (
<h1>
Scroll Snap Slider:
</h1>
<ScrollSnapSliderDemo />
{/* <ScrollSnapSliderDemo /> */}
<h1>
Thumbnail Slider Demo:
</h1>
Expand Down
51 changes: 51 additions & 0 deletions src/SliderProgress/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, {
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { Props } from './types';
Expand Down Expand Up @@ -38,6 +40,8 @@ const SliderProgress: React.FC<Props> = (props) => {
const Tag = htmlElement as React.ElementType;
const IndicatorTag = indicatorHTMLElement as React.ElementType;

const indicatorRef = useRef(null);

useEffect(() => {
const newSegmentStyle = {
width: '',
Expand Down Expand Up @@ -70,6 +74,48 @@ const SliderProgress: React.FC<Props> = (props) => {
scrollOffset,
]);

const [state, setState] = useState({
prevClientX: 0,
isDragging: false,
});

const onMouseDown = useCallback((event) => {
const indicator = indicatorRef.current;
if (indicator) {
setState({
prevClientX: event.clientX,
isDragging: true,
});
}
}, []);

const onMouseMove = useCallback((event) => {
const {
prevClientX,
isDragging,
} = state;

if (isDragging) {
const sliderTrack = sliderTrackRef.current;
const xDistance = prevClientX + event.clientX;
const ratioDragged = xDistance / sliderTrack.scrollWidth;
console.log(ratioDragged);
const pixelsDragged = sliderTrack.scrollWidth * ratioDragged;
console.log(pixelsDragged);
sliderTrackRef.current.scrollLeft = sliderTrack.scrollLeft + (sliderTrack.scrollWidth * ratioDragged);
}
}, [
state,
sliderTrackRef,
]);

const clearState = useCallback(() => {
setState({
prevClientX: 0,
isDragging: false,
});
}, []);

return (
<Tag
id={id}
Expand All @@ -88,8 +134,13 @@ const SliderProgress: React.FC<Props> = (props) => {
>
<IndicatorTag
id={indicatorID}
ref={indicatorRef}
className={indicatorClassName}
{...indicatorHTMLAttributes}
onMouseMove={onMouseMove}
onMouseDown={onMouseDown}
onMouseUp={clearState}
onMouseLeave={clearState}
style={{
position: 'absolute',
top: 0,
Expand Down

0 comments on commit d19e904

Please sign in to comment.