diff --git a/packages/datum-ui/scripts/check-component-coverage.mjs b/packages/datum-ui/scripts/check-component-coverage.mjs index f93c5ef3..4ec48fae 100644 --- a/packages/datum-ui/scripts/check-component-coverage.mjs +++ b/packages/datum-ui/scripts/check-component-coverage.mjs @@ -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/
/'`. + */ +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')) @@ -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)) diff --git a/packages/datum-ui/scripts/component-coverage-baseline.json b/packages/datum-ui/scripts/component-coverage-baseline.json index 58facd88..fe3585a5 100644 --- a/packages/datum-ui/scripts/component-coverage-baseline.json +++ b/packages/datum-ui/scripts/component-coverage-baseline.json @@ -29,9 +29,6 @@ "base/separator": [ "test" ], - "base/sidebar": [ - "test" - ], "base/skeleton": [ "test" ], @@ -46,8 +43,5 @@ ], "features/nprogress": [ "test" - ], - "features/stepper": [ - "test" ] } diff --git a/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx b/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx new file mode 100644 index 00000000..1ae7d560 --- /dev/null +++ b/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx @@ -0,0 +1,122 @@ +/// +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 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 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 void>) => { + zoomEvents = events + return fakeMap + }, +})) +vi.mock('../../../../../../shadcn/ui/map/hooks', async importOriginal => ({ + ...(await importOriginal>()), + 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() + 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() + 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() + 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() + 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() + 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() + 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() + }) +}) diff --git a/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx b/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx new file mode 100644 index 00000000..761ae289 --- /dev/null +++ b/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx @@ -0,0 +1,21 @@ +/// +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( + +
+ , + ) + 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') + }) +}) diff --git a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx new file mode 100644 index 00000000..921ec5e5 --- /dev/null +++ b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx @@ -0,0 +1,107 @@ +/// +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[]) { + 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() + 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() + 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() + 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() + 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() + 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() + 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((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() + 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() + }) +}) diff --git a/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx new file mode 100644 index 00000000..b58a13ae --- /dev/null +++ b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx @@ -0,0 +1,113 @@ +/// +import { fireEvent, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SidebarInput, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarTrigger, useSidebar } from '../index' + +const viewport = { mobile: false } +vi.mock('@repo/shadcn/hooks/use-mobile', () => ({ useIsMobile: () => viewport.mobile })) + +/** Shows the sidebar state the provider exposes. */ +function Probe() { + const { state, openMobile } = useSidebar() + return +} + +function renderSidebar(props: Partial> = {}) { + return render( + + + + + , + ) +} + +const state = () => screen.getByTestId('probe').getAttribute('data-state') + +beforeEach(() => { + viewport.mobile = false + // Below the lg breakpoint the provider starts collapsed; test at desktop width. + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }) + document.cookie = 'sidebar_state=; max-age=0; path=/' +}) + +afterEach(() => vi.restoreAllMocks()) + +describe('sidebarProvider', () => { + it('toggles between expanded and collapsed with the trigger', async () => { + renderSidebar() + expect(state()).toBe('expanded') + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(state()).toBe('collapsed') + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(state()).toBe('expanded') + }) + + it('starts collapsed with defaultOpen false', () => { + renderSidebar({ defaultOpen: false }) + expect(state()).toBe('collapsed') + }) + + it('reports changes through onOpenChange when controlled', async () => { + const onOpenChange = vi.fn() + renderSidebar({ open: true, onOpenChange }) + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(onOpenChange).toHaveBeenCalledWith(false) + expect(state()).toBe('expanded') + }) + + it('toggles with Cmd+B and Ctrl+B', () => { + renderSidebar() + fireEvent.keyDown(window, { key: 'b', metaKey: true }) + expect(state()).toBe('collapsed') + fireEvent.keyDown(window, { key: 'b', ctrlKey: true }) + expect(state()).toBe('expanded') + }) + + it('ignores a bare b pressed on the page', () => { + renderSidebar() + fireEvent.keyDown(window, { key: 'b' }) + expect(state()).toBe('expanded') + }) + + it('ignores a b typed in the sidebar input', async () => { + renderSidebar() + await userEvent.type(screen.getByPlaceholderText('Filter'), 'b') + expect(state()).toBe('expanded') + }) + + it('remembers the state in a cookie', async () => { + renderSidebar() + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(document.cookie).toContain('sidebar_state=false') + }) + + it('opens the mobile sheet instead of collapsing on a phone', async () => { + viewport.mobile = true + renderSidebar() + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(screen.getByTestId('probe')).toHaveAttribute('data-open-mobile', 'true') + }) +}) + +describe('sidebarMenuButton', () => { + it('marks the active item and does not run a disabled one', async () => { + const onClick = vi.fn() + render( + + + + Projects + + + Billing + + + , + ) + expect(screen.getByRole('button', { name: 'Projects' })).toHaveAttribute('data-active', 'true') + await userEvent.click(screen.getByRole('button', { name: 'Billing' })) + expect(onClick).not.toHaveBeenCalled() + }) +}) diff --git a/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx b/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx new file mode 100644 index 00000000..46248124 --- /dev/null +++ b/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx @@ -0,0 +1,118 @@ +/// +import type * as Stepperize from '@stepperize/react' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, expect, it } from 'vitest' +import { defineStepper } from '../index' +import { getStepState, onStepKeyDown, stepDomId } from '../utils' + +const { Stepper, steps } = defineStepper( + { id: 'account', title: 'Account' }, + { id: 'billing', title: 'Billing' }, + { id: 'review', title: 'Review' }, +) + +function renderStepper({ disabledStep }: { disabledStep?: string } = {}) { + return render( + + {({ methods }) => ( + <> + + {steps.map(step => ( + methods.goTo(step.id)}> + {step.title} + + ))} + + {methods.current.id} + + + + + + )} + , + ) +} + +const current = () => screen.getByTestId('current').textContent + +describe('stepper', () => { + it('starts on the first step and moves next and back', async () => { + renderStepper() + expect(current()).toBe('account') + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + expect(current()).toBe('billing') + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + expect(current()).toBe('account') + }) + + it('does not move before the first step or past the last', async () => { + renderStepper() + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + expect(current()).toBe('account') + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + expect(current()).toBe('review') + }) + + it('marks the current step and the completed ones', async () => { + renderStepper() + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + // Each step is an
  • holding its tab button and its title. + const stepItem = (title: string) => screen.getByText(title).closest('li')! + const stateOf = (title: string) => stepItem(title).getAttribute('data-state') + expect(stepItem('Billing').querySelector('[role="tab"]')).toHaveAttribute('aria-current', 'step') + expect(stateOf('Account')).toBe('completed') + expect(stateOf('Billing')).toBe('active') + expect(stateOf('Review')).toBe('inactive') + }) + + it('does not reach a disabled step by clicking it', async () => { + renderStepper({ disabledStep: 'review' }) + const reviewTab = screen.getByText('Review').closest('li')!.querySelector('[role="tab"]')! + expect(reviewTab).toBeDisabled() + await userEvent.click(reviewTab) + expect(current()).toBe('account') + // An enabled step is reachable the same way, so the check above is meaningful. + await userEvent.click(screen.getByText('Billing').closest('li')!.querySelector('[role="tab"]')!) + expect(current()).toBe('billing') + }) +}) + +describe('stepper helpers', () => { + it('derives each step\'s state from the current index', () => { + expect(getStepState(1, 0)).toBe('completed') + expect(getStepState(1, 1)).toBe('active') + expect(getStepState(1, 2)).toBe('inactive') + }) + + it('builds a stable DOM id per instance and step', () => { + expect(stepDomId('s1-', 'billing')).toBe(stepDomId('s1-', 'billing')) + expect(stepDomId('s1-', 'billing')).not.toBe(stepDomId('s2-', 'billing')) + }) + + it('moves focus with the arrow keys, and only forward to a reachable step', () => { + const make = (id: string, state: string) => { + const wrapper = document.createElement('div') + wrapper.setAttribute('data-state', state) + const button = document.createElement('button') + button.id = stepDomId('t-', id) + wrapper.append(button) + document.body.append(wrapper) + return button + } + const prev = make('a', 'completed') + const next = make('c', 'inactive') + const key = (k: string) => ({ key: k }) as React.KeyboardEvent + const step = (id: string) => ({ id }) as Stepperize.Step + onStepKeyDown(key('ArrowRight'), step('c'), step('a'), 't-') + expect(document.activeElement).not.toBe(next) + onStepKeyDown(key('ArrowLeft'), step('c'), step('a'), 't-') + expect(document.activeElement).toBe(prev) + next.parentElement!.setAttribute('data-state', 'active') + onStepKeyDown(key('ArrowDown'), step('c'), step('a'), 't-') + expect(document.activeElement).toBe(next) + }) +}) diff --git a/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx new file mode 100644 index 00000000..7587fbc6 --- /dev/null +++ b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx @@ -0,0 +1,116 @@ +/// +import type { ReactNode } from 'react' +import type { Task } from '../../types' +import { act, renderHook, waitFor } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import { MemoryTaskStorage } from '../../engine/storage/memory-storage' +import { TaskQueueProvider } from '../../provider/task-queue-provider' +import { createOrgMetadata, createProjectMetadata, createUserMetadata } from '../../utils' +import { useTaskQueue } from '../use-task-queue' +import { getContextLabel, matchesCurrentScope, useCurrentScope, useTasksWithLabels } from '../use-task-scope' + +function wrapper({ children }: { children: ReactNode }) { + return {children} +} + +const org = { id: 'org-1', name: 'Acme' } +const project = { id: 'proj-1', name: 'Web' } + +describe('useTaskQueue', () => { + it('throws outside a TaskQueueProvider', () => { + expect(() => renderHook(() => useTaskQueue())).toThrow('useTaskQueue must be used within a TaskQueueProvider') + }) + + it('lists an enqueued task and cancels it', async () => { + const { result } = renderHook(() => useTaskQueue(), { wrapper }) + let id = '' + act(() => { + id = result.current.enqueue({ + title: 'Slow task', + cancelable: true, + processor: ctx => new Promise((resolve) => { + const timer = setInterval(() => { + if (ctx.cancelled) { + clearInterval(timer) + resolve() + } + }, 5) + }), + }).id + }) + await waitFor(() => expect(result.current.tasks.map(task => task.title)).toContain('Slow task')) + act(() => result.current.cancel(id)) + await waitFor(() => expect(result.current.tasks.find(task => task.id === id)?.status).toBe('cancelled')) + }) + + it('filters by status and dismisses a finished task', async () => { + const { result } = renderHook(() => useTaskQueue({ status: 'completed' }), { wrapper }) + let id = '' + act(() => { + // A task that never finishes must stay out of the completed list. + result.current.enqueue({ title: 'Never done', processor: () => new Promise(() => {}) }) + id = result.current.enqueue({ title: 'Quick task', processor: async () => {} }).id + }) + await waitFor(() => expect(result.current.tasks.map(task => task.id)).toEqual([id])) + expect(result.current.tasks.every(task => task.status === 'completed')).toBe(true) + act(() => result.current.dismiss(id)) + await waitFor(() => expect(result.current.tasks).toHaveLength(0)) + }) +}) + +describe('useCurrentScope', () => { + it('prefers the project, then the org, then the global scope', () => { + expect(renderHook(() => useCurrentScope({ projectId: 'proj-1', orgId: 'org-1' })).result.current) + .toEqual({ type: 'project', projectId: 'proj-1', orgId: 'org-1' }) + expect(renderHook(() => useCurrentScope({ orgId: 'org-1' })).result.current).toEqual({ type: 'org', orgId: 'org-1' }) + expect(renderHook(() => useCurrentScope({})).result.current).toEqual({ type: 'global' }) + }) +}) + +describe('matchesCurrentScope', () => { + const projectTask = createProjectMetadata(project, org) + const orgTask = createOrgMetadata(org) + const userTask = createUserMetadata() + + it('matches a project task only in that project', () => { + expect(matchesCurrentScope(projectTask, { type: 'project', projectId: 'proj-1' })).toBe(true) + expect(matchesCurrentScope(projectTask, { type: 'project', projectId: 'proj-2' })).toBe(false) + }) + + it('matches an org task in that org, but not the org\'s project tasks', () => { + expect(matchesCurrentScope(orgTask, { type: 'org', orgId: 'org-1' })).toBe(true) + expect(matchesCurrentScope(projectTask, { type: 'org', orgId: 'org-1' })).toBe(false) + }) + + it('matches nothing on a global page or without metadata', () => { + expect(matchesCurrentScope(userTask, { type: 'global' })).toBe(false) + expect(matchesCurrentScope(undefined, { type: 'project', projectId: 'proj-1' })).toBe(false) + }) +}) + +describe('getContextLabel', () => { + it('labels each scope', () => { + expect(getContextLabel(createProjectMetadata(project, org))).toBe('Project: Web') + expect(getContextLabel(createOrgMetadata(org))).toBe('Org: Acme') + expect(getContextLabel(createUserMetadata())).toBe('User') + expect(getContextLabel({ scope: 'edge', projectName: 'Web' })).toBe('AI Edge: Web') + expect(getContextLabel({ scope: 'billing' })).toBe('Billing') + expect(getContextLabel(undefined)).toBeUndefined() + }) +}) + +describe('useTasksWithLabels', () => { + const task = (metadata: Task['metadata']) => ({ id: String(Math.random()), metadata }) as Task + + it('shows no labels without tasks or when every task belongs to the current project', () => { + expect(renderHook(() => useTasksWithLabels([], { projectId: 'proj-1' })).result.current.showLabels).toBe(false) + const tasks = [task(createProjectMetadata(project, org))] + expect(renderHook(() => useTasksWithLabels(tasks, { projectId: 'proj-1' })).result.current.showLabels).toBe(false) + }) + + it('shows labels on a global page and for mixed scopes', () => { + const tasks = [task(createProjectMetadata(project, org)), task(createOrgMetadata(org))] + expect(renderHook(() => useTasksWithLabels(tasks, {})).result.current.showLabels).toBe(true) + expect(renderHook(() => useTasksWithLabels(tasks, { projectId: 'proj-1' })).result.current.showLabels).toBe(true) + }) +})