/
syntax-vue.js
86 lines (76 loc) · 2.27 KB
/
syntax-vue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use strict";
const {
builders: { concat, group },
} = require("../document");
/**
* v-for="... in ..."
* v-for="... of ..."
* v-for="(..., ...) in ..."
* v-for="(..., ...) of ..."
*/
function printVueFor(value, textToDoc) {
const { left, operator, right } = parseVueFor(value);
return concat([
group(
textToDoc(`function _(${left}) {}`, {
parser: "babel",
__isVueForBindingLeft: true,
})
),
" ",
operator,
" ",
textToDoc(right, { parser: "__js_expression" }),
]);
}
// modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
function parseVueFor(value) {
const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
const forIteratorRE = /,([^,\]}]*)(?:,([^,\]}]*))?$/;
const stripParensRE = /^\(|\)$/g;
const inMatch = value.match(forAliasRE);
if (!inMatch) {
return;
}
const res = {};
res.for = inMatch[3].trim();
const alias = inMatch[1].trim().replace(stripParensRE, "");
const iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
res.alias = alias.replace(forIteratorRE, "");
res.iterator1 = iteratorMatch[1].trim();
if (iteratorMatch[2]) {
res.iterator2 = iteratorMatch[2].trim();
}
} else {
res.alias = alias;
}
return {
left: `${[res.alias, res.iterator1, res.iterator2]
.filter(Boolean)
.join(",")}`,
operator: inMatch[2],
right: res.for,
};
}
function printVueSlotScope(value, textToDoc) {
return textToDoc(`function _(${value}) {}`, {
parser: "babel",
__isVueSlotScope: true,
});
}
function isVueEventBindingExpression(eventBindingValue) {
// https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
// arrow function or anonymous function
const fnExpRE = /^([\w$]+|\([^)]*?\))\s*=>|^function\s*\(/;
// simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
const simplePathRE = /^[$A-Z_a-z][\w$]*(?:\.[$A-Z_a-z][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[$A-Z_a-z][\w$]*])*$/;
// https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
const value = eventBindingValue.trim();
return fnExpRE.test(value) || simplePathRE.test(value);
}
module.exports = {
isVueEventBindingExpression,
printVueFor,
printVueSlotScope,
};