Skip to content

Commit

Permalink
feat(navigation): implement keyboard shortcuts for navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
pascaliske committed Jul 25, 2023
1 parent a0c52dd commit 56bd42c
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/app/components/navigation/navigation.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Component, OnInit, DestroyRef, inject } from '@angular/core'
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'
import { NgFor, NgIf, AsyncPipe } from '@angular/common'
import { RouterLink, RouterLinkActive, Router, NavigationEnd } from '@angular/router'
import { Observable, timer } from 'rxjs'
import { Observable, fromEvent, timer } from 'rxjs'
import { filter, map } from 'rxjs/operators'
import { BrowserApiService } from 'shared/browser-api/browser-api.service'
import { ThemeService } from 'shared/theme/theme.service'
Expand Down Expand Up @@ -75,6 +75,7 @@ export class NavigationComponent implements OnInit {

public ngOnInit(): void {
this.watchNavigationEnd()
this.watchKeyboard()
}

public toggle(): void {
Expand Down Expand Up @@ -119,6 +120,32 @@ export class NavigationComponent implements OnInit {
})
}

private watchKeyboard(): void {
this.browserApiService.with('document', document => {
fromEvent<KeyboardEvent>(document, 'keypress')
.pipe(takeUntilDestroyed(this.destroy))
.subscribe((event: KeyboardEvent) => {
// toggle mobile navigation
if (event.key === 'm' && this.isMobile) {
this.toggle()
return
}

// toggle color scheme
if (event.key === 't') {
this.themeService.next()
return
}

// go to page
const link: NavigationLink = this.links?.[parseInt(event.key ?? '', 10) - 1]
if (link && (!this.isMobile || this.isOpen)) {
this.router.navigate([link.target]).catch(() => {})
}
})
})
}

public get icon(): 'menu' | 'close' {
if (this.state === NavigationState.CLOSED || this.state === NavigationState.FADE_OUT) {
return 'close'
Expand Down

0 comments on commit 56bd42c

Please sign in to comment.