form.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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. // 当设置了AutoScrollBottom、并且不指定锚点进行输出时,滚动到底部
  117. if (AutoScrollBottom && msg.command !== 'output_ctl' && msg.spec.before === undefined && msg.spec.after === 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}}<label for="{{id_name}}">{{label}}</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}}<label for="{{id_name}}">{{label}}</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}}<label for="{{id_name}}">{{label}}</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. that.code_mirror.setSize(null, 20 * that.spec.rows);
  541. CodeMirror.autoLoadMode(that.code_mirror, config.mode);
  542. if (config.theme)
  543. load_codemirror_theme(config.theme);
  544. }, ShowDuration + 100);
  545. }
  546. };
  547. TextareaInputController.prototype.update_input = function (spec) {
  548. var attributes = spec.attributes;
  549. this.update_input_helper(-1, attributes);
  550. };
  551. TextareaInputController.prototype.get_value = function () {
  552. return this.element.find('textarea').val();
  553. };
  554. function CheckboxRadioController(webio_session, task_id, spec) {
  555. FormItemController.apply(this, arguments);
  556. this.create_element();
  557. }
  558. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  559. const checkbox_radio_tpl = `
  560. <div class="form-group">
  561. {{#label}}<label>{{label}}</label>{{/label}}
  562. {{#inline}}<br>{{/inline}}
  563. {{#options}}
  564. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  565. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" name="{{name}}" value="{{value}}" {{#selected}}checked{{/selected}} {{#disabled}}disabled{{/disabled}} class="form-check-input">
  566. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  567. {{label}}
  568. </label>
  569. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  570. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  571. </div>
  572. {{/options}}
  573. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  574. </div>`;
  575. CheckboxRadioController.prototype.create_element = function () {
  576. var spec = deep_copy(this.spec);
  577. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  578. spec['id_name_prefix'] = id_name_prefix;
  579. for (var idx in spec.options) {
  580. spec.options[idx]['idx'] = idx;
  581. }
  582. const html = Mustache.render(checkbox_radio_tpl, spec);
  583. var elem = $(html);
  584. this.element = elem;
  585. const ignore_keys = {'value': '', 'label': '', 'selected': ''};
  586. for (idx = 0; idx < this.spec.options.length; idx++) {
  587. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  588. // blur事件时,发送当前值到服务器
  589. // checkbox_radio 不产生blur事件
  590. // input_elem.on('blur', this.send_value_listener);
  591. // 将额外的html参数加到input标签上
  592. for (var key in this.spec.options[idx]) {
  593. if (key in ignore_keys) continue;
  594. input_elem.attr(key, this.spec.options[idx][key]);
  595. }
  596. }
  597. };
  598. CheckboxRadioController.prototype.update_input = function (spec) {
  599. var attributes = spec.attributes;
  600. var idx = -1;
  601. if ('target_value' in spec) {
  602. this.element.find('input').each(function (index) {
  603. if ($(this).val() === spec.target_value) {
  604. idx = index;
  605. return false;
  606. }
  607. });
  608. }
  609. this.update_input_helper(idx, attributes);
  610. };
  611. CheckboxRadioController.prototype.get_value = function () {
  612. if (this.spec.type === 'radio') {
  613. return this.element.find('input').val();
  614. } else {
  615. var value_arr = this.element.find('input').serializeArray();
  616. var res = [];
  617. var that = this;
  618. $.each(value_arr, function (idx, val) {
  619. if (val.name === that.spec.name)
  620. res.push(val.value);
  621. });
  622. return res;
  623. }
  624. };
  625. function ButtonsController(webio_session, task_id, spec) {
  626. FormItemController.apply(this, arguments);
  627. this.last_checked_value = null; // 上次点击按钮的value
  628. this.create_element();
  629. }
  630. ButtonsController.prototype.accept_input_types = ["actions"];
  631. const buttons_tpl = `
  632. <div class="form-group">
  633. {{#label}}<label>{{label}}</label> <br> {{/label}}
  634. {{#buttons}}
  635. <button type="submit" value="{{value}}" aria-describedby="{{name}}_help" {{#disabled}}disabled{{/disabled}} class="btn btn-primary">{{label}}</button>
  636. {{/buttons}}
  637. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  638. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  639. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  640. </div>`;
  641. ButtonsController.prototype.create_element = function () {
  642. const html = Mustache.render(buttons_tpl, this.spec);
  643. this.element = $(html);
  644. // todo:是否有必要监听click事件,因为点击后即提交了表单
  645. var that = this;
  646. this.element.find('button').on('click', function (e) {
  647. var btn = $(this);
  648. that.last_checked_value = btn.val();
  649. });
  650. };
  651. ButtonsController.prototype.update_input = function (spec) {
  652. var attributes = spec.attributes;
  653. var idx = -1;
  654. if ('target_value' in spec) {
  655. this.element.find('button').each(function (index) {
  656. if ($(this).val() === spec.target_value) {
  657. idx = index;
  658. return false;
  659. }
  660. });
  661. }
  662. this.update_input_helper(idx, attributes);
  663. };
  664. ButtonsController.prototype.get_value = function () {
  665. return this.last_checked_value;
  666. };
  667. function FileInputController(webio_session, task_id, spec) {
  668. FormItemController.apply(this, arguments);
  669. this.data_url_value = null;
  670. this.create_element();
  671. }
  672. FileInputController.prototype.accept_input_types = ["file"];
  673. const file_input_tpl = `
  674. <div class="form-group">
  675. {{#label}}<label for="{{id_name}}">{{label}}</label>{{/label}}
  676. <div class="custom-file">
  677. <input type="file" name="{{name}}" class="custom-file-input" id="{{id_name}}" aria-describedby="{{id_name}}_help">
  678. <label class="custom-file-label" for="{{id_name}}">{{placeholder}}</label>
  679. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  680. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  681. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  682. </div>
  683. </div>`;
  684. FileInputController.prototype.create_element = function () {
  685. var spec = deep_copy(this.spec);
  686. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  687. spec['id_name'] = id_name;
  688. const html = Mustache.render(file_input_tpl, spec);
  689. this.element = $(html);
  690. var input_elem = this.element.find('input[type="file"]');
  691. const ignore_keys = {
  692. 'label': '',
  693. 'invalid_feedback': '',
  694. 'valid_feedback': '',
  695. 'help_text': '',
  696. 'placeholder': ''
  697. };
  698. for (var key in this.spec) {
  699. if (key in ignore_keys) continue;
  700. input_elem.attr(key, this.spec[key]);
  701. }
  702. // 文件选中后先不通知后端
  703. var that = this;
  704. input_elem.on('change', function () {
  705. var file = input_elem[0].files[0];
  706. var fr = new FileReader();
  707. fr.onload = function () {
  708. that.data_url_value = {
  709. 'filename': file.name, 'dataurl': fr.result
  710. };
  711. console.log(that.data_url_value);
  712. };
  713. fr.readAsDataURL(file);
  714. });
  715. // todo 通过回调的方式调用init
  716. setTimeout(bsCustomFileInput.init, ShowDuration + 100);
  717. };
  718. FileInputController.prototype.update_input = function (spec) {
  719. var attributes = spec.attributes;
  720. this.update_input_helper(-1, attributes);
  721. };
  722. FileInputController.prototype.get_value = function () {
  723. return this.data_url_value;
  724. };
  725. /*
  726. * 会话
  727. * 向外暴露的事件:on_session_create、on_session_close、on_server_message
  728. * 提供的函数:start_session、send_message、close_session
  729. * */
  730. function WebIOSession() {
  731. this.on_session_create = () => {
  732. };
  733. this.on_session_close = () => {
  734. };
  735. this.on_server_message = (msg) => {
  736. };
  737. this.start_session = function (debug = false) {
  738. };
  739. this.send_message = function (msg) {
  740. };
  741. this.close_session = function () {
  742. this.on_session_close();
  743. };
  744. }
  745. function WebSocketWebIOSession(ws_url) {
  746. WebIOSession.apply(this);
  747. this.ws = null;
  748. this.debug = false;
  749. var url = new URL(ws_url);
  750. if (url.protocol !== 'wss:' && url.protocol !== 'ws:') {
  751. var protocol = url.protocol || window.location.protocol;
  752. url.protocol = protocol.replace('https', 'wss').replace('http', 'ws');
  753. }
  754. ws_url = url.href;
  755. var this_ = this;
  756. this.start_session = function (debug = false) {
  757. this.debug = debug;
  758. this.ws = new WebSocket(ws_url);
  759. this.ws.onopen = this.on_session_create;
  760. this.ws.onclose = this.on_session_close;
  761. this.ws.onmessage = function (evt) {
  762. var msg = JSON.parse(evt.data);
  763. if (debug) console.debug('>>>', msg);
  764. this_.on_server_message(msg);
  765. };
  766. };
  767. this.send_message = function (msg) {
  768. if (this.ws === null)
  769. return console.error('WebSocketWebIOSession.ws is null when invoke WebSocketWebIOSession.send_message. ' +
  770. 'Please call WebSocketWebIOSession.start_session first');
  771. this.ws.send(JSON.stringify(msg));
  772. if (this.debug) console.debug('<<<', msg);
  773. };
  774. this.close_session = function () {
  775. this.on_session_close();
  776. try {
  777. this.ws.close()
  778. } catch (e) {
  779. }
  780. };
  781. }
  782. function HttpWebIOSession(api_url, pull_interval_ms = 1000) {
  783. WebIOSession.apply(this);
  784. this.api_url = api_url;
  785. this.interval_pull_id = null;
  786. this.webio_session_id = '';
  787. this.debug = false;
  788. var this_ = this;
  789. this._on_request_success = function (data, textStatus, jqXHR) {
  790. var sid = jqXHR.getResponseHeader('webio-session-id');
  791. if (sid) this_.webio_session_id = sid;
  792. for (var idx in data) {
  793. var msg = data[idx];
  794. if (this_.debug) console.debug('>>>', msg);
  795. this_.on_server_message(msg);
  796. }
  797. };
  798. this.start_session = function (debug = false) {
  799. this.debug = debug;
  800. function pull() {
  801. $.ajax({
  802. type: "GET",
  803. url: this_.api_url,
  804. contentType: "application/json; charset=utf-8",
  805. dataType: "json",
  806. headers: {"webio-session-id": this_.webio_session_id},
  807. success: function (data, textStatus, jqXHR) {
  808. this_._on_request_success(data, textStatus, jqXHR);
  809. this_.on_session_create();
  810. },
  811. error: function () {
  812. console.error('Http pulling failed');
  813. }
  814. })
  815. }
  816. pull();
  817. this.interval_pull_id = setInterval(pull, pull_interval_ms);
  818. };
  819. this.send_message = function (msg) {
  820. if (this_.debug) console.debug('<<<', msg);
  821. $.ajax({
  822. type: "POST",
  823. url: this.api_url,
  824. data: JSON.stringify(msg),
  825. contentType: "application/json; charset=utf-8",
  826. dataType: "json",
  827. headers: {"webio-session-id": this_.webio_session_id},
  828. success: this_._on_request_success,
  829. error: function () { // todo
  830. console.error('Http push event failed, event data: %s', msg);
  831. }
  832. })
  833. };
  834. this.close_session = function () {
  835. this.on_session_close();
  836. clearInterval(this.interval_pull_id);
  837. };
  838. }
  839. var WebIOSession_;
  840. function WebIOController(webio_session, output_container_elem, input_container_elem) {
  841. WebIOSession_ = webio_session;
  842. webio_session.on_session_close = function () {
  843. document.title = 'Closed';
  844. $('#title').text('Closed'); // todo
  845. };
  846. this.output_ctrl = new OutputController(webio_session, output_container_elem);
  847. this.input_ctrl = new FormsController(webio_session, input_container_elem);
  848. this.output_cmds = make_set(this.output_ctrl.accept_command);
  849. this.input_cmds = make_set(this.input_ctrl.accept_command);
  850. var this_ = this;
  851. webio_session.on_server_message = function (msg) {
  852. if (msg.command in this_.input_cmds)
  853. this_.input_ctrl.handle_message(msg);
  854. else if (msg.command in this_.output_cmds)
  855. this_.output_ctrl.handle_message(msg);
  856. else if (msg.command === 'close_session')
  857. webio_session.close_session();
  858. else
  859. console.error('Unknown command:%s', msg.command);
  860. };
  861. }
  862. return {
  863. 'HttpWebIOSession': HttpWebIOSession,
  864. 'WebSocketWebIOSession': WebSocketWebIOSession,
  865. 'WebIOController': WebIOController,
  866. 'DisplayAreaButtonOnClick': DisplayAreaButtonOnClick,
  867. }
  868. })));