Files
ThreadNet-Web/src/components/views/avatars/BaseAvatar.tsx
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

141 lines
4.7 KiB
TypeScript
Raw Normal View History

/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
2024-09-09 14:57:16 +01:00
Copyright 2019 Michael Telatynski <7t3chguy@gmail.com>
Copyright 2018 New Vector Ltd
Copyright 2015, 2016 OpenMarket Ltd
2024-09-09 14:57:16 +01:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import React, { AriaRole, forwardRef, useCallback, useContext, useEffect, useState } from "react";
2020-07-07 15:18:10 +01:00
import classNames from "classnames";
2024-08-05 08:59:27 +01:00
import { ClientEvent, SyncState } from "matrix-js-sdk/src/matrix";
import { Avatar } from "@vector-im/compound-web";
2021-06-18 16:13:55 +01:00
import SettingsStore from "../../../settings/SettingsStore";
import { ButtonEvent } from "../elements/AccessibleButton";
2019-12-17 17:26:12 +00:00
import MatrixClientContext from "../../../contexts/MatrixClientContext";
import { useTypedEventEmitter } from "../../../hooks/useEventEmitter";
import { _t } from "../../../languageHandler";
import { useScopedRoomContext } from "../../../contexts/ScopedRoomContext.tsx";
2020-07-06 22:42:46 +01:00
interface IProps {
name?: React.ComponentProps<typeof Avatar>["name"]; // The name (first initial used as default)
idName?: React.ComponentProps<typeof Avatar>["id"]; // ID for generating hash colours
title?: string; // onHover title text
url?: string | null; // highest priority of them all, shortcut to set in urls[0]
urls?: string[]; // [highest_priority, ... , lowest_priority]
type?: React.ComponentProps<typeof Avatar>["type"];
size: string;
onClick?: (ev: ButtonEvent) => void;
2020-07-07 15:18:10 +01:00
className?: string;
2022-04-22 17:09:44 +02:00
tabIndex?: number;
altText?: string;
role?: AriaRole;
2020-07-06 22:42:46 +01:00
}
const calculateUrls = (url?: string | null, urls?: string[], lowBandwidth = false): string[] => {
// work out the full set of urls to try to load. This is formed like so:
// imageUrls: [ props.url, ...props.urls ]
let _urls: string[] = [];
if (!lowBandwidth) {
_urls = urls || [];
if (url) {
// copy urls and put url first
_urls = [url, ..._urls];
}
}
// deduplicate URLs
return Array.from(new Set(_urls));
};
const useImageUrl = ({ url, urls }: { url?: string | null; urls?: string[] }): [string, () => void] => {
// Since this is a hot code path and the settings store can be slow, we
// use the cached lowBandwidth value from the room context if it exists
const roomContext = useScopedRoomContext("lowBandwidth");
const lowBandwidth = roomContext?.lowBandwidth ?? SettingsStore.getValue("lowBandwidth");
const [imageUrls, setUrls] = useState<string[]>(calculateUrls(url, urls, lowBandwidth));
const [urlsIndex, setIndex] = useState<number>(0);
2020-05-24 14:12:16 +01:00
const onError = useCallback(() => {
setIndex((i) => i + 1); // try the next one
}, []);
2018-02-06 17:50:53 +00:00
2020-02-21 10:41:33 +00:00
useEffect(() => {
setUrls(calculateUrls(url, urls, lowBandwidth));
2020-02-21 10:41:33 +00:00
setIndex(0);
}, [url, JSON.stringify(urls)]); // eslint-disable-line react-hooks/exhaustive-deps
2020-02-21 10:41:33 +00:00
const cli = useContext(MatrixClientContext);
2024-08-05 08:59:27 +01:00
const onClientSync = useCallback((syncState: SyncState, prevState: SyncState | null) => {
2020-02-21 10:41:33 +00:00
// Consider the client reconnected if there is no error with syncing.
// This means the state could be RECONNECTING, SYNCING, PREPARED or CATCHUP.
const reconnected = syncState !== "ERROR" && prevState !== syncState;
2020-05-24 14:12:16 +01:00
if (reconnected) {
2020-05-25 19:02:44 +01:00
setIndex(0);
}
2020-05-24 14:12:16 +01:00
}, []);
useTypedEventEmitter(cli, ClientEvent.Sync, onClientSync);
2020-02-21 10:41:33 +00:00
const imageUrl = imageUrls[urlsIndex];
2020-05-24 14:12:16 +01:00
return [imageUrl, onError];
2020-02-21 10:41:33 +00:00
};
const BaseAvatar = forwardRef<HTMLElement, IProps>((props, ref) => {
2020-02-21 10:41:33 +00:00
const {
name,
idName,
2023-09-01 10:45:50 +01:00
title,
2020-02-21 10:41:33 +00:00
url,
urls,
size = "40px",
2020-02-21 10:41:33 +00:00
onClick,
className,
type = "round",
altText = _t("common|avatar"),
2020-02-21 10:41:33 +00:00
...otherProps
} = props;
2021-06-29 13:11:58 +01:00
const [imageUrl, onError] = useImageUrl({ url, urls });
2020-02-21 10:41:33 +00:00
const extraProps: Partial<React.ComponentProps<typeof Avatar>> = {};
2020-02-21 10:41:33 +00:00
if (onClick) {
extraProps["aria-live"] = "off";
extraProps["role"] = "button";
} else if (!imageUrl) {
extraProps["role"] = "presentation";
extraProps["aria-label"] = undefined;
2020-02-21 10:41:33 +00:00
} else {
extraProps["role"] = undefined;
2020-02-21 10:41:33 +00:00
}
return (
<Avatar
ref={ref}
src={imageUrl}
id={idName ?? ""}
name={name ?? ""}
type={type}
size={size}
className={classNames("mx_BaseAvatar", className)}
aria-label={altText}
onError={onError}
title={title}
onClick={onClick}
{...extraProps}
{...otherProps}
data-testid="avatar-img"
/>
);
});
2020-02-21 10:41:33 +00:00
export default BaseAvatar;
export type BaseAvatarType = React.FC<IProps>;