Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
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>
113 changes: 113 additions & 0 deletions docs/examples/disabled-handle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/* 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,
};

// Basic editable with disabled handles
const EditableWithDisabled = () => {
const [value, setValue] = useState<number[]>([0, 30, 100]);
const [disabled, setDisabled] = useState<boolean[]>([true, false, true]);

return (
<div>
<Slider
range={{
editable: true,
minCount: 2,
maxCount: 5,
}}
value={value}
onChange={(v) => setValue(v as number[])}
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>
<p style={{ marginTop: 8, color: '#999', fontSize: 12 }}>
Try: Click track to add handle • Drag handle to edge to delete • Toggle checkboxes to disable handles
</p>
</div>
);
};

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

return (
<div>
<Slider range={{ draggableTrack: true }} value={value} onChange={(v) => setValue(v as number[])} 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<number[]>([10, 50, 90]);

return (
<div>
<Slider range value={value} onChange={(v) => setValue(v as number[])} 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>
);
};

export default () => (
<div>
<div style={style}>
<h3>Disabled Handle + Draggable Track</h3>
<p>Toggle checkboxes to disable/enable specific handles. Drag the track area to move the range.</p>
<BasicDisabledHandle />
</div>

<div style={style}>
<h3>Disabled Handle as Boundary</h3>
<DisabledHandleAsBoundary />
</div>
<div>
<div style={style}>
<h3>Editable + Disabled Array</h3>
<p>Toggle checkboxes to enable/disable handles in editable mode</p>
<EditableWithDisabled />
</div>
</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
65 changes: 58 additions & 7 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,25 @@ 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 Array.isArray(value) && value.length === rawDisabled.length && rawDisabled.every(Boolean);
}, [rawDisabled, value]);
Comment on lines +191 to +197
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

聚合 disabled 仍然漏掉非受控 / 默认句柄数。

Line 196 现在只拿 value.lengthrawDisabled.length 对齐。这样 <Slider range disabled={[true, true]} /><Slider range count={2} disabled={[true, true, true]} /><Slider range defaultValue={[10, 20]} disabled={[true, true]} /> 这类初始化里,所有已渲染 handle 都是禁用的,但根节点 disabled 仍会是 false-disabled 样式和依赖聚合禁用态的分支都会失真。这里需要按和 rawValues 相同的规则推导期望长度,而不是只看 value

🔧 建议修复
  const disabled = React.useMemo(() => {
    if (typeof rawDisabled === 'boolean') {
      return rawDisabled;
-    };
+    }

-    return Array.isArray(value) && value.length === rawDisabled.length && rawDisabled.every(Boolean);
-  }, [rawDisabled, value]);
+    const sourceValues = Array.isArray(value)
+      ? value
+      : Array.isArray(defaultValue)
+        ? defaultValue
+        : undefined;
+
+    const expectedLength =
+      sourceValues?.length ?? (range ? (count >= 0 ? count + 1 : 2) : 1);
+
+    return (
+      expectedLength > 0 &&
+      rawDisabled.length === expectedLength &&
+      Array.from({ length: expectedLength }, (_, index) => rawDisabled[index] === true).every(Boolean)
+    );
+  }, [rawDisabled, value, defaultValue, range, count]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Slider.tsx` around lines 191 - 197, The current disabled aggregation in
the useMemo (symbols: rawDisabled, value, disabled) only compares
rawDisabled.length to value.length and thus misses uncontrolled/default handles;
change the logic to mirror how effective handle count is computed elsewhere by
using rawValues (or the same helper that yields rawValues) instead of value when
determining expected length and in the dependency array so disabled is true when
rawDisabled aligns with the actual rendered handles (e.g., use rawValues.length
and depend on rawValues, rawDisabled).


const isHandleDisabled = React.useCallback(
(index: number) => {
if (typeof rawDisabled === 'boolean') {
return rawDisabled;
}
return rawDisabled[index] || false;
},
[rawDisabled],
);

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

// ============================ Values ============================
Expand All @@ -257,8 +276,8 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
mergedValue === null || mergedValue === undefined
? []
: Array.isArray(mergedValue)
? mergedValue
: [mergedValue];
? mergedValue
: [mergedValue];

const [val0 = mergedMin] = valueList;
let returnValues = mergedValue === null ? [] : [val0];
Expand Down Expand Up @@ -321,7 +340,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 +367,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
offsetValues,
rangeEditable,
minCount,
isHandleDisabled,
);

/**
Expand Down Expand Up @@ -378,10 +398,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 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 +492,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 +595,7 @@ const Slider = React.forwardRef<SliderRef, SliderProps<number | number[]>>((prop
ariaValueTextFormatterForHandle,
styles: styles || {},
classNames: classNames || {},
isHandleDisabled,
}),
[
mergedMin,
Expand All @@ -565,6 +615,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
Loading
Loading