mirror of
https://github.com/Yidadaa/ChatGPT-Next-Web.git
synced 2025-08-08 16:51:54 +08:00
merge
This commit is contained in:
@@ -8,6 +8,15 @@ async function createStream(req: NextRequest) {
|
||||
|
||||
const res = await requestOpenai(req);
|
||||
|
||||
const contentType = res.headers.get("Content-Type") ?? "";
|
||||
if (!contentType.includes("stream")) {
|
||||
const content = await (
|
||||
await res.text()
|
||||
).replace(/provided:.*. You/, "provided: ***. You");
|
||||
console.log("[Stream] error ", content);
|
||||
return "```json\n" + content + "```";
|
||||
}
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
function onParse(event: any) {
|
||||
@@ -44,6 +53,9 @@ export async function POST(req: NextRequest) {
|
||||
return new Response(stream);
|
||||
} catch (error) {
|
||||
console.error("[Chat Stream]", error);
|
||||
return new Response(
|
||||
["```json\n", JSON.stringify(error, null, " "), "\n```"].join(""),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -3,8 +3,11 @@ import { requestOpenai } from "../common";
|
||||
|
||||
async function makeRequest(req: NextRequest) {
|
||||
try {
|
||||
const res = await requestOpenai(req);
|
||||
return new Response(res.body);
|
||||
const api = await requestOpenai(req);
|
||||
const res = new NextResponse(api.body);
|
||||
res.headers.set("Content-Type", "application/json");
|
||||
res.headers.set("Cache-Control", "no-cache");
|
||||
return res;
|
||||
} catch (e) {
|
||||
console.error("[OpenAI] ", req.body, e);
|
||||
return NextResponse.json(
|
||||
|
@@ -6,11 +6,22 @@
|
||||
justify-content: center;
|
||||
padding: 10px;
|
||||
|
||||
box-shadow: var(--card-shadow);
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
overflow: hidden;
|
||||
user-select: none;
|
||||
outline: none;
|
||||
border: none;
|
||||
color: rgb(51, 51, 51);
|
||||
|
||||
&[disabled] {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.shadow {
|
||||
box-shadow: var(--card-shadow);
|
||||
}
|
||||
|
||||
.border {
|
||||
@@ -18,7 +29,6 @@
|
||||
}
|
||||
|
||||
.icon-button:hover {
|
||||
filter: brightness(0.9);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
@@ -36,25 +46,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
@mixin dark-button {
|
||||
div:not(:global(.no-dark))>.icon-button-icon {
|
||||
filter: invert(0.5);
|
||||
}
|
||||
|
||||
.icon-button:hover {
|
||||
filter: brightness(1.2);
|
||||
}
|
||||
}
|
||||
|
||||
:global(.dark) {
|
||||
@include dark-button;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
@include dark-button;
|
||||
}
|
||||
|
||||
.icon-button-text {
|
||||
margin-left: 5px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
@@ -7,22 +7,33 @@ export function IconButton(props: {
|
||||
icon: JSX.Element;
|
||||
text?: string;
|
||||
bordered?: boolean;
|
||||
shadow?: boolean;
|
||||
noDark?: boolean;
|
||||
className?: string;
|
||||
title?: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
<button
|
||||
className={
|
||||
styles["icon-button"] +
|
||||
` ${props.bordered && styles.border} ${props.className ?? ""}`
|
||||
` ${props.bordered && styles.border} ${props.shadow && styles.shadow} ${
|
||||
props.className ?? ""
|
||||
} clickable`
|
||||
}
|
||||
onClick={props.onClick}
|
||||
title={props.title}
|
||||
disabled={props.disabled}
|
||||
role="button"
|
||||
>
|
||||
<div className={styles["icon-button-icon"]}>{props.icon}</div>
|
||||
<div
|
||||
className={styles["icon-button-icon"] + ` ${props.noDark && "no-dark"}`}
|
||||
>
|
||||
{props.icon}
|
||||
</div>
|
||||
{props.text && (
|
||||
<div className={styles["icon-button-text"]}>{props.text}</div>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
110
app/components/chat-list.tsx
Normal file
110
app/components/chat-list.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import DeleteIcon from "../icons/delete.svg";
|
||||
import styles from "./home.module.scss";
|
||||
import {
|
||||
DragDropContext,
|
||||
Droppable,
|
||||
Draggable,
|
||||
OnDragEndResponder,
|
||||
} from "@hello-pangea/dnd";
|
||||
|
||||
import { useChatStore } from "../store";
|
||||
|
||||
import Locale from "../locales";
|
||||
import { isMobileScreen } from "../utils";
|
||||
|
||||
export function ChatItem(props: {
|
||||
onClick?: () => void;
|
||||
onDelete?: () => void;
|
||||
title: string;
|
||||
count: number;
|
||||
time: string;
|
||||
selected: boolean;
|
||||
id: number;
|
||||
index: number;
|
||||
}) {
|
||||
return (
|
||||
<Draggable draggableId={`${props.id}`} index={props.index}>
|
||||
{(provided) => (
|
||||
<div
|
||||
className={`${styles["chat-item"]} ${
|
||||
props.selected && styles["chat-item-selected"]
|
||||
}`}
|
||||
onClick={props.onClick}
|
||||
ref={provided.innerRef}
|
||||
{...provided.draggableProps}
|
||||
{...provided.dragHandleProps}
|
||||
>
|
||||
<div className={styles["chat-item-title"]}>{props.title}</div>
|
||||
<div className={styles["chat-item-info"]}>
|
||||
<div className={styles["chat-item-count"]}>
|
||||
{Locale.ChatItem.ChatItemCount(props.count)}
|
||||
</div>
|
||||
<div className={styles["chat-item-date"]}>{props.time}</div>
|
||||
</div>
|
||||
<div className={styles["chat-item-delete"]} onClick={props.onDelete}>
|
||||
<DeleteIcon />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Draggable>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatList() {
|
||||
const [sessions, selectedIndex, selectSession, removeSession, moveSession] =
|
||||
useChatStore((state) => [
|
||||
state.sessions,
|
||||
state.currentSessionIndex,
|
||||
state.selectSession,
|
||||
state.removeSession,
|
||||
state.moveSession,
|
||||
]);
|
||||
|
||||
const onDragEnd: OnDragEndResponder = (result) => {
|
||||
const { destination, source } = result;
|
||||
if (!destination) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
destination.droppableId === source.droppableId &&
|
||||
destination.index === source.index
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
moveSession(source.index, destination.index);
|
||||
};
|
||||
|
||||
return (
|
||||
<DragDropContext onDragEnd={onDragEnd}>
|
||||
<Droppable droppableId="chat-list">
|
||||
{(provided) => (
|
||||
<div
|
||||
className={styles["chat-list"]}
|
||||
ref={provided.innerRef}
|
||||
{...provided.droppableProps}
|
||||
>
|
||||
{sessions.map((item, i) => (
|
||||
<ChatItem
|
||||
title={item.topic}
|
||||
time={item.lastUpdate}
|
||||
count={item.messages.length}
|
||||
key={item.id}
|
||||
id={item.id}
|
||||
index={i}
|
||||
selected={i === selectedIndex}
|
||||
onClick={() => selectSession(i)}
|
||||
onDelete={() =>
|
||||
(!isMobileScreen() || confirm(Locale.Home.DeleteChat)) &&
|
||||
removeSession(i)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{provided.placeholder}
|
||||
</div>
|
||||
)}
|
||||
</Droppable>
|
||||
</DragDropContext>
|
||||
);
|
||||
}
|
83
app/components/chat.module.scss
Normal file
83
app/components/chat.module.scss
Normal file
@@ -0,0 +1,83 @@
|
||||
@import "../styles/animation.scss";
|
||||
|
||||
.prompt-toast {
|
||||
position: absolute;
|
||||
bottom: -50px;
|
||||
z-index: 999;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: calc(100% - 40px);
|
||||
|
||||
.prompt-toast-inner {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
background-color: var(--white);
|
||||
color: var(--black);
|
||||
|
||||
border: var(--border-in-light);
|
||||
box-shadow: var(--card-shadow);
|
||||
padding: 10px 20px;
|
||||
border-radius: 100px;
|
||||
|
||||
animation: slide-in-from-top ease 0.3s;
|
||||
|
||||
.prompt-toast-content {
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.context-prompt {
|
||||
.context-prompt-row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
margin-bottom: 10px;
|
||||
|
||||
.context-role {
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.context-content {
|
||||
flex: 1;
|
||||
max-width: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.context-delete-button {
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.context-prompt-button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.memory-prompt {
|
||||
margin-top: 20px;
|
||||
|
||||
.memory-prompt-title {
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
margin-bottom: 10px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
.memory-prompt-action {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
.memory-prompt-content {
|
||||
background-color: var(--gray);
|
||||
border-radius: 6px;
|
||||
padding: 10px;
|
||||
font-size: 12px;
|
||||
user-select: text;
|
||||
}
|
||||
}
|
689
app/components/chat.tsx
Normal file
689
app/components/chat.tsx
Normal file
@@ -0,0 +1,689 @@
|
||||
import { useDebouncedCallback } from "use-debounce";
|
||||
import { memo, useState, useRef, useEffect, useLayoutEffect } from "react";
|
||||
|
||||
import SendWhiteIcon from "../icons/send-white.svg";
|
||||
import BrainIcon from "../icons/brain.svg";
|
||||
import ExportIcon from "../icons/export.svg";
|
||||
import MenuIcon from "../icons/menu.svg";
|
||||
import CopyIcon from "../icons/copy.svg";
|
||||
import DownloadIcon from "../icons/download.svg";
|
||||
import LoadingIcon from "../icons/three-dots.svg";
|
||||
import BotIcon from "../icons/bot.svg";
|
||||
import AddIcon from "../icons/add.svg";
|
||||
import DeleteIcon from "../icons/delete.svg";
|
||||
|
||||
import {
|
||||
Message,
|
||||
SubmitKey,
|
||||
useChatStore,
|
||||
BOT_HELLO,
|
||||
ROLES,
|
||||
createMessage,
|
||||
} from "../store";
|
||||
|
||||
import {
|
||||
copyToClipboard,
|
||||
downloadAs,
|
||||
getEmojiUrl,
|
||||
isMobileScreen,
|
||||
selectOrCopy,
|
||||
} from "../utils";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { ControllerPool } from "../requests";
|
||||
import { Prompt, usePromptStore } from "../store/prompt";
|
||||
import Locale from "../locales";
|
||||
|
||||
import { IconButton } from "./button";
|
||||
import styles from "./home.module.scss";
|
||||
import chatStyle from "./chat.module.scss";
|
||||
|
||||
import { Input, Modal, showModal, showToast } from "./ui-lib";
|
||||
|
||||
const Markdown = dynamic(
|
||||
async () => memo((await import("./markdown")).Markdown),
|
||||
{
|
||||
loading: () => <LoadingIcon />,
|
||||
},
|
||||
);
|
||||
|
||||
const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
|
||||
loading: () => <LoadingIcon />,
|
||||
});
|
||||
|
||||
export function Avatar(props: { role: Message["role"] }) {
|
||||
const config = useChatStore((state) => state.config);
|
||||
|
||||
if (props.role !== "user") {
|
||||
return <BotIcon className={styles["user-avtar"]} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles["user-avtar"]}>
|
||||
<Emoji unified={config.avatar} size={18} getEmojiUrl={getEmojiUrl} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function exportMessages(messages: Message[], topic: string) {
|
||||
const mdText =
|
||||
`# ${topic}\n\n` +
|
||||
messages
|
||||
.map((m) => {
|
||||
return m.role === "user"
|
||||
? `## ${Locale.Export.MessageFromYou}:\n${m.content}`
|
||||
: `## ${Locale.Export.MessageFromChatGPT}:\n${m.content.trim()}`;
|
||||
})
|
||||
.join("\n\n");
|
||||
const filename = `${topic}.md`;
|
||||
|
||||
showModal({
|
||||
title: Locale.Export.Title,
|
||||
children: (
|
||||
<div className="markdown-body">
|
||||
<pre className={styles["export-content"]}>{mdText}</pre>
|
||||
</div>
|
||||
),
|
||||
actions: [
|
||||
<IconButton
|
||||
key="copy"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Export.Copy}
|
||||
onClick={() => copyToClipboard(mdText)}
|
||||
/>,
|
||||
<IconButton
|
||||
key="download"
|
||||
icon={<DownloadIcon />}
|
||||
bordered
|
||||
text={Locale.Export.Download}
|
||||
onClick={() => downloadAs(mdText, filename)}
|
||||
/>,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function PromptToast(props: {
|
||||
showToast?: boolean;
|
||||
showModal?: boolean;
|
||||
setShowModal: (_: boolean) => void;
|
||||
}) {
|
||||
const chatStore = useChatStore();
|
||||
const session = chatStore.currentSession();
|
||||
const context = session.context;
|
||||
|
||||
const addContextPrompt = (prompt: Message) => {
|
||||
chatStore.updateCurrentSession((session) => {
|
||||
session.context.push(prompt);
|
||||
});
|
||||
};
|
||||
|
||||
const removeContextPrompt = (i: number) => {
|
||||
chatStore.updateCurrentSession((session) => {
|
||||
session.context.splice(i, 1);
|
||||
});
|
||||
};
|
||||
|
||||
const updateContextPrompt = (i: number, prompt: Message) => {
|
||||
chatStore.updateCurrentSession((session) => {
|
||||
session.context[i] = prompt;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={chatStyle["prompt-toast"]} key="prompt-toast">
|
||||
{props.showToast && (
|
||||
<div
|
||||
className={chatStyle["prompt-toast-inner"] + " clickable"}
|
||||
role="button"
|
||||
onClick={() => props.setShowModal(true)}
|
||||
>
|
||||
<BrainIcon />
|
||||
<span className={chatStyle["prompt-toast-content"]}>
|
||||
{Locale.Context.Toast(context.length)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{props.showModal && (
|
||||
<div className="modal-mask">
|
||||
<Modal
|
||||
title={Locale.Context.Edit}
|
||||
onClose={() => props.setShowModal(false)}
|
||||
actions={[
|
||||
<IconButton
|
||||
key="reset"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Memory.Reset}
|
||||
onClick={() =>
|
||||
confirm(Locale.Memory.ResetConfirm) &&
|
||||
chatStore.resetSession()
|
||||
}
|
||||
/>,
|
||||
<IconButton
|
||||
key="copy"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Memory.Copy}
|
||||
onClick={() => copyToClipboard(session.memoryPrompt)}
|
||||
/>,
|
||||
]}
|
||||
>
|
||||
<>
|
||||
<div className={chatStyle["context-prompt"]}>
|
||||
{context.map((c, i) => (
|
||||
<div className={chatStyle["context-prompt-row"]} key={i}>
|
||||
<select
|
||||
value={c.role}
|
||||
className={chatStyle["context-role"]}
|
||||
onChange={(e) =>
|
||||
updateContextPrompt(i, {
|
||||
...c,
|
||||
role: e.target.value as any,
|
||||
})
|
||||
}
|
||||
>
|
||||
{ROLES.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Input
|
||||
value={c.content}
|
||||
type="text"
|
||||
className={chatStyle["context-content"]}
|
||||
rows={1}
|
||||
onInput={(e) =>
|
||||
updateContextPrompt(i, {
|
||||
...c,
|
||||
content: e.currentTarget.value as any,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<IconButton
|
||||
icon={<DeleteIcon />}
|
||||
className={chatStyle["context-delete-button"]}
|
||||
onClick={() => removeContextPrompt(i)}
|
||||
bordered
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<div className={chatStyle["context-prompt-row"]}>
|
||||
<IconButton
|
||||
icon={<AddIcon />}
|
||||
text={Locale.Context.Add}
|
||||
bordered
|
||||
className={chatStyle["context-prompt-button"]}
|
||||
onClick={() =>
|
||||
addContextPrompt({
|
||||
role: "system",
|
||||
content: "",
|
||||
date: "",
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className={chatStyle["memory-prompt"]}>
|
||||
<div className={chatStyle["memory-prompt-title"]}>
|
||||
<span>
|
||||
{Locale.Memory.Title} ({session.lastSummarizeIndex} of{" "}
|
||||
{session.messages.length})
|
||||
</span>
|
||||
|
||||
<label className={chatStyle["memory-prompt-action"]}>
|
||||
{Locale.Memory.Send}
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={session.sendMemory}
|
||||
onChange={() =>
|
||||
chatStore.updateCurrentSession(
|
||||
(session) =>
|
||||
(session.sendMemory = !session.sendMemory),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
</label>
|
||||
</div>
|
||||
<div className={chatStyle["memory-prompt-content"]}>
|
||||
{session.memoryPrompt || Locale.Memory.EmptyContent}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</Modal>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useSubmitHandler() {
|
||||
const config = useChatStore((state) => state.config);
|
||||
const submitKey = config.submitKey;
|
||||
|
||||
const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key !== "Enter") return false;
|
||||
if (e.key === "Enter" && e.nativeEvent.isComposing) return false;
|
||||
return (
|
||||
(config.submitKey === SubmitKey.AltEnter && e.altKey) ||
|
||||
(config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
|
||||
(config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
|
||||
(config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
|
||||
(config.submitKey === SubmitKey.Enter &&
|
||||
!e.altKey &&
|
||||
!e.ctrlKey &&
|
||||
!e.shiftKey &&
|
||||
!e.metaKey)
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
submitKey,
|
||||
shouldSubmit,
|
||||
};
|
||||
}
|
||||
|
||||
export function PromptHints(props: {
|
||||
prompts: Prompt[];
|
||||
onPromptSelect: (prompt: Prompt) => void;
|
||||
}) {
|
||||
if (props.prompts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={styles["prompt-hints"]}>
|
||||
{props.prompts.map((prompt, i) => (
|
||||
<div
|
||||
className={styles["prompt-hint"]}
|
||||
key={prompt.title + i.toString()}
|
||||
onClick={() => props.onPromptSelect(prompt)}
|
||||
>
|
||||
<div className={styles["hint-title"]}>{prompt.title}</div>
|
||||
<div className={styles["hint-content"]}>{prompt.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useScrollToBottom() {
|
||||
// for auto-scroll
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
// auto scroll
|
||||
useLayoutEffect(() => {
|
||||
const dom = scrollRef.current;
|
||||
if (dom && autoScroll) {
|
||||
setTimeout(() => (dom.scrollTop = dom.scrollHeight), 1);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
scrollRef,
|
||||
autoScroll,
|
||||
setAutoScroll,
|
||||
};
|
||||
}
|
||||
|
||||
export function Chat(props: {
|
||||
showSideBar?: () => void;
|
||||
sideBarShowing?: boolean;
|
||||
}) {
|
||||
type RenderMessage = Message & { preview?: boolean };
|
||||
|
||||
const chatStore = useChatStore();
|
||||
const [session, sessionIndex] = useChatStore((state) => [
|
||||
state.currentSession(),
|
||||
state.currentSessionIndex,
|
||||
]);
|
||||
const fontSize = useChatStore((state) => state.config.fontSize);
|
||||
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [userInput, setUserInput] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { submitKey, shouldSubmit } = useSubmitHandler();
|
||||
const { scrollRef, setAutoScroll } = useScrollToBottom();
|
||||
const [hitBottom, setHitBottom] = useState(false);
|
||||
|
||||
const onChatBodyScroll = (e: HTMLElement) => {
|
||||
const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
|
||||
setHitBottom(isTouchBottom);
|
||||
};
|
||||
|
||||
// prompt hints
|
||||
const promptStore = usePromptStore();
|
||||
const [promptHints, setPromptHints] = useState<Prompt[]>([]);
|
||||
const onSearch = useDebouncedCallback(
|
||||
(text: string) => {
|
||||
setPromptHints(promptStore.search(text));
|
||||
},
|
||||
100,
|
||||
{ leading: true, trailing: true },
|
||||
);
|
||||
|
||||
const onPromptSelect = (prompt: Prompt) => {
|
||||
setUserInput(prompt.content);
|
||||
setPromptHints([]);
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
const scrollInput = () => {
|
||||
const dom = inputRef.current;
|
||||
if (!dom) return;
|
||||
const paddingBottomNum: number = parseInt(
|
||||
window.getComputedStyle(dom).paddingBottom,
|
||||
10,
|
||||
);
|
||||
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
|
||||
};
|
||||
|
||||
// only search prompts when user input is short
|
||||
const SEARCH_TEXT_LIMIT = 30;
|
||||
const onInput = (text: string) => {
|
||||
scrollInput();
|
||||
setUserInput(text);
|
||||
const n = text.trim().length;
|
||||
|
||||
// clear search results
|
||||
if (n === 0) {
|
||||
setPromptHints([]);
|
||||
} else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
|
||||
// check if need to trigger auto completion
|
||||
if (text.startsWith("/")) {
|
||||
let searchText = text.slice(1);
|
||||
if (searchText.length === 0) {
|
||||
searchText = " ";
|
||||
}
|
||||
onSearch(searchText);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// submit user input
|
||||
const onUserSubmit = () => {
|
||||
setIsLoading(true);
|
||||
chatStore.onUserInput(userInput).then(() => setIsLoading(false));
|
||||
setUserInput("");
|
||||
setPromptHints([]);
|
||||
if (!isMobileScreen()) inputRef.current?.focus();
|
||||
setAutoScroll(true);
|
||||
};
|
||||
|
||||
// stop response
|
||||
const onUserStop = (messageId: number) => {
|
||||
ControllerPool.stop(sessionIndex, messageId);
|
||||
};
|
||||
|
||||
// check if should send message
|
||||
const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (shouldSubmit(e)) {
|
||||
setAutoScroll(true);
|
||||
onUserSubmit();
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
const onRightClick = (e: any, message: Message) => {
|
||||
// auto fill user input
|
||||
if (message.role === "user") {
|
||||
setUserInput(message.content);
|
||||
}
|
||||
|
||||
// copy to clipboard
|
||||
if (selectOrCopy(e.currentTarget, message.content)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const onResend = (botIndex: number) => {
|
||||
// find last user input message and resend
|
||||
for (let i = botIndex; i >= 0; i -= 1) {
|
||||
if (messages[i].role === "user") {
|
||||
setIsLoading(true);
|
||||
chatStore
|
||||
.onUserInput(messages[i].content)
|
||||
.then(() => setIsLoading(false));
|
||||
chatStore.updateCurrentSession((session) =>
|
||||
session.messages.splice(i, 2),
|
||||
);
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const config = useChatStore((state) => state.config);
|
||||
|
||||
const context: RenderMessage[] = session.context.slice();
|
||||
|
||||
if (
|
||||
context.length === 0 &&
|
||||
session.messages.at(0)?.content !== BOT_HELLO.content
|
||||
) {
|
||||
context.push(BOT_HELLO);
|
||||
}
|
||||
|
||||
// preview messages
|
||||
const messages = context
|
||||
.concat(session.messages as RenderMessage[])
|
||||
.concat(
|
||||
isLoading
|
||||
? [
|
||||
{
|
||||
...createMessage({
|
||||
role: "assistant",
|
||||
content: "……",
|
||||
}),
|
||||
preview: true,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
)
|
||||
.concat(
|
||||
userInput.length > 0 && config.sendPreviewBubble
|
||||
? [
|
||||
{
|
||||
...createMessage({
|
||||
role: "user",
|
||||
content: userInput,
|
||||
}),
|
||||
preview: true,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
|
||||
const [showPromptModal, setShowPromptModal] = useState(false);
|
||||
|
||||
// Auto focus
|
||||
useEffect(() => {
|
||||
if (props.sideBarShowing && isMobileScreen()) return;
|
||||
inputRef.current?.focus();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={styles.chat} key={session.id}>
|
||||
<div className={styles["window-header"]}>
|
||||
<div
|
||||
className={styles["window-header-title"]}
|
||||
onClick={props?.showSideBar}
|
||||
>
|
||||
<div
|
||||
className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
|
||||
onClick={() => {
|
||||
const newTopic = prompt(Locale.Chat.Rename, session.topic);
|
||||
if (newTopic && newTopic !== session.topic) {
|
||||
chatStore.updateCurrentSession(
|
||||
(session) => (session.topic = newTopic!),
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{session.topic}
|
||||
</div>
|
||||
<div className={styles["window-header-sub-title"]}>
|
||||
{Locale.Chat.SubTitle(session.messages.length)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles["window-actions"]}>
|
||||
<div className={styles["window-action-button"] + " " + styles.mobile}>
|
||||
<IconButton
|
||||
icon={<MenuIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.ChatList}
|
||||
onClick={props?.showSideBar}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["window-action-button"]}>
|
||||
<IconButton
|
||||
icon={<BrainIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.CompressedHistory}
|
||||
onClick={() => {
|
||||
setShowPromptModal(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["window-action-button"]}>
|
||||
<IconButton
|
||||
icon={<ExportIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.Export}
|
||||
onClick={() => {
|
||||
exportMessages(
|
||||
session.messages.filter((msg) => !msg.isError),
|
||||
session.topic,
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PromptToast
|
||||
showToast={!hitBottom}
|
||||
showModal={showPromptModal}
|
||||
setShowModal={setShowPromptModal}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={styles["chat-body"]}
|
||||
ref={scrollRef}
|
||||
onScroll={(e) => onChatBodyScroll(e.currentTarget)}
|
||||
onWheel={(e) => setAutoScroll(hitBottom && e.deltaY > 0)}
|
||||
onTouchStart={() => {
|
||||
inputRef.current?.blur();
|
||||
setAutoScroll(false);
|
||||
}}
|
||||
>
|
||||
{messages.map((message, i) => {
|
||||
const isUser = message.role === "user";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={
|
||||
isUser ? styles["chat-message-user"] : styles["chat-message"]
|
||||
}
|
||||
>
|
||||
<div className={styles["chat-message-container"]}>
|
||||
<div className={styles["chat-message-avatar"]}>
|
||||
<Avatar role={message.role} />
|
||||
</div>
|
||||
{(message.preview || message.streaming) && (
|
||||
<div className={styles["chat-message-status"]}>
|
||||
{Locale.Chat.Typing}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles["chat-message-item"]}>
|
||||
{!isUser &&
|
||||
!(message.preview || message.content.length === 0) && (
|
||||
<div className={styles["chat-message-top-actions"]}>
|
||||
{message.streaming ? (
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => onUserStop(message.id ?? i)}
|
||||
>
|
||||
{Locale.Chat.Actions.Stop}
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => onResend(i)}
|
||||
>
|
||||
{Locale.Chat.Actions.Retry}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => copyToClipboard(message.content)}
|
||||
>
|
||||
{Locale.Chat.Actions.Copy}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(message.preview || message.content.length === 0) &&
|
||||
!isUser ? (
|
||||
<LoadingIcon />
|
||||
) : (
|
||||
<div
|
||||
className="markdown-body"
|
||||
style={{ fontSize: `${fontSize}px` }}
|
||||
onContextMenu={(e) => onRightClick(e, message)}
|
||||
onDoubleClickCapture={() => {
|
||||
if (!isMobileScreen()) return;
|
||||
setUserInput(message.content);
|
||||
}}
|
||||
>
|
||||
<Markdown content={message.content} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!isUser && !message.preview && (
|
||||
<div className={styles["chat-message-actions"]}>
|
||||
<div className={styles["chat-message-action-date"]}>
|
||||
{message.date.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className={styles["chat-input-panel"]}>
|
||||
<PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
|
||||
<div className={styles["chat-input-panel-inner"]}>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
className={styles["chat-input"]}
|
||||
placeholder={Locale.Chat.Input(submitKey)}
|
||||
rows={2}
|
||||
onInput={(e) => onInput(e.currentTarget.value)}
|
||||
value={userInput}
|
||||
onKeyDown={onInputKeyDown}
|
||||
onFocus={() => setAutoScroll(isMobileScreen())}
|
||||
onBlur={() => {
|
||||
setAutoScroll(false);
|
||||
setTimeout(() => setPromptHints([]), 500);
|
||||
}}
|
||||
autoFocus={!props?.sideBarShowing}
|
||||
/>
|
||||
<IconButton
|
||||
icon={<SendWhiteIcon />}
|
||||
text={Locale.Chat.Send}
|
||||
className={styles["chat-input-send"]}
|
||||
noDark
|
||||
disabled={!userInput}
|
||||
onClick={onUserSubmit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
47
app/components/error.tsx
Normal file
47
app/components/error.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import React from "react";
|
||||
import { IconButton } from "./button";
|
||||
import GithubIcon from "../icons/github.svg";
|
||||
import { ISSUE_URL } from "../constant";
|
||||
|
||||
interface IErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
info: React.ErrorInfo | null;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null, info: null };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo) {
|
||||
// Update state with error details
|
||||
this.setState({ hasError: true, error, info });
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
// Render error message
|
||||
return (
|
||||
<div className="error">
|
||||
<h2>Oops, something went wrong!</h2>
|
||||
<pre>
|
||||
<code>{this.state.error?.toString()}</code>
|
||||
<code>{this.state.info?.componentStack}</code>
|
||||
</pre>
|
||||
|
||||
<a href={ISSUE_URL} className="report">
|
||||
<IconButton
|
||||
text="Report This Error"
|
||||
icon={<GithubIcon />}
|
||||
bordered
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// if no error occurred, render children
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
@import "./window.scss";
|
||||
@import "../styles/animation.scss";
|
||||
|
||||
@mixin container {
|
||||
background-color: var(--white);
|
||||
@@ -73,7 +74,7 @@
|
||||
.sidebar {
|
||||
position: absolute;
|
||||
left: -100%;
|
||||
z-index: 999;
|
||||
z-index: 1000;
|
||||
height: var(--full-height);
|
||||
transition: all ease 0.3s;
|
||||
box-shadow: none;
|
||||
@@ -124,7 +125,7 @@
|
||||
border-radius: 10px;
|
||||
margin-bottom: 10px;
|
||||
box-shadow: var(--card-shadow);
|
||||
transition: all 0.3s ease;
|
||||
transition: background-color 0.3s ease;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
border: 2px solid transparent;
|
||||
@@ -132,18 +133,6 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@keyframes slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
||||
|
||||
.chat-item:hover {
|
||||
background-color: var(--hover-color);
|
||||
}
|
||||
@@ -218,6 +207,7 @@
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 20px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.chat-body-title {
|
||||
@@ -343,6 +333,7 @@
|
||||
.chat-input-panel {
|
||||
width: 100%;
|
||||
padding: 20px;
|
||||
padding-top: 5px;
|
||||
box-sizing: border-box;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect, useLayoutEffect } from "react";
|
||||
import { useDebouncedCallback } from "use-debounce";
|
||||
require("../polyfill");
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import { IconButton } from "./button";
|
||||
import styles from "./home.module.scss";
|
||||
@@ -9,33 +10,20 @@ import styles from "./home.module.scss";
|
||||
import SettingsIcon from "../icons/settings.svg";
|
||||
import GithubIcon from "../icons/github.svg";
|
||||
import ChatGptIcon from "../icons/chatgpt.svg";
|
||||
import SendWhiteIcon from "../icons/send-white.svg";
|
||||
import BrainIcon from "../icons/brain.svg";
|
||||
import ExportIcon from "../icons/export.svg";
|
||||
|
||||
import BotIcon from "../icons/bot.svg";
|
||||
import AddIcon from "../icons/add.svg";
|
||||
import DeleteIcon from "../icons/delete.svg";
|
||||
import LoadingIcon from "../icons/three-dots.svg";
|
||||
import MenuIcon from "../icons/menu.svg";
|
||||
import CloseIcon from "../icons/close.svg";
|
||||
import CopyIcon from "../icons/copy.svg";
|
||||
import DownloadIcon from "../icons/download.svg";
|
||||
|
||||
import { Message, SubmitKey, useChatStore, ChatSession } from "../store";
|
||||
import { showModal, showToast } from "./ui-lib";
|
||||
import {
|
||||
copyToClipboard,
|
||||
downloadAs,
|
||||
isIOS,
|
||||
isMobileScreen,
|
||||
selectOrCopy,
|
||||
} from "../utils";
|
||||
import { useChatStore } from "../store";
|
||||
import { isMobileScreen } from "../utils";
|
||||
import Locale from "../locales";
|
||||
import { Chat } from "./chat";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { REPO_URL } from "../constant";
|
||||
import { ControllerPool } from "../requests";
|
||||
import { Prompt, usePromptStore } from "../store/prompt";
|
||||
import { ErrorBoundary } from "./error";
|
||||
|
||||
import calcTextareaHeight from "../calcTextareaHeight";
|
||||
|
||||
@@ -48,482 +36,14 @@ export function Loading(props: { noLogo?: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
|
||||
loading: () => <LoadingIcon />,
|
||||
});
|
||||
|
||||
const Settings = dynamic(async () => (await import("./settings")).Settings, {
|
||||
loading: () => <Loading noLogo />,
|
||||
});
|
||||
|
||||
const Emoji = dynamic(async () => (await import("emoji-picker-react")).Emoji, {
|
||||
loading: () => <LoadingIcon />,
|
||||
const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
|
||||
loading: () => <Loading noLogo />,
|
||||
});
|
||||
|
||||
export function Avatar(props: { role: Message["role"] }) {
|
||||
const config = useChatStore((state) => state.config);
|
||||
|
||||
if (props.role === "assistant") {
|
||||
return <BotIcon className={styles["user-avtar"]} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles["user-avtar"]}>
|
||||
<Emoji unified={config.avatar} size={18} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatItem(props: {
|
||||
onClick?: () => void;
|
||||
onDelete?: () => void;
|
||||
title: string;
|
||||
count: number;
|
||||
time: string;
|
||||
selected: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`${styles["chat-item"]} ${
|
||||
props.selected && styles["chat-item-selected"]
|
||||
}`}
|
||||
onClick={props.onClick}
|
||||
>
|
||||
<div className={styles["chat-item-title"]}>{props.title}</div>
|
||||
<div className={styles["chat-item-info"]}>
|
||||
<div className={styles["chat-item-count"]}>
|
||||
{Locale.ChatItem.ChatItemCount(props.count)}
|
||||
</div>
|
||||
<div className={styles["chat-item-date"]}>{props.time}</div>
|
||||
</div>
|
||||
<div className={styles["chat-item-delete"]} onClick={props.onDelete}>
|
||||
<DeleteIcon />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatList() {
|
||||
const [sessions, selectedIndex, selectSession, removeSession] = useChatStore(
|
||||
(state) => [
|
||||
state.sessions,
|
||||
state.currentSessionIndex,
|
||||
state.selectSession,
|
||||
state.removeSession,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles["chat-list"]}>
|
||||
{sessions.map((item, i) => (
|
||||
<ChatItem
|
||||
title={item.topic}
|
||||
time={item.lastUpdate}
|
||||
count={item.messages.length}
|
||||
key={i}
|
||||
selected={i === selectedIndex}
|
||||
onClick={() => selectSession(i)}
|
||||
onDelete={() => confirm(Locale.Home.DeleteChat) && removeSession(i)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useSubmitHandler() {
|
||||
const config = useChatStore((state) => state.config);
|
||||
const submitKey = config.submitKey;
|
||||
|
||||
const shouldSubmit = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Enter") return false;
|
||||
|
||||
return (
|
||||
(config.submitKey === SubmitKey.AltEnter && e.altKey) ||
|
||||
(config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
|
||||
(config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
|
||||
(config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
|
||||
(config.submitKey === SubmitKey.Enter &&
|
||||
!e.altKey &&
|
||||
!e.ctrlKey &&
|
||||
!e.shiftKey &&
|
||||
!e.metaKey)
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
submitKey,
|
||||
shouldSubmit,
|
||||
};
|
||||
}
|
||||
|
||||
export function PromptHints(props: {
|
||||
prompts: Prompt[];
|
||||
onPromptSelect: (prompt: Prompt) => void;
|
||||
}) {
|
||||
if (props.prompts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={styles["prompt-hints"]}>
|
||||
{props.prompts.map((prompt, i) => (
|
||||
<div
|
||||
className={styles["prompt-hint"]}
|
||||
key={prompt.title + i.toString()}
|
||||
onClick={() => props.onPromptSelect(prompt)}
|
||||
>
|
||||
<div className={styles["hint-title"]}>{prompt.title}</div>
|
||||
<div className={styles["hint-content"]}>{prompt.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Chat(props: {
|
||||
showSideBar?: () => void;
|
||||
sideBarShowing?: boolean;
|
||||
autoSize: {
|
||||
minRows: number;
|
||||
maxRows: number;
|
||||
};
|
||||
}) {
|
||||
type RenderMessage = Message & { preview?: boolean };
|
||||
|
||||
const chatStore = useChatStore();
|
||||
const [session, sessionIndex] = useChatStore((state) => [
|
||||
state.currentSession(),
|
||||
state.currentSessionIndex,
|
||||
]);
|
||||
const fontSize = useChatStore((state) => state.config.fontSize);
|
||||
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const [userInput, setUserInput] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [textareaStyle, setTextareaStyle] = useState({});
|
||||
const { submitKey, shouldSubmit } = useSubmitHandler();
|
||||
|
||||
// prompt hints
|
||||
const promptStore = usePromptStore();
|
||||
const [promptHints, setPromptHints] = useState<Prompt[]>([]);
|
||||
const onSearch = useDebouncedCallback(
|
||||
(text: string) => {
|
||||
setPromptHints(promptStore.search(text));
|
||||
},
|
||||
100,
|
||||
{ leading: true, trailing: true }
|
||||
);
|
||||
|
||||
const onPromptSelect = (prompt: Prompt) => {
|
||||
setUserInput(prompt.content);
|
||||
setPromptHints([]);
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
const scrollInput = () => {
|
||||
const dom = inputRef.current;
|
||||
if (!dom) return;
|
||||
const paddingBottomNum: number = parseInt(
|
||||
window.getComputedStyle(dom).paddingBottom,
|
||||
10
|
||||
);
|
||||
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
|
||||
};
|
||||
|
||||
// only search prompts when user input is short
|
||||
const SEARCH_TEXT_LIMIT = 30;
|
||||
const onInput = (text: string) => {
|
||||
scrollInput();
|
||||
setUserInput(text);
|
||||
const n = text.trim().length;
|
||||
|
||||
// clear search results
|
||||
if (n === 0) {
|
||||
setPromptHints([]);
|
||||
} else if (!chatStore.config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
|
||||
// check if need to trigger auto completion
|
||||
if (text.startsWith("/") && text.length > 1) {
|
||||
onSearch(text.slice(1));
|
||||
}
|
||||
}
|
||||
|
||||
resizeTextarea();
|
||||
};
|
||||
|
||||
// set style for textarea
|
||||
const resizeTextarea = () => {
|
||||
const { minRows, maxRows } = props.autoSize;
|
||||
setTextareaStyle(calcTextareaHeight(inputRef.current, minRows, maxRows));
|
||||
};
|
||||
|
||||
// submit user input
|
||||
const onUserSubmit = () => {
|
||||
if (userInput.length <= 0) return;
|
||||
setIsLoading(true);
|
||||
chatStore.onUserInput(userInput).then(() => setIsLoading(false));
|
||||
setUserInput("");
|
||||
setPromptHints([]);
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
// stop response
|
||||
const onUserStop = (messageIndex: number) => {
|
||||
console.log(ControllerPool, sessionIndex, messageIndex);
|
||||
ControllerPool.stop(sessionIndex, messageIndex);
|
||||
};
|
||||
|
||||
// check if should send message
|
||||
const onInputKeyDown = (e: KeyboardEvent) => {
|
||||
if (shouldSubmit(e)) {
|
||||
onUserSubmit();
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
const onRightClick = (e: any, message: Message) => {
|
||||
// auto fill user input
|
||||
if (message.role === "user") {
|
||||
setUserInput(message.content);
|
||||
}
|
||||
|
||||
// copy to clipboard
|
||||
if (selectOrCopy(e.currentTarget, message.content)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
const onResend = (botIndex: number) => {
|
||||
// find last user input message and resend
|
||||
for (let i = botIndex; i >= 0; i -= 1) {
|
||||
if (messages[i].role === "user") {
|
||||
setIsLoading(true);
|
||||
chatStore
|
||||
.onUserInput(messages[i].content)
|
||||
.then(() => setIsLoading(false));
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// for auto-scroll
|
||||
const latestMessageRef = useRef<HTMLDivElement>(null);
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
// preview messages
|
||||
const messages = (session.messages as RenderMessage[])
|
||||
.concat(
|
||||
isLoading
|
||||
? [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "……",
|
||||
date: new Date().toLocaleString(),
|
||||
preview: true,
|
||||
},
|
||||
]
|
||||
: []
|
||||
)
|
||||
.concat(
|
||||
userInput.length > 0
|
||||
? [
|
||||
{
|
||||
role: "user",
|
||||
content: userInput,
|
||||
date: new Date().toLocaleString(),
|
||||
preview: true,
|
||||
},
|
||||
]
|
||||
: []
|
||||
);
|
||||
|
||||
// auto scroll
|
||||
useLayoutEffect(() => {
|
||||
setTimeout(() => {
|
||||
const dom = latestMessageRef.current;
|
||||
const inputDom = inputRef.current;
|
||||
|
||||
// only scroll when input overlaped message body
|
||||
let shouldScroll = true;
|
||||
if (dom && inputDom) {
|
||||
const domRect = dom.getBoundingClientRect();
|
||||
const inputRect = inputDom.getBoundingClientRect();
|
||||
shouldScroll = domRect.top > inputRect.top;
|
||||
}
|
||||
|
||||
if (dom && autoScroll && shouldScroll) {
|
||||
dom.scrollIntoView({
|
||||
block: "end",
|
||||
});
|
||||
}
|
||||
}, 500);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={styles.chat} key={session.id}>
|
||||
<div className={styles["window-header"]}>
|
||||
<div
|
||||
className={styles["window-header-title"]}
|
||||
onClick={props?.showSideBar}
|
||||
>
|
||||
<div
|
||||
className={`${styles["window-header-main-title"]} ${styles["chat-body-title"]}`}
|
||||
onClick={() => {
|
||||
const newTopic = prompt(Locale.Chat.Rename, session.topic);
|
||||
if (newTopic && newTopic !== session.topic) {
|
||||
chatStore.updateCurrentSession(
|
||||
(session) => (session.topic = newTopic!)
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{session.topic}
|
||||
</div>
|
||||
<div className={styles["window-header-sub-title"]}>
|
||||
{Locale.Chat.SubTitle(session.messages.length)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles["window-actions"]}>
|
||||
<div className={styles["window-action-button"] + " " + styles.mobile}>
|
||||
<IconButton
|
||||
icon={<MenuIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.ChatList}
|
||||
onClick={props?.showSideBar}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["window-action-button"]}>
|
||||
<IconButton
|
||||
icon={<BrainIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.CompressedHistory}
|
||||
onClick={() => {
|
||||
showMemoryPrompt(session);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["window-action-button"]}>
|
||||
<IconButton
|
||||
icon={<ExportIcon />}
|
||||
bordered
|
||||
title={Locale.Chat.Actions.Export}
|
||||
onClick={() => {
|
||||
exportMessages(session.messages, session.topic);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles["chat-body"]}>
|
||||
{messages.map((message, i) => {
|
||||
const isUser = message.role === "user";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={
|
||||
isUser ? styles["chat-message-user"] : styles["chat-message"]
|
||||
}
|
||||
>
|
||||
<div className={styles["chat-message-container"]}>
|
||||
<div className={styles["chat-message-avatar"]}>
|
||||
<Avatar role={message.role} />
|
||||
</div>
|
||||
{(message.preview || message.streaming) && (
|
||||
<div className={styles["chat-message-status"]}>
|
||||
{Locale.Chat.Typing}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles["chat-message-item"]}>
|
||||
{!isUser &&
|
||||
!(message.preview || message.content.length === 0) && (
|
||||
<div className={styles["chat-message-top-actions"]}>
|
||||
{message.streaming ? (
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => onUserStop(i)}
|
||||
>
|
||||
{Locale.Chat.Actions.Stop}
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => onResend(i)}
|
||||
>
|
||||
{Locale.Chat.Actions.Retry}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={styles["chat-message-top-action"]}
|
||||
onClick={() => copyToClipboard(message.content)}
|
||||
>
|
||||
{Locale.Chat.Actions.Copy}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(message.preview || message.content.length === 0) &&
|
||||
!isUser ? (
|
||||
<LoadingIcon />
|
||||
) : (
|
||||
<div
|
||||
className="markdown-body"
|
||||
style={{ fontSize: `${fontSize}px` }}
|
||||
onContextMenu={(e) => onRightClick(e, message)}
|
||||
onDoubleClickCapture={() => {
|
||||
if (!isMobileScreen()) return;
|
||||
setUserInput(message.content);
|
||||
}}
|
||||
>
|
||||
<Markdown content={message.content} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!isUser && !message.preview && (
|
||||
<div className={styles["chat-message-actions"]}>
|
||||
<div className={styles["chat-message-action-date"]}>
|
||||
{message.date.toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={latestMessageRef} style={{ opacity: 0, height: "1px" }}>
|
||||
-
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles["chat-input-panel"]}>
|
||||
<PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
|
||||
<div className={styles["chat-input-panel-inner"]}>
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
style={textareaStyle}
|
||||
className={styles["chat-input"]}
|
||||
placeholder={Locale.Chat.Input(submitKey)}
|
||||
onInput={(e) => onInput(e.currentTarget.value)}
|
||||
value={userInput}
|
||||
onKeyDown={(e) => onInputKeyDown(e as any)}
|
||||
onFocus={() => setAutoScroll(true)}
|
||||
onBlur={() => {
|
||||
setAutoScroll(false);
|
||||
setTimeout(() => setPromptHints([]), 500);
|
||||
}}
|
||||
autoFocus={!props?.sideBarShowing}
|
||||
/>
|
||||
<IconButton
|
||||
icon={<SendWhiteIcon />}
|
||||
text={Locale.Chat.Send}
|
||||
className={styles["chat-input-send"] + " no-dark"}
|
||||
onClick={onUserSubmit}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useSwitchTheme() {
|
||||
const config = useChatStore((state) => state.config);
|
||||
|
||||
@@ -537,72 +57,26 @@ function useSwitchTheme() {
|
||||
document.body.classList.add("light");
|
||||
}
|
||||
|
||||
const themeColor = getComputedStyle(document.body)
|
||||
.getPropertyValue("--theme-color")
|
||||
.trim();
|
||||
const metaDescription = document.querySelector('meta[name="theme-color"]');
|
||||
metaDescription?.setAttribute("content", themeColor);
|
||||
const metaDescriptionDark = document.querySelector(
|
||||
'meta[name="theme-color"][media]',
|
||||
);
|
||||
const metaDescriptionLight = document.querySelector(
|
||||
'meta[name="theme-color"]:not([media])',
|
||||
);
|
||||
|
||||
if (config.theme === "auto") {
|
||||
metaDescriptionDark?.setAttribute("content", "#151515");
|
||||
metaDescriptionLight?.setAttribute("content", "#fafafa");
|
||||
} else {
|
||||
const themeColor = getComputedStyle(document.body)
|
||||
.getPropertyValue("--theme-color")
|
||||
.trim();
|
||||
metaDescriptionDark?.setAttribute("content", themeColor);
|
||||
metaDescriptionLight?.setAttribute("content", themeColor);
|
||||
}
|
||||
}, [config.theme]);
|
||||
}
|
||||
|
||||
function exportMessages(messages: Message[], topic: string) {
|
||||
const mdText =
|
||||
`# ${topic}\n\n` +
|
||||
messages
|
||||
.map((m) => {
|
||||
return m.role === "user" ? `## ${m.content}` : m.content.trim();
|
||||
})
|
||||
.join("\n\n");
|
||||
const filename = `${topic}.md`;
|
||||
|
||||
showModal({
|
||||
title: Locale.Export.Title,
|
||||
children: (
|
||||
<div className="markdown-body">
|
||||
<pre className={styles["export-content"]}>{mdText}</pre>
|
||||
</div>
|
||||
),
|
||||
actions: [
|
||||
<IconButton
|
||||
key="copy"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Export.Copy}
|
||||
onClick={() => copyToClipboard(mdText)}
|
||||
/>,
|
||||
<IconButton
|
||||
key="download"
|
||||
icon={<DownloadIcon />}
|
||||
bordered
|
||||
text={Locale.Export.Download}
|
||||
onClick={() => downloadAs(mdText, filename)}
|
||||
/>,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function showMemoryPrompt(session: ChatSession) {
|
||||
showModal({
|
||||
title: `${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`,
|
||||
children: (
|
||||
<div className="markdown-body">
|
||||
<pre className={styles["export-content"]}>
|
||||
{session.memoryPrompt || Locale.Memory.EmptyContent}
|
||||
</pre>
|
||||
</div>
|
||||
),
|
||||
actions: [
|
||||
<IconButton
|
||||
key="copy"
|
||||
icon={<CopyIcon />}
|
||||
bordered
|
||||
text={Locale.Memory.Copy}
|
||||
onClick={() => copyToClipboard(session.memoryPrompt)}
|
||||
/>,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const useHasHydrated = () => {
|
||||
const [hasHydrated, setHasHydrated] = useState<boolean>(false);
|
||||
|
||||
@@ -613,13 +87,13 @@ const useHasHydrated = () => {
|
||||
return hasHydrated;
|
||||
};
|
||||
|
||||
export function Home() {
|
||||
function _Home() {
|
||||
const [createNewSession, currentIndex, removeSession] = useChatStore(
|
||||
(state) => [
|
||||
state.newSession,
|
||||
state.currentSessionIndex,
|
||||
state.removeSession,
|
||||
]
|
||||
],
|
||||
);
|
||||
const loading = !useHasHydrated();
|
||||
const [showSideBar, setShowSideBar] = useState(true);
|
||||
@@ -684,11 +158,12 @@ export function Home() {
|
||||
setOpenSettings(true);
|
||||
setShowSideBar(false);
|
||||
}}
|
||||
shadow
|
||||
/>
|
||||
</div>
|
||||
<div className={styles["sidebar-action"]}>
|
||||
<a href={REPO_URL} target="_blank">
|
||||
<IconButton icon={<GithubIcon />} />
|
||||
<IconButton icon={<GithubIcon />} shadow />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -700,6 +175,7 @@ export function Home() {
|
||||
createNewSession();
|
||||
setShowSideBar(false);
|
||||
}}
|
||||
shadow
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -725,3 +201,11 @@ export function Home() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Home() {
|
||||
return (
|
||||
<ErrorBoundary>
|
||||
<_Home></_Home>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
7
app/components/input-range.module.scss
Normal file
7
app/components/input-range.module.scss
Normal file
@@ -0,0 +1,7 @@
|
||||
.input-range {
|
||||
border: var(--border-in-light);
|
||||
border-radius: 10px;
|
||||
padding: 5px 15px 5px 10px;
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
}
|
37
app/components/input-range.tsx
Normal file
37
app/components/input-range.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import * as React from "react";
|
||||
import styles from "./input-range.module.scss";
|
||||
|
||||
interface InputRangeProps {
|
||||
onChange: React.ChangeEventHandler<HTMLInputElement>;
|
||||
title?: string;
|
||||
value: number | string;
|
||||
className?: string;
|
||||
min: string;
|
||||
max: string;
|
||||
step: string;
|
||||
}
|
||||
|
||||
export function InputRange({
|
||||
onChange,
|
||||
title,
|
||||
value,
|
||||
className,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
}: InputRangeProps) {
|
||||
return (
|
||||
<div className={styles["input-range"] + ` ${className ?? ""}`}>
|
||||
{title || value}
|
||||
<input
|
||||
type="range"
|
||||
title={title}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
onChange={onChange}
|
||||
></input>
|
||||
</div>
|
||||
);
|
||||
}
|
@@ -4,8 +4,8 @@ import RemarkMath from "remark-math";
|
||||
import RemarkBreaks from "remark-breaks";
|
||||
import RehypeKatex from "rehype-katex";
|
||||
import RemarkGfm from "remark-gfm";
|
||||
import RehypePrsim from "rehype-prism-plus";
|
||||
import { useRef } from "react";
|
||||
import RehypeHighlight from "rehype-highlight";
|
||||
import { useRef, useState, RefObject, useEffect } from "react";
|
||||
import { copyToClipboard } from "../utils";
|
||||
|
||||
export function PreCode(props: { children: any }) {
|
||||
@@ -27,14 +27,47 @@ export function PreCode(props: { children: any }) {
|
||||
);
|
||||
}
|
||||
|
||||
const useLazyLoad = (ref: RefObject<Element>): boolean => {
|
||||
const [isIntersecting, setIntersecting] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setIntersecting(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
if (ref.current) {
|
||||
observer.observe(ref.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [ref]);
|
||||
|
||||
return isIntersecting;
|
||||
};
|
||||
|
||||
export function Markdown(props: { content: string }) {
|
||||
return (
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
|
||||
rehypePlugins={[RehypeKatex, [RehypePrsim, { ignoreMissing: true }]]}
|
||||
rehypePlugins={[
|
||||
RehypeKatex,
|
||||
[
|
||||
RehypeHighlight,
|
||||
{
|
||||
detect: false,
|
||||
ignoreMissing: true,
|
||||
},
|
||||
],
|
||||
]}
|
||||
components={{
|
||||
pre: PreCode,
|
||||
}}
|
||||
linkTarget={"_blank"}
|
||||
>
|
||||
{props.content}
|
||||
</ReactMarkdown>
|
||||
|
@@ -18,3 +18,12 @@
|
||||
.avatar {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.password-input {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
|
||||
.password-eye {
|
||||
margin-right: 4px;
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useRef, useMemo } from "react";
|
||||
import { useState, useEffect, useMemo, HTMLProps } from "react";
|
||||
|
||||
import EmojiPicker, { Theme as EmojiTheme } from "emoji-picker-react";
|
||||
|
||||
@@ -8,6 +8,8 @@ import ResetIcon from "../icons/reload.svg";
|
||||
import CloseIcon from "../icons/close.svg";
|
||||
import ClearIcon from "../icons/clear.svg";
|
||||
import EditIcon from "../icons/edit.svg";
|
||||
import EyeIcon from "../icons/eye.svg";
|
||||
import EyeOffIcon from "../icons/eye-off.svg";
|
||||
|
||||
import { List, ListItem, Popover, showToast } from "./ui-lib";
|
||||
|
||||
@@ -19,15 +21,18 @@ import {
|
||||
ALL_MODELS,
|
||||
useUpdateStore,
|
||||
useAccessStore,
|
||||
ModalConfigValidator,
|
||||
} from "../store";
|
||||
import { Avatar, PromptHints } from "./home";
|
||||
import { Avatar } from "./chat";
|
||||
|
||||
import Locale, { AllLangs, changeLang, getLang } from "../locales";
|
||||
import { getCurrentVersion } from "../utils";
|
||||
import { getCurrentVersion, getEmojiUrl } from "../utils";
|
||||
import Link from "next/link";
|
||||
import { UPDATE_URL } from "../constant";
|
||||
import { SearchService, usePromptStore } from "../store/prompt";
|
||||
import { requestUsage } from "../requests";
|
||||
import { ErrorBoundary } from "./error";
|
||||
import { InputRange } from "./input-range";
|
||||
|
||||
function SettingItem(props: {
|
||||
title: string;
|
||||
@@ -47,16 +52,35 @@ function SettingItem(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordInput(props: HTMLProps<HTMLInputElement>) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
function changeVisibility() {
|
||||
setVisible(!visible);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles["password-input"]}>
|
||||
<IconButton
|
||||
icon={visible ? <EyeIcon /> : <EyeOffIcon />}
|
||||
onClick={changeVisibility}
|
||||
className={styles["password-eye"]}
|
||||
/>
|
||||
<input {...props} type={visible ? "text" : "password"} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Settings(props: { closeSettings: () => void }) {
|
||||
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
|
||||
const [config, updateConfig, resetConfig, clearAllData] = useChatStore(
|
||||
(state) => [
|
||||
const [config, updateConfig, resetConfig, clearAllData, clearSessions] =
|
||||
useChatStore((state) => [
|
||||
state.config,
|
||||
state.updateConfig,
|
||||
state.resetConfig,
|
||||
state.clearAllData,
|
||||
],
|
||||
);
|
||||
state.clearSessions,
|
||||
]);
|
||||
|
||||
const updateStore = useUpdateStore();
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false);
|
||||
@@ -72,32 +96,23 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
}
|
||||
|
||||
const [usage, setUsage] = useState<{
|
||||
granted?: number;
|
||||
used?: number;
|
||||
subscription?: number;
|
||||
}>();
|
||||
const [loadingUsage, setLoadingUsage] = useState(false);
|
||||
function checkUsage() {
|
||||
setLoadingUsage(true);
|
||||
requestUsage()
|
||||
.then((res) =>
|
||||
setUsage({
|
||||
granted: res?.total_granted,
|
||||
used: res?.total_used,
|
||||
}),
|
||||
)
|
||||
.then((res) => setUsage(res))
|
||||
.finally(() => {
|
||||
setLoadingUsage(false);
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
checkUpdate();
|
||||
checkUsage();
|
||||
}, []);
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
const enabledAccessControl = useMemo(
|
||||
() => accessStore.enabledAccessControl(),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -105,8 +120,16 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
const builtinCount = SearchService.count.builtin;
|
||||
const customCount = promptStore.prompts.size ?? 0;
|
||||
|
||||
const showUsage = !!accessStore.token || !!accessStore.accessCode;
|
||||
|
||||
useEffect(() => {
|
||||
checkUpdate();
|
||||
showUsage && checkUsage();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ErrorBoundary>
|
||||
<div className={styles["window-header"]}>
|
||||
<div className={styles["window-header-title"]}>
|
||||
<div className={styles["window-header-main-title"]}>
|
||||
@@ -120,7 +143,7 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
<div className={styles["window-action-button"]}>
|
||||
<IconButton
|
||||
icon={<ClearIcon />}
|
||||
onClick={clearAllData}
|
||||
onClick={clearSessions}
|
||||
bordered
|
||||
title={Locale.Settings.Actions.ClearAll}
|
||||
/>
|
||||
@@ -152,6 +175,7 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
<EmojiPicker
|
||||
lazyLoadEmojis
|
||||
theme={EmojiTheme.AUTO}
|
||||
getEmojiUrl={getEmojiUrl}
|
||||
onEmojiClick={(e) => {
|
||||
updateConfig((config) => (config.avatar = e.unified));
|
||||
setShowEmojiPicker(false);
|
||||
@@ -251,8 +275,7 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.FontSize.Title}
|
||||
subTitle={Locale.Settings.FontSize.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
<InputRange
|
||||
title={`${config.fontSize ?? 14}px`}
|
||||
value={config.fontSize}
|
||||
min="12"
|
||||
@@ -264,7 +287,7 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
(config.fontSize = Number.parseInt(e.currentTarget.value)),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
></InputRange>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem title={Locale.Settings.TightBorder}>
|
||||
@@ -278,6 +301,19 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
}
|
||||
></input>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem title={Locale.Settings.SendPreviewBubble}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={config.sendPreviewBubble}
|
||||
onChange={(e) =>
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.sendPreviewBubble = e.currentTarget.checked),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
</SettingItem>
|
||||
</List>
|
||||
<List>
|
||||
<SettingItem
|
||||
@@ -316,14 +352,14 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.AccessCode.Title}
|
||||
subTitle={Locale.Settings.AccessCode.SubTitle}
|
||||
>
|
||||
<input
|
||||
<PasswordInput
|
||||
value={accessStore.accessCode}
|
||||
type="text"
|
||||
placeholder={Locale.Settings.AccessCode.Placeholder}
|
||||
onChange={(e) => {
|
||||
accessStore.updateCode(e.currentTarget.value);
|
||||
}}
|
||||
></input>
|
||||
/>
|
||||
</SettingItem>
|
||||
) : (
|
||||
<></>
|
||||
@@ -333,28 +369,30 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.Token.Title}
|
||||
subTitle={Locale.Settings.Token.SubTitle}
|
||||
>
|
||||
<input
|
||||
<PasswordInput
|
||||
value={accessStore.token}
|
||||
type="text"
|
||||
placeholder={Locale.Settings.Token.Placeholder}
|
||||
onChange={(e) => {
|
||||
accessStore.updateToken(e.currentTarget.value);
|
||||
}}
|
||||
></input>
|
||||
/>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem
|
||||
title={Locale.Settings.Usage.Title}
|
||||
subTitle={
|
||||
loadingUsage
|
||||
? Locale.Settings.Usage.IsChecking
|
||||
: Locale.Settings.Usage.SubTitle(
|
||||
usage?.granted ?? "[?]",
|
||||
usage?.used ?? "[?]",
|
||||
)
|
||||
showUsage
|
||||
? loadingUsage
|
||||
? Locale.Settings.Usage.IsChecking
|
||||
: Locale.Settings.Usage.SubTitle(
|
||||
usage?.used ?? "[?]",
|
||||
usage?.subscription ?? "[?]",
|
||||
)
|
||||
: Locale.Settings.Usage.NoAccess
|
||||
}
|
||||
>
|
||||
{loadingUsage ? (
|
||||
{!showUsage || loadingUsage ? (
|
||||
<div />
|
||||
) : (
|
||||
<IconButton
|
||||
@@ -369,20 +407,19 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.HistoryCount.Title}
|
||||
subTitle={Locale.Settings.HistoryCount.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
<InputRange
|
||||
title={config.historyMessageCount.toString()}
|
||||
value={config.historyMessageCount}
|
||||
min="0"
|
||||
max="25"
|
||||
step="2"
|
||||
step="1"
|
||||
onChange={(e) =>
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.historyMessageCount = e.target.valueAsNumber),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
></InputRange>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem
|
||||
@@ -412,7 +449,9 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
onChange={(e) => {
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.modelConfig.model = e.currentTarget.value),
|
||||
(config.modelConfig.model = ModalConfigValidator.model(
|
||||
e.currentTarget.value,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -427,9 +466,8 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.Temperature.Title}
|
||||
subTitle={Locale.Settings.Temperature.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
value={config.modelConfig.temperature.toFixed(1)}
|
||||
<InputRange
|
||||
value={config.modelConfig.temperature?.toFixed(1)}
|
||||
min="0"
|
||||
max="2"
|
||||
step="0.1"
|
||||
@@ -437,10 +475,12 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.modelConfig.temperature =
|
||||
e.currentTarget.valueAsNumber),
|
||||
ModalConfigValidator.temperature(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
></input>
|
||||
></InputRange>
|
||||
</SettingItem>
|
||||
<SettingItem
|
||||
title={Locale.Settings.MaxTokens.Title}
|
||||
@@ -449,13 +489,15 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
<input
|
||||
type="number"
|
||||
min={100}
|
||||
max={4096}
|
||||
max={32000}
|
||||
value={config.modelConfig.max_tokens}
|
||||
onChange={(e) =>
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.modelConfig.max_tokens =
|
||||
e.currentTarget.valueAsNumber),
|
||||
ModalConfigValidator.max_tokens(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
)
|
||||
}
|
||||
></input>
|
||||
@@ -464,9 +506,8 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
title={Locale.Settings.PresencePenlty.Title}
|
||||
subTitle={Locale.Settings.PresencePenlty.SubTitle}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
value={config.modelConfig.presence_penalty.toFixed(1)}
|
||||
<InputRange
|
||||
value={config.modelConfig.presence_penalty?.toFixed(1)}
|
||||
min="-2"
|
||||
max="2"
|
||||
step="0.5"
|
||||
@@ -474,13 +515,15 @@ export function Settings(props: { closeSettings: () => void }) {
|
||||
updateConfig(
|
||||
(config) =>
|
||||
(config.modelConfig.presence_penalty =
|
||||
e.currentTarget.valueAsNumber),
|
||||
ModalConfigValidator.presence_penalty(
|
||||
e.currentTarget.valueAsNumber,
|
||||
)),
|
||||
);
|
||||
}}
|
||||
></input>
|
||||
></InputRange>
|
||||
</SettingItem>
|
||||
</List>
|
||||
</div>
|
||||
</>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
@@ -1,3 +1,5 @@
|
||||
@import "../styles/animation.scss";
|
||||
|
||||
.card {
|
||||
background-color: var(--white);
|
||||
border-radius: 10px;
|
||||
@@ -24,18 +26,6 @@
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
@keyframes slide-in {
|
||||
from {
|
||||
transform: translateY(10px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.list-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -138,6 +128,8 @@
|
||||
justify-content: center;
|
||||
|
||||
.toast-content {
|
||||
max-width: 80vw;
|
||||
word-break: break-all;
|
||||
font-size: 14px;
|
||||
background-color: var(--white);
|
||||
box-shadow: var(--card-shadow);
|
||||
@@ -149,6 +141,17 @@
|
||||
}
|
||||
}
|
||||
|
||||
.input {
|
||||
border: var(--border-in-light);
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
font-family: inherit;
|
||||
background-color: var(--white);
|
||||
color: var(--black);
|
||||
resize: none;
|
||||
min-width: 50px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 600px) {
|
||||
.modal-container {
|
||||
width: 90vw;
|
||||
@@ -157,4 +160,4 @@
|
||||
max-height: 50vh;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -2,6 +2,7 @@ import styles from "./ui-lib.module.scss";
|
||||
import LoadingIcon from "../icons/three-dots.svg";
|
||||
import CloseIcon from "../icons/close.svg";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import React from "react";
|
||||
|
||||
export function Popover(props: {
|
||||
children: JSX.Element;
|
||||
@@ -140,3 +141,17 @@ export function showToast(content: string, delay = 3000) {
|
||||
|
||||
root.render(<Toast content={content} />);
|
||||
}
|
||||
|
||||
export type InputProps = React.HTMLProps<HTMLTextAreaElement> & {
|
||||
autoHeight?: boolean;
|
||||
rows?: number;
|
||||
};
|
||||
|
||||
export function Input(props: InputProps) {
|
||||
return (
|
||||
<textarea
|
||||
{...props}
|
||||
className={`${styles["input"]} ${props.className}`}
|
||||
></textarea>
|
||||
);
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
.window-header {
|
||||
padding: 14px 20px;
|
||||
border-bottom: rgba(0, 0, 0, 0.1) 1px solid;
|
||||
position: relative;
|
||||
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -9,6 +10,7 @@
|
||||
|
||||
.window-header-title {
|
||||
max-width: calc(100% - 100px);
|
||||
overflow: hidden;
|
||||
|
||||
.window-header-main-title {
|
||||
font-size: 20px;
|
||||
@@ -32,4 +34,4 @@
|
||||
|
||||
.window-action-button {
|
||||
margin-left: 10px;
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
export const OWNER = "Yidadaa";
|
||||
export const REPO = "ChatGPT-Next-Web";
|
||||
export const REPO_URL = `https://github.com/${OWNER}/${REPO}`;
|
||||
export const UPDATE_URL = `${REPO_URL}#%E4%BF%9D%E6%8C%81%E6%9B%B4%E6%96%B0-keep-updated`;
|
||||
export const ISSUE_URL = `https://github.com/${OWNER}/${REPO}/issues`;
|
||||
export const UPDATE_URL = `${REPO_URL}#keep-updated`;
|
||||
export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/commits?per_page=1`;
|
||||
export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`;
|
||||
|
4
app/icons/eye-off.svg
Normal file
4
app/icons/eye-off.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M19.7071 5.70711C20.0976 5.31658 20.0976 4.68342 19.7071 4.29289C19.3166 3.90237 18.6834 3.90237 18.2929 4.29289L14.032 8.55382C13.4365 8.20193 12.7418 8 12 8C9.79086 8 8 9.79086 8 12C8 12.7418 8.20193 13.4365 8.55382 14.032L4.29289 18.2929C3.90237 18.6834 3.90237 19.3166 4.29289 19.7071C4.68342 20.0976 5.31658 20.0976 5.70711 19.7071L9.96803 15.4462C10.5635 15.7981 11.2582 16 12 16C14.2091 16 16 14.2091 16 12C16 11.2582 15.7981 10.5635 15.4462 9.96803L19.7071 5.70711ZM12.518 10.0677C12.3528 10.0236 12.1792 10 12 10C10.8954 10 10 10.8954 10 12C10 12.1792 10.0236 12.3528 10.0677 12.518L12.518 10.0677ZM11.482 13.9323L13.9323 11.482C13.9764 11.6472 14 11.8208 14 12C14 13.1046 13.1046 14 12 14C11.8208 14 11.6472 13.9764 11.482 13.9323ZM15.7651 4.8207C14.6287 4.32049 13.3675 4 12 4C9.14754 4 6.75717 5.39462 4.99812 6.90595C3.23268 8.42276 2.00757 10.1376 1.46387 10.9698C1.05306 11.5985 1.05306 12.4015 1.46387 13.0302C1.92276 13.7326 2.86706 15.0637 4.21194 16.3739L5.62626 14.9596C4.4555 13.8229 3.61144 12.6531 3.18002 12C3.6904 11.2274 4.77832 9.73158 6.30147 8.42294C7.87402 7.07185 9.81574 6 12 6C12.7719 6 13.5135 6.13385 14.2193 6.36658L15.7651 4.8207ZM12 18C11.2282 18 10.4866 17.8661 9.78083 17.6334L8.23496 19.1793C9.37136 19.6795 10.6326 20 12 20C14.8525 20 17.2429 18.6054 19.002 17.0941C20.7674 15.5772 21.9925 13.8624 22.5362 13.0302C22.947 12.4015 22.947 11.5985 22.5362 10.9698C22.0773 10.2674 21.133 8.93627 19.7881 7.62611L18.3738 9.04043C19.5446 10.1771 20.3887 11.3469 20.8201 12C20.3097 12.7726 19.2218 14.2684 17.6986 15.5771C16.1261 16.9282 14.1843 18 12 18Z" fill="#000000"/>
|
||||
</svg>
|
After Width: | Height: | Size: 1.8 KiB |
4
app/icons/eye.svg
Normal file
4
app/icons/eye.svg
Normal file
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||
<svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M6.30147 15.5771C4.77832 14.2684 3.6904 12.7726 3.18002 12C3.6904 11.2274 4.77832 9.73158 6.30147 8.42294C7.87402 7.07185 9.81574 6 12 6C14.1843 6 16.1261 7.07185 17.6986 8.42294C19.2218 9.73158 20.3097 11.2274 20.8201 12C20.3097 12.7726 19.2218 14.2684 17.6986 15.5771C16.1261 16.9282 14.1843 18 12 18C9.81574 18 7.87402 16.9282 6.30147 15.5771ZM12 4C9.14754 4 6.75717 5.39462 4.99812 6.90595C3.23268 8.42276 2.00757 10.1376 1.46387 10.9698C1.05306 11.5985 1.05306 12.4015 1.46387 13.0302C2.00757 13.8624 3.23268 15.5772 4.99812 17.0941C6.75717 18.6054 9.14754 20 12 20C14.8525 20 17.2429 18.6054 19.002 17.0941C20.7674 15.5772 21.9925 13.8624 22.5362 13.0302C22.947 12.4015 22.947 11.5985 22.5362 10.9698C21.9925 10.1376 20.7674 8.42276 19.002 6.90595C17.2429 5.39462 14.8525 4 12 4ZM10 12C10 10.8954 10.8955 10 12 10C13.1046 10 14 10.8954 14 12C14 13.1046 13.1046 14 12 14C10.8955 14 10 13.1046 10 12ZM12 8C9.7909 8 8.00004 9.79086 8.00004 12C8.00004 14.2091 9.7909 16 12 16C14.2092 16 16 14.2091 16 12C16 9.79086 14.2092 8 12 8Z" fill="#000000"/>
|
||||
</svg>
|
After Width: | Height: | Size: 1.3 KiB |
@@ -1,7 +1,7 @@
|
||||
/* eslint-disable @next/next/no-page-custom-font */
|
||||
import "./styles/globals.scss";
|
||||
import "./styles/markdown.scss";
|
||||
import "./styles/prism.scss";
|
||||
import "./styles/highlight.scss";
|
||||
import process from "child_process";
|
||||
import { ACCESS_CODES, IS_IN_DOCKER } from "./api/access";
|
||||
|
||||
@@ -21,7 +21,7 @@ export const metadata = {
|
||||
description: "Your personal ChatGPT Chat Bot.",
|
||||
appleWebApp: {
|
||||
title: "ChatGPT Next Web",
|
||||
statusBarStyle: "black-translucent",
|
||||
statusBarStyle: "default",
|
||||
},
|
||||
themeColor: "#fafafa",
|
||||
};
|
||||
@@ -53,6 +53,11 @@ export default function RootLayout({
|
||||
name="viewport"
|
||||
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
|
||||
/>
|
||||
<meta
|
||||
name="theme-color"
|
||||
content="#151515"
|
||||
media="(prefers-color-scheme: dark)"
|
||||
/>
|
||||
<Meta />
|
||||
<link rel="manifest" href="/site.webmanifest"></link>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"></link>
|
||||
|
@@ -3,7 +3,7 @@ import { SubmitKey } from "../store/app";
|
||||
const cn = {
|
||||
WIP: "该功能仍在开发中……",
|
||||
Error: {
|
||||
Unauthorized: "现在是未授权状态,请在设置页填写授权码。",
|
||||
Unauthorized: "现在是未授权状态,请在设置页输入访问密码。",
|
||||
},
|
||||
ChatItem: {
|
||||
ChatItemCount: (count: number) => `${count} 条对话`,
|
||||
@@ -33,11 +33,16 @@ const cn = {
|
||||
Title: "导出聊天记录为 Markdown",
|
||||
Copy: "全部复制",
|
||||
Download: "下载文件",
|
||||
MessageFromYou: "来自你的消息",
|
||||
MessageFromChatGPT: "来自 ChatGPT 的消息",
|
||||
},
|
||||
Memory: {
|
||||
Title: "上下文记忆 Prompt",
|
||||
Title: "历史记忆",
|
||||
EmptyContent: "尚未记忆",
|
||||
Copy: "全部复制",
|
||||
Send: "发送记忆",
|
||||
Copy: "复制记忆",
|
||||
Reset: "重置对话",
|
||||
ResetConfirm: "重置后将清空当前对话记录以及历史记忆,确认重置?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "新的聊天",
|
||||
@@ -58,6 +63,7 @@ const cn = {
|
||||
en: "English",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
},
|
||||
},
|
||||
Avatar: "头像",
|
||||
@@ -77,6 +83,7 @@ const cn = {
|
||||
SendKey: "发送键",
|
||||
Theme: "主题",
|
||||
TightBorder: "紧凑边框",
|
||||
SendPreviewBubble: "发送预览气泡",
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "禁用提示词自动补全",
|
||||
@@ -97,21 +104,22 @@ const cn = {
|
||||
},
|
||||
Token: {
|
||||
Title: "API Key",
|
||||
SubTitle: "使用自己的 Key 可绕过受控访问限制",
|
||||
SubTitle: "使用自己的 Key 可绕过密码访问限制",
|
||||
Placeholder: "OpenAI API Key",
|
||||
},
|
||||
Usage: {
|
||||
Title: "账户余额",
|
||||
SubTitle(granted: any, used: any) {
|
||||
return `总共 $${granted},已使用 $${used}`;
|
||||
Title: "余额查询",
|
||||
SubTitle(used: any, total: any) {
|
||||
return `本月已使用 $${used},订阅总额 $${total}`;
|
||||
},
|
||||
IsChecking: "正在检查…",
|
||||
Check: "重新检查",
|
||||
NoAccess: "输入 API Key 或访问密码查看余额",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "访问码",
|
||||
SubTitle: "现在是受控访问状态",
|
||||
Placeholder: "请输入访问码",
|
||||
Title: "访问密码",
|
||||
SubTitle: "现在是未授权访问状态",
|
||||
Placeholder: "请输入访问密码",
|
||||
},
|
||||
Model: "模型 (model)",
|
||||
Temperature: {
|
||||
@@ -137,7 +145,7 @@ const cn = {
|
||||
Topic:
|
||||
"使用四到五个字直接返回这句话的简要主题,不要解释、不要标点、不要语气词、不要多余文本,如果没有主题,请直接返回“闲聊”",
|
||||
Summarize:
|
||||
"简要总结一下你和用户的对话,用作后续的上下文提示 prompt,控制在 50 字以内",
|
||||
"简要总结一下你和用户的对话,用作后续的上下文提示 prompt,控制在 200 字以内",
|
||||
},
|
||||
ConfirmClearAll: "确认清除所有聊天、设置数据?",
|
||||
},
|
||||
@@ -145,6 +153,11 @@ const cn = {
|
||||
Success: "已写入剪切板",
|
||||
Failed: "复制失败,请赋予剪切板权限",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `已设置 ${x} 条前置上下文`,
|
||||
Edit: "前置上下文和历史记忆",
|
||||
Add: "新增一条",
|
||||
},
|
||||
};
|
||||
|
||||
export type LocaleType = typeof cn;
|
||||
|
@@ -35,11 +35,17 @@ const en: LocaleType = {
|
||||
Title: "All Messages",
|
||||
Copy: "Copy All",
|
||||
Download: "Download",
|
||||
MessageFromYou: "Message From You",
|
||||
MessageFromChatGPT: "Message From ChatGPT",
|
||||
},
|
||||
Memory: {
|
||||
Title: "Memory Prompt",
|
||||
EmptyContent: "Nothing yet.",
|
||||
Copy: "Copy All",
|
||||
Send: "Send Memory",
|
||||
Copy: "Copy Memory",
|
||||
Reset: "Reset Session",
|
||||
ResetConfirm:
|
||||
"Resetting will clear the current conversation history and historical memory. Are you sure you want to reset?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "New Chat",
|
||||
@@ -54,12 +60,13 @@ const en: LocaleType = {
|
||||
Close: "Close",
|
||||
},
|
||||
Lang: {
|
||||
Name: "Language",
|
||||
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
|
||||
Options: {
|
||||
cn: "简体中文",
|
||||
en: "English",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
},
|
||||
},
|
||||
Avatar: "Avatar",
|
||||
@@ -78,6 +85,7 @@ const en: LocaleType = {
|
||||
SendKey: "Send Key",
|
||||
Theme: "Theme",
|
||||
TightBorder: "Tight Border",
|
||||
SendPreviewBubble: "Send Preview Bubble",
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "Disable auto-completion",
|
||||
@@ -104,11 +112,12 @@ const en: LocaleType = {
|
||||
},
|
||||
Usage: {
|
||||
Title: "Account Balance",
|
||||
SubTitle(granted: any, used: any) {
|
||||
return `Total $${granted}, Used $${used}`;
|
||||
SubTitle(used: any, total: any) {
|
||||
return `Used this month $${used}, subscription $${total}`;
|
||||
},
|
||||
IsChecking: "Checking...",
|
||||
Check: "Check Again",
|
||||
NoAccess: "Enter API Key to check balance",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "Access Code",
|
||||
@@ -141,7 +150,7 @@ const en: LocaleType = {
|
||||
Topic:
|
||||
"Please generate a four to five word title summarizing our conversation without any lead-in, punctuation, quotation marks, periods, symbols, or additional text. Remove enclosing quotation marks.",
|
||||
Summarize:
|
||||
"Summarize our discussion briefly in 50 characters or less to use as a prompt for future context.",
|
||||
"Summarize our discussion briefly in 200 words or less to use as a prompt for future context.",
|
||||
},
|
||||
ConfirmClearAll: "Confirm to clear all chat and setting data?",
|
||||
},
|
||||
@@ -149,6 +158,11 @@ const en: LocaleType = {
|
||||
Success: "Copied to clipboard",
|
||||
Failed: "Copy failed, please grant permission to access clipboard",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `With ${x} contextual prompts`,
|
||||
Edit: "Contextual and Memory Prompts",
|
||||
Add: "Add One",
|
||||
},
|
||||
};
|
||||
|
||||
export default en;
|
||||
|
@@ -35,11 +35,17 @@ const es: LocaleType = {
|
||||
Title: "Todos los mensajes",
|
||||
Copy: "Copiar todo",
|
||||
Download: "Descargar",
|
||||
MessageFromYou: "Mensaje de ti",
|
||||
MessageFromChatGPT: "Mensaje de ChatGPT",
|
||||
},
|
||||
Memory: {
|
||||
Title: "Historial de memoria",
|
||||
EmptyContent: "Aún no hay nada.",
|
||||
Copy: "Copiar todo",
|
||||
Send: "Send Memory",
|
||||
Reset: "Reset Session",
|
||||
ResetConfirm:
|
||||
"Resetting will clear the current conversation history and historical memory. Are you sure you want to reset?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "Nuevo chat",
|
||||
@@ -60,6 +66,7 @@ const es: LocaleType = {
|
||||
en: "Inglés",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
},
|
||||
},
|
||||
Avatar: "Avatar",
|
||||
@@ -78,6 +85,7 @@ const es: LocaleType = {
|
||||
SendKey: "Tecla de envío",
|
||||
Theme: "Tema",
|
||||
TightBorder: "Borde ajustado",
|
||||
SendPreviewBubble: "Enviar burbuja de vista previa",
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "Desactivar autocompletado",
|
||||
@@ -104,11 +112,12 @@ const es: LocaleType = {
|
||||
},
|
||||
Usage: {
|
||||
Title: "Saldo de la cuenta",
|
||||
SubTitle(granted: any, used: any) {
|
||||
return `Total $${granted}, Usado $${used}`;
|
||||
SubTitle(used: any, total: any) {
|
||||
return `Usado $${used}, subscription $${total}`;
|
||||
},
|
||||
IsChecking: "Comprobando...",
|
||||
Check: "Comprobar de nuevo",
|
||||
NoAccess: "Introduzca la clave API para comprobar el saldo",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "Código de acceso",
|
||||
@@ -141,14 +150,21 @@ const es: LocaleType = {
|
||||
Topic:
|
||||
"Por favor, genera un título de cuatro a cinco palabras que resuma nuestra conversación sin ningún inicio, puntuación, comillas, puntos, símbolos o texto adicional. Elimina las comillas que lo envuelven.",
|
||||
Summarize:
|
||||
"Resuma nuestra discusión brevemente en 50 caracteres o menos para usarlo como un recordatorio para futuros contextos.",
|
||||
"Resuma nuestra discusión brevemente en 200 caracteres o menos para usarlo como un recordatorio para futuros contextos.",
|
||||
},
|
||||
ConfirmClearAll: "¿Confirmar para borrar todos los datos de chat y configuración?",
|
||||
ConfirmClearAll:
|
||||
"¿Confirmar para borrar todos los datos de chat y configuración?",
|
||||
},
|
||||
Copy: {
|
||||
Success: "Copiado al portapapeles",
|
||||
Failed: "La copia falló, por favor concede permiso para acceder al portapapeles",
|
||||
Failed:
|
||||
"La copia falló, por favor concede permiso para acceder al portapapeles",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `With ${x} contextual prompts`,
|
||||
Edit: "Contextual and Memory Prompts",
|
||||
Add: "Add One",
|
||||
},
|
||||
};
|
||||
|
||||
export default es;
|
||||
export default es;
|
||||
|
@@ -2,10 +2,11 @@ import CN from "./cn";
|
||||
import EN from "./en";
|
||||
import TW from "./tw";
|
||||
import ES from "./es";
|
||||
import IT from "./it";
|
||||
|
||||
export type { LocaleType } from "./cn";
|
||||
|
||||
export const AllLangs = ["en", "cn", "tw", "es"] as const;
|
||||
export const AllLangs = ["en", "cn", "tw", "es", "it"] as const;
|
||||
type Lang = (typeof AllLangs)[number];
|
||||
|
||||
const LANG_KEY = "lang";
|
||||
@@ -47,6 +48,8 @@ export function getLang(): Lang {
|
||||
return "tw";
|
||||
} else if (lang.includes("es")) {
|
||||
return "es";
|
||||
} else if (lang.includes("it")) {
|
||||
return "it";
|
||||
} else {
|
||||
return "en";
|
||||
}
|
||||
@@ -57,4 +60,4 @@ export function changeLang(lang: Lang) {
|
||||
location.reload();
|
||||
}
|
||||
|
||||
export default { en: EN, cn: CN, tw: TW, es: ES }[getLang()];
|
||||
export default { en: EN, cn: CN, tw: TW, es: ES, it: IT }[getLang()];
|
||||
|
171
app/locales/it.ts
Normal file
171
app/locales/it.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { SubmitKey } from "../store/app";
|
||||
import type { LocaleType } from "./index";
|
||||
|
||||
const it: LocaleType = {
|
||||
WIP: "Work in progress...",
|
||||
Error: {
|
||||
Unauthorized:
|
||||
"Accesso non autorizzato, inserire il codice di accesso nella pagina delle impostazioni.",
|
||||
},
|
||||
ChatItem: {
|
||||
ChatItemCount: (count: number) => `${count} messaggi`,
|
||||
},
|
||||
Chat: {
|
||||
SubTitle: (count: number) => `${count} messaggi con ChatGPT`,
|
||||
Actions: {
|
||||
ChatList: "Vai alla Chat List",
|
||||
CompressedHistory: "Prompt di memoria della cronologia compressa",
|
||||
Export: "Esportazione di tutti i messaggi come Markdown",
|
||||
Copy: "Copia",
|
||||
Stop: "Stop",
|
||||
Retry: "Riprova",
|
||||
},
|
||||
Rename: "Rinomina Chat",
|
||||
Typing: "Typing…",
|
||||
Input: (submitKey: string) => {
|
||||
var inputHints = `Scrivi qualcosa e premi ${submitKey} per inviare`;
|
||||
if (submitKey === String(SubmitKey.Enter)) {
|
||||
inputHints += ", premi Shift + Enter per andare a capo";
|
||||
}
|
||||
return inputHints;
|
||||
},
|
||||
Send: "Invia",
|
||||
},
|
||||
Export: {
|
||||
Title: "Tutti i messaggi",
|
||||
Copy: "Copia tutto",
|
||||
Download: "Scarica",
|
||||
MessageFromYou: "Messaggio da te",
|
||||
MessageFromChatGPT: "Messaggio da ChatGPT",
|
||||
},
|
||||
Memory: {
|
||||
Title: "Prompt di memoria",
|
||||
EmptyContent: "Vuoto.",
|
||||
Copy: "Copia tutto",
|
||||
Send: "Send Memory",
|
||||
Reset: "Reset Session",
|
||||
ResetConfirm:
|
||||
"Resetting will clear the current conversation history and historical memory. Are you sure you want to reset?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "Nuova Chat",
|
||||
DeleteChat: "Confermare la cancellazione della conversazione selezionata?",
|
||||
},
|
||||
Settings: {
|
||||
Title: "Impostazioni",
|
||||
SubTitle: "Tutte le impostazioni",
|
||||
Actions: {
|
||||
ClearAll: "Cancella tutti i dati",
|
||||
ResetAll: "Resetta tutte le impostazioni",
|
||||
Close: "Chiudi",
|
||||
},
|
||||
Lang: {
|
||||
Name: "Lingue",
|
||||
Options: {
|
||||
cn: "简体中文",
|
||||
en: "English",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
},
|
||||
},
|
||||
Avatar: "Avatar",
|
||||
FontSize: {
|
||||
Title: "Dimensione carattere",
|
||||
SubTitle: "Regolare la dimensione dei caratteri del contenuto della chat",
|
||||
},
|
||||
Update: {
|
||||
Version: (x: string) => `Versione: ${x}`,
|
||||
IsLatest: "Ultima versione",
|
||||
CheckUpdate: "Controlla aggiornamenti",
|
||||
IsChecking: "Sto controllando gli aggiornamenti...",
|
||||
FoundUpdate: (x: string) => `Trovata nuova versione: ${x}`,
|
||||
GoToUpdate: "Aggiorna",
|
||||
},
|
||||
SendKey: "Tasto invia",
|
||||
Theme: "tema",
|
||||
TightBorder: "Bordi stretti",
|
||||
SendPreviewBubble: "Invia l'anteprima della bolla",
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "Disabilita l'auto completamento",
|
||||
SubTitle: "Input / per attivare il completamento automatico",
|
||||
},
|
||||
List: "Elenco dei suggerimenti",
|
||||
ListCount: (builtin: number, custom: number) =>
|
||||
`${builtin} built-in, ${custom} user-defined`,
|
||||
Edit: "Modifica",
|
||||
},
|
||||
HistoryCount: {
|
||||
Title: "Conteggio dei messaggi allegati",
|
||||
SubTitle: "Numero di messaggi inviati allegati per richiesta",
|
||||
},
|
||||
CompressThreshold: {
|
||||
Title: "Soglia di compressione della cronologia",
|
||||
SubTitle:
|
||||
"Comprimerà se la lunghezza dei messaggi non compressi supera il valore",
|
||||
},
|
||||
Token: {
|
||||
Title: "Chiave API",
|
||||
SubTitle:
|
||||
"Utilizzare la chiave per ignorare il limite del codice di accesso",
|
||||
Placeholder: "OpenAI API Key",
|
||||
},
|
||||
Usage: {
|
||||
Title: "Bilancio Account",
|
||||
SubTitle(used: any, total: any) {
|
||||
return `Usato in questo mese $${used}, subscription $${total}`;
|
||||
},
|
||||
IsChecking: "Controllando...",
|
||||
Check: "Controlla ancora",
|
||||
NoAccess: "Inserire la chiave API per controllare il saldo",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "Codice d'accesso",
|
||||
SubTitle: "Controllo d'accesso abilitato",
|
||||
Placeholder: "Inserisci il codice d'accesso",
|
||||
},
|
||||
Model: "Modello GPT",
|
||||
Temperature: {
|
||||
Title: "Temperature",
|
||||
SubTitle: "Un valore maggiore rende l'output più casuale",
|
||||
},
|
||||
MaxTokens: {
|
||||
Title: "Token massimi",
|
||||
SubTitle: "Lunghezza massima dei token in ingresso e dei token generati",
|
||||
},
|
||||
PresencePenlty: {
|
||||
Title: "Penalità di presenza",
|
||||
SubTitle:
|
||||
"Un valore maggiore aumenta la probabilità di parlare di nuovi argomenti",
|
||||
},
|
||||
},
|
||||
Store: {
|
||||
DefaultTopic: "Nuova conversazione",
|
||||
BotHello: "Ciao, come posso aiutarti oggi?",
|
||||
Error: "Qualcosa è andato storto, riprova più tardi.",
|
||||
Prompt: {
|
||||
History: (content: string) =>
|
||||
"Questo è un riassunto della cronologia delle chat tra l'IA e l'utente:" +
|
||||
content,
|
||||
Topic:
|
||||
"Si prega di generare un titolo di quattro o cinque parole che riassuma la nostra conversazione senza alcuna traccia, punteggiatura, virgolette, punti, simboli o testo aggiuntivo. Rimuovere le virgolette",
|
||||
Summarize:
|
||||
"Riassumi brevemente la nostra discussione in 200 caratteri o meno per usarla come spunto per una futura conversazione.",
|
||||
},
|
||||
ConfirmClearAll:
|
||||
"Confermi la cancellazione di tutti i dati della chat e delle impostazioni?",
|
||||
},
|
||||
Copy: {
|
||||
Success: "Copiato sugli appunti",
|
||||
Failed:
|
||||
"Copia fallita, concedere l'autorizzazione all'accesso agli appunti",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `Con ${x} prompts contestuali`,
|
||||
Edit: "Prompt contestuali e di memoria",
|
||||
Add: "Aggiungi altro",
|
||||
},
|
||||
};
|
||||
|
||||
export default it;
|
@@ -4,7 +4,7 @@ import type { LocaleType } from "./index";
|
||||
const tw: LocaleType = {
|
||||
WIP: "該功能仍在開發中……",
|
||||
Error: {
|
||||
Unauthorized: "目前您的狀態是未授權,請前往設定頁面填寫授權碼。",
|
||||
Unauthorized: "目前您的狀態是未授權,請前往設定頁面輸入授權碼。",
|
||||
},
|
||||
ChatItem: {
|
||||
ChatItemCount: (count: number) => `${count} 條對話`,
|
||||
@@ -34,11 +34,16 @@ const tw: LocaleType = {
|
||||
Title: "匯出聊天記錄為 Markdown",
|
||||
Copy: "複製全部",
|
||||
Download: "下載檔案",
|
||||
MessageFromYou: "來自你的訊息",
|
||||
MessageFromChatGPT: "來自 ChatGPT 的訊息",
|
||||
},
|
||||
Memory: {
|
||||
Title: "上下文記憶 Prompt",
|
||||
EmptyContent: "尚未記憶",
|
||||
Copy: "複製全部",
|
||||
Send: "發送記憶",
|
||||
Reset: "重置對話",
|
||||
ResetConfirm: "重置後將清空當前對話記錄以及歷史記憶,確認重置?",
|
||||
},
|
||||
Home: {
|
||||
NewChat: "新的對話",
|
||||
@@ -59,6 +64,7 @@ const tw: LocaleType = {
|
||||
en: "English",
|
||||
tw: "繁體中文",
|
||||
es: "Español",
|
||||
it: "Italiano",
|
||||
},
|
||||
},
|
||||
Avatar: "大頭貼",
|
||||
@@ -77,6 +83,7 @@ const tw: LocaleType = {
|
||||
SendKey: "發送鍵",
|
||||
Theme: "主題",
|
||||
TightBorder: "緊湊邊框",
|
||||
SendPreviewBubble: "發送預覽氣泡",
|
||||
Prompt: {
|
||||
Disable: {
|
||||
Title: "停用提示詞自動補全",
|
||||
@@ -97,21 +104,22 @@ const tw: LocaleType = {
|
||||
},
|
||||
Token: {
|
||||
Title: "API Key",
|
||||
SubTitle: "使用自己的 Key 可規避受控訪問限制",
|
||||
SubTitle: "使用自己的 Key 可規避授權訪問限制",
|
||||
Placeholder: "OpenAI API Key",
|
||||
},
|
||||
Usage: {
|
||||
Title: "帳戶餘額",
|
||||
SubTitle(granted: any, used: any) {
|
||||
return `總共 $${granted},已使用 $${used}`;
|
||||
SubTitle(used: any, total: any) {
|
||||
return `本月已使用 $${used},订阅总额 $${total}`;
|
||||
},
|
||||
IsChecking: "正在檢查…",
|
||||
Check: "重新檢查",
|
||||
NoAccess: "輸入API Key查看餘額",
|
||||
},
|
||||
AccessCode: {
|
||||
Title: "訪問碼",
|
||||
SubTitle: "現在是受控訪問狀態",
|
||||
Placeholder: "請輸入訪問碼",
|
||||
Title: "授權碼",
|
||||
SubTitle: "現在是未授權訪問狀態",
|
||||
Placeholder: "請輸入授權碼",
|
||||
},
|
||||
Model: "模型 (model)",
|
||||
Temperature: {
|
||||
@@ -136,7 +144,7 @@ const tw: LocaleType = {
|
||||
"這是 AI 與用戶的歷史聊天總結,作為前情提要:" + content,
|
||||
Topic: "直接返回這句話的簡要主題,無須解釋,若無主題,請直接返回「閒聊」",
|
||||
Summarize:
|
||||
"簡要總結一下你和用戶的對話,作為後續的上下文提示 prompt,且字數控制在 50 字以內",
|
||||
"簡要總結一下你和用戶的對話,作為後續的上下文提示 prompt,且字數控制在 200 字以內",
|
||||
},
|
||||
ConfirmClearAll: "確認清除所有對話、設定數據?",
|
||||
},
|
||||
@@ -144,6 +152,11 @@ const tw: LocaleType = {
|
||||
Success: "已複製到剪貼簿中",
|
||||
Failed: "複製失敗,請賦予剪貼簿權限",
|
||||
},
|
||||
Context: {
|
||||
Toast: (x: any) => `已設置 ${x} 條前置上下文`,
|
||||
Edit: "前置上下文和歷史記憶",
|
||||
Add: "新增壹條",
|
||||
},
|
||||
};
|
||||
|
||||
export default tw;
|
||||
|
@@ -1,4 +1,5 @@
|
||||
import { Analytics } from "@vercel/analytics/react";
|
||||
|
||||
import { Home } from "./components/home";
|
||||
|
||||
export default function App() {
|
||||
|
27
app/polyfill.ts
Normal file
27
app/polyfill.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
declare global {
|
||||
interface Array<T> {
|
||||
at(index: number): T | undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.prototype.at) {
|
||||
Array.prototype.at = function (index: number) {
|
||||
// Get the length of the array
|
||||
const length = this.length;
|
||||
|
||||
// Convert negative index to a positive index
|
||||
if (index < 0) {
|
||||
index = length + index;
|
||||
}
|
||||
|
||||
// Return undefined if the index is out of range
|
||||
if (index < 0 || index >= length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Use Array.prototype.slice method to get value at the specified index
|
||||
return Array.prototype.slice.call(this, index, index + 1)[0];
|
||||
};
|
||||
}
|
||||
|
||||
export {};
|
@@ -1,6 +1,6 @@
|
||||
import type { ChatRequest, ChatReponse } from "./api/openai/typing";
|
||||
import { filterConfig, Message, ModelConfig, useAccessStore } from "./store";
|
||||
import Locale from "./locales";
|
||||
import { Message, ModelConfig, useAccessStore, useChatStore } from "./store";
|
||||
import { showToast } from "./components/ui-lib";
|
||||
|
||||
const TIME_OUT_MS = 30000;
|
||||
|
||||
@@ -9,7 +9,7 @@ const makeRequestParam = (
|
||||
options?: {
|
||||
filterBot?: boolean;
|
||||
stream?: boolean;
|
||||
}
|
||||
},
|
||||
): ChatRequest => {
|
||||
let sendMessages = messages.map((v) => ({
|
||||
role: v.role,
|
||||
@@ -20,10 +20,12 @@ const makeRequestParam = (
|
||||
sendMessages = sendMessages.filter((m) => m.role !== "assistant");
|
||||
}
|
||||
|
||||
const modelConfig = useChatStore.getState().config.modelConfig;
|
||||
|
||||
return {
|
||||
model: "gpt-3.5-turbo",
|
||||
messages: sendMessages,
|
||||
stream: options?.stream,
|
||||
...modelConfig,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -44,7 +46,7 @@ function getHeaders() {
|
||||
|
||||
export function requestOpenaiClient(path: string) {
|
||||
return (body: any, method = "POST") =>
|
||||
fetch("/api/openai", {
|
||||
fetch("/api/openai?_vercel_no_cache=1", {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -69,20 +71,49 @@ export async function requestChat(messages: Message[]) {
|
||||
}
|
||||
|
||||
export async function requestUsage() {
|
||||
const res = await requestOpenaiClient(
|
||||
"dashboard/billing/credit_grants?_vercel_no_cache=1"
|
||||
)(null, "GET");
|
||||
const formatDate = (d: Date) =>
|
||||
`${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
|
||||
.getDate()
|
||||
.toString()
|
||||
.padStart(2, "0")}`;
|
||||
const ONE_DAY = 2 * 24 * 60 * 60 * 1000;
|
||||
const now = new Date(Date.now() + ONE_DAY);
|
||||
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||
const startDate = formatDate(startOfMonth);
|
||||
const endDate = formatDate(now);
|
||||
|
||||
try {
|
||||
const response = (await res.json()) as {
|
||||
total_available: number;
|
||||
total_granted: number;
|
||||
total_used: number;
|
||||
const [used, subs] = await Promise.all([
|
||||
requestOpenaiClient(
|
||||
`dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`,
|
||||
)(null, "GET"),
|
||||
requestOpenaiClient("dashboard/billing/subscription")(null, "GET"),
|
||||
]);
|
||||
|
||||
const response = (await used.json()) as {
|
||||
total_usage?: number;
|
||||
error?: {
|
||||
type: string;
|
||||
message: string;
|
||||
};
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("[Request usage] ", error, res.body);
|
||||
};
|
||||
|
||||
const total = (await subs.json()) as {
|
||||
hard_limit_usd?: number;
|
||||
};
|
||||
|
||||
if (response.error && response.error.type) {
|
||||
showToast(response.error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.total_usage) {
|
||||
response.total_usage = Math.round(response.total_usage) / 100;
|
||||
}
|
||||
|
||||
return {
|
||||
used: response.total_usage,
|
||||
subscription: total.hard_limit_usd,
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestChatStream(
|
||||
@@ -91,20 +122,15 @@ export async function requestChatStream(
|
||||
filterBot?: boolean;
|
||||
modelConfig?: ModelConfig;
|
||||
onMessage: (message: string, done: boolean) => void;
|
||||
onError: (error: Error) => void;
|
||||
onError: (error: Error, statusCode?: number) => void;
|
||||
onController?: (controller: AbortController) => void;
|
||||
}
|
||||
},
|
||||
) {
|
||||
const req = makeRequestParam(messages, {
|
||||
stream: true,
|
||||
filterBot: options?.filterBot,
|
||||
});
|
||||
|
||||
// valid and assign model config
|
||||
if (options?.modelConfig) {
|
||||
Object.assign(req, filterConfig(options.modelConfig));
|
||||
}
|
||||
|
||||
console.log("[Request] ", req);
|
||||
|
||||
const controller = new AbortController();
|
||||
@@ -155,11 +181,10 @@ export async function requestChatStream(
|
||||
finish();
|
||||
} else if (res.status === 401) {
|
||||
console.error("Anauthorized");
|
||||
responseText = Locale.Error.Unauthorized;
|
||||
finish();
|
||||
options?.onError(new Error("Anauthorized"), res.status);
|
||||
} else {
|
||||
console.error("Stream Error", res.body);
|
||||
options?.onError(new Error("Stream Error"));
|
||||
options?.onError(new Error("Stream Error"), res.status);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("NetWork Error", err);
|
||||
@@ -187,23 +212,22 @@ export const ControllerPool = {
|
||||
|
||||
addController(
|
||||
sessionIndex: number,
|
||||
messageIndex: number,
|
||||
controller: AbortController
|
||||
messageId: number,
|
||||
controller: AbortController,
|
||||
) {
|
||||
const key = this.key(sessionIndex, messageIndex);
|
||||
const key = this.key(sessionIndex, messageId);
|
||||
this.controllers[key] = controller;
|
||||
return key;
|
||||
},
|
||||
|
||||
stop(sessionIndex: number, messageIndex: number) {
|
||||
const key = this.key(sessionIndex, messageIndex);
|
||||
stop(sessionIndex: number, messageId: number) {
|
||||
const key = this.key(sessionIndex, messageId);
|
||||
const controller = this.controllers[key];
|
||||
console.log(controller);
|
||||
controller?.abort();
|
||||
},
|
||||
|
||||
remove(sessionIndex: number, messageIndex: number) {
|
||||
const key = this.key(sessionIndex, messageIndex);
|
||||
remove(sessionIndex: number, messageId: number) {
|
||||
const key = this.key(sessionIndex, messageId);
|
||||
delete this.controllers[key];
|
||||
},
|
||||
|
||||
|
211
app/store/app.ts
211
app/store/app.ts
@@ -14,8 +14,20 @@ import Locale from "../locales";
|
||||
export type Message = ChatCompletionResponseMessage & {
|
||||
date: string;
|
||||
streaming?: boolean;
|
||||
isError?: boolean;
|
||||
id?: number;
|
||||
};
|
||||
|
||||
export function createMessage(override: Partial<Message>): Message {
|
||||
return {
|
||||
id: Date.now(),
|
||||
date: new Date().toLocaleString(),
|
||||
role: "user",
|
||||
content: "",
|
||||
...override,
|
||||
};
|
||||
}
|
||||
|
||||
export enum SubmitKey {
|
||||
Enter = "Enter",
|
||||
CtrlEnter = "Ctrl + Enter",
|
||||
@@ -39,6 +51,7 @@ export interface ChatConfig {
|
||||
fontSize: number;
|
||||
theme: Theme;
|
||||
tightBorder: boolean;
|
||||
sendPreviewBubble: boolean;
|
||||
|
||||
disablePromptHint: boolean;
|
||||
|
||||
@@ -52,6 +65,8 @@ export interface ChatConfig {
|
||||
|
||||
export type ModelConfig = ChatConfig["modelConfig"];
|
||||
|
||||
export const ROLES: Message["role"][] = ["system", "user", "assistant"];
|
||||
|
||||
const ENABLE_GPT4 = true;
|
||||
|
||||
export const ALL_MODELS = [
|
||||
@@ -81,43 +96,39 @@ export const ALL_MODELS = [
|
||||
},
|
||||
];
|
||||
|
||||
export function isValidModel(name: string) {
|
||||
return ALL_MODELS.some((m) => m.name === name && m.available);
|
||||
export function limitNumber(
|
||||
x: number,
|
||||
min: number,
|
||||
max: number,
|
||||
defaultValue: number,
|
||||
) {
|
||||
if (typeof x !== "number" || isNaN(x)) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return Math.min(max, Math.max(min, x));
|
||||
}
|
||||
|
||||
export function isValidNumber(x: number, min: number, max: number) {
|
||||
return typeof x === "number" && x <= max && x >= min;
|
||||
export function limitModel(name: string) {
|
||||
return ALL_MODELS.some((m) => m.name === name && m.available)
|
||||
? name
|
||||
: ALL_MODELS[4].name;
|
||||
}
|
||||
|
||||
export function filterConfig(oldConfig: ModelConfig): Partial<ModelConfig> {
|
||||
const config = Object.assign({}, oldConfig);
|
||||
|
||||
const validator: {
|
||||
[k in keyof ModelConfig]: (x: ModelConfig[keyof ModelConfig]) => boolean;
|
||||
} = {
|
||||
model(x) {
|
||||
return isValidModel(x as string);
|
||||
},
|
||||
max_tokens(x) {
|
||||
return isValidNumber(x as number, 100, 4000);
|
||||
},
|
||||
presence_penalty(x) {
|
||||
return isValidNumber(x as number, -2, 2);
|
||||
},
|
||||
temperature(x) {
|
||||
return isValidNumber(x as number, 0, 2);
|
||||
},
|
||||
};
|
||||
|
||||
Object.keys(validator).forEach((k) => {
|
||||
const key = k as keyof ModelConfig;
|
||||
if (!validator[key](config[key])) {
|
||||
delete config[key];
|
||||
}
|
||||
});
|
||||
|
||||
return config;
|
||||
}
|
||||
export const ModalConfigValidator = {
|
||||
model(x: string) {
|
||||
return limitModel(x);
|
||||
},
|
||||
max_tokens(x: number) {
|
||||
return limitNumber(x, 0, 32000, 2000);
|
||||
},
|
||||
presence_penalty(x: number) {
|
||||
return limitNumber(x, -2, 2, 0);
|
||||
},
|
||||
temperature(x: number) {
|
||||
return limitNumber(x, 0, 2, 1);
|
||||
},
|
||||
};
|
||||
|
||||
const DEFAULT_CONFIG: ChatConfig = {
|
||||
historyMessageCount: 4,
|
||||
@@ -128,6 +139,7 @@ const DEFAULT_CONFIG: ChatConfig = {
|
||||
fontSize: 14,
|
||||
theme: Theme.Auto as Theme,
|
||||
tightBorder: false,
|
||||
sendPreviewBubble: true,
|
||||
|
||||
disablePromptHint: false,
|
||||
|
||||
@@ -148,7 +160,9 @@ export interface ChatStat {
|
||||
export interface ChatSession {
|
||||
id: number;
|
||||
topic: string;
|
||||
sendMemory: boolean;
|
||||
memoryPrompt: string;
|
||||
context: Message[];
|
||||
messages: Message[];
|
||||
stat: ChatStat;
|
||||
lastUpdate: string;
|
||||
@@ -156,6 +170,10 @@ export interface ChatSession {
|
||||
}
|
||||
|
||||
const DEFAULT_TOPIC = Locale.Store.DefaultTopic;
|
||||
export const BOT_HELLO: Message = createMessage({
|
||||
role: "assistant",
|
||||
content: Locale.Store.BotHello,
|
||||
});
|
||||
|
||||
function createEmptySession(): ChatSession {
|
||||
const createDate = new Date().toLocaleString();
|
||||
@@ -163,14 +181,10 @@ function createEmptySession(): ChatSession {
|
||||
return {
|
||||
id: Date.now(),
|
||||
topic: DEFAULT_TOPIC,
|
||||
sendMemory: true,
|
||||
memoryPrompt: "",
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: Locale.Store.BotHello,
|
||||
date: createDate,
|
||||
},
|
||||
],
|
||||
context: [],
|
||||
messages: [],
|
||||
stat: {
|
||||
tokenCount: 0,
|
||||
wordCount: 0,
|
||||
@@ -185,7 +199,9 @@ interface ChatStore {
|
||||
config: ChatConfig;
|
||||
sessions: ChatSession[];
|
||||
currentSessionIndex: number;
|
||||
clearSessions: () => void;
|
||||
removeSession: (index: number) => void;
|
||||
moveSession: (from: number, to: number) => void;
|
||||
selectSession: (index: number) => void;
|
||||
newSession: () => void;
|
||||
currentSession: () => ChatSession;
|
||||
@@ -199,6 +215,7 @@ interface ChatStore {
|
||||
messageIndex: number,
|
||||
updater: (message?: Message) => void,
|
||||
) => void;
|
||||
resetSession: () => void;
|
||||
getMessagesWithMemory: () => Message[];
|
||||
getMemoryPrompt: () => Message;
|
||||
|
||||
@@ -223,6 +240,13 @@ export const useChatStore = create<ChatStore>()(
|
||||
...DEFAULT_CONFIG,
|
||||
},
|
||||
|
||||
clearSessions() {
|
||||
set(() => ({
|
||||
sessions: [createEmptySession()],
|
||||
currentSessionIndex: 0,
|
||||
}));
|
||||
},
|
||||
|
||||
resetConfig() {
|
||||
set(() => ({ config: { ...DEFAULT_CONFIG } }));
|
||||
},
|
||||
@@ -268,6 +292,31 @@ export const useChatStore = create<ChatStore>()(
|
||||
});
|
||||
},
|
||||
|
||||
moveSession(from: number, to: number) {
|
||||
set((state) => {
|
||||
const { sessions, currentSessionIndex: oldIndex } = state;
|
||||
|
||||
// move the session
|
||||
const newSessions = [...sessions];
|
||||
const session = newSessions[from];
|
||||
newSessions.splice(from, 1);
|
||||
newSessions.splice(to, 0, session);
|
||||
|
||||
// modify current session id
|
||||
let newIndex = oldIndex === from ? to : oldIndex;
|
||||
if (oldIndex > from && oldIndex <= to) {
|
||||
newIndex -= 1;
|
||||
} else if (oldIndex < from && oldIndex >= to) {
|
||||
newIndex += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
currentSessionIndex: newIndex,
|
||||
sessions: newSessions,
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
newSession() {
|
||||
set((state) => ({
|
||||
currentSessionIndex: 0,
|
||||
@@ -298,18 +347,15 @@ export const useChatStore = create<ChatStore>()(
|
||||
},
|
||||
|
||||
async onUserInput(content) {
|
||||
const userMessage: Message = {
|
||||
const userMessage: Message = createMessage({
|
||||
role: "user",
|
||||
content,
|
||||
date: new Date().toLocaleString(),
|
||||
};
|
||||
});
|
||||
|
||||
const botMessage: Message = {
|
||||
content: "",
|
||||
const botMessage: Message = createMessage({
|
||||
role: "assistant",
|
||||
date: new Date().toLocaleString(),
|
||||
streaming: true,
|
||||
};
|
||||
});
|
||||
|
||||
// get recent messages
|
||||
const recentMessages = get().getMessagesWithMemory();
|
||||
@@ -332,23 +378,32 @@ export const useChatStore = create<ChatStore>()(
|
||||
botMessage.streaming = false;
|
||||
botMessage.content = content;
|
||||
get().onNewMessage(botMessage);
|
||||
ControllerPool.remove(sessionIndex, messageIndex);
|
||||
ControllerPool.remove(
|
||||
sessionIndex,
|
||||
botMessage.id ?? messageIndex,
|
||||
);
|
||||
} else {
|
||||
botMessage.content = content;
|
||||
set(() => ({}));
|
||||
}
|
||||
},
|
||||
onError(error) {
|
||||
botMessage.content += "\n\n" + Locale.Store.Error;
|
||||
onError(error, statusCode) {
|
||||
if (statusCode === 401) {
|
||||
botMessage.content = Locale.Error.Unauthorized;
|
||||
} else {
|
||||
botMessage.content += "\n\n" + Locale.Store.Error;
|
||||
}
|
||||
botMessage.streaming = false;
|
||||
userMessage.isError = true;
|
||||
botMessage.isError = true;
|
||||
set(() => ({}));
|
||||
ControllerPool.remove(sessionIndex, messageIndex);
|
||||
ControllerPool.remove(sessionIndex, botMessage.id ?? messageIndex);
|
||||
},
|
||||
onController(controller) {
|
||||
// collect controller for stop/retry
|
||||
ControllerPool.addController(
|
||||
sessionIndex,
|
||||
messageIndex,
|
||||
botMessage.id ?? messageIndex,
|
||||
controller,
|
||||
);
|
||||
},
|
||||
@@ -370,17 +425,24 @@ export const useChatStore = create<ChatStore>()(
|
||||
getMessagesWithMemory() {
|
||||
const session = get().currentSession();
|
||||
const config = get().config;
|
||||
const n = session.messages.length;
|
||||
const recentMessages = session.messages.slice(
|
||||
n - config.historyMessageCount,
|
||||
);
|
||||
const messages = session.messages.filter((msg) => !msg.isError);
|
||||
const n = messages.length;
|
||||
|
||||
const memoryPrompt = get().getMemoryPrompt();
|
||||
const context = session.context.slice();
|
||||
|
||||
if (session.memoryPrompt) {
|
||||
recentMessages.unshift(memoryPrompt);
|
||||
if (
|
||||
session.sendMemory &&
|
||||
session.memoryPrompt &&
|
||||
session.memoryPrompt.length > 0
|
||||
) {
|
||||
const memoryPrompt = get().getMemoryPrompt();
|
||||
context.push(memoryPrompt);
|
||||
}
|
||||
|
||||
const recentMessages = context.concat(
|
||||
messages.slice(Math.max(0, n - config.historyMessageCount)),
|
||||
);
|
||||
|
||||
return recentMessages;
|
||||
},
|
||||
|
||||
@@ -396,6 +458,13 @@ export const useChatStore = create<ChatStore>()(
|
||||
set(() => ({ sessions }));
|
||||
},
|
||||
|
||||
resetSession() {
|
||||
get().updateCurrentSession((session) => {
|
||||
session.messages = [];
|
||||
session.memoryPrompt = "";
|
||||
});
|
||||
},
|
||||
|
||||
summarizeSession() {
|
||||
const session = get().currentSession();
|
||||
|
||||
@@ -408,7 +477,8 @@ export const useChatStore = create<ChatStore>()(
|
||||
requestWithPrompt(session.messages, Locale.Store.Prompt.Topic).then(
|
||||
(res) => {
|
||||
get().updateCurrentSession(
|
||||
(session) => (session.topic = trimTopic(res)),
|
||||
(session) =>
|
||||
(session.topic = res ? trimTopic(res) : DEFAULT_TOPIC),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -418,11 +488,13 @@ export const useChatStore = create<ChatStore>()(
|
||||
let toBeSummarizedMsgs = session.messages.slice(
|
||||
session.lastSummarizeIndex,
|
||||
);
|
||||
|
||||
const historyMsgLength = countMessages(toBeSummarizedMsgs);
|
||||
|
||||
if (historyMsgLength > 4000) {
|
||||
if (historyMsgLength > get().config?.modelConfig?.max_tokens ?? 4000) {
|
||||
const n = toBeSummarizedMsgs.length;
|
||||
toBeSummarizedMsgs = toBeSummarizedMsgs.slice(
|
||||
-config.historyMessageCount,
|
||||
Math.max(0, n - config.historyMessageCount),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -485,7 +557,20 @@ export const useChatStore = create<ChatStore>()(
|
||||
}),
|
||||
{
|
||||
name: LOCAL_KEY,
|
||||
version: 1,
|
||||
version: 1.2,
|
||||
migrate(persistedState, version) {
|
||||
const state = persistedState as ChatStore;
|
||||
|
||||
if (version === 1) {
|
||||
state.sessions.forEach((s) => (s.context = []));
|
||||
}
|
||||
|
||||
if (version < 1.2) {
|
||||
state.sessions.forEach((s) => (s.sendMemory = true));
|
||||
}
|
||||
|
||||
return state;
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
@@ -99,19 +99,19 @@ export const usePromptStore = create<PromptStore>()(
|
||||
({
|
||||
title,
|
||||
content,
|
||||
} as Prompt)
|
||||
} as Prompt),
|
||||
);
|
||||
})
|
||||
.concat([...(state?.prompts?.values() ?? [])]);
|
||||
|
||||
const allPromptsForSearch = builtinPrompts.reduce(
|
||||
(pre, cur) => pre.concat(cur),
|
||||
[]
|
||||
[],
|
||||
);
|
||||
SearchService.count.builtin = res.en.length + res.cn.length;
|
||||
SearchService.init(allPromptsForSearch);
|
||||
});
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
),
|
||||
);
|
||||
|
23
app/styles/animation.scss
Normal file
23
app/styles/animation.scss
Normal file
@@ -0,0 +1,23 @@
|
||||
@keyframes slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slide-in-from-top {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-20px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0px);
|
||||
}
|
||||
}
|
@@ -117,7 +117,7 @@ body {
|
||||
|
||||
select {
|
||||
border: var(--border-in-light);
|
||||
padding: 8px 10px;
|
||||
padding: 10px;
|
||||
border-radius: 10px;
|
||||
appearance: none;
|
||||
cursor: pointer;
|
||||
@@ -126,6 +126,10 @@ select {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
label {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
input {
|
||||
text-align: center;
|
||||
}
|
||||
@@ -155,19 +159,11 @@ input[type="checkbox"]:checked::after {
|
||||
|
||||
input[type="range"] {
|
||||
appearance: none;
|
||||
border: var(--border-in-light);
|
||||
border-radius: 10px;
|
||||
padding: 5px 15px 5px 10px;
|
||||
background-color: var(--white);
|
||||
color: var(--black);
|
||||
|
||||
&::before {
|
||||
content: attr(value);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
@mixin thumb() {
|
||||
appearance: none;
|
||||
height: 8px;
|
||||
width: 20px;
|
||||
@@ -176,19 +172,45 @@ input[type="range"]::-webkit-slider-thumb {
|
||||
cursor: pointer;
|
||||
transition: all ease 0.3s;
|
||||
margin-left: 5px;
|
||||
border: none;
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb:hover {
|
||||
input[type="range"]::-webkit-slider-thumb {
|
||||
@include thumb();
|
||||
}
|
||||
|
||||
input[type="range"]::-moz-range-thumb {
|
||||
@include thumb();
|
||||
}
|
||||
|
||||
input[type="range"]::-ms-thumb {
|
||||
@include thumb();
|
||||
}
|
||||
|
||||
@mixin thumbHover() {
|
||||
transform: scaleY(1.2);
|
||||
width: 24px;
|
||||
}
|
||||
|
||||
input[type="range"]::-webkit-slider-thumb:hover {
|
||||
@include thumbHover();
|
||||
}
|
||||
|
||||
input[type="range"]::-moz-range-thumb:hover {
|
||||
@include thumbHover();
|
||||
}
|
||||
|
||||
input[type="range"]::-ms-thumb:hover {
|
||||
@include thumbHover();
|
||||
}
|
||||
|
||||
input[type="number"],
|
||||
input[type="text"] {
|
||||
input[type="text"],
|
||||
input[type="password"] {
|
||||
appearance: none;
|
||||
border-radius: 10px;
|
||||
border: var(--border-in-light);
|
||||
height: 32px;
|
||||
min-height: 36px;
|
||||
box-sizing: border-box;
|
||||
background: var(--white);
|
||||
color: var(--black);
|
||||
@@ -235,6 +257,7 @@ pre {
|
||||
.copy-code-button {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 1em;
|
||||
cursor: pointer;
|
||||
padding: 0px 5px;
|
||||
background-color: var(--black);
|
||||
@@ -255,3 +278,30 @@ pre {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.clickable {
|
||||
cursor: pointer;
|
||||
|
||||
div:not(.no-dark) > svg {
|
||||
filter: invert(0.5);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
}
|
||||
|
||||
.error {
|
||||
width: 80%;
|
||||
border-radius: 20px;
|
||||
border: var(--border-in-light);
|
||||
box-shadow: var(--card-shadow);
|
||||
padding: 20px;
|
||||
overflow: auto;
|
||||
background-color: var(--white);
|
||||
color: var(--black);
|
||||
|
||||
pre {
|
||||
overflow: auto;
|
||||
}
|
||||
}
|
||||
|
115
app/styles/highlight.scss
Normal file
115
app/styles/highlight.scss
Normal file
@@ -0,0 +1,115 @@
|
||||
.markdown-body {
|
||||
pre {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
pre,
|
||||
code {
|
||||
font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
|
||||
}
|
||||
|
||||
pre code {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
code {
|
||||
padding: 3px 5px;
|
||||
}
|
||||
|
||||
.hljs,
|
||||
pre {
|
||||
background: #1a1b26;
|
||||
color: #cbd2ea;
|
||||
}
|
||||
|
||||
/*!
|
||||
Theme: Tokyo-night-Dark
|
||||
origin: https://github.com/enkia/tokyo-night-vscode-theme
|
||||
Description: Original highlight.js style
|
||||
Author: (c) Henri Vandersleyen <hvandersleyen@gmail.com>
|
||||
License: see project LICENSE
|
||||
Touched: 2022
|
||||
*/
|
||||
.hljs-comment,
|
||||
.hljs-meta {
|
||||
color: #565f89;
|
||||
}
|
||||
|
||||
.hljs-deletion,
|
||||
.hljs-doctag,
|
||||
.hljs-regexp,
|
||||
.hljs-selector-attr,
|
||||
.hljs-selector-class,
|
||||
.hljs-selector-id,
|
||||
.hljs-selector-pseudo,
|
||||
.hljs-tag,
|
||||
.hljs-template-tag,
|
||||
.hljs-variable.language_ {
|
||||
color: #f7768e;
|
||||
}
|
||||
|
||||
.hljs-link,
|
||||
.hljs-literal,
|
||||
.hljs-number,
|
||||
.hljs-params,
|
||||
.hljs-template-variable,
|
||||
.hljs-type,
|
||||
.hljs-variable {
|
||||
color: #ff9e64;
|
||||
}
|
||||
|
||||
.hljs-attribute,
|
||||
.hljs-built_in {
|
||||
color: #e0af68;
|
||||
}
|
||||
|
||||
.hljs-keyword,
|
||||
.hljs-property,
|
||||
.hljs-subst,
|
||||
.hljs-title,
|
||||
.hljs-title.class_,
|
||||
.hljs-title.class_.inherited__,
|
||||
.hljs-title.function_ {
|
||||
color: #7dcfff;
|
||||
}
|
||||
|
||||
.hljs-selector-tag {
|
||||
color: #73daca;
|
||||
}
|
||||
|
||||
.hljs-addition,
|
||||
.hljs-bullet,
|
||||
.hljs-quote,
|
||||
.hljs-string,
|
||||
.hljs-symbol {
|
||||
color: #9ece6a;
|
||||
}
|
||||
|
||||
.hljs-code,
|
||||
.hljs-formula,
|
||||
.hljs-section {
|
||||
color: #7aa2f7;
|
||||
}
|
||||
|
||||
.hljs-attr,
|
||||
.hljs-char.escape_,
|
||||
.hljs-keyword,
|
||||
.hljs-name,
|
||||
.hljs-operator {
|
||||
color: #bb9af7;
|
||||
}
|
||||
|
||||
.hljs-punctuation {
|
||||
color: #c0caf5;
|
||||
}
|
||||
|
||||
.hljs-emphasis {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.hljs-strong {
|
||||
font-weight: 700;
|
||||
}
|
||||
}
|
@@ -1,122 +0,0 @@
|
||||
.markdown-body {
|
||||
pre {
|
||||
background: #282a36;
|
||||
color: #f8f8f2;
|
||||
}
|
||||
|
||||
code[class*="language-"],
|
||||
pre[class*="language-"] {
|
||||
color: #f8f8f2;
|
||||
background: none;
|
||||
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
|
||||
font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
|
||||
text-align: left;
|
||||
white-space: pre;
|
||||
word-spacing: normal;
|
||||
word-break: normal;
|
||||
word-wrap: normal;
|
||||
line-height: 1.5;
|
||||
-moz-tab-size: 4;
|
||||
-o-tab-size: 4;
|
||||
tab-size: 4;
|
||||
-webkit-hyphens: none;
|
||||
-moz-hyphens: none;
|
||||
-ms-hyphens: none;
|
||||
hyphens: none;
|
||||
}
|
||||
|
||||
/* Code blocks */
|
||||
pre[class*="language-"] {
|
||||
padding: 1em;
|
||||
margin: 0.5em 0;
|
||||
overflow: auto;
|
||||
border-radius: 0.3em;
|
||||
}
|
||||
|
||||
:not(pre) > code[class*="language-"],
|
||||
pre[class*="language-"] {
|
||||
background: #282a36;
|
||||
}
|
||||
|
||||
/* Inline code */
|
||||
:not(pre) > code[class*="language-"] {
|
||||
padding: 0.1em;
|
||||
border-radius: 0.3em;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.token.comment,
|
||||
.token.prolog,
|
||||
.token.doctype,
|
||||
.token.cdata {
|
||||
color: #6272a4;
|
||||
}
|
||||
|
||||
.token.punctuation {
|
||||
color: #f8f8f2;
|
||||
}
|
||||
|
||||
.namespace {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.token.property,
|
||||
.token.tag,
|
||||
.token.constant,
|
||||
.token.symbol,
|
||||
.token.deleted {
|
||||
color: #ff79c6;
|
||||
}
|
||||
|
||||
.token.boolean,
|
||||
.token.number {
|
||||
color: #bd93f9;
|
||||
}
|
||||
|
||||
.token.selector,
|
||||
.token.attr-name,
|
||||
.token.string,
|
||||
.token.char,
|
||||
.token.builtin,
|
||||
.token.inserted {
|
||||
color: #50fa7b;
|
||||
}
|
||||
|
||||
.token.operator,
|
||||
.token.entity,
|
||||
.token.url,
|
||||
.language-css .token.string,
|
||||
.style .token.string,
|
||||
.token.variable {
|
||||
color: #f8f8f2;
|
||||
}
|
||||
|
||||
.token.atrule,
|
||||
.token.attr-value,
|
||||
.token.function,
|
||||
.token.class-name {
|
||||
color: #f1fa8c;
|
||||
}
|
||||
|
||||
.token.keyword {
|
||||
color: #8be9fd;
|
||||
}
|
||||
|
||||
.token.regex,
|
||||
.token.important {
|
||||
color: #ffb86c;
|
||||
}
|
||||
|
||||
.token.important,
|
||||
.token.bold {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.token.italic {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.token.entity {
|
||||
cursor: help;
|
||||
}
|
||||
}
|
41
app/utils.ts
41
app/utils.ts
@@ -1,27 +1,30 @@
|
||||
import { EmojiStyle } from "emoji-picker-react";
|
||||
import { showToast } from "./components/ui-lib";
|
||||
import Locale from "./locales";
|
||||
|
||||
export function trimTopic(topic: string) {
|
||||
const s = topic.split("");
|
||||
let lastChar = s.at(-1); // 获取 s 的最后一个字符
|
||||
let pattern = /[,。!?、,.!?]/; // 定义匹配中文和英文标点符号的正则表达式
|
||||
while (lastChar && pattern.test(lastChar!)) {
|
||||
s.pop();
|
||||
lastChar = s.at(-1);
|
||||
}
|
||||
|
||||
return s.join("");
|
||||
return topic.replace(/[,。!?”“"、,.!?]*$/, "");
|
||||
}
|
||||
|
||||
export function copyToClipboard(text: string) {
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then((res) => {
|
||||
showToast(Locale.Copy.Success);
|
||||
})
|
||||
.catch((err) => {
|
||||
showToast(Locale.Copy.Failed);
|
||||
export async function copyToClipboard(text: string) {
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(text).catch((err) => {
|
||||
console.error("Failed to copy: ", err);
|
||||
});
|
||||
} else {
|
||||
const textArea = document.createElement("textarea");
|
||||
textArea.value = text;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.focus();
|
||||
textArea.select();
|
||||
try {
|
||||
document.execCommand("copy");
|
||||
console.log("Text copied to clipboard");
|
||||
} catch (err) {
|
||||
console.error("Failed to copy: ", err);
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadAs(text: string, filename: string) {
|
||||
@@ -85,3 +88,7 @@ export function getCurrentVersion() {
|
||||
|
||||
return currentId;
|
||||
}
|
||||
|
||||
export function getEmojiUrl(unified: string, style: EmojiStyle) {
|
||||
return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
|
||||
}
|
||||
|
Reference in New Issue
Block a user