# Understand the shared data model

A grid, a form and a chart often show different parts of the same records. As
soon as users filter, edit or refresh those records, each view needs to agree
about what changed. Aster gives those views a shared data context and keeps
unsaved edits separate until they are saved.

If you have not run a page yet, start with [Get started](/docs/guide/getting-started.md).
This guide explains the pieces you will use when adding a second view or an
editing workflow.


```diagram
{
  "source": "docs/diagrams/shared-views.svg",
  "narrow": "docs/diagrams/shared-views-narrow.svg",
  "description": "A Grid and TileGrid share one collection and selection over the same DataContext record store."
}
```

## Connect once for the views that share data

A `DataContext` connects a transport to an OData service. It loads the service's
metadata and owns the schema, record store and synchronization for that context.
Use the same context for views that should share records.

```javascript
import { DataContext, fetchTransport } from "./lib/aster-ui.js";

const ctx = await DataContext.connect(
  fetchTransport("https://your-service.example/odata/")
);
```

The service metadata describes entity sets, property types, keys, relationships
and annotations such as labels, allowed values and validation constraints.
Controls use that information to choose editors and filter operators. The server
must still enforce permissions and validation; client metadata is not an access
control boundary.

For local development, the examples use an optional WebAssembly service with
the same transport interface. Replace its transport with your service connection
when ready. See [installation and distribution](/docs/guide/library.md) for the files involved.

## Connect different backends through virtual data sources

