Skip to content

Instantly share code, notes, and snippets.

@heyMP
Created December 1, 2021 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyMP/2e1e65c012c5c437310e8948b9f3c490 to your computer and use it in GitHub Desktop.
Save heyMP/2e1e65c012c5c437310e8948b9f3c490 to your computer and use it in GitHub Desktop.
Typing a Resize Observer in web comopnents.
import type { ReactiveControllerHost, ReactiveController } from 'lit';
export class MatchMediaController implements ReactiveController {
// reference to the host element using this controller
host: ReactiveControllerHost & Element;
// the output value
value = false;
private mediaQuery: string;
private resizeObserver?: ResizeObserver;
constructor(host: ReactiveControllerHost & Element, mediaQuery: string = '') {
(this.host = host).addController(this);
this.mediaQuery = mediaQuery;
}
hostConnected() {
this.resizeObserver = new ResizeObserver(this.evaluate.bind(this));
if (this.host) {
this.resizeObserver.observe(this.host);
}
}
hostDisconnected() {
if (this.resizeObserver)
this.resizeObserver.disconnect();
}
evaluate() {
// use matchMedia to evaluate if the current media query is a match.
const value = window.matchMedia(this.mediaQuery).matches;
// dirty check value to determine to update or not
if (this.value !== value) {
this.value = value;
// request a render update
this.host.requestUpdate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment