diff --git a/src/assets/translations/en.ts b/src/assets/translations/en.ts index e07e28608..069198031 100644 --- a/src/assets/translations/en.ts +++ b/src/assets/translations/en.ts @@ -405,6 +405,10 @@ export default { fileTeacher: 'Teacher', fileUploadTime: 'Uploaded', fileCategory: 'Category', + courseFileView: 'Course File View', + filesByTime: 'By Time', + filesByCategory: 'By Category', + uncategorized: 'Uncategorized', fileDescription: 'Description', somethingWentWrong: 'Something Went Wrong', tryAgain: 'Try Again', diff --git a/src/assets/translations/zh.ts b/src/assets/translations/zh.ts index d3297d47b..73ab77b7e 100644 --- a/src/assets/translations/zh.ts +++ b/src/assets/translations/zh.ts @@ -380,6 +380,10 @@ const zh: typeof en = { fileTeacher: '教师', fileUploadTime: '上传时间', fileCategory: '分类', + courseFileView: '课程文件显示方式', + filesByTime: '按时间', + filesByCategory: '按分类', + uncategorized: '未分类', fileDescription: '描述', somethingWentWrong: '出错了', tryAgain: '重试', diff --git a/src/data/__tests__/legacy.test.ts b/src/data/__tests__/legacy.test.ts index d92ff85dd..b7ce5364f 100644 --- a/src/data/__tests__/legacy.test.ts +++ b/src/data/__tests__/legacy.test.ts @@ -181,6 +181,7 @@ describe('importing user data saved by 18.0.x', () => { archived: { notice: ['n2'], assignment: [], file: ['f1'] }, hiddenCourses: ['c3'], courseOrder: ['c2', 'c1'], + collapsedFileCategories: {}, currentSemester: '2025-2026-1', latestSemester: null, }); diff --git a/src/data/__tests__/userData.test.ts b/src/data/__tests__/userData.test.ts index cf3aec339..5b612b1d1 100644 --- a/src/data/__tests__/userData.test.ts +++ b/src/data/__tests__/userData.test.ts @@ -6,6 +6,7 @@ import { setArchived, setCourseHidden, setCourseOrder, + toggleFileCategory, queueAction, removeAction, failAction, @@ -31,6 +32,7 @@ describe('user data', () => { archived: { notice: [], assignment: [], file: [] }, hiddenCourses: [], courseOrder: [], + collapsedFileCategories: {}, currentSemester: null, latestSemester: null, }); @@ -116,6 +118,27 @@ describe('user data', () => { }); }); + it('restores file category choices independently for each course', async () => { + toggleFileCategory('a', 'category:slides'); + toggleFileCategory('a', 'uncategorized'); + toggleFileCategory('b', 'category:slides'); + toggleFileCategory('a', 'category:slides'); + const saved = Storage.getItemSync(USER_DATA_KEY)!; + + resetUserData(); + Storage.setItemSync(USER_DATA_KEY, saved); + await useUserDataStore.persist.rehydrate(); + expect(getUserData().collapsedFileCategories).toEqual({ + a: ['uncategorized'], + b: ['category:slides'], + }); + + toggleFileCategory('a', 'uncategorized'); + expect(getUserData().collapsedFileCategories).toEqual({ + b: ['category:slides'], + }); + }); + it('keeps lists added later when reading older saved data', async () => { (Storage as unknown as { __store: Map }).__store.set( USER_DATA_KEY, @@ -132,6 +155,7 @@ describe('user data', () => { }); expect(getUserData().hiddenCourses).toEqual(['c']); expect(getUserData().courseOrder).toEqual([]); + expect(getUserData().collapsedFileCategories).toEqual({}); }); describe('applyLatestSemester', () => { diff --git a/src/data/mock.ts b/src/data/mock.ts index 1f2cf875a..ec8f47246 100644 --- a/src/data/mock.ts +++ b/src/data/mock.ts @@ -1101,6 +1101,7 @@ export const mockUserData: UserData = { }, hiddenCourses: [research.id], courseOrder: [], + collapsedFileCategories: {}, // Fetched from the emulated server, like a real account. currentSemester: null, latestSemester: null, diff --git a/src/data/userData.ts b/src/data/userData.ts index 908068560..6fd86344c 100644 --- a/src/data/userData.ts +++ b/src/data/userData.ts @@ -32,6 +32,8 @@ export interface UserData { hiddenCourses: string[]; /** Course ids in the order the user dragged them into. */ courseOrder: string[]; + /** Collapsed file category keys, by course id. */ + collapsedFileCategories: Partial>; /** * The semester the app shows. Starts as the school's current semester and * can be changed in Settings. @@ -50,6 +52,7 @@ export const emptyUserData = (): UserData => ({ archived: { notice: [], assignment: [], file: [] }, hiddenCourses: [], courseOrder: [], + collapsedFileCategories: {}, currentSemester: null, latestSemester: null, }); @@ -181,6 +184,21 @@ export const setCourseOrder = (courseIds: string[]) => { useUserDataStore.setState({ courseOrder: courseIds }); }; +export const toggleFileCategory = (courseId: string, categoryKey: string) => { + useUserDataStore.setState(state => { + const current = state.collapsedFileCategories[courseId] ?? []; + const next = toggle(current, [categoryKey], !current.includes(categoryKey)); + const collapsedFileCategories = { + ...state.collapsedFileCategories, + [courseId]: next, + }; + if (!next.length) { + delete collapsedFileCategories[courseId]; + } + return { collapsedFileCategories }; + }); +}; + export const setCurrentSemester = (semesterId: string) => { useUserDataStore.setState({ currentSemester: semesterId }); }; diff --git a/src/helpers/__tests__/groupCourseFiles.test.ts b/src/helpers/__tests__/groupCourseFiles.test.ts new file mode 100644 index 000000000..e3475d6f4 --- /dev/null +++ b/src/helpers/__tests__/groupCourseFiles.test.ts @@ -0,0 +1,61 @@ +import { groupCourseFiles } from 'helpers/groupCourseFiles'; +import { file } from 'test-utils/fixtures/cards'; + +const slides = file().category!; +const labs = { ...slides, id: 'labs', title: 'Labs' }; +const other = 'Uncategorized'; + +it('keeps upload order within each category and puts unclassified files last', () => { + const syllabus = file({ id: 'syllabus', category: undefined }); + const lecture2 = file({ id: 'lecture2', category: slides }); + const lab = file({ id: 'lab', category: labs }); + const lecture1 = file({ id: 'lecture1', category: slides }); + const notes = file({ id: 'notes', category: { ...slides, title: ' ' } }); + const files = Object.freeze([syllabus, lecture2, lab, lecture1, notes]); + + expect(groupCourseFiles(files, other)).toEqual([ + { key: `category:${slides.id}`, heading: slides.title, expanded: true }, + lecture2, + lecture1, + { key: `category:${labs.id}`, heading: labs.title, expanded: true }, + lab, + { key: 'uncategorized', heading: other, expanded: true }, + syllabus, + notes, + ]); +}); + +it('keeps different categories with the same title distinct and omits empty groups', () => { + const first = file({ id: 'first', category: slides }); + const second = file({ + id: 'second', + category: { ...labs, title: slides.title }, + }); + + expect(groupCourseFiles([first, second], other)).toEqual([ + { key: `category:${slides.id}`, heading: slides.title, expanded: true }, + first, + { key: `category:${labs.id}`, heading: slides.title, expanded: true }, + second, + ]); + expect(groupCourseFiles([], other)).toEqual([]); +}); + +it('keeps collapsed headings in order and uses ids even when a category is renamed', () => { + const renamed = { ...slides, title: 'Lecture notes' }; + const lecture = file({ id: 'lecture', category: renamed }); + const lab = file({ id: 'lab', category: labs }); + const syllabus = file({ id: 'syllabus', category: undefined }); + + expect( + groupCourseFiles([syllabus, lecture, lab], other, [ + `category:${slides.id}`, + 'uncategorized', + ]), + ).toEqual([ + { key: `category:${slides.id}`, heading: renamed.title, expanded: false }, + { key: `category:${labs.id}`, heading: labs.title, expanded: true }, + lab, + { key: 'uncategorized', heading: other, expanded: false }, + ]); +}); diff --git a/src/helpers/groupCourseFiles.ts b/src/helpers/groupCourseFiles.ts new file mode 100644 index 000000000..c26a82f1d --- /dev/null +++ b/src/helpers/groupCourseFiles.ts @@ -0,0 +1,46 @@ +import type { File } from 'data/types/state'; + +export interface FileCategoryHeading { + key: string; + heading: string; + expanded: boolean; +} + +/** + * Files arrive newest first. Keeping each category in the order it first + * appears puts the category with the latest upload at the top. + */ +export const groupCourseFiles = ( + files: readonly File[], + uncategorizedTitle: string, + collapsedKeys: readonly string[] = [], +): (File | FileCategoryHeading)[] => { + const groups = new Map(); + const uncategorizedKey = 'uncategorized'; + const collapsed = new Set(collapsedKeys); + for (const file of files) { + const category = file.category?.title.trim() ? file.category : undefined; + const key = category ? `category:${category.id}` : uncategorizedKey; + let group = groups.get(key); + if (!group) { + group = [ + { + key, + heading: category?.title ?? uncategorizedTitle, + expanded: !collapsed.has(key), + }, + ]; + groups.set(key, group); + } + if (group[0].expanded) { + group.push(file); + } + } + + const uncategorized = groups.get(uncategorizedKey); + if (uncategorized) { + groups.delete(uncategorizedKey); + groups.set(uncategorizedKey, uncategorized); + } + return [...groups.values()].flat(); +}; diff --git a/src/helpers/systemIcons.ts b/src/helpers/systemIcons.ts index c9fe85595..139fcfe6a 100644 --- a/src/helpers/systemIcons.ts +++ b/src/helpers/systemIcons.ts @@ -358,6 +358,16 @@ export const systemIcons = { android: 'arrow_forward', windows: 'ArrowRightRegular', }, + disclosureExpanded: { + ios: 'chevron.down', + android: 'expand_more', + windows: 'ChevronDownRegular', + }, + disclosureCollapsed: { + ios: 'chevron.forward', + android: 'chevron_right', + windows: 'ChevronRightRegular', + }, close: { ios: 'xmark', android: 'close', windows: 'DismissRegular' }, refresh: { ios: 'arrow.clockwise', @@ -510,6 +520,7 @@ export const materialCodepoints: Record = { check: 0xe5ca, check_circle: 0xe86c, checklist: 0xe6b1, + chevron_right: 0xe5cc, close: 0xe5cd, cloud_off: 0xe2c1, code: 0xe86f, @@ -524,6 +535,7 @@ export const materialCodepoints: Record = { error: 0xe000, event_busy: 0xe615, event_upcoming: 0xf238, + expand_more: 0xe5cf, favorite: 0xe87d, feedback: 0xe87f, file_export: 0xf3b2, diff --git a/src/screens/CourseDetail.tsx b/src/screens/CourseDetail.tsx index 81e52bd52..060c87e32 100644 --- a/src/screens/CourseDetail.tsx +++ b/src/screens/CourseDetail.tsx @@ -13,7 +13,11 @@ import { import { Assignment, Course, File, Notice } from 'data/types/state'; import { useCourse } from 'data/queries'; import { useLoggedIn } from 'data/auth'; -import { useUserData, type BookmarkType } from 'data/userData'; +import { + toggleFileCategory, + useUserData, + type BookmarkType, +} from 'data/userData'; import { toggleArchived, toggleFavorite } from 'services/listActions'; import { useAssignments, @@ -30,9 +34,17 @@ import Empty from 'components/Empty'; import SafeArea from 'components/SafeArea'; import FlatList from 'components/FlatList'; import ListBackground from 'components/ListBackground'; +import SystemIcon from 'components/SystemIcon'; +import { Paragraph } from 'components/Text'; +import Touchable from 'components/Touchable'; +import { + groupCourseFiles, + type FileCategoryHeading, +} from 'helpers/groupCourseFiles'; import { t } from 'helpers/i18n'; import useDetailNavigator from 'hooks/useDetailNavigator'; import { SplitViewContext } from 'navigation/SplitView'; +import Spacing from 'constants/Spacing'; import Styles from 'constants/Styles'; import NotFound from 'components/NotFound'; import useHeaderTitle from 'hooks/useHeaderTitle'; @@ -50,6 +62,7 @@ import { hasGlassHeader } from 'navigation/options'; import { isApple } from 'helpers/platform'; import { scrollInsetBehavior } from 'constants/scrollInsetBehavior'; import { useWindowTitle } from 'hooks/useWindow'; +import { useTheme } from 'theme'; type NavigationProp = MainStackNavigationProp< CourseDetailParamList, @@ -57,7 +70,9 @@ type NavigationProp = MainStackNavigationProp< >; interface CourseItemListProps { - data: T[]; + data: (T | FileCategoryHeading)[]; + header?: React.ReactElement; + onToggleCategory?: (key: string) => void; card: React.FC<{ data: T; fav?: boolean; @@ -81,6 +96,8 @@ interface CourseItemListProps { /** One of the course's notices, assignments and files tabs. */ const CourseItemList = ({ data, + header, + onToggleCategory, card: Card, detailScreen, type, @@ -89,6 +106,7 @@ const CourseItemList = ({ }: CourseItemListProps) => { const navigation = useNavigation(); const loggedIn = useLoggedIn(); + const theme = useTheme(); // Every item of the course, archived ones too, which their cards show as // such (Unarchive in their actions). const archivedIds = useUserData(userData => userData.archived[type]); @@ -109,22 +127,54 @@ const CourseItemList = ({ )} ( - toggleFavorite(type, item.id, !!item.isFavorite)} - archived={archivedSet.has(item.id)} - onToggleArchived={() => - toggleArchived(type, [item.id], archivedSet.has(item.id)) - } - hideCourseName - markArchived - onPress={() => navigation.push(detailScreen, { id: item.id })} - /> - )} - keyExtractor={item => item.id} + ListHeaderComponent={header} + getItemType={item => ('heading' in item ? 'heading' : type)} + renderItem={({ item, index }) => { + if ('heading' in item) { + return ( + onToggleCategory?.(item.key)} + style={styles.categoryHeading} + type="opacity" + > + + {item.heading} + + + + ); + } + const next = data[index + 1]; + return ( + + toggleFavorite(type, item.id, !!item.isFavorite) + } + archived={archivedSet.has(item.id)} + onToggleArchived={() => + toggleArchived(type, [item.id], archivedSet.has(item.id)) + } + hideCourseName + markArchived + onPress={() => navigation.push(detailScreen, { id: item.id })} + /> + ); + }} + keyExtractor={item => + 'heading' in item ? item.key : `item:${item.id}` + } refreshing={refresh.isPending} onRefresh={handleRefresh} contentInsetAdjustmentBehavior={scrollInsetBehavior} @@ -186,6 +236,10 @@ const CourseDetailContent: React.FC<{ const refreshFiles = useRefreshCourseFiles(course.id); const [index, setIndex] = useState(0); + const [filesByCategory, setFilesByCategory] = useState(false); + const collapsedFileCategories = useUserData( + data => data.collapsedFileCategories[course.id], + ); // The floating tabs' height, which the lists scroll clear of. const [tabsHeight, setTabsHeight] = useState(0); @@ -241,10 +295,32 @@ const CourseDetailContent: React.FC<{ topInset={tabsHeight} /> ); - case 'file': + case 'file': { + const courseFiles = files.filter(file => file.courseId === course.id); return ( i.courseId === course.id)} + data={ + filesByCategory + ? groupCourseFiles( + courseFiles, + t('uncategorized'), + collapsedFileCategories, + ) + : courseFiles + } + header={ + courseFiles.length ? ( + setFilesByCategory(i === 1)} + /> + ) : undefined + } + onToggleCategory={categoryKey => + toggleFileCategory(course.id, categoryKey) + } card={FileCard} detailScreen="FileDetail" type="file" @@ -252,6 +328,7 @@ const CourseDetailContent: React.FC<{ topInset={tabsHeight} /> ); + } default: return null; } @@ -362,6 +439,14 @@ const CoursePage: React.FC> = ({ }; const styles = StyleSheet.create({ + categoryHeading: { + flexDirection: 'row', + alignItems: 'center', + gap: Spacing.s, + minHeight: 48, + paddingHorizontal: Spacing.m, + paddingVertical: Spacing.s, + }, floatingTabs: { position: 'absolute', // Its own height, not the screen's (SafeAreaView flexes by default). diff --git a/src/screens/__tests__/CourseDetail.test.tsx b/src/screens/__tests__/CourseDetail.test.tsx index c62a64493..faf0d13fa 100644 --- a/src/screens/__tests__/CourseDetail.test.tsx +++ b/src/screens/__tests__/CourseDetail.test.tsx @@ -4,6 +4,7 @@ import { render, screen, userEvent, + within, } from '@testing-library/react-native'; import { initialAuth, useAuthStore } from 'data/auth'; import { @@ -19,6 +20,7 @@ import { t } from 'helpers/i18n'; import useDetailNavigator from 'hooks/useDetailNavigator'; import * as options from 'navigation/options'; import CourseDetail from 'screens/CourseDetail'; +import { file } from 'test-utils/fixtures/cards'; import { fireLayout } from 'test-utils/layout'; import { screenProps } from 'test-utils/screenProps'; @@ -29,6 +31,7 @@ jest.mock('@react-navigation/native', () => ({ useIsFocused: () => true, })); jest.mock('data/queries', () => ({ useCourse: jest.fn() })); +let mockListedFiles: typeof mockFiles; const mockRefresh = { notice: { isPending: false, mutate: jest.fn() }, assignment: { isPending: false, mutate: jest.fn() }, @@ -39,7 +42,7 @@ jest.mock('data/content', () => ({ useAssignments: () => ({ assignments: require('data/mock').mockAssignments, }), - useFiles: () => ({ files: require('data/mock').mockFiles }), + useFiles: () => ({ files: mockListedFiles }), useRefreshCourseNotices: () => mockRefresh.notice, useRefreshCourseAssignments: () => mockRefresh.assignment, useRefreshCourseFiles: () => mockRefresh.file, @@ -99,6 +102,7 @@ const selectTab = (index: number) => fireEvent(screen.getByText(t('files')), 'selectionChange', index); beforeEach(() => { + mockListedFiles = mockFiles; jest.mocked(useCourse).mockReturnValue(course); }); @@ -136,6 +140,92 @@ it('says so when a tab has nothing yet', async () => { jest.mocked(useCourse).mockReturnValue({ ...course, id: 'new-course' }); await renderScreen(); expect(screen.getByText(t('noNotices'))).toBeTruthy(); + await selectTab(2); + expect(screen.getByText(t('noFiles'))).toBeTruthy(); + expect(screen.queryByText(t('filesByCategory'))).toBeNull(); +}); + +it('switches the course files between upload order and category headings', async () => { + const syllabus = file({ + id: 'syllabus', + courseId: course.id, + title: 'Syllabus', + category: undefined, + }); + const lecture = file({ courseId: course.id }); + const other = file({ + id: 'other', + courseId: 'other-course', + title: 'Other course file', + }); + mockListedFiles = [syllabus, other, lecture]; + const firstFile = () => within(screen.getAllByTestId('file-card')[0]); + const slides = () => + screen.queryByRole('button', { name: lecture.category!.title }); + + await renderScreen(); + expect(screen.queryByText(t('filesByCategory'))).toBeNull(); + await selectTab(2); + expect(firstFile().getByText(syllabus.title)).toBeTruthy(); + expect(slides()).toBeNull(); + + await fireEvent(screen.getByText(t('filesByCategory')), 'selectionChange', 1); + expect(slides()).toBeTruthy(); + expect(screen.getByRole('button', { name: t('uncategorized') })).toBeTruthy(); + expect(firstFile().getByText(lecture.title)).toBeTruthy(); + expect(screen.queryByText(other.title)).toBeNull(); + expect(screen.queryAllByTestId('card-separator')).toHaveLength(0); + await userEvent.press(screen.getByText(lecture.title)); + expect(mockPush).toHaveBeenCalledWith('FileDetail', { id: lecture.id }); + + await selectTab(1); + expect(screen.queryByText(t('filesByTime'))).toBeNull(); + await selectTab(2); + expect(slides()).toBeTruthy(); + await fireEvent(screen.getByText(t('filesByTime')), 'selectionChange', 0); + expect(slides()).toBeNull(); + expect(firstFile().getByText(syllabus.title)).toBeTruthy(); + expect(screen.getAllByTestId('card-separator')).toHaveLength(1); +}); + +it('toggles categories individually and remembers them when the course is reopened', async () => { + const lecture = file({ courseId: course.id }); + const syllabus = file({ + id: 'syllabus', + courseId: course.id, + title: 'Syllabus', + category: undefined, + }); + mockListedFiles = [lecture, syllabus]; + const selectCategories = () => + fireEvent(screen.getByText(t('filesByCategory')), 'selectionChange', 1); + const slides = (expanded: boolean) => + screen.getByRole('button', { name: lecture.category!.title, expanded }); + const uncategorized = (expanded: boolean) => + screen.getByRole('button', { name: t('uncategorized'), expanded }); + + const { unmount } = await renderScreen(); + await selectTab(2); + await selectCategories(); + expect(screen.getByText(lecture.title)).toBeTruthy(); + await userEvent.press(slides(true)); + expect(screen.queryByText(lecture.title)).toBeNull(); + expect(screen.getByText(syllabus.title)).toBeTruthy(); + await userEvent.press(uncategorized(true)); + expect(screen.queryAllByTestId('file-card')).toHaveLength(0); + expect(screen.queryByText(t('noFiles'))).toBeNull(); + + await unmount(); + await renderScreen(); + await selectTab(2); + expect(screen.getByText(lecture.title)).toBeTruthy(); + expect(screen.getByText(syllabus.title)).toBeTruthy(); + await selectCategories(); + expect(screen.queryAllByTestId('file-card')).toHaveLength(0); + await userEvent.press(slides(false)); + expect(screen.getByText(lecture.title)).toBeTruthy(); + expect(uncategorized(false)).toBeTruthy(); + expect(screen.queryByText(syllabus.title)).toBeNull(); }); it('opens an item on top of the course', async () => { diff --git a/src/web/fluentIcons.ts b/src/web/fluentIcons.ts index 170a373e5..44b88201b 100644 --- a/src/web/fluentIcons.ts +++ b/src/web/fluentIcons.ts @@ -30,6 +30,8 @@ import { CheckmarkCircleRegular, } from '@fluentui/react-icons/svg/checkmark-circle'; import { CheckmarkCircleWarningRegular } from '@fluentui/react-icons/svg/checkmark-circle-warning'; +import { ChevronDownRegular } from '@fluentui/react-icons/svg/chevron-down'; +import { ChevronRightRegular } from '@fluentui/react-icons/svg/chevron-right'; import { CircleRegular } from '@fluentui/react-icons/svg/circle'; import { ClipboardTaskListLtrFilled, @@ -168,6 +170,8 @@ export const fluentIcons: Record = { CheckmarkCircleRegular, CheckmarkCircleWarningRegular, CheckmarkRegular, + ChevronDownRegular, + ChevronRightRegular, CircleRegular, ClipboardTaskListLtrRegular, ClockAlarmRegular,