Merge pull request #3924 from alexandrevryghem/made-expandable-navbar-section-more-accessible-7_x

[Port dspace-7_x] Made expandable navbar section more keyboard accessible
This commit is contained in:
Tim Donohue
2025-01-30 11:58:31 -06:00
committed by GitHub
7 changed files with 383 additions and 74 deletions

View File

@@ -67,8 +67,8 @@ export class ExpandableAdminSidebarSectionComponent extends AdminSidebarSectionC
this.sidebarActiveBg$ = this.variableService.getVariable('--ds-admin-sidebar-active-bg'); this.sidebarActiveBg$ = this.variableService.getVariable('--ds-admin-sidebar-active-bg');
this.isSidebarCollapsed$ = this.menuService.isMenuCollapsed(this.menuID); this.isSidebarCollapsed$ = this.menuService.isMenuCollapsed(this.menuID);
this.isSidebarPreviewCollapsed$ = this.menuService.isMenuPreviewCollapsed(this.menuID); this.isSidebarPreviewCollapsed$ = this.menuService.isMenuPreviewCollapsed(this.menuID);
this.isExpanded$ = combineLatestObservable([this.active, this.isSidebarCollapsed$, this.isSidebarPreviewCollapsed$]).pipe( this.isExpanded$ = combineLatestObservable([this.active$, this.isSidebarCollapsed$, this.isSidebarPreviewCollapsed$]).pipe(
map(([active, sidebarCollapsed, sidebarPreviewCollapsed]) => (active && (!sidebarCollapsed || !sidebarPreviewCollapsed))) map(([active, sidebarCollapsed, sidebarPreviewCollapsed]) => (active && (!sidebarCollapsed || !sidebarPreviewCollapsed))),
); );
} }

View File

@@ -1,35 +1,37 @@
<div class="ds-menu-item-wrapper text-md-center" <div class="ds-menu-item-wrapper text-md-center"
[id]="'expandable-navbar-section-' + section.id" [id]="'expandable-navbar-section-' + section.id"
(mouseenter)="onMouseEnter($event, isActive)" (mouseenter)="onMouseEnter($event)"
(mouseleave)="onMouseLeave($event, isActive)" (mouseleave)="onMouseLeave($event)"
data-test="navbar-section-wrapper" data-test="navbar-section-wrapper">
*ngVar="(active | async) as isActive"> <a href="javascript:void(0);" routerLinkActive="active"
<a href="javascript:void(0);" routerLinkActive="active" role="menuitem"
role="menuitem" (keyup.enter)="toggleSection($event)"
(keyup.enter)="toggleSection($event)" (keyup.space)="toggleSection($event)"
(keyup.space)="toggleSection($event)" (click)="toggleSection($event)"
(click)="toggleSection($event)" (keydown)="keyDown($event)"
(keydown.space)="$event.preventDefault()" aria-haspopup="menu"
aria-haspopup="menu" data-test="navbar-section-toggler"
data-test="navbar-section-toggler" [attr.aria-expanded]="(active$ | async).valueOf()"
[attr.aria-expanded]="isActive" [attr.aria-controls]="expandableNavbarSectionId()"
[attr.aria-controls]="expandableNavbarSectionId(section.id)" class="d-flex flex-row flex-nowrap align-items-center gapx-1 ds-menu-toggler-wrapper"
class="d-flex flex-row flex-nowrap align-items-center gapx-1 ds-menu-toggler-wrapper" [class.disabled]="section.model?.disabled">
[class.disabled]="section.model?.disabled">
<span class="flex-fill"> <span class="flex-fill">
<ng-container <ng-container
*ngComponentOutlet="(sectionMap$ | async).get(section.id).component; injector: (sectionMap$ | async).get(section.id).injector;"></ng-container> *ngComponentOutlet="(sectionMap$ | async).get(section.id).component; injector: (sectionMap$ | async).get(section.id).injector;"></ng-container>
<!-- <span class="sr-only">{{'nav.expandable-navbar-section-suffix' | translate}}</span>-->
</span> </span>
<i class="fas fa-caret-down fa-xs toggle-menu-icon" aria-hidden="true"></i> <i class="fas fa-caret-down fa-xs toggle-menu-icon" aria-hidden="true"></i>
</a> </a>
<div @slide *ngIf="isActive" (click)="deactivateSection($event)" <div *ngIf="(active$ | async).valueOf() === true" (click)="deactivateSection($event)"
[id]="expandableNavbarSectionId(section.id)" [id]="expandableNavbarSectionId()"
role="menu" [dsHoverOutsideOfParentSelector]="'#expandable-navbar-section-' + section.id"
class="dropdown-menu show nav-dropdown-menu m-0 shadow-none border-top-0 px-3 px-md-0 pt-0 pt-md-1"> (dsHoverOutside)="deactivateSection($event, false)"
<div *ngFor="let subSection of (subSections$ | async)" class="text-nowrap" role="presentation"> role="menu"
<ng-container class="dropdown-menu show nav-dropdown-menu m-0 shadow-none border-top-0 px-3 px-md-0 pt-0 pt-md-1">
*ngComponentOutlet="(sectionMap$ | async).get(subSection.id).component; injector: (sectionMap$ | async).get(subSection.id).injector;"></ng-container> <div @slide role="presentation">
</div> <div *ngFor="let subSection of (subSections$ | async)" class="text-nowrap" role="presentation">
<ng-container
*ngComponentOutlet="(sectionMap$ | async).get(subSection.id).component; injector: (sectionMap$ | async).get(subSection.id).injector;"></ng-container>
</div>
</div> </div>
</div>
</div> </div>

