import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; import { mosaicCount } from '@/test/arbitraries'; import { MOSAIC_MAX_PHOTOS, mosaicLayout, type MosaicTile, } from './mosaicLayout'; // The grid cells ("column,row") a tile covers, from its 'start / end' strings function cells(tile: MosaicTile): string[] { const [c0, c1] = tile.column.split(' / ').map(Number); const [r0, r1] = tile.row.split(' / ').map(Number); const result: string[] = []; for (let c = c0; c < c1; c++) { for (let r = r0; r < r1; r++) result.push(`${c},${r}`); } return result; } describe('mosaicLayout', () => { it('gives nothing for 0, a negative or a fractional count', () => { expect(mosaicLayout(0)).toEqual([]); expect(mosaicLayout(-1)).toEqual([]); expect(mosaicLayout(1.5)).toEqual([]); expect(mosaicLayout(Number.NaN)).toEqual([]); }); it('gives one wide tile for 1', () => { expect(mosaicLayout(1)).toEqual([ { column: '1 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, ]); }); it('gives two equal tiles for 2', () => { expect(mosaicLayout(2)).toEqual([ { column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, { column: '3 / 5', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, ]); }); it('gives a large and two wide tiles for 3', () => { expect(mosaicLayout(3).map((tile) => tile.phoneRatio)).toEqual([ '4 / 3', '3 / 2', '3 / 2', ]); expect(mosaicLayout(3)[2]).toMatchObject({ column: '3 / 5', row: '2 / 3', }); }); it('gives design E for 4, and the same for 5 or more', () => { expect(mosaicLayout(4)).toEqual([ { column: '1 / 3', row: '1 / 3', wide: true, phoneRatio: '4 / 3' }, { column: '3 / 5', row: '1 / 2', wide: true, phoneRatio: '3 / 2' }, { column: '3 / 4', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, { column: '4 / 5', row: '2 / 3', wide: false, phoneRatio: '1 / 1' }, ]); expect(mosaicLayout(5)).toEqual(mosaicLayout(4)); expect(mosaicLayout(12)).toEqual(mosaicLayout(4)); }); it('returns fresh objects, so a caller cannot change the layout', () => { mosaicLayout(4)[0].column = 'x'; expect(mosaicLayout(4)[0].column).toBe('1 / 3'); }); it('fills the 4 x 2 grid without overlap and stays well formed (invariant)', () => { fc.assert( fc.property(mosaicCount, (count) => { const tiles = mosaicLayout(count); expect(mosaicLayout(count)).toEqual(tiles); if (count <= 0) { expect(tiles).toEqual([]); return; } expect(tiles).toHaveLength(Math.min(count, MOSAIC_MAX_PHOTOS)); const covered = tiles.flatMap(cells); expect(new Set(covered).size).toBe(covered.length); if (count >= 2) expect(covered).toHaveLength(8); if (count >= 2) { // (A single photo, never shown, spans the whole grid) expect(tiles[0]).toMatchObject({ column: '1 / 3', row: '1 / 3', }); expect(tiles.filter((tile) => !tile.wide).length % 2).toBe( 0, ); } }), ); }); });