Skip to content

Commit

Permalink
Hide seconds if duration is > 1 min
Browse files Browse the repository at this point in the history
  • Loading branch information
adriankumpf committed Jan 17, 2020
1 parent 120e82c commit 2b24f54
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
2 changes: 0 additions & 2 deletions lib/teslamate/convert.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ defmodule TeslaMate.Convert do
@week @day * 7
@divisor [@week, @day, @hour, @minute, 1]

def sec_to_str(sec) when sec < 5, do: nil

def sec_to_str(sec) when is_number(sec) do
{_, [s, m, h, d, w]} =
Enum.reduce(@divisor, {sec, []}, fn divisor, {n, acc} ->
Expand Down
19 changes: 11 additions & 8 deletions lib/teslamate_web/live/car_live/summary.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ defmodule TeslaMateWeb.CarLive.Summary do
fetch_timer: nil,
settings: settings,
translate_state: &translate_state/1,
duration: duration_str(summary.since),
duration: humanize_duration(summary.since),
error: nil,
error_timeout: nil,
loading: false
Expand Down Expand Up @@ -54,7 +54,7 @@ defmodule TeslaMateWeb.CarLive.Summary do
@impl true
def handle_info(:update_duration, socket) do
Process.send_after(self(), :update_duration, :timer.seconds(1))
{:noreply, assign(socket, duration: duration_str(socket.assigns.summary.since))}
{:noreply, assign(socket, duration: humanize_duration(socket.assigns.summary.since))}
end

def handle_info(:resume_logging, socket) do
Expand Down Expand Up @@ -84,7 +84,8 @@ defmodule TeslaMateWeb.CarLive.Summary do
end

def handle_info(%Summary{since: since} = summary, socket) do
{:noreply, assign(socket, summary: summary, duration: duration_str(since), loading: false)}
{:noreply,
assign(socket, summary: summary, duration: humanize_duration(since), loading: false)}
end

def handle_info({:status, true}, socket) do
Expand Down Expand Up @@ -150,11 +151,13 @@ defmodule TeslaMateWeb.CarLive.Summary do
defp cancel_timer(nil), do: :ok
defp cancel_timer(ref) when is_reference(ref), do: Process.cancel_timer(ref)

defp duration_str(nil), do: nil
defp humanize_duration(nil), do: nil

defp duration_str(date) do
DateTime.utc_now()
|> DateTime.diff(date, :second)
|> Convert.sec_to_str()
defp humanize_duration(date) do
case DateTime.utc_now() |> DateTime.diff(date, :second) do
dur when dur < 5 -> nil
dur when dur > 60 -> dur |> Convert.sec_to_str() |> Enum.reject(&String.ends_with?(&1, "s"))
dur -> dur |> Convert.sec_to_str()
end
end
end

0 comments on commit 2b24f54

Please sign in to comment.