View File

@@ -1,15 +1,17 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { ComponentFixture, TestBed, waitForAsync, fakeAsync, flush } from '@angular/core/testing';
import { ExpandableNavbarSectionComponent } from './expandable-navbar-section.component'; import { ExpandableNavbarSectionComponent } from './expandable-navbar-section.component';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { MenuServiceStub } from '../../shared/testing/menu-service.stub'; import { MenuServiceStub } from '../../shared/testing/menu-service.stub';
import { Component } from '@angular/core'; import { Component, DebugElement } from '@angular/core';
import { of as observableOf } from 'rxjs'; import { of as observableOf } from 'rxjs';
import { HostWindowService } from '../../shared/host-window.service'; import { HostWindowService } from '../../shared/host-window.service';
import { MenuService } from '../../shared/menu/menu.service'; import { MenuService } from '../../shared/menu/menu.service';
import { LinkMenuItemModel } from '../../shared/menu/menu-item/models/link.model';
import { MenuSection } from '../../shared/menu/menu-section.model';
import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub'; import { HostWindowServiceStub } from '../../shared/testing/host-window-service.stub';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { VarDirective } from '../../shared/utils/var.directive'; import { HoverOutsideDirective } from '../../shared/utils/hover-outside.directive';
describe('ExpandableNavbarSectionComponent', () => { describe('ExpandableNavbarSectionComponent', () => {
let component: ExpandableNavbarSectionComponent; let component: ExpandableNavbarSectionComponent;
@@ -20,18 +22,18 @@ describe('ExpandableNavbarSectionComponent', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [NoopAnimationsModule], imports: [NoopAnimationsModule],
declarations: [ExpandableNavbarSectionComponent, TestComponent, VarDirective], declarations: [
ExpandableNavbarSectionComponent,
HoverOutsideDirective,
TestComponent,
],
providers: [ providers: [
{ provide: 'sectionDataProvider', useValue: {} }, { provide: 'sectionDataProvider', useValue: {} },
{ provide: MenuService, useValue: menuService }, { provide: MenuService, useValue: menuService },
{ provide: HostWindowService, useValue: new HostWindowServiceStub(800) } { provide: HostWindowService, useValue: new HostWindowServiceStub(800) },
] TestComponent,
}).overrideComponent(ExpandableNavbarSectionComponent, { ],
set: { }).compileComponents();
entryComponents: [TestComponent]
}
})
.compileComponents();
})); }));
beforeEach(() => { beforeEach(() => {
@@ -43,10 +45,6 @@ describe('ExpandableNavbarSectionComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should create', () => {
expect(component).toBeTruthy();
});
describe('when the mouse enters the section header (while inactive)', () => { describe('when the mouse enters the section header (while inactive)', () => {
beforeEach(() => { beforeEach(() => {
spyOn(component, 'onMouseEnter').and.callThrough(); spyOn(component, 'onMouseEnter').and.callThrough();
@@ -143,6 +141,8 @@ describe('ExpandableNavbarSectionComponent', () => {
}); });
describe('when spacebar is pressed on section header (while inactive)', () => { describe('when spacebar is pressed on section header (while inactive)', () => {
let sidebarToggler: DebugElement;
beforeEach(() => { beforeEach(() => {
spyOn(component, 'toggleSection').and.callThrough(); spyOn(component, 'toggleSection').and.callThrough();
spyOn(menuService, 'toggleActiveSection'); spyOn(menuService, 'toggleActiveSection');
@@ -151,15 +151,27 @@ describe('ExpandableNavbarSectionComponent', () => {
component.ngOnInit(); component.ngOnInit();
fixture.detectChanges(); fixture.detectChanges();
const sidebarToggler = fixture.debugElement.query(By.css('[data-test="navbar-section-toggler"]')); sidebarToggler = fixture.debugElement.query(By.css('[data-test="navbar-section-toggler"]'));
// dispatch the (keyup.space) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(new KeyboardEvent('keyup', { key: ' ' }));
}); });
it('should call toggleSection on the menuService', () => { it('should call toggleSection on the menuService', () => {
// dispatch the (keyup.space) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(new KeyboardEvent('keyup', { code: 'Space', key: ' ' }));
expect(component.toggleSection).toHaveBeenCalled(); expect(component.toggleSection).toHaveBeenCalled();
expect(menuService.toggleActiveSection).toHaveBeenCalled(); expect(menuService.toggleActiveSection).toHaveBeenCalled();
}); });
// Should not do anything in order to work correctly with NVDA: https://www.nvaccess.org/
it('should not do anything on keydown space', () => {
const event: Event = new KeyboardEvent('keydown', { code: 'Space', key: ' ' });
spyOn(event, 'preventDefault').and.callThrough();
// dispatch the (keyup.space) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(event);
expect(event.preventDefault).toHaveBeenCalled();
});
}); });
describe('when spacebar is pressed on section header (while active)', () => { describe('when spacebar is pressed on section header (while active)', () => {
@@ -181,13 +193,116 @@ describe('ExpandableNavbarSectionComponent', () => {
expect(menuService.toggleActiveSection).toHaveBeenCalled(); expect(menuService.toggleActiveSection).toHaveBeenCalled();
}); });
}); });
describe('when enter is pressed on section header (while inactive)', () => {
let sidebarToggler: DebugElement;
beforeEach(() => {
spyOn(component, 'toggleSection').and.callThrough();
spyOn(menuService, 'toggleActiveSection');
// Make sure section is 'inactive'. Requires calling ngOnInit() to update component 'active' property.
spyOn(menuService, 'isSectionActive').and.returnValue(observableOf(false));
component.ngOnInit();
fixture.detectChanges();
sidebarToggler = fixture.debugElement.query(By.css('[data-test="navbar-section-toggler"]'));
});
// Should not do anything in order to work correctly with NVDA: https://www.nvaccess.org/
it('should not do anything on keydown space', () => {
const event: Event = new KeyboardEvent('keydown', { code: 'Enter' });
spyOn(event, 'preventDefault').and.callThrough();
// dispatch the (keyup.space) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(event);
expect(event.preventDefault).toHaveBeenCalled();
});
});
describe('when arrow down is pressed on section header', () => {
it('should call activateSection', () => {
spyOn(component, 'activateSection').and.callThrough();
const sidebarToggler: DebugElement = fixture.debugElement.query(By.css('[data-test="navbar-section-toggler"]'));
// dispatch the (keydown.ArrowDown) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { code: 'ArrowDown' }));
expect(component.focusOnFirstChildSection).toBe(true);
expect(component.activateSection).toHaveBeenCalled();
});
});
describe('when tab is pressed on section header', () => {
it('should call deactivateSection', () => {
spyOn(component, 'deactivateSection').and.callThrough();
const sidebarToggler: DebugElement = fixture.debugElement.query(By.css('[data-test="navbar-section-toggler"]'));
// dispatch the (keydown.ArrowDown) action used in our component HTML
sidebarToggler.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { code: 'Tab' }));
expect(component.deactivateSection).toHaveBeenCalled();
});
});
describe('navigateDropdown', () => {
beforeEach(fakeAsync(() => {
jasmine.getEnv().allowRespy(true);
spyOn(menuService, 'getSubSectionsByParentID').and.returnValue(observableOf([
Object.assign(new MenuSection(), {
id: 'subSection1',
model: Object.assign(new LinkMenuItemModel(), {
type: 'TEST_LINK',
}),
parentId: component.section.id,
}),
Object.assign(new MenuSection(), {
id: 'subSection2',
model: Object.assign(new LinkMenuItemModel(), {
type: 'TEST_LINK',
}),
parentId: component.section.id,
}),
]));
component.ngOnInit();
flush();
fixture.detectChanges();
component.focusOnFirstChildSection = true;
component.active$.next(true);
fixture.detectChanges();
}));
it('should close the modal on Tab', () => {
spyOn(menuService, 'deactivateSection').and.callThrough();
const firstSubsection: DebugElement = fixture.debugElement.queryAll(By.css('.dropdown-menu a[role="menuitem"]'))[0];
firstSubsection.nativeElement.focus();
firstSubsection.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { code: 'Tab' }));
expect(menuService.deactivateSection).toHaveBeenCalled();
});
it('should close the modal on Escape', () => {
spyOn(menuService, 'deactivateSection').and.callThrough();
const firstSubsection: DebugElement = fixture.debugElement.queryAll(By.css('.dropdown-menu a[role="menuitem"]'))[0];
firstSubsection.nativeElement.focus();
firstSubsection.nativeElement.dispatchEvent(new KeyboardEvent('keydown', { code: 'Escape' }));
expect(menuService.deactivateSection).toHaveBeenCalled();
});
});
}); });
describe('on smaller, mobile screens', () => { describe('on smaller, mobile screens', () => {
beforeEach(waitForAsync(() => { beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [NoopAnimationsModule], imports: [NoopAnimationsModule],
declarations: [ExpandableNavbarSectionComponent, TestComponent, VarDirective], declarations: [
ExpandableNavbarSectionComponent,
HoverOutsideDirective,
TestComponent,
],
providers: [ providers: [
{ provide: 'sectionDataProvider', useValue: {} }, { provide: 'sectionDataProvider', useValue: {} },
{ provide: MenuService, useValue: menuService }, { provide: MenuService, useValue: menuService },
@@ -261,7 +376,9 @@ describe('ExpandableNavbarSectionComponent', () => {
// declare a test component // declare a test component
@Component({ @Component({
selector: 'ds-test-cmp', selector: 'ds-test-cmp',
template: `` template: `
<a role="menuitem">link</a>
`,
}) })
class TestComponent { class TestComponent {
} }

View File

@@ -1,4 +1,4 @@
import { Component, HostListener, Inject, Injector, OnInit } from '@angular/core'; import { Component, HostListener, Inject, Injector, OnInit, AfterViewChecked, OnDestroy } from '@angular/core';
import { NavbarSectionComponent } from '../navbar-section/navbar-section.component'; import { NavbarSectionComponent } from '../navbar-section/navbar-section.component';
import { MenuService } from '../../shared/menu/menu.service'; import { MenuService } from '../../shared/menu/menu.service';
import { slide } from '../../shared/animations/slide'; import { slide } from '../../shared/animations/slide';
@@ -6,6 +6,7 @@ import { first } from 'rxjs/operators';
import { HostWindowService } from '../../shared/host-window.service'; import { HostWindowService } from '../../shared/host-window.service';
import { MenuID } from '../../shared/menu/menu-id.model'; import { MenuID } from '../../shared/menu/menu-id.model';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { MenuSection } from '../../shared/menu/menu-section.model';
/** /**
* Represents an expandable section in the navbar * Represents an expandable section in the navbar
@@ -16,7 +17,8 @@ import { Observable } from 'rxjs';
styleUrls: ['./expandable-navbar-section.component.scss'], styleUrls: ['./expandable-navbar-section.component.scss'],
animations: [slide] animations: [slide]
}) })
export class ExpandableNavbarSectionComponent extends NavbarSectionComponent implements OnInit { export class ExpandableNavbarSectionComponent extends NavbarSectionComponent implements AfterViewChecked, OnInit, OnDestroy {
/** /**
* This section resides in the Public Navbar * This section resides in the Public Navbar
*/ */
@@ -27,6 +29,11 @@ export class ExpandableNavbarSectionComponent extends NavbarSectionComponent imp
*/ */
mouseEntered = false; mouseEntered = false;
/**
* Whether the section was expanded
*/
focusOnFirstChildSection = false;
/** /**
* True if screen size was small before a resize event * True if screen size was small before a resize event
*/ */
@@ -37,6 +44,18 @@ export class ExpandableNavbarSectionComponent extends NavbarSectionComponent imp
*/ */
isMobile$: Observable<boolean>; isMobile$: Observable<boolean>;
/**
* Boolean used to add the event listeners to the items in the expandable menu when expanded. This is done for
* performance reasons, there is currently an *ngIf on the menu to prevent the {@link HoverOutsideDirective} to tank
* performance when not expanded.
*/
addArrowEventListeners = false;
/**
* List of current dropdown items who have event listeners
*/
private dropdownItems: NodeListOf<HTMLElement>;
@HostListener('window:resize', ['$event']) @HostListener('window:resize', ['$event'])
onResize() { onResize() {
this.isMobile$.pipe( this.isMobile$.pipe(
@@ -51,29 +70,80 @@ export class ExpandableNavbarSectionComponent extends NavbarSectionComponent imp
}); });
} }
constructor(@Inject('sectionDataProvider') menuSection, constructor(
protected menuService: MenuService, @Inject('sectionDataProvider') public section: MenuSection,
protected injector: Injector, protected menuService: MenuService,
private windowService: HostWindowService protected injector: Injector,
protected windowService: HostWindowService,
) { ) {
super(menuSection, menuService, injector); super(section, menuService, injector);
this.isMobile$ = this.windowService.isMobile(); this.isMobile$ = this.windowService.isMobile();
} }
ngOnInit() { ngOnInit() {
super.ngOnInit(); super.ngOnInit();
this.subs.push(this.active$.subscribe((active: boolean) => {
if (active === true) {
this.addArrowEventListeners = true;
} else {
this.focusOnFirstChildSection = undefined;
this.unsubscribeFromEventListeners();
}
}));
}
ngAfterViewChecked(): void {
if (this.addArrowEventListeners) {
this.dropdownItems = document.querySelectorAll(`#${this.expandableNavbarSectionId()} *[role="menuitem"]`);
this.dropdownItems.forEach((item: HTMLElement) => {
item.addEventListener('keydown', this.navigateDropdown.bind(this));
});
if (this.focusOnFirstChildSection && this.dropdownItems.length > 0) {
this.dropdownItems.item(0).focus();
}
this.addArrowEventListeners = false;
}
}
ngOnDestroy(): void {
super.ngOnDestroy();
this.unsubscribeFromEventListeners();
}
/**
* Activate this section if it's currently inactive, deactivate it when it's currently active.
* Also saves whether this toggle was performed by a keyboard event (non-click event) in order to know if thi first
* item should be focussed when activating a section.
*
* @param {Event} event The user event that triggered this method
*/
override toggleSection(event: Event): void {
this.focusOnFirstChildSection = event.type !== 'click';
super.toggleSection(event);
}
/**
* Removes all the current event listeners on the dropdown items (called when the menu is closed & on component
* destruction)
*/
unsubscribeFromEventListeners(): void {
if (this.dropdownItems) {
this.dropdownItems.forEach((item: HTMLElement) => {
item.removeEventListener('keydown', this.navigateDropdown.bind(this));
});
this.dropdownItems = undefined;
}
} }
/** /**
* When the mouse enters the section toggler activate the menu section * When the mouse enters the section toggler activate the menu section
* @param $event * @param $event
* @param isActive
*/ */
onMouseEnter($event: Event, isActive: boolean) { onMouseEnter($event: Event): void {
this.isMobile$.pipe( this.isMobile$.pipe(
first() first()
).subscribe((isMobile) => { ).subscribe((isMobile) => {
if (!isMobile && !isActive && !this.mouseEntered) { if (!isMobile && !this.active$.value && !this.mouseEntered) {
this.activateSection($event); this.activateSection($event);
} }
this.mouseEntered = true; this.mouseEntered = true;
@@ -83,13 +153,12 @@ export class ExpandableNavbarSectionComponent extends NavbarSectionComponent imp
/** /**
* When the mouse leaves the section toggler deactivate the menu section * When the mouse leaves the section toggler deactivate the menu section
* @param $event * @param $event
* @param isActive
*/ */
onMouseLeave($event: Event, isActive: boolean) { onMouseLeave($event: Event): void {
this.isMobile$.pipe( this.isMobile$.pipe(
first() first()
).subscribe((isMobile) => { ).subscribe((isMobile) => {
if (!isMobile && isActive && this.mouseEntered) { if (!isMobile && this.active$.value && this.mouseEntered) {
this.deactivateSection($event); this.deactivateSection($event);
} }
this.mouseEntered = false; this.mouseEntered = false;
@@ -98,9 +167,60 @@ export class ExpandableNavbarSectionComponent extends NavbarSectionComponent imp
/** /**
* returns the ID of the DOM element representing the navbar section * returns the ID of the DOM element representing the navbar section
* @param sectionId
*/ */
expandableNavbarSectionId(sectionId: string) { expandableNavbarSectionId(): string {
return `expandable-navbar-section-${sectionId}-dropdown`; return `expandable-navbar-section-${this.section.id}-dropdown`;
}
/**
* Handles the navigation between the menu items
*
* @param event
*/
navigateDropdown(event: KeyboardEvent): void {
if (event.code === 'Tab') {
this.deactivateSection(event, false);
return;
} else if (event.code === 'Escape') {
this.deactivateSection(event, false);
(document.querySelector(`a[aria-controls="${this.expandableNavbarSectionId()}"]`) as HTMLElement)?.focus();
return;
}
event.preventDefault();
event.stopPropagation();
const items: NodeListOf<Element> = document.querySelectorAll(`#${this.expandableNavbarSectionId()} *[role="menuitem"]`);
if (items.length === 0) {
return;
}
const currentIndex: number = Array.from(items).findIndex((item: Element) => item === event.target);
if (event.key === 'ArrowDown') {
(items[(currentIndex + 1) % items.length] as HTMLElement).focus();
} else if (event.key === 'ArrowUp') {
(items[(currentIndex - 1 + items.length) % items.length] as HTMLElement).focus();
}
}
/**
* Handles all the keydown events on the dropdown toggle
*
* @param event
*/
keyDown(event: KeyboardEvent): void {
switch (event.code) {
// Works for both Tab & Shift Tab
case 'Tab':
this.deactivateSection(event, false);
break;
case 'ArrowDown':
this.focusOnFirstChildSection = true;
this.activateSection(event);
break;
case 'Space':
case 'Enter':
event.preventDefault();
break;
}
} }
} }

View File

@@ -13,6 +13,7 @@ import { MenuModule } from '../shared/menu/menu.module';
import { SharedModule } from '../shared/shared.module'; import { SharedModule } from '../shared/shared.module';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { ThemedNavbarComponent } from './themed-navbar.component'; import { ThemedNavbarComponent } from './themed-navbar.component';
import { HoverOutsideDirective } from '../shared/utils/hover-outside.directive';
const effects = [ const effects = [
NavbarEffects NavbarEffects
@@ -25,6 +26,10 @@ const ENTRY_COMPONENTS = [
ThemedExpandableNavbarSectionComponent, ThemedExpandableNavbarSectionComponent,
]; ];
const DIRECTIVES = [
HoverOutsideDirective,
];
@NgModule({ @NgModule({
imports: [ imports: [
CommonModule, CommonModule,
@@ -35,12 +40,14 @@ const ENTRY_COMPONENTS = [
CoreModule.forRoot() CoreModule.forRoot()
], ],
declarations: [ declarations: [
...DIRECTIVES,
...ENTRY_COMPONENTS, ...ENTRY_COMPONENTS,
NavbarComponent, NavbarComponent,
ThemedNavbarComponent, ThemedNavbarComponent,
], ],
providers: [], providers: [],
exports: [ exports: [
...DIRECTIVES,
ThemedNavbarComponent, ThemedNavbarComponent,
NavbarSectionComponent, NavbarSectionComponent,
ThemedExpandableNavbarSectionComponent ThemedExpandableNavbarSectionComponent

View File

@@ -20,9 +20,9 @@ import { MenuItemType } from '../menu-item-type.model';
export class MenuSectionComponent implements OnInit, OnDestroy { export class MenuSectionComponent implements OnInit, OnDestroy {
/** /**
* Observable that emits whether or not this section is currently active * {@link BehaviorSubject} containing the current state to whether this section is currently active
*/ */
active: Observable<boolean>; active$: BehaviorSubject<boolean> = new BehaviorSubject(false);
/** /**
* The ID of the menu this section resides in * The ID of the menu this section resides in
@@ -55,7 +55,11 @@ export class MenuSectionComponent implements OnInit, OnDestroy {
* Set initial values for instance variables * Set initial values for instance variables
*/ */
ngOnInit(): void { ngOnInit(): void {
this.active = this.menuService.isSectionActive(this.menuID, this.section.id).pipe(distinctUntilChanged()); this.subs.push(this.menuService.isSectionActive(this.menuID, this.section.id).pipe(distinctUntilChanged()).subscribe((isActive: boolean) => {
if (this.active$.value !== isActive) {
this.active$.next(isActive);
}
}));
this.initializeInjectorData(); this.initializeInjectorData();
} }
@@ -73,9 +77,12 @@ export class MenuSectionComponent implements OnInit, OnDestroy {
/** /**
* Activate this section * Activate this section
* @param {Event} event The user event that triggered this method * @param {Event} event The user event that triggered this method
* @param skipEvent Weather the event should still be triggered after deactivating the section or not
*/ */
activateSection(event: Event) { activateSection(event: Event, skipEvent = true): void {
event.preventDefault(); if (skipEvent) {
event.preventDefault();
}
if (!this.section.model?.disabled) { if (!this.section.model?.disabled) {
this.menuService.activateSection(this.menuID, this.section.id); this.menuService.activateSection(this.menuID, this.section.id);
} }
@@ -83,10 +90,14 @@ export class MenuSectionComponent implements OnInit, OnDestroy {
/** /**
* Deactivate this section * Deactivate this section
*
* @param {Event} event The user event that triggered this method * @param {Event} event The user event that triggered this method
* @param skipEvent Weather the event should still be triggered after deactivating the section or not
*/ */
deactivateSection(event: Event) { deactivateSection(event: Event, skipEvent = true): void {
event.preventDefault(); if (skipEvent) {
event.preventDefault();
}
this.menuService.deactivateSection(this.menuID, this.section.id); this.menuService.deactivateSection(this.menuID, this.section.id);
} }

View File

@@ -0,0 +1,52 @@
import {
Directive,
ElementRef,
EventEmitter,
HostListener,
Input,
Output,
} from '@angular/core';
/**
* Directive to detect when the user hovers outside the element the directive was put on
*
* **Performance Consideration**: it's probably not good for performance to use this excessively (on
* {@link ExpandableNavbarSectionComponent} for example, a workaround for this problem was to add an `*ngIf` to prevent
* this Directive from always being active)
*/
@Directive({
selector: '[dsHoverOutside]',
})
export class HoverOutsideDirective {
/**
* Emits null when the user hovers outside of the element
*/
@Output()
public dsHoverOutside = new EventEmitter();
/**
* CSS selector for the parent element to monitor. If set, the directive will use this
* selector to determine if the hover event originated within the selected parent element.
* If left unset, the directive will monitor mouseover hover events for the element it is applied to.
*/
@Input()
public dsHoverOutsideOfParentSelector: string;
constructor(
private elementRef: ElementRef,
) {
}
@HostListener('document:mouseover', ['$event'])
public onMouseOver(event: MouseEvent): void {
const targetElement: HTMLElement = event.target as HTMLElement;
const element: Element = document.querySelector(this.dsHoverOutsideOfParentSelector);
const hoveredInside = (element ? new ElementRef(element) : this.elementRef).nativeElement.contains(targetElement);
if (!hoveredInside) {
this.dsHoverOutside.emit(null);
}
}
}