UNPKG

@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.

329 lines (326 loc) 11.6 kB
import { jsx, jsxs, Fragment } from 'react/jsx-runtime'; import { useAiChatMessages, RegisterAiKnowledge, RegisterAiTool } 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 { AiChatComposer } from './internal/AiChatComposer.js'; import { AiChatUserMessage } from './internal/AiChatUserMessage.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, copilotId, overrides, components, 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 = null; let footerHeight = null; let messagesHeight = null; const resetTrailingSpace = () => { trailingSpacer?.style.removeProperty("height"); bottomTrailingMarker?.style.removeProperty("top"); }; const resizeObserver = new ResizeObserver((entries) => { if (!trailingSpacer || !bottomTrailingMarker) { return; } const lastMessage = messages2.lastElementChild; const penultimateMessage = lastMessage?.previousElementSibling; if (!lastMessage || !penultimateMessage) { resetTrailingSpace(); return; } if (container.scrollHeight === container.clientHeight) { resetTrailingSpace(); return; } 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 ?? null; } else if (entry.target === footer) { updatedFooterHeight = entryHeight ?? null; } else if (entry.target === messages2) { updatedMessagesHeight = entryHeight ?? null; } } if (updatedContainerHeight === null || updatedFooterHeight === null || updatedMessagesHeight === null) { resetTrailingSpace(); return; } if (updatedContainerHeight === containerHeight && updatedFooterHeight === footerHeight && updatedMessagesHeight === messagesHeight) { return; } containerHeight = updatedContainerHeight; footerHeight = updatedFooterHeight; messagesHeight = updatedMessagesHeight; 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`; }); resizeObserver.observe(container); resizeObserver.observe(footer); resizeObserver.observe(messages2); return () => { resizeObserver.disconnect(); resetTrailingSpace(); }; }, [hasLastSentMessage] ); useIntersectionCallback( bottomTrailingMarkerRef, (isIntersecting) => { onScrollAtBottomChange.current(isIntersecting); }, { root: containerRef, rootMargin: MIN_DISTANCE_BOTTOM_SCROLL_INDICATOR } ); useEffect( () => { scrollToBottom.current("instant"); }, [] ); useEffect( () => { if (lastSentMessageId) { scrollToBottom.current("smooth", true); } }, [lastSentMessageId] ); useEffect( () => { const onScrollAtBottomChangeCallback = onScrollAtBottomChange.current; return () => { onScrollAtBottomChangeCallback(null); }; }, [] ); 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 }, message.id); } else if (message.role === "assistant") { return /* @__PURE__ */ jsx(AiChatAssistantMessage, { message, overrides, components, copilotId }, message.id); } else { return null; } }) }); } ); const AiChat = forwardRef( ({ chatId, copilotId, autoFocus, overrides, knowledge, tools = {}, layout = "inset", components, className, ...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) { requestAnimationFrame(() => { bottomMarkerRef.current?.scrollIntoView({ behavior, block: "end" }); }); } else { bottomTrailingMarkerRef.current?.scrollIntoView({ behavior, block: "end" }); } } ); return /* @__PURE__ */ jsxs("div", { ref: containerRef, ...props, className: cn( "lb-root lb-ai-chat", layout === "compact" ? "lb-ai-chat:layout-compact" : "lb-ai-chat:layout-inset", className ), children: [ knowledge ? knowledge.map((source, index) => /* @__PURE__ */ jsx(RegisterAiKnowledge, { description: source.description, value: source.value }, index)) : null, Object.entries(tools).map(([name, tool]) => /* @__PURE__ */ jsx(RegisterAiTool, { chatId, name, tool }, name)), /* @__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, { ref: messagesRef, copilotId, messages, overrides, components, lastSentMessageId, scrollToBottom, onScrollAtBottomChange, containerRef, footerRef, messagesRef, bottomTrailingMarkerRef, trailingSpacerRef }), /* @__PURE__ */ jsx("div", { ref: trailingSpacerRef, "data-trailing-spacer": "", style: { pointerEvents: "none" }, "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(AiChatComposer, { chatId, copilotId, overrides, autoFocus, onUserMessageCreate: ({ id }) => setLastSentMessageId(id), className: 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