form.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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.WebIO = factory());
  5. }(this, (function () {
  6. 'use strict';
  7. const b64toBlob = (b64Data, contentType = 'application/octet-stream', sliceSize = 512) => {
  8. const byteCharacters = atob(b64Data);
  9. const byteArrays = [];
  10. for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
  11. const slice = byteCharacters.slice(offset, offset + sliceSize);
  12. const byteNumbers = new Array(slice.length);
  13. for (let i = 0; i < slice.length; i++) {
  14. byteNumbers[i] = slice.charCodeAt(i);
  15. }
  16. const byteArray = new Uint8Array(byteNumbers);
  17. byteArrays.push(byteArray);
  18. }
  19. const blob = new Blob(byteArrays, {type: contentType});
  20. return blob;
  21. };
  22. function extend(Child, Parent) {
  23. var F = function () {
  24. };
  25. F.prototype = Parent.prototype;
  26. Child.prototype = new F();
  27. Child.prototype.constructor = Child;
  28. Child.uber = Parent.prototype;
  29. }
  30. function make_set(arr) {
  31. var set = {};
  32. for (var idx in arr)
  33. set[arr[idx]] = '';
  34. return set;
  35. }
  36. function deep_copy(obj) {
  37. return JSON.parse(JSON.stringify(obj));
  38. }
  39. function LRUMap() {
  40. this.keys = [];
  41. this.map = {};
  42. this.push = function (key, value) {
  43. if (key in this.map)
  44. return console.error("LRUMap: key:%s already in map", key);
  45. this.keys.push(key);
  46. this.map[key] = value;
  47. };
  48. this.get_value = function (key) {
  49. return this.map[key];
  50. };
  51. this.get_top = function () {
  52. var top_key = this.keys[this.keys.length - 1];
  53. return this.map[top_key];
  54. };
  55. this.set_value = function (key, value) {
  56. if (!(key in this.map))
  57. return console.error("LRUMap: key:%s not in map when call `set_value`", key);
  58. this.map[key] = value;
  59. };
  60. this.move_to_top = function (key) {
  61. const index = this.keys.indexOf(key);
  62. if (index > -1) {
  63. this.keys.splice(index, 1);
  64. this.keys.push(key);
  65. } else {
  66. return console.error("LRUMap: key:%s not in map when call `move_to_top`", key);
  67. }
  68. };
  69. this.remove = function (key) {
  70. if (key in this.map) {
  71. delete this.map[key];
  72. this.keys.splice(this.keys.indexOf(key), 1);
  73. } else {
  74. return console.error("LRUMap: key:%s not in map when call `remove`", key);
  75. }
  76. };
  77. }
  78. var AutoScrollBottom = true; // 是否有新内容时自动滚动到底部
  79. OutputController.prototype.accept_command = ['output', 'output_ctl'];
  80. function OutputController(webio_session, container_elem) {
  81. this.webio_session = webio_session;
  82. this.container_elem = $(container_elem);
  83. this.md_parser = new Mditor.Parser();
  84. this.container_parent = this.container_elem.parent();
  85. this.body = $('html,body');
  86. }
  87. OutputController.prototype.scroll_bottom = function () {
  88. this.container_parent.stop().animate({scrollTop: this.container_parent[0].scrollHeight}, 700);
  89. var that = this;
  90. setTimeout(function () {
  91. // body.scrollTop(body[0].scrollHeight); // 整个页面自动滚动
  92. that.body.stop().animate({scrollTop: that.body[0].scrollHeight}, 700);
  93. }, ShowDuration + 10);
  94. };
  95. OutputController.prototype.handle_message = function (msg) {
  96. if (msg.command === 'output') {
  97. const func_name = `get_${msg.spec.type}_element`;
  98. if (!(func_name in OutputController.prototype)) {
  99. return console.error('Unknown output type:%s', msg.spec.type);
  100. }
  101. var elem = OutputController.prototype[func_name].call(this, msg.spec);
  102. if (msg.spec.anchor !== undefined) {
  103. this.container_elem.find(`#${msg.spec.anchor}`).attr('id', '');
  104. elem.attr('id', msg.spec.anchor);
  105. }
  106. if (msg.spec.before !== undefined) {
  107. this.container_elem.find('#' + msg.spec.before).before(elem);
  108. } else if (msg.spec.after !== undefined) {
  109. this.container_elem.find('#' + msg.spec.after).after(elem);
  110. } else {
  111. this.container_elem.append(elem);
  112. }
  113. } else if (msg.command === 'output_ctl') {
  114. this.handle_output_ctl(msg);
  115. }
  116. // note:当接收到scroll_to指令时,忽略AutoScrollBottom
  117. if (AutoScrollBottom && !(msg.command === 'output_ctl' && msg.spec.scroll_to !== undefined))
  118. this.scroll_bottom();
  119. };
  120. // OutputController.prototype.get_[output_type]_element return a jQuery obj
  121. OutputController.prototype.get_text_element = function (spec) {
  122. var elem = spec.inline ? $('<span></span>') : $('<p></p>');
  123. spec.content = spec.content.replace(/ /g, '\u00A0');
  124. // make '\n' to <br/>
  125. var lines = (spec.content || '').split('\n');
  126. for (var idx = 0; idx < lines.length - 1; idx++)
  127. elem.append(document.createTextNode(lines[idx])).append('<br/>');
  128. elem.append(document.createTextNode(lines[lines.length - 1]));
  129. return elem;
  130. };
  131. OutputController.prototype.get_markdown_element = function (spec) {
  132. return $(this.md_parser.parse(spec.content));
  133. };
  134. OutputController.prototype.get_html_element = function (spec) {
  135. return $($.parseHTML(spec.content));
  136. };
  137. OutputController.prototype.get_buttons_element = function (spec) {
  138. const btns_tpl = `<div class="form-group">{{#buttons}}
  139. <button value="{{value}}" onclick="WebIO.DisplayAreaButtonOnClick(this, '{{callback_id}}')" class="btn btn-primary {{#small}}btn-sm{{/small}}">{{label}}</button>
  140. {{/buttons}}</div>`;
  141. var html = Mustache.render(btns_tpl, spec);
  142. return $(html);
  143. };
  144. OutputController.prototype.get_file_element = function (spec) {
  145. const html = `<div class="form-group"><button type="button" class="btn btn-link">${spec.name}</button></div>`;
  146. var element = $(html);
  147. var blob = b64toBlob(spec.content);
  148. element.on('click', 'button', function (e) {
  149. saveAs(blob, spec.name, {}, false);
  150. });
  151. return element;
  152. };
  153. OutputController.prototype.handle_output_ctl = function (msg) {
  154. if (msg.spec.title) {
  155. $('#title').text(msg.spec.title); // 直接使用#title不规范 todo
  156. document.title = msg.spec.title;
  157. }
  158. if (msg.spec.output_fixed_height !== undefined)
  159. if (msg.spec.output_fixed_height)
  160. $('.container').removeClass('no-fix-height'); // todo 不规范
  161. else
  162. $('.container').addClass('no-fix-height'); // todo 不规范
  163. if (msg.spec.auto_scroll_bottom !== undefined)
  164. AutoScrollBottom = msg.spec.auto_scroll_bottom;
  165. if (msg.spec.set_anchor !== undefined) {
  166. this.container_elem.find(`#${msg.spec.set_anchor}`).attr('id', '');
  167. this.container_elem.append(`<div id="${msg.spec.set_anchor}"></div>`);
  168. }
  169. if (msg.spec.clear_before !== undefined)
  170. this.container_elem.find(`#${msg.spec.clear_before}`).prevAll().remove();
  171. if (msg.spec.clear_after !== undefined)
  172. this.container_elem.find(`#${msg.spec.clear_after}~*`).remove();
  173. if (msg.spec.scroll_to !== undefined)
  174. $([document.documentElement, document.body]).animate({
  175. scrollTop: $(`#${msg.spec.scroll_to}`).offset().top
  176. }, 400);
  177. if (msg.spec.clear_range !== undefined) {
  178. if (this.container_elem.find(`#${msg.spec.clear_range[0]}`).length &&
  179. this.container_elem.find(`#${msg.spec.clear_range[1]}`).length) {
  180. this.container_elem.find(`#${msg.spec.clear_range[0]}~*`).each(function () {
  181. if (this.id === msg.spec.clear_range[1])
  182. return false;
  183. $(this).remove();
  184. });
  185. }
  186. }
  187. };
  188. // 显示区按钮点击回调函数
  189. function DisplayAreaButtonOnClick(this_ele, callback_id) {
  190. if (WebIOSession_ === undefined)
  191. return console.error("can't invoke DisplayAreaButtonOnClick when WebIOController is not instantiated");
  192. var val = $(this_ele).val();
  193. WebIOSession_.send_message({
  194. event: "callback",
  195. task_id: callback_id,
  196. data: val
  197. });
  198. }
  199. const ShowDuration = 200; // ms, 显示表单的过渡动画时长
  200. FormsController.prototype.accept_command = ['input', 'input_group', 'update_input', 'destroy_form'];
  201. function FormsController(webio_session, container_elem) {
  202. this.webio_session = webio_session;
  203. this.container_elem = container_elem;
  204. this.form_ctrls = new LRUMap(); // task_id -> stack of FormGroupController
  205. // hide old_ctrls显示的表单,激活 task_id 对应的表单
  206. // 需要保证 task_id 对应有表单
  207. this._activate_form = function (task_id, old_ctrl) {
  208. var ctrls = this.form_ctrls.get_value(task_id);
  209. var ctrl = ctrls[ctrls.length - 1];
  210. if (ctrl === old_ctrl || old_ctrl === undefined) {
  211. console.log('开:%s', ctrl.spec.label);
  212. return ctrl.element.show(ShowDuration, function () {
  213. if (AutoScrollBottom)
  214. $('[auto_focus]').focus();
  215. });
  216. }
  217. this.form_ctrls.move_to_top(task_id);
  218. var that = this;
  219. old_ctrl.element.hide(100, () => {
  220. // ctrl.element.show(100);
  221. // 需要在回调中重新获取当前前置表单元素,因为100ms内可能有变化
  222. var t = that.form_ctrls.get_top();
  223. if (t) t[t.length - 1].element.show(ShowDuration, function () {
  224. if (AutoScrollBottom)
  225. $('[auto_focus]').focus();
  226. });
  227. });
  228. };
  229. // var that = this;
  230. // this.msg_queue = async.queue((msg) => {
  231. // that.consume_message(msg)
  232. // }, 1);
  233. //
  234. // var l = new Lock(this.consume_message);
  235. this.handle_message_ = function (msg) {
  236. // this.msg_queue.push(msg);
  237. // l.mutex_run(that, msg);
  238. // console.log('start handle_message %s %s', msg.command, msg.spec.label);
  239. this.consume_message(msg);
  240. // console.log('end handle_message %s %s', msg.command, msg.spec.label);
  241. };
  242. /*
  243. * 每次函数调用返回后,this.form_ctrls.get_top()的栈顶对应的表单为当前活跃表单
  244. * */
  245. this.handle_message = function (msg) {
  246. var old_ctrls = this.form_ctrls.get_top();
  247. var old_ctrl = old_ctrls && old_ctrls[old_ctrls.length - 1];
  248. var target_ctrls = this.form_ctrls.get_value(msg.task_id);
  249. if (target_ctrls === undefined) {
  250. this.form_ctrls.push(msg.task_id, []);
  251. target_ctrls = this.form_ctrls.get_value(msg.task_id);
  252. }
  253. // 创建表单
  254. if (msg.command in make_set(['input', 'input_group'])) {
  255. var ctrl = new FormController(this.webio_session, msg.task_id, msg.spec);
  256. target_ctrls.push(ctrl);
  257. this.container_elem.append(ctrl.element);
  258. this._activate_form(msg.task_id, old_ctrl);
  259. } else if (msg.command in make_set(['update_input'])) {
  260. // 更新表单
  261. if (target_ctrls.length === 0) {
  262. return console.error('No form to current message. task_id:%s', msg.task_id);
  263. }
  264. target_ctrls[target_ctrls.length - 1].dispatch_ctrl_message(msg.spec);
  265. // 表单前置 removed
  266. // this._activate_form(msg.task_id, old_ctrl);
  267. } else if (msg.command === 'destroy_form') {
  268. if (target_ctrls.length === 0) {
  269. return console.error('No form to current message. task_id:%s', msg.task_id);
  270. }
  271. var deleted = target_ctrls.pop();
  272. if (target_ctrls.length === 0)
  273. this.form_ctrls.remove(msg.task_id);
  274. // 销毁的是当前显示的form
  275. if (old_ctrls === target_ctrls) {
  276. var that = this;
  277. deleted.element.hide(100, () => {
  278. deleted.element.remove();
  279. var t = that.form_ctrls.get_top();
  280. if (t) t[t.length - 1].element.show(ShowDuration, function () {
  281. if (AutoScrollBottom)
  282. $('[auto_focus]').focus();
  283. });
  284. });
  285. } else {
  286. deleted.element.remove();
  287. }
  288. }
  289. }
  290. }
  291. function FormStack() {
  292. push();
  293. pop();
  294. empty();
  295. show();// 显示栈顶元素
  296. hide();// 隐藏栈顶元素
  297. }
  298. function FormController(webio_session, task_id, spec) {
  299. this.webio_session = webio_session;
  300. this.task_id = task_id;
  301. this.spec = spec;
  302. this.element = undefined;
  303. this.name2input_controllers = {}; // name -> input_controller
  304. this.create_element();
  305. }
  306. FormController.prototype.input_controllers = [FileInputController, CommonInputController, CheckboxRadioController, ButtonsController, TextareaInputController];
  307. FormController.prototype.create_element = function () {
  308. var tpl = `
  309. <div class="card" style="display: none">
  310. <h5 class="card-header">{{label}}</h5>
  311. <div class="card-body">
  312. <form>
  313. <div class="input-container"></div>
  314. <div class="ws-form-submit-btns">
  315. <button type="submit" class="btn btn-primary">提交</button>
  316. <button type="reset" class="btn btn-warning">重置</button>
  317. </div>
  318. </form>
  319. </div>
  320. </div>`;
  321. const html = Mustache.render(tpl, {label: this.spec.label});
  322. this.element = $(html);
  323. // 如果表单最后一个输入元素为actions组件,则隐藏默认的"提交"/"重置"按钮
  324. if (this.spec.inputs.length && this.spec.inputs[this.spec.inputs.length - 1].type === 'actions')
  325. this.element.find('.ws-form-submit-btns').hide();
  326. // 输入控件创建
  327. var body = this.element.find('.input-container');
  328. for (var idx in this.spec.inputs) {
  329. var input_spec = this.spec.inputs[idx];
  330. var ctrl = undefined;
  331. for (var i in this.input_controllers) {
  332. var ctrl_cls = this.input_controllers[i];
  333. // console.log(ctrl_cls, ctrl_cls.prototype.accept_input_types);
  334. if (input_spec.type in make_set(ctrl_cls.prototype.accept_input_types)) {
  335. ctrl = new ctrl_cls(this.webio_session, this.task_id, input_spec);
  336. break;
  337. }
  338. }
  339. if (ctrl) {
  340. this.name2input_controllers[input_spec.name] = ctrl;
  341. body.append(ctrl.element);
  342. } else {
  343. console.error('Unvalid input type:%s', input_spec.type);
  344. }
  345. }
  346. // 事件绑定
  347. var that = this;
  348. this.element.on('submit', 'form', function (e) {
  349. e.preventDefault(); // avoid to execute the actual submit of the form.
  350. var data = {};
  351. $.each(that.name2input_controllers, (name, ctrl) => {
  352. data[name] = ctrl.get_value();
  353. });
  354. that.webio_session.send_message({
  355. event: "from_submit",
  356. task_id: that.task_id,
  357. data: data
  358. });
  359. });
  360. };
  361. FormController.prototype.dispatch_ctrl_message = function (spec) {
  362. if (!(spec.target_name in this.name2input_controllers)) {
  363. return console.error('Can\'t find input[name=%s] element in curr form!', spec.target_name);
  364. }
  365. this.name2input_controllers[spec.target_name].update_input(spec);
  366. };
  367. function FormItemController(webio_session, task_id, spec) {
  368. this.webio_session = webio_session;
  369. this.task_id = task_id;
  370. this.spec = spec;
  371. this.element = undefined;
  372. var that = this;
  373. this.send_value_listener = function (e) {
  374. var this_elem = $(this);
  375. that.webio_session.send_message({
  376. event: "input_event",
  377. task_id: that.task_id,
  378. data: {
  379. event_name: e.type.toLowerCase(),
  380. name: that.spec.name,
  381. value: that.get_value()
  382. }
  383. });
  384. };
  385. /*
  386. * input_idx: 更新作用对象input标签的索引, -1 为不指定对象
  387. * attributes:更新值字典
  388. * */
  389. this.update_input_helper = function (input_idx, attributes) {
  390. var attr2selector = {
  391. 'invalid_feedback': 'div.invalid-feedback',
  392. 'valid_feedback': 'div.valid-feedback',
  393. 'help_text': 'small.text-muted'
  394. };
  395. for (var attribute in attr2selector) {
  396. if (attribute in attributes) {
  397. if (input_idx === -1)
  398. this.element.find(attr2selector[attribute]).text(attributes[attribute]);
  399. else
  400. this.element.find(attr2selector[attribute]).eq(input_idx).text(attributes[attribute]);
  401. delete attributes[attribute];
  402. }
  403. }
  404. var input_elem = this.element.find('input,select');
  405. if (input_idx >= 0)
  406. input_elem = input_elem.eq(input_idx);
  407. if ('valid_status' in attributes) {
  408. var class_name = attributes.valid_status ? 'is-valid' : 'is-invalid';
  409. input_elem.removeClass('is-valid is-invalid').addClass(class_name);
  410. delete attributes.valid_status;
  411. }
  412. input_elem.attr(attributes);
  413. }
  414. }
  415. function CommonInputController(webio_session, task_id, spec) {
  416. FormItemController.apply(this, arguments);
  417. this.create_element();
  418. }
  419. CommonInputController.prototype.accept_input_types = ["text", "password", "number", "color", "date", "range", "time", "select", "file"];
  420. /*
  421. *
  422. * type=
  423. * */
  424. const common_input_tpl = `
  425. <div class="form-group">
  426. <label for="{{id_name}}">{{label}}</label>
  427. <input type="{{type}}" id="{{id_name}}" aria-describedby="{{id_name}}_help" {{#list}}list="{{list}}"{{/list}} class="form-control" >
  428. <datalist id="{{id_name}}-list">
  429. {{#datalist}}
  430. <option>{{.}}</option>
  431. {{/datalist}}
  432. </datalist>
  433. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  434. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  435. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  436. </div>`;
  437. const select_input_tpl = `
  438. <div class="form-group">
  439. <label for="{{id_name}}">{{label}}</label>
  440. <select id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control">
  441. {{#options}}
  442. <option value="{{value}}" {{#selected}}selected{{/selected}} {{#disabled}}disabled{{/disabled}}>{{label}}</option>
  443. {{/options}}
  444. </select>
  445. <div class="invalid-feedback">{{invalid_feedback}}</div>
  446. <div class="valid-feedback">{{valid_feedback}}</div>
  447. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  448. </div>`;
  449. CommonInputController.prototype.create_element = function () {
  450. var spec = deep_copy(this.spec);
  451. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  452. spec['id_name'] = id_name;
  453. if (spec.datalist)
  454. spec['list'] = id_name + '-list';
  455. var html;
  456. if (spec.type === 'select')
  457. html = Mustache.render(select_input_tpl, spec);
  458. else
  459. html = Mustache.render(common_input_tpl, spec);
  460. this.element = $(html);
  461. var input_elem = this.element.find('#' + id_name);
  462. // blur事件时,发送当前值到服务器
  463. input_elem.on('blur', this.send_value_listener);
  464. // 将额外的html参数加到input标签上
  465. const ignore_keys = {
  466. 'type': '',
  467. 'label': '',
  468. 'invalid_feedback': '',
  469. 'valid_feedback': '',
  470. 'help_text': '',
  471. 'options': '',
  472. 'datalist': ''
  473. };
  474. for (var key in this.spec) {
  475. if (key in ignore_keys) continue;
  476. input_elem.attr(key, this.spec[key]);
  477. }
  478. };
  479. CommonInputController.prototype.update_input = function (spec) {
  480. var attributes = spec.attributes;
  481. this.update_input_helper(-1, attributes);
  482. };
  483. CommonInputController.prototype.get_value = function () {
  484. return this.element.find('input,select').val();
  485. };
  486. function TextareaInputController(webio_session, task_id, spec) {
  487. FormItemController.apply(this, arguments);
  488. this.create_element();
  489. }
  490. function load_codemirror_theme(theme, url_tpl = "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/theme/%N.min.css") {
  491. var cssId = 'codemirror_theme_' + theme; // you could encode the css path itself to generate id..
  492. if (!document.getElementById(cssId)) {
  493. var head = document.getElementsByTagName('head')[0];
  494. var link = document.createElement('link');
  495. link.id = cssId;
  496. link.rel = 'stylesheet';
  497. link.type = 'text/css';
  498. link.href = url_tpl.replace('%N', theme);
  499. link.media = 'all';
  500. head.appendChild(link);
  501. }
  502. }
  503. TextareaInputController.prototype.accept_input_types = ["textarea"];
  504. const textarea_input_tpl = `
  505. <div class="form-group">
  506. <label for="{{id_name}}">{{label}}</label>
  507. <textarea id="{{id_name}}" aria-describedby="{{id_name}}_help" rows="{{rows}}" class="form-control" >{{value}}</textarea>
  508. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  509. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  510. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  511. </div>`;
  512. TextareaInputController.prototype.create_element = function () {
  513. var spec = deep_copy(this.spec);
  514. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  515. spec['id_name'] = id_name;
  516. var html = Mustache.render(textarea_input_tpl, spec);
  517. this.element = $(html);
  518. var input_elem = this.element.find('#' + id_name);
  519. // blur事件时,发送当前值到服务器
  520. // input_elem.on('blur', this.send_value_listener);
  521. // 将额外的html参数加到input标签上
  522. const ignore_keys = make_set(['value', 'type', 'label', 'invalid_feedback', 'valid_feedback', 'help_text', 'rows', 'codemirror']);
  523. for (var key in this.spec) {
  524. if (key in ignore_keys) continue;
  525. input_elem.attr(key, this.spec[key]);
  526. }
  527. if (spec.codemirror) {
  528. var that = this;
  529. setTimeout(function () {
  530. var config = {
  531. 'mode': 'python',
  532. 'lineNumbers': true, // 显示行数
  533. 'indentUnit': 4, //缩进单位为4
  534. 'styleActiveLine': true, // 当前行背景高亮
  535. 'matchBrackets': true, //括号匹配
  536. 'lineWrapping': true, //自动换行
  537. };
  538. for (var k in that.spec.codemirror) config[k] = that.spec.codemirror[k];
  539. that.code_mirror = CodeMirror.fromTextArea(that.element.find('textarea')[0], config);
  540. CodeMirror.autoLoadMode(that.code_mirror, config.mode);
  541. if(config.theme)
  542. load_codemirror_theme(config.theme);
  543. }, ShowDuration + 100);
  544. }
  545. };
  546. TextareaInputController.prototype.update_input = function (spec) {
  547. var attributes = spec.attributes;
  548. this.update_input_helper(-1, attributes);
  549. };
  550. TextareaInputController.prototype.get_value = function () {
  551. return this.element.find('textarea').val();
  552. };
  553. function CheckboxRadioController(webio_session, task_id, spec) {
  554. FormItemController.apply(this, arguments);
  555. this.create_element();
  556. }
  557. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  558. const checkbox_radio_tpl = `
  559. <div class="form-group">
  560. <label>{{label}}</label> {{#inline}}<br>{{/inline}}
  561. {{#options}}
  562. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  563. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" name="{{name}}" value="{{value}}" {{#selected}}checked{{/selected}} {{#disabled}}disabled{{/disabled}} class="form-check-input">
  564. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  565. {{label}}
  566. </label>
  567. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  568. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  569. </div>
  570. {{/options}}
  571. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  572. </div>`;
  573. CheckboxRadioController.prototype.create_element = function () {
  574. var spec = deep_copy(this.spec);
  575. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  576. spec['id_name_prefix'] = id_name_prefix;
  577. for (var idx in spec.options) {
  578. spec.options[idx]['idx'] = idx;
  579. }
  580. const html = Mustache.render(checkbox_radio_tpl, spec);
  581. var elem = $(html);
  582. this.element = elem;
  583. const ignore_keys = {'value': '', 'label': '', 'selected': ''};
  584. for (idx = 0; idx < this.spec.options.length; idx++) {
  585. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  586. // blur事件时,发送当前值到服务器
  587. // checkbox_radio 不产生blur事件
  588. // input_elem.on('blur', this.send_value_listener);
  589. // 将额外的html参数加到input标签上
  590. for (var key in this.spec.options[idx]) {
  591. if (key in ignore_keys) continue;
  592. input_elem.attr(key, this.spec.options[idx][key]);
  593. }
  594. }
  595. };
  596. CheckboxRadioController.prototype.update_input = function (spec) {
  597. var attributes = spec.attributes;
  598. var idx = -1;
  599. if ('target_value' in spec) {
  600. this.element.find('input').each(function (index) {
  601. if ($(this).val() === spec.target_value) {
  602. idx = index;
  603. return false;
  604. }
  605. });
  606. }
  607. this.update_input_helper(idx, attributes);
  608. };
  609. CheckboxRadioController.prototype.get_value = function () {
  610. if (this.spec.type === 'radio') {
  611. return this.element.find('input').val();
  612. } else {
  613. var value_arr = this.element.find('input').serializeArray();
  614. var res = [];
  615. var that = this;
  616. $.each(value_arr, function (idx, val) {
  617. if (val.name === that.spec.name)
  618. res.push(val.value);
  619. });
  620. return res;
  621. }
  622. };
  623. function ButtonsController(webio_session, task_id, spec) {
  624. FormItemController.apply(this, arguments);
  625. this.last_checked_value = null; // 上次点击按钮的value
  626. this.create_element();
  627. }
  628. ButtonsController.prototype.accept_input_types = ["actions"];
  629. const buttons_tpl = `
  630. <div class="form-group">
  631. <label>{{label}}</label> <br>
  632. {{#buttons}}
  633. <button type="submit" value="{{value}}" aria-describedby="{{name}}_help" {{#disabled}}disabled{{/disabled}} class="btn btn-primary">{{label}}</button>
  634. {{/buttons}}
  635. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  636. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  637. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  638. </div>`;
  639. ButtonsController.prototype.create_element = function () {
  640. const html = Mustache.render(buttons_tpl, this.spec);
  641. this.element = $(html);
  642. // todo:是否有必要监听click事件,因为点击后即提交了表单
  643. var that = this;
  644. this.element.find('button').on('click', function (e) {
  645. var btn = $(this);
  646. that.last_checked_value = btn.val();
  647. });
  648. };
  649. ButtonsController.prototype.update_input = function (spec) {
  650. var attributes = spec.attributes;
  651. var idx = -1;
  652. if ('target_value' in spec) {
  653. this.element.find('button').each(function (index) {
  654. if ($(this).val() === spec.target_value) {
  655. idx = index;
  656. return false;
  657. }
  658. });
  659. }
  660. this.update_input_helper(idx, attributes);
  661. };
  662. ButtonsController.prototype.get_value = function () {
  663. return this.last_checked_value;
  664. };
  665. function FileInputController(webio_session, task_id, spec) {
  666. FormItemController.apply(this, arguments);
  667. this.data_url_value = null;
  668. this.create_element();
  669. }
  670. FileInputController.prototype.accept_input_types = ["file"];
  671. const file_input_tpl = `
  672. <div class="form-group">
  673. <label for="customFile">{{label}}</label>
  674. <div class="custom-file">
  675. <input type="file" class="custom-file-input" id="{{name}}" aria-describedby="{{name}}_help">
  676. <label class="custom-file-label" for="{{name}}">{{placeholder}}</label>
  677. </div>
  678. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  679. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  680. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  681. </div>`;
  682. FileInputController.prototype.create_element = function () {
  683. var spec = deep_copy(this.spec);
  684. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  685. spec['id_name'] = id_name;
  686. const html = Mustache.render(file_input_tpl, spec);
  687. this.element = $(html);
  688. var input_elem = this.element.find('input[type="file"]');
  689. const ignore_keys = {
  690. 'label': '',
  691. 'invalid_feedback': '',
  692. 'valid_feedback': '',
  693. 'help_text': '',
  694. 'placeholder': ''
  695. };
  696. for (var key in this.spec) {
  697. if (key in ignore_keys) continue;
  698. input_elem.attr(key, this.spec[key]);
  699. }
  700. // 文件选中后先不通知后端
  701. var that = this;
  702. input_elem.on('change', function () {
  703. var file = input_elem[0].files[0];
  704. var fr = new FileReader();
  705. fr.onload = function () {
  706. that.data_url_value = {
  707. 'filename': file.name, 'dataurl': fr.result
  708. };
  709. console.log(that.data_url_value);
  710. };
  711. fr.readAsDataURL(file);
  712. });
  713. // todo 通过回调的方式调用init
  714. setTimeout(bsCustomFileInput.init, ShowDuration + 100);
  715. };
  716. FileInputController.prototype.update_input = function (spec) {
  717. var attributes = spec.attributes;
  718. this.update_input_helper(-1, attributes);
  719. };
  720. FileInputController.prototype.get_value = function () {
  721. return this.data_url_value;
  722. };
  723. /*
  724. * 会话
  725. * 向外暴露的事件:on_session_create、on_session_close、on_server_message
  726. * 提供的函数:start_session、send_message、close_session
  727. * */
  728. function WebIOSession() {
  729. this.on_session_create = () => {
  730. };
  731. this.on_session_close = () => {
  732. };
  733. this.on_server_message = (msg) => {
  734. };
  735. this.start_session = function (debug = false) {
  736. };
  737. this.send_message = function (msg) {
  738. };
  739. this.close_session = function () {
  740. this.on_session_close();
  741. };
  742. }
  743. function WebSocketWebIOSession(ws_url) {
  744. WebIOSession.apply(this);
  745. this.ws = null;
  746. this.debug = false;
  747. var this_ = this;
  748. this.start_session = function (debug = false) {
  749. this.debug = debug;
  750. this.ws = new WebSocket(ws_url);
  751. this.ws.onopen = this.on_session_create;
  752. this.ws.onclose = this.on_session_close;
  753. this.ws.onmessage = function (evt) {
  754. var msg = JSON.parse(evt.data);
  755. if (debug) console.debug('>>>', msg);
  756. this_.on_server_message(msg);
  757. };
  758. };
  759. this.send_message = function (msg) {
  760. if (this.ws === null)
  761. return console.error('WebSocketWebIOSession.ws is null when invoke WebSocketWebIOSession.send_message. ' +
  762. 'Please call WebSocketWebIOSession.start_session first');
  763. this.ws.send(JSON.stringify(msg));
  764. if (this.debug) console.debug('<<<', msg);
  765. };
  766. this.close_session = function () {
  767. this.on_session_close();
  768. try {
  769. this.ws.close()
  770. } catch (e) {
  771. }
  772. };
  773. }
  774. function HttpWebIOSession(api_url, pull_interval_ms = 1000) {
  775. WebIOSession.apply(this);
  776. this.api_url = api_url;
  777. this.interval_pull_id = null;
  778. this.webio_session_id = '';
  779. this.debug = false;
  780. var this_ = this;
  781. this._on_request_success = function (data, textStatus, jqXHR) {
  782. var sid = jqXHR.getResponseHeader('webio-session-id');
  783. if (sid) this_.webio_session_id = sid;
  784. for (var idx in data) {
  785. var msg = data[idx];
  786. if (this_.debug) console.debug('>>>', msg);
  787. this_.on_server_message(msg);
  788. }
  789. };
  790. this.start_session = function (debug = false) {
  791. this.debug = debug;
  792. function pull() {
  793. $.ajax({
  794. type: "GET",
  795. url: this_.api_url,
  796. contentType: "application/json; charset=utf-8",
  797. dataType: "json",
  798. headers: {webio_session_id: this_.webio_session_id},
  799. success: function (data, textStatus, jqXHR) {
  800. this_._on_request_success(data, textStatus, jqXHR);
  801. this_.on_session_create();
  802. },
  803. error: function () {
  804. console.error('Http pulling failed');
  805. }
  806. })
  807. }
  808. pull();
  809. this.interval_pull_id = setInterval(pull, pull_interval_ms);
  810. };
  811. this.send_message = function (msg) {
  812. if (this_.debug) console.debug('<<<', msg);
  813. $.ajax({
  814. type: "POST",
  815. url: this.api_url,
  816. data: JSON.stringify(msg),
  817. contentType: "application/json; charset=utf-8",
  818. dataType: "json",
  819. headers: {webio_session_id: this_.webio_session_id},
  820. success: this_._on_request_success,
  821. error: function () { // todo
  822. console.error('Http push event failed, event data: %s', msg);
  823. }
  824. })
  825. };
  826. this.close_session = function () {
  827. this.on_session_close();
  828. clearInterval(this.interval_pull_id);
  829. };
  830. }
  831. var WebIOSession_;
  832. function WebIOController(webio_session, output_container_elem, input_container_elem) {
  833. WebIOSession_ = webio_session;
  834. webio_session.on_session_close = function () {
  835. document.title = 'Closed';
  836. $('#title').text('Closed'); // todo
  837. };
  838. this.output_ctrl = new OutputController(webio_session, output_container_elem);
  839. this.input_ctrl = new FormsController(webio_session, input_container_elem);
  840. this.output_cmds = make_set(this.output_ctrl.accept_command);
  841. this.input_cmds = make_set(this.input_ctrl.accept_command);
  842. var this_ = this;
  843. webio_session.on_server_message = function (msg) {
  844. if (msg.command in this_.input_cmds)
  845. this_.input_ctrl.handle_message(msg);
  846. else if (msg.command in this_.output_cmds)
  847. this_.output_ctrl.handle_message(msg);
  848. else if (msg.command === 'close_session')
  849. webio_session.close_session();
  850. else
  851. console.error('Unknown command:%s', msg.command);
  852. };
  853. }
  854. return {
  855. 'HttpWebIOSession': HttpWebIOSession,
  856. 'WebSocketWebIOSession': WebSocketWebIOSession,
  857. 'WebIOController': WebIOController,
  858. 'DisplayAreaButtonOnClick': DisplayAreaButtonOnClick,
  859. }
  860. })));