Skip to content

Commit

Permalink
Add support for an onDocChange option to query abort handlers
Browse files Browse the repository at this point in the history
FEATURE: When registering an `abort` handler for a completion query, you can now use
the `onDocChange` option to indicate that your query should be aborted as soon as the
document changes while it is running.

See https://discuss.codemirror.net/t/debounce-completionsource-individually/8431
  • Loading branch information
marijnh committed Jul 16, 2024
1 parent 2ef51c4 commit a6ba03d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export interface CompletionSection {
export class CompletionContext {
/// @internal
abortListeners: (() => void)[] | null = []
/// @internal
abortOnDocChange = false

/// Create a new completion context. (Mostly useful for testing
/// completion sources—in the editor, the extension will create
Expand Down Expand Up @@ -132,8 +134,19 @@ export class CompletionContext {
/// Allows you to register abort handlers, which will be called when
/// the query is
/// [aborted](#autocomplete.CompletionContext.aborted).
addEventListener(type: "abort", listener: () => void) {
if (type == "abort" && this.abortListeners) this.abortListeners.push(listener)
///
/// By default, running queries will not be aborted for regular
/// typing or backspacing, on the assumption that they are likely to
/// return a result with a
/// [`validFor`](#autocomplete.CompletionResult.validFor) field that
/// allows the result to be used after all. Passing `onDocChange:
/// true` will cause this query to be aborted for any document
/// change.
addEventListener(type: "abort", listener: () => void, options?: {onDocChange: boolean}) {
if (type == "abort" && this.abortListeners) {
this.abortListeners.push(listener)
if (options && options.onDocChange) this.abortOnDocChange = true
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const completionPlugin = ViewPlugin.fromClass(class implements PluginValu
for (let i = 0; i < this.running.length; i++) {
let query = this.running[i]
if (doesReset ||
query.context.abortOnDocChange && update.docChanged ||
query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
for (let handler of query.context.abortListeners!) {
try { handler() }
Expand Down

0 comments on commit a6ba03d

Please sign in to comment.