Skip to content

Finish class-to-function React component migration - #729

Merged
bpowers merged 7 commits into
mainfrom
functional-components-migration
Jun 8, 2026
Merged

bpowers merged 7 commits into
mainfrom
functional-components-migration

Conversation

@bpowers

@bpowers bpowers commented Jun 8, 2026

Copy link
Copy Markdown
Owner

Summary

Completes the class-to-function React component migration started in #721/#722/#723. After this branch, the only class component left in the codebase is ErrorBoundary (no hook equivalent for getDerivedStateFromError/componentDidCatch); every other component in src/diagram, src/app, src/simlin-serve/web, the website docs, and the diagram test helpers is now a function component.

Each batch was implemented by a fresh subagent and then adversarially reviewed by a separate subagent, iterating until no material findings remained.

Batches (one commit each)

  1. diagram: components/ library — SvgIcon, IconButton, Button, Drawer, Snackbar(+Content), TextField, SpeedDial(+Action/Icon), Tabs(+Tab). Adds a Tabs test (was untested) and a Drawer StrictMode focus-restore regression test.
  2. diagram: small leaves — FlowIcon, LinkIcon, ModelIcon, Status, UndoRedoBar, ZoomBar, ErrorDetails, Snapshotter, ErrorToast, DeleteProjectButton, ModelPropertiesDrawer, StaticDiagram. Status/UndoRedoBar/ZoomBar wrapped in React.memo to keep their pan-frame bailout. Adds behavior tests for the previously-untested leaves (incl. a fake-timer ErrorToast suite).
  3. diagram: complex panels — ModuleDetails, LineChart, LookupEditor, VariableDetails, HostedWebEditor. Preserves the projectGeneration-keyed-remount invariant via lazy useState initializers; extracts a framework-free hosted-web-editor-core.ts.
  4. diagram: Editor.tsx — the 2.2k-line imperative shell, following the Canvas pattern (refs object, latest ref, StrictMode-safe controller-per-mount, post-commit effects for onSelectionChanged/navReset). Five internal-touching test suites retargeted to observable behavior.
  5. app: remaining components — Login, NewProject, NewUser, Home, App/InnerApp. Firebase auth subscription moves to a StrictMode-safe mount effect; tests drive the auth chain via the captured onAuthStateChanged listener with no production test seam.
  6. serve: web SPA — App, EditorHost, EmptyState, NewProjectButton, ProjectList, diagram-mock. EditorHost preserves the 150ms selection debounce, projectFocused-once-per-path-change, WebSocket version gating, and 409 sidecar-redirect.
  7. diagram: website + test helpers + docs — website SimlinDiagram and the class-based controlled-wrapper test helpers; docs/dev/typescript.md updated to mandate function components for new code and document the conversion pattern; src/diagram/CLAUDE.md Editor notes refreshed.

Notable outcomes from the review loop

  • The Editor.tsx StrictMode review surfaced (and the implementer fixed) a real double-fetch regression in HostedWebEditor — the deferred load now schedules+cancels a timer to reproduce the class's setTimeout(0)/clearTimeout pairing.
  • An initial useImperativeHandle test seam added to InnerApp was reworked out: the app tests now assert observable behavior with no production test-coupling.
  • Filed diagram: Snapshotter modelErrors appends use non-functional setState (clobber-prone, currently dead code) #728 (latent non-functional setState in the currently-dead Snapshotter path) as tracked tech debt.

Verification

Every commit passed the full pre-commit hook (Rust fmt/clippy/test, TS lint/build/tsc/test, Python). Repo-wide grep confirms ErrorBoundary is the sole remaining class component.

🤖 Generated with Claude Code

bpowers added 7 commits June 8, 2026 09:27
Convert SvgIcon, IconButton, Button, Drawer, Snackbar (and
SnackbarContent), TextField, SpeedDial (and SpeedDialAction,
SpeedDialIcon), and Tabs (and Tab) from React.PureComponent to function
components, continuing the class-to-function migration. Public APIs are
unchanged: prop interfaces, export shapes, and call sites are untouched.

