form.js 30 KB

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