theme.js 2.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
const fs = require('fs')
const path = require('path')
3
const { parseJson } = require('./json')
fxy060608's avatar
fxy060608 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

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
}

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

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

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

fxy060608's avatar
fxy060608 已提交
30
module.exports = {
D
DCloud_LXH 已提交
31
  getTheme: () => themeConfig,
fxy060608's avatar
fxy060608 已提交
32 33
  darkmode,
  hasTheme,
D
DCloud_LXH 已提交
34 35
  initTheme (manifestJson = {}) {
    const platform = process.env.UNI_PLATFORM
36
    const themeLocation = (manifestJson[platform] || {}).themeLocation || 'theme.json'
D
DCloud_LXH 已提交
37
    if (!hasTheme(themeLocation)) {
fxy060608's avatar
fxy060608 已提交
38 39 40 41 42 43
      return
    }
    if (darkmode()) {
      return
    }
    try {
D
DCloud_LXH 已提交
44
      themeConfig = Object.keys(themeConfig).length ? themeConfig : getJson(themeLocation, true)
D
DCloud_LXH 已提交
45
      global.uniPlugin.defaultTheme = themeConfig.light
fxy060608's avatar
fxy060608 已提交
46 47 48 49
    } catch (e) {
      console.error(e)
    }
  },
D
DCloud_LXH 已提交
50 51
  parseTheme (json, _theme) {
    const theme = themeConfig[_theme] || global.uniPlugin.defaultTheme
fxy060608's avatar
fxy060608 已提交
52 53 54 55 56 57 58 59 60 61 62
    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))
63 64 65 66 67 68 69 70
  },
  copyMiniProgramThemeJson (platformOptions, vueOptions) {
    platformOptions.themeLocation || (platformOptions.themeLocation = 'theme.json')
    return {
      from: path.resolve(process.env.UNI_INPUT_DIR, platformOptions.themeLocation),
      to: path.resolve(process.env.UNI_OUTPUT_DIR, platformOptions.themeLocation),
      transform: content => JSON.stringify(parseJson(content.toString(), true))
    }
fxy060608's avatar
fxy060608 已提交
71
  }
D
DCloud_LXH 已提交
72
}