Skip to content

refactor(course-outline): migrate to React Query and consolidate outline architecture#3073

Open
navinkarkera wants to merge 106 commits into
openedx:masterfrom
open-craft:navin/fAL-3835/outline-refactor
Open

refactor(course-outline): migrate to React Query and consolidate outline architecture#3073
navinkarkera wants to merge 106 commits into
openedx:masterfrom
open-craft:navin/fAL-3835/outline-refactor

Conversation

@navinkarkera

@navinkarkera navinkarkera commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Description

Large architectural refactor of the course outline module. Migrated from Redux to React Query for outline data and mutation flows, consolidated context management, and unified component rendering.

1. Redux to React Query Migration

  • Removed Redux outline slice, thunks, selectors, and all Redux-based state management
  • All outline data fetching now uses React Query hooks
  • Mutations (reorder, delete, configure, publish, duplicate) centralized in apiHooks.ts
  • Cache invalidation handled via dedicated utilities in cacheInvalidation.ts

2. Context Consolidation

  • Outline state consolidated into CourseOutlineContext; sidebar/drag contexts remain separate
  • Extracted state management into focused hooks: useOutlineReorderState, useOutlineStatusState, useConfigureModal, useDeleteModal, useHighlightsModal, useUnlinkModal, useCreateBlockSidebar, useModalState
  • Sidebar modal state simplified with OutlineModals component

3. Component Unification

  • Card components (SectionCard, SubsectionCard, UnitCard) replaced by single recursive OutlineNode component; legacy style/message modules remain where still imported
  • Introduced OutlineTree for recursive outline rendering with depth-based logic

4. Test Infrastructure Modernization

  • Old fixture usage replaced by shared builders/utilities in __mocks__/testSetup.tsx and __mocks__/helpers.ts
  • Added comprehensive hook tests (apiHooks, useOutlineReorderState, etc.)
  • Migrated all outline tests to use new fixture builders and shared setup

5. Bug fixes

  • Title Edit Escape Fix: Pressing Escape while editing a title now correctly cancels the edit instead of saving. Previously the blur handler fired on Escape, persisting unintended changes.
  • ?show Scroll Fix: Repeated scroll to item based on ?show= is prevented. It will only scroll to the item once.

Replacing redux with react query has improved the performance a lot. Going back and forth from outline to any other page is instant.

Useful information to include:

  • Which user roles will this change impact?: "Developer"

Supporting information

Testing instructions

Outline Loading & Display

  1. Open course in Studio → Course Outline
  2. Verify outline loads with sections, subsections, units
  3. Test "Expand All" / "Collapse All" buttons

Drag-and-Drop Reordering

  1. Drag section to reorder → verify optimistic update + API success
  2. Drag subsection between sections → verify move succeeds
  3. Drag unit between subsections if unit drag handles are available/supported → verify move succeeds
  4. Use Escape to cancel drag operation

Add Operations

  1. Add new section → verify appears in outline
  2. Add new subsection → verify appears under parent section
  3. Add new unit → verify appears under parent subsection
  4. Add from library (subsection/unit) → verify import succeeds

Edit Operations

  1. Inline edit section/subsection/unit title → verify saves on Enter, cancels on Escape
  2. Open configure modal for section → verify settings save
  3. Open configure modal for subsection → verify settings save
  4. Open configure modal for unit → verify settings save

Delete Operations

  1. Delete unit → verify confirmation modal, item removed
  2. Delete subsection → verify confirmation modal, item + children removed
  3. Delete section → verify confirmation modal, item + children removed

Publish Operations

  1. Publish individual unit → verify publish modal, status updates
  2. Publish subsection → verify all units published
  3. Publish section → verify all children published

Sidebar & Navigation

  1. Click section → verify sidebar opens with section details
  2. Click subsection → verify sidebar shows subsection details
  3. Click unit → verify sidebar shows unit details

Search & URL Parameters

  1. Use outline search → verify results highlight and expand
  2. Navigate with ?show=<block_id> URL param → verify correct item expands, scrolls into view, and highlights once without repeated scroll on later selection or sidebar interaction

Other information

  • I have heavily used GPT 5.5, GPT 5.4 and GPT 5.4-mini models, it took some time and multiple iterations but still faster than writing each and every line manually.
  • Each line of code was reviewed by me.
  • I have done multiple rounds of manual testing as well as AI led testing via playwright cli.
  • Sorry for the huge PR , but I could not split it into smaller PRs.

