All files / src/components TabLink.tsx

93.93% Statements 31/33
85.71% Branches 6/7
60% Functions 3/5
93.93% Lines 31/33

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 721x 1x 1x                                             1x 1x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x   3x     3x   1x                     1x 1x 44x   44x 44x 44x 44x 44x 44x 44x 44x   44x     44x  
import { addHistory } from '@/helpers/history';
import { useStatusBar } from '@/components/StatusBar';
import Link from '@mui/material/Link';
import { MouseEvent, ReactNode } from 'react';
 
/**
 * Props for {@link TabLink}. A plain anchor plus optional search-history
 * recording; extra props are spread onto the underlying MUI `Link`.
 * @example
 * ```tsx
 * const props: TabLinkProps = { href: "https://example.com/p/1", children: "View" };
 * ```
 * @source
 */
interface TabLinkProps {
  /** Destination URL; opened in a background tab (or a new window outside the extension). */
  href: string;
  /** Link content. */
  children: ReactNode;
  /** Optional history entry recorded when the link is clicked. */
  history?: HistoryEntry;
  /** Additional props forwarded to the underlying MUI `Link`. */
  [key: string]: unknown;
}
 
// When the user clicks on a link in the table
const handleResultClick = (event: MouseEvent<HTMLAnchorElement>, history?: HistoryEntry) => {
  // Stop the form from propagating
  event.preventDefault();
  // Use currentTarget (the element the handler is bound to) rather than
  // target, which could be a child element inside the anchor.
  const anchor = event.currentTarget;
  if (typeof chrome?.tabs !== 'undefined') {
    chrome.tabs.create({ url: anchor.href, active: false });
  } else {
    window.open(anchor.href, '_blank');
  }
 
  if (history) {
    addHistory(history);
  }
};
 
/**
 * TabLink component that displays a link with a custom onClick handler.
 * @category Components
 * @param props - The component props
 * @returns The TabLink component
 * @example
 * ```tsx
 * <TabLink href="https://example.com/p/1" history={entry}>Acetone</TabLink>
 * // Clicking opens the URL in a background tab and records `entry` in history.
 * ```
 * @source
 */
export default function TabLink({ href, history, children, ...props }: TabLinkProps) {
  const { setStatusText } = useStatusBar();
 
  return (
    <Link
      href={href}
      onClick={(e) => handleResultClick(e, history)}
      onMouseEnter={() => setStatusText(href)}
      onMouseLeave={() => setStatusText(null)}
      sx={{ textDecoration: 'none', '&:hover': { textDecoration: 'underline' } }}
      {...props}
    >
      {children}
    </Link>
  );
}