FIX: puts focus-event at application level (#7568)

Also attempts to use simpler and newer APIs
This commit is contained in:
Joffrey JAFFEUX 2019-05-20 13:48:03 +02:00 committed by GitHub
parent b788948985
commit bc8c77723e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 69 deletions

View File

@ -0,0 +1,36 @@
function gotFocus() {
if (!Discourse.get("hasFocus")) {
Discourse.setProperties({ hasFocus: true, notify: false });
}
}
function lostFocus() {
if (Discourse.get("hasFocus")) {
Discourse.set("hasFocus", false);
}
}
let onchange;
export default Ember.Mixin.create({
ready() {
this._super(...arguments);
onchange = () => {
document.visibilityState === "hidden" ? lostFocus() : gotFocus();
};
// Default to true
Discourse.set("hasFocus", true);
document.addEventListener("visibilitychange", onchange);
},
reset() {
this._super(...arguments);
document.removeEventListener("visibilitychange", onchange);
onchange = undefined;
}
});

View File

@ -4,10 +4,11 @@ import {
default as computed,
observes
} from "ember-addons/ember-computed-decorators";
import FocusEvent from "discourse-common/mixins/focus-event";
const _pluginCallbacks = [];
const Discourse = Ember.Application.extend({
const Discourse = Ember.Application.extend(FocusEvent, {
rootElement: "#main",
_docTitle: document.title,
RAW_TEMPLATES: {},

View File

@ -1,68 +0,0 @@
/**
Keep track of when the browser is in focus.
**/
export default {
name: "focus-event",
initialize: function() {
var hidden = "hidden";
// Default to true
Discourse.set("hasFocus", true);
var gotFocus = function() {
if (!Discourse.get("hasFocus")) {
Discourse.setProperties({ hasFocus: true, notify: false });
}
};
var lostFocus = function() {
if (Discourse.get("hasFocus")) {
Discourse.set("hasFocus", false);
}
};
var onchange = function(evt) {
var v = "visible",
h = "hidden",
evtMap = {
focus: v,
focusin: v,
pageshow: v,
blur: h,
focusout: h,
pagehide: h
};
evt = evt || window.event;
if (evt.type in evtMap) {
if (evtMap[evt.type] === "hidden") {
lostFocus();
} else {
gotFocus();
}
} else {
if (this[hidden]) {
lostFocus();
} else {
gotFocus();
}
}
};
// from StackOverflow http://stackoverflow.com/a/1060034/17174
if (hidden in document) {
document.addEventListener("visibilitychange", onchange);
} else if ((hidden = "mozHidden") in document) {
document.addEventListener("mozvisibilitychange", onchange);
} else if ((hidden = "webkitHidden") in document) {
document.addEventListener("webkitvisibilitychange", onchange);
} else if ((hidden = "msHidden") in document) {
document.addEventListener("msvisibilitychange", onchange);
}
// All others (including iPad which is a bit weird and gives onpageshow / hide
else {
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
}
}
};