From f68070807cba4c845b1a0606593b7f26c2a962bb Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Thu, 31 Oct 2024 21:48:47 +0200 Subject: [PATCH] web/media: handle unicode correctly for fallback avatars --- web/src/api/media.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/web/src/api/media.ts b/web/src/api/media.ts index ef83ff7..b825327 100644 --- a/web/src/api/media.ts +++ b/web/src/api/media.ts @@ -70,8 +70,16 @@ function escapeHTMLChar(char: string): string { } } +function getFallbackCharacter(from: unknown, idx: number): string { + if (!from || typeof from !== "string" || from.length <= idx) { + return "" + } + // Array.from appears to be the only way to handle Unicode correctly + return Array.from(from.slice(0, (idx + 1) * 2))[idx]?.toUpperCase().toWellFormed() ?? "" +} + export const getAvatarURL = (userID: UserID, content?: Partial): string | undefined => { - const fallbackCharacter = (content?.displayname?.[0]?.toUpperCase() ?? userID[1].toUpperCase()).toWellFormed() + const fallbackCharacter = getFallbackCharacter(content?.displayname, 0) || getFallbackCharacter(userID, 1) const backgroundColor = getUserColor(userID) const [server, mediaID] = parseMXC(content?.avatar_url) if (!mediaID) {