Switch 3D
Yaya12085
Off
"use client";
import { type CSSProperties, useId } from "react";
/**
* Switch 3D: a white pill with a sunken track and a steel knob that rolls
* across, the whole switch tilting toward you on hover. Pure CSS on a real
* checkbox. Yaya12085's switch on uiverse.io (bright-dolphin-91).
*
* <Switch3D label="Dark mode" />
* <Switch3D checked={on} onChange={setOn} size={0.6} />
*/
export type Switch3DProps = {
/** Read by screen readers; the switch itself has no text. */
label: string;
checked?: boolean;
defaultChecked?: boolean;
onChange?: (checked: boolean) => void;
/** 1 is 120×60px. */
size?: number;
className?: string;
style?: CSSProperties;
};
const CSS = `
.zs-sw{display:inline-block;zoom:var(--z)}
.zs-sw input{position:absolute;opacity:0;width:1px;height:1px;pointer-events:none}
.zs-sw label{height:60px;width:120px;background-color:#fff;border-radius:30px;display:flex;align-items:center;cursor:pointer;position:relative;
box-shadow:inset 0 0 5px 4px #fff,inset 0 0 20px 1px rgba(0,0,0,.488),10px 20px 30px rgba(0,0,0,.096),inset 0 0 0 3px rgba(0,0,0,.3);
transition:transform .4s}
.zs-sw label:hover{transform:perspective(100px) rotateX(5deg) rotateY(-5deg)}
.zs-sw input:checked~label:hover{transform:perspective(100px) rotateX(-5deg) rotateY(5deg)}
.zs-sw input:focus-visible~label{outline:2px solid #2997ff;outline-offset:4px}
.zs-sw label::before{position:absolute;content:"";height:40px;width:40px;border-radius:50%;left:10px;background-color:#000;
background-image:linear-gradient(130deg,#757272 10%,#fff 11%,#726f6f 62%);
box-shadow:0 2px 1px rgba(0,0,0,.3),10px 10px 10px rgba(0,0,0,.3);transition:.4s}
.zs-sw input:checked~label::before{left:70px;background-color:#000;background-image:linear-gradient(315deg,#000 0%,#414141 70%)}
@media (prefers-reduced-motion:reduce){.zs-sw label,.zs-sw label::before{transition:none}}
`;
export function Switch3D({ label, checked, defaultChecked, onChange, size = 1, className, style }: Switch3DProps) {
const id = useId();
return (
<span className={`zs-sw${className ? ` ${className}` : ""}`} style={{ "--z": size, ...style } as CSSProperties}>
<style>{CSS}</style>
<input
id={id}
type="checkbox"
role="switch"
aria-label={label}
checked={checked}
defaultChecked={defaultChecked}
onChange={(e) => onChange?.(e.target.checked)}
/>
<label htmlFor={id} />
</span>
);
}