dict.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. Blockly.Blocks['dicts_create_with'] = {
  2. /**
  3. * Block for creating a dict with any number of elements of any type.
  4. * @this Blockly.Block
  5. */
  6. init: function() {
  7. console.log("init");
  8. this.setInputsInline(false);
  9. this.setColour(Blockly.Blocks.dicts.HUE);
  10. this.itemCount_ = 1;
  11. this.updateShape_();
  12. this.setOutput(true, 'dict');
  13. this.setTooltip(Blockly.Msg.DICTS_CREATE_WITH_TOOLTIP);
  14. },
  15. /**
  16. * Create XML to represent dict inputs.
  17. * @return {Element} XML storage element.
  18. * @this Blockly.Block
  19. */
  20. mutationToDom: function(workspace) {
  21. var container = document.createElement('mutation');
  22. container.setAttribute('items', this.itemCount_);
  23. return container;
  24. },
  25. /**
  26. * Parse XML to restore the dict inputs.
  27. * @param {!Element} xmlElement XML storage element.
  28. * @this Blockly.Block
  29. */
  30. domToMutation: function(xmlElement) {
  31. this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
  32. this.updateShape_();
  33. },
  34. fixEmpty_: function() {
  35. if (this.itemCount_ > 0) {
  36. this.getInput("START").fieldRow[0].setText("dictionary of");
  37. } else {
  38. this.getInput("START").fieldRow[0].setText(Blockly.Msg.DICTS_CREATE_EMPTY_TITLE);
  39. }
  40. },
  41. addRow: function(i) {
  42. if (!this.getInput('VALUE'+i)) {
  43. this.appendValueInput('VALUE' + i)
  44. .setCheck(null)
  45. .setAlign(Blockly.ALIGN_RIGHT)
  46. .appendField(
  47. new Blockly.FieldTextInput(
  48. Blockly.Msg.DICTS_CREATE_WITH_ITEM_KEY),
  49. 'KEY'+i)
  50. .appendField(Blockly.Msg.DICTS_CREATE_WITH_ITEM_MAPPING);
  51. }
  52. },
  53. /**
  54. * Modify this block to have the correct number of inputs.
  55. * @private
  56. * @this Blockly.Block
  57. */
  58. updateShape_: function() {
  59. var that = this;
  60. function addField(field, block, e) {
  61. var rect = field.fieldGroup_.getBoundingClientRect();
  62. var yPosition = e.clientY;
  63. if (yPosition < rect.top+rect.height/2) {
  64. that.itemCount_ += 1;
  65. that.addRow(that.itemCount_);
  66. } else {
  67. if (that.itemCount_ > 0) {
  68. that.removeInput('VALUE' + that.itemCount_);
  69. that.itemCount_ -= 1;
  70. }
  71. }
  72. that.fixEmpty_();
  73. }
  74. var clickablePlusMinus = new Blockly.FieldClickImage("images/plus_minus_v.png", 24, 24, '+', addField, '-2px');
  75. // Rebuild block.
  76. if (!this.getInput("START")) {
  77. this.appendDummyInput('START')
  78. .appendField("dictionary of")
  79. .appendField(clickablePlusMinus);
  80. }
  81. this.fixEmpty_();
  82. for (var i = 1; i <= this.itemCount_; i++) {
  83. this.addRow(i);
  84. }
  85. }
  86. };