theme.js 1.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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
}

D
DCloud_LXH 已提交
18 19
function hasTheme (themeLocation = '') {
  const themeJsonPath = path.join(process.env.UNI_INPUT_DIR, themeLocation || 'theme.json')
fxy060608's avatar
fxy060608 已提交
20 21 22 23 24 25 26
  return fs.existsSync(themeJsonPath)
}

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

D
DCloud_LXH 已提交
27 28
let themeConfig = {}

fxy060608's avatar
fxy060608 已提交
29
module.exports = {
D
DCloud_LXH 已提交
30
  getTheme: () => themeConfig,
fxy060608's avatar
fxy060608 已提交
31 32
  darkmode,
  hasTheme,
D
DCloud_LXH 已提交
33 34 35 36
  initTheme (manifestJson = {}) {
    const platform = process.env.UNI_PLATFORM
    const themeLocation = (manifestJson[platform] || {}).themeLocation
    if (!hasTheme(themeLocation)) {
fxy060608's avatar
fxy060608 已提交
37 38 39 40 41 42
      return
    }
    if (darkmode()) {
      return
    }
    try {
D
DCloud_LXH 已提交
43 44
      themeConfig = getJson(themeLocation || 'theme.json', true)
      global.uniPlugin.defaultTheme = themeConfig.light
fxy060608's avatar
fxy060608 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    } 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))
  }
D
DCloud_LXH 已提交
63
}