mirror of
https://github.com/wavetermdev/waveterm.git
synced 2024-12-21 16:38:23 +01:00
936d4bfb30
This migrates all remaining eventbus events sent over the websocket to use the wps interface. WPS is more flexible for registering events and callbacks and provides support for more reliable unsubscribes and resubscribes.
68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
// Copyright 2024, Command Line Inc.
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package wshutil
|
|
|
|
import (
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/wavetermdev/waveterm/pkg/wps"
|
|
)
|
|
|
|
// event inverter. converts WaveEvents to a listener.On() API
|
|
|
|
type singleListener struct {
|
|
Id string
|
|
Fn func(*wps.WaveEvent)
|
|
}
|
|
|
|
type EventListener struct {
|
|
Lock *sync.Mutex
|
|
Listeners map[string][]singleListener
|
|
}
|
|
|
|
func MakeEventListener() *EventListener {
|
|
return &EventListener{
|
|
Lock: &sync.Mutex{},
|
|
Listeners: make(map[string][]singleListener),
|
|
}
|
|
}
|
|
|
|
func (el *EventListener) On(eventName string, fn func(*wps.WaveEvent)) string {
|
|
id := uuid.New().String()
|
|
el.Lock.Lock()
|
|
defer el.Lock.Unlock()
|
|
larr := el.Listeners[eventName]
|
|
larr = append(larr, singleListener{Id: id, Fn: fn})
|
|
el.Listeners[eventName] = larr
|
|
return id
|
|
}
|
|
|
|
func (el *EventListener) Unregister(eventName string, id string) {
|
|
el.Lock.Lock()
|
|
defer el.Lock.Unlock()
|
|
larr := el.Listeners[eventName]
|
|
newArr := make([]singleListener, 0)
|
|
for _, sl := range larr {
|
|
if sl.Id == id {
|
|
continue
|
|
}
|
|
newArr = append(newArr, sl)
|
|
}
|
|
el.Listeners[eventName] = newArr
|
|
}
|
|
|
|
func (el *EventListener) getListeners(eventName string) []singleListener {
|
|
el.Lock.Lock()
|
|
defer el.Lock.Unlock()
|
|
return el.Listeners[eventName]
|
|
}
|
|
|
|
func (el *EventListener) RecvEvent(e *wps.WaveEvent) {
|
|
larr := el.getListeners(e.Event)
|
|
for _, sl := range larr {
|
|
sl.Fn(e)
|
|
}
|
|
}
|