Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

1.8 KB
Raw Blame
import type { AnchorHTMLAttributes, MouseEvent, ReactNode } from "react";

import {
  getPageBasename,
  navigate,
} from "embedding-sdk-package/lib/private/data-app-routing";

export interface DataAppLinkProps extends Omit<
  AnchorHTMLAttributes<HTMLAnchorElement>,
  "href"
> {
  to: string;
  children?: ReactNode;
}

/**
 * Internal-only navigation link inside a data app.
 *
 * Renders a plain anchor rather than a router `<Link>`: a data app is mounted
 * outside the app's route tree, so it has no router context to read.
 *
 * The `href` is the app's page in Metabase, so opening the link in a new tab or
 * copying its address lands on the app rather than on its iframe, which refuses
 * to load as a top-level page. A plain click navigates inside the app.
 */
export const DataAppLink = ({
  to,
  children,
  onClick,
  target,
  rel,
  ...rest
}: DataAppLinkProps) => {
  const href = getPageBasename() + to;

  const isExternalTarget = target != null && target !== "_self";
  const resolvedRel = rel ?? (isExternalTarget ? "noopener noreferrer" : rel);

  const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
    onClick?.(event);

    if (event.defaultPrevented) {
      return;
    }

    if (isExternalTarget) {
      // Explicit `target="_blank"` etc. — let the browser handle it.
      return;
    }

    if (
      event.button !== 0 ||
      event.metaKey ||
      event.ctrlKey ||
      event.shiftKey ||
      event.altKey
    ) {
      // Modifier keys / middle / right click — the browser handles it (new tab,
      // download, etc.). Don't preventDefault; the native action is wanted.
      return;
    }

    event.preventDefault();
    navigate(to);
  };

  return (
    <a
      href={href}
      target={target}
      rel={resolvedRel}
      onClick={handleClick}
      {...rest}
    >
      {children}
    </a>
  );
};