88 StateEffect ,
99 StateField ,
1010} from "@codemirror/state" ;
11- import type { EditorView } from "@codemirror/view" ;
11+ import { type EditorView , ViewPlugin } from "@codemirror/view" ;
1212import type {
1313 LSPClientWithWorkspace ,
1414 LSPPluginAPI ,
@@ -18,7 +18,8 @@ import type {
1818} from "./types" ;
1919
2020const setPublishedDiagnostics = StateEffect . define < LspDiagnostic [ ] > ( ) ;
21- let diagnosticsEventTimer = 0 ;
21+ let diagnosticsEventTimer : ReturnType < typeof setTimeout > | null = null ;
22+ let diagnosticsViewCount = 0 ;
2223
2324export const LSP_DIAGNOSTICS_EVENT = "acode:lsp-diagnostics-updated" ;
2425
@@ -67,6 +68,12 @@ function emitDiagnosticsUpdated(): void {
6768 document . dispatchEvent ( event ) ;
6869}
6970
71+ function clearScheduledDiagnosticsUpdated ( ) : void {
72+ if ( diagnosticsEventTimer == null ) return ;
73+ clearTimeout ( diagnosticsEventTimer ) ;
74+ diagnosticsEventTimer = null ;
75+ }
76+
7077const lspPublishedDiagnostics = StateField . define < LspDiagnostic [ ] > ( {
7178 create ( ) : LspDiagnostic [ ] {
7279 return [ ] ;
@@ -164,13 +171,30 @@ function sameDiagnostics(
164171}
165172
166173function scheduleDiagnosticsUpdated ( ) : void {
167- if ( diagnosticsEventTimer ) return ;
168- diagnosticsEventTimer = window . setTimeout ( ( ) => {
169- diagnosticsEventTimer = 0 ;
170- emitDiagnosticsUpdated ( ) ;
174+ if ( diagnosticsEventTimer != null ) return ;
175+ diagnosticsEventTimer = setTimeout ( ( ) => {
176+ diagnosticsEventTimer = null ;
177+ if ( diagnosticsViewCount > 0 ) {
178+ emitDiagnosticsUpdated ( ) ;
179+ }
171180 } , 32 ) ;
172181}
173182
183+ const diagnosticsLifecyclePlugin = ViewPlugin . fromClass (
184+ class {
185+ constructor ( ) {
186+ diagnosticsViewCount ++ ;
187+ }
188+
189+ destroy ( ) : void {
190+ diagnosticsViewCount = Math . max ( 0 , diagnosticsViewCount - 1 ) ;
191+ if ( ! diagnosticsViewCount ) {
192+ clearScheduledDiagnosticsUpdated ( ) ;
193+ }
194+ }
195+ } ,
196+ ) ;
197+
174198function mapDiagnostics (
175199 plugin : LSPPluginAPI ,
176200 state : EditorState ,
@@ -262,6 +286,7 @@ export function lspDiagnosticsUiExtension(includeGutter = true): Extension[] {
262286 ? ( ) => [ ]
263287 : undefined ;
264288 const extensions : Extension [ ] = [
289+ diagnosticsLifecyclePlugin ,
265290 lspPublishedDiagnostics ,
266291 linter ( lspLinterSource , {
267292 needsRefresh ( update ) {
0 commit comments