form.js 32 KB

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