본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Rich Tree View - 사용자 지정

원문 보기 위키 갱신

Rich Tree View - 사용자 지정 (Customization)

Rich Tree View 컴포넌트를 사용자 지정하는 방법을 알아봅니다.

출처: MUI X documentation

본문

:::success 슬롯 사용 방법은 공통 개념—슬롯과 하위 컴포넌트를 참고하세요. :::

기본 (Basics)

사용자 지정 아이콘 (Custom icons)

collapseIcon 슬롯, expandIcon 슬롯, defaultEndIcon prop을 사용해 RichTreeView 아이콘을 사용자 지정할 수 있습니다. 아래 데모는 Material Icons 같은 기존 아이콘 라이브러리를 사용하거나 Material UI의 SvgIcon으로 처음부터 아이콘을 만들어 추가하는 방법을 보여 줍니다.

import Box from '@mui/material/Box';
import AddBoxIcon from '@mui/icons-material/AddBox';
import IndeterminateCheckBoxIcon from '@mui/icons-material/IndeterminateCheckBox';
import SvgIcon, { SvgIconProps } from '@mui/material/SvgIcon';
import { styled } from '@mui/material/styles';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { TreeItem, treeItemClasses } from '@mui/x-tree-view/TreeItem';
import { MUI_X_PRODUCTS } from '../../datasets/products';

const CustomTreeItem = styled(TreeItem)({
  [`& .${treeItemClasses.iconContainer}`]: {
    '& .close': {
      opacity: 0.3,
    },
  },
});

function CloseSquare(props: SvgIconProps) {
  return (
    <SvgIcon
      className="close"
      fontSize="inherit"
      style={{ width: 14, height: 14 }}
      {...props}
    >
      {/* tslint:disable-next-line: max-line-length */}
      <path d="M17.485 17.512q-.281.281-.682.281t-.696-.268l-4.12-4.147-4.12 4.147q-.294.268-.696.268t-.682-.281-.281-.682.294-.669l4.12-4.147-4.12-4.147q-.294-.268-.294-.669t.281-.682.682-.281.696 .268l4.12 4.147 4.12-4.147q.294-.268.696-.268t.682.281 .281.669-.294.682l-4.12 4.147 4.12 4.147q.294.268 .294.669t-.281.682zM22.047 22.074v0 0-20.147 0h-20.12v0 20.147 0h20.12zM22.047 24h-20.12q-.803 0-1.365-.562t-.562-1.365v-20.147q0-.776.562-1.351t1.365-.575h20.147q.776 0 1.351.575t.575 1.351v20.147q0 .803-.575 1.365t-1.378.562v0z" />
    </SvgIcon>
  );
}

export default function CustomIcons() {
  return (
    <Box sx={{ minHeight: 352, minWidth: 250 }}>
      <RichTreeView
        defaultExpandedItems={['grid']}
        slots={{
          expandIcon: AddBoxIcon,
          collapseIcon: IndeterminateCheckBoxIcon,
          endIcon: CloseSquare,
          item: CustomTreeItem,
        }}
        items={MUI_X_PRODUCTS}
      />
    </Box>
  );
}

사용자 지정 토글 애니메이션 (Custom toggle animations)

TreeItem의 groupTransition 슬롯을 사용해 애니메이션을 처리하는 컴포넌트를 전달할 수 있습니다.

아래 데모는 Material UI의 Collapse 컴포넌트와 react-spring 라이브러리를 함께 사용해 애니메이션합니다.

:::info RichTreeViewPro는 기본적으로 평면(flat) DOM 구조를 사용합니다. 중첩된 groupTransition 슬롯에 의존하는 애니메이션을 사용하려면 가상화를 비활성화하고 domStructure="nested"를 설정하세요:

<RichTreeViewPro items={ITEMS} disableVirtualization domStructure="nested" />

:::

import Box from '@mui/material/Box';
import Collapse from '@mui/material/Collapse';
import { TransitionProps } from '@mui/material/transitions';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { useSpring, animated } from '@react-spring/web';
import { MUI_X_PRODUCTS } from '../../datasets/products';

