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

61 lines
2.0 KiB
TypeScript
Raw Normal View History

import { useEffect, type InputHTMLAttributes, type RefObject } from "preact/compat";
interface FormTextBoxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "onBlur" | "value"> {
id?: string;
2025-08-03 21:18:18 +03:00
currentValue?: string;
onChange?(newValue: string, validity: ValidityState): void;
onBlur?(newValue: string): void;
2025-08-05 19:06:47 +03:00
inputRef?: RefObject<HTMLInputElement>;
2025-08-03 21:18:18 +03:00
}
export default function FormTextBox({ inputRef, className, type, currentValue, onChange, onBlur, autoFocus, ...rest}: FormTextBoxProps) {
useEffect(() => {
if (autoFocus) {
inputRef?.current?.focus();
}
}, []);
function applyLimits(value: string) {
if (type === "number") {
const { min, max } = rest;
const currentValueNum = parseInt(value, 10);
if (min && currentValueNum < parseInt(String(min), 10)) {
return String(min);
} else if (max && currentValueNum > parseInt(String(max), 10)) {
return String(max);
}
}
return value;
}
2025-08-03 21:18:18 +03:00
return (
2025-08-04 21:17:35 +03:00
<input
2025-08-05 19:06:47 +03:00
ref={inputRef}
className={`form-control ${className ?? ""}`}
2025-08-14 21:31:09 +03:00
type={type ?? "text"}
2025-08-04 21:17:35 +03:00
value={currentValue}
onInput={onChange && (e => {
const target = e.currentTarget;
const currentValue = applyLimits(e.currentTarget.value);
onChange?.(currentValue, target.validity);
})}
onBlur={(e => {
const currentValue = applyLimits(e.currentTarget.value);
e.currentTarget.value = currentValue;
onBlur?.(currentValue);
})}
2025-08-14 21:31:09 +03:00
{...rest}
/>
2025-08-03 21:18:18 +03:00
);
2025-08-14 21:31:09 +03:00
}
export function FormTextBoxWithUnit(props: FormTextBoxProps & { unit: string }) {
return (
<label class="input-group tn-number-unit-pair">
<FormTextBox {...props} />
<span class="input-group-text">{props.unit}</span>
</label>
2025-08-14 21:31:09 +03:00
)
}