field_textinput.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 Text input field.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.FieldTextInput');
  26. goog.require('Blockly.Field');
  27. goog.require('Blockly.Msg');
  28. goog.require('goog.asserts');
  29. goog.require('goog.dom');
  30. goog.require('goog.dom.TagName');
  31. goog.require('goog.userAgent');
  32. /**
  33. * Class for an editable text field.
  34. * @param {string} text The initial content of the field.
  35. * @param {Function=} opt_validator An optional function that is called
  36. * to validate any constraints on what the user entered. Takes the new
  37. * text as an argument and returns either the accepted text, a replacement
  38. * text, or null to abort the change.
  39. * @extends {Blockly.Field}
  40. * @constructor
  41. */
  42. Blockly.FieldTextInput = function(text, opt_validator) {
  43. Blockly.FieldTextInput.superClass_.constructor.call(this, text,
  44. opt_validator);
  45. };
  46. goog.inherits(Blockly.FieldTextInput, Blockly.Field);
  47. /**
  48. * Point size of text. Should match blocklyText's font-size in CSS.
  49. */
  50. Blockly.FieldTextInput.FONTSIZE = 11;
  51. /**
  52. * Mouse cursor style when over the hotspot that initiates the editor.
  53. */
  54. Blockly.FieldTextInput.prototype.CURSOR = 'text';
  55. /**
  56. * Allow browser to spellcheck this field.
  57. * @private
  58. */
  59. Blockly.FieldTextInput.prototype.spellcheck_ = true;
  60. /**
  61. * Close the input widget if this input is being deleted.
  62. */
  63. Blockly.FieldTextInput.prototype.dispose = function() {
  64. Blockly.WidgetDiv.hideIfOwner(this);
  65. Blockly.FieldTextInput.superClass_.dispose.call(this);
  66. };
  67. /**
  68. * Set the text in this field.
  69. * @param {?string} text New text.
  70. * @override
  71. */
  72. Blockly.FieldTextInput.prototype.setValue = function(text) {
  73. if (text === null) {
  74. return; // No change if null.
  75. }
  76. if (this.sourceBlock_) {
  77. var validated = this.callValidator(text);
  78. // If the new text is invalid, validation returns null.
  79. // In this case we still want to display the illegal result.
  80. if (validated !== null) {
  81. text = validated;
  82. }
  83. }
  84. Blockly.Field.prototype.setValue.call(this, text);
  85. };
  86. /**
  87. * Set whether this field is spellchecked by the browser.
  88. * @param {boolean} check True if checked.
  89. */
  90. Blockly.FieldTextInput.prototype.setSpellcheck = function(check) {
  91. this.spellcheck_ = check;
  92. };
  93. /**
  94. * Show the inline free-text editor on top of the text.
  95. * @param {boolean=} opt_quietInput True if editor should be created without
  96. * focus. Defaults to false.
  97. * @private
  98. */
  99. Blockly.FieldTextInput.prototype.showEditor_ = function(opt_quietInput) {
  100. this.workspace_ = this.sourceBlock_.workspace;
  101. var quietInput = opt_quietInput || false;
  102. if (!quietInput && (goog.userAgent.MOBILE || goog.userAgent.ANDROID ||
  103. goog.userAgent.IPAD)) {
  104. // Mobile browsers have issues with in-line textareas (focus & keyboards).
  105. var fieldText = this;
  106. Blockly.prompt(Blockly.Msg.CHANGE_VALUE_TITLE, this.text_,
  107. function(newValue) {
  108. if (fieldText.sourceBlock_) {
  109. newValue = fieldText.callValidator(newValue);
  110. }
  111. fieldText.setValue(newValue);
  112. });
  113. return;
  114. }
  115. Blockly.WidgetDiv.show(this, this.sourceBlock_.RTL, this.widgetDispose_());
  116. var div = Blockly.WidgetDiv.DIV;
  117. // Create the input.
  118. var htmlInput =
  119. goog.dom.createDom(goog.dom.TagName.INPUT, 'blocklyHtmlInput');
  120. htmlInput.setAttribute('spellcheck', this.spellcheck_);
  121. var fontSize =
  122. (Blockly.FieldTextInput.FONTSIZE * this.workspace_.scale) + 'pt';
  123. div.style.fontSize = fontSize;
  124. htmlInput.style.fontSize = fontSize;
  125. /** @type {!HTMLInputElement} */
  126. Blockly.FieldTextInput.htmlInput_ = htmlInput;
  127. div.appendChild(htmlInput);
  128. htmlInput.value = htmlInput.defaultValue = this.text_;
  129. htmlInput.oldValue_ = null;
  130. this.validate_();
  131. this.resizeEditor_();
  132. // if (!quietInput) {
  133. htmlInput.focus();
  134. htmlInput.select();
  135. // }
  136. // Bind to keydown -- trap Enter without IME and Esc to hide.
  137. htmlInput.onKeyDownWrapper_ =
  138. Blockly.bindEventWithChecks_(htmlInput, 'keydown', this,
  139. this.onHtmlInputKeyDown_);
  140. // Bind to keyup -- trap Enter; resize after every keystroke.
  141. htmlInput.onKeyUpWrapper_ =
  142. Blockly.bindEventWithChecks_(htmlInput, 'keyup', this,
  143. this.onHtmlInputChange_);
  144. // Bind to keyPress -- repeatedly resize when holding down a key.
  145. htmlInput.onKeyPressWrapper_ =
  146. Blockly.bindEventWithChecks_(htmlInput, 'keypress', this,
  147. this.onHtmlInputChange_);
  148. htmlInput.onWorkspaceChangeWrapper_ = this.resizeEditor_.bind(this);
  149. this.workspace_.addChangeListener(htmlInput.onWorkspaceChangeWrapper_);
  150. };
  151. /**
  152. * Handle key down to the editor.
  153. * @param {!Event} e Keyboard event.
  154. * @private
  155. */
  156. Blockly.FieldTextInput.prototype.onHtmlInputKeyDown_ = function(e) {
  157. var htmlInput = Blockly.FieldTextInput.htmlInput_;
  158. var tabKey = 9, enterKey = 13, escKey = 27;
  159. if (e.keyCode == enterKey) {
  160. Blockly.WidgetDiv.hide();
  161. } else if (e.keyCode == escKey) {
  162. htmlInput.value = htmlInput.defaultValue;
  163. Blockly.WidgetDiv.hide();
  164. } else if (e.keyCode == tabKey) {
  165. Blockly.WidgetDiv.hide();
  166. this.sourceBlock_.tab(this, !e.shiftKey);
  167. e.preventDefault();
  168. }
  169. };
  170. /**
  171. * Handle a change to the editor.
  172. * @param {!Event} e Keyboard event.
  173. * @private
  174. */
  175. Blockly.FieldTextInput.prototype.onHtmlInputChange_ = function(e) {
  176. var htmlInput = Blockly.FieldTextInput.htmlInput_;
  177. // Update source block.
  178. var text = htmlInput.value;
  179. if (text !== htmlInput.oldValue_) {
  180. htmlInput.oldValue_ = text;
  181. this.setValue(text);
  182. this.validate_();
  183. } else if (goog.userAgent.WEBKIT) {
  184. // Cursor key. Render the source block to show the caret moving.
  185. // Chrome only (version 26, OS X).
  186. this.sourceBlock_.render();
  187. }
  188. this.resizeEditor_();
  189. Blockly.svgResize(this.sourceBlock_.workspace);
  190. };
  191. /**
  192. * Check to see if the contents of the editor validates.
  193. * Style the editor accordingly.
  194. * @private
  195. */
  196. Blockly.FieldTextInput.prototype.validate_ = function() {
  197. var valid = true;
  198. goog.asserts.assertObject(Blockly.FieldTextInput.htmlInput_);
  199. var htmlInput = Blockly.FieldTextInput.htmlInput_;
  200. if (this.sourceBlock_) {
  201. valid = this.callValidator(htmlInput.value);
  202. }
  203. if (valid === null) {
  204. Blockly.addClass_(htmlInput, 'blocklyInvalidInput');
  205. } else {
  206. Blockly.removeClass_(htmlInput, 'blocklyInvalidInput');
  207. }
  208. };
  209. /**
  210. * Resize the editor and the underlying block to fit the text.
  211. * @private
  212. */
  213. Blockly.FieldTextInput.prototype.resizeEditor_ = function() {
  214. var div = Blockly.WidgetDiv.DIV;
  215. var bBox = this.fieldGroup_.getBBox();
  216. div.style.width = bBox.width * this.workspace_.scale + 'px';
  217. div.style.height = bBox.height * this.workspace_.scale + 'px';
  218. var xy = this.getAbsoluteXY_();
  219. // In RTL mode block fields and LTR input fields the left edge moves,
  220. // whereas the right edge is fixed. Reposition the editor.
  221. if (this.sourceBlock_.RTL) {
  222. var borderBBox = this.getScaledBBox_();
  223. xy.x += borderBBox.width;
  224. xy.x -= div.offsetWidth;
  225. }
  226. // Shift by a few pixels to line up exactly.
  227. xy.y += 1;
  228. if (goog.userAgent.GECKO && Blockly.WidgetDiv.DIV.style.top) {
  229. // Firefox mis-reports the location of the border by a pixel
  230. // once the WidgetDiv is moved into position.
  231. xy.x -= 1;
  232. xy.y -= 1;
  233. }
  234. if (goog.userAgent.WEBKIT) {
  235. xy.y -= 3;
  236. }
  237. div.style.left = xy.x + 'px';
  238. div.style.top = xy.y + 'px';
  239. };
  240. /**
  241. * Close the editor, save the results, and dispose of the editable
  242. * text field's elements.
  243. * @return {!Function} Closure to call on destruction of the WidgetDiv.
  244. * @private
  245. */
  246. Blockly.FieldTextInput.prototype.widgetDispose_ = function() {
  247. var thisField = this;
  248. return function() {
  249. var htmlInput = Blockly.FieldTextInput.htmlInput_;
  250. // Save the edit (if it validates).
  251. var text = htmlInput.value;
  252. if (thisField.sourceBlock_) {
  253. var text1 = thisField.callValidator(text);
  254. if (text1 === null) {
  255. // Invalid edit.
  256. text = htmlInput.defaultValue;
  257. } else {
  258. // Validation function has changed the text.
  259. text = text1;
  260. if (thisField.onFinishEditing_) {
  261. thisField.onFinishEditing_(text);
  262. }
  263. }
  264. }
  265. thisField.setValue(text);
  266. thisField.sourceBlock_.rendered && thisField.sourceBlock_.render();
  267. Blockly.unbindEvent_(htmlInput.onKeyDownWrapper_);
  268. Blockly.unbindEvent_(htmlInput.onKeyUpWrapper_);
  269. Blockly.unbindEvent_(htmlInput.onKeyPressWrapper_);
  270. thisField.workspace_.removeChangeListener(
  271. htmlInput.onWorkspaceChangeWrapper_);
  272. Blockly.FieldTextInput.htmlInput_ = null;
  273. // Delete style properties.
  274. var style = Blockly.WidgetDiv.DIV.style;
  275. style.width = 'auto';
  276. style.height = 'auto';
  277. style.fontSize = '';
  278. };
  279. };
  280. /**
  281. * Ensure that only a number may be entered.
  282. * @param {string} text The user's text.
  283. * @return {?string} A string representing a valid number, or null if invalid.
  284. */
  285. Blockly.FieldTextInput.numberValidator = function(text) {
  286. console.warn('Blockly.FieldTextInput.numberValidator is deprecated. ' +
  287. 'Use Blockly.FieldNumber instead.');
  288. if (text === null) {
  289. return null;
  290. }
  291. text = String(text);
  292. // TODO: Handle cases like 'ten', '1.203,14', etc.
  293. // 'O' is sometimes mistaken for '0' by inexperienced users.
  294. text = text.replace(/O/ig, '0');
  295. // Strip out thousands separators.
  296. text = text.replace(/,/g, '');
  297. var n = parseFloat(text || 0);
  298. return isNaN(n) ? null : String(n);
  299. };
  300. /**
  301. * Ensure that only a nonnegative integer may be entered.
  302. * @param {string} text The user's text.
  303. * @return {?string} A string representing a valid int, or null if invalid.
  304. */
  305. Blockly.FieldTextInput.nonnegativeIntegerValidator = function(text) {
  306. var n = Blockly.FieldTextInput.numberValidator(text);
  307. if (n) {
  308. n = String(Math.max(0, Math.floor(n)));
  309. }
  310. return n;
  311. };