pywebio.js 43 KB

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