[Aster WebData](https://getaster.now/products/aster-webdata/) provides **virtual data sources** beside its
database tables. A virtual source is a short Python or TypeScript script that
returns rows, with its fields declared beside it; the server publishes OData
metadata and exposes the source's records and supported writes to the UI. The
script can call a REST API or an HTTP legacy service on a configured connection
and map the answer to the declared fields. WebData checks every row against those
fields and does the filtering, sorting and paging the script leaves undone.

Follow [the SQL and API walkthrough](/docs/guide/integrate-sql-and-apis.md) for the complete
request flow and a source definition.

This makes the combination useful for data integration applications. For example,
a device workspace can bring together inventory from a database, status from a
management API and records from a legacy service's HTTP interface. Aster UI consumes
the service contract for those sources through its existing collections, forms
and grids; each view does not need its own backend-specific integration.

Virtual sources can also participate in workflows that read or write other data
sources. Virtual-source scripts and operations can fetch, insert, update or
delete records in another set through `db`, subject to access policy and
the execution context. This goes beyond displaying several APIs on one page:
the integration logic can live behind the shared service contract.

The distinction between a workflow and a transaction matters. Cross-source
calls do not imply automatic joins across arbitrary backends or an atomic
transaction covering a database and a REST service. Atomic write support
is bounded by the participating backends' declared transaction capabilities.
Design partial-failure handling for external effects and check the server
release's supported query and write operations.

Virtual-source adapters run on the server; they are not bundled into the UI
packages. Query pushdown depends on what the adapter declares and implements.
Without pushdown, the engine filters, sorts and pages the returned records within
its configured limits; this is not a substitute for an efficient adapter over a
large remote dataset.

## A collection is a query and its loaded pages

The record store holds shared records. A `Collection` holds a query and the keys
at positions in that query's result. It loads pages as views need them; it does
not have to hold the entire result before a user can scroll or filter it.

```javascript
const devices = ctx.collection(
  { set: "Devices", orderBy: [{ field: "name" }] },
  { pageSize: 40, keepPages: 4 }
);
```

Bind both a Grid and a TileGrid to `devices` to share the same result. Changes to
the query apply to the service result, including records on pages that have not
loaded. A known update reaches views through the record store. If an update's
position in a partially loaded result is uncertain, the collection refreshes the
relevant result rather than guessing its order.

Query results are not a snapshot transaction. Concurrent service changes may
require a refresh, and applications should handle errors while retaining useful
confirmed content. See [filtering, grouping and export](/docs/guide/filter-group-export.md)
and [stable refresh feedback](/docs/guide/connected-views.md#keep-live-refreshes-stable).

## Selection belongs to the data workflow

A `Selection` tracks record keys independently of the mounted rows or tiles.
Sharing one selection lets a user switch presentation without losing their picks.

```javascript
import { Selection } from "./lib/aster-ui.js";

const selection = new Selection(ctx.store, devices, {
  multiple: true, ordered: false, fallback: false,
});
table.ctx = tiles.ctx = ctx;
table.collection = tiles.collection = devices;
table.selection = tiles.selection = selection;
```

Here `table` and `tiles` are existing Grid and TileGrid elements. The controls
present selection; the application chooses its policy. The
[shared collection example](/examples/grid.html) demonstrates single, multiple
and ordered selection, including an optional ordered-selection limit.

## Edit a draft, then save it

```diagram
{
  "source": "docs/diagrams/save-draft.svg",
  "narrow": "docs/diagrams/save-draft-narrow.svg",
  "description": "A form edits a separate draft; after a successful save, the service response updates the shared store and its views."
}
```


An `EditModel` holds a record's uncommitted values, validation state and baseline.
A form writes into that draft. Saving sends changes to the service; a successful
response updates the shared record store, so the grid and other views follow.

```javascript
import { EditModel } from "./lib/aster-ui.js";

// key is a record key obtained from the collection or shared selection.
const edit = new EditModel(ctx, "Devices", key);
form.model = edit;
await edit.save();
```

This illustrates the ownership boundary; a real Save action handles validation,
request errors and conflicts, and keeps the draft available when saving fails.
The edit model tracks concurrency information when the service supplies it.
Resolve a conflict explicitly rather than discarding someone's input.

Decide what happens when selection changes with a dirty draft: refuse the move,
ask for confirmation, or retain an editor per record. The
[connected grid and form](/docs/guide/connected-views.md) introduces the flow;
[retained sessions](/docs/guide/keyed-sessions.md) covers longer-lived editors. Dispose edit
models when their owner releases them.

## Share state without wiring controls together

Use a `PageScope` to publish named state such as the active selection or editor.
PageRules can read that state to explain why an action is unavailable. For
example, Save can depend on a dirty editor that is not already saving.

Use `SharedFilters` when charts, lists and summary widgets intentionally
contribute criteria to the same workspace. Participation is explicit: a view
chooses which contributions it consumes. The
[dashboard guide](/docs/guide/dashboard-widgets.md) demonstrates that pattern.

[JS or YAML composition](/docs/guide/declarative-workspace.md) can declare these relationships,
while registered JS functions own requests, commands and cleanup. Choose it when
several controls and their lifecycles form a reusable workspace; ordinary JS
property assignment remains available for small pages.

## Release resources with their owner

A screen that creates a collection owns releasing it with `ctx.release(devices)`.
A control borrowing that collection does not become its owner. The screen also
stops its effects and disposes edit models that it created. Selection has no
dispose method; release references to it when the owning workflow ends.
Composition models can register cleanup with their lifetime so the same rule
holds when a workspace is removed or recreated.

Avoid recreating the context or collection on every render. Keep stable record
keys in custom templates, and let signals update the affected values. See
[composition ownership](/docs/guide/workspace-patterns.md) for activation and cleanup patterns.

## Service and realtime boundaries

The connected views in this guide synchronize every change known to their
shared context. When another user changes a record, the application reports it
with `ctx.reload(set, key, "external")`, typically from a server event or a
periodic refresh. The context reads the record again, every view showing it
updates, a collection drops it if it no longer matches the filter, and an open
edit either takes in the change or reports a conflict on the fields the user
edited. The examples' "another user" controls drive this same path.
Authentication is application-configured; see
[authentication and session recovery](/docs/guide/authentication.md).

For detailed APIs use [DataContext](/docs/reference/api/class-DataContext.md),
[Collection](/docs/reference/api/class-Collection.md), [Selection](/docs/reference/api/class-Selection.md)
and [EditModel](/docs/reference/api/class-EditModel.md). The
[data core internals](/docs/guide/data.md) explain implementation details when you need them.

## Continue with an editable screen

Next, [connect a grid and form](/docs/guide/connected-views.md) to apply the context,
selection and draft ownership described here. Then
[compose a workspace](/docs/guide/declarative-workspace.md) when you want reusable named
children, commands and lazy views around that model.
