You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "gabotorresruiz (via GitHub)" <gi...@apache.org> on 2026/03/21 04:19:27 UTC
[PR] Fix the jpeg export of ag-grid tables [superset]
gabotorresruiz opened a new pull request, #38781:
URL: https://github.com/apache/superset/pull/38781
<!---
Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
Example:
fix(dashboard): load charts correctly
-->
### SUMMARY
<!--- Describe the change below, including rationale and design decisions -->
This PR fixes an existing issue when downloading an `ag-grid` table as an image (jpeg). Now everytime we want to export as an image an `ag-grid` table, this should should work as expected.
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
<!--- Skip this if not applicable -->
**Before:** (jpeg image generated on export)
<img width="584" height="399" alt="image" src="https://github.com/user-attachments/assets/6059a6d6-33cc-41bd-a87b-674ae6f2ecdd" />
**After:** (jpeg image generated on export)

### TESTING INSTRUCTIONS
<!--- Required! What steps can be taken to manually verify the changes? -->
1. Open an `ag-grid` Table chart (or a dashboard with an `ag-grid` table).
2. Click `Export screenshot (jpeg)` from chart editor. All loaded rows should appear with correct layout and colors.
3. Click `Download as image` from a dashboard. All loaded rows should appear with correct layout and colors.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "alexandrusoare (via GitHub)" <gi...@apache.org>.
alexandrusoare commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r3000665732
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:
##########
@@ -140,8 +146,32 @@ export const ThemedAgGridReact = forwardRef<
return baseTheme.withParams(finalParams);
}, [theme, isDarkMode, themeOverrides]);
+ // Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
+ const handleGridReady = useCallback(
+ (event: GridReadyEvent) => {
+ if (containerRef.current) {
+ (containerRef.current as any)._agGridFirstDataRendered = false;
Review Comment:
Is there a way to avoid this `any` type casting in this scenario?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4102218534
## **Sequence Diagram**
This PR introduces a dedicated ag grid export path that waits for the table to be fully rendered, captures the full print layout, and then restores the grid state. It also surfaces a loading warning when export is attempted before first data render.
```mermaid
sequenceDiagram
participant User
participant ThemedAgGrid
participant ExportUtility
participant AgGrid
participant ImageEngine
AgGrid->>ThemedAgGrid: Grid ready and first data rendered events
ThemedAgGrid->>ThemedAgGrid: Store grid api and rendered flag on container
User->>ExportUtility: Export screenshot jpeg
ExportUtility->>ExportUtility: Detect ag grid container and readiness
alt Grid is ready
ExportUtility->>AgGrid: Switch to print layout and stabilize table
ExportUtility->>ImageEngine: Capture table wrapper as jpeg
ExportUtility->>AgGrid: Restore normal layout
ExportUtility-->>User: Download image
else Grid still loading
ExportUtility-->>User: Show loading warning
end
```
---
*Generated by [CodeAnt AI](https://codeant.ai)*
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r3002300414
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:
##########
@@ -140,8 +146,32 @@ export const ThemedAgGridReact = forwardRef<
return baseTheme.withParams(finalParams);
}, [theme, isDarkMode, themeOverrides]);
+ // Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
+ const handleGridReady = useCallback(
+ (event: GridReadyEvent) => {
+ if (containerRef.current) {
+ (containerRef.current as any)._agGridFirstDataRendered = false;
Review Comment:
Yeah, nice catch! I just push this fix. Thanks @alexandrusoare
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "msyavuz (via GitHub)" <gi...@apache.org>.
msyavuz commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2974654038
##########
superset-frontend/src/utils/downloadAsImage.test.ts:
##########
@@ -0,0 +1,584 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import domToImage from 'dom-to-image-more';
+import { addWarningToast } from 'src/components/MessageToasts/actions';
+import downloadAsImageOptimized, {
+ waitForStableScrollHeight,
+} from './downloadAsImage';
+
+jest.mock('dom-to-image-more', () => ({
+ __esModule: true,
+ default: { toJpeg: jest.fn() },
+}));
+
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addWarningToast: jest.fn(),
+}));
+
+jest.mock('@apache-superset/core/translation', () => ({
+ t: (str: string) => str,
+}));
+
+const mockToJpeg = domToImage.toJpeg as jest.Mock;
+const mockAddWarningToast = addWarningToast as jest.Mock;
+
+// document.fonts.ready is not implemented in jsdom; provide a resolved promise
+Object.defineProperty(document, 'fonts', {
+ value: { ready: Promise.resolve() },
+ configurable: true,
+});
+
+// Build a synthetic React event that resolves `currentTarget.closest()` to a given element
+function syntheticEventFor(el: Element) {
+ return { currentTarget: { closest: () => el } } as any;
+}
+
+// Build and attach an ag-grid DOM structure; returns cleanup function
+function buildAgGridElement() {
+ const container = document.createElement('div');
+ const agContainer = document.createElement('div');
+ agContainer.setAttribute('data-themed-ag-grid', 'true');
+ const agRootWrapper = document.createElement('div');
+ agRootWrapper.className = 'ag-root-wrapper';
+ agContainer.appendChild(agRootWrapper);
+ container.appendChild(agContainer);
+ document.body.appendChild(container);
+ return {
+ container,
+ agContainer,
+ agRootWrapper,
+ cleanup: () => document.body.removeChild(container),
+ };
+}
+
+// Attach a mock GridApi and set the first-data-rendered flag on the container
+function attachMockApi(
+ agContainer: HTMLElement,
+ { firstDataRendered = true } = {},
+) {
+ const api = { setGridOption: jest.fn() };
+ (agContainer as any)._agGridApi = api;
+ (agContainer as any)._agGridFirstDataRendered = firstDataRendered;
+ return api;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockToJpeg.mockResolvedValue('data:image/jpeg;base64,test');
+});
+
+test('waitForStableScrollHeight resolves after 2 consecutive stable scrollHeight readings', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ await jest.runAllTimersAsync();
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight respects a custom minStablePolls', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ // With minStablePolls=5 the promise must not resolve after just 2 polls.
+ const promise = waitForStableScrollHeight(el, 5000, 5);
+ jest.advanceTimersByTime(300);
+ let resolved = false;
+ promise.then(() => { resolved = true; });
+ // Flush microtasks so the .then() above has a chance to run if resolved
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // Now run the remaining polls (2 more stable polls → total 5) and confirm resolution.
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resets stable count when height changes mid-poll', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 100;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => height,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ // Poll 1: height is 100, stableCount becomes 1
+ jest.advanceTimersByTime(100);
+ // Height changes — stable counter must reset
+ height = 200;
+ // Run until new height stabilises (2 consecutive 100 ms polls)
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves after maxMs even if height never stabilises', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 0;
+ Object.defineProperty(el, 'scrollHeight', {
+ // Always increments so stableFrames never reaches 4
+ get: () => {
+ height += 1;
+ return height;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el, 200);
+ jest.advanceTimersByTime(400); // past the 200 ms deadline
+ await promise;
+
+ jest.useRealTimers();
+});
Review Comment:
These tests are missing excepts right? It goes for all the tests in this file. Good coverage though!
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:
##########
@@ -140,8 +146,31 @@ export const ThemedAgGridReact = forwardRef<
return baseTheme.withParams(finalParams);
}, [theme, isDarkMode, themeOverrides]);
+ // Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
+ const handleGridReady = useCallback(
+ (event: GridReadyEvent) => {
+ if (containerRef.current) {
+ (containerRef.current as any)._agGridApi = event.api;
Review Comment:
Might be relevant @gabotorresruiz
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4102216939
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2976532723
##########
superset-frontend/src/utils/downloadAsImage.tsx:
##########
@@ -280,6 +334,126 @@ export default function downloadAsImageOptimized(
return;
}
+ const filter = (node: Element) =>
+ typeof node.className === 'string'
+ ? !node.className.includes('mapboxgl-control-container') &&
+ !node.className.includes('header-controls')
+ : true;
+
+ // Only apply ag-grid path for single-chart captures.
+ const agContainers = elementToPrint.querySelectorAll('[data-themed-ag-grid]');
+ const agContainer =
+ agContainers.length === 1 ? (agContainers[0] as HTMLElement) : null;
+ const agRootWrapper = agContainer
+ ? (agContainer.querySelector('.ag-root-wrapper') as HTMLElement | null)
+ : null;
+
+ if (agContainer && agRootWrapper) {
+ const api = (agContainer as any)._agGridApi as
+ | { setGridOption: (key: string, value: unknown) => void }
+ | undefined;
+ const isFirstDataRendered =
+ (agContainer as any)._agGridFirstDataRendered === true;
+
+ if (!isFirstDataRendered) {
+ addWarningToast(
+ t('The chart is still loading. Please wait a moment and try again.'),
+ );
+ return;
+ }
+
+ // Capture resolved pixel widths before print layout can re-trigger sizeColumnsToFit.
+ // sizeColumnsToFit() sets flex (not pixel widths), so after print layout expands the
+ // container it recalculates column widths wider. We restore with flex: null to force
+ // pixel widths when calling applyColumnState after the layout switch.
+ const savedColumnState = (api as any)?.getColumnState?.() as
+ | ColumnState[]
+ | undefined;
+ const visibleColumnState =
+ savedColumnState?.filter(col => !col.hide) ?? [];
+ const originalWidth =
+ visibleColumnState.reduce((sum, col) => sum + (col.width ?? 0), 0) ||
+ agRootWrapper.offsetWidth;
+
+ // Chrome SVG foreignObject bug: % min-height resolves against canvas height,
+ // causing cells to expand to full image height and overlap adjacent rows.
+ const cellFixups: CellFixup[] = [];
+
+ try {
+ await document.fonts.ready;
+
+ if (api) {
+ api.setGridOption('domLayout', 'print');
+
+ // Wait for ResizeObserver + any triggered sizeColumnsToFit() to settle,
+ // then restore column widths before measurement.
+ await new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ );
+
+ if (visibleColumnState.length > 0) {
+ (api as any).applyColumnState?.({
+ state: visibleColumnState.map(col => ({
+ colId: col.colId,
+ width: col.width,
+ flex: null,
+ })),
+ applyOrder: false,
+ });
+ }
+
+ // Rows never scrolled into view have stale cached heights; remeasure all.
+ (api as any).resetRowHeights?.();
+
+ // 5 polls × POLL_INTERVAL_MS = 500 ms; autoHeight rows batch-measure slowly.
+ await waitForStableScrollHeight(agRootWrapper, 5000, 5);
+ }
+
+ agRootWrapper.querySelectorAll('.ag-cell').forEach(cell => {
+ const el = cell as HTMLElement;
+ const rowHeight = (el.parentElement as HTMLElement)?.offsetHeight ?? 0;
+ // scrollHeight catches any cells where resetRowHeights lagged behind.
+ const minH = Math.max(rowHeight, el.scrollHeight);
+ cellFixups.push({
+ el,
+ minHeight: el.style.minHeight,
+ overflow: el.style.overflow,
+ });
+ el.style.minHeight = minH > 0 ? `${minH}px` : '0px';
+ el.style.overflow = 'hidden';
+ });
+
+ const imageHeight = agRootWrapper.scrollHeight;
+
+ const dataUrl = await domToImage.toJpeg(agRootWrapper, {
+ bgcolor: theme?.colorBgContainer,
+ filter,
+ quality: IMAGE_DOWNLOAD_QUALITY,
+ height: imageHeight,
+ width: originalWidth,
+ cacheBust: true,
+ });
+
+ const link = document.createElement('a');
+ link.download = `${generateFileStem(description)}.jpg`;
+ link.href = dataUrl;
+ link.click();
+ } catch (error) {
+ console.error('Creating image failed', error);
+ addWarningToast(
+ t('Image download failed, please refresh and try again.'),
+ );
+ } finally {
+ cellFixups.forEach(({ el, minHeight, overflow }) => {
+ el.style.minHeight = minHeight;
+ el.style.overflow = overflow;
+ });
+ api?.setGridOption('domLayout', 'normal');
Review Comment:
**Suggestion:** Column state is modified for capture by stripping `flex`, but it is never restored afterward, so the live grid can remain in a mutated non-original state after download. Restore the previously captured column state in `finally` so the grid returns to its pre-export behavior. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Ag-grid columns may remain altered after screenshot export.
- ⚠️ Saved table columnState can capture export-time mutations.
```
</details>
```suggestion
if (api) {
api.setGridOption('domLayout', 'normal');
(api as any).applyColumnState?.({
state: savedColumnState ?? [],
applyOrder: false,
});
}
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Trigger ag-grid chart screenshot from Explore menu (`Export screenshot (jpeg)`), which
calls `downloadAsImage('.panel-body .chart-container', ..., true, theme)` in
`superset-frontend/src/explore/components/useExploreAdditionalActionsMenu/index.tsx:736-745`.
2. Ag-grid branch runs in `superset-frontend/src/utils/downloadAsImage.tsx:351+`; it
captures state then forces pixel widths with `applyColumnState(... flex: null ...)` at
`downloadAsImage.tsx:395-403`.
3. In `finally`, code only resets layout (`api?.setGridOption('domLayout', 'normal')`) at
`downloadAsImage.tsx:451`; original `savedColumnState` is never restored.
4. The grid listens to state updates (`onStateUpdated={handleGridStateChange}` at
`plugins/plugin-chart-ag-grid-table/src/AgGridTable/index.tsx:497`), and persisted state
is read from `api.getColumnState()` (`AgGridTable/index.tsx:315,329,344`), so export-time
mutations can leak into live/persisted column behavior.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/utils/downloadAsImage.tsx
**Line:** 451:451
**Comment:**
*Logic Error: Column state is modified for capture by stripping `flex`, but it is never restored afterward, so the live grid can remain in a mutated non-original state after download. Restore the previously captured column state in `finally` so the grid returns to its pre-export behavior.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=1ad41ab8b8e20a4e52dec078e84e6c7265d3a3db5e0316825c8da3aacc3ecf1f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=1ad41ab8b8e20a4e52dec078e84e6c7265d3a3db5e0316825c8da3aacc3ecf1f&reaction=dislike'>👎</a>
##########
superset-frontend/src/utils/downloadAsImage.tsx:
##########
@@ -280,6 +334,126 @@ export default function downloadAsImageOptimized(
return;
}
+ const filter = (node: Element) =>
+ typeof node.className === 'string'
+ ? !node.className.includes('mapboxgl-control-container') &&
+ !node.className.includes('header-controls')
+ : true;
+
+ // Only apply ag-grid path for single-chart captures.
+ const agContainers = elementToPrint.querySelectorAll('[data-themed-ag-grid]');
Review Comment:
**Suggestion:** The ag-grid-specific export path is selected whenever exactly one `[data-themed-ag-grid]` exists inside the target element, which also matches dashboard captures containing a single ag-grid chart. In that case, the code exports only `.ag-root-wrapper` instead of the whole dashboard, producing an incomplete screenshot. Restrict the ag-grid path so it is skipped for dashboard-level captures. [logic error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Dashboard image export captures only ag-grid area.
- ⚠️ Dashboard header "Download as Image" gives incomplete screenshot.
```
</details>
```suggestion
const isDashboardCapture =
(elementToPrint as HTMLElement).classList.contains('dashboard');
const agContainers = isDashboardCapture
? []
: elementToPrint.querySelectorAll('[data-themed-ag-grid]');
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In dashboard header download flow, `useDownloadMenuItems` calls
`downloadAsImage('.dashboard', ..., true)` from
`superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx:68,88`.
2. Ensure dashboard contains exactly one ag-grid chart; ag-grid wrapper always has
`data-themed-ag-grid="true"` from
`superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:63`.
3. In `superset-frontend/src/utils/downloadAsImage.tsx:344-346`, code sees exactly one
`[data-themed-ag-grid]` and selects ag-grid path.
4. Function then exports only `agRootWrapper` via `domToImage.toJpeg(agRootWrapper, ...)`
at `downloadAsImage.tsx:428`, so the downloaded image excludes other dashboard content.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/utils/downloadAsImage.tsx
**Line:** 344:344
**Comment:**
*Logic Error: The ag-grid-specific export path is selected whenever exactly one `[data-themed-ag-grid]` exists inside the target element, which also matches dashboard captures containing a single ag-grid chart. In that case, the code exports only `.ag-root-wrapper` instead of the whole dashboard, producing an incomplete screenshot. Restrict the ag-grid path so it is skipped for dashboard-level captures.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=e59a4ff7a1e5dd2c89337fc0100dd08f279d542c042b6b2a6fe4f16f2bcc7281&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=e59a4ff7a1e5dd2c89337fc0100dd08f279d542c042b6b2a6fe4f16f2bcc7281&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4113214191
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2976518461
##########
superset-frontend/src/utils/downloadAsImage.test.ts:
##########
@@ -0,0 +1,584 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import domToImage from 'dom-to-image-more';
+import { addWarningToast } from 'src/components/MessageToasts/actions';
+import downloadAsImageOptimized, {
+ waitForStableScrollHeight,
+} from './downloadAsImage';
+
+jest.mock('dom-to-image-more', () => ({
+ __esModule: true,
+ default: { toJpeg: jest.fn() },
+}));
+
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addWarningToast: jest.fn(),
+}));
+
+jest.mock('@apache-superset/core/translation', () => ({
+ t: (str: string) => str,
+}));
+
+const mockToJpeg = domToImage.toJpeg as jest.Mock;
+const mockAddWarningToast = addWarningToast as jest.Mock;
+
+// document.fonts.ready is not implemented in jsdom; provide a resolved promise
+Object.defineProperty(document, 'fonts', {
+ value: { ready: Promise.resolve() },
+ configurable: true,
+});
+
+// Build a synthetic React event that resolves `currentTarget.closest()` to a given element
+function syntheticEventFor(el: Element) {
+ return { currentTarget: { closest: () => el } } as any;
+}
+
+// Build and attach an ag-grid DOM structure; returns cleanup function
+function buildAgGridElement() {
+ const container = document.createElement('div');
+ const agContainer = document.createElement('div');
+ agContainer.setAttribute('data-themed-ag-grid', 'true');
+ const agRootWrapper = document.createElement('div');
+ agRootWrapper.className = 'ag-root-wrapper';
+ agContainer.appendChild(agRootWrapper);
+ container.appendChild(agContainer);
+ document.body.appendChild(container);
+ return {
+ container,
+ agContainer,
+ agRootWrapper,
+ cleanup: () => document.body.removeChild(container),
+ };
+}
+
+// Attach a mock GridApi and set the first-data-rendered flag on the container
+function attachMockApi(
+ agContainer: HTMLElement,
+ { firstDataRendered = true } = {},
+) {
+ const api = { setGridOption: jest.fn() };
+ (agContainer as any)._agGridApi = api;
+ (agContainer as any)._agGridFirstDataRendered = firstDataRendered;
+ return api;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockToJpeg.mockResolvedValue('data:image/jpeg;base64,test');
+});
+
+test('waitForStableScrollHeight resolves after 2 consecutive stable scrollHeight readings', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ await jest.runAllTimersAsync();
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight respects a custom minStablePolls', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ // With minStablePolls=5 the promise must not resolve after just 2 polls.
+ const promise = waitForStableScrollHeight(el, 5000, 5);
+ jest.advanceTimersByTime(300);
+ let resolved = false;
+ promise.then(() => { resolved = true; });
+ // Flush microtasks so the .then() above has a chance to run if resolved
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // Now run the remaining polls (2 more stable polls → total 5) and confirm resolution.
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resets stable count when height changes mid-poll', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 100;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => height,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ // Poll 1: height is 100, stableCount becomes 1
+ jest.advanceTimersByTime(100);
+ // Height changes — stable counter must reset
+ height = 200;
+ // Run until new height stabilises (2 consecutive 100 ms polls)
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves after maxMs even if height never stabilises', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 0;
+ Object.defineProperty(el, 'scrollHeight', {
+ // Always increments so stableFrames never reaches 4
+ get: () => {
+ height += 1;
+ return height;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el, 200);
+ jest.advanceTimersByTime(400); // past the 200 ms deadline
+ await promise;
+
+ jest.useRealTimers();
+});
Review Comment:
Done! Thanks
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4112841516
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2969051119
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:
##########
@@ -140,8 +146,31 @@ export const ThemedAgGridReact = forwardRef<
return baseTheme.withParams(finalParams);
}, [theme, isDarkMode, themeOverrides]);
+ // Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
+ const handleGridReady = useCallback(
+ (event: GridReadyEvent) => {
+ if (containerRef.current) {
+ (containerRef.current as any)._agGridApi = event.api;
Review Comment:
**Suggestion:** The readiness flag is never reset when a new grid instance becomes ready, so `_agGridFirstDataRendered` can stay `true` from a previous render and let image export run before the new rows are actually painted. Reset the flag in the grid-ready handler before storing the API. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Ag-grid screenshot may capture pre-rendered table state.
- ⚠️ Loading guard in `downloadAsImage` can be bypassed.
- ⚠️ Explore and dashboard screenshot UX becomes inconsistent.
```
</details>
```suggestion
(containerRef.current as any)._agGridFirstDataRendered = false;
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Open an Explore ag-grid table and let it render once; `handleFirstDataRendered` sets
`(containerRef.current as any)._agGridFirstDataRendered = true` at
`superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:162-166`.
2. Trigger a grid re-initialization path where `onGridReady` fires again (wired from
`AgGridDataTable` at
`plugins/plugin-chart-ag-grid-table/src/AgGridTable/index.tsx:224-227` into
`ThemedAgGridReact` `handleGridReady` at `index.tsx:150-156`); current code updates
`_agGridApi` but never clears `_agGridFirstDataRendered`.
3. Immediately click **Export screenshot (jpeg)** from Explore menu
(`src/explore/components/useExploreAdditionalActionsMenu/index.tsx:735-745` or `839-849`)
or dashboard menu (`src/dashboard/components/SliceHeaderControls/index.tsx:249-44`), both
calling `downloadAsImage(...)`.
4. In `src/utils/downloadAsImage.tsx:356-364`, readiness check only verifies
`_agGridFirstDataRendered === true`; stale `true` lets capture proceed before current rows
are painted, producing premature/incomplete ag-grid screenshot.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx
**Line:** 153:153
**Comment:**
*Logic Error: The readiness flag is never reset when a new grid instance becomes ready, so `_agGridFirstDataRendered` can stay `true` from a previous render and let image export run before the new rows are actually painted. Reset the flag in the grid-ready handler before storing the API.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=14e29854605cf98484b4f624421799744f911cb1107ada611949b2e643a87b58&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=14e29854605cf98484b4f624421799744f911cb1107ada611949b2e643a87b58&reaction=dislike'>👎</a>
##########
superset-frontend/src/utils/downloadAsImage.tsx:
##########
@@ -280,6 +334,126 @@ export default function downloadAsImageOptimized(
return;
}
+ const filter = (node: Element) =>
+ typeof node.className === 'string'
+ ? !node.className.includes('mapboxgl-control-container') &&
+ !node.className.includes('header-controls')
+ : true;
+
+ // ag-grid: switch to print layout (all rows in DOM), capture the live element
+ const agContainer = elementToPrint.querySelector(
+ '[data-themed-ag-grid]',
+ ) as HTMLElement | null;
+ const agRootWrapper = elementToPrint.querySelector(
+ '.ag-root-wrapper',
+ ) as HTMLElement | null;
+
+ if (agContainer && agRootWrapper) {
Review Comment:
**Suggestion:** The ag-grid shortcut currently runs for any container that contains an ag-grid instance, including full-dashboard exports. In dashboard downloads this makes the function capture only `.ag-root-wrapper` (the first table) and return early, so the exported image is no longer the whole dashboard. Restrict the ag-grid-only path to non-dashboard containers so full dashboard screenshots still use the clone-based capture. [logic error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Dashboard image export captures only first ag-grid chart.
- ⚠️ Other dashboard charts omitted from downloaded screenshot.
- ⚠️ Regression in client-side dashboard screenshot path.
```
</details>
```suggestion
if (
agContainer &&
agRootWrapper &&
!elementToPrint.classList.contains('dashboard')
) {
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Open a dashboard containing at least one ag-grid chart and use dashboard header action
"Download as Image" (menu wiring in
`superset-frontend/src/dashboard/components/menu/DownloadMenuItems/index.tsx:68-89`,
selector is `.dashboard`).
2. This calls `downloadAsImage(SCREENSHOT_NODE_SELECTOR, dashboardTitle, true)` at
`DownloadMenuItems/index.tsx:88`, so `downloadAsImageOptimized` resolves `elementToPrint`
to the full dashboard root.
3. In `superset-frontend/src/utils/downloadAsImage.tsx:344-351`,
`elementToPrint.querySelector('[data-themed-ag-grid]')` and
`.querySelector('.ag-root-wrapper')` succeed because ag-grid wrappers are present
(`data-themed-ag-grid` is rendered by
`packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:52`).
4. Condition `if (agContainer && agRootWrapper)` at `downloadAsImage.tsx:351` enters
ag-grid-only branch, captures `domToImage.toJpeg(agRootWrapper, ...)` at `:428`, then
returns at `:453`; clone-based whole-dashboard capture path at `:457+` is skipped, so
output is only first ag-grid table.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/utils/downloadAsImage.tsx
**Line:** 351:351
**Comment:**
*Logic Error: The ag-grid shortcut currently runs for any container that contains an ag-grid instance, including full-dashboard exports. In dashboard downloads this makes the function capture only `.ag-root-wrapper` (the first table) and return early, so the exported image is no longer the whole dashboard. Restrict the ag-grid-only path to non-dashboard containers so full dashboard screenshots still use the clone-based capture.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=5eacd241e9342a9713228280eae7fde7cf18aac10b05e55bdc16114290745625&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=5eacd241e9342a9713228280eae7fde7cf18aac10b05e55bdc16114290745625&reaction=dislike'>👎</a>
##########
superset-frontend/src/utils/downloadAsImage.test.ts:
##########
@@ -0,0 +1,584 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import domToImage from 'dom-to-image-more';
+import { addWarningToast } from 'src/components/MessageToasts/actions';
+import downloadAsImageOptimized, {
+ waitForStableScrollHeight,
+} from './downloadAsImage';
+
+jest.mock('dom-to-image-more', () => ({
+ __esModule: true,
+ default: { toJpeg: jest.fn() },
+}));
+
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addWarningToast: jest.fn(),
+}));
+
+jest.mock('@apache-superset/core/translation', () => ({
+ t: (str: string) => str,
+}));
+
+const mockToJpeg = domToImage.toJpeg as jest.Mock;
+const mockAddWarningToast = addWarningToast as jest.Mock;
+
+// document.fonts.ready is not implemented in jsdom; provide a resolved promise
+Object.defineProperty(document, 'fonts', {
+ value: { ready: Promise.resolve() },
+ configurable: true,
+});
+
+// Build a synthetic React event that resolves `currentTarget.closest()` to a given element
+function syntheticEventFor(el: Element) {
+ return { currentTarget: { closest: () => el } } as any;
+}
+
+// Build and attach an ag-grid DOM structure; returns cleanup function
+function buildAgGridElement() {
+ const container = document.createElement('div');
+ const agContainer = document.createElement('div');
+ agContainer.setAttribute('data-themed-ag-grid', 'true');
+ const agRootWrapper = document.createElement('div');
+ agRootWrapper.className = 'ag-root-wrapper';
+ agContainer.appendChild(agRootWrapper);
+ container.appendChild(agContainer);
+ document.body.appendChild(container);
+ return {
+ container,
+ agContainer,
+ agRootWrapper,
+ cleanup: () => document.body.removeChild(container),
+ };
+}
+
+// Attach a mock GridApi and set the first-data-rendered flag on the container
+function attachMockApi(
+ agContainer: HTMLElement,
+ { firstDataRendered = true } = {},
+) {
+ const api = { setGridOption: jest.fn() };
+ (agContainer as any)._agGridApi = api;
+ (agContainer as any)._agGridFirstDataRendered = firstDataRendered;
+ return api;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockToJpeg.mockResolvedValue('data:image/jpeg;base64,test');
+});
+
Review Comment:
**Suggestion:** Timer mode cleanup is only done manually inside individual tests, so any early assertion failure can leave Jest in fake-timer mode and break subsequent tests. Add an `afterEach` guard that always restores real timers. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ⚠️ Failed fake-timer test can cascade unrelated failures.
- ⚠️ CI debugging slows from misleading downstream timer errors.
```
</details>
```suggestion
afterEach(() => {
jest.useRealTimers();
});
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run this suite (`src/utils/downloadAsImage.test.ts`) through Jest
(`jest.config.js:22-24`), where many tests switch to fake timers (for example `:214`,
`:235`, `:273`, `:533`).
2. Each fake-timer test restores timers manually at the end (for example `:231`, `:251`,
`:304`) instead of guaranteed teardown.
3. If a test aborts before its final `jest.useRealTimers()` (e.g., assertion failure at
`:223/:228` or rejected `exportPromise` before cleanup), timer mode remains fake because
global setup has no `afterEach` restoring timers (`spec/helpers/setup.ts` contains no
`afterEach`).
4. Subsequent tests in the same file then run under leaked fake timers; async code using
`setTimeout` inside `waitForStableScrollHeight` (`src/utils/downloadAsImage.tsx:313,316`)
can hang or require manual clock advancement, causing cascading failures/noisy
diagnostics.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/utils/downloadAsImage.test.ts
**Line:** 85:85
**Comment:**
*Possible Bug: Timer mode cleanup is only done manually inside individual tests, so any early assertion failure can leave Jest in fake-timer mode and break subsequent tests. Add an `afterEach` guard that always restores real timers.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=ea57bdf2e55eec7ff906abea471ae7ca4d49c3a939c143721fe2f63bdd741d1e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38781&comment_hash=ea57bdf2e55eec7ff906abea471ae7ca4d49c3a939c143721fe2f63bdd741d1e&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2976516728
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/index.tsx:
##########
@@ -140,8 +146,31 @@ export const ThemedAgGridReact = forwardRef<
return baseTheme.withParams(finalParams);
}, [theme, isDarkMode, themeOverrides]);
+ // Expose gridApi and first-data-rendered flag on the container for downloadAsImage.
+ const handleGridReady = useCallback(
+ (event: GridReadyEvent) => {
+ if (containerRef.current) {
+ (containerRef.current as any)._agGridApi = event.api;
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4114988211
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2969056422
##########
superset-frontend/src/utils/downloadAsImage.test.ts:
##########
@@ -0,0 +1,584 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import domToImage from 'dom-to-image-more';
+import { addWarningToast } from 'src/components/MessageToasts/actions';
+import downloadAsImageOptimized, {
+ waitForStableScrollHeight,
+} from './downloadAsImage';
+
+jest.mock('dom-to-image-more', () => ({
+ __esModule: true,
+ default: { toJpeg: jest.fn() },
+}));
+
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addWarningToast: jest.fn(),
+}));
+
+jest.mock('@apache-superset/core/translation', () => ({
+ t: (str: string) => str,
+}));
+
+const mockToJpeg = domToImage.toJpeg as jest.Mock;
+const mockAddWarningToast = addWarningToast as jest.Mock;
+
+// document.fonts.ready is not implemented in jsdom; provide a resolved promise
+Object.defineProperty(document, 'fonts', {
+ value: { ready: Promise.resolve() },
+ configurable: true,
+});
+
+// Build a synthetic React event that resolves `currentTarget.closest()` to a given element
+function syntheticEventFor(el: Element) {
+ return { currentTarget: { closest: () => el } } as any;
+}
+
+// Build and attach an ag-grid DOM structure; returns cleanup function
+function buildAgGridElement() {
+ const container = document.createElement('div');
+ const agContainer = document.createElement('div');
+ agContainer.setAttribute('data-themed-ag-grid', 'true');
+ const agRootWrapper = document.createElement('div');
+ agRootWrapper.className = 'ag-root-wrapper';
+ agContainer.appendChild(agRootWrapper);
+ container.appendChild(agContainer);
+ document.body.appendChild(container);
+ return {
+ container,
+ agContainer,
+ agRootWrapper,
+ cleanup: () => document.body.removeChild(container),
+ };
+}
+
+// Attach a mock GridApi and set the first-data-rendered flag on the container
+function attachMockApi(
+ agContainer: HTMLElement,
+ { firstDataRendered = true } = {},
+) {
+ const api = { setGridOption: jest.fn() };
+ (agContainer as any)._agGridApi = api;
+ (agContainer as any)._agGridFirstDataRendered = firstDataRendered;
+ return api;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockToJpeg.mockResolvedValue('data:image/jpeg;base64,test');
+});
+
+test('waitForStableScrollHeight resolves after 2 consecutive stable scrollHeight readings', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ await jest.runAllTimersAsync();
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight respects a custom minStablePolls', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ // With minStablePolls=5 the promise must not resolve after just 2 polls.
+ const promise = waitForStableScrollHeight(el, 5000, 5);
+ jest.advanceTimersByTime(300);
+ let resolved = false;
+ promise.then(() => { resolved = true; });
+ // Flush microtasks so the .then() above has a chance to run if resolved
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // Now run the remaining polls (2 more stable polls → total 5) and confirm resolution.
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resets stable count when height changes mid-poll', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 100;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => height,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ // Poll 1: height is 100, stableCount becomes 1
+ jest.advanceTimersByTime(100);
+ // Height changes — stable counter must reset
+ height = 200;
+ // Run until new height stabilises (2 consecutive 100 ms polls)
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves after maxMs even if height never stabilises', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 0;
+ Object.defineProperty(el, 'scrollHeight', {
+ // Always increments so stableFrames never reaches 4
+ get: () => {
+ height += 1;
+ return height;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el, 200);
+ jest.advanceTimersByTime(400); // past the 200 ms deadline
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves if scrollHeight throws (element removed from DOM)', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let shouldThrow = false;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => {
+ if (shouldThrow) throw new Error('element detached');
+ return 100;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ jest.advanceTimersByTime(100); // poll 1: stable, stableCount = 1
+ shouldThrow = true; // simulate DOM removal
+ jest.advanceTimersByTime(100); // poll 2: throws → resolves immediately
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('shows warning toast when element is not found', async () => {
+ const handler = downloadAsImageOptimized('div', 'test');
+ // closest() returning null simulates a selector that matches nothing
+ await handler({ currentTarget: { closest: () => null } } as any);
+
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'Image download failed, please refresh and try again.',
+ );
+ expect(mockToJpeg).not.toHaveBeenCalled();
+});
+
+test('shows "still loading" toast when grid has not yet rendered its first rows', async () => {
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ attachMockApi(agContainer, { firstDataRendered: false });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ await handler(syntheticEventFor(container));
+
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'The chart is still loading. Please wait a moment and try again.',
+ );
+ expect(mockToJpeg).not.toHaveBeenCalled();
+
+ cleanup();
+});
+
+test('switches to print layout, captures JPEG, and restores normal layout', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'print');
+ expect(mockToJpeg).toHaveBeenCalledWith(
+ expect.any(HTMLElement),
+ expect.objectContaining({ quality: 0.95 }),
+ );
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'normal');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('restores normal layout in finally even when image capture throws', async () => {
+ jest.useFakeTimers();
+ mockToJpeg.mockRejectedValue(new Error('capture failed'));
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'normal');
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'Image download failed, please refresh and try again.',
+ );
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('still captures image when _agGridApi is absent (graceful degradation)', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ // No API — only the first-data-rendered flag
+ (agContainer as any)._agGridFirstDataRendered = true;
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(mockToJpeg).toHaveBeenCalled();
+ expect(mockAddWarningToast).not.toHaveBeenCalled();
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('resolves ag-cell min-height to row pixel height when content fits within it', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, agRootWrapper, cleanup } =
+ buildAgGridElement();
+ attachMockApi(agContainer);
+
+ // Build a row with a cell inside the grid
+ const row = document.createElement('div');
+ row.className = 'ag-row';
+ Object.defineProperty(row, 'offsetHeight', { get: () => 32, configurable: true });
+ const cell = document.createElement('div');
+ cell.className = 'ag-cell';
+ row.appendChild(cell);
+ agRootWrapper.appendChild(row);
+
+ let capturedMinHeight = '';
+ mockToJpeg.mockImplementation(() => {
+ capturedMinHeight = cell.style.minHeight;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ // Cell min-height was resolved to the row's pixel height during capture
+ expect(capturedMinHeight).toBe('32px');
+ // Cell min-height was restored after capture
+ expect(cell.style.minHeight).toBe('');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('uses cell scrollHeight when it exceeds row offsetHeight (stale row heights for off-screen rows)', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, agRootWrapper, cleanup } =
+ buildAgGridElement();
+ attachMockApi(agContainer);
+
+ const row = document.createElement('div');
+ row.className = 'ag-row';
+ Object.defineProperty(row, 'offsetHeight', { get: () => 25, configurable: true }); // stale default
+ const cell = document.createElement('div');
+ cell.className = 'ag-cell';
+ Object.defineProperty(cell, 'scrollHeight', { get: () => 120, configurable: true }); // actual content
+ row.appendChild(cell);
+ agRootWrapper.appendChild(row);
+
+ let capturedMinHeight = '';
+ mockToJpeg.mockImplementation(() => {
+ capturedMinHeight = cell.style.minHeight;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ // Uses the larger content height, not the stale row height
+ expect(capturedMinHeight).toBe('120px');
+ expect(cell.style.minHeight).toBe('');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('derives image width from getColumnState by summing visible column pixel widths', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ // 3 visible columns (200 + 350 + 150 = 700 px) plus one hidden column excluded from sum
+ (api as any).getColumnState = jest.fn(() => [
+ { colId: 'col1', width: 200, hide: false },
+ { colId: 'col2', width: 350, hide: false },
+ { colId: 'col3', width: 150, hide: false },
+ { colId: 'col4', width: 999, hide: true },
+ ]);
+ (api as any).applyColumnState = jest.fn();
+
+ let capturedWidth: number | undefined;
+ mockToJpeg.mockImplementation((_el: HTMLElement, opts: { width?: number }) => {
+ capturedWidth = opts.width;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test coverage for non-ag-grid path</b></div>
<div id="fix">
All tests use ag-grid elements, leaving the general chart download path untested, which could hide bugs in clone-based image generation.
</div>
</div>
<div id="suggestion">
<div id="issue"><b>Missing test assertion for image width</b></div>
<div id="fix">
The test mocks getColumnState but does not check if the calculated width is passed to toJpeg, potentially missing bugs in width derivation.
</div>
</div>
<small><i>Code Review Run #35b4d7</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #38781:
URL: https://github.com/apache/superset/pull/38781#discussion_r2969056422
##########
superset-frontend/src/utils/downloadAsImage.test.ts:
##########
@@ -0,0 +1,584 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import domToImage from 'dom-to-image-more';
+import { addWarningToast } from 'src/components/MessageToasts/actions';
+import downloadAsImageOptimized, {
+ waitForStableScrollHeight,
+} from './downloadAsImage';
+
+jest.mock('dom-to-image-more', () => ({
+ __esModule: true,
+ default: { toJpeg: jest.fn() },
+}));
+
+jest.mock('src/components/MessageToasts/actions', () => ({
+ addWarningToast: jest.fn(),
+}));
+
+jest.mock('@apache-superset/core/translation', () => ({
+ t: (str: string) => str,
+}));
+
+const mockToJpeg = domToImage.toJpeg as jest.Mock;
+const mockAddWarningToast = addWarningToast as jest.Mock;
+
+// document.fonts.ready is not implemented in jsdom; provide a resolved promise
+Object.defineProperty(document, 'fonts', {
+ value: { ready: Promise.resolve() },
+ configurable: true,
+});
+
+// Build a synthetic React event that resolves `currentTarget.closest()` to a given element
+function syntheticEventFor(el: Element) {
+ return { currentTarget: { closest: () => el } } as any;
+}
+
+// Build and attach an ag-grid DOM structure; returns cleanup function
+function buildAgGridElement() {
+ const container = document.createElement('div');
+ const agContainer = document.createElement('div');
+ agContainer.setAttribute('data-themed-ag-grid', 'true');
+ const agRootWrapper = document.createElement('div');
+ agRootWrapper.className = 'ag-root-wrapper';
+ agContainer.appendChild(agRootWrapper);
+ container.appendChild(agContainer);
+ document.body.appendChild(container);
+ return {
+ container,
+ agContainer,
+ agRootWrapper,
+ cleanup: () => document.body.removeChild(container),
+ };
+}
+
+// Attach a mock GridApi and set the first-data-rendered flag on the container
+function attachMockApi(
+ agContainer: HTMLElement,
+ { firstDataRendered = true } = {},
+) {
+ const api = { setGridOption: jest.fn() };
+ (agContainer as any)._agGridApi = api;
+ (agContainer as any)._agGridFirstDataRendered = firstDataRendered;
+ return api;
+}
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockToJpeg.mockResolvedValue('data:image/jpeg;base64,test');
+});
+
+test('waitForStableScrollHeight resolves after 2 consecutive stable scrollHeight readings', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ await jest.runAllTimersAsync();
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight respects a custom minStablePolls', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => 100,
+ configurable: true,
+ });
+
+ // With minStablePolls=5 the promise must not resolve after just 2 polls.
+ const promise = waitForStableScrollHeight(el, 5000, 5);
+ jest.advanceTimersByTime(300);
+ let resolved = false;
+ promise.then(() => { resolved = true; });
+ // Flush microtasks so the .then() above has a chance to run if resolved
+ await Promise.resolve();
+ expect(resolved).toBe(false);
+
+ // Now run the remaining polls (2 more stable polls → total 5) and confirm resolution.
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resets stable count when height changes mid-poll', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 100;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => height,
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ // Poll 1: height is 100, stableCount becomes 1
+ jest.advanceTimersByTime(100);
+ // Height changes — stable counter must reset
+ height = 200;
+ // Run until new height stabilises (2 consecutive 100 ms polls)
+ jest.advanceTimersByTime(300);
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves after maxMs even if height never stabilises', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let height = 0;
+ Object.defineProperty(el, 'scrollHeight', {
+ // Always increments so stableFrames never reaches 4
+ get: () => {
+ height += 1;
+ return height;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el, 200);
+ jest.advanceTimersByTime(400); // past the 200 ms deadline
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('waitForStableScrollHeight resolves if scrollHeight throws (element removed from DOM)', async () => {
+ jest.useFakeTimers();
+ const el = document.createElement('div');
+ let shouldThrow = false;
+ Object.defineProperty(el, 'scrollHeight', {
+ get: () => {
+ if (shouldThrow) throw new Error('element detached');
+ return 100;
+ },
+ configurable: true,
+ });
+
+ const promise = waitForStableScrollHeight(el);
+ jest.advanceTimersByTime(100); // poll 1: stable, stableCount = 1
+ shouldThrow = true; // simulate DOM removal
+ jest.advanceTimersByTime(100); // poll 2: throws → resolves immediately
+ await promise;
+
+ jest.useRealTimers();
+});
+
+test('shows warning toast when element is not found', async () => {
+ const handler = downloadAsImageOptimized('div', 'test');
+ // closest() returning null simulates a selector that matches nothing
+ await handler({ currentTarget: { closest: () => null } } as any);
+
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'Image download failed, please refresh and try again.',
+ );
+ expect(mockToJpeg).not.toHaveBeenCalled();
+});
+
+test('shows "still loading" toast when grid has not yet rendered its first rows', async () => {
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ attachMockApi(agContainer, { firstDataRendered: false });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ await handler(syntheticEventFor(container));
+
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'The chart is still loading. Please wait a moment and try again.',
+ );
+ expect(mockToJpeg).not.toHaveBeenCalled();
+
+ cleanup();
+});
+
+test('switches to print layout, captures JPEG, and restores normal layout', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'print');
+ expect(mockToJpeg).toHaveBeenCalledWith(
+ expect.any(HTMLElement),
+ expect.objectContaining({ quality: 0.95 }),
+ );
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'normal');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('restores normal layout in finally even when image capture throws', async () => {
+ jest.useFakeTimers();
+ mockToJpeg.mockRejectedValue(new Error('capture failed'));
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(api.setGridOption).toHaveBeenCalledWith('domLayout', 'normal');
+ expect(mockAddWarningToast).toHaveBeenCalledWith(
+ 'Image download failed, please refresh and try again.',
+ );
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('still captures image when _agGridApi is absent (graceful degradation)', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ // No API — only the first-data-rendered flag
+ (agContainer as any)._agGridFirstDataRendered = true;
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ expect(mockToJpeg).toHaveBeenCalled();
+ expect(mockAddWarningToast).not.toHaveBeenCalled();
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('resolves ag-cell min-height to row pixel height when content fits within it', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, agRootWrapper, cleanup } =
+ buildAgGridElement();
+ attachMockApi(agContainer);
+
+ // Build a row with a cell inside the grid
+ const row = document.createElement('div');
+ row.className = 'ag-row';
+ Object.defineProperty(row, 'offsetHeight', { get: () => 32, configurable: true });
+ const cell = document.createElement('div');
+ cell.className = 'ag-cell';
+ row.appendChild(cell);
+ agRootWrapper.appendChild(row);
+
+ let capturedMinHeight = '';
+ mockToJpeg.mockImplementation(() => {
+ capturedMinHeight = cell.style.minHeight;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ // Cell min-height was resolved to the row's pixel height during capture
+ expect(capturedMinHeight).toBe('32px');
+ // Cell min-height was restored after capture
+ expect(cell.style.minHeight).toBe('');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('uses cell scrollHeight when it exceeds row offsetHeight (stale row heights for off-screen rows)', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, agRootWrapper, cleanup } =
+ buildAgGridElement();
+ attachMockApi(agContainer);
+
+ const row = document.createElement('div');
+ row.className = 'ag-row';
+ Object.defineProperty(row, 'offsetHeight', { get: () => 25, configurable: true }); // stale default
+ const cell = document.createElement('div');
+ cell.className = 'ag-cell';
+ Object.defineProperty(cell, 'scrollHeight', { get: () => 120, configurable: true }); // actual content
+ row.appendChild(cell);
+ agRootWrapper.appendChild(row);
+
+ let capturedMinHeight = '';
+ mockToJpeg.mockImplementation(() => {
+ capturedMinHeight = cell.style.minHeight;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
+
+ // Uses the larger content height, not the stale row height
+ expect(capturedMinHeight).toBe('120px');
+ expect(cell.style.minHeight).toBe('');
+
+ cleanup();
+ jest.useRealTimers();
+});
+
+test('derives image width from getColumnState by summing visible column pixel widths', async () => {
+ jest.useFakeTimers();
+ const { container, agContainer, cleanup } = buildAgGridElement();
+ const api = attachMockApi(agContainer);
+
+ // 3 visible columns (200 + 350 + 150 = 700 px) plus one hidden column excluded from sum
+ (api as any).getColumnState = jest.fn(() => [
+ { colId: 'col1', width: 200, hide: false },
+ { colId: 'col2', width: 350, hide: false },
+ { colId: 'col3', width: 150, hide: false },
+ { colId: 'col4', width: 999, hide: true },
+ ]);
+ (api as any).applyColumnState = jest.fn();
+
+ let capturedWidth: number | undefined;
+ mockToJpeg.mockImplementation((_el: HTMLElement, opts: { width?: number }) => {
+ capturedWidth = opts.width;
+ return Promise.resolve('data:image/jpeg;base64,test');
+ });
+
+ const handler = downloadAsImageOptimized('div', 'My Chart');
+ const exportPromise = handler(syntheticEventFor(container));
+ await jest.runAllTimersAsync();
+ await exportPromise;
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test coverage for non-ag-grid path</b></div>
<div id="fix">
All tests use ag-grid elements, leaving the general chart download path untested, which could hide bugs in clone-based image generation.
</div>
</div>
<div id="suggestion">
<div id="issue"><b>Missing test assertion for image width</b></div>
<div id="fix">
The test mocks getColumnState but does not check if the calculated width is passed to toJpeg, potentially missing bugs in width derivation.
</div>
</div>
<small><i>Code Review Run #35b4d7</i></small>
</div><div>
<div id="suggestion">
<div id="issue"><b>Incorrect async timing in tests</b></div>
<div id="fix">
Tests using jest.useFakeTimers() for ag-grid paths don't handle requestAnimationFrame, so the code after layout waits (rAF calls) doesn't run, making assertions on domToImage.toJpeg and layout restores unreliable.
</div>
</div>
<small><i>Code Review Run #1f1c51</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/ThemedAgGridReact.test.tsx:
##########
@@ -171,6 +173,47 @@ test('passes all props through to AgGridReact', () => {
);
});
+test('onGridReady wrapper calls user callback and exposes api on container', () => {
+ const onGridReady = jest.fn();
+
+ render(
+ <ThemedAgGridReact
+ rowData={mockRowData}
+ columnDefs={mockColumnDefs}
+ onGridReady={onGridReady}
+ />,
+ );
+
+ // Retrieve the wrapped handler that was passed to AgGridReact
+ const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
+ const wrappedOnGridReady = lastCall.onGridReady as Function;
+
+ const mockApi = { setGridOption: jest.fn() };
+ wrappedOnGridReady({ api: mockApi });
+
+ // The user-provided callback must be forwarded
+ expect(onGridReady).toHaveBeenCalledWith({ api: mockApi });
+});
+
+test('onFirstDataRendered wrapper calls user callback', () => {
+ const onFirstDataRendered = jest.fn();
+
+ render(
+ <ThemedAgGridReact
+ rowData={mockRowData}
+ columnDefs={mockColumnDefs}
+ onFirstDataRendered={onFirstDataRendered}
+ />,
+ );
+
+ const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
+ const wrappedOnFirstDataRendered = lastCall.onFirstDataRendered as Function;
+
+ wrappedOnFirstDataRendered({ firstRow: 0 });
+
+ expect(onFirstDataRendered).toHaveBeenCalledWith({ firstRow: 0 });
+});
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test assertion</b></div>
<div id="fix">
The test should verify that the _agGridFirstDataRendered flag is set to true on the container after the wrapped handler is called, as per the component's behavior.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
test('onFirstDataRendered wrapper calls user callback', () => {
const onFirstDataRendered = jest.fn();
const { container } = render(
<ThemedAgGridReact
rowData={mockRowData}
columnDefs={mockColumnDefs}
onFirstDataRendered={onFirstDataRendered}
/>,
);
const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
const wrappedOnFirstDataRendered = lastCall.onFirstDataRendered as Function;
wrappedOnFirstDataRendered({ firstRow: 0 });
expect(onFirstDataRendered).toHaveBeenCalledWith({ firstRow: 0 });
const wrapper = container.querySelector('[data-themed-ag-grid="true"]');
expect((wrapper as any)._agGridFirstDataRendered).toBe(true);
});
````
</div>
</details>
</div>
<small><i>Code Review Run #1f1c51</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset-frontend/packages/superset-ui-core/src/components/ThemedAgGridReact/ThemedAgGridReact.test.tsx:
##########
@@ -171,6 +173,47 @@ test('passes all props through to AgGridReact', () => {
);
});
+test('onGridReady wrapper calls user callback and exposes api on container', () => {
+ const onGridReady = jest.fn();
+
+ render(
+ <ThemedAgGridReact
+ rowData={mockRowData}
+ columnDefs={mockColumnDefs}
+ onGridReady={onGridReady}
+ />,
+ );
+
+ // Retrieve the wrapped handler that was passed to AgGridReact
+ const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
+ const wrappedOnGridReady = lastCall.onGridReady as Function;
+
+ const mockApi = { setGridOption: jest.fn() };
+ wrappedOnGridReady({ api: mockApi });
+
+ // The user-provided callback must be forwarded
+ expect(onGridReady).toHaveBeenCalledWith({ api: mockApi });
+});
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Incomplete test assertions</b></div>
<div id="fix">
The test name claims to verify API exposure on the container, but it only checks callback forwarding. Add checks for (wrapper as any)._agGridApi and _agGridFirstDataRendered properties on the themed div.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
test('onGridReady wrapper calls user callback and exposes api on container', () => {
const onGridReady = jest.fn();
const { container } = render(
<ThemedAgGridReact
rowData={mockRowData}
columnDefs={mockColumnDefs}
onGridReady={onGridReady}
/>,
);
// Retrieve the wrapped handler that was passed to AgGridReact
const lastCall = (AgGridReact as jest.Mock).mock.calls.at(-1)[0];
const wrappedOnGridReady = lastCall.onGridReady as Function;
const mockApi = { setGridOption: jest.fn() };
wrappedOnGridReady({ api: mockApi });
// The user-provided callback must be forwarded
expect(onGridReady).toHaveBeenCalledWith({ api: mockApi });
// Assert that the container has the _agGridApi property set
const wrapper = container.querySelector('[data-themed-ag-grid="true"]');
expect((wrapper as any)._agGridApi).toBe(mockApi);
expect((wrapper as any)._agGridFirstDataRendered).toBe(false);
});
````
</div>
</details>
</div>
<small><i>Code Review Run #1f1c51</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] Fix the jpeg export of ag-grid tables [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4102223453
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 0c99834ef9c0ceb95f633a7864e02c995ac168cb |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69be1c4f8432880008a86c5c |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-38781--superset-docs-preview.netlify.app](https://deploy-preview-38781--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-38781--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #38781:
URL: https://github.com/apache/superset/pull/38781#issuecomment-4144409866
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(ag-grid): jpeg export of ag-grid tables [superset]
Posted by "gabotorresruiz (via GitHub)" <gi...@apache.org>.
gabotorresruiz merged PR #38781:
URL: https://github.com/apache/superset/pull/38781
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org