# Active Team Sharing

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

- Active Team Sharing ensures that any Shared Entities are 'live'
- This means that changes to the object by any sharing user are available to all other sharing users
- Sharing users can be notified in a variety of ways about changes to the Shared Entity

By default [Team Sharing](https://www.adaptabletools.com/docs/handbook-team-sharing/index.md) uses Snapshot Sharing, where each Shared Entity is a separate and unique object.

However AdapTable also allows users to upload a SharedEntity through Active Sharing.

- Active Team Sharing is designed for use cases where items are updated relatively occasionally, so use sensibly
- Don't use it when objects will continually be simultaneously updated by very large numbers of users

In this scenario, the Shared Entity remains linked after it has been uploaded to Team Share by a user (and then subsequently downloaded by her colleagues).

It is then the responsibility of AdapTable to ensure that any local changes to a Shared Entity are automatically synchronised to TeamSharing.

An Adaptable Object can have only 1 Active entity

### How Active Sharing Works

Active Sharing works by using the `Revision` property of the Shared Entity.

AdapTable uses a concurrency model which allows Objects to be shared and updated by multiple users.

As soon as any user uploads a new Shared Entity as Active, it will be implicitly marked with Revision 1.

Any subsequent changes to this object (either by the creator or by any other user which downloaded it) will be automatically synchronised with the Team Share, and the Revision of the Shared Entity will be incremented

The concurrency model is **optimistic**: any local change is possible and the remote state update is triggered

If Team Share contains a higher Revision for a Shared Entity than that which has been triggered, the update is rejected.

## Notifying Active Entity Changes

When a SharedEntity is Active, AdapTable can be configured to watch for all changes and notify any users allowing them to update their local copy.

### Update Interval

Team Sharing can be configured so AdapTable regularly checks for a change in an Active Shared Entity.

This is done via the `updateInterval` property in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md).

### `updateInterval`

Frequency (in minutes) to check if Active Shared Entities have a newer revision

By default AdapTable will **not** poll an Active Shared Entity location to see if there are any changes pending.

Set this property (set in minutes) to change this behaviour:

```ts {4}
// Poll every 5 minutes to see if an Active Shared Entity has changed
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    updateInterval: 5,
  },
};
```

### Update Notification

AdapTable always fires the [Team Sharing Entity Changed](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md) Event whenever an Active Shared Entity is synchronised.

In addition, the `updateNotification` property in [Team Sharing Options](https://www.adaptabletools.com/docs/technical-reference-team-sharing/index.md) can be configured so that each run-time user can be informed of a change to an Active SharedEntity in one of 3 ways:

- **Alert with Toast Notification** - a Toast Notification will appear in the current window and an Alert is fired
- **Alert without Notification** - the [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) Toolbar and ToolPanel show the Alert but there is no notification
- **System Status** - a [System Status](https://www.adaptabletools.com/docs/handbook-system-status-message/index.md) message is posted

### `updateNotification`

How AdapTable informs users when Active Shared Entities have newer revisions

By default AdapTable will **not** tell a user when an Active Shared Entity has a newer revision.

This property allows you to change that by specifying one of 3 options:

- `Alert`: Fire an Alert
- `AlertWithNotification`: Fire an Alert and show a Toast Notification
- `SystemStatus`: Publish a System Status Message

```ts {4}
// Fire an Alert with a Display Notification when there is a newer version of an Active Shared Entity
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    updateNotification: 'AlertWithNotification',
  },
};
```

### `showUpdateNotificationOncePerUpdate`

Show the update notification only once per Shared Entity revision

When `false` (the default), each poll can show the update again until the user clicks **Dismiss**.

Set this to `true` to show the notification once for that revision (no Dismiss button — AdapTable treats it as seen after the first display).

```ts {4,5}
const adaptableOptions: AdaptableOptions = {
  teamSharingOptions: {
    updateNotification: 'AlertWithNotification',
    showUpdateNotificationOncePerUpdate: true,
  },
};
```

**Example: Active Team Sharing**

Active Team Sharing

- This demo shows how Team Sharing works in AdapTable
- There are 2 users each with their own Initial State:
  - **Alice** - has a Format Column for `Name` Column
  - **Bob** - has a Format Column for `Language` Column and uses the Dark Theme
- Switching between users - via the custom toolbar - loads a new AdapTable instance with that User's Initial State
- Team Sharing is enabled in this demo, allowing **Alice** and **Bob** to share entities between them
- Note: this demo uses local storage to simulate an api call - but in the real world the shared entity would be stored remotely.
- We have set 2 more Team Sharing Options properties for the purposes of this demo:
  - `suppressOverrideConfigWarning` was set to true so that no Override Config warning appears
  - `updateInterval` has been set to a very unrealistic 10 seconds so you can immediately see the Alert appear
### Expand to see how Team Sharing is applied

We create 2 Initial Adaptable States - one for each user:
```ts
// Alice
{
  FormatColumn: {
    FormatColumns: [
      {
        Name: 'FormatColumn-name-201',
        Scope: {
          ColumnIds: ['name'],
        },
        Style: {
          BackColor: 'lightblue',
          ForeColor: 'var(--ab-color-palette-17)',
        },
      },
    ],
  },
  Theme: {
    CurrentTheme: 'light',
  },
}
// Bob
{
  FormatColumn: {
    FormatColumns: [
      {
        Name: 'FormatColumn-language-202',
        Scope: {
          ColumnIds: ['language'],
        },
        Style: {
          BackColor: 'var(--ab-color-palette-21)',
          ForeColor: 'var(--ab-color-palette-13)',
        },
      },
    ],
  },
  Theme: {
    CurrentTheme: 'dark',
  },
}
```
In TeamSharingOptions - which is passed into AdaptableOptions - we do 3 things:
- set `enableTeamSharing` to true
- provide an implementation for `loadSharedEntities`
- provide an implementation for `persistSharedEntities`
```ts
const teamSharingOptions: TeamSharingOptions = {
  enableTeamSharing: true,
  loadSharedEntities: async adaptableId => {
    const data = localStorage.getItem(TEAM_SHARING_STATE_KEY);
    if (!data) {
      return [];
    }
    try {
      return JSON.parse(data);
    } catch (e) {
      return [];
    }
  },
  persistSharedEntities: (adaptableId, entries) => {
    localStorage.setItem(TEAM_SHARING_ID, JSON.stringify(entries));
    return Promise.resolve();
  },
};
```

1. As **Alice** share the Format Column for the `Name` Column
2. As **Bob** download that Format Column from the Team Share
3. Note that the new Format Column appears in the Grid for **Bob**

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 = 'ActiveTeamSharingDemo_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', 'Alert', 'SystemStatus'],
        },
      ],
      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: 'Active Team Sharing Demo' + userName,
    adaptableStateKey: `ActiveTeamSharingDemo_${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();
      },
      updateNotification: 'AlertWithNotification',
      suppressOverrideConfigWarning: true,
      updateInterval: 0.1, // unrealistic in real world
    },
    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(`ActiveTeamSharingDemo_${user}`);
            });
            context.adaptableApi.stateApi.reloadInitialState();
          },
        },
      ],
    },
  };
};
```

