Skip to content

Implement redux store and save/load interlinear projects#86

Merged
alex-rawlings-yyc merged 11 commits into
mainfrom
redux
May 27, 2026
Merged

Implement redux store and save/load interlinear projects#86
alex-rawlings-yyc merged 11 commits into
mainfrom
redux

Conversation

@imnasnainaec
Copy link
Copy Markdown
Contributor

@imnasnainaec imnasnainaec commented May 27, 2026

Resolves #84
Fixes #85 (leaving decisions-to-make for later work)

(I decided to fix 85 in the same pr as implementing 84 in order to put the redux store to the test.)

Devin review: https://app.devin.ai/review/sillsdev/interlinearizer-extension/pull/86


This change is Reviewable


Claude summary of changes

Analysis store: migration to Redux Toolkit

AnalysisStore.tsx was rewritten from a hand-rolled useSyncExternalStore store to Redux Toolkit backed by react-redux. The mutation logic and index-building that previously lived inline in the provider component moved into a new Redux slice. The store ref is also initialized lazily so configureStore is only called once per provider instance rather than on every render.

New files:

  • src/store/analysisSlice.tsAnalysisState, writeGloss (prepare/reducer), setAnalysis, and memoized selectors (selectApprovedGloss, selectAnalysis, selectApprovedIdByTokenRef).
  • src/store/index.tscreateAnalysisStore factory (one store per provider instance for isolated state), plus exported AnalysisStore, AnalysisRootState, and AnalysisDispatch types.
  • src/__tests__/store/analysisSlice.test.ts — unit tests for setAnalysis, writeGloss, and selectApprovedGloss.

Changed files:

  • src/components/AnalysisStore.tsxAnalysisStoreProvider now wraps children with <Provider store={store}>. The three public hooks (useGloss, useAnalysis, useGlossDispatch) delegate to useSelector/useDispatch from react-redux instead of managing listeners manually. Callback props (onSave, onGlossChange) are kept in refs so useGlossDispatch returns a stable function without re-creating on parent re-renders. Store ref is populated via a lazy initializer.
  • src/__tests__/components/PhraseBox.test.tsx, src/__tests__/components/TokenChip.test.tsx — test fixtures updated to use the TokenSnapshot type.

Dependencies added: @reduxjs/toolkit ^2.12.0, react-redux ^9.3.0.


Active project analysis: load and save on project switch

When the user selects an interlinear project, InterlinearizerLoader now fetches that project's stored TextAnalysis from the backend and passes it to Interlinearizer as initialAnalysis. Gloss writes are persisted back via a new saveAnalysis command. The key prop on <Interlinearizer> is set to activeProject?.id so the Redux store inside AnalysisStoreProvider is fully remounted on every project switch. isAnalysisLoading is also explicitly cleared when the active project is unset, so the loading indicator does not linger after project deselection.

Changed files:

  • src/services/projectStorage.ts — new updateAnalysis(token, id, analysis) function: serialized read-modify-write via the existing enqueueProjectOp queue, replaces only the analysis field on the stored project.
  • src/main.ts — two new backend command handlers registered on activation:
    • interlinearizer.getProject — reads the project from storage and returns it as a JSON string, or undefined if not found.
    • interlinearizer.saveAnalysis — parses an incoming JSON string and writes it via projectStorage.updateAnalysis; sends an error notification and rethrows on failure.
  • src/types/interlinearizer.d.ts — both new commands declared in the CommandHandlers module augmentation.
  • src/components/InterlinearizerLoader.tsxactiveProjectAnalysis state and isAnalysisLoading flag added. A useEffect (keyed on activeProject?.id) fires an async load via sendCommand('interlinearizer.getProject', ...) with a cancellation guard for unmount-during-flight. A handleSaveAnalysis callback fires sendCommand('interlinearizer.saveAnalysis', ...) on each gloss write; the callback is a no-op when no project is active. isAnalysisLoading is reset to false when activeProject is undefined. showLoading now includes isAnalysisLoading.
  • src/__tests__/services/projectStorage.test.ts — four tests covering updateAnalysis: happy path, project-not-found, concurrent-call serialization, and the error propagation path.
  • src/__tests__/main.test.ts — tests for both new command handlers (success, storage failure, JSON parse failure, not-found).
  • src/__tests__/components/InterlinearizerLoader.test.tsx — tests covering the analysis load effect (valid JSON, rejected promise, cancelled-on-unmount) and the handleSaveAnalysis guard (with and without an active project).

