Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
import { Tooltip } from "bootstrap";
import { ComponentChildren, CSSProperties } from "preact";
import { useCallback, useEffect, useMemo, useRef } from "preact/hooks";
import { escapeQuotes } from "../../services/utils";
import { useUniqueName } from "./hooks";
interface FormCheckboxProps {
name?: string;
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;
/**
* Shows the native mixed state (a dash), e.g. for a parent whose children are partially selected.
* `indeterminate` is a DOM property only (there is no HTML attribute), so it is applied via a ref.
*/
indeterminate?: boolean;
disabled?: boolean;
/** `-1` keeps the box out of the tab order, for one that a pointer reaches through its row. */
tabIndex?: number;
onChange(newValue: boolean): void;
containerStyle?: CSSProperties;
}
export default function FormCheckbox({ name, disabled, label, currentValue, indeterminate, tabIndex, onChange, hint, containerStyle }: FormCheckboxProps) {
const labelRef = useRef<HTMLLabelElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const id = useUniqueName(name);
useEffect(() => {
if (inputRef.current) {
inputRef.current.indeterminate = indeterminate ?? false;
}
}, [indeterminate]);
useEffect(() => {
if (!hint || !labelRef.current) return;
const tooltipInstance = Tooltip.getOrCreateInstance(labelRef.current, {
html: true,
customClass: "tooltip-top"
});
return () => tooltipInstance?.dispose();
}, [hint]);
const labelStyle = useMemo(() =>
hint ? { textDecoration: "underline dotted var(--main-text-color)" } : undefined,
[hint]
);
const handleChange = useCallback((e: Event) => {
onChange((e.target as HTMLInputElement).checked);
}, [onChange]);
const titleText = useMemo(() => hint ? escapeQuotes(hint) : undefined, [hint]);
return (
<div className={`form-checkbox ${disabled ? "disabled" : ""}`} style={containerStyle}>
<label
className="form-check-label tn-checkbox"
style={labelStyle}
title={titleText}
ref={labelRef}
>
<input
id={id}
ref={inputRef}
className="form-check-input"
type="checkbox"
name={id}
checked={currentValue || false}
value="1"
disabled={disabled}
tabIndex={tabIndex}
onChange={handleChange} />
{label}
</label>
</div>
);
}