@dcloudio/uni-template-compiler 2.0.1-33920220314003 → 2.0.1-34720220422002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,17 +5,25 @@ const deprecated = {
5
5
  }
6
6
  }
7
7
  module.exports = function parseEvent (el) {
8
- if (el.events) {
8
+ if (el.events || el.nativeEvents) {
9
9
  const {
10
10
  events: eventsMap
11
11
  } = deprecated
12
- Object.keys(el.events).forEach(name => {
13
- // 过时事件类型转换
14
- if (eventsMap[name]) {
15
- el.events[eventsMap[name]] = el.events[name]
16
- delete el.events[name]
17
- // warnLogs.add(`警告:事件${name}已过时,推荐使用${eventsMap[name]}代替`)
18
- }
19
- })
12
+ normalizeEvent(el.events, eventsMap)
13
+ normalizeEvent(el.nativeEvents, eventsMap)
20
14
  }
15
+ }
16
+
17
+ function normalizeEvent (events, eventsMap) {
18
+ if (!events) {
19
+ return
20
+ }
21
+ Object.keys(events).forEach(name => {
22
+ // 过时事件类型转换
23
+ if (eventsMap[name]) {
24
+ events[eventsMap[name]] = events[name]
25
+ delete events[name]
26
+ // warnLogs.add(`警告:事件${name}已过时,推荐使用${eventsMap[name]}代替`)
27
+ }
28
+ })
21
29
  }
package/lib/constants.js CHANGED
@@ -28,6 +28,7 @@ const INTERNAL_GET_EVENT = '__get_event'
28
28
  const INTERNAL_GET_REFS = '__get_refs'
29
29
  const INTERNAL_EVENT_PROXY = '__e'
30
30
  const INTERNAL_EVENT_LINK = '__l'
31
+ const INTERNAL_EVENT_WRAP = '__w'
31
32
 
32
33
  const ALLOWED_GLOBAL_OBJECT = [
33
34
  'Math',
@@ -63,6 +64,7 @@ module.exports = {
63
64
  ATTR_DATA_EVENT_OPTS: 'data-event-opts',
64
65
  ATTR_DATA_COM_TYPE: 'data-com-type',
65
66
  ATTR_DATA_EVENT_PARAMS: 'data-event-params',
67
+ ATTR_DATA_EVENT_LIST: 'data-event-list',
66
68
  ATTE_DATA_CUSTOM_HIDDEN: 'data-custom-hidden',
67
69
  INTERNAL_GET_ORIG,
68
70
  INTERNAL_GET_CLASS,
@@ -71,6 +73,7 @@ module.exports = {
71
73
  INTERNAL_GET_REFS,
72
74
  INTERNAL_EVENT_PROXY,
73
75
  INTERNAL_EVENT_LINK,
76
+ INTERNAL_EVENT_WRAP,
74
77
  INTERNAL_SET_MODEL,
75
78
  INTERNAL_SET_SYNC,
76
79
  METHOD_BUILT_IN: [
@@ -320,17 +320,21 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false,
320
320
  }
321
321
  }
322
322
 
323
+ const testCatch = function (stop) {
324
+ return function (path) {
325
+ // TODO 仅使用 name 容易误判
326
+ if (path.node.object.name === '$event' && path.node.property.name ===
327
+ 'stopPropagation') {
328
+ isCatch = true
329
+ stop && path.stop()
330
+ }
331
+ }
332
+ }
323
333
  // 如果 v-for 遍历的值为 数组、对象、方法 则进入底部匿名表达式处理
324
334
  if (anonymous && isSafeScoped(state)) {
325
335
  funcPath.traverse({
326
336
  noScope: true,
327
- MemberExpression (path) {
328
- if (path.node.object.name === '$event' && path.node.property.name ===
329
- 'stopPropagation') {
330
- isCatch = true
331
- path.stop()
332
- }
333
- },
337
+ MemberExpression: testCatch(),
334
338
  AssignmentExpression (path) { // "update:title": function($event) {title = $event}
335
339
  const left = path.node.left
336
340
  const right = path.node.right
@@ -368,6 +372,7 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false,
368
372
  if (anonymous) {
369
373
  // 处理复杂表达式中使用的局部变量(主要在v-for中定义)
370
374
  funcPath.traverse({
375
+ MemberExpression: testCatch(),
371
376
  Identifier (path) {
372
377
  const scope = path.scope
373
378
  const node = path.node
@@ -1,7 +1,13 @@
1
1
  const t = require('@babel/types')
2
2
 
3
3
  const {
4
- ATTR_DATA_COM_TYPE
4
+ METHOD_CREATE_ELEMENT,
5
+ ATTR_DATA_EVENT_OPTS,
6
+ ATTR_DATA_COM_TYPE,
7
+ ATTR_DATA_EVENT_LIST,
8
+ ATTR_DATA_EVENT_PARAMS,
9
+ ATTE_DATA_CUSTOM_HIDDEN,
10
+ INTERNAL_EVENT_WRAP
5
11
  } = require('../../../constants')
6
12
 
7
13
  const processRef = require('./ref')
@@ -37,7 +43,8 @@ module.exports = function traverseData (path, state, tagName) {
37
43
  })
38
44
 
39
45
  // 该组件是引入的小程序组件
40
- if (state.options.wxComponents[tagName]) {
46
+ const wxComponent = state.options.wxComponents[tagName]
47
+ if (wxComponent) {
41
48
  addAttrProperties.push(
42
49
  t.objectProperty(
43
50
  t.stringLiteral(ATTR_DATA_COM_TYPE),
@@ -45,12 +52,94 @@ module.exports = function traverseData (path, state, tagName) {
45
52
  )
46
53
  )
47
54
  if (state.options.platform.name === 'mp-alipay') {
48
- addAttrProperties.push(
49
- t.objectProperty(
50
- t.stringLiteral('ref'),
51
- t.stringLiteral('__r')
55
+ if (!wxComponent.startsWith('plugin://')) {
56
+ addAttrProperties.push(
57
+ t.objectProperty(
58
+ t.stringLiteral('ref'),
59
+ t.stringLiteral('__r')
60
+ )
52
61
  )
53
- )
62
+ }
63
+ const on = path.node.properties.find(prop => prop.key.name === 'on')
64
+ if (on) {
65
+ const properties = on.value.properties
66
+ const list = []
67
+ for (let index = 0; index < properties.length; index++) {
68
+ const element = properties[index]
69
+ if (element.value.value === '__e') {
70
+ list.push(element.key.value)
71
+ }
72
+ }
73
+ if (list.length) {
74
+ addAttrProperties.push(
75
+ t.objectProperty(
76
+ t.stringLiteral(ATTR_DATA_EVENT_LIST),
77
+ t.stringLiteral(list.join(','))
78
+ )
79
+ )
80
+ }
81
+ }
82
+ if (wxComponent.startsWith('plugin://')) {
83
+ const wrapperTag = 'plugin-wrapper'
84
+ const orgPath = path.parentPath
85
+ const orgNode = orgPath.node
86
+ const args = orgNode.arguments
87
+ const orgTag = args[0]
88
+ orgTag.$mpPlugin = true
89
+ args[0] = t.stringLiteral(wrapperTag)
90
+ const orgOptions = args[1]
91
+ const orgOptionsProps = orgOptions.properties
92
+ const targetAttrs = []
93
+ const targetOptionsProps = [
94
+ t.objectProperty(t.identifier('attrs'), t.objectExpression(targetAttrs))
95
+ ]
96
+ const uniAttrs = [
97
+ ATTR_DATA_EVENT_OPTS,
98
+ ATTR_DATA_COM_TYPE,
99
+ ATTR_DATA_EVENT_PARAMS,
100
+ ATTR_DATA_EVENT_LIST,
101
+ ATTE_DATA_CUSTOM_HIDDEN,
102
+ 'vue-id'
103
+ ]
104
+ for (let a = orgOptionsProps.length - 1; a >= 0; a--) {
105
+ const prop = orgOptionsProps[a]
106
+ if (prop.key.name === 'attrs') {
107
+ const attrs = prop.value.properties
108
+ for (let b = attrs.length - 1; b >= 0; b--) {
109
+ const element = attrs[b]
110
+ const key = element.key.value
111
+ if (!uniAttrs.includes(key)) {
112
+ attrs.splice(b, 1)
113
+ targetAttrs.push(element)
114
+ }
115
+ }
116
+ attrs.push(t.objectProperty(t.stringLiteral('onPluginWrap'), t.stringLiteral(INTERNAL_EVENT_WRAP)))
117
+ } else if (prop.key.name === 'on') {
118
+ const ons = prop.value.properties
119
+ ons.forEach(item => {
120
+ const attrs = path.node.properties.find(prop => prop.key.name === 'attrs').value.properties
121
+ const vueId = attrs.find(prop => prop.key.value === 'vue-id').value
122
+ const eventName = item.key.value
123
+ targetAttrs.push(t.objectProperty(t.stringLiteral(eventName), t.binaryExpression('+', t.stringLiteral(eventName), vueId)))
124
+ })
125
+ } else {
126
+ orgOptionsProps.splice(a, 1)
127
+ targetOptionsProps.push(prop)
128
+ }
129
+ }
130
+ const orgChild = args[2]
131
+ const targetOptions = t.objectExpression(targetOptionsProps)
132
+ targetOptions.$mpProcessed = true
133
+ const targetArguments = [
134
+ orgTag,
135
+ targetOptions
136
+ ]
137
+ if (orgChild) {
138
+ targetArguments.push(orgChild)
139
+ }
140
+ const targetNode = t.callExpression(t.identifier(METHOD_CREATE_ELEMENT), targetArguments)
141
+ args[2] = targetNode
142
+ }
54
143
  }
55
144
  }
56
145
 
@@ -167,7 +167,8 @@ module.exports = {
167
167
  tagNode.value = getComponentName(hyphenate(tagName))
168
168
 
169
169
  // 组件增加 vueId
170
- if (this.options.platform.isComponent(tagNode.value)) {
170
+ // 跳过支付宝插件组件
171
+ if (this.options.platform.isComponent(tagNode.value) && !tagNode.$mpPlugin) {
171
172
  addVueId(path, this)
172
173
  }
173
174
 
@@ -215,7 +216,11 @@ module.exports = {
215
216
  // event
216
217
  return path.skip()
217
218
  }
218
- path = path.findParent((path) => path.isLogicalExpression()) || path
219
+ let newPath = path
220
+ while (newPath) {
221
+ path = newPath
222
+ newPath = path.findParent((path) => path.isLogicalExpression())
223
+ }
219
224
  path.skip()
220
225
  if (path.findParent((path) => path.shouldSkip)) {
221
226
  return
@@ -250,6 +255,15 @@ module.exports = {
250
255
  t.isMemberExpression(callee) // message.split('').reverse().join('')
251
256
  ) {
252
257
  // Object.assign...
258
+ let newPath = path
259
+ while (newPath) {
260
+ path = newPath
261
+ newPath = path.findParent((path) => path.isLogicalExpression())
262
+ }
263
+ path.skip()
264
+ if (path.findParent((path) => path.shouldSkip)) {
265
+ return
266
+ }
253
267
  path.replaceWith(getMemberExpr(path, IDENTIFIER_GLOBAL, path.node, this))
254
268
  }
255
269
  },
@@ -1,524 +1,524 @@
1
- const path = require('path')
2
-
3
- const t = require('@babel/types')
4
- const babelTraverse = require('@babel/traverse').default
5
-
6
- const generate = require('./generate')
7
- const uniI18n = require('@dcloudio/uni-cli-i18n')
8
-
9
- const {
10
- genCode,
11
- getCode,
12
- getForKey,
13
- traverseKey,
14
- isComponent
15
- } = require('../util')
16
-
17
- const {
18
- ATTE_DATA_CUSTOM_HIDDEN
19
- } = require('../constants')
20
-
21
- module.exports = function traverse (ast, state = {}) {
22
- babelTraverse(ast, {
23
- WithStatement (path) {
24
- state.ast = traverseExpr(path.node.body.body[0].argument, state)
25
- }
26
- })
27
- initParent(state.ast)
28
- return state.ast
29
- }
30
-
31
- function initParent (ast, parentNode) {
32
- if (Array.isArray(ast)) {
33
- ast.forEach(node => initParent(node, parentNode))
34
- } else if (typeof ast === 'object') {
35
- ast.parent = parentNode
36
-
37
- const vueId = ast.$vueId
38
- if (vueId) {
39
- const vuePid = getVueParentId(parentNode)
40
- if (vuePid) {
41
- ast.attr['vue-id'] = genCode(
42
- t.binaryExpression(
43
- '+',
44
- t.binaryExpression(
45
- '+',
46
- t.parenthesizedExpression(vueId),
47
- t.stringLiteral(',')
48
- ),
49
- t.parenthesizedExpression(vuePid)
50
- )
51
- )
52
- }
53
- }
54
- initParent(ast.children, ast)
55
- }
56
- }
57
-
58
- function getVueParentId (parentNode) {
59
- if (!parentNode) {
60
- return
61
- }
62
- return parentNode.$vueId || getVueParentId(parentNode.parent)
63
- }
64
-
65
- function traverseExpr (exprNode, state) {
66
- if (t.isCallExpression(exprNode)) {
67
- return traverseCallExpr(exprNode, state)
68
- } else if (t.isConditionalExpression(exprNode)) {
69
- return traverseConditionalExpr(exprNode, state)
70
- } else if (t.isArrayExpression(exprNode)) {
71
- return traverseArrayExpression(exprNode, state)
72
- } else if (t.isIdentifier(exprNode) && exprNode.name === 'undefined') {
73
- return {
74
- type: 'block',
75
- attr: {},
76
- children: []
77
- }
78
- } else if (t.isUnaryExpression(exprNode) && exprNode.operator === 'void') {
79
- return false
80
- } else {
81
- throw new Error(`暂不支持 ${getCode(exprNode)} 语法`)
82
- }
83
- }
84
-
85
- const traverses = {
86
- _c: traverseCreateElement,
87
- _t: traverseRenderSlot,
88
- _l: traverseRenderList,
89
- _u: traverseResolveScopedSlots,
90
- _v: traverseCreateTextVNode,
91
- _e: traverseCreateEmptyVNode,
92
- _g: '暂不支持 v-on="$listeners" 用法',
93
- _b: '暂不支持 v-bind="" 用法'
94
- }
95
-
96
- function traverseCallExpr (callExprNode, state) {
97
- const traverse = traverses[callExprNode.callee.name]
98
- if (!traverse) {
99
- throw new Error(
100
- `CallExpression ${callExprNode.callee.name} is not yet implemented`
101
- )
102
- } else if (typeof traverse === 'string') {
103
- throw new Error(traverse)
104
- }
105
-
106
- return traverse(callExprNode, state)
107
- }
108
-
109
- function traverseConditionalExpr (conditionalExprNode, state) {
110
- const prefix = state.options.platform.directive
111
- const ret = [{
112
- type: 'block',
113
- attr: {
114
- [prefix + 'if']: genCode(conditionalExprNode.test)
115
- },
116
- children: normalizeChildren(
117
- traverseExpr(conditionalExprNode.consequent, state)
118
- )
119
- }]
120
- if (
121
- !(
122
- t.isCallExpression(conditionalExprNode.alternate) &&
123
- t.isIdentifier(conditionalExprNode.alternate.callee) &&
124
- conditionalExprNode.alternate.callee.name === '_e'
125
- )
126
- ) {
127
- // test?_c():_e()
128
- ret.push({
129
- type: 'block',
130
- attr: {
131
- [prefix + 'else']: ''
132
- },
133
- children: normalizeChildren(
134
- traverseExpr(conditionalExprNode.alternate, state)
135
- )
136
- })
137
- }
138
- return ret
139
- }
140
-
141
- function traverseCreateElement (callExprNode, state) {
142
- const args = callExprNode.arguments
143
- const tagNode = args[0]
144
- if (!t.isStringLiteral(tagNode)) {
145
- throw new Error(`暂不支持动态组件[${tagNode.name}]`)
146
- }
147
-
148
- const node = {
149
- type: tagNode.value,
150
- attr: {},
151
- children: []
152
- }
153
-
154
- if (args.length < 2) {
155
- return node
156
- }
157
-
158
- const dataNodeOrChildNodes = args[1]
159
- if (t.isObjectExpression(dataNodeOrChildNodes)) {
160
- Object.assign(node.attr, traverseDataNode(dataNodeOrChildNodes, state, node))
161
- } else {
162
- node.children = normalizeChildren(traverseExpr(dataNodeOrChildNodes, state))
163
- }
164
- if (args.length < 3) {
165
- return node
166
- }
167
- const childNodes = args[2]
168
- if (!t.isNumericLiteral(childNodes)) {
169
- if (node.children && node.children.length) {
170
- node.children = node.children.concat(normalizeChildren(traverseExpr(childNodes, state)))
171
- } else {
172
- node.children = normalizeChildren(traverseExpr(childNodes, state))
173
- }
174
- }
175
- return node
176
- }
177
-
178
- function traverseDataNode (dataNode, state, node) {
179
- const ret = {}
180
- const specialEvents = state.options.platform.specialEvents[node.type] || {}
181
- const specialEventNames = Object.keys(specialEvents)
182
- dataNode.properties.forEach(property => {
183
- switch (property.key.name) {
184
- case 'slot':
185
- ret.slot = genCode(property.value)
186
- break
187
- case 'scopedSlots': // Vue 2.6
188
- property.value.$node = node
189
- node.children = normalizeChildren(traverseExpr(property.value, state))
190
- break
191
- case 'attrs':
192
- case 'domProps':
193
- case 'on':
194
- case 'nativeOn':
195
- property.value.properties.forEach(attrProperty => {
196
- if (attrProperty.key.value === 'vue-id') { // initParent 时再处理 vue-id
197
- node.$vueId = attrProperty.value
198
- ret[attrProperty.key.value] = genCode(attrProperty.value)
199
- } else {
200
- if (specialEventNames.includes(attrProperty.key.value)) {
201
- if (t.isIdentifier(attrProperty.value)) {
202
- ret[specialEvents[attrProperty.key.value]] = attrProperty.value.name
203
- }
204
- } else {
205
- ret[attrProperty.key.value] = genCode(attrProperty.value)
206
- }
207
- }
208
- })
209
- break
210
- case 'class':
211
- case 'staticClass':
212
- ret.class = genCode(property.value)
213
- break
214
- case 'style':
215
- case 'staticStyle':
216
- ret.style = genCode(property.value)
217
- break
218
- case 'directives':
219
- property.value.elements.find(objectExpression => {
220
- if (t.isObjectExpression(objectExpression)) {
221
- const nameProperty = objectExpression.properties[0]
222
- const isShowDir =
223
- nameProperty &&
224
- nameProperty.key.name === 'name' &&
225
- t.isStringLiteral(nameProperty.value) &&
226
- nameProperty.value.value === 'show'
227
- if (isShowDir) {
228
- objectExpression.properties.find(valueProperty => {
229
- const isValue = valueProperty.key.name === 'value'
230
- if (isValue) {
231
- let key
232
- // 自定义组件不支持 hidden 属性
233
- const platform = state.options.platform.name
234
- const platforms = ['mp-weixin', 'mp-qq', 'mp-jd', 'mp-toutiao', 'mp-lark']
235
- if (isComponent(node.type) && platforms.includes(platform)) {
236
- // 字节跳动|飞书小程序自定义属性不会反应在DOM上,只能使用事件格式
237
- key = `${platform === 'mp-toutiao' || platform === 'mp-lark' ? 'bind:-' : ''}${ATTE_DATA_CUSTOM_HIDDEN}`
238
- } else {
239
- key = 'hidden'
240
- }
241
- ret[key] = genCode(valueProperty.value, false, true)
242
- }
243
- return isValue
244
- })
245
- }
246
- return isShowDir
247
- }
248
- })
249
- break
250
- }
251
- })
252
- return ret
253
- }
254
-
255
- function normalizeChildren (nodes) {
256
- if (!Array.isArray(nodes)) {
257
- nodes = [nodes]
258
- }
259
- return nodes.filter(node => {
260
- if (typeof node === 'string' && !node.trim()) {
261
- return false
262
- }
263
- return true
264
- })
265
- }
266
-
267
- function traverseArrayExpression (arrayExprNodes, state) {
268
- return arrayExprNodes.elements.reduce((nodes, exprNode) => {
269
- return nodes.concat(traverseExpr(exprNode, state))
270
- }, [])
271
- }
272
-
273
- function genSlotNode (slotName, slotNode, fallbackNodes, state) {
274
- if (!fallbackNodes || t.isNullLiteral(fallbackNodes)) {
275
- return slotNode
276
- }
277
- // 支付宝小程序默认插槽为 $default
278
- if (state.options.platform.name === 'mp-alipay') {
279
- slotName = slotName === 'default' ? '$default' : slotName
280
- }
281
- const prefix = state.options.platform.directive
282
- return [{
283
- type: 'block',
284
- attr: {
285
- [prefix + 'if']: '{{$slots.' + slotName + '}}'
286
- },
287
- children: [].concat(slotNode)
288
- }, {
289
- type: 'block',
290
- attr: {
291
- [prefix + 'else']: ''
292
- },
293
- children: normalizeChildren(
294
- traverseExpr(fallbackNodes, state)
295
- )
296
- }]
297
- }
298
-
299
- function traverseRenderSlot (callExprNode, state) {
300
- if (!t.isStringLiteral(callExprNode.arguments[0])) {
301
- state.errors.add(uniI18n.__('templateCompiler.notSupportDynamicSlotName', { 0: 'v-slot' }))
302
- return
303
- }
304
-
305
- const slotName = callExprNode.arguments[0].value
306
-
307
- let deleteSlotName = false // 标记是否组件 slot 手动指定了 name="default"
308
- if (state.options.scopedSlotsCompiler !== 'augmented' && callExprNode.arguments.length > 2) { // 作用域插槽
309
- const props = {}
310
- callExprNode.arguments[2].properties.forEach(property => {
311
- props[property.key.value] = genCode(property.value)
312
- })
313
- deleteSlotName = props.SLOT_DEFAULT && Object.keys(props).length === 1
314
- if (!deleteSlotName) {
315
- delete props.SLOT_DEFAULT
316
- return genSlotNode(
317
- slotName,
318
- state.options.platform.createScopedSlots(slotName, props, state),
319
- callExprNode.arguments[1],
320
- state
321
- )
322
- }
323
- }
324
-
325
- const node = {
326
- type: 'slot',
327
- attr: {
328
- name: slotName
329
- },
330
- children: []
331
- }
332
-
333
- if (deleteSlotName) {
334
- delete node.attr.name
335
- }
336
-
337
- return genSlotNode(slotName, node, callExprNode.arguments[1], state)
338
- }
339
-
340
- function traverseResolveScopedSlots (callExprNode, state) {
341
- function single (children, slotName, ignore) {
342
- if (Array.isArray(children) && children.length === 1) {
343
- const child = children[0]
344
- if (!child.type) {
345
- return
346
- }
347
- if (ignore.includes(child.type)) {
348
- return single(child.children, slotName, ignore)
349
- }
350
- child.attr = child.attr || {}
351
- child.attr.slot = slotName
352
- return true
353
- }
354
- }
355
- return callExprNode.arguments[0].elements.map(slotNode => {
356
- let keyProperty = false
357
- let fnProperty = false
358
- let proxyProperty = false
359
- slotNode.properties.forEach(property => {
360
- switch (property.key.name) {
361
- case 'key':
362
- keyProperty = property
363
- break
364
- case 'fn':
365
- fnProperty = property
366
- break
367
- case 'proxy':
368
- proxyProperty = property
369
- }
370
- })
371
- const slotName = keyProperty.value.value
372
- const returnExprNodes = fnProperty.value.body.body[0].argument
373
- const parentNode = callExprNode.$node
374
- if (slotNode.scopedSlotsCompiler !== 'augmented' && !proxyProperty) {
375
- const resourcePath = state.options.resourcePath
376
- const ownerName = path.basename(resourcePath, path.extname(resourcePath))
377
-
378
- const parentName = parentNode.type
379
-
380
- const paramExprNode = fnProperty.value.params[0]
381
- return state.options.platform.resolveScopedSlots(
382
- slotName, {
383
- genCode,
384
- generate,
385
- ownerName,
386
- parentName,
387
- parentNode,
388
- resourcePath,
389
- paramExprNode,
390
- returnExprNodes,
391
- traverseExpr: function (exprNode, state) {
392
- const ast = traverseExpr(exprNode, state)
393
- initParent(ast)
394
- return ast
395
- },
396
- normalizeChildren
397
- },
398
- state
399
- )
400
- }
401
- if (state.options.scopedSlotsCompiler === 'auto' && slotNode.scopedSlotsCompiler === 'augmented') {
402
- parentNode.attr['scoped-slots-compiler'] = 'augmented'
403
- }
404
- const children = normalizeChildren(traverseExpr(returnExprNodes, state))
405
- // 除百度、字节外其他小程序仅默认插槽可以支持多个节点
406
- if (single(children, slotName, ['template', 'block'])) {
407
- return children[0]
408
- }
409
- return {
410
- type: 'block',
411
- attr: {
412
- slot: slotName
413
- },
414
- children
415
- }
416
- })
417
- }
418
-
419
- function traverseRenderList (callExprNode, state) {
420
- const params = callExprNode.arguments[1].params
421
- const forItem = params.length > 0 ? params[0].name : 'item'
422
- const forIndex = params.length > 1 ? params[1].name : ''
423
-
424
- const forReturnStatementArgument =
425
- callExprNode.arguments[1].body.body[0].argument
426
-
427
- const forKey = traverseKey(forReturnStatementArgument, state)
428
-
429
- const prefix = state.options.platform.directive
430
-
431
- const isBaidu = state.options.platform.name === 'mp-baidu'
432
- let forValue = genCode(callExprNode.arguments[0], isBaidu)
433
-
434
- if (isBaidu && forKey) {
435
- forValue += ` trackBy ${getForKey(forKey, forIndex, state)}`
436
- }
437
-
438
- const attr = {
439
- [prefix + 'for']: forValue,
440
- [prefix + 'for-item']: forItem
441
- }
442
-
443
- if (forIndex) {
444
- attr[prefix + 'for-index'] = forIndex
445
- }
446
-
447
- if (forKey && !isBaidu) {
448
- const key = getForKey(forKey, forIndex, state)
449
- if (key) {
450
- attr[prefix + 'key'] = key
451
- }
452
- }
453
-
454
- const children = traverseExpr(forReturnStatementArgument, state)
455
- // 支付宝小程序在 block 标签上使用 key 时顺序不能保障
456
- if (state.options.platform.name === 'mp-alipay' && t.isCallExpression(forReturnStatementArgument) && children &&
457
- children.type) {
458
- children.attr = children.attr || {}
459
- Object.assign(children.attr, attr)
460
- return children
461
- }
462
- return {
463
- type: 'block',
464
- attr,
465
- children: normalizeChildren(children)
466
- }
467
- }
468
-
469
- function getLeftStringLiteral (expr) {
470
- if (t.isBinaryExpression(expr) && !expr.$toString) {
471
- return getLeftStringLiteral(expr.left)
472
- } else if (t.isStringLiteral(expr)) {
473
- return expr
474
- }
475
- }
476
-
477
- function trim (text, type) {
478
- // TODO 保留换行符?
479
- if (type === 'left') {
480
- text = text.trimLeft()
481
- } else if (type === 'right') {
482
- text = text.trimRight()
483
- } else {
484
- text = text.trim()
485
- }
486
- return text
487
- }
488
-
489
- function traverseCreateTextVNode (callExprNode, state) {
490
- // trimStart|Left and trimEnd|End
491
- const arg = callExprNode.arguments[0]
492
- if (t.isStringLiteral(arg)) {
493
- arg.value = trim(arg.value)
494
- } else if (t.isBinaryExpression(arg) && !arg.$toString) { // 非_s()
495
- // right
496
- const right = arg.right
497
- if (t.isStringLiteral(right)) {
498
- right.value = trim(right.value, 'right')
499
- }
500
- // left
501
- const left = getLeftStringLiteral(arg.left)
502
- if (left && left.value) {
503
- left.value = trim(left.value, 'left')
504
- }
505
- }
506
- if (
507
- state.options.platform.name === 'mp-baidu' ||
508
- state.options.platform.name === 'mp-qq'
509
- ) {
510
- const code = genCode(arg, false, false, false)
511
- if (code.indexOf('{{') === 0) {
512
- if (state.options.platform.name === 'mp-qq') { // 似乎百度也可以走该逻辑, 为了稳定性,仅限 qq
513
- return code.replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t')
514
- }
515
- return code.replace(/([^\\])\\n/g, '$1\\\\n').replace(/([^\\])\\t/g, '$1\\\\t')
516
- }
517
- return code
518
- }
519
- return genCode(arg, false, false, false).replace(/\\\\n/g, '\\n')
520
- }
521
-
522
- function traverseCreateEmptyVNode (callExprNode, state) {
523
- return ''
524
- }
1
+ const path = require('path')
2
+
3
+ const t = require('@babel/types')
4
+ const babelTraverse = require('@babel/traverse').default
5
+
6
+ const generate = require('./generate')
7
+ const uniI18n = require('@dcloudio/uni-cli-i18n')
8
+
9
+ const {
10
+ genCode,
11
+ getCode,
12
+ getForKey,
13
+ traverseKey,
14
+ isComponent
15
+ } = require('../util')
16
+
17
+ const {
18
+ ATTE_DATA_CUSTOM_HIDDEN
19
+ } = require('../constants')
20
+
21
+ module.exports = function traverse (ast, state = {}) {
22
+ babelTraverse(ast, {
23
+ WithStatement (path) {
24
+ state.ast = traverseExpr(path.node.body.body[0].argument, state)
25
+ }
26
+ })
27
+ initParent(state.ast)
28
+ return state.ast
29
+ }
30
+
31
+ function initParent (ast, parentNode) {
32
+ if (Array.isArray(ast)) {
33
+ ast.forEach(node => initParent(node, parentNode))
34
+ } else if (typeof ast === 'object') {
35
+ ast.parent = parentNode
36
+
37
+ const vueId = ast.$vueId
38
+ if (vueId) {
39
+ const vuePid = getVueParentId(parentNode)
40
+ if (vuePid) {
41
+ ast.attr['vue-id'] = genCode(
42
+ t.binaryExpression(
43
+ '+',
44
+ t.binaryExpression(
45
+ '+',
46
+ t.parenthesizedExpression(vueId),
47
+ t.stringLiteral(',')
48
+ ),
49
+ t.parenthesizedExpression(vuePid)
50
+ )
51
+ )
52
+ }
53
+ }
54
+ initParent(ast.children, ast)
55
+ }
56
+ }
57
+
58
+ function getVueParentId (parentNode) {
59
+ if (!parentNode) {
60
+ return
61
+ }
62
+ return parentNode.$vueId || getVueParentId(parentNode.parent)
63
+ }
64
+
65
+ function traverseExpr (exprNode, state) {
66
+ if (t.isCallExpression(exprNode)) {
67
+ return traverseCallExpr(exprNode, state)
68
+ } else if (t.isConditionalExpression(exprNode)) {
69
+ return traverseConditionalExpr(exprNode, state)
70
+ } else if (t.isArrayExpression(exprNode)) {
71
+ return traverseArrayExpression(exprNode, state)
72
+ } else if (t.isIdentifier(exprNode) && exprNode.name === 'undefined') {
73
+ return {
74
+ type: 'block',
75
+ attr: {},
76
+ children: []
77
+ }
78
+ } else if (t.isUnaryExpression(exprNode) && exprNode.operator === 'void') {
79
+ return false
80
+ } else {
81
+ throw new Error(`暂不支持 ${getCode(exprNode)} 语法`)
82
+ }
83
+ }
84
+
85
+ const traverses = {
86
+ _c: traverseCreateElement,
87
+ _t: traverseRenderSlot,
88
+ _l: traverseRenderList,
89
+ _u: traverseResolveScopedSlots,
90
+ _v: traverseCreateTextVNode,
91
+ _e: traverseCreateEmptyVNode,
92
+ _g: '暂不支持 v-on="$listeners" 用法',
93
+ _b: '暂不支持 v-bind="" 用法'
94
+ }
95
+
96
+ function traverseCallExpr (callExprNode, state) {
97
+ const traverse = traverses[callExprNode.callee.name]
98
+ if (!traverse) {
99
+ throw new Error(
100
+ `CallExpression ${callExprNode.callee.name} is not yet implemented`
101
+ )
102
+ } else if (typeof traverse === 'string') {
103
+ throw new Error(traverse)
104
+ }
105
+
106
+ return traverse(callExprNode, state)
107
+ }
108
+
109
+ function traverseConditionalExpr (conditionalExprNode, state) {
110
+ const prefix = state.options.platform.directive
111
+ const ret = [{
112
+ type: 'block',
113
+ attr: {
114
+ [prefix + 'if']: genCode(conditionalExprNode.test)
115
+ },
116
+ children: normalizeChildren(
117
+ traverseExpr(conditionalExprNode.consequent, state)
118
+ )
119
+ }]
120
+ if (
121
+ !(
122
+ t.isCallExpression(conditionalExprNode.alternate) &&
123
+ t.isIdentifier(conditionalExprNode.alternate.callee) &&
124
+ conditionalExprNode.alternate.callee.name === '_e'
125
+ )
126
+ ) {
127
+ // test?_c():_e()
128
+ ret.push({
129
+ type: 'block',
130
+ attr: {
131
+ [prefix + 'else']: ''
132
+ },
133
+ children: normalizeChildren(
134
+ traverseExpr(conditionalExprNode.alternate, state)
135
+ )
136
+ })
137
+ }
138
+ return ret
139
+ }
140
+
141
+ function traverseCreateElement (callExprNode, state) {
142
+ const args = callExprNode.arguments
143
+ const tagNode = args[0]
144
+ if (!t.isStringLiteral(tagNode)) {
145
+ throw new Error(`暂不支持动态组件[${tagNode.name}]`)
146
+ }
147
+
148
+ const node = {
149
+ type: tagNode.value,
150
+ attr: {},
151
+ children: []
152
+ }
153
+
154
+ if (args.length < 2) {
155
+ return node
156
+ }
157
+
158
+ const dataNodeOrChildNodes = args[1]
159
+ if (t.isObjectExpression(dataNodeOrChildNodes)) {
160
+ Object.assign(node.attr, traverseDataNode(dataNodeOrChildNodes, state, node))
161
+ } else {
162
+ node.children = normalizeChildren(traverseExpr(dataNodeOrChildNodes, state))
163
+ }
164
+ if (args.length < 3) {
165
+ return node
166
+ }
167
+ const childNodes = args[2]
168
+ if (!t.isNumericLiteral(childNodes)) {
169
+ if (node.children && node.children.length) {
170
+ node.children = node.children.concat(normalizeChildren(traverseExpr(childNodes, state)))
171
+ } else {
172
+ node.children = normalizeChildren(traverseExpr(childNodes, state))
173
+ }
174
+ }
175
+ return node
176
+ }
177
+
178
+ function traverseDataNode (dataNode, state, node) {
179
+ const ret = {}
180
+ const specialEvents = state.options.platform.specialEvents[node.type] || {}
181
+ const specialEventNames = Object.keys(specialEvents)
182
+ dataNode.properties.forEach(property => {
183
+ switch (property.key.name) {
184
+ case 'slot':
185
+ ret.slot = genCode(property.value)
186
+ break
187
+ case 'scopedSlots': // Vue 2.6
188
+ property.value.$node = node
189
+ node.children = normalizeChildren(traverseExpr(property.value, state))
190
+ break
191
+ case 'attrs':
192
+ case 'domProps':
193
+ case 'on':
194
+ case 'nativeOn':
195
+ property.value.properties.forEach(attrProperty => {
196
+ if (attrProperty.key.value === 'vue-id') { // initParent 时再处理 vue-id
197
+ node.$vueId = attrProperty.value
198
+ ret[attrProperty.key.value] = genCode(attrProperty.value)
199
+ } else {
200
+ if (specialEventNames.includes(attrProperty.key.value)) {
201
+ if (t.isIdentifier(attrProperty.value)) {
202
+ ret[specialEvents[attrProperty.key.value]] = attrProperty.value.name
203
+ }
204
+ } else {
205
+ ret[attrProperty.key.value] = genCode(attrProperty.value)
206
+ }
207
+ }
208
+ })
209
+ break
210
+ case 'class':
211
+ case 'staticClass':
212
+ ret.class = genCode(property.value)
213
+ break
214
+ case 'style':
215
+ case 'staticStyle':
216
+ ret.style = genCode(property.value)
217
+ break
218
+ case 'directives':
219
+ property.value.elements.find(objectExpression => {
220
+ if (t.isObjectExpression(objectExpression)) {
221
+ const nameProperty = objectExpression.properties[0]
222
+ const isShowDir =
223
+ nameProperty &&
224
+ nameProperty.key.name === 'name' &&
225
+ t.isStringLiteral(nameProperty.value) &&
226
+ nameProperty.value.value === 'show'
227
+ if (isShowDir) {
228
+ objectExpression.properties.find(valueProperty => {
229
+ const isValue = valueProperty.key.name === 'value'
230
+ if (isValue) {
231
+ let key
232
+ // 自定义组件不支持 hidden 属性
233
+ const platform = state.options.platform.name
234
+ const platforms = ['mp-weixin', 'mp-qq', 'mp-jd', 'mp-xhs', 'mp-toutiao', 'mp-lark']
235
+ if (isComponent(node.type) && platforms.includes(platform)) {
236
+ // 字节跳动|飞书小程序自定义属性不会反应在DOM上,只能使用事件格式
237
+ key = `${platform === 'mp-toutiao' || platform === 'mp-lark' ? 'bind:-' : ''}${ATTE_DATA_CUSTOM_HIDDEN}`
238
+ } else {
239
+ key = 'hidden'
240
+ }
241
+ ret[key] = genCode(valueProperty.value, false, true)
242
+ }
243
+ return isValue
244
+ })
245
+ }
246
+ return isShowDir
247
+ }
248
+ })
249
+ break
250
+ }
251
+ })
252
+ return ret
253
+ }
254
+
255
+ function normalizeChildren (nodes) {
256
+ if (!Array.isArray(nodes)) {
257
+ nodes = [nodes]
258
+ }
259
+ return nodes.filter(node => {
260
+ if (typeof node === 'string' && !node.trim()) {
261
+ return false
262
+ }
263
+ return true
264
+ })
265
+ }
266
+
267
+ function traverseArrayExpression (arrayExprNodes, state) {
268
+ return arrayExprNodes.elements.reduce((nodes, exprNode) => {
269
+ return nodes.concat(traverseExpr(exprNode, state))
270
+ }, [])
271
+ }
272
+
273
+ function genSlotNode (slotName, slotNode, fallbackNodes, state) {
274
+ if (!fallbackNodes || t.isNullLiteral(fallbackNodes)) {
275
+ return slotNode
276
+ }
277
+ // 支付宝小程序默认插槽为 $default
278
+ if (state.options.platform.name === 'mp-alipay') {
279
+ slotName = slotName === 'default' ? '$default' : slotName
280
+ }
281
+ const prefix = state.options.platform.directive
282
+ return [{
283
+ type: 'block',
284
+ attr: {
285
+ [prefix + 'if']: '{{$slots.' + slotName + '}}'
286
+ },
287
+ children: [].concat(slotNode)
288
+ }, {
289
+ type: 'block',
290
+ attr: {
291
+ [prefix + 'else']: ''
292
+ },
293
+ children: normalizeChildren(
294
+ traverseExpr(fallbackNodes, state)
295
+ )
296
+ }]
297
+ }
298
+
299
+ function traverseRenderSlot (callExprNode, state) {
300
+ if (!t.isStringLiteral(callExprNode.arguments[0])) {
301
+ state.errors.add(uniI18n.__('templateCompiler.notSupportDynamicSlotName', { 0: 'v-slot' }))
302
+ return
303
+ }
304
+
305
+ const slotName = callExprNode.arguments[0].value
306
+
307
+ let deleteSlotName = false // 标记是否组件 slot 手动指定了 name="default"
308
+ if (state.options.scopedSlotsCompiler !== 'augmented' && callExprNode.arguments.length > 2) { // 作用域插槽
309
+ const props = {}
310
+ callExprNode.arguments[2].properties.forEach(property => {
311
+ props[property.key.value] = genCode(property.value)
312
+ })
313
+ deleteSlotName = props.SLOT_DEFAULT && Object.keys(props).length === 1
314
+ if (!deleteSlotName) {
315
+ delete props.SLOT_DEFAULT
316
+ return genSlotNode(
317
+ slotName,
318
+ state.options.platform.createScopedSlots(slotName, props, state),
319
+ callExprNode.arguments[1],
320
+ state
321
+ )
322
+ }
323
+ }
324
+
325
+ const node = {
326
+ type: 'slot',
327
+ attr: {
328
+ name: slotName
329
+ },
330
+ children: []
331
+ }
332
+
333
+ if (deleteSlotName) {
334
+ delete node.attr.name
335
+ }
336
+
337
+ return genSlotNode(slotName, node, callExprNode.arguments[1], state)
338
+ }
339
+
340
+ function traverseResolveScopedSlots (callExprNode, state) {
341
+ function single (children, slotName, ignore) {
342
+ if (Array.isArray(children) && children.length === 1) {
343
+ const child = children[0]
344
+ if (!child.type) {
345
+ return
346
+ }
347
+ if (ignore.includes(child.type)) {
348
+ return single(child.children, slotName, ignore)
349
+ }
350
+ child.attr = child.attr || {}
351
+ child.attr.slot = slotName
352
+ return true
353
+ }
354
+ }
355
+ return callExprNode.arguments[0].elements.map(slotNode => {
356
+ let keyProperty = false
357
+ let fnProperty = false
358
+ let proxyProperty = false
359
+ slotNode.properties.forEach(property => {
360
+ switch (property.key.name) {
361
+ case 'key':
362
+ keyProperty = property
363
+ break
364
+ case 'fn':
365
+ fnProperty = property
366
+ break
367
+ case 'proxy':
368
+ proxyProperty = property
369
+ }
370
+ })
371
+ const slotName = keyProperty.value.value
372
+ const returnExprNodes = fnProperty.value.body.body[0].argument
373
+ const parentNode = callExprNode.$node
374
+ if (slotNode.scopedSlotsCompiler !== 'augmented' && !proxyProperty) {
375
+ const resourcePath = state.options.resourcePath
376
+ const ownerName = path.basename(resourcePath, path.extname(resourcePath))
377
+
378
+ const parentName = parentNode.type
379
+
380
+ const paramExprNode = fnProperty.value.params[0]
381
+ return state.options.platform.resolveScopedSlots(
382
+ slotName, {
383
+ genCode,
384
+ generate,
385
+ ownerName,
386
+ parentName,
387
+ parentNode,
388
+ resourcePath,
389
+ paramExprNode,
390
+ returnExprNodes,
391
+ traverseExpr: function (exprNode, state) {
392
+ const ast = traverseExpr(exprNode, state)
393
+ initParent(ast)
394
+ return ast
395
+ },
396
+ normalizeChildren
397
+ },
398
+ state
399
+ )
400
+ }
401
+ if (state.options.scopedSlotsCompiler === 'auto' && slotNode.scopedSlotsCompiler === 'augmented') {
402
+ parentNode.attr['scoped-slots-compiler'] = 'augmented'
403
+ }
404
+ const children = normalizeChildren(traverseExpr(returnExprNodes, state))
405
+ // 除百度、字节外其他小程序仅默认插槽可以支持多个节点
406
+ if (single(children, slotName, ['template', 'block'])) {
407
+ return children[0]
408
+ }
409
+ return {
410
+ type: 'block',
411
+ attr: {
412
+ slot: slotName
413
+ },
414
+ children
415
+ }
416
+ })
417
+ }
418
+
419
+ function traverseRenderList (callExprNode, state) {
420
+ const params = callExprNode.arguments[1].params
421
+ const forItem = params.length > 0 ? params[0].name : 'item'
422
+ const forIndex = params.length > 1 ? params[1].name : ''
423
+
424
+ const forReturnStatementArgument =
425
+ callExprNode.arguments[1].body.body[0].argument
426
+
427
+ const forKey = traverseKey(forReturnStatementArgument, state)
428
+
429
+ const prefix = state.options.platform.directive
430
+
431
+ const isBaidu = state.options.platform.name === 'mp-baidu'
432
+ let forValue = genCode(callExprNode.arguments[0], isBaidu)
433
+
434
+ if (isBaidu && forKey) {
435
+ forValue += ` trackBy ${getForKey(forKey, forIndex, state)}`
436
+ }
437
+
438
+ const attr = {
439
+ [prefix + 'for']: forValue,
440
+ [prefix + 'for-item']: forItem
441
+ }
442
+
443
+ if (forIndex) {
444
+ attr[prefix + 'for-index'] = forIndex
445
+ }
446
+
447
+ if (forKey && !isBaidu) {
448
+ const key = getForKey(forKey, forIndex, state)
449
+ if (key) {
450
+ attr[prefix + 'key'] = key
451
+ }
452
+ }
453
+
454
+ const children = traverseExpr(forReturnStatementArgument, state)
455
+ // 支付宝小程序在 block 标签上使用 key 时顺序不能保障
456
+ if (state.options.platform.name === 'mp-alipay' && t.isCallExpression(forReturnStatementArgument) && children &&
457
+ children.type) {
458
+ children.attr = children.attr || {}
459
+ Object.assign(children.attr, attr)
460
+ return children
461
+ }
462
+ return {
463
+ type: 'block',
464
+ attr,
465
+ children: normalizeChildren(children)
466
+ }
467
+ }
468
+
469
+ function getLeftStringLiteral (expr) {
470
+ if (t.isBinaryExpression(expr) && !expr.$toString) {
471
+ return getLeftStringLiteral(expr.left)
472
+ } else if (t.isStringLiteral(expr)) {
473
+ return expr
474
+ }
475
+ }
476
+
477
+ function trim (text, type) {
478
+ // TODO 保留换行符?
479
+ if (type === 'left') {
480
+ text = text.trimLeft()
481
+ } else if (type === 'right') {
482
+ text = text.trimRight()
483
+ } else {
484
+ text = text.trim()
485
+ }
486
+ return text
487
+ }
488
+
489
+ function traverseCreateTextVNode (callExprNode, state) {
490
+ // trimStart|Left and trimEnd|End
491
+ const arg = callExprNode.arguments[0]
492
+ if (t.isStringLiteral(arg)) {
493
+ arg.value = trim(arg.value)
494
+ } else if (t.isBinaryExpression(arg) && !arg.$toString) { // 非_s()
495
+ // right
496
+ const right = arg.right
497
+ if (t.isStringLiteral(right)) {
498
+ right.value = trim(right.value, 'right')
499
+ }
500
+ // left
501
+ const left = getLeftStringLiteral(arg.left)
502
+ if (left && left.value) {
503
+ left.value = trim(left.value, 'left')
504
+ }
505
+ }
506
+ if (
507
+ state.options.platform.name === 'mp-baidu' ||
508
+ state.options.platform.name === 'mp-qq'
509
+ ) {
510
+ const code = genCode(arg, false, false, false)
511
+ if (code.indexOf('{{') === 0) {
512
+ if (state.options.platform.name === 'mp-qq') { // 似乎百度也可以走该逻辑, 为了稳定性,仅限 qq
513
+ return code.replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t')
514
+ }
515
+ return code.replace(/([^\\])\\n/g, '$1\\\\n').replace(/([^\\])\\t/g, '$1\\\\t')
516
+ }
517
+ return code
518
+ }
519
+ return genCode(arg, false, false, false).replace(/\\\\n/g, '\\n')
520
+ }
521
+
522
+ function traverseCreateEmptyVNode (callExprNode, state) {
523
+ return ''
524
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dcloudio/uni-template-compiler",
3
- "version": "2.0.1-33920220314003",
3
+ "version": "2.0.1-34720220422002",
4
4
  "description": "uni-template-compiler",
5
5
  "main": "lib/index.js",
6
6
  "repository": {
@@ -22,5 +22,5 @@
22
22
  "@babel/types": "^7.3.3",
23
23
  "vue-template-compiler": "^2.6.10"
24
24
  },
25
- "gitHead": "e367d8b4acffd31f7b4377e8f564ac5bad167016"
25
+ "gitHead": "6577bf36e4d78c84bb8ceedc63bfbd463cb36b4d"
26
26
  }