pywebio.js 41 KB

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