mana-common
Version:
Common utils for mana
128 lines (103 loc) • 3.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CancellationTokenSource = exports.CancellationToken = void 0;
exports.cancelled = cancelled;
exports.checkCancelled = checkCancelled;
exports.isCancelled = isCancelled;
var _event = require("./event");
/*---------------------------------------------------------------------------------------------
* 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 */
// 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
}));
var CancellationToken;
exports.CancellationToken = CancellationToken;
(function (CancellationToken) {
CancellationToken.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: _event.Event.None
});
CancellationToken.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: shortcutEvent
});
})(CancellationToken || (exports.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 _event.Emitter();
}
return this._emitter.event;
}
}
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();
}
}
exports.CancellationTokenSource = CancellationTokenSource;
const cancelledMessage = 'Cancelled';
function cancelled() {
return new Error(cancelledMessage);
}
function isCancelled(err) {
return !!err && err.message === cancelledMessage;
}
function checkCancelled(token) {
if (!!token && token.isCancellationRequested) {
throw cancelled();
}
}