Middle Truncation

New

Canvas-measured binary search text truncation preserving the start and end of strings with responsive resize sync.

$ pnpm dlx shadcn@latest add @byphongphan/middle-truncation
Requires @byphongphan in components.json
text
Loading preview...

Installation

Install the following dependencies:

$ pnpm add clsx tailwind-merge
Requires @byphongphan in components.json

Copy and paste the component into your project.

components/ui/middle-truncation.tsx

Update the import paths to match your project setup.

Usage

import { MiddleTruncation } from "@/components/ui/middle-truncation"
export function Example() { return ( <div className="w-64"> {/* Preserves 8 characters at the end (e.g. extension) */} <MiddleTruncation end={8}> very-long-project-name-production-deployment-v2.final.tsx </MiddleTruncation>
{/* Balanced split preserving at least 6 characters at the end */} <MiddleTruncation minEnd={6} ellipsis="···"> 0x71C6633279268a2F7c09361730a8435d8eFEb947 </MiddleTruncation> </div> )}

Features

  • Binary Search Algorithm: Uses sub-millisecond binary search to compute the exact truncation cutoff in $O(\log N)$ time.
  • Canvas 2D Measurement: Accurately measures text width matching computed CSS font styling without DOM reflows.
  • ResizeObserver with RAF Debouncing: Syncs layout adjustments directly with the browser's paint cycle for jank-free responsiveness.
  • SSR Safe: Gracefully handles server-side environments with fallback measurement and isomorphic layout effects.

Examples

Resizable Card Sandbox

Drag the vertical handle on the right edge to see real-time binary-search truncation recalculations:

<MiddleTruncation>/Users/ncdai/Code/chanhdai/src/components/ui/button.tsx
<MiddleTruncation end=4>FY26_Q1_Consolidated_Financial_Statements.pdf
<MiddleTruncation minEnd=12>/Users/ncdai/Code/chanhdai/node_modules/shadcn/package.json
<MiddleTruncation ellipsis=" ... ">https://www.apple.com/newsroom/2026/01/FY26_Q1_Consolidated_Financial_Statements.pdf

File Extension Truncation

Preserves the tail of a long filename so users can always identify the file format and extension:

Asset Filename
quarterly-financial-report-q4-verified-signed-2026.pdf

Crypto Address / Hash Truncation

Truncates Ethereum addresses or commit hashes with a custom minimalist ellipsis separator:

Ethereum Wallet
0x71C6633279268a2F7c09361730a8435d8eFEb947

Balanced Split with Min End

Maintains an even middle split while enforcing a minimum guaranteed suffix length:

Balanced Split (minEnd=12)
src/features/authentication/providers/oauth-google-provider-v2.tsx

Command Palette

Quick search and commands navigation