pywebio.js 43 KB

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