# Run in Tauri and installed web apps

Use this guide to fit Aster UI controls around shell chrome and screen edges,
open links and save files through [Tauri](https://tauri.app/), and show people
when the data service is unavailable. Your application owns the shell: its
configuration and permissions, the web app manifest, the service worker and
its cache policy.

Check the [supported platforms](/docs/guide/supported-platforms.md) against the system
WebView on each Tauri target and the browsers people install your web app
from.

## Content Security Policy

Aster loads its scripts and styles from files and sets dynamic styles through
JavaScript style properties, so it needs no inline scripts or style
attributes. Keep `style-src-attr 'none'` in your policy.

In Tauri, set the policy at `app.security.csp` in `tauri.conf.json`. Tauri
adds nonces and hashes for your bundled scripts and styles when it builds the
app, and its commands need `ipc:` and `http://ipc.localhost` in `connect-src`;
see [Tauri's CSP page](https://v2.tauri.app/security/csp/). Add the origins
your app calls to `connect-src`:

```json
{
  "app": {
    "security": {
      "csp": "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'none'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost https://api.example.com"
    }
  }
}
```

Add `'wasm-unsafe-eval'` to `script-src` if the app loads WebAssembly,
including the OData mock.

## Screen edges and the on-screen keyboard

Aster uses viewport insets to size and position dialogs, sheets, windows,
toasts and maximised panels, so they stay clear of the notch, the home
indicator, a title bar and the on-screen keyboard. Selects, pickers and menus
are placed by the browser's anchor positioning. The
[elements reference](/docs/reference/api/group-elements.md) lists the inset variables
and how they combine.

- On iOS, add `viewport-fit=cover` when you want the page to draw into the
  safe area:

  ```html
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  ```

- When your shell covers part of the page that Aster cannot measure, such as
  a native toolbar, set the host inset for that edge to the full distance it
  blocks, including any safe area it covers. A host inset replaces the
  computed edge:

  ```css
  :root { --aster-host-inset-top: 44px; }
  ```

- While an editable field inside an open dialog or popover has focus, Aster
  measures how much of the bottom edge the on-screen keyboard covers and keeps
  those overlays above it. Nothing needs configuring.

On phones, set a dialog's `presentation` property to `"sheet"` to open it
from the bottom edge; see the
[`presentation` reference](/docs/reference/api/attr-Dialog.presentation.md).

## Application documents

Add `aster-app` to the `html` element of a document that is an application
rather than a page of text:

```html
<html class="aster-app">
```

It turns off automatic text inflation and suppresses the WebKit long-press
callout outside inputs, textareas, editable content and elements marked
`data-copyable`. It also contains overscroll in Aster's grid scrollers, split
panes, window bodies and portlet bodies, so reaching their end does not
scroll or refresh the page behind them.

To stop the whole document from bouncing or refreshing on overscroll, set
`overscroll-behavior: none` on `html` yourself.

An installed app uses the plain shell, edge to edge; see
[Choose an app shell](/docs/guide/app-shells.md).

## Title bar for frameless windows

A desktop window without the operating system's title bar can draw its own
with [`aster-title-bar`](/docs/reference/api/group-title-bar.md): a leading View, a
centred title and trailing actions. Import `@getaster/elements-preview` and
its `styles/title-bar.css`, and place the bar at the top of the window. Its
background and title drag the window, and the buttons, links and fields in it
stay clickable. A sticky or fixed bar pinned to the top reports its bottom
edge, so dialogs, menus and toasts open below it.

In Tauri, turn off the window's native decorations in `tauri.conf.json`:

```json
{
  "app": {
    "windows": [{ "label": "main", "title": "Invoices", "decorations": false }]
  }
}
```

Then allow dragging in `src-tauri/capabilities/default.json`. The core window
defaults handle a double-click on a drag region:

```json
{
  "identifier": "default",
  "windows": ["main"],
  "permissions": ["core:default", "core:window:allow-start-dragging"]
}
```

The bar draws no minimise, maximise or close buttons. If your window needs
them, put your own buttons in `actions`, call the
[window API](https://v2.tauri.app/learn/window-customization/) from them, and
grant the matching permissions, such as `core:window:allow-minimize`,
`core:window:allow-toggle-maximize` and `core:window:allow-close`.

On macOS, a window can instead keep its traffic lights over the page with
`"titleBarStyle": "Overlay"` and `"hiddenTitle": true` in place of
`"decorations": false`. Reserve room for the buttons at the start of the bar,
and check the width on the macOS versions you support:

```css
aster-title-bar { --aster-title-bar-inset-start: 72px; }
```

For an installed web app on a desktop browser that supports
[Window Controls Overlay](https://web.dev/articles/window-controls-overlay),
set `"display": "standalone"` and include `"window-controls-overlay"` in
`display_override` in the manifest. While the overlay is visible, the bar
uses the title bar area the browser makes available.

## Links that leave the app

Field email links, Menu link items, Sidebar and Breadcrumbs links, and links
in Markdown render as plain `<a href>` elements, and no Aster element opens a
window or navigates from script. One document listener can therefore send
external links to the system browser or mail client.

The [opener plugin](https://v2.tauri.app/plugin/opener/) opens links that
target a new window, and links clicked with Control or Shift held. The
listener below handles the remaining plain clicks on the destinations your
capability allows, and tells the person when the system refuses to open one:

```ts
import { openUrl } from "@tauri-apps/plugin-opener";

const allowedOrigins = new Set(["https://help.example.com"]);

document.addEventListener("click", (event) => {
  if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
  const link = event.composedPath().find((node): node is HTMLAnchorElement => node instanceof HTMLAnchorElement && node.hasAttribute("href"));
  if (!link) return;
  const target = link.getAttribute("target") ?? document.querySelector("base[target]")?.getAttribute("target");
  if (target === "_blank") return;
  const url = new URL(link.href, location.href);
  if (url.protocol !== "mailto:" && !allowedOrigins.has(url.origin)) return;
  event.preventDefault();
  openUrl(url.href).catch(() => showMessage(`Could not open ${url.href}`));
});
```

`showMessage` stands for your application's own notice. Check an ordinary
link, a link with `target="_blank"` and one that inherits `_blank` from a
`<base target>` element. Grant the same destinations in the window's
capability:

```json
{
  "identifier": "default",
  "windows": ["main"],
  "permissions": [
    "core:default",
    {
      "identifier": "opener:allow-open-url",
      "allow": [{ "url": "https://help.example.com/*" }, { "url": "mailto:*" }]
    }
  ]
}
```

When your application handles a Sidebar route itself, call `preventDefault()`
on Sidebar's `navigate` event. Sidebar then cancels the link click before it
reaches the document listener.

## Saving exported files

[`Grid.exportCsv()`](/docs/reference/api/method-Grid.exportCsv.md) and `exportCsv()`
in `@getaster/data` return a promise for the CSV text, so your application
decides how to save it. In a browser, offer the text as a download from a
button the person pressed:

```ts
button.addEventListener("click", async () => {
  try {
    const text = await grid.exportCsv();
    const link = document.createElement("a");
    link.href = URL.createObjectURL(new Blob([text], { type: "text/csv" }));
    link.download = "orders.csv";
    link.click();
    setTimeout(() => URL.revokeObjectURL(link.href));
  } catch {
    showMessage("The export failed.");
  }
});
```

In a desktop Tauri app, install the
[dialog plugin](https://v2.tauri.app/plugin/dialog/) and the
[file system plugin](https://v2.tauri.app/plugin/file-system/), ask for a
destination, then write the file:

```ts
import { save } from "@tauri-apps/plugin-dialog";
import { writeTextFile } from "@tauri-apps/plugin-fs";

button.addEventListener("click", async () => {
  try {
    const path = await save({ defaultPath: "orders.csv", filters: [{ name: "CSV", extensions: ["csv"] }] });
    if (path !== null) await writeTextFile(path, await grid.exportCsv());
  } catch {
    showMessage("The file could not be saved.");
  }
});
```

Grant `dialog:allow-save` and `fs:allow-write-text-file`. The dialog adds the
chosen file to the file system scope until the app restarts, as the
[dialog reference](https://v2.tauri.app/reference/javascript/dialog/#save)
describes.

## Remembering settings

Grids, split panes and sidebars save their layout when you give them a
persistence key, and the conversation composer saves its editing mode. They
use the browser's local storage by default. To keep these settings in a Tauri
app's own store, supply a `Preferences` backend and await `flush()` in your
window's close handler; the
[preferences reference](/docs/reference/api/class-Preferences.md) shows a backend over
the Tauri Store plugin.

## Showing when the service is unreachable

[`DataContext.reachability`](/docs/reference/api/attr-DataContext.reachability.md)
starts as `"unknown"`. Any completed HTTP response, including an error
status, makes it `"reachable"`. An `offline` event or a request that fails
with `NetworkError` makes it `"unreachable"`, and an `online` event returns it
to `"unknown"` until a request answers. Give `fetchTransport` a `timeout` so
a request on a stalled network, including reading its body, fails with a
`NetworkError` instead of waiting indefinitely.

`DataContext.connect` has no context to report on until it succeeds, so
handle a failed connection separately:

```ts
import { DataContext, NetworkError, fetchTransport } from "@getaster/data";
import { effect } from "@preact/signals-core";

const serviceRoot = "https://api.example.com/odata";
const network = {
  subscribe(listener: (state: "online" | "offline") => void) {
    const online = () => listener("online");
    const offline = () => listener("offline");
    addEventListener("online", online);
    addEventListener("offline", offline);
    return () => {
      removeEventListener("online", online);
      removeEventListener("offline", offline);
    };
  },
};

try {
  const ctx = await DataContext.connect(fetchTransport(serviceRoot, undefined, { timeout: 15_000 }), { reachabilitySource: network });
  effect(() => { notice.hidden = ctx.reachability.value !== "unreachable"; });
} catch (error) {
  showMessage(error instanceof NetworkError ? "The service cannot be reached." : "The service could not be loaded.");
}
```

The [DataView example](/playground/dataview.html) shows a reachability
indicator next to a tracked query.

## Precaching for an installed web app

The standalone distribution's `asset-manifest.json` lists its versioned
scripts, styles and fonts with their sizes and SHA-256 hashes, plus the
optional mock WebAssembly file. Precache the files you use as one version,
and cache your application's pages and choose a policy for service data
separately; see [precache the distribution](/docs/guide/library.md#precache-the-distribution).

## Keyboard shortcuts and focus

Configure application-wide shortcuts in your shell's menus. Aster handles
keys for the control that has focus, and listens for Escape on the document
for some interactions, such as dismissing a toast while focus is on the page
body.

When a window opens or comes back to the front, focus starts where your
application puts it; [Manage focus](/docs/guide/focus.md) explains how to choose the
first target and why the focus ring can appear before the person clicks.

## Where to go next

[Supported platforms](/docs/guide/supported-platforms.md) lists the minimum WebView
versions. The [data reference](/docs/reference/api/group-data.md) covers tracked
queries, reachability and preferences in full.
