hyperlink-reader.js 2.1 KB

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