saveInterlinearAnalysis: runtime validation of TextAnalysis shape

saveInterlinearAnalysis in src/main.ts now validates the parsed JSON against the TextAnalysis shape before passing it to projectStorage.updateAnalysis. Malformed payloads throw a TypeError that is caught by the existing error handler, triggering the usual log + notification + rethrow path.

Type guards are consolidated into src/types/typeGuards.ts.

New files:

  • src/types/typeGuards.tsisInterlinearProjectSummary and isTextAnalysis type guards.

Deleted files:

  • src/utils/interlinear-project-summary.ts — merged into src/types/typeGuards.ts.

Changed files:

  • src/main.tsisTextAnalysis guard called after JSON.parse; import updated to src/types/typeGuards.
  • src/components/CreateProjectModal.tsx, src/components/SelectInterlinearProjectModal.tsx — import updated to src/types/typeGuards.
  • src/__tests__/main.test.ts — two new cases in the interlinearizer.saveAnalysis describe block: invalid JSON (SyntaxError) and a parsed object missing required arrays (TypeError).
  • jest.config.ts — removed the now-deleted src/utils/interlinear-project-summary.ts coverage exclusion.

Summary by CodeRabbit

  • New Features
    • Analysis changes are now automatically saved to your interlinear projects
    • Project analysis is loaded when opening a project to preserve your previous work

Review Change Stack

imnasnainaec and others added 4 commits May 27, 2026 11:56
Converts the custom useSyncExternalStore-based analysis store to Redux
Toolkit. Public API (AnalysisStoreProvider, useGloss, useAnalysis,
useGlossDispatch) is unchanged; all existing tests pass unmodified.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replaces the useRef triple-ref pattern with the conventional useMemo
approach for creating a stable context value object.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When the user selects an interlinear project, InterlinearizerLoader now
fetches the stored TextAnalysis via a new interlinearizer.getProject command
and passes it to Interlinearizer as initialAnalysis. A key prop forces the
Redux store inside AnalysisStoreProvider to remount on every project switch
so stale state never bleeds across projects. Gloss writes are persisted back
via a new interlinearizer.saveAnalysis command backed by a serialized
updateAnalysis function in projectStorage. Both commands are declared in
CommandHandlers and covered by full 100% test coverage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@imnasnainaec imnasnainaec self-assigned this May 27, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 27, 2026

Warning

Review limit reached

@imnasnainaec, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 25 minutes and 48 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 39ddab05-f9cf-42fc-b7f6-a8066c5738a8

📥 Commits

Reviewing files that changed from the base of the PR and between 9b923d0 and 5b335ad.

📒 Files selected for processing (5)
  • src/__tests__/components/InterlinearizerLoader.test.tsx
  • src/components/InterlinearizerLoader.tsx
  • src/store/analysisSlice.ts
  • src/types/interlinearizer.d.ts
  • src/types/typeGuards.ts
📝 Walkthrough

Walkthrough

This PR migrates analysis state management from a custom external store to Redux Toolkit and integrates per-project analysis loading and persistence. It introduces backend commands to fetch and save analyses, adds runtime type guards, refactors the AnalysisStore component to use Redux selectors and a callback-ref context, and wires the InterlinearizerLoader to load analysis on project selection and persist updates via the save callback.

Changes

Redux-backed analysis state and persistence