function TransitionComponent(props: TransitionProps) {
  const style = useSpring({
    to: {
      opacity: props.in ? 1 : 0,
      transform: `translate3d(${props.in ? 0 : 20}px,0,0)`,
    },
  });

  return (
    <animated.div style={style}>
      <Collapse {...props} />
    </animated.div>
  );
}

export default function CustomAnimation() {
  return (
    <Box sx={{ minHeight: 352, minWidth: 250 }}>
      <RichTreeView
        defaultExpandedItems={['grid']}
        slotProps={{ item: { slots: { groupTransition: TransitionComponent } } }}
        items={MUI_X_PRODUCTS}
      />
    </Box>
  );
}

사용자 지정 스타일링 (Custom styling)

treeItemClasses를 사용해 TreeItem의 내부 요소를 타겟으로 지정하고 스타일을 변경할 수 있습니다. DOM 구조는 사용 가능한 스타일링 패턴에 영향을 줍니다: 중첩(nested) DOM은 부모 항목에서 자식 그룹을 스타일링할 수 있게 하고, 평면(flat) DOM은 보이는 모든 항목을 형제로 렌더링합니다.

import Box from '@mui/material/Box';
import { styled, alpha } from '@mui/material/styles';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { TreeItem, treeItemClasses } from '@mui/x-tree-view/TreeItem';
import { MUI_X_PRODUCTS } from '../../datasets/products';

const CONNECTOR_LINE_WIDTH = 1;
const CONNECTOR_LINE_CENTER = 17.5;
const CONNECTOR_LINE_LEFT = CONNECTOR_LINE_CENTER - CONNECTOR_LINE_WIDTH / 2;
const CONNECTOR_GAP = 16;

const CustomTreeItem = styled(TreeItem)(({ theme }) => ({
  color: theme.palette.grey[200],
  [`& .${treeItemClasses.content}`]: {
    borderRadius: theme.spacing(0.5),
    padding: theme.spacing(0.5, 1),
    margin: theme.spacing(0.2, 0),
    [`& .${treeItemClasses.label}`]: {
      fontSize: '0.8rem',
      fontWeight: 500,
    },
  },
  [`& .${treeItemClasses.iconContainer}`]: {
    borderRadius: '50%',
    backgroundColor: theme.palette.primary.dark,
    padding: theme.spacing(0, 1.2),
    ...theme.applyStyles('light', {
      backgroundColor: alpha(theme.palette.primary.main, 0.25),
    }),
    ...theme.applyStyles('dark', {
      color: theme.palette.primary.contrastText,
    }),
  },
  [`& .${treeItemClasses.groupTransition}`]: {
    marginLeft: CONNECTOR_LINE_LEFT,
    paddingLeft: CONNECTOR_GAP,
    borderLeft: `${CONNECTOR_LINE_WIDTH}px dashed ${alpha(theme.palette.text.primary, 0.4)}`,
  },
  ...theme.applyStyles('light', {
    color: theme.palette.grey[800],
  }),
}));

export default function CustomStyling() {
  return (
    <Box sx={{ minHeight: 352, minWidth: 250 }}>
      <RichTreeView
        defaultExpandedItems={['grid']}
        slots={{ item: CustomTreeItem }}
        items={MUI_X_PRODUCTS}
      />
    </Box>
  );
}

RichTreeViewPro는 기본적으로 평면 DOM을 사용하므로, 중첩 DOM 스타일링 패턴을 원한다면 가상화를 비활성화한 상태에서 domStructure="nested"를 사용하거나 스타일을 평면 DOM 구조에 맞게 조정하세요.

import Box from '@mui/material/Box';
import { styled, alpha } from '@mui/material/styles';
import { TreeItem, treeItemClasses } from '@mui/x-tree-view/TreeItem';
import { RichTreeViewPro } from '@mui/x-tree-view-pro/RichTreeViewPro';
import { MUI_X_PRODUCTS } from '../../datasets/products';

