# Setting Up Team Sharing

Canonical page: https://www.adaptabletools.com/docs/handbook-team-sharing-configuring

- Team Sharing is configured by developers at Design Time
- The UI Entitlements for Team Sharing allow some users only to download (and not upload)

Team Sharing is not available or enabled by default in AdapTable.

Instead, it needs to be explicitly enabled and set up by developers at design time.

Team Sharing uses a very similar loading and persisting pattern as [Comments](https://www.adaptabletools.com/docs/handbook-comments-configuring/index.md)

### Setting up Team Sharing in Team Sharing Options

There are 4 steps you **must** follow in order for Team Sharing to be available to end users:

Check the TeamSharing [Entitlement](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) is one of these 2 Access Levels:

- `Full` (preferable)
- `ReadOnly`

Alternatively, check the `defaultAccessLevel` property is set to *Full*

```tsx {6,7}
const adaptableOptions: AdaptableOptions = {
  entitlementOptions: {
    defaultAccessLevel: 'Hidden',
    moduleEntitlements: [
      {
        adaptableModule: 'TeamSharing',
        accessLevel: 'Full',
      },
    ],
  },
};
```

Team Sharing will not appear if the `defaultAccessLevel` property is set to *Hidden* and the Team Sharing Entitlement is not explicitly overridden

Set `enableTeamSharing` to **true** in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md) section of Adaptable Options.

### `enableTeamSharing`

Whether Team Sharing is enabled

Team Sharing is off until this is `true`. The load and persist functions below are also required, and the Team Sharing [Entitlement](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) must not be `Hidden`.

```ts {3}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
  },
};
```

The async `loadSharedEntities` property in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md) must be supplied.

This property is used for retrieving any Shared Items from the remote storage location.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
    async loadSharedEntities(adaptableId) {
      return new Promise(resolve => {
        const sharedEntities = JSON.parse(
          localStorage.getItem(`TEAM_SHARING:${adaptableId}`) || '[]'
        );
        resolve(sharedEntities);
      });
    },
  },
};
```

The async `persistSharedEntities` property in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md) must be supplied.

This property is used for persisting any Shared Items into the remote storage location.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
    async persistSharedEntities(adaptableId, sharedEntities) {
      return new Promise(resolve => {
        localStorage.setItem(
          `TEAM_SHARING:${adaptableId}`,
          JSON.stringify(sharedEntities)
        );
        resolve();
      });
    },
  },
};
```

Once Team Sharing is enabled, AdapTable will update the UI in 2 ways:

- include the Team Sharing screen in the Settings Panel
- add a _Share_ button to every screen in the Settings Panel that displays AdapTable Objects

The *Share* button's back and fore colours can be styled using 2 CSS variables:
- `--ab-color-action-share`
- `--ab-color-action-share-foreground`

## Remote State Management

TeamSharing Options provides 4 functions that allow developers to control TeamSharing state management and to provide their own load, persistence, hydration or serialization mechanisms:
- `loadSharedEntities` — **(mandatory)** loads Shared Entities from remote storage
- `persistSharedEntities` — **(mandatory)** uploads Shared Entities to remote storage
- `applySharedEntities` — **(optional)** hooks into the load flow after `loadSharedEntities` returns
- `saveSharedEntities` — **(optional)** hooks into the persistence flow before `persistSharedEntities` runs

