Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add focus visible logic from core #3

Merged
merged 5 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions pages/utils/focus-visible.page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import Button from "@cloudscape-design/components/button";

export default function ButtonsPage() {
return (
<main>
<h1>Testing visible focus outline</h1>
<Button id="first-button">First button</Button>

Check warning on line 9 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 9 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 9 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Prop "id" is forbidden on Components
<Button id="second-button">Second button</Button>

Check warning on line 10 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 10 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 10 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Prop "id" is forbidden on Components
<Button disabled={true} id="dismiss-focus">

Check warning on line 11 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 11 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / build / build

Prop "id" is forbidden on Components

Check warning on line 11 in pages/utils/focus-visible.page.tsx

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Prop "id" is forbidden on Components
Focus dismiss target
</Button>
</main>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { COMPONENT_METADATA_KEY } from "@cloudscape-design/component-toolkit/internal";
import { render } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import useBaseComponent, {
InternalBaseComponentProps,
} from "../../../../lib/components/internal/base-component/use-base-component";
import { useTelemetry } from "../../../../lib/components/internal/base-component/use-telemetry";
import { PACKAGE_VERSION } from "../../../../lib/components/internal/environment";

type InternalDemoProps = InternalBaseComponentProps;
function InternalDemo({ __internalRootRef }: InternalDemoProps) {
return <div ref={__internalRootRef}>Internal Demo Component</div>;
}

function Demo({ variant }: { variant: string }) {
const baseComponentProps = useBaseComponent("DemoComponent", { props: { variant } });
return <InternalDemo {...baseComponentProps} />;
}

vi.mock("../../../../lib/components/internal/base-component/use-telemetry", () => {
return { useTelemetry: vi.fn(() => null) };
});

test("should attach the metadata to the returned root DOM node", () => {
const { container } = render(<Demo variant="default" />);
const rootNode: any = container.firstChild;

Check warning on line 28 in src/internal/base-component/__tests__/use-base-component.test.tsx

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 28 in src/internal/base-component/__tests__/use-base-component.test.tsx

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 28 in src/internal/base-component/__tests__/use-base-component.test.tsx

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Unexpected any. Specify a different type
expect(rootNode[COMPONENT_METADATA_KEY]?.name).toBe("DemoComponent");
expect(rootNode[COMPONENT_METADATA_KEY]?.version).toBe(PACKAGE_VERSION);
});

test("should call the useTelemetry hook passing down the given component name and its props", () => {
vi.resetAllMocks();
render(<Demo variant="default" />);
expect(useTelemetry).toHaveBeenCalledWith("DemoComponent", { props: { variant: "default" } });
});
2 changes: 2 additions & 0 deletions src/internal/base-component/use-base-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
} from "@cloudscape-design/component-toolkit/internal";
import { MutableRefObject } from "react";
import { PACKAGE_SOURCE, PACKAGE_VERSION } from "../environment";
import useFocusVisible from "../utils/focus-visible";
import { useTelemetry } from "./use-telemetry";

initAwsUiVersions(PACKAGE_SOURCE, PACKAGE_VERSION);

export interface InternalBaseComponentProps {
__internalRootRef?: MutableRefObject<any> | null;

Check warning on line 17 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 17 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 17 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Unexpected any. Specify a different type
}

/**
Expand All @@ -21,8 +22,9 @@
* attached to the (internal) component's root DOM node. The hook takes care of attaching the metadata to this
* root DOM node and emits the telemetry for this component.
*/
export default function useBaseComponent<T = any>(componentName: string, config?: ComponentConfiguration) {

Check warning on line 25 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 25 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / build / build

Unexpected any. Specify a different type

Check warning on line 25 in src/internal/base-component/use-base-component.ts

View workflow job for this annotation

GitHub Actions / dry-run / Build chat components

Unexpected any. Specify a different type
useTelemetry(componentName, config);
useFocusVisible();
const elementRef = useComponentMetadata<T>(componentName, PACKAGE_VERSION);
return { __internalRootRef: elementRef };
}
24 changes: 24 additions & 0 deletions src/internal/keycode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// When updating the list of key codes, don't forget
// to modify corresponding list in test-utils
// to avoid failing unit tests
export enum KeyCode {
pageUp = 33,
pageDown = 34,
end = 35,
home = 36,
backspace = 8,
space = 32,
down = 40,
left = 37,
right = 39,
up = 38,
escape = 27,
enter = 13,
tab = 9,
shift = 16,
control = 17,
alt = 18,
meta = 91,
}
26 changes: 26 additions & 0 deletions src/internal/shared.scss
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,29 @@
@content;
}
}

