2024-07-30 20:44:19 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2024-09-11 18:26:43 +02:00
|
|
|
import { useRef } from "react";
|
2024-11-22 01:05:04 +01:00
|
|
|
import "./toggle.scss";
|
2024-07-30 20:44:19 +02:00
|
|
|
|
|
|
|
interface ToggleProps {
|
|
|
|
checked: boolean;
|
|
|
|
onChange: (value: boolean) => void;
|
|
|
|
label?: string;
|
|
|
|
id?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
const Toggle = ({ checked, onChange, label, id }: ToggleProps) => {
|
2024-09-11 18:26:43 +02:00
|
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
|
|
|
2024-07-30 20:44:19 +02:00
|
|
|
const handleChange = (e: any) => {
|
|
|
|
if (onChange != null) {
|
|
|
|
onChange(e.target.checked);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-09-11 18:26:43 +02:00
|
|
|
const handleLabelClick = () => {
|
|
|
|
if (inputRef.current) {
|
|
|
|
inputRef.current.click();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-07-30 20:44:19 +02:00
|
|
|
const inputId = id || `toggle-${Math.random().toString(36).substr(2, 9)}`;
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div className="check-toggle-wrapper">
|
2024-09-11 18:26:43 +02:00
|
|
|
<label htmlFor={inputId} className="checkbox-toggle">
|
|
|
|
<input id={inputId} type="checkbox" checked={checked} onChange={handleChange} ref={inputRef} />
|
2024-07-30 20:44:19 +02:00
|
|
|
<span className="slider" />
|
2024-09-11 18:26:43 +02:00
|
|
|
</label>
|
2024-07-30 20:44:19 +02:00
|
|
|
{label && (
|
2024-09-11 18:26:43 +02:00
|
|
|
<span className="toggle-label" onClick={handleLabelClick}>
|
2024-07-30 20:44:19 +02:00
|
|
|
{label}
|
2024-09-11 18:26:43 +02:00
|
|
|
</span>
|
2024-07-30 20:44:19 +02:00
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export { Toggle };
|