pywebio.js 43 KB

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