Created
April 3, 2023 15:24
-
-
Save SonyStone/eccbd06fd35949d85af38af10b0e61a3 to your computer and use it in GitHub Desktop.
breakpoints for angular
This file contains hidden or 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
import { BreakpointObserver } from '@angular/cdk/layout'; | |
import { | |
Directive, | |
EmbeddedViewRef, | |
Inject, | |
inject, | |
InjectionToken, | |
Input, | |
OnDestroy, | |
TemplateRef, | |
ViewContainerRef, | |
} from '@angular/core'; | |
import { distinctUntilChanged, map, Observable, shareReplay, Subscription } from 'rxjs'; | |
/** Tailwind css breakpoints */ | |
enum SCREENS { | |
sm = '(min-width: 640px)', | |
md = '(min-width: 768px)', | |
lg = '(min-width: 1024px)', | |
xl = '(min-width: 1280px)', | |
'2xl' = '(min-width: 1536px)', | |
'3xl' = '(min-width: 1770px)' | |
} | |
const screens = { | |
sm: SCREENS.sm, | |
md: SCREENS.md, | |
lg: SCREENS.lg, | |
xl: SCREENS.xl, | |
'2xl': SCREENS['2xl'], | |
'3xl': SCREENS['3xl'] | |
}; | |
export type Breakpoints = { [keyof in keyof typeof screens]: Observable<boolean> }; | |
export const BREAKPOINTS = new InjectionToken<Breakpoints>('breakpoints', { | |
providedIn: 'root', | |
factory() { | |
const breakpointObserver = inject(BreakpointObserver); | |
const breakpoints$ = breakpointObserver.observe(Object.values(screens)).pipe(shareReplay(1)); | |
return Object.entries(screens).reduce((acc, [key, screen]) => { | |
(acc as any)[key] = breakpoints$.pipe( | |
map((result) => !!result.breakpoints[screen]), | |
distinctUntilChanged(), | |
shareReplay(1) | |
); | |
return acc; | |
}, {} as Breakpoints); | |
} | |
}); | |
export const screen_sm = () => inject(BREAKPOINTS).sm; | |
export const screen_md = () => inject(BREAKPOINTS).md; | |
export const screen_lg = () => inject(BREAKPOINTS).lg; | |
export const screen_2xl = () => inject(BREAKPOINTS)['2xl']; | |
export const screen_3xl = () => inject(BREAKPOINTS)['3xl']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment