diff --git a/README.md b/README.md index 1ab27b7..3380af8 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# tp-element +# tp-media-query diff --git a/package.json b/package.json index c39fdff..78a0021 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,14 @@ { - "name": "@tp/tp-element", + "name": "@tp/tp-media-query", "version": "0.0.1", "description": "", - "main": "tp-element.js", + "main": "tp-media-query.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", - "url": "https://gitea.codeblob.work/tp-elements/tp-element.git" + "url": "https://gitea.codeblob.work/tp-elements/tp-media-query.git" }, "author": "trading_peter", "license": "Apache-2.0", diff --git a/tp-element.js b/tp-element.js deleted file mode 100644 index 6a92a2f..0000000 --- a/tp-element.js +++ /dev/null @@ -1,35 +0,0 @@ -/** -@license -Copyright (c) 2022 trading_peter -This program is available under Apache License Version 2.0 -*/ - -import { LitElement, html, css } from 'lit'; - -class TpElement extends LitElement { - static get styles() { - return [ - css` - :host { - display: block; - } - ` - ]; - } - - render() { - const { } = this; - - return html` - - `; - } - - static get properties() { - return { }; - } - - -} - -window.customElements.define('tp-element', TpElement); diff --git a/tp-media-query.js b/tp-media-query.js new file mode 100644 index 0000000..148c105 --- /dev/null +++ b/tp-media-query.js @@ -0,0 +1,68 @@ +/** +@license +Copyright (c) 2022 trading_peter +This program is available under Apache License Version 2.0 +*/ + +import { LitElement, css } from 'lit'; + +class TpMediaQuery extends LitElement { + static get styles() { + return [ + css` + :host { + display: none; + } + ` + ]; + } + + static get properties() { + return { + query: { type: String }, + }; + } + + constructor() { + super(); + this._boundQueryHandler = this.queryHandler.bind(this); + } + + connectedCallback() { + super.connectedCallback(); + this.checkQuery(); + } + + checkQuery() { + this._remove(); + var query = this.query; + if (!query) { + return; + } + if (query[0] !== '(') { + query = '(' + query + ')'; + } + this._queryMatch = window.matchMedia(query); + this._add(); + this.queryHandler(this._queryMatch); + } + + _add() { + if (this._queryMatch) { + this._queryMatch.addEventListener('change', this._boundQueryHandler); + } + } + + _remove() { + if (this._queryMatch) { + this._queryMatch.removeEventListener('change', this._boundQueryHandler); + } + this._queryMatch = null; + } + + queryHandler(mq) { + this.dispatchEvent(new CustomEvent('media-query-update', { detail: mq.matches, bubbles: true, composed: true })); + } +} + +window.customElements.define('tp-media-query', TpMediaQuery); \ No newline at end of file