'use strict';

var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var debounce = require('../../node_modules/lodash-es/debounce.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var classnames = require('classnames');
var index = require('../ToggleTip/index.js');
var Settings = require('../../constants/Settings.js');
var useHasTextOverflow = require('../../hooks/useHasTextOverflow.js');
var Button = require('../Button/Button.js');
var a11yUtils = require('../../utils/a11yUtils.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = Settings.settings.iotPrefix;
var propTypes = {
  /** Whether panel is open or not */
  isOpen: PropTypes__default.default.bool,
  /** Whether content area has any padding or not */
  isFullWidth: PropTypes__default.default.bool,
  /** Whether panel header is condensed or not */
  isCondensed: PropTypes__default.default.bool,
  /** Optional override of behavior of side panel which is to slide in */
  type: PropTypes__default.default.oneOf(['inline', 'over']),
  /** Which side the side panel will appear next to content */
  direction: PropTypes__default.default.oneOf(['left', 'right']),
  /** Callback for when close button is clicked */
  onToggle: PropTypes__default.default.func,
  /** Main Title */
  title: PropTypes__default.default.string,
  /** Sub title or description - will go away when content is scrolled */
  subtitle: PropTypes__default.default.string,
  /** Action items which will appear as part of header above the content */
  actionItems: PropTypes__default.default.oneOfType([PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
    buttonLabel: PropTypes__default.default.string,
    buttonIcon: PropTypes__default.default.elementType,
    buttonCallback: PropTypes__default.default.func
  })), PropTypes__default.default.node]),
  /** Optional test id */
  testId: PropTypes__default.default.string,
  /** Callback for when Primary footer button is clicked */
  onPrimaryButtonClick: PropTypes__default.default.func,
  /** Callback for when Secondary footer button is clicked */
  onSecondaryButtonClick: PropTypes__default.default.func,
  i18n: PropTypes__default.default.shape({
    closeIconLabel: PropTypes__default.default.string,
    openIconLabel: PropTypes__default.default.string,
    primaryButtonLabel: PropTypes__default.default.string,
    secondaryButtonLabel: PropTypes__default.default.string
  }),
  /** Toggle side panel busy state */
  isBusy: PropTypes__default.default.bool,
  /** should the footer primary button be disabled */
  isPrimaryButtonDisabled: PropTypes__default.default.bool,
  /** Custom width in pixels for the side panel (e.g., 400, '400px', or '25rem') */
  width: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string]),
  /** Custom background color for the side panel (e.g., '#f4f4f4', 'gray', or any valid CSS color) */
  backgroundColor: PropTypes__default.default.string
};
var defaultProps = {
  isOpen: false,
  isFullWidth: false,
  isCondensed: false,
  type: undefined,
  direction: 'right',
  title: null,
  subtitle: null,
  actionItems: null,
  testId: 'side-panel',
  i18n: {
    closeIconLabel: 'Close',
    openIconLabel: 'Open',
    primaryButtonLabel: 'Save',
    secondaryButtonLabel: 'Cancel'
  },
  onToggle: undefined,
  onPrimaryButtonClick: undefined,
  onSecondaryButtonClick: undefined,
  isBusy: false,
  isPrimaryButtonDisabled: false,
  width: undefined,
  backgroundColor: undefined
};
var baseClass = "".concat(iotPrefix, "--sidepanel");
var SidePanel = function SidePanel(_ref) {
  var isOpen = _ref.isOpen,
    isFullWidth = _ref.isFullWidth,
    isCondensed = _ref.isCondensed,
    type = _ref.type,
    direction = _ref.direction,
    title = _ref.title,
    subtitle = _ref.subtitle,
    actionItems = _ref.actionItems,
    testId = _ref.testId,
    i18n = _ref.i18n,
    onToggle = _ref.onToggle,
    onPrimaryButtonClick = _ref.onPrimaryButtonClick,
    onSecondaryButtonClick = _ref.onSecondaryButtonClick,
    children = _ref.children,
    style = _ref.style,
    isBusy = _ref.isBusy,
    isPrimaryButtonDisabled = _ref.isPrimaryButtonDisabled,
    width = _ref.width,
    backgroundColor = _ref.backgroundColor;
  var titleRef = React.useRef();
  var subtitleRef = React.useRef();
  var contentRef = React.useRef();
  var truncatesTitle = useHasTextOverflow(titleRef, title);
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var toggleIcon = React.useMemo(function () {
    return isOpen ? {
      icon: iconsReact.Close,
      label: mergedI18n.closeIconLabel,
      tooltipPostion: 'left',
      disabled: isBusy
    } : {
      icon: direction === 'right' ? iconsReact.ChevronLeft : iconsReact.ChevronRight,
      label: mergedI18n.openIconLabel,
      tooltipPostion: direction === 'right' ? 'left' : 'right'
    };
  }, [isOpen, mergedI18n.closeIconLabel, mergedI18n.openIconLabel, direction, isBusy]);
  var actionIconBtns = React.useMemo(function () {
    return actionItems && (Array.isArray(actionItems) && actionItems.map(function (e, i) {
      return /*#__PURE__*/React__default.default.createElement(Button, {
        testId: "".concat(testId, "-action-button-").concat(e.buttonLabel),
        className: "".concat(baseClass, "__action-bar__item-").concat(i + 1),
        key: "".concat(e.buttonLabel, "-").concat(i),
        hasIconOnly: true,
        iconDescription: e.buttonLabel,
        kind: "ghost",
        renderIcon: e.buttonIcon,
        onClick: e.buttonCallback,
        size: "sm",
        tabIndex: isOpen ? 0 : -1
      });
    }) || actionItems);
  }, [actionItems, testId, isOpen]);
  React.useEffect(function () {
    var currentElement = document.querySelector(".".concat(baseClass, "__content"));
    var keyboardfocusableElements = a11yUtils.getKeyboardFoucusableElements(currentElement !== null && currentElement !== void 0 ? currentElement : document);
    if (isOpen) {
      _toConsumableArray__default.default(keyboardfocusableElements).forEach(function (e) {
        e.setAttribute('tabindex', 0);
      });
    } else {
      _toConsumableArray__default.default(keyboardfocusableElements).forEach(function (e) {
        e.setAttribute('tabindex', -1);
      });
    }
  }, [isOpen]);

  // Since subtitle is dynamic we set a css variable with the height value to animate in condensed mode
  var _useState = React.useState('100%'),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    subtitleHeight = _useState2[0],
    setSubtitleHeight = _useState2[1];
  // Triggerd when the content is scrolled in either direction
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    isScrolling = _useState4[0],
    setIsScrolling = _useState4[1];
  // If content scrollTop is not 0 we set it to isScrolled
  var _useState5 = React.useState(false),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    isScrolled = _useState6[0],
    setIsScrolled = _useState6[1];
  React.useEffect(function () {
    setTimeout(function () {
      var _subtitleRef$current;
      return setSubtitleHeight(subtitleRef === null || subtitleRef === void 0 || (_subtitleRef$current = subtitleRef.current) === null || _subtitleRef$current === void 0 ? void 0 : _subtitleRef$current.getBoundingClientRect().height);
    }, 500);
  }, [subtitle]);
  var delayedScrollCheck = debounce(function () {
    var _contentRef$current;
    if (((_contentRef$current = contentRef.current) === null || _contentRef$current === void 0 ? void 0 : _contentRef$current.scrollTop) !== 0) {
      setIsScrolled(true);
    } else {
      setIsScrolled(false);
    }
  }, 250);
  React.useEffect(function () {
    delayedScrollCheck();
  }, [delayedScrollCheck, isScrolling]);
  var truncateString = function truncateString(str, length) {
    if (str.length <= length) {
      return str;
    }
    return "".concat(str.substring(0, length), "...");
  };
  var panelWidth = React.useMemo(function () {
    if (width !== undefined) {
      return typeof width === 'number' ? "".concat(width, "px") : width;
    }
    return undefined;
  }, [width]);
  var panelStyle = React.useMemo(function () {
    return _objectSpread(_objectSpread(_objectSpread({}, style), panelWidth && {
      width: panelWidth
    }), backgroundColor && {
      backgroundColor: backgroundColor
    });
  }, [style, panelWidth, backgroundColor]);
  return /*#__PURE__*/React__default.default.createElement("div", {
    key: "sidePanel--".concat(subtitle),
    "data-testid": testId,
    className: classnames__default.default("".concat(baseClass), _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".concat(baseClass, "--closed"), !isOpen), "".concat(baseClass, "--full-width"), isFullWidth), "".concat(baseClass, "--start"), direction === 'left'), "".concat(baseClass, "--inline"), type === 'inline'), "".concat(baseClass, "--slide-over"), type === 'over'), "".concat(baseClass, "--condensed"), isCondensed || isScrolled)),
    style: panelStyle
  }, onToggle && (isOpen || type === 'inline') ? /*#__PURE__*/React__default.default.createElement(Button, {
    testId: "".concat(testId, "-toggle-button"),
    hasIconOnly: true,
    wrapperClasses: "".concat(baseClass, "__toggle-button"),
    kind: "ghost",
    iconDescription: toggleIcon.label,
    renderIcon: toggleIcon.icon,
    onClick: onToggle,
    tooltipPosition: toggleIcon.tooltipPostion,
    disabled: toggleIcon.disabled
  }) : null, /*#__PURE__*/React__default.default.createElement("header", {
    className: "".concat(baseClass, "__header"),
    "aria-hidden": !isOpen
  }, title && truncatesTitle ? /*#__PURE__*/React__default.default.createElement(index.ToggleTip, {
    "data-testid": "".concat(testId, "-title"),
    ref: titleRef,
    showIcon: false,
    className: "".concat(baseClass, "__title"),
    tabIndex: isOpen ? 0 : -1,
    content: /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, title),
    triggerText: isCondensed || isScrolled ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, truncateString(title, 25)) : /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, truncateString(title, 50))
  }) : title ? /*#__PURE__*/React__default.default.createElement("h2", {
    "data-testid": "".concat(testId, "-title"),
    ref: titleRef,
    className: "".concat(baseClass, "__title")
  }, title) : null, subtitle ? /*#__PURE__*/React__default.default.createElement("p", {
    ref: subtitleRef,
    "data-testid": "".concat(testId, "-subtitle"),
    style: {
      '--sub-title-height': subtitleHeight
    },
    className: "".concat(baseClass, "__subtitle")
  }, subtitle) : null, actionIconBtns ? /*#__PURE__*/React__default.default.createElement("div", {
    "data-testid": "".concat(testId, "-action-bar"),
    className: "".concat(baseClass, "__action-bar"),
    "aria-hidden": !isOpen
  }, actionIconBtns) : null), /*#__PURE__*/React__default.default.createElement("section", {
    "data-testid": "".concat(testId, "-content"),
    ref: contentRef,
    className: "".concat(baseClass, "__content"),
    onScroll: function onScroll() {
      return setIsScrolling(function (prev) {
        return !prev;
      });
    },
    "aria-hidden": !isOpen
  }, children), onSecondaryButtonClick || onPrimaryButtonClick ? /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClass, "__footer"),
    "data-testid": "".concat(testId, "-footer"),
    "aria-hidden": !isOpen
  }, onSecondaryButtonClick ? /*#__PURE__*/React__default.default.createElement(Button, {
    testId: "".concat(testId, "-secondary-button"),
    className: "".concat(baseClass, "__footer__secondary-button"),
    onClick: onSecondaryButtonClick,
    tooltipPosition: toggleIcon.tooltipPostion,
    kind: "secondary",
    disabled: isBusy,
    tabIndex: isOpen ? 0 : -1
  }, mergedI18n.secondaryButtonLabel) : null, onPrimaryButtonClick ? /*#__PURE__*/React__default.default.createElement(Button, {
    testId: "".concat(testId, "-primary-button"),
    className: "".concat(baseClass, "__footer__primary-button"),
    kind: "primary",
    onClick: onPrimaryButtonClick,
    loading: isBusy,
    disabled: isPrimaryButtonDisabled,
    tabIndex: isOpen ? 0 : -1
  }, mergedI18n.primaryButtonLabel) : null) : null);
};
SidePanel.propTypes = propTypes;
SidePanel.defaultProps = defaultProps;
SidePanel.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "SidePanel",
  "props": {
    "isOpen": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Whether panel is open or not",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isFullWidth": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Whether content area has any padding or not",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isCondensed": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Whether panel header is condensed or not",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "type": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Optional override of behavior of side panel which is to slide in",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'inline'",
          "computed": false
        }, {
          "value": "'over'",
          "computed": false
        }]
      },
      "required": false
    },
    "direction": {
      "defaultValue": {
        "value": "'right'",
        "computed": false
      },
      "description": "Which side the side panel will appear next to content",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'left'",
          "computed": false
        }, {
          "value": "'right'",
          "computed": false
        }]
      },
      "required": false
    },
    "title": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Main Title",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "subtitle": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Sub title or description - will go away when content is scrolled",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "actionItems": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Action items which will appear as part of header above the content",
      "type": {
        "name": "union",
        "value": [{
          "name": "arrayOf",
          "value": {
            "name": "shape",
            "value": {
              "buttonLabel": {
                "name": "string",
                "required": false
              },
              "buttonIcon": {
                "name": "elementType",
                "required": false
              },
              "buttonCallback": {
                "name": "func",
                "required": false
              }
            }
          }
        }, {
          "name": "node"
        }]
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'side-panel'",
        "computed": false
      },
      "description": "Optional test id",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  closeIconLabel: 'Close',\n  openIconLabel: 'Open',\n  primaryButtonLabel: 'Save',\n  secondaryButtonLabel: 'Cancel',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "closeIconLabel": {
            "name": "string",
            "required": false
          },
          "openIconLabel": {
            "name": "string",
            "required": false
          },
          "primaryButtonLabel": {
            "name": "string",
            "required": false
          },
          "secondaryButtonLabel": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "onToggle": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Callback for when close button is clicked",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "onPrimaryButtonClick": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Callback for when Primary footer button is clicked",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "onSecondaryButtonClick": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Callback for when Secondary footer button is clicked",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "isBusy": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Toggle side panel busy state",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isPrimaryButtonDisabled": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "should the footer primary button be disabled",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "width": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Custom width in pixels for the side panel (e.g., 400, '400px', or '25rem')",
      "type": {
        "name": "union",
        "value": [{
          "name": "number"
        }, {
          "name": "string"
        }]
      },
      "required": false
    },
    "backgroundColor": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "description": "Custom background color for the side panel (e.g., '#f4f4f4', 'gray', or any valid CSS color)",
      "type": {
        "name": "string"
      },
      "required": false
    }
  }
};
var SidePanel$1 = SidePanel;

module.exports = SidePanel$1;
