# Middle Truncate

Shortens a string in the middle, so a path, a hash or a URL keeps both its start and its end.

```tsx
"use client"

import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react"
import * as stylex from "@stylexjs/stylex"
import { MiddleTruncate } from "@/components/ui/middle-truncate"
import { Text } from "@/components/ui/text"
import { color, duration, ease, font, radius, space } from "@/theme/tokens.stylex"

const MIN_PERCENT = 40
const KEY_STEP = 5

const styles = stylex.create({
  root: {
    width: "100%",
  },
  frame: {
    position: "relative",
    minWidth: "min(100%, 18rem)",
    maxWidth: "100%",
  },
  card: {
    margin: 0,
    padding: 0,
    listStyleType: "none",
    borderRadius: radius.lg,
    borderWidth: 1,
    borderStyle: "solid",
  },
  row: {
    display: "flex",
    alignItems: "center",
    gap: space.s4,
    paddingBlock: space.s3,
    paddingInline: space.s4,
    borderBlockStartWidth: { default: 1, ":first-child": 0 },
    borderBlockStartStyle: "solid",
    borderBlockStartColor: `color-mix(in oklab, ${color.border} 60%, transparent)`,
  },
  label: {
    flexShrink: 0,
    width: space.s24,
  },
  value: {
    flexGrow: 1,
    minWidth: 0,
  },
  mono: {
    fontFamily: font.mono,
  },
  handle: {
    position: "absolute",
    top: "50%",
    insetInlineStart: "100%",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    width: space.s3,
    height: space.s10,
    marginInlineStart: space.s2,
    borderRadius: radius.full,
    color: {
      default: color.border,
      ":hover": `color-mix(in oklab, ${color.foreground} 40%, transparent)`,
    },
    cursor: "ew-resize",
    touchAction: "none",
    userSelect: "none",
    transform: "translateY(-50%)",
    outlineStyle: { default: "none", ":focus-visible": "solid" },
    outlineWidth: 2,
    outlineColor: color.ring,
    transitionProperty: "color",
    transitionDuration: duration.color,
    transitionTimingFunction: ease.standard,
  },
  handleActive: {
    color: `color-mix(in oklab, ${color.foreground} 60%, transparent)`,
  },
  grip: {
    width: space.s1_5,
    height: space.s8,
    borderRadius: radius.full,
    backgroundColor: "currentColor",
  },
  resizing: {
    userSelect: "none",
  },
})

const rows = [
  { label: "File", value: "packages/ui/src/base/navigation-menu.tsx", mono: true },
  { label: "Branch", value: "feat/middle-truncate-without-a-measuring-script" },
  { label: "Commit", value: "6c37f5ec0c866624c17f543c65805bce4a8b67dc", mono: true },
  { label: "Registry", value: "https://www.arene.style/r/middle-truncate.json" },
  { label: "Preset", value: "@arene/typescript-config/react-library.json", mono: true },
  { label: "Docs", value: "www.arene.style/docs/components/middle-truncate" },
  { label: "Stylesheet", value: "node_modules/@arene/ui/interop.css", mono: true },
  { label: "Fits", value: "button.tsx", mono: true },
]

const clamp = (percent: number) => Math.min(100, Math.max(MIN_PERCENT, percent))

export default function MiddleTruncateDemo() {
  const rootRef = useRef<HTMLDivElement>(null)
  const drag = useRef<{ x: number; percent: number; width: number } | null>(null)
  const [percent, setPercent] = useState(100)
  const [resizing, setResizing] = useState(false)

  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
    const width = rootRef.current?.getBoundingClientRect().width
    if (!width) return
    event.preventDefault()
    event.currentTarget.setPointerCapture(event.pointerId)
    drag.current = { x: event.clientX, percent, width }
    setResizing(true)
  }

  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    const start = drag.current
    if (!start) return
    setPercent(clamp(start.percent + ((event.clientX - start.x) / start.width) * 100))
  }

  const onPointerUp = () => {
    drag.current = null
    setResizing(false)
  }

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    const next = {
      ArrowLeft: percent - KEY_STEP,
      ArrowRight: percent + KEY_STEP,
      Home: MIN_PERCENT,
      End: 100,
    }[event.key]
    if (next === undefined) return
    event.preventDefault()
    setPercent(clamp(next))
  }

  return (
    <div ref={rootRef} {...stylex.props(styles.root, resizing && styles.resizing)}>
      <div {...stylex.props(styles.frame)} style={{ width: `${percent}%` }}>
        <ul {...stylex.props(styles.card)}>
          {rows.map((row) => (
            <li key={row.label} {...stylex.props(styles.row)}>
              <Text size="xs" tone="muted" xstyle={styles.label}>
                {row.label}
              </Text>
              <Text size="sm" xstyle={[styles.value, row.mono && styles.mono]}>
                <MiddleTruncate>{row.value}</MiddleTruncate>
              </Text>
            </li>
          ))}
        </ul>
        <div
          role="separator"
          aria-orientation="vertical"
          aria-label="Resize the example"
          aria-valuemin={MIN_PERCENT}
          aria-valuemax={100}
          aria-valuenow={Math.round(percent)}
          tabIndex={0}
          {...stylex.props(styles.handle, resizing && styles.handleActive)}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerUp}
          onKeyDown={onKeyDown}
        >
          <div {...stylex.props(styles.grip)} />
        </div>
      </div>
    </div>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/middle-truncate
```