These 4 functions mirror exactly those used to save [Adaptable State remotely](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md#remote-storage)

### `loadSharedEntities`

Loads Shared Entities from remote storage

  [`Promise<SharedEntity[]>`](https://www.adaptabletools.com/docs/reference/sharedentity.md)

This **async** function retrieves available Shared Entities that the user can download from the Remote Location.

It then merges them automatically with Adaptable State.

```tsx
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
      loadSharedEntities: async (context: SharedEntitiesContext) => {
       return new Promise(resolve => {
         const sharedEntities = JSON.parse(
           localStorage.getItem(`TEAM_SHARING:${context.adaptableId}`) || '[]'
         );
         resolve(sharedEntities);
       });
     },
  },
};
```

### `persistSharedEntities`

Persists Shared Entities to remote storage

This **async** function uploads any Shared Entities into remote storage.

This means that they can be downloaded by other members of the team (if entitlements allow)

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
    persistSharedEntities: async (
        sharedEntities: SharedEntity[],
        context: SharedEntitiesContext) => {
           return new Promise(resolve => {
             localStorage.setItem(
               `TEAM_SHARING:${context.adaptableId}`,
               JSON.stringify(sharedEntities)
             );
             resolve();
           });
     },
  },
};
```

### `applySharedEntities`

(Optional) Hooks into load flow of Shared Entities

If defined, it will be invoked with the result of the `loadSharedEntities()` method invocation, and the result will be passed to Adaptable State.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
      applySharedEntities: (
        sharedEntities: SharedEntity[],
        context: SharedEntitiesContext
      ) => {
          return sharedEntities.map((sharedEntity) => {
              if (sharedEntity.EntityType === 'adaptableEntity' && sharedEntity.Module === 'Layout') {
                  return { ...sharedEntity, IsReadOnly: true };
              }
              return sharedEntity;
          });
      },
  },
};
```

### `saveSharedEntities`

(Optional) Hooks into persistence flow of Shared Entities

If defined, it will be invoked before `persistSharedEntities()`, and `persistSharedEntities()` will be invoked with the result of this method.

```tsx {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
      saveSharedEntities: (
        sharedEntities: SharedEntity[],
        context: SharedEntitiesContext
      ) => {
          return sharedEntities.map((sharedEntity) => {
              return { ...sharedEntity, IsReadOnly: false };
          });
      },
  },
};
```

**Example: Configuring and customizing state management**

Configuring and customizing TeamSharing State Management

Users have edit rights only on their own shared entities and read-only rights on other users shared entities.
This is done by hooking into the loading/persisting TeamSharing state mechanisms.
### Expand to see how the State Management is configured

1. The __loading & persisting__ mechanisms are configured as usual by providing implementations for `loadSharedEntities()` and `persistSharedEntities()` callbacks:
```ts {1,13}
loadSharedEntities: async () => {
    const data = localStorage.getItem(TEAM_SHARING_STATE_KEY);
    if (!data) {
        return [];
    }
    try {
        return JSON.parse(data);
    } catch (e) {
        return [];
    }
}, 
persistSharedEntities: entries => {
    localStorage.setItem(TEAM_SHARING_STATE_KEY, JSON.stringify(entries));
    return Promise.resolve();
},
```
2. We hook into the __load__ process and dynamically set the `IsReadOnly` property comparing the SharedEntity creating user with current user:
```ts {1}
applySharedEntities: entities => {
    return entities.map(entity => {
        // shared entity is readonly for anyone except it's creator
        entity.IsReadOnly = userName !== entity.UserName;
        return entity;
    });
}
```
3. We hook into the __persist__ process and undo the changes we did to the `IsReadOnly` property, otherwise we would "pollute" the remote TeamSharing state.
```ts {1}
saveSharedEntities: entities => {
    return entities.map(entity => {
        // revert the changes done in `applySharedEntities()`, otherwise we would change the remote state as well
        return {...entity, IsReadOnly: false};
    });
}
```

