Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support generics #181

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
12 changes: 8 additions & 4 deletions docs/demo/basic.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import '../../assets/style.less';
import React from 'react';
import Segmented from 'rc-segmented';
import React from 'react';

export default function App() {
import '../../assets/style.less';

const Demo = () => {
return (
<div>
<div className="wrapper">
Expand All @@ -27,8 +28,11 @@ export default function App() {
{ label: 'Android', value: 'Android', disabled: true },
'Web',
]}
onChange={(value) => console.log(value, typeof value)}
/>
</div>
</div>
);
}
};

export default Demo;
14 changes: 4 additions & 10 deletions docs/demo/controlled.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
import '../../assets/style.less';
import React from 'react';
import Segmented from 'rc-segmented';
import type { SegmentedValue } from 'rc-segmented';
import React from 'react';
import '../../assets/style.less';

export default class Demo extends React.Component<
unknown,
{ value: SegmentedValue }
> {
state = {
value: 'Web3',
};
export default class Demo extends React.Component<unknown, { value: string }> {
state = { value: 'Web3' };

render() {
return (
Expand Down
12 changes: 6 additions & 6 deletions docs/demo/refs.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import '../../assets/style.less';
import React from 'react';
import Segmented from 'rc-segmented';
import React from 'react';
import '../../assets/style.less';

class ClassComponentWithStringRef extends React.Component {
componentDidMount() {
// eslint-disable-next-line react/no-string-refs
console.log(this.refs.segmentedRef, 'ref');
console.log(this.refs.segmentedRef, 'ClassComponentWithStringRef');
}

render() {
Expand All @@ -22,7 +22,7 @@ class ClassComponent2 extends React.Component {
segmentedRef: HTMLDivElement | null = null;

componentDidMount() {
console.log(this.segmentedRef, 'ref');
console.log(this.segmentedRef, 'ClassComponent2');
}

render() {
Expand All @@ -42,7 +42,7 @@ class ClassComponentWithCreateRef extends React.Component<
segmentedRef = React.createRef<HTMLDivElement>();

componentDidMount() {
console.log(this.segmentedRef.current, 'ref');
console.log(this.segmentedRef.current, 'ClassComponentWithCreateRef');
}

render() {
Expand All @@ -55,7 +55,7 @@ class ClassComponentWithCreateRef extends React.Component<
function FunctionalComponent() {
const segmentedRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
console.log(segmentedRef.current, 'ref');
console.log(segmentedRef.current, 'FunctionalComponent');
}, []);
return <Segmented options={['iOS', 'Android', 'Web']} ref={segmentedRef} />;
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"pretty-quick": "pretty-quick",
"test": "jest",
"coverage": "jest --coverage",
"prepare": "husky install"
"prepare": "husky install && dumi setup"
},
"dependencies": {
"@babel/runtime": "^7.11.1",
Expand Down
247 changes: 126 additions & 121 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
import * as React from 'react';
import classNames from 'classnames';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import { composeRef } from 'rc-util/lib/ref';
import omit from 'rc-util/lib/omit';
import { composeRef } from 'rc-util/lib/ref';
import * as React from 'react';

import MotionThumb from './MotionThumb';

export type SegmentedValue = string | number;

export type SegmentedRawOption = SegmentedValue;
crazyair marked this conversation as resolved.
Show resolved Hide resolved

export interface SegmentedLabeledOption {
export interface SegmentedLabeledOption<T = React.Key> {
className?: string;
disabled?: boolean;
label: React.ReactNode;
value: SegmentedRawOption;
value: T;
crazyair marked this conversation as resolved.
Show resolved Hide resolved
/**
* html `title` property for label
*/
title?: string;
}

type SegmentedOptions = (SegmentedRawOption | SegmentedLabeledOption)[];

export interface SegmentedProps
extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> {
options: SegmentedOptions;
defaultValue?: SegmentedValue;
value?: SegmentedValue;
onChange?: (value: SegmentedValue) => void;
type SegmentedOptions<T = React.Key> = (T | SegmentedLabeledOption<T>)[];

export interface SegmentedProps<T = React.Key>
extends Omit<
React.HTMLProps<HTMLDivElement>,
'value' | 'defaultValue' | 'onChange'
> {
options: SegmentedOptions<T>;
defaultValue?: T;
value?: T;
onChange?: (value: T) => void;
disabled?: boolean;
prefixCls?: string;
direction?: 'ltr' | 'rtl';
Expand Down Expand Up @@ -72,11 +71,8 @@ const InternalSegmentedOption: React.FC<{
checked: boolean;
label: React.ReactNode;
title?: string;
value: SegmentedRawOption;
onChange: (
e: React.ChangeEvent<HTMLInputElement>,
value: SegmentedRawOption,
) => void;
value: React.Key;
onChange: (e: React.ChangeEvent<HTMLInputElement>, value: React.Key) => void;
}> = ({
prefixCls,
className,
Expand Down Expand Up @@ -115,110 +111,119 @@ const InternalSegmentedOption: React.FC<{
);
};

const Segmented = React.forwardRef<HTMLDivElement, SegmentedProps>(
(props, ref) => {
const {
prefixCls = 'rc-segmented',
direction,
options = [],
disabled,
defaultValue,
value,
onChange,
className = '',
motionName = 'thumb-motion',
...restProps
} = props;

const containerRef = React.useRef<HTMLDivElement>(null);
const mergedRef = React.useMemo(
() => composeRef<HTMLDivElement>(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] = useMergedState(segmentedOptions[0]?.value, {
value,
defaultValue,
});

// ======================= Change ========================
const [thumbShow, setThumbShow] = React.useState(false);

const handleChange = (
event: React.ChangeEvent<HTMLInputElement>,
val: SegmentedRawOption,
) => {
if (disabled) {
return;
}

setRawValue(val);

onChange?.(val);
};
const InternalSegmented: React.ForwardRefRenderFunction<
crazyair marked this conversation as resolved.
Show resolved Hide resolved
HTMLDivElement,
SegmentedProps
> = (props, ref) => {
const {
prefixCls = 'rc-segmented',
direction,
options = [],
disabled,
defaultValue,
value,
onChange,
className = '',
motionName = 'thumb-motion',
...restProps
} = props;

const containerRef = React.useRef<HTMLDivElement>(null);
const mergedRef = React.useMemo(
() => composeRef<HTMLDivElement>(containerRef, ref),
[containerRef, ref],
);

const divProps = omit(restProps, ['children']);

return (
<div
{...divProps}
className={classNames(
prefixCls,
{
[`${prefixCls}-rtl`]: direction === 'rtl',
[`${prefixCls}-disabled`]: disabled,
},
className,
)}
ref={mergedRef}
>
<div className={`${prefixCls}-group`}>
<MotionThumb
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] = useMergedState(segmentedOptions[0]?.value, {
value,
defaultValue,
});

// ======================= Change ========================
const [thumbShow, setThumbShow] = React.useState(false);

const handleChange = (
event: React.ChangeEvent<HTMLInputElement>,
val: React.Key,
) => {
if (disabled) {
return;
}

setRawValue(val);

onChange?.(val);
};

const divProps = omit(restProps, ['children']);

return (
<div
{...divProps}
className={classNames(
prefixCls,
{
[`${prefixCls}-rtl`]: direction === 'rtl',
[`${prefixCls}-disabled`]: disabled,
},
className,
)}
ref={mergedRef}
>
<div className={`${prefixCls}-group`}>
<MotionThumb
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((segmentedOption) => (
<InternalSegmentedOption
{...segmentedOption}
key={segmentedOption.value}
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);
}}
className={classNames(
segmentedOption.className,
`${prefixCls}-item`,
{
[`${prefixCls}-item-selected`]:
segmentedOption.value === rawValue && !thumbShow,
},
)}
checked={segmentedOption.value === rawValue}
onChange={handleChange}
disabled={!!disabled || !!segmentedOption.disabled}
/>
{segmentedOptions.map((segmentedOption) => (
<InternalSegmentedOption
{...segmentedOption}
key={segmentedOption.value}
prefixCls={prefixCls}
className={classNames(
segmentedOption.className,
`${prefixCls}-item`,
{
[`${prefixCls}-item-selected`]:
segmentedOption.value === rawValue && !thumbShow,
},
)}
checked={segmentedOption.value === rawValue}
onChange={handleChange}
disabled={!!disabled || !!segmentedOption.disabled}
/>
))}
</div>
))}
</div>
);
},
);
</div>
);
};

Segmented.displayName = 'Segmented';
const Segmented = React.forwardRef<HTMLDivElement, SegmentedProps>(
InternalSegmented,
) as (<Values = any>(
props: SegmentedProps<Values> & { ref?: React.Ref<HTMLDivElement> },
) => React.ReactElement) & { displayName?: string };

if (process.env.NODE_ENV !== 'production') {
Segmented.displayName = 'Segmented';
}

export default Segmented;
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
"rc-segmented": ["src/index.tsx"]
}
},
"include": [".dumi/**/*", ".dumirc.ts", "src", "tests", "docs/examples"],
"include": [".dumirc.ts", "**/*"]
}