const ITEM_HEIGHT = 36;
const CONNECTOR_LINE_WIDTH = 1;
const CONNECTOR_LINE_CENTER = 17.5;
const CONNECTOR_LINE_LEFT = CONNECTOR_LINE_CENTER - CONNECTOR_LINE_WIDTH / 2;
const CONNECTOR_GAP = 16;
const CONNECTOR_OFFSET = CONNECTOR_LINE_WIDTH + CONNECTOR_GAP;
const ITEM_CHILDREN_INDENTATION =
  CONNECTOR_LINE_LEFT + CONNECTOR_LINE_WIDTH + CONNECTOR_GAP;

const CustomTreeItem = styled(TreeItem)(({ theme }) => {
  const rowSpacing = theme.spacing(0.25);

  return {
    position: 'relative',
    color: theme.palette.grey[200],
    '&::before': {
      content: '""',
      position: 'absolute',
      left: `calc(var(--TreeView-itemChildrenIndentation) * var(--TreeView-itemDepth) - ${CONNECTOR_OFFSET}px)`,
      top: 0,
      bottom: 0,
      borderLeft: `${CONNECTOR_LINE_WIDTH}px dashed ${alpha(theme.palette.text.primary, 0.4)}`,
      opacity: 'clamp(0, var(--TreeView-itemDepth), 1)',
      pointerEvents: 'none',
    },
    [`& .${treeItemClasses.content}`]: {
      borderRadius: theme.spacing(0.5),
      height: `calc(var(--TreeView-itemHeight) - ${theme.spacing(0.5)})`,
      marginTop: rowSpacing,
      marginBottom: rowSpacing,
      marginLeft: `calc(var(--TreeView-itemChildrenIndentation) * var(--TreeView-itemDepth))`,
      width: `calc(100% - var(--TreeView-itemChildrenIndentation) * var(--TreeView-itemDepth))`,
      padding: theme.spacing(0.5, 1),
      [`& .${treeItemClasses.label}`]: {
        fontSize: '0.8rem',
        fontWeight: 500,
      },
    },
    [`& .${treeItemClasses.iconContainer}`]: {
      borderRadius: '50%',
      backgroundColor: theme.palette.primary.dark,
      padding: theme.spacing(0, 1.2),
      ...theme.applyStyles('light', {
        backgroundColor: alpha(theme.palette.primary.main, 0.25),
      }),
      ...theme.applyStyles('dark', {
        color: theme.palette.primary.contrastText,
      }),
    },
    ...theme.applyStyles('light', {
      color: theme.palette.grey[800],
    }),
  };
});

export default function CustomStylingRichTreeViewPro() {
  return (
    <Box sx={{ height: 352, minWidth: 250 }}>
      <RichTreeViewPro
        defaultExpandedItems={['grid']}
        itemChildrenIndentation={ITEM_CHILDREN_INDENTATION}
        itemHeight={ITEM_HEIGHT}
        slots={{ item: CustomTreeItem }}
        items={MUI_X_PRODUCTS}
      />
    </Box>
  );
}

고정 헤더 (Sticky headers)

--TreeView-itemDepth CSS 변수를 사용해 중첩 레벨을 서로 아래에 쌓으면서, 펼쳐진 항목이 하위 항목이 보이는 동안 스크롤 컨테이너 상단에 고정되게 할 수 있습니다. 고정된 항목 뒤로 콘텐츠가 스크롤되어 보이지 않도록 투명도가 아닌 불투명한 테마 인지(theme-aware) 배경색을 사용하세요. 고정 오프셋은 고정된 행 높이를 가정하므로, itemHeight prop을 전달해 이를 강제하세요.

:::info 이 레시피는 항목의 하위 항목이 해당 항목의 DOM 요소 안에 렌더링되는 중첩 DOM 구조에 의존합니다. 평면 DOM 구조에서는 효과가 없습니다. RichTreeViewPro는 기본적으로 평면 DOM 구조를 사용하므로, 가상화를 비활성화하고 domStructure="nested"를 설정하세요:

