pywebio.js 43 KB

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