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

refactor: Bubble.List re-render #479

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
10 changes: 8 additions & 2 deletions components/bubble/Bubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,16 @@ const Bubble: React.ForwardRefRenderFunction<BubbleRef, BubbleProps> = (props, r
);

// ============================ Avatar ============================
const avatarNode = React.isValidElement(avatar) ? avatar : <Avatar {...avatar} />;
const avatarNode = React.useMemo(
() => (React.isValidElement(avatar) ? avatar : <Avatar {...avatar} />),
[avatar],
);

// =========================== Content ============================
const mergedContent = messageRender ? messageRender(typedContent as any) : typedContent;
const mergedContent = React.useMemo(
() => (messageRender ? messageRender(typedContent as any) : typedContent),
[typedContent, messageRender],
);

// ============================ Render ============================
let contentNode: React.ReactNode;
Expand Down
45 changes: 25 additions & 20 deletions components/bubble/BubbleList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import * as React from 'react';
import { useXProviderContext } from '../x-provider';
import Bubble, { BubbleContext } from './Bubble';
import type { BubbleRef } from './Bubble';
import useDisplayData from './hooks/useDisplayData';
import useListData from './hooks/useListData';
import type { BubbleProps } from './interface';
import useStyle from './style';
Expand Down Expand Up @@ -37,6 +36,24 @@ export interface BubbleListProps extends React.HTMLAttributes<HTMLDivElement> {
roles?: RolesType;
}

const BubbleListItem: React.ForwardRefRenderFunction<Record<string, BubbleRef>, BubbleProps> = (
props,
ref,
) => (
<Bubble
{...props}
ref={(node) => {
if (node) {
(ref as React.RefObject<Record<string, BubbleRef>>).current[props.id!] = node;
} else {
delete (ref as React.RefObject<Record<string, BubbleRef>>).current?.[props.id!];
}
}}
/>
);

const MemoBubbleListItem = React.memo(React.forwardRef(BubbleListItem));

const TOLERANCE = 1;

const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps> = (props, ref) => {
Expand Down Expand Up @@ -80,8 +97,6 @@ const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps>
// ============================= Data =============================
const mergedData = useListData(items, roles);

const [displayData, onTypingComplete] = useDisplayData(mergedData);

// ============================ Scroll ============================
// Is current scrollTop at the end. User scroll will make this false.
const [scrollReachEnd, setScrollReachEnd] = React.useState(true);
Expand All @@ -108,7 +123,7 @@ const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps>
React.useEffect(() => {
if (autoScroll) {
// New date come, the origin last one is the second last one
const lastItemKey = displayData[displayData.length - 2]?.key;
const lastItemKey = mergedData[mergedData.length - 2]?.key;
const bubbleInst = bubbleRefs.current[lastItemKey!];

// Auto scroll if last 2 item is visible
Expand All @@ -124,7 +139,7 @@ const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps>
}
}
}
}, [displayData.length]);
}, [mergedData.length]);

