form.js 23 KB

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