Created
October 8, 2021 02:08
-
-
Save Cellane/dc257340548b03180716b0e9b61e67f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule LiveViewStudioWeb.SalesDashboardLive do | |
use LiveViewStudioWeb, :live_view | |
alias LiveViewStudio.Sales | |
def mount(_params, _session, socket) do | |
socket = | |
socket | |
|> assign_stats() | |
|> assign(refresh_interval: 5, refresh_ref: nil) | |
socket = if connected?(socket), do: assign_schedule_refresh(socket), else: socket | |
{:ok, socket} | |
end | |
def render(assigns) do | |
~H""" | |
<h1>Sales Dashboard</h1> | |
<div id="dashboard"> | |
<div class="stats"> | |
<div class="stat"> | |
<span class="value"> | |
<%= @new_orders %> | |
</span> | |
<span class="name"> | |
New Orders | |
</span> | |
</div> | |
<div class="stat"> | |
<span class="value"> | |
$<%= @sales_amount %> | |
</span> | |
<span class="name"> | |
Sales Amount | |
</span> | |
</div> | |
<div class="stat"> | |
<span class="value"> | |
<%= @satisfaction %>% | |
</span> | |
<span class="name"> | |
Satisfaction | |
</span> | |
</div> | |
</div> | |
<div class="controls"> | |
<form phx-change="select_refresh"> | |
<label> | |
Last updated at: <%= Timex.format!(@last_updated_at, "%H:%M:%S", :strftime) %> | |
</label> | |
<label for="refresh"> | |
Refresh every: | |
</label> | |
<select name="refresh"> | |
<%= options_for_select(refresh_options(), @refresh_interval) %> | |
</select> | |
</form> | |
<button phx-click="refresh"> | |
<img src="images/refresh.svg"> | |
Refresh | |
</button> | |
</div> | |
</div> | |
""" | |
end | |
def handle_event("refresh", _params, socket) do | |
{:noreply, assign_stats(socket)} | |
end | |
def handle_event( | |
"select_refresh", | |
%{"refresh" => refresh_interval}, | |
%{assigns: %{refresh_ref: refresh_ref}} = socket | |
) do | |
Process.cancel_timer(refresh_ref) | |
{:noreply, | |
socket | |
|> assign(refresh_interval: String.to_integer(refresh_interval)) | |
|> assign_schedule_refresh()} | |
end | |
def handle_info(:tick, socket) do | |
{:noreply, | |
socket | |
|> assign_stats() | |
|> assign_schedule_refresh()} | |
end | |
defp assign_stats(socket) do | |
assign(socket, | |
new_orders: Sales.new_orders(), | |
sales_amount: Sales.sales_amount(), | |
satisfaction: Sales.satisfaction(), | |
last_updated_at: Timex.now("Asia/Tokyo") | |
) | |
end | |
defp assign_schedule_refresh(%{assigns: %{refresh_interval: refresh_interval}} = socket) do | |
assign(socket, | |
refresh_ref: Process.send_after(self(), :tick, :timer.seconds(refresh_interval)) | |
) | |
end | |
defp refresh_options do | |
[{"1s", 1}, {"5s", 5}, {"15s", 15}, {"30s", 30}, {"1m", 60}] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment