"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 }