# All files / src/components sequence.tsx

57.4% Statements 31/54
74.28% Branches 26/35
73.33% Functions 11/15
55.76% Lines 29/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285

    16x

    8x

    8x

    4x

    4x

    4x

    4x
    4x

    4x

    340x

    8x
    3x

    8x

    8x
    8x
    8x

    8x
    2x

    2x
    1x

    8x

    5x

    8x

    8x
    4x

    4x

    1x

    6x
    6x

     import {
      useState,
      type ReactNode,
      useMemo,
      useCallback,
      memo,
      useEffect,
      useRef,
      type CSSProperties,
    } from 'react';
    import cn from 'classnames';

    import Button from './button';
    import { Dropdown } from './dropdown-button';
    import CopyToClipboard from './copy-to-clipboard';
    import InfoList, { type InfoListItem } from './info-list';
    import SequenceTools, { type SequenceToolName } from './sequence-tools';

    import DownloadIcon from '../svg/download.svg';
    import SpinnerIcon from '../svg/spinner.svg';

    import aminoAcidsProps from './data/amino-acid-properties.json' with { type: 'json' };

    import '../styles/components/sequence.scss';

    type AminoAcidProperty = {
      name: string;
      aminoAcids: Set<string>;
      colour: string;
    };

    const aaProps: AminoAcidProperty[] = aminoAcidsProps.map((aaProp) => ({
      ...aaProp,
      // Optimise for later lookup
      aminoAcids: new Set(aaProp.aminoAcids),
    }));

    const chunksOfTen = /(.{1,10})/g;

    const SequenceChunks = memo(
      ({
        sequence,
        computeHighlights,
      }: {
        sequence: string;
        computeHighlights: boolean;
      }) => {
        const ref = useRef<HTMLDivElement>(null);

        const chunks = useMemo(() => sequence.match(chunksOfTen) || [], [sequence]);

        useEffect(() => {
          // Don't run until needed the first time
          Eif (!computeHighlights) {
            return;
          }
          // OK, we requested a highlight, compute them all at once
          for (const [index, chunk] of chunks.entries()) {
            const boxShadow: string[] = [];

            let xOffset = 0;
            // start at negative values to get closer to the letters
            let yOffset = -3;
            for (const { name, aminoAcids } of aaProps) {
              for (const letter of chunk) {
                if (aminoAcids.has(letter)) {
                  boxShadow.push(
                    `${xOffset}ch ${yOffset}px 0 1px var(--color-${name}, transparent)`
                  );
                }
                xOffset += 10;
              }
              yOffset += 2;
              xOffset = 0;
            }
            const node = ref.current?.children[index] as HTMLElement | undefined;
            if (node) {
              // Avoid React by setting directly on the nodes
              node?.style.setProperty('--box-shadow', boxShadow.join(', '));
            }
          }
        }, [chunks, computeHighlights]);

        return (
          <div className="sequence" ref={ref}>
            {chunks.map((chunk, index) => (
              <span
                // eslint-disable-next-line react/no-array-index-key
                key={index}
                className={cn('sequence__chunk', {
                  'sequence__chunk--display-last':
                    index + 1 === chunks.length && chunk.length === 10,
                })}
              >
                {chunk}
              </span>
            ))}
          </div>
        );
      }
    );

    const visibleElement = (onClick: () => unknown) => (
      <Button variant="tertiary" onClick={onClick}>
        Highlight
      </Button>
    );

    type SequenceProps = {
      /**
       * The sequence
       */
      sequence?: string;
      /**
       * The accession corresponding to the sequence
       */
      accession?: string;
      /**
       * Action triggered when the "Show sequence" button is clicked.
       * This button will be displayed by default if no sequence is passed
       * down to the component.
       */
      onShowSequence?: () => void;
      /**
       * Display option to show/hide the sequence. If no sequence is
       * provided and `onShowSequence` is defined, this defaults to "true"
       */
      isCollapsible?: boolean;
      /**
       * If the sequence is loading, display a spinner in the button
       */
      isLoading?: boolean;
      /**
       * Data to be displayed in an InfoData component above the sequence
       */
      infoData?: InfoListItem[];
      /**
       * The URL to download the isoform sequence
       */
      downloadUrl?: string;
      /**
       * Callback which is fired when the BLAST button is clicked. If no callback
       * is provided then no BLAST button will be displayed.
       */
      onBlastClick?: () => void;
      /** Callback which is fired when the Add button is clicked. If no callback
       * is provided then no Add button will be displayed.
       */
      addToBasketButton?: ReactNode;
      showActionBar?: boolean;
      onCopy?: (copied: string) => void;
      sequenceTools?: SequenceToolName[];
    };

    const Sequence = ({
      sequence,
      accession,
      onShowSequence,
      onCopy,
      isCollapsible = false,
      isLoading = false,
      infoData,
      onBlastClick,
      addToBasketButton,
      downloadUrl,
      showActionBar = true,
      sequenceTools,
    }: SequenceProps) => {
      const [highlights, setHighlights] = useState<AminoAcidProperty[]>([]);
      const [computeHighlights, setComputeHighlights] = useState(false);
      const [isCollapsed, setIsCollapsed] = useState(
        isCollapsible || (onShowSequence && !sequence)
      );

      const handleShowSequenceClick = useCallback(() => {
        setIsCollapsed(false);
        // Request call of sequence
        if (!sequence && onShowSequence) {
          onShowSequence();
        }
      }, [onShowSequence, sequence]);

      const sequenceStyle = useMemo(
        () =>
          Object.fromEntries(
            highlights.map((highlight) => [
              `--color-${highlight.name}`,
              highlight.colour,
            ])
          ),
        [highlights]
      );

      const handleToggleHighlight = useCallback((aaProp: AminoAcidProperty) => {
        setComputeHighlights(true);
        setHighlights((highlights) => {
          const highlightsSet = new Set(highlights);
          if (highlightsSet.has(aaProp)) {
            highlightsSet.delete(aaProp);
          } else {
            highlightsSet.add(aaProp);
          }
          return Array.from(highlightsSet);
        });
      }, []);

      if (isCollapsed || !sequence) {
        return (
          <div>
            <Button variant="secondary" onClick={handleShowSequenceClick}>
              Show sequence {isLoading && <SpinnerIcon />}
            </Button>
          </div>
        );
      }

      return (
        <div>
          {isCollapsible && (
            <Button variant="secondary" onClick={() => setIsCollapsed(true)}>
              Hide sequence
            </Button>
          )}
          <section className="sequence-container" style={sequenceStyle}>
            {showActionBar && accession && (
              <div className="action-bar button-group">
                {/* Not sure why keys are needed, but otherwise gets the React key
                warnings messages and children are rendered as array... */}
                <SequenceTools
                  accession={accession}
                  onBlastClick={onBlastClick}
                  tools={sequenceTools}
                  key="tools"
                />
                {downloadUrl && (
                  <a
                    className="button tertiary"
                    href={downloadUrl}
                    download
                    key="link"
                  >
                    <DownloadIcon />
                    Download
                  </a>
                )}
                {addToBasketButton}
                <Dropdown visibleElement={visibleElement} key="highlight">
                  {aaProps.map((aaProp) => {
                    const inputId = `${accession}-${aaProp.name}`;
                    return (
                      <label key={aaProp.name} htmlFor={inputId}>
                        <input
                          type="checkbox"
                          id={inputId}
                          onChange={() => handleToggleHighlight(aaProp)}
                          checked={highlights.includes(aaProp)}
                          style={{ accentColor: aaProp.colour } as CSSProperties}
                        />
                        {aaProp.name}
                      </label>
                    );
                  })}
                </Dropdown>
                <CopyToClipboard
                  textToCopy={sequence}
                  beforeCopy="Copy sequence"
                  afterCopy="Copied"
                  className="tertiary"
                  onCopy={onCopy}
                  key="copy"
                />
              </div>
            )}
            <InfoList infoData={infoData} isCompact columns />
            <SequenceChunks
              sequence={sequence}
              computeHighlights={computeHighlights}
            />
          </section>
        </div>
      );
    };

    export default Sequence;