sadpandajoe commented on code in PR #41351:
URL: https://github.com/apache/superset/pull/41351#discussion_r3521961195


##########
superset-frontend/packages/superset-ui-core/src/components/DropdownContainer/DropdownContainer.tsx:
##########
@@ -220,6 +325,59 @@ export const DropdownContainer = forwardRef(
           }
         }
 
+        // A "nothing overflows" verdict on the pass that consumed an item-set-
+        // change reset may reflect a transient mid-reflow measurement. When 
that
+        // happens, do NOT settle immediately. Instead:
+        //   • If the rAF hasn't been scheduled yet: schedule it (one-shot) and
+        //     return without settling; recalculating stays true so the trigger
+        //     remains mounted throughout the confirmation window.
+        //   • If the rAF is already scheduled (a second layout effect run
+        //     triggered by the setItemsWidth call above): also return without
+        //     settling for the same reason.
+        // The rAF callback reads the DOM directly at a point where the browser
+        // has reflowed and calls the setters itself. It also resets the guard
+        // refs so subsequent effect runs (e.g. from a real resize) behave
+        // normally.
+        if (
+          newOverflowingIndex === -1 &&
+          pendingConfirmForLengthRef.current === items.length
+        ) {
+          if (!confirmationScheduledRef.current) {
+            confirmationScheduledRef.current = true;
+            const scheduledVersion = confirmVersionRef.current;
+            rafIdRef.current = requestAnimationFrame(() => {
+              rafIdRef.current = 0;
+              if (!mountedRef.current) return;
+              // A newer item-set change superseded this confirmation while the
+              // frame was queued; let the newer one's own confirmation settle.
+              if (confirmVersionRef.current !== scheduledVersion) return;
+              // Reset guard refs so future layout effect runs are unaffected.
+              pendingConfirmForLengthRef.current = -1;
+              confirmationScheduledRef.current = false;
+              hadContentAtLastChangeRef.current = false;

Review Comment:
   Addressed in 734f608 — the confirmation rAF callback now no-ops when a 
settling pass has already cleared the pending confirmation (it checks 
`confirmVersionRef` for supersession and 
`pendingConfirmForLengthRef`/`confirmationScheduledRef` for an already-settled 
state before touching `overflowingIndex`).



##########
superset-frontend/packages/superset-ui-core/src/components/DropdownContainer/DropdownContainer.tsx:
##########
@@ -220,6 +325,59 @@ export const DropdownContainer = forwardRef(
           }
         }
 
+        // A "nothing overflows" verdict on the pass that consumed an item-set-
+        // change reset may reflect a transient mid-reflow measurement. When 
that
+        // happens, do NOT settle immediately. Instead:
+        //   • If the rAF hasn't been scheduled yet: schedule it (one-shot) and
+        //     return without settling; recalculating stays true so the trigger
+        //     remains mounted throughout the confirmation window.
+        //   • If the rAF is already scheduled (a second layout effect run
+        //     triggered by the setItemsWidth call above): also return without
+        //     settling for the same reason.
+        // The rAF callback reads the DOM directly at a point where the browser
+        // has reflowed and calls the setters itself. It also resets the guard
+        // refs so subsequent effect runs (e.g. from a real resize) behave
+        // normally.
+        if (
+          newOverflowingIndex === -1 &&
+          pendingConfirmForLengthRef.current === items.length
+        ) {
+          if (!confirmationScheduledRef.current) {
+            confirmationScheduledRef.current = true;
+            const scheduledVersion = confirmVersionRef.current;
+            rafIdRef.current = requestAnimationFrame(() => {
+              rafIdRef.current = 0;
+              if (!mountedRef.current) return;
+              // A newer item-set change superseded this confirmation while the
+              // frame was queued; let the newer one's own confirmation settle.
+              if (confirmVersionRef.current !== scheduledVersion) return;
+              // Reset guard refs so future layout effect runs are unaffected.
+              pendingConfirmForLengthRef.current = -1;
+              confirmationScheduledRef.current = false;
+              hadContentAtLastChangeRef.current = false;
+              const el = containerRef.current;
+              if (!el) {
+                setOverflowingIndex(-1);
+                setRecalculating(false);
+                return;
+              }
+              const kids = Array.from(el.children);
+              const confirmIdx = kids.findIndex(
+                c =>
+                  c.getBoundingClientRect().right >
+                  el.getBoundingClientRect().right + 1,
+              );
+              setOverflowingIndex(confirmIdx);
+              setRecalculating(false);
+            });
+          }
+          // Either way (just scheduled or already pending): hold off settling 
so
+          // recalculating stays true and the button guard keeps the trigger 
mounted.
+          return;
+        }
+
+        pendingConfirmForLengthRef.current = -1;
+        confirmationScheduledRef.current = false;
         setOverflowingIndex(newOverflowingIndex);
         setRecalculating(false);

Review Comment:
   Addressed — the normal settle path now cancels any queued confirmation frame 
(734f608) and clears `hadContentAtLastChangeRef` (3f365ade38), so a settled 
state no longer keeps the trigger mounted or lets a stale frame run.



##########
superset-frontend/packages/superset-ui-core/src/components/DropdownContainer/DropdownContainer.overflow.test.tsx:
##########
@@ -0,0 +1,325 @@
+/**
+ * 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.
+ */
+
+/**
+ * Overflow-engine regression tests for DropdownContainer.
+ *
+ * jsdom has no real layout, so these tests drive the component's real overflow
+ * recalculation by mocking the two measurement sources it reads:
+ *   1. `useResizeDetector` — supplies the container width.
+ *   2. `getBoundingClientRect` — supplies per-element geometry. The inner
+ *      `data-test="container"` spans [0, containerRight]; every child is
+ *      ITEM_W wide and laid out left-to-right by its DOM index, so children
+ *      whose right edge exceeds `containerRight` overflow.
+ *
+ * This exercises the production code path in DropdownContainer.tsx
+ * (useLayoutEffect → overflowingIndex → notOverflowedItems/overflowedItems →
+ * showDropdownButton) rather than mocking the result.
+ */
+import { screen, render, waitFor, act } from '@superset-ui/core/spec';
+import * as resizeDetector from 'react-resize-detector';
+import { DropdownContainer } from '..';
+
+const ITEM_W = 100;
+// 350px container ⇒ at most 3 items (rights 100/200/300) fit before overflow.
+const BAR_WIDTH = 350;
+
+// Mutable so a test can simulate the transient layout window where a freshly
+// enlarged item set is momentarily measured as fitting before reflow settles.
+let containerRight = BAR_WIDTH;
+// Mutable width fed to the component through the mocked resize detector.
+let mockWidth = 0;
+// Stable ref object React attaches the outer node to (mirrors 
useResizeDetector).
+const fakeRef: { current: HTMLDivElement | null } = { current: null };
+
+const buildRect = (left: number, right: number): DOMRect =>
+  ({
+    left,
+    right,
+    width: right - left,
+    top: 0,
+    bottom: 0,
+    height: 0,
+    x: left,
+    y: 0,
+    toJSON: () => ({}),
+  }) as DOMRect;
+
+const installLayoutMock = () => {
+  HTMLElement.prototype.getBoundingClientRect = function mockRect(
+    this: HTMLElement,
+  ) {
+    const dataTest = this.getAttribute?.('data-test');
+    if (dataTest === 'container') {
+      return buildRect(0, containerRight);
+    }
+    const parent = this.parentElement;
+    if (parent?.getAttribute?.('data-test') === 'container') {
+      const index = Array.prototype.indexOf.call(parent.children, this);
+      return buildRect(index * ITEM_W, index * ITEM_W + ITEM_W);
+    }
+    // Outer wrapper div (its first child is the inner container).
+    if (
+      (this.children[0] as HTMLElement | undefined)?.getAttribute?.(
+        'data-test',
+      ) === 'container'
+    ) {
+      return buildRect(0, containerRight);
+    }
+    return buildRect(0, 0);
+  };
+};

Review Comment:
   Addressed in 3f365ade38 — the original 
`HTMLElement.prototype.getBoundingClientRect` is captured at module scope and 
restored in `afterEach` so the mock cannot leak into other suites.



##########
superset-frontend/packages/superset-ui-core/src/components/DropdownContainer/DropdownContainer.overflow.test.tsx:
##########
@@ -0,0 +1,325 @@
+/**
+ * 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.
+ */
+
+/**
+ * Overflow-engine regression tests for DropdownContainer.
+ *
+ * jsdom has no real layout, so these tests drive the component's real overflow
+ * recalculation by mocking the two measurement sources it reads:
+ *   1. `useResizeDetector` — supplies the container width.
+ *   2. `getBoundingClientRect` — supplies per-element geometry. The inner
+ *      `data-test="container"` spans [0, containerRight]; every child is
+ *      ITEM_W wide and laid out left-to-right by its DOM index, so children
+ *      whose right edge exceeds `containerRight` overflow.
+ *
+ * This exercises the production code path in DropdownContainer.tsx
+ * (useLayoutEffect → overflowingIndex → notOverflowedItems/overflowedItems →
+ * showDropdownButton) rather than mocking the result.
+ */
+import { screen, render, waitFor, act } from '@superset-ui/core/spec';
+import * as resizeDetector from 'react-resize-detector';
+import { DropdownContainer } from '..';
+
+const ITEM_W = 100;
+// 350px container ⇒ at most 3 items (rights 100/200/300) fit before overflow.
+const BAR_WIDTH = 350;
+
+// Mutable so a test can simulate the transient layout window where a freshly
+// enlarged item set is momentarily measured as fitting before reflow settles.
+let containerRight = BAR_WIDTH;
+// Mutable width fed to the component through the mocked resize detector.
+let mockWidth = 0;
+// Stable ref object React attaches the outer node to (mirrors 
useResizeDetector).
+const fakeRef: { current: HTMLDivElement | null } = { current: null };
+
+const buildRect = (left: number, right: number): DOMRect =>
+  ({
+    left,
+    right,
+    width: right - left,
+    top: 0,
+    bottom: 0,
+    height: 0,
+    x: left,
+    y: 0,
+    toJSON: () => ({}),
+  }) as DOMRect;
+
+const installLayoutMock = () => {
+  HTMLElement.prototype.getBoundingClientRect = function mockRect(
+    this: HTMLElement,
+  ) {
+    const dataTest = this.getAttribute?.('data-test');
+    if (dataTest === 'container') {
+      return buildRect(0, containerRight);
+    }
+    const parent = this.parentElement;
+    if (parent?.getAttribute?.('data-test') === 'container') {
+      const index = Array.prototype.indexOf.call(parent.children, this);
+      return buildRect(index * ITEM_W, index * ITEM_W + ITEM_W);
+    }
+    // Outer wrapper div (its first child is the inner container).
+    if (
+      (this.children[0] as HTMLElement | undefined)?.getAttribute?.(
+        'data-test',
+      ) === 'container'
+    ) {
+      return buildRect(0, containerRight);
+    }
+    return buildRect(0, 0);
+  };
+};
+
+let resizeSpy: jest.SpyInstance;
+let rafSpy: jest.SpyInstance;
+let cancelRafSpy: jest.SpyInstance;
+
+// Deterministic requestAnimationFrame: the component schedules a one-shot
+// confirmation frame to re-measure after an item-set change. Rather than sleep
+// and hope jsdom's timer-backed rAF fires inside the window, we capture the
+// callbacks and invoke them explicitly via flushRAF(). cancelAnimationFrame
+// removes a queued frame, so the supersession path can be exercised directly.
+let rafQueue: Array<{ id: number; cb: FrameRequestCallback }> = [];
+let rafSeq = 0;
+
+// Run every currently-queued frame once (frames scheduled during the flush are
+// left for the next flush, so a single call models a single browser frame).
+const flushRAF = () => {
+  const pending = rafQueue;
+  rafQueue = [];
+  pending.forEach(({ cb }) => cb(0));
+};
+
+beforeEach(() => {
+  containerRight = BAR_WIDTH;
+  mockWidth = 0;
+  fakeRef.current = null;
+  rafQueue = [];
+  rafSeq = 0;
+  installLayoutMock();
+  global.ResizeObserver = jest.fn().mockImplementation(() => ({
+    observe: jest.fn(),
+    unobserve: jest.fn(),
+    disconnect: jest.fn(),
+  })) as unknown as typeof ResizeObserver;
+  rafSpy = jest
+    .spyOn(window, 'requestAnimationFrame')
+    .mockImplementation((cb: FrameRequestCallback) => {
+      rafSeq += 1;
+      rafQueue.push({ id: rafSeq, cb });
+      return rafSeq;
+    });
+  cancelRafSpy = jest
+    .spyOn(window, 'cancelAnimationFrame')
+    .mockImplementation((id: number) => {
+      rafQueue = rafQueue.filter(frame => frame.id !== id);
+    });
+  resizeSpy = jest
+    .spyOn(resizeDetector, 'useResizeDetector')
+    .mockImplementation(
+      () =>
+        ({ ref: fakeRef, width: mockWidth, height: 50 }) as ReturnType<
+          typeof resizeDetector.useResizeDetector
+        >,
+    );
+});
+
+afterEach(() => {
+  resizeSpy?.mockRestore();
+  rafSpy?.mockRestore();
+  cancelRafSpy?.mockRestore();
+});

Review Comment:
   Addressed in 3f365ade38 — the original implementation is restored in 
`afterEach`.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to