diff --git a/src/App.tsx b/src/App.tsx index 312233b..0dd3e64 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -34,6 +34,10 @@ import GitVegasLogo from './assets/GitVegas.svg?react'; // Form context for sharing form state across components interface FormContextType { username: string; + usernames: string[]; + isMultiUser: boolean; + groupByUsers: boolean; + setGroupByUsers: (value: boolean) => void; startDate: string; endDate: string; githubToken: string; @@ -77,6 +81,7 @@ function App() { const [isManuallySpinning, setIsManuallySpinning] = useState(false); const [isDataLoadingComplete, setIsDataLoadingComplete] = useState(false); const [searchText, setSearchText] = useLocalStorage('header-search-text', ''); + const [groupByUsers, setGroupByUsers] = useLocalStorage('group-by-users', false); const handleUrlParamsProcessed = useCallback(() => { setInitialLoadingCount(1); @@ -110,6 +115,12 @@ function App() { const { username, startDate, endDate, githubToken, apiMode } = formSettings; + // Parse usernames for multi-user detection + const usernames = useMemo(() => { + return username ? username.split(',').map(u => u.trim()).filter(Boolean) : []; + }, [username]); + const isMultiUser = usernames.length > 1; + const { results, searchItemsCount, @@ -124,6 +135,7 @@ function App() { apiMode, searchText, githubToken, + isMultiUser: isMultiUser && groupByUsers, }); const { @@ -423,6 +435,10 @@ function App() { {/* API Mode Switch */} - - - { - e.preventDefault(); - setApiMode('summary'); - }} - > - Summary - - 0 ? searchItemsCount : undefined} - onSelect={e => { - e.preventDefault(); - setApiMode('search'); + - GitHub Issues & PRs - - 0 ? eventsCount : undefined} - onSelect={e => { - e.preventDefault(); - setApiMode('events'); + { + e.preventDefault(); + setApiMode('summary'); + }} + > + Summary + + 0 ? searchItemsCount : undefined} + onSelect={e => { + e.preventDefault(); + setApiMode('search'); + }} + > + GitHub Issues & PRs + + 0 ? eventsCount : undefined} + onSelect={e => { + e.preventDefault(); + setApiMode('events'); + }} + > + GitHub Events + + + + {isMultiUser && ( + - GitHub Events - - + + Group by users + + setGroupByUsers(!groupByUsers)} + aria-label="Group by users" + /> + + )} diff --git a/src/hooks/useGitHubDataProcessing.ts b/src/hooks/useGitHubDataProcessing.ts index 2a344e7..5ee45c5 100644 --- a/src/hooks/useGitHubDataProcessing.ts +++ b/src/hooks/useGitHubDataProcessing.ts @@ -12,6 +12,7 @@ interface UseGitHubDataProcessingProps { apiMode: 'search' | 'events' | 'summary'; searchText: string; githubToken?: string; + isMultiUser?: boolean; } interface UseGitHubDataProcessingReturn { @@ -30,6 +31,7 @@ export const useGitHubDataProcessing = ({ apiMode, searchText, githubToken, + isMultiUser = false, }: UseGitHubDataProcessingProps): UseGitHubDataProcessingReturn => { const [enrichedResults, setEnrichedResults] = useState([]); const [isEnriching, setIsEnriching] = useState(false); @@ -44,7 +46,8 @@ export const useGitHubDataProcessing = ({ return categorizeRawSearchItems( indexedDBSearchItems as unknown as GitHubItem[], startDate, - endDate + endDate, + isMultiUser ); } else if (apiMode === 'summary') { // Summary view: merge both events AND search items for complete picture @@ -52,13 +55,22 @@ export const useGitHubDataProcessing = ({ const processedSearchItems = categorizeRawSearchItems( indexedDBSearchItems as unknown as GitHubItem[], startDate, - endDate + endDate, + isMultiUser ); - + + if (isMultiUser) { + // Multi-user: skip deduplication, keep all items from both sources + const combinedResults = [...processedSearchItems, ...processedEvents]; + return combinedResults.sort((a, b) => + new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime() + ); + } + // Combine both datasets, removing duplicates based on html_url const urlSet = new Set(); const combinedResults: GitHubItem[] = []; - + // Add search items first (they are more complete/accurate) processedSearchItems.forEach(item => { if (!urlSet.has(item.html_url)) { @@ -66,7 +78,7 @@ export const useGitHubDataProcessing = ({ combinedResults.push(item); } }); - + // Add events that aren't already covered by search items processedEvents.forEach(item => { if (!urlSet.has(item.html_url)) { @@ -74,15 +86,15 @@ export const useGitHubDataProcessing = ({ combinedResults.push(item); } }); - + // Sort by updated_at (newest first) - return combinedResults.sort((a, b) => + return combinedResults.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime() ); } else { return []; } - }, [apiMode, indexedDBEvents, indexedDBSearchItems, startDate, endDate]); + }, [apiMode, indexedDBEvents, indexedDBSearchItems, startDate, endDate, isMultiUser]); // Enrich items with PR details when a token is available // Uses SWR pattern: show cached data immediately, then fetch fresh data in background @@ -148,10 +160,11 @@ export const useGitHubDataProcessing = ({ const rawSearchItems = categorizeRawSearchItems( indexedDBSearchItems as unknown as GitHubItem[], startDate, - endDate + endDate, + isMultiUser ); return filterItemsByAdvancedSearch(rawSearchItems, searchText).length; - }, [indexedDBSearchItems, startDate, endDate, searchText]); + }, [indexedDBSearchItems, startDate, endDate, searchText, isMultiUser]); const eventsCount = useMemo(() => { const rawEvents = processRawEvents(indexedDBEvents, startDate, endDate); diff --git a/src/utils/rawDataUtils.ts b/src/utils/rawDataUtils.ts index a75acad..a71b39a 100644 --- a/src/utils/rawDataUtils.ts +++ b/src/utils/rawDataUtils.ts @@ -582,7 +582,8 @@ export const processRawEvents = ( export const categorizeRawSearchItems = ( rawItems: GitHubItem[], startDate?: string, - endDate?: string + endDate?: string, + skipDedup = false ): GitHubItem[] => { // Set up date filtering if dates are provided const startDateTime = startDate ? new Date(startDate).getTime() : 0; @@ -595,7 +596,7 @@ export const categorizeRawSearchItems = ( console.warn('Skipping item with missing title:', item.html_url || item.id); return false; } - + const itemTime = new Date(item.updated_at).getTime(); // Filter by date range if dates are provided @@ -609,10 +610,15 @@ export const categorizeRawSearchItems = ( return true; }); + // Skip deduplication in multi-user mode to preserve per-user items + if (skipDedup) { + return dateFilteredItems; + } + // Then remove duplicates based on html_url (unique identifier for issues/PRs) const urlSet = new Set(); const deduplicatedItems: GitHubItem[] = []; - + dateFilteredItems.forEach(item => { if (!urlSet.has(item.html_url)) { urlSet.add(item.html_url); diff --git a/src/views/EventView.tsx b/src/views/EventView.tsx index 3f631a0..05fb5a8 100644 --- a/src/views/EventView.tsx +++ b/src/views/EventView.tsx @@ -1,10 +1,19 @@ -import { memo, useCallback, useEffect } from 'react'; +import React, { memo, useCallback, useEffect, useMemo } from 'react'; import { Text, Checkbox, Box, Pagination, + Button, + Heading, + Avatar, + Token, } from '@primer/react'; +import { + ChevronDownIcon, + ChevronUpIcon, + PeopleIcon, +} from '@primer/octicons-react'; import { GitHubItem, GitHubEvent, getItemId } from '../types'; import { ResultsContainer } from '../components/ResultsContainer'; @@ -29,25 +38,89 @@ interface EventViewProps { rawEvents?: GitHubEvent[]; } +/** Groups items by user login, preserving configured user order. */ +const groupItemsByUser = ( + items: GitHubItem[], + configuredUsernames: string[] +): Record => { + const userGroups: Record = {}; + const configuredLower = configuredUsernames.map(u => u.toLowerCase()); + + items.forEach(item => { + const login = item.user.login; + if (!userGroups[login]) { + userGroups[login] = []; + } + userGroups[login].push(item); + }); + + const ordered: Record = {}; + for (const configUser of configuredUsernames) { + const matchKey = Object.keys(userGroups).find( + k => k.toLowerCase() === configUser.toLowerCase() + ); + if (matchKey && userGroups[matchKey].length > 0) { + ordered[matchKey] = userGroups[matchKey]; + } + } + Object.keys(userGroups) + .filter(k => !configuredLower.includes(k.toLowerCase())) + .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) + .forEach(k => { + if (userGroups[k].length > 0) { + ordered[k] = userGroups[k]; + } + }); + + return ordered; +}; + const EventView = memo(function EventView({ items, rawEvents = [], }: EventViewProps) { - const { searchText, setSearchText } = useFormContext(); + const { searchText, setSearchText, isMultiUser, groupByUsers, usernames } = useFormContext(); + const showUserGroups = isMultiUser && groupByUsers; - // Pagination state + // Pagination state (per-section for multi-user, single for single-user) const [currentPage, setCurrentPage] = useLocalStorage('eventView-currentPage', 1); + const [sectionPages, setSectionPages] = useLocalStorage>('eventView-sectionPages', {}); + const [collapsedSections, setCollapsedSections] = useLocalStorage>('eventView-collapsedSections', new Set()); const itemsPerPage = 100; + const getSectionPage = useCallback((sectionName: string) => { + return sectionPages[sectionName] || 1; + }, [sectionPages]); + + const setSectionPage = useCallback((sectionName: string, page: number) => { + setSectionPages(prev => ({ ...prev, [sectionName]: page })); + }, [setSectionPages]); + // Filter and sort items const filteredItems = filterItemsByAdvancedSearch(items, searchText); const sortedItems = sortItemsByUpdatedDate(filteredItems); + // --- Multi-user grouping --- + const perUserItems = useMemo(() => { + if (!showUserGroups) return null; + return groupItemsByUser(sortedItems, usernames); + }, [showUserGroups, sortedItems, usernames]); + + // Build flat list of displayed items for selection + const allDisplayedItems = useMemo(() => { + if (showUserGroups && perUserItems) { + return Object.entries(perUserItems) + .filter(([login]) => !collapsedSections.has(`@user:${login}`)) + .flatMap(([, items]) => items); + } + return sortedItems; + }, [showUserGroups, perUserItems, sortedItems, collapsedSections]); + // Shared hooks const { selectedItems, toggleItemSelection, selectAllItems, clearSelection, - selectAllState, - } = useListSelection('eventView-selectedItems', sortedItems); + bulkSelectItems, selectAllState, + } = useListSelection('eventView-selectedItems', allDisplayedItems); const { selectedItemForDialog, setSelectedItemForDialog, @@ -59,13 +132,35 @@ const EventView = memo(function EventView({ // Reset to first page when search changes useEffect(() => { setCurrentPage(1); - }, [searchText, setCurrentPage]); + setSectionPages({}); + }, [searchText, setCurrentPage, setSectionPages]); - // Pagination + // Single-user pagination const totalPages = Math.ceil(sortedItems.length / itemsPerPage); const startIndex = (currentPage - 1) * itemsPerPage; const paginatedItems = sortedItems.slice(startIndex, startIndex + itemsPerPage); + // Toggle section collapse + const toggleSectionCollapse = useCallback((sectionName: string) => { + setCollapsedSections(prev => { + const newSet = new Set(prev); + if (newSet.has(sectionName)) { + newSet.delete(sectionName); + } else { + newSet.add(sectionName); + if (showUserGroups && perUserItems) { + const login = sectionName.replace('@user:', ''); + const userItems = perUserItems[login]; + if (userItems) { + const idsToRemove = userItems.map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } + } + } + return newSet; + }); + }, [showUserGroups, perUserItems, bulkSelectItems]); + // Copy handler const copyResultsToClipboard = useCallback(async (format: 'detailed' | 'compact') => { const selectedItemsArray = @@ -108,7 +203,7 @@ const EventView = memo(function EventView({ /> Select All - {totalPages > 1 && ( + {!showUserGroups && totalPages > 1 && ( (Page {currentPage} of {totalPages}) @@ -138,7 +233,90 @@ const EventView = memo(function EventView({ showClearSearch={!!searchText} onClearSearch={() => setSearchText('')} /> + ) : showUserGroups && perUserItems ? ( + // Multi-user: group by user + Object.entries(perUserItems).map(([login, userItems]) => { + if (userItems.length === 0) return null; + const userCollapseKey = `@user:${login}`; + const isUserCollapsed = collapsedSections.has(userCollapseKey); + const avatarUrl = userItems[0]?.user?.avatar_url; + + // Per-user pagination + const userPage = getSectionPage(login); + const userTotalPages = Math.ceil(userItems.length / itemsPerPage); + const userStartIndex = (userPage - 1) * itemsPerPage; + const paginatedUserItems = userItems.slice(userStartIndex, userStartIndex + itemsPerPage); + + return ( +
+
+ + + {avatarUrl ? ( + + ) : ( + + )} + + {login} + + + + + +
+ {!isUserCollapsed && ( + + {paginatedUserItems.map((item: GitHubItem, index: number) => ( + + ))} + {userTotalPages > 1 && ( + + setSectionPage(login, page)} + showPages={{ narrow: false }} + marginPageCount={2} + surroundingPageCount={2} + /> + + )} + + )} +
+ ); + }) ) : ( + // Single-user: existing behavior <> {paginatedItems.map((item: GitHubItem, index: number) => ( => { + const userGroups: Record = {}; + const configuredLower = configuredUsernames.map(u => u.toLowerCase()); + + items.forEach(item => { + const login = item.user.login; + if (!userGroups[login]) { + userGroups[login] = []; + } + userGroups[login].push(item); + }); + + const ordered: Record = {}; + for (const configUser of configuredUsernames) { + const matchKey = Object.keys(userGroups).find( + k => k.toLowerCase() === configUser.toLowerCase() + ); + if (matchKey && userGroups[matchKey].length > 0) { + ordered[matchKey] = userGroups[matchKey]; + } + } + Object.keys(userGroups) + .filter(k => !configuredLower.includes(k.toLowerCase())) + .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) + .forEach(k => { + if (userGroups[k].length > 0) { + ordered[k] = userGroups[k]; + } + }); + + return ordered; +}; + const IssuesAndPRsList = memo(function IssuesAndPRsList({ results, }: { results: GitHubItem[]; }) { - const { searchText, setSearchText } = useFormContext(); + const { searchText, setSearchText, isMultiUser, groupByUsers, usernames } = useFormContext(); + const showUserGroups = isMultiUser && groupByUsers; const [collapsedSections, setCollapsedSections] = useLocalStorage>('issuesAndPRs-collapsedSections', new Set()); @@ -143,7 +184,32 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ const hasRawData = results && results.length > 0; const hasSearchText = searchText && searchText.trim().length > 0; + // --- Multi-user grouping --- + const perUserGroupedItems = useMemo(() => { + if (!showUserGroups) return null; + const userItems = groupItemsByUser(filteredResults, usernames); + const result: Record = {}; + + for (const [login, items] of Object.entries(userItems)) { + const groups: { 'PRs': GitHubItem[]; 'Issues': GitHubItem[] } = { 'PRs': [], 'Issues': [] }; + items.forEach(item => { + if (item.pull_request) { + groups['PRs'].push(item); + } else { + groups['Issues'].push(item); + } + }); + Object.keys(groups).forEach(key => { + groups[key as keyof typeof groups] = sortItemsByUpdatedDate(groups[key as keyof typeof groups]); + }); + result[login] = groups; + } + return result; + }, [showUserGroups, filteredResults, usernames]); + + // --- Single-user grouping (existing logic) --- const groupedItems = useMemo(() => { + if (showUserGroups) return { 'PRs': [] as GitHubItem[], 'Issues': [] as GitHubItem[] }; const groups: { 'PRs': GitHubItem[]; 'Issues': GitHubItem[] } = { 'PRs': [], 'Issues': [] }; filteredResults.forEach(item => { if (item.pull_request) { @@ -156,14 +222,23 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ groups[key as keyof typeof groups] = sortItemsByUpdatedDate(groups[key as keyof typeof groups]); }); return groups; - }, [filteredResults]); + }, [showUserGroups, filteredResults]); // Build flat list of items from expanded sections for selection const allDisplayedItems = useMemo(() => { + if (showUserGroups && perUserGroupedItems) { + return Object.entries(perUserGroupedItems) + .filter(([login]) => !collapsedSections.has(`@user:${login}`)) + .flatMap(([login, groups]) => + Object.entries(groups) + .filter(([groupName]) => !collapsedSections.has(`@user:${login}/${groupName}`)) + .flatMap(([, items]) => items) + ); + } return Object.entries(groupedItems) .filter(([groupName]) => !collapsedSections.has(groupName)) .flatMap(([, items]) => items); - }, [groupedItems, collapsedSections]); + }, [showUserGroups, perUserGroupedItems, groupedItems, collapsedSections]); // Shared hooks const { @@ -184,25 +259,50 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ newSet.delete(sectionName); } else { newSet.add(sectionName); - const sectionItems = groupedItems[sectionName as keyof typeof groupedItems] || []; - if (sectionItems.length > 0) { - const idsToRemove = sectionItems.map(item => getItemId(item)); - bulkSelectItems(idsToRemove, false); + if (showUserGroups && perUserGroupedItems) { + if (sectionName.startsWith('@user:') && !sectionName.includes('/')) { + const login = sectionName.replace('@user:', ''); + const userGroups = perUserGroupedItems[login]; + if (userGroups) { + const idsToRemove = Object.values(userGroups).flat().map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } + } else if (sectionName.includes('/')) { + const [userPart, groupName] = sectionName.split('/'); + const login = userPart.replace('@user:', ''); + const userGroups = perUserGroupedItems[login]; + if (userGroups && userGroups[groupName as keyof typeof userGroups]) { + const idsToRemove = userGroups[groupName as keyof typeof userGroups].map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } + } + } else { + const sectionItems = groupedItems[sectionName as keyof typeof groupedItems] || []; + if (sectionItems.length > 0) { + const idsToRemove = sectionItems.map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } } } return newSet; }); - }, [groupedItems, bulkSelectItems]); + }, [showUserGroups, perUserGroupedItems, groupedItems, bulkSelectItems]); // Copy handler const copyResultsToClipboard = useCallback(async (format: 'detailed' | 'compact') => { - const groupedData = Object.entries(groupedItems) - .filter(([, items]) => items.length > 0) - .map(([groupName, items]) => ({ groupName, items })); + const allGroups = showUserGroups && perUserGroupedItems + ? Object.entries(perUserGroupedItems).flatMap(([login, groups]) => + Object.entries(groups) + .filter(([, items]) => items.length > 0) + .map(([groupName, items]) => ({ groupName: `${login} - ${groupName}`, items })) + ) + : Object.entries(groupedItems) + .filter(([, items]) => items.length > 0) + .map(([groupName, items]) => ({ groupName, items })); - let finalGroupedData = groupedData; + let finalGroupedData = allGroups; if (selectedItems.size > 0) { - finalGroupedData = groupedData + finalGroupedData = allGroups .map(group => ({ ...group, items: group.items.filter(item => selectedItems.has(getItemId(item))), @@ -210,7 +310,7 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ .filter(group => group.items.length > 0); } - const allItems = Object.values(groupedItems).flat(); + const allItems = allGroups.flatMap(g => g.items); const selectedItemsArray = selectedItems.size > 0 ? allItems.filter(item => selectedItems.has(getItemId(item))) @@ -223,7 +323,7 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ onSuccess: () => triggerCopy(format), onError: (error: Error) => console.error('Failed to copy grouped results:', error), }); - }, [groupedItems, selectedItems, triggerCopy]); + }, [showUserGroups, perUserGroupedItems, groupedItems, selectedItems, triggerCopy]); // Select all toggle const handleSelectAllChange = () => { @@ -234,6 +334,69 @@ const IssuesAndPRsList = memo(function IssuesAndPRsList({ } }; + /** Renders a PRs/Issues group section. */ + const renderGroupSection = ( + groupName: string, + groupItems: GitHubItem[], + collapseKey: string, + ) => { + if (groupItems.length === 0) return null; + const isCollapsed = collapsedSections.has(collapseKey); + + return ( +
+
+ + + { + if (isCollapsed) return; + const sectionItemIds = groupItems.map(getItemId); + const allSelected = sectionItemIds.every(id => selectedItems.has(id)); + bulkSelectItems(sectionItemIds, !allSelected); + }} + sx={{ flexShrink: 0 }} + aria-label={`Select all items in ${groupName} section`} + disabled={isCollapsed} + /> + + {groupName} ({groupItems.length}) + + + + +
+ {!isCollapsed && ( + + )} +
+ ); + }; + return ( setSearchText('')} /> - ) : ( + ) : showUserGroups && perUserGroupedItems ? ( + // Multi-user: group by user, then by PRs/Issues
- {Object.entries(groupedItems).map(([groupName, groupItems]) => { - if (groupItems.length === 0) return null; + {Object.entries(perUserGroupedItems).map(([login, groups]) => { + const userItemCount = Object.values(groups).reduce((sum, items) => sum + items.length, 0); + if (userItemCount === 0) return null; + const userCollapseKey = `@user:${login}`; + const isUserCollapsed = collapsedSections.has(userCollapseKey); + const firstItem = Object.values(groups).flat()[0]; + const avatarUrl = firstItem?.user?.avatar_url; + return ( -
+
- { - if (collapsedSections.has(groupName)) return; - const sectionItemIds = groupItems.map(getItemId); - const allSelected = sectionItemIds.every(id => selectedItems.has(id)); - bulkSelectItems(sectionItemIds, !allSelected); - }} - sx={{ flexShrink: 0 }} - aria-label={`Select all items in ${groupName} section`} - disabled={collapsedSections.has(groupName)} - /> - - {groupName} ({groupItems.length}) + {avatarUrl ? ( + + ) : ( + + )} + + {login} +
- {!collapsedSections.has(groupName) && ( - + {!isUserCollapsed && ( + + {Object.entries(groups).map(([groupName, groupItems]) => + renderGroupSection(groupName, groupItems, `@user:${login}/${groupName}`) + )} + )}
); })}
+ ) : ( + // Single-user: existing behavior +
+ {Object.entries(groupedItems).map(([groupName, groupItems]) => + renderGroupSection(groupName, groupItems, groupName) + )} +
)}
diff --git a/src/views/Summary.tsx b/src/views/Summary.tsx index 08ce445..f71eb52 100644 --- a/src/views/Summary.tsx +++ b/src/views/Summary.tsx @@ -6,10 +6,12 @@ import { Checkbox, Box, Token, + Avatar, } from '@primer/react'; import { ChevronDownIcon, ChevronUpIcon, + PeopleIcon, } from '@primer/octicons-react'; import { GitHubItem, GitHubEvent, getItemId } from '../types'; @@ -67,12 +69,53 @@ const groupItemsByUrl = (groupItems: GitHubItem[]): Record return urlGroups; }; +/** Groups items by user login, preserving configured user order. */ +const groupItemsByUser = ( + items: GitHubItem[], + configuredUsernames: string[] +): Record => { + const userGroups: Record = {}; + const configuredLower = configuredUsernames.map(u => u.toLowerCase()); + + items.forEach(item => { + const login = item.user.login; + if (!userGroups[login]) { + userGroups[login] = []; + } + userGroups[login].push(item); + }); + + // Order: configured users first (in order), then others alphabetically + const ordered: Record = {}; + for (const configUser of configuredUsernames) { + // Find the actual case-sensitive key that matches + const matchKey = Object.keys(userGroups).find( + k => k.toLowerCase() === configUser.toLowerCase() + ); + if (matchKey && userGroups[matchKey].length > 0) { + ordered[matchKey] = userGroups[matchKey]; + } + } + // Add remaining users not in configured list + Object.keys(userGroups) + .filter(k => !configuredLower.includes(k.toLowerCase())) + .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) + .forEach(k => { + if (userGroups[k].length > 0) { + ordered[k] = userGroups[k]; + } + }); + + return ordered; +}; + const SummaryView = memo(function SummaryView({ items, rawEvents = [], indexedDBSearchItems = [], }: SummaryProps) { - const { startDate, endDate, searchText, setSearchText } = useFormContext(); + const { startDate, endDate, searchText, setSearchText, isMultiUser, groupByUsers, usernames } = useFormContext(); + const showUserGroups = isMultiUser && groupByUsers; const [collapsedSections, setCollapsedSections] = useLocalStorage>('summary-collapsedSections', new Set()); @@ -85,17 +128,67 @@ const SummaryView = memo(function SummaryView({ return filterItemsByAdvancedSearch(indexedDBSearchItems, searchText); }, [indexedDBSearchItems, searchText]); - // Group items for summary view - const actionGroups = useMemo(() => { + // --- Multi-user grouping --- + type UserActionGroups = Record>; + const perUserActionGroups = useMemo((): UserActionGroups | null => { + if (!showUserGroups) return null; + const userItems = groupItemsByUser(sortedItems, usernames); + const userSearchItems = groupItemsByUser(filteredIndexedDBSearchItems, usernames); + + const result: Record> = {}; + // Process all users that appear in either items or search items + const allUsers = new Set([...Object.keys(userItems), ...Object.keys(userSearchItems)]); + for (const login of allUsers) { + result[login] = groupSummaryData( + userItems[login] || [], + userSearchItems[login] || [], + startDate, + endDate + ); + } + + // Re-order by configured usernames first + const configuredLower = usernames.map(u => u.toLowerCase()); + const ordered: Record> = {}; + for (const configUser of usernames) { + const matchKey = Object.keys(result).find( + k => k.toLowerCase() === configUser.toLowerCase() + ); + if (matchKey) { + ordered[matchKey] = result[matchKey]; + } + } + Object.keys(result) + .filter(k => !configuredLower.includes(k.toLowerCase())) + .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) + .forEach(k => { + ordered[k] = result[k]; + }); + + return ordered; + }, [showUserGroups, sortedItems, filteredIndexedDBSearchItems, usernames, startDate, endDate]); + + // --- Single-user grouping (existing logic) --- + const actionGroups = useMemo((): Record => { + if (showUserGroups) return {}; return groupSummaryData(sortedItems, filteredIndexedDBSearchItems, startDate, endDate); - }, [sortedItems, filteredIndexedDBSearchItems, startDate, endDate]); + }, [showUserGroups, sortedItems, filteredIndexedDBSearchItems, startDate, endDate]); // Build flat list of items from expanded sections for selection - const allDisplayedItems = useMemo(() => { + const allDisplayedItems = useMemo((): GitHubItem[] => { + if (showUserGroups && perUserActionGroups) { + return Object.entries(perUserActionGroups) + .filter(([login]) => !collapsedSections.has(`@user:${login}`)) + .flatMap(([login, groups]) => + Object.entries(groups) + .filter(([groupName]) => !collapsedSections.has(`@user:${login}/${groupName}`)) + .flatMap(([, items]) => items) + ); + } return Object.entries(actionGroups) .filter(([groupName]) => !collapsedSections.has(groupName)) .flatMap(([, items]) => items); - }, [actionGroups, collapsedSections]); + }, [showUserGroups, perUserActionGroups, actionGroups, collapsedSections]); // Shared hooks const { @@ -110,6 +203,21 @@ const SummaryView = memo(function SummaryView({ const { isCopied, triggerCopy } = useCopyFeedback(2000); + // Get all action groups flattened (for copy and other operations) + const allActionGroups = useMemo(() => { + if (showUserGroups && perUserActionGroups) { + const merged: Record = {}; + Object.entries(perUserActionGroups).forEach(([login, groups]) => { + Object.entries(groups).forEach(([groupName, items]) => { + const key = `${login} - ${groupName}`; + merged[key] = items; + }); + }); + return merged; + } + return actionGroups; + }, [showUserGroups, perUserActionGroups, actionGroups]); + // Toggle section collapse and clear selections on collapse const toggleSectionCollapse = useCallback((sectionName: string) => { setCollapsedSections(prev => { @@ -118,20 +226,43 @@ const SummaryView = memo(function SummaryView({ newSet.delete(sectionName); } else { newSet.add(sectionName); - const sectionItems = actionGroups[sectionName as keyof typeof actionGroups] || []; - if (sectionItems.length > 0) { - const idsToRemove = sectionItems.map(item => getItemId(item)); - bulkSelectItems(idsToRemove, false); + // Find items in this section to deselect + if (showUserGroups && perUserActionGroups) { + // Could be a user section or a group within a user + if (sectionName.startsWith('@user:') && !sectionName.includes('/')) { + // User section - deselect all items for this user + const login = sectionName.replace('@user:', ''); + const userGroups = perUserActionGroups[login]; + if (userGroups) { + const idsToRemove = Object.values(userGroups).flat().map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } + } else if (sectionName.includes('/')) { + // Action group within a user + const [userPart, groupName] = sectionName.split('/'); + const login = userPart.replace('@user:', ''); + const userGroups = perUserActionGroups[login]; + if (userGroups && userGroups[groupName]) { + const idsToRemove = userGroups[groupName].map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } + } + } else { + const sectionItems = actionGroups[sectionName as keyof typeof actionGroups] || []; + if (sectionItems.length > 0) { + const idsToRemove = sectionItems.map(item => getItemId(item)); + bulkSelectItems(idsToRemove, false); + } } } return newSet; }); - }, [actionGroups, bulkSelectItems]); + }, [showUserGroups, perUserActionGroups, actionGroups, bulkSelectItems]); // Copy handler const copyResultsToClipboard = useCallback(async (format: 'detailed' | 'compact') => { - const groupedData = formatGroupedDataForClipboard(actionGroups, selectedItems); - const allItems = getAllDisplayedItems(actionGroups); + const groupedData = formatGroupedDataForClipboard(allActionGroups, selectedItems); + const allItems = getAllDisplayedItems(allActionGroups); const selectedItemsArray = selectedItems.size > 0 ? allItems.filter(item => selectedItems.has(getItemId(item))) @@ -144,7 +275,7 @@ const SummaryView = memo(function SummaryView({ onSuccess: () => triggerCopy(format), onError: (error: Error) => console.error('Failed to copy grouped results:', error), }); - }, [actionGroups, selectedItems, triggerCopy]); + }, [allActionGroups, selectedItems, triggerCopy]); // Select all toggle const handleSelectAllChange = () => { @@ -157,7 +288,87 @@ const SummaryView = memo(function SummaryView({ const hasRawEvents = rawEvents && rawEvents.length > 0; const hasSearchText = searchText && searchText.trim().length > 0; - const hasItems = Object.values(actionGroups).some(items => items.length > 0); + const hasItems = showUserGroups && perUserActionGroups + ? Object.values(perUserActionGroups).some(groups => + Object.values(groups).some(items => items.length > 0) + ) + : Object.values(actionGroups).some(items => items.length > 0); + + /** Renders the action group sections (shared between single and multi-user). */ + const renderActionGroup = ( + groupName: string, + groupItems: GitHubItem[], + collapseKey: string, + ) => { + if (groupItems.length === 0) return null; + const urlGroups = groupItemsByUrl(groupItems); + const mostRecentIds = Object.values(urlGroups).map(items => getItemId(getMostRecent(items))); + const selectedCount = mostRecentIds.filter(id => selectedItems.has(id)).length; + const isCollapsed = collapsedSections.has(collapseKey); + + return ( +
+
+ + + { + if (isCollapsed) return; + bulkSelectItems(mostRecentIds, selectedCount !== mostRecentIds.length); + }} + sx={{ flexShrink: 0 }} + aria-label={`Select all events in ${groupName} section`} + disabled={isCollapsed} + /> + + {groupName} + + 0 ? `${selectedCount} / ${mostRecentIds.length}` : `${mostRecentIds.length}`} + size="small" + sx={{ ml: 2, flexShrink: 0 }} + /> + + + +
+ {!isCollapsed && ( +
+ {Object.entries(urlGroups).map(([url, items]) => { + const mostRecent = getMostRecent(items); + return ( +
+ 1 ? items.length : undefined} + /> +
+ ); + })} +
+ )} +
+ ); + }; return ( setSearchText('')} /> - ) : ( - Object.entries(actionGroups).map(([groupName, groupItems]) => { - if (groupItems.length === 0) return null; - const urlGroups = groupItemsByUrl(groupItems); - const mostRecentIds = Object.values(urlGroups).map(items => getItemId(getMostRecent(items))); - const selectedCount = mostRecentIds.filter(id => selectedItems.has(id)).length; - const isCollapsed = collapsedSections.has(groupName); + ) : showUserGroups && perUserActionGroups ? ( + // Multi-user: group by user, then by action type + Object.entries(perUserActionGroups).map(([login, groups]) => { + const userItemCount = Object.values(groups).reduce((sum, items) => sum + items.length, 0); + if (userItemCount === 0) return null; + const userCollapseKey = `@user:${login}`; + const isUserCollapsed = collapsedSections.has(userCollapseKey); + // Get first item to extract avatar URL + const firstItem = Object.values(groups).flat()[0]; + const avatarUrl = firstItem?.user?.avatar_url; return ( -
+
- { - if (isCollapsed) return; - bulkSelectItems(mostRecentIds, selectedCount !== mostRecentIds.length); - }} - sx={{ flexShrink: 0 }} - aria-label={`Select all events in ${groupName} section`} - disabled={isCollapsed} - /> - - {groupName} + {avatarUrl ? ( + + ) : ( + + )} + + {login} 0 ? `${selectedCount} / ${mostRecentIds.length}` : `${mostRecentIds.length}`} + text={`${userItemCount}`} size="small" sx={{ ml: 2, flexShrink: 0 }} /> @@ -234,7 +443,7 @@ const SummaryView = memo(function SummaryView({
- {!isCollapsed && ( -
- {Object.entries(urlGroups).map(([url, items]) => { - const mostRecent = getMostRecent(items); - return ( -
- 1 ? items.length : undefined} - /> -
- ); - })} -
+ {!isUserCollapsed && ( + + {Object.entries(groups).map(([groupName, groupItems]) => + renderActionGroup(groupName, groupItems, `@user:${login}/${groupName}`) + )} + )}
); }) + ) : ( + // Single-user: existing behavior + Object.entries(actionGroups).map(([groupName, groupItems]) => + renderActionGroup(groupName, groupItems, groupName) + ) )}