- Share with each user a FormatColumn
- Notice that users can delete only their own shared FormatColumn

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts
  onAdaptableReady.ts  [template]
  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 {InitialState, AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

// use a common Team Sharing state key for both users
const TEAM_SHARING_STATE_KEY = 'ConfigStateTeamSharingDemo_TeamSharingState';
export const getAdaptableOptionsForUser = (
  userName: 'Alice' | 'Bob',
  updateCurrentUser: (userName: 'Alice' | 'Bob') => void
): AdaptableOptions<WebFramework> => {
  const commonInitialState: InitialState = {
    Dashboard: {
      Revision: Date.now(),
      Tabs: [
        {
          Name: 'Select Current User',
          Toolbars: ['CurrentUser'],
        },
      ],
      ModuleButtons: ['FormatColumn', 'TeamSharing'],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  };
  const userSpecificInitialState =
    userName === 'Alice'
      ? {
          FormatColumn: {
            FormatColumns: [
              {
                Name: 'formatColumn-name',
                Scope: {
                  ColumnIds: ['name'],
                },
                Style: {
                  BackColor: 'lightblue',
                  ForeColor: 'var(--ab-color-palette-17)',
                },
              },
            ],
          },
          Theme: {
            CurrentTheme: 'light',
          },
        }
      : // Bob
        {
          FormatColumn: {
            FormatColumns: [
              {
                Name: 'formatColumn-language',
                Scope: {
                  ColumnIds: ['language'],
                },
                Style: {
                  BackColor: 'var(--ab-color-palette-21)',
                  ForeColor: 'var(--ab-color-palette-13)',
                },
              },
            ],
          },
          Theme: {
            CurrentTheme: 'dark',
          },
        };

  return {
    primaryKey: 'id',
    adaptableId: 'State Configuration Team Sharing Demo',
    adaptableStateKey: `StateConfigTeamSharingDemo_${userName}`,
    userName,
    initialState: {
      ...commonInitialState,
      ...userSpecificInitialState,
    },
    teamSharingOptions: {
      enableTeamSharing: true,
      loadSharedEntities: async () => {
        const data = localStorage.getItem(TEAM_SHARING_STATE_KEY);
        if (!data) {
          return [];
        }

        try {
          return JSON.parse(data);
        } catch (e) {
          return [];
        }
      },
      persistSharedEntities: entries => {
        localStorage.setItem(TEAM_SHARING_STATE_KEY, JSON.stringify(entries));
        return Promise.resolve();
      },
      applySharedEntities: entities => {
        return entities.map(entity => {
          // shared entity is readonly for anyone except it's creator
          entity.IsReadOnly = userName !== entity.UserName;
          return entity;
        });
      },
      saveSharedEntities: entities => {
        return entities.map(entity => {
          // revert the changes done in `applySharedEntities()`, otherwise we would change the remote state as well
          return {...entity, IsReadOnly: false};
        });
      },
    },
    dashboardOptions: {
      customToolbars: [
        {
          name: 'CurrentUser',
          title: 'Current User',
          toolbarButtons: [
            {
              label: 'Alice',
              buttonStyle: () => {
                return {
                  tone: userName === 'Alice' ? 'success' : 'neutral',
                  variant: userName === 'Alice' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Alice');
              },
            },
            {
              label: 'Bob',
              buttonStyle: () => {
                return {
                  tone: userName === 'Bob' ? 'success' : 'neutral',
                  variant: userName === 'Bob' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Bob');
              },
            },
          ],
        },
      ],
      customDashboardButtons: [
        {
          tooltip: 'Reset state',
          icon: {
            name: 'refresh',
          },
          buttonStyle: {
            tone: 'error',
          },
          onClick: (button, context) => {
            localStorage.removeItem(TEAM_SHARING_STATE_KEY);
            ['Alice', 'Bob'].forEach(user => {
              localStorage.removeItem(`StateConfigTeamSharingDemo_${user}`);
            });
            context.adaptableApi.stateApi.reloadInitialState();
          },
        },
      ],
    },
  };
};
```

**`src/index.ts`**

```ts
import {
  Adaptable,
  AdaptableApi,
  AdaptableOptions,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable';

import '@adaptabletools/adaptable/index.css';

import './styles.css';

import {gridOptions} from './gridOptions';
import {onAdaptableReady} from './onAdaptableReady';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';

let currentAdaptableInstance: AdaptableApi | undefined;

let currentUser: 'Alice' | 'Bob' = 'Alice';

function updateCurrentUser(userName: 'Alice' | 'Bob') {
  currentUser = userName;
  initializeAdaptable(currentUser);
}

async function initializeAdaptable(userName: 'Alice' | 'Bob') {
  // destroy the previous instance (if existing)
  if (currentAdaptableInstance) {
    const config: any = {
      unmount: true,
      destroyApi: true,
    };
    currentAdaptableInstance.destroy(config);
  }

  currentAdaptableInstance = await Adaptable.init(
    {
      ...getAdaptableOptionsForUser(userName, updateCurrentUser),
    } as AdaptableOptions<WebFramework>,
    {
      gridOptions: {...gridOptions},
      modules: agGridModules,
    }
  );
  currentAdaptableInstance.eventApi.on(
    'AdaptableReady',
    (readyInfo: AdaptableReadyInfo) => {
      onAdaptableReady(readyInfo);
    }
  );
}

initializeAdaptable(currentUser);
```

**`src/App.tsx`** (React version)

```ts
import * as React from 'react';
import {useState} from 'react';
import {
  Adaptable,
  AdaptableApi,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable-react-aggrid';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = ({
  currentUser,
  onCurrentUserChange,
}: {
  currentUser: 'Alice' | 'Bob';
  onCurrentUserChange: (userName: 'Alice' | 'Bob') => void;
}) => {
  const adaptableApiRef = React.useRef<AdaptableApi>(null);

  const adaptableOptions = getAdaptableOptionsForUser(
    currentUser,
    onCurrentUserChange
  );

  const agGridOptions = {...gridOptions};
  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <Adaptable.Provider
        gridOptions={agGridOptions}
        adaptableOptions={adaptableOptions}
        modules={[...agGridModules]}
        onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
          // save a reference to adaptable api
          adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
          onAdaptableReady(adaptableReadyInfo);
        }}>
        <Adaptable.UI key={`${currentUser}-ui`} style={{flex: 'none'}} />
        <Adaptable.AgGridReact />
      </Adaptable.Provider>
    </div>
  );
};

const App: React.FunctionComponent = () => {
  const [currentUser, setCurrentUser] = useState<'Alice' | 'Bob'>('Alice');

  return (
    <Grid
      key={currentUser}
      currentUser={currentUser}
      onCurrentUserChange={userName => setCurrentUser(userName)}
    />
  );
};
export default App;
```

**`src/app/app.component.ts`** (Angular version)

```ts
import {ChangeDetectorRef, Component, Inject} from '@angular/core';

import {AdaptableReadyInfo, AdaptableOptions} from '@adaptabletools/adaptable-angular-aggrid';
import {GridOptions} from 'ag-grid-enterprise';

// Adaptable styles
import '@adaptabletools/adaptable-angular-aggrid/index.css';

// AG Grid styles

import './styles.css';

// grid configuration
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {onAdaptableReady} from './onAdaptableReady';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';

@Component({
  standalone: false,
  selector: 'app-root',
  template: `
    <div id="demoOutputAbove"></div>
    <adaptable-provider
      *ngIf="isUpToDate"
      [adaptableOptions]="adaptableOpts"
      [gridOptions]="agGridOptions"
      [modules]="modules"
      (adaptableReady)="adaptableReady($event)"
      style="height: 100vh; width: 100vw;">
      <adaptable-ui style="flex: none"></adaptable-ui>
      <ag-grid-angular
        *adaptable="let adaptable"
        [gridOptions]="adaptable.gridOptions"
        [modules]="adaptable.modules"
        style="flex: 1">
      </ag-grid-angular>
    </adaptable-provider>
    <div id="demoOutputBelow"></div>
  `,
  styles: [
    `
      :host {
        height: 100vh;
        display: flex;
        flex-flow: column;
      }
    `,
  ],
})
export class AppComponent {
  adaptableOpts: AdaptableOptions<WebFramework>;
  agGridOptions: GridOptions<WebFramework>;
  modules = agGridModules;

  currentUser: 'Alice' | 'Bob';
  isUpToDate = true;

  constructor(
    @Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef
  ) {
    this.currentUser = 'Alice';
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  setCurrentUser(currentUser: 'Alice' | 'Bob') {
    this.isUpToDate = false;
    this.changeDetectorRef.detectChanges();

    this.currentUser = currentUser;
    this.initializeAdaptable();
    this.isUpToDate = true;
    this.changeDetectorRef.detectChanges();
  }

  initializeAdaptable() {
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  adaptableReady($event: AdaptableReadyInfo) {
    onAdaptableReady($event);
  }
}
```

**`src/App.vue`** (Vue version)

```ts
<template>
  <Grid
    :key="currentUser"
    :currentUser="currentUser"
    @currentUserChange="setCurrentUser" />
</template>

<script lang="ts">
import {ref, defineComponent} from 'vue';
import {
  AdaptableProvider,
  AdaptableAgGridVue,
  AdaptableUI,
} from '@adaptabletools/adaptable-vue3-aggrid';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = defineComponent({
  props: {
    currentUser: {
      type: String,
      required: true,
    },
  },
  emits: ['currentUserChange'],
  setup(props, {emit}) {
    const adaptableOptions = getAdaptableOptionsForUser(
      props.currentUser,
      userName => emit('currentUserChange', userName)
    );

    const agGridOptions = {...gridOptions};

    return {
      adaptableOptions,
      agGridOptions,
      agGridModules,
      onAdaptableReady,
    };
  },
  components: {
    AdaptableProvider,
    AdaptableAgGridVue,
    AdaptableUI,
  },
  template: `
    <AdaptableProvider
        :gridOptions="agGridOptions"
        :adaptableOptions="adaptableOptions"
        :modules="agGridModules"
        @onAdaptableReady="onAdaptableReady">
      <div style="display: flex; flex-direction: column; height: 100vh">
        <AdaptableUI :key="currentUser + '-ui'" style="flex: none" />
        <AdaptableAgGridVue style="flex: 1"  />
      </div>
    </AdaptableProvider>
  `,
});

export default defineComponent({
  name: 'App',
  components: {
    Grid,
  },
  setup() {
    const currentUser = ref('Alice');

    const setCurrentUser = userName => {
      currentUser.value = userName;
    };

    return {
      currentUser,
      setCurrentUser,
    };
  },
});
</script>
```

## Migrating Shared Entities

When [autoMigrateState](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-migrating-state/index.md) is left at its default (`true`), AdapTable migrates shared entities as they are loaded, before `applySharedEntities` runs. The Team Sharing panel, import, and update checks then see the current object shape.

### `persistMigratedSharedEntities`

Writes migrated shared entities back to the server once per grid session

When this is `true`, a user with full Team Sharing rights saves the migrated shared entities once per grid session so the server copy matches the current shape.

The write does not change `Revision` or `ChangedAt`.

Set it to `false` when the shared store is read-only for most users.

```ts {4}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    enableTeamSharing: true,
    persistMigratedSharedEntities: false,
  },
};
```

With `autoMigrateState` set to `false`, shared entities stay as they are stored.

## UI Entitlements

The UI Entitlements for Team Sharing are as follows:

- `Hidden` the Team Sharing UI is completely unavailable

- `ReadOnly` - users can import existing Shared items, but are not allowed to create or delete them;
  

Changes to _Active_ entities **are** still pushed if the Entitlement is ReadOnly

- `Full` - everything is available in the UI, and users have full Read, Write and Download access

**Example: Team Sharing Admin and User**

A user is an admin and can share entities, and one is a normal user that can only apply shared entities.

User **Alice** has entitlements set to Full and **Bob** has entitlements set to ReadOnly.

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts
  onAdaptableReady.ts  [template]
  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, InitialState} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

// use a common Team Sharing state key for both users
const TEAM_SHARING_STATE_KEY = 'EntitlementsTeamSharingDemo_TeamSharingState';
export const getAdaptableOptionsForUser = (
  userName: 'Alice' | 'Bob',
  updateCurrentUser: (userName: 'Alice' | 'Bob') => void
): AdaptableOptions<WebFramework> => {
  const commonInitialState: InitialState = {
    Dashboard: {
      Revision: Date.now(),
      Tabs: [
        {
          Name: 'Select Current User',
          Toolbars: ['CurrentUser'],
        },
      ],
      ModuleButtons: ['FormatColumn', 'TeamSharing'],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  };
  const userSpecificInitialState =
    userName === 'Alice'
      ? {
          FormatColumn: {
            FormatColumns: [
              {
                Name: 'formatColumn-name',
                Scope: {
                  ColumnIds: ['name'],
                },
                Style: {
                  BackColor: 'lightblue',
                  ForeColor: 'var(--ab-color-palette-17)',
                },
              },
            ],
          },
          Theme: {
            CurrentTheme: 'light',
          },
        }
      : // Bob
        {
          FormatColumn: {
            FormatColumns: [
              {
                Name: 'formatColumn-language',
                Scope: {
                  ColumnIds: ['language'],
                },
                Style: {
                  BackColor: 'var(--ab-color-palette-21)',
                  ForeColor: 'var(--ab-color-palette-13)',
                },
              },
            ],
          },
          Theme: {
            CurrentTheme: 'dark',
          },
        };

  const isAlice = userName === 'Alice';

  return {
    primaryKey: 'id',
    adaptableId: 'Entitlements Team Sharing Demo',
    adaptableStateKey: `EntitlementsTeamSharingDemo_${userName}`,
    userName,
    initialState: {
      ...commonInitialState,
      ...userSpecificInitialState,
    },
    entitlementOptions: {
      moduleEntitlements: [
        {
          adaptableModule: 'TeamSharing',
          accessLevel: isAlice ? 'Full' : 'ReadOnly',
        },
      ],
    },
    teamSharingOptions: {
      enableTeamSharing: true,
      loadSharedEntities: async () => {
        const data = localStorage.getItem(TEAM_SHARING_STATE_KEY);
        if (!data) {
          return [];
        }

        try {
          return JSON.parse(data);
        } catch (e) {
          return [];
        }
      },
      persistSharedEntities: entries => {
        localStorage.setItem(TEAM_SHARING_STATE_KEY, JSON.stringify(entries));
        return Promise.resolve();
      },
    },
    dashboardOptions: {
      customToolbars: [
        {
          name: 'CurrentUser',
          title: 'Current User',
          toolbarButtons: [
            {
              label: 'Alice',
              buttonStyle: () => {
                return {
                  tone: userName === 'Alice' ? 'success' : 'neutral',
                  variant: userName === 'Alice' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Alice');
              },
            },
            {
              label: 'Bob',
              buttonStyle: () => {
                return {
                  tone: userName === 'Bob' ? 'success' : 'neutral',
                  variant: userName === 'Bob' ? 'raised' : 'outlined',
                };
              },
              onClick: () => {
                updateCurrentUser('Bob');
              },
            },
          ],
        },
      ],
      customDashboardButtons: [
        {
          tooltip: 'Reset state',
          icon: {
            name: 'refresh',
          },
          buttonStyle: {
            tone: 'error',
          },
          onClick: (button, context) => {
            localStorage.removeItem(TEAM_SHARING_STATE_KEY);
            ['Alice', 'Bob'].forEach(user => {
              localStorage.removeItem(`EntitlementsTeamSharingDemo_${user}`);
            });
            context.adaptableApi.stateApi.reloadInitialState();
          },
        },
      ],
    },
  };
};
```

**`src/index.ts`**

```ts
import {
  Adaptable,
  AdaptableApi,
  AdaptableOptions,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable';

import '@adaptabletools/adaptable/index.css';

import './styles.css';

import {gridOptions} from './gridOptions';
import {onAdaptableReady} from './onAdaptableReady';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';
import {AgGridConfig} from '@adaptabletools/adaptable';

let currentAdaptableInstance: AdaptableApi | undefined;

let currentUser: 'Alice' | 'Bob' = 'Alice';

function updateCurrentUser(userName: 'Alice' | 'Bob') {
  currentUser = userName;
  initializeAdaptable(currentUser);
}

async function initializeAdaptable(userName: 'Alice' | 'Bob') {
  // destroy the previous instance (if existing)
  if (currentAdaptableInstance) {
    const config: any = {
      unmount: true,
      destroyApi: true,
    };
    currentAdaptableInstance.destroy(config);
  }

  const adaptableOptions: AdaptableOptions<WebFramework> = {
    ...getAdaptableOptionsForUser(userName, updateCurrentUser),
  };

  const agGridConfig: AgGridConfig = {
    gridOptions: {...gridOptions},
    modules: agGridModules,
  };

  currentAdaptableInstance = await Adaptable.init(
    adaptableOptions,
    agGridConfig
  );
  currentAdaptableInstance.eventApi.on(
    'AdaptableReady',
    (readyInfo: AdaptableReadyInfo) => {
      onAdaptableReady(readyInfo);
    }
  );
}

initializeAdaptable(currentUser);
```

**`src/App.tsx`** (React version)

```ts
import * as React from 'react';
import {useState} from 'react';
import {
  Adaptable,
  AdaptableApi,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable-react-aggrid';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = ({
  currentUser,
  onCurrentUserChange,
}: {
  currentUser: 'Alice' | 'Bob';
  onCurrentUserChange: (userName: 'Alice' | 'Bob') => void;
}) => {
  const adaptableApiRef = React.useRef<AdaptableApi>(null);

  const adaptableOptions = getAdaptableOptionsForUser(
    currentUser,
    onCurrentUserChange
  );

  const agGridOptions = {...gridOptions};
  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <Adaptable.Provider
        gridOptions={agGridOptions}
        adaptableOptions={adaptableOptions}
        modules={[...agGridModules]}
        onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
          // save a reference to adaptable api
          adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
          onAdaptableReady(adaptableReadyInfo);
        }}>
        <Adaptable.UI key={`${currentUser}-ui`} style={{flex: 'none'}} />
        <Adaptable.AgGridReact />
      </Adaptable.Provider>
    </div>
  );
};

const App: React.FunctionComponent = () => {
  const [currentUser, setCurrentUser] = useState<'Alice' | 'Bob'>('Alice');

  return (
    <Grid
      key={currentUser}
      currentUser={currentUser}
      onCurrentUserChange={userName => setCurrentUser(userName)}
    />
  );
};
export default App;
```

**`src/app/app.component.ts`** (Angular version)

```ts
import {ChangeDetectorRef, Component, Inject} from '@angular/core';

import {AdaptableReadyInfo, AdaptableOptions} from '@adaptabletools/adaptable-angular-aggrid';
import {GridOptions} from 'ag-grid-enterprise';

// Adaptable styles
import '@adaptabletools/adaptable-angular-aggrid/index.css';

// AG Grid styles

import './styles.css';

// grid configuration
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {onAdaptableReady} from './onAdaptableReady';
import {getAdaptableOptionsForUser} from './adaptableOptions';
import {WebFramework} from './rowData';

@Component({
  standalone: false,
  selector: 'app-root',
  template: `
    <div id="demoOutputAbove"></div>
    <adaptable-provider
      *ngIf="isUpToDate"
      [adaptableOptions]="adaptableOpts"
      [gridOptions]="agGridOptions"
      [modules]="modules"
      (adaptableReady)="adaptableReady($event)"
      style="height: 100vh; width: 100vw;">
      <adaptable-ui style="flex: none"></adaptable-ui>
      <ag-grid-angular
        *adaptable="let adaptable"
        [gridOptions]="adaptable.gridOptions"
        [modules]="adaptable.modules"
        style="flex: 1">
      </ag-grid-angular>
    </adaptable-provider>
    <div id="demoOutputBelow"></div>
  `,
  styles: [
    `
      :host {
        height: 100vh;
        display: flex;
        flex-flow: column;
      }
    `,
  ],
})
export class AppComponent {
  adaptableOpts: AdaptableOptions<WebFramework>;
  agGridOptions: GridOptions<WebFramework>;
  modules = agGridModules;

  currentUser: 'Alice' | 'Bob';
  isUpToDate = true;

  constructor(
    @Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef
  ) {
    this.currentUser = 'Alice';
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  setCurrentUser(currentUser: 'Alice' | 'Bob') {
    this.isUpToDate = false;
    this.changeDetectorRef.detectChanges();

    this.currentUser = currentUser;
    this.initializeAdaptable();
    this.isUpToDate = true;
    this.changeDetectorRef.detectChanges();
  }

  initializeAdaptable() {
    this.adaptableOpts = getAdaptableOptionsForUser(
      this.currentUser,
      (user: 'Alice' | 'Bob') => this.setCurrentUser(user)
    );
    this.agGridOptions = {...gridOptions};
  }

  adaptableReady($event: AdaptableReadyInfo) {
    onAdaptableReady($event);
  }
}
```

**`src/App.vue`** (Vue version)

```ts
<template>
  <Grid
    :key="currentUser"
    :currentUser="currentUser"
    @currentUserChange="setCurrentUser" />
</template>

<script lang="ts">
import {ref, defineComponent} from 'vue';
import {
  AdaptableProvider,
  AdaptableAgGridVue,
  AdaptableUI,
} from '@adaptabletools/adaptable-vue3-aggrid';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {getAdaptableOptionsForUser} from './adaptableOptions';

const Grid = defineComponent({
  props: {
    currentUser: {
      type: String,
      required: true,
    },
  },
  emits: ['currentUserChange'],
  setup(props, {emit}) {
    const adaptableOptions = getAdaptableOptionsForUser(
      props.currentUser,
      userName => emit('currentUserChange', userName)
    );

    const agGridOptions = {...gridOptions};

    return {
      adaptableOptions,
      agGridOptions,
      agGridModules,
      onAdaptableReady,
    };
  },
  components: {
    AdaptableProvider,
    AdaptableAgGridVue,
    AdaptableUI,
  },
  template: `
    <AdaptableProvider
        :gridOptions="agGridOptions"
        :adaptableOptions="adaptableOptions"
        :modules="agGridModules"
        @onAdaptableReady="onAdaptableReady">
      <div style="display: flex; flex-direction: column; height: 100vh">
        <AdaptableUI :key="currentUser + '-ui'" style="flex: none" />
        <AdaptableAgGridVue style="flex: 1"  />
      </div>
    </AdaptableProvider>
  `,
});

export default defineComponent({
  name: 'App',
  components: {
    Grid,
  },
  setup() {
    const currentUser = ref('Alice');

    const setCurrentUser = userName => {
      currentUser.value = userName;
    };

    return {
      currentUser,
      setCurrentUser,
    };
  },
});
</script>
```

#### Entity Entitlements

ReadOnly rights at entity level can be specified by setting `IsReadOnly` to true for the SharedEntity

This can only be done programmatically - there is no option to set this in the UI

## Override Warning

AdapTable warns users if they try to import an object in Team Sharing that already exists in  [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

It does this by checking the `Uuid` (not the `Name`) of the imported [Adaptable Object](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md#adaptable-objects)

If the user proceeds with the import after seeing the warning, the new object will overwrite the existing one.

This behaviour can be changed using the `suppressOverrideConfigWarning` property in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md).

### `suppressOverrideConfigWarning`

Suppress messages warning that imported Object already exists

Set this property to *true* to suppress the warning when an Imported Object already exists.

This will have the effect of ensuring that the overwrite will happen automatically.

```ts {4}
// Suppress warnings from AdapTable when importing an existing object
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    suppressOverrideConfigWarning: true
  },
} 
```
