UNPKG

@penaprieto/design-system

Version:

Multi-brand React design system with design tokens from Figma

57 lines (56 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Rating = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); require("./Rating.css"); const Icon_1 = require("../Icon"); const Rating = ({ value: controlledValue, defaultValue = 0, max = 5, size = 'medium', readOnly = false, disabled = false, allowHalf = false, onChange, showValue = false, className = '', }) => { const isControlled = controlledValue !== undefined; const [internalValue, setInternalValue] = (0, react_1.useState)(defaultValue); const [hoverValue, setHoverValue] = (0, react_1.useState)(null); const value = isControlled ? controlledValue : internalValue; const displayValue = hoverValue !== null ? hoverValue : value; const handleClick = (starValue) => { if (readOnly || disabled) return; if (!isControlled) { setInternalValue(starValue); } onChange === null || onChange === void 0 ? void 0 : onChange(starValue); }; const handleMouseEnter = (starValue) => { if (readOnly || disabled) return; setHoverValue(starValue); }; const handleMouseLeave = () => { if (readOnly || disabled) return; setHoverValue(null); }; const getStarFill = (index) => { const starValue = index + 1; if (displayValue >= starValue) return 'full'; if (allowHalf && displayValue >= starValue - 0.5) return 'half'; return 'empty'; }; const rootClassName = [ 'ds-rating', `ds-rating--${size}`, readOnly && 'ds-rating--readonly', disabled && 'ds-rating--disabled', className, ] .filter(Boolean) .join(' '); return ((0, jsx_runtime_1.jsxs)("div", { className: rootClassName, children: [(0, jsx_runtime_1.jsx)("div", { className: "ds-rating__stars", onMouseLeave: handleMouseLeave, children: Array.from({ length: max }).map((_, index) => { const fill = getStarFill(index); const fullValue = index + 1; const halfValue = index + 0.5; return ((0, jsx_runtime_1.jsxs)("div", { className: "ds-rating__star-wrapper", onMouseEnter: () => handleMouseEnter(fullValue), children: [allowHalf && ((0, jsx_runtime_1.jsx)("div", { className: "ds-rating__star-half", onClick: () => handleClick(halfValue), onMouseEnter: () => handleMouseEnter(halfValue) })), (0, jsx_runtime_1.jsx)("div", { className: `ds-rating__star ds-rating__star--${fill}`, onClick: () => handleClick(fullValue), children: (0, jsx_runtime_1.jsx)(Icon_1.Icon, { name: fill === 'full' ? 'star-filled' : 'star', size: size === 'small' ? 16 : size === 'large' ? 32 : 24 }) })] }, index)); }) }), showValue && ((0, jsx_runtime_1.jsx)("span", { className: "ds-rating__value", children: value.toFixed(allowHalf ? 1 : 0) }))] })); }; exports.Rating = Rating;