Repository navigation
Finish class-to-function React component migration - #729
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Code reviewI reviewed the major class-to-function-component conversions in this PR (the imperative shells: I have no findings to flag. The conversion is careful and the StrictMode invariants that motivated each pattern are well-handled:
Overall correctness: the patch is correct. — Generated by Claude Code |
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 forgetDerivedStateFromError/componentDidCatch); every other component insrc/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)
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.diagram: small leaves— FlowIcon, LinkIcon, ModelIcon, Status, UndoRedoBar, ZoomBar, ErrorDetails, Snapshotter, ErrorToast, DeleteProjectButton, ModelPropertiesDrawer, StaticDiagram. Status/UndoRedoBar/ZoomBar wrapped inReact.memoto keep their pan-frame bailout. Adds behavior tests for the previously-untested leaves (incl. a fake-timer ErrorToast suite).diagram: complex panels— ModuleDetails, LineChart, LookupEditor, VariableDetails, HostedWebEditor. Preserves the projectGeneration-keyed-remount invariant via lazyuseStateinitializers; extracts a framework-freehosted-web-editor-core.ts.diagram: Editor.tsx— the 2.2k-line imperative shell, following the Canvas pattern (refs object,latestref, StrictMode-safe controller-per-mount, post-commit effects foronSelectionChanged/navReset). Five internal-touching test suites retargeted to observable behavior.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 capturedonAuthStateChangedlistener with no production test seam.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.diagram: website + test helpers + docs— website SimlinDiagram and the class-based controlled-wrapper test helpers;docs/dev/typescript.mdupdated to mandate function components for new code and document the conversion pattern;src/diagram/CLAUDE.mdEditor notes refreshed.Notable outcomes from the review loop
setTimeout(0)/clearTimeoutpairing.useImperativeHandletest seam added toInnerAppwas reworked out: the app tests now assert observable behavior with no production test-coupling.setStatein 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
ErrorBoundaryis the sole remaining class component.🤖 Generated with Claude Code