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[] = [ 62 { name: 'xs', size: 0 }, { name: 'sm', size: 320 }, 63 { name: 'md', size: 520 }, { name: 'lg', size: 840 } 64 ] 65 66 private updateCurrentBreakpoint(breakpoint: string) { 67 if (this.currentBreakpoint !== breakpoint) { 68 this.currentBreakpoint = breakpoint 69 AppStorage.Set<string>('currentBreakpoint', this.currentBreakpoint) 70 console.log('on current breakpoint: ' + this.currentBreakpoint) 71 } 72 } 73 74 public register() { 75 this.breakpoints.forEach((breakpoint: Breakpoint, index) => { 76 let condition 77 if (index === this.breakpoints.length - 1) { 78 condition = '(' + breakpoint.size + 'vp<=width' + ')' 79 } else { 80 condition = '(' + breakpoint.size + 'vp<=width<' + this.breakpoints[index + 1].size + 'vp)' 81 } 82 console.log(condition) 83 breakpoint.mediaQueryListener = mediaQuery.matchMediaSync(condition) 84 breakpoint.mediaQueryListener.on('change', (mediaQueryResult) => { 85 if (mediaQueryResult.matches) { 86 this.updateCurrentBreakpoint(breakpoint.name) 87 } 88 }) 89 }) 90 } 91 92 public unregister() { 93 this.breakpoints.forEach((breakpoint: Breakpoint) => { 94 breakpoint.mediaQueryListener.off('change') 95 }) 96 } 97}