# Migration tool

> Convert AG Grid and MUI X Data Grid code to Birch UI Grid with the birchui-migrate codemod, or paste a configuration into the playground and see the result live.

`@birchui/migrate` converts AG Grid and MUI X Data Grid code to Birch UI Grid. The `birchui-migrate` command rewrites whole projects in React, Vue, Angular and plain JavaScript or TypeScript, and the same converters run in the browser below. Every mapping follows the [AG Grid](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md) and [MUI X](https://docs.birchui.com/getting-started/migrating-from-mui-x.md) migration guides.

## Playground

Paste AG Grid `columnDefs` or `gridOptions`, or MUI X `columns` and props, as JSON or as a JavaScript object literal. The playground shows the converted configuration, the notes for anything that needs your attention, and a live grid with sample rows generated from the column fields.

**Live demo: Migration playground** (runs on the HTML version of this page). Source of `demos/migration-tool.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import {
  createGrid,
  type ColumnDef,
  type GridApi,
  type GridModule,
  type GridOptions,
  type RowData,
} from '@birchui/core';
import {
  AggregationModule,
  ClipboardModule,
  ExcelModule,
  FillHandleModule,
  MasterDetailModule,
  PivotModule,
  RangeSelectionModule,
  RowGroupingModule,
  StatusBarModule,
  TreeDataModule,
} from '@birchui/grid-pro';
import {
  convertSnippet,
  stripCode,
  type MigrationSource,
  type MigrationWarning,
  type SnippetConversion,
} from '@birchui/migrate';
import { button, docsTheme, field, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Migration playground', height: 780 };

interface Sample {
  id: string;
  label: string;
  from: MigrationSource;
  source: string;
}

const SAMPLES: Sample[] = [
  {
    id: 'orders',
    label: 'AG Grid: orders with grouping',
    from: 'ag-grid',
    source: `const gridOptions = {
  columnDefs: [
    { field: 'region', rowGroup: true, hide: true },
    { field: 'orderId', headerName: 'Order', width: 120, pinned: 'left' },
    { field: 'customer', filter: 'agTextColumnFilter', flex: 1, minWidth: 180 },
    { field: 'product', filter: 'agSetColumnFilter' },
    { field: 'quantity', headerName: 'Qty', type: 'numericColumn', aggFunc: 'sum', editable: true },
    { field: 'revenue', type: 'numericColumn', aggFunc: 'sum', valueFormatter: (params) => usd.format(params.value) },
    { field: 'orderDate', headerName: 'Ordered', cellDataType: 'dateString', sort: 'desc' },
    { field: 'status', cellRenderer: StatusBadge },
  ],
  defaultColDef: { sortable: true, resizable: true, floatingFilter: true },
  autoGroupColumnDef: { headerName: 'Region', minWidth: 200 },
  groupDefaultExpanded: 1,
  rowSelection: { mode: 'multiRow', checkboxes: true },
  cellSelection: true,
  statusBar: { statusPanels: [{ statusPanel: 'agAggregationComponent' }] },
  sideBar: true,
  onCellValueChanged: (event) => saveOrder(event.data),
};`,
  },
  {
    id: 'crm',
    label: 'AG Grid: CRM master/detail',
    from: 'ag-grid',
    source: `const gridOptions = {
  columnDefs: [
    { field: 'name', cellRenderer: 'agGroupCellRenderer' },
    { field: 'account' },
    { field: 'calls', type: 'numericColumn' },
    { field: 'minutes', valueFormatter: "x.toLocaleString() + 'm'" },
  ],
  defaultColDef: { flex: 1 },
  masterDetail: true,
  detailRowHeight: 240,
  detailCellRendererParams: {
    detailGridOptions: {
      columnDefs: [{ field: 'callId' }, { field: 'direction' }, { field: 'number' }, { field: 'duration' }],
      defaultColDef: { flex: 1 },
    },
    getDetailRowData: (params) => params.successCallback(params.data.callRecords),
  },
};`,
  },
  {
    id: 'mui',
    label: 'MUI X: DataGridPremium with aggregation',
    from: 'mui',
    source: `const columns = [
  { field: 'region', headerName: 'Region', width: 140 },
  { field: 'rep', headerName: 'Sales rep', flex: 1 },
  { field: 'closedAt', headerName: 'Closed', type: 'date' },
  { field: 'units', headerName: 'Units', type: 'number' },
  { field: 'revenue', headerName: 'Revenue', type: 'number', valueFormatter: (value) => currency.format(value) },
  { field: 'stage', type: 'singleSelect', valueOptions: ['Won', 'Lost', 'Pending'], renderCell: (params) => <Chip label={params.value} /> },
];

const props = {
  rows: sales,
  columns,
  checkboxSelection: true,
  rowGroupingModel: ['region'],
  aggregationModel: { units: 'sum', revenue: 'sum' },
  initialState: { pinnedColumns: { left: ['rep'] } },
  pagination: true,
};`,
  },
];

const PRO_MODULES: Record<string, GridModule> = {
  AggregationModule,
  ClipboardModule,
  ExcelModule,
  FillHandleModule,
  MasterDetailModule,
  PivotModule,
  RangeSelectionModule,
  RowGroupingModule,
  StatusBarModule,
  TreeDataModule,
};

const COMPANIES = [
  'Northwind Traders',
  'Blue Harbor Foods',
  'Alpine Outfitters',
  'Kestrel Logistics',
  'Maison Duval',
  'Sakura Retail Group',
];
const PEOPLE = ['Amelia Hart', 'Jonas Becker', 'Priya Natarajan', 'Diego Alvarez', 'Hana Sato', 'Liam O’Connor'];
const PRODUCTS = ['Standing desk', 'Ergonomic chair', 'Monitor arm', '27" 4K monitor', 'USB-C dock', 'Desk lamp'];
const COUNTRIES = ['United States', 'Germany', 'France', 'Japan', 'Brazil', 'Canada'];
const REGIONS = ['North America', 'Europe', 'Asia Pacific', 'Latin America'];
const STATUSES = ['Open', 'Shipped', 'Delivered', 'Cancelled'];

const PANEL =
  'display:flex;flex-direction:column;min-width:0;min-height:0;border:1px solid var(--line);border-radius:8px;background:var(--bg);overflow:hidden';
const PANEL_TITLE =
  'margin:0;padding:6px 10px;font-size:12px;font-weight:600;color:var(--muted);border-bottom:1px solid var(--line)';
const MONO =
  'font-family:var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);font-size:12px;line-height:1.5';

function panel(title: string): { root: HTMLElement; content: HTMLElement } {
  const root = document.createElement('section');
  root.style.cssText = PANEL;
  const heading = document.createElement('h3');
  heading.style.cssText = PANEL_TITLE;
  heading.textContent = title;
  const content = document.createElement('div');
  content.style.cssText = 'flex:1;min-height:0;position:relative;overflow:auto';
  root.append(heading, content);
  return { root, content };
}

function leafColumns(columns: unknown[]): ColumnDef[] {
  return columns.flatMap((column) => {
    const children = (column as { children?: unknown[] }).children;
    return Array.isArray(children) ? leafColumns(children) : [column as ColumnDef];
  });
}

function sampleValue(column: ColumnDef, index: number, random: () => number): unknown {
  const pick = <T>(list: readonly T[]): T => list[Math.floor(random() * list.length)];
  const name = (column.field ?? column.id ?? '').toString();
  const key = name.toLowerCase();
  const options = column.options;
  if (Array.isArray(options) && options.length) {
    const option = pick(options);
    return typeof option === 'object' && option !== null ? (option as { value: unknown }).value : option;
  }
  if (column.type === 'boolean' || /^(is|has)[A-Z]|active|shipped|paid|discontinued/.test(name)) return random() < 0.5;
  if (column.type === 'date' || /date|time|day/.test(key) || /[a-z](At|On)$/.test(name))
    return new Date(Date.UTC(2026, 0, 1) + Math.floor(random() * 330) * 86_400_000).toISOString().slice(0, 10);
  if (/^id$|orderid|number|no$|code|sku|tracking|callid/.test(key))
    return `${name.slice(0, 3).toUpperCase()}-${10001 + index}`;
  if (/email/.test(key)) return `${pick(PEOPLE).split(' ')[0].toLowerCase()}@example.com`;
  if (/country/.test(key)) return pick(COUNTRIES);
  if (/region/.test(key)) return pick(REGIONS);
  if (/customer|company|account|client/.test(key)) return pick(COMPANIES);
  if (/name|rep|owner|agent|manager/.test(key)) return pick(PEOPLE);
  if (/product|item/.test(key)) return pick(PRODUCTS);
  if (/status|stage/.test(key)) return pick(STATUSES);
  if (/direction/.test(key)) return pick(['In', 'Out']);
  if (/qty|quantity|units|count|calls|stock|minutes|duration/.test(key)) return 1 + Math.floor(random() * 40);
  if (column.type === 'number' || /price|total|amount|revenue|cost|sales|value|balance/.test(key))
    return Math.round(random() * 500000) / 100;
  return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${index + 1}`;
}

