UNPKG

1.57 kBJavaScriptView Raw
1var colors = require('colors');
2
3/**
4 * 处理函数依赖
5 *
6 * @param {string} content 文本内容
7 * @param {Object} attrs 属性
8 * @param {string} attrs.data 数据项
9 * @param {Object} scope 作用域
10 * @param {Function} scope.contentScope 内容生成作用域
11 */
12module.exports = function (content, attrs, scope) {
13 var fns = {};
14 var list = [];
15 var contentScope = scope.contentScope(content);
16 var fnNodes = {};
17 contentScope.querySelector('function*').forEach(function (node) {
18 fnNodes[node.attrs.name] = {
19 node: node,
20 require: 0
21 };
22 });
23 /**
24 * 记录依赖关系
25 *
26 * @param {string} depend 依赖列表
27 */
28 function record(depend, level) {
29 if (!depend) {
30 return;
31 }
32 depend.split(/\s*,\s*/).forEach(function (name) {
33 var item = fnNodes[name];
34 if (!item) {
35 return;
36 }
37 var node = item.node;
38 if (node.pending) {
39 console.error(colors.red('A circular reference. name = %j'), name);
40 return;
41 }
42 if (!fns[name]) {
43 list.push(fnNodes[name]);
44 }
45 fns[name] = fnNodes[name];
46 fns[name].require += level;
47 node.pending = true;
48 record(node.attrs.depend, level + 1);
49 node.pending = false;
50 });
51 }
52 record(attrs.depend, 0);
53 list.sort(function (a, b) {
54 return b.require - a.require;
55 });
56 return list.map(function (item) {
57 var match = item.node.content.match(/^\n([^\S\n]+)/);
58 var space = match ? match[1] : '';
59 return space + contentScope.buildBlock(item.node);
60 }).join('\n');
61};
\No newline at end of file