cannery/lib/cannery_web/views/view_helpers.ex

93 lines
2.3 KiB
Elixir
Raw Normal View History

2022-02-12 02:28:04 -05:00
defmodule CanneryWeb.ViewHelpers do
@moduledoc """
Contains common helpers that can be used in liveviews and regular views. These
are automatically imported into any Phoenix View using `use CanneryWeb,
:view`
"""
import Phoenix.Component
2022-02-12 02:28:04 -05:00
2022-03-04 22:05:08 -05:00
@id_length 16
2022-02-12 02:28:04 -05:00
@doc """
Returns a <time> element that renders the naivedatetime in the user's local
timezone with Alpine.js
"""
2022-02-15 22:56:49 -05:00
@spec display_datetime(NaiveDateTime.t() | nil) :: Phoenix.LiveView.Rendered.t()
def display_datetime(nil), do: ""
2022-02-15 23:52:44 -05:00
2022-02-12 02:28:04 -05:00
def display_datetime(datetime) do
assigns = %{
2022-03-04 22:05:08 -05:00
id: :crypto.strong_rand_bytes(@id_length) |> Base.url_encode64(),
2022-02-12 02:28:04 -05:00
datetime: datetime |> DateTime.from_naive!("Etc/UTC") |> DateTime.to_iso8601(:extended)
}
~H"""
<time
id={@id}
datetime={@datetime}
x-data={"{
2022-02-12 02:28:04 -05:00
date:
Intl.DateTimeFormat([], {dateStyle: 'short', timeStyle: 'long'})
2022-02-15 17:30:58 -05:00
.format(new Date(\"#{@datetime}\"))
}"}
x-text="date"
>
2022-02-15 17:30:58 -05:00
<%= @datetime %>
</time>
"""
end
@doc """
Returns a <date> element that renders the Date in the user's local
timezone with Alpine.js
"""
2022-02-15 22:56:49 -05:00
@spec display_date(Date.t() | nil) :: Phoenix.LiveView.Rendered.t()
def display_date(nil), do: ""
2022-02-15 23:52:44 -05:00
2022-02-15 17:30:58 -05:00
def display_date(date) do
2022-03-04 22:05:08 -05:00
assigns = %{
id: :crypto.strong_rand_bytes(@id_length) |> Base.url_encode64(),
date: date |> Date.to_iso8601(:extended)
}
2022-02-15 17:30:58 -05:00
~H"""
<time
id={@id}
datetime={@date}
x-data={"{
2022-02-15 17:30:58 -05:00
date:
Intl.DateTimeFormat([], {timeZone: 'Etc/UTC', dateStyle: 'short'}).format(new Date(\"#{@date}\"))
}"}
x-text="date"
>
2022-02-15 17:30:58 -05:00
<%= @date %>
2022-02-12 02:28:04 -05:00
</time>
"""
end
2022-02-15 22:41:07 -05:00
@doc """
Displays emoji as text emoji if SHIBAO_MODE is set to true :)
"""
@spec display_emoji(String.t()) :: String.t()
2022-02-15 23:52:44 -05:00
def display_emoji("😔"),
do:
if(Application.get_env(:cannery, CanneryWeb.ViewHelpers)[:shibao_mode], do: "q_q", else: "😔")
2022-02-15 22:41:07 -05:00
def display_emoji(other_emoji), do: other_emoji
2022-11-09 21:04:57 -05:00
@doc """
Get a random color in `#ffffff` hex format
## Examples
iex> random_color()
"#cc0066"
"""
@spec random_color() :: <<_::7>>
def random_color do
["#cc0066", "#ff6699", "#6666ff", "#0066cc", "#00cc66", "#669900", "#ff9900", "#996633"]
|> Enum.random()
end
2022-02-12 02:28:04 -05:00
end