Adds read-only offline navigation to Phoenix LiveView pages.
Use via FogOfWar.region/1.
Usage
For a simple public page, where everyone will see the same data, wrap the routed content in a region.
<FogOfWar.region>
<.link navigate={~p"/"}>Back to index</.link>
<output>{@detail}</output>
</FogOfWar.region>Each time they visit that route, it's cached in the browser.
Caching user-specific markup
What about multiple users? If Bob and Sally used the same open browser, they shouldn't see each other's cached content!
Use user_id to save personalized markup:
<FogOfWar.region
user_id={@current_user && @current_user.id}
require_user_id
>
<h1>Settings</h1>
<p>{@current_user && @current_user.email}</p>
</FogOfWar.region>With cached content in IndexDB encrypted at rest, to prevent low-effort dumping attacks on compromised systems. And when using user-id on a region, users can't see markup cached from other users who may have logged in on the same device.
However, it is only encrypted with a key that is stored locally. So it is possible that if Bob signs in with the same browser Sally has used, and Bob is either malicious or compromised by something that can execute scripts in his browser and knows about FogOfWar, Sally's data can be exposed.
The solution is to ensure that when Sally logs out, her key is no longer available. Let's set this up.
Cache security
To give user-specific markup much stronger security guarantees, you need to take another step.
To protect per-user snapshots after logout, enable server-derived account
keys. Configure a callback that receives the authenticated connection and
returns the same stable string as the region's user_id, or nil to deny
access. Include the tenant when account IDs are tenant-local.
config :fow, account_key_identity: {MyAppWeb.OfflineIdentity, :account_scope}For example, if your authentication plug assigns current_user:
defmodule MyAppWeb.OfflineIdentity do
def account_scope(%Plug.Conn{assigns: %{current_user: %{id: id}}}), do: to_string(id)
def account_scope(_conn), do: nil
endAdd the built-in endpoint inside your authenticated, CSRF-protected browser scope. Keep this path at the application root.
post "/_fow/account-key", FogOfWar.AccountKeyEndpoint, []FoW reuses the matching key in IndexedDB. If it is missing or belongs to another account, FoW requests a key the first time a signed-in region renders.
The built-in endpoint derives the encryption key from the application's
secret_key_base, the authenticated account scope, and the browser's
persistent device ID. The same inputs produce the same key across deploys.
Keep the secret stable across releases and replicas. If it changes, a newly
issued key cannot decrypt snapshots written with the previous key. A browser
that still holds the previous key can continue to read them until it locks
the cache or replaces that key.
Locking the cache on logout
There are two ways to lock the per-user cache: in the UI when the users click a logout button of some sort, or programmatically from the server, from any connected LiveView.
The preferred approach is in the UI, because there's no chance for eg. a redirect to accidentally outrun the clearing action.
In the UI: Wrap your existing logout control with logout/1. FoW clears the stored
account key before forwarding the click or form submission. Phoenix still
handles the session and any cross-tab refreshes.
<FogOfWar.logout>
<.link href={~p"/users/log-out"} method="delete">Log out</.link>
</FogOfWar.logout>From a LiveView: a LiveView can also request the same local clear with
push_event(socket, "fow:logout", %{}). FoW listens even when the page has no
region active, so this can be done from any LiveView.
Let the browser finish the clear before redirecting. If you need
completion, listen for the browser event fog-of-war:account-locked.
Changing cache security policy
When FoW first successfully installs a server-derived account key, it automatically removes older per-user snapshots saved using the default policy, for every account on that browser. It removes those records from IndexedDB and localStorage and keeps public snapshots. Have users reload any tabs still running the older client during the rollout.
If you switch back to the default policy, reset the FoW cache. Close
other tabs for the app, then open the browser's storage inspector for
your app's origin. Delete the fog-of-war IndexedDB database and the
localStorage entries beginning with fog-of-war:page:, then reload.
Public bundles use the same format with either policy.
Cache expiry
To expire the saved copy two hours after its last online capture:
<FogOfWar.region max_age="PT2H">
<h1>Trip details</h1>
</FogOfWar.region>- ISO 8601 is supported, from Elixir's
Durationmodule, like:PT2H(two hours),P7D(seven days),P1M(one month), andP1Y(one year, counted as 365 days). - Omit
max_ageto keep snapshots without a time limit. Offline visits do not renew the expiry. Bundled snapshots age from the time of export, so it is probably important that the bottom of your nav tree not have expiry.Durationuses 30-day months and 365-day years, and rounds up fractional milliseconds, so don't use this for anything you need to expire at a very precise date/time.
Summary
Functions
Directory containing the package's JavaScript entry and supporting modules.
Opens a floating panel for inspecting saved pages and testing offline navigation.
Clears the offline account key before activating the enclosed logout control.
Wraps the routed content that Fog of War saves for offline navigation.
Functions
Directory containing the package's JavaScript entry and supporting modules.
Opens a floating panel for inspecting saved pages and testing offline navigation.
Put the panel outside the cached region, for example in a shared LiveView layout:
<FogOfWar.dev_tools socket={@socket} enabled={true} dock="bottom-right" />To enable it across your app in development, omit enabled from the
component call and add this to config/config.exs:
config :fow, dev_tools: config_env() == :devThe panel is disabled by default. Call installFogOfWar(liveSocket)
before connecting LiveSocket to register its hook.
Use Pause to disconnect and Play to reconnect on the current route. In Cache, select a saved page to inspect its HTML or select a navigation event to see its outcome. The navigation log lasts until the document reloads.
Clear unused removes saved pages whose routes are closed in cooperating FoW tabs. It requires browser support for Web Locks.
Attributes
socket(:any) (required) - The current LiveView socket.enabled(:boolean) - Show or hide the panel explicitly. Omit to use application configuration. Defaults tonil.dock(:string) - Initial dock; a saved user layout takes precedence. Defaults to"bottom". Must be one of"top-left","top","top-right","bottom-right","bottom", or"bottom-left".semi_transparent(:boolean) - Start with a translucent panel. The toolbar toggle lets the user change it. Defaults tofalse.scale(:any) - Positive numeric scale for text, controls, and spacing. The panel keeps its dimensions. Defaults to1.0.
Clears the offline account key before activating the enclosed logout control.
Wrap only the logout link, button, or dedicated logout form. Use an ordinary
same-tab link, a native button with phx-click, or a form. To cover keyboard
form submission, wrap the whole form. FoW forwards the original control
after clearing the key so the application's existing logout handler runs.
Place the wrapper outside any region that can be rendered offline.
Use a distinct id for each wrapper if the page has more than one.
Attributes
id(:string) - Defaults to"fog-of-war-logout".- Global attributes are accepted.
Slots
inner_block(required)
Wraps the routed content that Fog of War saves for offline navigation.
Put one region at the top of each participating LiveView's rendered content.
Include any navigation and content the user needs offline. Keep persistent
controls such as dev_tools/1 outside the region. FoW saves this section and
its descendants after connected renders. Offline, it restores the saved HTML
for the destination, and server actions will be disabled until the connection
with the server comes back.
Examples
For a simple public page, where everyone will see the same data, wrap the routed content in a region.
<FogOfWar.region>
<.link navigate={~p"/"}>Back to index</.link>
<output>{@detail}</output>
</FogOfWar.region>Each time they visit that route, it's cached in the browser.
For account scoping and logout setup, use the following pattern, but also see this module's docs on cache security!
<FogOfWar.region
user_id={@current_user && @current_user.id}
require_user_id
>
<h1>Settings</h1>
<p>{@current_user && @current_user.email}</p>
</FogOfWar.region>To expire the saved copy two hours after its last online capture:
<FogOfWar.region max_age="PT2H">
<h1>Trip details</h1>
</FogOfWar.region>- ISO 8601 is supported, from Elixir's
Durationmodule, like:PT2H(two hours),P7D(seven days),P1M(one month), andP1Y(one year, counted as 365 days). - Omit
max_ageto keep snapshots without a time limit. Offline visits do not renew the expiry. Bundled snapshots age from the time of export, so it is probably important that the bottom of your nav tree not have expiry.Durationuses 30-day months and 365-day years, and rounds up fractional milliseconds, so don't use this for anything you need to expire at a very precise date/time.
Offline hooks
Use a normal LiveView hook on an element inside the region. Register it
once in offlineHooks when installing FoW, before connecting your
LiveSocket. That registers the hook for live pages and cached visits.
The region uses its usual markup.
<FogOfWar.region>
<output id="count">{@count}</output>
<span id="count-parity" phx-hook="CounterParity" data-value={@count}></span>
</FogOfWar.region>The server renders the count and leaves the label empty. The hook fills in “Even count” or “Odd count”, using the value in the element’s data attribute.
import {installFogOfWar} from "fow"
const CounterParity = {
mounted() { this.updated() },
updated() {
this.el.textContent = Number(this.el.dataset.value) % 2 === 0
? "Even count"
: "Odd count"
},
destroyed() { this.el.textContent = "" },
}
installFogOfWar(liveSocket, {offlineHooks: {CounterParity}})
liveSocket.connect()For the full LiveView callback contract, see
Client hooks via phx-hook.
LiveView calls the usual callbacks online. On a cached visit, FoW supplies
this.el and the hook's own methods, calls mounted after insertion, and
calls destroyed when the cached page leaves. Use ordinary data-* attributes
to pass values into the hook. (Of course, server events and server-driven
updates require a connected LiveView, and many existing hooks are not written
to work offline, but many hooks can be).
A cold offline launch shows the bundled startup markup. The hook mounts on the next cached navigation or when LiveView connects.
Attributes
id(:string) - Defaults to"fog-of-war-region".path(:string) - Override the cache route with a same-origin pathname such as /settings. Defaults tonil.user_id(:any) - Stable, server-assigned account identifier. Omit for public capture. Defaults tonil.require_user_id(:boolean) - Skip capture when the account ID is missing or blank. Defaults tofalse.max_age(:any) - A positive ISO 8601 duration string, Duration struct, or integer milliseconds. Omit for no expiry. Defaults tonil.class(:string) - CSS classes for the rendered section. Defaults tonil.- Global attributes are accepted. Additional HTML attributes for the section.
Slots
inner_block(required) - The routed content to save and restore.