function sampleRows(columns: ColumnDef[], count: number): RowData[] {
  const random = seededRandom(42);
  return Array.from({ length: count }, (_, index) => {
    const row: RowData = { __rowId: `row-${index}` };
    for (const column of columns) if (column.field) row[column.field] = sampleValue(column, index, random);
    return row;
  });
}

function previewOptions(result: SnippetConversion): GridOptions | null {
  const value = stripCode(result.value);
  const options = (result.kind === 'columns' ? { columns: Array.isArray(value) ? value : [value] } : value) as Record<
    string,
    unknown
  >;
  if (!options || !Array.isArray(options.columns)) return null;
  const columns = leafColumns(options.columns).filter((column) => column.field || column.id);
  if (!columns.length) return null;
  const preview: Record<string, unknown> = { ...options };
  for (const key of [
    'rows',
    'getRowId',
    'rowModel',
    'datasource',
    'licenseKey',
    'modules',
    'theme',
    'rowHeight',
    'getDataPath',
    'getParentId',
  ])
    delete preview[key];
  const masterDetail = preview.masterDetail as { render?: unknown } | undefined;
  if (masterDetail && typeof masterDetail.render !== 'function') delete preview.masterDetail;
  if (preview.treeData) delete preview.treeData;
  const modules = result.modules
    .filter((name) => !(name === 'MasterDetailModule' && !preview.masterDetail) && !(name === 'TreeDataModule'))
    .map((name) => PRO_MODULES[name])
    .filter(Boolean);
  return {
    ...(preview as Partial<GridOptions>),
    columns,
    rows: sampleRows(columns, 48),
    getRowId: (row) => String(row.__rowId),
    modules,
    theme: docsTheme(),
    ariaLabel: 'Preview of the converted grid with sample rows',
  };
}