Best Practices Checklist

We're trying to move away from some deprecated patterns in this codebase. Please
check if your PR meets these recommendations before asking for a review:

  • Any new files are using TypeScript (.ts, .tsx).
  • Avoid propTypes and defaultProps in any new or modified code.
  • Tests should use the helpers in src/testUtils.tsx (specifically initializeMocks)
  • Do not add new fields to the Redux state/store. Use React Context to share state among multiple components.
  • Use React Query to load data from REST APIs. See any apiHooks.ts in this repo for examples.
  • All new i18n messages in messages.ts files have a description for translators to use.
  • Avoid using ../ in import paths. To import from parent folders, use @src, e.g. import { initializeMocks } from '@src/testUtils'; instead of from '../../../../testUtils'

@openedx-webhooks openedx-webhooks added open-source-contribution PR author is not from Axim or 2U core contributor PR author is a Core Contributor (who may or may not have write access to this repo). labels Jun 2, 2026
@openedx-webhooks

openedx-webhooks commented Jun 2, 2026

Copy link
Copy Markdown

Thanks for the pull request, @navinkarkera!

This repository is currently maintained by @bradenmacdonald.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

Details
Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

@github-project-automation github-project-automation Bot moved this to Needs Triage in Contributions Jun 2, 2026
@navinkarkera navinkarkera changed the title feat: refactor course outline to remove redux refactor: course outline to remove redux Jun 2, 2026
@mphilbrick211 mphilbrick211 moved this from Needs Triage to Waiting on Author in Contributions Jun 2, 2026
@navinkarkera navinkarkera force-pushed the navin/fAL-3835/outline-refactor branch from f28d857 to b13cc19 Compare June 4, 2026 14:55
…o context

- Add intent-level drag handlers (previewSections, cancelReorderPreview,
  commitSectionReorder, commitSubsectionReorder, commitUnitReorder)
- Use preview/commit snapshot pattern with rollback on failure
- Await refreshed sections before clearing subsection/unit reorder preview
- Add optimistic section preview on drag drop
- Remove setSections/restoreSectionList from public API
- Remove duplicate useCourseOutlineIndex hook from apiHooks
After successful section/subsection/unit reorder, sync React Query outline index cache so committed tree does not snap back to pre-drop state.

CourseOutlineStateContext.tsx:
- Replace acceptReorderPreview with acceptReorderAndSyncSections /
  acceptReorderAndSyncSectionOrder helpers that update query cache on success.
- Use effectiveOutlineIndexData (prefer query cache) over outlineIndexData.
- Read sections from query-backed data with Redux fallback.

apiHooks.ts:
- Extract replaceSectionInOutlineIndex, appendSectionToOutlineIndex,
  insertDuplicatedSectionInOutlineIndex, invalidateParentQueriesAndSync helpers.
- Remove remaining Redux dispatch imports (addSection, updateSectionList,
  duplicateSection); write to query cache instead.

CourseOutline.test.tsx:
- Update courseId fixture to realistic format.
…mplify boilerplate

- CourseOutlineStateContext: removed 13 trivial context pass-through assertions, merged 2 duplicate courseId-change tests into 1
- useDeleteModal: merged 2 similar 'close but no clear selection' tests, removed defensive early-return
- useUnlinkModal: removed defensive early-return test
- useHighlightsModal: removed 3 trivial tests, kept 2 real filtering edge-case tests
- Preserved: selection state-machine, highlights filtering, complex drag-drop logic
- Net: 22→16 tests (27% fewer), 742→638 lines (14% reduction)
…ls stub

- Production hook calls useEnableCourseHighlightsEmails at initialization
- Mock must exist even though we don't test that specific behavior
- All 4 Phase 2 test suites now pass (9 tests)
Also makes outline discussions settings optional through the tree prop path.
@navinkarkera navinkarkera changed the title refactor: course outline to remove redux refactor(course-outline): migrate to React Query and consolidate outline architecture Jun 11, 2026
@navinkarkera

Copy link
Copy Markdown
Contributor Author

Card components (SectionCard, SubsectionCard, UnitCard) replaced by single recursive OutlineNode component; legacy style/message modules remain where still imported

I'll be creating a small follow up PR to move styles and message files out of these folders.

