form.js 32 KB

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