From eb6d58261fef9e3b93df50c3a32ef356761098dc Mon Sep 17 00:00:00 2001 From: Joely Date: Tue, 10 Nov 2026 17:29:11 -0500 Subject: [PATCH] components 0.7.0 (unpublished): MD3 feed of cards; Card.Cover's 16:9 in the vendor list and the documents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Layout `Feed` (MD3 canonical layout «feed»): as many columns as fit at least `paneMetrics.fixedPane` wide (MD3's 360 dp pane), one on a phone, each item as wide as its column, 16 dp between items both ways. `feedColumns` is the geometry and `useFeedColumns` the measured hook for a virtualized list. Until measured, the window's width decides; it follows a resized window. - VendorList is that feed, virtualized: a FlatList with `numColumns` (a new list when the count changes, as React Native requires), the rows keeping the screen's margins. `sections` stays its input, flattened in order. - imageKitCard / imageKitCardLqip take the card's width and crop to 16:9 (`ar-16-9`) instead of the window's width at load time and a fixed height. - DocumentCovers shows the sides whole, side by side and sharing the width, where each is at least a feed column (360 dp), else the carousel; it no longer measures the cover's height, which now follows its width. - Peer: react-native-paper ^5.12.14 (Card.Cover keeps 16:9). Co-Authored-By: Claude Opus 5.5 --- packages/components/package-lock.json | 6 +- packages/components/package.json | 4 +- packages/components/src/Layout/Feed.js | 72 +++++++++++ .../src/Layout/__tests__/Feed.test.js | 108 +++++++++++++++++ packages/components/src/Layout/index.js | 4 +- .../components/src/Partner/DocumentCovers.js | 25 ++-- .../__tests__/documentRequirement.test.js | 27 +++-- .../components/src/VendorList/VendorList.js | 63 +++++++--- .../src/VendorList/VendorListItem.js | 19 ++- .../VendorList/__tests__/VendorList.test.js | 114 ++++++++++++++++++ packages/components/src/index.js | 3 + packages/components/src/utils.js | 26 ++-- 12 files changed, 406 insertions(+), 65 deletions(-) create mode 100644 packages/components/src/Layout/Feed.js create mode 100644 packages/components/src/Layout/__tests__/Feed.test.js create mode 100644 packages/components/src/VendorList/__tests__/VendorList.test.js diff --git a/packages/components/package-lock.json b/packages/components/package-lock.json index f9312ac8..457cca5b 100644 --- a/packages/components/package-lock.json +++ b/packages/components/package-lock.json @@ -1,12 +1,12 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.6.0", + "version": "0.7.0", "license": "ISC", "devDependencies": { "@jmstechnologiesinc/partner": "0.2.54", @@ -22,7 +22,7 @@ "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", - "@jmstechnologiesinc/react-native-paper": "^5.12.12", + "@jmstechnologiesinc/react-native-paper": "^5.12.14", "@jmstechnologiesinc/react-native-phone-input": "^1.3.16", "@jmstechnologiesinc/react-native-size-matters": "^0.4.4", "@jmstechnologiesinc/user": "^0.1.2", diff --git a/packages/components/package.json b/packages/components/package.json index 4641419b..07f41698 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -1,6 +1,6 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.6.0", + "version": "0.7.0", "description": "Biblioteca de componentes de interfaz compartida por las aplicaciones de Daxir.", "author": "yerloveraaa ", "homepage": "https://github.com/jmstechnologiesinc/react-native-components#readme", @@ -39,7 +39,7 @@ "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", - "@jmstechnologiesinc/react-native-paper": "^5.12.12", + "@jmstechnologiesinc/react-native-paper": "^5.12.14", "@jmstechnologiesinc/react-native-phone-input": "^1.3.16", "@jmstechnologiesinc/react-native-size-matters": "^0.4.4", "@jmstechnologiesinc/user": "^0.1.2", diff --git a/packages/components/src/Layout/Feed.js b/packages/components/src/Layout/Feed.js new file mode 100644 index 00000000..20461b85 --- /dev/null +++ b/packages/components/src/Layout/Feed.js @@ -0,0 +1,72 @@ +import React, { Children, useCallback, useState } from 'react'; +import { StyleSheet, View } from 'react-native'; + +import { useTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { paneMetrics } from './metrics'; +import { useWindowSizeClass } from './useWindowSizeClass'; + +/** + * The columns of an MD3 feed (canonical layout «feed») in `width`: as many as fit at least + * `paneMetrics.fixedPane` wide (MD3's 360 dp pane) with `gap` between them, never fewer than one, and + * the width each one takes. A column is whole dp, so a row never overflows its width by a fraction and + * wraps its last item. + * + * @param {number} width the width the columns share + * @param {ReturnType} metrics + * @param {number} gap the space between two columns + * @returns {{columns: number, itemWidth: number}} + */ +export const feedColumns = (width, metrics, gap) => { + const columns = Math.max(1, Math.floor((width + gap) / (metrics.fixedPane + gap))); + return { columns, itemWidth: Math.max(0, Math.floor((width - gap * (columns - 1)) / columns)) }; +}; + +/** + * The feed geometry of a block that measures itself: its `onLayout`, the `gap` between its items (both + * ways) and its columns (`feedColumns`) in its width less `inset`, the horizontal space the block keeps + * for itself. Until it is measured, the window's width decides, so a feed is laid out at its columns from + * its first frame, and a rotation or a resized window lays it out again. + * + * @param {number} [inset] the block's own horizontal margins, both sides together + * @returns {{columns: number, itemWidth: number, gap: number, onLayout: (event: object) => void}} + */ +export const useFeedColumns = (inset = 0) => { + const theme = useTheme(); + const { width: windowWidth } = useWindowSizeClass(); + const [measuredWidth, setMeasuredWidth] = useState(null); + const onLayout = useCallback((event) => setMeasuredWidth(event.nativeEvent.layout.width), []); + const gap = theme.spacing.x4; + return { ...feedColumns((measuredWidth ?? windowWidth) - inset, paneMetrics(theme), gap), gap, onLayout }; +}; + +/** + * MD3's feed canonical layout for a few items (cards): a grid of `feedColumns`, one column on a phone and + * more where they fit, each item as wide as its column. A card never stretches across a wide window. The + * block does not scroll: it lays its items out in the host's scroll. A long list scrolls virtualized with + * `useFeedColumns` (VendorList). + * + * @param {{children: React.ReactNode, testID?: string}} props testIDs `` and `-item-` + * (default `feed`) + */ +const Feed = ({ children, testID = 'feed' }) => { + const { itemWidth, gap, onLayout } = useFeedColumns(); + return ( + + {Children.toArray(children).map((child, index) => ( + + {child} + + ))} + + ); +}; + +const styles = StyleSheet.create({ + grid: { + flexDirection: 'row', + flexWrap: 'wrap', + }, +}); + +export default Feed; diff --git a/packages/components/src/Layout/__tests__/Feed.test.js b/packages/components/src/Layout/__tests__/Feed.test.js new file mode 100644 index 00000000..1b069dd5 --- /dev/null +++ b/packages/components/src/Layout/__tests__/Feed.test.js @@ -0,0 +1,108 @@ +import React from 'react'; +import { Dimensions, Text } from 'react-native'; +import renderer, { act } from 'react-test-renderer'; + +import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import Feed, { feedColumns } from '../Feed'; +import { paneMetrics } from '../metrics'; + +// MD3's feed: as many columns as fit at least a fixed pane wide, each item as wide as its column. + +const INITIAL_WINDOW = Dimensions.get('window'); +const METRICS = paneMetrics(MD3LightTheme); +// The theme's tokens are scaled under jest (size-matters on the default window): widths are taken from the theme. +const GAP = MD3LightTheme.spacing.x4; +const TWO_COLUMNS = 2 * METRICS.fixedPane + GAP; + +const setWindow = (width) => + act(() => { + Dimensions.set({ window: { ...INITIAL_WINDOW, width, height: 1000 } }); + }); + +const mounted = []; + +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + }); + act(() => { + Dimensions.set({ window: INITIAL_WINDOW }); + }); +}); + +const hostOf = (tree, testID) => + tree.root.findAll((node) => typeof node.type === 'string' && node.props.testID === testID)[0]; + +const flatStyle = (node) => Object.assign({}, ...[node.props.style].flat(Infinity).filter(Boolean)); + +const measure = (tree, width) => act(() => hostOf(tree, 'feed').props.onLayout({ nativeEvent: { layout: { width } } })); + +const feed = () => ( + + Ride + Delivery + {null} + Driver + +); + +describe('feedColumns', () => { + it('is one column until two fit at least a fixed pane wide each, with the gap between them', () => { + expect(feedColumns(TWO_COLUMNS - 1, METRICS, GAP).columns).toBe(1); + expect(feedColumns(TWO_COLUMNS, METRICS, GAP).columns).toBe(2); + expect(feedColumns(3 * METRICS.fixedPane + 2 * GAP, METRICS, GAP).columns).toBe(3); + }); + + it('is never fewer than one column, however narrow the width', () => { + expect(feedColumns(100, METRICS, GAP)).toEqual({ columns: 1, itemWidth: 100 }); + }); + + it('shares the width between the columns in whole dp, so a row never wraps by a fraction', () => { + const width = TWO_COLUMNS + 101; + const { itemWidth } = feedColumns(width, METRICS, GAP); + expect(itemWidth).toBe(Math.floor((width - GAP) / 2)); + expect(2 * itemWidth + GAP).toBeLessThanOrEqual(width); + }); +}); + +describe('Feed', () => { + it('lays its items out in a wrapping row, each as wide as its column, the gap between them both ways', () => { + const tree = render(feed()); + measure(tree, TWO_COLUMNS + 100); + expect(flatStyle(hostOf(tree, 'feed'))).toEqual( + expect.objectContaining({ flexDirection: 'row', flexWrap: 'wrap', gap: GAP }) + ); + const itemWidth = Math.floor((TWO_COLUMNS + 100 - GAP) / 2); + // An empty child is not an item. + expect(['feed-item-0', 'feed-item-1', 'feed-item-2'].map((id) => flatStyle(hostOf(tree, id)).width)).toEqual([ + itemWidth, + itemWidth, + itemWidth, + ]); + expect(hostOf(tree, 'feed-item-3')).toBeUndefined(); + }); + + it('is a single column as wide as itself on a phone', () => { + const tree = render(feed()); + measure(tree, 358); + expect(flatStyle(hostOf(tree, 'feed-item-0')).width).toBe(358); + }); + + it("until it is measured, takes its columns from the window's width, and follows a resized window", () => { + setWindow(TWO_COLUMNS); + const tree = render(feed()); + expect(flatStyle(hostOf(tree, 'feed-item-0')).width).toBe(Math.floor((TWO_COLUMNS - GAP) / 2)); + setWindow(TWO_COLUMNS - 1); + expect(flatStyle(hostOf(tree, 'feed-item-0')).width).toBe(Math.floor(TWO_COLUMNS - 1)); + }); +}); diff --git a/packages/components/src/Layout/index.js b/packages/components/src/Layout/index.js index 8af1ecc0..ff487324 100644 --- a/packages/components/src/Layout/index.js +++ b/packages/components/src/Layout/index.js @@ -1,5 +1,6 @@ // The MD3 pane system: window size classes, the collapse table, the pane -// scaffold and its pieces, and the bottom sheet a host opens itself. The side +// scaffold and its pieces, the feed of cards, and the bottom sheet a host +// opens itself. The side // sheet and the sheets' header are the scaffold's own (PaneLayout, BottomSheet); // the rail is `SideNav variant="rail"`. Web-safe // (react-native-web without stubs) and themed through `useTheme()`; every size @@ -21,6 +22,7 @@ export { paneArrangement } from './paneArrangement'; export { usePaneContext } from './PaneContext'; export { default as PaneLayout } from './PaneLayout'; export { default as ListDetail, fitsListDetail } from './ListDetail'; +export { default as Feed, feedColumns, useFeedColumns } from './Feed'; export { default as Breadcrumbs } from './Breadcrumbs'; export { default as Pane } from './Pane'; export { default as PaneHeader } from './PaneHeader'; diff --git a/packages/components/src/Partner/DocumentCovers.js b/packages/components/src/Partner/DocumentCovers.js index f198081b..a86cb811 100644 --- a/packages/components/src/Partner/DocumentCovers.js +++ b/packages/components/src/Partner/DocumentCovers.js @@ -6,13 +6,14 @@ import { Card, Modal, Portal, TouchableRipple, useTheme } from '@jmstechnologies import { accessibilityProps, isWeb } from '../accessibility'; import DocumentViewer from '../DocumentViewer/DocumentViewer'; +import { paneMetrics } from '../Layout/metrics'; import SheetHeader from '../Layout/SheetHeader'; import { localized } from '../Localization/Localization'; /** * Two covers or more: a Material 3 hero carousel, one large item with the next one peeking, or all of them whole, side - * by side, where the width fits them at Material's largest large item (twice as wide as the cover is tall, the - * cover's height measured from the first one). + * by side and sharing the width, where each one is at least as wide as a column of MD3's feed (`paneMetrics.fixedPane`, + * 360 dp: Layout `feedColumns`). A cover is Card.Cover's 16:9, so its height follows the width it is given. * * The carousel's measures are Material's (material-components-android carousel): it snaps to an item, items stand * 8 dp apart, and the item that peeks is a small item of at most 56 dp (`m3_carousel_small_item_size_max`), here the @@ -23,14 +24,14 @@ import { localized } from '../Localization/Localization'; * on is followed from the scroll position, so a new width (a rotation, a resized window) scrolls back to it. */ const CoverCarousel = ({ covers, renderCover, testID }) => { - const { spacing } = useTheme(); + const theme = useTheme(); + const { spacing } = theme; const [width, setWidth] = useState(0); - const [coverHeight, setCoverHeight] = useState(0); const carouselRef = useRef(null); const restingItem = useRef(0); const gap = spacing.x2; - // Until the carousel is measured its items are 0 wide; their height is the cover's, so nothing below moves. + // Until the carousel is measured its items are 0 wide, and so 0 tall: it takes its height on its first layout. const itemWidth = Math.max(0, width - spacing.x14 - gap); const interval = itemWidth + gap; // An item rests where it starts, but the scroll view stops at its end, where the last item shows whole and the @@ -44,27 +45,21 @@ const CoverCarousel = ({ covers, renderCover, testID }) => { 0 ); - const largeItemMax = 2 * coverHeight; - const fitWhole = coverHeight > 0 && width >= covers.length * largeItemMax + (covers.length - 1) * gap; + const share = (width - (covers.length - 1) * gap) / covers.length; + const fitWhole = share >= paneMetrics(theme).fixedPane; // `restOf` changes only with these two. useEffect(() => { carouselRef.current?.scrollTo({ x: restOf(restingItem.current), animated: false }); }, [interval, lastOffset]); - const measureCover = (event) => setCoverHeight(event.nativeEvent.layout.height); const coversAt = (coverWidth) => - covers.map((cover, index) => - renderCover(cover, index, { - style: { width: coverWidth }, - onLayout: index === 0 ? measureCover : undefined, - }) - ); + covers.map((cover, index) => renderCover(cover, index, { style: { width: coverWidth } })); return ( setWidth(event.nativeEvent.layout.width)} testID={`${testID}-covers`}> {fitWhole ? ( - {coversAt(largeItemMax)} + {coversAt(Math.floor(share))} ) : ( act(() => { - propsOf(tree, 'document-requirement-cover-0').onLayout({ nativeEvent: { layout: { height: COVER_HEIGHT } } }); propsOf(tree, 'document-requirement-covers').onLayout({ nativeEvent: { layout: { width } } }); }); +// A column of MD3's feed: the narrowest a cover is shown whole, side by side (the theme's tokens are scaled under jest). +const { fixedPane: FEED_COLUMN } = paneMetrics(MD3LightTheme); describe('requirementTitle', () => { it("is the rule's own name for the market, in the reader's language", () => { @@ -225,14 +226,24 @@ describe('DocumentRequirementCard', () => { expect(scrollTo).toHaveBeenCalledWith({ x: 2 * wider - spacing.x2 - 600, animated: false }); }); - it('shows both sides whole, without a carousel, where they fit at the largest large item', () => { + it('shows both sides whole, side by side and sharing the width, where each one fits a feed column', () => { const { spacing } = MD3LightTheme; const tree = render(); - // Twice as wide as the cover is tall, each, and the gap between them. - layOut(tree, 2 * (2 * COVER_HEIGHT) + spacing.x2); + const width = 2 * FEED_COLUMN + spacing.x2 + 100; + layOut(tree, width); + expect(hasTestID(tree, 'document-requirement-carousel')).toBe(false); + const share = Math.floor((width - spacing.x2) / 2); + expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: share }); + expect(propsOf(tree, 'document-requirement-cover-1').style).toEqual({ width: share }); + }); + + it('keeps the carousel where a side by side cover would be narrower than a feed column', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + layOut(tree, 2 * FEED_COLUMN + spacing.x2 - 1); + expect(hasTestID(tree, 'document-requirement-carousel')).toBe(true); + layOut(tree, 2 * FEED_COLUMN + spacing.x2); expect(hasTestID(tree, 'document-requirement-carousel')).toBe(false); - expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: 2 * COVER_HEIGHT }); - expect(propsOf(tree, 'document-requirement-cover-1').style).toEqual({ width: 2 * COVER_HEIGHT }); }); it('on the web, shows the scrollbar and makes each photo a button named by its label', () => { diff --git a/packages/components/src/VendorList/VendorList.js b/packages/components/src/VendorList/VendorList.js index 4ef6e6a5..d9050f55 100644 --- a/packages/components/src/VendorList/VendorList.js +++ b/packages/components/src/VendorList/VendorList.js @@ -1,27 +1,58 @@ import React from 'react'; -import { SectionList, View } from 'react-native'; +import { FlatList, View } from 'react-native'; import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; +import { useFeedColumns } from '../Layout/Feed'; +import { sectionPaddings } from '../ScreenWrapper/ScreenWrapperSection'; import VendorListItem from './VendorListItem'; const keyExtractor = (item) => `vendor-list-${item.id}`; const Separator = () => ; -const VendorList = ({ sections, onPress, withPaddingHorizontal, ...props }) => ( - ( - - )} - stickySectionHeadersEnabled={false} - showsVerticalScrollIndicator={false} - showsHorizontalScrollIndicator={false} - ItemSeparatorComponent={Separator} - ListFooterComponent={Separator} - /> -); +/** + * The vendors as MD3's feed (Layout `Feed`), virtualized: one column of cards on a phone and more where they fit, + * each card as wide as its column. `sections` is each section's `data`, in order, in one feed. With + * `withPaddingHorizontal` the cards keep the screen's side margins and the header (`ListHeaderComponent`) spans the + * whole width. + */ +const VendorList = ({ sections, onPress, withPaddingHorizontal, ...props }) => { + const { columns, itemWidth, gap, onLayout } = useFeedColumns( + withPaddingHorizontal ? sectionPaddings.left + sectionPaddings.right : 0 + ); + // A row of several columns keeps the side margins and the gap (FlatList's `columnWrapperStyle`, which a single + // column does not have); a single column's card keeps the margins itself. + const rowMargins = withPaddingHorizontal + ? { paddingLeft: sectionPaddings.left, paddingRight: sectionPaddings.right } + : null; + const cardMargins = withPaddingHorizontal + ? { marginLeft: sectionPaddings.left, marginRight: sectionPaddings.right } + : null; + + return ( + section.data)} + numColumns={columns} + columnWrapperStyle={columns > 1 ? [{ gap }, rowMargins] : undefined} + onLayout={onLayout} + keyExtractor={keyExtractor} + renderItem={({ item }) => ( + 1 ? null : cardMargins} + onPress={onPress} + /> + )} + showsVerticalScrollIndicator={false} + showsHorizontalScrollIndicator={false} + ItemSeparatorComponent={Separator} + ListFooterComponent={Separator} + /> + ); +}; export default VendorList; diff --git a/packages/components/src/VendorList/VendorListItem.js b/packages/components/src/VendorList/VendorListItem.js index b4d02315..2d0d1549 100644 --- a/packages/components/src/VendorList/VendorListItem.js +++ b/packages/components/src/VendorList/VendorListItem.js @@ -4,26 +4,23 @@ import { Card, Text, MD3LightTheme } from '@jmstechnologiesinc/react-native-pape import { VENDOR_INDUSTRIES_MAPPING } from '@jmstechnologiesinc/vendor'; import { interpunct, getMainPhoto } from '@jmstechnologiesinc/commons'; -import { sectionPaddings } from '../ScreenWrapper/ScreenWrapperSection'; import { imageKitCard, imageKitCardLqip, isPublicUrl } from '../utils'; import { localized } from '../Localization/Localization'; -const VendorListItem = ({ item, withPaddingHorizontal, onPress }) => { +/** + * One vendor's card in the feed (VendorList): `width` is its column's, which ImageKit sizes the photo to; `style` is + * the list's layout for it (its side margins in a single column). + */ +const VendorListItem = ({ item, width, style, onPress }) => { const mainPhoto = getMainPhoto(item.photos); const isPublic = isPublicUrl(mainPhoto); return ( - onPress(item)} - > + onPress(item)}> diff --git a/packages/components/src/VendorList/__tests__/VendorList.test.js b/packages/components/src/VendorList/__tests__/VendorList.test.js new file mode 100644 index 00000000..08d93474 --- /dev/null +++ b/packages/components/src/VendorList/__tests__/VendorList.test.js @@ -0,0 +1,114 @@ +jest.mock('react-native-localize', () => ({ + findBestLanguageTag: jest.fn(() => ({ languageTag: 'en', isRTL: false })), +})); + +import React from 'react'; +import { Dimensions, FlatList } from 'react-native'; +import renderer, { act } from 'react-test-renderer'; + +import { Card, MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import { paneMetrics } from '../../Layout/metrics'; +import { setI18nConfig } from '../../Localization/Localization'; +import { sectionPaddings } from '../../ScreenWrapper/ScreenWrapperSection'; +import VendorList from '../VendorList'; + +// The vendors as MD3's feed: one column of cards on a phone, more where they fit, each card as wide as its column +// and its photo fetched at that width. + +const INITIAL_WINDOW = Dimensions.get('window'); +// The theme's tokens are scaled under jest (size-matters on the default window): widths are taken from the theme. +const GAP = MD3LightTheme.spacing.x4; +const MARGINS = sectionPaddings.left + sectionPaddings.right; +const TWO_COLUMNS = 2 * paneMetrics(MD3LightTheme).fixedPane + GAP + MARGINS; +// A card is whole dp wide (Layout `feedColumns`). +const PHONE_CARD = Math.floor(390 - MARGINS); + +const vendor = (id, photo) => ({ + id, + title: `Vendor ${id}`, + photos: [photo], + industries: [], + formattedFulfillmentMethod: 'Delivery', + formattedHitDistance: '0.9 mi', +}); +const SECTIONS = [{ data: [vendor('a', 'vendors/a.jpg'), vendor('b', 'https://example.com/b.jpg')] }]; + +const mounted = []; + +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + }); + act(() => { + Dimensions.set({ window: INITIAL_WINDOW }); + }); +}); + +beforeAll(() => setI18nConfig()); + +const listOf = (tree) => tree.root.findByType(FlatList); +const cardsOf = (tree) => tree.root.findAllByType(Card); +const flatStyle = (style) => Object.assign({}, ...[style].flat(Infinity).filter(Boolean)); +const measure = (tree, width) => act(() => listOf(tree).props.onLayout({ nativeEvent: { layout: { width } } })); +const list = () => {}} />; + +describe('VendorList', () => { + it("on a phone, is one column of cards as wide as the screen's margins leave", () => { + const tree = render(list()); + measure(tree, 390); + expect(listOf(tree).props.numColumns).toBe(1); + expect(listOf(tree).props.columnWrapperStyle).toBeUndefined(); + expect(flatStyle(cardsOf(tree)[0].props.style)).toEqual( + expect.objectContaining({ + width: PHONE_CARD, + marginLeft: sectionPaddings.left, + marginRight: sectionPaddings.right, + }) + ); + }); + + it('lays the cards out in columns where two fit, the rows keeping the margins and the gap', () => { + const width = TWO_COLUMNS + 100; + const tree = render(list()); + measure(tree, width); + expect(listOf(tree).props.numColumns).toBe(2); + expect(flatStyle(listOf(tree).props.columnWrapperStyle)).toEqual({ + gap: GAP, + paddingLeft: sectionPaddings.left, + paddingRight: sectionPaddings.right, + }); + const cardStyle = flatStyle(cardsOf(tree)[0].props.style); + expect(cardStyle.width).toBe(Math.floor((width - MARGINS - GAP) / 2)); + expect(cardStyle.marginLeft).toBeUndefined(); + }); + + it('is a new list when its number of columns changes, as React Native requires', () => { + const tree = render(list()); + measure(tree, 390); + const singleColumn = listOf(tree); + measure(tree, TWO_COLUMNS); + expect(listOf(tree)).not.toBe(singleColumn); + expect(listOf(tree).props.numColumns).toBe(2); + }); + + it("fetches a vendor's photo from ImageKit at its card's width, cropped to the cover's 16:9", () => { + const tree = render(list()); + measure(tree, 390); + const [ownPhoto, publicPhoto] = tree.root.findAllByType(Card.Cover).map((cover) => cover.props.source); + expect(ownPhoto.uri).toContain(`tr:w-${PHONE_CARD},ar-16-9,`); + expect(ownPhoto.uri).toMatch(/\/vendors\/a\.jpg$/); + expect(ownPhoto.lqipUri).toContain(`tr:w-${PHONE_CARD},ar-16-9,q-1,bl-10,f-webp/`); + // A public photo is shown as it is. + expect(publicPhoto.uri).toBe('https://example.com/b.jpg'); + }); +}); diff --git a/packages/components/src/index.js b/packages/components/src/index.js index 691026a8..3b9103a3 100644 --- a/packages/components/src/index.js +++ b/packages/components/src/index.js @@ -114,6 +114,9 @@ export { PaneLayout, ListDetail, fitsListDetail, + Feed, + feedColumns, + useFeedColumns, Breadcrumbs, Pane, PaneHeader, diff --git a/packages/components/src/utils.js b/packages/components/src/utils.js index 1c330809..41336f91 100644 --- a/packages/components/src/utils.js +++ b/packages/components/src/utils.js @@ -1,7 +1,6 @@ import { Dimensions, Linking, PixelRatio, Platform } from 'react-native'; import { moderateScale } from '@jmstechnologiesinc/react-native-size-matters'; -import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; import { Config } from './Config'; @@ -95,19 +94,28 @@ function imageKitPhotoGalleryMainImageLqip(photo, cropMode = 'cm-pad_resize') { ); } -const HORIZONTAL_CARD_PADDING = MD3LightTheme.spacing.x4 * 2; -const NET_CARD_WIDTH = Dimensions.get('window').width - HORIZONTAL_CARD_PADDING; +// Card.Cover's frame (Material's 16:9 card media). ImageKit crops the photo to it at the card's own width, so the +// photo is fetched at the size the card shows it, whatever the window. +const CARD_ASPECT_RATIO = 'ar-16-9'; -function imageKitCard(photo) { +/** + * @param {string|string[]} photo + * @param {number} width the card's width, in dp + */ +function imageKitCard(photo, width) { return imagekitUrl( - `tr:w-${NET_CARD_WIDTH},h-${moderateScale( - 195 - )},q-100,pr-true,fo-auto,lo-true,${format},dpr-${PixelRatio.get()}/${photo}` + `tr:w-${Math.round( + width + )},${CARD_ASPECT_RATIO},q-100,pr-true,fo-auto,lo-true,${format},dpr-${PixelRatio.get()}/${photo}` ); } -function imageKitCardLqip(photo) { - return imagekitUrl(`tr:w-${NET_CARD_WIDTH},h-${moderateScale(195)},q-1,bl-10,f-webp/${photo}`); +/** + * @param {string|string[]} photo + * @param {number} width the card's width, in dp + */ +function imageKitCardLqip(photo, width) { + return imagekitUrl(`tr:w-${Math.round(width)},${CARD_ASPECT_RATIO},q-1,bl-10,f-webp/${photo}`); } export {