-
Notifications
You must be signed in to change notification settings - Fork 39
/
menuly_codegen.js
101 lines (62 loc) · 1.98 KB
/
menuly_codegen.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
Blockly.JSON = new Blockly.Generator('JSON');
Blockly.JSON.fromWorkspace = function(workspace) {
var json_text = '';
var top_blocks = workspace.getTopBlocks(false);
for(var i in top_blocks) {
var top_block = top_blocks[i];
if(top_block.type == 'start') {
var json_structure = this.generalBlockToObj( top_block );
json_text += JSON.stringify(json_structure, null, 4) + '\n\n';
}
}
return json_text;
};
Blockly.JSON.generalBlockToObj = function(block) {
if(block) {
// dispatcher:
var func = this[block.type];
if(func) {
return func.call(this, block);
} else {
console.log("Don't know how to generate JSON code for a '"+block.type+"'");
}
} else {
return null;
}
};
Blockly.JSON['start'] = function(block) {
var json = this.generalBlockToObj( block.getInputTargetBlock( 'json' ) );
return json;
};
Blockly.JSON['true'] = function(block) {
return true;
};
Blockly.JSON['false'] = function(block) {
return false;
};
Blockly.JSON['string'] = function(block) {
var string_value = block.getFieldValue( 'string_value' );
return string_value ;
};
Blockly.JSON['number'] = function(block) {
var number_value = Number(block.getFieldValue( 'number_value' ));
return number_value ;
};
Blockly.JSON['dictionary'] = function(block) {
var dictionary = {};
for(var i = 0; i<block.length; i++) {
var pair_key = block.getFieldValue( 'key_field_'+i );
var pair_value = this.generalBlockToObj( block.getInputTargetBlock( 'element_'+i ) );
dictionary[pair_key] = pair_value;
}
return dictionary;
};
Blockly.JSON['array'] = function(block) {
var array = [];
for(var i = 0; i<block.length; i++) {
var element_value = this.generalBlockToObj( block.getInputTargetBlock( 'element_'+i ) );
array[i] = element_value;
}
return array;
};