field_dropdown.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * @license
  3. * Visual Blocks Editor
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Dropdown input field. Used for editable titles and variables.
  22. * In the interests of a consistent UI, the toolbox shares some functions and
  23. * properties with the context menu.
  24. * @author fraser@google.com (Neil Fraser)
  25. */
  26. 'use strict';
  27. goog.provide('Blockly.FieldDropdown');
  28. goog.require('Blockly.Field');
  29. goog.require('goog.dom');
  30. goog.require('goog.events');
  31. goog.require('goog.style');
  32. goog.require('goog.ui.Menu');
  33. goog.require('goog.ui.MenuItem');
  34. goog.require('goog.userAgent');
  35. /**
  36. * Class for an editable dropdown field.
  37. * @param {(!Array.<!Array.<string>>|!Function)} menuGenerator An array of
  38. * options for a dropdown list, or a function which generates these options.
  39. * @param {Function=} opt_validator A function that is executed when a new
  40. * option is selected, with the newly selected value as its sole argument.
  41. * If it returns a value, that value (which must be one of the options) will
  42. * become selected in place of the newly selected option, unless the return
  43. * value is null, in which case the change is aborted.
  44. * @extends {Blockly.Field}
  45. * @constructor
  46. */
  47. Blockly.FieldDropdown = function(menuGenerator, opt_validator) {
  48. this.menuGenerator_ = menuGenerator;
  49. this.trimOptions_();
  50. var firstTuple = this.getOptions_()[0];
  51. // Call parent's constructor.
  52. Blockly.FieldDropdown.superClass_.constructor.call(this, firstTuple[1],
  53. opt_validator);
  54. };
  55. goog.inherits(Blockly.FieldDropdown, Blockly.Field);
  56. /**
  57. * Horizontal distance that a checkmark ovehangs the dropdown.
  58. */
  59. Blockly.FieldDropdown.CHECKMARK_OVERHANG = 25;
  60. /**
  61. * Android can't (in 2014) display "▾", so use "▼" instead.
  62. */
  63. Blockly.FieldDropdown.ARROW_CHAR = goog.userAgent.ANDROID ? '\u25BC' : '\u25BE';
  64. /**
  65. * Mouse cursor style when over the hotspot that initiates the editor.
  66. */
  67. Blockly.FieldDropdown.prototype.CURSOR = 'default';
  68. /**
  69. * Install this dropdown on a block.
  70. */
  71. Blockly.FieldDropdown.prototype.init = function() {
  72. if (this.fieldGroup_) {
  73. // Dropdown has already been initialized once.
  74. return;
  75. }
  76. // Add dropdown arrow: "option ▾" (LTR) or "▾ אופציה" (RTL)
  77. this.arrow_ = Blockly.createSvgElement('tspan', {}, null);
  78. this.arrow_.appendChild(document.createTextNode(
  79. this.sourceBlock_.RTL ? Blockly.FieldDropdown.ARROW_CHAR + ' ' :
  80. ' ' + Blockly.FieldDropdown.ARROW_CHAR));
  81. Blockly.FieldDropdown.superClass_.init.call(this);
  82. // Force a reset of the text to add the arrow.
  83. var text = this.text_;
  84. this.text_ = null;
  85. this.setText(text);
  86. };
  87. /**
  88. * Create a dropdown menu under the text.
  89. * @private
  90. */
  91. Blockly.FieldDropdown.prototype.showEditor_ = function() {
  92. Blockly.WidgetDiv.show(this, this.sourceBlock_.RTL, null);
  93. var thisField = this;
  94. function callback(e) {
  95. var menuItem = e.target;
  96. if (menuItem) {
  97. var value = menuItem.getValue();
  98. if (thisField.sourceBlock_) {
  99. // Call any validation function, and allow it to override.
  100. value = thisField.callValidator(value);
  101. }
  102. if (value !== null) {
  103. thisField.setValue(value);
  104. }
  105. }
  106. Blockly.WidgetDiv.hideIfOwner(thisField);
  107. }
  108. var menu = new goog.ui.Menu();
  109. menu.setRightToLeft(this.sourceBlock_.RTL);
  110. var options = this.getOptions_();
  111. for (var i = 0; i < options.length; i++) {
  112. var text = options[i][0]; // Human-readable text.
  113. var value = options[i][1]; // Language-neutral value.
  114. var menuItem = new goog.ui.MenuItem(text);
  115. menuItem.setRightToLeft(this.sourceBlock_.RTL);
  116. menuItem.setValue(value);
  117. menuItem.setCheckable(true);
  118. menu.addChild(menuItem, true);
  119. menuItem.setChecked(value == this.value_);
  120. }
  121. // Listen for mouse/keyboard events.
  122. goog.events.listen(menu, goog.ui.Component.EventType.ACTION, callback);
  123. // Listen for touch events (why doesn't Closure handle this already?).
  124. function callbackTouchStart(e) {
  125. var control = this.getOwnerControl(/** @type {Node} */ (e.target));
  126. // Highlight the menu item.
  127. control.handleMouseDown(e);
  128. }
  129. function callbackTouchEnd(e) {
  130. var control = this.getOwnerControl(/** @type {Node} */ (e.target));
  131. // Activate the menu item.
  132. control.performActionInternal(e);
  133. }
  134. menu.getHandler().listen(menu.getElement(), goog.events.EventType.TOUCHSTART,
  135. callbackTouchStart);
  136. menu.getHandler().listen(menu.getElement(), goog.events.EventType.TOUCHEND,
  137. callbackTouchEnd);
  138. // Record windowSize and scrollOffset before adding menu.
  139. var windowSize = goog.dom.getViewportSize();
  140. var scrollOffset = goog.style.getViewportPageOffset(document);
  141. var xy = this.getAbsoluteXY_();
  142. var borderBBox = this.getScaledBBox_();
  143. var div = Blockly.WidgetDiv.DIV;
  144. menu.render(div);
  145. var menuDom = menu.getElement();
  146. Blockly.addClass_(menuDom, 'blocklyDropdownMenu');
  147. // Record menuSize after adding menu.
  148. var menuSize = goog.style.getSize(menuDom);
  149. // Recalculate height for the total content, not only box height.
  150. menuSize.height = menuDom.scrollHeight;
  151. // Position the menu.
  152. // Flip menu vertically if off the bottom.
  153. if (xy.y + menuSize.height + borderBBox.height >=
  154. windowSize.height + scrollOffset.y) {
  155. xy.y -= menuSize.height + 2;
  156. } else {
  157. xy.y += borderBBox.height;
  158. }
  159. if (this.sourceBlock_.RTL) {
  160. xy.x += borderBBox.width;
  161. xy.x += Blockly.FieldDropdown.CHECKMARK_OVERHANG;
  162. // Don't go offscreen left.
  163. if (xy.x < scrollOffset.x + menuSize.width) {
  164. xy.x = scrollOffset.x + menuSize.width;
  165. }
  166. } else {
  167. xy.x -= Blockly.FieldDropdown.CHECKMARK_OVERHANG;
  168. // Don't go offscreen right.
  169. if (xy.x > windowSize.width + scrollOffset.x - menuSize.width) {
  170. xy.x = windowSize.width + scrollOffset.x - menuSize.width;
  171. }
  172. }
  173. Blockly.WidgetDiv.position(xy.x, xy.y, windowSize, scrollOffset,
  174. this.sourceBlock_.RTL);
  175. menu.setAllowAutoFocus(true);
  176. menuDom.focus();
  177. };
  178. /**
  179. * Factor out common words in statically defined options.
  180. * Create prefix and/or suffix labels.
  181. * @private
  182. */
  183. Blockly.FieldDropdown.prototype.trimOptions_ = function() {
  184. this.prefixField = null;
  185. this.suffixField = null;
  186. var options = this.menuGenerator_;
  187. if (!goog.isArray(options) || options.length < 2) {
  188. return;
  189. }
  190. var strings = options.map(function(t) {return t[0];});
  191. var shortest = Blockly.shortestStringLength(strings);
  192. var prefixLength = Blockly.commonWordPrefix(strings, shortest);
  193. var suffixLength = Blockly.commonWordSuffix(strings, shortest);
  194. if (!prefixLength && !suffixLength) {
  195. return;
  196. }
  197. if (shortest <= prefixLength + suffixLength) {
  198. // One or more strings will entirely vanish if we proceed. Abort.
  199. return;
  200. }
  201. if (prefixLength) {
  202. this.prefixField = strings[0].substring(0, prefixLength - 1);
  203. }
  204. if (suffixLength) {
  205. this.suffixField = strings[0].substr(1 - suffixLength);
  206. }
  207. // Remove the prefix and suffix from the options.
  208. var newOptions = [];
  209. for (var i = 0; i < options.length; i++) {
  210. var text = options[i][0];
  211. var value = options[i][1];
  212. text = text.substring(prefixLength, text.length - suffixLength);
  213. newOptions[i] = [text, value];
  214. }
  215. this.menuGenerator_ = newOptions;
  216. };
  217. /**
  218. * Return a list of the options for this dropdown.
  219. * @return {!Array.<!Array.<string>>} Array of option tuples:
  220. * (human-readable text, language-neutral name).
  221. * @private
  222. */
  223. Blockly.FieldDropdown.prototype.getOptions_ = function() {
  224. if (goog.isFunction(this.menuGenerator_)) {
  225. return this.menuGenerator_.call(this);
  226. }
  227. return /** @type {!Array.<!Array.<string>>} */ (this.menuGenerator_);
  228. };
  229. /**
  230. * Get the language-neutral value from this dropdown menu.
  231. * @return {string} Current text.
  232. */
  233. Blockly.FieldDropdown.prototype.getValue = function() {
  234. return this.value_;
  235. };
  236. /**
  237. * Set the language-neutral value for this dropdown menu.
  238. * @param {string} newValue New value to set.
  239. */
  240. Blockly.FieldDropdown.prototype.setValue = function(newValue) {
  241. if (newValue === null || newValue === this.value_) {
  242. return; // No change if null.
  243. }
  244. if (this.sourceBlock_ && Blockly.Events.isEnabled()) {
  245. Blockly.Events.fire(new Blockly.Events.Change(
  246. this.sourceBlock_, 'field', this.name, this.value_, newValue));
  247. }
  248. this.value_ = newValue;
  249. // Look up and display the human-readable text.
  250. var options = this.getOptions_();
  251. for (var i = 0; i < options.length; i++) {
  252. // Options are tuples of human-readable text and language-neutral values.
  253. if (options[i][1] == newValue) {
  254. this.setText(options[i][0]);
  255. return;
  256. }
  257. }
  258. // Value not found. Add it, maybe it will become valid once set
  259. // (like variable names).
  260. this.setText(newValue);
  261. };
  262. /**
  263. * Set the text in this field. Trigger a rerender of the source block.
  264. * @param {?string} text New text.
  265. */
  266. Blockly.FieldDropdown.prototype.setText = function(text) {
  267. if (this.sourceBlock_ && this.arrow_) {
  268. // Update arrow's colour.
  269. this.arrow_.style.fill = this.sourceBlock_.getColour();
  270. }
  271. if (text === null || text === this.text_) {
  272. // No change if null.
  273. return;
  274. }
  275. this.text_ = text;
  276. this.updateTextNode_();
  277. if (this.textElement_) {
  278. // Insert dropdown arrow.
  279. if (this.sourceBlock_.RTL) {
  280. this.textElement_.insertBefore(this.arrow_, this.textElement_.firstChild);
  281. } else {
  282. this.textElement_.appendChild(this.arrow_);
  283. }
  284. }
  285. if (this.sourceBlock_ && this.sourceBlock_.rendered) {
  286. this.sourceBlock_.render();
  287. this.sourceBlock_.bumpNeighbours_();
  288. }
  289. };
  290. /**
  291. * Close the dropdown menu if this input is being deleted.
  292. */
  293. Blockly.FieldDropdown.prototype.dispose = function() {
  294. Blockly.WidgetDiv.hideIfOwner(this);
  295. Blockly.FieldDropdown.superClass_.dispose.call(this);
  296. };