Picture component improvements

This commit is contained in:
tmshv committed 2022-09-06 22:10:40 +03:00
1 parent f81bda7f46
commit 1f2cd2c83d
2 files changed
+45 -33

No files matched your search

+33 -33
View File
@@ -2,51 +2,51 @@ import s from "./picture.module.css"
import { memo } from "react" import { memo } from "react"
import Image from "next/image" import Image from "next/image"
import { Pic } from "@/types" import classnames from "classnames/bind"
import { getLayoutFromSize } from "./lib"
const modifiers = new Map([ const cx = classnames.bind(s)
["square", s.square],
["vertical", s.vertical],
["horizontal", ""],
])
function size(w: number, h: number, tolerance: number) { export type PictureProps = {
const r = w / h
if (r < 1 && r > tolerance) {
return "square"
}
if (w < h) {
return "vertical"
}
return "horizontal"
}
export type PictureProps = Pic & {
style?: React.CSSProperties style?: React.CSSProperties
src: string
alt?: string
width: number
height: number
caption?: React.ReactNode
blur?: string
wide?: boolean wide?: boolean
layoutTolerance?: number
} }
export const Picture: React.FC<PictureProps> = memo(({ wide = false, ...props }) => { export const Picture: React.FC<PictureProps> = memo(({
const ss = size(props.width, props.height, 0.95) wide: userWide = false,
const layout = modifiers.get(ss) layoutTolerance = 0.95,
const w = ss === "horizontal" ? wide : false style,
src,
alt,
width,
height,
caption,
blur,
}) => {
const layout = getLayoutFromSize(width, height, layoutTolerance)
const wide = layout === "horizontal" ? userWide : false
return ( return (
<figure className={`${s.pic} ${layout} ${w ? s.wide : ""}`}> <figure className={cx(s.pic, layout, { wide })} style={style}>
<Image <Image
className={s.img} className={s.img}
src={props.src} src={src}
alt={props.alt} alt={alt}
width={props.width} width={width}
height={props.height} height={height}
layout={"responsive"} layout={"responsive"}
blurDataURL={props.blur} blurDataURL={blur}
placeholder={props.blur ? "blur": "empty"} placeholder={blur ? "blur" : "empty"}
/> />
{!props.caption ? null : ( {!caption ? null : (
<figcaption>{props.caption}</figcaption> <figcaption>{caption}</figcaption>
)} )}
</figure> </figure>
) )
+12
View File
@@ -0,0 +1,12 @@
export function getLayoutFromSize(w: number, h: number, tolerance: number) {
const r = w / h
if (r < 1 && r > tolerance) {
return "square"
}
if (w < h) {
return "vertical"
}
return "horizontal"
}