// the motion mixin definition is an exception from these scoping rules
/* stylelint-disable @cloudscape-design/no-motion-outside-of-mixin, selector-combinator-disallowed-list, selector-pseudo-class-no-unknown, selector-class-pattern */
@mixin with-motion {
@content;

@media (prefers-reduced-motion: reduce) {
animation: none;
transition: none;
}
:global(.awsui-motion-disabled) &,
:global(.awsui-mode-entering) & {
animation: none;
transition: none;
}
}
/* stylelint-enable @cloudscape-design/no-motion-outside-of-mixin, selector-combinator-disallowed-list, selector-pseudo-class-no-unknown, selector-class-pattern */

// mixin to apply styles only when keyboard focus is needed
// requires JavaScript part from useFocusVisible hook to be applied
@mixin when-visible {
// stylelint-disable-next-line selector-combinator-disallowed-list
body[data-awsui-focus-visible="true"] &:focus {
@content;
}
}
89 changes: 89 additions & 0 deletions src/internal/utils/__tests__/focus-visible.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import useFocusVisible from "../../../../lib/components/internal/utils/focus-visible";

function Fixture() {
useFocusVisible();
return <button>Test</button>;
}

describe("Focus visible", () => {
afterEach(() => {
cleanup();
});

test("should disable focus by default", () => {
render(<Fixture />);
expect(document.body).not.toHaveAttribute("data-awsui-focus-visible");
});

[
{ key: "Shift", keyCode: 16 },
{ key: "Alt", keyCode: 17 },
{ key: "Control", keyCode: 18 },
{ key: "Meta", keyCode: 91 },
].forEach((key) => {
test(`should not enable focus when ${key.key} key is pressed`, () => {
render(<Fixture />);
fireEvent.keyDown(document.body, key);
expect(document.body).not.toHaveAttribute("data-awsui-focus-visible");
});
});

test(`should enable focus when shift-tab is pressed`, () => {
render(<Fixture />);
fireEvent.keyDown(document.body, { key: "Tab", keyCode: 65, shiftKey: true });
expect(document.body).toHaveAttribute("data-awsui-focus-visible", "true");
});

test("should enable focus when keyboard interaction happened", () => {
render(<Fixture />);
fireEvent.keyDown(document.body);
expect(document.body).toHaveAttribute("data-awsui-focus-visible", "true");
});

test("should disable focus when mouse is used after keyboard", () => {
render(<Fixture />);
fireEvent.keyDown(document.body);
fireEvent.mouseDown(document.body);
expect(document.body).not.toHaveAttribute("data-awsui-focus-visible");
});

test("should work with multiple components", () => {
render(
<>
<Fixture />
<Fixture />
</>,
);
fireEvent.keyDown(document.body);
expect(document.body).toHaveAttribute("data-awsui-focus-visible", "true");
});

test("should add listeners only once", () => {
vi.spyOn(document, "addEventListener");
vi.spyOn(document, "removeEventListener");
const { rerender } = render(
<>
<Fixture />
<Fixture />
</>,
);
expect(document.addEventListener).toHaveBeenCalledTimes(2);
expect(document.removeEventListener).toHaveBeenCalledTimes(0);
rerender(<Fixture />);
expect(document.removeEventListener).toHaveBeenCalledTimes(0);
rerender(<span />);
expect(document.removeEventListener).toHaveBeenCalledTimes(2);
});

test("should initialize late components with updated state", () => {
const { rerender } = render(<Fixture key={1} />);
fireEvent.keyDown(document.body);
expect(document.body).toHaveAttribute("data-awsui-focus-visible", "true");
rerender(<Fixture key={2} />);
expect(document.body).toHaveAttribute("data-awsui-focus-visible", "true");
});
});
31 changes: 31 additions & 0 deletions src/internal/utils/__tests__/use-merge-refs.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { render } from "@testing-library/react";
// eslint-disable-next-line no-restricted-imports
import React from "react";
import { describe, expect, test, vi } from "vitest";
import { useMergeRefs } from "../use-merge-refs";

