render.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const _richText_text_styles_ = ['bold', 'underline', 'italic', 'danger', 'sup', 'sub'];
  2. function renderRichText(body) {
  3. let sections = body.sections || [];
  4. let nodes = [];
  5. sections.forEach(section => {
  6. nodes.push(renderSection(section));
  7. });
  8. return nodes;
  9. }
  10. function renderSection(section) {
  11. let blocks = section.blocks || [];
  12. let inline = blocks.length > 1;
  13. let node = document.createElement('p');
  14. blocks.forEach(block => {
  15. node.appendChild(renderBlock(block, inline));
  16. });
  17. return node;
  18. }
  19. function renderBlock(block, inline) {
  20. let container = document.createElement('span');
  21. let type = '';
  22. if (block.type === 'text') {
  23. type = 'text';
  24. if (block.param != undefined) {
  25. _richText_text_styles_.forEach(style => {
  26. if (block.param[style] === true) {
  27. type += ' ' + style;
  28. }
  29. })
  30. }
  31. container.textContent = block.value;
  32. } else if (block.type === 'image') {
  33. type = 'image loading';
  34. if (inline === true) {
  35. type += ' inline';
  36. }
  37. let img = container.appendChild(new Image());
  38. img.src = block.value;
  39. img.onload = function () {
  40. this.parentNode.className = this.parentNode.className.replace(/loading/g, '');
  41. }
  42. } else if (block.type === 'audio') {
  43. type = 'audio';
  44. let audio = container.appendChild(new Audio());
  45. audio.src = block.value;
  46. audio.controls = true;
  47. audio.setAttribute("type", "audio/mpeg");
  48. }
  49. container.className = type;
  50. return container;
  51. }