# Row Autosize
URL: https://pro.rv-grid.com/api/row-autosize/
Source: src/content/docs/api/row-autosize.md
## Module Extensions

### `HTMLRevoGridElement` (Extended from `global`)

```ts
interface HTMLRevoGridElement {
  /**
       * Direct row auto-size configuration.
       */
      rowAutoSize?: RowAutoSizeConfig;
  /**
       * Template-friendly alias for `rowAutoSize`.
       */
      'row-auto-size'?: RowAutoSizeConfig
}
```

---

### `HTMLRevoGridElementEventMap` (Extended from `global`)

```ts
interface HTMLRevoGridElementEventMap {
  /**
       * Event triggered when the row auto size is updated
       *
       * @example
       * ```typescript
       * grid.addEventListener(ROW_AUTO_SIZE_CONFIG_UPDATE_EVENT, (e) => {
       *   console.log(e);
       * });
       */
      [ROW_AUTO_SIZE_CONFIG_UPDATE_EVENT]: RowAutoSizeConfig
}
```

---

### `AdditionalData` (Extended from `@revolist/revogrid`)

```ts
interface AdditionalData {
  /**
       * Additional data property for row auto size
       * @deprecated Use `grid.rowAutoSize` instead.
       */
      rowAutoSize?: RowAutoSizeConfig
}
```

## Plugin API

### `RowAutoSizePlugin`

The RowAutoSizePlugin enables dynamic row height calculation based on cell content.
It efficiently manages row heights by calculating them before rendering and updating
the grid's dimension store accordingly.

**Key Features**:
- Pre-calculates row heights based on cell content
- Supports dynamic content updates
- Efficient caching mechanism for calculated heights
- Configurable minimum and maximum row heights
- Support for both sync and async height calculations

Usage Example:
```typescript
import { RowAutoSizePlugin } from './row-autosize';

const grid = document.createElement('revo-grid');
grid.plugins = [RowAutoSizePlugin];