<RichTreeViewPro items={ITEMS} disableVirtualization domStructure="nested" />

:::

import Box from '@mui/material/Box';
import { styled } from '@mui/material/styles';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { treeItemClasses } from '@mui/x-tree-view/TreeItem';
import { MUI_X_PRODUCTS, DEFAULT_EXPANDED_ITEMS } from '../../datasets/deepProducts';

const ITEM_HEIGHT = 32;

const StickyRichTreeView = styled(RichTreeView)(({ theme }) => ({
  // Extra space so the last parents can also reach the top and stick.
  paddingBottom: 224,
  [`& .${treeItemClasses.content}[data-expanded]`]: {
    position: 'sticky',
    // Stack deeper levels below shallower ones.
    top: `calc(var(--TreeView-itemDepth) * ${ITEM_HEIGHT}px)`,
    zIndex: 'calc(100 - var(--TreeView-itemDepth))',
    backgroundColor: (theme.vars || theme).palette.background.paper,
    boxShadow: (theme.vars || theme).shadows[1],
    // Paint the hover, focus, and selected states over the solid background.
    backgroundImage:
      'linear-gradient(var(--sticky-overlay, transparent), var(--sticky-overlay, transparent))',
    '&:hover': {
      '--sticky-overlay': (theme.vars || theme).palette.action.hover,
    },
    '&[data-focused]': {
      '--sticky-overlay': (theme.vars || theme).palette.action.focus,
    },
    '&[data-selected]': {
      '--sticky-overlay': theme.alpha(
        (theme.vars || theme).palette.primary.main,
        (theme.vars || theme).palette.action.selectedOpacity,
      ),
    },
  },
}));

export default function StickyHeaders() {
  return (
    <Box sx={{ height: 352, width: 280, overflowY: 'auto' }}>
      <StickyRichTreeView
        items={MUI_X_PRODUCTS}
        itemHeight={ITEM_HEIGHT}
        defaultExpandedItems={DEFAULT_EXPANDED_ITEMS}
      />
    </Box>
  );
}

사용자 지정 Tree Item (Custom Tree Item)

TreeItem 사용자 지정 API를 사용해 새로운 레이아웃을 만들고 동작을 관리할 수 있습니다.

TreeItem의 구조와 제공되는 사용자 지정 유틸리티에 대해 더 알아보려면 Tree Item 사용자 지정을 참고하세요.

Headless API

useTreeItem() 훅을 사용해 완전히 사용자 지정된 자신만의 컴포넌트를 만들 수 있습니다. 아래 데모는 아바타와 사용자 지정 타이포그래피 요소를 추가하는 방법을 보여 줍니다.

import * as React from 'react';
import Box from '@mui/material/Box';
import Avatar from '@mui/material/Avatar';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { TreeViewDefaultItemModelProperties } from '@mui/x-tree-view/models';
import { useTreeItem, UseTreeItemParameters } from '@mui/x-tree-view/useTreeItem';
import {
  TreeItemContent,
  TreeItemIconContainer,
  TreeItemGroupTransition,
  TreeItemLabel,
  TreeItemRoot,
  TreeItemCheckbox,
} from '@mui/x-tree-view/TreeItem';
import { TreeItemIcon } from '@mui/x-tree-view/TreeItemIcon';
import { TreeItemProvider } from '@mui/x-tree-view/TreeItemProvider';
import { TreeItemDragAndDropOverlay } from '@mui/x-tree-view/TreeItemDragAndDropOverlay';

const ITEMS: TreeViewDefaultItemModelProperties[] = [
  {
    id: '1',
    label: 'Amelia Hart',
    children: [{ id: '2', label: 'Jane Fisher' }],
  },
  {
    id: '3',
    label: 'Bailey Monroe',
    children: [
      { id: '4', label: 'Freddie Reed' },
      {
        id: '5',
        label: 'Georgia Johnson',
        children: [{ id: '6', label: 'Samantha Malone' }],
      },
    ],
  },
];

interface CustomTreeItemProps
  extends
    Omit<UseTreeItemParameters, 'rootRef'>,
    Omit<React.HTMLAttributes<HTMLLIElement>, 'onFocus'> {}

const CustomTreeItem = React.forwardRef(function CustomTreeItem(
  props: CustomTreeItemProps,
  ref: React.Ref<HTMLLIElement>,
) {
  const { id, itemId, label, disabled, children, ...other } = props;

  const {
    getContextProviderProps,
    getRootProps,
    getContentProps,
    getIconContainerProps,
    getCheckboxProps,
    getLabelProps,
    getGroupTransitionProps,
    getDragAndDropOverlayProps,
    status,
  } = useTreeItem({ id, itemId, children, label, disabled, rootRef: ref });

  return (
    <TreeItemProvider {...getContextProviderProps()}>
      <TreeItemRoot {...getRootProps(other)}>
        <TreeItemContent {...getContentProps()}>
          <TreeItemIconContainer {...getIconContainerProps()}>
            <TreeItemIcon status={status} />
          </TreeItemIconContainer>
          <Box sx={{ flexGrow: 1, display: 'flex', gap: 1 }}>
            <Avatar
              sx={(theme) => ({
                background: theme.palette.primary.main,
                width: 24,
                height: 24,
                fontSize: '0.8rem',
              })}
            >
              {(label as string)[0]}
            </Avatar>
            <TreeItemCheckbox {...getCheckboxProps()} />
            <TreeItemLabel {...getLabelProps()} />
          </Box>
          <TreeItemDragAndDropOverlay {...getDragAndDropOverlayProps()} />
        </TreeItemContent>
        {children && <TreeItemGroupTransition {...getGroupTransitionProps()} />}
      </TreeItemRoot>
    </TreeItemProvider>
  );
});

export default function HeadlessAPI() {
  return (
    <Box sx={{ minHeight: 200, minWidth: 250 }}>
      <RichTreeView
        defaultExpandedItems={['3']}
        items={ITEMS}
        slots={{ item: CustomTreeItem }}
      />
    </Box>
  );
}

공통 예제 (Common examples)

파일 탐색기 (File explorer)

아래 파일 탐색기 데모는 위에서 설명한 많은 사용자 지정 옵션을 활용해 RichTreeView를 기본 디자인과 크게 다르게 보이게 합니다:

import * as React from 'react';
import { animated, useSpring } from '@react-spring/web';
import { styled, alpha } from '@mui/material/styles';
import { TransitionProps } from '@mui/material/transitions';
import Box from '@mui/material/Box';
import Collapse from '@mui/material/Collapse';
import Typography from '@mui/material/Typography';
import ArticleIcon from '@mui/icons-material/Article';
import DeleteIcon from '@mui/icons-material/Delete';
import FolderOpenIcon from '@mui/icons-material/FolderOpen';
import FolderRounded from '@mui/icons-material/FolderRounded';
import ImageIcon from '@mui/icons-material/Image';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import VideoCameraBackIcon from '@mui/icons-material/VideoCameraBack';
import { RichTreeView } from '@mui/x-tree-view/RichTreeView';
import { useTreeItem, UseTreeItemParameters } from '@mui/x-tree-view/useTreeItem';
import {
  TreeItemCheckbox,
  TreeItemIconContainer,
  TreeItemLabel,
} from '@mui/x-tree-view/TreeItem';
import { TreeItemIcon } from '@mui/x-tree-view/TreeItemIcon';
import { TreeItemProvider } from '@mui/x-tree-view/TreeItemProvider';
import { TreeItemDragAndDropOverlay } from '@mui/x-tree-view/TreeItemDragAndDropOverlay';
import { useTreeItemModel } from '@mui/x-tree-view/hooks';

type FileType = 'image' | 'pdf' | 'doc' | 'video' | 'folder' | 'pinned' | 'trash';

type ExtendedTreeItemProps = {
  fileType?: FileType;
  id: string;
  label: string;
  children?: ExtendedTreeItemProps[];
};

