@trail-ui/react
Version:
101 lines (98 loc) • 2.96 kB
JavaScript
import {
customToast
} from "./chunk-VRBQ3HMS.mjs";
import {
_Input
} from "./chunk-2ARW3G6Z.mjs";
import {
useFocusHandler
} from "./chunk-SSX6C2M6.mjs";
import {
useTableContext
} from "./chunk-LRSSE262.mjs";
// src/editable-table/editable-components/number-input.tsx
import { useEffect, useRef, useState } from "react";
import { jsx } from "react/jsx-runtime";
function EditableNumberInput(props) {
const [value, setValue] = useState("");
const [initialValue, setinitialValue] = useState("");
const inputRef = useRef(null);
const { updateData } = useTableContext(props.cell);
const { focusCurrentCell, isCurrentCellFocused, tableRef } = useFocusHandler(props.cell, false);
const columnMeta = props.cell.column.columnDef.meta;
const cancelAndExit = () => {
setValue(typeof props.cell.getValue() === "string" ? props.cell.getValue() : "");
requestAnimationFrame(() => {
props.onCancel();
});
};
const saveAndExit = () => {
const isEmpty = value !== initialValue && value.trim().length === 0;
if (isEmpty) {
customToast("Value cannot be empty", "error");
cancelAndExit();
return;
}
if (value !== initialValue) {
updateData(value);
}
requestAnimationFrame(() => {
props.onCancel();
});
};
const onKeyDown = (e) => {
const tableWrapper = document.querySelector(".editable-table");
const activeElement = document.activeElement;
if (activeElement && activeElement.tagName === "INPUT" && !(tableWrapper == null ? void 0 : tableWrapper.contains(activeElement)) || e.key === "Tab") {
return;
}
if (e.key === "Enter") {
saveAndExit();
e.preventDefault();
} else if (e.key === "Escape") {
cancelAndExit();
e.preventDefault();
}
};
const onBlur = (e) => {
var _a;
if (value === initialValue) {
cancelAndExit();
} else {
const relatedTarget = e.relatedTarget;
const isMovingWithinTable = relatedTarget && ((_a = inputRef.current) == null ? void 0 : _a.contains(relatedTarget));
if (!isMovingWithinTable) {
saveAndExit();
}
}
};
useEffect(() => {
setinitialValue(props.cell.getValue());
setValue(props.cell.getValue());
}, []);
useEffect(() => {
var _a, _b;
if (isCurrentCellFocused && ((_a = tableRef.current) == null ? void 0 : _a.contains(document.activeElement)))
(_b = inputRef.current) == null ? void 0 : _b.focus();
}, [isCurrentCellFocused]);
return /* @__PURE__ */ jsx(
_Input,
{
className: `max-w-[${props.cell.column.columnDef.size}px]`,
type: "number",
step: (columnMeta == null ? void 0 : columnMeta.step) || 0.25,
"aria-label": columnMeta.label,
ref: inputRef,
value,
onBlur,
onChange: (input) => {
setValue(input.target.value);
},
onKeyDown,
onFocus: focusCurrentCell
}
);
}
export {
EditableNumberInput
};