Middle Truncate

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

  • Filepackages/ui/src/base/navigation-menu.tsx
  • Branchfeat/middle-truncate-without-a-measuring-script
  • Commit6c37f5ec0c866624c17f543c65805bce4a8b67dc
  • Registryhttps://www.arene.style/r/middle-truncate.json
  • Preset@arene/typescript-config/react-library.json
  • Docswww.arene.style/docs/components/middle-truncate
  • Stylesheetnode_modules/@arene/ui/interop.css
  • Fitsbutton.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

pnpm dlx shadcn@latest add @arene/middle-truncate

Needs the arene setup first.

Usage

import { MiddleTruncate } from "@/components/ui/middle-truncate"
<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 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.

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

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.

end=46c37f5ec0c866624c17f543c65805bce4a8b67dc
end=86c37f5ec0c866624c17f543c65805bce4a8b67dc
end=166c37f5ec0c866624c17f543c65805bce4a8b67dc
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, and takes xstyle, className and inline style alongside every span attribute.

MiddleTruncate

PropTypeDefault
childrenstring—
endnumber8
renderReactElement | ((props, state) => ReactElement)<span />
xstyleStyleXStyles—
classNamestring—

Data attributes

AttributeOnEffect
data-slot="middle-truncate"the rootTargets the component from a parent
data-headthe rootThe text before the ellipsis
data-tailthe rootThe text after the ellipsis