tharikida-ui
Version:
A modern, lightweight React UI component library with built-in theming, accessibility, and full TypeScript support. Create beautiful, responsive, and customizable web apps faster with ready-to-use components for any project.
72 lines (71 loc) • 3.34 kB
JavaScript
"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { useTheme } from "../../theme/ThemeProvider";
const ToggleSwitch = ({ checked, onChange, styles, className = "", disabled = false, }) => {
const theme = useTheme();
const [internalChecked, setInternalChecked] = useState(false);
const isControlled = typeof checked === "boolean";
const currentChecked = isControlled ? checked : internalChecked;
const switchWidth = 40;
const switchHeight = 22;
const knobSize = 15;
const spacing = (switchHeight - knobSize) / 2;
// Handles toggle action
const handleChange = (event) => {
if (!isControlled) {
setInternalChecked(event.target.checked);
}
onChange?.(event);
};
// Compute shadow offsets based on checked state
const computedShadowOffsetX = currentChecked ? "0px" : theme.shadowOffsetX;
const computedShadowOffsetY = currentChecked ? "0px" : theme.shadowOffsetY;
return (_jsxs("label", { className: `tharikida-toggle-switch ${className}`, style: {
display: "inline-block",
position: "relative",
width: switchWidth,
height: switchHeight,
...styles,
opacity: disabled ? 0.6 : 1,
cursor: disabled ? "not-allowed" : "pointer",
fontFamily: theme.fontFamily,
fontSize: theme.fontSize,
fontWeight: theme.fontWeight,
lineHeight: theme.lineHeight,
letterSpacing: theme.letterSpacing,
padding: theme.padding,
margin: theme.margin,
transition: theme.transitionDuration,
}, children: [_jsx("input", { type: "checkbox", checked: currentChecked, onChange: handleChange, disabled: disabled, style: {
opacity: 0,
width: 0,
height: 0,
position: "absolute",
} }), _jsx("span", { style: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
background: currentChecked
? theme.primaryColor
: theme.backgroundColor,
borderRadius: switchHeight / 2,
transitionDuration: theme.transitionDuration,
border: `${theme.borderWidth} ${theme.borderStyle} ${theme.borderColor}`,
display: "flex",
alignItems: "center",
justifyContent: currentChecked ? "flex-end" : "flex-start",
padding: spacing,
boxShadow: `${theme.shadowInset ? "inset " : ""}${computedShadowOffsetX} ${computedShadowOffsetY} ${theme.shadowBlur} ${theme.shadowSpread} ${theme.shadowColor}`,
}, children: _jsx("span", { style: {
width: knobSize,
height: knobSize,
background: theme.textColor,
borderRadius: "50%",
transition: `all ${theme.transitionDuration}`,
boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
} }) })] }));
};
export default ToggleSwitch;