const SEVERITY_LABELS: Record<MigrationWarning['severity'], string> = {
  manual: 'Manual',
  warning: 'Check',
  info: 'Note',
};
const SEVERITY_COLORS: Record<MigrationWarning['severity'], string> = {
  manual: 'var(--warn)',
  warning: 'var(--accent)',
  info: 'var(--muted)',
};

function renderWarnings(list: HTMLElement, warnings: readonly MigrationWarning[]): void {
  list.replaceChildren();
  const ordered = [...warnings].sort(
    (a, b) => ['manual', 'warning', 'info'].indexOf(a.severity) - ['manual', 'warning', 'info'].indexOf(b.severity),
  );
  if (!ordered.length) {
    const empty = document.createElement('p');
    empty.style.cssText = 'margin:0;padding:10px;font-size:13px;color:var(--muted)';
    empty.textContent = 'Everything converted without notes.';
    list.append(empty);
    return;
  }
  for (const warning of ordered) {
    const item = document.createElement('li');
    item.style.cssText =
      'padding:6px 10px;border-bottom:1px solid var(--line);font-size:12.5px;line-height:1.45;color:var(--text)';
    const badge = document.createElement('strong');
    badge.style.cssText = `display:inline-block;min-width:52px;margin-right:6px;font-size:11px;text-transform:uppercase;letter-spacing:.03em;color:${SEVERITY_COLORS[warning.severity]}`;
    badge.textContent = SEVERITY_LABELS[warning.severity];
    const path = document.createElement('code');
    path.style.cssText = `${MONO};color:var(--ink)`;
    path.textContent = warning.path;
    const message = document.createElement('span');
    message.textContent = ` ${warning.message} `;
    const link = document.createElement('a');
    link.href = warning.docsUrl.replace(/^https:\/\/birchui\.com/, '');
    link.textContent = 'Docs';
    item.append(badge, path, message, link);
    list.append(item);
  }
}

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  body.style.cssText =
    'flex:1;min-height:0;position:relative;display:grid;gap:10px;padding:10px;grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr));grid-auto-rows:minmax(260px,1fr);overflow:auto;background:var(--bg-soft)';

  const sampleSelect = document.createElement('select');
  for (const sample of SAMPLES) sampleSelect.add(new Option(sample.label, sample.id));
  const fromSelect = document.createElement('select');
  fromSelect.add(new Option('AG Grid', 'ag-grid'));
  fromSelect.add(new Option('MUI X Data Grid', 'mui'));

  const input = panel('Paste AG Grid or MUI X configuration (JSON or a JavaScript object literal)');
  const textarea = document.createElement('textarea');
  textarea.spellcheck = false;
  textarea.wrap = 'off';
  textarea.setAttribute('aria-label', 'Configuration to convert');
  textarea.style.cssText = `${MONO};width:100%;height:100%;box-sizing:border-box;border:0;padding:10px;resize:none;background:var(--code-bg, var(--bg));color:var(--ink);outline-offset:-2px`;
  input.content.append(textarea);

  const output = panel('Birch UI Grid configuration');
  const code = document.createElement('pre');
  code.setAttribute('aria-live', 'polite');
  code.style.cssText = `${MONO};margin:0;padding:10px;min-height:100%;box-sizing:border-box;white-space:pre;background:var(--code-bg, var(--bg));color:var(--ink)`;
  output.content.append(code);

  const notes = panel('Warnings and manual steps');
  const list = document.createElement('ul');
  list.style.cssText = 'list-style:none;margin:0;padding:0';
  notes.content.append(list);

  const preview = panel('Live preview with sample rows');
  const stage = document.createElement('div');
  stage.style.cssText = 'position:absolute;inset:0';
  preview.content.append(stage);

  body.append(input.root, output.root, notes.root, preview.root);

  let grid: GridApi | null = null;
  let timer: ReturnType<typeof setTimeout> | null = null;
  let converted = '';

  const showPreview = (result: SnippetConversion | null) => {
    grid?.destroy();
    grid = null;
    stage.replaceChildren();
    const options = result ? previewOptions(result) : null;
    if (!options) {
      const empty = document.createElement('p');
      empty.style.cssText = 'margin:0;padding:10px;font-size:13px;color:var(--muted)';
      empty.textContent = 'The preview appears once the configuration has columns.';
      stage.append(empty);
      return;
    }
    grid = createGrid(stage, options);
  };

  const convert = () => {
    const from = fromSelect.value as MigrationSource;
    try {
      const result = convertSnippet(textarea.value, from);
      converted = result.output;
      code.textContent = result.output;
      renderWarnings(list, result.warnings);
      showPreview(result);
      const manual = result.warnings.filter((w) => w.severity === 'manual').length;
      const checks = result.warnings.filter((w) => w.severity === 'warning').length;
      status.textContent = `Converted ${result.kind === 'columns' ? 'column definitions' : 'grid options'}: ${manual} manual step${manual === 1 ? '' : 's'}, ${checks} to check${result.modules.length ? `, Grid Pro modules: ${result.modules.join(', ')}` : ''}.`;
    } catch (error) {
      converted = '';
      code.textContent = (error as Error).message;
      renderWarnings(list, []);
      showPreview(null);
      status.textContent =
        'The configuration could not be parsed. Nothing is evaluated, so function calls must be replaced by values.';
    }
  };

  const schedule = () => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(convert, 250);
  };

  const loadSample = () => {
    const sample = SAMPLES.find((s) => s.id === sampleSelect.value) ?? SAMPLES[0];
    fromSelect.value = sample.from;
    textarea.value = sample.source;
    convert();
  };

  const copy = button('Copy result', () => {
    if (!converted) return;
    navigator.clipboard?.writeText(converted).then(
      () => (status.textContent = 'Copied the converted configuration.'),
      () => (status.textContent = 'Copying is not allowed here; select the text instead.'),
    );
  });

  toolbar.append(field('Example', sampleSelect), field('Library', fromSelect), copy);
  sampleSelect.addEventListener('change', loadSample);
  fromSelect.addEventListener('change', convert);
  textarea.addEventListener('input', schedule);
  const stopTheme = onDocsThemeChange((theme) => grid?.update({ theme }));
  loadSample();

  return () => {
    if (timer) clearTimeout(timer);
    sampleSelect.removeEventListener('change', loadSample);
    fromSelect.removeEventListener('change', convert);
    textarea.removeEventListener('input', schedule);
    stopTheme();
    grid?.destroy();
  };
}
```

Nothing you paste is evaluated. Functions and variable names are kept as placeholders, callbacks are rewritten as text (`(params) => params.data.price` becomes `(row) => row.price`), and the preview leaves out anything that would need your own code to run, such as cell renderers and formatters.

## Run the codemod

Install the tool next to TypeScript, which it uses to parse your files:

```sh
npm install --save-dev @birchui/migrate typescript
```

Start with a dry run. It prints a unified diff and a summary and does not change any file:

```sh
npx birchui-migrate "src/**/*.{ts,tsx,js,jsx,vue,html}" --report migration-report.md
```

```text
14 files scanned, 6 would change. 83 converted, 7 manual steps, 12 warnings. Estimated effort: about 3 hours.
Run again with --write to apply the changes.
```

When the diff looks right, commit your work, apply the changes and format the files:

```sh
npx birchui-migrate "src/**/*.{ts,tsx,js,jsx,vue,html}" --write
npx prettier --write src
```

| Option | Description |
| --- | --- |
| `<glob...>` | Files, directories or globs. `node_modules`, `dist` and `build` are skipped |
| `--from ag-grid` or `--from mui` | Only convert one library. By default it is detected from the imports |
| `--framework react\|vue\|angular\|js` | Override the framework detected from the imports |
| `--write` | Write the converted files |
| `--report <file.md>` | Write a markdown report |
| `--quiet` | Print only the summary |

Running the tool again on converted files changes nothing, so you can migrate a large codebase folder by folder.

## What it converts

| Code | Result |
| --- | --- |
| React `<AgGridReact>` | `<BirchGrid>` with converted props and `on…` event props. Grid Pro modules are hoisted to a constant, the `ag-theme-*` class of the wrapper becomes `theme`, and `gridRef.current.api.x()` calls go to the ref, which is the full `GridApi` |
| `createGrid(el, options)` and `new Grid(el, options)` | `createGrid` from `@birchui/core`. Event handlers move to `grid.on(name, handler)` after the call |
| Vue `<ag-grid-vue>` | `<birchui-grid>` with kebab-case bindings and `@event` handlers. Declarations in `<script setup>` that the template uses are converted too |
| Angular `<ag-grid-angular>` | `<birchui-grid>` in inline templates and `templateUrl` files. Options without an input of their own go into `[options]`, and modules become a component member |
| MUI X `<DataGrid>`, `<DataGridPro>`, `<DataGridPremium>` | `<BirchGrid>`. `initialState`, `pinnedColumns`, `columnVisibilityModel` and `aggregationModel` are applied to the column declarations, and `useGridApiRef()` becomes `useRef<GridApi>(null)` |
| Column definitions and grid options | Literals typed `ColDef`, `GridOptions` or `GridColDef`, and literals a grid refers to, including those inside `useMemo`, `useState`, `ref` and class properties |
| Callbacks | `params` callbacks are rewritten to the Birch UI arguments. A helper used once, such as `valueFormatter: currencyFormatter`, is rewritten where it is declared |
| API calls | Calls on `api`, `gridApi`, `params.api`, `this.agGrid.api` and `apiRef.current`. For example `exportDataAsExcel(params)` becomes `exportExcel?.(params)` and adds `ExcelModule`, and `setFilterModel` converts the filter model |
| Imports and setup | AG Grid and MUI X imports and type names, CSS imports, `ModuleRegistry.registerModules` and `LicenseManager.setLicenseKey` |

A master/detail grid configured with `detailCellRendererParams` gets a generated `masterDetail.render` that creates the detail grid:

```ts title="Converted master/detail"
masterDetail: {
  height: 260,
  render: (row, container) => {
    const detail = createGrid(container, {
      columns: [{ field: 'callId' }, { field: 'direction' }, { field: 'number', minWidth: 150 }],
      rows: row.callRecords,
    });
    return () => detail.destroy();
  },
},
modules: [MasterDetailModule],
```

## Warnings and manual steps

Every change is reported with a severity:

| Severity | Meaning |
| --- | --- |
| `info` | Converted or safely ignored; nothing to do |
| `warning` | Converted, but the behaviour differs. Check it |
| `manual` | Rewrite by hand. The tool keeps your code and adds a marker |

A manual step leaves one marker comment in the converted code, with a link to the page that explains the change:

```tsx
{
  field: 'status',
  /* birchui-migrate: cellRenderer: StatusBadge is a framework component; rewrite it as cell: (ctx) => string | Node, or mount the component into a DOM node you return (https://birchui.com/getting-started/migrating-from-ag-grid/#cell-renderers) */
  cell: StatusBadge,
},
```

Templates get an HTML comment instead. Search for `birchui-migrate:` to find every marker, and remove each one when you have dealt with it.

The report from `--report` lists, for each file, what was converted, the manual steps as a checklist, the warnings and an effort estimate: 5 minutes per changed file, plus 15 minutes per manual step and 5 minutes per warning.

## Use the converters in code

The converters are plain functions with no dependencies, so you can also convert configuration at runtime, for example while both grids live side by side:

```ts title="orders-grid.ts"
import { createGrid, type GridModule } from '@birchui/core';
import * as GridPro from '@birchui/grid-pro';
import { convertAgGridOptions } from '@birchui/migrate';
import { ordersGridOptions } from './legacy/orders-grid-options';

