-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathavatar.ex
114 lines (99 loc) · 2.93 KB
/
avatar.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
defmodule PetalComponents.Avatar do
use Phoenix.Component
import PetalComponents.Icon
attr(:src, :string, default: nil, doc: "hosted avatar URL")
attr(:alt, :string, default: nil, doc: "alt text for avatar image")
attr(:size, :string, default: "md", values: ["xs", "sm", "md", "lg", "xl"])
attr(:class, :any, default: nil, doc: "CSS class")
attr(:name, :string, default: nil, doc: "name for placeholder initials")
attr(:random_color, :boolean,
default: false,
doc: "generates a random color for placeholder initials avatar"
)
attr(:rest, :global)
def avatar(assigns) do
~H"""
<%= if src_blank?(@src) && !@name do %>
<div
{@rest}
role="img"
aria-label="user avatar"
class={[
"pc-avatar--with-placeholder-icon",
"pc-avatar--#{@size}",
@class
]}
>
<.icon name="hero-user-solid" class="pc-avatar__placeholder-icon" />
</div>
<% else %>
<%= if src_blank?(@src) && @name do %>
<div
{@rest}
style={maybe_generate_random_color(@random_color, @name)}
role="img"
aria-label="user avatar"
class={[
"pc-avatar--with-placeholder-initials",
"pc-avatar--#{@size}",
@class
]}
>
{generate_initials(@name)}
</div>
<% else %>
<img
{@rest}
src={@src}
alt={@alt || @src}
class={[
"pc-avatar--with-image",
"pc-avatar--#{@size}",
@class
]}
/>
<% end %>
<% end %>
"""
end
attr(:size, :string, default: "md", values: ["xs", "sm", "md", "lg", "xl"])
attr(:class, :any, default: nil, doc: "CSS class")
attr(:avatars, :list, default: [], doc: "list of your hosted avatar URLs")
attr(:rest, :global)
def avatar_group(assigns) do
~H"""
<div {@rest} class={["pc-avatar-group--#{@size}", @class]}>
<%= for src <- @avatars do %>
<.avatar src={src} size={@size} class="pc-avatar-group" />
<% end %>
</div>
"""
end
defp src_blank?(src), do: !src || src == ""
defp maybe_generate_random_color(false, _), do: nil
defp maybe_generate_random_color(true, name) do
"background-color: #{generate_color_from_string(name)}; color: white;"
end
defp generate_color_from_string(string) do
a_number =
string
|> String.to_charlist()
|> Enum.reduce(0, fn x, acc -> x + acc end)
"hsl(#{rem(a_number, 360)}, 100%, 35%)"
end
defp generate_initials(name) when is_binary(name) do
word_array = String.split(name)
if length(word_array) == 1 do
List.first(word_array)
|> String.slice(0..1)
|> String.upcase()
else
initial1 = String.first(List.first(word_array))
initial2 = String.first(List.last(word_array))
String.upcase(initial1 <> initial2)
end
end
defp generate_initials(_) do
""
end
end