Skip to content

Rate support precision #196

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
20 changes: 3 additions & 17 deletions assets/index.less
Original file line number Diff line number Diff line change
@@ -45,11 +45,6 @@
float: right;
}

&-first,
&-second {
transition: all .3s;
}

&-focused, &:hover {
transform: scale(1.1);
}
@@ -58,10 +53,11 @@
position: absolute;
left: 0;
top: 0;
width: 50%;
width: 0%;
height: 100%;
overflow: hidden;
opacity: 0;
opacity: 1;
color: @rate-star-color;

.@{rate-prefix-cls}-rtl & {
right: 0;
@@ -73,16 +69,6 @@
&-half &-second {
opacity: 1;
}

&-half &-first,
&-full &-second {
color: @rate-star-color;
}

&-half:hover &-first,
&-full:hover &-second {
color: tint(@rate-star-color,30%);
}
}
}

11 changes: 10 additions & 1 deletion docs/examples/simple.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint no-console: 0 */
import React from 'react';
import Rate from 'rc-rate';
import React from 'react';
import '../../assets/index.less';

function onChange(v: number) {
@@ -59,5 +59,14 @@ export default () => (
style={{ fontSize: 50, marginTop: 24 }}
character={<i className="anticon anticon-star" />}
/>
<h2>Precision</h2>
<Rate
defaultValue={1.2}
precision={0.1}
onChange={onChange}
count={10}
style={{ fontSize: 50, marginTop: 24 }}
character={<i className="anticon anticon-star" />}
/>
</div>
);
61 changes: 44 additions & 17 deletions src/Rate.tsx
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@ import React from 'react';
import type { StarProps } from './Star';
import Star from './Star';
import useRefs from './useRefs';
import { getOffsetLeft } from './util';
import { clamp, getBoundingClientRect, roundValueToPrecision } from './util';

export interface RateProps
extends Pick<StarProps, 'count' | 'character' | 'characterRender' | 'allowHalf' | 'disabled'> {
@@ -32,6 +32,10 @@ export interface RateProps
* @default true
*/
keyboard?: boolean;
/**
* Define the minimum increment value change
*/
precision?: number;
}

export interface RateRef {
@@ -49,9 +53,14 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {
defaultValue,
value: propValue,
count = 5,
/**
* allow half star
* @deprecated Since precision has been implemented, `allowHalf` is no longer needed.
*/
allowHalf = false,
allowClear = true,
keyboard = true,
precision = 1,

// Display
character = '★',
@@ -76,6 +85,8 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {

const [getStarRef, setStarRef] = useRefs<HTMLElement>();
const rateRef = React.useRef<HTMLUListElement>(null);
const mergedPrecision = allowHalf ? 0.5 : precision > 0 ? precision : 1;
const reverse = direction === 'rtl';

// ============================ Ref =============================
const triggerFocus = () => {
@@ -99,19 +110,36 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {
});
const [cleanedValue, setCleanedValue] = useMergedState<number | null>(null);

const getStarValue = (index: number, x: number) => {
const reverse = direction === 'rtl';
let starValue = index + 1;
if (allowHalf) {
const starEle = getStarRef(index);
const leftDis = getOffsetLeft(starEle);
const width = starEle.clientWidth;
if (reverse && x - leftDis > width / 2) {
starValue -= 0.5;
} else if (!reverse && x - leftDis < width / 2) {
starValue -= 0.5;
}
const calculatePercentage = (delta: number, left: number, right: number) => {
return (reverse ? right - delta : delta - left) / (right - left);
};

const dealWithMergedPrecision = (delta: number) => {
const rootNode = rateRef.current;
const { right, left } = getBoundingClientRect(rootNode);
const percentage = calculatePercentage(delta, left, right);

let newHover = roundValueToPrecision(count * percentage + mergedPrecision / 2, mergedPrecision);
newHover = clamp(newHover, mergedPrecision, count);
return newHover;
};

const getStarValue = (index: number, delta: number) => {
let starValue = index;

const starEle = getStarRef(index);
const { left, right } = getBoundingClientRect(starEle);
if (!left || !right) return allowHalf ? starValue + 0.5 : starValue + 1;

const percentage = calculatePercentage(delta, left, right);
let roundedValue = roundValueToPrecision(percentage + mergedPrecision / 2, mergedPrecision);
roundedValue = clamp(roundedValue, mergedPrecision, 1);
starValue += roundedValue;

if (mergedPrecision > 1) {
return dealWithMergedPrecision(delta);
}

return starValue;
};

@@ -138,7 +166,7 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {
const [hoverValue, setHoverValue] = React.useState<number | null>(null);

const onHover = (event: React.MouseEvent<HTMLDivElement>, index: number) => {
const nextHoverValue = getStarValue(index, event.pageX);
const nextHoverValue = getStarValue(index, event.clientX);
if (nextHoverValue !== cleanedValue) {
setHoverValue(nextHoverValue);
setCleanedValue(null);
@@ -159,7 +187,7 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {

// =========================== Click ============================
const onClick = (event: React.MouseEvent | React.KeyboardEvent, index: number) => {
const newValue = getStarValue(index, (event as React.MouseEvent).pageX);
const newValue = getStarValue(index, (event as React.MouseEvent).clientX);
let isReset = false;
if (allowClear) {
isReset = newValue === value;
@@ -171,8 +199,7 @@ function Rate(props: RateProps, ref: React.Ref<RateRef>) {

const onInternalKeyDown: React.KeyboardEventHandler<HTMLUListElement> = (event) => {
const { keyCode } = event;
const reverse = direction === 'rtl';
const step = allowHalf ? 0.5 : 1;
const step = mergedPrecision;

if (keyboard) {
if (keyCode === KeyCode.RIGHT && value < count && !reverse) {
17 changes: 13 additions & 4 deletions src/Star.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import KeyCode from 'rc-util/lib/KeyCode';
import classNames from 'classnames';
import KeyCode from 'rc-util/lib/KeyCode';
Copy link
Member

Choose a reason for hiding this comment

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

既然都调整代码了,感觉可以直接把 hover 一些逻辑挪到 Star 里。以前放 Rate 计算其实不太内聚的

Copy link
Author

Choose a reason for hiding this comment

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

hover和click的一些逻辑存在耦合,不太好直接单拎出来

import React from 'react';

export interface StarProps {
value?: number;
@@ -73,7 +73,9 @@ function Star(props: StarProps, ref: React.Ref<HTMLLIElement>) {
classNameList.add(`${prefixCls}-focused`);
}
}

const memoWidth = React.useMemo(() => {
return Math.max(0, Math.min((value - index) * 100, 100));
}, [index, value]);
// >>>>> Node
const characterNode = typeof character === 'function' ? character(props) : character;
let start: React.ReactNode = (
@@ -88,7 +90,14 @@ function Star(props: StarProps, ref: React.Ref<HTMLLIElement>) {
aria-setsize={count}
tabIndex={disabled ? -1 : 0}
>
<div className={`${prefixCls}-first`}>{characterNode}</div>
<div
className={`${prefixCls}-first`}
style={{
width: `${memoWidth}%`,
}}
>
{characterNode}
</div>
<div className={`${prefixCls}-second`}>{characterNode}</div>
</div>
</li>
26 changes: 26 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -38,3 +38,29 @@ export function getOffsetLeft(el: HTMLElement) {
pos.left += getScroll(w);
return pos.left;
}

export const getBoundingClientRect = (element: HTMLElement) => {
return element.getBoundingClientRect();
};

function getDecimalPrecision(value: number) {
const decimalPart = value.toString().split('.')[1];
return decimalPart ? decimalPart.length : 0;
}

export function roundValueToPrecision(value: number, precision: number) {
if (value == null) {
return value;
}

const nearest = Math.round(value / precision) * precision;
return Number(nearest.toFixed(getDecimalPrecision(precision)));
}

export function clamp(
val: number,
min: number = Number.MIN_SAFE_INTEGER,
max: number = Number.MAX_SAFE_INTEGER,
): number {
return Math.max(min, Math.min(val, max));
}
Loading