mana-common
Version:
Common utils for mana
111 lines (92 loc) • 2.7 kB
JavaScript
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation and others. All rights reserved.
* Licensed under the MIT License. See https://github.com/Microsoft/vscode/blob/master/LICENSE.txt for license information.
*--------------------------------------------------------------------------------------------*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Event, Emitter } from './event'; // eslint-disable-next-line @typescript-eslint/no-explicit-any
const shortcutEvent = Object.freeze(Object.assign(function (callback, context) {
const handle = setTimeout(callback.bind(context), 0);
return {
dispose() {
clearTimeout(handle);
}
};
}, {
maxListeners: 0
}));
export var CancellationToken;
(function (CancellationToken) {
CancellationToken.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: Event.None
});
CancellationToken.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: shortcutEvent
});
})(CancellationToken || (CancellationToken = {}));
class MutableToken {
constructor() {
this._isCancelled = false;
this._emitter = void 0;
}
cancel() {
if (!this._isCancelled) {
this._isCancelled = true;
if (this._emitter) {
this._emitter.fire(undefined);
this._emitter = undefined;
}
}
}
get isCancellationRequested() {
return this._isCancelled;
}
get onCancellationRequested() {
if (this._isCancelled) {
return shortcutEvent;
}
if (!this._emitter) {
this._emitter = new Emitter();
}
return this._emitter.event;
}
}
export class CancellationTokenSource {
constructor() {
this._token = void 0;
}
get token() {
if (!this._token) {
// be lazy and create the token only when
// actually needed
this._token = new MutableToken();
}
return this._token;
}
cancel() {
if (!this._token) {
// save an object by returning the default
// cancelled token when cancellation happens
// before someone asks for the token
this._token = CancellationToken.Cancelled;
} else if (this._token !== CancellationToken.Cancelled) {
this._token.cancel();
}
}
dispose() {
this.cancel();
}
}
const cancelledMessage = 'Cancelled';
export function cancelled() {
return new Error(cancelledMessage);
}
export function isCancelled(err) {
return !!err && err.message === cancelledMessage;
}
export function checkCancelled(token) {
if (!!token && token.isCancellationRequested) {
throw cancelled();
}
}