Stateful and lifecycle-bearing components map their behavior onto hooks:
TextField's isFocused becomes useState and its one-shot generated id a
lazy useState initializer; Drawer's mount/update/unmount focus
management and keydown listener become two useEffects. The Drawer focus
effect guards its prior-focus save against StrictMode's double-invoked
mount effect so closing a drawer mounted open restores focus to the
originally-focused element rather than the hidden panel. Tab's
static contextType becomes useContext.

These are UI chrome components, not render-hot per-element pieces, so
they follow the plain-function style of the already-converted siblings
(Dialog, Menu, Checkbox) rather than the React.memo treatment used for
the drawing layer. Adds a Tabs test (previously untested) and a Drawer
StrictMode focus-restore regression test.
Convert FlowIcon, LinkIcon, ModelIcon, Status, UndoRedoBar, ZoomBar,
ErrorDetails, Snapshotter, ErrorToast (Toast), DeleteProjectButton,
ModelPropertiesDrawer, and StaticDiagram from React.PureComponent to
function components. Public APIs are unchanged; no caller edits needed.

Status, UndoRedoBar, and ZoomBar are wrapped in React.memo: the Editor
replaces its controller snapshot wholesale on every optimistic-view
frame, so a pan/momentum gesture re-renders the Editor every frame.
PureComponent previously bailed these three out on stable props; memo
restores that bailout (their handlers are stable bound Editor methods,
so it holds). The remaining leaves are trivially cheap or out of the pan
path and stay plain functions.

ErrorToast's auto-hide timer becomes a single useEffect keyed on
[open, duration] that reproduces the class's mount-start plus
restart-on-duration-change, reading open/onClose/id/message through refs
so an unrelated message-only re-render does not restart the timer; the
cleanup clears the pending timer (StrictMode-safe). StaticDiagram and
DeleteProjectButton guard their post-await state updates against
unmount. Adds behavior tests for the previously-untested components,
including a fake-timer ErrorToast suite and StaticDiagram resolved-load
and cancelled-guard tests.
Convert ModuleDetails, LineChart, LookupEditor, VariableDetails, and
HostedWebEditor from React.PureComponent to function components. Public
APIs are unchanged; no caller edits needed.

VariableDetails and ModuleDetails seed their Slate editors and
deserialized contents from props in the constructor and rely on the
Editor's projectGeneration-keyed remount to refresh them. The conversion
preserves this exactly by mapping every constructor-seeded field to a
lazy useState initializer (one run per mount) and adding no prop->state
sync effect that would fight the keyed remount. VariableDetails' latex
load (formerly componentDidMount + componentDidUpdate on ident) becomes
a useEffect keyed on the view ident with a request-id and mounted-ref
race guard.

HostedWebEditor's coordination logic is extracted into a framework-free
hosted-web-editor-core.ts (loadProject/saveProject/deleteProject/
redirectToHome with injected fetch) so it is unit-testable without the
WASM Editor. The deferred initial load is scheduled with setTimeout and
cancelled in the effect cleanup, reproducing the class's
componentDidMount setTimeout(0) / componentWillUnmount clearTimeout
pairing so React StrictMode's throwaway first mount does not fire a
duplicate network request. LineChart's ResizeObserver, one-shot clip id,
and non-rendering drag flag map to useEffect/lazy-useState/useRef.

Tests are retargeted from class internals (.state, prototype methods,
component refs) to observable behavior, and strengthened: the latex test
asserts the rendered KaTeX text identity so a stale success cannot
overwrite the current variable undetected; a StrictMode mount test pins
the load-once guarantee; a new shell suite covers the readOnlyMode
no-op guards, save version commit, and post-delete navigation.
Convert the diagram editor's imperative shell from React.PureComponent
to a React.memo function component, completing the class-to-function
migration of the diagram package (ErrorBoundary intentionally remains a
class, having no hook equivalent). This follows the Canvas.tsx
conversion pattern from #723.

Instance fields (the ProjectController, its unsubscribe, lastNavResetSeq,
the errorKey WeakMap/counter, and liveSnapshotUrl) move into a single
mutable refs object; EditorState becomes one useState with a merge-style
setState helper so the many partial and functional setState calls keep
their class semantics. A latest ref refreshed synchronously each render
is what escaped callbacks (the controller subscription, the global
keydown listener, the snapshot image load handlers) read, so they always
observe current props and state.

