Spaces:
Running
Running
File size: 10,971 Bytes
54ee264 b2e1e16 54ee264 b2e1e16 54ee264 b2e1e16 54ee264 | 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | // Headless test: verify custom function blocks generate JS correctly.
const Blockly = require('blockly');
const { javascriptGenerator, Order } = require('blockly/javascript');
const FN_COLOR = '#E91E63';
const OVAL_COLOR = '#FF8C1A';
function escXml(s) {
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
// --- Simulated app blocks (statement blocks return strings; value blocks tuples) ---
javascriptGenerator.forBlock['rb_js_set_var'] = function (block) {
const name = block.getFieldValue('name') || 'myVar';
let value = '';
const t = block.getInputTargetBlock('value');
if (t) {
const tuple = javascriptGenerator.blockToCode(t, Order.ATOMIC);
value = Array.isArray(tuple) ? tuple[0] : tuple || '';
}
const code = `myVar${''} = ${value || 'undefined'};`;
return block.outputConnection ? [code, Order.ATOMIC] : code; // statement -> string
};
javascriptGenerator.forBlock['rb_js_const_number'] = function (block) {
return [String(block.getFieldValue('value') ?? 0), Order.ATOMIC];
};
javascriptGenerator.forBlock['rb_js_console'] = function (block) {
let value = '';
const t = block.getInputTargetBlock('value');
if (t) {
const tuple = javascriptGenerator.blockToCode(t, Order.ATOMIC);
value = Array.isArray(tuple) ? tuple[0] : tuple || '';
}
const code = `console.log(${value || "''"});`;
return block.outputConnection ? [code, Order.ATOMIC] : code;
};
// --- Minimal app block definitions ---
Blockly.Blocks['rb_js_set_var'] = {
init() {
this.appendDummyInput().appendField('set var').appendField('myVar', 'name');
this.appendValueInput('value');
this.setPreviousStatement(true);
this.setNextStatement(true);
},
};
Blockly.Blocks['rb_js_const_number'] = {
init() {
this.appendDummyInput().appendField('value').appendField(new Blockly.FieldNumber(0), 'value');
this.setOutput(true);
},
};
Blockly.Blocks['rb_js_console'] = {
init() {
this.appendDummyInput().appendField('print');
this.appendValueInput('value');
this.setPreviousStatement(true);
this.setNextStatement(true);
},
};
// --- Register the custom function block types (mirrors customFunctionBlocks.ts) ---
function parseFnData(block) {
try {
const d = JSON.parse(String(block.data || '{}'));
if (d && typeof d === 'object' && typeof d.name === 'string') return d;
} catch {}
return null;
}
function paramSegsOf(segments) {
return (segments || []).filter((s) => s.kind === 'param');
}
function encodeName(name) {
return String(name).replace(/%/g, '\\u0025').replace(/\s+/g, '_').replace(/\W/g, (ch) => {
return '%' + ch.codePointAt(0).toString(16).toUpperCase();
});
}
function fnParamNames(data) {
return paramSegsOf(data.segments).map((s) => encodeName(s.name));
}
Blockly.Blocks['rb_custom_fn'] = {
init() {
this.setColour(FN_COLOR);
this.appendDummyInput();
this.setInputsInline(true);
},
domToMutation(m) {
try {
const data = {
name: m.getAttribute('name') || '',
segments: JSON.parse(m.getAttribute('segments') || '[]'),
asyncFn: m.getAttribute('async') === 'true',
returns: m.getAttribute('returns') === 'true',
};
this.data = JSON.stringify(data);
// rebuild layout: define + param value inputs + body statement
for (const input of [...this.inputList]) this.removeInput(input.name);
const row = this.appendDummyInput();
row.appendField('define');
row.appendField(data.name, 'name');
let pendingText = '';
let idx = 0;
for (const seg of data.segments) {
if (seg.kind === 'text') pendingText += seg.text;
else {
const vi = this.appendValueInput('PARAM' + idx);
if (pendingText) vi.appendField(pendingText);
pendingText = '';
if (seg.type === 'boolean') vi.setCheck('Boolean');
idx++;
}
}
const props = this.appendDummyInput();
if (pendingText) props.appendField(pendingText);
props.appendField(data.asyncFn ? 'TRUE' : 'FALSE', 'asyncFn');
props.appendField('async');
props.appendField(data.returns ? 'TRUE' : 'FALSE', 'returns');
props.appendField('return value');
this.appendStatementInput('body');
this.setInputsInline(true);
} catch (e) {
throw e;
}
},
mutationToDom() {
const m = Blockly.utils.xml.createElement('mutation');
const d = parseFnData(this) || { name: '', segments: [] };
m.setAttribute('name', String(d.name || ''));
m.setAttribute('segments', JSON.stringify(d.segments || []));
m.setAttribute('async', d.asyncFn ? 'true' : 'false');
m.setAttribute('returns', d.returns ? 'true' : 'false');
return m;
},
};
Blockly.Blocks['rb_custom_call'] = {
init() {
this.setColour(FN_COLOR);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.appendDummyInput();
this.setInputsInline(true);
},
domToMutation(m) {
const data = {
name: m.getAttribute('name') || '',
segments: JSON.parse(m.getAttribute('segments') || '[]'),
returns: m.getAttribute('returns') === 'true',
};
this.data = JSON.stringify(data);
for (const input of [...this.inputList]) this.removeInput(input.name);
const head = this.appendDummyInput();
head.appendField(data.name, 'fnName');
let pendingText = '';
let idx = 0;
for (const seg of data.segments) {
if (seg.kind === 'text') pendingText += seg.text;
else {
const vi = this.appendValueInput('PARAM' + idx);
if (pendingText) vi.appendField(pendingText);
pendingText = '';
if (seg.type === 'boolean') vi.setCheck('Boolean');
idx++;
}
}
const trail = this.appendDummyInput();
if (pendingText) trail.appendField(pendingText);
this.setInputsInline(true);
},
mutationToDom() {
const m = Blockly.utils.xml.createElement('mutation');
const d = parseFnData(this) || { name: '', segments: [] };
m.setAttribute('name', String(d.name || ''));
m.setAttribute('segments', JSON.stringify(d.segments || []));
return m;
},
};
Blockly.Blocks['rb_custom_param_var'] = {
init() {
this.setColour(OVAL_COLOR);
this.setOutput(true);
this.appendDummyInput().appendField('param', 'name');
this.setInputsInline(true);
},
};
// generators use second param `gen` (mirrors the fix)
javascriptGenerator.forBlock['rb_custom_fn'] = function (block, gen) {
const data = parseFnData(block);
const name = encodeName(block.getFieldValue('name') || (data && data.name) || 'myFunction');
const asyncFn = block.getFieldValue('asyncFn') === 'TRUE';
const params = (data ? fnParamNames(data) : []).join(', ');
const body = gen.statementToCode(block, 'body');
return `${asyncFn ? 'async ' : ''}function ${name}(${params}) {\n${body}\n}`;
};
function callCode(block, gen, isValue) {
const data = parseFnData(block);
const name = encodeName((data && data.name) || 'myFunction');
const params = paramSegsOf((data && data.segments) || []);
const args = params
.map((_, i) => {
try {
return gen.valueToCode(block, 'PARAM' + i, Order.ATOMIC) || 'undefined';
} catch {
return 'undefined';
}
})
.join(', ');
return isValue ? `${name}(${args})` : `${name}(${args});`;
}
javascriptGenerator.forBlock['rb_custom_call'] = function (block, gen) {
return callCode(block, gen, false);
};
javascriptGenerator.forBlock['rb_custom_call_value'] = function (block, gen) {
return [callCode(block, gen, true), Order.ATOMIC];
};
javascriptGenerator.forBlock['rb_custom_param_var'] = function (block) {
return [encodeName(String(block.getFieldValue('name') || '')), Order.ATOMIC];
};
// --- Build a workspace with a function hat containing body blocks + a caller ---
const xml = `
<xml>
<block type="rb_custom_fn">
<mutation name="greet" segments='[{"kind":"text","text":"Say hi to "},{"kind":"param","name":"who","type":"variable"}]' async="false" returns="false"></mutation>
<field name="name">greet</field>
<field name="asyncFn">FALSE</field>
<field name="returns">FALSE</field>
<statement name="body">
<block type="rb_js_console">
<value name="value">
<block type="rb_custom_param_var">
<field name="name">who</field>
<data>greet</data>
</block>
</value>
</block>
</statement>
<value name="PARAM0">
<block type="rb_custom_param_var">
<field name="name">who</field>
<data>greet</data>
</block>
</value>
</block>
<block type="rb_custom_call">
<mutation name="greet" segments='[{"kind":"text","text":"Say hi to "},{"kind":"param","name":"who","type":"variable"}]' returns="false"></mutation>
<value name="PARAM0">
<block type="rb_js_const_number"><field name="value">42</field></block>
</value>
</block>
</xml>`;
const ws = new Blockly.Workspace();
Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(xml), ws);
let ok = true;
function check(label, actual, expected) {
const pass = actual === expected;
if (!pass) ok = false;
console.log((pass ? 'PASS' : 'FAIL') + ' ' + label);
if (!pass) {
console.log(' expected: ' + JSON.stringify(expected));
console.log(' actual: ' + JSON.stringify(actual));
}
}
// Generate from the whole workspace
javascriptGenerator.init(ws);
const whole = javascriptGenerator.workspaceToCode(ws);
const expectedWhole = `function greet(who) {
console.log(who);
}
greet(42);`;
check('workspaceToCode', whole, expectedWhole);
// Generate the fn hat alone via blockToCode (as generateCodeFromBlock does)
const fnBlock = ws.getTopBlocks(true).find((b) => b.type === 'rb_custom_fn');
const fnTuple = javascriptGenerator.blockToCode(fnBlock);
check('fn blockToCode is string', typeof fnTuple === 'string', true);
check('fn blockToCode', fnTuple, `function greet(who) {
console.log(who);
}`);
// Caller alone
const callBlock = ws.getTopBlocks(true).find((b) => b.type === 'rb_custom_call');
const callStr = javascriptGenerator.blockToCode(callBlock);
check('call blockToCode is string', typeof callStr === 'string', true);
check('call blockToCode', callStr, 'greet(42);');
// Caller with an empty param socket must not emit `greet(, )` (syntax error);
// the empty arg falls back to `undefined`.
const emptyXml = `<xml><block type="rb_custom_call">` +
`<mutation name="greet" segments='[{"kind":"text","text":"Say hi to "},{"kind":"param","name":"who","type":"variable"}]' returns="false"></mutation>` +
`</block></xml>`;
const ws2 = new Blockly.Workspace();
Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(emptyXml), ws2);
javascriptGenerator.init(ws2);
const emptyCall = javascriptGenerator.workspaceToCode(ws2);
check('empty-arg caller -> undefined', emptyCall, 'greet(undefined);');
process.exit(ok ? 0 : 1);
|