**`src/index.ts`**

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

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

import './styles.css';

import {gridOptions} from './gridOptions';
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);
  }

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

  currentAdaptableInstance = await Adaptable.init(
    {
      ...getAdaptableOptionsForUser(userName, updateCurrentUser),
    } as AdaptableOptions<WebFramework>,
    agGridConfig
  );
  currentAdaptableInstance.eventApi.on(
    'AdaptableReady',
    (readyInfo: AdaptableReadyInfo) => {
      /*
      if (userName == 'Alice') {
        const entitiies: AdaptableSharedEntity[] =
          readyInfo.adaptableApi.teamSharingApi.getLoadedAdaptableSharedEntities();

        if (entitiies && entitiies.length == 0) {
          // load the team share
          const formatColumns: FormatColumn[] =
            readyInfo.adaptableApi.formatColumnApi.getFormatColumnsForColumnId(
              'name'
            );
          if (formatColumns.length > 0) {
            const formatColumn: FormatColumn = formatColumns[0];
            const sharedEntityConfig: AdaptableSharedEntityConfig = {
              description: 'nice format for name',
              type: 'Active',
            };
            readyInfo.adaptableApi.teamSharingApi.shareAdaptableEntity(
              formatColumn,
              'FormatColumn',
              sharedEntityConfig
            );
            console.log('Alice has shared the Format Column');
          }
        }
      }
      if (userName == 'Bob') {
        //  setTimeout(() => {
        //  const entitiies: AdaptableSharedEntity[] = readyInfo.adaptableApi.teamSharingApi.getLoadedAdaptableSharedEntities()
        //  console.log('entities', entitiies)
        //  }, 5000);
        setTimeout(() => {
          const entitiies: AdaptableSharedEntity[] =
            readyInfo.adaptableApi.teamSharingApi.getLoadedAdaptableSharedEntities();

          if (entitiies && entitiies.length == 1) {
            const formatColumn: AdaptableSharedEntity | undefined =
              entitiies.find(
                (e: AdaptableSharedEntity) =>
                  e.Module == 'FormatColumn' && e.Type == 'Active'
              );

            if (formatColumn && formatColumn.Revision == 1) {
              readyInfo.adaptableApi.teamSharingApi.importSharedEntry(
                formatColumn
              );
            }
          }
        }, 7000);
      }
      */
    }
  );
}

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>
```

### FAQ

**What happens to my Active Object if a colleague with the same revision number saves his first?**
The Team Sharing module works on a first come, first served basis.
If, for example, you and your colleague both load Revision 3 of a Shared Entity and both make edits but he is quicker to save, then his edit to Revision 4 is persisted, and yours will be rejected.
You can still do everything locally but, practically speaking, you are now working on a local fork of the Shared Entity.
The only way to synchronise again with your colleagues is to download the latest version of the Shared Entity and repeat your actions (and hope that this time nobody interferes with your update).
