@liveblocks/react-ui
Version:
A set of React pre-built components for the Liveblocks products. Liveblocks is the all-in-one toolkit to build collaborative products like Figma, Notion, and more.
392 lines (389 loc) • 13.8 kB
JavaScript
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useAiChatMessages, RegisterAiTool, RegisterAiKnowledge } from '@liveblocks/react';
import { useLatest } from '@liveblocks/react/_private';
import { forwardRef, useEffect, useState, useRef, useImperativeHandle } from 'react';
import { ArrowDownIcon } from '../icons/ArrowDown.js';
import { SpinnerIcon } from '../icons/Spinner.js';
import { useOverrides } from '../overrides.js';
import { cn } from '../utils/cn.js';
import { useIntersectionCallback } from '../utils/use-visible.js';
import { AiChatAssistantMessage } from './internal/AiChatAssistantMessage.js';
import { AiChatUserMessage } from './internal/AiChatUserMessage.js';
import { AiComposer } from './internal/AiComposer.js';
const MIN_DISTANCE_BOTTOM_SCROLL_INDICATOR = 60;
const defaultComponents = {
Empty: () => null,
Loading: () => /* @__PURE__ */ jsx("div", { className: "lb-loading lb-ai-chat-loading", children: /* @__PURE__ */ jsx(SpinnerIcon, {}) })
};
const AiChatMessages = forwardRef(
({
messages,
overrides,
components,
showReasoning,
showRetrievals,
showSources,
lastSentMessageId,
scrollToBottom,
onScrollAtBottomChange,
containerRef,
footerRef,
messagesRef,
bottomTrailingMarkerRef,
trailingSpacerRef,
className,
...props
}, forwardedRef) => {
const hasLastSentMessage = lastSentMessageId !== null;
useEffect(
() => {
if (!hasLastSentMessage) {
return;
}
const container = containerRef.current;
const footer = footerRef.current;
const messages2 = messagesRef.current;
if (!container || !footer || !messages2) {
return;
}
const trailingSpacer = trailingSpacerRef.current;
const bottomTrailingMarker = bottomTrailingMarkerRef.current;
let containerHeight = void 0;
let footerHeight = void 0;
let messagesHeight = void 0;
const resetTrailingSpace = () => {
trailingSpacer?.style.removeProperty("height");
bottomTrailingMarker?.style.removeProperty("top");
};
const updateTrailingSpace = (updatedContainerHeight, updatedFooterHeight, updatedMessagesHeight) => {
if (!trailingSpacer || !bottomTrailingMarker) {
return;
}
const lastMessage = messages2.lastElementChild;
const penultimateMessage = lastMessage?.previousElementSibling;
if (updatedContainerHeight === void 0) {
updatedContainerHeight = container.getBoundingClientRect().height;
}
if (updatedFooterHeight === void 0) {
updatedFooterHeight = footer.getBoundingClientRect().height;
}
if (updatedMessagesHeight === void 0) {
updatedMessagesHeight = messages2.getBoundingClientRect().height;
}
if (updatedContainerHeight === containerHeight && updatedFooterHeight === footerHeight && updatedMessagesHeight === messagesHeight) {
if (!lastMessage || !penultimateMessage || container.scrollHeight === container.clientHeight) {
resetTrailingSpace();
}
return;
}
containerHeight = updatedContainerHeight;
footerHeight = updatedFooterHeight;
messagesHeight = updatedMessagesHeight;
if (!lastMessage || !penultimateMessage) {
resetTrailingSpace();
return;
}
if (container.scrollHeight === container.clientHeight) {
resetTrailingSpace();
return;
}
const penultimateMessageScrollMarginTop = Number.parseFloat(
getComputedStyle(penultimateMessage).scrollMarginTop
);
const messagesRect = messages2.getBoundingClientRect();
const penultimateMessageRect = penultimateMessage.getBoundingClientRect();
const heightFromPenultimateMessageTopToMessagesListBottom = messagesRect.bottom - penultimateMessageRect.top;
const differenceHeight = penultimateMessageScrollMarginTop + heightFromPenultimateMessageTopToMessagesListBottom + (footerHeight ?? 0);
const trailingSpace = Math.max(containerHeight - differenceHeight, 0);
trailingSpacer.style.height = `${trailingSpace}px`;
bottomTrailingMarker.style.top = `${-trailingSpace}px`;
};
const resizeObserver = new ResizeObserver((entries) => {
let updatedContainerHeight = containerHeight;
let updatedFooterHeight = footerHeight;
let updatedMessagesHeight = messagesHeight;
for (const entry of entries) {
const entryHeight = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;
if (entry.target === container) {
updatedContainerHeight = entryHeight;
} else if (entry.target === footer) {
updatedFooterHeight = entryHeight;
} else if (entry.target === messages2) {
updatedMessagesHeight = entryHeight;
}
}
updateTrailingSpace(
updatedContainerHeight,
updatedFooterHeight,
updatedMessagesHeight
);
});
resizeObserver.observe(container);
resizeObserver.observe(footer);
resizeObserver.observe(messages2);
requestAnimationFrame(() => updateTrailingSpace());
return () => {
resizeObserver.disconnect();
resetTrailingSpace();
};
},
// This effect only uses stable refs.
[hasLastSentMessage]
// eslint-disable-line react-hooks/exhaustive-deps
);
useIntersectionCallback(
bottomTrailingMarkerRef,
(isIntersecting) => {
onScrollAtBottomChange.current(isIntersecting);
},
{ root: containerRef, rootMargin: MIN_DISTANCE_BOTTOM_SCROLL_INDICATOR }
);
useEffect(
() => {
scrollToBottom.current("instant");
},
// `scrollToBottom` is a stable ref containing the callback.
[]
// eslint-disable-line react-hooks/exhaustive-deps
);
useEffect(
() => {
if (lastSentMessageId) {
scrollToBottom.current("smooth", true);
}
},
// `scrollToBottom` is a stable ref containing the callback.
[lastSentMessageId]
// eslint-disable-line react-hooks/exhaustive-deps
);
useEffect(
() => {
const onScrollAtBottomChangeCallback = onScrollAtBottomChange.current;
return () => {
onScrollAtBottomChangeCallback(null);
};
},
// `onScrollAtBottomChange` is a stable ref containing the callback.
[]
// eslint-disable-line react-hooks/exhaustive-deps
);
return /* @__PURE__ */ jsx(
"div",
{
className: cn("lb-ai-chat-messages", className),
ref: forwardedRef,
...props,
children: messages.map((message) => {
if (message.role === "user") {
return /* @__PURE__ */ jsx(
AiChatUserMessage,
{
message,
overrides,
components
},
message.id
);
} else if (message.role === "assistant") {
return /* @__PURE__ */ jsx(
AiChatAssistantMessage,
{
message,
overrides,
components,
showReasoning,
showRetrievals,
showSources
},
message.id
);
} else {
return null;
}
})
}
);
}
);
function scrollIntoView(element, options) {
if (!element) {
return;
}
if (element.getClientRects().length === 0) {
return;
}
element.scrollIntoView(options);
}
const AiChat = forwardRef(
({
chatId,
copilotId,
autoFocus,
overrides,
knowledge: localKnowledge,
tools = {},
onComposerSubmit,
layout = "inset",
showReasoning,
showRetrievals,
showSources,
components,
className,
responseTimeout,
...props
}, forwardedRef) => {
const { messages, isLoading, error } = useAiChatMessages(chatId);
const [lastSentMessageId, setLastSentMessageId] = useState(null);
const $ = useOverrides(overrides);
const Empty = components?.Empty ?? defaultComponents.Empty;
const Loading = components?.Loading ?? defaultComponents.Loading;
const containerRef = useRef(null);
const messagesRef = useRef(null);
const footerRef = useRef(null);
const bottomMarkerRef = useRef(null);
const bottomTrailingMarkerRef = useRef(null);
const trailingSpacerRef = useRef(null);
const [isScrollAtBottom, setScrollAtBottom] = useState(
null
);
const onScrollAtBottomChange = useLatest(setScrollAtBottom);
const isScrollIndicatorVisible = messages && isScrollAtBottom !== null ? !isScrollAtBottom : false;
useImperativeHandle(
forwardedRef,
() => containerRef.current,
[]
);
const scrollToBottom = useLatest(
(behavior, includeTrailingSpace = false) => {
if (includeTrailingSpace) {
setTimeout(() => {
scrollIntoView(bottomMarkerRef.current, {
behavior,
block: "end"
});
}, 0);
} else {
scrollIntoView(bottomTrailingMarkerRef.current, {
behavior,
block: "end"
});
}
}
);
return /* @__PURE__ */ jsxs(
"div",
{
ref: containerRef,
...props,
className: cn(
"lb-root lb-ai-chat",
`lb-ai-chat:layout-${layout}`,
className
),
children: [
Object.entries(tools).map(([name, tool]) => /* @__PURE__ */ jsx(RegisterAiTool, { chatId, name, tool }, name)),
localKnowledge ? localKnowledge.map((knowledge, index) => /* @__PURE__ */ jsx(
RegisterAiKnowledge,
{
chatId,
...knowledge
},
`${index}:${knowledge.description}`
)) : null,
/* @__PURE__ */ jsx("div", { className: "lb-ai-chat-content", children: isLoading ? /* @__PURE__ */ jsx(Loading, {}) : error !== void 0 ? /* @__PURE__ */ jsx("div", { className: "lb-error lb-ai-chat-error", children: $.AI_CHAT_MESSAGES_ERROR(error) }) : messages.length === 0 ? /* @__PURE__ */ jsx(Empty, { chatId, copilotId }) : /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
AiChatMessages,
{
messages,
overrides,
components,
showReasoning,
showRetrievals,
showSources,
lastSentMessageId,
scrollToBottom,
onScrollAtBottomChange,
containerRef,
footerRef,
messagesRef,
bottomTrailingMarkerRef,
trailingSpacerRef,
ref: forwardedRef
}
),
/* @__PURE__ */ jsx(
"div",
{
ref: trailingSpacerRef,
"data-trailing-spacer": "",
style: {
pointerEvents: "none",
height: 0
},
"aria-hidden": true
}
)
] }) }),
/* @__PURE__ */ jsxs("div", { className: "lb-ai-chat-footer", ref: footerRef, children: [
/* @__PURE__ */ jsx("div", { className: "lb-ai-chat-footer-actions", children: /* @__PURE__ */ jsx(
"div",
{
className: "lb-root lb-elevation lb-elevation-moderate lb-ai-chat-scroll-indicator",
"data-visible": isScrollIndicatorVisible ? "" : void 0,
children: /* @__PURE__ */ jsx(
"button",
{
className: "lb-ai-chat-scroll-indicator-button",
tabIndex: isScrollIndicatorVisible ? 0 : -1,
"aria-hidden": !isScrollIndicatorVisible,
onClick: () => scrollToBottom.current("smooth"),
children: /* @__PURE__ */ jsx("span", { className: "lb-icon-container", children: /* @__PURE__ */ jsx(ArrowDownIcon, {}) })
}
)
}
) }),
/* @__PURE__ */ jsx(
AiComposer,
{
chatId,
copilotId,
overrides,
autoFocus,
responseTimeout,
onComposerSubmit,
onComposerSubmitted: ({ id }) => setLastSentMessageId(id),
className: cn(
"lb-ai-chat-composer",
layout === "inset" ? "lb-elevation lb-elevation-moderate" : void 0
)
},
chatId
)
] }),
messages && messages.length > 0 ? /* @__PURE__ */ jsx(
"div",
{
ref: bottomMarkerRef,
style: { position: "sticky", height: 0 },
"aria-hidden": true,
"data-bottom-marker": "",
children: /* @__PURE__ */ jsx(
"div",
{
ref: bottomTrailingMarkerRef,
style: {
position: "absolute",
height: 0
},
"data-bottom-trailing-marker": ""
}
)
}
) : null
]
}
);
}
);
export { AiChat };
//# sourceMappingURL=AiChat.js.map