Blockly.Blocks['dicts_create_with'] = { /** * Block for creating a dict with any number of elements of any type. * @this Blockly.Block */ init: function() { console.log("init"); this.setInputsInline(false); this.setColour(Blockly.Blocks.dicts.HUE); this.itemCount_ = 1; this.updateShape_(); this.setOutput(true, 'dict'); this.setTooltip(Blockly.Msg.DICTS_CREATE_WITH_TOOLTIP); }, /** * Create XML to represent dict inputs. * @return {Element} XML storage element. * @this Blockly.Block */ mutationToDom: function(workspace) { var container = document.createElement('mutation'); container.setAttribute('items', this.itemCount_); return container; }, /** * Parse XML to restore the dict inputs. * @param {!Element} xmlElement XML storage element. * @this Blockly.Block */ domToMutation: function(xmlElement) { this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10); this.updateShape_(); }, fixEmpty_: function() { if (this.itemCount_ > 0) { this.getInput("START").fieldRow[0].setText("dictionary of"); } else { this.getInput("START").fieldRow[0].setText(Blockly.Msg.DICTS_CREATE_EMPTY_TITLE); } }, addRow: function(i) { if (!this.getInput('VALUE'+i)) { this.appendValueInput('VALUE' + i) .setCheck(null) .setAlign(Blockly.ALIGN_RIGHT) .appendField( new Blockly.FieldTextInput( Blockly.Msg.DICTS_CREATE_WITH_ITEM_KEY), 'KEY'+i) .appendField(Blockly.Msg.DICTS_CREATE_WITH_ITEM_MAPPING); } }, /** * Modify this block to have the correct number of inputs. * @private * @this Blockly.Block */ updateShape_: function() { var that = this; function addField(field, block, e) { var rect = field.fieldGroup_.getBoundingClientRect(); var yPosition = e.clientY; if (yPosition < rect.top+rect.height/2) { that.itemCount_ += 1; that.addRow(that.itemCount_); } else { if (that.itemCount_ > 0) { that.removeInput('VALUE' + that.itemCount_); that.itemCount_ -= 1; } } that.fixEmpty_(); } var clickablePlusMinus = new Blockly.FieldClickImage("images/plus_minus_v.png", 24, 24, '+', addField, '-2px'); // Rebuild block. if (!this.getInput("START")) { this.appendDummyInput('START') .appendField("dictionary of") .appendField(clickablePlusMinus); } this.fixEmpty_(); for (var i = 1; i <= this.itemCount_; i++) { this.addRow(i); } } }; Blockly.Python.dicts_create_with = function(block) { var value_keys = Blockly.Python.valueToCode(block, 'keys', Blockly. Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable. var code = new Array(block.itemCount_); for (var n = 1; n <= block.itemCount_; n++) { var key = Blockly.Python.quote_(block.getFieldValue('KEY' + n)); var value = Blockly.Python.valueToCode(block, 'VALUE' + n, Blockly.Python.ORDER_NONE) || '___'; code[n-1] = key +": "+ value; } code = '{' + code.join(', ') + '}'; return [code, Blockly.Python.ORDER_ATOMIC]; };