Files
Trilium/apps/client/src/widgets/react/FormCheckbox.tsx

69 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Tooltip } from "bootstrap";
2025-12-23 13:06:33 +02:00
import { ComponentChildren, CSSProperties } from "preact";
import { useCallback, useEffect, useMemo, useRef } from "preact/hooks";
2025-12-21 13:19:42 +02:00
import { escapeQuotes } from "../../services/utils";
import { useUniqueName } from "./hooks";
2025-08-03 21:18:18 +03:00
interface FormCheckboxProps {
name?: string;
2025-08-07 19:20:35 +03:00
label: string | ComponentChildren;
/**
* If set, the checkbox label will be underlined and dotted, indicating a hint. When hovered, it will show the hint text.
*/
hint?: string;
currentValue: boolean;
2025-08-05 18:05:41 +03:00
disabled?: boolean;
2025-08-03 21:18:18 +03:00
onChange(newValue: boolean): void;
containerStyle?: CSSProperties;
2025-08-03 21:18:18 +03:00
}
2025-12-21 13:19:42 +02:00
export default function FormCheckbox({ name, disabled, label, currentValue, onChange, hint, containerStyle }: FormCheckboxProps) {
const labelRef = useRef<HTMLLabelElement>(null);
const id = useUniqueName(name);
useEffect(() => {
if (!hint || !labelRef.current) return;
2025-12-21 13:19:42 +02:00
const tooltipInstance = Tooltip.getOrCreateInstance(labelRef.current, {
html: true,
customClass: "tooltip-top"
});
2025-12-21 13:19:42 +02:00
return () => tooltipInstance?.dispose();
}, [hint]);
2025-12-21 13:19:42 +02:00
const labelStyle = useMemo(() =>
hint ? { textDecoration: "underline dotted var(--main-text-color)" } : undefined,
2025-12-21 13:19:42 +02:00
[hint]
);
2025-12-21 13:19:42 +02:00
const handleChange = useCallback((e: Event) => {
onChange((e.target as HTMLInputElement).checked);
}, [onChange]);
2025-12-21 13:19:42 +02:00
const titleText = useMemo(() => hint ? escapeQuotes(hint) : undefined, [hint]);
2025-08-03 21:18:18 +03:00
return (
<div className={`form-checkbox ${disabled ? "disabled" : ""}`} style={containerStyle}>
<label
className="form-check-label tn-checkbox"
style={labelStyle}
title={titleText}
ref={labelRef}
>
2025-08-03 21:18:18 +03:00
<input
id={id}
2025-08-03 21:18:18 +03:00
className="form-check-input"
type="checkbox"
name={id}
2025-08-03 21:18:18 +03:00
checked={currentValue || false}
value="1"
2025-08-05 18:05:41 +03:00
disabled={disabled}
onChange={handleChange} />
2025-08-03 21:18:18 +03:00
{label}
</label>
</div>
);
2025-12-21 13:19:42 +02:00
}