pywebio.js 43 KB

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