{"version":3,"file":"InlineEdit.mjs","names":[],"sources":["../../../src/inline-edit/InlineEdit.tsx"],"sourcesContent":["/*!\n *\n *  Copyright (c) \"Neo4j\"\n *  Neo4j Sweden AB [http://neo4j.com]\n *\n *  This file is part of Neo4j.\n *\n *  Neo4j is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\nimport classNames from 'classnames';\nimport type React from 'react';\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\nimport { useFocusWithin } from 'react-aria';\n\nimport {\n  type HtmlAttributes,\n  type PolymorphicCommonProps,\n} from '../_common/types';\nimport { useSemicontrolledState } from '../_common/use-semi-controlled-state';\nimport { needleWarningMessage, randomId } from '../_common/utils';\nimport { IconButton } from '../icon-button';\nimport { CheckIconOutline } from '../icons/generated/heroIcons/CheckIconOutline';\nimport { PencilIconOutline } from '../icons/generated/heroIcons/PencilIconOutline';\nimport { XMarkIconOutline } from '../icons/generated/heroIcons/XMarkIconOutline';\nimport { Typography } from '../typography';\nimport { type TypographyVariants } from '../typography';\nimport { getIconStyle, getMinHeight } from './utils';\n\ntype InlineEditProps = {\n  /** Label text */\n  label?: ReactNode;\n\n  /**\n   * The aria label for the input. If not provided, defaults to the `label` text, or a generic\n   * \"Inline edit input\" string as a last resort.\n   */\n  ariaLabel?: string;\n\n  /**\n   * The typographyVariant of the component applied to Typography as its variant.\n   * @default subheading-medium\n   */\n  typographyVariant?: TypographyVariants;\n\n  /**\n   * The default input value. Use for an uncontrolled component.\n   */\n  defaultValue?: string;\n\n  /**\n   * The input value. Makes the component controlled.\n   */\n  value?: string;\n\n  /**\n   * Callback when the input value changes. Must be used when the component is controlled.\n   */\n  onChange?: (value: string) => void;\n\n  /**\n   * Placeholder text displayed when the input is empty.\n   */\n  placeholder: string;\n\n  /**\n   * @default false\n   */\n  isDisabled?: boolean;\n\n  /**\n   * If edit pencil icon should be visible on hover\n   * @default false\n   */\n  hasEditIcon?: boolean;\n\n  /**\n   * If the input is in editing mode\n   * Used in a stateless inline edit\n   * @default undefined\n   */\n  isEditing?: boolean;\n\n  /** Callback when confirm icon button is pressed */\n  onConfirm?: (\n    value: string,\n    event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n  ) => void;\n\n  /** Callback when cancel icon button is pressed */\n  onCancel?: (\n    event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n  ) => void;\n\n  /**\n   * What the input should do on blur\n   * - \"confirm\" will confirm the value\n   * - \"cancel\" will cancel the value\n   * - \"none\" will do nothing\n   * @default \"confirm\"\n   */\n  blurBehavior?: 'confirm' | 'cancel' | 'none';\n\n  /** props applied to the internal input element */\n  inputProps?: HtmlAttributes<'input'>;\n\n  /**\n   * If the input is fluid\n   * @default false\n   */\n  isFluid?: boolean;\n};\n\n// The input should not be less than this (it does shrink if container is smaller though).\nconst MINIMUM_WIDTH = 320;\n\nexport const InlineEdit = <T extends React.ElementType = 'div'>({\n  as,\n  className,\n  defaultValue,\n  htmlAttributes,\n  label,\n  ariaLabel,\n  onChange,\n  onCancel,\n  onConfirm,\n  ref,\n  style,\n  value,\n  hasEditIcon = false,\n  inputProps,\n  isDisabled = false,\n  isEditing,\n  blurBehavior = 'confirm',\n  isFluid = false,\n  typographyVariant = 'subheading-medium',\n  placeholder,\n  ...restProps\n}: PolymorphicCommonProps<T, InlineEditProps>) => {\n  const [hasEditMode, setEditMode] = useState(false);\n\n  const [currentValue, setCurrentValue] = useSemicontrolledState({\n    isControlled: value !== undefined,\n    onChange,\n    state: value ?? defaultValue ?? '',\n  });\n  const [previousConfirmedValue, setPreviousConfirmedValue] =\n    useState(currentValue);\n\n  const mirrorRef = useRef<HTMLSpanElement>(null);\n  const containerRef = useRef<HTMLDivElement>(null);\n  /**\n   * This ref is used to prevent the blur behavior from being triggered on mouse down events\n   * on the confirm and cancel buttons. So when true, the blur behavior is not triggered.\n   * This is needed due to Webkit browsers (like Safari) triggering blur on mouse down events.\n   *\n   * It is also used to prevent the blur behavior from being triggered after the component exits edit mode without blur.\n   * This bug caused the handler to be called when something was focused after confirming.\n   */\n  const blurWithinRef = useRef(false);\n\n  // Validate controlled mode requirements\n  useEffect(() => {\n    if (value !== undefined && onChange === undefined) {\n      needleWarningMessage(\n        'onChange prop should be supplied when using controlled mode (value prop is provided).',\n      );\n    }\n  }, [value, onChange]);\n\n  const { focusWithinProps } = useFocusWithin({\n    onBlurWithin: () => {\n      if (blurWithinRef.current) {\n        return;\n      }\n\n      if (blurBehavior === 'confirm') {\n        onConfirmHandler();\n        return;\n      }\n      if (blurBehavior === 'cancel') {\n        onCancelHandler();\n        return;\n      }\n    },\n  });\n\n  const resetToDefaults = useCallback(() => {\n    // In controlled mode, don't reset the value - let the parent manage it\n    // In uncontrolled mode, reset to default value\n    if (value === undefined) {\n      setCurrentValue(previousConfirmedValue ?? '');\n    }\n    // Only reset edit mode if isEditing is not controlled (undefined)\n    if (isEditing === undefined) {\n      blurWithinRef.current = true;\n      setEditMode(false);\n    }\n  }, [previousConfirmedValue, isEditing, setCurrentValue, value]);\n\n  const resetEditState = useCallback(() => {\n    // Only reset edit mode if isEditing is not controlled (undefined)\n    if (isEditing === undefined) {\n      blurWithinRef.current = true;\n      setEditMode(false);\n    }\n  }, [isEditing]);\n\n  const onConfirmHandler = useCallback(\n    async (\n      event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n    ) => {\n      setPreviousConfirmedValue(currentValue);\n      onConfirm?.(currentValue, event);\n      resetEditState();\n    },\n    [onConfirm, currentValue, resetEditState],\n  );\n\n  const onCancelHandler = useCallback(\n    (\n      event?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>,\n    ) => {\n      onCancel?.(event);\n      resetToDefaults();\n    },\n    [onCancel, resetToDefaults],\n  );\n\n  const inputID = useMemo(() => {\n    return inputProps?.id ?? randomId(12);\n  }, [inputProps?.id]);\n\n  const handleKeyDown = useCallback(\n    (event: React.KeyboardEvent) => {\n      if (['Enter', 'Escape'].includes(event.key)) {\n        if (event.key === 'Enter') {\n          onConfirmHandler();\n        }\n        if (event.key === 'Escape') {\n          onCancelHandler();\n        }\n        event.preventDefault();\n        event.stopPropagation();\n      }\n    },\n    [onConfirmHandler, onCancelHandler],\n  );\n\n  const handleInputChange = useCallback(\n    (event: React.ChangeEvent<HTMLInputElement>) => {\n      const newValue = event.target.value;\n      setCurrentValue(newValue);\n    },\n    [setCurrentValue],\n  );\n\n  const isInEditMode = isEditing ?? hasEditMode;\n\n  const handleEditClick = useCallback(() => {\n    if (isDisabled === false) {\n      setEditMode(true);\n      blurWithinRef.current = false;\n    }\n  }, [isDisabled]);\n\n  const updateInputWidth = useCallback(() => {\n    if (mirrorRef.current && containerRef.current && !isFluid) {\n      const mirrorWidth = mirrorRef.current.offsetWidth;\n      const newWidth = Math.max(mirrorWidth, MINIMUM_WIDTH);\n      containerRef.current.style.width = `${newWidth}px`;\n    }\n  }, [mirrorRef, containerRef, isFluid]);\n\n  // Width calculation effect\n  useLayoutEffect(() => {\n    updateInputWidth();\n  }, [updateInputWidth, isInEditMode, currentValue]);\n\n  const displayText = currentValue || placeholder;\n  const buttonAriaLabel = `${displayText}, edit`;\n  const inputAriaLabel =\n    ariaLabel ?? (typeof label === 'string' ? label : 'Inline edit input');\n\n  return (\n    <Typography\n      as={as ?? 'div'}\n      variant={typographyVariant}\n      className={classNames('ndl-inline-edit', className, {\n        'ndl-disabled': isDisabled,\n        'ndl-fluid': isFluid,\n      })}\n      style={style}\n      ref={ref}\n      htmlAttributes={htmlAttributes}\n      {...restProps}\n    >\n      {Boolean(label) && <label htmlFor={inputID}>{label}</label>}\n      {isInEditMode === true ? (\n        <div\n          className=\"ndl-inline-edit-container\"\n          ref={containerRef}\n          {...focusWithinProps}\n        >\n          {/* Mirror span for measuring width */}\n          <span\n            aria-hidden={true}\n            className=\"ndl-inline-edit-mirror\"\n            ref={mirrorRef}\n          >\n            {displayText}\n          </span>\n          <input\n            {...inputProps}\n            // eslint-disable-next-line jsx-a11y/no-autofocus\n            autoFocus\n            aria-label={inputAriaLabel}\n            className={classNames(\n              'ndl-inline-edit-input',\n              inputProps?.className,\n            )}\n            id={inputID}\n            value={currentValue}\n            onChange={handleInputChange}\n            onKeyDown={handleKeyDown}\n            placeholder={placeholder}\n          />\n          <div className=\"ndl-inline-edit-buttons\">\n            <IconButton\n              description=\"Accept\"\n              tooltipProps={{\n                root: { placement: 'bottom' },\n              }}\n              onClick={onConfirmHandler}\n              size=\"small\"\n              isFloating={true}\n              htmlAttributes={{\n                onMouseDown: () => {\n                  blurWithinRef.current = true;\n                },\n              }}\n            >\n              <CheckIconOutline />\n            </IconButton>\n            <IconButton\n              description=\"Cancel\"\n              tooltipProps={{\n                root: { placement: 'bottom' },\n              }}\n              onClick={(event) => onCancelHandler(event)}\n              size=\"small\"\n              isFloating={true}\n              htmlAttributes={{\n                onMouseDown: () => {\n                  blurWithinRef.current = true;\n                },\n              }}\n            >\n              <XMarkIconOutline />\n            </IconButton>\n          </div>\n        </div>\n      ) : (\n        <button\n          type=\"button\"\n          className={classNames('ndl-inline-idle-container', {\n            'ndl-disabled': isDisabled,\n            'ndl-has-edit-icon': hasEditIcon,\n            'ndl-placeholder': displayText === placeholder,\n          })}\n          aria-disabled={isDisabled}\n          aria-label={buttonAriaLabel}\n          disabled={isDisabled}\n          onClick={handleEditClick}\n          style={{\n            minHeight: getMinHeight(typographyVariant),\n          }}\n        >\n          <span className=\"ndl-inline-edit-text\">{displayText}</span>\n          {hasEditIcon && (\n            <PencilIconOutline\n              className=\"ndl-inline-edit-pencil-icon\"\n              style={getIconStyle(typographyVariant)}\n            />\n          )}\n        </button>\n      )}\n    </Typography>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuIE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AAtBF,MAAM,gBAAgB;AAEtB,MAAa,cAAmD,SAsBd;;CAtBc,IAAA,EAC9D,IACA,WACA,cACA,gBACA,OACA,WACA,UACA,UACA,WACA,KACA,OACA,OACA,cAAc,OACd,YACA,aAAa,OACb,WACA,eAAe,WACf,UAAU,OACV,oBAAoB,qBACpB,gBAAA,MACG,YAAA,yBAAA,MAAA,SAAA;CAEH,MAAM,CAAC,aAAa,eAAe,SAAS,KAAK;CAEjD,MAAM,CAAC,cAAc,mBAAmB,uBAAuB;EAC7D,cAAc,UAAU,KAAA;EACxB;EACA,QAAA,QAAO,UAAA,QAAA,UAAA,KAAA,IAAA,QAAS,kBAAA,QAAA,UAAA,KAAA,IAAA,QAAgB;CAClC,CAAC;CACD,MAAM,CAAC,wBAAwB,6BAC7B,SAAS,YAAY;CAEvB,MAAM,YAAY,OAAwB,IAAI;CAC9C,MAAM,eAAe,OAAuB,IAAI;;;;;;;;;CAShD,MAAM,gBAAgB,OAAO,KAAK;CAGlC,gBAAgB;EACd,IAAI,UAAU,KAAA,KAAa,aAAa,KAAA,GACtC,qBACE,uFACF;CAEJ,GAAG,CAAC,OAAO,QAAQ,CAAC;CAEpB,MAAM,EAAE,qBAAqB,eAAe,EAC1C,oBAAoB;EAClB,IAAI,cAAc,SAChB;EAGF,IAAI,iBAAiB,WAAW;GAC9B,iBAAiB;GACjB;EACF;EACA,IAAI,iBAAiB,UAAU;GAC7B,gBAAgB;GAChB;EACF;CACF,EACF,CAAC;CAED,MAAM,kBAAkB,kBAAkB;EAGxC,IAAI,UAAU,KAAA,GACZ,gBAAgB,2BAA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