2024-07-03 23:32:55 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
import { Markdown } from "@/app/element/markdown";
|
|
|
|
import { TypingIndicator } from "@/app/element/typingindicator";
|
2024-09-05 23:40:24 +02:00
|
|
|
import { atoms, fetchWaveFile, getUserName, globalStore, WOS } from "@/store/global";
|
2024-09-05 23:43:14 +02:00
|
|
|
import { BlockService } from "@/store/services";
|
2024-07-25 11:30:49 +02:00
|
|
|
import { WshServer } from "@/store/wshserver";
|
2024-08-30 02:00:24 +02:00
|
|
|
import { adaptFromReactOrNativeKeyEvent, checkKeyPressed } from "@/util/keyutil";
|
2024-09-05 23:43:14 +02:00
|
|
|
import { isBlank } from "@/util/util";
|
2024-09-05 23:40:24 +02:00
|
|
|
import { atom, Atom, PrimitiveAtom, useAtomValue, useSetAtom, WritableAtom } from "jotai";
|
2024-07-03 23:32:55 +02:00
|
|
|
import type { OverlayScrollbars } from "overlayscrollbars";
|
|
|
|
import { OverlayScrollbarsComponent, OverlayScrollbarsComponentRef } from "overlayscrollbars-react";
|
2024-09-06 00:35:57 +02:00
|
|
|
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
|
2024-07-03 23:32:55 +02:00
|
|
|
import tinycolor from "tinycolor2";
|
|
|
|
import "./waveai.less";
|
|
|
|
|
2024-07-25 11:30:49 +02:00
|
|
|
interface ChatMessageType {
|
|
|
|
id: string;
|
|
|
|
user: string;
|
|
|
|
text: string;
|
|
|
|
isAssistant: boolean;
|
|
|
|
isUpdating?: boolean;
|
|
|
|
isError?: string;
|
|
|
|
}
|
|
|
|
|
2024-07-18 01:01:11 +02:00
|
|
|
const outline = "2px solid var(--accent-color)";
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
interface ChatItemProps {
|
|
|
|
chatItem: ChatMessageType;
|
|
|
|
itemCount: number;
|
|
|
|
}
|
|
|
|
|
2024-07-29 22:21:44 +02:00
|
|
|
function promptToMsg(prompt: OpenAIPromptMessageType): ChatMessageType {
|
|
|
|
return {
|
2024-08-13 06:20:13 +02:00
|
|
|
id: crypto.randomUUID(),
|
2024-07-29 22:21:44 +02:00
|
|
|
user: prompt.role,
|
|
|
|
text: prompt.content,
|
|
|
|
isAssistant: prompt.role == "assistant",
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-07-25 11:30:49 +02:00
|
|
|
export class WaveAiModel implements ViewModel {
|
2024-08-23 01:25:53 +02:00
|
|
|
viewType: string;
|
2024-07-25 11:30:49 +02:00
|
|
|
blockId: string;
|
2024-09-05 23:40:24 +02:00
|
|
|
blockAtom: Atom<Block>;
|
|
|
|
viewIcon?: Atom<string | HeaderIconButton>;
|
|
|
|
viewName?: Atom<string>;
|
|
|
|
viewText?: Atom<string | HeaderElem[]>;
|
|
|
|
preIconButton?: Atom<HeaderIconButton>;
|
|
|
|
endIconButtons?: Atom<HeaderIconButton[]>;
|
|
|
|
messagesAtom: PrimitiveAtom<Array<ChatMessageType>>;
|
|
|
|
addMessageAtom: WritableAtom<unknown, [message: ChatMessageType], void>;
|
|
|
|
updateLastMessageAtom: WritableAtom<unknown, [text: string, isUpdating: boolean], void>;
|
|
|
|
simulateAssistantResponseAtom: WritableAtom<unknown, [userMessage: ChatMessageType], Promise<void>>;
|
2024-08-01 09:03:19 +02:00
|
|
|
textAreaRef: React.RefObject<HTMLTextAreaElement>;
|
2024-07-25 11:30:49 +02:00
|
|
|
|
|
|
|
constructor(blockId: string) {
|
2024-08-23 01:25:53 +02:00
|
|
|
this.viewType = "waveai";
|
2024-07-25 11:30:49 +02:00
|
|
|
this.blockId = blockId;
|
|
|
|
this.blockAtom = WOS.getWaveObjectAtom<Block>(`block:${blockId}`);
|
2024-09-05 23:40:24 +02:00
|
|
|
this.viewIcon = atom((get) => {
|
2024-07-25 11:30:49 +02:00
|
|
|
return "sparkles"; // should not be hardcoded
|
|
|
|
});
|
2024-09-05 23:40:24 +02:00
|
|
|
this.viewName = atom("Wave Ai");
|
|
|
|
this.messagesAtom = atom([]);
|
2024-07-25 11:30:49 +02:00
|
|
|
|
2024-09-05 23:40:24 +02:00
|
|
|
this.addMessageAtom = atom(null, (get, set, message: ChatMessageType) => {
|
2024-07-25 11:30:49 +02:00
|
|
|
const messages = get(this.messagesAtom);
|
|
|
|
set(this.messagesAtom, [...messages, message]);
|
|
|
|
});
|
|
|
|
|
2024-09-05 23:40:24 +02:00
|
|
|
this.updateLastMessageAtom = atom(null, (get, set, text: string, isUpdating: boolean) => {
|
2024-07-25 11:30:49 +02:00
|
|
|
const messages = get(this.messagesAtom);
|
|
|
|
const lastMessage = messages[messages.length - 1];
|
|
|
|
if (lastMessage.isAssistant && !lastMessage.isError) {
|
|
|
|
const updatedMessage = { ...lastMessage, text: lastMessage.text + text, isUpdating };
|
|
|
|
set(this.messagesAtom, [...messages.slice(0, -1), updatedMessage]);
|
|
|
|
}
|
|
|
|
});
|
2024-09-05 23:40:24 +02:00
|
|
|
this.simulateAssistantResponseAtom = atom(null, async (get, set, userMessage: ChatMessageType) => {
|
2024-07-25 11:30:49 +02:00
|
|
|
const typingMessage: ChatMessageType = {
|
2024-08-13 06:20:13 +02:00
|
|
|
id: crypto.randomUUID(),
|
2024-07-25 11:30:49 +02:00
|
|
|
user: "assistant",
|
|
|
|
text: "",
|
|
|
|
isAssistant: true,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Add a typing indicator
|
|
|
|
set(this.addMessageAtom, typingMessage);
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
const parts = userMessage.text.split(" ");
|
|
|
|
let currentPart = 0;
|
|
|
|
|
|
|
|
const intervalId = setInterval(() => {
|
|
|
|
if (currentPart < parts.length) {
|
|
|
|
const part = parts[currentPart] + " ";
|
|
|
|
set(this.updateLastMessageAtom, part, true);
|
|
|
|
currentPart++;
|
|
|
|
} else {
|
|
|
|
clearInterval(intervalId);
|
|
|
|
set(this.updateLastMessageAtom, "", false);
|
|
|
|
}
|
|
|
|
}, 100);
|
|
|
|
}, 1500);
|
|
|
|
});
|
2024-09-05 23:40:24 +02:00
|
|
|
this.viewText = atom((get) => {
|
2024-08-28 21:05:29 +02:00
|
|
|
const settings = get(atoms.settingsAtom);
|
2024-09-05 23:43:14 +02:00
|
|
|
const isCloud = isBlank(settings?.["ai:apitoken"]) && isBlank(settings?.["ai:baseurl"]);
|
2024-08-28 21:05:29 +02:00
|
|
|
let modelText = "gpt-4o-mini";
|
2024-09-05 23:43:14 +02:00
|
|
|
if (!isCloud && !isBlank(settings?.["ai:model"])) {
|
2024-08-28 21:05:29 +02:00
|
|
|
modelText = settings["ai:model"];
|
|
|
|
}
|
2024-07-30 07:35:21 +02:00
|
|
|
const viewTextChildren: HeaderElem[] = [
|
|
|
|
{
|
|
|
|
elemtype: "text",
|
2024-08-28 21:05:29 +02:00
|
|
|
text: modelText,
|
2024-07-30 07:35:21 +02:00
|
|
|
},
|
|
|
|
];
|
|
|
|
return viewTextChildren;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async populateMessages(): Promise<void> {
|
|
|
|
const history = await this.fetchAiData();
|
|
|
|
globalStore.set(this.messagesAtom, history.map(promptToMsg));
|
|
|
|
}
|
|
|
|
|
|
|
|
async fetchAiData(): Promise<Array<OpenAIPromptMessageType>> {
|
|
|
|
const { data, fileInfo } = await fetchWaveFile(this.blockId, "aidata");
|
|
|
|
if (!data) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
const history: Array<OpenAIPromptMessageType> = JSON.parse(new TextDecoder().decode(data));
|
|
|
|
return history;
|
2024-07-25 11:30:49 +02:00
|
|
|
}
|
|
|
|
|
2024-08-01 09:03:19 +02:00
|
|
|
giveFocus(): boolean {
|
|
|
|
if (this?.textAreaRef?.current) {
|
|
|
|
this.textAreaRef.current?.focus();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-07-25 11:30:49 +02:00
|
|
|
useWaveAi() {
|
2024-09-05 23:40:24 +02:00
|
|
|
const messages = useAtomValue(this.messagesAtom);
|
|
|
|
const addMessage = useSetAtom(this.addMessageAtom);
|
|
|
|
const simulateResponse = useSetAtom(this.simulateAssistantResponseAtom);
|
|
|
|
const clientId = useAtomValue(atoms.clientId);
|
2024-07-29 22:21:44 +02:00
|
|
|
const blockId = this.blockId;
|
2024-07-25 11:30:49 +02:00
|
|
|
|
|
|
|
const sendMessage = (text: string, user: string = "user") => {
|
|
|
|
const newMessage: ChatMessageType = {
|
2024-08-13 06:20:13 +02:00
|
|
|
id: crypto.randomUUID(),
|
2024-07-25 11:30:49 +02:00
|
|
|
user,
|
|
|
|
text,
|
|
|
|
isAssistant: false,
|
|
|
|
};
|
|
|
|
addMessage(newMessage);
|
|
|
|
// send message to backend and get response
|
2024-08-28 03:49:49 +02:00
|
|
|
const settings = globalStore.get(atoms.settingsAtom);
|
2024-07-25 11:30:49 +02:00
|
|
|
const opts: OpenAIOptsType = {
|
2024-08-28 03:49:49 +02:00
|
|
|
model: settings["ai:model"],
|
|
|
|
apitoken: settings["ai:apitoken"],
|
|
|
|
maxtokens: settings["ai:maxtokens"],
|
|
|
|
timeout: settings["ai:timeoutms"] / 1000,
|
|
|
|
baseurl: settings["ai:baseurl"],
|
2024-07-25 11:30:49 +02:00
|
|
|
};
|
2024-07-29 22:21:44 +02:00
|
|
|
const newPrompt: OpenAIPromptMessageType = {
|
|
|
|
role: "user",
|
|
|
|
content: text,
|
2024-07-25 11:30:49 +02:00
|
|
|
};
|
2024-08-28 03:49:49 +02:00
|
|
|
if (newPrompt.name == "*username") {
|
|
|
|
newPrompt.name = getUserName();
|
|
|
|
}
|
2024-09-05 23:40:25 +02:00
|
|
|
const temp = async () => {
|
2024-07-30 07:35:21 +02:00
|
|
|
const history = await this.fetchAiData();
|
|
|
|
const beMsg: OpenAiStreamRequest = {
|
|
|
|
clientid: clientId,
|
|
|
|
opts: opts,
|
|
|
|
prompt: [...history, newPrompt],
|
|
|
|
};
|
2024-08-28 21:05:29 +02:00
|
|
|
const aiGen = WshServer.StreamWaveAiCommand(beMsg, { timeout: 60000 });
|
2024-07-25 11:30:49 +02:00
|
|
|
let fullMsg = "";
|
|
|
|
for await (const msg of aiGen) {
|
|
|
|
fullMsg += msg.text ?? "";
|
|
|
|
}
|
|
|
|
const response: ChatMessageType = {
|
|
|
|
id: newMessage.id,
|
|
|
|
user: newMessage.user,
|
|
|
|
text: fullMsg,
|
|
|
|
isAssistant: true,
|
|
|
|
};
|
2024-07-29 22:21:44 +02:00
|
|
|
|
|
|
|
const responsePrompt: OpenAIPromptMessageType = {
|
|
|
|
role: "assistant",
|
|
|
|
content: fullMsg,
|
|
|
|
};
|
2024-09-05 23:43:14 +02:00
|
|
|
const writeToHistory = BlockService.SaveWaveAiData(blockId, [...history, newPrompt, responsePrompt]);
|
2024-07-29 22:21:44 +02:00
|
|
|
const typeResponse = simulateResponse(response);
|
|
|
|
Promise.all([writeToHistory, typeResponse]);
|
2024-07-25 11:30:49 +02:00
|
|
|
};
|
|
|
|
temp();
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
messages,
|
|
|
|
sendMessage,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function makeWaveAiViewModel(blockId): WaveAiModel {
|
|
|
|
const waveAiModel = new WaveAiModel(blockId);
|
|
|
|
return waveAiModel;
|
|
|
|
}
|
|
|
|
|
2024-07-03 23:32:55 +02:00
|
|
|
const ChatItem = ({ chatItem, itemCount }: ChatItemProps) => {
|
2024-07-04 18:07:29 +02:00
|
|
|
const { isAssistant, text, isError } = chatItem;
|
2024-07-03 23:32:55 +02:00
|
|
|
const senderClassName = isAssistant ? "chat-msg-assistant" : "chat-msg-user";
|
|
|
|
const msgClassName = `chat-msg ${senderClassName}`;
|
2024-07-18 01:01:11 +02:00
|
|
|
const cssVar = "--panel-bg-color";
|
2024-07-03 23:32:55 +02:00
|
|
|
const panelBgColor = getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim();
|
|
|
|
const color = tinycolor(panelBgColor);
|
|
|
|
const newColor = color.isValid() ? tinycolor(panelBgColor).darken(6).toString() : "none";
|
|
|
|
const backgroundColor = itemCount % 2 === 0 ? "none" : newColor;
|
|
|
|
|
|
|
|
const renderError = (err: string): React.JSX.Element => <div className="chat-msg-error">{err}</div>;
|
|
|
|
|
|
|
|
const renderContent = (): React.JSX.Element => {
|
|
|
|
if (isAssistant) {
|
2024-07-04 18:07:29 +02:00
|
|
|
if (isError) {
|
|
|
|
return renderError(isError);
|
2024-07-03 23:32:55 +02:00
|
|
|
}
|
|
|
|
return text ? (
|
|
|
|
<>
|
|
|
|
<div className="chat-msg-header">
|
|
|
|
<i className="fa-sharp fa-solid fa-sparkles"></i>
|
|
|
|
</div>
|
2024-09-06 00:35:57 +02:00
|
|
|
<Markdown text={text} />
|
2024-07-03 23:32:55 +02:00
|
|
|
</>
|
|
|
|
) : (
|
|
|
|
<>
|
|
|
|
<div className="chat-msg-header">
|
|
|
|
<i className="fa-sharp fa-solid fa-sparkles"></i>
|
|
|
|
</div>
|
|
|
|
<TypingIndicator className="typing-indicator" />
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<div className="chat-msg-header">
|
|
|
|
<i className="fa-sharp fa-solid fa-user"></i>
|
|
|
|
</div>
|
2024-09-06 00:35:57 +02:00
|
|
|
<Markdown className="msg-text" text={text} />
|
2024-07-03 23:32:55 +02:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div className={msgClassName} style={{ backgroundColor }}>
|
|
|
|
{renderContent()}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
interface ChatWindowProps {
|
|
|
|
chatWindowRef: React.RefObject<HTMLDivElement>;
|
|
|
|
messages: ChatMessageType[];
|
|
|
|
}
|
|
|
|
|
2024-09-05 23:43:14 +02:00
|
|
|
const ChatWindow = memo(
|
2024-07-04 18:07:29 +02:00
|
|
|
forwardRef<OverlayScrollbarsComponentRef, ChatWindowProps>(({ chatWindowRef, messages }, ref) => {
|
|
|
|
const [isUserScrolling, setIsUserScrolling] = useState(false);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
2024-07-04 18:07:29 +02:00
|
|
|
const osRef = useRef<OverlayScrollbarsComponentRef>(null);
|
2024-09-05 23:40:24 +02:00
|
|
|
const prevMessagesLenRef = useRef(messages.length);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
2024-07-04 18:07:29 +02:00
|
|
|
useImperativeHandle(ref, () => osRef.current as OverlayScrollbarsComponentRef);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (osRef.current && osRef.current.osInstance()) {
|
|
|
|
const { viewport } = osRef.current.osInstance().elements();
|
2024-09-05 23:40:24 +02:00
|
|
|
const curMessagesLen = messages.length;
|
|
|
|
if (prevMessagesLenRef.current !== curMessagesLen || !isUserScrolling) {
|
2024-07-04 18:07:29 +02:00
|
|
|
setIsUserScrolling(false);
|
|
|
|
viewport.scrollTo({
|
|
|
|
behavior: "auto",
|
|
|
|
top: chatWindowRef.current?.scrollHeight || 0,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-09-05 23:40:24 +02:00
|
|
|
prevMessagesLenRef.current = curMessagesLen;
|
2024-07-04 18:07:29 +02:00
|
|
|
}
|
|
|
|
}, [messages, isUserScrolling]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (osRef.current && osRef.current.osInstance()) {
|
|
|
|
const { viewport } = osRef.current.osInstance().elements();
|
|
|
|
|
|
|
|
const handleUserScroll = () => {
|
|
|
|
setIsUserScrolling(true);
|
|
|
|
};
|
|
|
|
|
|
|
|
viewport.addEventListener("wheel", handleUserScroll, { passive: true });
|
|
|
|
viewport.addEventListener("touchmove", handleUserScroll, { passive: true });
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
viewport.removeEventListener("wheel", handleUserScroll);
|
|
|
|
viewport.removeEventListener("touchmove", handleUserScroll);
|
2024-09-05 23:40:24 +02:00
|
|
|
if (osRef.current && osRef.current.osInstance()) {
|
|
|
|
osRef.current.osInstance().destroy();
|
|
|
|
}
|
2024-07-04 18:07:29 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
const handleScrollbarInitialized = (instance: OverlayScrollbars) => {
|
|
|
|
const { viewport } = instance.elements();
|
2024-07-03 23:32:55 +02:00
|
|
|
viewport.scrollTo({
|
|
|
|
behavior: "auto",
|
|
|
|
top: chatWindowRef.current?.scrollHeight || 0,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2024-07-04 18:07:29 +02:00
|
|
|
return (
|
|
|
|
<OverlayScrollbarsComponent
|
|
|
|
ref={osRef}
|
|
|
|
className="scrollable"
|
|
|
|
options={{ scrollbars: { autoHide: "leave" } }}
|
|
|
|
events={{ initialized: handleScrollbarInitialized }}
|
|
|
|
>
|
|
|
|
<div ref={chatWindowRef} className="chat-window">
|
|
|
|
<div className="filler"></div>
|
|
|
|
{messages.map((chitem, idx) => (
|
|
|
|
<ChatItem key={idx} chatItem={chitem} itemCount={idx + 1} />
|
|
|
|
))}
|
|
|
|
</div>
|
|
|
|
</OverlayScrollbarsComponent>
|
|
|
|
);
|
|
|
|
})
|
|
|
|
);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
interface ChatInputProps {
|
|
|
|
value: string;
|
2024-07-04 18:07:29 +02:00
|
|
|
termFontSize: number;
|
2024-07-03 23:32:55 +02:00
|
|
|
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
|
|
|
|
onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
|
|
|
|
onMouseDown: (e: React.MouseEvent<HTMLTextAreaElement>) => void;
|
2024-08-01 09:03:19 +02:00
|
|
|
model: WaveAiModel;
|
2024-07-03 23:32:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const ChatInput = forwardRef<HTMLTextAreaElement, ChatInputProps>(
|
2024-08-01 09:03:19 +02:00
|
|
|
({ value, onChange, onKeyDown, onMouseDown, termFontSize, model }, ref) => {
|
2024-07-03 23:32:55 +02:00
|
|
|
const textAreaRef = useRef<HTMLTextAreaElement>(null);
|
|
|
|
|
|
|
|
useImperativeHandle(ref, () => textAreaRef.current as HTMLTextAreaElement);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2024-08-01 09:03:19 +02:00
|
|
|
model.textAreaRef = textAreaRef;
|
2024-07-03 23:32:55 +02:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
const adjustTextAreaHeight = () => {
|
|
|
|
if (textAreaRef.current == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Adjust the height of the textarea to fit the text
|
|
|
|
const textAreaMaxLines = 100;
|
|
|
|
const textAreaLineHeight = termFontSize * 1.5;
|
|
|
|
const textAreaMinHeight = textAreaLineHeight;
|
|
|
|
const textAreaMaxHeight = textAreaLineHeight * textAreaMaxLines;
|
|
|
|
|
|
|
|
textAreaRef.current.style.height = "1px";
|
|
|
|
const scrollHeight = textAreaRef.current.scrollHeight;
|
|
|
|
const newHeight = Math.min(Math.max(scrollHeight, textAreaMinHeight), textAreaMaxHeight);
|
|
|
|
textAreaRef.current.style.height = newHeight + "px";
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
adjustTextAreaHeight();
|
|
|
|
}, [value]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<textarea
|
|
|
|
ref={textAreaRef}
|
|
|
|
autoComplete="off"
|
|
|
|
autoCorrect="off"
|
|
|
|
className="waveai-input"
|
|
|
|
onMouseDown={onMouseDown} // When the user clicks on the textarea
|
|
|
|
onChange={onChange}
|
|
|
|
onKeyDown={onKeyDown}
|
|
|
|
style={{ fontSize: termFontSize }}
|
|
|
|
placeholder="Send a Message..."
|
|
|
|
value={value}
|
|
|
|
></textarea>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
2024-08-22 00:49:23 +02:00
|
|
|
const WaveAi = ({ model }: { model: WaveAiModel; blockId: string }) => {
|
2024-07-25 11:30:49 +02:00
|
|
|
const { messages, sendMessage } = model.useWaveAi();
|
2024-07-03 23:32:55 +02:00
|
|
|
const waveaiRef = useRef<HTMLDivElement>(null);
|
|
|
|
const chatWindowRef = useRef<HTMLDivElement>(null);
|
|
|
|
const osRef = useRef<OverlayScrollbarsComponentRef>(null);
|
|
|
|
const inputRef = useRef<HTMLTextAreaElement>(null);
|
2024-07-04 18:07:29 +02:00
|
|
|
const submitTimeoutRef = useRef<NodeJS.Timeout>(null);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
const [value, setValue] = useState("");
|
|
|
|
const [selectedBlockIdx, setSelectedBlockIdx] = useState<number | null>(null);
|
2024-07-04 18:07:29 +02:00
|
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
const termFontSize: number = 14;
|
|
|
|
|
2024-07-30 07:35:21 +02:00
|
|
|
// a weird workaround to initialize ansynchronously
|
|
|
|
useEffect(() => {
|
|
|
|
model.populateMessages();
|
|
|
|
}, []);
|
|
|
|
|
2024-07-03 23:32:55 +02:00
|
|
|
useEffect(() => {
|
|
|
|
return () => {
|
2024-07-04 18:07:29 +02:00
|
|
|
if (submitTimeoutRef.current) {
|
|
|
|
clearTimeout(submitTimeoutRef.current);
|
|
|
|
}
|
2024-07-03 23:32:55 +02:00
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
2024-07-04 18:07:29 +02:00
|
|
|
const submit = useCallback(
|
|
|
|
(messageStr: string) => {
|
|
|
|
if (!isSubmitting) {
|
|
|
|
setIsSubmitting(true);
|
|
|
|
sendMessage(messageStr);
|
|
|
|
|
|
|
|
clearTimeout(submitTimeoutRef.current);
|
|
|
|
submitTimeoutRef.current = setTimeout(() => {
|
|
|
|
setIsSubmitting(false);
|
|
|
|
}, 500);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[isSubmitting, sendMessage, setValue]
|
|
|
|
);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
const handleTextAreaChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
|
|
|
setValue(e.target.value);
|
|
|
|
};
|
|
|
|
|
|
|
|
const updatePreTagOutline = (clickedPre?: HTMLElement | null) => {
|
|
|
|
const pres = chatWindowRef.current?.querySelectorAll("pre");
|
|
|
|
if (!pres) return;
|
|
|
|
|
|
|
|
pres.forEach((preElement, idx) => {
|
|
|
|
if (preElement === clickedPre) {
|
|
|
|
setSelectedBlockIdx(idx);
|
|
|
|
} else {
|
|
|
|
preElement.style.outline = "none";
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (clickedPre) {
|
|
|
|
clickedPre.style.outline = outline;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (selectedBlockIdx !== null) {
|
|
|
|
const pres = chatWindowRef.current?.querySelectorAll("pre");
|
|
|
|
if (pres && pres[selectedBlockIdx]) {
|
|
|
|
pres[selectedBlockIdx].style.outline = outline;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [selectedBlockIdx]);
|
|
|
|
|
|
|
|
const handleTextAreaMouseDown = () => {
|
|
|
|
updatePreTagOutline();
|
|
|
|
setSelectedBlockIdx(null);
|
|
|
|
};
|
|
|
|
|
2024-07-04 18:07:29 +02:00
|
|
|
const handleEnterKeyPressed = useCallback(() => {
|
|
|
|
const isCurrentlyUpdating = messages.some((message) => message.isUpdating);
|
|
|
|
if (isCurrentlyUpdating || value === "") return;
|
|
|
|
|
2024-07-03 23:32:55 +02:00
|
|
|
submit(value);
|
|
|
|
setValue("");
|
|
|
|
setSelectedBlockIdx(null);
|
2024-07-04 18:07:29 +02:00
|
|
|
}, [messages, value]);
|
2024-07-03 23:32:55 +02:00
|
|
|
|
|
|
|
const handleContainerClick = (event: React.MouseEvent<HTMLDivElement>) => {
|
|
|
|
inputRef.current?.focus();
|
|
|
|
|
|
|
|
const target = event.target as HTMLElement;
|
|
|
|
if (
|
|
|
|
target.closest(".copy-button") ||
|
|
|
|
target.closest(".fa-square-terminal") ||
|
|
|
|
target.closest(".waveai-input")
|
|
|
|
) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const pre = target.closest("pre");
|
|
|
|
updatePreTagOutline(pre);
|
|
|
|
};
|
|
|
|
|
|
|
|
const updateScrollTop = () => {
|
|
|
|
const pres = chatWindowRef.current?.querySelectorAll("pre");
|
|
|
|
if (!pres || selectedBlockIdx === null) return;
|
|
|
|
|
|
|
|
const block = pres[selectedBlockIdx];
|
|
|
|
if (!block || !osRef.current?.osInstance()) return;
|
|
|
|
|
|
|
|
const { viewport, scrollOffsetElement } = osRef.current?.osInstance().elements();
|
|
|
|
const chatWindowTop = scrollOffsetElement.scrollTop;
|
|
|
|
const chatWindowHeight = chatWindowRef.current.clientHeight;
|
|
|
|
const chatWindowBottom = chatWindowTop + chatWindowHeight;
|
|
|
|
const elemTop = block.offsetTop;
|
|
|
|
const elemBottom = elemTop + block.offsetHeight;
|
|
|
|
const elementIsInView = elemBottom <= chatWindowBottom && elemTop >= chatWindowTop;
|
|
|
|
|
|
|
|
if (!elementIsInView) {
|
|
|
|
let scrollPosition;
|
|
|
|
if (elemBottom > chatWindowBottom) {
|
|
|
|
scrollPosition = elemTop - chatWindowHeight + block.offsetHeight + 15;
|
|
|
|
} else if (elemTop < chatWindowTop) {
|
|
|
|
scrollPosition = elemTop - 15;
|
|
|
|
}
|
|
|
|
viewport.scrollTo({
|
|
|
|
behavior: "auto",
|
|
|
|
top: scrollPosition,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const shouldSelectCodeBlock = (key: "ArrowUp" | "ArrowDown") => {
|
|
|
|
const textarea = inputRef.current;
|
|
|
|
const cursorPosition = textarea?.selectionStart || 0;
|
|
|
|
const textBeforeCursor = textarea?.value.slice(0, cursorPosition) || "";
|
|
|
|
|
|
|
|
return (
|
|
|
|
(textBeforeCursor.indexOf("\n") === -1 && cursorPosition === 0 && key === "ArrowUp") ||
|
|
|
|
selectedBlockIdx !== null
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleArrowUpPressed = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
|
|
if (shouldSelectCodeBlock("ArrowUp")) {
|
|
|
|
e.preventDefault();
|
|
|
|
const pres = chatWindowRef.current?.querySelectorAll("pre");
|
|
|
|
let blockIndex = selectedBlockIdx;
|
|
|
|
if (!pres) return;
|
|
|
|
if (blockIndex === null) {
|
|
|
|
setSelectedBlockIdx(pres.length - 1);
|
|
|
|
} else if (blockIndex > 0) {
|
|
|
|
blockIndex--;
|
|
|
|
setSelectedBlockIdx(blockIndex);
|
|
|
|
}
|
|
|
|
updateScrollTop();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleArrowDownPressed = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
|
|
|
if (shouldSelectCodeBlock("ArrowDown")) {
|
|
|
|
e.preventDefault();
|
|
|
|
const pres = chatWindowRef.current?.querySelectorAll("pre");
|
|
|
|
let blockIndex = selectedBlockIdx;
|
|
|
|
if (!pres) return;
|
|
|
|
if (blockIndex === null) return;
|
|
|
|
if (blockIndex < pres.length - 1 && blockIndex >= 0) {
|
|
|
|
setSelectedBlockIdx(++blockIndex);
|
|
|
|
updateScrollTop();
|
|
|
|
} else {
|
|
|
|
inputRef.current.focus();
|
|
|
|
setSelectedBlockIdx(null);
|
|
|
|
}
|
|
|
|
updateScrollTop();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleTextAreaKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
2024-08-30 02:00:24 +02:00
|
|
|
const waveEvent = adaptFromReactOrNativeKeyEvent(e);
|
|
|
|
if (checkKeyPressed(waveEvent, "Enter")) {
|
2024-07-03 23:32:55 +02:00
|
|
|
e.preventDefault();
|
|
|
|
handleEnterKeyPressed();
|
2024-08-30 02:00:24 +02:00
|
|
|
} else if (checkKeyPressed(waveEvent, "ArrowUp")) {
|
2024-07-03 23:32:55 +02:00
|
|
|
handleArrowUpPressed(e);
|
2024-08-30 02:00:24 +02:00
|
|
|
} else if (checkKeyPressed(waveEvent, "ArrowDown")) {
|
2024-07-03 23:32:55 +02:00
|
|
|
handleArrowDownPressed(e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
2024-07-10 03:15:37 +02:00
|
|
|
<div ref={waveaiRef} className="waveai" onClick={handleContainerClick}>
|
2024-07-03 23:32:55 +02:00
|
|
|
<ChatWindow ref={osRef} chatWindowRef={chatWindowRef} messages={messages} />
|
|
|
|
<div className="waveai-input-wrapper">
|
|
|
|
<ChatInput
|
|
|
|
ref={inputRef}
|
|
|
|
value={value}
|
2024-08-01 09:03:19 +02:00
|
|
|
model={model}
|
2024-07-03 23:32:55 +02:00
|
|
|
onChange={handleTextAreaChange}
|
|
|
|
onKeyDown={handleTextAreaKeyDown}
|
|
|
|
onMouseDown={handleTextAreaMouseDown}
|
|
|
|
termFontSize={termFontSize}
|
|
|
|
/>
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
);
|
2024-07-10 03:15:37 +02:00
|
|
|
};
|
2024-07-03 23:32:55 +02:00
|
|
|
|
2024-09-05 23:40:24 +02:00
|
|
|
export { makeWaveAiViewModel, WaveAi };
|