Packages
Fog of War: offline snapshots, caching, and read-only navigation for Phoenix LiveView web and WebView apps
Current section
Files
Jump to
Current section
Files
README.md
# Fog of War for Phoenix LiveView
<p class="fow-overview-logo"><img src="assets/logo.png" alt="Fog of War: LiveView Offline" width="300"></p>
LiveView is great. Offline is also great. Fog of War is an approach to fairly easy offline, which can work for a wide variety of LiveView apps.
## What's 'Fog of War'?
'Fog of War' was an idiom from old Real-Time Strategy games. Like an explored part of a game map, it shows what was there the last time you looked!
Specifically, if you're offline, this library shows the last markup that the LiveView loaded with.
Unvisited screens are still unavailable, but you can style links to them gracefully. You can navigate around the screens you've already seen. And, for mobile, where the first visit might be while offline, you can create a bundle of important screens to 'pre-explore' the map.
If you immediately have questions, like "What?! Why?!", see the [Rationale and Approach](docs/guides/rationale.md), which goes into some more detail.
## Example apps
| Counters | Fog of War: LiveView Offline |
| --- | --- |
| [](https://fow-counters.fly.dev/) | [](https://fow.fly.dev/) |
Visit [Counters](https://fow-counters.fly.dev/) to see a basic offline/online demo. And [Fog of War: LiveView Offline](https://fow.fly.dev/) for a multiplayer game where we use it to recreate the RTS fog of war idiom, where going offline to travel through places you've already seen is a game mechanic.
Run the example apps yourself as web, desktop, or mobile apps: [example apps quickstart](docs/guides/example-apps-quickstart.md).
## Installation
Add Fog of War to the dependencies in your Phoenix app’s `mix.exs`:
```elixir
defp deps do
[
{:fow, "~> 0.1.0"},
# Your existing dependencies...
]
end
```
Run `mix deps.get` from your Phoenix app directory.
In `assets/js/app.js`, import the hook and install it before connecting your existing LiveSocket:
```javascript
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
// 1. import it,
import {FogOfWar, installFogOfWar} from "fow"
const csrfToken = document.querySelector("meta[name='csrf-token']").content
const liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
// 2. add the hook
hooks: {FogOfWar},
})
// 3. install FoW on the socket
installFogOfWar(liveSocket)
liveSocket.connect()
window.liveSocket = liveSocket
```
## Usage Example
Use one `FogOfWar` hook per participating LiveView route.
For example, let's imagine two routes in the browser scope in `lib/my_app_web/router.ex`:
```elixir
scope "/", MyAppWeb do
pipe_through :browser
live "/counter", CounterLive
live "/notes", NotesLive
end
```
In `lib/my_app_web/live/counter_live.ex`:
```elixir
defmodule MyAppWeb.CounterLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket), do: {:ok, assign(socket, count: 0)}
def handle_event("increment", _params, socket),
do: {:noreply, update(socket, :count, &(&1 + 1))}
def render(assigns) do
~H"""
<FogOfWar.region>
<nav>
<.link navigate={~p"/counter"}>Counter</.link>
<.link navigate={~p"/notes"}>Notes</.link>
</nav>
<h1>Counter</h1>
<output>{@count}</output>
<button phx-click="increment">Increment counter</button>
</FogOfWar.region>
"""
end
end
```
In `lib/my_app_web/live/notes_live.ex`:
```elixir
defmodule MyAppWeb.NotesLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, assign(socket, note: "This is the last note received from the server.")}
end
def render(assigns) do
~H"""
<FogOfWar.region max_age="PT2H">
<nav>
<.link navigate={~p"/counter"}>Counter</.link>
<.link navigate={~p"/notes"}>Notes</.link>
</nav>
<h1>Notes</h1>
<p>{@note}</p>
</FogOfWar.region>
"""
end
end
```
Visit both pages while connected. When disconnected, their links and browser Back/Forward can show their saved content. Server actions are disabled and are never queued for replay. Reconnecting after offline navigation fetches the currently displayed route from the server, thanks to Phoenix' already robust reconnection logic.
FoW saves one region per route. Put the region directly inside the main
LiveView container and include the navigation and content users need offline.
The Notes example uses `max_age="PT2H"` to expire its saved copy after two hours.
See the [region options and examples](FogOfWar.html#region/1).
## Browser storage
- FoW saves rendered pages by URL path in IndexedDB, with localStorage and
in-memory fallbacks.
- For personalized pages, use `user_id` to scope cached content to an account
and `require_user_id` to skip capture when no account is present.
See [Caching user-specific markup](FogOfWar.html#module-caching-user-specific-markup).
- For apps that need per-user snapshots to stay locked after logout, enable
server-derived account keys. See [Cache security](FogOfWar.html#module-cache-security)
and [Locking the cache on logout](FogOfWar.html#module-locking-the-cache-on-logout).
Use the developer tools below to inspect saved pages, storage usage, and navigation events.
## Developer tools
See `FogOfWar.dev_tools/1`.

## Offline hooks
A hook can run on a live page and when FoW restores that page from cache.
For example, this hook turns its element’s background red one second after it mounts.
In `assets/js/app.js`:
```javascript
const TurnRed = {
mounted() {
this.timer = setTimeout(() => { this.el.style.backgroundColor = "red" }, 1000)
},
destroyed() { clearTimeout(this.timer) },
}
const liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
hooks: {FogOfWar, TurnRed},
})
installFogOfWar(liveSocket, {offlineHooks: {TurnRed}})
liveSocket.connect()
```
Use `phx-hook="TurnRed"` on an element with an ID inside a FoW region:
```heex
<FogOfWar.region>
<p id="notice" phx-hook="TurnRed">Watch this background.</p>
</FogOfWar.region>
```
See the [region docs for lifecycle details](FogOfWar.html#region/1-offline-hooks).
## Desktop & Mobile
FoW can wrap your Phoenix site in a native WebView with a bundled startup page,
assets, and optional public offline routes. To check your toolchain first, run
[Counters from the example apps quickstart](docs/guides/example-apps-quickstart.md).
### Create the manifest
From your Phoenix app directory, run:
```sh
mix fow.manifest --name "My App" --url http://127.0.0.1:4000
```
This writes `.fow.json`. For example, a Phoenix project with the Counter and
Notes routes above might generate:
```json
{
"schema": 3,
"app": {
"name": "My App",
"slug": "my_app",
"identifier": "dev.fogofwar.myapp",
"version": "0.1.0",
"icon": null
},
"web": {
"origin": "http://127.0.0.1:4000",
"endpoint": "MyAppWeb.Endpoint",
"router": "MyAppWeb.Router",
"discovered_routes": ["/counter", "/notes"]
},
"startup": {"path": "/"},
"preload": {"paths": []},
"assets": {
"static_root": "priv/static",
"directories": ["assets", "css", "fonts", "images"]
},
"mob": {"platforms": ["android", "ios"]},
"elixirkit": {"width": 1060, "height": 760},
"default_env": "dev",
"envs": {"dev": {}}
}
```
- Set `startup.path` to the page the app opens first, for example `/counter`.
- Add routes users should be able to open on their first offline launch to
`preload.paths`, for example `["/notes"]`. Use concrete paths. The same
bundle ships to everyone who installs the app, so choose startup and preload
pages whose content and assets can be shared publicly. The startup page is
included automatically.
- Set `app.icon` to your icon’s project-relative path if one wasn’t found.
Review `app.identifier` before distributing the app.
To build against a deployed site as well as localhost, add a `prod` entry
under `envs`. This one uses the production website and a distinct app identifier:
```json
"envs": {
"dev": {},
"prod": {
"web": {"origin": "https://app.example.com"},
"app": {"identifier": "com.example.myapp"}
}
}
```
An environment’s values override the corresponding top-level defaults.
Unspecified values are inherited, so both builds open the same startup path
in this example. Commit `.fow.json` with your app.
### Build and run on desktop
The current FoW desktop wrapper builds and installs a macOS app. Tauri also
supports Windows and Linux. Those platforms would need their own FoW WebView
integration and packaging.
For a local build, start Phoenix and leave it running. The build fetches the
startup page and preload routes from the selected `web.origin`. For a hosted
build, make sure that site is reachable instead.
From your Phoenix app directory:
```sh
mix fow.desktop
```
This uses `default_env` (`dev` above), puts the app in `~/Applications`, and
registers it with Spotlight. Press **⌘ Space**, type your app’s name, and open
it. The generated source is in `.fow/dev/projects/desktop/`.
To build against the production site in the example above:
```sh
mix fow.desktop --env prod
```
Add `--force` to replace existing generated files and the installed app. Builds
with the same app name share the same installation path. If you want both
installed side by side, override `app.name` as well as `app.identifier`.
### Build and run on Android
Install the Android SDK, Platform Tools, and the [Mob toolchain](https://mob.hexdocs.pm/getting_started.html).
From your Phoenix app directory, install Mob’s generator once:
```sh
mix archive.install hex mob_new
```
Add `"android-dev": {"mob": {"platforms": ["android"]}}` under `envs` so this
build prepares just the Android bundle. It inherits your local `web.origin`.
List your virtual devices and boot one. Replace `YOUR_AVD_NAME` with a name from
the list. If the list is empty, create a device in Android Studio’s Device Manager.
These commands can run from any directory with the SDK tools on your PATH:
```sh
emulator -list-avds
emulator -avd YOUR_AVD_NAME
```
Once Android has booted, use a second terminal. If you’re building against
localhost, start Phoenix on your computer and forward the port in your manifest:
```sh
adb devices
adb reverse tcp:4000 tcp:4000
```
A hosted HTTPS origin needs no port forwarding. With more than one device
connected, use the serial from `adb devices` with `adb -s SERIAL reverse …`
and add `--device SERIAL` to the Mix command.
From your Phoenix app directory, prepare, build, and deploy in one step:
```sh
mix fow.mobile --env android-dev --platform android
```
Open the app by name in the emulator’s launcher. For a fresh build, append
`--force` to replace the bundle and generated project. For native development,
open `.fow/android-dev/projects/mobile/android/` in Android Studio after the
first build. From its parent directory, the generated Mob project also supports
`mix mob.emulators --list --android` and
`mix mob.emulators --start --id YOUR_AVD_NAME`. Keep a separate checkout of
the generated project if you plan to edit it.
## Styling offline pages and navigation
Fog of War toggles `fow-offline` on `<html>` when its coordinator enters offline mode (including the developer tools' Pause control). Add `class="fow-nav"` to a navigation link, or a container around navigation links. Fog of War toggles `fow-nav-uncached` when that link's destination is unavailable in the usable cache; a container gets the class if any of its links is unavailable. The classes update after navigation and cache changes, including changes from other tabs. Unmarked elements are left alone.
```heex
<.link navigate={~p"/counters/one"} class="my-container fow-nav">
<span class="my-thing">Counter one</span>
</.link>
```
```css
.fow-offline .my-container.fow-nav .my-thing { color: #916018; }
.fow-offline .my-container.fow-nav.fow-nav-uncached .my-thing { opacity: .4; }
.fow-offline .my-container .my-thing { /* Any offline presentation. */ }
```
`fow-nav-uncached` is maintained online too, so its usual styling should be scoped beneath `.fow-offline`. “Cached” follows the same lookup rules as offline navigation: same origin, no query string, a compatible snapshot build and schema. A hash uses its page's cached snapshot.
These classes describe availability; the coordinator still blocks offline server actions and unavailable navigation. They do not imply that an element is disabled or add an accessibility state. Style your server-action buttons separately; the Counter example dims them while offline.
For a non-link element, set `class="fow-nav" data-fog-of-war-to="/destination"`
to style it based on the destination’s offline availability.
## Optional view transitions
Use one forward/back animation for both LiveView navigation and cached visits.
Pass the same transition helper to your LiveSocket and FoW:
```javascript
import {FogOfWar, installFogOfWar, createFogOfWarTransitions} from "fow"
const transitions = createFogOfWarTransitions()
const liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
hooks: {FogOfWar},
dom: {onDocumentPatch: transitions.onDocumentPatch},
})
installFogOfWar(liveSocket, {transition: transitions.navigate})
liveSocket.connect()
```
Give the moving content a CSS `view-transition-name`. The Counter example's stylesheet demonstrates left/right animation using `html[data-fog-of-war-direction="forward"]` and `"back"`, leaving its header and developer tools fixed. Previously visited routes determine direction; a newly visited shallower route is treated as back. Ordinary events on the same route do not animate. Unsupported browsers and reduced-motion preferences use immediate updates. The slide starts when the route changes. Interactive swipe previews depend on the browser or native WebView.