theme.js 2.2 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

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

D
DCloud_LXH 已提交
9 10 11
let themeConfig = {}
let manifestJsonDarkmode = false

fxy060608's avatar
fxy060608 已提交
12 13 14 15 16
function parseThemeByJsonStr (jsonStr, keys, theme) {
  if (jsonStr.indexOf('@') === -1) {
    return jsonStr
  }
  keys.forEach(key => {
D
DCloud_LXH 已提交
17 18 19
    jsonStr = jsonStr.replace(new RegExp('@' + key, 'g'), $1 => {
      return theme[key] || $1
    })
fxy060608's avatar
fxy060608 已提交
20 21 22 23
  })
  return jsonStr
}

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

function darkmode () {
D
DCloud_LXH 已提交
30
  return manifestJsonDarkmode && !!(global.uniPlugin.options || {}).darkmode
fxy060608's avatar
fxy060608 已提交
31 32 33
}

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