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
32 changes: 24 additions & 8 deletions packages/datum-ui/scripts/check-component-coverage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,25 @@ function walk(dir) {
return out
}

/**
* The [section, name] pairs an export's source publishes. A source under
* src/components/ is one component; an aggregate entry under src/exports/
* (e.g. ./map re-exports Map and PlaceAutocomplete) publishes every component
* it re-exports with `export * from '../components/<section>/<name>'`.
*/
function componentsOf(source) {
const direct = source.match(/^\.\/src\/components\/(base|features)\/([^/]+)\//)
if (direct) {
return [[direct[1], direct[2]]]
}
if (!/^\.\/src\/exports\/[^/]+\.ts$/.test(source)) {
return []
}
const text = fs.readFileSync(path.join(PKG_ROOT, source), 'utf8')
return [...text.matchAll(/export \* from '\.\.\/components\/(base|features)\/([^/']+)'/g)]
.map(([, section, name]) => [section, name])
}

/** Public component exports resolved to { key, name, dir }. */
function collectComponents() {
const pkg = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'))
Expand All @@ -53,14 +72,11 @@ function collectComponents() {
if (typeof source !== 'string') {
continue
}
const m = source.match(/^\.\/src\/components\/(base|features)\/([^/]+)\//)
if (!m) {
continue
}
const [, section, name] = m
const key = `${section}/${name}`
if (!seen.has(key)) {
seen.set(key, { key, name, dir: path.join(PKG_ROOT, 'src', 'components', section, name) })
for (const [section, name] of componentsOf(source)) {
const key = `${section}/${name}`
if (!seen.has(key)) {
seen.set(key, { key, name, dir: path.join(PKG_ROOT, 'src', 'components', section, name) })
}
}
}
return [...seen.values()].sort((a, b) => a.key.localeCompare(b.key))
Expand Down
6 changes: 0 additions & 6 deletions packages/datum-ui/scripts/component-coverage-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@
"base/separator": [
"test"
],
"base/sidebar": [
"test"
],
"base/skeleton": [
"test"
],
Expand All @@ -46,8 +43,5 @@
],
"features/nprogress": [
"test"
],
"features/stepper": [
"test"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/// <reference types="@testing-library/jest-dom/vitest" />
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MapFullscreenControl, MapLocateControl, MapZoomControl } from '../index'

// A Leaflet map stand-in: the controls only call these methods and listen to
// these events, so the tests drive them directly without a real map.
const handlers = new Map<string, (event?: unknown) => void>()
const fakeMap = {
zoom: 10,
getZoom: () => fakeMap.zoom,
getMaxZoom: () => 18,
getMinZoom: () => 0,
zoomIn: vi.fn(),
zoomOut: vi.fn(),
locate: vi.fn(),
stopLocate: vi.fn(),
toggleFullscreen: vi.fn(),
on: vi.fn((event: string, handler: (event?: unknown) => void) => {
handlers.set(event, handler)
}),
off: vi.fn(),
}
let zoomEvents: Record<string, () => void> = {}

class FakeFullScreenControl {
addTo() {
return this
}

getContainer() {
return document.createElement('div')
}

remove() {}
}

// `shared` and `hooks` are modules the @repo/shadcn exports map does not
// expose, so they are mocked by path, as map-tile-layer.test.tsx does.
vi.mock('../../../../../../shadcn/ui/map/shared', () => ({
_useMap: () => fakeMap,
_useMapEvents: (events: Record<string, () => void>) => {
zoomEvents = events
return fakeMap
},
}))
vi.mock('../../../../../../shadcn/ui/map/hooks', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
useLeaflet: () => ({
L: {
Control: { FullScreen: FakeFullScreenControl },
// MapControlContainer stops clicks and scrolls on a control reaching the map.
DomEvent: { disableClickPropagation: () => {}, disableScrollPropagation: () => {} },
// The locate control marks the found location with a div icon.
divIcon: (options: unknown) => options,
},
}),
}))

beforeEach(() => {
vi.clearAllMocks()
handlers.clear()
fakeMap.zoom = 10
})

describe('mapZoomControl', () => {
it('zooms in and out', async () => {
render(<MapZoomControl />)
await userEvent.click(screen.getByRole('button', { name: /zoom in/i }))
await userEvent.click(screen.getByRole('button', { name: /zoom out/i }))
expect(fakeMap.zoomIn).toHaveBeenCalledTimes(1)
expect(fakeMap.zoomOut).toHaveBeenCalledTimes(1)
})

it('disables zoom in at the maximum zoom', () => {
fakeMap.zoom = 18
render(<MapZoomControl />)
expect(screen.getByRole('button', { name: /zoom in/i })).toBeDisabled()
expect(screen.getByRole('button', { name: /zoom out/i })).toBeEnabled()
})

it('follows the map when its zoom changes', () => {
render(<MapZoomControl />)
fakeMap.zoom = 0
act(() => zoomEvents.zoomend?.())
expect(screen.getByRole('button', { name: /zoom out/i })).toBeDisabled()
})
})

describe('mapLocateControl', () => {
it('asks the map to locate the person and reports the location', async () => {
const onLocationFound = vi.fn()
render(<MapLocateControl onLocationFound={onLocationFound} />)
await userEvent.click(screen.getByRole('button'))
expect(fakeMap.locate).toHaveBeenCalledWith(expect.objectContaining({ setView: true, maxZoom: 18 }))
const found = { latlng: { lat: 52.5, lng: 13.4 }, accuracy: 10 }
act(() => handlers.get('locationfound')?.(found))
expect(onLocationFound).toHaveBeenCalledWith(found)
})

it('reports a location error', async () => {
const onLocationError = vi.fn()
render(<MapLocateControl onLocationError={onLocationError} />)
await userEvent.click(screen.getByRole('button'))
const error = { message: 'denied', code: 1 }
act(() => handlers.get('locationerror')?.(error))
expect(onLocationError).toHaveBeenCalledWith(error)
})
})

describe('mapFullscreenControl', () => {
it('toggles fullscreen and follows the map\'s fullscreen events', async () => {
render(<MapFullscreenControl />)
await userEvent.click(screen.getByRole('button', { name: 'Enter fullscreen' }))
expect(fakeMap.toggleFullscreen).toHaveBeenCalledTimes(1)
act(() => handlers.get('enterFullscreen')?.())
expect(screen.getByRole('button', { name: 'Exit fullscreen' })).toBeInTheDocument()
act(() => handlers.get('exitFullscreen')?.())
expect(screen.getByRole('button', { name: 'Enter fullscreen' })).toBeInTheDocument()
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// <reference types="@testing-library/jest-dom/vitest" />
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { Map } from '../index'

// A smoke test with the real lazy modules: Leaflet renders into jsdom's DOM,
// so the map mounts without a browser. Controls and layers are tested with a
// fake map in map-controls.test.tsx and map-tile-layer.test.tsx.
describe('map', () => {
it('loads Leaflet and renders the map with its children', async () => {
const { container } = render(
<Map center={[52.52, 13.405]} zoom={11}>
<div data-testid="map-child" />
</Map>,
)
expect(await screen.findByTestId('map-child', {}, { timeout: 5000 })).toBeInTheDocument()
const mapElement = container.querySelector('.leaflet-container')
expect(mapElement).not.toBeNull()
expect(mapElement).toHaveClass('min-h-96')
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/// <reference types="@testing-library/jest-dom/vitest" />
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { PlaceAutocomplete } from '../index'

function feature(name: string, osmId: number) {
return {
type: 'Feature',
geometry: { type: 'Point', coordinates: [13.4, 52.5] },
properties: { osm_id: osmId, osm_type: 'N', osm_key: 'place', osm_value: 'city', type: 'city', name, country: 'Germany' },
}
}

function respond(features: ReturnType<typeof feature>[]) {
return new Response(JSON.stringify({ type: 'FeatureCollection', features }), { status: 200 })
}

afterEach(() => vi.unstubAllGlobals())

describe('placeAutocomplete', () => {
it('searches after typing and lists the results', async () => {
const fetchFn = vi.fn((_url: string) => Promise.resolve(respond([feature('Berlin', 1), feature('Bern', 2)])))
vi.stubGlobal('fetch', fetchFn)
const onResultsChange = vi.fn()
render(<PlaceAutocomplete debounceMs={0} onResultsChange={onResultsChange} />)
await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin')
expect(await screen.findByRole('option', { name: /Berlin/ })).toBeInTheDocument()
expect(screen.getByRole('option', { name: /Bern/ })).toBeInTheDocument()
// The list can show an earlier keystroke's results first; wait for the full query.
await waitFor(() => expect(String(fetchFn.mock.calls.at(-1)?.[0])).toContain('Berlin'))
await waitFor(() => expect(onResultsChange).toHaveBeenLastCalledWith(expect.arrayContaining([expect.objectContaining({ properties: expect.objectContaining({ name: 'Berlin' }) })])))
})

it('selects a result with the arrow keys and Enter, then closes the list', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([feature('Berlin', 1), feature('Bern', 2)]))))
const onPlaceSelect = vi.fn()
render(<PlaceAutocomplete debounceMs={0} onPlaceSelect={onPlaceSelect} />)
const input = screen.getByPlaceholderText('Search')
await userEvent.type(input, 'Ber')
await screen.findByRole('option', { name: /Berlin/ })
await userEvent.keyboard('{ArrowDown}{Enter}')
expect(onPlaceSelect).toHaveBeenCalledTimes(1)
expect(onPlaceSelect.mock.calls[0]![0].properties.name).toMatch(/Bern/)
await waitFor(() => expect(screen.queryByRole('option')).toBeNull())
})

it('closes the list on Escape without selecting', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([feature('Berlin', 1)]))))
const onPlaceSelect = vi.fn()
render(<PlaceAutocomplete debounceMs={0} onPlaceSelect={onPlaceSelect} />)
await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin')
await screen.findByRole('option', { name: /Berlin/ })
await userEvent.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('option')).toBeNull())
expect(onPlaceSelect).not.toHaveBeenCalled()
})

it('sends no request for a blank query', async () => {
const fetchFn = vi.fn()
vi.stubGlobal('fetch', fetchFn)
render(<PlaceAutocomplete debounceMs={0} />)
await userEvent.type(screen.getByPlaceholderText('Search'), ' ')
await new Promise(resolve => setTimeout(resolve, 20))
expect(fetchFn).not.toHaveBeenCalled()
})

it('shows the empty state when nothing matches', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([]))))
render(<PlaceAutocomplete debounceMs={0} />)
await userEvent.type(screen.getByPlaceholderText('Search'), 'Nowhere')
await waitFor(() => expect(screen.getByText(/can't find/i)).toBeInTheDocument())
})

it('shows the error state when the request fails', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')))
render(<PlaceAutocomplete debounceMs={0} />)
await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin')
// Each letter starts a search, so query afresh rather than hold an element an
// earlier search rendered.
await waitFor(() => expect(screen.getByText(/network down/)).toBeInTheDocument())
})

it('cancels an earlier search so its late response never replaces the latest results', async () => {
let resolveFirst: (value: Response) => void = () => {}
let firstSignal: AbortSignal | undefined
// Like a real fetch, the first request rejects once its signal aborts.
const fetchFn = vi.fn()
.mockImplementationOnce((_url: string, init: RequestInit) => new Promise<Response>((resolve, reject) => {
resolveFirst = resolve
firstSignal = init.signal ?? undefined
firstSignal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')))
}))
.mockImplementation(() => Promise.resolve(respond([feature('Berlin', 1)])))
vi.stubGlobal('fetch', fetchFn)
render(<PlaceAutocomplete debounceMs={50} />)
const input = screen.getByPlaceholderText('Search')
await userEvent.type(input, 'Ber')
await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1))
await userEvent.type(input, 'lin')
expect(await screen.findByRole('option', { name: /Berlin/ })).toBeInTheDocument()
expect(firstSignal?.aborted).toBe(true)
resolveFirst(respond([feature('Bermuda', 9)]))
await new Promise(resolve => setTimeout(resolve, 20))
expect(screen.queryByRole('option', { name: /Bermuda/ })).toBeNull()
})
})
Loading
Loading