-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.js
78 lines (66 loc) · 2.24 KB
/
block.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
/**
* Created by zouxuan on 4/26/17.
*/
(function (global) {
'use strict'
function createBlock(name, value, content) {
var item = elem('div', {'class': 'block', draggable: true, 'data-name': name}, [name]);
if (value !== undefined && value !== null) {
item.appendChild(elem('input', {type: 'number', value: value}));
if (Array.isArray(content)) {
item.appendChild(elem('div', {'class': 'container'}, content.map(function (block) {
return createBlock.apply(null, block);
})));
}
} else if (typeof content === 'string') {
item.appendChild(document.createTextNode(' ' + content));
}
return item;
}
function blockContents(block) {
var container = block.querySelector('.container');
return container ? [].slice.call(container.children) : null;
}
function blockValue(block) {
var input = block.querySelector('input');
return input ? Number(input.value) : null;
}
function blockUnits(block) {
if (block.children.length > 1 && block.lastChild.nodeType === Node.TEXT_NODE && block.lastChild.textContent) {
return block.lastChild.textContent.slice(1);
}
}
function blockScript(block) {
var script = [block.dataset.name];
var value = blockValue(block);
if (value !== null) {
script.push(blockValue(block));
}
var contents = blockContents(block);
var unit = blockUnits(block);
if (contents) {
script.push(contents.map(blockScript));
}
if (unit) {
script.push(unit);
}
return script.filter(function (notNull) {
return notNull !== null;
});
}
function runBlocks(block) {
block.forEach(function (block) {
trigger('run', block);
});
}
global.Block = {
create: createBlock,
value: blockValue,
contents: blockContents,
script: blockScript,
run: runBlocks,
trigger: trigger
};
window.addEventListener('unload', file.saveLocal, false);
window.addEventListener('load', file.restoreLocal, false);
})(window);