// ========================== Outer Ref ===========================
React.useImperativeHandle(ref, () => ({
Expand All @@ -142,8 +157,8 @@ const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps>

if (bubbleInst) {
// Block current auto scrolling
const index = displayData.findIndex((dataItem) => dataItem.key === key);
setScrollReachEnd(index === displayData.length - 1);
const index = mergedData.findIndex((dataItem) => dataItem.key === key);
setScrollReachEnd(index === mergedData.length - 1);

// Do native scroll
bubbleInst.nativeElement.scrollIntoView({
Expand Down Expand Up @@ -181,22 +196,12 @@ const BubbleList: React.ForwardRefRenderFunction<BubbleListRef, BubbleListProps>
ref={listRef}
onScroll={onInternalScroll}
>
{displayData.map(({ key, ...bubble }) => (
<Bubble
{mergedData.map(({ key, ...bubble }) => (
<MemoBubbleListItem
{...bubble}
key={key}
ref={(node) => {
if (node) {
bubbleRefs.current[key] = node;
} else {
delete bubbleRefs.current[key];
}
}}
ref={bubbleRefs}
typing={initialized ? bubble.typing : false}
onTypingComplete={() => {
bubble.onTypingComplete?.();
onTypingComplete(key);
}}
/>
))}
</div>
Expand Down
7 changes: 7 additions & 0 deletions components/bubble/demo/debug-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## zh-CN

仅用于调制多种场景 Bubble.List 是否符合预期

## en-US

Only use in debug to check Bubble.List
107 changes: 107 additions & 0 deletions components/bubble/demo/debug-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { Bubble } from '@ant-design/x';
import { App, Button, Flex, type GetProps, type GetRef, Select } from 'antd';
import React from 'react';

type BubbleListItems = Required<GetProps<typeof Bubble.List>>['items'];

const Demo = () => {
const { message } = App.useApp();

const [bubbleList, setBubbleList] = React.useState<BubbleListItems>([
{
id: '0',
key: '0',
content: `#0 - message content`,
typing: true,
},
]);

const listRef = React.useRef<GetRef<typeof Bubble.List>>(null);

// add a new bubble to the beginning of the list
function unshiftBubble() {
const firstId = bubbleList[0]?.id;

const id = `${firstId !== undefined ? Number(firstId) - 1 : 0}`;

setBubbleList((preList) => [
{
id,
key: id,
content: `#${id} - message content`,
},
...preList,
]);

message.success(`#${id} message rendered!`);
}

// add a new bubble to the end of the list
function pushBubble() {
const lastId = bubbleList[bubbleList.length - 1]?.id;

const id = `${lastId !== undefined ? Number(lastId) + 1 : 0}`;

setBubbleList((preList) => [
...preList,
{
id,
key: id,
content: `#${id} - message content`,
typing: true,
},
]);

message.success(`#${id} message rendered!`);
}

YumoImer marked this conversation as resolved.
Show resolved Hide resolved
// remove a bubble from the list
function deleteBubble(id: string) {
setBubbleList((preList) => preList.filter((item) => item.id !== id));

message.success(`#${id} message deleted!`);
}

function scrollTo(id: number) {
listRef.current?.scrollTo?.({ key: id, block: 'nearest' });

message.success(`scroll to #${id} message!`);
}

const selectOptions = React.useMemo(
() =>
bubbleList.map((item) => ({
value: item.id,
label: item.content,
})),
[bubbleList],
);

return (
<Flex vertical gap={16}>
<Flex gap={16}>
<Button onClick={unshiftBubble}>unshift bubble</Button>
<Button onClick={pushBubble}>push bubble</Button>
<Select
placeholder="delete bubble"
style={{ width: 200 }}
onChange={deleteBubble}
options={selectOptions}
/>
<Select
placeholder="scroll to"
style={{ width: 200 }}
onChange={scrollTo}
options={selectOptions}
/>
</Flex>
<Bubble.List style={{ height: 300, overflow: 'auto' }} items={bubbleList} ref={listRef} />
</Flex>
);
};

export default () => (
<App>
<Demo />
</App>
);
42 changes: 0 additions & 42 deletions components/bubble/hooks/useDisplayData.ts

This file was deleted.

1 change: 1 addition & 0 deletions components/bubble/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Often used when chatting.

<!-- prettier-ignore -->
<code src="./demo/debug.tsx" debug>debug</code>
<code src="./demo/debug-list.tsx" debug>debug list</code>
<code src="./demo/basic.tsx">Basic</code>
<code src="./demo/avatar-and-placement.tsx">Placement and avatar</code>
<code src="./demo/header-and-footer.tsx">Header and footer</code>
Expand Down
1 change: 1 addition & 0 deletions components/bubble/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ demo:

<!-- prettier-ignore -->
<code src="./demo/debug.tsx" debug>debug</code>
<code src="./demo/debug-list.tsx" debug>debug list</code>
<code src="./demo/basic.tsx">基本</code>
<code src="./demo/avatar-and-placement.tsx">支持位置和头像</code>
<code src="./demo/header-and-footer.tsx">头和尾</code>
Expand Down
Loading