@navinkarkera navinkarkera marked this pull request as ready for review June 11, 2026 16:51
@navinkarkera

Copy link
Copy Markdown
Contributor Author

@ChrisChV @bradenmacdonald This is ready for review.

@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.95502% with 44 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.61%. Comparing base (94900a0) to head (88a1c1b).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/course-outline/OutlineNode.tsx 92.76% 11 Missing ⚠️
src/course-outline/data/outlineIndexCacheUtils.ts 94.20% 4 Missing ⚠️
src/course-outline/state/useConfigureModal.ts 90.90% 4 Missing ⚠️
src/course-outline/CourseOutlineContext.tsx 94.73% 3 Missing ⚠️
src/course-outline/drag-helper/DraggableList.tsx 91.17% 3 Missing ⚠️
src/course-outline/outline-level.ts 97.72% 3 Missing ⚠️
src/CourseAuthoringRoutes.tsx 77.77% 2 Missing ⚠️
src/course-outline/CourseOutline.tsx 96.49% 2 Missing ⚠️
src/course-outline/OutlineTree.tsx 96.82% 1 Missing and 1 partial ⚠️
src/course-outline/data/queryKeys.ts 87.50% 2 Missing ⚠️
... and 5 more
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3073      +/-   ##
==========================================
- Coverage   95.61%   95.61%   -0.01%     
==========================================
  Files        1391     1410      +19     
  Lines       33077    33408     +331     
  Branches     7444     7841     +397     
==========================================
+ Hits        31628    31942     +314     
- Misses       1396     1414      +18     
+ Partials       53       52       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ChrisChV ChrisChV left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@navinkarkera Thanks for this work! It is an amazing refactor! It is a lot of code. I've left some comments, I'm missing some files, and need to test the changes