grid.rowAutoSize = {
  minHeight: 24,
  maxHeight: 200,
  // Optional: Custom height calculator
  calculateHeight: (rowData, columns) => {
    // Custom logic to calculate row height
    return 50;
  }
};
```

#### Dependencies

- **Config integration** `additionalData.rowAutoSize`: Reads legacy row auto-size configuration from additionalData.rowAutoSize.

```ts
class RowAutoSizePlugin {
  destroy(): void;
}
```

---

### `DEFAULT_MIN_HEIGHT`

Default lower bound for automatically calculated row heights.

Used when no `rowAutoSize.minHeight` is configured and as the fallback height
for approximate or unavailable measurements.

```ts
DEFAULT_MIN_HEIGHT: 24;
```

---

### `DEFAULT_MAX_HEIGHT`

Default upper bound for automatically calculated row heights.

Used when no `rowAutoSize.maxHeight` is configured.

```ts
DEFAULT_MAX_HEIGHT: 200;
```

---

### `CALCULATION_DEBOUNCE`

Debounce interval, in milliseconds, for viewport-triggered recalculations.

```ts
CALCULATION_DEBOUNCE: 10;
```

---

### `PRECALCULATE_ROWS_BATCH_SIZE`

Number of non-precise rows to pre-calculate per frame.

Approximate row sizing is CPU-only, so processing all rows at once can block
initial render or column resize on large datasets. Batching keeps the UI
responsive while still warming the cache ahead of scroll.

```ts
PRECALCULATE_ROWS_BATCH_SIZE: 500;
```

---

### `AUTO_SIZE_CLASS`

Host class applied to grids that have `RowAutoSizePlugin` installed.

The plugin stylesheet scopes row wrapping and measurement styles under this
class so the visual change is opt-in per grid instance.

```ts
AUTO_SIZE_CLASS: string;
```

---

### `CALCULATION_CLASS`

Class for the hidden DOM element used to measure precise wrapped content.

Static layout and wrapping styles for this element live in
`row-autosize.style.scss`; runtime code only sets dynamic width and copied
text metrics.

```ts
CALCULATION_CLASS: string;
```

---

### `MEASURED_CELL_STYLE_PROPS`

Computed style properties copied from a rendered cell to the hidden
measurement element before precise measurement.

Keep this list focused on properties that affect text flow, padding, and
measured content height. Structural measurement styles belong in SCSS.

```ts
MEASURED_CELL_STYLE_PROPS: readonly ["boxSizing", "font", "fontFamily", "fontSize", "fontStyle", "fontWeight", "letterSpacing", "lineHeight", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", "textIndent", "textTransform", "textWrap", "whiteSpace", "wordBreak", "overflowWrap"];
```

---

### `RowAutoSizeMeasurer`

Manages the hidden measurement element used by `RowAutoSizePlugin`.

The measurer owns DOM setup/teardown for precise row sizing. It does not
decide which rows or columns should be measured; callers provide row/column
coordinates and an effective column width. Static styles are supplied by
`row-autosize.style.scss`, while dynamic width and copied text metrics are
applied inline for each measurement.

```ts
class RowAutoSizeMeasurer {
  /**
     * Create or remove the hidden calculation element to match precise sizing.
     *
     * @param enabled - Whether precise DOM measurement should be available.
     */
  sync(enabled: boolean);

  /**
     * Measure an already-rendered grid cell by cloning its child nodes into the
     * hidden calculation element.
     *
     * This is the most accurate path because it inherits rendered cell content,
     * nested markup, and computed text metrics. Returns `null` when the target
     * cell is not currently rendered or the measurement element is not available.
     *
     * @param rowIndex - Source row index rendered in the viewport.
     * @param colIndex - Visual column index within the column type.
     * @param colType - RevoGrid column region.
     * @param columnWidth - Fallback width used when the rendered cell has no
     * measurable layout width.
     * @returns Measured content height in pixels, or `null` when the rendered cell
     * cannot be measured.
     */
  measureRenderedCellContentHeight(;

  /**
     * Measure plain text using the hidden calculation element.
     *
     * This is the precise fallback used when a cell is not rendered but the plugin
     * still has content and column width available.
     *
     * @param content - Text content to measure.
     * @param columnWidth - Width in pixels to apply before measuring.
     * @returns Measured content height in pixels, or the default minimum height
     * when the calculation element is unavailable.
     */
  measureTextContentHeight(content: string, columnWidth: number): number;

  /**
     * Remove the hidden calculation element and release DOM references.
     */
  destroy();
}
```

---

### `RowAutoSizeCalculationState`

Tracks row height calculation cache, in-flight calculations, and invalidation
versions for `RowAutoSizePlugin`.

The version token protects against async races: callers capture the version
before starting a calculation and compare it again before writing the result.
Any row invalidation or full reset changes the token and makes stale
calculations harmless.

```ts
class RowAutoSizeCalculationState {
  /**
     * Get a cached calculated height for a source row.
     *
     * @param rowIndex - Source row index.
     * @returns Cached height, or `undefined` when the row needs calculation.
     */
  getCached(rowIndex: number): number | undefined;

  /**
     * Store the calculated height for a source row.
     *
     * @param rowIndex - Source row index.
     * @param height - Clamped row height in pixels.
     */
  setCached(rowIndex: number, height: number);

  /**
     * Check whether a row already has an active calculation.
     *
     * @param rowIndex - Source row index.
     * @returns `true` when calculation is in flight.
     */
  isPending(rowIndex: number): boolean;

  /**
     * Mark a source row as currently being calculated.
     *
     * @param rowIndex - Source row index.
     */
  markPending(rowIndex: number);

  /**
     * Clear the in-flight marker for a source row.
     *
     * @param rowIndex - Source row index.
     */
  clearPending(rowIndex: number);

  /**
     * Invalidate specific rows after content, width, or rendered DOM changes.
     *
     * Cached heights and pending markers are removed, and each row version is
     * incremented so older async calculations cannot write stale heights.
     *
     * @param rowIndexes - Source row indexes to invalidate.
     */
  invalidateRows(rowIndexes: number[]);

  /**
     * Clear all row state and advance the global calculation epoch.
     *
     * Use when source data, config, or column sizing changes invalidate every
     * cached height.
     */
  reset();

  /**
     * Clear all row state without advancing the epoch.
     *
     * Intended for plugin teardown when no future calculation result should be
     * observed.
     */
  clear();

  /**
     * Return a stable version token for the current row calculation state.
     *
     * Callers should capture this value before starting async work and compare it
     * with a fresh value before committing the result.
     *
     * @param rowIndex - Source row index.
     * @returns Token containing the global epoch and row-specific version.
     */
  getVersion(rowIndex: number): string;
}
```

---

### `RowAutoSizeConfig`

```ts
export type RowAutoSizeConfig = {
  /**
   * Minimum row height in pixels
   * @default 24
   */
  minHeight?: number;

  /**
   * Maximum row height in pixels
   * @default 200
   */
  maxHeight?: number;

  /**
   * Custom height calculator function
   * If provided, will be used instead of the default calculator
   */
  calculateHeight?: (
    rowData: DataType,
    columns: ColumnRegular[],
  ) => number | Promise<number>;

  /**
   * Whether to warm row height cache for all rows in non-precise mode.
   *
   * Enabled by default and processed in chunks to avoid blocking large grids.
   * Disable to calculate only visible rows and preserve the older demand-driven
   * behavior.
   *
   * @default true
   */
  precalculate?: boolean;

  /**
   * Number of non-precise rows to pre-calculate per animation frame.
   *
   * Larger values warm the cache faster but can make each frame heavier. Values
   * lower than 1 fall back to the default batch size.
   *
   * @default 500
   */
  precalculateBatchSize?: number;
};
```

---

### `clampRowHeight`

Clamp a measured or custom row height to the active row auto-size bounds.

**@param** height - Raw height calculated by the plugin or supplied by
 * `rowAutoSize.calculateHeight`.
 *
**@param** config - Active row auto-size configuration.
 *
**@returns** Height constrained by configured or default min/max limits.

```ts
export function clampRowHeight(height: number, config: RowAutoSizeConfig): number;
```

---

### `calculateApproximateContentHeight`

Estimate wrapped text height without reading rendered cell DOM.

This path is used when precise measurement is disabled or unavailable. It is
intentionally simple and deterministic: text is split by line breaks, each
line is wrapped using an approximate character width, and the result is
converted to pixels with a fixed approximate line height.

**@param** content - Cell text content.
 *
**@param** columnWidth - Effective column width in pixels.
 *
**@returns** Estimated content height in pixels, never lower than the default
 * minimum row height.

```ts
export function calculateApproximateContentHeight(content: string, columnWidth: number): number;
```

---

### `getEditedRowIndexes`

Resolve affected source row indexes from RevoGrid edit events.

Supports both single-cell edits and range edits so callers can invalidate and
recalculate only rows whose content changed.

**@param** event - `afteredit` detail for a single edit or range edit.
 *
**@returns** Source row indexes that need recalculation.

```ts
export function getEditedRowIndexes(
  event: BeforeSaveDataDetails | BeforeRangeSaveDataDetails,
): number[];
```
