1
0

pywebio.js 38 KB

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