form.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. $('input[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. $('input[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. $('input[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.input_controllers = {}; // name -> input_controller
  191. this.create_element();
  192. }
  193. FormController.prototype.create_element = function () {
  194. var tpl = `
  195. <div class="card" style="display: none">
  196. <h5 class="card-header">{{label}}</h5>
  197. <div class="card-body">
  198. <form>
  199. <div class="input-container"></div>
  200. <button type="submit" class="btn btn-primary">提交</button>
  201. <button type="reset" class="btn btn-warning">重置</button>
  202. </form>
  203. </div>
  204. </div>`;
  205. const html = Mustache.render(tpl, {label: this.spec.label});
  206. this.element = $(html);
  207. // 输入控件创建
  208. var body = this.element.find('.input-container');
  209. for (var idx in this.spec.inputs) {
  210. var i = this.spec.inputs[idx];
  211. var ctrl;
  212. if (i.type in make_set(CommonInputController.prototype.accept_input_types)) {
  213. ctrl = new CommonInputController(this.ws_client, this.coro_id, i);
  214. } else if (i.type in make_set(CheckboxRadioController.prototype.accept_input_types)) {
  215. ctrl = new CheckboxRadioController(this.ws_client, this.coro_id, i);
  216. }
  217. this.input_controllers[i.name] = ctrl;
  218. body.append(ctrl.element);
  219. }
  220. // 事件绑定
  221. var that = this;
  222. this.element.on('submit', 'form', function (e) {
  223. e.preventDefault(); // avoid to execute the actual submit of the form.
  224. var data = {};
  225. $.each(that.input_controllers, (name, ctrl) => {
  226. data[name] = ctrl.get_value();
  227. });
  228. ws.send(JSON.stringify({
  229. event: "from_submit",
  230. coro_id: that.coro_id,
  231. data: data
  232. }));
  233. });
  234. };
  235. FormController.prototype.dispatch_ctrl_message = function (spec) {
  236. if (!(spec.target_name in this.input_controllers)) {
  237. return console.error('Can\'t find input[name=%s] element in curr form!', spec.target_name);
  238. }
  239. this.input_controllers[spec.target_name].update_input(spec);
  240. };
  241. function FormItemController(ws_client, coro_id, spec) {
  242. this.ws_client = ws_client;
  243. this.coro_id = coro_id;
  244. this.spec = spec;
  245. this.element = undefined;
  246. var that = this;
  247. this.send_value_listener = function (e) {
  248. var this_elem = $(this);
  249. that.ws_client.send(JSON.stringify({
  250. event: "input_event",
  251. coro_id: that.coro_id,
  252. data: {
  253. event_name: e.type.toLowerCase(),
  254. name: this_elem.attr('name'),
  255. value: this_elem.val()
  256. }
  257. }));
  258. };
  259. /*
  260. * input_idx: 更新作用对象input标签的索引, -1 为不指定对象
  261. * attributes:更新值字典
  262. * */
  263. this.update_input_helper = function (input_idx, attributes) {
  264. var attr2selector = {
  265. 'invalid_feedback': 'div.invalid-feedback',
  266. 'valid_feedback': 'div.valid-feedback',
  267. 'help_text': 'small.text-muted'
  268. };
  269. for (var attribute in attr2selector) {
  270. if (attribute in attributes) {
  271. if (input_idx === -1)
  272. this.element.find(attr2selector[attribute]).text(attributes[attribute]);
  273. else
  274. this.element.find(attr2selector[attribute]).eq(input_idx).text(attributes[attribute]);
  275. delete attributes[attribute];
  276. }
  277. }
  278. var input_elem = this.element.find('input');
  279. if (input_idx >= 0)
  280. input_elem = input_elem.eq(input_idx);
  281. if ('valid_status' in attributes) {
  282. var class_name = attributes.valid_status ? 'is-valid' : 'is-invalid';
  283. input_elem.removeClass('is-valid is-invalid').addClass(class_name);
  284. delete attributes.valid_status;
  285. }
  286. input_elem.attr(attributes);
  287. }
  288. }
  289. function CommonInputController(ws_client, coro_id, spec) {
  290. FormItemController.apply(this, arguments);
  291. this.create_element();
  292. }
  293. CommonInputController.prototype.accept_input_types = ["text", "password", "number", "color", "date", "range", "time"];
  294. /*
  295. *
  296. * type=
  297. * */
  298. const common_input_tpl = `
  299. <div class="form-group">
  300. <label for="{{id_name}}">{{label}}</label>
  301. <input type="{{type}}" id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control">
  302. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  303. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  304. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  305. </div>`;
  306. CommonInputController.prototype.create_element = function () {
  307. var spec = deep_copy(this.spec);
  308. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  309. spec['id_name'] = id_name;
  310. const html = Mustache.render(common_input_tpl, spec);
  311. this.element = $(html);
  312. var input_elem = this.element.find('#' + id_name);
  313. // blur事件时,发送当前值到服务器
  314. input_elem.on('blur', this.send_value_listener);
  315. // 将额外的html参数加到input标签上
  316. const ignore_keys = {'type': '', 'label': '', 'invalid_feedback': '', 'valid_feedback': '', 'help_text': ''};
  317. for (var key in this.spec) {
  318. if (key in ignore_keys) continue;
  319. input_elem.attr(key, this.spec[key]);
  320. }
  321. };
  322. CommonInputController.prototype.update_input = function (spec) {
  323. var attributes = spec.attributes;
  324. this.update_input_helper(-1, attributes);
  325. };
  326. CommonInputController.prototype.get_value = function () {
  327. return this.element.find('input').val();
  328. };
  329. function CheckboxRadioController(ws_client, coro_id, spec) {
  330. FormItemController.apply(this, arguments);
  331. this.create_element();
  332. }
  333. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  334. const checkbox_radio_tpl = `
  335. <div class="form-group">
  336. <label>{{label}}</label> {{#inline}}<br>{{/inline}}
  337. {{#options}}
  338. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  339. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" class="form-check-input" name="{{name}}" value="{{value}}">
  340. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  341. {{label}}
  342. </label>
  343. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  344. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  345. </div>
  346. {{/options}}
  347. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  348. </div>`;
  349. CheckboxRadioController.prototype.create_element = function () {
  350. var spec = deep_copy(this.spec);
  351. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  352. spec['id_name_prefix'] = id_name_prefix;
  353. for (var idx in spec.options) {
  354. spec.options[idx]['idx'] = idx;
  355. }
  356. const html = Mustache.render(checkbox_radio_tpl, spec);
  357. var elem = $(html);
  358. this.element = elem;
  359. const ignore_keys = {'value': '', 'label': ''};
  360. for (idx = 0; idx < this.spec.options.length; idx++) {
  361. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  362. // blur事件时,发送当前值到服务器
  363. // checkbox_radio 不产生blur事件
  364. // input_elem.on('blur', this.send_value_listener);
  365. // 将额外的html参数加到input标签上
  366. for (var key in this.spec.options[idx]) {
  367. if (key in ignore_keys) continue;
  368. input_elem.attr(key, this.spec[key]);
  369. }
  370. }
  371. };
  372. CheckboxRadioController.prototype.update_input = function (spec) {
  373. var attributes = spec.attributes;
  374. var idx = -1;
  375. if ('target_value' in spec) {
  376. this.element.find('input').each(function (index) {
  377. if ($(this).val() == spec.target_value) {
  378. idx = index;
  379. return false;
  380. }
  381. });
  382. }
  383. this.update_input_helper(idx, attributes);
  384. };
  385. CheckboxRadioController.prototype.get_value = function () {
  386. if (this.spec.type === 'radio') {
  387. return this.element.find('input').val();
  388. } else {
  389. var value_arr = this.element.find('input').serializeArray();
  390. var res = [];
  391. var that = this;
  392. $.each(value_arr, function (idx, val) {
  393. if (val.name === that.spec.name)
  394. res.push(val.value);
  395. });
  396. return res;
  397. }
  398. };
  399. function WSREPLController(ws_client, output_container_elem, input_container_elem) {
  400. this.output_ctrl = new OutputController(ws_client, output_container_elem);
  401. this.input_ctrl = new FormsController(ws_client, input_container_elem);
  402. this.output_cmds = make_set(this.output_ctrl.accept_command);
  403. this.input_cmds = make_set(this.input_ctrl.accept_command);
  404. this.handle_message = function (msg) {
  405. if (msg.command in this.input_cmds)
  406. this.input_ctrl.handle_message(msg);
  407. else if (msg.command in this.output_cmds)
  408. this.output_ctrl.handle_message(msg);
  409. else
  410. console.error('Unknown command:%s', msg.command);
  411. };
  412. }
  413. return {
  414. 'WSREPLController': WSREPLController
  415. }
  416. })));