This commit is contained in:
2026-05-25 17:08:18 +08:00
parent df501f6151
commit f1259b71b5
9178 changed files with 1626125 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2019-present afc163
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
# @rc-component/segmented
[![NPM version][npm-image]][npm-url] [![npm download][download-image]][download-url] [![dumi](https://img.shields.io/badge/docs%20by-dumi-blue?style=flat-square)](https://github.com/umijs/dumi) [![build status][github-actions-image]][github-actions-url] [![Codecov][codecov-image]][codecov-url] [![bundle size][bundlephobia-image]][bundlephobia-url]
[npm-image]: http://img.shields.io/npm/v/@rc-component/segmented.svg?style=flat-square
[npm-url]: http://npmjs.org/package/@rc-component/segmented
[github-actions-image]: https://github.com/react-component/segmented/actions/workflows/main.yml/badge.svg
[github-actions-url]: https://github.com/react-component/segmented/actions/workflows/main.yml
[codecov-image]: https://codecov.io/gh/react-component/segmented/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/react-component/segmented/branch/master
[download-image]: https://img.shields.io/npm/dm/@rc-component/segmented.svg?style=flat-square
[download-url]: https://npmjs.org/package/@rc-component/segmented
[bundlephobia-url]: https://bundlephobia.com/package/@rc-component/segmented
[bundlephobia-image]: https://badgen.net/bundlephobia/minzip/@rc-component/segmented
React Segmented Control.
![](https://gw.alipayobjects.com/mdn/rms_50855f/afts/img/A*bmGGQpnWs0oAAAAAAAAAAAAAARQnAQ)
## Live Demo
https://react-component.github.io/segmented/
## Install
[![@rc-component/segmented](https://nodei.co/npm/@rc-component/segmented.png)](https://npmjs.org/package/@rc-component/segmented)
## Usage
```js
import Segmented from '@rc-component/segmented';
import '@rc-component/segmented/assets/index.css'; // import '@rc-component/segmented/assets/index.less';
import { render } from 'react-dom';
render(
<Segmented
options={['Antd', 'Antv', 'Egg.js']}
onChange={(value) => handleValueChange(value)}
/>,
mountNode,
);
```
## API
Please note that **onChange** API
changed on v2.0.0+
| Property | Type | Default | Description |
| --------- | --------- | --------- | --------- |
| prefixCls | string | `rc-segmented` | prefixCls of this component |
| className | string | '' | additional class name of segmented |
| style | React.CSSProperties | | style properties of segmented |
| options | Array<string \| number \| [SegmentedOption](#SegmentedOption)> | [] | options for choices |
| value | string \| number | | value of segmented |
| defaultValue | string \| number | | defaultValue of segmented |
| value | string \| number | | currently selected value of segmented |
| onChange | (value: string \| number) => void | | defaultValue of segmented |
| disabled | boolean | false | disabled status of segmented |
### SegmentedOption
| Property | Type | Default | Description |
| --------- | --------- | --------- | --------- |
| label | ReactNode | | label of segmented option |
| value | string \| number | | value of segmented option |
| className | string | '' | additional class name of segmented option |
| disabled | boolean | false | disabled status of segmented option |
## Development
```
npm install
npm start
```
## License
@rc-component/segmented is released under the MIT license.
+97
View File
@@ -0,0 +1,97 @@
.rc-segmented {
display: inline-block;
padding: 2px;
background-color: rgba(0, 0, 0, 0.04);
}
.rc-segmented-group {
position: relative;
display: flex;
flex-direction: row;
align-items: stretch;
justify-content: flex-start;
width: 100%;
border-radius: 2px;
}
.rc-segmented-item {
position: relative;
min-height: 28px;
padding: 4px 10px;
color: rgba(0, 0, 0, 0.85);
text-align: center;
cursor: pointer;
}
.rc-segmented-item-selected {
background-color: white;
color: #262626;
}
.rc-segmented-item:hover,
.rc-segmented-item:focus {
color: #262626;
}
.rc-segmented-item-disabled,
.rc-segmented-item-disabled:hover,
.rc-segmented-item-disabled:focus {
color: rgba(0, 0, 0, 0.25);
cursor: not-allowed;
}
.rc-segmented-item-label {
z-index: 2;
line-height: 24px;
}
.rc-segmented-item-input {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
}
.rc-segmented-thumb {
background-color: white;
position: absolute;
width: 0;
height: 100%;
padding: 4px 0;
transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.rc-segmented-vertical .rc-segmented-group {
flex-direction: column;
}
.rc-segmented-vertical .rc-segmented-item {
width: 100%;
text-align: left;
}
.rc-segmented-vertical .rc-segmented-thumb {
width: 100%;
height: 0;
padding: 0 4px;
transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), height 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.rc-segmented-disabled .rc-segmented-item,
.rc-segmented-disabled .rc-segmented-item:hover,
.rc-segmented-disabled .rc-segmented-item:focus,
.rc-segmented-disabled .rc-segmented-item:hover,
.rc-segmented-disabled .rc-segmented-item:hover:hover,
.rc-segmented-disabled .rc-segmented-item:focus:hover,
.rc-segmented-disabled .rc-segmented-item:focus,
.rc-segmented-disabled .rc-segmented-item:hover:focus,
.rc-segmented-disabled .rc-segmented-item:focus:focus {
color: rgba(0, 0, 0, 0.25);
cursor: not-allowed;
}
.rc-segmented-thumb-motion-appear-active,
.rc-segmented-thumb-motion-enter-active {
transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
will-change: transform, width;
}
.rc-segmented-rtl {
direction: rtl;
}
.rc-segmented-item:focus {
outline: none;
}
.rc-segmented-item-focused {
border-radius: 2px;
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
+130
View File
@@ -0,0 +1,130 @@
@segmented-prefix-cls: rc-segmented;
@disabled-color: fade(#000, 25%);
@selected-bg-color: white;
@text-color: #262626;
@transition-duration: 0.3s;
@transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1);
.segmented-disabled-item() {
&,
&:hover,
&:focus {
color: @disabled-color;
cursor: not-allowed;
}
}
.segmented-item-selected() {
background-color: @selected-bg-color;
}
.@{segmented-prefix-cls} {
display: inline-block;
padding: 2px;
background-color: rgba(0, 0, 0, 0.04);
&-group {
position: relative;
display: flex;
flex-direction: row;
align-items: stretch;
justify-content: flex-start;
width: 100%;
border-radius: 2px;
}
&-item {
position: relative;
min-height: 28px;
padding: 4px 10px;
color: fade(#000, 85%);
text-align: center;
cursor: pointer;
&-selected {
.segmented-item-selected();
color: @text-color;
}
&:hover,
&:focus {
color: @text-color;
}
&-disabled {
.segmented-disabled-item();
}
&-label {
z-index: 2;
line-height: 24px;
}
&-input {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
}
}
&-thumb {
.segmented-item-selected();
position: absolute;
width: 0;
height: 100%;
padding: 4px 0;
transition: transform @transition-duration @transition-timing-function,
width @transition-duration @transition-timing-function;
}
&-vertical &-group {
flex-direction: column;
}
&-vertical &-item {
width: 100%;
text-align: left;
}
&-vertical &-thumb {
width: 100%;
height: 0;
padding: 0 4px;
transition: transform @transition-duration @transition-timing-function,
height @transition-duration @transition-timing-function;
}
// disabled styles
&-disabled &-item,
&-disabled &-item:hover,
&-disabled &-item:focus {
.segmented-disabled-item();
}
&-thumb-motion-appear-active,
&-thumb-motion-enter-active {
transition: transform @transition-duration @transition-timing-function,
width @transition-duration @transition-timing-function;
will-change: transform, width;
}
&-rtl {
direction: rtl;
}
}
.rc-segmented-item {
&:focus {
outline: none;
}
&-focused {
border-radius: 2px;
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
}
+12
View File
@@ -0,0 +1,12 @@
@import './index.less';
// reset
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.wrapper {
margin-bottom: 10px;
}
@@ -0,0 +1,14 @@
import * as React from 'react';
import type { SegmentedValue } from '.';
export interface MotionThumbInterface {
containerRef: React.RefObject<HTMLDivElement>;
value: SegmentedValue;
getValueIndex: (value: SegmentedValue) => number;
prefixCls: string;
motionName: string;
onMotionStart: VoidFunction;
onMotionEnd: VoidFunction;
direction?: 'ltr' | 'rtl';
vertical?: boolean;
}
export default function MotionThumb(props: MotionThumbInterface): React.JSX.Element | null;
+165
View File
@@ -0,0 +1,165 @@
import CSSMotion from '@rc-component/motion';
import useLayoutEffect from "@rc-component/util/es/hooks/useLayoutEffect";
import { composeRef } from "@rc-component/util/es/ref";
import { clsx } from 'clsx';
import * as React from 'react';
const calcThumbStyle = (targetElement, vertical) => {
if (!targetElement) return null;
const style = {
left: targetElement.offsetLeft,
right: targetElement.parentElement.clientWidth - targetElement.clientWidth - targetElement.offsetLeft,
width: targetElement.clientWidth,
top: targetElement.offsetTop,
bottom: targetElement.parentElement.clientHeight - targetElement.clientHeight - targetElement.offsetTop,
height: targetElement.clientHeight
};
if (vertical) {
// Adjusts positioning and size for vertical layout by setting horizontal properties to 0 and using vertical properties from the style object.
return {
left: 0,
right: 0,
width: 0,
top: style.top,
bottom: style.bottom,
height: style.height
};
}
return {
left: style.left,
right: style.right,
width: style.width,
top: 0,
bottom: 0,
height: 0
};
};
const toPX = value => value !== undefined ? `${value}px` : undefined;
export default function MotionThumb(props) {
const {
prefixCls,
containerRef,
value,
getValueIndex,
motionName,
onMotionStart,
onMotionEnd,
direction,
vertical = false
} = props;
const thumbRef = React.useRef(null);
const [prevValue, setPrevValue] = React.useState(value);
// =========================== Effect ===========================
const findValueElement = val => {
const index = getValueIndex(val);
const ele = containerRef.current?.querySelectorAll(`.${prefixCls}-item`)[index];
return ele?.offsetParent && ele;
};
const [prevStyle, setPrevStyle] = React.useState(null);
const [nextStyle, setNextStyle] = React.useState(null);
useLayoutEffect(() => {
if (prevValue !== value) {
const prev = findValueElement(prevValue);
const next = findValueElement(value);
const calcPrevStyle = calcThumbStyle(prev, vertical);
const calcNextStyle = calcThumbStyle(next, vertical);
setPrevValue(value);
setPrevStyle(calcPrevStyle);
setNextStyle(calcNextStyle);
if (prev && next) {
onMotionStart();
} else {
onMotionEnd();
}
}
}, [value]);
const thumbStart = React.useMemo(() => {
if (vertical) {
return toPX(prevStyle?.top ?? 0);
}
if (direction === 'rtl') {
return toPX(-prevStyle?.right);
}
return toPX(prevStyle?.left);
}, [vertical, direction, prevStyle]);
const thumbActive = React.useMemo(() => {
if (vertical) {
return toPX(nextStyle?.top ?? 0);
}
if (direction === 'rtl') {
return toPX(-nextStyle?.right);
}
return toPX(nextStyle?.left);
}, [vertical, direction, nextStyle]);
// =========================== Motion ===========================
const onAppearStart = () => {
if (vertical) {
return {
transform: 'translateY(var(--thumb-start-top))',
height: 'var(--thumb-start-height)'
};
}
return {
transform: 'translateX(var(--thumb-start-left))',
width: 'var(--thumb-start-width)'
};
};
const onAppearActive = () => {
if (vertical) {
return {
transform: 'translateY(var(--thumb-active-top))',
height: 'var(--thumb-active-height)'
};
}
return {
transform: 'translateX(var(--thumb-active-left))',
width: 'var(--thumb-active-width)'
};
};
const onVisibleChanged = () => {
setPrevStyle(null);
setNextStyle(null);
onMotionEnd();
};
// =========================== Render ===========================
// No need motion when nothing exist in queue
if (!prevStyle || !nextStyle) {
return null;
}
return /*#__PURE__*/React.createElement(CSSMotion, {
visible: true,
motionName: motionName,
motionAppear: true,
onAppearStart: onAppearStart,
onAppearActive: onAppearActive,
onVisibleChanged: onVisibleChanged
}, ({
className: motionClassName,
style: motionStyle
}, ref) => {
const mergedStyle = {
...motionStyle,
'--thumb-start-left': thumbStart,
'--thumb-start-width': toPX(prevStyle?.width),
'--thumb-active-left': thumbActive,
'--thumb-active-width': toPX(nextStyle?.width),
'--thumb-start-top': thumbStart,
'--thumb-start-height': toPX(prevStyle?.height),
'--thumb-active-top': thumbActive,
'--thumb-active-height': toPX(nextStyle?.height)
};
// It's little ugly which should be refactor when @umi/test update to latest jsdom
const motionProps = {
ref: composeRef(thumbRef, ref),
style: mergedStyle,
className: clsx(`${prefixCls}-thumb`, motionClassName)
};
if (process.env.NODE_ENV === 'test') {
motionProps['data-test-style'] = JSON.stringify(mergedStyle);
}
return /*#__PURE__*/React.createElement("div", motionProps);
});
}
+38
View File
@@ -0,0 +1,38 @@
import * as React from 'react';
export type SemanticName = 'item' | 'label';
export type SegmentedValue = string | number;
export type SegmentedRawOption = SegmentedValue;
export interface SegmentedLabeledOption<ValueType = SegmentedRawOption> {
className?: string;
disabled?: boolean;
label: React.ReactNode;
value: ValueType;
/**
* html `title` property for label
*/
title?: string;
}
type ItemRender = (node: React.ReactNode, info: {
item: SegmentedLabeledOption;
}) => React.ReactNode;
type SegmentedOptions<T = SegmentedRawOption> = (T | SegmentedLabeledOption<T>)[];
export interface SegmentedProps<ValueType = SegmentedValue> extends Omit<React.HTMLProps<HTMLDivElement>, 'defaultValue' | 'value' | 'onChange'> {
options: SegmentedOptions<ValueType>;
defaultValue?: ValueType;
value?: ValueType;
onChange?: (value: ValueType) => void;
disabled?: boolean;
prefixCls?: string;
direction?: 'ltr' | 'rtl';
motionName?: string;
vertical?: boolean;
name?: string;
classNames?: Partial<Record<SemanticName, string>>;
styles?: Partial<Record<SemanticName, React.CSSProperties>>;
itemRender?: ItemRender;
}
declare const Segmented: React.ForwardRefExoticComponent<Omit<SegmentedProps<SegmentedValue>, "ref"> & React.RefAttributes<HTMLDivElement>>;
declare const TypedSegmented: <ValueType>(props: SegmentedProps<ValueType> & {
ref?: React.ForwardedRef<HTMLDivElement>;
}) => ReturnType<typeof Segmented>;
export default TypedSegmented;
+230
View File
@@ -0,0 +1,230 @@
import _extends from "@babel/runtime/helpers/esm/extends";
import useControlledState from "@rc-component/util/es/hooks/useControlledState";
import omit from "@rc-component/util/es/omit";
import { composeRef } from "@rc-component/util/es/ref";
import { clsx } from 'clsx';
import * as React from 'react';
import MotionThumb from "./MotionThumb";
function getValidTitle(option) {
if (typeof option.title !== 'undefined') {
return option.title;
}
// read `label` when title is `undefined`
if (typeof option.label !== 'object') {
return option.label?.toString();
}
}
function normalizeOptions(options) {
return options.map(option => {
if (typeof option === 'object' && option !== null) {
const validTitle = getValidTitle(option);
return {
...option,
title: validTitle
};
}
return {
label: option?.toString(),
title: option?.toString(),
value: option
};
});
}
const InternalSegmentedOption = ({
prefixCls,
className,
style,
styles,
classNames: segmentedClassNames,
data,
disabled,
checked,
label,
title,
value,
name,
onChange,
onFocus,
onBlur,
onKeyDown,
onKeyUp,
onMouseDown,
itemRender = node => node
}) => {
const handleChange = event => {
if (disabled) {
return;
}
onChange(event, value);
};
const itemContent = /*#__PURE__*/React.createElement("label", {
className: clsx(className, {
[`${prefixCls}-item-disabled`]: disabled
}),
style: style,
onMouseDown: onMouseDown
}, /*#__PURE__*/React.createElement("input", {
name: name,
className: `${prefixCls}-item-input`,
type: "radio",
disabled: disabled,
checked: checked,
onChange: handleChange,
onFocus: onFocus,
onBlur: onBlur,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp
}), /*#__PURE__*/React.createElement("div", {
className: clsx(`${prefixCls}-item-label`, segmentedClassNames?.label),
title: title,
style: styles?.label
}, label));
return itemRender(itemContent, {
item: data
});
};
const Segmented = /*#__PURE__*/React.forwardRef((props, ref) => {
const {
prefixCls = 'rc-segmented',
direction,
vertical,
options = [],
disabled,
defaultValue,
value,
name,
onChange,
className = '',
style,
styles,
classNames: segmentedClassNames,
motionName = 'thumb-motion',
itemRender,
...restProps
} = props;
const containerRef = React.useRef(null);
const mergedRef = React.useMemo(() => composeRef(containerRef, ref), [containerRef, ref]);
const segmentedOptions = React.useMemo(() => {
return normalizeOptions(options);
}, [options]);
// Note: We should not auto switch value when value not exist in options
// which may break single source of truth.
const [rawValue, setRawValue] = useControlledState(defaultValue ?? segmentedOptions[0]?.value, value);
// ======================= Change ========================
const [thumbShow, setThumbShow] = React.useState(false);
const handleChange = (event, val) => {
setRawValue(val);
onChange?.(val);
};
const divProps = omit(restProps, ['children']);
// ======================= Focus ========================
const [isKeyboard, setIsKeyboard] = React.useState(false);
const [isFocused, setIsFocused] = React.useState(false);
const handleFocus = () => {
setIsFocused(true);
};
const handleBlur = () => {
setIsFocused(false);
};
const handleMouseDown = () => {
setIsKeyboard(false);
};
// capture keyboard tab interaction for correct focus style
const handleKeyUp = event => {
if (event.key === 'Tab') {
setIsKeyboard(true);
}
};
// ======================= Keyboard ========================
const onOffset = offset => {
const currentIndex = segmentedOptions.findIndex(option => option.value === rawValue);
const total = segmentedOptions.length;
const nextIndex = (currentIndex + offset + total) % total;
const nextOption = segmentedOptions[nextIndex];
if (nextOption) {
setRawValue(nextOption.value);
onChange?.(nextOption.value);
}
};
const handleKeyDown = event => {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowUp':
onOffset(-1);
break;
case 'ArrowRight':
case 'ArrowDown':
onOffset(1);
break;
}
};
const renderOption = segmentedOption => {
const {
value: optionValue,
disabled: optionDisabled
} = segmentedOption;
return /*#__PURE__*/React.createElement(InternalSegmentedOption, _extends({}, segmentedOption, {
name: name,
data: segmentedOption,
itemRender: itemRender,
key: optionValue,
prefixCls: prefixCls,
className: clsx(segmentedOption.className, `${prefixCls}-item`, segmentedClassNames?.item, {
[`${prefixCls}-item-selected`]: optionValue === rawValue && !thumbShow,
[`${prefixCls}-item-focused`]: isFocused && isKeyboard && optionValue === rawValue
}),
style: styles?.item,
classNames: segmentedClassNames,
styles: styles,
checked: optionValue === rawValue,
onChange: handleChange,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onMouseDown: handleMouseDown,
disabled: !!disabled || !!optionDisabled
}));
};
return /*#__PURE__*/React.createElement("div", _extends({
role: "radiogroup",
"aria-label": "segmented control",
tabIndex: disabled ? undefined : 0,
"aria-orientation": vertical ? 'vertical' : 'horizontal',
style: style
}, divProps, {
className: clsx(prefixCls, {
[`${prefixCls}-rtl`]: direction === 'rtl',
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-vertical`]: vertical
}, className),
ref: mergedRef
}), /*#__PURE__*/React.createElement("div", {
className: `${prefixCls}-group`
}, /*#__PURE__*/React.createElement(MotionThumb, {
vertical: vertical,
prefixCls: prefixCls,
value: rawValue,
containerRef: containerRef,
motionName: `${prefixCls}-${motionName}`,
direction: direction,
getValueIndex: val => segmentedOptions.findIndex(n => n.value === val),
onMotionStart: () => {
setThumbShow(true);
},
onMotionEnd: () => {
setThumbShow(false);
}
}), segmentedOptions.map(renderOption)));
});
if (process.env.NODE_ENV !== 'production') {
Segmented.displayName = 'Segmented';
}
const TypedSegmented = Segmented;
export default TypedSegmented;
@@ -0,0 +1,14 @@
import * as React from 'react';
import type { SegmentedValue } from '.';
export interface MotionThumbInterface {
containerRef: React.RefObject<HTMLDivElement>;
value: SegmentedValue;
getValueIndex: (value: SegmentedValue) => number;
prefixCls: string;
motionName: string;
onMotionStart: VoidFunction;
onMotionEnd: VoidFunction;
direction?: 'ltr' | 'rtl';
vertical?: boolean;
}
export default function MotionThumb(props: MotionThumbInterface): React.JSX.Element | null;
+174
View File
@@ -0,0 +1,174 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = MotionThumb;
var _motion = _interopRequireDefault(require("@rc-component/motion"));
var _useLayoutEffect = _interopRequireDefault(require("@rc-component/util/lib/hooks/useLayoutEffect"));
var _ref = require("@rc-component/util/lib/ref");
var _clsx = require("clsx");
var React = _interopRequireWildcard(require("react"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
const calcThumbStyle = (targetElement, vertical) => {
if (!targetElement) return null;
const style = {
left: targetElement.offsetLeft,
right: targetElement.parentElement.clientWidth - targetElement.clientWidth - targetElement.offsetLeft,
width: targetElement.clientWidth,
top: targetElement.offsetTop,
bottom: targetElement.parentElement.clientHeight - targetElement.clientHeight - targetElement.offsetTop,
height: targetElement.clientHeight
};
if (vertical) {
// Adjusts positioning and size for vertical layout by setting horizontal properties to 0 and using vertical properties from the style object.
return {
left: 0,
right: 0,
width: 0,
top: style.top,
bottom: style.bottom,
height: style.height
};
}
return {
left: style.left,
right: style.right,
width: style.width,
top: 0,
bottom: 0,
height: 0
};
};
const toPX = value => value !== undefined ? `${value}px` : undefined;
function MotionThumb(props) {
const {
prefixCls,
containerRef,
value,
getValueIndex,
motionName,
onMotionStart,
onMotionEnd,
direction,
vertical = false
} = props;
const thumbRef = React.useRef(null);
const [prevValue, setPrevValue] = React.useState(value);
// =========================== Effect ===========================
const findValueElement = val => {
const index = getValueIndex(val);
const ele = containerRef.current?.querySelectorAll(`.${prefixCls}-item`)[index];
return ele?.offsetParent && ele;
};
const [prevStyle, setPrevStyle] = React.useState(null);
const [nextStyle, setNextStyle] = React.useState(null);
(0, _useLayoutEffect.default)(() => {
if (prevValue !== value) {
const prev = findValueElement(prevValue);
const next = findValueElement(value);
const calcPrevStyle = calcThumbStyle(prev, vertical);
const calcNextStyle = calcThumbStyle(next, vertical);
setPrevValue(value);
setPrevStyle(calcPrevStyle);
setNextStyle(calcNextStyle);
if (prev && next) {
onMotionStart();
} else {
onMotionEnd();
}
}
}, [value]);
const thumbStart = React.useMemo(() => {
if (vertical) {
return toPX(prevStyle?.top ?? 0);
}
if (direction === 'rtl') {
return toPX(-prevStyle?.right);
}
return toPX(prevStyle?.left);
}, [vertical, direction, prevStyle]);
const thumbActive = React.useMemo(() => {
if (vertical) {
return toPX(nextStyle?.top ?? 0);
}
if (direction === 'rtl') {
return toPX(-nextStyle?.right);
}
return toPX(nextStyle?.left);
}, [vertical, direction, nextStyle]);
// =========================== Motion ===========================
const onAppearStart = () => {
if (vertical) {
return {
transform: 'translateY(var(--thumb-start-top))',
height: 'var(--thumb-start-height)'
};
}
return {
transform: 'translateX(var(--thumb-start-left))',
width: 'var(--thumb-start-width)'
};
};
const onAppearActive = () => {
if (vertical) {
return {
transform: 'translateY(var(--thumb-active-top))',
height: 'var(--thumb-active-height)'
};
}
return {
transform: 'translateX(var(--thumb-active-left))',
width: 'var(--thumb-active-width)'
};
};
const onVisibleChanged = () => {
setPrevStyle(null);
setNextStyle(null);
onMotionEnd();
};
// =========================== Render ===========================
// No need motion when nothing exist in queue
if (!prevStyle || !nextStyle) {
return null;
}
return /*#__PURE__*/React.createElement(_motion.default, {
visible: true,
motionName: motionName,
motionAppear: true,
onAppearStart: onAppearStart,
onAppearActive: onAppearActive,
onVisibleChanged: onVisibleChanged
}, ({
className: motionClassName,
style: motionStyle
}, ref) => {
const mergedStyle = {
...motionStyle,
'--thumb-start-left': thumbStart,
'--thumb-start-width': toPX(prevStyle?.width),
'--thumb-active-left': thumbActive,
'--thumb-active-width': toPX(nextStyle?.width),
'--thumb-start-top': thumbStart,
'--thumb-start-height': toPX(prevStyle?.height),
'--thumb-active-top': thumbActive,
'--thumb-active-height': toPX(nextStyle?.height)
};
// It's little ugly which should be refactor when @umi/test update to latest jsdom
const motionProps = {
ref: (0, _ref.composeRef)(thumbRef, ref),
style: mergedStyle,
className: (0, _clsx.clsx)(`${prefixCls}-thumb`, motionClassName)
};
if (process.env.NODE_ENV === 'test') {
motionProps['data-test-style'] = JSON.stringify(mergedStyle);
}
return /*#__PURE__*/React.createElement("div", motionProps);
});
}
+38
View File
@@ -0,0 +1,38 @@
import * as React from 'react';
export type SemanticName = 'item' | 'label';
export type SegmentedValue = string | number;
export type SegmentedRawOption = SegmentedValue;
export interface SegmentedLabeledOption<ValueType = SegmentedRawOption> {
className?: string;
disabled?: boolean;
label: React.ReactNode;
value: ValueType;
/**
* html `title` property for label
*/
title?: string;
}
type ItemRender = (node: React.ReactNode, info: {
item: SegmentedLabeledOption;
}) => React.ReactNode;
type SegmentedOptions<T = SegmentedRawOption> = (T | SegmentedLabeledOption<T>)[];
export interface SegmentedProps<ValueType = SegmentedValue> extends Omit<React.HTMLProps<HTMLDivElement>, 'defaultValue' | 'value' | 'onChange'> {
options: SegmentedOptions<ValueType>;
defaultValue?: ValueType;
value?: ValueType;
onChange?: (value: ValueType) => void;
disabled?: boolean;
prefixCls?: string;
direction?: 'ltr' | 'rtl';
motionName?: string;
vertical?: boolean;
name?: string;
classNames?: Partial<Record<SemanticName, string>>;
styles?: Partial<Record<SemanticName, React.CSSProperties>>;
itemRender?: ItemRender;
}
declare const Segmented: React.ForwardRefExoticComponent<Omit<SegmentedProps<SegmentedValue>, "ref"> & React.RefAttributes<HTMLDivElement>>;
declare const TypedSegmented: <ValueType>(props: SegmentedProps<ValueType> & {
ref?: React.ForwardedRef<HTMLDivElement>;
}) => ReturnType<typeof Segmented>;
export default TypedSegmented;
+239
View File
@@ -0,0 +1,239 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _useControlledState = _interopRequireDefault(require("@rc-component/util/lib/hooks/useControlledState"));
var _omit = _interopRequireDefault(require("@rc-component/util/lib/omit"));
var _ref = require("@rc-component/util/lib/ref");
var _clsx = require("clsx");
var React = _interopRequireWildcard(require("react"));
var _MotionThumb = _interopRequireDefault(require("./MotionThumb"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
function getValidTitle(option) {
if (typeof option.title !== 'undefined') {
return option.title;
}
// read `label` when title is `undefined`
if (typeof option.label !== 'object') {
return option.label?.toString();
}
}
function normalizeOptions(options) {
return options.map(option => {
if (typeof option === 'object' && option !== null) {
const validTitle = getValidTitle(option);
return {
...option,
title: validTitle
};
}
return {
label: option?.toString(),
title: option?.toString(),
value: option
};
});
}
const InternalSegmentedOption = ({
prefixCls,
className,
style,
styles,
classNames: segmentedClassNames,
data,
disabled,
checked,
label,
title,
value,
name,
onChange,
onFocus,
onBlur,
onKeyDown,
onKeyUp,
onMouseDown,
itemRender = node => node
}) => {
const handleChange = event => {
if (disabled) {
return;
}
onChange(event, value);
};
const itemContent = /*#__PURE__*/React.createElement("label", {
className: (0, _clsx.clsx)(className, {
[`${prefixCls}-item-disabled`]: disabled
}),
style: style,
onMouseDown: onMouseDown
}, /*#__PURE__*/React.createElement("input", {
name: name,
className: `${prefixCls}-item-input`,
type: "radio",
disabled: disabled,
checked: checked,
onChange: handleChange,
onFocus: onFocus,
onBlur: onBlur,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp
}), /*#__PURE__*/React.createElement("div", {
className: (0, _clsx.clsx)(`${prefixCls}-item-label`, segmentedClassNames?.label),
title: title,
style: styles?.label
}, label));
return itemRender(itemContent, {
item: data
});
};
const Segmented = /*#__PURE__*/React.forwardRef((props, ref) => {
const {
prefixCls = 'rc-segmented',
direction,
vertical,
options = [],
disabled,
defaultValue,
value,
name,
onChange,
className = '',
style,
styles,
classNames: segmentedClassNames,
motionName = 'thumb-motion',
itemRender,
...restProps
} = props;
const containerRef = React.useRef(null);
const mergedRef = React.useMemo(() => (0, _ref.composeRef)(containerRef, ref), [containerRef, ref]);
const segmentedOptions = React.useMemo(() => {
return normalizeOptions(options);
}, [options]);
// Note: We should not auto switch value when value not exist in options
// which may break single source of truth.
const [rawValue, setRawValue] = (0, _useControlledState.default)(defaultValue ?? segmentedOptions[0]?.value, value);
// ======================= Change ========================
const [thumbShow, setThumbShow] = React.useState(false);
const handleChange = (event, val) => {
setRawValue(val);
onChange?.(val);
};
const divProps = (0, _omit.default)(restProps, ['children']);
// ======================= Focus ========================
const [isKeyboard, setIsKeyboard] = React.useState(false);
const [isFocused, setIsFocused] = React.useState(false);
const handleFocus = () => {
setIsFocused(true);
};
const handleBlur = () => {
setIsFocused(false);
};
const handleMouseDown = () => {
setIsKeyboard(false);
};
// capture keyboard tab interaction for correct focus style
const handleKeyUp = event => {
if (event.key === 'Tab') {
setIsKeyboard(true);
}
};
// ======================= Keyboard ========================
const onOffset = offset => {
const currentIndex = segmentedOptions.findIndex(option => option.value === rawValue);
const total = segmentedOptions.length;
const nextIndex = (currentIndex + offset + total) % total;
const nextOption = segmentedOptions[nextIndex];
if (nextOption) {
setRawValue(nextOption.value);
onChange?.(nextOption.value);
}
};
const handleKeyDown = event => {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowUp':
onOffset(-1);
break;
case 'ArrowRight':
case 'ArrowDown':
onOffset(1);
break;
}
};
const renderOption = segmentedOption => {
const {
value: optionValue,
disabled: optionDisabled
} = segmentedOption;
return /*#__PURE__*/React.createElement(InternalSegmentedOption, (0, _extends2.default)({}, segmentedOption, {
name: name,
data: segmentedOption,
itemRender: itemRender,
key: optionValue,
prefixCls: prefixCls,
className: (0, _clsx.clsx)(segmentedOption.className, `${prefixCls}-item`, segmentedClassNames?.item, {
[`${prefixCls}-item-selected`]: optionValue === rawValue && !thumbShow,
[`${prefixCls}-item-focused`]: isFocused && isKeyboard && optionValue === rawValue
}),
style: styles?.item,
classNames: segmentedClassNames,
styles: styles,
checked: optionValue === rawValue,
onChange: handleChange,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
onMouseDown: handleMouseDown,
disabled: !!disabled || !!optionDisabled
}));
};
return /*#__PURE__*/React.createElement("div", (0, _extends2.default)({
role: "radiogroup",
"aria-label": "segmented control",
tabIndex: disabled ? undefined : 0,
"aria-orientation": vertical ? 'vertical' : 'horizontal',
style: style
}, divProps, {
className: (0, _clsx.clsx)(prefixCls, {
[`${prefixCls}-rtl`]: direction === 'rtl',
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-vertical`]: vertical
}, className),
ref: mergedRef
}), /*#__PURE__*/React.createElement("div", {
className: `${prefixCls}-group`
}, /*#__PURE__*/React.createElement(_MotionThumb.default, {
vertical: vertical,
prefixCls: prefixCls,
value: rawValue,
containerRef: containerRef,
motionName: `${prefixCls}-${motionName}`,
direction: direction,
getValueIndex: val => segmentedOptions.findIndex(n => n.value === val),
onMotionStart: () => {
setThumbShow(true);
},
onMotionEnd: () => {
setThumbShow(false);
}
}), segmentedOptions.map(renderOption)));
});
if (process.env.NODE_ENV !== 'production') {
Segmented.displayName = 'Segmented';
}
const TypedSegmented = Segmented;
var _default = exports.default = TypedSegmented;
+94
View File
@@ -0,0 +1,94 @@
{
"name": "@rc-component/segmented",
"version": "1.3.0",
"description": "React segmented controls used in ant.design",
"keywords": [
"react",
"react-component",
"react-segmented",
"react-segmented-controls",
"segmented controls",
"antd",
"ant-design"
],
"main": "./lib/index",
"module": "./es/index",
"types": "./es/index.d.ts",
"files": [
"assets/*.css",
"assets/*.less",
"es",
"lib",
"dist"
],
"homepage": "https://react-component.github.io/segmented",
"repository": {
"type": "git",
"url": "git@github.com:react-component/segmented.git"
},
"bugs": {
"url": "http://github.com/react-component/segmented/issues"
},
"license": "MIT",
"scripts": {
"start": "dumi dev",
"type:check": "tsc --noEmit",
"docs:build": "dumi build",
"docs:deploy": "gh-pages -d .doc",
"compile": "father build && lessc assets/index.less assets/index.css",
"gh-pages": "GH_PAGES=1 npm run docs:build && npm run docs:deploy",
"prepublishOnly": "npm run compile && rc-np",
"lint": "eslint src/ --ext .ts,.tsx,.jsx,.js,.md",
"prettier": "prettier --write \"**/*.{ts,tsx,js,jsx,json,md}\"",
"pretty-quick": "pretty-quick",
"test": "jest",
"coverage": "jest --coverage",
"prepare": "husky install"
},
"dependencies": {
"@babel/runtime": "^7.11.1",
"@rc-component/util": "^1.3.0",
"clsx": "^2.1.1",
"@rc-component/motion": "^1.1.4"
},
"devDependencies": {
"@rc-component/father-plugin": "^2.0.1",
"@rc-component/np": "^1.0.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^14.2.1",
"@testing-library/user-event": "^14.5.2",
"@types/jest": "^29.2.4",
"@types/node": "^24.5.2",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.1",
"@umijs/fabric": "^3.0.0",
"@umijs/test": "^4.0.36",
"dumi": "^2.1.2",
"eslint": "^7.0.0",
"father": "^4.1.1",
"gh-pages": "^3.1.0",
"husky": "^8.0.0",
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"less": "^3.10.3",
"prettier": "^2.0.5",
"pretty-quick": "^3.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.3.0"
},
"peerDependencies": {
"react": ">=16.0.0",
"react-dom": ">=16.0.0"
},
"publishConfig": {
"access": "public"
},
"cnpm": {
"mode": "npm"
},
"tnpm": {
"mode": "npm"
}
}