theme.js 1.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
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
const fs = require('fs')
const path = require('path')

const {
  getJson
} = require('./json')

function parseThemeByJsonStr (jsonStr, keys, theme) {
  if (jsonStr.indexOf('@') === -1) {
    return jsonStr
  }
  keys.forEach(key => {
    jsonStr = jsonStr.replace(new RegExp('@' + key, 'g'), theme[key])
  })
  return jsonStr
}

const themeJsonPath = path.join(process.env.UNI_INPUT_DIR, 'theme.json')

function hasTheme () {
  return fs.existsSync(themeJsonPath)
}

function darkmode () {
  return !!(global.uniPlugin.options || {}).darkmode
}

module.exports = {
  darkmode,
  hasTheme,
  initTheme () {
    if (!hasTheme()) {
      return
    }
    if (darkmode()) {
      return
    }
    try {
      const theme = getJson('theme.json', true)
      global.uniPlugin.defaultTheme = theme.light
    } catch (e) {
      console.error(e)
    }
  },
  parseTheme (json) {
    const theme = global.uniPlugin.defaultTheme
    if (!theme) {
      return json
    }
    const keys = Object.keys(theme)
    if (!keys.length) {
      return json
    }
    if (typeof json === 'string') {
      return parseThemeByJsonStr(json, keys, theme)
    }
    return JSON.parse(parseThemeByJsonStr(JSON.stringify(json), keys, theme))
  }
}