shift73k/lib/shift73k_web/live/live_helpers.ex

73 lines
1.8 KiB
Elixir
Raw Normal View History

2021-03-05 19:23:32 -05:00
defmodule Shift73kWeb.LiveHelpers do
2020-09-14 10:17:47 -04:00
import Phoenix.LiveView
2021-03-05 19:23:32 -05:00
alias Shift73k.Accounts
alias Shift73k.Accounts.User
alias Shift73kWeb.UserAuth
alias Shift73k.Shifts
2020-09-14 12:22:25 -04:00
@doc """
Performs the {:noreply, socket} for a given socket.
This helps make the noreply pipeable
"""
def live_noreply(socket), do: {:noreply, socket}
@doc """
Performs the {:ok, socket} for a given socket.
This helps make the ok reply pipeable
"""
def live_okreply(socket), do: {:ok, socket}
@doc """
Loads default assigns for liveviews
"""
def assign_defaults(socket, session) do
2021-03-05 19:23:32 -05:00
Shift73kWeb.Endpoint.subscribe(UserAuth.pubsub_topic())
assign_current_user(socket, session)
2020-09-14 10:17:47 -04:00
end
# For liveviews, ensures current_user is in socket assigns.
def assign_current_user(socket, session) do
2020-09-14 10:17:47 -04:00
with user_token when not is_nil(user_token) <- session["user_token"],
%User{} = user <- Accounts.get_user_by_session_token(user_token) do
assign(socket, :current_user, user)
else
_ -> socket
end
2020-09-14 10:17:47 -04:00
end
@doc """
Copies current flash into new put_flash invocations.
To be used before a push_patch.
"""
def copy_flash(%{assigns: %{flash: flash}} = socket) do
Enum.reduce(flash, socket, fn {k, v}, acc ->
put_flash(acc, String.to_existing_atom(k), v)
end)
end
2021-03-15 15:46:59 -04:00
def format_shift_time(time) do
time
|> Calendar.strftime("%-I:%M%P")
|> String.trim_trailing("m")
end
2021-03-15 15:46:59 -04:00
def format_shift_length(%{} = shift_or_template) do
shift_or_template
|> Shifts.shift_length()
|> format_shift_length()
end
def format_shift_length(minutes) when is_integer(minutes) do
h = Integer.floor_div(minutes, 60)
m = rem(minutes, 60)
cond do
h > 0 && m > 0 -> "#{h}h #{m}m"
h > 0 -> "#{h}h"
m > 0 -> "#{m}m"
true -> "0m"
end
2021-03-15 15:46:59 -04:00
end
2020-09-14 10:17:47 -04:00
end