Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(TreeList): new useList family component #1417

Merged
merged 7 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/components/Table/__stories__/Table.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ const WithTableActionsTemplate: StoryFn<TableProps<DataItem>> = (args) => {
}

const items = ['action 1', 'action 2', 'action 3'];
return <TreeSelect items={items} size="s" />;

return (
<TreeSelect items={items} size="s" getItemContent={(title) => ({title})} />
);
}}
/>
</React.Fragment>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ const tableColumnSetupCn = b(null);
const controlsCn = b('controls');
const requiredDndItemCn = b('required-item');

function identity<T>(value: T): T {
return value;
}

const reorderArray = <T extends unknown>(list: T[], startIndex: number, endIndex: number): T[] => {
const result = [...list];
const [removed] = result.splice(startIndex, 1);
Expand Down Expand Up @@ -152,7 +156,7 @@ const useDndRenderItem = (sortable: boolean | undefined) => {
{...provided.draggableProps}
{...provided.dragHandleProps}
style={style}
active={snapshot.isDragging}
dragging={snapshot.isDragging}
/>
);
}}
Expand Down Expand Up @@ -277,6 +281,7 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {
return (
<TreeSelect
className={tableColumnSetupCn}
getItemContent={identity}
multiple
size="l"
open={open}
Expand Down
127 changes: 127 additions & 0 deletions src/components/TreeList/TreeList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import React from 'react';

import {useUniqId} from '../../hooks';
import {ListItemView, getItemRenderState, useList, useListKeydown} from '../useList';
import type {ListItemId} from '../useList';
import {block} from '../utils/cn';

import {TreeListContainer} from './components/TreeListContainer/TreeListContainer';
import type {TreeListProps, TreeListRenderContainerProps} from './types';

const b = block('tree-list');

export const TreeList = <T,>({
id,
size = 'm',
items,
className,
expandedById,
disabledById,
activeItemId,
selectedById,
getId,
renderItem: propsRenderItem,
renderContainer = TreeListContainer,
onItemClick,
multiple,
setActiveItemId,
containerRef: propsContainerRef,
getItemContent,
}: TreeListProps<T>) => {
const uniqId = useUniqId();
const treeListId = id ?? uniqId;
const containerRefLocal = React.useRef<HTMLDivElement>(null);
const containerRef = propsContainerRef ?? containerRefLocal;

const listParsedState = useList({
items,
getId,
expandedById,
disabledById,
activeItemId,
selectedById,
});

const handleItemClick = React.useCallback(
(listItemId: ListItemId) => {
onItemClick?.({
id: listItemId,
data: listParsedState.itemsById[listItemId],
isGroup: listItemId in listParsedState.groupsState,
disabled: disabledById
? Boolean(disabledById[listItemId])
: Boolean(listParsedState.initialState.disabledById[listItemId]),
isLastItem:
listParsedState.visibleFlattenIds[
listParsedState.visibleFlattenIds.length - 1
] === listItemId,
});
},
[
disabledById,
listParsedState.groupsState,
listParsedState.initialState.disabledById,
listParsedState.itemsById,
listParsedState.visibleFlattenIds,
onItemClick,
],
);

useListKeydown({
containerRef,
onItemClick: handleItemClick,
...listParsedState,
activeItemId,
disabledById,
setActiveItemId,
});

const renderItem: TreeListRenderContainerProps<T>['renderItem'] = (
itemId,
index,
renderContextProps,
) => {
const renderState = getItemRenderState({
id: itemId,
size,
onItemClick: handleItemClick,
...listParsedState,
expandedById,
disabledById,
activeItemId,
selectedById,
});

// redefining the view logic for groups and multiple selection of list items
renderState.props.hasSelectionIcon = Boolean(multiple) && !renderState.context.groupState;

if (propsRenderItem) {
return propsRenderItem({
data: renderState.data,
props: renderState.props,
itemState: renderState.context,
index,
renderContext: renderContextProps,
});
}

return (
<ListItemView
{...renderState.props}
{...getItemContent(listParsedState.itemsById[itemId])}
{...renderContextProps}
/>
);
};

// not JSX decl here is from weird `react-beautiful-dnd` render bug
return renderContainer({
id: `list-${treeListId}`,
size,
containerRef,
className: b(null, className),
...listParsedState,
...{expandedById, disabledById, activeItemId, selectedById},
renderItem,
});
};
58 changes: 58 additions & 0 deletions src/components/TreeList/__stories__/TreeList.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type {Meta, StoryObj} from '@storybook/react';

import {TreeList} from '../TreeList';

import {DefaultStory} from './stories/DefaultStory';
import {InfinityScrollStory} from './stories/InfinityScrollStory';
import {WithDndListStory} from './stories/WithDndListStory';
import {WithFiltrationAndControlsStory} from './stories/WithFiltrationAndControlsStory';
import {WithGroupSelectionAndCustomIconStory} from './stories/WithGroupSelectionAndCustomIconStory';
import {WithItemLinksAndActionsStory} from './stories/WithItemLinksAndActionsStory';

export default {
title: 'Unstable/TreeList',
component: TreeList,
} as Meta;

type DefaultStoryObj = StoryObj<typeof DefaultStory>;

export const Default: DefaultStoryObj = {
render: DefaultStory,
};

type InfinityScrollStoryObj = StoryObj<typeof InfinityScrollStory>;

export const InfinityScroll: InfinityScrollStoryObj = {
render: InfinityScrollStory,
};

type WithDndListStoryObj = StoryObj<typeof WithDndListStory>;

export const WithDndList: WithDndListStoryObj = {
parameters: {
// Strict mode ruins sortable list due to this react-beautiful-dnd issue
// https://github.com/atlassian/react-beautiful-dnd/issues/2350
disableStrictMode: true,
},
render: WithDndListStory,
};

type WithFiltrationAndControlsStoryObj = StoryObj<typeof WithFiltrationAndControlsStory>;

export const WithFiltrationAndControls: WithFiltrationAndControlsStoryObj = {
render: WithFiltrationAndControlsStory,
};

type WithGroupSelectionAndCustomIconStoryObj = StoryObj<
typeof WithGroupSelectionAndCustomIconStory
>;

export const WithGroupSelectionAndCustomIcon: WithGroupSelectionAndCustomIconStoryObj = {
render: WithGroupSelectionAndCustomIconStory,
};

type WithItemLinksAndActionsStoryObj = StoryObj<typeof WithItemLinksAndActionsStory>;

export const WithItemLinksAndActions: WithItemLinksAndActionsStoryObj = {
render: WithItemLinksAndActionsStory,
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';

import {ListContainerView, computeItemSize} from '../../../useList';
import {VirtualizedListContainer} from '../../../useList/__stories__/components/VirtualizedListContainer';
import type {TreeSelectRenderContainerProps} from '../../types';
import type {TreeListRenderContainerProps} from '../../types';

// custom container renderer example
export const RenderVirtualizedContainer = <T,>({
Expand All @@ -11,7 +11,7 @@ export const RenderVirtualizedContainer = <T,>({
visibleFlattenIds,
renderItem,
size,
}: TreeSelectRenderContainerProps<T>) => {
}: TreeListRenderContainerProps<T>) => {
return (
<ListContainerView fixedHeight id={id} ref={containerRef}>
<VirtualizedListContainer
Expand Down
25 changes: 25 additions & 0 deletions src/components/TreeList/__stories__/stories/DefaultStory.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import React from 'react';

import {Flex} from '../../../layout';
import {createRandomizedData} from '../../../useList/__stories__/utils/makeData';
import {TreeList} from '../../TreeList';
import type {TreeListProps} from '../../types';

function identity<T>(value: T): T {
return value;
}

export interface DefaultStoryProps
extends Omit<TreeListProps<{title: string}>, 'items' | 'getItemContent'> {
itemsCount?: number;
}

export const DefaultStory = ({itemsCount = 5, ...props}: DefaultStoryProps) => {
const items = React.useMemo(() => createRandomizedData({num: itemsCount}), [itemsCount]);

return (
<Flex width="500">
<TreeList {...props} items={items} getItemContent={identity} />
</Flex>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import React from 'react';

import {Label} from '../../../Label';
import {Loader} from '../../../Loader';
import {Flex, spacing} from '../../../layout';
import {ListItemView, useListState} from '../../../useList';
import {IntersectionContainer} from '../../../useList/__stories__/components/IntersectionContainer/IntersectionContainer';
import {useInfinityFetch} from '../../../useList/__stories__/utils/useInfinityFetch';
import {TreeList} from '../../TreeList';
import type {TreeListOnItemClick, TreeListProps} from '../../types';
import {RenderVirtualizedContainer} from '../components/RenderVirtualizedContainer';

function identity<T>(value: T): T {
return value;
}

export interface InfinityScrollStoryProps
extends Omit<
TreeListProps<{title: string}>,
'value' | 'onUpdate' | 'items' | 'multiple' | 'size' | 'getItemContent'
> {
itemsCount?: number;
}

export const InfinityScrollStory = ({itemsCount = 5, ...storyProps}: InfinityScrollStoryProps) => {
const listState = useListState();

const handleItemClick: TreeListOnItemClick<{title: string}> = ({id, isGroup, disabled}) => {
if (disabled) return;

listState.setActiveItemId(id);

if (isGroup) {
listState.setExpanded((prevState) => ({
...prevState,
[id]: id in prevState ? !prevState[id] : false,
}));
} else {
listState.setSelected((prevState) => ({
...prevState,
[id]: !prevState[id],
}));
}
};

const {
data: items = [],
onFetchMore,
canFetchMore,
isLoading,
} = useInfinityFetch<{title: string}>(itemsCount, true);

return (
<Flex direction="column">
<TreeList
size="l"
{...storyProps}
{...listState}
getItemContent={identity}
items={items}
multiple
onItemClick={handleItemClick}
renderItem={({data, props, itemState: {isLastItem, groupState}}) => {
const node = (
<ListItemView
{...props}
{...data}
endSlot={
groupState ? (
<Label>{groupState.childrenIds.length}</Label>
) : undefined
}
/>
);

if (isLastItem) {
return (
<IntersectionContainer
onIntersect={canFetchMore ? onFetchMore : undefined}
>
{node}
</IntersectionContainer>
);
}

return node;
}}
renderContainer={RenderVirtualizedContainer}
/>
{isLoading && (
<Flex justifyContent="center" className={spacing({py: 2})}>
<Loader size={'m'} />
</Flex>
)}
</Flex>
);
};
Loading
Loading