theme.js 2.1 KB
Newer Older
D
DCloud_LXH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
import { normallizeStyles } from 'uni-shared'
import { weexGetSystemInfoSync } from '../api/device/system'

const ON_THEME_CHANGE = 'api.onThemeChange'

function onThemeChange (callback = () => { }) {
  UniServiceJSBridge.on(ON_THEME_CHANGE, callback)
}

function offThemeChange (callback = () => { }) {
  UniServiceJSBridge.off(ON_THEME_CHANGE, callback)
}

export function parseTheme (pageStyle) {
  let parsedStyle = {}
  if (__uniConfig.darkmode) {
    let theme = 'light'
    const systemInfo = weexGetSystemInfoSync()
    if (systemInfo) {
      theme = systemInfo.hostTheme || systemInfo.osTheme
    }
    parsedStyle = normallizeStyles(pageStyle, __uniConfig.themeConfig, theme)
  }
  return __uniConfig.darkmode ? parsedStyle : pageStyle
}

export function useTabBarThemeChange (tabBar, options) {
  if (__uniConfig.darkmode) {
    const fn = () => {
      const {
        list = [], color, selectedColor,
        backgroundColor, borderStyle
      } = parseTheme(options, false)
      const tabbarStyle = {
        color,
        selectedColor,
        backgroundColor,
        borderStyle
      }

      tabBar && tabBar.setTabBarStyle(tabbarStyle)
      tabBar && tabBar.setTabBarItems({
        list: list.map((item) => ({
          iconPath: item.iconPath,
          selectedIconPath: item.selectedIconPath
        }))
      })
      // TODO 暂未实现
      // tabBar && tabBar.setAnimationAlphaBGColor(parseTheme((__uniConfig.window || {}).backgroundColor, false))
    }

    fn()

    onThemeChange(fn)
  }
}

export function useWebviewThemeChange (webview, getWebviewStyle) {
  if (__uniConfig.darkmode) {
    const fn = () => {
      const {
        animationAlphaBGColor, background,
        backgroundColorBottom, backgroundColorTop,
        titleNView: { backgroundColor, titleColor } = {}
      } = getWebviewStyle()
      webview && webview.setStyle({
        animationAlphaBGColor,
        background,
        backgroundColorBottom,
        backgroundColorTop,
        titleNView: {
          backgroundColor,
          titleColor
        }
      })
    }
    onThemeChange(fn)
    webview.addEventListener('close', () => offThemeChange(fn))
  }
}