From 829ee44f70a1fa94f7b54b2f409cfbb7a00dae28 Mon Sep 17 00:00:00 2001 From: brandonkelly Date: Fri, 4 Aug 2023 07:31:58 -0700 Subject: [PATCH] User initial avatars #13492 --- src/elements/User.php | 61 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/src/elements/User.php b/src/elements/User.php index 6154535e7f8..848e626f708 100644 --- a/src/elements/User.php +++ b/src/elements/User.php @@ -99,6 +99,26 @@ class User extends Element implements IdentityInterface public const IMPERSONATE_KEY = 'Craft.UserSessionService.prevImpersonateUserId'; + private static array $photoColors = [ + 'red-100', + 'orange-200', + 'amber-200', + 'yellow-200', + 'lime-200', + 'green-200', + 'emerald-200', + 'teal-200', + 'cyan-200', + 'sky-200', + 'blue-200', + 'indigo-200', + 'violet-200', + 'purple-200', + 'fuchsia-200', + 'pink-100', + 'rose-200', + ]; + // User statuses // ------------------------------------------------------------------------- @@ -1266,7 +1286,46 @@ public function getThumbUrl(int $size): ?string */ protected function thumbSvg(): ?string { - return file_get_contents(Craft::getAlias('@appicons/user.svg')); + $name = $this->getName(); + $words = StringHelper::splitOnWords($name); + if (count($words) > 2) { + $words = [$words[0], end($words)]; + } + $initials = implode('', array_map(fn($word) => mb_strtoupper(mb_substr($word, 0, 1)), $words)); + + // Choose a color based on the UUID + $uid = strtolower($this->uid ?? '00ff'); + $color1Index = (int)base_convert(substr($uid, 0, 2), 16, 10); + $color2Index = (int)base_convert(substr($uid, 2, 2), 16, 10); + if ($color2Index >= $color1Index - 1 && $color2Index <= $color1Index + 1) { + $color2Index = $color1Index + 2; + } + $totalColors = count(self::$photoColors); + $color1 = self::$photoColors[$color1Index % $totalColors]; + $color2 = self::$photoColors[$color2Index % $totalColors]; + + $gradientId = sprintf('gradient-%s', StringHelper::randomString(10)); + + return << + + + + + + + + + + $initials + $initials + +XML; } /**