form.js 29 KB

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