This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/domain/avatar.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2022-02-25 15:52:54 +05:30
import { Platform } from "../platform/web/Platform";
import { MediaRepository } from "../matrix/net/MediaRepository";
export function avatarInitials(name: string): string {
2020-08-17 14:17:47 +05:30
let firstChar = name.charAt(0);
if (firstChar === "!" || firstChar === "@" || firstChar === "#") {
firstChar = name.charAt(1);
2020-08-13 16:11:00 +05:30
}
2020-08-17 14:17:47 +05:30
return firstChar.toUpperCase();
2020-08-13 16:11:00 +05:30
}
/**
* calculates a numeric hash for a given string
*
* @param {string} str string to hash
*
* @return {number}
*/
2022-02-25 15:52:54 +05:30
function hashCode(str: string): number {
2020-08-13 16:11:00 +05:30
let hash = 0;
2022-02-25 15:52:54 +05:30
let i: number;
let chr: number;
2020-08-13 16:11:00 +05:30
if (str.length === 0) {
return hash;
}
for (i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return Math.abs(hash);
}
2022-02-25 15:52:54 +05:30
export function getIdentifierColorNumber(id: string): number {
2020-08-13 16:11:00 +05:30
return (hashCode(id) % 8) + 1;
2020-08-05 22:08:55 +05:30
}
2022-04-26 17:51:19 +05:30
export function getAvatarHttpUrl(avatarUrl: string | undefined, cssSize: number, platform: Platform, mediaRepository: MediaRepository): string | undefined {
if (avatarUrl) {
const imageSize = cssSize * platform.devicePixelRatio;
return mediaRepository.mxcUrlThumbnail(avatarUrl, imageSize, imageSize, "crop");
}
2022-04-26 17:51:19 +05:30
return undefined;
}