const { options, events, modules, warnings } = convertAgGridOptions(ordersGridOptions, { createGrid });
const proModules = GridPro as unknown as Record<string, GridModule>;

const grid = createGrid(document.querySelector<HTMLElement>('#orders')!, {
  columns: [],
  ...options,
  modules: modules.map((name) => proModules[name]),
});
for (const [name, handler] of Object.entries(events)) grid.on(name as 'cellClick', handler as () => void);
for (const warning of warnings) console.warn(`${warning.path}: ${warning.message}`);
```

At runtime, AG Grid callbacks keep working because they are wrapped and still receive `params` objects. Pass `{ mode: 'source' }` to get rewritten source code instead, and `{ eventProps: true }` to get events as React `on…` props. `convertMuiColumns` and `convertMuiProps` do the same for MUI X, and `@birchui/migrate/codemod` exports `migrateSource`, `migrateFiles`, `unifiedDiff` and `renderReport`. See the [API reference](https://docs.birchui.com/api/migrate.md).

## Known gaps

These need your own code, and the tool marks them as manual steps:

- **Framework components** used as cell renderers, cell editors, header components and detail renderers. A Birch UI `cell` function returns text or a DOM node.
- **JSX in MUI X** `renderCell` and `getDetailPanelContent`, and MUI X `slots` such as a toolbar.
- **The side bar and tool panels**, which are planned.
- **Values that are not literals in the file**, such as column definitions built by a function or imported from another module. Run the tool on that module too, or convert those definitions with `convertAgGridColumnDefs`.
- **Event payloads used beyond the mapped fields**, for example `event.api` in handlers other than `onGridReady`.

After the codemod, read the [AG Grid](https://docs.birchui.com/getting-started/migrating-from-ag-grid.md) or [MUI X](https://docs.birchui.com/getting-started/migrating-from-mui-x.md) guide for the differences in behaviour, and run your type checker: converted callbacks now take Birch UI types such as `CellContext` and `ColumnDef`.
