pywebio.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. return $($.parseHTML(spec.content));
  169. };
  170. OutputController.prototype.get_buttons_element = function (spec) {
  171. const btns_tpl = `<div class="form-group">{{#buttons}}
  172. <button value="{{value}}" onclick="WebIO.DisplayAreaButtonOnClick(this, '{{callback_id}}')" class="btn btn-primary {{#small}}btn-sm{{/small}}">{{label}}</button>
  173. {{/buttons}}</div>`;
  174. var html = Mustache.render(btns_tpl, spec);
  175. return $(html);
  176. };
  177. OutputController.prototype.get_file_element = function (spec) {
  178. const html = `<div class="form-group"><button type="button" class="btn btn-link">${spec.name}</button></div>`;
  179. var element = $(html);
  180. var blob = b64toBlob(spec.content);
  181. element.on('click', 'button', function (e) {
  182. saveAs(blob, spec.name, {}, false);
  183. });
  184. return element;
  185. };
  186. OutputController.prototype.handle_output_ctl = function (msg) {
  187. if (msg.spec.title) {
  188. $('#title').text(msg.spec.title); // 直接使用#title不规范 todo
  189. document.title = msg.spec.title;
  190. }
  191. if (msg.spec.output_fixed_height !== undefined) {
  192. OutputFixedHeight = msg.spec.output_fixed_height;
  193. if (msg.spec.output_fixed_height)
  194. $('.container').removeClass('no-fix-height'); // todo 不规范
  195. else
  196. $('.container').addClass('no-fix-height'); // todo 不规范
  197. }
  198. if (msg.spec.auto_scroll_bottom !== undefined)
  199. AutoScrollBottom = msg.spec.auto_scroll_bottom;
  200. if (msg.spec.set_anchor !== undefined) {
  201. this.container_elem.find(`#${msg.spec.set_anchor}`).attr('id', '');
  202. this.container_elem.append(`<div id="${msg.spec.set_anchor}"></div>`);
  203. }
  204. if (msg.spec.clear_before !== undefined)
  205. this.container_elem.find(`#${msg.spec.clear_before}`).prevAll().remove();
  206. if (msg.spec.clear_after !== undefined)
  207. this.container_elem.find(`#${msg.spec.clear_after}~*`).remove();
  208. if (msg.spec.scroll_to !== undefined) {
  209. var target = $(`#${msg.spec.scroll_to}`);
  210. 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 FormStack() {
  337. push();
  338. pop();
  339. empty();
  340. show();// 显示栈顶元素
  341. hide();// 隐藏栈顶元素
  342. }
  343. function FormController(webio_session, task_id, spec) {
  344. this.webio_session = webio_session;
  345. this.task_id = task_id;
  346. this.spec = spec;
  347. this.element = undefined;
  348. this.name2input_controllers = {}; // name -> input_controller
  349. this.create_element();
  350. }
  351. FormController.prototype.input_controllers = [FileInputController, CommonInputController, CheckboxRadioController, ButtonsController, TextareaInputController];
  352. FormController.prototype.create_element = function () {
  353. var tpl = `
  354. <div class="card" style="display: none">
  355. <h5 class="card-header">{{label}}</h5>
  356. <div class="card-body">
  357. <form>
  358. <div class="input-container"></div>
  359. <div class="ws-form-submit-btns">
  360. <button type="submit" class="btn btn-primary">提交</button>
  361. <button type="reset" class="btn btn-warning">重置</button>
  362. {{#cancelable}}<button type="button" class="pywebio_cancel_btn btn btn-danger">取消</button>{{/cancelable}}
  363. </div>
  364. </form>
  365. </div>
  366. </div>`;
  367. var that = this;
  368. const html = Mustache.render(tpl, {label: this.spec.label, cancelable: this.spec.cancelable});
  369. this.element = $(html);
  370. this.element.find('.pywebio_cancel_btn').on('click', function (e) {
  371. that.webio_session.send_message({
  372. event: "from_cancel",
  373. task_id: that.task_id,
  374. data: null
  375. });
  376. });
  377. // 如果表单最后一个输入元素为actions组件,则隐藏默认的"提交"/"重置"按钮
  378. if (this.spec.inputs.length && this.spec.inputs[this.spec.inputs.length - 1].type === 'actions')
  379. this.element.find('.ws-form-submit-btns').hide();
  380. // 输入控件创建
  381. var body = this.element.find('.input-container');
  382. for (var idx in this.spec.inputs) {
  383. var input_spec = this.spec.inputs[idx];
  384. var ctrl = undefined;
  385. for (var i in this.input_controllers) {
  386. var ctrl_cls = this.input_controllers[i];
  387. // console.log(ctrl_cls, ctrl_cls.prototype.accept_input_types);
  388. if (input_spec.type in make_set(ctrl_cls.prototype.accept_input_types)) {
  389. ctrl = new ctrl_cls(this.webio_session, this.task_id, input_spec);
  390. break;
  391. }
  392. }
  393. if (ctrl) {
  394. this.name2input_controllers[input_spec.name] = ctrl;
  395. body.append(ctrl.element);
  396. } else {
  397. console.error('Unvalid input type:%s', input_spec.type);
  398. }
  399. }
  400. // 事件绑定
  401. this.element.on('submit', 'form', function (e) {
  402. e.preventDefault(); // avoid to execute the actual submit of the form.
  403. var data = {};
  404. $.each(that.name2input_controllers, (name, ctrl) => {
  405. data[name] = ctrl.get_value();
  406. });
  407. that.webio_session.send_message({
  408. event: "from_submit",
  409. task_id: that.task_id,
  410. data: data
  411. });
  412. });
  413. };
  414. FormController.prototype.dispatch_ctrl_message = function (spec) {
  415. if (!(spec.target_name in this.name2input_controllers)) {
  416. return console.error('Can\'t find input[name=%s] element in curr form!', spec.target_name);
  417. }
  418. this.name2input_controllers[spec.target_name].update_input(spec);
  419. };
  420. function FormItemController(webio_session, task_id, spec) {
  421. this.webio_session = webio_session;
  422. this.task_id = task_id;
  423. this.spec = spec;
  424. this.element = undefined;
  425. var that = this;
  426. this.send_value_listener = function (e) {
  427. var this_elem = $(this);
  428. that.webio_session.send_message({
  429. event: "input_event",
  430. task_id: that.task_id,
  431. data: {
  432. event_name: e.type.toLowerCase(),
  433. name: that.spec.name,
  434. value: that.get_value()
  435. }
  436. });
  437. };
  438. /*
  439. * input_idx: 更新作用对象input标签的索引, -1 为不指定对象
  440. * attributes:更新值字典
  441. * */
  442. this.update_input_helper = function (input_idx, attributes) {
  443. var attr2selector = {
  444. 'invalid_feedback': 'div.invalid-feedback',
  445. 'valid_feedback': 'div.valid-feedback',
  446. 'help_text': 'small.text-muted'
  447. };
  448. for (var attribute in attr2selector) {
  449. if (attribute in attributes) {
  450. if (input_idx === -1)
  451. this.element.find(attr2selector[attribute]).text(attributes[attribute]);
  452. else
  453. this.element.find(attr2selector[attribute]).eq(input_idx).text(attributes[attribute]);
  454. delete attributes[attribute];
  455. }
  456. }
  457. var input_elem = this.element.find('input,select,textarea');
  458. if (input_idx >= 0)
  459. input_elem = input_elem.eq(input_idx);
  460. if ('valid_status' in attributes) {
  461. var class_name = attributes.valid_status ? 'is-valid' : 'is-invalid';
  462. input_elem.removeClass('is-valid is-invalid').addClass(class_name);
  463. delete attributes.valid_status;
  464. }
  465. input_elem.attr(attributes);
  466. }
  467. }
  468. function CommonInputController(webio_session, task_id, spec) {
  469. FormItemController.apply(this, arguments);
  470. this.create_element();
  471. }
  472. CommonInputController.prototype.accept_input_types = ["text", "password", "number", "color", "date", "range", "time", "select", "file"];
  473. /*
  474. *
  475. * type=
  476. * */
  477. const common_input_tpl = `
  478. <div class="form-group">
  479. {{#label}}<label for="{{id_name}}">{{label}}</label>{{/label}}
  480. <input type="{{type}}" id="{{id_name}}" aria-describedby="{{id_name}}_help" {{#list}}list="{{list}}"{{/list}} class="form-control" >
  481. <datalist id="{{id_name}}-list">
  482. {{#datalist}}
  483. <option>{{.}}</option>
  484. {{/datalist}}
  485. </datalist>
  486. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  487. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  488. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  489. </div>`;
  490. const select_input_tpl = `
  491. <div class="form-group">
  492. {{#label}}<label for="{{id_name}}">{{label}}</label>{{/label}}
  493. <select id="{{id_name}}" aria-describedby="{{id_name}}_help" class="form-control" {{#multiple}}multiple{{/multiple}}>
  494. {{#options}}
  495. <option value="{{value}}" {{#selected}}selected{{/selected}} {{#disabled}}disabled{{/disabled}}>{{label}}</option>
  496. {{/options}}
  497. </select>
  498. <div class="invalid-feedback">{{invalid_feedback}}</div>
  499. <div class="valid-feedback">{{valid_feedback}}</div>
  500. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  501. </div>`;
  502. CommonInputController.prototype.create_element = function () {
  503. var spec = deep_copy(this.spec);
  504. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  505. spec['id_name'] = id_name;
  506. if (spec.datalist)
  507. spec['list'] = id_name + '-list';
  508. var html;
  509. if (spec.type === 'select')
  510. html = Mustache.render(select_input_tpl, spec);
  511. else
  512. html = Mustache.render(common_input_tpl, spec);
  513. this.element = $(html);
  514. var input_elem = this.element.find('#' + id_name);
  515. // blur事件时,发送当前值到服务器
  516. input_elem.on('blur', this.send_value_listener);
  517. // 将额外的html参数加到input标签上
  518. const ignore_keys = {
  519. 'type': '',
  520. 'label': '',
  521. 'invalid_feedback': '',
  522. 'valid_feedback': '',
  523. 'help_text': '',
  524. 'options': '',
  525. 'datalist': '',
  526. 'multiple':''
  527. };
  528. for (var key in this.spec) {
  529. if (key in ignore_keys) continue;
  530. input_elem.attr(key, this.spec[key]);
  531. }
  532. };
  533. CommonInputController.prototype.update_input = function (spec) {
  534. var attributes = spec.attributes;
  535. this.update_input_helper(-1, attributes);
  536. };
  537. CommonInputController.prototype.get_value = function () {
  538. return this.element.find('input,select').val();
  539. };
  540. function TextareaInputController(webio_session, task_id, spec) {
  541. FormItemController.apply(this, arguments);
  542. this.create_element();
  543. }
  544. function load_codemirror_theme(theme, url_tpl = "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/theme/%N.min.css") {
  545. var cssId = 'codemirror_theme_' + theme; // you could encode the css path itself to generate id..
  546. if (!document.getElementById(cssId)) {
  547. var head = document.getElementsByTagName('head')[0];
  548. var link = document.createElement('link');
  549. link.id = cssId;
  550. link.rel = 'stylesheet';
  551. link.type = 'text/css';
  552. link.href = url_tpl.replace('%N', theme);
  553. link.media = 'all';
  554. head.appendChild(link);
  555. }
  556. }
  557. TextareaInputController.prototype.accept_input_types = ["textarea"];
  558. const textarea_input_tpl = `
  559. <div class="form-group">
  560. {{#label}}<label for="{{id_name}}">{{label}}</label>{{/label}}
  561. <textarea id="{{id_name}}" aria-describedby="{{id_name}}_help" rows="{{rows}}" class="form-control" >{{value}}</textarea>
  562. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  563. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  564. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  565. </div>`;
  566. TextareaInputController.prototype.create_element = function () {
  567. var spec = deep_copy(this.spec);
  568. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  569. spec['id_name'] = id_name;
  570. var html = Mustache.render(textarea_input_tpl, spec);
  571. this.element = $(html);
  572. var input_elem = this.element.find('#' + id_name);
  573. // blur事件时,发送当前值到服务器
  574. // input_elem.on('blur', this.send_value_listener);
  575. // 将额外的html参数加到input标签上
  576. const ignore_keys = make_set(['value', 'type', 'label', 'invalid_feedback', 'valid_feedback', 'help_text', 'rows', 'code']);
  577. for (var key in this.spec) {
  578. if (key in ignore_keys) continue;
  579. input_elem.attr(key, this.spec[key]);
  580. }
  581. if (spec.code) {
  582. var that = this;
  583. var config = {
  584. 'mode': 'python',
  585. 'lineNumbers': true, // 显示行数
  586. 'indentUnit': 4, //缩进单位为4
  587. 'styleActiveLine': true, // 当前行背景高亮
  588. 'matchBrackets': true, //括号匹配
  589. 'lineWrapping': true, //自动换行
  590. };
  591. for (var k in that.spec.code) config[k] = that.spec.code[k];
  592. CodeMirror.autoLoadMode(that.code_mirror, config.mode);
  593. if (config.theme)
  594. load_codemirror_theme(config.theme);
  595. setTimeout(function () { // 需要等待当前表单被添加到文档树中后,再初始化CodeMirror,否则CodeMirror样式会发生错误
  596. that.code_mirror = CodeMirror.fromTextArea(that.element.find('textarea')[0], config);
  597. that.code_mirror.setSize(null, 20 * that.spec.rows);
  598. }, 100);
  599. setTimeout(function () { // 需要等待当前表单显示后,重新计算表单高度
  600. // 重新计算表单高度
  601. that.element.parents('.card').height('auto');
  602. }, ShowDuration);
  603. }
  604. };
  605. TextareaInputController.prototype.update_input = function (spec) {
  606. var attributes = spec.attributes;
  607. this.update_input_helper.call(this, -1, attributes);
  608. };
  609. TextareaInputController.prototype.get_value = function () {
  610. return this.element.find('textarea').val();
  611. };
  612. function CheckboxRadioController(webio_session, task_id, spec) {
  613. FormItemController.apply(this, arguments);
  614. this.create_element();
  615. }
  616. CheckboxRadioController.prototype.accept_input_types = ["checkbox", "radio"];
  617. const checkbox_radio_tpl = `
  618. <div class="form-group">
  619. {{#label}}<label>{{label}}</label>{{/label}}
  620. {{#inline}}<br>{{/inline}}
  621. {{#options}}
  622. <div class="form-check {{#inline}}form-check-inline{{/inline}}">
  623. <input type="{{type}}" id="{{id_name_prefix}}-{{idx}}" name="{{name}}" value="{{value}}" {{#selected}}checked{{/selected}} {{#disabled}}disabled{{/disabled}} class="form-check-input">
  624. <label class="form-check-label" for="{{id_name_prefix}}-{{idx}}">
  625. {{label}}
  626. </label>
  627. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  628. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  629. </div>
  630. {{/options}}
  631. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  632. </div>`;
  633. CheckboxRadioController.prototype.create_element = function () {
  634. var spec = deep_copy(this.spec);
  635. const id_name_prefix = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  636. spec['id_name_prefix'] = id_name_prefix;
  637. for (var idx in spec.options) {
  638. spec.options[idx]['idx'] = idx;
  639. }
  640. const html = Mustache.render(checkbox_radio_tpl, spec);
  641. var elem = $(html);
  642. this.element = elem;
  643. const ignore_keys = {'value': '', 'label': '', 'selected': ''};
  644. for (idx = 0; idx < this.spec.options.length; idx++) {
  645. var input_elem = elem.find('#' + id_name_prefix + '-' + idx);
  646. // blur事件时,发送当前值到服务器
  647. // checkbox_radio 不产生blur事件
  648. // input_elem.on('blur', this.send_value_listener);
  649. // 将额外的html参数加到input标签上
  650. for (var key in this.spec.options[idx]) {
  651. if (key in ignore_keys) continue;
  652. input_elem.attr(key, this.spec.options[idx][key]);
  653. }
  654. }
  655. };
  656. CheckboxRadioController.prototype.update_input = function (spec) {
  657. var attributes = spec.attributes;
  658. var idx = -1;
  659. if ('target_value' in spec) {
  660. this.element.find('input').each(function (index) {
  661. if ($(this).val() === spec.target_value) {
  662. idx = index;
  663. return false;
  664. }
  665. });
  666. }
  667. this.update_input_helper(idx, attributes);
  668. };
  669. CheckboxRadioController.prototype.get_value = function () {
  670. if (this.spec.type === 'radio') {
  671. return this.element.find('input:checked').val() || '';
  672. } else {
  673. var value_arr = this.element.find('input').serializeArray();
  674. var res = [];
  675. var that = this;
  676. $.each(value_arr, function (idx, val) {
  677. if (val.name === that.spec.name)
  678. res.push(val.value);
  679. });
  680. return res;
  681. }
  682. };
  683. function ButtonsController(webio_session, task_id, spec) {
  684. FormItemController.apply(this, arguments);
  685. this.submit_value = null; // 提交表单时按钮组的value
  686. this.create_element();
  687. }
  688. ButtonsController.prototype.accept_input_types = ["actions"];
  689. const buttons_tpl = `
  690. <div class="form-group">
  691. {{#label}}<label>{{label}}</label> <br> {{/label}}
  692. {{#buttons}}
  693. <button type="{{btn_type}}" data-type="{{type}}" value="{{value}}" aria-describedby="{{name}}_help" {{#disabled}}disabled{{/disabled}} class="btn btn-primary">{{label}}</button>
  694. {{/buttons}}
  695. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  696. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  697. <small id="{{name}}_help" class="form-text text-muted">{{help_text}}</small>
  698. </div>`;
  699. ButtonsController.prototype.create_element = function () {
  700. for (var b of this.spec.buttons) b['btn_type'] = b.type === "submit" ? "submit" : "button";
  701. const html = Mustache.render(buttons_tpl, this.spec);
  702. this.element = $(html);
  703. var that = this;
  704. this.element.find('button').on('click', function (e) {
  705. var btn = $(this);
  706. if (btn.data('type') === 'submit') {
  707. that.submit_value = btn.val();
  708. // 不可以使用 btn.parents('form').submit(), 会导致input 的required属性失效
  709. } else if (btn.data('type') === 'reset') {
  710. btn.parents('form').trigger("reset");
  711. } else if (btn.data('type') === 'cancel') {
  712. that.webio_session.send_message({
  713. event: "from_cancel",
  714. task_id: that.task_id,
  715. data: null
  716. });
  717. } else {
  718. console.error("`actions` input: unknown button type '%s'", btn.data('type'));
  719. }
  720. });
  721. };
  722. ButtonsController.prototype.update_input = function (spec) {
  723. var attributes = spec.attributes;
  724. var idx = -1;
  725. if ('target_value' in spec) {
  726. this.element.find('button').each(function (index) {
  727. if ($(this).val() === spec.target_value) {
  728. idx = index;
  729. return false;
  730. }
  731. });
  732. }
  733. this.update_input_helper(idx, attributes);
  734. };
  735. ButtonsController.prototype.get_value = function () {
  736. return this.submit_value;
  737. };
  738. function FileInputController(webio_session, task_id, spec) {
  739. FormItemController.apply(this, arguments);
  740. this.data_url_value = null;
  741. this.create_element();
  742. }
  743. FileInputController.prototype.accept_input_types = ["file"];
  744. const file_input_tpl = `
  745. <div class="form-group">
  746. {{#label}}<label for="{{id_name}}">{{label}}</label>{{/label}}
  747. <div class="custom-file">
  748. <input type="file" name="{{name}}" class="custom-file-input" id="{{id_name}}" aria-describedby="{{id_name}}_help">
  749. <label class="custom-file-label" for="{{id_name}}">{{placeholder}}</label>
  750. <div class="invalid-feedback">{{invalid_feedback}}</div> <!-- input 添加 is-invalid 类 -->
  751. <div class="valid-feedback">{{valid_feedback}}</div> <!-- input 添加 is-valid 类 -->
  752. <small id="{{id_name}}_help" class="form-text text-muted">{{help_text}}</small>
  753. </div>
  754. </div>`;
  755. FileInputController.prototype.create_element = function () {
  756. var spec = deep_copy(this.spec);
  757. const id_name = spec.name + '-' + Math.floor(Math.random() * Math.floor(9999));
  758. spec['id_name'] = id_name;
  759. const html = Mustache.render(file_input_tpl, spec);
  760. this.element = $(html);
  761. var input_elem = this.element.find('input[type="file"]');
  762. const ignore_keys = {
  763. 'label': '',
  764. 'invalid_feedback': '',
  765. 'valid_feedback': '',
  766. 'help_text': '',
  767. 'placeholder': ''
  768. };
  769. for (var key in this.spec) {
  770. if (key in ignore_keys) continue;
  771. input_elem.attr(key, this.spec[key]);
  772. }
  773. // 文件选中后先不通知后端
  774. var that = this;
  775. input_elem.on('change', function () {
  776. var file = input_elem[0].files[0];
  777. var fr = new FileReader();
  778. fr.onload = function () {
  779. that.data_url_value = {
  780. 'filename': file.name, 'dataurl': fr.result
  781. };
  782. console.log(that.data_url_value);
  783. };
  784. fr.readAsDataURL(file);
  785. });
  786. // todo 通过回调的方式调用init
  787. setTimeout(bsCustomFileInput.init, ShowDuration + 100);
  788. };
  789. FileInputController.prototype.update_input = function (spec) {
  790. var attributes = spec.attributes;
  791. this.update_input_helper(-1, attributes);
  792. };
  793. FileInputController.prototype.get_value = function () {
  794. return this.data_url_value;
  795. };
  796. /*
  797. * 会话
  798. * 向外暴露的事件:on_session_create、on_session_close、on_server_message
  799. * 提供的函数:start_session、send_message、close_session
  800. * */
  801. function WebIOSession() {
  802. this.on_session_create = () => {
  803. };
  804. this.on_session_close = () => {
  805. };
  806. this.on_server_message = (msg) => {
  807. };
  808. this.start_session = function (debug = false) {
  809. };
  810. this.send_message = function (msg) {
  811. };
  812. this.close_session = function () {
  813. this.on_session_close();
  814. };
  815. }
  816. function WebSocketWebIOSession(ws_url) {
  817. WebIOSession.apply(this);
  818. this.ws = null;
  819. this.debug = false;
  820. var url = new URL(ws_url);
  821. if (url.protocol !== 'wss:' && url.protocol !== 'ws:') {
  822. var protocol = url.protocol || window.location.protocol;
  823. url.protocol = protocol.replace('https', 'wss').replace('http', 'ws');
  824. }
  825. ws_url = url.href;
  826. var this_ = this;
  827. this.start_session = function (debug = false) {
  828. this.debug = debug;
  829. this.ws = new WebSocket(ws_url);
  830. this.ws.onopen = this.on_session_create;
  831. this.ws.onclose = this.on_session_close;
  832. this.ws.onmessage = function (evt) {
  833. var msg = JSON.parse(evt.data);
  834. if (debug) console.debug('>>>', msg);
  835. this_.on_server_message(msg);
  836. };
  837. };
  838. this.send_message = function (msg) {
  839. if (this.ws === null)
  840. return console.error('WebSocketWebIOSession.ws is null when invoke WebSocketWebIOSession.send_message. ' +
  841. 'Please call WebSocketWebIOSession.start_session first');
  842. this.ws.send(JSON.stringify(msg));
  843. if (this.debug) console.debug('<<<', msg);
  844. };
  845. this.close_session = function () {
  846. this.on_session_close();
  847. try {
  848. this.ws.close()
  849. } catch (e) {
  850. }
  851. };
  852. }
  853. function HttpWebIOSession(api_url, pull_interval_ms = 1000) {
  854. WebIOSession.apply(this);
  855. this.api_url = api_url;
  856. this.interval_pull_id = null;
  857. this.webio_session_id = '';
  858. this.debug = false;
  859. var this_ = this;
  860. this._on_request_success = function (data, textStatus, jqXHR) {
  861. var sid = jqXHR.getResponseHeader('webio-session-id');
  862. if (sid) this_.webio_session_id = sid;
  863. for (var idx in data) {
  864. var msg = data[idx];
  865. if (this_.debug) console.debug('>>>', msg);
  866. this_.on_server_message(msg);
  867. }
  868. };
  869. this.start_session = function (debug = false) {
  870. this.debug = debug;
  871. function pull() {
  872. $.ajax({
  873. type: "GET",
  874. url: this_.api_url,
  875. contentType: "application/json; charset=utf-8",
  876. dataType: "json",
  877. headers: {"webio-session-id": this_.webio_session_id},
  878. success: function (data, textStatus, jqXHR) {
  879. this_._on_request_success(data, textStatus, jqXHR);
  880. this_.on_session_create();
  881. },
  882. error: function () {
  883. console.error('Http pulling failed');
  884. }
  885. })
  886. }
  887. pull();
  888. this.interval_pull_id = setInterval(pull, pull_interval_ms);
  889. };
  890. this.send_message = function (msg) {
  891. if (this_.debug) console.debug('<<<', msg);
  892. $.ajax({
  893. type: "POST",
  894. url: this.api_url,
  895. data: JSON.stringify(msg),
  896. contentType: "application/json; charset=utf-8",
  897. dataType: "json",
  898. headers: {"webio-session-id": this_.webio_session_id},
  899. success: this_._on_request_success,
  900. error: function () { // todo
  901. console.error('Http push event failed, event data: %s', msg);
  902. }
  903. })
  904. };
  905. this.close_session = function () {
  906. this.on_session_close();
  907. clearInterval(this.interval_pull_id);
  908. };
  909. }
  910. var WebIOSession_;
  911. function WebIOController(webio_session, output_container_elem, input_container_elem) {
  912. WebIOSession_ = webio_session;
  913. webio_session.on_session_close = function () {
  914. $('#favicon32').attr('href', 'image/favicon_closed_32.png'); // todo:remove hard code
  915. $('#favicon16').attr('href', 'image/favicon_closed_16.png');
  916. };
  917. this.output_ctrl = new OutputController(webio_session, output_container_elem);
  918. this.input_ctrl = new FormsController(webio_session, input_container_elem);
  919. this.output_cmds = make_set(this.output_ctrl.accept_command);
  920. this.input_cmds = make_set(this.input_ctrl.accept_command);
  921. var this_ = this;
  922. webio_session.on_server_message = function (msg) {
  923. if (msg.command in this_.input_cmds)
  924. this_.input_ctrl.handle_message(msg);
  925. else if (msg.command in this_.output_cmds)
  926. this_.output_ctrl.handle_message(msg);
  927. else if (msg.command === 'close_session')
  928. webio_session.close_session();
  929. else
  930. console.error('Unknown command:%s', msg.command);
  931. };
  932. }
  933. return {
  934. 'HttpWebIOSession': HttpWebIOSession,
  935. 'WebSocketWebIOSession': WebSocketWebIOSession,
  936. 'WebIOController': WebIOController,
  937. 'DisplayAreaButtonOnClick': DisplayAreaButtonOnClick,
  938. }
  939. })));