form.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. this.container_elem[0].innerHTML += this.md_parser.parse(msg.spec.content);
  86. }
  87. }
  88. OutputController.prototype.accept_command = ['output'];
  89. FormsController.prototype.accept_command = ['input', 'input_group', 'update_input', 'destroy_form'];
  90. function FormsController(ws_client, container_elem) {
  91. this.ws_client = ws_client;
  92. this.container_elem = container_elem;
  93. this.form_ctrls = new LRUMap(); // coro_id -> stack of FormGroupController
  94. // hide old_ctrls显示的表单,激活coro_id对应的表单
  95. // 需要保证 coro_id 对应有表单
  96. this._activate_form = function (coro_id, old_ctrl) {
  97. var ctrls = this.form_ctrls.get_value(coro_id);
  98. var ctrl = ctrls[ctrls.length - 1];
  99. if (ctrl === old_ctrl || old_ctrl === undefined) {
  100. console.log('开:%s', ctrl.spec.label);
  101. return ctrl.element.show(200, function () {
  102. // 有时候autofocus属性不生效,手动激活一下
  103. $('[autofocus]').focus();
  104. });
  105. }
  106. this.form_ctrls.move_to_top(coro_id);
  107. var that = this;
  108. old_ctrl.element.hide(100, () => {
  109. // ctrl.element.show(100);
  110. // 需要在回调中重新获取当前前置表单元素,因为100ms内可能有变化
  111. var t = that.form_ctrls.get_top();
  112. if (t) t[t.length - 1].element.show(200, function () {
  113. // 有时候autofocus属性不生效,手动激活一下
  114. $('[autofocus]').focus();
  115. });
  116. });
  117. };
  118. var that = this;
  119. this.msg_queue = async.queue((msg) => {
  120. that.consume_message(msg)
  121. }, 1);
  122. var l = new Lock(this.consume_message);
  123. this.handle_message_ = function (msg) {
  124. // this.msg_queue.push(msg);
  125. // l.mutex_run(that, msg);
  126. // console.log('start handle_message %s %s', msg.command, msg.spec.label);
  127. this.consume_message(msg);
  128. // console.log('end handle_message %s %s', msg.command, msg.spec.label);
  129. };
  130. /*
  131. * 每次函数调用返回后,this.form_ctrls.get_top()的栈顶对应的表单为当前活跃表单
  132. * */
  133. this.handle_message = function (msg) {
  134. var old_ctrls = this.form_ctrls.get_top();
  135. var old_ctrl = old_ctrls && old_ctrls[old_ctrls.length - 1];
  136. var target_ctrls = this.form_ctrls.get_value(msg.coro_id);
  137. if (target_ctrls === undefined) {
  138. this.form_ctrls.push(msg.coro_id, []);
  139. target_ctrls = this.form_ctrls.get_value(msg.coro_id);
  140. }
  141. // 创建表单
  142. if (msg.command in make_set(['input', 'input_group'])) {
  143. var ctrl = new FormController(this.ws_client, msg.coro_id, msg.spec);
  144. target_ctrls.push(ctrl);
  145. this.container_elem.append(ctrl.element);
  146. this._activate_form(msg.coro_id, old_ctrl);
  147. } else if (msg.command in make_set(['update_input'])) {
  148. // 更新表单
  149. if (target_ctrls.length === 0) {
  150. return console.error('No form to current message. coro_id:%s', msg.coro_id);
  151. }
  152. target_ctrls[target_ctrls.length - 1].dispatch_ctrl_message(msg.spec);
  153. // 表单前置 removed
  154. // this._activate_form(msg.coro_id, old_ctrl);
  155. } else if (msg.command === 'destroy_form') {
  156. if (target_ctrls.length === 0) {
  157. return console.error('No form to current message. coro_id:%s', msg.coro_id);
  158. }
  159. var deleted = target_ctrls.pop();
  160. if (target_ctrls.length === 0)
  161. this.form_ctrls.remove(msg.coro_id);
  162. // 销毁的是当前显示的form
  163. if (old_ctrls === target_ctrls) {
  164. var that = this;
  165. deleted.element.hide(100, () => {
  166. deleted.element.remove();
  167. var t = that.form_ctrls.get_top();
  168. if (t) t[t.length - 1].element.show(200, function () {
  169. $('[autofocus]').focus();
  170. });
  171. });
  172. } else {
  173. deleted.element.remove();
  174. }
  175. }
  176. }
  177. }
  178. function FormStack() {
  179. push();
  180. pop();
  181. empty();
  182. show();// 显示栈顶元素
  183. hide();// 隐藏栈顶元素
  184. }
  185. function FormController(ws_client, coro_id, spec) {
  186. this.ws_client = ws_client;
  187. this.coro_id = coro_id;
  188. this.spec = spec;
  189. this.element = undefined;
  190. this.name2input_controllers = {}; // name -> input_controller
  191. this.create_element();
  192. }
  193. FormController.prototype.input_controllers = [CommonInputController, CheckboxRadioController, ButtonsController];
  194. FormController.prototype.create_element = function () {
  195. var tpl = `
  196. <div class="card" style="display: none">
  197. <h5 class="card-header">{{label}}</h5>
  198. <div class="card-body">
  199. <form>
  200. <div class="input-container"></div>
  201. <div class="ws-form-submit-btns">
  202. <button type="submit" class="btn btn-primary">提交</button>
  203. <button type="reset" class="btn btn-warning">重置</button>
  204. </div>
  205. </form>
  206. </div>
  207. </div>`;
  208. const html = Mustache.render(tpl, {label: this.spec.label});
  209. this.element = $(html);
  210. // 如果表单最后一个输入元素为actions组件,则隐藏默认的"提交"/"重置"按钮
  211. if(this.spec.inputs.length && this.spec.inputs[this.spec.inputs.length-1].type==='actions')
  212. this.element.find('.ws-form-submit-btns').hide();
  213. // 输入控件创建
  214. var body = this.element.find('.input-container');
  215. for (var idx in this.spec.inputs) {
  216. var input_spec = this.spec.inputs[idx];
  217. var ctrl = undefined;
  218. for (var i in this.input_controllers) {
  219. var ctrl_cls = this.input_controllers[i];
  220. // console.log(ctrl_cls, ctrl_cls.prototype.accept_input_types);
  221. if (input_spec.type in make_set(ctrl_cls.prototype.accept_input_types)) {
  222. ctrl = new ctrl_cls(this.ws_client, this.coro_id, input_spec);
  223. break;
  224. }
  225. }
  226. if (ctrl) {
  227. this.name2input_controllers[input_spec.name] = ctrl;
  228. body.append(ctrl.element);
  229. } else {
  230. console.error('Unvalid input type:%s', input_spec.type);
  231. }
  232. }
  233. // 事件绑定
  234. var that = this;
  235. this.element.on('submit', 'form', function (e) {
  236. e.preventDefault(); // avoid to execute the actual submit of the form.
  237. var data = {};
  238. $.each(that.name2input_controllers, (name, ctrl) => {
  239. data[name] = ctrl.get_value();
  240. });
  241. ws.send(JSON.stringify({
  242. event: "from_submit",
  243. coro_id: that.coro_id,
  244. data: data
  245. }));
  246. });
  247. };
  248. FormController.prototype.dispatch_ctrl_message = function (spec) {
  249. if (!(spec.target_name in this.name2input_controllers)) {
  250. return console.error('Can\'t find input[name=%s] element in curr form!', spec.target_name);
  251. }
  252. this.name2input_controllers[spec.target_name].update_input(spec);
  253. };
  254. function FormItemController(ws_client, coro_id, spec) {
  255. this.ws_client = ws_client;
  256. this.coro_id = coro_id;
  257. this.spec = spec;
  258. this.element = undefined;
  259. var that = this;
  260. this.send_value_listener = function (e) {
  261. var this_elem = $(this);
  262. that.ws_client.send(JSON.stringify({
  263. event: "input_event",
  264. coro_id: that.coro_id,
  265. data: {
  266. event_name: e.type.toLowerCase(),
  267. name: that.spec.name,
  268. value: that.get_value()
  269. }
  270. }));
  271. };
  272. /*
  273. * input_idx: 更新作用对象input标签的索引, -1 为不指定对象
  274. * attributes:更新值字典
  275. * */
  276. this.update_input_helper = function (input_idx, attributes) {
  277. var attr2selector = {
  278. 'invalid_feedback': 'div.invalid-feedback',
  279. 'valid_feedback': 'div.valid-feedback',
  280. 'help_text': 'small.text-muted'
  281. };
  282. for (var attribute in attr2selector) {
  283. if (attribute in attributes) {
  284. if (input_idx === -1)
  285. this.element.find(attr2selector[attribute]).text(attributes[attribute]);
  286. else
  287. this.element.find(attr2selector[attribute]).eq(input_idx).text(attributes[attribute]);
  288. delete attributes[attribute];
  289. }
  290. }
  291. var input_elem = this.element.find('input');
  292. if (input_idx >= 0)
  293. input_elem = input_elem.eq(input_idx);
  294. if ('valid_status' in attributes) {
  295. var class_name = attributes.valid_status ? 'is-valid' : 'is-invalid';
  296. input_elem.removeClass('is-valid is-invalid').addClass(class_name);
  297. delete attributes.valid_status;
  298. }
  299. input_elem.attr(attributes);
  300. }
  301. }
  302. function CommonInputController(ws_client, coro_id, spec) {
  303. FormItemController.apply(this, arguments);
  304. this.create_element();
  305. }
  306. CommonInputController.prototype.accept_input_types = ["text", "password", "number", "color", "date", "range", "time", "select"];
  307. /*
  308. *
  309. * type=
  310. * */
  311. const common_input_tpl = `
  312. <div class="form-group">
  313. <label for="{{id_name}}">{{label}}</label>
  314. <input type="{{type}}" id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control">
  315. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  316. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  317. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  318. </div>`;
  319. const select_input_tpl = `
  320. <div class="form-group">
  321. <label for="{{id_name}}">{{label}}</label>
  322. <select id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control">
  323. {{#options}}
  324. <option value="{{value}}" {{#selected}}selected{{/selected}} {{#disabled}}disabled{{/disabled}}>{{label}}</option>
  325. {{/options}}
  326. </select>
  327. <div class="invalid-feedback">{{invalid_feedback}}</div>
  328. <div class="valid-feedback">{{valid_feedback}}</div>
  329. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  330. </div>`;
  331. CommonInputController.prototype.create_element = function () {
  332. var spec = deep_copy(this.spec);
  333. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  334. spec['id_name'] = id_name;
  335. var html;
  336. if (spec.type === 'select')
  337. html = Mustache.render(select_input_tpl, spec);
  338. else
  339. html = Mustache.render(common_input_tpl, spec);
  340. this.element = $(html);
  341. var input_elem = this.element.find('#' + id_name);
  342. // blur事件时,发送当前值到服务器
  343. input_elem.on('blur', this.send_value_listener);
  344. // 将额外的html参数加到input标签上
  345. const ignore_keys = {
  346. 'type': '',
  347. 'label': '',
  348. 'invalid_feedback': '',
  349. 'valid_feedback': '',
  350. 'help_text': '',
  351. 'options': ''
  352. };
  353. for (var key in this.spec) {
  354. if (key in ignore_keys) continue;
  355. input_elem.attr(key, this.spec[key]);
  356. }
  357. };
  358. CommonInputController.prototype.update_input = function (spec) {
  359. var attributes = spec.attributes;
  360. this.update_input_helper(-1, attributes);
  361. };
  362. CommonInputController.prototype.get_value = function () {
  363. return this.element.find('input,select').val();
  364. };
  365. function CheckboxRadioController(ws_client, coro_id, spec) {
  366. FormItemController.apply(this, arguments);
  367. this.create_element();
  368. }
  369. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  370. const checkbox_radio_tpl = `
  371. <div class="form-group">
  372. <label>{{label}}</label> {{#inline}}<br>{{/inline}}
  373. {{#options}}
  374. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  375. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" name="{{name}}" value="{{value}}" {{#selected}}checked{{/selected}} {{#disabled}}disabled{{/disabled}} class="form-check-input">
  376. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  377. {{label}}
  378. </label>
  379. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  380. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  381. </div>
  382. {{/options}}
  383. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  384. </div>`;
  385. CheckboxRadioController.prototype.create_element = function () {
  386. var spec = deep_copy(this.spec);
  387. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  388. spec['id_name_prefix'] = id_name_prefix;
  389. for (var idx in spec.options) {
  390. spec.options[idx]['idx'] = idx;
  391. }
  392. const html = Mustache.render(checkbox_radio_tpl, spec);
  393. var elem = $(html);
  394. this.element = elem;
  395. const ignore_keys = {'value': '', 'label': '', 'selected': ''};
  396. for (idx = 0; idx < this.spec.options.length; idx++) {
  397. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  398. // blur事件时,发送当前值到服务器
  399. // checkbox_radio 不产生blur事件
  400. // input_elem.on('blur', this.send_value_listener);
  401. // 将额外的html参数加到input标签上
  402. for (var key in this.spec.options[idx]) {
  403. if (key in ignore_keys) continue;
  404. input_elem.attr(key, this.spec.options[idx][key]);
  405. }
  406. }
  407. };
  408. CheckboxRadioController.prototype.update_input = function (spec) {
  409. var attributes = spec.attributes;
  410. var idx = -1;
  411. if ('target_value' in spec) {
  412. this.element.find('input').each(function (index) {
  413. if ($(this).val() === spec.target_value) {
  414. idx = index;
  415. return false;
  416. }
  417. });
  418. }
  419. this.update_input_helper(idx, attributes);
  420. };
  421. CheckboxRadioController.prototype.get_value = function () {
  422. if (this.spec.type === 'radio') {
  423. return this.element.find('input').val();
  424. } else {
  425. var value_arr = this.element.find('input').serializeArray();
  426. var res = [];
  427. var that = this;
  428. $.each(value_arr, function (idx, val) {
  429. if (val.name === that.spec.name)
  430. res.push(val.value);
  431. });
  432. return res;
  433. }
  434. };
  435. function ButtonsController(ws_client, coro_id, spec) {
  436. FormItemController.apply(this, arguments);
  437. this.last_checked_value = null; // 上次点击按钮的value
  438. this.create_element();
  439. }
  440. ButtonsController.prototype.accept_input_types = ["actions"];
  441. const buttons_tpl = `
  442. <div class="form-group">
  443. <label>{{label}}</label> <br>
  444. {{#buttons}}
  445. <button type="submit" value="{{value}}" aria-describedby="{{name}}_help" {{#disabled}}disabled{{/disabled}} class="btn btn-primary">{{label}}</button>
  446. {{/buttons}}
  447. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  448. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  449. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  450. </div>`;
  451. ButtonsController.prototype.create_element = function () {
  452. const html = Mustache.render(buttons_tpl, this.spec);
  453. this.element = $(html);
  454. // todo:是否有必要监听click事件,因为点击后即提交了表单
  455. var that = this;
  456. this.element.find('button').on('click', function (e) {
  457. var btn = $(this);
  458. that.last_checked_value = btn.val();
  459. });
  460. };
  461. ButtonsController.prototype.update_input = function (spec) {
  462. var attributes = spec.attributes;
  463. var idx = -1;
  464. if ('target_value' in spec) {
  465. this.element.find('button').each(function (index) {
  466. if ($(this).val() === spec.target_value) {
  467. idx = index;
  468. return false;
  469. }
  470. });
  471. }
  472. this.update_input_helper(idx, attributes);
  473. };
  474. ButtonsController.prototype.get_value = function () {
  475. return this.last_checked_value;
  476. };
  477. function WSREPLController(ws_client, output_container_elem, input_container_elem) {
  478. this.output_ctrl = new OutputController(ws_client, output_container_elem);
  479. this.input_ctrl = new FormsController(ws_client, input_container_elem);
  480. this.output_cmds = make_set(this.output_ctrl.accept_command);
  481. this.input_cmds = make_set(this.input_ctrl.accept_command);
  482. this.handle_message = function (msg) {
  483. if (msg.command in this.input_cmds)
  484. this.input_ctrl.handle_message(msg);
  485. else if (msg.command in this.output_cmds)
  486. this.output_ctrl.handle_message(msg);
  487. else
  488. console.error('Unknown command:%s', msg.command);
  489. };
  490. }
  491. return {
  492. 'WSREPLController': WSREPLController
  493. }
  494. })));