# Mailpick

Turns every mailto link into a small menu: Gmail, Outlook, Outlook for work or school, Yahoo Mail, the default mail app, or copy the address. Wrap the app once and existing links just work, with to, cc, subject and body filled in. On phones it slides up as a bottom sheet. Built on ui-sdk Menu, so focus, arrow keys and ARIA are done.

React component from Creative UI. Docs: https://ui.krutikraut.com/docs/mailpick

## Installation

```bash
npx shadcn@latest add @creative-ui/mailpick
```

On an older shadcn CLI, use the URL: `npx shadcn@latest add https://ui.krutikraut.com/r/mailpick.json`

Add `@layer ui-sdk;` at the top of your global stylesheet, above `@import "tailwindcss"`. Then wrap your app in <MailpickProvider>.

## Dependencies

- `@ui-sdk/react@0.1.0-beta.20` (npm)
- `@ui-sdk/core@0.1.0-beta.20` (npm)
- `lucide-react` (npm)
- `utils` (shadcn)

## Usage

```tsx
// app/layout.tsx
import { MailpickProvider } from "@/components/mailpick"

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <MailpickProvider>{children}</MailpickProvider>
      </body>
    </html>
  )
}

// That's all most sites need: every mailto link now opens the menu.
// To build a link from its parts, inside a shadcn Button:
import { MailpickLink, useMailpick } from "@/components/mailpick"

<Button asChild>
  <MailpickLink to="hello@studio.com" subject="New project">Email us</MailpickLink>
</Button>

// Open it from code:
const { open } = useMailpick()
<Button onClick={(e) => open("mailto:sales@acme.com", e.currentTarget)}>Talk to sales</Button>

// Fewer options, a webmail of your own, and analytics:
<MailpickProvider
  providers={[
    "gmail",
    "outlook",
    { id: "acme", label: "Acme Mail", icon: AcmeLogo, href: (mail) => `https://mail.acme.com/compose?to=${encodeURIComponent(mail.to.join(","))}` },
    "copy",
  ]}
  onSelect={({ provider }) => track("email_click", { provider })}
>

// Leave one link alone:
<a href="mailto:jobs@studio.com" data-mailpick="off">jobs@studio.com</a>
```

## Props

### MailpickProvider

Wrap the app once. It listens for clicks on mailto links and opens one shared menu.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `providers` | `(ProviderId \| Provider)[]` | `["gmail", "outlook", "office", "yahoo", "app", "copy"]` | Which choices show, in order. `office` is Outlook for work and school accounts, `app` the default mail app. Custom options are `{ id, label, hint?, icon?, mark?, href: (mail) => string }`: `icon` is a component for the tile, and without one the tile shows `mark` or the label's first letter. |
| `title` | `string` | `"Send with"` | The small label above the address. |
| `intercept` | `boolean` | `true` | Catch plain mailto links. With `false`, only `MailpickLink` and `open()` show the menu. |
| `mobile` | `"native" \| "menu"` | `"menu"` | On phones, show the choices as a bottom sheet (ui-sdk's sheet presentation), or let the phone's own mail app open as usual. |
| `rememberLast` | `boolean` | `true` | Focus the visitor's last pick when the menu opens and tag it "Last used". Stored in localStorage only. |
| `onSelect` | `(e: { provider, mail, href }) => void` | - | Fires when someone picks an option, with its id, the parsed message and the original link. For analytics. |
| `side` | `"top" \| "bottom"` | `"bottom"` | Which side of the link the menu opens on. It flips when there's no room. |
| `align` | `"start" \| "center" \| "end"` | `"start"` | How the menu lines up with the link. |
| `className` | `string` | - | Classes for the menu, for one-off tweaks. |

### MailpickLink

A real mailto link built from its parts, so it works with JavaScript off. It opens the menu even with `intercept={false}`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `to` | `string \| string[]` | - | The addresses. |
| `cc` | `string \| string[]` | - | Copied addresses. |
| `bcc` | `string \| string[]` | - | Blind-copied addresses. |
| `subject` | `string` | - | The subject line. |
| `body` | `string` | - | The message. Line breaks are kept. |
| `href` | `string` | - | A ready mailto link. Wins over the parts. |

Also accepts all native `<a>` props.

## Also exported

- `useMailpick(): { open(mailto, anchor?), close(), parseMailto(href) }`: Opens the menu from code. `mailto` is a link or `{ to, cc, bcc, subject, body }`. Without `anchor` the menu opens near the top of the window. Outside a provider, `open()` follows the plain link.
- `parseMailto(href): { to, cc, bcc, subject, body }`: In `lib/parse-mailto.ts`, with no React, so it also runs on the server. `buildMailto(parts)` goes the other way.
- `mailpickProviders, type Provider`: In `lib/mailpick-providers.ts`: the built-in options and their compose URLs, to reuse or extend.

## Notes

- Only a plain left click opens the menu. Ctrl/⌘, Shift or Alt clicks, right clicks, links inside `data-mailpick="off"`, and clicks something else already handled with `preventDefault()` all behave as if Mailpick weren't there.
- On phones the choices slide up as a bottom sheet you can swipe away, so a tap never jumps straight into one mail app. Set `mobile="native"` to let the phone's own mail app open instead.
- Gmail, Outlook and Yahoo open in a new tab with to, cc, bcc, subject and body filled in. They're real links, not `window.open`, so popup blockers leave them alone. A `target="_blank"` mailto link no longer leaves an empty tab behind.
- `+` in an address stays a plus, as the mailto spec says, so `name+tag@x.com` survives. Bad percent-encoding is shown as written instead of throwing.
- Copy address shows a check for 900 ms and closes. If the browser refuses the clipboard, the address is shown as text to select instead.
- Gmail, Outlook and Yahoo show their colour logos on white tiles, the same in light and dark. The logos are trademarks of Google, Microsoft and Yahoo, used to name their services; the SVGs come from openly licensed sets (credits in the file). Give a provider your own `icon` to replace one.
- Web options show a small ↗ on the highlighted row, since they open in a new tab.
- Built on `@ui-sdk/react` Menu, which handles focus, the arrow keys, Home and End, typeahead, Escape, Tab and the ARIA menu roles. Add `@layer ui-sdk;` at the top of your global stylesheet, above `@import "tailwindcss"`. It needs React 19, and this item pins 0.1.0-beta.20.

## Source

### registry/new-york/blocks/mailpick/mailpick.tsx

```tsx
"use client"

import * as React from "react"
import { createMenuController, Menu, MenuContent, MenuItem, MenuSeparator } from "@ui-sdk/react/menu"
import { ArrowUpRightIcon, CheckIcon, CopyIcon, MailIcon } from "lucide-react"

import { cn } from "@/lib/utils"
import {
  defaultProviderIds,
  resolveProviders,
  type Provider,
  type ProviderId,
} from "@/registry/new-york/lib/mailpick-providers"
import {
  buildMailto,
  isMailto,
  parseMailto,
  type MailtoParts,
  type ParsedMailto,
} from "@/registry/new-york/lib/parse-mailto"

const STORAGE_KEY = "mailpick:last"
const COPIED_FOR = 900

type Payload = { href: string; mail: ParsedMailto }

export type MailpickSelectEvent = {
  /** The id of the option picked, like `"gmail"` or `"copy"`. */
  provider: string
  mail: ParsedMailto
  /** The mailto link the menu was opened with. */
  href: string
}

type MailpickApi = {
  /** Opens the menu for a mailto link or its parts, beside `anchor`, or near the top of the window without one. */
  open: (mailto: string | MailtoParts, anchor?: HTMLElement | null) => void
  close: () => void
  parseMailto: typeof parseMailto
}

const MailpickContext = React.createContext<MailpickApi | null>(null)

type MailpickProviderProps = {
  children?: React.ReactNode
  /** Which choices show, in order. Ids of the built-in ones, or your own. */
  providers?: readonly (ProviderId | Provider)[]
  /** The small label above the address. */
  title?: string
  /** Catch plain mailto links under the provider. With `false`, only `MailpickLink` and `open()` show the menu. */
  intercept?: boolean
  /** On phones, show the choices as a bottom sheet (the default), or let the phone's own mail app open. */
  mobile?: "native" | "menu"
  /** Focus the visitor's last pick and tag it "Last used". Kept in localStorage only. */
  rememberLast?: boolean
  /** Fires when someone picks an option. For analytics. */
  onSelect?: (event: MailpickSelectEvent) => void
  side?: "top" | "bottom"
  align?: "start" | "center" | "end"
  /** Classes for the menu itself. */
  className?: string
}

function readLast() {
  try {
    return window.localStorage.getItem(STORAGE_KEY)
  } catch {
    return null
  }
}

function writeLast(id: string) {
  try {
    window.localStorage.setItem(STORAGE_KEY, id)
  } catch {}
}

function isTouch() {
  return typeof window !== "undefined" && window.matchMedia?.("(pointer: coarse)").matches
}

/** The old way, for when the clipboard API is missing or refused. */
function copyWithTextarea(text: string) {
  const area = document.createElement("textarea")
  area.value = text
  area.setAttribute("readonly", "")
  area.style.cssText = "position:fixed;top:0;left:0;opacity:0"
  document.body.appendChild(area)
  area.select()
  let copied = false
  try {
    copied = document.execCommand("copy")
  } catch {}
  area.remove()
  if (!copied) throw new Error("Copy failed")
}

async function copyText(text: string) {
  try {
    await navigator.clipboard.writeText(text)
  } catch {
    copyWithTextarea(text)
  }
}

/** The closest link the click came through, unless it came from inside the menu. */
function linkFrom(event: MouseEvent) {
  const path = event.composedPath().filter((node): node is Element => node instanceof Element)
  if (path.some((node) => node.hasAttribute("data-mailpick-menu"))) return null
  return (path.find((node) => node.tagName === "A") as HTMLAnchorElement | undefined) ?? null
}

/**
 * Turns every mailto link under it into a small menu: Gmail, Outlook, Yahoo Mail, the default mail app,
 * or copy the address. Wrap the app once; existing links don't change.
 */
