2017-08-02 10:05:59 +03:00
|
|
|
import Evented from '@ember/object/evented';
|
|
|
|
import Service from '@ember/service';
|
|
|
|
import {run} from '@ember/runloop';
|
2015-10-28 14:36:45 +03:00
|
|
|
|
2015-11-20 20:26:34 +03:00
|
|
|
const MEDIA_QUERIES = {
|
|
|
|
maxWidth600: '(max-width: 600px)',
|
|
|
|
isMobile: '(max-width: 800px)',
|
|
|
|
maxWidth900: '(max-width: 900px)',
|
|
|
|
maxWidth1000: '(max-width: 1000px)'
|
|
|
|
};
|
|
|
|
|
2017-08-02 10:05:59 +03:00
|
|
|
export default Service.extend(Evented, {
|
2015-10-28 14:36:45 +03:00
|
|
|
init() {
|
2015-11-20 20:26:34 +03:00
|
|
|
this._super(...arguments);
|
|
|
|
this._handlers = [];
|
|
|
|
this.loadQueries(MEDIA_QUERIES);
|
|
|
|
},
|
|
|
|
|
2015-10-28 14:36:45 +03:00
|
|
|
loadQueries(queries) {
|
|
|
|
Object.keys(queries).forEach((key) => {
|
2015-11-20 20:26:34 +03:00
|
|
|
this.loadQuery(key, queries[key]);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
2015-10-28 14:36:45 +03:00
|
|
|
loadQuery(key, queryString) {
|
2015-11-20 20:26:34 +03:00
|
|
|
let query = window.matchMedia(queryString);
|
|
|
|
|
|
|
|
this.set(key, query.matches);
|
|
|
|
|
2015-10-28 14:36:45 +03:00
|
|
|
let handler = run.bind(this, () => {
|
2015-11-20 20:26:34 +03:00
|
|
|
let lastValue = this.get(key);
|
|
|
|
let newValue = query.matches;
|
|
|
|
if (lastValue !== newValue) {
|
2017-08-02 10:05:59 +03:00
|
|
|
this.set(key, newValue);
|
|
|
|
this.trigger('change', key, newValue);
|
2015-11-20 20:26:34 +03:00
|
|
|
}
|
|
|
|
});
|
|
|
|
query.addListener(handler);
|
|
|
|
this._handlers.push([query, handler]);
|
|
|
|
},
|
|
|
|
|
2015-10-28 14:36:45 +03:00
|
|
|
willDestroy() {
|
2015-11-20 20:26:34 +03:00
|
|
|
this._handlers.forEach(([query, handler]) => {
|
|
|
|
query.removeListener(handler);
|
|
|
|
});
|
|
|
|
this._super(...arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
});
|