output.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import {b64toBlob} from "../utils";
  2. import * as marked from 'marked';
  3. /*
  4. * 当前限制
  5. * 若Widget被作为其他Widget的子项时,该Widget中绑定的事件将会失效
  6. * */
  7. export interface Widget {
  8. handle_type: string;
  9. get_element(spec: any): JQuery; // The length of element must equal 1
  10. }
  11. let Text = {
  12. handle_type: 'text',
  13. get_element: function (spec: any): JQuery {
  14. let elem = spec.inline ? $('<span></span>') : $('<p></p>');
  15. spec.content = spec.content.replace(/ /g, '\u00A0');
  16. // make '\n' to <br/>
  17. let lines = (spec.content || '').split('\n');
  18. for (let idx = 0; idx < lines.length - 1; idx++)
  19. elem.append(document.createTextNode(lines[idx])).append('<br/>');
  20. elem.append(document.createTextNode(lines[lines.length - 1]));
  21. return elem;
  22. }
  23. };
  24. marked.setOptions({
  25. breaks: true, //可行尾不加两空格直接换行
  26. smartLists: true,
  27. smartypants: false,
  28. mangle: false,
  29. highlight: function (code, lang, callback) {
  30. if (Prism.languages[lang]) {
  31. try {
  32. code = Prism.highlight(code, Prism.languages[lang]);
  33. } catch (e) {
  34. console.error('Prism highlight error:' + e)
  35. }
  36. }
  37. if (callback)
  38. return callback(null, code);
  39. else
  40. return code;
  41. },
  42. });
  43. let Markdown = {
  44. handle_type: 'markdown',
  45. get_element: function (spec: any) {
  46. // spec.options, see also https://marked.js.org/using_advanced#options
  47. let html_str = marked(spec.content, spec.options);
  48. if (spec.sanitize)
  49. try {
  50. html_str = DOMPurify.sanitize(html_str);
  51. } catch (e) {
  52. console.log('Sanitize html failed: %s\nHTML: \n%s', e, html_str);
  53. }
  54. return $(html_str);
  55. }
  56. };
  57. // 将html字符串解析成jQuery对象
  58. function parseHtml(html_str: string) {
  59. let nodes = $.parseHTML(html_str, null, true);
  60. let elem;
  61. if (nodes.length != 1)
  62. elem = $(document.createElement('div')).append(nodes);
  63. else
  64. elem = $(nodes[0]);
  65. return elem;
  66. }
  67. let Html = {
  68. handle_type: 'html',
  69. get_element: function (spec: any) {
  70. let html_str = spec.content;
  71. if (spec.sanitize)
  72. try {
  73. html_str = DOMPurify.sanitize(html_str);
  74. } catch (e) {
  75. console.log('Sanitize html failed: %s\nHTML: \n%s', e, html_str);
  76. }
  77. return parseHtml(html_str);
  78. }
  79. };
  80. let Buttons = {
  81. handle_type: 'buttons',
  82. get_element: function (spec: any) {
  83. const btns_tpl = `<div>{{#buttons}}
  84. <button class="btn {{#color}}btn-{{color}}{{/color}}{{#small}} btn-sm{{/small}}">{{label}}</button>
  85. {{/buttons}}</div>`;
  86. spec.color = spec.link ? "link" : "primary";
  87. let html = Mustache.render(btns_tpl, spec);
  88. let elem = $(html);
  89. let btns = elem.find('button');
  90. for (let idx = 0; idx < spec.buttons.length; idx++) {
  91. // note: 若Buttons被作为其他Widget的子项时,Buttons中绑定的事件将会失效,所以使用onclick attr设置点击事件
  92. btns.eq(idx).attr('onclick', `WebIO.pushData(${JSON.stringify(spec.buttons[idx].value)}, "${spec.callback_id}")`);
  93. }
  94. return elem;
  95. }
  96. };
  97. // 已废弃。为了向下兼容而保留
  98. let File = {
  99. handle_type: 'file',
  100. get_element: function (spec: any) {
  101. const html = `<div><button type="button" class="btn btn-link">${spec.name}</button></div>`;
  102. let element = $(html);
  103. let blob = b64toBlob(spec.content);
  104. element.on('click', 'button', function (e) {
  105. saveAs(blob, spec.name, {}, false);
  106. });
  107. return element;
  108. }
  109. };
  110. let Table = {
  111. handle_type: 'table',
  112. get_element: function (spec: { data: any[][], span: { [i: string]: { col: number, row: number } } }) {
  113. const table_tpl = `
  114. <table>
  115. <tr>
  116. {{#header}}
  117. <th{{#col}} colspan="{{col}}"{{/col}}{{#row}} rowspan="{{row}}"{{/row}}>{{& data}}</th>
  118. {{/header}}
  119. </tr>
  120. {{#tdata}}
  121. <tr>
  122. {{# . }}
  123. <td{{#col}} colspan="{{col}}"{{/col}}{{#row}} rowspan="{{row}}"{{/row}}>{{& data}}</td>
  124. {{/ . }}
  125. </tr>
  126. {{/tdata}}
  127. </table>`;
  128. interface itemType {
  129. data: string,
  130. col?: number,
  131. row?: number
  132. }
  133. // 将spec转化成模版引擎的输入
  134. let table_data: itemType[][] = [];
  135. for (let row_id in spec.data) {
  136. table_data.push([]);
  137. let row = spec.data[row_id];
  138. for (let col_id in row) {
  139. let data = spec.data[row_id][col_id];
  140. // 处理简单类型单元格,即单元格不是output命令的spec
  141. if (typeof data !== 'object') {
  142. data = {type: 'text', content: data, inline: true};
  143. }
  144. table_data[row_id].push({
  145. data: outputSpecToHtml(data),
  146. ...(spec.span[row_id + ',' + col_id] || {})
  147. });
  148. }
  149. }
  150. let header: itemType[], data: itemType[][];
  151. [header, ...data] = table_data;
  152. let html = Mustache.render(table_tpl, {header: header, tdata: data});
  153. return $(html);
  154. }
  155. };
  156. let CustomWidget = {
  157. handle_type: 'custom_widget',
  158. get_element: function (spec: { template: string, data: { [i: string]: any } }) {
  159. spec.data['pywebio_output_parse'] = function () {
  160. if (this.type)
  161. return outputSpecToHtml(this);
  162. else
  163. return outputSpecToHtml({type: 'text', content: this, inline: true});
  164. };
  165. let html = Mustache.render(spec.template, spec.data);
  166. return parseHtml(html);
  167. }
  168. };
  169. let all_widgets: Widget[] = [Text, Markdown, Html, Buttons, File, Table, CustomWidget];
  170. let type2widget: { [i: string]: Widget } = {};
  171. for (let w of all_widgets)
  172. type2widget[w.handle_type] = w;
  173. export function getWidgetElement(spec: any) {
  174. if (!(spec.type in type2widget))
  175. throw Error("Unknown type in getWidgetElement() :" + spec.type);
  176. let elem = type2widget[spec.type].get_element(spec);
  177. if (spec.style) {
  178. // add style attribute
  179. let old_style = elem.attr('style') || '';
  180. elem.attr({"style": old_style + spec.style});
  181. }
  182. if(spec.container_dom_id){
  183. let dom_id = 'pywebio-scope-'+spec.container_dom_id;
  184. if(spec.container_selector)
  185. elem.find(spec.container_selector).attr('id', dom_id);
  186. else
  187. elem.attr('id', dom_id);
  188. }
  189. return elem;
  190. }
  191. // 将output指令的spec字段解析成html字符串
  192. export function outputSpecToHtml(spec: any) {
  193. let html = '';
  194. try {
  195. let nodes = getWidgetElement(spec);
  196. for (let node of nodes)
  197. html += node.outerHTML || '';
  198. } catch (e) {
  199. console.error('Get sub widget html error,', e, spec);
  200. }
  201. return html;
  202. }