Layer / File(s) Summary
Type guards and command contracts
src/types/typeGuards.ts, src/types/interlinearizer.d.ts, src/components/CreateProjectModal.tsx, src/components/SelectInterlinearProjectModal.tsx
New isInterlinearProjectSummary and isTextAnalysis type guards validate runtime shapes, and command handler signatures declare interlinearizer.getProject and interlinearizer.saveAnalysis contracts. Component imports updated to use the new type guard location.
Redux store configuration and analysis slice
src/store/analysisSlice.ts, src/store/index.ts
Redux slice manages TextAnalysis and analysisLanguage, with setAnalysis and writeGloss reducers, memoized selectors for approved analysis lookups by token reference, and a store factory with typed state/dispatch.
Migrate AnalysisStore to Redux Provider
src/components/AnalysisStore.tsx
Replaces custom external store with Redux Provider, introduces callback-ref context (AnalysisCallbackCtx) to invoke latest save/gloss callbacks, and rewrites hooks to use useSelector with memoized selectors instead of snapshot subscriptions.
Backend commands for project and analysis management
src/main.ts
Implements getInterlinearProject and saveInterlinearAnalysis command handlers, registers both with platform command system, validates TextAnalysis via type guard, logs and notifies on errors, and adds registrations to activation context.
Storage update API for persisting analysis
src/services/projectStorage.ts
Adds updateAnalysis function that performs serialized per-project read-modify-write to replace a project's stored analysis, returning undefined when project is missing and propagating storage errors.
Load and persist analysis in InterlinearizerLoader
src/components/InterlinearizerLoader.tsx
Fetches analysis via interlinearizer.getProject on project change with cancellation-flag error handling, stores in local state, passes to Interlinearizer as initial state with project-id key, and persists updates through onSaveAnalysis callback using interlinearizer.saveAnalysis.
Tests for store, commands, storage, and components
src/__tests__/store/analysisSlice.test.ts, src/__tests__/main.test.ts, src/__tests__/services/projectStorage.test.ts, src/__tests__/components/InterlinearizerLoader.test.tsx, src/__tests__/components/PhraseBox.test.tsx, src/__tests__/components/TokenChip.test.tsx
Comprehensive test suites for slice reducers/selectors, backend command handlers with error cases and JSON validation, storage persistence, and updates component tests to mock new command props, validate type-guard imports, and use TokenSnapshot type in fixtures.
Configuration and dependency updates
package.json, jest.config.ts
Adds @reduxjs/toolkit and react-redux runtime dependencies and removes coverage exclusion for refactored type-guard utility.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • sillsdev/interlinearizer-extension#25: New isTextAnalysis type-guard and analysis persistence logic build on the TextAnalysis/token analysis shapes defined in the finalized interlinear model.
  • sillsdev/interlinearizer-extension#24: Both PRs extend src/main.ts command registration; main PR adds interlinearizer.getProject/interlinearizer.saveAnalysis, retrieved PR adds command handlers in overlapping extension activation flow.
  • sillsdev/interlinearizer-extension#81: Both PRs coordinate the isInterlinearProjectSummary refactor moving from utils to types module, plus jest.config.ts coverage updates for the same file.

Suggested labels

🟥High

Suggested reviewers

  • jasonleenaylor

Poem

🐰 Hops through Redux with glee,
Analysis state flows so free,
Load, persist, dispatch with care,
No custom stores anywhere!
Type-guards stand tall, selectors sing,
What a glorious state-management thing!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective: migrating to Redux and implementing persistence for interlinear projects, which are the core changes throughout the PR.
Linked Issues check ✅ Passed PR fully addresses #84 (Redux migration with new store files, reduced external store code) and #85 (project switching with analysis persistence via new command handlers and projectStorage.updateAnalysis integration).
Out of Scope Changes check ✅ Passed All changes directly support Redux migration and save/load functionality. Minor supporting changes (coverage config removal, consolidation of type guards to src/types) are aligned with the stated objectives.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch redux

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@imnasnainaec imnasnainaec changed the title Redux Implement redux store and save/load interlinear projects May 27, 2026
imnasnainaec and others added 3 commits May 27, 2026 14:20
…s on re-render

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Consolidates isInterlinearProjectSummary and the new isTextAnalysis type
guards into src/types/typeGuards.ts, removes the src/utils/ files, and
adds tests for the invalid-JSON and wrong-shape branches.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@imnasnainaec imnasnainaec marked this pull request as ready for review May 27, 2026 18:39
coderabbitai[bot]

This comment was marked as resolved.

imnasnainaec and others added 3 commits May 27, 2026 14:56
Adds helper guards (isAssignmentStatus, isTokenSnapshot, isAnalysisRecord,
isAnalysisLink, isSegmentAnalysisLink, isTokenAnalysisLink, isPhraseAnalysisLink)
and wires them into isTextAnalysis via .every() so malformed array elements are
rejected at runtime, not just the top-level array presence. Full JSDoc added to
all helpers.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Also handles the edge case where an approved link exists but its analysis
record is missing — previously silently swallowed, now falls through to
create a fresh pair.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@alex-rawlings-yyc alex-rawlings-yyc left a comment

Choose a reason for hiding this comment

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

:lgtm:

@alex-rawlings-yyc reviewed 20 files and all commit messages, and made 1 comment.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on imnasnainaec).

@alex-rawlings-yyc alex-rawlings-yyc merged commit 1c9cdb7 into main May 27, 2026
11 checks passed
@alex-rawlings-yyc alex-rawlings-yyc deleted the redux branch May 27, 2026 20:38
@coderabbitai coderabbitai Bot mentioned this pull request Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Update active state when switching interlinear projects Consider using redux for our store state

2 participants