form.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = global || self, global.WebIO = factory());
  5. }(this, (function () {
  6. 'use strict';
  7. const b64toBlob = (b64Data, contentType = 'application/octet-stream', sliceSize = 512) => {
  8. const byteCharacters = atob(b64Data);
  9. const byteArrays = [];
  10. for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
  11. const slice = byteCharacters.slice(offset, offset + sliceSize);
  12. const byteNumbers = new Array(slice.length);
  13. for (let i = 0; i < slice.length; i++) {
  14. byteNumbers[i] = slice.charCodeAt(i);
  15. }
  16. const byteArray = new Uint8Array(byteNumbers);
  17. byteArrays.push(byteArray);
  18. }
  19. const blob = new Blob(byteArrays, {type: contentType});
  20. return blob;
  21. };
  22. function extend(Child, Parent) {
  23. var F = function () {
  24. };
  25. F.prototype = Parent.prototype;
  26. Child.prototype = new F();
  27. Child.prototype.constructor = Child;
  28. Child.uber = Parent.prototype;
  29. }
  30. function make_set(arr) {
  31. var set = {};
  32. for (var idx in arr)
  33. set[arr[idx]] = '';
  34. return set;
  35. }
  36. function deep_copy(obj) {
  37. return JSON.parse(JSON.stringify(obj));
  38. }
  39. function LRUMap() {
  40. this.keys = [];
  41. this.map = {};
  42. this.push = function (key, value) {
  43. if (key in this.map)
  44. return console.error("LRUMap: key:%s already in map", key);
  45. this.keys.push(key);
  46. this.map[key] = value;
  47. };
  48. this.get_value = function (key) {
  49. return this.map[key];
  50. };
  51. this.get_top = function () {
  52. var top_key = this.keys[this.keys.length - 1];
  53. return this.map[top_key];
  54. };
  55. this.set_value = function (key, value) {
  56. if (!(key in this.map))
  57. return console.error("LRUMap: key:%s not in map when call `set_value`", key);
  58. this.map[key] = value;
  59. };
  60. this.move_to_top = function (key) {
  61. const index = this.keys.indexOf(key);
  62. if (index > -1) {
  63. this.keys.splice(index, 1);
  64. this.keys.push(key);
  65. } else {
  66. return console.error("LRUMap: key:%s not in map when call `move_to_top`", key);
  67. }
  68. };
  69. this.remove = function (key) {
  70. if (key in this.map) {
  71. delete this.map[key];
  72. this.keys.splice(this.keys.indexOf(key), 1);
  73. } else {
  74. return console.error("LRUMap: key:%s not in map when call `remove`", key);
  75. }
  76. };
  77. }
  78. var AutoScrollBottom = true; // 是否有新内容时自动滚动到底部
  79. OutputController.prototype.accept_command = ['output', 'output_ctl'];
  80. function OutputController(ws_client, container_elem) {
  81. this.ws_client = ws_client;
  82. this.container_elem = $(container_elem);
  83. this.md_parser = new Mditor.Parser();
  84. this.container_parent = this.container_elem.parent();
  85. this.body = $('html,body');
  86. }
  87. OutputController.prototype.scroll_bottom = function () {
  88. this.container_parent.stop().animate({scrollTop: this.container_parent[0].scrollHeight}, 700);
  89. var that = this;
  90. setTimeout(function () {
  91. // body.scrollTop(body[0].scrollHeight); // 整个页面自动滚动
  92. that.body.stop().animate({scrollTop: that.body[0].scrollHeight}, 700);
  93. }, ShowDuration + 10);
  94. };
  95. OutputController.prototype.handle_message = function (msg) {
  96. if (msg.command === 'output') {
  97. const func_name = `get_${msg.spec.type}_element`;
  98. if (!(func_name in OutputController.prototype)) {
  99. return console.error('Unknown output type:%s', msg.spec.type);
  100. }
  101. var elem = OutputController.prototype[func_name].call(this, msg.spec);
  102. if (msg.spec.anchor !== undefined) {
  103. this.container_elem.find(`#${msg.spec.anchor}`).attr('id', '');
  104. elem.attr('id', msg.spec.anchor);
  105. }
  106. if (msg.spec.before !== undefined) {
  107. this.container_elem.find('#' + msg.spec.before).before(elem);
  108. } else if (msg.spec.after !== undefined) {
  109. this.container_elem.find('#' + msg.spec.after).after(elem);
  110. } else {
  111. this.container_elem.append(elem);
  112. }
  113. } else if (msg.command === 'output_ctl') {
  114. this.handle_output_ctl(msg);
  115. }
  116. // note:当接收到scroll_to指令时,忽略AutoScrollBottom
  117. if (AutoScrollBottom && !(msg.command === 'output_ctl' && msg.spec.scroll_to !== undefined))
  118. this.scroll_bottom();
  119. };
  120. // OutputController.prototype.get_[output_type]_element return a jQuery obj
  121. OutputController.prototype.get_text_element = function (spec) {
  122. var elem = $('<p></p>');
  123. // make '\n' to <br/>
  124. var lines = (spec.content || '').split('\n');
  125. for (var idx = 0; idx < lines.length - 1; idx++)
  126. elem.append(document.createTextNode(lines[idx])).append('<br/>');
  127. elem.append(document.createTextNode(lines[lines.length - 1]));
  128. return elem;
  129. };
  130. OutputController.prototype.get_markdown_element = function (spec) {
  131. return $(this.md_parser.parse(spec.content));
  132. };
  133. OutputController.prototype.get_html_element = function (spec) {
  134. return $($.parseHTML(spec.content));
  135. };
  136. OutputController.prototype.get_buttons_element = function (spec) {
  137. const btns_tpl = `<div class="form-group">{{#buttons}}
  138. <button value="{{value}}" onclick="WebIO.DisplayAreaButtonOnClick(this, '{{callback_id}}')" class="btn btn-primary {{#small}}btn-sm{{/small}}">{{label}}</button>
  139. {{/buttons}}</div>`;
  140. var html = Mustache.render(btns_tpl, spec);
  141. return $(html);
  142. };
  143. OutputController.prototype.get_file_element = function (spec) {
  144. const html = `<div class="form-group"><button type="button" class="btn btn-link">${spec.name}</button></div>`;
  145. var element = $(html);
  146. var blob = b64toBlob(spec.content);
  147. element.on('click', 'button', function (e) {
  148. saveAs(blob, spec.name, {}, false);
  149. });
  150. return element;
  151. };
  152. OutputController.prototype.handle_output_ctl = function (msg) {
  153. if (msg.spec.title) {
  154. $('#title').text(msg.spec.title); // 直接使用#title不规范 todo
  155. document.title = msg.spec.title;
  156. }
  157. if (msg.spec.output_fixed_height !== undefined)
  158. if (msg.spec.output_fixed_height)
  159. $('.container').removeClass('no-fix-height'); // todo 不规范
  160. else
  161. $('.container').addClass('no-fix-height'); // todo 不规范
  162. if (msg.spec.auto_scroll_bottom !== undefined)
  163. AutoScrollBottom = msg.spec.auto_scroll_bottom;
  164. if (msg.spec.set_anchor !== undefined) {
  165. this.container_elem.find(`#${msg.spec.set_anchor}`).attr('id','');
  166. this.container_elem.append(`<div id="${msg.spec.set_anchor}"></div>`);
  167. }
  168. if (msg.spec.clear_before !== undefined)
  169. this.container_elem.find(`#${msg.spec.clear_before}`).prevAll().remove();
  170. if (msg.spec.clear_after !== undefined)
  171. this.container_elem.find(`#${msg.spec.clear_after}~*`).remove();
  172. if (msg.spec.scroll_to !== undefined)
  173. $([document.documentElement, document.body]).animate({
  174. scrollTop: $(`#${msg.spec.scroll_to}`).offset().top
  175. }, 400);
  176. if (msg.spec.clear_range !== undefined) {
  177. if (this.container_elem.find(`#${msg.spec.clear_range[0]}`).length &&
  178. this.container_elem.find(`#${msg.spec.clear_range[1]}`).length) {
  179. this.container_elem.find(`#${msg.spec.clear_range[0]}~*`).each(function () {
  180. if (this.id === msg.spec.clear_range[1])
  181. return false;
  182. $(this).remove();
  183. });
  184. }
  185. }
  186. };
  187. // 显示区按钮点击回调函数
  188. function DisplayAreaButtonOnClick(this_ele, callback_id) {
  189. if (WSClient === undefined)
  190. return console.error("can't invoke DisplayAreaButtonOnClick when WebIOController is not instantiated");
  191. var val = $(this_ele).val();
  192. WSClient.send(JSON.stringify({
  193. event: "callback",
  194. coro_id: callback_id,
  195. data: val
  196. }));
  197. }
  198. const ShowDuration = 200; // ms, 显示表单的过渡动画时长
  199. FormsController.prototype.accept_command = ['input', 'input_group', 'update_input', 'destroy_form'];
  200. function FormsController(ws_client, container_elem) {
  201. this.ws_client = ws_client;
  202. this.container_elem = container_elem;
  203. this.form_ctrls = new LRUMap(); // coro_id -> stack of FormGroupController
  204. // hide old_ctrls显示的表单,激活coro_id对应的表单
  205. // 需要保证 coro_id 对应有表单
  206. this._activate_form = function (coro_id, old_ctrl) {
  207. var ctrls = this.form_ctrls.get_value(coro_id);
  208. var ctrl = ctrls[ctrls.length - 1];
  209. if (ctrl === old_ctrl || old_ctrl === undefined) {
  210. console.log('开:%s', ctrl.spec.label);
  211. return ctrl.element.show(ShowDuration, function () {
  212. if (AutoScrollBottom)
  213. $('[auto_focus]').focus();
  214. });
  215. }
  216. this.form_ctrls.move_to_top(coro_id);
  217. var that = this;
  218. old_ctrl.element.hide(100, () => {
  219. // ctrl.element.show(100);
  220. // 需要在回调中重新获取当前前置表单元素,因为100ms内可能有变化
  221. var t = that.form_ctrls.get_top();
  222. if (t) t[t.length - 1].element.show(ShowDuration, function () {
  223. if (AutoScrollBottom)
  224. $('[auto_focus]').focus();
  225. });
  226. });
  227. };
  228. // var that = this;
  229. // this.msg_queue = async.queue((msg) => {
  230. // that.consume_message(msg)
  231. // }, 1);
  232. //
  233. // var l = new Lock(this.consume_message);
  234. this.handle_message_ = function (msg) {
  235. // this.msg_queue.push(msg);
  236. // l.mutex_run(that, msg);
  237. // console.log('start handle_message %s %s', msg.command, msg.spec.label);
  238. this.consume_message(msg);
  239. // console.log('end handle_message %s %s', msg.command, msg.spec.label);
  240. };
  241. /*
  242. * 每次函数调用返回后,this.form_ctrls.get_top()的栈顶对应的表单为当前活跃表单
  243. * */
  244. this.handle_message = function (msg) {
  245. var old_ctrls = this.form_ctrls.get_top();
  246. var old_ctrl = old_ctrls && old_ctrls[old_ctrls.length - 1];
  247. var target_ctrls = this.form_ctrls.get_value(msg.coro_id);
  248. if (target_ctrls === undefined) {
  249. this.form_ctrls.push(msg.coro_id, []);
  250. target_ctrls = this.form_ctrls.get_value(msg.coro_id);
  251. }
  252. // 创建表单
  253. if (msg.command in make_set(['input', 'input_group'])) {
  254. var ctrl = new FormController(this.ws_client, msg.coro_id, msg.spec);
  255. target_ctrls.push(ctrl);
  256. this.container_elem.append(ctrl.element);
  257. this._activate_form(msg.coro_id, old_ctrl);
  258. } else if (msg.command in make_set(['update_input'])) {
  259. // 更新表单
  260. if (target_ctrls.length === 0) {
  261. return console.error('No form to current message. coro_id:%s', msg.coro_id);
  262. }
  263. target_ctrls[target_ctrls.length - 1].dispatch_ctrl_message(msg.spec);
  264. // 表单前置 removed
  265. // this._activate_form(msg.coro_id, old_ctrl);
  266. } else if (msg.command === 'destroy_form') {
  267. if (target_ctrls.length === 0) {
  268. return console.error('No form to current message. coro_id:%s', msg.coro_id);
  269. }
  270. var deleted = target_ctrls.pop();
  271. if (target_ctrls.length === 0)
  272. this.form_ctrls.remove(msg.coro_id);
  273. // 销毁的是当前显示的form
  274. if (old_ctrls === target_ctrls) {
  275. var that = this;
  276. deleted.element.hide(100, () => {
  277. deleted.element.remove();
  278. var t = that.form_ctrls.get_top();
  279. if (t) t[t.length - 1].element.show(ShowDuration, function () {
  280. if (AutoScrollBottom)
  281. $('[auto_focus]').focus();
  282. });
  283. });
  284. } else {
  285. deleted.element.remove();
  286. }
  287. }
  288. }
  289. }
  290. function FormStack() {
  291. push();
  292. pop();
  293. empty();
  294. show();// 显示栈顶元素
  295. hide();// 隐藏栈顶元素
  296. }
  297. function FormController(ws_client, coro_id, spec) {
  298. this.ws_client = ws_client;
  299. this.coro_id = coro_id;
  300. this.spec = spec;
  301. this.element = undefined;
  302. this.name2input_controllers = {}; // name -> input_controller
  303. this.create_element();
  304. }
  305. FormController.prototype.input_controllers = [FileInputController, CommonInputController, CheckboxRadioController, ButtonsController, TextareaInputController];
  306. FormController.prototype.create_element = function () {
  307. var tpl = `
  308. <div class="card" style="display: none">
  309. <h5 class="card-header">{{label}}</h5>
  310. <div class="card-body">
  311. <form>
  312. <div class="input-container"></div>
  313. <div class="ws-form-submit-btns">
  314. <button type="submit" class="btn btn-primary">提交</button>
  315. <button type="reset" class="btn btn-warning">重置</button>
  316. </div>
  317. </form>
  318. </div>
  319. </div>`;
  320. const html = Mustache.render(tpl, {label: this.spec.label});
  321. this.element = $(html);
  322. // 如果表单最后一个输入元素为actions组件,则隐藏默认的"提交"/"重置"按钮
  323. if (this.spec.inputs.length && this.spec.inputs[this.spec.inputs.length - 1].type === 'actions')
  324. this.element.find('.ws-form-submit-btns').hide();
  325. // 输入控件创建
  326. var body = this.element.find('.input-container');
  327. for (var idx in this.spec.inputs) {
  328. var input_spec = this.spec.inputs[idx];
  329. var ctrl = undefined;
  330. for (var i in this.input_controllers) {
  331. var ctrl_cls = this.input_controllers[i];
  332. // console.log(ctrl_cls, ctrl_cls.prototype.accept_input_types);
  333. if (input_spec.type in make_set(ctrl_cls.prototype.accept_input_types)) {
  334. ctrl = new ctrl_cls(this.ws_client, this.coro_id, input_spec);
  335. break;
  336. }
  337. }
  338. if (ctrl) {
  339. this.name2input_controllers[input_spec.name] = ctrl;
  340. body.append(ctrl.element);
  341. } else {
  342. console.error('Unvalid input type:%s', input_spec.type);
  343. }
  344. }
  345. // 事件绑定
  346. var that = this;
  347. this.element.on('submit', 'form', function (e) {
  348. e.preventDefault(); // avoid to execute the actual submit of the form.
  349. var data = {};
  350. $.each(that.name2input_controllers, (name, ctrl) => {
  351. data[name] = ctrl.get_value();
  352. });
  353. ws.send(JSON.stringify({
  354. event: "from_submit",
  355. coro_id: that.coro_id,
  356. data: data
  357. }));
  358. });
  359. };
  360. FormController.prototype.dispatch_ctrl_message = function (spec) {
  361. if (!(spec.target_name in this.name2input_controllers)) {
  362. return console.error('Can\'t find input[name=%s] element in curr form!', spec.target_name);
  363. }
  364. this.name2input_controllers[spec.target_name].update_input(spec);
  365. };
  366. function FormItemController(ws_client, coro_id, spec) {
  367. this.ws_client = ws_client;
  368. this.coro_id = coro_id;
  369. this.spec = spec;
  370. this.element = undefined;
  371. var that = this;
  372. this.send_value_listener = function (e) {
  373. var this_elem = $(this);
  374. that.ws_client.send(JSON.stringify({
  375. event: "input_event",
  376. coro_id: that.coro_id,
  377. data: {
  378. event_name: e.type.toLowerCase(),
  379. name: that.spec.name,
  380. value: that.get_value()
  381. }
  382. }));
  383. };
  384. /*
  385. * input_idx: 更新作用对象input标签的索引, -1 为不指定对象
  386. * attributes:更新值字典
  387. * */
  388. this.update_input_helper = function (input_idx, attributes) {
  389. var attr2selector = {
  390. 'invalid_feedback': 'div.invalid-feedback',
  391. 'valid_feedback': 'div.valid-feedback',
  392. 'help_text': 'small.text-muted'
  393. };
  394. for (var attribute in attr2selector) {
  395. if (attribute in attributes) {
  396. if (input_idx === -1)
  397. this.element.find(attr2selector[attribute]).text(attributes[attribute]);
  398. else
  399. this.element.find(attr2selector[attribute]).eq(input_idx).text(attributes[attribute]);
  400. delete attributes[attribute];
  401. }
  402. }
  403. var input_elem = this.element.find('input,select');
  404. if (input_idx >= 0)
  405. input_elem = input_elem.eq(input_idx);
  406. if ('valid_status' in attributes) {
  407. var class_name = attributes.valid_status ? 'is-valid' : 'is-invalid';
  408. input_elem.removeClass('is-valid is-invalid').addClass(class_name);
  409. delete attributes.valid_status;
  410. }
  411. input_elem.attr(attributes);
  412. }
  413. }
  414. function CommonInputController(ws_client, coro_id, spec) {
  415. FormItemController.apply(this, arguments);
  416. this.create_element();
  417. }
  418. CommonInputController.prototype.accept_input_types = ["text", "password", "number", "color", "date", "range", "time", "select", "file"];
  419. /*
  420. *
  421. * type=
  422. * */
  423. const common_input_tpl = `
  424. <div class="form-group">
  425. <label for="{{id_name}}">{{label}}</label>
  426. <input type="{{type}}" id="{{id_name}}" aria-describedby="{{id_name}}_help" {{#list}}list="{{list}}"{{/list}} class="form-control" >
  427. <datalist id="{{id_name}}-list">
  428. {{#datalist}}
  429. <option>{{.}}</option>
  430. {{/datalist}}
  431. </datalist>
  432. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  433. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  434. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  435. </div>`;
  436. const select_input_tpl = `
  437. <div class="form-group">
  438. <label for="{{id_name}}">{{label}}</label>
  439. <select id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control">
  440. {{#options}}
  441. <option value="{{value}}" {{#selected}}selected{{/selected}} {{#disabled}}disabled{{/disabled}}>{{label}}</option>
  442. {{/options}}
  443. </select>
  444. <div class="invalid-feedback">{{invalid_feedback}}</div>
  445. <div class="valid-feedback">{{valid_feedback}}</div>
  446. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  447. </div>`;
  448. CommonInputController.prototype.create_element = function () {
  449. var spec = deep_copy(this.spec);
  450. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  451. spec['id_name'] = id_name;
  452. if (spec.datalist)
  453. spec['list'] = id_name + '-list';
  454. var html;
  455. if (spec.type === 'select')
  456. html = Mustache.render(select_input_tpl, spec);
  457. else
  458. html = Mustache.render(common_input_tpl, spec);
  459. this.element = $(html);
  460. var input_elem = this.element.find('#' + id_name);
  461. // blur事件时,发送当前值到服务器
  462. input_elem.on('blur', this.send_value_listener);
  463. // 将额外的html参数加到input标签上
  464. const ignore_keys = {
  465. 'type': '',
  466. 'label': '',
  467. 'invalid_feedback': '',
  468. 'valid_feedback': '',
  469. 'help_text': '',
  470. 'options': '',
  471. 'datalist': ''
  472. };
  473. for (var key in this.spec) {
  474. if (key in ignore_keys) continue;
  475. input_elem.attr(key, this.spec[key]);
  476. }
  477. };
  478. CommonInputController.prototype.update_input = function (spec) {
  479. var attributes = spec.attributes;
  480. this.update_input_helper(-1, attributes);
  481. };
  482. CommonInputController.prototype.get_value = function () {
  483. return this.element.find('input,select').val();
  484. };
  485. function TextareaInputController(ws_client, coro_id, spec) {
  486. FormItemController.apply(this, arguments);
  487. this.create_element();
  488. }
  489. TextareaInputController.prototype.accept_input_types = ["textarea"];
  490. const textarea_input_tpl = `
  491. <div class="form-group">
  492. <label for="{{id_name}}">{{label}}</label>
  493. <textarea id="{{id_name}}" aria-describedby="{{id_name}}_help" rows="{{rows}}" class="form-control" >{{value}}</textarea>
  494. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  495. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  496. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  497. </div>`;
  498. TextareaInputController.prototype.create_element = function () {
  499. var spec = deep_copy(this.spec);
  500. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  501. spec['id_name'] = id_name;
  502. var html = Mustache.render(textarea_input_tpl, spec);
  503. this.element = $(html);
  504. var input_elem = this.element.find('#' + id_name);
  505. // blur事件时,发送当前值到服务器
  506. // input_elem.on('blur', this.send_value_listener);
  507. // 将额外的html参数加到input标签上
  508. const ignore_keys = make_set(['value', 'type', 'label', 'invalid_feedback', 'valid_feedback', 'help_text', 'rows', 'codemirror']);
  509. for (var key in this.spec) {
  510. if (key in ignore_keys) continue;
  511. input_elem.attr(key, this.spec[key]);
  512. }
  513. if (spec.codemirror) {
  514. var that = this;
  515. setTimeout(function () {
  516. var config = {
  517. 'lineNumbers': true, // 显示行数
  518. 'indentUnit': 4, //缩进单位为4
  519. 'styleActiveLine': true, // 当前行背景高亮
  520. 'matchBrackets': true, //括号匹配
  521. 'lineWrapping': true, //自动换行
  522. };
  523. for (var k in that.spec.codemirror) config[k] = that.spec.codemirror[k];
  524. that.code_mirror = CodeMirror.fromTextArea(that.element.find('textarea')[0], config);
  525. CodeMirror.autoLoadMode(that.code_mirror, that.spec.codemirror.mode);
  526. }, ShowDuration + 100);
  527. }
  528. };
  529. TextareaInputController.prototype.update_input = function (spec) {
  530. var attributes = spec.attributes;
  531. this.update_input_helper(-1, attributes);
  532. };
  533. TextareaInputController.prototype.get_value = function () {
  534. return this.element.find('textarea').val();
  535. };
  536. function CheckboxRadioController(ws_client, coro_id, spec) {
  537. FormItemController.apply(this, arguments);
  538. this.create_element();
  539. }
  540. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  541. const checkbox_radio_tpl = `
  542. <div class="form-group">
  543. <label>{{label}}</label> {{#inline}}<br>{{/inline}}
  544. {{#options}}
  545. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  546. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" name="{{name}}" value="{{value}}" {{#selected}}checked{{/selected}} {{#disabled}}disabled{{/disabled}} class="form-check-input">
  547. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  548. {{label}}
  549. </label>
  550. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  551. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  552. </div>
  553. {{/options}}
  554. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  555. </div>`;
  556. CheckboxRadioController.prototype.create_element = function () {
  557. var spec = deep_copy(this.spec);
  558. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  559. spec['id_name_prefix'] = id_name_prefix;
  560. for (var idx in spec.options) {
  561. spec.options[idx]['idx'] = idx;
  562. }
  563. const html = Mustache.render(checkbox_radio_tpl, spec);
  564. var elem = $(html);
  565. this.element = elem;
  566. const ignore_keys = {'value': '', 'label': '', 'selected': ''};
  567. for (idx = 0; idx < this.spec.options.length; idx++) {
  568. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  569. // blur事件时,发送当前值到服务器
  570. // checkbox_radio 不产生blur事件
  571. // input_elem.on('blur', this.send_value_listener);
  572. // 将额外的html参数加到input标签上
  573. for (var key in this.spec.options[idx]) {
  574. if (key in ignore_keys) continue;
  575. input_elem.attr(key, this.spec.options[idx][key]);
  576. }
  577. }
  578. };
  579. CheckboxRadioController.prototype.update_input = function (spec) {
  580. var attributes = spec.attributes;
  581. var idx = -1;
  582. if ('target_value' in spec) {
  583. this.element.find('input').each(function (index) {
  584. if ($(this).val() === spec.target_value) {
  585. idx = index;
  586. return false;
  587. }
  588. });
  589. }
  590. this.update_input_helper(idx, attributes);
  591. };
  592. CheckboxRadioController.prototype.get_value = function () {
  593. if (this.spec.type === 'radio') {
  594. return this.element.find('input').val();
  595. } else {
  596. var value_arr = this.element.find('input').serializeArray();
  597. var res = [];
  598. var that = this;
  599. $.each(value_arr, function (idx, val) {
  600. if (val.name === that.spec.name)
  601. res.push(val.value);
  602. });
  603. return res;
  604. }
  605. };
  606. function ButtonsController(ws_client, coro_id, spec) {
  607. FormItemController.apply(this, arguments);
  608. this.last_checked_value = null; // 上次点击按钮的value
  609. this.create_element();
  610. }
  611. ButtonsController.prototype.accept_input_types = ["actions"];
  612. const buttons_tpl = `
  613. <div class="form-group">
  614. <label>{{label}}</label> <br>
  615. {{#buttons}}
  616. <button type="submit" value="{{value}}" aria-describedby="{{name}}_help" {{#disabled}}disabled{{/disabled}} class="btn btn-primary">{{label}}</button>
  617. {{/buttons}}
  618. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  619. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  620. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  621. </div>`;
  622. ButtonsController.prototype.create_element = function () {
  623. const html = Mustache.render(buttons_tpl, this.spec);
  624. this.element = $(html);
  625. // todo:是否有必要监听click事件,因为点击后即提交了表单
  626. var that = this;
  627. this.element.find('button').on('click', function (e) {
  628. var btn = $(this);
  629. that.last_checked_value = btn.val();
  630. });
  631. };
  632. ButtonsController.prototype.update_input = function (spec) {
  633. var attributes = spec.attributes;
  634. var idx = -1;
  635. if ('target_value' in spec) {
  636. this.element.find('button').each(function (index) {
  637. if ($(this).val() === spec.target_value) {
  638. idx = index;
  639. return false;
  640. }
  641. });
  642. }
  643. this.update_input_helper(idx, attributes);
  644. };
  645. ButtonsController.prototype.get_value = function () {
  646. return this.last_checked_value;
  647. };
  648. function FileInputController(ws_client, coro_id, spec) {
  649. FormItemController.apply(this, arguments);
  650. this.data_url_value = null;
  651. this.create_element();
  652. }
  653. FileInputController.prototype.accept_input_types = ["file"];
  654. const file_input_tpl = `
  655. <div class="form-group">
  656. <label for="customFile">{{label}}</label>
  657. <div class="custom-file">
  658. <input type="file" class="custom-file-input" id="{{name}}" aria-describedby="{{name}}_help">
  659. <label class="custom-file-label" for="{{name}}">{{placeholder}}</label>
  660. </div>
  661. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  662. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  663. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  664. </div>`;
  665. FileInputController.prototype.create_element = function () {
  666. var spec = deep_copy(this.spec);
  667. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  668. spec['id_name'] = id_name;
  669. const html = Mustache.render(file_input_tpl, spec);
  670. this.element = $(html);
  671. var input_elem = this.element.find('input[type="file"]');
  672. const ignore_keys = {
  673. 'label': '',
  674. 'invalid_feedback': '',
  675. 'valid_feedback': '',
  676. 'help_text': '',
  677. 'placeholder': ''
  678. };
  679. for (var key in this.spec) {
  680. if (key in ignore_keys) continue;
  681. input_elem.attr(key, this.spec[key]);
  682. }
  683. // 文件选中后先不通知后端
  684. var that = this;
  685. input_elem.on('change', function () {
  686. var file = input_elem[0].files[0];
  687. var fr = new FileReader();
  688. fr.onload = function () {
  689. that.data_url_value = {
  690. 'filename': file.name, 'dataurl': fr.result
  691. };
  692. console.log(that.data_url_value);
  693. };
  694. fr.readAsDataURL(file);
  695. });
  696. // todo 通过回调的方式调用init
  697. setTimeout(bsCustomFileInput.init, ShowDuration + 100);
  698. };
  699. FileInputController.prototype.update_input = function (spec) {
  700. var attributes = spec.attributes;
  701. this.update_input_helper(-1, attributes);
  702. };
  703. FileInputController.prototype.get_value = function () {
  704. return this.data_url_value;
  705. };
  706. var WSClient;
  707. function WebIOController(ws_client, output_container_elem, input_container_elem) {
  708. WSClient = ws_client;
  709. this.output_ctrl = new OutputController(ws_client, output_container_elem);
  710. this.input_ctrl = new FormsController(ws_client, input_container_elem);
  711. this.output_cmds = make_set(this.output_ctrl.accept_command);
  712. this.input_cmds = make_set(this.input_ctrl.accept_command);
  713. this.handle_message = function (msg) {
  714. if (msg.command in this.input_cmds)
  715. this.input_ctrl.handle_message(msg);
  716. else if (msg.command in this.output_cmds)
  717. this.output_ctrl.handle_message(msg);
  718. else
  719. console.error('Unknown command:%s', msg.command);
  720. };
  721. }
  722. return {
  723. 'WebIOController': WebIOController,
  724. 'DisplayAreaButtonOnClick': DisplayAreaButtonOnClick,
  725. }
  726. })));