File size: 2,457 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { Fragment } from 'react';

import { cx } from './lib/cx';

type HighlightPartProps = {
  children: React.ReactNode;
  classNames: InternalHighlightClassNames;
  highlightedTagName: React.ElementType;
  nonHighlightedTagName: React.ElementType;
  isHighlighted: boolean;
};

function HighlightPart({
  classNames,
  children,
  highlightedTagName,
  isHighlighted,
  nonHighlightedTagName,
}: HighlightPartProps) {
  const TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName;

  return (
    <TagName
      className={
        isHighlighted ? classNames.highlighted : classNames.nonHighlighted
      }
    >
      {children}
    </TagName>
  );
}

type HighlightedPart = {
  isHighlighted: boolean;
  value: string;
};

export type InternalHighlightClassNames = {
  /**
   * Class names to apply to the root element
   */
  root: string;
  /**
   * Class names to apply to the highlighted parts
   */
  highlighted: string;
  /**
   * Class names to apply to the non-highlighted parts
   */
  nonHighlighted: string;
  /**
   * Class names to apply to the separator between highlighted parts
   */
  separator: string;
};

export type InternalHighlightProps = React.HTMLAttributes<HTMLSpanElement> & {
  classNames: InternalHighlightClassNames;
  highlightedTagName?: React.ElementType;
  nonHighlightedTagName?: React.ElementType;
  separator?: React.ReactNode;
  parts: HighlightedPart[][];
};

export function InternalHighlight({
  parts,
  highlightedTagName = 'mark',
  nonHighlightedTagName = 'span',
  separator = ', ',
  className,
  classNames,
  ...props
}: InternalHighlightProps) {
  return (
    <span {...props} className={cx(classNames.root, className)}>
      {parts.map((part, partIndex) => {
        const isLastPart = partIndex === parts.length - 1;

        return (
          <Fragment key={partIndex}>
            {part.map((subPart, subPartIndex) => (
              <HighlightPart
                key={subPartIndex}
                classNames={classNames}
                highlightedTagName={highlightedTagName}
                nonHighlightedTagName={nonHighlightedTagName}
                isHighlighted={subPart.isHighlighted}
              >
                {subPart.value}
              </HighlightPart>
            ))}

            {!isLastPart && (
              <span className={classNames.separator}>{separator}</span>
            )}
          </Fragment>
        );
      })}
    </span>
  );
}