uniapp.ts 4.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import { extend } from '@vue/shared'
D
DCloud_LXH 已提交
2 3
import type { Rule, Declaration, Plugin, Root } from 'postcss'
import postcss from 'postcss'
fxy060608's avatar
fxy060608 已提交
4 5 6 7 8 9
import selectorParser from 'postcss-selector-parser'
import {
  createRpx2Unit,
  defaultRpx2Unit,
  isBuiltInComponent,
  COMPONENT_SELECTOR_PREFIX,
D
DCloud_LXH 已提交
10
  normalizeStyles,
fxy060608's avatar
fxy060608 已提交
11 12
} from '@dcloudio/uni-shared'

D
DCloud_LXH 已提交
13 14 15 16 17 18
import {
  parsePagesJsonOnce,
  normalizeThemeConfigOnce,
  getPlatformManifestJsonOnce,
} from '../../json'

fxy060608's avatar
fxy060608 已提交
19
export interface UniAppCssProcessorOptions {
fxy060608's avatar
fxy060608 已提交
20 21 22 23 24
  unit?: string // 目标单位,默认rem
  unitRatio?: number // 单位转换比例,默认10/320
  unitPrecision?: number // 单位精度,默认5
}

25
const defaultUniAppCssProcessorOptions = extend({}, defaultRpx2Unit)
fxy060608's avatar
fxy060608 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

const BG_PROPS = [
  'background',
  'background-clip',
  'background-color',
  'background-image',
  'background-origin',
  'background-position',
  'background-repeat',
  'background-size',
  'background-attachment',
]

function transform(
  selector: selectorParser.Node,
41 42
  state: { bg: boolean },
  { rewriteTag }: TransformOptions
fxy060608's avatar
fxy060608 已提交
43 44 45 46
) {
  if (selector.type !== 'tag') {
    return
  }
47

fxy060608's avatar
fxy060608 已提交
48
  const { value } = selector
49 50 51
  selector.value = rewriteTag(value)
  if (value === 'page' && selector.value === 'uni-page-body') {
    state.bg = true
fxy060608's avatar
fxy060608 已提交
52 53 54 55 56 57 58 59 60 61 62
  }
}

function createBodyBackgroundRule(origRule: Rule) {
  const bgDecls: Declaration[] = []
  origRule.walkDecls((decl) => {
    if (BG_PROPS.indexOf(decl.prop) !== -1) {
      bgDecls.push(decl.clone())
    }
  })
  if (bgDecls.length) {
fxy060608's avatar
fxy060608 已提交
63
    const { rule } = require('postcss')
fxy060608's avatar
fxy060608 已提交
64 65 66 67
    origRule.after(rule({ selector: 'body' }).append(bgDecls))
  }
}

68 69 70 71 72 73 74
type RewriteTag = (tag: string) => string

interface TransformOptions {
  rewriteTag: RewriteTag
}

function walkRules(options: TransformOptions) {
fxy060608's avatar
fxy060608 已提交
75 76 77
  return (rule: Rule) => {
    const state = { bg: false }
    rule.selector = selectorParser((selectors) =>
78
      selectors.walk((selector) => transform(selector, state, options))
fxy060608's avatar
fxy060608 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    ).processSync(rule.selector)
    state.bg && createBodyBackgroundRule(rule)
  }
}

function walkDecls(rpx2unit: ReturnType<typeof createRpx2Unit>) {
  return (decl: Declaration) => {
    const { value } = decl
    if (value.indexOf('rpx') === -1 && value.indexOf('upx') === -1) {
      return
    }
    decl.value = rpx2unit(decl.value)
  }
}

D
DCloud_LXH 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
function darkmodeAtRule(root: Root, platform: UniApp.PLATFORM) {
  const pageJson = parsePagesJsonOnce(process.env.UNI_PLATFORM, platform)
  const filePath = root.source?.input.file || ''
  if (
    process.env.VUE_APP_DARK_MODE === 'true' &&
    filePath.indexOf('App.vue') !== -1
  ) {
    const pageBGC = (pageJson.globalStyle || {}).backgroundColor || ''
    if (pageBGC.indexOf('@') === 0) {
      ;['dark', 'light'].forEach((theme) => {
        const { backgroundColor } = normalizeStyles(
          { backgroundColor: pageBGC },
          normalizeThemeConfigOnce(getPlatformManifestJsonOnce()),
          theme as UniApp.ThemeMode
        )
        if (backgroundColor !== 'undefined') {
          const mediaRoot = postcss.parse(`
D
DCloud_LXH 已提交
111
            /* #ifndef APP-NVUE*/
D
DCloud_LXH 已提交
112 113 114 115 116 117
            @media (prefers-color-scheme: ${theme}) {
              body,
              uni-page-body {
                background-color: ${backgroundColor};
              }
            }
D
DCloud_LXH 已提交
118
            /* #endif */
D
DCloud_LXH 已提交
119 120 121 122 123 124 125 126
          `)
          root.nodes = [...mediaRoot.nodes, ...root.nodes]
        }
      })
    }
  }
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
const baiduTags: Record<string, string> = {
  navigator: 'nav',
}

function rewriteBaiduTags(tag: string) {
  return baiduTags[tag] || tag
}

function rewriteUniH5Tags(tag: string) {
  if (tag === 'page') {
    return 'uni-page-body'
  }
  if (isBuiltInComponent(tag)) {
    return COMPONENT_SELECTOR_PREFIX + tag
  }
  return tag
}

function rewriteUniAppTags(tag: string) {
  if (tag === 'page') {
    return 'body'
  }
  if (isBuiltInComponent(tag)) {
    return COMPONENT_SELECTOR_PREFIX + tag
  }
  return tag
}

const transforms: Record<string, RewriteTag | undefined> = {
  h5: rewriteUniH5Tags,
  app: rewriteUniAppTags,
  'mp-baidu': rewriteBaiduTags,
}

fxy060608's avatar
fxy060608 已提交
161
const uniapp = (opts?: UniAppCssProcessorOptions) => {
162 163
  const platform = process.env.UNI_PLATFORM
  const { unit, unitRatio, unitPrecision } = extend(
fxy060608's avatar
fxy060608 已提交
164 165
    {},
    defaultUniAppCssProcessorOptions,
fxy060608's avatar
fxy060608 已提交
166
    opts
fxy060608's avatar
fxy060608 已提交
167 168 169 170 171 172 173 174
  )
  const rpx2unit = createRpx2Unit(unit, unitRatio, unitPrecision)
  return {
    postcssPlugin: 'uni-app',
    prepare() {
      return {
        OnceExit(root) {
          root.walkDecls(walkDecls(rpx2unit))
175
          const rewriteTag = transforms[platform]
D
DCloud_LXH 已提交
176 177 178
          if (['h5', 'app'].includes(platform)) {
            darkmodeAtRule(root, platform)
          }
179 180 181 182 183 184 185
          if (rewriteTag) {
            root.walkRules(
              walkRules({
                rewriteTag,
              })
            )
          }
fxy060608's avatar
fxy060608 已提交
186 187 188 189 190 191 192
        },
      }
    },
  } as Plugin
}
uniapp.postcss = true
export default uniapp