# How It Works

Learn how `@re-dev/react-truncate` measures text across rendering paths, handles responsive updates, and performs on real-browser benchmarks.

Source: https://truncate.js.org/guides/how-it-works/

Different truncation scenarios require different trade-offs: plain Latin text can be measured quickly in memory with Canvas, CJK text needs browser line-breaking rules, rich text must preserve inline DOM nodes, and tag groups need indivisible items. `@re-dev/react-truncate` picks the lightest measurement path that fits the current component and props.

## Measurement Paths

| Path                 | Engine                   | Best For                                          |
| -------------------- | ------------------------ | ------------------------------------------------- |
| Plain text (default) | Canvas `measureText`     | Latin / English text, or `separator=""`           |
| CJK / `break-all`    | Browser DOM wrap         | CJK mixed text (default), `word-break: break-all` |
| `preserveMarkup`     | Inline DOM binary search | Collapsed inline links and styles (opt-in)        |
| `TruncateGroup`      | Item box binary search   | Indivisible tags, avatars, buttons                |

## How Each Path Works

### Plain Text

When the content has no CJK characters, `preserveMarkup` is off, and `word-break: break-all` is not applied, `<Truncate />` (along with `<ShowMore />` and `<MiddleTruncate />`) reads the container content width once, syncs the computed font and `letter-spacing` to an offscreen Canvas context, and computes line breaks in memory via `canvas.measureText()` before committing a single render.

If CSS properties that Canvas cannot reproduce are active (such as `text-transform`, custom `word-spacing`, or `font-variant`), or if Canvas is unavailable in the environment, the component automatically falls back to a hidden DOM measurer without extra configuration.

### CJK & `break-all`

Chinese, Japanese, and Korean text follow browser-native line-breaking and punctuation rules that simple space splitting cannot match accurately. Starting from `v0.7.0`, when using the default `separator=" "` with CJK characters—or when `word-break: break-all` is set—the component routes through `browser-text` to measure against real browser wrapping.

For large CJK lists where minimizing reflow matters more than native CJK punctuation rules, passing `separator=""` bypasses `browser-text` and stays on the pure Canvas path (see the benchmark numbers below).

### Inline Markup

`preserveMarkup` is opt-in by design. When enabled, the component clones the rendered inline DOM into a hidden measurement container and binary-searches by line height so links, classes, and inline styles remain intact in the collapsed state. Enable it only when collapsed output needs live inline markup.

### Item Groups

`<TruncateGroup />` (added in `v0.7.0`) measures the bounding boxes (`getBoundingClientRect`) of its direct children and binary-searches for the longest prefix that fits within `lines` rows, rendering `+N` or a custom `ellipsis` for the rest. Because it operates on whole items, layout recalculations stay much lower than character-level DOM measurement.

### Resize & Fonts

Starting from `v0.7.0`, container resizes and web font updates are handled automatically:

* **Container resizing**: Uses `ResizeObserver` on the parent element (covering resizable panels and hidden-to-visible transitions) with `flushSync` so re-measurement finishes before paint without multi-line flicker. Environments without `ResizeObserver` fall back to `window.resize`.
* **Web font loading**: Listens to `document.fonts.ready` and `loadingdone`, recalculating automatically once fonts settle even when container width does not change.

## Performance Baseline

The numbers below come from the repository's real-browser benchmark suite (located in `bench/`, reproducible locally with `pnpm bench`), comparing internal paths alongside native CSS `-webkit-line-clamp` as a browser baseline.

**Test Environment**

* **OS & Hardware**: macOS (Darwin 27.3.0, arm64), Apple M3 Max (14 logical cores)
* **Runtime & Browser**: Node v22.19.0, Playwright Chromium 145.0.7632.6 (headless), viewport `1440 × 900`
* **Sampling**: 2 warm-up rounds + 10 recorded rounds per scenario; continuous resize runs 50 steps from `640px` to `320px` per round (500 pooled step samples)

### First Mount

100 cards, in ms:

| Scenario (100 items)              |  Wall P50 / P95 |   CPU P50 / P95 | Layout / Style |
| --------------------------------- | --------------: | --------------: | -------------: |
| CSS `-webkit-line-clamp`          |   31.90 / 33.00 |   11.37 / 25.23 |              1 |
| `Truncate` (English, Canvas)      |   58.00 / 90.70 |   59.10 / 94.07 |            101 |
| `Truncate` (CJK + `separator=""`) | 115.30 / 149.80 | 113.61 / 148.56 |            101 |
| `TruncateGroup` (12 tags / card)  |  90.40 / 189.90 |  83.01 / 183.37 |             12 |
| `Truncate` (CJK default, DOM)     | 298.10 / 340.30 | 289.34 / 339.44 |           2500 |
| `Truncate` (`preserveMarkup`)     | 340.40 / 396.80 | 347.99 / 397.85 |           2500 |

Note: `LayoutCount` and `RecalcStyleCount` were identical across all six scenarios and are shown together as `Layout / Style`.

### Container Resize

20 cards resized across 50 steps, in ms per step:

| Scenario (20 items)               | Wall P50 / P95 | CPU P50 / P95 |
| --------------------------------- | -------------: | ------------: |
| CSS `-webkit-line-clamp`          |  16.70 / 18.00 |   1.49 / 1.73 |
| `Truncate` (English, Canvas)      |  16.70 / 17.60 |   6.56 / 7.12 |
| `Truncate` (CJK + `separator=""`) |  16.70 / 17.60 |   8.59 / 8.96 |
| `TruncateGroup` (12 tags / card)  |  16.70 / 25.10 | 12.25 / 12.67 |
| `Truncate` (CJK default, DOM)     |  16.70 / 22.20 | 14.33 / 15.07 |
| `Truncate` (`preserveMarkup`)     |  25.00 / 33.50 | 22.27 / 25.12 |

### Bundle Size

| Output File            |       Raw |     Gzip |
| ---------------------- | --------: | -------: |
| `dist/index.mjs` (ESM) | 17.85 KiB | 6.54 KiB |
| `dist/index.cjs` (CJS) | 18.97 KiB | 6.80 KiB |
| `dist/index.js` (IIFE) | 18.97 KiB | 6.84 KiB |

Zero runtime dependencies (`dependencies` is empty); only `react` and `react-dom` are declared as peer dependencies.

## Practical Guidance

* **Static multi-line clamping**: If you do not need expand/collapse controls, custom ellipsis elements, middle truncation, or `onTruncate` callbacks, native CSS `-webkit-line-clamp` remains the lightest option.
* **Large English / Latin feeds**: The default Canvas path performs roughly 1 layout read per card on mount and stays at 60fps during 20-card continuous resize (6.56ms CPU per step).
* **Large CJK feeds**: Pair long lists with virtualization so only visible cards mount; if native CJK punctuation rules are optional, passing `separator=""` reduces 100-card `LayoutCount` from 2500 to 101.
* **Rich text and tag groups**: Enable `preserveMarkup` only when collapsed output needs live inline markup, and use `<TruncateGroup />` for indivisible tags, avatars, or buttons.
