pywebio.js 43 KB

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