phonetic-text-xform.js 2.0 KB

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