-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(terminal): add cancel logic when user close terminal
- Loading branch information
Showing
2 changed files
with
74 additions
and
8 deletions.
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
packages/extensions/js-runner-and-debugger/src/web/utils/cancel-manager.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
type CancelHandler = () => void; | ||
|
||
class CancelSignal { | ||
private _cancelled: boolean = false; | ||
private _handlers: CancelHandler[] = []; | ||
|
||
get cancelled(): boolean { | ||
return this._cancelled; | ||
} | ||
|
||
addEventListener(type: 'cancel', handler: CancelHandler) { | ||
if (type === 'cancel') { | ||
this._handlers.push(handler); | ||
} | ||
} | ||
|
||
removeEventListener(type: 'cancel', handler: CancelHandler) { | ||
if (type === 'cancel') { | ||
this._handlers = this._handlers.filter(h => h !== handler); | ||
} | ||
} | ||
|
||
dispatchEvent(type: 'cancel') { | ||
if (type === 'cancel' && !this._cancelled) { | ||
this._cancelled = true; | ||
this._handlers.forEach(handler => handler()); | ||
} | ||
} | ||
} | ||
|
||
export class CancelManager { | ||
private _signal: CancelSignal; | ||
|
||
constructor() { | ||
this._signal = new CancelSignal(); | ||
} | ||
|
||
get signal(): CancelSignal { | ||
return this._signal; | ||
} | ||
|
||
async runCancellable<T>(promise: Promise<T>): Promise<T> { | ||
return new Promise<T>((resolve, reject) => { | ||
this._signal.addEventListener('cancel', () => | ||
reject(new Error('Operation cancelled')) | ||
); | ||
promise.then(resolve).catch(reject); | ||
}); | ||
} | ||
|
||
cancel() { | ||
this._signal.dispatchEvent('cancel'); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters