# Truncate Middle

> Shortens long text in the middle so the start and the end stay visible, and recomputes when the container resizes.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/truncate-middle`
- File: `src/components/haze/ui/truncate-middle.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/truncate-middle

## Use when
- File names, IDs, hashes or paths whose beginning and end both matter.
- A table cell or list row that has a fixed width.

## Avoid when
- Prose; use a normal end ellipsis or wrap the text.
- The full value must be readable without hovering; show it in full.

## Alternatives
- [badge](https://hazeui.com/ui/badge.md)
- [copy-button](https://hazeui.com/ui/copy-button.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| text | `string` |  | yes | The full string. |
| endChars | `number` |  | no | Characters kept at the end. By default the file extension plus seven characters, or eight when there is no extension. |
| class | `string` |  | no | Classes on the element, for example font-mono. |

## Accessibility
- The full string stays in the DOM: the hidden middle is zero width but still selectable, so copying a selection gives the whole value and assistive technology reads it all. Only the ellipsis is skipped.
- The full text is also in the title attribute for hover. Without scripts a CSS end ellipsis is used.
- No motion.

## Agent prompts

### Install and use

Install the Haze UI component "Truncate Middle" with `npx shadcn@latest add @haze/truncate-middle`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TruncateMiddle from "@/components/haze/ui/truncate-middle.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/truncate-middle.md

### Customize with real content

Adapt the Haze truncate-middle ui for our product. Replace the demo values of these props with our real content: text, endChars, class. Keep the layout, the heading level rules and these accessibility details: The full string stays in the DOM: the hidden middle is zero width but still selectable, so copying a selection gives the whole value and assistive technology reads it all. Only the ellipsis is skipped. The full text is also in the title attribute for hover. Without scripts a CSS end ellipsis is used. No motion. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using truncate-middle, check it fits: use it when file names, ids, hashes or paths whose beginning and end both matter.; a table cell or list row that has a fixed width.. Avoid it when prose; use a normal end ellipsis or wrap the text.; the full value must be readable without hovering; show it in full.. Alternatives: @haze/badge, @haze/copy-button.

## Example requests that should lead here
- Show long file names in the upload list so the extension is still visible

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  text: string;
  endChars?: number;
  class?: string;
}

const { text, endChars, class: className } = Astro.props;
---

{/* Three parts keep the full string in the DOM: the start, the hidden middle (zero width, still selectable and read aloud) and the end. Without scripts the start holds everything and the CSS ellipsis applies. */}
<span data-haze-truncate-middle data-end-chars={endChars} title={text} class={cn("block min-w-0 max-w-full truncate whitespace-pre", className)}><span data-tm-start>{text}</span><span data-tm-middle class="inline-block w-0 overflow-hidden align-bottom"></span><span data-tm-gap aria-hidden="true" hidden class="select-none">…</span><span data-tm-end></span></span>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const startEl = root.querySelector<HTMLElement>("[data-tm-start]");
    const middleEl = root.querySelector<HTMLElement>("[data-tm-middle]");
    const gapEl = root.querySelector<HTMLElement>("[data-tm-gap]");
    const endEl = root.querySelector<HTMLElement>("[data-tm-end]");
    if (!startEl || !middleEl || !gapEl || !endEl) return;
    const full = startEl.textContent ?? "";
    const chars = Array.from(full);
    const requested = Number(root.dataset.endChars);
    const extension = /\.[A-Za-z0-9]{1,8}$/.exec(full)?.[0].length ?? 0;
    const tail = Math.min(chars.length, Number.isFinite(requested) && requested > 0 ? Math.round(requested) : extension + 7 || 8);

    // The whole string is always present; only where the visible gap sits changes.
    const show = (head: number) => {
      const hidden = head < chars.length - tail;
      startEl.textContent = chars.slice(0, hidden ? head : chars.length).join("");
      middleEl.textContent = hidden ? chars.slice(head, chars.length - tail).join("") : "";
      gapEl.hidden = !hidden;
      endEl.textContent = hidden ? chars.slice(chars.length - tail).join("") : "";
    };
    const fits = () => root.scrollWidth <= root.clientWidth;
    const layout = () => {
      show(chars.length);
      if (!fits()) {
        let low = 0;
        let high = chars.length - tail - 1;
        show(0);
        while (low < high) {
          const mid = Math.ceil((low + high) / 2);
          show(mid);
          if (fits()) low = mid;
          else high = mid - 1;
        }
        show(low);
      }
    };

    let width = -1;
    new ResizeObserver(() => {
      if (root.clientWidth === width) return;
      width = root.clientWidth;
      layout();
    }).observe(root);
    document.fonts?.ready.then(layout);
    root.setAttribute("data-enhanced", "");
  }

  // One shared listener: selections drop the clipped middle, so copying puts the full string on the clipboard.
  if (!document.documentElement.hasAttribute("data-haze-truncate-copy")) {
    document.documentElement.setAttribute("data-haze-truncate-copy", "");
    document.addEventListener("copy", event => {
      const selection = getSelection();
      if (!selection || selection.isCollapsed) return;
      let copied = selection.toString();
      let changed = false;
      for (const root of document.querySelectorAll<HTMLElement>("[data-haze-truncate-middle][data-enhanced]")) {
        const middle = root.querySelector("[data-tm-middle]");
        if (!middle?.textContent || !selection.containsNode(root, true)) continue;
        const shown = (root.querySelector("[data-tm-start]")?.textContent ?? "") + (root.querySelector("[data-tm-end]")?.textContent ?? "");
        if (!copied.includes(shown)) continue;
        copied = copied.replace(shown, root.title);
        changed = true;
      }
      if (!changed) return;
      event.clipboardData?.setData("text/plain", copied);
      event.preventDefault();
    });
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-truncate-middle]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-truncate-middle-listener")) {
    document.documentElement.setAttribute("data-haze-truncate-middle-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
