field_table.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /**
  2. * @license
  3. * Visual Blocks Editor
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://blockly.googlecode.com/
  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 Table field.
  22. * @author fraser@google.com (Neil Fraser)
  23. * @author Andrew Mee
  24. * @author acbart@vt.edu (Austin Cory Bart)
  25. */
  26. 'use strict';
  27. goog.provide('Blockly.FieldTable');
  28. goog.require('Blockly.Field');
  29. goog.require('Blockly.Msg');
  30. goog.require('goog.asserts');
  31. goog.require('goog.math.Size');
  32. goog.require('goog.dom');
  33. goog.require('goog.userAgent');
  34. /**
  35. * Class for an editable table.
  36. * @param {array} data The initial content of the table, expected to be
  37. * an array of arrays, with the first row being an array of strings.
  38. * @extends {Blockly.Field}
  39. * @constructor
  40. */
  41. Blockly.FieldTable = function(data) {
  42. this.size_ = new goog.math.Size(0, 25);
  43. this.tableElements_ = [];
  44. this.setData(data);
  45. /*this.setData([["name", "age", "gender"],
  46. ["Cory", 25, "M"],
  47. ["Ellie", 21, "F"]]);*/
  48. };
  49. goog.inherits(Blockly.FieldTable, Blockly.Field);
  50. /**
  51. * Clone this FieldTable.
  52. * @return {!Blockly.FieldTable} The result of calling the constructor again
  53. * with the current values of the arguments used during construction.
  54. */
  55. Blockly.FieldTable.prototype.clone = function() {
  56. return new Blockly.FieldTable(this.getData());
  57. };
  58. /**
  59. * Mouse cursor style when over the hotspot that initiates the editor.
  60. */
  61. Blockly.FieldTable.prototype.CURSOR = 'pointer';
  62. /**
  63. * Close the input widget if this input is being deleted.
  64. */
  65. Blockly.FieldTable.prototype.dispose = function() {
  66. Blockly.WidgetDiv.hideIfOwner(this);
  67. this.tableElements_ = null;
  68. Blockly.FieldTable.superClass_.dispose.call(this);
  69. };
  70. /**
  71. * Install this table on a block.
  72. * @param {!Blockly.Block} block The block containing this table.
  73. */
  74. Blockly.FieldTable.prototype.init = function(block) {
  75. if (this.sourceBlock_) {
  76. // Table has already been initialized once.
  77. return;
  78. }
  79. this.sourceBlock_ = block;
  80. // Build the DOM.
  81. var offsetY = 6 - Blockly.BlockSvg.FIELD_HEIGHT;
  82. this.fieldGroup_ = Blockly.createSvgElement('g', {}, null);
  83. this.setData(this.data_);
  84. block.getSvgRoot().appendChild(this.fieldGroup_);
  85. };
  86. /**
  87. * Set the data of the table.
  88. * @param {?array} data New data
  89. * @override
  90. */
  91. Blockly.FieldTable.prototype.setData = function(data) {
  92. if (data === null) {
  93. if (this.data_ == null) {
  94. this.setData([[""]]);
  95. }
  96. // No change if null.
  97. return;
  98. }
  99. // [{"name": "Cory", "age": 25}, {"name": "Ellie", "age": 21}]
  100. // Ensure that we are dealing with an array of hashes with strings as keys
  101. var tableWidth = null;
  102. var maximumLetterWidths = []; // *Extremely* terrible system for estimating
  103. // table widths. Ugh.
  104. if (Array.isArray(data)) {
  105. for (var i = 0; i < data.length; i++) {
  106. var row = data[i];
  107. if (!Array.isArray(row)) {
  108. return;
  109. }
  110. // Make sure that the rows are the same length
  111. if (tableWidth != null && row.length != tableWidth) {
  112. return;
  113. }
  114. tableWidth = row.length;
  115. var value = (""+row[j]).length;
  116. for (var j = 0; j < row.length; j++) {
  117. if (maximumLetterWidths.length <= j ||
  118. maximumLetterWidths[j] == value) {
  119. maximumLetterWidths[j] = value;
  120. }
  121. }
  122. }
  123. }
  124. for (var i = 1; i < maximumLetterWidths.length; i++) {
  125. maximumLetterWidths[i] += maximumLetterWidths[i-1];
  126. }
  127. // It's valid, assign it!
  128. this.data_ = data;
  129. // Empty the table
  130. this.tableElements_ = this.tableElements_.filter(function(element) {
  131. goog.dom.removeChildren(/** @type {!Element} */ (element));
  132. });
  133. // Prevent any field from being empty?
  134. // text = Blockly.Field.NBSP
  135. var y = 2;
  136. var maximumElementWidths = [];
  137. for (var i = 0; i < data.length; i++) {
  138. var tableRow = Blockly.createSvgElement('text',
  139. {}, this.fieldGroup_);
  140. this.tableElements_.push(tableRow);
  141. var row = data[i];
  142. var x = 0;
  143. for (var j = 0; j < row.length; j++) {
  144. var value = row[j];
  145. var properties = {x: x, y:y, 'fill': 'white'};
  146. if (i == 0) {
  147. properties['text-decoration'] = 'underline';
  148. }
  149. var cell = Blockly.createSvgElement('tspan', properties, tableRow);
  150. cell.appendChild(document.createTextNode(value));
  151. x = maximumLetterWidths[j]*8;
  152. }
  153. y += 20;
  154. }
  155. // Cached width is obsolete. Clear it.
  156. this.size_.width = 0;
  157. // Re-render source block in case we shifted things around
  158. if (this.sourceBlock_ && this.sourceBlock_.rendered) {
  159. this.sourceBlock_.render();
  160. this.sourceBlock_.bumpNeighbours_();
  161. this.sourceBlock_.workspace.fireChangeEvent();
  162. }
  163. };
  164. /**
  165. * Draws the border with the correct width.
  166. * Saves the computed width in a property.
  167. * @private
  168. */
  169. Blockly.FieldTable.prototype.render_ = function() {
  170. if (this.visible_ && this.tableElements_) {
  171. // Calculate the width of the header row
  172. if (this.tableElements_.length >= 1) {
  173. this.size_.width = this.tableElements_[0].getBBox().width;
  174. } else {
  175. this.size_.width = 50;
  176. }
  177. // Calculate the height of the entire thing
  178. this.size_.height= (this.data_.length || 1)*20 + (Blockly.BlockSvg.SEP_SPACE_Y+5) ;
  179. // And update the border rectangle
  180. if (this.borderRect_) {
  181. this.borderRect_.setAttribute('width',
  182. this.size_.width + Blockly.BlockSvg.SEP_SPACE_X);
  183. this.borderRect_.setAttribute('height',
  184. this.size_.height - (Blockly.BlockSvg.SEP_SPACE_Y+5));
  185. }
  186. }
  187. };
  188. /**
  189. * Show the inline free-text editor on top of the text.
  190. * @param {boolean=} opt_quietInput True if editor should be created without
  191. * focus. Defaults to false.
  192. * @private
  193. */
  194. Blockly.FieldTable.prototype.showEditor_ = function(opt_quietInput) {
  195. var quietInput = opt_quietInput || false;
  196. if (!quietInput && (goog.userAgent.MOBILE || goog.userAgent.ANDROID ||
  197. goog.userAgent.IPAD)) {
  198. // Mobile browsers have issues with in-line textareas (focus & keyboards).
  199. var newValue = window.prompt(Blockly.Msg.CHANGE_VALUE_TITLE, this.text_);
  200. if (this.changeHandler_) {
  201. var override = this.changeHandler_(newValue);
  202. if (override !== undefined) {
  203. newValue = override;
  204. }
  205. }
  206. if (newValue !== null) {
  207. this.setText(newValue);
  208. }
  209. return;
  210. }
  211. Blockly.WidgetDiv.show(this, this.sourceBlock_.RTL, this.widgetDispose_());
  212. var div = Blockly.WidgetDiv.DIV;
  213. // Create the input.
  214. var htmlInput = goog.dom.createDom('table', 'blocklyHtmlInput');
  215. Blockly.FieldTable.htmlInput_ = htmlInput;
  216. htmlInput.style.resize = 'none';
  217. htmlInput.style['line-height'] = '20px';
  218. htmlInput.style['overflow'] = 'hidden';
  219. htmlInput.style.height = '100%';//this.size_.height - Blockly.BlockSvg.SEP_SPACE_Y + 'px';
  220. div.appendChild(htmlInput);
  221. htmlInput.value = htmlInput.defaultValue = this.text_;
  222. htmlInput.oldValue_ = null;
  223. this.validate_();
  224. this.resizeEditor_();
  225. if (!quietInput) {
  226. htmlInput.focus();
  227. }
  228. // Bind to keydown -- trap Enter without IME and Esc to hide.
  229. htmlInput.onKeyDownWrapper_ =
  230. Blockly.bindEvent_(htmlInput, 'keydown', this, this.onHtmlInputKeyDown_);
  231. // Bind to keyup -- trap Enter; resize after every keystroke.
  232. // Bind to keyup -- trap Enter and Esc; resize after every keystroke.
  233. htmlInput.onKeyUpWrapper_ =
  234. Blockly.bindEvent_(htmlInput, 'keyup', this, this.onHtmlInputChange_);
  235. // Bind to keyPress -- repeatedly resize when holding down a key.
  236. htmlInput.onKeyPressWrapper_ =
  237. Blockly.bindEvent_(htmlInput, 'keypress', this, this.onHtmlInputChange_);
  238. var workspaceSvg = this.sourceBlock_.workspace.getCanvas();
  239. htmlInput.onWorkspaceChangeWrapper_ =
  240. Blockly.bindEvent_(workspaceSvg, 'blocklyWorkspaceChange', this,
  241. this.resizeEditor_);
  242. };
  243. /**
  244. * Handle key down to the editor.
  245. * @param {!Event} e Keyboard event.
  246. * @private
  247. */
  248. Blockly.FieldTable.prototype.onHtmlInputKeyDown_ = function(e) {
  249. var htmlInput = Blockly.FieldTable.htmlInput_;
  250. var escKey = 27;
  251. if (e.keyCode == escKey) {
  252. this.setText(htmlInput.defaultValue);
  253. Blockly.WidgetDiv.hide();
  254. }
  255. };
  256. /**
  257. * Handle a change to the editor.
  258. * @param {!Event} e Keyboard event.
  259. * @private
  260. */
  261. Blockly.FieldTable.prototype.onHtmlInputChange_ = function(e) {
  262. var htmlInput = Blockly.FieldTable.htmlInput_;
  263. var escKey = 27;
  264. if (e.keyCode == escKey) {
  265. // Esc
  266. this.setText(htmlInput.defaultValue);
  267. Blockly.WidgetDiv.hide();
  268. } else {
  269. // Update source block.
  270. var text = htmlInput.value;
  271. if (text !== htmlInput.oldValue_) {
  272. htmlInput.oldValue_ = text;
  273. this.setText(text);
  274. this.validate_();
  275. } else if (goog.userAgent.WEBKIT) {
  276. // Cursor key. Render the source block to show the caret moving.
  277. // Chrome only (version 26, OS X).
  278. this.sourceBlock_.render();
  279. }
  280. this.resizeEditor_();
  281. }
  282. };
  283. Blockly.FieldTable.prototype.getData = function() {
  284. return this.data_;
  285. // TODO
  286. // Loop through grabbing everything
  287. /*var myRows = [];
  288. var $headers = $("th");
  289. var $rows = $("tbody tr").each(function(index) {
  290. $cells = $(this).find("td");
  291. myRows[index] = {};
  292. $cells.each(function(cellIndex) {
  293. myRows[index][$($headers[cellIndex]).html()] = $(this).html();
  294. });
  295. });*/
  296. };
  297. /**
  298. * Resize the editor and the underlying block to fit the text.
  299. * @private
  300. */
  301. Blockly.FieldTable.prototype.resizeEditor_ = function() {
  302. var div = Blockly.WidgetDiv.DIV;
  303. var bBox = this.fieldGroup_.getBBox();
  304. var htmlInput = Blockly.FieldTable.htmlInput_;
  305. //div.style.width = bBox.width + 'px';
  306. if (htmlInput.clientHeight < htmlInput.scrollHeight) {
  307. div.style.width = (bBox.width) + 'px';
  308. } else {
  309. div.style.width = bBox.width + 'px';
  310. }
  311. div.style.height = bBox.height + 'px';
  312. // Position the editor
  313. var xy = this.getAbsoluteXY_();
  314. // In RTL mode block fields and LTR input fields the left edge moves,
  315. // whereas the right edge is fixed. Reposition the editor.
  316. if (this.sourceBlock_.RTL) {
  317. var borderBBox = this.borderRect_.getBBox();
  318. xy.x += borderBBox.width;
  319. xy.x -= div.offsetWidth;
  320. }
  321. // Shift by a few pixels to line up exactly.
  322. xy.y += 1;
  323. if (goog.userAgent.WEBKIT) {
  324. xy.y -= 3;
  325. }
  326. div.style.left = xy.x + 'px';
  327. div.style.top = xy.y + 'px';
  328. };
  329. /**
  330. * Close the editor, save the results, and dispose of the editable
  331. * text field's elements.
  332. * @return {!Function} Closure to call on destruction of the WidgetDiv.
  333. * @private
  334. */
  335. Blockly.FieldTable.prototype.widgetDispose_ = function() {
  336. var thisField = this;
  337. return function() {
  338. var htmlInput = Blockly.FieldTable.htmlInput_;
  339. // Save the edit (if it validates).
  340. var text = htmlInput.value;
  341. if (thisField.changeHandler_) {
  342. text = thisField.changeHandler_(text);
  343. if (text === null) {
  344. // Invalid edit.
  345. text = htmlInput.defaultValue;
  346. }
  347. }
  348. thisField.setText(text);
  349. thisField.sourceBlock_.rendered && thisField.sourceBlock_.render();
  350. Blockly.unbindEvent_(htmlInput.onKeyUpWrapper_);
  351. Blockly.unbindEvent_(htmlInput.onKeyPressWrapper_);
  352. Blockly.unbindEvent_(htmlInput.onWorkspaceChangeWrapper_);
  353. Blockly.FieldTable.htmlInput_ = null;
  354. // Delete the width property.
  355. Blockly.WidgetDiv.DIV.style.width = 'auto';
  356. };
  357. };