UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

187 lines 11 kB
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; }; import { jsx as _jsx, jsxs as _jsxs } from "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/>. */ import classNames from 'classnames'; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react'; import { useFocusWithin } from 'react-aria'; import { useSemicontrolledState } from '../_common/use-semi-controlled-state'; import { needleWarningMessage, randomId } from '../_common/utils'; import { IconButton } from '../icon-button'; import { CheckIconOutline, PencilIconOutline, XMarkIconOutline, } from '../icons'; import { Typography } from '../typography'; import { getIconStyle, getMinHeight } from './utils'; // The input should not be less than this (it does shrink if container is smaller though). const MINIMUM_WIDTH = 320; export 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] = useState(false); const [currentValue, setCurrentValue] = useSemicontrolledState({ isControlled: value !== undefined, onChange, state: (_b = value !== null && value !== void 0 ? value : defaultValue) !== null && _b !== void 0 ? _b : '', }); const [previousConfirmedValue, setPreviousConfirmedValue] = useState(currentValue); const mirrorRef = useRef(null); const containerRef = 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 = useRef(false); // Validate controlled mode requirements useEffect(() => { if (value !== undefined && onChange === undefined) { needleWarningMessage('onChange prop should be supplied when using controlled mode (value prop is provided).'); } }, [value, onChange]); const { focusWithinProps } = useFocusWithin({ onBlurWithin: () => { if (blurWithinRef.current) { return; } if (blurBehavior === 'confirm') { onConfirmHandler(); return; } if (blurBehavior === 'cancel') { onCancelHandler(); return; } }, }); const resetToDefaults = 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 = useCallback(() => { // Only reset edit mode if isEditing is not controlled (undefined) if (isEditing === undefined) { blurWithinRef.current = true; setEditMode(false); } }, [isEditing]); const onConfirmHandler = 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 = useCallback((event) => { onCancel === null || onCancel === void 0 ? void 0 : onCancel(event); resetToDefaults(); }, [onCancel, resetToDefaults]); const inputID = useMemo(() => { var _a; return (_a = inputProps === null || inputProps === void 0 ? void 0 : inputProps.id) !== null && _a !== void 0 ? _a : randomId(12); }, [inputProps === null || inputProps === void 0 ? void 0 : inputProps.id]); const handleKeyDown = 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 = useCallback((e) => { const newValue = e.target.value; setCurrentValue(newValue); }, [setCurrentValue]); const isInEditMode = isEditing !== null && isEditing !== void 0 ? isEditing : hasEditMode; const handleEditClick = useCallback(() => { if (isDisabled === false) { setEditMode(true); blurWithinRef.current = false; } }, [isDisabled]); const updateInputWidth = 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 useLayoutEffect(() => { updateInputWidth(); }, [updateInputWidth, isInEditMode, currentValue]); const displayText = currentValue || placeholder; return (_jsxs(Typography, Object.assign({ as: as !== null && as !== void 0 ? as : 'div', variant: typographyVariant, className: classNames('ndl-inline-edit', className, { 'ndl-disabled': isDisabled, 'ndl-fluid': isFluid, }), style: style, ref: ref, htmlAttributes: htmlAttributes }, restProps, { children: [Boolean(label) && _jsx("label", { htmlFor: inputID, children: label }), isInEditMode === true ? (_jsxs("div", Object.assign({ className: "ndl-inline-edit-container", ref: containerRef }, focusWithinProps, { children: [_jsx("span", { "aria-hidden": true, className: "ndl-inline-edit-mirror", ref: mirrorRef, children: displayText }), _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: classNames('ndl-inline-edit-input', inputProps === null || inputProps === void 0 ? void 0 : inputProps.className), id: inputID, value: currentValue, onChange: handleInputChange, onKeyDown: handleKeyDown, placeholder: placeholder })), _jsxs("div", { className: "ndl-inline-edit-buttons", children: [_jsx(IconButton, { description: "Accept", tooltipProps: { root: { placement: 'bottom' }, }, onClick: onConfirmHandler, size: "small", isFloating: true, htmlAttributes: { onMouseDown: () => { blurWithinRef.current = true; }, }, children: _jsx(CheckIconOutline, {}) }), _jsx(IconButton, { description: "Cancel", tooltipProps: { root: { placement: 'bottom' }, }, onClick: (event) => onCancelHandler(event), size: "small", isFloating: true, htmlAttributes: { onMouseDown: () => { blurWithinRef.current = true; }, }, children: _jsx(XMarkIconOutline, {}) })] })] }))) : (_jsxs("button", { className: classNames('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: getMinHeight(typographyVariant), }, children: [_jsx("span", { className: "ndl-inline-edit-text", children: displayText }), hasEditIcon && (_jsx(PencilIconOutline, { className: "ndl-inline-edit-pencil-icon", style: getIconStyle(typographyVariant) }))] }))] }))); }; //# sourceMappingURL=InlineEdit.js.map