Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions superset-frontend/src/components/Accessibility/SkipLink.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/**
* 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 userEvent from '@testing-library/user-event';
import { render, screen } from 'spec/helpers/testing-library';
import SkipLink from './SkipLink';

const targets: HTMLElement[] = [];

const createTarget = (id: string) => {
const target = document.createElement('div');
target.id = id;
document.body.appendChild(target);
targets.push(target);
return target;
};

afterEach(() => {
targets.splice(0).forEach(target => target.remove());
window.location.hash = '';
});

test('renders the default label pointing at #main-content', () => {
render(<SkipLink />);
expect(
screen.getByRole('link', { name: 'Skip to main content' }),
).toHaveAttribute('href', '#main-content');
});

test('renders custom children and targetId', () => {
render(<SkipLink targetId="my-target">Jump to content</SkipLink>);
expect(screen.getByRole('link', { name: 'Jump to content' })).toHaveAttribute(
'href',
'#my-target',
);
});

// A fixed negative offset leaves part of the link visible once larger text
// makes it taller than the offset; translating by its own height does not.
test('hides the link by its own height until it is focused', () => {
render(<SkipLink />);
const link = screen.getByRole('link', { name: 'Skip to main content' });
expect(link).toHaveStyle({ transform: 'translateY(-100%)' });
expect(link).not.toHaveStyle({ top: '-100px' });
});

test('moves focus to the target and removes the temporary tabindex on blur', async () => {
const target = createTarget('target-area');
render(<SkipLink targetId="target-area">Skip</SkipLink>);

await userEvent.click(screen.getByRole('link', { name: 'Skip' }));

expect(target).toHaveFocus();
expect(target).toHaveAttribute('tabindex', '-1');

target.blur();
expect(target).not.toHaveAttribute('tabindex');
});

test('keeps a tabindex the target already had', async () => {
const target = createTarget('target-area');
target.setAttribute('tabindex', '0');
render(<SkipLink targetId="target-area">Skip</SkipLink>);

await userEvent.click(screen.getByRole('link', { name: 'Skip' }));
expect(target).toHaveFocus();

target.blur();
expect(target).toHaveAttribute('tabindex', '0');
});

test('falls back to the URL hash when the target is missing', async () => {
render(<SkipLink targetId="missing-target">Skip</SkipLink>);

await userEvent.click(screen.getByRole('link', { name: 'Skip' }));

expect(window.location.hash).toBe('#missing-target');
});
89 changes: 89 additions & 0 deletions superset-frontend/src/components/Accessibility/SkipLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* 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 { FC, MouseEvent, ReactNode } from 'react';
import { styled } from '@apache-superset/core/theme';
import { t } from '@apache-superset/core/translation';

/**
* SkipLink - WCAG 2.4.1 Bypass Blocks.
* Lets keyboard users skip the navigation and jump to the main content.
* The link sits just above the viewport and moves into view when focused.
*/
const StyledSkipLink = styled.a`
position: absolute;
top: 0;
left: 0;
z-index: 10000;
/* Translating by the link's own height keeps it fully off-screen at any
text size, unlike a fixed negative offset. */
transform: translateY(-100%);
padding: ${({ theme }) => theme.sizeUnit * 3}px
${({ theme }) => theme.sizeUnit * 4}px;
background: ${({ theme }) => theme.colorPrimary};
color: ${({ theme }) => theme.colorTextLightSolid};
font-size: ${({ theme }) => theme.fontSizeSM}px;
font-weight: ${({ theme }) => theme.fontWeightStrong};
text-decoration: none;
border-radius: 0 0 ${({ theme }) => theme.borderRadius}px
${({ theme }) => theme.borderRadius}px;

&:focus,
&:focus-visible {
transform: none;
outline: 3px solid ${({ theme }) => theme.colorPrimaryBorderHover};
outline-offset: 2px;
}
`;

interface SkipLinkProps {
targetId?: string;
children?: ReactNode;
}

const SkipLink: FC<SkipLinkProps> = ({
targetId = 'main-content',
children = t('Skip to main content'),
}) => {
const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {
e.preventDefault();
const el = document.getElementById(targetId);
if (!el) {
window.location.hash = `#${targetId}`;
return;
}
// tabindex="-1" makes the target programmatically focusable without
// adding it to the tab order; it is removed on blur to restore the
// element's original markup.
if (!el.hasAttribute('tabindex')) {
el.setAttribute('tabindex', '-1');
el.addEventListener('blur', () => el.removeAttribute('tabindex'), {
once: true,
});
}
el.focus();
};

return (
<StyledSkipLink href={`#${targetId}`} onClick={handleClick}>
{children}
</StyledSkipLink>
);
};