const ITEMS: ExtendedTreeItemProps[] = [
  {
    id: '1',
    label: 'Documents',
    children: [
      {
        id: '1.1',
        label: 'Company',
        children: [
          { id: '1.1.1', label: 'Invoice', fileType: 'pdf' },
          { id: '1.1.2', label: 'Meeting notes', fileType: 'doc' },
          { id: '1.1.3', label: 'Tasks list', fileType: 'doc' },
          { id: '1.1.4', label: 'Equipment', fileType: 'pdf' },
          { id: '1.1.5', label: 'Video conference', fileType: 'video' },
        ],
      },
      { id: '1.2', label: 'Personal', fileType: 'folder' },
      { id: '1.3', label: 'Group photo', fileType: 'image' },
    ],
  },
  {
    id: '2',
    label: 'Bookmarked',
    fileType: 'pinned',
    children: [
      { id: '2.1', label: 'Learning materials', fileType: 'folder' },
      { id: '2.2', label: 'News', fileType: 'folder' },
      { id: '2.3', label: 'Forums', fileType: 'folder' },
      { id: '2.4', label: 'Travel documents', fileType: 'pdf' },
    ],
  },
  { id: '3', label: 'History', fileType: 'folder' },
  { id: '4', label: 'Trash', fileType: 'trash' },
];

function DotIcon() {
  return (
    <Box
      sx={{
        width: 6,
        height: 6,
        borderRadius: '70%',
        bgcolor: 'warning.main',
        display: 'inline-block',
        verticalAlign: 'middle',
        zIndex: 1,
        mx: 1,
      }}
    />
  );
}
declare module 'react' {
  interface CSSProperties {
    '--tree-view-color'?: string;
    '--tree-view-bg-color'?: string;
  }
}

const TreeItemRoot = styled('li')(({ theme }) => ({
  listStyle: 'none',
  margin: 0,
  padding: 0,
  outline: 0,
  color: theme.palette.grey[400],
  ...theme.applyStyles('light', {
    color: theme.palette.grey[800],
  }),
}));

const TreeItemContent = styled('div')(({ theme }) => ({
  padding: theme.spacing(0.5),
  paddingRight: theme.spacing(1),
  paddingLeft: `calc(${theme.spacing(1)} + var(--TreeView-itemChildrenIndentation) * var(--TreeView-itemDepth))`,
  width: '100%',
  boxSizing: 'border-box', // prevent width + padding to overflow
  position: 'relative',
  display: 'flex',
  alignItems: 'center',
  gap: theme.spacing(1),
  cursor: 'pointer',
  WebkitTapHighlightColor: 'transparent',
  flexDirection: 'row-reverse',
  borderRadius: theme.spacing(0.7),
  marginBottom: theme.spacing(0.5),
  marginTop: theme.spacing(0.5),
  fontWeight: 500,
  '&[data-expanded]:not([data-focused], [data-selected]) .labelIcon': {
    color: theme.palette.primary.dark,
    ...theme.applyStyles('light', {
      color: theme.palette.primary.main,
    }),
    '&::before': {
      content: '""',
      display: 'block',
      position: 'absolute',
      left: '16px',
      top: '44px',
      height: 'calc(100% - 48px)',
      width: '1.5px',
      backgroundColor: theme.palette.grey[700],
      ...theme.applyStyles('light', {
        backgroundColor: theme.palette.grey[300],
      }),
    },
  },
  [`&[data-focused], &[data-selected]`]: {
    backgroundColor: theme.palette.primary.dark,
    color: theme.palette.primary.contrastText,
    ...theme.applyStyles('light', {
      backgroundColor: theme.palette.primary.main,
    }),
  },
  '&:not([data-focused], [data-selected]):hover': {
    backgroundColor: alpha(theme.palette.primary.main, 0.1),
    color: 'white',
    ...theme.applyStyles('light', {
      color: theme.palette.primary.main,
    }),
  },
}));