function MailpickProvider({
  children,
  providers = defaultProviderIds,
  title = "Send with",
  intercept = true,
  mobile = "menu",
  rememberLast = true,
  onSelect,
  side = "bottom",
  align = "start",
  className,
}: MailpickProviderProps) {
  const [menu] = React.useState(() => createMenuController<Payload>())
  const [last, setLast] = React.useState<string | null>(null)
  const [copy, setCopy] = React.useState<"idle" | "copied" | "failed">("idle")
  const [centered, setCentered] = React.useState(false)
  const anchorRef = React.useRef<HTMLElement | null>(null)
  const contentRef = React.useRef<HTMLDivElement>(null)
  const copyTimer = React.useRef<number | undefined>(undefined)

  const settings = React.useRef({ intercept, mobile, rememberLast, onSelect })
  React.useEffect(() => {
    settings.current = { intercept, mobile, rememberLast, onSelect }
  })

  const open = React.useCallback<MailpickApi["open"]>(
    (mailto, anchor) => {
      const href = typeof mailto === "string" ? mailto.trim() : buildMailto(mailto)
      const remembered = settings.current.rememberLast ? readLast() : null
      window.clearTimeout(copyTimer.current)
      anchorRef.current = anchor ?? null
      setLast(remembered)
      setCopy("idle")
      setCentered(!anchor)
      void menu.open({
        payload: { href, mail: parseMailto(href) },
        anchor: anchor ?? { x: window.innerWidth / 2, y: window.innerHeight * 0.2 },
        // With a last pick, focus it ourselves once it mounts; it may be hidden now, so fall back to the first.
        focus: remembered ? "none" : "first",
      })
      if (!remembered) return
      let frames = 0
      const focusLast = () => {
        const content = contentRef.current
        if (!content && frames++ < 10) return void requestAnimationFrame(focusLast)
        const item =
          content?.querySelector<HTMLElement>(`[data-provider="${CSS.escape(remembered)}"]`) ??
          content?.querySelector<HTMLElement>("[data-provider]")
        item?.focus({ preventScroll: true })
      }
      requestAnimationFrame(focusLast)
    },
    [menu]
  )

  const close = React.useCallback(() => {
    menu.close()
  }, [menu])

  React.useEffect(() => {
    const onClick = (event: MouseEvent) => {
      if (event.defaultPrevented || event.button !== 0) return
      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
      const link = linkFrom(event)
      const href = link?.getAttribute("href")
      if (!link || !isMailto(href)) return
      if (link.closest('[data-mailpick="off"]')) return
      if (!settings.current.intercept && !link.hasAttribute("data-mailpick-link")) return
      if (settings.current.mobile === "native" && isTouch()) return
      // Also stops the empty tab a target="_blank" mailto link leaves behind.
      event.preventDefault()
      open(href, link)
    }
    const onNavigate = () => menu.close()
    document.addEventListener("click", onClick)
    window.addEventListener("popstate", onNavigate)
    window.addEventListener("hashchange", onNavigate)
    return () => {
      document.removeEventListener("click", onClick)
      window.removeEventListener("popstate", onNavigate)
      window.removeEventListener("hashchange", onNavigate)
      window.clearTimeout(copyTimer.current)
    }
  }, [menu, open])

  const api = React.useMemo<MailpickApi>(() => ({ open, close, parseMailto }), [open, close])
  const options = React.useMemo(() => resolveProviders(providers), [providers])

  const choose = (id: string, payload: Payload) => {
    const { rememberLast, onSelect } = settings.current
    if (rememberLast && id !== "copy") writeLast(id)
    onSelect?.({ provider: id, mail: payload.mail, href: payload.href })
  }

  const copyAddress = (payload: Payload) => {
    choose("copy", payload)
    copyText(payload.mail.to.join(", ")).then(
      () => {
        setCopy("copied")
        copyTimer.current = window.setTimeout(() => menu.close(), COPIED_FOR)
      },
      () => setCopy("failed")
    )
  }

  return (
    <MailpickContext.Provider value={api}>
      {children}
      <span aria-live="polite" className="sr-only">
        {copy === "copied" ? "Copied" : ""}
      </span>
      <Menu
        controller={menu}
        presentation={mobile === "menu" ? "auto" : "popover"}
        onOpenChange={(isOpen) => {
          if (!isOpen) window.clearTimeout(copyTimer.current)
        }}
      >
        <MenuContent<Payload>
          ref={contentRef}
          data-mailpick-menu=""
          side={side}
          align={centered ? "center" : align}
          sideOffset={8}
          collisionPadding={8}
          finalFocus={() => anchorRef.current}
          className={cn(
            "group/menu max-h-(--available-height) overflow-y-auto overscroll-contain border bg-popover text-popover-foreground outline-none",
            // A popover beside the link: soft corners, a quiet lift, a quick scale from where it opened.
            "data-[presentation=popover]:w-72 data-[presentation=popover]:max-w-[calc(100vw-16px)] data-[presentation=popover]:rounded-[18px] data-[presentation=popover]:[corner-shape:squircle] data-[presentation=popover]:p-1.5",
            "data-[presentation=popover]:shadow-[0_1px_2px_rgb(0_0_0/0.04),0_16px_40px_-16px_rgb(0_0_0/0.28)]",
            "data-[presentation=popover]:origin-(--transform-origin) data-[presentation=popover]:transition-[opacity,scale] data-[presentation=popover]:duration-150 data-[presentation=popover]:ease-[cubic-bezier(0.23,1,0.32,1)]",
            "data-[presentation=popover]:data-starting-style:scale-[0.96] data-[presentation=popover]:data-starting-style:opacity-0",
            "data-[presentation=popover]:data-ending-style:scale-[0.96] data-[presentation=popover]:data-ending-style:opacity-0 data-[presentation=popover]:data-ending-style:duration-100",
            // A bottom sheet on phones (ui-sdk slides it up and lets a swipe close it): full width, big rows.
            "data-[presentation=sheet]:w-full data-[presentation=sheet]:max-w-none data-[presentation=sheet]:rounded-t-[28px] data-[presentation=sheet]:rounded-b-none data-[presentation=sheet]:border-x-0 data-[presentation=sheet]:border-b-0",
            "data-[presentation=sheet]:px-2 data-[presentation=sheet]:pb-[max(0.75rem,env(safe-area-inset-bottom))]",
            "motion-reduce:transition-none",
            className
          )}
          render={(props, state) => {
            const payload = state.payload
            const addresses = payload?.mail.to.join(", ") || "New message"
            return (
              <div {...props} aria-label={`${title} ${addresses}`}>
                {payload && (
                  <MailpickMenu
                    title={title}
                    addresses={addresses}
                    payload={payload}
                    options={options}
                    last={last}
                    copy={copy}
                    onChoose={choose}
                    onCopy={copyAddress}
                  />
                )}
              </div>
            )
          }}
        />
      </Menu>
    </MailpickContext.Provider>
  )
}

type MailpickMenuProps = {
  title: string
  addresses: string
  payload: Payload
  options: Provider[]
  last: string | null
  copy: "idle" | "copied" | "failed"
  onChoose: (id: string, payload: Payload) => void
  onCopy: (payload: Payload) => void
}

