UNPKG

curls

Version:

💪 Responsive, expressive UI primitives for React written with Style Hooks and Emotion

113 lines (101 loc) • 3 kB
function _extends() { _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } return _extends.apply(this, arguments) } import React, {useRef, useEffect, useState} from 'react' import {css} from '@emotion/core' import {createElement, useStyles} from '@style-hooks/core' import {useBasicBox} from '../Box' import {supportsCSS, loadImage, pushCss} from '../utils' import * as styles from './styles' import getImage from './getImage' const getOrientation = (width, height) => width > height ? 'landscape' : width === height ? 'square' : 'portrait' const useImageOrientation = () => { const element = useRef(null), [orientation, setOrientation] = useState('square') function _ref2({target}) { return setOrientation( getOrientation(target.naturalWidth, target.naturalHeight) ) } useEffect(() => { if (element.current !== null) { const loader = loadImage(element.current) loader.then(_ref2) return loader.cancel.bind(loader) } }, [element.current]) return [element, orientation] } const defaultStyles = { name: '1js0tti', styles: 'display:flex;position:relative;justify-content:center;align-items:center;overflow:hidden;& img{object-fit:cover;}', }, supportsObjectFit = supportsCSS('object-fit') export const useAvatar = props => useStyles( 'avatar', styles, pushCss( _extends( { size: 'sm', }, props ), defaultStyles ) ), Avatar = React.forwardRef((_ref, ref) => { let props = _extends({}, _ref) let imageRef, src = props.src if (supportsObjectFit) props.orientation = props.orientation || 'square' else { const o = useImageOrientation() imageRef = o[0] props.orientation = props.orientation || o[1] } props = useBasicBox(useAvatar(props)) const imgProps = _extends( { src, ref: el => { imageRef !== void 0 && (imageRef.current = el) if (typeof ref === 'function') ref(el) else if ( typeof ref === 'object' && ref !== null && ref.current !== void 0 ) ref.current = el }, }, props ) delete props.alt delete props.defaultSrc props.children = (props.children || getImage)(imgProps) return createElement('span', props) }) if (process.env.NODE_ENV !== 'production') { const propTypes = require('./propTypes').default, boxPropTypes = require('../Box/propTypes').default, flexPropTypes = require('../Flex/propTypes').default Avatar.displayName = 'Avatar' Avatar.propTypes = _extends({}, propTypes, boxPropTypes, flexPropTypes) }