const CustomCollapse = styled(Collapse)({
  padding: 0,
});

const AnimatedCollapse = animated(CustomCollapse);

function TransitionComponent(props: TransitionProps) {
  const style = useSpring({
    to: {
      opacity: props.in ? 1 : 0,
      transform: `translate3d(0,${props.in ? 0 : 20}px,0)`,
    },
  });

  return <AnimatedCollapse style={style} {...props} />;
}

const TreeItemLabelText = styled(Typography)({
  color: 'inherit',
  fontFamily: 'General Sans',
  fontWeight: 500,
});

interface CustomLabelProps {
  children: React.ReactNode;
  icon?: React.ElementType;
  expandable?: boolean;
}

function CustomLabel({
  icon: Icon,
  expandable,
  children,
  ...other
}: CustomLabelProps) {
  return (
    <TreeItemLabel
      {...other}
      sx={{
        display: 'flex',
        alignItems: 'center',
      }}
    >
      {Icon && (
        <Box
          component={Icon}
          className="labelIcon"
          sx={{ color: 'inherit', mr: 1, fontSize: '1.2rem' }}
        />
      )}
      <TreeItemLabelText variant="body2">{children}</TreeItemLabelText>
      {expandable && <DotIcon />}
    </TreeItemLabel>
  );
}

const getIconFromFileType = (fileType: FileType) => {
  switch (fileType) {
    case 'image':
      return ImageIcon;
    case 'pdf':
      return PictureAsPdfIcon;
    case 'doc':
      return ArticleIcon;
    case 'video':
      return VideoCameraBackIcon;
    case 'folder':
      return FolderRounded;
    case 'pinned':
      return FolderOpenIcon;
    case 'trash':
      return DeleteIcon;
    default:
      return ArticleIcon;
  }
};

interface CustomTreeItemProps
  extends
    Omit<UseTreeItemParameters, 'rootRef'>,
    Omit<React.HTMLAttributes<HTMLLIElement>, 'onFocus'> {}

const CustomTreeItem = React.forwardRef(function CustomTreeItem(
  props: CustomTreeItemProps,
  ref: React.Ref<HTMLLIElement>,
) {
  const { id, itemId, label, disabled, children, ...other } = props;

  const {
    getContextProviderProps,
    getRootProps,
    getContentProps,
    getIconContainerProps,
    getCheckboxProps,
    getLabelProps,
    getGroupTransitionProps,
    getDragAndDropOverlayProps,
    status,
  } = useTreeItem({ id, itemId, children, label, disabled, rootRef: ref });

  const item = useTreeItemModel<ExtendedTreeItemProps>(itemId)!;

  let icon;
  if (status.expandable) {
    icon = FolderRounded;
  } else if (item.fileType) {
    icon = getIconFromFileType(item.fileType);
  }

  return (
    <TreeItemProvider {...getContextProviderProps()}>
      <TreeItemRoot {...getRootProps(other)}>
        <TreeItemContent {...getContentProps()}>
          <TreeItemIconContainer {...getIconContainerProps()}>
            <TreeItemIcon status={status} />
          </TreeItemIconContainer>
          <TreeItemCheckbox {...getCheckboxProps()} />
          <CustomLabel
            {...getLabelProps({
              icon,
              expandable: status.expandable && status.expanded,
            })}
          />
          <TreeItemDragAndDropOverlay {...getDragAndDropOverlayProps()} />
        </TreeItemContent>
        {children && <TransitionComponent {...getGroupTransitionProps()} />}
      </TreeItemRoot>
    </TreeItemProvider>
  );
});

export default function FileExplorer() {
  return (
    <RichTreeView
      items={ITEMS}
      defaultExpandedItems={['1', '1.1']}
      defaultSelectedItems="1.1"
      sx={{ height: 'fit-content', flexGrow: 1, maxWidth: 400, overflowY: 'auto' }}
      slots={{ item: CustomTreeItem }}
      itemChildrenIndentation={24}
    />
  );
}

더 알아보기 (Learn more)