Skip to content

Commit

Permalink
WIP refactor 1
Browse files Browse the repository at this point in the history
  • Loading branch information
mj12albert committed May 31, 2024
1 parent 29a9fbe commit 4da80a7
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 45 deletions.
4 changes: 2 additions & 2 deletions docs/pages/base-ui/api/use-slider.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@
"dragging": { "type": { "name": "boolean", "description": "boolean" }, "required": true },
"getFingerNewValue": {
"type": {
"name": "(args: { finger: { x: number; y: number }; move?: boolean; offset?: number; boundary?: Partial<DOMRect> }) => { newValue: number | number[]; activeIndex: number; newPercentageValue: number }",
"description": "(args: { finger: { x: number; y: number }; move?: boolean; offset?: number; boundary?: Partial<DOMRect> }) => { newValue: number | number[]; activeIndex: number; newPercentageValue: number }"
"name": "(args: { finger: { x: number; y: number }; offset?: number; boundary?: Partial<DOMRect>; activeIndex?: number }) => { newValue: number | number[]; activeIndex: number; newPercentageValue: number }",
"description": "(args: { finger: { x: number; y: number }; offset?: number; boundary?: Partial<DOMRect>; activeIndex?: number }) => { newValue: number | number[]; activeIndex: number; newPercentageValue: number }"
},
"required": true
},
Expand Down
12 changes: 7 additions & 5 deletions docs/pages/experiments/slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ export function TrackFill(props: any) {

const { axis, disabled, isRtl, orientation, percentageValues } = useSliderContext();

const isRange = percentageValues.length > 1;
const values = percentageValues.slice().sort((a, b) => a - b);

const isRange = values.length > 1;

let internalStyles;

if (isRange) {
const trackOffset = percentageValues[0];
const trackLeap = percentageValues[percentageValues.length - 1] - trackOffset;
const trackOffset = values[0];
const trackLeap = values[values.length - 1] - trackOffset;

internalStyles = {
...axisProps[axis].offset(trackOffset),
Expand All @@ -39,11 +41,11 @@ export function TrackFill(props: any) {
} else if (orientation === 'vertical') {
internalStyles = {
[inverted ? 'top' : 'bottom']: 0,
height: `${inverted ? 100 - percentageValues[0] : percentageValues[0]}%`,
height: `${inverted ? 100 - values[0] : values[0]}%`,
};
} else {
internalStyles = {
width: `${inverted ? 100 - percentageValues[0] : percentageValues[0]}%`,
width: `${inverted ? 100 - values[0] : values[0]}%`,
[(isRtl || inverted) && isRtl !== inverted ? 'right' : 'left']: 0,
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/mui-base/src/Slider/Root/SliderRoot.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,9 @@ export interface UseSliderReturnValue {
disabled: boolean;
getFingerNewValue: (args: {
finger: { x: number; y: number };
move?: boolean;
offset?: number;
boundary?: Partial<DOMRect>;
activeIndex?: number;
}) => { newValue: number | number[]; activeIndex: number; newPercentageValue: number };
handleValueChange: (
value: number | number[],
Expand Down
79 changes: 50 additions & 29 deletions packages/mui-base/src/Slider/Root/useSliderRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import {
UseSliderReturnValue,
} from './SliderRoot.types';

function asc(a: number, b: number) {
return a - b;
}
// function asc(a: number, b: number) {
// return a - b;
// }

function findClosest(values: number[], currentValue: number) {
function findClosest(values: readonly number[], currentValue: number) {
const { index: closestIndex } =
values.reduce<{ distance: number; index: number } | null>(
(acc, value: number, index: number) => {
Expand Down Expand Up @@ -50,6 +50,7 @@ export function focusThumb({
setActive?: (num: number) => void;
}) {
const doc = ownerDocument(sliderRef.current);
// console.log('focusThumb activeIndex', activeIndex);
if (
!sliderRef.current?.contains(doc.activeElement) ||
Number(doc?.activeElement?.getAttribute('data-index')) !== activeIndex
Expand All @@ -71,9 +72,11 @@ function setValueIndex({
newValue: number;
index: number;
}) {
// console.log('setValueIndex activeIndex', index);
const output = values.slice();
output[index] = newValue;
return output.sort(asc);
return output;
// return output.sort(asc);
}

export function trackFinger(
Expand Down Expand Up @@ -177,7 +180,7 @@ function useSliderRoot(parameters: UseSliderParameters): UseSliderReturnValue {
const range = Array.isArray(valueState);

const values = React.useMemo(() => {
return (range ? valueState.slice().sort(asc) : [valueState]).map((val) =>
return (range ? valueState.slice() /* .sort(asc) */ : [valueState]).map((val) =>
val == null ? min : clamp(val, min, max),
);
}, [max, min, range, valueState]);
Expand Down Expand Up @@ -236,21 +239,21 @@ function useSliderRoot(parameters: UseSliderParameters): UseSliderReturnValue {
newValue = clamp(newValue, values[index - 1] || -Infinity, values[index + 1] || Infinity);
}

const previousValue = newValue;
// const previousValue = newValue;
newValue = setValueIndex({
values,
newValue,
index,
});

let activeIndex = index;
/* let activeIndex = index;
// Potentially swap the index if needed.
if (!disableSwap) {
activeIndex = newValue.indexOf(previousValue);
}
} */

focusThumb({ sliderRef, activeIndex });
focusThumb({ sliderRef, activeIndex: index });
}

setValueState(newValue);
Expand Down Expand Up @@ -279,7 +282,7 @@ function useSliderRoot(parameters: UseSliderParameters): UseSliderReturnValue {
],
);

const previousIndex = React.useRef<number>();
// const previousIndex = React.useRef<number>();
let axis = orientation;
if (isRtl && orientation === 'horizontal') {
axis += '-reverse';
Expand All @@ -288,14 +291,14 @@ function useSliderRoot(parameters: UseSliderParameters): UseSliderReturnValue {
const getFingerNewValue = React.useCallback(
({
finger,
move = false,
offset = 0,
boundary = {},
activeIndex,
}: {
finger: { x: number; y: number };
move?: boolean;
offset?: number;
boundary?: Partial<DOMRect>;
activeIndex?: number;
}) => {
const { width = 0, height = 0, bottom = 0, left = 0 } = boundary;
let percent;
Expand All @@ -320,39 +323,57 @@ function useSliderRoot(parameters: UseSliderParameters): UseSliderReturnValue {
}

newValue = clamp(newValue, min, max);
let activeIndex = 0;
// let activeIndex = 0;
// console.log('there newValue', newValue);
// const singleValue = newValue;

let derivedIndex = 0;

if (range) {
if (!move) {
activeIndex = findClosest(values, newValue)!;
} else {
activeIndex = previousIndex.current!;
}
// if (!move) {
// activeIndex = findClosest(values, newValue)!;
// } else {
// activeIndex = previousIndex.current!;
// }

derivedIndex = activeIndex ?? findClosest(values, newValue) ?? 0;

// if (!activeIndex) {
// activeIndex = findClosest(values, newValue);
// }

// Bound the new value to the thumb's neighbours.
if (disableSwap) {
newValue = clamp(
newValue,
values[activeIndex - 1] || -Infinity,
values[activeIndex + 1] || Infinity,
values[derivedIndex - 1] || -Infinity,
values[derivedIndex + 1] || Infinity,
);
}

const previousValue = newValue;
// const previousValue = newValue;
// console.log('newValue1', newValue);
newValue = setValueIndex({
values,
newValue,
index: activeIndex,
index: derivedIndex,
});
// console.log('newValue2', newValue);

// Potentially swap the index if needed.
if (!(disableSwap && move)) {
activeIndex = newValue.indexOf(previousValue);
previousIndex.current = activeIndex;
}
// if (!disableSwap && !move) {
// activeIndex = newValue.indexOf(previousValue);
// previousIndex.current = activeIndex;
// }
}

return { newValue, activeIndex, newPercentageValue: percent };
// console.log('xxxxxx', newValue, 'activeIndex', activeIndex);
// console.log('here singleValue', singleValue);

return {
newValue,
activeIndex: activeIndex ?? derivedIndex,
newPercentageValue: percent,
};
},
[axis, disableSwap, marksValues, max, min, range, step, values],
);
Expand Down
38 changes: 30 additions & 8 deletions packages/mui-base/src/Slider/SliderTrack/useSliderTrack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { focusThumb, trackFinger } from '../Root/useSliderRoot';
import { UseSliderTrackParameters, UseSliderTrackReturnValue } from './SliderTrack.types';

const INTENTIONAL_DRAG_COUNT_THRESHOLD = 2;

/**
*
* API:
Expand Down Expand Up @@ -51,6 +52,8 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT
});
}, [subitems]);

const activeIndexRef = React.useRef(-1);

const handleTouchMove = useEventCallback((nativeEvent: TouchEvent | PointerEvent) => {
const finger = trackFinger(nativeEvent, touchId);

Expand All @@ -68,15 +71,16 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT
return;
}

const { newValue, activeIndex } = getFingerNewValue({
const activeIndex = activeIndexRef.current;

const { newValue } = getFingerNewValue({
finger,
move: true,
offset: offsetRef.current,
// TODO: getBoundingClientRect adjust for padding/border?
boundary: trackRef.current?.getBoundingClientRect(),
activeIndex,
});

focusThumb({ sliderRef: trackRef, activeIndex, setActive });
// focusThumb({ sliderRef: trackRef, activeIndex, setActive });
setValueState(newValue);

if (!dragging && moveCount.current > INTENTIONAL_DRAG_COUNT_THRESHOLD) {
Expand All @@ -98,11 +102,11 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT

const { newValue } = getFingerNewValue({
finger,
move: true,
boundary: trackRef.current?.getBoundingClientRect(),
});

setActive(-1);
activeIndexRef.current = -1;
if (nativeEvent.type === 'touchend') {
setOpen(-1);
}
Expand Down Expand Up @@ -135,6 +139,9 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT
finger,
boundary: trackRef.current?.getBoundingClientRect(),
});

activeIndexRef.current = activeIndex;

focusThumb({ sliderRef: trackRef, activeIndex, setActive });

setValueState(newValue);
Expand Down Expand Up @@ -197,14 +204,29 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT

// Avoid text selection
event.preventDefault();

const finger = trackFinger(event, touchId);

if (finger !== false) {
const { newValue, activeIndex, newPercentageValue } = getFingerNewValue({
const {
newValue,
newPercentageValue,
activeIndex: returnedActiveIndex,
} = getFingerNewValue({
finger,
boundary: trackRef.current?.getBoundingClientRect(),
});
// console.log('here newValue/singleValue', newValue, singleValue);

// const activeIndex = Array.isArray(newValue) ? newValue.indexOf(singleValue) : 0;
// console.log('returnedActiveIndex activeIndex', returnedActiveIndex);
// console.log('derived activeIndex', activeIndex);

// const activeIndex = findActiveIndex({ isRange, move: false });

activeIndexRef.current = returnedActiveIndex;

focusThumb({ sliderRef: trackRef, activeIndex, setActive });
focusThumb({ sliderRef: trackRef, activeIndex: returnedActiveIndex, setActive });

// if the event lands on a thumb, don't change the value, just get the
// percentageValue difference represented by the distance between the click origin
Expand All @@ -219,7 +241,7 @@ export function useSliderTrack(parameters: UseSliderTrackParameters): UseSliderT
setValueState(newValue);

if (handleValueChange && !areValuesEqual(newValue)) {
handleValueChange(newValue, activeIndex, event);
handleValueChange(newValue, returnedActiveIndex, event);
}
}
}
Expand Down

0 comments on commit 4da80a7

Please sign in to comment.