FIX: always listen on window resize (#21536)

When using `navigator.virtualKeyboard.overlaysContent = false` we can rely on using only the resize event. Also attempts to no over trigger `setProperty` when value didn't change.
This commit is contained in:
Joffrey JAFFEUX 2023-05-13 15:39:46 +02:00 committed by GitHub
parent eec10efc3d
commit 4cfa78c3f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,84 +1,52 @@
import { bind } from "discourse-common/utils/decorators";
import Component from "@ember/component";
import isZoomed from "discourse/plugins/chat/discourse/lib/zoom-check";
import { inject as service } from "@ember/service";
const CSS_VAR = "--chat-vh";
let lastVH;
export default class ChatVh extends Component {
@service capabilities;
tagName = "";
didInsertElement() {
this._super(...arguments);
this.setVHFromVisualViewPort();
if ("virtualKeyboard" in navigator) {
navigator.virtualKeyboard.overlaysContent = true;
navigator.virtualKeyboard.addEventListener(
"geometrychange",
this.setVHFromKeyboard
);
} else {
(window?.visualViewport || window).addEventListener(
"resize",
this.setVHFromVisualViewPort
);
navigator.virtualKeyboard.overlaysContent = false;
}
this.activeWindow = window.visualViewport || window;
this.activeWindow.addEventListener("resize", this.setVH);
this.setVH();
}
willDestroyElement() {
this._super(...arguments);
if ("virtualKeyboard" in navigator) {
navigator.virtualKeyboard.removeEventListener(
"geometrychange",
this.setVHFromKeyboard
);
} else {
(window?.visualViewport || window).removeEventListener(
"resize",
this.setVHFromVisualViewPort
);
}
this.activeWindow?.removeEventListener("resize", this.setVH);
lastVH = null;
}
@bind
setVHFromKeyboard(event) {
if (this.isDestroying || this.isDestroyed) {
setVH() {
const vh = (this.activeWindow?.height || window.innerHeight) * 0.01;
if (lastVH === vh) {
return;
} else if (this.capabilities.touch && lastVH < vh && vh - lastVH > 1) {
this.#blurActiveElement();
}
if (isZoomed()) {
return;
}
lastVH = vh;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const keyboardHeight = event.target.boundingRect.height;
const viewportHeight =
window.visualViewport?.height || window.innerHeight;
const vhInPixels = (viewportHeight - keyboardHeight) * 0.01;
document.documentElement.style.setProperty(CSS_VAR, `${vhInPixels}px`);
});
});
document.documentElement.style.setProperty(CSS_VAR, `${vh}px`);
}
@bind
setVHFromVisualViewPort() {
if (this.isDestroying || this.isDestroyed) {
return;
#blurActiveElement() {
if (document.activeElement?.blur) {
document.activeElement.blur();
}
if (isZoomed()) {
return;
}
requestAnimationFrame(() => {
const vhInPixels =
(window.visualViewport?.height || window.innerHeight) * 0.01;
document.documentElement.style.setProperty(CSS_VAR, `${vhInPixels}px`);
});
}
}