Explore here ism y mark down, for some reason it is not being rendered with the line breaks? \n?… Save Share Download ▾ ReportJump to turn (7) 1 here ism y mark down, for some reason it is not being rendered with the line bre 2 Here is my message row and message content files respectively. Can you modify my 3 the persistent highlighting is fixed but it is not correctly putting the annotat 4 could we change the code such that the annotations store the start and end numbe 5 can you please get rid of const [annotationStart, setAnnotationStart] = useState 6 This code is completely broken, now the annotate box appears before the user hig 7 Ok here is my code base again MessageRow and MessageContent respectively. Right here ism y mark down, for some reason it is not being rendered with the line breaks? \n? return <Markdown
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
text={text}
renderLaTex={true}
customComponents={{
img: MarkdownImage as any,
cite: CitationTextHighlighter as any,
table: DataTable as any,
}}
/>
Assistant2024-05-14 21:38 UTC Copy response
Copy first prompt Copy first response
Details
Provider openai
Model provenance As recorded by source dataset
Turns 7 (14 messages)
Language en
Added to archive Nov 24, 2026
ID 01m867701g85hwrrx67px2pwrvSource & license Imported from WildChat-4.8M (source ). Imported records earn no Research Points.
Upstream record: 3d8be1875915091a2fd7430ed34af28b
allenai/WildChat-4.8M, revision c827c6df8fcf008219ffaffa4d1dd77491099367
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
Markdown by default does not recognize \n as a line break; it needs either two spaces at the end of a line or an actual line break. Here are some steps you can take to ensure your line breaks are rendered correctly:
Ensure Proper Line Breaks in Markdown Text
Two Spaces at End of Line: Ensure that each line you want to break ends with two spaces.
Double Line Break: Use two line breaks (newlines) to start a new paragraph.
Example:
Consider a markdown string text:
markdown Copy code
const text = `This is the first line.
This is the second line.
This is the third line.`
Notice:
The first line ends with two spaces ("line. ").
There are double newlines between the second and third lines.
React Component Adjustments
Using a well-configured React Markdown component can simplify this. Ensure your Markdown component or library properly handles these conventions.
Using react-markdown library:
You might be using a library like react-markdown, which allows additional configuration. Although your component seems custom, the general principle should apply.
Here's an example configuration using react-markdown:
tsx Copy code
import React from 'react';
import ReactMarkdown from 'react-markdown';
import cn from 'classnames'; // Assuming you use classnames for styling
const MarkdownImage = (props) => {
// Define the custom image component
};
const CitationTextHighlighter = (props) => {
// Define the custom citation component
};
const DataTable = (props) => {
// Define the custom table component
};
const MyMarkdownComponent = ({ text }) => {
return (
<ReactMarkdown
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
children={text}
components={{
img: MarkdownImage,
cite: CitationTextHighlighter,
table: DataTable,
}}
/>
);
};
export default MyMarkdownComponent;
Additional Tips:
Verify Your Text: Ensure the text variable contains the required spacing and newlines at appropriate places.
Custom Renderers: Depending on the library you use, custom components might need specific handling for rendering children correctly.
In your provided code example, ensuring text contains the appropriate markdown syntax and leveraging a robust Markdown rendering library should resolve line break issues. If issues persist, consider library-specific documentation for additional configurations.
Here is my message row and message content files respectively. Can you modify my annotation code such that the box actually appears in place of the message text. i.e it positions itself as part of the message and pushes text after the annotation to the right as the annotation grows as it is typed. Also can you make the highlight persistent as well when an annotation is created? import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Markdown,
Tooltip,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
code Copy code
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
Show full message · 531 lines Assistant2024-05-14 23:24 UTC Copy response
To ensure annotations are properly incorporated into your message rendering logic such that they appear inline with the text and push the rest of the text to the right, we'll focus on updating the annotated text rendering in MessageContent and the logic for adding new annotations.
Here's an updated version of your code with improvements:
Render annotated text inline within the message text .
Make the annotations persistent and aligned properly .
Modify the annotation input box position to appear inline as well .
Modified Code:
MessageRow Component:
Show full message · 549 lines the persistent highlighting is fixed but it is not correctly putting the annotation inline with the highlighted/selected text> I want the annotation box to also be persistent and in line please! Also dont let it break the markdown by having the annotation box within the text.
Assistant2024-05-14 23:41 UTC Copy response
To achieve inline annotations with a persistent annotation box that allows for annotations to be added without breaking the markdown text, we'll create a div that absolutely positions the annotation box at the correct location inline with the selected text.
Here's how you can adapt the provided code to achieve this behavior:
Step-by-Step Implementation:
Persistent Inline Annotation Box:
The annotation box needs to be positioned relative to the selected text.
We will use absolute positioning to place the annotation box correctly and ensure it stays within the content.
Ensure Markdown Integrity:
Ensure that the rendered markdown text is not broken by correctly segmenting and annotating parts.
Code Implementation:
MessageRow Component:
Show full message · 567 lines could we change the code such that the annotations store the start and end numbers for the indexing of annotations? so we have; type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
}; can you make the needed changes?
Assistant2024-05-14 23:55 UTC Copy response
Certainly! We can modify your code to store the start and end indices for each annotation and use these indices to properly render the annotated text inline without breaking Markdown formatting.
Here's how you can adapt the provided code to incorporate annotation indices:
Step-by-Step Implementation:
Store start and end indices in annotations:
Update the Annotation type to include start and end properties.
Modify the annotation creation logic to store these indices.
Render annotated text using the indices:
Use the stored indices to correctly segment and render annotations inline.
Code Implementation:
MessageRow Component:
Show full message · 569 lines can you please get rid of const [annotationStart, setAnnotationStart] = useState<number | null>(null);
const [annotationEnd, setAnnotationEnd] = useState<number | null>(null); altogether and use the start and end attributes of Annotate
Assistant2024-05-15 00:05 UTC Copy response
Certainly! Let's modify the code to utilize the start and end attributes directly from the Annotation type and remove the state management for annotationStart and annotationEnd.
Code Implementation:
MessageRow Component:
Show full message · 577 lines This code is completely broken, now the annotate box appears before the user highlights anything, plus highlighting anything does nothing...
Assistant2024-05-15 00:38 UTC Copy response
I'm sorry about the confusion. Let's fix and simplify the implementation to ensure the annotation box only appears when text is selected and the annotations are applied correctly. We'll ensure the annotation box does not appear before any text is highlighted and it allows for entering annotations properly.
Here's the step-by-step and corrected code:
Step-by-Step Implementation:
Show Annotation Input Box Only on Selection:
Ensure the annotation input box only appears when text is selected.
Keep tracking the start and end positions directly in the Annotation type.
Use the Selected Text for Annotation:
Display the annotation input box immediately after the selected text.
Use the start and end indices for further rendering and processing.
Code Implementation:
MessageRow Component:
Show full message · 576 lines Ok here is my code base again MessageRow and MessageContent respectively. Right now the annotation box doesnt show up, and the selected text is inserted within the message, and the selected text is not highlighted. can you make it so the selected text is highlighted, the annotation box is inserted instead of the selected text. import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Markdown,
Tooltip,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
Annotation,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
code Copy code
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
Show full message · 542 lines Assistant2024-05-15 01:01 UTC Copy response
To achieve the desired behavior where:
The selected text is highlighted.
An annotation input box appears immediately after the selected text.
The annotation input box is hidden initially and only shown upon text selection.
The annotated text is inserted into the main text content with the annotation input box in place.
Below is the refined implementation for MessageRow and MessageContent components.
Implementation:
MessageRow Component:
Show full message · 559 lines
Turns (7) const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
code Copy code
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotations code for error highlighing in prompts!!!
type Annotation = {
text: string;
annotation: string;
};
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationStart, setAnnotationStart] = useState<number | null>(null);
const [annotationEnd, setAnnotationEnd] = useState<number | null>(null);
const inputRef = useRef(null);
// Function to handle text selection
const handleMouseUp = (start: number, end: number) => {
const selection = window.getSelection();
if (selection && selection.toString()) {
setSelectedText(selection.toString());
setAnnotationStart(start);
setAnnotationEnd(end);
}
};
// Function to add annotation
const addAnnotation = (a: string) => {
const newAnnotations = [
...annotations,
{ text: selectedText, annotation: a }
];
code Copy code
setAnnotations(newAnnotations);
setSelectedText('');
setAnnotationStart(null);
setAnnotationEnd(null);
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
{hasSteps && (
<Button
label={${isStepsExpanded ? 'Hide' : 'Show'} steps}
startIcon={}
kind="secondary"
size="md"
aria-label={${isStepsExpanded ? 'Hide' : 'Show'} steps}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
code Copy code
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{//This is where we render the annotated box
}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
/>
{annotationStart !== null && annotationEnd !== null && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif' // Adjust the font family as needed
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
addAnnotation(target.value);
target.value = '';
}
}}
/>
)}
{//This was an old rendering pipeline.
}
{/**<MessageContent isLast={isLast} message={message} onRetry={onRetry} />*/}
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
import { Transition } from '@headlessui/react';
import { PropsWithChildren } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
};
export const MessageContent: React.FC = ({ isLast, message, onRetry, annotations = [], onAnnotate }) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
code Copy code
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return
}
code Copy code
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ text: annotatedText }, index) => {
const startIndex = text.indexOf(annotatedText, lastIndex);
if (startIndex !== -1) {
const endIndex = startIndex + annotatedText.length;
parts.push(
text.substring(lastIndex, startIndex),
<span key={index} className={cn("bg-yellow-100’, ‘annotated-text")}>
{annotatedText}
</span>
);
lastIndex = endIndex;
}
});
if (lastIndex < text.length) {
parts.push(text.substring(lastIndex));
}
return parts;
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
{message.text}
{message.error}
{isLast && (
Retry?
)}
</>
);
} else if (isUser) {
content = (
<>
{message.files && message.files.length > 0 && (
{message.files.map((file) => (
))}
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
{message.text}
)}
{!hasLoadingMessage && (
...
)}
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}
)}
{message.error}
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
{renderAnnotatedText(message.text)}
code Copy code
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
</>
);
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren & { type?: 'default' | 'error' }) => (
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotations code for error highlighting in prompts!!!
type Annotation = {
text: string;
annotation: string;
};
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState<string>("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationStart, setAnnotationStart] = useState<number | null>(null);
const [annotationEnd, setAnnotationEnd] = useState<number | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
setSelectedText(selection.toString());
setAnnotationStart(start);
setAnnotationEnd(end);
}
};
// Function to add an annotation
const addAnnotation = (a: string) => {
const newAnnotations = [
...annotations,
{ text: selectedText, annotation: a }
];
setAnnotations(newAnnotations);
setSelectedText('');
setAnnotationStart(null);
setAnnotationEnd(null);
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
/>
{annotationStart !== null && annotationEnd !== null && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif' // Adjust the font family as needed
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
addAnnotation(target.value);
target.value = '';
}
}}
/>
)}
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
};
export const MessageContent: React.FC<Props> = ({ isLast, message, onRetry, annotations = [], onAnnotate }) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return <Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ text: annotatedText }, index) => {
const startIndex = text.indexOf(annotatedText, lastIndex);
if (startIndex !== -1) {
const endIndex = startIndex + annotatedText.length;
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, startIndex)}</span>,
<span key={index} className={cn("bg-yellow-100", "annotated-text")}>
{annotatedText}
</span>
);
lastIndex = endIndex;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</Text>
</div>
);
};
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren & { type?: 'default' | 'error' }) => (
<div
className={cn('flex items-start gap-1', {
'text-volcanic-700': type === 'default',
'text-danger-500': type === 'error',
})}
>
<Icon name="warning" size="md" className="flex items-center text-p" />
<Text as="span">{children}</Text>
</div>
);
Key Changes:
MessageRow:
The handleMouseUp function should be attached correctly to manage text selection.
The MessageContent component is properly passed the annotations and handles annotation creation.
MessageContent:
The renderAnnotatedText function segments the text to wrap annotations inline.
The onMouseUp handling is correctly wired to manage text selections and propagate them for annotation.
These changes should allow for inline annotations in your message content, where the annotation highlights and expands correctly as text is added, ensuring the rest of the text shifts accordingly. This setup maintains the persistent highlighting of annotations.
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotations code for error highlighting in prompts!!!
type Annotation = {
text: string;
annotation: string;
};
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState<string>("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationStart, setAnnotationStart] = useState<number | null>(null);
const [annotationEnd, setAnnotationEnd] = useState<number | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
setSelectedText(selection.toString());
setAnnotationStart(start);
setAnnotationEnd(end);
}
};
// Function to add annotation
const addAnnotation = (a: string) => {
const newAnnotations = [
...annotations,
{ text: selectedText, annotation: a }
];
setAnnotations(newAnnotations);
setSelectedText('');
setAnnotationStart(null);
setAnnotationEnd(null);
if (inputRef.current) inputRef.current.style.display = "none";
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box inline */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
addAnnotation={addAnnotation} // Added prop
annotationStart={annotationStart} // Added prop
annotationEnd={annotationEnd} // Added prop
inputRef={inputRef} // Added prop
/>
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren, useEffect } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
addAnnotation?: (annotation: string) => void; // Added prop
annotationStart?: number | null; // Added prop
annotationEnd?: number | null; // Added prop
inputRef?: React.RefObject<HTMLInputElement>; // Added prop
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
};
export const MessageContent: React.FC<Props> = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate,
addAnnotation,
annotationStart,
annotationEnd,
inputRef
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
useEffect(() => {
if (annotationStart !== null && annotationEnd !== null && inputRef.current) {
const selectionRect = contentRef.current?.getBoundingClientRect();
const rangeRect = document.createRange().getBoundingClientRect();
// Calculating position of the annotation box
const top = (rangeRect.top - selectionRect.top) + selectionRect.height + window.scrollY;
const left = (rangeRect.left - selectionRect.left) + window.scrollX;
inputRef.current.style.position = "absolute";
inputRef.current.style.top = `${top}px`;
inputRef.current.style.left = `${left}px`;
inputRef.current.style.display = "block";
inputRef.current.focus();
}
}, [annotationStart, annotationEnd]);
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
);
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ text: annotatedText }, index) => {
const startIndex = text.indexOf(annotatedText, lastIndex);
if (startIndex !== -1) {
const endIndex = startIndex + annotatedText.length;
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, startIndex)}</span>,
<span key={index} className={cn("bg-yellow-100", "annotated-text")}>
{annotatedText}
</span>
);
lastIndex = endIndex;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
{annotationStart !== null && annotationEnd !== null && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif' // Adjust the font family as needed
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
if (addAnnotation) addAnnotation(target.value);
target.value = '';
}
}}
/>
)}
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</Text>
</div>
);
};
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotation code for error highlighting in prompts!!!
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState<string>("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationStart, setAnnotationStart] = useState<number | null>(null);
const [annotationEnd, setAnnotationEnd] = useState<number | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
setSelectedText(selection.toString());
setAnnotationStart(start);
setAnnotationEnd(end);
if (inputRef.current) inputRef.current.style.display = "block";
}
};
// Function to add an annotation
const addAnnotation = (a: string) => {
if (annotationStart !== null && annotationEnd !== null) {
const newAnnotations = [
...annotations,
{
text: selectedText,
annotation: a,
start: annotationStart,
end: annotationEnd
}
];
setAnnotations(newAnnotations);
setSelectedText('');
setAnnotationStart(null);
setAnnotationEnd(null);
if (inputRef.current) inputRef.current.style.display = "none";
}
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box inline */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
addAnnotation={addAnnotation} // Added prop
annotationStart={annotationStart} // Added prop
annotationEnd={annotationEnd} // Added prop
inputRef={inputRef} // Added prop
/>
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren, useEffect } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
addAnnotation?: (annotation: string) => void; // Added prop
annotationStart?: number | null; // Added prop
annotationEnd?: number | null; // Added prop
inputRef?: React.RefObject<HTMLInputElement>; // Added prop
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
export const MessageContent: React.FC<Props> = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate,
addAnnotation,
annotationStart,
annotationEnd,
inputRef
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
useEffect(() => {
if (annotationStart !== null && annotationEnd !== null && inputRef.current) {
const selectionRect = contentRef.current?.getBoundingClientRect();
const rangeRect = document.createRange().getBoundingClientRect();
// Calculating position of the annotation box
const top = (rangeRect.top - selectionRect.top) + selectionRect.height + window.scrollY;
const left = (rangeRect.left - selectionRect.left) + window.scrollX;
inputRef.current.style.position = "absolute";
inputRef.current.style.top = `${top}px`;
inputRef.current.style.left = `${left}px`;
inputRef.current.style.display = "block";
inputRef.current.focus();
}
}, [annotationStart, annotationEnd]);
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
);
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ text: annotatedText, start, end }, index) => {
if (start !== -1) {
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, start)}</span>,
<span key={index} className={cn("bg-yellow-100", "annotated-text")}>
{annotatedText}
</span>
);
lastIndex = end;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
{annotationStart !== null && annotationEnd !== null && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif' // Adjust the font family as needed
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
if (addAnnotation) addAnnotation(target.value);
target.value = '';
}
}}
/>
)}
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotation code for error highlighting in prompts!!!
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState<string>("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
setSelectedText(selection.toString());
if (inputRef.current) inputRef.current.style.display = "block";
// Position the input box
if (inputRef.current) {
const selectionRect = range.getBoundingClientRect();
const containerRect = range.commonAncestorContainer.parentElement?.getBoundingClientRect();
if (containerRect) {
const top = selectionRect.bottom - containerRect.top + window.scrollY;
const left = selectionRect.left - containerRect.left + window.scrollX;
inputRef.current.style.position = "absolute";
inputRef.current.style.top = `${top}px`;
inputRef.current.style.left = `${left}px`;
}
}
}
};
// Function to add an annotation
const addAnnotation = (a: string) => {
const selection = window.getSelection();
if (selection && selection.toString() && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
const newAnnotations = [
...annotations,
{
text: selectedText,
annotation: a,
start: start,
end: end,
}
];
setAnnotations(newAnnotations);
setSelectedText('');
if (inputRef.current) inputRef.current.style.display = "none";
}
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box inline */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
addAnnotation={addAnnotation} // Added prop
inputRef={inputRef} // Added prop
/>
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren, useEffect } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
addAnnotation?: (annotation: string) => void; // Added prop
inputRef?: React.RefObject<HTMLInputElement>; // Added prop
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
export const MessageContent: React.FC<Props> = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate,
addAnnotation,
inputRef
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
useEffect(() => {
if (inputRef.current) {
const inputBox = inputRef.current;
if (inputBox.style.display === "block") {
inputBox.focus();
}
}
}, []);
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
);
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ start, end, text: annotatedText }, index) => {
if (start !== -1) {
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, start)}</span>,
<span key={index} className={cn("bg-yellow-100", "annotated-text")}>
{annotatedText}
</span>
);
lastIndex = end;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif', // Adjust the font family as needed
display: 'none' // Initially hidden
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
if (addAnnotation) addAnnotation(target.value);
target.value = '';
}
}}
/>
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</Text>
</div>
);
};
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren & { type?: 'default' | 'error' }) => (
<div
className={cn('flex items-start gap-1', {
'text-volcanic-700': type === 'default',
'text-danger-500': type === 'error',
})}
>
<Icon name="warning" size="md" className="flex items-center text-p" />
<Text as="span">{children}</Text>
</div>
);
Key Changes:
Removal of annotationStart and annotationEnd State:
Removed the states annotationStart and `annotation
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotation code for error highlighting in prompts!!!
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
// State to manage the selected text and annotations
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [selectedText, setSelectedText] = useState<string>("");
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
if (range && selection.toString().length > 0) {
const start = range.startOffset;
const end = range.endOffset;
setAnnotations([...annotations, {
text: selection.toString(),
annotation: "",
start,
end
}]);
setSelectedText(selection.toString());
const boundingRect = range.getBoundingClientRect();
const inputBox = inputRef.current;
if (inputBox) {
const containerRect = range.commonAncestorContainer.parentElement!.getBoundingClientRect();
inputBox.style.position = "absolute";
inputBox.style.top = `${boundingRect.bottom - containerRect.top}px`;
inputBox.style.left = `${boundingRect.left - containerRect.left}px`;
inputBox.style.display = "block";
inputBox.focus();
}
}
}
};
const addAnnotation = (annotationText: string, index: number) => {
const newAnnotations = annotations.map((annotation, i) =>
i === index ? { ...annotation, annotation: annotationText } : annotation
);
setAnnotations(newAnnotations);
setSelectedText("");
const inputBox = inputRef.current;
if (inputBox) inputBox.style.display = 'none';
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box inline */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
/>
{inputRef.current && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif', // Adjust the font family as needed
display: 'none' // Initially hidden
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
const index = annotations.findIndex(a => a.text === selectedText);
if (index !== -1) {
addAnnotation(target.value, index);
}
target.value = '';
}
}}
/>
)}
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
} from '@/types/message';
import { cn } from '@/utils';
import { useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
type Annotation = {
text: string;
annotation: string;
start: number;
end: number;
};
export const MessageContent: React.FC<Props> = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate,
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
);
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ start, end, text: annotatedText }, index) => {
if (start !== -1) {
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, start)}</span>,
<span key={index} className={cn("bg-yellow-100", "annotated-text")}>
{annotatedText}
</span>
);
lastIndex = end;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{' '}
{isLast && isAborted && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</Text>
</div>
);
};
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren & { type?: 'default' | 'error' }) => (
<div
className={cn('flex items-start gap-1', {
'text-volcanic-700': type === 'default',
'text-danger-500': type === 'error',
})}
>
<Icon name="warning" size="md" className="flex items-center text-p" />
<Text as="span">{children}</Text>
</div>
);
Key Changes:
Annotation Input Box Visibility:
The annotation input box is initially hidden and only shown when text is selected.
Positioning of the input box is correctly set based on the selected text's position
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
code Copy code
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotations code for error highlighing in prompts!!!
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const inputRef = useRef(null);
// Function to add an annotation
const addAnnotation = (annotationText: string, index: number) => {
const newAnnotations = annotations.map((annotation, i) =>
i === index ? { ...annotation, annotation: annotationText } : annotation
);
code Copy code
setAnnotations(newAnnotations);
setSelectedText('');
const inputBox = inputRef.current;
if (inputBox) inputBox.style.display = "none";
// Function to handle text selection
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
if (range && selection.toString().length > 0) {
const start = range.startOffset;
const end = range.endOffset;
code Copy code
setAnnotations([...annotations, {
text: selection.toString(),
annotation: '',
start,
end
}]);
setSelectedText(selection.toString());
const boundingRect = range.getBoundingClientRect();
const inputBox = inputRef.current;
if (inputBox) {
const containerRect = range.commonAncestorContainer.parentElement!.getBoundingClientRect();
inputBox.style.position = 'absolute';
inputBox.style.top = `${boundingRect.bottom - containerRect.top}px`;
inputBox.style.left = `${boundingRect.left - containerRect.left}px`;
inputBox.style.display = 'block';
inputBox.focus();
}
}
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
{hasSteps && (
<Button
label={${isStepsExpanded ? 'Hide' : 'Show'} steps}
startIcon={}
kind="secondary"
size="md"
aria-label={${isStepsExpanded ? 'Hide' : 'Show'} steps}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
code Copy code
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{//This is where we render the annotated box
}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
/>
{inputRef.current && (
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif' // Adjust the font family as needed
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base'
)}
placeholder="Add annotation . . ."
onKeyDown={(e) => {
if (e.key === "Enter") {
const target = e.target as HTMLInputElement;
const index = annotations.findIndex(a => a.text === selectedText);
if (index !== -1) {
addAnnotation(target.value, index);
}
target.value = "";
}
}}
/>
)}
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
import { Transition } from '@headlessui/react';
import { PropsWithChildren } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
Annotation,
} from '@/types/message';
import { cn } from '@/utils';
import { useState, useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
import internal from 'stream';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
export const MessageContent: React.FC = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
code Copy code
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return
}
code Copy code
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ start, end, text: annotatedText }, index) => {
if (start !== -1) {
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, start)}</span>,
<span key={index} className={cn('bg-yellow-100”, “annotated-text')}>
{annotatedText}
</span>
);
lastIndex = end;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
{message.text}
{message.error}
{isLast && (
Retry?
)}
</>
);
// } else if (isUser) {
// content = (
//
// {renderAnnotatedText(message.text)}
//
// );
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
{message.text}
)}
{!hasLoadingMessage && (
...
)}
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}
)}
{message.error}
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
{renderAnnotatedText(message.text)}
code Copy code
{isAborted && (
<MessageInfo>
This generation was stopped.{" "}
{isLast && isAborted && (
<button className='underline underline-offset-1' type='button' onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
</>
);
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren & { type?: 'default' | 'error' }) => (
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import { useLongPress } from 'react-aria';
import { Avatar } from '@/components/Avatar';
import IconButton from '@/components/IconButton';
import { LongPressMenu } from '@/components/LongPressMenu';
import { MessageContent } from '@/components/MessageContent';
import {
Button,
CopyToClipboardButton,
CopyToClipboardIconButton,
Icon,
Tooltip,
Markdown,
} from '@/components/Shared';
import { ToolEvents } from '@/components/ToolEvents';
import { ReservedClasses } from '@/constants';
import { Breakpoint, useBreakpoint } from '@/hooks/breakpoint';
import { getMessageRowId } from '@/hooks/citations';
import { useCitationsStore } from '@/stores';
import {
type ChatMessage,
isAbortedMessage,
isErroredMessage,
isFulfilledMessage,
isFulfilledOrTypingMessage,
isFulfilledOrTypingMessageWithCitations,
isUserMessage,
Annotation,
} from '@/types/message';
import { cn } from '@/utils';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
delay?: boolean;
className?: string;
onCopy?: VoidFunction;
onRetry?: VoidFunction;
};
/**
* Renders a single message row from the user or from our models.
*/
const MessageRow = forwardRef<HTMLDivElement, Props>(function MessageRowInternal(
{ message, delay = false, isLast, className = '', onCopy, onRetry },
ref
) {
const breakpoint = useBreakpoint();
const [isShowing, setIsShowing] = useState(false);
const [isLongPressMenuOpen, setIsLongPressMenuOpen] = useState(false);
const [isStepsExpanded, setIsStepsExpanded] = useState<boolean>(isLast);
const {
citations: { selectedCitation, hoveredGenerationId },
hoverCitation,
} = useCitationsStore();
const hasSteps =
(isFulfilledOrTypingMessage(message) ||
isErroredMessage(message) ||
isAbortedMessage(message)) &&
!!message.toolEvents &&
message.toolEvents.length > 0;
const getMessageText = () => {
if (isFulfilledMessage(message)) {
return message.originalText;
}
return message.text;
};
const enableLongPress =
(isFulfilledMessage(message) || isUserMessage(message)) && breakpoint === Breakpoint.sm;
const { longPressProps } = useLongPress({
onLongPress: () => setIsLongPressMenuOpen(true),
});
// Delay the appearance of the message to make it feel more natural.
useEffect(() => {
if (delay) {
setTimeout(() => setIsShowing(true), 300);
}
}, []);
useEffect(() => {
if (isLast) {
setIsStepsExpanded(true);
}
}, [isLast]);
const [highlightMessage, setHighlightMessage] = useState(false);
const prevSelectedCitationGenId = usePreviousDistinct(selectedCitation?.generationId);
useEffect(() => {
if (isFulfilledOrTypingMessage(message) && message.citations && message.generationId) {
if (
selectedCitation?.generationId === message.generationId &&
prevSelectedCitationGenId !== message.generationId
) {
setHighlightMessage(true);
setTimeout(() => {
setHighlightMessage(false);
}, 1000);
}
}
}, [selectedCitation?.generationId, prevSelectedCitationGenId]);
if (delay && !isShowing) return null;
const handleOnMouseEnter = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(message.generationId);
}
};
const handleOnMouseLeave = () => {
if (isFulfilledOrTypingMessageWithCitations(message)) {
hoverCitation(null);
}
};
// Annotation code for error highlighting in prompts!!!
// State to manage the selected text and annotations
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [selectedText, setSelectedText] = useState<string>("");
const inputRef = useRef<HTMLInputElement>(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
if (range && selection.toString().length > 0) {
const start = range.startOffset;
const end = range.endOffset;
setAnnotations([
...annotations,
{
text: selection.toString(),
annotation: "",
start,
end,
},
]);
setSelectedText(selection.toString());
const boundingRect = range.getBoundingClientRect();
const inputBox = inputRef.current;
if (inputBox) {
const containerRect = range.commonAncestorContainer.parentElement!.getBoundingClientRect();
inputBox.style.position = "absolute";
inputBox.style.top = `${boundingRect.bottom - containerRect.top}px`;
inputBox.style.left = `${boundingRect.left - containerRect.left}px`;
inputBox.style.display = "block";
inputBox.focus();
}
}
}
};
const addAnnotation = (annotationText: string) => {
const newAnnotations = annotations.map((annotation) =>
annotation.text === selectedText ? { ...annotation, annotation: annotationText } : annotation
);
setAnnotations(newAnnotations);
setSelectedText("");
const inputBox = inputRef.current;
if (inputBox) inputBox.style.display = "none";
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
ref={ref}
>
<LongPressMenu
isOpen={isLongPressMenuOpen}
close={() => setIsLongPressMenuOpen(false)}
className="md:hidden"
>
<div className={cn('flex flex-col divide-y', 'divide-marble-300')}>
<div className="flex flex-col gap-y-4 pt-4">
<CopyToClipboardButton
value={getMessageText()}
label="Copy text"
kind="secondary"
iconAtStart
onClick={onCopy}
/>
{hasSteps && (
<Button
label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
startIcon={<Icon name="list" />}
kind="secondary"
size="md"
aria-label={`${isStepsExpanded ? 'Hide' : 'Show'} steps`}
animate={false}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
)}
</div>
</div>
</LongPressMenu>
<div
className={cn(
'group flex h-fit w-full flex-col gap-2 rounded-md p-2 text-left md:flex-row',
'transition-colors ease-in-out',
'hover:bg-secondary-100',
{
'bg-secondary-50':
isFulfilledOrTypingMessage(message) &&
message.generationId &&
hoveredGenerationId === message.generationId,
'bg-primary-50 hover:bg-primary-50': highlightMessage,
}
)}
{...(enableLongPress && longPressProps)}
>
<div className="flex w-full gap-x-2">
<Avatar message={message} />
<div className="flex w-full min-w-0 max-w-message flex-1 flex-col items-center gap-x-3 md:flex-row">
<div className="w-full">
{hasSteps && <ToolEvents show={isStepsExpanded} events={message.toolEvents} />}
{/* Render the annotated box inline */}
<MessageContent
isLast={isLast}
message={message}
annotations={annotations}
onAnnotate={handleMouseUp}
onRetry={onRetry}
/>
<input
ref={inputRef}
type='text'
style={{
fontSize: '14px', // Adjust the font size as needed
height: '2rem', // Adjust the height as needed
width: '200px', // Adjust the width as needed
padding: '0.5rem', // Adjust the padding as needed
lineHeight: '1.5', // Adjust the line height as needed
fontFamily: 'Arial, sans-serif', // Adjust the font family as needed
display: 'none', // Initially hidden
}}
className={cn(
'min-h-[1rem] md:min-h-[2rem]',
"w-auto",
'self-center',
'rounded',
'px-1 px-2',
'border',
'bg-danger-50',
'text-lg',
'border-secondary-400',
'transition ease-in-out',
'focus:border-secondary-700',
'focus:outline-none',
'placeholder-base',
)}
placeholder='Add annotation . . .'
onKeyDown={(e) => {
if (e.key === 'Enter') {
const target = e.target as HTMLInputElement;
addAnnotation(target.value);
target.value = '';
}
}}
/>
{annotations.map((annotation, index) => (
<div key={index} className='bg-secondary-50 p-1 my-1'>
<span className='font-bold'>{annotation.text}</span>: {annotation.annotation}
</div>
))}
</div>
<div
className={cn('flex h-full items-end justify-end self-end', {
'hidden md:invisible md:flex':
!isFulfilledMessage(message) && !isUserMessage(message),
'hidden md:invisible md:flex md:group-hover:visible': !isLast,
})}
>
{hasSteps && (
<Tooltip label={`${isStepsExpanded ? 'Hide' : 'Show'} steps'} hover>
<IconButton
iconName="list"
className="rounded hover:bg-secondary-100"
iconClassName={cn(
'text-volcanic-800 group-hover/icon-button:text-secondary-800',
{
'hidden md:invisible md:flex': !isFulfilledMessage(message),
}
)}
onClick={() => setIsStepsExpanded((prevIsExpanded) => !prevIsExpanded)}
/>
</Tooltip>
)}
<CopyToClipboardIconButton value={getMessageText()} onClick={onCopy} />
</div>
</div>
</div>
</div>
</div>
);
});
export default MessageRow;
MessageContent Component:
jsx Copy code
import { Transition } from '@headlessui/react';
import { PropsWithChildren } from 'react';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
import { Icon } from '@/components/Shared';
import { Markdown, Text } from '@/components/Shared';
import { UploadedFile } from '@/components/UploadedFile';
import {
type ChatMessage,
MessageType,
isAbortedMessage,
isErroredMessage,
isFulfilledOrTypingMessage,
isLoadingMessage,
Annotation,
} from '@/types/message';
import { cn } from '@/utils';
import { useRef } from 'react';
import { STYLE_LEVEL_TO_CLASSES } from '@/components/Shared';
type Props = {
isLast: boolean;
message: ChatMessage;
annotations?: Annotation[];
onRetry?: VoidFunction;
onAnnotate?: (start: number, end: number) => void;
};
const BOT_ERROR_MESSAGE = 'Unable to generate a response since an error was encountered. ';
export const MessageContent: React.FC<Props> = ({
isLast,
message,
onRetry,
annotations = [],
onAnnotate,
}) => {
const isUser = message.type === MessageType.USER;
const isLoading = isLoadingMessage(message);
const isBotError = isErroredMessage(message);
const isUserError = isUser && message.error;
const isAborted = isAbortedMessage(message);
const isTypingOrFulfilledMessage = isFulfilledOrTypingMessage(message);
const contentRef = useRef<HTMLDivElement>(null);
const handleMouseUp = () => {
const selection = window.getSelection();
if (selection && selection.toString()) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
// Call the annotation handler passed as props
if (onAnnotate) {
onAnnotate(start, end);
}
}
};
const renderAnnotatedText = (text: string) => {
if (annotations.length === 0) {
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
/>
);
}
const parts: React.ReactNode[] = [];
let lastIndex = 0;
annotations.forEach(({ start, end, text: annotatedText }, index) => {
if (start !== -1) {
parts.push(
<span key={`part-${index}-${lastIndex}`}>{text.substring(lastIndex, start)}</span>,
<span key={index} className={cn('bg-yellow-100', 'annotated-text')}>
{annotatedText}
</span>
);
lastIndex = end;
}
});
if (lastIndex < text.length) {
parts.push(<span key={`part-${lastIndex}`}>{text.substring(lastIndex)}</span>);
}
return parts;
};
let content: React.ReactNode = null;
if (isUserError) {
content = (
<>
<Text>{message.text}</Text>
<MessageInfo type="error">
{message.error}
{isLast && (
<button className="underline underline-offset-1" type="button" onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
</>
);
} else if (isUser) {
content = (
<>
<Markdown text={message.text} />
{message.files && message.files.length > 0 && (
<div className="flex flex-wrap gap-2 py-2">
{message.files.map((file) => (
<UploadedFile key={file.id} file={file} />
))}
</div>
)}
</>
);
} else if (isLoading) {
const hasLoadingMessage = message.text.length > 0;
content = (
<Text className={cn('flex min-w-0 text-volcanic-700')} as="span">
{hasLoadingMessage && (
<Transition
appear={true}
show={true}
enterFrom="opacity-0"
enterTo="opacity-full"
enter="transition-opacity ease-in-out duration-500"
>
{message.text}
</Transition>
)}
{!hasLoadingMessage && (
<span className="w-max">
<div className="animate-typing-ellipsis overflow-hidden whitespace-nowrap pr-1">
...
</div>
</span>
)}
</Text>
);
} else if (isBotError) {
content = (
<>
{message.text.length > 0 ? (
<Markdown text={message.text} />
) : (
<Text className={cn('text-volcanic-700')}>{BOT_ERROR_MESSAGE}</Text>
)}
<MessageInfo type="error">{message.error}</MessageInfo>
</>
);
} else {
const hasCitations =
isTypingOrFulfilledMessage && message.citations && message.citations.length > 0;
content = (
<>
<div ref={contentRef} onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
{isAborted && (
<MessageInfo>
This generation was stopped.{" "}
{isLast && isAborted && (
<button className='underline underline-offset-1' type='button' onClick={onRetry}>
Retry?
</button>
)}
</MessageInfo>
)}
</>
);
}
return (
<div className="flex w-full flex-col justify-center gap-y-1 py-1">
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl"
>
{content}
</Text>
</div>
);
};
const MessageInfo = ({
type = 'default',
children,
}: PropsWithChildren<{ type?: 'default' | 'error' }>) => (
<div
className={cn('flex items-start gap-1', {
'text-volcanic-700': type === 'default',
'text-danger-500': type === 'error',
})}
>
<Icon name="warning" size="md" className="flex items-center text-p" />
<Text as="span">{children}</Text>
</div>
);
Key Enhancements:
Ensured the annotation input box is shown only when text is selected.
Managed the selected text through state and updated the annotations accordingly.
Positioned the annotation input box accurately relative to the selected text.
Highlighted the annotated text and handled the rendering appropriately in MessageContent.