Skip to content

Commit

Permalink
add support for global graph listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
krisl committed Jul 30, 2023
1 parent d6658b7 commit f1ddc60
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,31 @@ describe('Components', () => {
})
})

describe('Listeners', () => {
test('smoke', () => {
let listenCallbackCounter = 0
const creator = new Graferse()
creator.addListener(() => { listenCallbackCounter++ })

// no one has been called yet
expect(listenCallbackCounter).toEqual(0)

// clearAllLocks invokes listeners
creator.clearAllLocks("test")
expect(listenCallbackCounter).toEqual(1)

// notifyWaiters invokes listeners
creator.notifyWaiters(new Set())
expect(listenCallbackCounter).toEqual(2)

// recursive calling of notifyWaiters
creator.lastCallCache.set("agent1", () => creator.notifyWaiters(new Set()))
creator.notifyWaiters(new Set(["agent1"]))
// listener is invoked once for each agent
expect(listenCallbackCounter).toEqual(4)
})
})

describe('Exceptions', () => {
test('node not on path', () => {
const getLockForLink = (from: Lock, to: Lock) => {
Expand Down
12 changes: 12 additions & 0 deletions src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ class Graferse
linkLocks: LinkLock[] = []
lockGroups: Lock[][] = []
lastCallCache = new Map<string,() => void>()
listeners: Array<() => void> = []

makeLock() {
const lock = new Lock()
Expand All @@ -144,6 +145,16 @@ class Graferse
return linkLock
}

addListener(listener: () => void) {
this.listeners.push(listener)
}

notifyListeners() {
for (const listener of this.listeners) {
listener()
}
}

notifyWaiters(whoCanMoveNow: Set<string>) {
for (const waiter of whoCanMoveNow) {
const lastCall = this.lastCallCache.get(waiter)
Expand All @@ -152,6 +163,7 @@ class Graferse
}
lastCall()
}
this.notifyListeners()
}

clearAllLocks(byWhom: string) {
Expand Down

0 comments on commit f1ddc60

Please sign in to comment.