"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useInternalValue;
var _element = require("@wordpress/element");
var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal"));
/**
 * WordPress dependencies
 */

/**
 * External dependencies
 */

function useInternalValue(value) {
  const [internalValue, setInternalValue] = (0, _element.useState)(value || {});
  const [previousValue, setPreviousValue] = (0, _element.useState)(value);

  // If the value prop changes, update the internal state.
  // See:
  // - https://github.com/WordPress/gutenberg/pull/51387#issuecomment-1722927384.
  // - https://react.dev/reference/react/useState#storing-information-from-previous-renders.
  if (!(0, _fastDeepEqual.default)(value, previousValue)) {
    setPreviousValue(value);
    setInternalValue(value);
  }
  const setInternalURLInputValue = nextValue => {
    setInternalValue({
      ...internalValue,
      url: nextValue
    });
  };
  const setInternalTextInputValue = nextValue => {
    setInternalValue({
      ...internalValue,
      title: nextValue
    });
  };
  const createSetInternalSettingValueHandler = settingsKeys => nextValue => {
    // Only apply settings values which are defined in the settings prop.
    const settingsUpdates = Object.keys(nextValue).reduce((acc, key) => {
      if (settingsKeys.includes(key)) {
        acc[key] = nextValue[key];
      }
      return acc;
    }, {});
    setInternalValue({
      ...internalValue,
      ...settingsUpdates
    });
  };
  return [internalValue, setInternalValue, setInternalURLInputValue, setInternalTextInputValue, createSetInternalSettingValueHandler];
}
//# sourceMappingURL=use-internal-value.js.map