Skip to content
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
2 changes: 2 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,7 @@ declare module '@lightningjs/blits' {
export interface RouterHooks {
init?: () => Promise<> | void;
beforeEach?: (to: Route, from: Route) => string | Route | Promise<string | Route> | void;
afterEach?: (to: Route, toComponent: ComponentBase, from: Route, fromComponent: ComponentBase) => string | Route | Promise<string | Route> | void;
error?: (err: string) => string | Route | Promise<string | Route> | void;
}

Expand Down Expand Up @@ -749,6 +750,7 @@ declare module '@lightningjs/blits' {

export interface RouteHooks {
before?: (to: Route, from: Route) => string | Route | Promise<string | Route>;
after?: (to: Route, toComponent: ComponentBase, from: Route, fromComponent: ComponentBase) => string | Route | Promise<string | Route>;
}

export type Route = {
Expand Down
36 changes: 36 additions & 0 deletions src/router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ export const navigate = async function () {
return
}
}

// add the previous route (technically still the current route at this point)
// into the history stack when inHistory is true and we're not navigating back
if (
Expand Down Expand Up @@ -459,6 +460,41 @@ export const navigate = async function () {
const children = this[symbols.children]
this.activeView = children[children.length - 1]

if (this.parent[symbols.routerHooks]) {
const hooks = this.parent[symbols.routerHooks]
if (hooks.afterEach) {
try {
// Get the previous view before it's removed
const previousView =
!reuse && children.length > 1 ? children[children.length - 2] : null

await hooks.afterEach.call(this.parent, {
to: route,
toComponent: view,
from: previousRoute,
fromComponent: previousView,
})
} catch (error) {
Log.error('Error in "AfterEach" Hook', error)
}
}
}

if (route.hooks.after) {
try {
// Get the previous view before it's removed
const previousView = !reuse && children.length > 1 ? children[children.length - 2] : null
await route.hooks.after.call(this.parent, {
to: route,
toComponent: view,
from: previousRoute,
fromComponent: previousView,
})
} catch (error) {
Log.error('Error or Rejected Promise in "After" Hook', error)
}
}

// set focus to the view that we're routing to (unless explicitly disabling passing focus)
if (route.options.passFocus !== false) {
focus ? focus.$focus() : /** @type {BlitsComponent} */ (view).$focus()
Expand Down