Skip to content

refactor(app): decompose widget-editor-modal into sub-components (#573) - #627

Merged
alfredo1996 merged 3 commits into
release/2.0from
refactor/issue-573-extract-save-hook
May 1, 2026
Merged

refactor(app): decompose widget-editor-modal into sub-components (#573)#627
alfredo1996 merged 3 commits into
release/2.0from
refactor/issue-573-extract-save-hook

Conversation

@alfredo1996

@alfredo1996 alfredo1996 commented Apr 28, 2026

Copy link
Copy Markdown
Owner

Summary

  • Extract 8 sub-components from the 1,405-line widget-editor-modal monolith, reducing it to 857 lines
  • use-widget-save.ts — encapsulates widget construction for all 3 save paths (handleSave, handleRunAndSave, handleLabSave)
  • use-auto-preview.ts — auto-preview debouncing, run+save shortcut, keyboard handler
  • 4 Advanced tab sections: caching, interactivity, styling, form-refresh
  • lab-metadata-form.tsx — template name/description/tags
  • modal-footer.tsx — save/cancel buttons for lab + normal modes
  • Bug fix: buildClickAction() now correctly receives layout argument

Test plan

  • 52 new unit tests across 6 test files — all passing
  • 2288 total unit tests passing (173 files)
  • TypeScript compiles clean (zero errors from changed files)
  • Zero lint errors on changed files
  • E2E blocked by pre-existing webpack tls module resolution issue (not related to this PR)

Closes #573

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Refactor

    • Restructured the widget editor modal to improve code organization and maintainability through modular component composition. Extracted preview logic and save functionality into dedicated hooks for better separation of concerns.
  • Tests

    • Added comprehensive unit test coverage for widget editor components and core functionality including caching, form refresh, interactivity, styling, and modal operations.

@coderabbitai

coderabbitai Bot commented Apr 28, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@alfredo1996 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 37 minutes and 27 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5a2d7eed-00e9-4c61-b407-2feb28d67923

📥 Commits

Reviewing files that changed from the base of the PR and between 5075de4 and 45a7dd6.

📒 Files selected for processing (17)
  • app/src/components/widget-editor-modal.tsx
  • app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-form-refresh-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-interactivity-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-styling-section.test.tsx
  • app/src/components/widget-editor/__tests__/lab-metadata-form.test.tsx
  • app/src/components/widget-editor/__tests__/modal-footer.test.tsx
  • app/src/components/widget-editor/__tests__/use-auto-preview.test.tsx
  • app/src/components/widget-editor/__tests__/use-widget-save.test.tsx
  • app/src/components/widget-editor/advanced-caching-section.tsx
  • app/src/components/widget-editor/advanced-form-refresh-section.tsx
  • app/src/components/widget-editor/advanced-interactivity-section.tsx
  • app/src/components/widget-editor/advanced-styling-section.tsx
  • app/src/components/widget-editor/lab-metadata-form.tsx
  • app/src/components/widget-editor/modal-footer.tsx
  • app/src/components/widget-editor/use-auto-preview.ts
  • app/src/components/widget-editor/use-widget-save.ts

Walkthrough

Refactors WidgetEditorModal by extracting inline preview logic, run-and-save keyboard handling, and widget serialization into dedicated hooks and components. Introduces useAutoPreview for preview execution and save-status management, useBuildWidgetForSave for widget payload construction, and six new UI section components replacing inline configuration blocks. Removes ~591 lines from the modal while maintaining existing functionality.

Changes

Cohort / File(s) Summary
Core Modal Refactoring
app/src/components/widget-editor-modal.tsx
Removes local preview effects, handlePreview/handleSave implementations, CMD/Ctrl+Shift+Enter flow, and large inline UI sections. Delegates to new hooks and sub-components; net reduction of 548 lines.
Preview and Save Hooks
app/src/components/widget-editor/use-auto-preview.ts, use-widget-save.ts
useAutoPreview: manages preview execution with debounce (800ms on query change), auto-trigger on open, and keyboard shortcut (CMD/Ctrl+Shift+Enter) for run-and-save with brief "saved" status. useBuildWidgetForSave: constructs DashboardWidget payload with chart-type-specific handling for parameter-select, form modes, query history recording, and conditional fields (click-action, styling, caching, transforms).
Advanced Settings Components
app/src/components/widget-editor/advanced-caching-section.tsx, advanced-form-refresh-section.tsx, advanced-interactivity-section.tsx, advanced-styling-section.tsx
Four new client components wrapping widget-editor store state for caching (TTL input with 1–1440 minute range), form refresh widget selection (with bulk select), click-action enablement and collision alerts, and rule-based styling toggle with rule-count display.
Modal Structure Components
app/src/components/widget-editor/lab-metadata-form.tsx, modal-footer.tsx
LabMetadataForm: three inputs for lab name, description, and tags. ModalFooter: conditional cancel/save/lab-save buttons with dynamic disable logic based on chart type, query presence, required field validation, and loading states.
Component Test Coverage
app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx, advanced-form-refresh-section.test.tsx, advanced-interactivity-section.test.tsx, advanced-styling-section.test.tsx, lab-metadata-form.test.tsx, modal-footer.test.tsx
Six comprehensive Vitest + RTL suites verifying correct rendering, state synchronization with store, user interactions (checkbox toggles, input changes, button clicks), conditional visibility, pluralization, validation logic (TTL clamping, required field checks), and bulk selection behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

Suggested labels

enhancement, pkg:app, area:widgets

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main refactoring: decomposing widget-editor-modal into sub-components, matching the primary objective of splitting a large monolithic component into smaller, testable pieces.
Linked Issues check ✅ Passed All four acceptance criteria from #573 are met: duplicated local state removed via store-only approach, single initialization path via store methods, buildClickAction unified in one place, modal decomposed into <500-line sub-components, and comprehensive unit tests added.
Out of Scope Changes check ✅ Passed All changes are directly aligned with #573 objectives: sub-component extraction, hook creation for save/preview logic, state consolidation, and test coverage. No unrelated features or scope creep detected.

✏️ 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 refactor/issue-573-extract-save-hook

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
Review rate limit: 0/1 reviews remaining, refill in 37 minutes and 27 seconds.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (3)
app/src/components/widget-editor/__tests__/lab-metadata-form.test.tsx (1)

64-67: Assert semantic required behavior, not just the asterisk.

Consider validating the input has required to lock in accessibility semantics.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/__tests__/lab-metadata-form.test.tsx` around
lines 64 - 67, The test currently asserts only that an asterisk is rendered;
instead assert the input has the semantic required attribute: render
LabMetadataForm, query the "template name" input (e.g. via
screen.getByLabelText('Template name') or screen.getByRole('textbox', { name:
/template name/i }) to target the template name field in LabMetadataForm) and
expect that element.toHaveAttribute('required') or element.required to be true;
replace or augment the getByText("*") assertion with this required-attribute
check to ensure accessibility semantics.
app/src/components/widget-editor/lab-metadata-form.tsx (1)

17-25: Expose required semantics on Template Name input.

The field is visually required but not semantically marked required.

💡 Suggested fix
         <Input
           id="lab-template-name"
           value={labName}
           onChange={(e) => setLabName(e.target.value)}
           placeholder="My chart template"
+          required
+          aria-required="true"
         />
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/lab-metadata-form.tsx` around lines 17 - 25,
The Template Name input is only visually marked required but lacks semantic
required attributes; update the Input usage in lab-metadata-form (the Input tied
to labName / setLabName) to include required and aria-required="true" (or the
component's equivalent prop) so the field is programmatically exposed as
required to assistive tech and HTML validation.
app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx (1)

94-121: Consider adding edge-case tests for TTL parser guardrails.

Add cases for >1440 clamping and invalid numeric intermediates so this doesn’t regress.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx`
around lines 94 - 121, Add tests in advanced-caching-section.test.tsx that
exercise AdvancedCachingSection’s TTL parser guardrails: render
AdvancedCachingSection with mockEnableCache = true and fireEvent.change on the
"cache-ttl" input with a value >1440 (e.g., "2000") and assert
mockSetCacheTtlMinutes was called with 1440, and add another test that sends
invalid/intermediate numeric inputs (e.g., "", "abc", "1.5") to the same
"cache-ttl" input and assert mockSetCacheTtlMinutes is clamped/normalized to the
minimum (1) or expected safe value; reference the AdvancedCachingSection
component, the "cache-ttl" test id, and mockSetCacheTtlMinutes when adding these
tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/src/components/widget-editor/advanced-caching-section.tsx`:
- Around line 38-40: The onChange handler for the TTL uses
Number(e.target.value) and Math.max but can save NaN and doesn't enforce the
upper bound; update the handler that calls setCacheTtlMinutes to parse the input
(e.g., parseInt/parseFloat), check isNaN and default to 1 if invalid, then clamp
the value between 1 and 1440 using Math.max/Math.min before passing to
setCacheTtlMinutes (refer to the onChange arrow function and the
setCacheTtlMinutes call).

In `@app/src/components/widget-editor/advanced-form-refresh-section.tsx`:
- Around line 14-17: The UI currently uses refreshWidgetIds.length and raw
includes() which counts/marks IDs that might not be visible; instead derive
selection state from the visible widget list (otherWidgets) before rendering and
when computing bulk/row state. Create a visibleSelectedIds/visibleSelectedSet by
filtering refreshWidgetIds to only IDs present in otherWidgets (e.g., const
visibleSelectedIds = refreshWidgetIds.filter(id => otherWidgets.some(w => w.id
=== id)); const visibleSelectedSet = new Set(visibleSelectedIds)); use
visibleSelectedIds.length for the "n of m selected" display and
visibleSelectedSet.has(id) for per-row checked state; update bulk toggle
handlers to add/remove only the visible widget ids to/from the global
refreshWidgetIds via setRefreshWidgetIds(prev => { const s = new Set(prev); if
(selecting) visibleIds.forEach(id => s.add(id)); else visibleIds.forEach(id =>
s.delete(id)); return Array.from(s); }) so store still holds other selections
but UI reflects only visible ones.

In `@app/src/components/widget-editor/modal-footer.tsx`:
- Around line 41-43: The lab error banner (labError) is being rendered
regardless of the current editor mode and can leak stale errors into "add" or
"edit" sessions; update the rendering in modal-footer.tsx (ModalFooter/its JSX)
to only show the paragraph when labError is set AND mode === "lab" (i.e., change
the condition from just labError to labError && mode === "lab"), ensuring the
component uses the passed-in mode prop so lab-only errors don't appear in other
modes.
- Around line 47-81: The save validation is inconsistent between the lab and
normal branches causing param-select templates to be unsavable in lab mode and
allowing empty connectionId in normal mode; extract the predicate into a single
helper (e.g., canSaveWidget or validateSaveGuard) that encapsulates the rules:
if isParamSelect then require paramWidgetName.trim() and if paramUIType ===
"select" require connectionId && String(chartOptions.seedQuery ?? "").trim();
else if isContentOnly allow save; else (non-content) require connectionId &&
query.trim(); then replace the duplicated disabled expressions in both
LoadingButton branches to call this helper and ensure onLabSave/onSave (and
buildWidgetForSave) are only invoked when the helper returns true. Use the
existing symbols isLabMode, isParamSelect, paramWidgetName, paramUIType,
connectionId, chartOptions.seedQuery, isContentOnly, query, onLabSave, onSave,
saveStatus and buildWidgetForSave to locate and update the logic.

In `@app/src/components/widget-editor/use-auto-preview.ts`:
- Around line 181-186: When the modal closes in the useEffect watching open,
also reset the save status to avoid a stale "Saved!" message: after clearing
savedTimerRef (in the useEffect that checks if (!open && savedTimerRef.current
!== null)), call setSaveStatus('idle') (or the hook's neutral state value) so
saveStatus is reset; reference the useAutoPreview hook's savedTimerRef,
saveStatus, setSaveStatus and the open variable when making this change.
- Around line 130-136: The run+save path in handleRunAndSave currently calls
previewQueryRef.current.mutate without sending the extracted query parameters,
so parameterized queries fail; update handleRunAndSave to include the same
extracted params payload that handlePreview sends (pass the params/parsedParams
or the same param object used by handlePreview) when calling
previewQueryRef.current.mutate and any subsequent save/mutate logic so
parameterized queries receive their params.

---

Nitpick comments:
In
`@app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx`:
- Around line 94-121: Add tests in advanced-caching-section.test.tsx that
exercise AdvancedCachingSection’s TTL parser guardrails: render
AdvancedCachingSection with mockEnableCache = true and fireEvent.change on the
"cache-ttl" input with a value >1440 (e.g., "2000") and assert
mockSetCacheTtlMinutes was called with 1440, and add another test that sends
invalid/intermediate numeric inputs (e.g., "", "abc", "1.5") to the same
"cache-ttl" input and assert mockSetCacheTtlMinutes is clamped/normalized to the
minimum (1) or expected safe value; reference the AdvancedCachingSection
component, the "cache-ttl" test id, and mockSetCacheTtlMinutes when adding these
tests.

In `@app/src/components/widget-editor/__tests__/lab-metadata-form.test.tsx`:
- Around line 64-67: The test currently asserts only that an asterisk is
rendered; instead assert the input has the semantic required attribute: render
LabMetadataForm, query the "template name" input (e.g. via
screen.getByLabelText('Template name') or screen.getByRole('textbox', { name:
/template name/i }) to target the template name field in LabMetadataForm) and
expect that element.toHaveAttribute('required') or element.required to be true;
replace or augment the getByText("*") assertion with this required-attribute
check to ensure accessibility semantics.

In `@app/src/components/widget-editor/lab-metadata-form.tsx`:
- Around line 17-25: The Template Name input is only visually marked required
but lacks semantic required attributes; update the Input usage in
lab-metadata-form (the Input tied to labName / setLabName) to include required
and aria-required="true" (or the component's equivalent prop) so the field is
programmatically exposed as required to assistive tech and HTML validation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 86a5241f-ea07-47e0-a5f0-b67d484b8aaa

📥 Commits

Reviewing files that changed from the base of the PR and between 2b5ca1f and 5075de4.

📒 Files selected for processing (15)
  • app/src/components/widget-editor-modal.tsx
  • app/src/components/widget-editor/__tests__/advanced-caching-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-form-refresh-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-interactivity-section.test.tsx
  • app/src/components/widget-editor/__tests__/advanced-styling-section.test.tsx
  • app/src/components/widget-editor/__tests__/lab-metadata-form.test.tsx
  • app/src/components/widget-editor/__tests__/modal-footer.test.tsx
  • app/src/components/widget-editor/advanced-caching-section.tsx
  • app/src/components/widget-editor/advanced-form-refresh-section.tsx
  • app/src/components/widget-editor/advanced-interactivity-section.tsx
  • app/src/components/widget-editor/advanced-styling-section.tsx
  • app/src/components/widget-editor/lab-metadata-form.tsx
  • app/src/components/widget-editor/modal-footer.tsx
  • app/src/components/widget-editor/use-auto-preview.ts
  • app/src/components/widget-editor/use-widget-save.ts

Comment on lines +38 to +40
onChange={(e) =>
setCacheTtlMinutes(Math.max(1, Number(e.target.value)))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

TTL normalization allows invalid values (NaN) and ignores max bound.

Current conversion can store NaN, and values above 1440 are not clamped before writing to state.

💡 Suggested fix
           <Input
             id="cache-ttl"
             type="number"
             min={1}
             max={1440}
             value={cacheTtlMinutes}
-            onChange={(e) =>
-              setCacheTtlMinutes(Math.max(1, Number(e.target.value)))
-            }
+            onChange={(e) => {
+              const parsed = Number.parseInt(e.target.value, 10);
+              if (Number.isNaN(parsed)) return;
+              setCacheTtlMinutes(Math.min(1440, Math.max(1, parsed)));
+            }}
             className="w-24"
           />
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onChange={(e) =>
setCacheTtlMinutes(Math.max(1, Number(e.target.value)))
}
onChange={(e) => {
const parsed = Number.parseInt(e.target.value, 10);
if (Number.isNaN(parsed)) return;
setCacheTtlMinutes(Math.min(1440, Math.max(1, parsed)));
}}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/advanced-caching-section.tsx` around lines
38 - 40, The onChange handler for the TTL uses Number(e.target.value) and
Math.max but can save NaN and doesn't enforce the upper bound; update the
handler that calls setCacheTtlMinutes to parse the input (e.g.,
parseInt/parseFloat), check isNaN and default to 1 if invalid, then clamp the
value between 1 and 1440 using Math.max/Math.min before passing to
setCacheTtlMinutes (refer to the onChange arrow function and the
setCacheTtlMinutes call).

Comment on lines +14 to +17
const refreshWidgetIds = useWidgetEditorStore((s) => s.refreshWidgetIds);
const setRefreshWidgetIds = useWidgetEditorStore(
(s) => s.setRefreshWidgetIds,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Derive selection state from the visible widget list.

Lines 31-49 use refreshWidgetIds.length and raw includes() checks directly. If the store still contains ids for widgets that were deleted or moved out of otherWidgets, the UI can show n of m selected while no visible row is checked, and the bulk-action label becomes inconsistent.

Proposed fix
   const refreshWidgetIds = useWidgetEditorStore((s) => s.refreshWidgetIds);
   const setRefreshWidgetIds = useWidgetEditorStore(
     (s) => s.setRefreshWidgetIds,
   );
+  const visibleSelectedWidgetIds = otherWidgets
+    .map((w) => w.id)
+    .filter((id) => refreshWidgetIds.includes(id));
+  const allVisibleSelected =
+    otherWidgets.length > 0 &&
+    visibleSelectedWidgetIds.length === otherWidgets.length;
 
   return (
@@
             <span className="text-xs text-muted-foreground">
-              {refreshWidgetIds.length} of {otherWidgets.length} selected
+              {visibleSelectedWidgetIds.length} of {otherWidgets.length} selected
             </span>
             <Button
@@
               className="h-6 text-xs px-2"
               onClick={() => {
-                const allSelected = otherWidgets.every((w) =>
-                  refreshWidgetIds.includes(w.id),
-                );
                 setRefreshWidgetIds(
-                  allSelected ? [] : otherWidgets.map((w) => w.id),
+                  allVisibleSelected ? [] : otherWidgets.map((w) => w.id),
                 );
               }}
             >
-              {otherWidgets.every((w) => refreshWidgetIds.includes(w.id))
+              {allVisibleSelected
                 ? "Deselect all"
                 : "Select all"}
             </Button>
@@
               <Checkbox
                 id={`refresh-widget-${w.id}`}
-                checked={refreshWidgetIds.includes(w.id)}
+                checked={visibleSelectedWidgetIds.includes(w.id)}
                 onCheckedChange={(checked) => {
                   if (checked) {
-                    setRefreshWidgetIds([...refreshWidgetIds, w.id]);
+                    setRefreshWidgetIds(
+                      Array.from(new Set([...visibleSelectedWidgetIds, w.id])),
+                    );
                   } else {
                     setRefreshWidgetIds(
-                      refreshWidgetIds.filter((id: string) => id !== w.id),
+                      visibleSelectedWidgetIds.filter((id) => id !== w.id),
                     );
                   }
                 }}
               />

Also applies to: 27-77

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/advanced-form-refresh-section.tsx` around
lines 14 - 17, The UI currently uses refreshWidgetIds.length and raw includes()
which counts/marks IDs that might not be visible; instead derive selection state
from the visible widget list (otherWidgets) before rendering and when computing
bulk/row state. Create a visibleSelectedIds/visibleSelectedSet by filtering
refreshWidgetIds to only IDs present in otherWidgets (e.g., const
visibleSelectedIds = refreshWidgetIds.filter(id => otherWidgets.some(w => w.id
=== id)); const visibleSelectedSet = new Set(visibleSelectedIds)); use
visibleSelectedIds.length for the "n of m selected" display and
visibleSelectedSet.has(id) for per-row checked state; update bulk toggle
handlers to add/remove only the visible widget ids to/from the global
refreshWidgetIds via setRefreshWidgetIds(prev => { const s = new Set(prev); if
(selecting) visibleIds.forEach(id => s.add(id)); else visibleIds.forEach(id =>
s.delete(id)); return Array.from(s); }) so store still holds other selections
but UI reflects only visible ones.

Comment on lines +41 to +43
{labError && (
<p className="text-sm text-destructive mr-auto">{labError}</p>
)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Only show labError in lab mode.

Lines 41-43 render the template-save error banner even when mode is "add" or "edit". Since the parent keeps labError in component state, a failed lab save can leak a stale error into a later widget-edit session.

Proposed fix
-      {labError && (
+      {isLabMode && labError && (
         <p className="text-sm text-destructive mr-auto">{labError}</p>
       )}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{labError && (
<p className="text-sm text-destructive mr-auto">{labError}</p>
)}
{isLabMode && labError && (
<p className="text-sm text-destructive mr-auto">{labError}</p>
)}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/modal-footer.tsx` around lines 41 - 43, The
lab error banner (labError) is being rendered regardless of the current editor
mode and can leak stale errors into "add" or "edit" sessions; update the
rendering in modal-footer.tsx (ModalFooter/its JSX) to only show the paragraph
when labError is set AND mode === "lab" (i.e., change the condition from just
labError to labError && mode === "lab"), ensuring the component uses the
passed-in mode prop so lab-only errors don't appear in other modes.

Comment on lines +47 to +81
{isLabMode ? (
<LoadingButton
type="button"
disabled={!labName.trim() || (!isContentOnly && !query.trim())}
loading={labSaving}
loadingText="Saving..."
onClick={onLabSave}
>
{mode === "lab-edit" ? "Save Template" : "Create Template"}
</LoadingButton>
) : (
<LoadingButton
type="button"
disabled={
isParamSelect
? !paramWidgetName.trim() ||
(paramUIType === "select" &&
(!connectionId ||
!String(chartOptions.seedQuery ?? "").trim()))
: isContentOnly
? false
: isForm
? !connectionId || !query.trim()
: !query.trim()
}
loading={saveStatus === "saving"}
loadingText="Saving..."
onClick={onSave}
>
{saveStatus === "saved"
? "Saved!"
: mode === "edit"
? "Save Changes"
: "Add Widget"}
</LoadingButton>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Unify the save guard across both branches.

Lines 50-71 validate different things depending on mode, and that breaks real flows. In lab mode, parameter-select templates are effectively unsavable because the predicate requires query, even though that editor path uses paramWidgetName/seedQuery instead. In normal mode, the default branch still allows saving non-content widgets with a query but no connectionId, and buildWidgetForSave() will persist that empty connection id.

Proposed fix
   const isParamSelect = chartType === "parameter-select";
   const isForm = chartType === "form";
   const isLabMode = mode === "lab-edit" || mode === "lab-create";
+  const hasRequiredWidgetFields = isParamSelect
+    ? !!paramWidgetName.trim() &&
+      (paramUIType !== "select" ||
+        (!!connectionId && !!String(chartOptions.seedQuery ?? "").trim()))
+    : isContentOnly
+      ? true
+      : !!connectionId && !!query.trim();
+
+  const widgetSaveDisabled = !hasRequiredWidgetFields;
+  const labSaveDisabled = !labName.trim() || !hasRequiredWidgetFields;
 
   return (
     <DialogFooter>
@@
       {isLabMode ? (
         <LoadingButton
           type="button"
-          disabled={!labName.trim() || (!isContentOnly && !query.trim())}
+          disabled={labSaveDisabled}
           loading={labSaving}
           loadingText="Saving..."
           onClick={onLabSave}
         >
@@
       ) : (
         <LoadingButton
           type="button"
-          disabled={
-            isParamSelect
-              ? !paramWidgetName.trim() ||
-                (paramUIType === "select" &&
-                  (!connectionId ||
-                    !String(chartOptions.seedQuery ?? "").trim()))
-              : isContentOnly
-                ? false
-                : isForm
-                  ? !connectionId || !query.trim()
-                  : !query.trim()
-          }
+          disabled={widgetSaveDisabled}
           loading={saveStatus === "saving"}
           loadingText="Saving..."
           onClick={onSave}
         >
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/modal-footer.tsx` around lines 47 - 81, The
save validation is inconsistent between the lab and normal branches causing
param-select templates to be unsavable in lab mode and allowing empty
connectionId in normal mode; extract the predicate into a single helper (e.g.,
canSaveWidget or validateSaveGuard) that encapsulates the rules: if
isParamSelect then require paramWidgetName.trim() and if paramUIType ===
"select" require connectionId && String(chartOptions.seedQuery ?? "").trim();
else if isContentOnly allow save; else (non-content) require connectionId &&
query.trim(); then replace the duplicated disabled expressions in both
LoadingButton branches to call this helper and ensure onLabSave/onSave (and
buildWidgetForSave) are only invoked when the helper returns true. Use the
existing symbols isLabMode, isParamSelect, paramWidgetName, paramUIType,
connectionId, chartOptions.seedQuery, isContentOnly, query, onLabSave, onSave,
saveStatus and buildWidgetForSave to locate and update the logic.

Comment on lines +130 to +136
const handleRunAndSave = useCallback(() => {
if (chartType === "markdown" || chartType === "iframe") return;
if (!query.trim() || saveStatus === "saving") return;
setSaveStatus("saving");
previewQueryRef.current.mutate(
{ connectionId, query },
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Run+save path drops query params for parameterized queries.

handlePreview sends extracted params, but the keyboard run+save path does not. Queries with references can fail only on this shortcut.

💡 Suggested fix
   const handleRunAndSave = useCallback(() => {
     if (chartType === "markdown" || chartType === "iframe") return;
     if (!query.trim() || saveStatus === "saving") return;
     setSaveStatus("saving");
+    const referenced = extractReferencedParams(query, allParamValues);
+    const params =
+      Object.keys(referenced).length > 0 ? referenced : undefined;
     previewQueryRef.current.mutate(
-      { connectionId, query },
+      { connectionId, query, params },
       {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/use-auto-preview.ts` around lines 130 - 136,
The run+save path in handleRunAndSave currently calls
previewQueryRef.current.mutate without sending the extracted query parameters,
so parameterized queries fail; update handleRunAndSave to include the same
extracted params payload that handlePreview sends (pass the params/parsedParams
or the same param object used by handlePreview) when calling
previewQueryRef.current.mutate and any subsequent save/mutate logic so
parameterized queries receive their params.

Comment on lines +181 to +186
useEffect(() => {
if (!open && savedTimerRef.current !== null) {
clearTimeout(savedTimerRef.current);
savedTimerRef.current = null;
}
}, [open]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Reset saveStatus when modal closes to avoid stale “Saved!” on reopen.

If the modal closes before the 1.5s timer completes, the timer is cleared but status can remain "saved".

💡 Suggested fix
   useEffect(() => {
     if (!open && savedTimerRef.current !== null) {
       clearTimeout(savedTimerRef.current);
       savedTimerRef.current = null;
     }
+    if (!open) {
+      setSaveStatus("idle");
+    }
   }, [open]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/components/widget-editor/use-auto-preview.ts` around lines 181 - 186,
When the modal closes in the useEffect watching open, also reset the save status
to avoid a stale "Saved!" message: after clearing savedTimerRef (in the
useEffect that checks if (!open && savedTimerRef.current !== null)), call
setSaveStatus('idle') (or the hook's neutral state value) so saveStatus is
reset; reference the useAutoPreview hook's savedTimerRef, saveStatus,
setSaveStatus and the open variable when making this change.

alfredorubin96 and others added 2 commits May 1, 2026 17:18
Extract save logic, auto-preview, and Advanced tab sections from the
1,405-line monolith into 8 focused sub-components with 52 unit tests.
Modal reduced to 857 lines. Fixes buildClickAction missing layout arg.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@alfredo1996
alfredo1996 force-pushed the refactor/issue-573-extract-save-hook branch from 3b23be9 to efb66ea Compare May 1, 2026 15:18
…e hooks

Cover the two untested hooks extracted in #573 to meet SonarCloud's
80% new-code coverage gate. Tests verify: auto-preview on open with
debounce, query-change debounce, CMD/Ctrl+Shift+Enter run-and-save
shortcut, saveStatus lifecycle, widget payload construction for all
chart types (bar, parameter-select, form, markdown, iframe), click
action/styling/cache/transforms inclusion/exclusion, and query
history recording.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sonarqubecloud

sonarqubecloud Bot commented May 1, 2026

Copy link
Copy Markdown

@alfredo1996
alfredo1996 merged commit 3a883c8 into release/2.0 May 1, 2026
11 of 13 checks passed
@alfredo1996
alfredo1996 deleted the refactor/issue-573-extract-save-hook branch May 16, 2026 17:47
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.

2 participants