Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 14 additions & 0 deletions assets/index.less
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@
cursor: -webkit-grabbing;
cursor: grabbing;
}

&-disabled {
background-color: #fff;
border-color: @disabledColor;
box-shadow: none;
cursor: not-allowed;

&:hover,
&:active {
border-color: @disabledColor;
box-shadow: none;
cursor: not-allowed;
}
}
}

&-mark {
Expand Down
9 changes: 9 additions & 0 deletions docs/demo/disabled-handle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
title: Disabled Handle
title.zh-CN: 禁用特定滑块
nav:
title: Demo
path: /demo
---

<code src="../examples/disabled-handle.tsx"></code>
85 changes: 85 additions & 0 deletions docs/examples/disabled-handle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/* eslint react/no-multi-comp: 0, no-console: 0 */
import Slider from '@rc-component/slider';
import React, { useState } from 'react';
import '../../assets/index.less';

const style: React.CSSProperties = {
width: 400,
margin: 50,
};

const BasicDisabledHandle = () => {
const [value, setValue] = useState([0, 30, 60, 100]);
const [disabled, setDisabled] = useState([true, false, false, true]);

return (
<div>
<Slider range value={value} onChange={setValue} disabled={disabled} />
<div style={{ marginTop: 16 }}>
{value.map((val, index) => (
<label key={index} style={{ marginRight: 16 }}>
<input
type="checkbox"
checked={disabled[index]}
onChange={() => {
const newDisabled = [...disabled];
newDisabled[index] = !newDisabled[index];
setDisabled(newDisabled);
}}
/>
Handle {index + 1} ({val}) {disabled[index] ? 'Disabled' : 'Enabled'}
</label>
))}
</div>
</div>
);
};

const DisabledHandleAsBoundary = () => {
const [value, setValue] = useState([10, 50, 90]);

return (
<div>
<Slider range value={value} onChange={setValue} disabled={[false, true, false]} />
<p style={{ marginTop: 8, color: '#999' }}>
Middle handle (50) is disabled and acts as a boundary.
First handle cannot go beyond 50, third handle cannot go below 50.
Disabled handle has gray border and not-allowed cursor.
</p>
</div>
);
};

const MultipleDisabledBoundaries = () => {
const [value, setValue] = useState([10, 30, 50, 70, 90]);

return (
<div>
<Slider range value={value} onChange={setValue} disabled={[true, false, true, false, true]} />
<p style={{ marginTop: 8, color: '#999' }}>
Handles at 10, 50, 90 are disabled.
Handle at 30 can only move between 10-50, handle at 70 can only move between 50-90.
</p>
</div>
);
};

export default () => (
<div>
<div style={style}>
<h3>Basic Disabled Handle</h3>
<p>Toggle checkboxes to disable/enable specific handles</p>
<BasicDisabledHandle />
Comment thread
coderabbitai[bot] marked this conversation as resolved.
</div>

<div style={style}>
<h3>Disabled Handle as Boundary</h3>
<DisabledHandleAsBoundary />
</div>

<div style={style}>
<h3>Multiple Disabled Boundaries</h3>
<MultipleDisabledBoundaries />
</div>
</div>
);
19 changes: 13 additions & 6 deletions src/Handles/Handle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const Handle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {
min,
max,
direction,
disabled,
disabled: globalDisabled,
keyboard,
range,
tabIndex,
Expand All @@ -65,15 +65,21 @@ const Handle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {
ariaValueTextFormatterForHandle,
styles,
classNames,
isHandleDisabled,
} = React.useContext(SliderContext);

const handleDisabled =
globalDisabled || (isHandleDisabled ? isHandleDisabled(valueIndex) : false);

const handlePrefixCls = `${prefixCls}-handle`;

// ============================ Events ============================
const onInternalStartMove = (e: React.MouseEvent | React.TouchEvent) => {
if (!disabled) {
onStartMove(e, valueIndex);
if (handleDisabled) {
e.stopPropagation();
return;
}
onStartMove(e, valueIndex);
};

const onInternalFocus = (e: React.FocusEvent<HTMLDivElement>) => {
Expand All @@ -86,7 +92,7 @@ const Handle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {

// =========================== Keyboard ===========================
const onKeyDown: React.KeyboardEventHandler<HTMLDivElement> = (e) => {
if (!disabled && keyboard) {
if (!handleDisabled && keyboard) {
let offset: number | 'min' | 'max' = null;

// Change the value
Expand Down Expand Up @@ -161,12 +167,12 @@ const Handle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {

if (valueIndex !== null) {
divProps = {
tabIndex: disabled ? null : getIndex(tabIndex, valueIndex),
tabIndex: handleDisabled ? null : getIndex(tabIndex, valueIndex),
role: 'slider',
'aria-valuemin': min,
'aria-valuemax': max,
'aria-valuenow': value,
'aria-disabled': disabled,
'aria-disabled': handleDisabled,
'aria-label': getIndex(ariaLabelForHandle, valueIndex),
'aria-labelledby': getIndex(ariaLabelledByForHandle, valueIndex),
'aria-required': getIndex(ariaRequired, valueIndex),
Expand All @@ -190,6 +196,7 @@ const Handle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {
[`${handlePrefixCls}-${valueIndex + 1}`]: valueIndex !== null && range,
[`${handlePrefixCls}-dragging`]: dragging,
[`${handlePrefixCls}-dragging-delete`]: draggingDelete,
[`${handlePrefixCls}-disabled`]: handleDisabled,
},
classNames.handle,
)}
Expand Down
60 changes: 55 additions & 5 deletions src/Slider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export interface SliderProps<ValueType = number | number[]> {
id?: string;

// Status
disabled?: boolean;
disabled?: boolean | boolean[];
keyboard?: boolean;
autoFocus?: boolean;
onFocus?: (e: React.FocusEvent<HTMLDivElement>) => void;
Expand Down Expand Up @@ -131,8 +131,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop

id,

// Status
disabled = false,
disabled: rawDisabled = false,
keyboard = true,
autoFocus,
onFocus,
Expand Down Expand Up @@ -188,6 +187,24 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
const handlesRef = React.useRef<HandlesRef>(null);
const containerRef = React.useRef<HTMLDivElement>(null);

// ============================ Disabled ============================
const disabled = React.useMemo(() => {
if (typeof rawDisabled === 'boolean') {
return rawDisabled;
}
return rawDisabled.every((d) => d);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里如果给的是 disabled={[true]}  ,但是有 2 个节点也会被当成全部 disabled。

}, [rawDisabled]);
Comment thread
zombieJ marked this conversation as resolved.
Outdated

const isHandleDisabled = React.useCallback(
(index: number) => {
if (typeof rawDisabled === 'boolean') {
return rawDisabled;
}
return rawDisabled[index] || false;
},
[rawDisabled],
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Comment thread
coderabbitai[bot] marked this conversation as resolved.

const direction = React.useMemo<Direction>(() => {
if (vertical) {
return reverse ? 'ttb' : 'btt';
Expand Down Expand Up @@ -247,6 +264,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
markList,
allowCross,
mergedPush,
isHandleDisabled,
);

// ============================ Values ============================
Expand Down Expand Up @@ -321,7 +339,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
});

const onDelete = (index: number) => {
if (disabled || !rangeEditable || rawValues.length <= minCount) {
if (disabled || !rangeEditable || rawValues.length <= minCount || isHandleDisabled(index)) {
return;
}

Expand All @@ -348,6 +366,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
offsetValues,
rangeEditable,
minCount,
isHandleDisabled,
);

/**
Expand Down Expand Up @@ -378,10 +397,39 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
let focusIndex = valueIndex;

if (rangeEditable && valueDist !== 0 && (!maxCount || rawValues.length < maxCount)) {
const leftDisabled = isHandleDisabled(valueBeforeIndex);
const rightDisabled = isHandleDisabled(valueBeforeIndex + 1);

if (leftDisabled && rightDisabled) {
return;
}

cloneNextValues.splice(valueBeforeIndex + 1, 0, newValue);
focusIndex = valueBeforeIndex + 1;
} else {
if (isHandleDisabled(valueIndex)) {
let nearestIndex = -1;
let nearestDist = mergedMax - mergedMin;

rawValues.forEach((val, index) => {
if (!isHandleDisabled(index)) {
const dist = Math.abs(newValue - val);
if (dist < nearestDist) {
nearestDist = dist;
nearestIndex = index;
}
}
});

// If all handles are disabled, do nothing
if (nearestIndex === -1) {
return;
}

valueIndex = nearestIndex;
}
cloneNextValues[valueIndex] = newValue;
focusIndex = valueIndex;
Comment thread
EmilyyyLiu marked this conversation as resolved.
Comment on lines +411 to +433
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

轨道 / Mark 点击的回退选择会让 handle 穿过禁用边界。

Line 415-423 在最近的 handle 是禁用时,会从整个 rawValues 里找“最近的启用 handle”。这会选到禁用边界另一侧的候选:例如 values=[0, 20, 100]disabled=[false, true, false] 时点击 30,这里会把 0 改到 30,直接越过 20。更糟的是后面还会排序,禁用标记会跟着索引错位到新的值上。回退搜索需要限制在 newValue 所在的禁用分段内,或者显式过滤掉移动路径上存在禁用 handle 的候选。

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Slider.tsx` around lines 411 - 433, The current fallback that finds the
nearest enabled handle when isHandleDisabled(valueIndex) is true (using
rawValues, newValue and nearestIndex) can pick a handle across a disabled
boundary and allow handles to jump past disabled handles; change the search in
that block so candidates are limited to handles that can be reached without
crossing any disabled handle between the original index and the candidate: when
scanning rawValues for a nearestIndex, skip any candidate if any index between
the original valueIndex and that candidate is disabled (i.e., ensure the move
path contains no disabled handles), or alternatively restrict the search to the
contiguous enabled segment around the clicked position; update the logic that
sets cloneNextValues[valueIndex], valueIndex and focusIndex accordingly so you
never select a nearestIndex that requires crossing a disabled handle (refer to
isHandleDisabled, rawValues, valueIndex, newValue, cloneNextValues, focusIndex).

}

// Fill value to match default 2 (only when `rawValues` is empty)
Expand Down Expand Up @@ -443,7 +491,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
const [keyboardValue, setKeyboardValue] = React.useState<number>(null);

const onHandleOffsetChange = (offset: number | 'min' | 'max', valueIndex: number) => {
if (!disabled) {
if (!disabled && !isHandleDisabled(valueIndex)) {
const next = offsetValues(rawValues, offset, valueIndex);

onBeforeChange?.(getTriggerValue(rawValues));
Expand Down Expand Up @@ -546,6 +594,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
ariaValueTextFormatterForHandle,
styles: styles || {},
classNames: classNames || {},
isHandleDisabled,
}),
[
mergedMin,
Expand All @@ -565,6 +614,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
ariaValueTextFormatterForHandle,
styles,
classNames,
isHandleDisabled,
],
);

Expand Down
14 changes: 12 additions & 2 deletions src/Tracks/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,18 @@ export interface TrackProps {
}

const Tracks: React.FC<TrackProps> = (props) => {
const { prefixCls, style, values, startPoint, onStartMove } = props;
const { included, range, min, styles, classNames } = React.useContext(SliderContext);
const { prefixCls, style, values, startPoint, onStartMove: propsOnStartMove } = props;
const { included, range, min, styles, classNames, isHandleDisabled } = React.useContext(SliderContext);

const hasDisabledHandle = React.useMemo(() => {
if (!isHandleDisabled) return false;
for (let i = 0; i < values.length; i++) {
if (isHandleDisabled(i)) return true;
}
return false;
}, [isHandleDisabled, values.length]);

const onStartMove = hasDisabledHandle ? undefined : propsOnStartMove;

// =========================== List ===========================
const trackList = React.useMemo(() => {
Expand Down
1 change: 1 addition & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface SliderContextProps {
ariaValueTextFormatterForHandle?: AriaValueFormat | AriaValueFormat[];
classNames: SliderClassNames;
styles: SliderStyles;
isHandleDisabled?: (index: number) => boolean;
}

const SliderContext = React.createContext<SliderContextProps>({
Expand Down
9 changes: 9 additions & 0 deletions src/hooks/useDrag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ function useDrag(
offsetValues: OffsetValues,
editable: boolean,
minCount: number,
isHandleDisabled?: (index: number) => boolean,
): [
draggingIndex: number,
draggingValue: number,
Expand Down Expand Up @@ -91,6 +92,10 @@ function useDrag(
(valueIndex: number, offsetPercent: number, deleteMark: boolean) => {
if (valueIndex === -1) {
// >>>> Dragging on the track
if (isHandleDisabled && originValues.some((_, index) => isHandleDisabled(index))) {
return;
}

const startValue = originValues[0];
const endValue = originValues[originValues.length - 1];
const maxStartOffset = min - startValue;
Expand Down Expand Up @@ -126,6 +131,10 @@ function useDrag(

// 如果是点击 track 触发的,需要传入变化后的初始值,而不能直接用 rawValues
const initialValues = startValues || rawValues;
if (isHandleDisabled && isHandleDisabled(valueIndex)) {
return;
}

const originValue = initialValues[valueIndex];

setDraggingIndex(valueIndex);
Expand Down
Loading
Loading