-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(mobile-service): use media-query event for isMobile signal
- Loading branch information
Showing
3 changed files
with
13 additions
and
48 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,45 +1,21 @@ | ||
import { Injectable, Signal, effect, signal } from '@angular/core'; | ||
import { Injectable, signal } from '@angular/core'; | ||
import { toSignal } from '@angular/core/rxjs-interop'; | ||
import { fromEvent } from 'rxjs'; | ||
import { fromEvent, map } from 'rxjs'; | ||
|
||
const SM_QUERY_LIST = matchMedia('(min-width: 640px)'); | ||
|
||
@Injectable({ | ||
providedIn: 'root' | ||
}) | ||
export class MobileService { | ||
private readonly _resize: Signal<Event | undefined>; | ||
private readonly _isMobile = signal(false); | ||
|
||
public get resize(): Signal<Event | undefined> { | ||
return this._resize; | ||
} | ||
|
||
public get isMobile(): Signal<boolean> { | ||
return this._isMobile.asReadonly(); | ||
} | ||
|
||
public constructor() { | ||
const resize$ = fromEvent(window, 'resize'); | ||
this._resize = toSignal(resize$); | ||
|
||
effect( | ||
() => { | ||
// Reference resize signal to trigger computation on window resize | ||
if (!this._resize()) { | ||
return; | ||
} | ||
|
||
this._isMobile.set(window.innerWidth < 640); | ||
}, | ||
{ | ||
allowSignalWrites: true | ||
} | ||
); | ||
|
||
this._isMobile.set(window.innerWidth < 640); | ||
} | ||
public isMobile = toSignal( | ||
fromEvent<MediaQueryListEvent>(SM_QUERY_LIST, 'change').pipe(map((event) => !event.matches)), | ||
{ | ||
initialValue: !SM_QUERY_LIST.matches | ||
} | ||
); | ||
} | ||
|
||
export class MobileServiceMock { | ||
public readonly isMobile = signal(false).asReadonly(); | ||
public readonly resize = signal<Event | undefined>(undefined).asReadonly(); | ||
} |