Fix mobile AI chat keyboard overlap and keep input focused

This commit is contained in:
2026-02-23 13:05:42 +01:00
parent 273859902d
commit 7696b6b298
2 changed files with 35 additions and 7 deletions

View File

@@ -76,7 +76,9 @@
const messages = chatRoot.querySelector(".ai-chat__messages");
const form = chatRoot.querySelector(".ai-chat__form");
const input = chatRoot.querySelector(".ai-chat__input");
const sendBtn = chatRoot.querySelector(".ai-chat__send");
const backToTop = document.getElementById("back-to-top");
const viewport = window.visualViewport;
function addMessage(text, fromUser) {
const bubble = document.createElement("p");
@@ -96,12 +98,14 @@
addMessage(introMessage, false);
}
input.focus();
syncKeyboardOffset();
}
function closeChat() {
panel.classList.remove("is-open");
panel.setAttribute("aria-hidden", "true");
fab.setAttribute("aria-expanded", "false");
syncKeyboardOffset();
}
function randomItem(items) {
@@ -123,6 +127,18 @@
);
}
function syncKeyboardOffset() {
if (!viewport) {
chatRoot.style.setProperty("--ai-chat-keyboard-offset", "0px");
return;
}
const offset = Math.max(
0,
Math.round(window.innerHeight - viewport.height - viewport.offsetTop),
);
chatRoot.style.setProperty("--ai-chat-keyboard-offset", `${offset}px`);
}
fab.addEventListener("click", () => {
if (panel.classList.contains("is-open")) {
closeChat();
@@ -132,6 +148,10 @@
});
closeBtn.addEventListener("click", closeChat);
sendBtn.addEventListener("pointerdown", (event) => {
// Keep focus on the input so mobile keyboards stay open after sending.
event.preventDefault();
});
form.addEventListener("submit", (event) => {
event.preventDefault();
@@ -142,6 +162,7 @@
addMessage(text, true);
addMessage(buildReply(), false);
input.value = "";
input.focus({ preventScroll: true });
});
if (backToTop) {
@@ -152,5 +173,11 @@
});
window.addEventListener("resize", syncChatPosition);
}
if (viewport) {
viewport.addEventListener("resize", syncKeyboardOffset);
viewport.addEventListener("scroll", syncKeyboardOffset);
}
window.addEventListener("resize", syncKeyboardOffset);
syncChatPosition();
syncKeyboardOffset();
})();