@exadel/esl
Version:
Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components
47 lines (46 loc) • 1.52 kB
JavaScript
import { SyntheticEventTarget } from '../../../esl-utils/dom/events';
import { ALL, NOT_ALL } from './media-query-const';
import { ESLMediaChangeEvent } from './media-query-base';
/**
* Simple media condition implementation
* @author Alexey Stsefanovich (ala'n)
*
* Wraps matchMedia instance
*/
export class MediaQueryCondition extends SyntheticEventTarget {
constructor(query) {
super();
this._mq = matchMedia(query.trim() || 'all');
this._onChange = this._onChange.bind(this);
}
get matches() {
return this._mq.matches;
}
addEventListener(type, callback = type) {
super.addEventListener(type, callback);
if (this.getEventListeners('change').length > 1)
return;
this._mq.addEventListener('change', this._onChange);
}
removeEventListener(type, callback = type) {
super.removeEventListener(type, callback);
if (this.hasEventListener())
return;
this._mq.removeEventListener('change', this._onChange);
}
/** Optimize query. Can simplify query to {@link MediaQueryConstCondition} */
optimize() {
if (ALL.eq(this))
return ALL;
if (NOT_ALL.eq(this))
return NOT_ALL;
return this;
}
toString() {
return this._mq.media;
}
/** Handles query change and dispatches it on top level in case result value is changed */
_onChange() {
this.dispatchEvent(new ESLMediaChangeEvent(this._mq.matches));
}
}