Skip to content

Commit b5b6fe6

Browse files
committed
feat(json-crdt-peritext-ui): 🎸 add <Img> and <Favicon> components
1 parent 34bdb11 commit b5b6fe6

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import {createElement as h, useMemo} from 'react';
2+
import {Avatar} from 'nice-ui/lib/1-inline/Avatar';
3+
import {Img, ImgProps} from '../Img';
4+
import {getDomain} from '../../web/util';
5+
6+
export interface FaviconProps extends ImgProps {
7+
url?: string;
8+
domain?: string;
9+
size?: number;
10+
}
11+
12+
export const Favicon: React.FC<FaviconProps> = (props) => {
13+
const {domain: _domain, url, size = 16, ...rest} = props;
14+
const domain = useMemo(() => _domain || getDomain(url || ''), [_domain, url]);
15+
16+
if (!domain)
17+
return h(Avatar, {name: url || domain, width: size, height: size, letters: 1});
18+
19+
return h(Img, {
20+
...rest,
21+
alt: domain + ' favicon',
22+
width: size,
23+
height: size,
24+
src: 'https://www.google.com/s2/favicons?domain=' + domain,
25+
renderError: () => h(Img, {
26+
...rest,
27+
alt: domain + ' favicon',
28+
width: size,
29+
height: size,
30+
src: 'https://' + domain + '/favicon.ico',
31+
renderError: () => h(Avatar, {name: domain, width: size, height: size, letters: 1}),
32+
}),
33+
});
34+
};
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import {createElement, useState} from 'react';
2+
3+
export interface ImgProps extends React.ImgHTMLAttributes<HTMLImageElement> {
4+
renderError?: (error: Error | unknown, props: ImgProps) => React.ReactNode;
5+
}
6+
7+
export const Img: React.FC<ImgProps> = (props) => {
8+
const {renderError, onError, ...rest} = props;
9+
const [error, setError] = useState<unknown | undefined>(void 0);
10+
11+
if (error && renderError) return renderError(error, props);
12+
13+
return createElement('img', {...rest, onError: (e: unknown) => {
14+
setError(e);
15+
onError?.(e as any);
16+
}});
17+
};

0 commit comments

Comments
 (0)