Merge pull request #318 from leedom92/textarea-height-optimize
feat: textarea with adaptive height
This commit is contained in:
commit
d6b2cf8bcb
@ -17,7 +17,7 @@ async function makeRequest(req: NextRequest) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
status: 500,
|
status: 500,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
118
app/calcTextareaHeight.ts
Normal file
118
app/calcTextareaHeight.ts
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
/**
|
||||||
|
* fork from element-plus
|
||||||
|
* https://github.com/element-plus/element-plus/blob/dev/packages/components/input/src/utils.ts
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { isFirefox } from "./utils";
|
||||||
|
|
||||||
|
let hiddenTextarea: HTMLTextAreaElement | undefined = undefined;
|
||||||
|
|
||||||
|
const HIDDEN_STYLE = `
|
||||||
|
height:0 !important;
|
||||||
|
visibility:hidden !important;
|
||||||
|
${isFirefox() ? "" : "overflow:hidden !important;"}
|
||||||
|
position:absolute !important;
|
||||||
|
z-index:-1000 !important;
|
||||||
|
top:0 !important;
|
||||||
|
right:0 !important;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const CONTEXT_STYLE = [
|
||||||
|
"letter-spacing",
|
||||||
|
"line-height",
|
||||||
|
"padding-top",
|
||||||
|
"padding-bottom",
|
||||||
|
"font-family",
|
||||||
|
"font-weight",
|
||||||
|
"font-size",
|
||||||
|
"text-rendering",
|
||||||
|
"text-transform",
|
||||||
|
"width",
|
||||||
|
"text-indent",
|
||||||
|
"padding-left",
|
||||||
|
"padding-right",
|
||||||
|
"border-width",
|
||||||
|
"box-sizing",
|
||||||
|
];
|
||||||
|
|
||||||
|
type NodeStyle = {
|
||||||
|
contextStyle: string;
|
||||||
|
boxSizing: string;
|
||||||
|
paddingSize: number;
|
||||||
|
borderSize: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type TextAreaHeight = {
|
||||||
|
height: string;
|
||||||
|
minHeight?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function calculateNodeStyling(targetElement: Element): NodeStyle {
|
||||||
|
const style = window.getComputedStyle(targetElement);
|
||||||
|
|
||||||
|
const boxSizing = style.getPropertyValue("box-sizing");
|
||||||
|
|
||||||
|
const paddingSize =
|
||||||
|
Number.parseFloat(style.getPropertyValue("padding-bottom")) +
|
||||||
|
Number.parseFloat(style.getPropertyValue("padding-top"));
|
||||||
|
|
||||||
|
const borderSize =
|
||||||
|
Number.parseFloat(style.getPropertyValue("border-bottom-width")) +
|
||||||
|
Number.parseFloat(style.getPropertyValue("border-top-width"));
|
||||||
|
|
||||||
|
const contextStyle = CONTEXT_STYLE.map(
|
||||||
|
(name) => `${name}:${style.getPropertyValue(name)}`,
|
||||||
|
).join(";");
|
||||||
|
|
||||||
|
return { contextStyle, paddingSize, borderSize, boxSizing };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function calcTextareaHeight(
|
||||||
|
targetElement: HTMLTextAreaElement,
|
||||||
|
minRows: number = 2,
|
||||||
|
maxRows?: number,
|
||||||
|
): TextAreaHeight {
|
||||||
|
if (!hiddenTextarea) {
|
||||||
|
hiddenTextarea = document.createElement("textarea");
|
||||||
|
document.body.appendChild(hiddenTextarea);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { paddingSize, borderSize, boxSizing, contextStyle } =
|
||||||
|
calculateNodeStyling(targetElement);
|
||||||
|
|
||||||
|
hiddenTextarea.setAttribute("style", `${contextStyle};${HIDDEN_STYLE}`);
|
||||||
|
hiddenTextarea.value = targetElement.value || targetElement.placeholder || "";
|
||||||
|
|
||||||
|
let height = hiddenTextarea.scrollHeight;
|
||||||
|
const result = {} as TextAreaHeight;
|
||||||
|
|
||||||
|
if (boxSizing === "border-box") {
|
||||||
|
height = height + borderSize;
|
||||||
|
} else if (boxSizing === "content-box") {
|
||||||
|
height = height - paddingSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
hiddenTextarea.value = "";
|
||||||
|
const singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
|
||||||
|
|
||||||
|
if (minRows) {
|
||||||
|
let minHeight = singleRowHeight * minRows;
|
||||||
|
if (boxSizing === "border-box") {
|
||||||
|
minHeight = minHeight + paddingSize + borderSize;
|
||||||
|
}
|
||||||
|
height = Math.max(minHeight, height);
|
||||||
|
result.minHeight = `${minHeight}px`;
|
||||||
|
}
|
||||||
|
if (maxRows) {
|
||||||
|
let maxHeight = singleRowHeight * maxRows;
|
||||||
|
if (boxSizing === "border-box") {
|
||||||
|
maxHeight = maxHeight + paddingSize + borderSize;
|
||||||
|
}
|
||||||
|
height = Math.min(maxHeight, height);
|
||||||
|
}
|
||||||
|
result.height = `${height}px`;
|
||||||
|
hiddenTextarea.parentNode?.removeChild(hiddenTextarea);
|
||||||
|
hiddenTextarea = undefined;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
@ -41,6 +41,8 @@ import chatStyle from "./chat.module.scss";
|
|||||||
|
|
||||||
import { Input, Modal, showModal, showToast } from "./ui-lib";
|
import { Input, Modal, showModal, showToast } from "./ui-lib";
|
||||||
|
|
||||||
|
import calcTextareaHeight from "../calcTextareaHeight";
|
||||||
|
|
||||||
const Markdown = dynamic(
|
const Markdown = dynamic(
|
||||||
async () => memo((await import("./markdown")).Markdown),
|
async () => memo((await import("./markdown")).Markdown),
|
||||||
{
|
{
|
||||||
@ -331,6 +333,10 @@ function useScrollToBottom() {
|
|||||||
export function Chat(props: {
|
export function Chat(props: {
|
||||||
showSideBar?: () => void;
|
showSideBar?: () => void;
|
||||||
sideBarShowing?: boolean;
|
sideBarShowing?: boolean;
|
||||||
|
autoSize: {
|
||||||
|
minRows: number;
|
||||||
|
maxRows?: number;
|
||||||
|
};
|
||||||
}) {
|
}) {
|
||||||
type RenderMessage = Message & { preview?: boolean };
|
type RenderMessage = Message & { preview?: boolean };
|
||||||
|
|
||||||
@ -348,6 +354,7 @@ export function Chat(props: {
|
|||||||
const { submitKey, shouldSubmit } = useSubmitHandler();
|
const { submitKey, shouldSubmit } = useSubmitHandler();
|
||||||
const { scrollRef, setAutoScroll } = useScrollToBottom();
|
const { scrollRef, setAutoScroll } = useScrollToBottom();
|
||||||
const [hitBottom, setHitBottom] = useState(false);
|
const [hitBottom, setHitBottom] = useState(false);
|
||||||
|
const [textareaStyle, setTextareaStyle] = useState({});
|
||||||
|
|
||||||
const onChatBodyScroll = (e: HTMLElement) => {
|
const onChatBodyScroll = (e: HTMLElement) => {
|
||||||
const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
|
const isTouchBottom = e.scrollTop + e.clientHeight >= e.scrollHeight - 20;
|
||||||
@ -381,6 +388,14 @@ export function Chat(props: {
|
|||||||
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
|
dom.scrollTop = dom.scrollHeight - dom.offsetHeight + paddingBottomNum;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// textarea has an adaptive height
|
||||||
|
const resizeTextarea = () => {
|
||||||
|
const dom = inputRef.current;
|
||||||
|
if (!dom) return;
|
||||||
|
const { minRows, maxRows } = props.autoSize;
|
||||||
|
setTextareaStyle(calcTextareaHeight(dom, minRows, maxRows));
|
||||||
|
};
|
||||||
|
|
||||||
// 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) => {
|
||||||
@ -512,6 +527,12 @@ export function Chat(props: {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Textarea Adaptive height
|
||||||
|
useEffect(() => {
|
||||||
|
resizeTextarea();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [userInput]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.chat} key={session.id}>
|
<div className={styles.chat} key={session.id}>
|
||||||
<div className={styles["window-header"]}>
|
<div className={styles["window-header"]}>
|
||||||
@ -667,8 +688,8 @@ export function Chat(props: {
|
|||||||
<textarea
|
<textarea
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
className={styles["chat-input"]}
|
className={styles["chat-input"]}
|
||||||
|
style={textareaStyle}
|
||||||
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}
|
||||||
|
@ -406,7 +406,7 @@
|
|||||||
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;
|
||||||
}
|
}
|
||||||
|
@ -189,6 +189,7 @@ function _Home() {
|
|||||||
key="chat"
|
key="chat"
|
||||||
showSideBar={() => setShowSideBar(true)}
|
showSideBar={() => setShowSideBar(true)}
|
||||||
sideBarShowing={showSideBar}
|
sideBarShowing={showSideBar}
|
||||||
|
autoSize={{ minRows: 2, maxRows: 6 }}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
@ -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>
|
||||||
|
@ -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,
|
||||||
@ -84,7 +84,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 +124,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 +213,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;
|
||||||
|
@ -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();
|
||||||
|
|
||||||
|
@ -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"]
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user