1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import mediaQuery from '@ohos.mediaquery' 17 18declare interface BreakPointTypeOption<T> { 19 xs?: T 20 sm?: T 21 md?: T 22 lg?: T 23 xl?: T 24 xxl?: T 25} 26 27export class BreakPointType<T> { 28 options: BreakPointTypeOption<T> 29 30 constructor(option: BreakPointTypeOption<T>) { 31 this.options = option 32 } 33 34 getValue(currentBreakPoint: string) { 35 if (currentBreakPoint === 'xs') { 36 return this.options.xs 37 } else if (currentBreakPoint === 'sm') { 38 return this.options.sm 39 } else if (currentBreakPoint === 'md') { 40 return this.options.md 41 } else if (currentBreakPoint === 'lg') { 42 return this.options.lg 43 } else if (currentBreakPoint === 'xl') { 44 return this.options.xl 45 } else if (currentBreakPoint === 'xxl') { 46 return this.options.xxl 47 } else { 48 return undefined 49 } 50 } 51} 52 53type Breakpoint = { 54 name: string 55 size: number 56 mediaQueryListener?: mediaQuery.MediaQueryListener 57} 58 59export class BreakpointSystem { 60 private currentBreakpoint: string = 'md' 61 private breakpoints: Breakpoint[] = [{ name: 'xs', size: 0 }, { name: 'sm', size: 320 }, 62 { name: 'md', size: 520 }, { name: 'lg', size: 840 }] 63 64 private updateCurrentBreakpoint(breakpoint: string) { 65 if (this.currentBreakpoint !== breakpoint) { 66 this.currentBreakpoint = breakpoint 67 AppStorage.Set<string>('currentBreakpoint', this.currentBreakpoint) 68 console.log('on current breakpoint: ' + this.currentBreakpoint) 69 } 70 } 71 72 public register() { 73 this.breakpoints.forEach((breakpoint: Breakpoint, index) => { 74 let condition 75 if (index === this.breakpoints.length - 1) { 76 condition = "(" + breakpoint.size + "vp<=width" + ")" 77 } else { 78 condition = "(" + breakpoint.size + "vp<=width<" + this.breakpoints[index + 1].size + "vp)" 79 } 80 console.log(condition) 81 breakpoint.mediaQueryListener = mediaQuery.matchMediaSync(condition) 82 breakpoint.mediaQueryListener.on('change', (mediaQueryResult) => { 83 if (mediaQueryResult.matches) { 84 this.updateCurrentBreakpoint(breakpoint.name) 85 } 86 }) 87 }) 88 } 89 90 public unregister() { 91 this.breakpoints.forEach((breakpoint: Breakpoint) => { 92 breakpoint.mediaQueryListener.off('change') 93 }) 94 } 95}