Grove.LiveView.Presence (Grove v0.1.1)
View SourceLiveView hooks for automatic presence tracking.
Use this module with Phoenix LiveView's on_mount callback to automatically
track and update presence when users join and interact with documents.
Usage
In your LiveView:
defmodule MyAppWeb.DocumentLive do
use MyAppWeb, :live_view
# Auto-track presence when connected
on_mount {Grove.LiveView.Presence, :track_presence}
def mount(%{"id" => doc_id}, session, socket) do
# Mount the tree first (sets grove_doc_id and grove_replica_id)
socket = Grove.LiveView.mount_tree(socket, doc_id,
replica_id: session["user_id"] || socket.id
)
# Initialize presence list
{:ok, assign(socket, :presences, Grove.Presence.list_replicas(doc_id))}
end
# Handle presence updates
def handle_info(%Phoenix.Socket.Broadcast{event: "presence_diff", payload: diff}, socket) do
presences = Grove.Presence.sync_diff(socket.assigns.presences, diff)
{:noreply, assign(socket, :presences, presences)}
end
endRequirements
The on_mount hook expects the following assigns to be set before it runs:
:grove_doc_id- Document identifier (set byGrove.LiveView.mount_tree/3):grove_replica_id- Replica identifier (set byGrove.LiveView.mount_tree/3)
If these are not set, the hook will skip tracking and continue normally.
Session Data
The hook reads the following from the session (if available):
"user_id"- User identifier (stored in meta)"user_name"- User display name (stored in meta)
Initial Metadata
When tracking begins, the following metadata is set:
%{
user_id: session["user_id"],
user_name: session["user_name"],
color: Grove.Presence.assign_color(replica_id),
cursor: nil,
selection: nil,
focus: nil,
joined_at: System.system_time(:second)
}
Summary
Functions
on_mount callback for automatic presence tracking.