mirror of
https://github.com/Yidadaa/ChatGPT-Next-Web.git
synced 2025-08-08 07:10:16 +08:00
fix: auto grow textarea
This commit is contained in:
48
app/utils.ts
48
app/utils.ts
@@ -97,3 +97,51 @@ export function getCurrentVersion() {
|
||||
export function getEmojiUrl(unified: string, style: EmojiStyle) {
|
||||
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;
|
||||
}
|
||||
|
Reference in New Issue
Block a user