form.js 28 KB

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