hyperlink-reader.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. "use strict";
  2. const {
  3. EventEmitter
  4. } = require('events');
  5. const parseSax = require('../../utils/parse-sax');
  6. const Enums = require('../../doc/enums');
  7. const RelType = require('../../xlsx/rel-type');
  8. class HyperlinkReader extends EventEmitter {
  9. constructor(_ref) {
  10. let {
  11. workbook,
  12. id,
  13. iterator,
  14. options
  15. } = _ref;
  16. super();
  17. this.workbook = workbook;
  18. this.id = id;
  19. this.iterator = iterator;
  20. this.options = options;
  21. }
  22. get count() {
  23. return this.hyperlinks && this.hyperlinks.length || 0;
  24. }
  25. each(fn) {
  26. return this.hyperlinks.forEach(fn);
  27. }
  28. async read() {
  29. const {
  30. iterator,
  31. options
  32. } = this;
  33. let emitHyperlinks = false;
  34. let hyperlinks = null;
  35. switch (options.hyperlinks) {
  36. case 'emit':
  37. emitHyperlinks = true;
  38. break;
  39. case 'cache':
  40. this.hyperlinks = hyperlinks = {};
  41. break;
  42. default:
  43. break;
  44. }
  45. if (!emitHyperlinks && !hyperlinks) {
  46. this.emit('finished');
  47. return;
  48. }
  49. try {
  50. for await (const events of parseSax(iterator)) {
  51. for (const {
  52. eventType,
  53. value
  54. } of events) {
  55. if (eventType === 'opentag') {
  56. const node = value;
  57. if (node.name === 'Relationship') {
  58. const rId = node.attributes.Id;
  59. switch (node.attributes.Type) {
  60. case RelType.Hyperlink:
  61. {
  62. const relationship = {
  63. type: Enums.RelationshipType.Styles,
  64. rId,
  65. target: node.attributes.Target,
  66. targetMode: node.attributes.TargetMode
  67. };
  68. if (emitHyperlinks) {
  69. this.emit('hyperlink', relationship);
  70. } else {
  71. hyperlinks[relationship.rId] = relationship;
  72. }
  73. }
  74. break;
  75. default:
  76. break;
  77. }
  78. }
  79. }
  80. }
  81. }
  82. this.emit('finished');
  83. } catch (error) {
  84. this.emit('error', error);
  85. }
  86. }
  87. }
  88. module.exports = HyperlinkReader;
  89. //# sourceMappingURL=hyperlink-reader.js.map