Needs the [arene setup](https://www.arene.style/docs/installation) first.

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx
   ```

2. Set up the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation). The component reads no tokens and needs no
   stylesheet of its own.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/middle-truncate.tsx"
   "use client"

   import {
     useLayoutEffect,
     useRef,
     useState,
     type CSSProperties,
     type MouseEvent,
     type PointerEvent,
   } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"

   const styles = stylex.create({
     root: {
       position: "relative",
       display: "inline-grid",
       gridTemplateColumns: "minmax(0.1px, 1fr)",
       width: "fit-content",
       maxWidth: "100%",
       overflowX: "clip",
       direction: "ltr",
       textDecoration: "inherit",
       whiteSpace: "pre",
       "::before": {
         content: "attr(data-head)",
         visibility: "hidden",
       },
     },
     split: {
       gridTemplateColumns: "minmax(2em, 1fr) minmax(0.1px, auto)",
       "::after": {
         content: "attr(data-tail)",
         visibility: "hidden",
       },
     },
     head: {
       position: "absolute",
       inset: 0,
       gridColumnEnd: "2",
       overflowX: "clip",
       textDecoration: "inherit",
       textOverflow: "ellipsis",
     },
     tail: {
       position: "absolute",
       inset: 0,
       display: "flex",
       justifyContent: "flex-end",
       gridColumnStart: "2",
       overflowX: "clip",
       textDecoration: "inherit",
     },
   })

   const MIN_HEAD = 8

   const printableAscii = /^[\x20-\x7e]*$/

   let segmenter: Intl.Segmenter | undefined

   function graphemeOffsets(text: string) {
     if (typeof Intl.Segmenter === "function") {
       segmenter ??= new Intl.Segmenter(undefined, { granularity: "grapheme" })
       return Array.from(segmenter.segment(text), (segment) => segment.index)
     }
     const offsets: number[] = []
     let offset = 0
     for (const character of text) {
       offsets.push(offset)
       offset += character.length
     }
     return offsets
   }

   function tailOffset(text: string, end: number) {
     const tailLength = Math.max(0, Math.trunc(end))
     if (printableAscii.test(text)) {
       return Math.min(text.length, Math.max(MIN_HEAD, text.length - tailLength))
     }
     const offsets = graphemeOffsets(text)
     return offsets[Math.max(MIN_HEAD, offsets.length - tailLength)] ?? text.length
   }

   function isClipped(root: Element) {
     if (screenReaderText.has(root)) return true
     for (const part of root.children) {
       if (part.scrollWidth > part.clientWidth) return true
     }
     return false
   }

   let canvas: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null | undefined
   let canvasFont = ""
   let canvasCase = "none"

   function selectFont(font: string) {
     if (canvas === undefined) {
       canvas =
         typeof OffscreenCanvas === "function"
           ? new OffscreenCanvas(1, 1).getContext("2d")
           : document.createElement("canvas").getContext("2d")
     }
     if (canvas && canvasFont !== font) {
       const [face = "", spacing = "0px", textCase = "none"] = font.split("\0")
       canvas.font = face
       if ("letterSpacing" in canvas) canvas.letterSpacing = spacing
       canvasFont = font
       canvasCase = textCase
     }
     return canvas !== null
   }

   function measure(text: string) {
     const cased =
       canvasCase === "uppercase"
         ? text.toUpperCase()
         : canvasCase === "lowercase"
           ? text.toLowerCase()
           : text
     return canvas?.measureText(cased).width ?? 0
   }

   function fontOf(element: Element) {
     const style = getComputedStyle(element)
     const caps = style.fontVariantCaps === "small-caps" ? "small-caps " : ""
     const spacing = style.letterSpacing === "normal" ? "0px" : style.letterSpacing
     const face = `${style.fontStyle} ${caps}${style.fontWeight} ${style.fontSize} ${style.fontFamily}`
     return `${face}\0${spacing}\0${style.textTransform}`
   }

   type Metrics = {
     font: string
     ends: number[]
     rights: Float64Array
     starts: number[]
     lefts: Float64Array
     tail: number
     ellipsis: number
   }

   type Glyphs = {
     head: string
     tail: string
     text: Text
     shown: string
     line?: Line
     metrics?: Metrics
   }

   type Line = { text: string; cut: number; middle: string }

   const glyphs = new Map<Element, Glyphs>()

   function metricsOf(known: Glyphs, font: string): Metrics {
     if (known.metrics?.font === font) return known.metrics
     const { head, tail } = known
     const ends = printableAscii.test(head)
       ? Array.from({ length: head.length }, (_, index) => index + 1)
       : [...graphemeOffsets(head).slice(1), head.length]
     const starts = printableAscii.test(tail)
       ? Array.from({ length: tail.length }, (_, index) => index)
       : graphemeOffsets(tail)
     known.metrics = {
       font,
       ends,
       rights: new Float64Array(ends.length).fill(-1),
       starts,
       lefts: new Float64Array(starts.length).fill(-1),
       tail: measure(tail),
       ellipsis: measure("…"),
     }
     return known.metrics
   }

   function rightOf(known: Glyphs, metrics: Metrics, index: number) {
     let right = metrics.rights[index] ?? 0
     if (right < 0) {
       right = measure(known.head.slice(0, metrics.ends[index]))
       metrics.rights[index] = right
     }
     return right
   }

   function suffixOf(known: Glyphs, metrics: Metrics, index: number) {
     let width = metrics.lefts[index] ?? 0
     if (width < 0) {
       width = measure(known.tail.slice(metrics.starts[index]))
       metrics.lefts[index] = width
     }
     return width
   }

   function glyphsOf(root: HTMLElement, text: Text) {
     const head = root.dataset.head ?? ""
     const tail = root.dataset.tail ?? ""
     let known = glyphs.get(root)
     if (!known || known.head !== head || known.tail !== tail || known.text !== text) {
       known = { head, tail, text, shown: text.data }
       glyphs.set(root, known)
     }
     return known
   }

   function lineOf(known: Glyphs, start: string, end: string): Line {
     const middle = `${known.head.slice(start.length)}${known.tail.slice(0, known.tail.length - end.length)}`
     return { text: `${start}…${end}`, cut: start.length, middle }
   }

   function shortened(root: HTMLElement, text: Text, width: number): Line | undefined {
     const known = glyphsOf(root, text)
     const font = fontOf(root)
     if (width <= 0 || !selectFont(font)) return undefined
     const metrics = metricsOf(known, font)
     const last = metrics.ends.length - 1
     if (rightOf(known, metrics, last) + metrics.tail <= width) return undefined
     const room = width - metrics.tail - metrics.ellipsis - 1
     const index = lastIndex(last + 1, (i) => rightOf(known, metrics, i) <= room)
     if (index >= 0) return lineOf(known, known.head.slice(0, metrics.ends[index]), known.tail)
     const start = known.head.slice(0, metrics.ends[0])
     const tailRoom = width - rightOf(known, metrics, 0) - metrics.ellipsis - 1
     const count = metrics.starts.length
     const dropped =
       count - 1 - lastIndex(count, (i) => suffixOf(known, metrics, count - 1 - i) <= tailRoom)
     return lineOf(known, start, known.tail.slice(metrics.starts[dropped] ?? known.tail.length))
   }

   function lastIndex(count: number, test: (index: number) => boolean) {
     let low = 0
     let high = count - 1
     let found = -1
     while (low <= high) {
       const middle = (low + high) >> 1
       if (test(middle)) {
         found = middle
         low = middle + 1
       } else {
         high = middle - 1
       }
     }
     return found
   }

   type Parts = { head: HTMLElement; tail: HTMLElement; text: Text }

   function partsOf(root: Element): Parts | undefined {
     const [head, tail] = root.children
     const text = head?.firstChild
     if (!(head instanceof HTMLElement) || !(tail instanceof HTMLElement)) return undefined
     return text instanceof Text ? { head, tail, text } : undefined
   }

   const screenReaderText = new Map<Element, HTMLSpanElement>()

   function describe(root: HTMLElement, full: string | undefined) {
     if (full === undefined) {
       screenReaderText.get(root)?.remove()
       screenReaderText.delete(root)
       return
     }
     const label = document.createElement("span")
     Object.assign(label.style, {
       position: "absolute",
       width: "1px",
       height: "1px",
       overflow: "hidden",
       clipPath: "inset(50%)",
       userSelect: "none",
       webkitUserSelect: "none",
     })
     label.textContent = full
     root.append(label)
     screenReaderText.set(root, label)
   }

   function show(root: HTMLElement, { head, tail, text }: Parts, line: Line | undefined) {
     const known = glyphs.get(root)
     const next = line?.text ?? known?.head ?? text.data
     if (text.data !== next) text.data = next
     if (known) {
       known.shown = next
       known.line = line
     }
     const cut = line !== undefined
     if (screenReaderText.has(root) === cut) return
     head.style.gridColumnEnd = cut ? "3" : ""
     head.style.textOverflow = cut ? "clip" : ""
     tail.style.display = cut ? "none" : ""
     if (cut) head.setAttribute("aria-hidden", "true")
     else head.removeAttribute("aria-hidden")
     describe(root, cut ? `${known?.head ?? ""}${known?.tail ?? ""}` : undefined)
   }

   function restore(root: HTMLElement) {
     const known = glyphs.get(root)
     const parts = partsOf(root)
     if (known && parts?.text.data === known.shown) parts.text.data = known.head
     if (parts) show(root, parts, undefined)
     glyphs.delete(root)
   }

   function covers(range: Range, text: Text, cut: number) {
     if (!range.intersectsNode(text)) return false
     const start = range.startContainer === text ? range.startOffset : 0
     const end = range.endContainer === text ? range.endOffset : text.length
     return start <= cut && end > cut
   }

   function copyWholeStrings(event: ClipboardEvent) {
     const selection = document.getSelection()
     if (event.defaultPrevented || !selection || selection.isCollapsed) return
     const ranges = Array.from({ length: selection.rangeCount }, (_, index) =>
       selection.getRangeAt(index),
     )
     const expanded: { text: Text; cut: number; middle: string }[] = []
     for (const { text, shown, line } of glyphs.values()) {
       if (!line || text.data !== shown || !ranges.some((range) => covers(range, text, line.cut))) {
         continue
       }
       text.replaceData(line.cut, 1, line.middle)
       expanded.push({ text, cut: line.cut, middle: line.middle })
     }
     if (expanded.length === 0) return
     requestAnimationFrame(() => {
       for (const { text, cut, middle } of expanded) {
         if (text.data.startsWith(middle, cut)) text.replaceData(cut, middle.length, "…")
       }
     })
   }

   const roots = new Set<HTMLElement>()
   let observer: ResizeObserver | undefined

   function remeasure() {
     for (const known of glyphs.values()) known.metrics = undefined
     for (const root of roots) {
       observer?.unobserve(root)
       observer?.observe(root)
     }
   }

   function shorten(entries: ResizeObserverEntry[]) {
     const lines = []
     for (const { target, contentRect } of entries) {
       const parts = partsOf(target)
       if (target instanceof HTMLElement && parts) {
         lines.push({ root: target, parts, line: shortened(target, parts.text, contentRect.width) })
       }
     }
     for (const { root, parts, line } of lines) show(root, parts, line)
   }

   function track(root: HTMLElement) {
     if (!observer) {
       observer = new ResizeObserver(shorten)
       document.fonts.addEventListener("loadingdone", remeasure)
       document.addEventListener("copy", copyWholeStrings)
     }
     roots.add(root)
     observer.observe(root)
     return () => {
       roots.delete(root)
       observer?.unobserve(root)
       restore(root)
     }
   }

   type MiddleTruncateProps = Omit<useRender.ComponentProps<"span">, "children"> & {
     children: string
     end?: number
     xstyle?: StyleXStyles
     style?: CSSProperties
   }

   function MiddleTruncate({
     children,
     end = 8,
     render,
     ref,
     xstyle,
     className,
     style,
     onPointerEnter,
     onMouseDown,
     ...props
   }: MiddleTruncateProps) {
     const [clipped, setClipped] = useState(false)
     const offset = tailOffset(children, end)
     const head = children.slice(0, offset)
     const tail = children.slice(offset)
     const split = tail !== ""
     const sx = stylex.props(styles.root, split && styles.split, xstyle)
     const rootRef = useRef<HTMLSpanElement>(null)

     useLayoutEffect(() => {
       const root = rootRef.current
       return root && split ? track(root) : undefined
     }, [head, tail, split])

     return useRender({
       defaultTagName: "span",
       render,
       ref: [ref ?? null, rootRef],
       props: {
         "data-slot": "middle-truncate",
         "data-head": head,
         "data-tail": split ? tail : undefined,
         title: clipped ? children : undefined,
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
         onPointerEnter: (event: PointerEvent<HTMLSpanElement>) => {
           onPointerEnter?.(event)
           setClipped(isClipped(event.currentTarget))
         },
         onMouseDown: (event: MouseEvent<HTMLSpanElement>) => {
           onMouseDown?.(event)
           if (event.detail < 3 || event.defaultPrevented) return
           event.preventDefault()
           window.getSelection()?.selectAllChildren(event.currentTarget)
         },
         children: (
           <>
             <span {...stylex.props(styles.head)}>{head}</span>
             {split && <span {...stylex.props(styles.tail)}>{tail}</span>}
           </>
         ),
       },
     })
   }

   export { MiddleTruncate, type MiddleTruncateProps }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { MiddleTruncate } from "@/components/ui/middle-truncate"
```

```tsx
<MiddleTruncate>packages/ui/src/base/navigation-menu.tsx</MiddleTruncate>
```

The component is as wide as its text until its container is narrower. Then the
start of the string gives way and the end stays. Constrain it as you would an
element with `text-overflow: ellipsis`. Give its parent a width, or
`min-width: 0` when the parent is a flex item.

It sets no font, size or colour. Put it inside [Text](https://www.arene.style/docs/components/text) or
pass `xstyle`. It inherits `text-decoration` from its parent element, so it is
underlined when it is a link or sits directly inside one.

> **Note**
>
> `children` is one string. The component splits it into two parts, so it cannot
> take elements.

> **Warning**
>
> Do not stretch the component with a width or `flex-grow`. A root wider than its
> text opens a gap at the cut. Stretch its parent instead.

## End

`end` is the number of characters kept after the ellipsis. It defaults to 8,
which covers a file extension or the last digits of a hash.

```tsx
import * as stylex from "@stylexjs/stylex"
import { MiddleTruncate } from "@/components/ui/middle-truncate"
import { HStack, VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import { font, space } from "@/theme/tokens.stylex"
import { widths } from "@/theme/widths"

const styles = stylex.create({
  label: {
    flexShrink: 0,
    width: space.s16,
  },
  value: {
    flexGrow: 1,
    flexBasis: 0,
    minWidth: 0,
    fontFamily: font.mono,
  },
})

const commit = "6c37f5ec0c866624c17f543c65805bce4a8b67dc"

export default function MiddleTruncateEnd() {
  return (
    <VStack gap={3} xstyle={widths.xs}>
      {[4, 8, 16].map((end) => (
        <HStack key={end} gap={3} align="center">
          <Text size="xs" tone="muted" xstyle={styles.label}>
            end={end}
          </Text>
          <Text size="sm" xstyle={styles.value}>
            <MiddleTruncate end={end}>{commit}</MiddleTruncate>
          </Text>
        </HStack>
      ))}
    </VStack>
  )
}
```

## How it cuts

CSS cuts the string in the prerendered HTML, so it is already short before any
script runs. The browser draws that ellipsis, and up to one character of space
can sit after it. Below the width of the end plus `2em`, the end is clipped at
its own start.

After hydration, one observer shared by every instance rewrites the visible
text as the start, an ellipsis and the end, on one line, whenever an instance
changes width. It measures each string once, on a canvas in the element's font.
In a container too narrow for the end, an ellipsis and one character, it keeps
the first character and shortens the end from its start.

The end never takes the first eight characters. A string shorter than `end`
plus eight keeps a shorter end, and a string of eight characters or fewer is cut
at its end like any ellipsis.

## Copying and the title

Copying a selection gives the whole string. For the copy, the component puts the
hidden middle back in place of the ellipsis, then restores it before the next
frame. Dragging the selection elsewhere, or a script that reads it, gets the
text on screen, ellipsis included. Screen readers read the whole string, and a
triple click selects all of it.

When the pointer enters a string that is cut, the component sets `title` to the
full string. Pass your own `title` to replace it.

## API reference

Pass `render` to replace the element or compose it with another component.

The component renders a `span` through Base UI's
[`useRender`](https://base-ui.com/react/utils/use-render), and takes `xstyle`,
`className` and inline `style` alongside every `span` attribute.

### MiddleTruncate

| Prop        | Type                                               | Default    |
| ----------- | -------------------------------------------------- | ---------- |
| `children`  | `string`                                           | —          |
| `end`       | `number`                                           | `8`        |
| `render`    | `ReactElement \| ((props, state) => ReactElement)` | `<span />` |
| `xstyle`    | `StyleXStyles`                                     | —          |
| `className` | `string`                                           | —          |

### Data attributes

| Attribute                     | On       | Effect                              |
| ----------------------------- | -------- | ----------------------------------- |
| `data-slot="middle-truncate"` | the root | Targets the component from a parent |
| `data-head`                   | the root | The text before the ellipsis        |
| `data-tail`                   | the root | The text after the ellipsis         |