function MailpickMenu({ title, addresses, payload, options, last, copy, onChoose, onCopy }: MailpickMenuProps) {
  const web = options.filter((option) => (option.kind ?? "web") === "web" && option.href)
  const local = options.filter((option) => option.kind === "app" || (option.kind === "copy" && payload.mail.to.length))

  const row = (option: Provider, content: React.ReactNode, newTab = false) => ({
    "data-provider": option.id,
    label: option.label,
    className: itemClass,
    children: (
      <>
        {content}
        {option.id === last && (
          <span className="shrink-0 rounded-full border px-1.5 py-px text-[11px] leading-4 text-muted-foreground">
            Last used
          </span>
        )}
        {newTab && (
          <ArrowUpRightIcon
            aria-hidden
            className="size-3.5 shrink-0 text-muted-foreground opacity-0 group-data-highlighted/item:opacity-100"
          />
        )}
      </>
    ),
  })

  return (
    <>
      {/* The grab handle, only on the sheet. */}
      <div aria-hidden className="hidden justify-center pt-2.5 pb-1 group-data-[presentation=sheet]/menu:flex">
        <span className="h-1 w-9 rounded-full bg-foreground/15" />
      </div>

      <div
        aria-hidden
        className="flex flex-col gap-0.5 px-2 pt-1.5 pb-2.5 group-data-[presentation=sheet]/menu:px-3 group-data-[presentation=sheet]/menu:pt-2 group-data-[presentation=sheet]/menu:pb-3"
      >
        <span className="text-[11px] font-medium tracking-[0.08em] text-muted-foreground uppercase">{title}</span>
        <span
          title={addresses}
          className="truncate text-sm font-medium group-data-[presentation=sheet]/menu:text-base"
        >
          {addresses}
        </span>
        {payload.mail.subject && (
          <span title={payload.mail.subject} className="truncate text-xs text-muted-foreground">
            {payload.mail.subject}
          </span>
        )}
      </div>

      {web.map((option) => (
        <MenuItem
          key={option.id}
          {...row(option, <Label option={option} extra=", opens in new tab" />, true)}
          render={<a href={option.href!(payload.mail)} target="_blank" rel="noopener noreferrer" />}
          onSelect={() => onChoose(option.id, payload)}
        />
      ))}

      {web.length > 0 && local.length > 0 && (
        <MenuSeparator className="mx-2 my-1.5 h-px bg-border group-data-[presentation=sheet]/menu:mx-3" />
      )}

      {local.map((option) =>
        option.kind === "app" ? (
          <MenuItem
            key={option.id}
            {...row(option, <Label option={option} icon={<MailIcon />} />)}
            render={<a href={payload.href} />}
            onSelect={() => onChoose(option.id, payload)}
          />
        ) : (
          <MenuItem
            key={option.id}
            {...row(
              option,
              copy === "failed" ? (
                <>
                  <Mark icon={<CopyIcon />} />
                  <span className="min-w-0 flex-1 cursor-text font-mono text-sm break-all select-all">
                    {payload.mail.to.join(", ")}
                  </span>
                </>
              ) : (
                <Label
                  option={copy === "copied" ? { ...option, label: "Copied" } : option}
                  icon={copy === "copied" ? <CheckIcon /> : <CopyIcon />}
                  done={copy === "copied"}
                />
              )
            )}
            closeOnSelect={false}
            onSelect={(event) => {
              event.preventDefault()
              if (copy === "idle") onCopy(payload)
            }}
          />
        )
      )}
    </>
  )
}

const itemClass = cn(
  "group/item flex min-h-10 w-full cursor-pointer items-center gap-3 rounded-[12px] px-2 py-1.5 text-left text-sm outline-none select-none [corner-shape:squircle]",
  "transition-[background-color,scale] duration-150 ease-out active:scale-[0.98] motion-reduce:transition-none",
  "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
  "focus-visible:ring-2 focus-visible:ring-ring",
  "pointer-coarse:min-h-11",
  "group-data-[presentation=sheet]/menu:min-h-14 group-data-[presentation=sheet]/menu:rounded-[16px] group-data-[presentation=sheet]/menu:px-3 group-data-[presentation=sheet]/menu:text-base"
)

function Mark({
  icon,
  logo: Logo,
  text,
  done,
}: {
  icon?: React.ReactNode
  logo?: React.ComponentType<{ className?: string }>
  text?: string
  done?: boolean
}) {
  if (Logo && !done) {
    // A white tile in both themes, like an app icon, so the brand colours read the same everywhere.
    return (
      <span
        aria-hidden
        className="grid size-7 shrink-0 place-items-center rounded-[8px] bg-white shadow-[inset_0_0_0_1px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)] [corner-shape:squircle] group-data-[presentation=sheet]/menu:size-9 group-data-[presentation=sheet]/menu:rounded-[11px]"
      >
        <Logo className="size-4 group-data-[presentation=sheet]/menu:size-5" />
      </span>
    )
  }
  return (
    <span
      aria-hidden
      className={cn(
        "grid size-7 shrink-0 place-items-center rounded-[8px] text-[13px] font-semibold [corner-shape:squircle] [&_svg]:size-[15px]",
        "group-data-[presentation=sheet]/menu:size-9 group-data-[presentation=sheet]/menu:rounded-[11px] group-data-[presentation=sheet]/menu:[&_svg]:size-[18px]",
        "transition-colors duration-150 ease-out",
        done
          ? "bg-primary text-primary-foreground"
          : "bg-muted text-foreground/70 shadow-[inset_0_0_0_1px_var(--border)]"
      )}
    >
      {icon ?? text}
    </span>
  )
}

function Label({
  option,
  icon,
  extra,
  done,
}: {
  option: Provider
  icon?: React.ReactNode
  /** Said to screen readers only. */
  extra?: string
  done?: boolean
}) {
  return (
    <>
      <Mark
        icon={icon}
        logo={icon ? undefined : (option.icon ?? BUILT_IN_LOGOS[option.id as ProviderId])}
        text={option.mark ?? option.label.charAt(0)}
        done={done}
      />
      <span className="flex min-w-0 flex-1 flex-col">
        <span className="truncate">
          {option.label}
          {extra && <span className="sr-only">{extra}</span>}
        </span>
        {option.hint && <span className="truncate text-xs text-muted-foreground">{option.hint}</span>}
      </span>
    </>
  )
}

type MailpickLinkProps = Omit<React.ComponentProps<"a">, "href"> &
  MailtoParts & {
    /** A ready mailto link. Wins over the parts. */
    href?: string
  }

/**
 * A real `<a href="mailto:…">` built from its parts, so it still works with JavaScript off. It opens the
 * menu even when the provider's `intercept` is off. Wrap it in `<Button asChild>` to look like a button.
 */
function MailpickLink({ to, cc, bcc, subject, body, href, ...props }: MailpickLinkProps) {
  return (
    <a
      data-slot="mailpick-link"
      data-mailpick-link=""
      href={href ?? buildMailto({ to, cc, bcc, subject, body })}
      {...props}
    />
  )
}

/** Without a provider, `open()` falls back to the plain mailto link. */
const fallback: MailpickApi = {
  open: (mailto) => {
    window.location.href = typeof mailto === "string" ? mailto : buildMailto(mailto)
  },
  close: () => {},
  parseMailto,
}

/** Opens and closes the menu from code, like a "Talk to sales" button. */
function useMailpick(): MailpickApi {
  return React.useContext(MailpickContext) ?? fallback
}

/* ---------- Logos ----------
   Colour marks for the built-in providers, shown on white tiles. Gmail is from Gil Barbara's
   "logos" set (CC0), Outlook from theSVG (MIT), Yahoo from selfh.st/icons (CC BY 4.0). The marks
   themselves are trademarks of Google, Microsoft and Yahoo, used here to name their services.
   Pass a provider an `icon` to show your own. */

/** Prefixes gradient ids per instance, so two copies of a logo on a page never share one. */
function useSvgIds() {
  const id = React.useId().replace(/[^a-zA-Z0-9_-]/g, "")
  return (name: string) => `mp${id}${name}`
}

function GmailLogo(props: React.ComponentProps<"svg">) {
  const u = useSvgIds()
  return (
    <svg viewBox="0 0 256 204" aria-hidden {...props}>
      <defs>
      <linearGradient id={u("SVGHzDbHcwG")} x1="165" x2="165" y1="44" y2="166" gradientUnits="userSpaceOnUse">
      <stop stopColor="#60d673" />
      <stop offset=".17" stopColor="#42c868" />
      <stop offset=".39" stopColor="#0ebc5f" />
      <stop offset=".62" stopColor="#00a9bb" />
      <stop offset=".86" stopColor="#3c90ff" />
      <stop offset="1" stopColor="#3186ff" />
      </linearGradient>
      <linearGradient id={u("SVG41ATXboZ")} x1="8" x2="184" y1="46.13" y2="46.13" gradientUnits="userSpaceOnUse">
      <stop offset=".08" stopColor="#ff63a0" />
      <stop offset=".3" stopColor="#fc413d" />
      <stop offset=".5" stopColor="#fc413d" />
      <stop offset=".65" stopColor="#fc413d" />
      <stop offset=".72" stopColor="#fc5c30" />
      <stop offset=".86" stopColor="#feb10c" />
      <stop offset=".91" stopColor="#fec700" />
      <stop offset=".96" stopColor="#ffdb0f" />
      </linearGradient>
      </defs>
      <path fill={`url(#${u("SVGHzDbHcwG")})`} d="M146 44h38v110c0 6.627-5.373 12-12 12h-20a6 6 0 0 1-6-6z" transform="translate(-11.636 -37.818)scale(1.45454)" />
      <path fill="#fc413d" d="M55.273 26.182H0v160c0 9.638 7.816 17.454 17.455 17.454h29.09a8.727 8.727 0 0 0 8.728-8.728z" />
      <path fill={`url(#${u("SVG41ATXboZ")})`} d="M39.226 30.456c-8.033-6.752-20.018-5.714-26.77 2.319c-6.752 8.032-5.714 20.017 2.319 26.77l76.078 63.949a8 8 0 0 0 10.295 0l76.078-63.95c8.032-6.752 9.07-18.737 2.318-26.77c-6.752-8.032-18.737-9.07-26.769-2.318L96 78.18z" transform="translate(-11.636 -37.818)scale(1.45454)" />
    </svg>
  )
}

