1- import { get , tick } from '../internal/client/runtime.js' ;
1+ import { get } from '../internal/client/runtime.js' ;
22import { set , source } from '../internal/client/reactivity/sources.js' ;
3- import { effect_tracking , render_effect } from '../internal/client/reactivity/effects.js' ;
3+ import { effect_tracking } from '../internal/client/reactivity/effects.js' ;
4+ import { createStartStopNotifier } from './start-stop-notifier.js' ;
45
56/**
67 * Creates a media query and provides a `current` property that reflects whether or not it matches.
78 */
89export class MediaQuery {
910 #version = source ( 0 ) ;
10- #subscribers = 0 ;
1111 #query;
12- /** @type {any } */
13- #listener;
12+ #notify;
1413
1514 get current ( ) {
1615 if ( effect_tracking ( ) ) {
1716 get ( this . #version) ;
18-
19- render_effect ( ( ) => {
20- if ( this . #subscribers === 0 ) {
21- this . #listener = ( ) => set ( this . #version, this . #version. v + 1 ) ;
22- this . #query. addEventListener ( 'change' , this . #listener) ;
23- }
24-
25- this . #subscribers += 1 ;
26-
27- return ( ) => {
28- tick ( ) . then ( ( ) => {
29- // Only count down after timeout, else we would reach 0 before our own render effect reruns,
30- // but reach 1 again when the tick callback of the prior teardown runs. That would mean we
31- // re-subcribe unnecessarily and create a memory leak because the old subscription is never cleaned up.
32- this . #subscribers -= 1 ;
33-
34- if ( this . #subscribers === 0 ) {
35- this . #query. removeEventListener ( 'change' , this . #listener) ;
36- }
37- } ) ;
38- } ;
39- } ) ;
17+ this . #notify( ) ;
4018 }
4119
4220 return this . #query. matches ;
@@ -48,5 +26,10 @@ export class MediaQuery {
4826 */
4927 constructor ( query , matches ) {
5028 this . #query = window . matchMedia ( query ) ;
29+ this . #notify = createStartStopNotifier ( ( ) => {
30+ const listener = ( ) => set ( this . #version, this . #version. v + 1 ) ;
31+ this . #query. addEventListener ( 'change' , listener ) ;
32+ return ( ) => this . #query. removeEventListener ( 'change' , listener ) ;
33+ } ) ;
5134 }
5235}
0 commit comments