Compare commits

..

28 Commits

Author SHA1 Message Date
Yifei Zhang
3c6f2962cc Merge pull request #617 from Yidadaa/bugfix-0408
fix: auto grow textarea
2023-04-08 03:13:14 +08:00
Yidadaa
45c8de42b9 fix: #528 wont send max_tokens 2023-04-08 03:03:07 +08:00
Yidadaa
637cda5b4c fix: #613 show all prompts when input / 2023-04-08 02:53:35 +08:00
Yidadaa
13035ecb0d fix: auto grow textarea 2023-04-08 02:36:02 +08:00
Yifei Zhang
d6b2cf8bcb Merge pull request #318 from leedom92/textarea-height-optimize
feat: textarea with adaptive height
2023-04-08 01:01:52 +08:00
Yifei Zhang
9afed21efd Merge pull request #595 from yorunning/fix
fix: hide toast when confirmation box is cancelled
2023-04-08 00:59:09 +08:00
Yorun
71d9fbc367 fix: hide toast on cancel session deletion on mobile 2023-04-07 14:51:08 +08:00
Yifei Zhang
f83859113e Update README.md 2023-04-07 13:58:56 +08:00
leedom
00d45e7cc4 fix: solve navigator undefined && merge from main 2023-04-07 13:47:34 +08:00
leedom
406ed8a02a Merge branch 'main' into textarea-height-optimize 2023-04-07 13:33:37 +08:00
Yifei Zhang
e793b0c49d Merge pull request #587 from zhongmeizhi/main
feat: 添加对热键的支持 Escape to close settings, Up Arrow to get last input
2023-04-07 13:09:09 +08:00
leedom
de740ec57f feat: add calcTextareaHeight.ts 2023-04-07 12:42:47 +08:00
leedom
e5b4cb28fe fix: useEffect hooks 2023-04-07 12:39:27 +08:00
leedom
cb210d82e1 update: resizeTextarea 2023-04-07 12:33:09 +08:00
Mokou
58b956f7cc feat: Hot keys: Escape to close settings, Up Arrow to get last input 2023-04-07 12:26:22 +08:00
leedom
620b98fe6a Merge branch 'main' into textarea-height-optimize 2023-04-07 12:20:53 +08:00
leedom
3656c8458f feat: textarea with adaptive height 2023-04-07 12:17:37 +08:00
leedom
a8a8becf96 merge 2023-04-07 07:29:17 +08:00
leedom
b8a605f07d merge 2023-04-07 07:18:53 +08:00
leedom
3825b3c2c2 Merge branch 'textarea-height-optimize' of github.com:leedom92/ChatGPT-Next-Web into textarea-height-optimize 2023-04-02 11:16:30 +08:00
Leedom
4369b26e22 Update calcTextareaHeight.js 2023-04-02 09:47:55 +08:00
leedom
6f7c2916ef Merge remote-tracking branch 'upstream/main' into textarea-height-optimize 2023-04-02 03:20:06 +08:00
Leedom
b419e7d918 Update home.tsx 2023-04-02 02:56:45 +08:00
Leedom
ad8e09d188 Update home.tsx 2023-04-02 02:54:46 +08:00
leedom
bce020fc8e feat: add calcTextareaHeight.js from element-ui 2023-04-02 02:42:00 +08:00
leedom
a811637176 refactor: use the method of element-ui 2023-04-02 02:40:00 +08:00
Leedom
9ba59351c5 Update home.tsx 2023-04-01 17:48:05 +08:00
leedom
2a79d35667 feat: add optimize textarea height when inputing 2023-04-01 17:34:38 +08:00
13 changed files with 163 additions and 41 deletions

View File

