forked from sseg/lit-media-query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlit-media-query.js
130 lines (120 loc) · 2.94 KB
/
lit-media-query.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import { LitElement, html } from 'lit-element';
/**
* The `lit-media-query` component detects when a media query
* is `true` or `false`.
*/
class LitMediaQuery extends LitElement {
/**
* Fired when `lit-media-query` changes detects a change
* in the media query (from `true` to `false` and vice versa).
*
* @event changed
* @param {boolean} value If media query is being fulfilled or not.
*/
static get properties() {
return {
/**
* Media query to be watched by the element.
*
* Can be modified at run time by setting a new value.
*/
query: { type: String },
_match: { type: Boolean }
};
}
constructor() {
super();
this.query = '(max-width:460px)';
this._match = false;
this.boundResizeHandler = this._handleRisize.bind(this);
}
render() {
return html`
<style>
:host {
display: none;
}
</style>
`;
}
firstUpdated() {
// Check media query once before 'resize' event
this._initialMediaQueryCheck();
}
connectedCallback() {
super.connectedCallback();
// Check if Visual Viewport API is supported
if (typeof window.visualViewport !== 'undefined') {
window.visualViewport.addEventListener('resize', this.boundResizeHandler);
} else {
window.addEventListener('resize', this.boundResizeHandler);
}
}
disconnectedCallback() {
// Remove event listeners
if (typeof window.visualViewport !== 'undefined') {
window.visualViewport.removeEventListener(
'resize',
this.boundResizeHandler
);
} else {
window.removeEventListener('resize', this.boundResizeHandler);
}
super.disconnectedCallback();
}
_initialMediaQueryCheck() {
if (window.matchMedia(this.query).matches) {
this.dispatchEvent(
new CustomEvent('changed', {
detail: {
value: true
},
composed: true,
bubbles: true
})
);
} else {
this.dispatchEvent(
new CustomEvent('changed', {
detail: {
value: false
},
composed: true,
bubbles: true
})
);
}
}
_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;
}
}
}
}
customElements.define('lit-media-query', LitMediaQuery);