codeant-ai-for-open-source[bot] commented on code in PR #38342: URL: https://github.com/apache/superset/pull/38342#discussion_r2872455577
########## superset-frontend/src/components/Accessibility/SkipLink.test.tsx: ########## @@ -0,0 +1,115 @@ +/** + * 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 { render, screen, fireEvent } from 'spec/helpers/testing-library'; +import SkipLink from './SkipLink'; + +describe('SkipLink', () => { + it('renders with default props', () => { + render(<SkipLink />); + const link = screen.getByText('Skip to main content'); + expect(link).toBeInTheDocument(); + expect(link).toHaveAttribute('href', '#main-content'); + expect(link).toHaveClass('a11y-skip-link'); + }); + + it('renders with custom targetId and children', () => { + render( + <SkipLink targetId="dashboard-content">Skip to dashboard</SkipLink>, + ); + const link = screen.getByText('Skip to dashboard'); + expect(link).toHaveAttribute('href', '#dashboard-content'); + }); + + it('focuses target element on click', () => { + const targetEl = document.createElement('div'); + targetEl.id = 'main-content'; + document.body.appendChild(targetEl); + + render(<SkipLink />); + const link = screen.getByText('Skip to main content'); + fireEvent.click(link); + + expect(document.activeElement).toBe(targetEl); + document.body.removeChild(targetEl); + }); + + it('sets tabindex temporarily and removes on blur', () => { + const targetEl = document.createElement('div'); + targetEl.id = 'main-content'; + document.body.appendChild(targetEl); + + render(<SkipLink />); + const link = screen.getByText('Skip to main content'); + fireEvent.click(link); + + // tabindex should be set after click/focus + expect(targetEl).toHaveAttribute('tabindex', '-1'); + + // tabindex should be removed after blur + fireEvent.blur(targetEl); + expect(targetEl).not.toHaveAttribute('tabindex'); + + document.body.removeChild(targetEl); + }); + + it('preserves existing tabindex on target', () => { + const targetEl = document.createElement('div'); + targetEl.id = 'main-content'; + targetEl.setAttribute('tabindex', '0'); + document.body.appendChild(targetEl); + + render(<SkipLink />); + const link = screen.getByText('Skip to main content'); + fireEvent.click(link); + + // Should keep the existing tabindex + expect(targetEl).toHaveAttribute('tabindex', '0'); + + // Should still have tabindex after blur (it was pre-existing) + fireEvent.blur(targetEl); + expect(targetEl).toHaveAttribute('tabindex', '0'); + + document.body.removeChild(targetEl); + }); + + it('falls back to hash navigation when target not found', () => { + render(<SkipLink targetId="nonexistent" />); + const link = screen.getByText('Skip to main content'); + + // Should not throw when target doesn't exist + fireEvent.click(link); + expect(window.location.hash).toBe('#nonexistent'); + }); + + it('prevents default link behavior', () => { + const targetEl = document.createElement('div'); + targetEl.id = 'main-content'; + document.body.appendChild(targetEl); + + render(<SkipLink />); + const link = screen.getByText('Skip to main content'); + + const preventDefaultSpy = jest.fn(); + link.addEventListener('click', preventDefaultSpy, { once: true }); + + fireEvent.click(link); + + document.body.removeChild(targetEl); + }); Review Comment: **Suggestion:** The "prevents default link behavior" test sets up a spy but never makes any assertion about it, so the test always passes and does not actually verify that the default navigation is prevented; add a concrete assertion that the location hash remains unchanged when the target exists to ensure the behavior is exercised. [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ SkipLink default-prevention regressions not detected by unit tests. - ⚠️ Accessibility behavior may break without automated test signal. ``` </details> ```suggestion it('prevents default link behavior', () => { const targetEl = document.createElement('div'); targetEl.id = 'main-content'; document.body.appendChild(targetEl); // Set an initial hash to detect unintended navigation window.location.hash = '#initial'; render(<SkipLink />); const link = screen.getByText('Skip to main content'); fireEvent.click(link); // Clicking the skip link should not change the location hash when the target exists expect(window.location.hash).toBe('#initial'); document.body.removeChild(targetEl); }); ``` <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Run the unit tests for the accessibility components with `npm test -- SkipLink.test.tsx`, which executes `superset-frontend/src/components/Accessibility/SkipLink.test.tsx`. 2. Observe the test case `it('prevents default link behavior', () => { ... })` at lines 100–114 in `SkipLink.test.tsx`; it sets up a `preventDefaultSpy` and calls `fireEvent.click(link)` but contains no `expect(...)` assertions. 3. In `superset-frontend/src/components/Accessibility/SkipLink.tsx` (the component imported via `import SkipLink from './SkipLink';`), temporarily remove or comment out the logic that prevents default navigation on click (e.g., the `event.preventDefault()` call in the click handler). 4. Re-run `npm test -- SkipLink.test.tsx` and note that all tests, including `'prevents default link behavior'`, still pass despite the regression, because the test at lines 100–114 never checks either the spy or `window.location.hash`, so it cannot fail based on the default-prevention 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/components/Accessibility/SkipLink.test.tsx **Line:** 100:114 **Comment:** *Logic Error: The "prevents default link behavior" test sets up a spy but never makes any assertion about it, so the test always passes and does not actually verify that the default navigation is prevented; add a concrete assertion that the location hash remains unchanged when the target exists to ensure the behavior is exercised. 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%2F38342&comment_hash=485491f0b08d8285ef418155792fa7c3463df389ff93d86da3ec539c69b2a663&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38342&comment_hash=485491f0b08d8285ef418155792fa7c3463df389ff93d86da3ec539c69b2a663&reaction=dislike'>👎</a> ########## superset-frontend/src/components/Accessibility/StatusAnnouncer.tsx: ########## @@ -0,0 +1,119 @@ +/** + * 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 { + createContext, + FC, + ReactNode, + useCallback, + useContext, + useMemo, + useRef, + useState, +} from 'react'; +import { css } from '@apache-superset/core/ui'; + +/** + * StatusAnnouncer - WCAG 4.1.2 Name, Role, Value + * Provides an ARIA live region for announcing dynamic content updates + * to assistive technologies (screen readers). + */ + +type Politeness = 'polite' | 'assertive'; + +interface StatusAnnouncerContextType { + announce: (message: string, politeness?: Politeness) => void; +} + +const StatusAnnouncerContext = createContext<StatusAnnouncerContextType>({ + announce: () => {}, +}); + +export const useStatusAnnouncer = () => useContext(StatusAnnouncerContext); + +const visuallyHiddenStyle = css` + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +`; + +interface StatusAnnouncerProviderProps { + children: ReactNode; +} + +export const StatusAnnouncerProvider: FC<StatusAnnouncerProviderProps> = ({ + children, +}) => { + const [politeMessage, setPoliteMessage] = useState(''); + const [assertiveMessage, setAssertiveMessage] = useState(''); + const clearTimeoutRef = useRef<ReturnType<typeof setTimeout>>(); + + const announce = useCallback( + (message: string, politeness: Politeness = 'polite') => { + if (clearTimeoutRef.current) { + clearTimeout(clearTimeoutRef.current); + } + + if (politeness === 'assertive') { + setAssertiveMessage(message); + } else { + setPoliteMessage(message); + } + + clearTimeoutRef.current = setTimeout(() => { + setPoliteMessage(''); + setAssertiveMessage(''); + }, 5000); + }, + [], + ); Review Comment: **Suggestion:** The timeout that clears the polite/assertive messages is never cleaned up on unmount, so if the provider is unmounted within 5 seconds of an announcement the timeout callback will still fire and attempt to update state on an unmounted component, causing React warnings and a small memory/resource leak; add a cleanup that clears any pending timeout when the provider unmounts. [resource leak] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ React warns about state updates after unmount. - ⚠️ Tests using StatusAnnouncerProvider may become flaky. - ⚠️ Minor timer leak when unmounting within five seconds. ``` </details> ```suggestion useEffect, useMemo, useRef, useState, } from 'react'; import { css } from '@apache-superset/core/ui'; /** * StatusAnnouncer - WCAG 4.1.2 Name, Role, Value * Provides an ARIA live region for announcing dynamic content updates * to assistive technologies (screen readers). */ type Politeness = 'polite' | 'assertive'; interface StatusAnnouncerContextType { announce: (message: string, politeness?: Politeness) => void; } const StatusAnnouncerContext = createContext<StatusAnnouncerContextType>({ announce: () => {}, }); export const useStatusAnnouncer = () => useContext(StatusAnnouncerContext); const visuallyHiddenStyle = css` position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; `; interface StatusAnnouncerProviderProps { children: ReactNode; } export const StatusAnnouncerProvider: FC<StatusAnnouncerProviderProps> = ({ children, }) => { const [politeMessage, setPoliteMessage] = useState(''); const [assertiveMessage, setAssertiveMessage] = useState(''); const clearTimeoutRef = useRef<ReturnType<typeof setTimeout>>(); const announce = useCallback( (message: string, politeness: Politeness = 'polite') => { if (clearTimeoutRef.current) { clearTimeout(clearTimeoutRef.current); } if (politeness === 'assertive') { setAssertiveMessage(message); } else { setPoliteMessage(message); } clearTimeoutRef.current = setTimeout(() => { setPoliteMessage(''); setAssertiveMessage(''); }, 5000); }, [], ); useEffect(() => { return () => { if (clearTimeoutRef.current) { clearTimeout(clearTimeoutRef.current); } }; }, []); ``` <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Render `StatusAnnouncerProvider` (default export from `superset-frontend/src/components/Accessibility/StatusAnnouncer.tsx:65`) in a React tree with any child component. 2. Inside a child component, call `const { announce } = useStatusAnnouncer(); announce('Loading...', 'polite');` which executes the callback in `announce()` at `StatusAnnouncer.tsx:72-88`, setting `clearTimeoutRef.current = setTimeout(...)`. 3. Unmount the subtree containing `StatusAnnouncerProvider` within 5 seconds (for example, in a route change or in a React Testing Library test calling `unmount()` on the rendered tree). 4. After unmount, the pending timeout fires and runs the callback at `StatusAnnouncer.tsx:84-86`, calling `setPoliteMessage('')` / `setAssertiveMessage('')` on an unmounted component, which in React produces "Can't perform a React state update on an unmounted component" warnings and keeps the timer alive until it finishes. ``` </details> <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/src/components/Accessibility/StatusAnnouncer.tsx **Line:** 25:90 **Comment:** *Resource Leak: The timeout that clears the polite/assertive messages is never cleaned up on unmount, so if the provider is unmounted within 5 seconds of an announcement the timeout callback will still fire and attempt to update state on an unmounted component, causing React warnings and a small memory/resource leak; add a cleanup that clears any pending timeout when the provider unmounts. 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%2F38342&comment_hash=f1be4720e65b1d1fe675b0f8cd2127cd5df10141ee24d47a82fba4ba52de835c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38342&comment_hash=f1be4720e65b1d1fe675b0f8cd2127cd5df10141ee24d47a82fba4ba52de835c&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: [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]