The controller is constructed once in a refs-init guard rather than the
useState initializer: StrictMode double-invokes the initializer, which
would build and orphan a second controller. The empty-deps mount effect
rebuilds the controller when a prior cleanup disposed it, so a StrictMode
mount/unmount/mount cycle creates a fresh controller on the second mount,
preserving the controller-per-mount lifecycle invariant. The two
componentDidUpdate behaviors become post-commit effects: onSelection
changed fires on every committed selection change but not on mount (a
prevSelection ref with a content-equal Set guard), and the navResetSeq
effect clears selection/details/tool once per undo-driven navigation
reset. Details panels stay keyed by projectGeneration.

Handlers passed to memo'd children (Canvas and the now-memo'd Status,
UndoRedoBar, ZoomBar, BreadcrumbBar) are useCallback-stable reading
through the latest ref, so their memoization holds on the pan path. The
five Editor test suites that reached into class internals are retargeted
to render a real Editor and assert observable behavior, in several cases
strengthened (real remount counts, real selection-ident mapping, a
StrictMode read-only-toast-once case).
Convert Login, NewProject, NewUser, Home, and App.tsx (both InnerApp and
the StrictMode-wrapping App) from class components to function
components. This completes the repo's diagram and app class-to-function
migration; the only class component that remains by design is
ErrorBoundary, which has no hook equivalent.

App's Firebase onAuthStateChanged subscription and deferred getUserInfo
move into an empty-deps mount effect whose cleanup unsubscribes and
clears the timer, so a StrictMode mount/unmount/mount leaves exactly one
live subscription. Instance fields (subscription handle, timers, the
unmount latch) move into a refs object, and the escaped async auth
handlers read current state through a latest ref refreshed each render,
matching the Canvas/Editor pattern. Home's post-fetch setState is guarded
by the same unmount latch the class used. The wouter route components
(home/editor) are useCallback-stable so an unrelated InnerApp re-render
does not remount Home and re-fire its project fetch, while still reading
the current user through the latest ref.

Form/page state maps to useState (a single merged object with a
class-parity setState helper where handlers issue multi-field patches,
per-field state elsewhere); constructor-derived state uses lazy
initializers. Tests that reached into class internals are retargeted to
observable behavior: the auth chain is driven by invoking the captured
onAuthStateChanged listener and asserting on the rendered DOM and mocked
fetch/signOut calls, with no production test seam. The StrictMode test
asserts every captured subscription is unsubscribed so a leaked
subscription is caught, and the route-stability regression test asserts
Home mounts once and reflects the current user.
Convert the simlin-serve web SPA's class components -- App,
EditorHost, EmptyState, NewProjectButton, ProjectList, and the
diagram-mock test Editor -- to function components, following the same
imperative-shell pattern used across the rest of the repo (instance
fields in a refs object, a latest ref for escaped callbacks, lazy
useState initializers, StrictMode-safe symmetric mount effects, and
componentDidUpdate prev-value comparisons as prevProps-ref-guarded
post-commit effects). Public APIs and call sites are unchanged.

EditorHost is the substantive one: its 150ms selection debounce clears
and reschedules a refs-held timer whose trailing edge reads the latest
path and selection and drops the frame on a path swap during the window;
projectFocused emits once on a path-present mount (mount effect) and once
per path change (the post-commit effect, which seeds its prevProps on the
first run so it never double-emits on mount); the 409 sidecar-redirect
and the load-key/path stale-drop guards on async load and save are
preserved verbatim, reading committed state through the latest ref. App
owns the single UpdatesSocket, created once in the mount effect and
closed on cleanup. Existing tests were already behavior-driven (real
renders, mocked fetch/WebSocket, fake timers, EditorMock.lastProps) and
stayed green unchanged.
…docs)