function OutlookLogo(props: React.ComponentProps<"svg">) {
  const u = useSvgIds()
  return (
    <svg viewBox="60 90.4 570.02 539.67" aria-hidden {...props}>
      <defs>
      <linearGradient id={u("SVGtM6GPe9H")} x1="9.989" x2="30.932" y1="22.365" y2="9.375" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#20a7fa" />
      <stop offset=".4" stopColor="#3bd5ff" />
      <stop offset="1" stopColor="#c4b0ff" />
      </linearGradient>
      <linearGradient id={u("SVGzumyLb1h")} x1="17.197" x2="28.856" y1="26.794" y2="8.126" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#165ad9" />
      <stop offset=".501" stopColor="#1880e5" />
      <stop offset="1" stopColor="#8587ff" />
      </linearGradient>
      <linearGradient id={u("SVGEDNiAe7B")} x1="25.701" x2="12.756" y1="27.048" y2="16.501" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset=".237" stopColor="#448aff" stopOpacity="0" />
      <stop offset=".792" stopColor="#0032b1" stopOpacity=".2" />
      </linearGradient>
      <linearGradient id={u("SVGLVAa9cRZ")} x1="24.053" x2="44.51" y1="31.11" y2="18.018" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#1a43a6" />
      <stop offset=".492" stopColor="#2052cb" />
      <stop offset="1" stopColor="#5f20cb" />
      </linearGradient>
      <linearGradient id={u("SVGPrLOHehy")} x1="29.828" x2="17.397" y1="30.327" y2="19.571" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#0045b9" stopOpacity="0" />
      <stop offset=".67" stopColor="#0d1f69" stopOpacity=".2" />
      </linearGradient>
      <linearGradient id={u("SVGPfnCWb3Q")} x1="41.998" x2="23.852" y1="29.943" y2="29.943" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#4dc4ff" />
      <stop offset=".196" stopColor="#0fafff" />
      </linearGradient>
      <linearGradient id={u("SVGsoPskbid")} x1="3.458" x2="20.929" y1="37.872" y2="37.86" gradientTransform="scale(15)" gradientUnits="userSpaceOnUse">
      <stop offset=".206" stopColor="#6ce0ff" />
      <stop offset=".535" stopColor="#50d5ff" stopOpacity="0" />
      </linearGradient>
      <radialGradient id={u("SVGWDe6xCII")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="matrix(0 -405.04051 438.393 0 360.027 102.268)" gradientUnits="userSpaceOnUse">
      <stop offset=".568" stopColor="#275ff0" stopOpacity="0" />
      <stop offset=".992" stopColor="#002177" />
      </radialGradient>
      <radialGradient id={u("SVGnxCXEcwX")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="rotate(-45 897.061 -224.265)scale(173.58)" gradientUnits="userSpaceOnUse">
      <stop offset=".259" stopColor="#0060d1" stopOpacity=".4" />
      <stop offset=".908" stopColor="#0383f1" stopOpacity="0" />
      </radialGradient>
      <radialGradient id={u("SVGTJGZtcBY")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="rotate(-52.658 784.06 187.412)scale(589.22098 532.80602)" gradientUnits="userSpaceOnUse">
      <stop offset=".732" stopColor="#f4a7f7" stopOpacity="0" />
      <stop offset="1" stopColor="#f4a7f7" stopOpacity=".502" />
      </radialGradient>
      <radialGradient id={u("SVGbswy2xan")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="rotate(123.339 27.956 281.58)scale(310.88699 806.7885)" gradientUnits="userSpaceOnUse">
      <stop offset="0" stopColor="#49deff" />
      <stop offset=".724" stopColor="#29c3ff" />
      </radialGradient>
      <radialGradient id={u("SVGUlEh92cn")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="rotate(46.924 -378.504 245.25)scale(315.927)" gradientUnits="userSpaceOnUse">
      <stop offset=".039" stopColor="#0091ff" />
      <stop offset=".919" stopColor="#183dad" />
      </radialGradient>
      <radialGradient id={u("SVGjiSAMeNm")} cx="0" cy="0" r="1" fx="0" fy="0" gradientTransform="matrix(0 168 -193.782 0 180 491.159)" gradientUnits="userSpaceOnUse">
      <stop offset=".558" stopColor="#0fa5f7" stopOpacity="0" />
      <stop offset="1" stopColor="#74c6ff" stopOpacity=".502" />
      </radialGradient>
      </defs>
      <path fill={`url(#${u("SVGtM6GPe9H")})`} d="m463.984 140.145l-344.347 218.27l-29.614-46.72v-40.257a43.26 43.26 0 0 1 19.72-36.293L309.91 105.258c30.496-19.79 69.777-19.793 100.277-.008Zm0 0" />
      <path fill={`url(#${u("SVGzumyLb1h")})`} d="M407.102 103.34a91 91 0 0 1 3.082 1.914l156.214 101.332l-387.336 245.52l-59.437-93.77L403.895 177.8c26.925-17.102 28.105-55.57 3.207-74.461Zm0 0" />
      <path fill={`url(#${u("SVGEDNiAe7B")})`} d="M407.102 103.34a91 91 0 0 1 3.082 1.914l156.214 101.332l-387.336 245.52l-59.437-93.77L403.895 177.8c26.925-17.102 28.105-55.57 3.207-74.461Zm0 0" />
      <path fill={`url(#${u("SVGLVAa9cRZ")})`} d="M333.602 498.988L179.066 452.11L507.63 243.836c27.672-17.54 27.601-57.938-.133-75.379l-1.48-.93l4.261 2.649l99.996 64.867a43.26 43.26 0 0 1 19.723 36.3v38.962Zm0 0" />
      <path fill={`url(#${u("SVGPrLOHehy")})`} d="M333.602 498.988L179.066 452.11L507.63 243.836c27.672-17.54 27.601-57.938-.133-75.379l-1.48-.93l4.261 2.649l99.996 64.867a43.26 43.26 0 0 1 19.723 36.3v38.962Zm0 0" />
      <path fill={`url(#${u("SVGWDe6xCII")})`} d="M410.188 105.25c-30.5-19.785-69.782-19.781-100.282.008L109.742 235.145a43.26 43.26 0 0 0-19.719 36.292v1.97a44.48 44.48 0 0 0 20.735 36.16l248.887 156.91L609.16 309.805a44.47 44.47 0 0 0 20.824-37.664v38.168l.008-38.965a43.28 43.28 0 0 0-19.722-36.301Zm0 0" />
      <path fill={`url(#${u("SVGPfnCWb3Q")})`} d="M315.77 630.05h220.449c51.777 0 93.75-41.972 93.75-93.75V272.14a44.48 44.48 0 0 1-20.82 37.665l-327.907 205.89a60.71 60.71 0 0 0-28.422 51.414c.004 34.762 28.184 62.942 62.95 62.942Zm0 0" />
      <path fill={`url(#${u("SVGnxCXEcwX")})`} d="M315.77 630.05h220.449c51.777 0 93.75-41.972 93.75-93.75V272.14a44.48 44.48 0 0 1-20.82 37.665l-327.907 205.89a60.71 60.71 0 0 0-28.422 51.414c.004 34.762 28.184 62.942 62.95 62.942Zm0 0" />
      <path fill={`url(#${u("SVGTJGZtcBY")})`} d="M315.77 630.05h220.449c51.777 0 93.75-41.972 93.75-93.75V272.14a44.48 44.48 0 0 1-20.82 37.665l-327.907 205.89a60.71 60.71 0 0 0-28.422 51.414c.004 34.762 28.184 62.942 62.95 62.942Zm0 0" />
      <path fill={`url(#${u("SVGbswy2xan")})`} d="M405.402 630.035H183.738c-51.777 0-93.75-41.972-93.75-93.75v-264.34a44.47 44.47 0 0 0 20.754 37.621l327.582 206.52a61.74 61.74 0 0 1 28.809 52.226c-.004 34.09-27.64 61.723-61.73 61.723Zm0 0" />
      <path fill={`url(#${u("SVGsoPskbid")})`} d="M405.402 630.035H183.738c-51.777 0-93.75-41.972-93.75-93.75v-264.34a44.47 44.47 0 0 0 20.754 37.621l327.582 206.52a61.74 61.74 0 0 1 28.809 52.226c-.004 34.09-27.64 61.723-61.73 61.723Zm0 0" />
      <path fill={`url(#${u("SVGUlEh92cn")})`} d="M108.75 345h142.5c26.926 0 48.75 21.824 48.75 48.75v142.5c0 26.926-21.824 48.75-48.75 48.75h-142.5C81.824 585 60 563.176 60 536.25v-142.5C60 366.824 81.824 345 108.75 345m0 0" />
      <path fill={`url(#${u("SVGjiSAMeNm")})`} d="M108.75 345h142.5c26.926 0 48.75 21.824 48.75 48.75v142.5c0 26.926-21.824 48.75-48.75 48.75h-142.5C81.824 585 60 563.176 60 536.25v-142.5C60 366.824 81.824 345 108.75 345m0 0" />
      <path fill="#fff" d="M179.387 534c-19.848 0-36.137-6.21-48.875-18.625q-19.11-18.622-19.11-48.605c0-21.11 6.465-38.18 19.395-51.22Q150.195 396 181.594 396q29.67 0 48.297 18.715c12.484 12.476 18.726 28.93 18.726 49.351c0 20.985-6.469 37.899-19.398 50.75Q209.919 534 179.387 534m.574-26.352q16.225 0 26.117-11.082c6.594-7.386 9.89-17.664 9.89-30.824q-.002-20.577-9.6-32.031q-9.605-11.454-25.638-11.453q-16.517 0-26.597 11.824q-10.083 11.736-10.082 31.102q0 19.652 10.082 31.101q10.078 11.362 25.828 11.363m0 0" />
      <path fill="#fff" d="M179.332 535.848q-29.655.001-48.691-19.13c-12.688-12.753-19.036-29.398-19.036-49.929q0-32.525 19.325-52.61q19.324-20.09 50.601-20.09q29.555.002 48.114 19.227q18.654 19.23 18.652 50.7c0 21.55-6.442 38.93-19.32 52.129q-19.23 19.703-49.645 19.703m.57-27.067c10.778 0 19.453-3.797 26.02-11.383q9.853-11.384 9.851-31.664q0-21.138-9.562-32.902q-9.567-11.766-25.54-11.766q-16.457-.002-26.5 12.149c-6.694 8.031-10.042 18.683-10.042 31.945q0 20.185 10.043 31.95q10.043 11.67 25.73 11.671m0 0" />
    </svg>
  )
}

function YahooLogo(props: React.ComponentProps<"svg">) {
  return (
    <svg viewBox="0 0 512 512" aria-hidden {...props}>
      <path fill="#7d2eff" d="m0 140.9l106 249.5l-38.6 90h94.3l141.1-339.5h-93.7l-56.8 143.4l-56-143.4zM407.4 31.6l-93.2 223.8h105L512 31.6zm-65.6 245.3c-32.2 0-58.3 26.1-58.3 58.3s26.1 58.3 58.3 58.3s58.3-26.1 58.3-58.3s-26.1-58.3-58.3-58.3" />
    </svg>
  )
}

const BUILT_IN_LOGOS: Partial<Record<ProviderId, React.ComponentType<{ className?: string }>>> = {
  gmail: GmailLogo,
  outlook: OutlookLogo,
  office: OutlookLogo,
  yahoo: YahooLogo,
}

export { MailpickLink, MailpickProvider, useMailpick, buildMailto, parseMailto }
export type { MailpickProviderProps, MailpickLinkProps, MailtoParts, ParsedMailto, Provider, ProviderId }
```

### registry/new-york/lib/parse-mailto.ts

```ts
/**
 * Reads and writes mailto links (RFC 6068). No React and no DOM, so it runs on the server and in tests.
 */

export type ParsedMailto = {
  to: string[]
  cc: string[]
  bcc: string[]
  subject: string
  body: string
}

/** The parts `buildMailto` and `MailpickLink` accept. A single address or a list for each field. */
export type MailtoParts = {
  to?: string | string[]
  cc?: string | string[]
  bcc?: string | string[]
  subject?: string
  body?: string
}

const MAILTO = /^\s*mailto:/i

export function isMailto(href: string | null | undefined): href is string {
  return typeof href === "string" && MAILTO.test(href)
}

/** Bad percent-encoding falls back to the raw text instead of throwing. */
function decode(value: string) {
  try {
    return decodeURIComponent(value)
  } catch {
    return value
  }
}

function splitAddresses(value: string) {
  return value
    .split(/[,;]/)
    .map((address) => address.trim())
    .filter(Boolean)
}

/**
 * Splits a mailto link into its addresses and fields. Addresses come from before the `?` and from any
 * `to=` values. Field names are read in any letter case, and `+` stays a plus, as the spec says, so
 * `name+tag@x.com` survives. That's why this doesn't use `URLSearchParams`.
 */
export function parseMailto(href: string): ParsedMailto {
  const rest = String(href ?? "")
    .trim()
    .replace(MAILTO, "")
  const query = rest.indexOf("?")
  const head = query === -1 ? rest : rest.slice(0, query)
  const search = query === -1 ? "" : rest.slice(query + 1)

  const mail: ParsedMailto = { to: splitAddresses(decode(head)), cc: [], bcc: [], subject: "", body: "" }

  for (const pair of search.split("&")) {
    if (!pair) continue
    const eq = pair.indexOf("=")
    const key = (eq === -1 ? pair : pair.slice(0, eq)).toLowerCase()
    const value = eq === -1 ? "" : decode(pair.slice(eq + 1))
    if (key === "to" || key === "cc" || key === "bcc") mail[key] = mail[key].concat(splitAddresses(value))
    else if (key === "subject") mail.subject = value
    else if (key === "body") mail.body = value
  }

  return mail
}

const list = (value: string | string[] | undefined) =>
  (Array.isArray(value) ? value : value ? [value] : []).flatMap(splitAddresses)

/** Encodes the way RFC 6068 wants: `@` and `,` left readable in addresses, line breaks as `%0D%0A`. */
function encodeField(value: string) {
  return encodeURIComponent(value.replace(/\r?\n/g, "\r\n"))
}

function encodeAddresses(addresses: string[]) {
  return addresses.map((address) => encodeURIComponent(address).replace(/%40/g, "@")).join(",")
}

/** Builds a mailto link from its parts. Empty fields are left out. */
export function buildMailto(parts: MailtoParts): string {
  const to = list(parts.to)
  const query = [
    ["cc", encodeAddresses(list(parts.cc))],
    ["bcc", encodeAddresses(list(parts.bcc))],
    ["subject", parts.subject ? encodeField(parts.subject) : ""],
    ["body", parts.body ? encodeField(parts.body) : ""],
  ]
    .filter(([, value]) => value)
    .map(([key, value]) => `${key}=${value}`)
    .join("&")
  return `mailto:${encodeAddresses(to)}${query ? `?${query}` : ""}`
}
```

### registry/new-york/lib/mailpick-providers.ts

```ts
import type { ComponentType } from "react"

import type { ParsedMailto } from "@/registry/new-york/lib/parse-mailto"

/**
 * One choice in the Mailpick menu.
 *
 * - `web` options are links that open in a new tab, above the divider.
 * - `app` hands the original mailto link to the visitor's mail app.
 * - `copy` copies the `to` addresses, and is hidden when there are none.
 */
export type Provider = {
  id: string
  label: string
  /** Small grey text under the label, like "Work or school". */
  hint?: string
  /** A logo for the tile beside the label. The built-in providers bring their own; custom ones show `mark`. */
  icon?: ComponentType<{ className?: string }>
  /** One or two letters for the tile when there's no icon. Defaults to the label's first letter. */
  mark?: string
  kind?: "web" | "app" | "copy"
  /** The compose URL for a `web` option. */
  href?: (mail: ParsedMailto) => string
}

export type ProviderId = "gmail" | "outlook" | "office" | "yahoo" | "app" | "copy"

/** Joins the filled fields into a query string, in the order given, with every value encoded. */
export function composeQuery(fields: Record<string, string>) {
  return Object.entries(fields)
    .filter(([, value]) => value)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join("&")
}

/** The fields most webmail compose pages read, under the names Outlook and Yahoo use. */
const outlookFields = (mail: ParsedMailto) => ({
  to: mail.to.join(","),
  cc: mail.cc.join(","),
  bcc: mail.bcc.join(","),
  subject: mail.subject,
  body: mail.body,
})

export const mailpickProviders: Record<ProviderId, Provider> = {
  gmail: {
    id: "gmail",
    label: "Gmail",
    mark: "G",
    href: (mail) =>
      `https://mail.google.com/mail/?view=cm&fs=1&${composeQuery({
        to: mail.to.join(","),
        cc: mail.cc.join(","),
        bcc: mail.bcc.join(","),
        su: mail.subject,
        body: mail.body,
      })}`,
  },
  outlook: {
    id: "outlook",
    label: "Outlook",
    hint: "Personal",
    mark: "O",
    href: (mail) => `https://outlook.live.com/mail/0/deeplink/compose?${composeQuery(outlookFields(mail))}`,
  },
  office: {
    id: "office",
    label: "Outlook",
    hint: "Work or school",
    mark: "O",
    href: (mail) => `https://outlook.office.com/mail/deeplink/compose?${composeQuery(outlookFields(mail))}`,
  },
  yahoo: {
    id: "yahoo",
    label: "Yahoo Mail",
    mark: "Y",
    href: (mail) => `https://compose.mail.yahoo.com/?${composeQuery(outlookFields(mail))}`,
  },
  app: { id: "app", label: "Default mail app", kind: "app" },
  copy: { id: "copy", label: "Copy address", kind: "copy" },
}

export const defaultProviderIds: ProviderId[] = ["gmail", "outlook", "office", "yahoo", "app", "copy"]

/** Turns ids and custom providers into providers, skipping unknown ids. */
export function resolveProviders(providers: readonly (ProviderId | Provider)[]): Provider[] {
  return providers.flatMap((p) => {
    const provider = typeof p === "string" ? mailpickProviders[p] : p
    return provider ? [provider] : []
  })
}
```