@@ -7,7 +7,7 @@ One-Click to deploy well-designed ChatGPT web UI on Vercel.
一键免费部署你的私人 ChatGPT 网页应用。 一键免费部署你的私人 ChatGPT 网页应用。
[演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [Join Discord](https://discord.gg/zrhvHCr79N) / [QQ 群](https://user-images.githubusercontent.com/16968934/228190818-7dd00845-e9b9-4363-97e5-44c507ac76da.jpeg) / [打赏开发者](https://user-images.githubusercontent.com/16968934/227772541-5bcd52d8-61b7-488c-a203-0330d8006e2b.jpg) [演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [Join Discord](https://discord.gg/zrhvHCr79N) / [QQ 群](https://user-images.githubusercontent.com/16968934/228190818-7dd00845-e9b9-4363-97e5-44c507ac76da.jpeg) / [打赏开发者](https://user-images.githubusercontent.com/16968934/227772541-5bcd52d8-61b7-488c-a203-0330d8006e2b.jpg) / [Buy Me a Coffee](https://www.buymeacoffee.com/yidadaa)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web) [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web)
@@ -169,6 +169,8 @@ bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/s
![More](./docs/images/more.png) ![More](./docs/images/more.png)
## Donation
[Buy Me a Coffee](https://www.buymeacoffee.com/yidadaa)
## Special Thanks ## Special Thanks
### Sponsor ### Sponsor
@@ -177,6 +179,11 @@ bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/s
[@ClarenceDan](https://github.com/ClarenceDan) [@ClarenceDan](https://github.com/ClarenceDan)
[@zhangjia](https://github.com/zhangjia) [@zhangjia](https://github.com/zhangjia)
[@hoochanlon](https://github.com/hoochanlon) [@hoochanlon](https://github.com/hoochanlon)
[@relativequantum](https://github.com/relativequantum)
[@desenmeng](https://github.com/desenmeng)
[@webees](https://github.com/webees)
[@chazzhou](https://github.com/chazzhou)
[@hauy](https://github.com/hauy)
### Contributor ### Contributor

View File

@@ -17,7 +17,7 @@ async function makeRequest(req: NextRequest) {
}, },
{ {
status: 500, status: 500,
} },
); );
} }
} }

View File

@@ -1,4 +1,4 @@
import { useDebouncedCallback } from "use-debounce"; import { useDebounce, useDebouncedCallback } from "use-debounce";
import { memo, useState, useRef, useEffect, useLayoutEffect } from "react"; import { memo, useState, useRef, useEffect, useLayoutEffect } from "react";
import SendWhiteIcon from "../icons/send-white.svg"; import SendWhiteIcon from "../icons/send-white.svg";
@@ -27,6 +27,7 @@ import {
getEmojiUrl, getEmojiUrl,
isMobileScreen, isMobileScreen,
selectOrCopy, selectOrCopy,
autoGrowTextArea,
} from "../utils"; } from "../utils";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
@@ -39,7 +40,7 @@ import { IconButton } from "./button";
import styles from "./home.module.scss"; import styles from "./home.module.scss";
import chatStyle from "./chat.module.scss"; import chatStyle from "./chat.module.scss";
import { Input, Modal, showModal, showToast } from "./ui-lib"; import { Input, Modal, showModal } from "./ui-lib";
const Markdown = dynamic( const Markdown = dynamic(
async () => memo((await import("./markdown")).Markdown), async () => memo((await import("./markdown")).Markdown),
@@ -343,6 +344,7 @@ export function Chat(props: {
const inputRef = useRef<HTMLTextAreaElement>(null); const inputRef = useRef<HTMLTextAreaElement>(null);
const [userInput, setUserInput] = useState(""); const [userInput, setUserInput] = useState("");
const [beforeInput, setBeforeInput] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const { submitKey, shouldSubmit } = useSubmitHandler(); const { submitKey, shouldSubmit } = useSubmitHandler();
const { scrollRef, setAutoScroll } = useScrollToBottom(); const { scrollRef, setAutoScroll } = useScrollToBottom();
@@ -380,6 +382,27 @@ export function Chat(props: {
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum; dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
}; };
// auto grow input
const [inputRows, setInputRows] = useState(2);
const measure = useDebouncedCallback(
() => {
const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
const inputRows = Math.min(
5,
Math.max(2 + Number(!isMobileScreen()), rows),
);
setInputRows(inputRows);
},
100,
{
leading: true,
trailing: true,
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(measure, [userInput]);
// only search prompts when user input is short // only search prompts when user input is short
const SEARCH_TEXT_LIMIT = 30; const SEARCH_TEXT_LIMIT = 30;
const onInput = (text: string) => { const onInput = (text: string) => {
@@ -394,9 +417,6 @@ export function Chat(props: {
// check if need to trigger auto completion // check if need to trigger auto completion
if (text.startsWith("/")) { if (text.startsWith("/")) {
let searchText = text.slice(1); let searchText = text.slice(1);
if (searchText.length === 0) {
searchText = " ";
}
onSearch(searchText); onSearch(searchText);
} }
} }
@@ -407,6 +427,7 @@ export function Chat(props: {
if (userInput.length <= 0) return; if (userInput.length <= 0) return;
setIsLoading(true); setIsLoading(true);
chatStore.onUserInput(userInput).then(() => setIsLoading(false)); chatStore.onUserInput(userInput).then(() => setIsLoading(false));
setBeforeInput(userInput);
setUserInput(""); setUserInput("");
setPromptHints([]); setPromptHints([]);
if (!isMobileScreen()) inputRef.current?.focus(); if (!isMobileScreen()) inputRef.current?.focus();
@@ -420,6 +441,12 @@ export function Chat(props: {
// check if should send message // check if should send message
const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// if ArrowUp and no userInput
if (e.key === "ArrowUp" && userInput.length <= 0) {
setUserInput(beforeInput);
e.preventDefault();
return;
}
if (shouldSubmit(e)) { if (shouldSubmit(e)) {
onUserSubmit(); onUserSubmit();
e.preventDefault(); e.preventDefault();
@@ -660,7 +687,6 @@ export function Chat(props: {
ref={inputRef} ref={inputRef}
className={styles["chat-input"]} className={styles["chat-input"]}
placeholder={Locale.Chat.Input(submitKey)} placeholder={Locale.Chat.Input(submitKey)}
rows={2}
onInput={(e) => onInput(e.currentTarget.value)} onInput={(e) => onInput(e.currentTarget.value)}
value={userInput} value={userInput}
onKeyDown={onInputKeyDown} onKeyDown={onInputKeyDown}
@@ -670,6 +696,7 @@ export function Chat(props: {
setTimeout(() => setPromptHints([]), 500); setTimeout(() => setPromptHints([]), 500);
}} }}
autoFocus={!props?.sideBarShowing} autoFocus={!props?.sideBarShowing}
rows={inputRows}
/> />
<IconButton <IconButton
icon={<SendWhiteIcon />} icon={<SendWhiteIcon />}

View File

@@ -406,17 +406,11 @@
background-color: var(--white); background-color: var(--white);
color: var(--black); color: var(--black);
font-family: inherit; font-family: inherit;
padding: 10px 14px 50px; padding: 10px 90px 10px 14px;
resize: none; resize: none;
outline: none; outline: none;
} }
@media only screen and (max-width: 600px) {
.chat-input {
font-size: 16px;
}
}
.chat-input:focus { .chat-input:focus {
border: 1px solid var(--primary); border: 1px solid var(--primary);
} }
@@ -427,7 +421,17 @@
position: absolute; position: absolute;
right: 30px; right: 30px;
bottom: 30px; bottom: 32px;
}
@media only screen and (max-width: 600px) {
.chat-input {
font-size: 16px;
}
.chat-input-send {
bottom: 30px;
}
} }
.export-content { .export-content {

View File

@@ -67,7 +67,7 @@ export function Markdown(props: { content: string }) {
components={{ components={{
pre: PreCode, pre: PreCode,
}} }}
linkTarget={'_blank'} linkTarget={"_blank"}
> >
{props.content} {props.content}
</ReactMarkdown> </ReactMarkdown>

View File

@@ -128,6 +128,19 @@ export function Settings(props: { closeSettings: () => void }) {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useEffect(() => {
const keydownEvent = (e: KeyboardEvent) => {
if (e.key === "Escape") {
props.closeSettings();
}
};
document.addEventListener("keydown", keydownEvent);
return () => {
document.removeEventListener("keydown", keydownEvent);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return ( return (
<ErrorBoundary> <ErrorBoundary>
<div className={styles["window-header"]}> <div className={styles["window-header"]}>

View File

@@ -21,11 +21,11 @@ const cn = {
Rename: "重命名对话", Rename: "重命名对话",
Typing: "正在输入…", Typing: "正在输入…",
Input: (submitKey: string) => { Input: (submitKey: string) => {
var inputHints = `输入消息,${submitKey} 发送`; var inputHints = `${submitKey} 发送`;
if (submitKey === String(SubmitKey.Enter)) { if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter 换行"; inputHints += "Shift + Enter 换行";
} }
return inputHints; return inputHints + "/ 触发补全";
}, },
Send: "发送", Send: "发送",
}, },
@@ -126,7 +126,7 @@ const cn = {
Model: "模型 (model)", Model: "模型 (model)",
Temperature: { Temperature: {
Title: "随机性 (temperature)", Title: "随机性 (temperature)",
SubTitle: "值越大,回复越随机", SubTitle: "值越大,回复越随机,大于 1 的值可能会导致乱码",
}, },
MaxTokens: { MaxTokens: {
Title: "单次回复限制 (max_tokens)", Title: "单次回复限制 (max_tokens)",

View File

@@ -23,11 +23,11 @@ const en: LocaleType = {
Rename: "Rename Chat", Rename: "Rename Chat",
Typing: "Typing…", Typing: "Typing…",
Input: (submitKey: string) => { Input: (submitKey: string) => {
var inputHints = `Type something and press ${submitKey} to send`; var inputHints = `${submitKey} to send`;
if (submitKey === String(SubmitKey.Enter)) { if (submitKey === String(SubmitKey.Enter)) {
inputHints += ", press Shift + Enter to newline"; inputHints += ", Shift + Enter to wrap";
} }
return inputHints; return inputHints + ", / to search prompts";
}, },
Send: "Send", Send: "Send",
}, },

View File

@@ -9,7 +9,7 @@ const makeRequestParam = (
options?: { options?: {
filterBot?: boolean; filterBot?: boolean;
stream?: boolean; stream?: boolean;
} },
): ChatRequest => { ): ChatRequest => {
let sendMessages = messages.map((v) => ({ let sendMessages = messages.map((v) => ({
role: v.role, role: v.role,
@@ -20,7 +20,11 @@ const makeRequestParam = (
sendMessages = sendMessages.filter((m) => m.role !== "assistant"); sendMessages = sendMessages.filter((m) => m.role !== "assistant");
} }
const modelConfig = useChatStore.getState().config.modelConfig; const modelConfig = { ...useChatStore.getState().config.modelConfig };
// @yidadaa: wont send max_tokens, because it is nonsense for Muggles
// @ts-expect-error
delete modelConfig.max_tokens;
return { return {
messages: sendMessages, messages: sendMessages,
@@ -84,7 +88,7 @@ export async function requestUsage() {
const [used, subs] = await Promise.all([ const [used, subs] = await Promise.all([
requestOpenaiClient( requestOpenaiClient(
`dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}` `dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`,
)(null, "GET"), )(null, "GET"),
requestOpenaiClient("dashboard/billing/subscription")(null, "GET"), requestOpenaiClient("dashboard/billing/subscription")(null, "GET"),
]); ]);
@@ -124,7 +128,7 @@ export async function requestChatStream(
onMessage: (message: string, done: boolean) => void; onMessage: (message: string, done: boolean) => void;
onError: (error: Error, statusCode?: number) => void; onError: (error: Error, statusCode?: number) => void;
onController?: (controller: AbortController) => void; onController?: (controller: AbortController) => void;
} },
) { ) {
const req = makeRequestParam(messages, { const req = makeRequestParam(messages, {
stream: true, stream: true,
@@ -213,7 +217,7 @@ export const ControllerPool = {
addController( addController(
sessionIndex: number, sessionIndex: number,
messageId: number, messageId: number,
controller: AbortController controller: AbortController,
) { ) {
const key = this.key(sessionIndex, messageId); const key = this.key(sessionIndex, messageId);
this.controllers[key] = controller; this.controllers[key] = controller;

View File

@@ -332,18 +332,19 @@ export const useChatStore = create<ChatStore>()(
const isLastSession = get().sessions.length === 1; const isLastSession = get().sessions.length === 1;
if (!isMobileScreen() || confirm(Locale.Home.DeleteChat)) { if (!isMobileScreen() || confirm(Locale.Home.DeleteChat)) {
get().removeSession(index); get().removeSession(index);
showToast(Locale.Home.DeleteToast, {
text: Locale.Home.Revert,
onClick() {
set((state) => ({
sessions: state.sessions
.slice(0, index)
.concat([deletedSession])
.concat(state.sessions.slice(index + Number(isLastSession))),
}));
},
});
} }
showToast(Locale.Home.DeleteToast, {
text: Locale.Home.Revert,
onClick() {
set((state) => ({
sessions: state.sessions
.slice(0, index)
.concat([deletedSession])
.concat(state.sessions.slice(index + Number(isLastSession))),
}));
},
});
}, },
currentSession() { currentSession() {

View File

@@ -1,6 +1,7 @@
import { create } from "zustand"; import { create } from "zustand";
import { persist } from "zustand/middleware"; import { persist } from "zustand/middleware";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { getLang } from "../locales";
export interface Prompt { export interface Prompt {
id?: number; id?: number;
@@ -25,11 +26,13 @@ export const SearchService = {
count: { count: {
builtin: 0, builtin: 0,
}, },
allBuiltInPrompts: [] as Prompt[],
init(prompts: Prompt[]) { init(prompts: Prompt[]) {
if (this.ready) { if (this.ready) {
return; return;
} }
this.allBuiltInPrompts = prompts;
this.engine.setCollection(prompts); this.engine.setCollection(prompts);
this.ready = true; this.ready = true;
}, },
@@ -78,6 +81,11 @@ export const usePromptStore = create<PromptStore>()(
}, },
search(text) { search(text) {
if (text.length === 0) {
// return all prompts
const userPrompts = get().prompts?.values?.() ?? [];
return SearchService.allBuiltInPrompts.concat([...userPrompts]);
}
return SearchService.search(text) as Prompt[]; return SearchService.search(text) as Prompt[];
}, },
}), }),
@@ -92,7 +100,11 @@ export const usePromptStore = create<PromptStore>()(
fetch(PROMPT_URL) fetch(PROMPT_URL)
.then((res) => res.json()) .then((res) => res.json())
.then((res) => { .then((res) => {
const builtinPrompts = [res.en, res.cn] let fetchPrompts = [res.en, res.cn];
if (getLang() === "cn") {
fetchPrompts = fetchPrompts.reverse();
}
const builtinPrompts = fetchPrompts
.map((promptList: PromptList) => { .map((promptList: PromptList) => {
return promptList.map( return promptList.map(
([title, content]) => ([title, content]) =>

View File

@@ -51,6 +51,12 @@ export function isMobileScreen() {
return window.innerWidth <= 600; return window.innerWidth <= 600;
} }
export function isFirefox() {
return (
typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)
);
}
export function selectOrCopy(el: HTMLElement, content: string) { export function selectOrCopy(el: HTMLElement, content: string) {
const currentSelection = window.getSelection(); const currentSelection = window.getSelection();
@@ -91,3 +97,51 @@ export function getCurrentVersion() {
export function getEmojiUrl(unified: string, style: EmojiStyle) { export function getEmojiUrl(unified: string, style: EmojiStyle) {
return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`; return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
} }
function getDomContentWidth(dom: HTMLElement) {
const style = window.getComputedStyle(dom);
const paddingWidth =
parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
const width = dom.clientWidth - paddingWidth;
return width;
}
function getOrCreateMeasureDom(id: string, init?: (dom: HTMLElement) => void) {
let dom = document.getElementById(id);
if (!dom) {
dom = document.createElement("span");
dom.style.position = "absolute";
dom.style.wordBreak = "break-word";
dom.style.fontSize = "14px";
dom.style.transform = "translateY(-200vh)";
dom.style.pointerEvents = "none";
dom.style.opacity = "0";
dom.id = id;
document.body.appendChild(dom);
init?.(dom);
}
return dom!;
}
export function autoGrowTextArea(dom: HTMLTextAreaElement) {
const measureDom = getOrCreateMeasureDom("__measure");
const singleLineDom = getOrCreateMeasureDom("__single_measure", (dom) => {
dom.innerText = "TEXT_FOR_MEASURE";
});
const width = getDomContentWidth(dom);
measureDom.style.width = width + "px";
measureDom.innerHTML = dom.value.trim().length > 0 ? dom.value : "1";
const lineWrapCount = Math.max(0, dom.value.split("\n").length - 1);
const height = parseFloat(window.getComputedStyle(measureDom).height);
const singleLineHeight = parseFloat(
window.getComputedStyle(singleLineDom).height,
);
const rows = Math.round(height / singleLineHeight) + lineWrapCount;
return rows;
}

View File

@@ -23,6 +23,6 @@
"@/*": ["./*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "app/calcTextareaHeight.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }