Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

8.9 KB
Raw Blame
import { Button as MantineButton } from "@mantine/core";
import { forwardRef } from "react";
import { useTranslation } from "react-i18next";
import type {
  ComponentPropsWithoutRef,
  CSSProperties,
  ElementType,
  ReactNode,
} from "react";
import {
  CONTROL_HEIGHT,
  CONTROL_PADDING,
  type ControlFontSize,
  type ControlPadding,
  resolveFontSize,
} from "@editor/ui/controlSizes";
import "@editor/ui/Button.css";

/** primary=solid, secondary=outlined, tertiary=ghost (tinted hover), quiet=plain (no bg, hovers to text colour). */
export type ButtonVariant = "primary" | "secondary" | "tertiary" | "quiet";
/** default(blue) | neutral | brand | ai | premium | danger | success | warning. */
export type ButtonAccent =
  | "default"
  | "neutral"
  | "brand"
  | "ai"
  | "premium"
  | "danger"
  | "success"
  | "warning";
export type ButtonSize = "sm" | "md" | "lg" | "xl";
/**
 * Relative label-size scale, applied on top of the `size`-derived base. `md`
 * leaves the base unchanged; other values scale it up/down. Unset inherits
 * Mantine's size default, so existing buttons are unchanged.
 */
export type ButtonFontSize = ControlFontSize;
/** `between` pins leftSection/label/rightSection to left/center/right (toolbar rows). */
export type ButtonJustify = "center" | "start" | "end" | "between";
export type ButtonShape = "default" | "circle" | "pill";

type ButtonOwnProps = {
  variant?: ButtonVariant;
  accent?: ButtonAccent;
  size?: ButtonSize;
  fat?: boolean;
  /** Label size relative to `size`. Defaults to the `size`-derived value. */
  fontSize?: ButtonFontSize;
  /** Padding override for both axes */
  p?: ControlPadding;
  /** Horizontal-padding override  */
  px?: ControlPadding;
  /** Vertical-padding override  */
  py?: ControlPadding;
  justify?: ButtonJustify;
  shape?: ButtonShape;
  /** Alternative to children; use one or the other. */
  text?: ReactNode;
  leftSection?: ReactNode;
  rightSection?: ReactNode;
  loading?: boolean;
  fullWidth?: boolean;
  /** false = no hover background change. */
  hover?: boolean;
  overflow?: "wrap" | "hidden";
  /** Polymorphic root element (e.g. `"a"` or a router Link). */
  as?: ElementType;
  style?: CSSProperties;
  children?: ReactNode;
};

export type ButtonProps = ButtonOwnProps &
  Omit<ComponentPropsWithoutRef<"button">, keyof ButtonOwnProps | "color"> & {
    href?: string;
    target?: string;
    rel?: string;
    htmlFor?: string;
  };

export interface ButtonGroupProps {
  children?: ReactNode;
  className?: string;
  style?: CSSProperties;
  orientation?: "horizontal" | "vertical";
  /** Border width between attached buttons (Mantine `--button-border-width`). */
  borderWidth?: number | string;
}

function ButtonGroup({
  children,
  className,
  style,
  orientation,
  borderWidth,
}: ButtonGroupProps) {
  return (
    <MantineButton.Group
      className={className}
      style={style}
      orientation={orientation}
      borderWidth={borderWidth}
    >
      {children}
    </MantineButton.Group>
  );
}

const FAT_HEIGHT = "2.75rem";
const FAT_PADDING_X = "lg" satisfies ControlPadding;

const MANTINE_VARIANT: Record<ButtonVariant, string> = {
  primary: "filled",
  secondary: "outline",
  tertiary: "subtle",
  quiet: "subtle",
};

const MANTINE_JUSTIFY: Record<ButtonJustify, string> = {
  center: "center",
  start: "flex-start",
  end: "flex-end",
  between: "space-between",
};

