shared-string-xform.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. const TextXform = require('./text-xform');
  2. const RichTextXform = require('./rich-text-xform');
  3. const PhoneticTextXform = require('./phonetic-text-xform');
  4. const BaseXform = require('../base-xform');
  5. // <si>
  6. // <r></r><r></r>...
  7. // </si>
  8. // <si>
  9. // <t></t>
  10. // </si>
  11. class SharedStringXform extends BaseXform {
  12. constructor(model) {
  13. super();
  14. this.model = model;
  15. this.map = {
  16. r: new RichTextXform(),
  17. t: new TextXform(),
  18. rPh: new PhoneticTextXform(),
  19. };
  20. }
  21. get tag() {
  22. return 'si';
  23. }
  24. render(xmlStream, model) {
  25. xmlStream.openNode(this.tag);
  26. if (model && model.hasOwnProperty('richText') && model.richText) {
  27. if (model.richText.length) {
  28. model.richText.forEach(text => {
  29. this.map.r.render(xmlStream, text);
  30. });
  31. } else {
  32. this.map.t.render(xmlStream, '');
  33. }
  34. } else if (model !== undefined && model !== null) {
  35. this.map.t.render(xmlStream, model);
  36. }
  37. xmlStream.closeNode();
  38. }
  39. parseOpen(node) {
  40. const {name} = node;
  41. if (this.parser) {
  42. this.parser.parseOpen(node);
  43. return true;
  44. }
  45. if (name === this.tag) {
  46. this.model = {};
  47. return true;
  48. }
  49. this.parser = this.map[name];
  50. if (this.parser) {
  51. this.parser.parseOpen(node);
  52. return true;
  53. }
  54. return false;
  55. }
  56. parseText(text) {
  57. if (this.parser) {
  58. this.parser.parseText(text);
  59. }
  60. }
  61. parseClose(name) {
  62. if (this.parser) {
  63. if (!this.parser.parseClose(name)) {
  64. switch (name) {
  65. case 'r': {
  66. let rt = this.model.richText;
  67. if (!rt) {
  68. rt = this.model.richText = [];
  69. }
  70. rt.push(this.parser.model);
  71. break;
  72. }
  73. case 't':
  74. this.model = this.parser.model;
  75. break;
  76. default:
  77. break;
  78. }
  79. this.parser = undefined;
  80. }
  81. return true;
  82. }
  83. switch (name) {
  84. case this.tag:
  85. return false;
  86. default:
  87. return true;
  88. }
  89. }
  90. }
  91. module.exports = SharedStringXform;