const Demo = React.forwardRef((props, ref) => {
const ref2 = React.createRef<HTMLDivElement>();
const mergedRef = useMergeRefs(ref, ref2);
return (
<>
<div ref={mergedRef} className="element1"></div>
</>
);
});

describe("use merge refs", function () {
test("merges two refs", () => {
const ref1 = React.createRef<HTMLDivElement>();
render(<Demo ref={ref1} />);
expect(ref1.current).toHaveClass("element1");
});
test("ref callback has been called", () => {
const ref1 = vi.fn();
render(<Demo ref={ref1} />);
expect(ref1).toHaveBeenCalledTimes(1);
expect(ref1).toHaveBeenCalledWith(expect.objectContaining({ className: "element1" }));
});
});
23 changes: 0 additions & 23 deletions src/internal/utils/events.ts

This file was deleted.

55 changes: 55 additions & 0 deletions src/internal/utils/focus-visible.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { useEffect } from "react";
import { KeyCode } from "../keycode";

export function isModifierKey(event: KeyboardEvent) {
// we do not want to highlight focused element
// when special keys are pressed
return [KeyCode.shift, KeyCode.alt, KeyCode.control, KeyCode.meta].indexOf(event.keyCode) > -1;
}

function setIsKeyboard(active: boolean) {
if (active) {
document.body.setAttribute("data-awsui-focus-visible", "true");
} else {
document.body.removeAttribute("data-awsui-focus-visible");
}
}

function handleMousedown() {
return setIsKeyboard(false);
}

function handleKeydown(event: KeyboardEvent) {
if (!isModifierKey(event)) {
setIsKeyboard(true);
}
}

let componentsCount = 0;

function addListeners() {
document.addEventListener("mousedown", handleMousedown);
document.addEventListener("keydown", handleKeydown);
}

function removeListeners() {
document.removeEventListener("mousedown", handleMousedown);
document.removeEventListener("keydown", handleKeydown);
}

export default function useFocusVisible() {
useEffect(() => {
if (componentsCount === 0) {
addListeners();
}
componentsCount++;
return () => {
componentsCount--;
if (componentsCount === 0) {
removeListeners();
}
};
}, []);
}
23 changes: 23 additions & 0 deletions test/functional/utils/focus-visible.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { BasePageObject } from "@cloudscape-design/browser-test-tools/page-objects";
import createWrapper from "@cloudscape-design/components/test-utils/selectors";
import { describe, expect, test } from "vitest";
import { setupTest } from "../../utils";

const wrapper = createWrapper();

describe("focus-visible", () => {
test(
"focus ring updates when switching from keyboard to mouse and back",
setupTest("/index.html#/utils/focus-visible", BasePageObject, async (page) => {
await page.waitForVisible(wrapper.findButton().toSelector());
await page.click("#first-button");
await expect(page.getElementAttribute("body", "data-awsui-focus-visible")).resolves.toBeNull();
await page.keys("Tab");
await expect(page.getElementAttribute("body", "data-awsui-focus-visible")).resolves.toBe("true");
await page.click("#second-button");
await expect(page.getElementAttribute("body", "data-awsui-focus-visible")).resolves.toBeNull();
}),
);
});
Loading