Convert the last remaining class components in the repo to function
components: the website's SimlinDiagram doc component (a lazy useState
initializer seeds the static demo project once per mount) and the
class-based controlled-wrapper test helpers in src/diagram/tests/
(ControlledAutocomplete, ControlledDrawer, ControlledSnackbar and its
inline wrappers, ControlledSpeedDial). The test wrappers become
forwardRef function components exposing the same imperative surface the
tests drive, so every assertion is unchanged.

With this, the only class component left in the codebase is
ErrorBoundary, which has no hook equivalent. Update docs/dev/typescript.md
to mandate function components for new code (ErrorBoundary the sole
exception) and document the established conversion pattern -- refs object
for instance state, a latest ref for escaped callbacks, lazy useState
initializers, StrictMode-safe symmetric mount effects, and post-commit
effects guarding componentDidUpdate comparisons. Refresh the Editor
notes and invariants in src/diagram/CLAUDE.md to describe the
function-component mechanism.
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.61%. Comparing base (cac628b) to head (ba12314).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #729      +/-   ##
==========================================
- Coverage   90.61%   90.61%   -0.01%     
==========================================
  Files         224      224              
  Lines      135889   135889              
==========================================
- Hits       123136   123132       -4     
- Misses      12753    12757       +4     

☔ 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.

@claude

claude Bot commented Jun 8, 2026

Copy link
Copy Markdown

Code review

I reviewed the major class-to-function-component conversions in this PR (the imperative shells: Editor.tsx, HostedWebEditor.tsx, EditorHost.tsx, App.tsx / InnerApp in both src/app and src/simlin-serve, plus the leaf-to-shell range including Login.tsx, Home.tsx, NewProject.tsx, NewUser.tsx, LookupEditor.tsx, LineChart.tsx, VariableDetails.tsx, ModuleDetails.tsx, Drawer.tsx, SimlinDiagram.tsx, and hosted-web-editor-core.ts).

I have no findings to flag. The conversion is careful and the StrictMode invariants that motivated each pattern are well-handled:

  • Editor.tsx constructs the ProjectController in a refs-init guard rather than the useState initializer, which correctly avoids orphaning a second controller under StrictMode's double-invoked lazy initializer. The mount-effect cleanup disposes and clears r.controller, so the second StrictMode mount rebuilds a fresh one via the same guard inside the effect. The readOnlyToastAppended latch, the prevSelection ref + setsEqual guard on the post-commit onSelectionChanged effect, the navResetSeq ref seeded from the initial snapshot, and the snapshot-URL ownership remaining on the refs object (so back-to-back snapshots don't both revoke the same stale value) all match the documented invariants.
  • HostedWebEditor.tsx schedules the project load via setTimeout(0) inside the mount effect so the StrictMode first-mount cancels via the cleanup before the fetch fires (one network request, matching the class). hosted-web-editor-core.ts correctly factors out the framework-free HTTP operations and the redirectToHome namespace-routed seam for the jsdom-non-spyable window.location.assign.
  • EditorHost.tsx's post-commit "update" effect (no dep array) guards its body with a prev.current.props === null check on first run, mirroring componentDidUpdate's "fire on change, not on mount" semantics. App in src/simlin-serve is intentionally not wrapped in StrictMode, so the double-invoke divergence on that no-deps effect does not surface in production or in the EditorHost tests (which render without StrictMode).
  • App.tsx / InnerApp keeps stable identities on the home/editor route components via useCallback([])/[handleLogout] (so wouter does not unmount/remount Home or HostedWebEditor on every InnerApp state change), and the firebase auth subscription / deferred getUserInfo schedule live in the mount effect with a symmetric cleanup.
  • LookupEditor.tsx, VariableDetails.tsx, ModuleDetails.tsx correctly use lazy useState initializers for their Slate editors and content seeds. The Editor keys these panels on projectGeneration, so a content change remounts the panel and re-seeds it; the deliberate absence of a prop-sync effect preserves that invariant.

Overall correctness: the patch is correct.

— Generated by Claude Code

@bpowers
bpowers merged commit 090c254 into main Jun 8, 2026
15 checks passed
@bpowers
bpowers deleted the functional-components-migration branch June 8, 2026 20:26
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.

1 participant