From 65f307b1fae3c41879a5ef69ee51ea53a968e645 Mon Sep 17 00:00:00 2001 From: Chris McCord Date: Thu, 27 Jan 2022 20:42:36 -0500 Subject: [PATCH] Add ping --- assets/js/app.js | 17 +++++++++++++++++ lib/live_beats_web/live/nav.ex | 10 +++++++++- .../templates/layout/live.html.heex | 7 +++++-- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/assets/js/app.js b/assets/js/app.js index f2bfd1d..ee7f86f 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -177,6 +177,23 @@ Hooks.AudioPlayer = { formatTime(seconds){ return new Date(1000 * seconds).toISOString().substr(14, 5) } } + +Hooks.Ping = { + mounted(){ + this.handleEvent("pong", () => { + console.log("pong") + this.el.innerText = `ping: ${Date.now() - this.nowMs}ms` + this.timer = setTimeout(() => this.ping(), 1000) + }) + this.ping() + }, + destroyed(){ clearTimeout(this.timer) }, + ping(){ + this.nowMs = Date.now() + this.pushEvent("ping", {}) + } +} + let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") let liveSocket = new LiveSocket("/live", Socket, { hooks: Hooks, diff --git a/lib/live_beats_web/live/nav.ex b/lib/live_beats_web/live/nav.ex index c2dcec6..af1da2b 100644 --- a/lib/live_beats_web/live/nav.ex +++ b/lib/live_beats_web/live/nav.ex @@ -8,7 +8,9 @@ defmodule LiveBeatsWeb.Nav do {:cont, socket |> assign(active_users: MediaLibrary.list_active_profiles(limit: 20)) - |> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3)} + |> assign(:region, System.get_env("FLY_REGION")) + |> attach_hook(:active_tab, :handle_params, &handle_active_tab_params/3) + |> attach_hook(:ping, :handle_event, &handle_event/3)} end defp handle_active_tab_params(params, _url, socket) do @@ -29,6 +31,12 @@ defmodule LiveBeatsWeb.Nav do {:cont, assign(socket, active_tab: active_tab)} end + defp handle_event("ping", _, socket) do + {:halt, push_event(socket, "pong", %{})} + end + + defp handle_event(_, _, socket), do: {:cont, socket} + defp current_user_profile_username(socket) do if user = socket.assigns.current_user do user.username diff --git a/lib/live_beats_web/templates/layout/live.html.heex b/lib/live_beats_web/templates/layout/live.html.heex index 95688c4..4b8b876 100644 --- a/lib/live_beats_web/templates/layout/live.html.heex +++ b/lib/live_beats_web/templates/layout/live.html.heex @@ -24,7 +24,7 @@ <.link navigate={home_path(@current_user)}> <.icon name={:status_online} class="w-8 h-8 text-purple-600 -mt-2 inline-block" outlined/> - LiveBeats + LiveBeats <%= @region %> @@ -55,7 +55,7 @@ <.link navigate={home_path(@current_user)}> <.icon name={:status_online} class="w-8 h-8 text-purple-600 -mt-2 inline-block" outlined/> - LiveBeats + LiveBeats <%= @region %> @@ -164,4 +164,7 @@ <%= @inner_content %> +
+
+