# Tree Data Grids

Canonical page: https://www.adaptabletools.com/docs/handbook-tree-data-grid

- AdapTable supports AG Grid Tree View
- Styling, Filtering, Sorting and Searching are all available when using Tree Data

AG Grid [Tree Data](https://www.ag-grid.com/javascript-data-grid/tree-data/) views are typically used for showing **hierarchical** data, e.g. a Company Organisation chart or a list of Folder / File contents.

Unlike [Master Detail](https://www.adaptabletools.com/docs/handbook-master-detail/index.md) Grids which show a different grid when you expand to see children, Tree Data views show the **same set of columns** when a row is expanded.

- Tree Data Grids also differ to [Row Grouping](https://www.adaptabletools.com/docs/handbook-grouping-rows/index.md) because the top row in each 'Group' is a 'real' record
- i.e. it is not merely aggregated data (though it can show agg data as in the `Size` Column in the demo below)

AdapTable fully supports using Tree Data - but at present it does not provide additional functionality.

- Tree Data contains some important restrictions - e.g. no [Row Grouping](https://www.adaptabletools.com/docs/handbook-grouping-rows/index.md) or [Pivoting](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md)  is possible
- Only use Tree Data Views it if your data is strictly hierarchical and the functionality it provides is vital

## Formatting

[Column Formatting and Styling](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) works normally with Tree Grids.

**Example: Tree Data Formatting**

Adding Format Columns to Tree Data in AdapTable

- In this example (and all the ones below) a list of files from the Github React repo are loaded and shown as Tree Data
- We have applied 2 [Conditional Styles](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md):
  - for the whole row where `Path` Column contains the word "runtime"
  - for the `Size` Column where its greater than 1000

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data Formatting',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-all',
          Scope: {
            All: true,
          },
          Rule: 'CONTAINS([path], "runtime") ',
          Style: {
            BackColor: '#fff3b8',
            FontStyle: 'Italic',
          },
        },
        {
          Name: 'formatColumn-size',
          Scope: {
            ColumnIds: ['size'],
          },
          Rule: '[size] > 1000',
          Style: {
            FontWeight: 'Bold',
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSizing: {
            path: {Width: 350},
            size: {Width: 100},
            type: {Width: 100},
          },
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```

## Searching

[Quick Search](https://www.adaptabletools.com/docs/handbook-quick-search/index.md) works normally in Tree Data Grids - including the generated "key" column.

**Example: Tree Data Quick Search**

Using Quick Search with Tree Data

- In this example we search on 'react-server' and we see results throughout grid, including the "key" column

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data - Searching',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    QuickSearch: {
      QuickSearchText: 'react-server',
    },
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSizing: {
            path: {Width: 350},
            size: {Width: 100},
            type: {Width: 100},
          },
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```

## Filtering

[Column Filters](https://www.adaptabletools.com/docs/handbook-column-filter/index.md) also work normally in Tree Data Grids.

AdapTable will automatically make the "Tree" column use an [In Filter](https://www.adaptabletools.com/docs/handbook-column-filter-in-filter/index.md), with a Tree-like structure.

**Example: Tree Data Column Filtering**

Using Column Filters with Tree Data

- In this example we provide 2 Column Filters:
  - the `Path` column for any cell that contains the text "runtime"
  - the `Size` column for values less than 400
- Note: the `Name` column (the "Tree" column) defaults to an `In` Filter with the data presented in Tree-based format

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data - Filtering',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSizing: {
            path: {Width: 350},
            size: {Width: 300},
            type: {Width: 100},
          },
          ColumnFilters: [
            {
              ColumnId: 'path',
              Expression: 'CONTAINS([path], "runtime")',
            },
            {
              ColumnId: 'size',
              Expression: '[size] < 400',
            },
          ],
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```

## Pinning

Column Pinning works normally with Tree Grids.

To pin the "key" column, use its autogenerated Id of "*ag-Grid-AutoColumn*" in the Layout

**Example: Tree Data Pinning**

Pinning Key Column in Tree Grid

- In this example we have pinned the "key" column (with an Id of "*ag-Grid-AutoColumn*") to the left

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data - Pinning',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSizing: {
            path: {Width: 700},
            size: {Width: 400},
            type: {Width: 300},
          },
          ColumnPinning: {
            'ag-Grid-AutoColumn': 'left',
            //  path: 'left',
          },
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    width: 500,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```

## Sizing

Column Sizing works normally with Tree Grids.

To set the size of the "key" column, use its autogenerated Id of "*ag-Grid-AutoColumn*" in the Layout

**Example: Tree Data Sizing**

Setting width of Key Column in Tree Grid

- In this example we have sized the "key" column (with an Id of "*ag-Grid-AutoColumn*") to be 300 pixels
- We have sized the other columns also (by using their ColumnIds)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data - Sizing',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSizing: {
            'ag-Grid-AutoColumn': {Width: 300},
            path: {Width: 200},
            size: {Width: 100},
            type: {Width: 100},
          },
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    width: 500,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```

## Sorting

Column Sorting works normally with Tree Grids.

To sort the "key" column, use its autogenerated Id of "*ag-Grid-AutoColumn*" in the Layout

**Example: Tree Data Sorting**

Sorting the Key Column in Tree Grid

- In this example we have sorted the "key" column (with an Id of "*ag-Grid-AutoColumn*") in descending order

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';

export const adaptableOptions: AdaptableOptions = {
  primaryKey: 'path',
  adaptableId: 'Tree Data - Sorting',
  autogeneratePrimaryKey: true,
  stateOptions: {
    loadState: () => Promise.resolve({}),
    persistState: () => Promise.resolve(),
  },
  initialState: {
    Layout: {
      CurrentLayout: 'Tree Layout',
      Layouts: [
        {
          TableColumns: ['path', 'size', 'type'],
          Name: 'Tree Layout',
          ColumnSorts: [
            {
              ColumnId: 'ag-Grid-AutoColumn',
              SortOrder: 'Desc',
            },
          ],
          RowSelection: {
            Mode: 'multiRow',
            Checkboxes: true,
            HeaderCheckbox: true,
          },
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },

  treeData: true, // enable Tree Data mode
  animateRows: true,
  autoGroupColumnDef: {
    headerName: 'Name',
    floatingFilter: true,
    filter: true,
    width: 500,
    cellRendererParams: {
      suppressCount: true,
    },
  },
  cellSelection: true,
  suppressColumnVirtualisation: false,
  suppressMenuHide: true,
  sideBar: true,
  columnDefs: columnDefs,
  getDataPath: data => {
    // removing the first part it behaves as it is at root level;
    const path = data.path.replace('packages/react/', '');
    return path.split('/');
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await getData();
  adaptableApi.gridApi.loadGridData(data);
};

function uniqueByPath(rows: any[]) {
  const seen = new Set<string>();
  return rows.filter(row => {
    const path = row?.path;
    if (typeof path !== 'string' || seen.has(path)) {
      return false;
    }
    seen.add(path);
    return true;
  });
}

async function getData() {
  const data = localStorage.getItem('data');

  if (data) {
    return uniqueByPath(JSON.parse(data));
  }

  const paths = [
    'https://api.github.com/repos/facebook/react/contents/packages/react',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src',
    'https://api.github.com/repos/facebook/react/contents/packages/react/npm',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/__tests__/__snapshots__',
    'https://api.github.com/repos/facebook/react/contents/packages/react/src/jsx',
  ];

  const promises = paths.map(async path => {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  });

  const allData = await Promise.all(promises);
  const flatData = uniqueByPath(
    allData.filter(dataList => Array.isArray(dataList)).reduce((acc, list) => [...acc, ...list], [])
  );

  localStorage.setItem('data', JSON.stringify(flatData));

  return flatData;
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'path',
    cellDataType: 'text',
  },
  {
    field: 'size',
    cellDataType: 'number',
    enableValue: true,
  },
  {
    field: 'type',
    cellDataType: 'text',
  },
];
```
