Skip to content

Commit

Permalink
feat(navigation-class-handler): new utility to add/remove a css class…
Browse files Browse the repository at this point in the history
… on the body while navigating
  • Loading branch information
simonmumenthaler committed Jan 23, 2024
1 parent 40cd715 commit 6dd1466
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions libs/components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@angular/common": "^16.0.0",
"@angular/core": "^16.0.0",
"@angular/forms": "^16.0.0",
"@angular/router": "^16.0.0",
"@shiftcode/ngx-core": "^4.0.0 || ^4.0.0-pr18",
"rxjs": "^7.5.0"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { DOCUMENT } from '@angular/common'
import { APP_INITIALIZER, EnvironmentProviders, makeEnvironmentProviders } from '@angular/core'
import { NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router } from '@angular/router'
import { delay, filter, switchMap, take, tap } from 'rxjs'

function provideNavigationClassHandlerFactory(
this: undefined,
className: string,
doc: Document,
router: Router,
): () => Promise<void> {
return () => {
const navigationEnd$ = router.events.pipe(
filter((ev) => ev instanceof NavigationEnd || ev instanceof NavigationCancel || ev instanceof NavigationError),
)

router.events
.pipe(
filter((e) => e instanceof NavigationStart),
tap(() => doc.body.classList.add(className)),
switchMap(() => navigationEnd$.pipe(take(1), delay(0))),
tap(() => doc.body.classList.remove(className)),
)
.subscribe()

// since we provide the factory as `APP_INITIALIZER` to get called, we need to return a promise
return Promise.resolve()
}
}

/**
* sets up a handler which adds the provided css class to the document#body while angular router is navigating
*/
export function provideNavigationClassHandler(className: string): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: APP_INITIALIZER,
multi: true,
useFactory: provideNavigationClassHandlerFactory.bind(void 0, className),
deps: [DOCUMENT, Router],
},
])
}
3 changes: 3 additions & 0 deletions libs/components/src/public-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export * from './lib/tooltip/tooltip-default-options.token'
// insert-view-ref
export * from './lib/insert-view-ref/insert-view-ref.directive'

// navigation-class-handler
export * from './lib/navigation-class-handler/navigation-class-handler'

// rx
export * from './lib/rx/rx-if.directive'
export * from './lib/rx/rx-let.directive'
Expand Down

0 comments on commit 6dd1466

Please sign in to comment.