lsp_events.go

 1package app
 2
 3import (
 4	"context"
 5	"maps"
 6	"time"
 7
 8	"github.com/charmbracelet/crush/internal/lsp"
 9	"github.com/charmbracelet/crush/internal/proto"
10	"github.com/charmbracelet/crush/internal/pubsub"
11)
12
13type (
14	LSPClientInfo = proto.LSPClientInfo
15	LSPEvent      = proto.LSPEvent
16)
17
18const (
19	LSPEventStateChanged       = proto.LSPEventStateChanged
20	LSPEventDiagnosticsChanged = proto.LSPEventDiagnosticsChanged
21)
22
23// SubscribeLSPEvents returns a channel for LSP events
24func (a *App) SubscribeLSPEvents(ctx context.Context) <-chan pubsub.Event[LSPEvent] {
25	return a.lspBroker.Subscribe(ctx)
26}
27
28// GetLSPStates returns the current state of all LSP clients
29func (a *App) GetLSPStates() map[string]LSPClientInfo {
30	return maps.Collect(a.lspStates.Seq2())
31}
32
33// GetLSPState returns the state of a specific LSP client
34func (a *App) GetLSPState(name string) (LSPClientInfo, bool) {
35	return a.lspStates.Get(name)
36}
37
38// updateLSPState updates the state of an LSP client and publishes an event
39func (a *App) updateLSPState(name string, state lsp.ServerState, err error, diagnosticCount int) {
40	info := LSPClientInfo{
41		Name:            name,
42		State:           state,
43		Error:           err,
44		DiagnosticCount: diagnosticCount,
45	}
46	if state == lsp.StateReady {
47		info.ConnectedAt = time.Now()
48	}
49	a.lspStates.Set(name, info)
50
51	// Publish state change event
52	a.lspBroker.Publish(pubsub.UpdatedEvent, LSPEvent{
53		Type:            LSPEventStateChanged,
54		Name:            name,
55		State:           state,
56		Error:           err,
57		DiagnosticCount: diagnosticCount,
58	})
59}
60
61// updateLSPDiagnostics updates the diagnostic count for an LSP client and publishes an event
62func (a *App) updateLSPDiagnostics(name string, diagnosticCount int) {
63	if info, exists := a.lspStates.Get(name); exists {
64		info.DiagnosticCount = diagnosticCount
65		a.lspStates.Set(name, info)
66
67		// Publish diagnostics change event
68		a.lspBroker.Publish(pubsub.UpdatedEvent, LSPEvent{
69			Type:            LSPEventDiagnosticsChanged,
70			Name:            name,
71			State:           info.State,
72			Error:           info.Error,
73			DiagnosticCount: diagnosticCount,
74		})
75	}
76}