Primitives
Truncate
Clamps text to N lines and shows a tooltip with the full value — but only when actually truncated.
Motiontooltip scale-in (shared Tooltip)
Install
Install Kineto and follow the theme setup once in your app.
bash
npm install kinetotsx
import { Truncate } from "kineto/truncate";Preview
This is a long single line that will clip and reveal a tooltip on hover
Short — no tooltip
tsx
"use client";
import * as React from "react";
import { cn } from "@/lib/cn";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
export interface TruncateProps extends React.HTMLAttributes<HTMLSpanElement> {
/** Number of lines before clamping. 1 = single-line ellipsis. */
lines?: number;
/** Tooltip content shown only when the text is actually clipped. Defaults to `children`. */
tooltip?: React.ReactNode;
}
/**
* Clamp text to `lines` and reveal the full value in a tooltip — but ONLY when it's genuinely
* truncated. It measures overflow (and re-measures on resize), so a label that happens to fit never
* gets a pointless tooltip. The common "title attribute on everything" anti-pattern, done right.
*/
const Truncate = React.forwardRef<HTMLSpanElement, TruncateProps>(
({ className, lines = 1, tooltip, children, style, ...props }, ref) => {
const innerRef = React.useRef<HTMLSpanElement>(null);
const [truncated, setTruncated] = React.useState(false);
React.useEffect(() => {
const el = innerRef.current;
if (!el) return;
const measure = () => {
// A 1px fudge avoids sub-pixel rounding flapping the tooltip on/off.
const overflowing =
lines === 1
? el.scrollWidth > el.clientWidth + 1
: el.scrollHeight > el.clientHeight + 1;
setTruncated(overflowing);
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, [children, lines]);
const clampStyle: React.CSSProperties =
lines === 1
? style ?? {}
: {
display: "-webkit-box",
WebkitBoxOrient: "vertical",
WebkitLineClamp: lines,
overflow: "hidden",
...style,
};
const text = (
<span
ref={mergeRefs(ref, innerRef)}
className={cn(lines === 1 && "block truncate", "min-w-0", className)}
style={clampStyle}
{...props}
>
{children}
</span>
);
if (!truncated) return text;
return (
<Tooltip>
<TooltipTrigger asChild>{text}</TooltipTrigger>
<TooltipContent>{tooltip ?? children}</TooltipContent>
</Tooltip>
);
}
);
Truncate.displayName = "Truncate";
/** Compose the forwarded ref with our measuring ref. */
function mergeRefs<T>(...refs: (React.Ref<T> | undefined)[]): React.RefCallback<T> {
return (node) => {
for (const ref of refs) {
if (typeof ref === "function") ref(node);
else if (ref) (ref as React.MutableRefObject<T | null>).current = node;
}
};
}
export { Truncate };src/components/ui/truncate.tsx
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| lines | number | 1 | Lines before clamping (1 = single-line ellipsis). |
| tooltip | ReactNode | — | Tooltip content when clipped; defaults to children. |