useOutlineMutation<{ sectionId: string; subsectionId: string; unitListIds: string[]; }, unknown>(courseId, {
operation: 'reorderUnits',
mutationFn: (variables) => setCourseItemOrderList(variables.subsectionId, variables.unitListIds),
onSettled: () => {}, // suppress default parent invalidation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be good to explain why parent invalidation is being suppressed from these functions.

Comment on lines +19 to +25
for (const m of mutations) {
if (m.status !== 'success' && m.status !== 'error') { continue; }
const t = m.submittedAt ?? 0;
if (t > 0 && (!latest || t > latest.submittedAt)) {
latest = { status: m.status as 'success' | 'error', submittedAt: t };
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In non-inline blocks/functions, I don't find the use of single-letter named variables very readable. Can you update it to readable names?

Comment on lines +35 to +41
for (const m of mutations) {
if (m.status !== 'success' && m.status !== 'error') { continue; }
const t = m.submittedAt ?? 0;
if (t > 0 && (!latest || (latest.submittedAt ?? 0) < t)) {
latest = m;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above


const latest = latestMutation(mutations);
const status = latest?.status;
if (status === 'error' && latest) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit

Suggested change
if (status === 'error' && latest) {
if (status === 'error') {

Comment on lines +1 to +20
export { getLastEditableItem, getLastEditableSubsection } from '../utils/editability';
export type { EditableSubsection } from '../utils/editability';
export {
computeErrorSignature,
filterDismissedErrors,
pruneDismissedErrorSignatures,
} from '../utils/outlineErrorDismissal';
export { useConfigureDialog } from './useConfigureModal';
export type { UseConfigureDialogOutput } from './useConfigureModal';
export { useCreateBlockSidebar } from './useCreateBlockSidebar';
export { useDeleteModal } from './useDeleteModal';
export type { UseDeleteModalOutput } from './useDeleteModal';
export { useHighlightsModal } from './useHighlightsModal';
export type { UseHighlightsModalOutput } from './useHighlightsModal';
export { useOutlineReorderState } from './useOutlineReorderState';
export type { UseOutlineReorderStateOutput } from './useOutlineReorderState';
export { useOutlineStatusState } from './useOutlineStatusState';
export type { UseOutlineStatusStateOutput } from './useOutlineStatusState';
export { useUnlinkModal } from './useUnlinkModal';
export type { UseUnlinkModalOutput } from './useUnlinkModal';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit

Suggested change
export { getLastEditableItem, getLastEditableSubsection } from '../utils/editability';
export type { EditableSubsection } from '../utils/editability';
export {
computeErrorSignature,
filterDismissedErrors,
pruneDismissedErrorSignatures,
} from '../utils/outlineErrorDismissal';
export { useConfigureDialog } from './useConfigureModal';
export type { UseConfigureDialogOutput } from './useConfigureModal';
export { useCreateBlockSidebar } from './useCreateBlockSidebar';
export { useDeleteModal } from './useDeleteModal';
export type { UseDeleteModalOutput } from './useDeleteModal';
export { useHighlightsModal } from './useHighlightsModal';
export type { UseHighlightsModalOutput } from './useHighlightsModal';
export { useOutlineReorderState } from './useOutlineReorderState';
export type { UseOutlineReorderStateOutput } from './useOutlineReorderState';
export { useOutlineStatusState } from './useOutlineStatusState';
export type { UseOutlineStatusStateOutput } from './useOutlineStatusState';
export { useUnlinkModal } from './useUnlinkModal';
export type { UseUnlinkModalOutput } from './useUnlinkModal';
export { getLastEditableItem, getLastEditableSubsection, type EditableSubsection } from '../utils/editability';
export {
computeErrorSignature,
filterDismissedErrors,
pruneDismissedErrorSignatures,
} from '../utils/outlineErrorDismissal';
export { useConfigureDialog, type UseConfigureDialogOutput } from './useConfigureModal';
export { useCreateBlockSidebar } from './useCreateBlockSidebar';
export { useDeleteModal, type UseDeleteModalOutput } from './useDeleteModal';
export { useHighlightsModal, type UseHighlightsModalOutput } from './useHighlightsModal';
export { useOutlineReorderState, type UseOutlineReorderStateOutput } from './useOutlineReorderState';
export { useOutlineStatusState, type UseOutlineStatusStateOutput } from './useOutlineStatusState';
export { useUnlinkModal, type UseUnlinkModalOutput } from './useUnlinkModal';

@@ -0,0 +1,47 @@
import { findLast, findLastIndex } from 'lodash';

import { type XBlock, type XBlockBase } from '@src/data/types';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import { type XBlock, type XBlockBase } from '@src/data/types';
import type { XBlock, XBlockBase } from '@src/data/types';

Comment on lines +2505 to +2512
await waitFor(() => {
const cachedData = queryClient.getQueryData(courseOutlineQueryKeys.index(courseId));
const firstSectionSubsections = cachedData?.courseStructure?.childInfo?.children[0]?.childInfo?.children || [];
expect(firstSectionSubsections.length).toBe(firstSection.childInfo.children.length + 1);
expect(firstSectionSubsections[firstSectionSubsections.length - 1]?.id).toBe(subsection.id);
const subsectionsSecondSection = cachedData?.courseStructure?.childInfo?.children[1]?.childInfo?.children || [];
expect(subsectionsSecondSection.length).toBe(section.childInfo.children.length - 1);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do all these expects need to be within waitFor?

Comment on lines +2551 to +2558
await waitFor(() => {
const cachedData = queryClient.getQueryData(courseOutlineQueryKeys.index(courseId));
const firstSectionSubsections = cachedData?.courseStructure?.childInfo?.children[0]?.childInfo?.children || [];
expect(firstSectionSubsections.length).toBe(section.childInfo.children.length - 1);
const subsectionsSecondSection = cachedData?.courseStructure?.childInfo?.children[1]?.childInfo?.children || [];
expect(subsectionsSecondSection.length).toBe(secondSection.childInfo.children.length + 1);
expect(subsectionsSecondSection[0]?.id).toBe(subsection.id);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

Comment on lines +4 to +5
import type { Depth } from './outline-level';
import { containsSearchResult } from './outline-level';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import type { Depth } from './outline-level';
import { containsSearchResult } from './outline-level';
import { containsSearchResult, type Depth } from './outline-level';

isHeaderVisible: boolean;
activeId: UniqueIdentifier | null;
overId: UniqueIdentifier | null;
scrollState: ScrollState | null | undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
scrollState: ScrollState | null | undefined;
scrollState?: ScrollState | null;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core contributor PR author is a Core Contributor (who may or may not have write access to this repo). open-source-contribution PR author is not from Axim or 2U

Projects

Status: Waiting on Author

Development

Successfully merging this pull request may close these issues.

4 participants