@neo4j-ndl/react
Version:
React implementation of Neo4j Design System
194 lines • 11.8 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InlineEdit = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const classnames_1 = __importDefault(require("classnames"));
const react_1 = require("react");
const react_aria_1 = require("react-aria");
const use_semi_controlled_state_1 = require("../_common/use-semi-controlled-state");
const utils_1 = require("../_common/utils");
const icon_button_1 = require("../icon-button");
const icons_1 = require("../icons");
const typography_1 = require("../typography");
const utils_2 = require("./utils");
// The input should not be less than this (it does shrink if container is smaller though).
const MINIMUM_WIDTH = 320;
const InlineEdit = (_a) => {
var _b;
var { as, className, defaultValue, htmlAttributes, label, onChange, onCancel, onConfirm, ref, style, value, hasEditIcon = false, inputProps, isDisabled = false, isEditing, blurBehavior = 'confirm', isFluid = false, typographyVariant = 'subheading-medium', placeholder } = _a, restProps = __rest(_a, ["as", "className", "defaultValue", "htmlAttributes", "label", "onChange", "onCancel", "onConfirm", "ref", "style", "value", "hasEditIcon", "inputProps", "isDisabled", "isEditing", "blurBehavior", "isFluid", "typographyVariant", "placeholder"]);
const [hasEditMode, setEditMode] = (0, react_1.useState)(false);
const [currentValue, setCurrentValue] = (0, use_semi_controlled_state_1.useSemicontrolledState)({
isControlled: value !== undefined,
onChange,
state: (_b = value !== null && value !== void 0 ? value : defaultValue) !== null && _b !== void 0 ? _b : '',
});
const [previousConfirmedValue, setPreviousConfirmedValue] = (0, react_1.useState)(currentValue);
const mirrorRef = (0, react_1.useRef)(null);
const containerRef = (0, react_1.useRef)(null);
/**
* This ref is used to prevent the blur behavior from being triggered on mouse down events
* on the confirm and cancel buttons. So when true, the blur behavior is not triggered.
* This is needed due to Webkit browsers (like Safari) triggering blur on mouse down events.
*
* It is also used to prevent the blur behavior from being triggered after the component exits edit mode without blur.
* This bug caused the handler to be called when something was focused after confirming.
*/
const blurWithinRef = (0, react_1.useRef)(false);
// Validate controlled mode requirements
(0, react_1.useEffect)(() => {
if (value !== undefined && onChange === undefined) {
(0, utils_1.needleWarningMessage)('onChange prop should be supplied when using controlled mode (value prop is provided).');
}
}, [value, onChange]);
const { focusWithinProps } = (0, react_aria_1.useFocusWithin)({
onBlurWithin: () => {
if (blurWithinRef.current) {
return;
}
if (blurBehavior === 'confirm') {
onConfirmHandler();
return;
}
if (blurBehavior === 'cancel') {
onCancelHandler();
return;
}
},
});
const resetToDefaults = (0, react_1.useCallback)(() => {
// In controlled mode, don't reset the value - let the parent manage it
// In uncontrolled mode, reset to default value
if (value === undefined) {
setCurrentValue(previousConfirmedValue !== null && previousConfirmedValue !== void 0 ? previousConfirmedValue : '');
}
// Only reset edit mode if isEditing is not controlled (undefined)
if (isEditing === undefined) {
blurWithinRef.current = true;
setEditMode(false);
}
}, [previousConfirmedValue, isEditing, setCurrentValue, value]);
const resetEditState = (0, react_1.useCallback)(() => {
// Only reset edit mode if isEditing is not controlled (undefined)
if (isEditing === undefined) {
blurWithinRef.current = true;
setEditMode(false);
}
}, [isEditing]);
const onConfirmHandler = (0, react_1.useCallback)((event) => __awaiter(void 0, void 0, void 0, function* () {
setPreviousConfirmedValue(currentValue);
onConfirm === null || onConfirm === void 0 ? void 0 : onConfirm(currentValue, event);
resetEditState();
}), [onConfirm, currentValue, resetEditState]);
const onCancelHandler = (0, react_1.useCallback)((event) => {
onCancel === null || onCancel === void 0 ? void 0 : onCancel(event);
resetToDefaults();
}, [onCancel, resetToDefaults]);
const inputID = (0, react_1.useMemo)(() => {
var _a;
return (_a = inputProps === null || inputProps === void 0 ? void 0 : inputProps.id) !== null && _a !== void 0 ? _a : (0, utils_1.randomId)(12);
}, [inputProps === null || inputProps === void 0 ? void 0 : inputProps.id]);
const handleKeyDown = (0, react_1.useCallback)((e) => {
if (['Enter', 'Escape'].includes(e.key)) {
if (e.key === 'Enter') {
onConfirmHandler();
}
if (e.key === 'Escape') {
onCancelHandler();
}
e.preventDefault();
e.stopPropagation();
}
}, [onConfirmHandler, onCancelHandler]);
const handleInputChange = (0, react_1.useCallback)((e) => {
const newValue = e.target.value;
setCurrentValue(newValue);
}, [setCurrentValue]);
const isInEditMode = isEditing !== null && isEditing !== void 0 ? isEditing : hasEditMode;
const handleEditClick = (0, react_1.useCallback)(() => {
if (isDisabled === false) {
setEditMode(true);
blurWithinRef.current = false;
}
}, [isDisabled]);
const updateInputWidth = (0, react_1.useCallback)(() => {
if (mirrorRef.current && containerRef.current && !isFluid) {
const mirrorWidth = mirrorRef.current.offsetWidth;
const newWidth = Math.max(mirrorWidth, MINIMUM_WIDTH);
containerRef.current.style.width = `${newWidth}px`;
}
}, [mirrorRef, containerRef, isFluid]);
// Width calculation effect
(0, react_1.useLayoutEffect)(() => {
updateInputWidth();
}, [updateInputWidth, isInEditMode, currentValue]);
const displayText = currentValue || placeholder;
return ((0, jsx_runtime_1.jsxs)(typography_1.Typography, Object.assign({ as: as !== null && as !== void 0 ? as : 'div', variant: typographyVariant, className: (0, classnames_1.default)('ndl-inline-edit', className, {
'ndl-disabled': isDisabled,
'ndl-fluid': isFluid,
}), style: style, ref: ref, htmlAttributes: htmlAttributes }, restProps, { children: [Boolean(label) && (0, jsx_runtime_1.jsx)("label", { htmlFor: inputID, children: label }), isInEditMode === true ? ((0, jsx_runtime_1.jsxs)("div", Object.assign({ className: "ndl-inline-edit-container", ref: containerRef }, focusWithinProps, { children: [(0, jsx_runtime_1.jsx)("span", { "aria-hidden": true, className: "ndl-inline-edit-mirror", ref: mirrorRef, children: displayText }), (0, jsx_runtime_1.jsx)("input", Object.assign({}, inputProps, {
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus: true, "aria-label": typeof label === 'string' ? label : 'Inline edit input', className: (0, classnames_1.default)('ndl-inline-edit-input', inputProps === null || inputProps === void 0 ? void 0 : inputProps.className), id: inputID, value: currentValue, onChange: handleInputChange, onKeyDown: handleKeyDown, placeholder: placeholder })), (0, jsx_runtime_1.jsxs)("div", { className: "ndl-inline-edit-buttons", children: [(0, jsx_runtime_1.jsx)(icon_button_1.IconButton, { description: "Accept", tooltipProps: {
root: { placement: 'bottom' },
}, onClick: onConfirmHandler, size: "small", isFloating: true, htmlAttributes: {
onMouseDown: () => {
blurWithinRef.current = true;
},
}, children: (0, jsx_runtime_1.jsx)(icons_1.CheckIconOutline, {}) }), (0, jsx_runtime_1.jsx)(icon_button_1.IconButton, { description: "Cancel", tooltipProps: {
root: { placement: 'bottom' },
}, onClick: (event) => onCancelHandler(event), size: "small", isFloating: true, htmlAttributes: {
onMouseDown: () => {
blurWithinRef.current = true;
},
}, children: (0, jsx_runtime_1.jsx)(icons_1.XMarkIconOutline, {}) })] })] }))) : ((0, jsx_runtime_1.jsxs)("button", { className: (0, classnames_1.default)('ndl-inline-idle-container', {
'n-text-neutral-text-weaker': displayText === placeholder,
'ndl-disabled': isDisabled,
'ndl-has-edit-icon': hasEditIcon,
}), "aria-disabled": isDisabled, disabled: isDisabled, onClick: handleEditClick, style: {
minHeight: (0, utils_2.getMinHeight)(typographyVariant),
}, children: [(0, jsx_runtime_1.jsx)("span", { className: "ndl-inline-edit-text", children: displayText }), hasEditIcon && ((0, jsx_runtime_1.jsx)(icons_1.PencilIconOutline, { className: "ndl-inline-edit-pencil-icon", style: (0, utils_2.getIconStyle)(typographyVariant) }))] }))] })));
};
exports.InlineEdit = InlineEdit;
//# sourceMappingURL=InlineEdit.js.map