From 21f4ce683d6d74326658fdaba39df6fe74b06f2d Mon Sep 17 00:00:00 2001 From: Dan Van Brunt Date: Fri, 16 Jun 2023 09:08:18 -0400 Subject: [PATCH] fix(Picture): Extend support for string based media breakpoints - now also supports defining your own breakpoints as media quires as a string of any complexity. - Non-breaking change that also works the previous way with px maxWidths. eg. `breakpoints={['(orientation: landscape)']}` --- lib/Picture.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/Picture.js b/lib/Picture.js index 8f9cc21..67a53ab 100644 --- a/lib/Picture.js +++ b/lib/Picture.js @@ -3,6 +3,7 @@ const React = require('react') const h = React.createElement const Picture = React.forwardRef(function Picture({ src, sizes, breakpoints, ...imgProps }, ref) { + if (!src) { return null } @@ -49,7 +50,7 @@ const Picture = React.forwardRef(function Picture({ src, sizes, breakpoints, ... return h( 'picture', {}, - flattendSrc.map(({ img, sizes, breakpoints, maxWidth }, i) => + flattendSrc.map(({ img, sizes, breakpoints, media }, i) => h( React.Fragment, { key: i }, @@ -59,7 +60,7 @@ const Picture = React.forwardRef(function Picture({ src, sizes, breakpoints, ... type: 'image/webp', srcSet: img.webpSrcSet, sizes: makeSizes(img, sizes, breakpoints), - ...(maxWidth ? { media: `(max-width: ${maxWidth}px)` } : {}), + media, }), img.srcSet && img.srcSet.length > 0 && @@ -67,7 +68,7 @@ const Picture = React.forwardRef(function Picture({ src, sizes, breakpoints, ... type: img.type, srcSet: img.srcSet, sizes: makeSizes(img, sizes, breakpoints), - ...(maxWidth ? { media: `(max-width: ${maxWidth}px)` } : {}), + media, }), ), ), @@ -86,11 +87,13 @@ function flattenSrc(src, sizes, breakpoints) { continue } + const breakpoint = typeof breakpoints[i] === 'number' ? `(max-width: ${breakpoints[i]}px)` : breakpoints[i] + result.push({ img: src[i], sizes: sizes[i], breakpoints: src.length === 1 ? breakpoints : [], - maxWidth: i === src.length - 1 ? null : breakpoints[i], + media: i === src.length - 1 ? null : breakpoint, }) }