const ButtonRoot = forwardRef<HTMLButtonElement, ButtonProps>(
  function ButtonRoot(
    {
      variant = "primary",
      accent = "default",
      size = "sm",
      fat = false,
      fontSize,
      p,
      px,
      py,
      justify = "center",
      shape = "default",
      text,
      leftSection,
      rightSection,
      loading = false,
      fullWidth = false,
      hover = true,
      overflow = "wrap",
      as,
      disabled,
      className,
      style,
      children,
      ...rest
    },
    ref,
  ) {
    const { t } = useTranslation();
    const label = text ?? children;
    const hasLabel = label != null && label !== false && label !== "";
    // A labelless button collapses to a square icon-only button — but never when
    // `fullWidth` is set (it must span its container, e.g. a loading execute
    // button whose label is momentarily absent while files hydrate).
    const iconOnly =
      !hasLabel && !fullWidth && (!!leftSection || !!rightSection || loading);

    // A button whose label is momentarily absent while loading still needs an
    // accessible name; the spinner and any icon are decorative.
    const fallbackLabel =
      !hasLabel && loading && !rest["aria-label"] && !rest["aria-labelledby"]
        ? t("common.loading", "Loading...")
        : undefined;

    // px/py override p for their axis; each stays undefined (= size default) if unset.
    const padX = px ?? p ?? (fat ? FAT_PADDING_X : undefined);
    const padY = py ?? p;

    // Sections flank a label → spread them without requiring justify="between".
    const effectiveJustify =
      justify === "center" && hasLabel && !!leftSection && !!rightSection
        ? "between"
        : justify;

    const classes = [
      "sui-btn",
      `sui-acc-${accent}`,
      `sui-btn--${variant}`,
      iconOnly ? "sui-btn--icon" : "",
      fat ? "sui-btn--fat" : "",
      shape !== "default" ? `sui-btn--${shape}` : "",
      overflow === "wrap" ? "sui-btn--wrap" : "",
      !hover ? "sui-btn--no-hover" : "",
      className ?? "",
    ]
      .filter(Boolean)
      .join(" ");

    // Accent palette → Mantine button vars (inline to win). --button-bd is a full `border` shorthand.
    const accentVars =
      variant === "primary"
        ? {
            "--button-bg": "var(--_solid)",
            "--button-hover": "var(--_solid-hover)",
            "--button-color": "var(--_on)",
            "--button-bd": "1px solid transparent",
          }
        : variant === "quiet"
          ? {
              "--button-bg": "transparent",
              "--button-hover": "transparent",
              "--button-color": "var(--_text)",
              "--button-hover-color": "var(--c-text)",
              "--button-bd": "1px solid transparent",
            }
          : variant === "secondary"
            ? {
                // Filled when the accent defines --_solid-2 (default = inverse
                // ink/snow); otherwise falls back to the outlined look.
                "--button-bg": "var(--_solid-2, transparent)",
                "--button-hover": "var(--_solid-2-hover, var(--_tint))",
                "--button-color": "var(--_on-2, var(--_text))",
                "--button-bd": "1px solid var(--_bd-2, var(--_bd))",
              }
            : {
                // tertiary (ghost) — neutral text + hover when the accent
                // defines --_tert-* (default); otherwise the accent link colour.
                "--button-bg": "transparent",
                "--button-hover": "var(--_tert-tint, var(--_tint))",
                "--button-color": "var(--_tert-text, var(--_text))",
                "--button-bd": "1px solid transparent",
              };

    // Loosely-typed alias so the polymorphic `component={as}` doesn't fight Mantine's typing.
    const Comp = MantineButton as ElementType;

    return (
      <Comp
        {...rest}
        aria-label={rest["aria-label"] ?? fallbackLabel}
        ref={ref}
        component={as}
        variant={MANTINE_VARIANT[variant]}
        size={size}
        justify={MANTINE_JUSTIFY[effectiveJustify]}
        leftSection={leftSection}
        rightSection={rightSection}
        loading={loading}
        fullWidth={fullWidth}
        disabled={disabled}
        className={classes}
        style={{
          ...(accentVars as CSSProperties),
          ...({
            "--button-height": fat ? FAT_HEIGHT : CONTROL_HEIGHT[size],
          } as CSSProperties),
          // Relative label size, scaled off the `size` base (unset → Mantine default).
          ...(fontSize
            ? ({
                "--button-fz": resolveFontSize(size, fontSize),
              } as CSSProperties)
            : {}),
          // Padding overrides (inline to beat Mantine's size-based value).
          // px → Mantine's own var; py → our --sui-btn-py (Mantine has no vertical padding).
          ...(padX
            ? ({ "--button-padding-x": CONTROL_PADDING[padX] } as CSSProperties)
            : {}),
          ...(padY
            ? ({ "--sui-btn-py": CONTROL_PADDING[padY] } as CSSProperties)
            : {}),
          // mantineTheme writes font-weight inline on every button root, so this must be inline too.
          ...(fat
            ? ({ fontWeight: "var(--font-weight-semibold)" } as CSSProperties)
            : {}),
          // Icon-only: zero the size padding inline so the lone icon centres.
          ...(iconOnly ? ({ "--button-padding-x": "0" } as CSSProperties) : {}),
          ...style,
        }}
      >
        {label}
      </Comp>
    );
  },
);

export const Button = Object.assign(ButtonRoot, { Group: ButtonGroup });