pywebio.js 40 KB

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