form.js 21 KB

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