"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useTreeViewJSXItems = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _useEventCallback = _interopRequireDefault(require("@mui/utils/useEventCallback"));
var _useForkRef = _interopRequireDefault(require("@mui/utils/useForkRef"));
var _useEnhancedEffect = _interopRequireDefault(require("@mui/utils/useEnhancedEffect"));
var _publishTreeViewEvent = require("../../utils/publishTreeViewEvent");
var _TreeViewProvider = require("../../TreeViewProvider");
var _TreeViewChildrenItemProvider = require("../../TreeViewProvider/TreeViewChildrenItemProvider");
var _useTreeViewItems = require("../useTreeViewItems/useTreeViewItems.utils");
var _TreeViewItemDepthContext = require("../../TreeViewItemDepthContext");
var _useTreeViewId = require("../../corePlugins/useTreeViewId/useTreeViewId.utils");
var _jsxRuntime = require("react/jsx-runtime");
const useTreeViewJSXItems = ({
  instance,
  setState
}) => {
  instance.preventItemUpdates();
  const insertJSXItem = (0, _useEventCallback.default)(item => {
    setState(prevState => {
      if (prevState.items.itemMetaMap[item.id] != null) {
        throw new Error(['MUI X: The Tree View component requires all items to have a unique `id` property.', 'Alternatively, you can use the `getItemId` prop to specify a custom id for each item.', `Two items were provided with the same id in the \`items\` prop: "${item.id}"`].join('\n'));
      }
      return (0, _extends2.default)({}, prevState, {
        items: (0, _extends2.default)({}, prevState.items, {
          itemMetaMap: (0, _extends2.default)({}, prevState.items.itemMetaMap, {
            [item.id]: item
          }),
          // For Simple Tree View, we don't have a proper `item` object, so we create a very basic one.
          itemMap: (0, _extends2.default)({}, prevState.items.itemMap, {
            [item.id]: {
              id: item.id,
              label: item.label
            }
          })
        })
      });
    });
    return () => {
      setState(prevState => {
        const newItemMetaMap = (0, _extends2.default)({}, prevState.items.itemMetaMap);
        const newItemMap = (0, _extends2.default)({}, prevState.items.itemMap);
        delete newItemMetaMap[item.id];
        delete newItemMap[item.id];
        return (0, _extends2.default)({}, prevState, {
          items: (0, _extends2.default)({}, prevState.items, {
            itemMetaMap: newItemMetaMap,
            itemMap: newItemMap
          })
        });
      });
      (0, _publishTreeViewEvent.publishTreeViewEvent)(instance, 'removeItem', {
        id: item.id
      });
    };
  });
  const setJSXItemsOrderedChildrenIds = (parentId, orderedChildrenIds) => {
    const parentIdWithDefault = parentId ?? _useTreeViewItems.TREE_VIEW_ROOT_PARENT_ID;
    setState(prevState => (0, _extends2.default)({}, prevState, {
      items: (0, _extends2.default)({}, prevState.items, {
        itemOrderedChildrenIds: (0, _extends2.default)({}, prevState.items.itemOrderedChildrenIds, {
          [parentIdWithDefault]: orderedChildrenIds
        }),
        itemChildrenIndexes: (0, _extends2.default)({}, prevState.items.itemChildrenIndexes, {
          [parentIdWithDefault]: (0, _useTreeViewItems.buildSiblingIndexes)(orderedChildrenIds)
        })
      })
    }));
  };
  const mapFirstCharFromJSX = (0, _useEventCallback.default)((itemId, firstChar) => {
    instance.updateFirstCharMap(firstCharMap => {
      firstCharMap[itemId] = firstChar;
      return firstCharMap;
    });
    return () => {
      instance.updateFirstCharMap(firstCharMap => {
        const newMap = (0, _extends2.default)({}, firstCharMap);
        delete newMap[itemId];
        return newMap;
      });
    };
  });
  return {
    instance: {
      insertJSXItem,
      setJSXItemsOrderedChildrenIds,
      mapFirstCharFromJSX
    }
  };
};
exports.useTreeViewJSXItems = useTreeViewJSXItems;
const isItemExpandable = reactChildren => {
  if (Array.isArray(reactChildren)) {
    return reactChildren.length > 0 && reactChildren.some(isItemExpandable);
  }
  return Boolean(reactChildren);
};
const useTreeViewJSXItemsItemPlugin = ({
  props,
  rootRef,
  contentRef
}) => {
  const {
    instance,
    treeId
  } = (0, _TreeViewProvider.useTreeViewContext)();
  const {
    children,
    disabled = false,
    label,
    itemId,
    id
  } = props;
  const parentContext = React.useContext(_TreeViewChildrenItemProvider.TreeViewChildrenItemContext);
  if (parentContext == null) {
    throw new Error(['MUI X: Could not find the Tree View Children Item context.', 'It looks like you rendered your component outside of a SimpleTreeView parent component.', 'This can also happen if you are bundling multiple versions of the Tree View.'].join('\n'));
  }
  const {
    registerChild,
    unregisterChild,
    parentId
  } = parentContext;
  const expandable = isItemExpandable(children);
  const pluginContentRef = React.useRef(null);
  const handleContentRef = (0, _useForkRef.default)(pluginContentRef, contentRef);

  // Prevent any flashing
  (0, _useEnhancedEffect.default)(() => {
    const idAttribute = (0, _useTreeViewId.generateTreeItemIdAttribute)({
      itemId,
      treeId,
      id
    });
    registerChild(idAttribute, itemId);
    return () => {
      unregisterChild(idAttribute);
    };
  }, [registerChild, unregisterChild, itemId, id, treeId]);
  React.useEffect(() => {
    return instance.insertJSXItem({
      id: itemId,
      idAttribute: id,
      parentId,
      expandable,
      disabled
    });
  }, [instance, parentId, itemId, expandable, disabled, id]);
  React.useEffect(() => {
    if (label) {
      return instance.mapFirstCharFromJSX(itemId, (pluginContentRef.current?.textContent ?? '').substring(0, 1).toLowerCase());
    }
    return undefined;
  }, [instance, itemId, label]);
  return {
    contentRef: handleContentRef,
    rootRef
  };
};
useTreeViewJSXItems.itemPlugin = useTreeViewJSXItemsItemPlugin;
useTreeViewJSXItems.wrapItem = ({
  children,
  itemId
}) => {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const depthContext = React.useContext(_TreeViewItemDepthContext.TreeViewItemDepthContext);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TreeViewChildrenItemProvider.TreeViewChildrenItemProvider, {
    itemId: itemId,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_TreeViewItemDepthContext.TreeViewItemDepthContext.Provider, {
      value: depthContext + 1,
      children: children
    })
  });
};
useTreeViewJSXItems.wrapRoot = ({
  children
}) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_TreeViewChildrenItemProvider.TreeViewChildrenItemProvider, {
  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_TreeViewItemDepthContext.TreeViewItemDepthContext.Provider, {
    value: 0,
    children: children
  })
});
useTreeViewJSXItems.params = {};