it('saves forward information', () => {})
it('can replace a location', () => {})
+
it('can simulate a navigation', () => {})
it('add entries to the queue', () => {
expect(history.queue).toHaveLength(2)
expect(history.location).toEqual(normaliezedLoc2)
})
+
+ it('can listen to navigations', () => {
+ const history = new AbstractHistory()
+ const spy = jest.fn()
+ history.listen(spy)
+ history.push(loc)
+ history.back()
+ expect(spy).toHaveBeenCalledTimes(1)
+ expect(spy).toHaveBeenCalledWith(START, normaliezedLoc, { type: 'back' })
+ history.forward()
+ expect(spy).toHaveBeenCalledTimes(2)
+ expect(spy).toHaveBeenLastCalledWith(normaliezedLoc, START, {
+ type: 'forward',
+ })
+ })
+
+ it('can stop listening to navigation', () => {
+ const history = new AbstractHistory()
+ const spy = jest.fn()
+ const spy2 = jest.fn()
+ // remove right away
+ history.listen(spy)()
+ const remove = history.listen(spy2)
+ history.push(loc)
+ history.back()
+ expect(spy).not.toHaveBeenCalled()
+ expect(spy2).toHaveBeenCalledTimes(1)
+ remove()
+ history.forward()
+ expect(spy).not.toHaveBeenCalled()
+ expect(spy2).toHaveBeenCalledTimes(1)
+ })
})
// import consola from 'consola'
-import { BaseHistory, HistoryLocation, HistoryLocationNormalized } from './base'
+import {
+ BaseHistory,
+ HistoryLocation,
+ HistoryLocationNormalized,
+ NavigationType,
+} from './base'
import { NavigationCallback, HistoryState, START } from './base'
// const cs = consola.withTag('abstract')
export class AbstractHistory extends BaseHistory {
// private _listeners: NavigationCallback[] = []
private teardowns: Array<() => void> = []
+ private listeners: NavigationCallback[] = []
public queue: HistoryLocationNormalized[] = [START]
public position: number = 0
}
listen(callback: NavigationCallback) {
- return () => {}
+ this.listeners.push(callback)
+ return () => {
+ const index = this.listeners.indexOf(callback)
+ if (index > -1) this.listeners.splice(index, 1)
+ }
}
get location() {
}
back() {
+ const from = this.location
if (this.position > 0) this.position--
+ this.triggerListeners(this.location, from, { type: NavigationType.back })
}
forward() {
+ const from = this.location
if (this.position < this.queue.length - 1) this.position++
+ this.triggerListeners(this.location, from, { type: NavigationType.forward })
}
destroy() {
for (const teardown of this.teardowns) teardown()
this.teardowns = []
}
+
+ private triggerListeners(
+ to: HistoryLocationNormalized,
+ from: HistoryLocationNormalized,
+ { type }: { type: NavigationType }
+ ): void {
+ const info = { type }
+ for (let callback of this.listeners) {
+ callback(to, from, info)
+ }
+ }
}