ok here is my handle mouse up... i want a annotation input box to appear right beside highlighted text... right now when a user highlights text it doesnt appear. fix this. // Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
console.log('select', selection?.toString())
if (selection && selection.toString()) {
const text = selection.toString();
const range = selection.getRangeAt(0);
code
const id = addAnnotation(selection.toString())
const rect = range.getBoundingClientRect();
setPosition({
top : rect.bottom + window.scrollY,
left : rect.right + window.scrollX
});
<div style={{
position: "absolute",
top: position.top,
left: position.left}}
>
<input
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 annot = message.annotations[id];
annot.annotation=target.value;
message.annotations[id] = annot;
target.value = "";
}
}}
/>
</div>
}
Assistant
User
Assistant
};
To fix the issue and ensure that the annotation input box appears right beside the highlighted text, you need to make sure that you properly set the position of the input box and render it appropriately. The main issues in your current code are:
The input box HTML code inside the function is not rendered. It's just a plain JSX inside the function, which doesn't get interpreted as React JSX.
You need to use a state to trigger the rendering of the annotation input box.
Let's update your code to address these issues:
Create a state to manage the annotation input box visibility and position.
Update the component rendering to conditionally display the annotation input box.
Here’s the updated code:
jsx
import React, { useState } from 'react';
// Function to handle and manage annotations
const TextAnnotation = ({ message, addAnnotation }) => {
const [position, setPosition] = useState({ top: 0, left: 0 });
const [isVisible, setIsVisible] = useState(false);
const [currentAnnotationId, setCurrentAnnotationId] = useState(null);
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
console.log('select', selection?.toString());
if (selection && selection.toString()) {
const text = selection.toString();
const range = selection.getRangeAt(0);
const id = addAnnotation(text);
setCurrentAnnotationId(id);
const rect = range.getBoundingClientRect();
setPosition({
top: rect.bottom + window.scrollY,
left: rect.left + window.scrollX,
});
setIsVisible(true);
} else {
setIsVisible(false);
}
};
return (
<div onMouseUp={handleMouseUp}>
{/* Your content where you want to handle text selection. Add this handler where necessary */}
<p>Select some text in this paragraph to annotate it.</p>
{isVisible && (
<div
style={{
position: 'absolute',
top: position.top,
left: position.left,
}}>
<input
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 annot = message.annotations[currentAnnotationId];
annot.annotation = target.value;
message.annotations[currentAnnotationId] = annot;
target.value = '';
setIsVisible(false); // Hide the input box once annotation is added
}
}}
/>
</div>
)}
</div>
);
};
In this revised code:
useState hooks are used to manage the position and visibility of the annotation input box.
The handleMouseUp function sets the position of the input box and toggles its visibility.
A conditional rendering (isVisible && [...]) ensures that the annotation input box is only rendered when visible.
This should make your annotation input box appear beside the highlighted text when the user makes a selection.
this is my whole code, why is it not working... import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import React 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,
Text,
} 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';
import { render } from '@headlessui/react/dist/utils/render';
import { v4 as uuidv4 } from 'uuid';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
// 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]);
The issue in your code is that the annotation input box is defined within the handleMouseUp function, but it's not being properly rendered. In React, rendering should be done within the component's return statement using state to conditionally display elements. To fix the issue, you need to:
Use state to manage the visibility and position of the annotation input box.
Ensure that the input box is rendered within the component's return statement, not inside the event handler.
Here is the corrected version of your component:
jsx
import { usePreviousDistinct } from '@react-hookz/web';
import { forwardRef, useEffect, useState, useRef } from 'react';
import React 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,
Text,
} 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';
import { render } from '@headlessui/react/dist/utils/render';
import { v4 as uuidv4 } from 'uuid';
import { CitationTextHighlighter } from '@/components/Citations/CitationTextHighlighter';
import { DataTable } from '@/components/DataTable';
import { MarkdownImage } from '@/components/MarkdownImage';
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();
message.annotations = {}
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 highlighing in prompts!!!
//
// State to manage the selected text and annotations
const [selectedText, setSelectedText] = useState<string>("");
const [annotations, setAnnotations] = useState<Annotation[]>([]);
const [annotationVisible, setAnnotationVisible] = useState<boolean>(false);
const annotationRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
// Function to handle text selection
const handleMouseUp = () => {
const selection = window.getSelection();
console.log('select', selection?.toString())
if (selection && selection.toString()) {
const text = selection.toString();
const range = selection.getRangeAt(0);
const id = addAnnotation(text);
const rect = range.getBoundingClientRect();
setPosition({
top : rect.bottom + window.scrollY,
left : rect.left + window.scrollX // changed to left.
});
setAnnotationVisible(true);
} else {
setAnnotationVisible(false);
}
};
// Function to add annotation
const addAnnotation = (s: string) => {
const selection = window.getSelection();
const id = uuidv4();
if (selection) {
const range = selection.getRangeAt(0);
const start = range.startOffset;
const end = range.endOffset;
const annot: Annotation = {
text: s,
annotation: '', // Set blank for now, grab annotation later.
start: start,
end: end
};
setAnnotations(prevAnnotations => [
...prevAnnotations,
{ text: s, annotation: "", start: start, end: end }
]);
message.annotations[id] = annot;
console.log(message.annotations[id]);
}
return id;
};
const renderAnnotatedText = (text: string) => {
const highlightRanges = Object.values(message.annotations).map(({ start, end }) => ({ start, end }));
return (
<Markdown
text={text}
className={cn(STYLE_LEVEL_TO_CLASSES.p)}
customComponents={{
img: MarkdownImage as any,
cite: CitationTextHighlighter as any,
table: DataTable as any,
}}
renderLaTex={true}
highlightedRanges={highlightRanges}
/>
);
};
return (
<div
id={
isFulfilledOrTypingMessage(message) && message.generationId
? getMessageRowId(message.generationId)
: undefined
}
className={cn(ReservedClasses.MESSAGE, 'flex', className)}
onMouseEnter={handleOnMouseEnter}
onMouseLeave={handleOnMouseLeave}
onMouseUp={handleMouseUp}
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} />}
<div className="flex w-full flex-col justify-center gap-y-1 py-1" onMouseUp={handleMouseUp}>
<Text
as="div"
className="flex flex-col gap-y-1 whitespace-pre-wrap [overflow-wrap:anywhere] md:max-w-4xl">
<div onMouseUp={handleMouseUp}>
{renderAnnotatedText(message.text)}
</div>
</Text>
</div>
{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>
{Object.values(message.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
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>
{annotationVisible && (
<div style={{ position: "absolute", top: position.top, left: position.left }}>
<input
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 annot = message.annotations[id];
annot.annotation = target.value;
message.annotations[id] = annot;
target.value = "";
setAnnotationVisible(false); // Hide the input box once annotation is added
}
}}
/>
</div>
)}
</div>
);
});
export default MessageRow;
Key Changes:
Annotation Input Box Rendering: The annotation input box is now rendered conditionally based on the annotationVisible state within the component's return statement instead of inside the handleMouseUp function.
Position Fix: Adjusted rect.right to rect.left for setPosition to place the input box beside the highlighted text correctly.
Missing id for Annotations: The onKeyDown event handler should correctly reference and update the annotation using the message.annotations[id].
Now, after you highlight some text, the annotation input box will appear beside the highlighted text and disappear after adding the annotation.