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
60 changes: 58 additions & 2 deletions frontend/src/components/app/SearchResultsList.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import SearchResult from './SearchResult';
import { useSearchResults, useConsolidatedPolling } from '../../hooks/useCaseSearch';
import { SearchResult as SearchResultType } from '../../../../shared/types';
import { useEffect, useMemo } from 'react';
import { useEffect, useMemo, useState, useRef } from 'react';
import { ClipboardDocumentIcon, CheckIcon } from '@heroicons/react/24/outline';

type DisplayItem = SearchResultType | 'divider';

Expand All @@ -11,6 +12,8 @@ function CaseResultItem({ searchResult }: { searchResult: SearchResultType }) {

export default function SearchResultsList() {
const { data, isLoading, isError, error } = useSearchResults();
const [copied, setCopied] = useState(false);
const copiedTimeoutRef = useRef<NodeJS.Timeout | null>(null);

// Extract batches and create a flat display list with dividers
const displayItems = useMemo(() => {
Expand Down Expand Up @@ -58,6 +61,34 @@ export default function SearchResultsList() {
// Use the consolidated polling approach for all non-terminal cases
const polling = useConsolidatedPolling();

// Function to copy all case numbers to clipboard
const copyCaseNumbers = async () => {
if (!searchResults || searchResults.length === 0) {
return;
}

// Extract case numbers, sort them alphanumerically, and join with newlines
const caseNumbers = searchResults
.map(result => result.zipCase.caseNumber)
.sort()
.join('\n');

try {
await navigator.clipboard.writeText(caseNumbers);
setCopied(true);

// Clear any existing timeout
if (copiedTimeoutRef.current) {
clearTimeout(copiedTimeoutRef.current);
}

// Reset copied state after 2 seconds
copiedTimeoutRef.current = setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy case numbers:', err);
}
};

// Start/stop polling based on whether we have non-terminal cases
useEffect(() => {
if (searchResults.length > 0) {
Expand All @@ -80,6 +111,15 @@ export default function SearchResultsList() {
};
}, [searchResults, polling]);

// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (copiedTimeoutRef.current) {
clearTimeout(copiedTimeoutRef.current);
}
};
}, []);

if (isError) {
console.error('Error in useSearchResults:', error);
}
Expand All @@ -102,7 +142,23 @@ export default function SearchResultsList() {
<>
{displayItems.length > 0 ? (
<div className="mt-8">
<h3 className="text-base font-semibold text-gray-900">Search Results</h3>
<div className="flex justify-between items-center">
<h3 className="text-base font-semibold text-gray-900">Search Results</h3>
<button
onClick={copyCaseNumbers}
className={`inline-flex items-center gap-x-2 rounded-md bg-white px-3 py-2 text-sm font-semibold shadow-sm ring-1 ring-inset hover:bg-gray-50 ${
copied ? 'text-green-700 ring-green-600' : 'text-gray-900 ring-gray-300'
}`}
aria-label="Copy all case numbers"
>
{copied ? (
<CheckIcon className="h-5 w-5 text-green-600" aria-hidden="true" />
) : (
<ClipboardDocumentIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
)}
Copy Case Numbers
</button>
</div>
<div className="mt-4">
{displayItems.map((item, index) => (
<div key={item === 'divider' ? `divider-${index}` : item.zipCase.caseNumber}>
Expand Down
81 changes: 81 additions & 0 deletions frontend/src/components/app/__tests__/SearchResultsList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import SearchResultsList from '../SearchResultsList';
import { SearchResult, ZipCase } from '../../../../../shared/types';
import userEvent from '@testing-library/user-event';

// Import hooks to mock
import * as hooks from '../../../hooks/useCaseSearch';
Expand Down Expand Up @@ -230,4 +231,84 @@ describe('SearchResultsList', () => {
// Console error should have been called
expect(console.error).toHaveBeenCalled();
});

it('renders copy case numbers button when results are present', () => {
const mockResults = {
case1: createSearchResult('case1', 'complete'),
case2: createSearchResult('case2', 'processing'),
};

vi.mocked(hooks.useSearchResults).mockReturnValue({
data: {
results: mockResults,
searchBatches: [['case1', 'case2']],
},
isLoading: false,
isError: false,
error: null,
} as any);

render(<SearchResultsList />, { wrapper: createWrapper() });

// Check that the copy button is rendered
expect(screen.getByRole('button', { name: /copy all case numbers/i })).toBeInTheDocument();
});

it('does not render copy case numbers button when no results', () => {
vi.mocked(hooks.useSearchResults).mockReturnValue({
data: { results: {}, searchBatches: [] },
isLoading: false,
isError: false,
error: null,
} as any);

render(<SearchResultsList />, { wrapper: createWrapper() });

// Check that the copy button is not rendered
expect(screen.queryByRole('button', { name: /copy all case numbers/i })).not.toBeInTheDocument();
});

it('copies case numbers to clipboard when button is clicked', async () => {
const user = userEvent.setup();

const mockResults = {
case2: createSearchResult('case2', 'processing'),
case3: createSearchResult('case3', 'queued'),
case1: createSearchResult('case1', 'complete'),
};

vi.mocked(hooks.useSearchResults).mockReturnValue({
data: {
results: mockResults,
searchBatches: [['case2', 'case3', 'case1']],
},
isLoading: false,
isError: false,
error: null,
} as any);

// Mock clipboard API
const writeTextMock = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
value: {
writeText: writeTextMock,
},
writable: true,
configurable: true,
});

render(<SearchResultsList />, { wrapper: createWrapper() });

const copyButton = screen.getByRole('button', { name: /copy all case numbers/i });
await user.click(copyButton);

// Verify clipboard.writeText was called with sorted case numbers
expect(writeTextMock).toHaveBeenCalledWith('case1\ncase2\ncase3');

// Verify button still shows "Copy Case Numbers" text
expect(screen.getByText('Copy Case Numbers')).toBeInTheDocument();

// Verify button has green styling indicating success
expect(copyButton).toHaveClass('text-green-700');
});
});