export default SkipLink;
19 changes: 19 additions & 0 deletions superset-frontend/src/components/Accessibility/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 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.
*/
export { default as SkipLink } from './SkipLink';
27 changes: 26 additions & 1 deletion superset-frontend/src/views/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { LOG_ACTIONS_SPA_NAVIGATION } from 'src/logger/LogUtils';
import { logEvent } from 'src/logger/actions';
import type { User } from 'src/types/bootstrapTypes';
import getBootstrapData from 'src/utils/getBootstrapData';
import App, { pageScrollShellCss } from './App';
import App, { mainContentFocusCss, pageScrollShellCss } from './App';

jest.mock('src/setup/setupApp', () => jest.fn());
jest.mock('src/setup/setupPlugins', () => jest.fn());
Expand Down Expand Up @@ -157,6 +157,31 @@ test('does not log spa_navigation for an anonymous user', () => {
}
});

// WCAG 2.4.1 (Bypass Blocks): keyboard users need a link ahead of the
// navigation that moves focus straight to the page content.
test('renders a skip link before the content that focuses the main landmark', () => {
const { unmount } = render(<App />);
const skipLink = screen.getByRole('link', { name: 'Skip to main content' });
const main = screen.getByRole('main');

expect(main).toHaveAttribute('id', 'main-content');
expect(skipLink).toHaveAttribute('href', '#main-content');
expect(
skipLink.compareDocumentPosition(main) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();

fireEvent.click(skipLink);
expect(main).toHaveFocus();
unmount();
});

// Programmatic focus on the main landmark should not flash an outline around
// the whole page content.
test('the main landmark hides the outline of its programmatic focus', () => {
expect(mainContentFocusCss.styles).toMatch(/\[tabindex='-1'\]:focus/);
expect(mainContentFocusCss.styles).toMatch(/outline:\s*none/);
});

// Locks in the page-scroll shell's CSS contract (superset#44867). #app is a
// growable flex item, so the shell must take the height #app grants it. A 100vh
// shell overflows #app whenever a host page injects content above it, and
Expand Down
20 changes: 19 additions & 1 deletion superset-frontend/src/views/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { css, useTheme } from '@apache-superset/core/theme';
import { Flex, Layout, Loading, Splitter } from '@superset-ui/core/components';
import { setupAGGridModules } from '@superset-ui/core/components/ThemedAgGridReact';
import { ErrorBoundary } from 'src/components';
import { SkipLink } from 'src/components/Accessibility';
import MobileRouteGuard from 'src/components/MobileRouteGuard';
import MenuWrapper from 'src/features/home/Menu';
import getBootstrapData, { applicationRoot } from 'src/utils/getBootstrapData';
Expand Down Expand Up @@ -170,6 +171,16 @@ const pageScrollContentCss = css`
flex-direction: column;
`;

// The skip link focuses the main landmark programmatically; that focus has no
// visible control behind it, so it should not paint an outline. Exported for
// App.test.tsx, like pageScrollShellCss.
export const mainContentFocusCss = css`
&[tabindex='-1']:focus,
&[tabindex='-1']:focus-visible {
outline: none;
}
`;
Comment on lines +177 to +182

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: When the main region is already visible, activating the link hides the focused link and leaves the focused landmark without a visible focus cue.

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes · 🏷️ Possible bug

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-frontend/src/views/App.tsx
**Line:** 177:182
**Comment:**
	*Possible Bug: When the main region is already visible, activating the link hides the focused link and leaves the focused landmark without a visible focus cue.

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.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎


// Renders the app shell and picks the scroll model: in chat panel mode <Layout>
// sits in a Splitter beside the chat panel; otherwise the page scrolls normally.
const AppContent = ({
Expand Down Expand Up @@ -201,7 +212,13 @@ const AppContent = ({

const layoutContent = (
<Layout css={isPanelOpen ? layoutCss : undefined}>
<Layout.Content css={isPanelOpen ? contentCss : pageScrollContentCss}>
<Layout.Content
id="main-content"
css={[
isPanelOpen ? contentCss : pageScrollContentCss,
mainContentFocusCss,
]}
>
<OutPortal node={layoutPortalNode} />
</Layout.Content>
</Layout>
Expand Down Expand Up @@ -254,6 +271,7 @@ const AppContent = ({

return (
<Flex vertical css={isPanelOpen ? lockedShellCss : pageScrollShellCss}>
<SkipLink />

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Question, not a blocker: MenuWrapper renders nothing when standalone is set or uiConfig.hideNav is on (Menu.tsx lines 579-580), but the skip link still renders, so a standalone dashboard gets a first tab stop that has no nav to skip. Should it follow the same check?

<MenuWrapper
data={bootstrapData.common.menu_data}
isFrontendRoute={isFrontendRoute}
Expand Down
3 changes: 3 additions & 0 deletions superset/translations/messages.pot
Original file line number Diff line number Diff line change
Expand Up @@ -13973,6 +13973,9 @@ msgstr ""
msgid "Skip spaces after delimiter"
msgstr ""

msgid "Skip to main content"
msgstr ""

#, python-format
msgid "Skipped %d system themes that cannot be deleted"
msgstr ""
Expand Down
Loading