Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/components/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/components/package.json
Original file line number Diff line number Diff line change
@@ -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 <yerloveraaa@gmail.com>",
"homepage": "https://github.com/jmstechnologiesinc/react-native-components#readme",
Expand Down Expand Up @@ -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",
Expand Down
72 changes: 72 additions & 0 deletions packages/components/src/Layout/Feed.js
Original file line number Diff line number Diff line change
@@ -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<typeof paneMetrics>} 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 `<testID>` and `<testID>-item-<n>`
* (default `feed`)
*/
const Feed = ({ children, testID = 'feed' }) => {
const { itemWidth, gap, onLayout } = useFeedColumns();
return (
<View onLayout={onLayout} style={[styles.grid, { gap }]} testID={testID}>
{Children.toArray(children).map((child, index) => (
<View key={child.key ?? index} style={{ width: itemWidth }} testID={`${testID}-item-${index}`}>
{child}
</View>
))}
</View>
);
};

const styles = StyleSheet.create({
grid: {
flexDirection: 'row',
flexWrap: 'wrap',
},
});

export default Feed;
108 changes: 108 additions & 0 deletions packages/components/src/Layout/__tests__/Feed.test.js
Original file line number Diff line number Diff line change
@@ -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(<Provider theme={MD3LightTheme}>{element}</Provider>);
});
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 = () => (
<Feed>
<Text key="ride">Ride</Text>
<Text key="delivery">Delivery</Text>
{null}
<Text key="driver">Driver</Text>
</Feed>
);

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));
});
});
4 changes: 3 additions & 1 deletion packages/components/src/Layout/index.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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';
Expand Down
25 changes: 10 additions & 15 deletions packages/components/src/Partner/DocumentCovers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 (
<View onLayout={(event) => setWidth(event.nativeEvent.layout.width)} testID={`${testID}-covers`}>
{fitWhole ? (
<View style={{ flexDirection: 'row', gap }}>{coversAt(largeItemMax)}</View>
<View style={{ flexDirection: 'row', gap }}>{coversAt(Math.floor(share))}</View>
) : (
<ScrollView
ref={carouselRef}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import renderer, { act } from 'react-test-renderer';
import { EN, ES } from '@jmstechnologiesinc/partner';
import { Card, MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper';

import { paneMetrics } from '../../Layout/metrics';
import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization';
import DocumentCaptureCard from '../DocumentCaptureCard';
import DocumentRequirementCard from '../DocumentRequirementCard';
Expand Down Expand Up @@ -102,13 +103,13 @@ const BOTH_SIDES = [
{ uri: 'file:///front.jpg', label: 'Front' },
{ uri: 'file:///back.jpg', label: 'Back' },
];
// The cover's height, as the first cover reports it (Card.Cover's own), and the width the covers are laid out in.
const COVER_HEIGHT = 195;
// The width the covers are laid out in.
const layOut = (tree, width) =>
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", () => {
Expand Down Expand Up @@ -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(<DocumentRequirementCard item={LICENCE} covers={BOTH_SIDES} />);
// 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(<DocumentRequirementCard item={LICENCE} covers={BOTH_SIDES} />);
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', () => {
Expand Down
Loading
Loading