spanContext.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {Component, createContext} from 'react';
  2. import {ProcessedSpanType} from './types';
  3. export type SpanContextProps = {
  4. addExpandedSpan: (span: Readonly<ProcessedSpanType>, callback?: () => void) => void;
  5. didAnchoredSpanMount: () => boolean;
  6. isSpanExpanded: (span: Readonly<ProcessedSpanType>) => boolean;
  7. markAnchoredSpanIsMounted: () => void;
  8. removeExpandedSpan: (span: Readonly<ProcessedSpanType>, callback?: () => void) => void;
  9. };
  10. const SpanContext = createContext<SpanContextProps>({
  11. didAnchoredSpanMount: () => false,
  12. markAnchoredSpanIsMounted: () => undefined,
  13. addExpandedSpan: () => undefined,
  14. removeExpandedSpan: () => undefined,
  15. isSpanExpanded: () => false,
  16. });
  17. type Props = {
  18. children: React.ReactNode;
  19. };
  20. export class Provider extends Component<Props> {
  21. isAnchoredSpanMounted = false;
  22. // This set keeps track of all spans which are currently expanded to show their details.
  23. // Since the span tree is virtualized, we need this so the tree can remember which spans have been expanded after they unmount
  24. expandedSpansMap: Set<Readonly<ProcessedSpanType>> = new Set();
  25. markAnchoredSpanIsMounted = () => (this.isAnchoredSpanMounted = true);
  26. didAnchoredSpanMount = () => this.isAnchoredSpanMounted;
  27. addExpandedSpan = (span: Readonly<ProcessedSpanType>, callback?: () => void) => {
  28. this.expandedSpansMap.add(span);
  29. callback?.();
  30. };
  31. removeExpandedSpan = (span: Readonly<ProcessedSpanType>, callback?: () => void) => {
  32. this.expandedSpansMap.delete(span);
  33. callback?.();
  34. };
  35. isSpanExpanded = (span: Readonly<ProcessedSpanType>) => {
  36. return this.expandedSpansMap.has(span);
  37. };
  38. render() {
  39. const childrenProps: SpanContextProps = {
  40. didAnchoredSpanMount: this.didAnchoredSpanMount,
  41. markAnchoredSpanIsMounted: this.markAnchoredSpanIsMounted,
  42. addExpandedSpan: this.addExpandedSpan,
  43. removeExpandedSpan: this.removeExpandedSpan,
  44. isSpanExpanded: this.isSpanExpanded,
  45. };
  46. return (
  47. <SpanContext.Provider value={childrenProps}>
  48. {this.props.children}
  49. </SpanContext.Provider>
  50. );
  51. }
  52. }
  53. export const Consumer = SpanContext.Consumer;