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