1
0

pywebio.js 43 KB

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