harmony-responsive/entry/src/main/ets/utils/BreakpointSystem.ets
2023-10-08 17:34:27 +08:00

59 lines
2.3 KiB
Plaintext

import mediaQuery from '@ohos.mediaquery';
import { CommonConstants as Const } from '../constants/CommonConstants';
export default class BreakpointSystem {
private currentBreakpoint: string = Const.MD;
private xsListener: mediaQuery.MediaQueryListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_1);
private smListener: mediaQuery.MediaQueryListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_2);
private mdListener: mediaQuery.MediaQueryListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_3);
private lgListener: mediaQuery.MediaQueryListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_4);
private isBreakpointXS = (mediaQueryResult: mediaQuery.MediaQueryResult) => {
if (mediaQueryResult.matches) {
this.updateCurrentBreakpoint(Const.XS);
}
}
private isBreakpointSM = (mediaQueryResult: mediaQuery.MediaQueryResult) => {
if (mediaQueryResult.matches) {
this.updateCurrentBreakpoint(Const.SM);
}
}
private isBreakpointMD = (mediaQueryResult: mediaQuery.MediaQueryResult) => {
if (mediaQueryResult.matches) {
this.updateCurrentBreakpoint(Const.MD);
}
}
private isBreakpointLG = (mediaQueryResult: mediaQuery.MediaQueryResult) => {
if (mediaQueryResult.matches) {
this.updateCurrentBreakpoint(Const.LG);
}
}
public register() {
this.xsListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_1);
this.xsListener.on('change', this.isBreakpointXS);
this.smListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_2);
this.smListener.on('change', this.isBreakpointSM);
this.mdListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_3);
this.mdListener.on('change', this.isBreakpointMD);
this.lgListener = mediaQuery.matchMediaSync(Const.BREAKPOINTS_SCOPE_4);
this.lgListener.on('change', this.isBreakpointLG);
}
private updateCurrentBreakpoint(breakpoint: string) {
if (this.currentBreakpoint !== breakpoint) {
this.currentBreakpoint = breakpoint;
AppStorage.set<string>('currentBreakpoint', this.currentBreakpoint);
}
}
public unregister() {
this.xsListener.off('change', this.isBreakpointXS);
this.smListener.off('change', this.isBreakpointSM);
this.mdListener.off('change', this.isBreakpointMD);
this.lgListener.off('change', this.isBreakpointLG);
}
}