2021-05-04 02:03:19 +08:00
|
|
|
defmodule LivebookWeb.UserHelpers do
|
2021-07-07 20:32:49 +08:00
|
|
|
use Phoenix.Component
|
2021-05-04 02:03:19 +08:00
|
|
|
|
|
|
|
alias Livebook.Users.User
|
|
|
|
|
|
|
|
@doc """
|
2021-07-07 20:32:49 +08:00
|
|
|
Renders user avatar.
|
2021-05-04 02:03:19 +08:00
|
|
|
|
2021-07-07 20:32:49 +08:00
|
|
|
## Examples
|
2021-05-04 02:03:19 +08:00
|
|
|
|
2021-07-07 20:32:49 +08:00
|
|
|
<.user_avatar user={@user} class="h-20 w-20" text_class="text-3xl" />
|
2021-05-04 02:03:19 +08:00
|
|
|
"""
|
2021-07-07 20:32:49 +08:00
|
|
|
def user_avatar(assigns) do
|
|
|
|
assigns =
|
|
|
|
assigns
|
|
|
|
|> assign_new(:class, fn -> "w-full h-full" end)
|
|
|
|
|> assign_new(:text_class, fn -> "" end)
|
|
|
|
|
|
|
|
~H"""
|
2021-11-02 01:20:56 +08:00
|
|
|
<div class={"#{@class} rounded-full flex items-center justify-center"}
|
|
|
|
style={"background-color: #{@user.hex_color}"}
|
|
|
|
aria-hidden="true">
|
2021-07-07 20:32:49 +08:00
|
|
|
<div class={"#{@text_class} text-gray-100 font-semibold"}>
|
|
|
|
<%= avatar_text(@user.name) %>
|
2021-05-04 02:03:19 +08:00
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
"""
|
|
|
|
end
|
|
|
|
|
|
|
|
defp avatar_text(nil), do: "?"
|
|
|
|
|
|
|
|
defp avatar_text(name) do
|
|
|
|
name
|
|
|
|
|> String.split()
|
|
|
|
|> Enum.map(&String.at(&1, 0))
|
|
|
|
|> Enum.map(&String.upcase/1)
|
|
|
|
|> case do
|
|
|
|
[initial] -> initial
|
|
|
|
initials -> List.first(initials) <> List.last(initials)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
2021-06-16 01:33:16 +08:00
|
|
|
Builds `Livebook.Users.User` using information from
|
|
|
|
session and socket.
|
2021-05-04 02:03:19 +08:00
|
|
|
|
|
|
|
Uses `user_data` from socket `connect_params` as initial
|
2021-06-16 01:33:16 +08:00
|
|
|
attributes if the socket is connected. Otherwise uses
|
|
|
|
`user_data` from session.
|
2021-05-04 02:03:19 +08:00
|
|
|
"""
|
2021-06-16 01:33:16 +08:00
|
|
|
def build_current_user(session, socket) do
|
|
|
|
%{"current_user_id" => current_user_id} = session
|
|
|
|
|
2021-05-04 02:03:19 +08:00
|
|
|
connect_params = get_connect_params(socket) || %{}
|
2021-06-16 01:33:16 +08:00
|
|
|
user_data = connect_params["user_data"] || session["user_data"] || %{}
|
2021-05-04 02:03:19 +08:00
|
|
|
|
|
|
|
case User.change(%{User.new() | id: current_user_id}, user_data) do
|
|
|
|
{:ok, user} -> user
|
|
|
|
{:error, _errors, user} -> user
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|