import React, { useMemo } from 'react' import Link from '../link' import useTheme from '../styles/use-theme' import withDefaults from '../utils/with-defaults' import ImageBrowserHttpsIcon from './image-browser-https-icon' import { getBrowserColors, BrowserColors } from './styles' interface Props { title?: string url?: string showFullLink?: boolean invert?: boolean className?: string } const defaultProps = { className: '', showFullLink: false, invert: false, } type NativeAttrs = Omit, keyof Props> export type ImageBrowserProps = Props & typeof defaultProps & NativeAttrs const getHostFromUrl = (url: string) => { try { return new URL(url).host } catch (e) { return url } } const getTitle = (title: string, colors: BrowserColors) => (
{title}
) const getAddressInput = (url: string, showFullLink: boolean, colors: BrowserColors) => (
{showFullLink ? url : getHostFromUrl(url)}
) const ImageBrowser = React.forwardRef>( ( { url, title, children, showFullLink, invert, className, ...props }, ref: React.Ref, ) => { const theme = useTheme() const colors = useMemo(() => getBrowserColors(invert, theme.palette), [invert, theme.palette]) const input = useMemo(() => { if (url) return getAddressInput(url, showFullLink, colors) if (title) return getTitle(title, colors) return null }, [url, showFullLink, title, colors]) return (
{input}
{children}
) }, ) export default withDefaults(ImageBrowser, defaultProps)