45 lines
1.8 KiB
TypeScript
45 lines
1.8 KiB
TypeScript
import React, { ImgHTMLAttributes, forwardRef } from 'react';
|
|
import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl';
|
|
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
|
|
|
export interface AuthenticatedMediaProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
|
|
/** The source URL of the media (may be an authenticated media URL) */
|
|
src?: string;
|
|
/** Override for authentication - if not provided, uses useMediaAuthentication hook */
|
|
useAuthentication?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Image component that handles Matrix authenticated media.
|
|
* Automatically fetches authenticated media URLs with the proper Authorization header
|
|
* and renders them as blob URLs.
|
|
*/
|
|
export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMediaProps>(
|
|
({ src, alt, useAuthentication: useAuthOverride, ...props }, ref) => {
|
|
const useAuthFromServer = useMediaAuthentication();
|
|
const useAuthentication = useAuthOverride ?? useAuthFromServer;
|
|
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
|
|
|
|
return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
|
|
},
|
|
);
|
|
|
|
AuthenticatedMedia.displayName = 'AuthenticatedMedia';
|
|
|
|
/**
|
|
* A simpler authenticated img component for use in places like custom HTML parsers.
|
|
* This component handles its own authentication state.
|
|
*/
|
|
export type AuthenticatedImgProps = ImgHTMLAttributes<HTMLImageElement>;
|
|
|
|
export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgProps>(
|
|
({ src, alt, ...props }, ref) => {
|
|
const useAuthentication = useMediaAuthentication();
|
|
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
|
|
|
|
return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
|
|
},
|
|
);
|
|
|
|
AuthenticatedImg.displayName = 'AuthenticatedImg';
|