Skip to content

Instantly share code, notes, and snippets.

@smashah
Created January 19, 2021 01:21
Show Gist options
  • Save smashah/fa04a3c408568fef30224e155e445ccf to your computer and use it in GitHub Desktop.
Save smashah/fa04a3c408568fef30224e155e445ccf to your computer and use it in GitHub Desktop.
Typescript implementation of lit-media-query (with initial test & listener cleanup)
import { LitElement, customElement, property } from 'lit-element';
@customElement('lit-media-query')
export class LitMediaQuery extends LitElement {
@property({ type: Boolean }) _match: boolean = false;
@property({ type: Boolean }) _initFired: boolean = false;
@property({ type: Boolean }) _registeredListeners: boolean = false;
@property({ type: String }) query: string = "(max-width:460px)";
setupListeners() {
// Check if Visual Viewport API is supported
if (!this._registeredListeners) {
if (typeof this.vp() !== 'undefined') {
this.vp().addEventListener('resize', () => this._handleRisize());
} else {
window.addEventListener('resize', () => this._handleRisize());
}
}
this._registeredListeners = true;
if (!this._initFired) {
this._handleRisize();
this._initFired = true;
}
}
vp() {
return window.visualViewport as any;
}
firstUpdated() {
this.setupListeners();
}
connectedCallback() {
super.connectedCallback()
this.setupListeners();
}
disconnectedCallback() {
if (this._registeredListeners) {
if (typeof this.vp() !== 'undefined') {
this.vp().removeEventListener('resize', () => this._handleRisize());
} else {
window.removeEventListener('resize', () => this._handleRisize());
}
}
this._initFired = false;
super.disconnectedCallback()
}
_handleRisize() {
if (window.matchMedia(this.query).matches) {
// From no match to match
if (this._match === false) {
this.dispatchEvent(new CustomEvent('changed', {
detail: {
value: true
},
composed: true,
bubbles: true
}));
this._match = true;
}
} else {
// From match to no match
if (this._match === true) {
this.dispatchEvent(new CustomEvent('changed', {
detail: {
value: false
},
composed: true,
bubbles: true
}));
this._match = false;
}
}
}
}
@smashah
Copy link
Author

smashah commented Jan 19, 2021

This is a typescript conversion of @Victor-Bernabe 's project lit-media-query - https://github.com/Victor-Bernabe/lit-media-query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment