All files / src/components/EditableTableV2 highlightValue.tsx

92.85% Statements 13/14
87.5% Branches 14/16
100% Functions 4/4
91.66% Lines 11/12

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            19x 2065x 2065x 1996x     69x 69x       69x 12x   57x   90x             54x                                    
import React, { ReactNode } from 'react';
 
import { Box } from '@mui/material';
import { darken, lighten } from '@mui/material/styles';
import highlightWords from 'highlight-words';
 
export const highlightValue = (value: unknown, query: unknown, matchExactly: boolean): ReactNode => {
  const text = String(value ?? '');
  if (!text || !query || !['string', 'number'].includes(typeof value) || !['string', 'number'].includes(typeof query)) {
    return text;
  }
  let chunks: ReturnType<typeof highlightWords>;
  try {
    chunks = highlightWords({ text, query: String(query), matchExactly });
  } catch {
    return text;
  }
  if (!chunks.some((chunk) => chunk.match)) {
    return text;
  }
  return (
    <span aria-label={text} role='note'>
      {chunks.map(({ key, match, text: chunkText }) => (
        <Box
          aria-hidden='true'
          component='span'
          key={key}
          sx={
            match
              ? (theme) => ({
                  backgroundColor:
                    theme.palette.mode === 'dark'
                      ? darken(theme.palette.warning.dark, 0.25)
                      : lighten(theme.palette.warning.light, 0.5),
                  borderRadius: '2px',
                  color: theme.palette.mode === 'dark' ? theme.palette.common.white : theme.palette.common.black,
                  padding: '2px 1px',
                })
              : undefined
          }
        >
          {chunkText}
        </Box>
      ))}
    </span>
  );
};