pywebio.js 40 KB

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