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

fix(components): update mobile menu behaviour #4395

Open
wants to merge 5 commits into
base: 4326-update-megadropdown-styles
Choose a base branch
from
Open
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
29 changes: 29 additions & 0 deletions packages/components/src/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
import { HeadingLevel } from "./types/index";
import { BannerType } from "./components/post-banner/banner-types";
import { DEVICE_SIZE } from "./components/post-header/post-header";
import { SwitchVariant } from "./components/post-language-switch/switch-variants";
import { Placement } from "@floating-ui/dom";
export { HeadingLevel } from "./types/index";
export { BannerType } from "./components/post-banner/banner-types";
export { DEVICE_SIZE } from "./components/post-header/post-header";
export { SwitchVariant } from "./components/post-language-switch/switch-variants";
export { Placement } from "@floating-ui/dom";
export namespace Components {
Expand Down Expand Up @@ -375,6 +377,10 @@ export namespace Components {
* Programmatically hide this tooltip
*/
"hide": () => Promise<void>;
/**
* Whether or not the popover should close when user clicks outside of it
*/
"manualClose": boolean;
/**
* Defines the placement of the tooltip according to the floating-ui options available at https://floating-ui.com/docs/computePosition#placement. Tooltips are automatically flipped to the opposite side if there is not enough available space and are shifted towards the viewport if they would overlap edge boundaries.
*/
Expand Down Expand Up @@ -494,6 +500,10 @@ export interface PostCollapsibleCustomEvent<T> extends CustomEvent<T> {
detail: T;
target: HTMLPostCollapsibleElement;
}
export interface PostHeaderCustomEvent<T> extends CustomEvent<T> {
detail: T;
target: HTMLPostHeaderElement;
}
export interface PostLanguageOptionCustomEvent<T> extends CustomEvent<T> {
detail: T;
target: HTMLPostLanguageOptionElement;
Expand Down Expand Up @@ -632,7 +642,18 @@ declare global {
prototype: HTMLPostFooterElement;
new (): HTMLPostFooterElement;
};
interface HTMLPostHeaderElementEventMap {
"postUpdateDevice": DEVICE_SIZE;
}
interface HTMLPostHeaderElement extends Components.PostHeader, HTMLStencilElement {
addEventListener<K extends keyof HTMLPostHeaderElementEventMap>(type: K, listener: (this: HTMLPostHeaderElement, ev: PostHeaderCustomEvent<HTMLPostHeaderElementEventMap[K]>) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof HTMLPostHeaderElementEventMap>(type: K, listener: (this: HTMLPostHeaderElement, ev: PostHeaderCustomEvent<HTMLPostHeaderElementEventMap[K]>) => any, options?: boolean | EventListenerOptions): void;
removeEventListener<K extends keyof DocumentEventMap>(type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
var HTMLPostHeaderElement: {
prototype: HTMLPostHeaderElement;
Expand Down Expand Up @@ -1040,6 +1061,10 @@ declare namespace LocalJSX {
"label": string;
}
interface PostHeader {
/**
* An event emitted when the device has changed
*/
"onPostUpdateDevice"?: (event: PostHeaderCustomEvent<DEVICE_SIZE>) => void;
}
/**
* @class PostIcon - representing a stencil component
Expand Down Expand Up @@ -1191,6 +1216,10 @@ declare namespace LocalJSX {
* Gap between the edge of the page and the popover
*/
"edgeGap"?: number;
/**
* Whether or not the popover should close when user clicks outside of it
*/
"manualClose"?: boolean;
/**
* Fires whenever the popover gets shown or hidden, passing the new state in event.details as a boolean
*/
Expand Down
10 changes: 10 additions & 0 deletions packages/components/src/components/post-header/post-header.scss
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,16 @@ slot[name='post-logo'] {
}
}

.navigation.extended {
height: calc(100vh - var(--header-height));
display: flex;
flex-direction: column;

::slotted(post-mainnavigation) {
flex-grow: 1;
}
}

::slotted(post-mainnavigation) {
background-color: var(--post-core-color-sandgrey-002);
gap: var(--post-core-dimension-32);
Expand Down
76 changes: 74 additions & 2 deletions packages/components/src/components/post-header/post-header.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
import { Component, h, Host, State, Element, Method, Watch } from '@stencil/core';
import {
Component,
h,
Host,
State,
Element,
Method,
Watch,
Event,
EventEmitter,
} from '@stencil/core';
import { throttle } from 'throttle-debounce';
import { version } from '@root/package.json';
import { SwitchVariant } from '@/components';
import { slideDown, slideUp } from '@/animations/slide';
import { getFocusableChildren } from '@/utils/get-focusable-children';

type DEVICE_SIZE = 'mobile' | 'tablet' | 'desktop' | null;
export type DEVICE_SIZE = 'mobile' | 'tablet' | 'desktop' | null;

@Component({
tag: 'post-header',
shadow: true,
styleUrl: './post-header.scss',
})
export class PostHeader {
private firstFocusableEl: HTMLElement | null;
private lastFocusableEl: HTMLElement | null;
private scrollParent = null;
private mobileMenu: HTMLElement;
private mobileMenuAnimation: Animation;
Expand All @@ -24,6 +37,7 @@ export class PostHeader {
window.addEventListener('resize', this.throttledResize, { passive: true });
this.handleResize();
this.handleScrollEvent();
this.getFocusableElements();
}

@Element() host: HTMLPostHeaderElement;
Expand All @@ -34,8 +48,23 @@ export class PostHeader {
@Watch('mobileMenuExtended')
frozeBody(isMobileMenuExtended: boolean) {
document.body.style.overflow = isMobileMenuExtended ? 'hidden' : '';

if (isMobileMenuExtended) {
this.host.addEventListener('keydown', e => {
this.keyboardHandler(e);
});
} else {
this.host.removeEventListener('keydown', e => {
this.keyboardHandler(e);
});
}
}

/**
* An event emitted when the device has changed
*/
@Event() postUpdateDevice: EventEmitter<DEVICE_SIZE>;

/**
* Toggles the mobile navigation.
*/
Expand All @@ -57,6 +86,47 @@ export class PostHeader {
if (!this.mobileMenuExtended) await this.mobileMenuAnimation.finished;
}

// Get all the focusable elements in the post-header mobile menu
private getFocusableElements() {
// Get elements in the correct order (different as the DOM order)
const focusableEls = [
...Array.from(this.host.querySelectorAll('.list-inline:not([slot="meta-navigation"]) > li')),
...Array.from(
this.host.querySelectorAll(
'nav > post-list > div > post-list-item, post-mainnavigation > .back-button, post-megadropdown-trigger',
),
),
...Array.from(
this.host.querySelectorAll(
'.list-inline[slot="meta-navigation"] > li, post-language-option',
),
),
];

// Add the main toggle menu button to the list of focusable children
const focusableChildren = [
this.host.querySelector('post-togglebutton'),
...focusableEls.flatMap(el => Array.from(getFocusableChildren(el))),
];

this.firstFocusableEl = focusableChildren[0];
this.lastFocusableEl = focusableChildren[focusableChildren.length - 1];
}

private keyboardHandler(e: KeyboardEvent) {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === this.firstFocusableEl) {
// If back tab (Tab + Shift) and first element is focused, focus goes to the last element of the megadropdown
e.preventDefault();
this.lastFocusableEl.focus();
Copy link
Member

Choose a reason for hiding this comment

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

This should only be done if the menu is open, otherwise it's impossible to go back to the logo and skiplinks:

image

Pressing [shift] + [tab] in this situation locks focus to the menu button.

} else if (!e.shiftKey && document.activeElement === this.lastFocusableEl) {
// If Tab and last element is focused, focus goes back to the first element of the megadropdown
e.preventDefault();
this.firstFocusableEl.focus();
}
}
}

private handleScrollEvent() {
// Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
const st = Math.max(
Expand Down Expand Up @@ -116,6 +186,8 @@ export class PostHeader {
// Apply only on change for doing work only when necessary
if (newDevice !== previousDevice) {
this.device = newDevice;

this.postUpdateDevice.emit(this.device);
window.requestAnimationFrame(() => {
this.switchLanguageSwitchMode();
});
Expand Down
7 changes: 7 additions & 0 deletions packages/components/src/components/post-header/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
<!-- Auto Generated Below -->


## Events

| Event | Description | Type |
| ------------------ | -------------------------------------------- | ------------------------------------------------ |
| `postUpdateDevice` | An event emitted when the device has changed | `CustomEvent<"desktop" \| "mobile" \| "tablet">` |


## Methods

### `toggleMobileMenu() => Promise<void>`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,15 @@ post-popovercontainer {
@include media.max(lg) {
--post-global-header-height: 64px;
--post-main-header-height: 48px;
position: absolute;
position: fixed;
top: var(--post-header-height) !important;
bottom: 0;
left: 0;
width: 100%;
height: auto;
max-height: calc(100vh - var(--header-height));
border-top: unset;
overflow: auto;

&.slide-in {
animation: slide-in;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { DEVICE_SIZE } from '@/components';
import { getFocusableChildren } from '@/utils/get-focusable-children';
import { Component, Element, Event, EventEmitter, h, Host, Method, State } from '@stencil/core';

@Component({
Expand All @@ -7,6 +9,12 @@ import { Component, Element, Event, EventEmitter, h, Host, Method, State } from
})
export class PostMegadropdown {
private popoverRef: HTMLPostPopovercontainerElement;
private header: HTMLPostHeaderElement | null;

private firstFocusableEl: HTMLElement | null;
private lastFocusableEl: HTMLElement | null;

@State() device: DEVICE_SIZE;

@Element() host: HTMLPostMegadropdownElement;

Expand Down Expand Up @@ -38,6 +46,10 @@ export class PostMegadropdown {
});
}

componentWillRender() {
this.getFocusableElements();
}

/**
* Toggles the dropdown visibility based on its current state.
*/
Expand All @@ -56,6 +68,7 @@ export class PostMegadropdown {
if (this.popoverRef) {
await this.popoverRef.show(target);
this.animationClass = 'slide-in';
this.host.addEventListener('keydown', e => this.keyboardHandler(e));
} else {
console.error('show: popoverRef is null or undefined');
}
Expand All @@ -66,12 +79,23 @@ export class PostMegadropdown {
*/
private hide() {
if (this.popoverRef) {
this.host.removeEventListener('keydown', e => this.keyboardHandler(e));
this.popoverRef.hide();
} else {
console.error('hide: popoverRef is null or undefined');
}
}

connectedCallback() {
this.header = this.host.closest('post-header');
if (this.header) {
this.header.addEventListener(
'postUpdateDevice',
(event: CustomEvent<DEVICE_SIZE>) => (this.device = event.detail),
);
}
}

private handleBackButtonClick() {
this.animationClass = 'slide-out';
}
Expand All @@ -82,17 +106,41 @@ export class PostMegadropdown {

private handleFocusout(event: FocusEvent) {
const relatedTarget = event.relatedTarget as HTMLElement;
const megadropdown= this.popoverRef.querySelector('.megadropdown');
const megadropdown = this.popoverRef.querySelector('.megadropdown');
if (!megadropdown.contains(relatedTarget)) {
this.hide();
}
}

private getFocusableElements() {
const focusableEls = Array.from(this.host.querySelectorAll('post-list-item, h3, .back-button'));
const focusableChildren = focusableEls.flatMap(el => Array.from(getFocusableChildren(el)));

this.firstFocusableEl = focusableChildren[0];
this.lastFocusableEl = focusableChildren[focusableChildren.length - 1];
}

// Loop through the focusable children
private keyboardHandler(e: KeyboardEvent) {
if (e.key === 'Tab' && this.device !== 'desktop') {
if (e.shiftKey && document.activeElement === this.firstFocusableEl) {
// If back tab (TAB + Shift) and first element is focused, focus goes to the last element of the megadropdown
e.preventDefault();
this.lastFocusableEl.focus();
} else if (!e.shiftKey && document.activeElement === this.lastFocusableEl) {
// If TAB and last element is focused, focus goes back to the first element of the megadropdown
e.preventDefault();
this.firstFocusableEl.focus();
}
}
}

render() {
return (
<Host>
<post-popovercontainer
class={this.animationClass}
manualClose={this.device !== 'desktop'}
placement="bottom"
edge-gap="0"
ref={el => (this.popoverRef = el)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ export class PostPopovercontainer {
*/
@Event() postToggle: EventEmitter<boolean>;

/**
* Whether or not the popover should close when user clicks outside of it
*/
@Prop() manualClose: boolean = false;

/**
* Defines the placement of the tooltip according to the floating-ui options available at https://floating-ui.com/docs/computePosition#placement.
* Tooltips are automatically flipped to the opposite side if there is not enough available space and are shifted
Expand All @@ -70,7 +75,6 @@ export class PostPopovercontainer {
@Prop() readonly arrow?: boolean = false;

componentDidLoad() {
this.host.setAttribute('popover', '');
this.host.addEventListener('beforetoggle', this.handleToggle.bind(this));
}

Expand Down Expand Up @@ -213,7 +217,7 @@ export class PostPopovercontainer {

render() {
return (
<Host data-version={version}>
<Host data-version={version} popover={this.manualClose ? 'manual' : 'auto'}>
{this.arrow && (
<span
class="arrow"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@

## Properties

| Property | Attribute | Description | Type | Default |
| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `arrow` | `arrow` | Wheter or not to display a little pointer arrow | `boolean` | `false` |
| `edgeGap` | `edge-gap` | Gap between the edge of the page and the popover | `number` | `8` |
| `placement` | `placement` | Defines the placement of the tooltip according to the floating-ui options available at https://floating-ui.com/docs/computePosition#placement. Tooltips are automatically flipped to the opposite side if there is not enough available space and are shifted towards the viewport if they would overlap edge boundaries. | `"bottom" \| "bottom-end" \| "bottom-start" \| "left" \| "left-end" \| "left-start" \| "right" \| "right-end" \| "right-start" \| "top" \| "top-end" \| "top-start"` | `'top'` |
| Property | Attribute | Description | Type | Default |
| ------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
| `arrow` | `arrow` | Wheter or not to display a little pointer arrow | `boolean` | `false` |
| `edgeGap` | `edge-gap` | Gap between the edge of the page and the popover | `number` | `8` |
| `manualClose` | `manual-close` | Whether or not the popover should close when user clicks outside of it | `boolean` | `false` |
| `placement` | `placement` | Defines the placement of the tooltip according to the floating-ui options available at https://floating-ui.com/docs/computePosition#placement. Tooltips are automatically flipped to the opposite side if there is not enough available space and are shifted towards the viewport if they would overlap edge boundaries. | `"bottom" \| "bottom-end" \| "bottom-start" \| "left" \| "left-end" \| "left-start" \| "right" \| "right-end" \| "right-start" \| "top" \| "top-end" \| "top-start"` | `'top'` |


## Events
Expand Down
Loading