2020-07-09 20:52:54 +00:00
|
|
|
/*
|
2024-09-09 13:57:16 +00:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2020-07-09 20:52:54 +00:00
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
|
2024-09-09 13:57:16 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
|
|
|
Please see LICENSE files in the repository root for full details.
|
2020-07-09 20:52:54 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A utility to ensure that a function is only called once triggered with
|
|
|
|
* a mark applied. Multiple marks can be applied to the function, however
|
|
|
|
* the function will only be called once upon trigger().
|
|
|
|
*
|
|
|
|
* The function starts unmarked.
|
|
|
|
*/
|
|
|
|
export class MarkedExecution {
|
2021-06-29 02:40:11 +00:00
|
|
|
private marked = false;
|
2020-07-09 20:52:54 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates a MarkedExecution for the provided function.
|
2021-06-24 01:34:25 +00:00
|
|
|
* @param {Function} fn The function to be called upon trigger if marked.
|
|
|
|
* @param {Function} onMarkCallback A function that is called when a new mark is made. Not
|
|
|
|
* called if a mark is already flagged.
|
2020-07-09 20:52:54 +00:00
|
|
|
*/
|
2024-01-02 18:56:39 +00:00
|
|
|
public constructor(
|
|
|
|
private fn: () => void,
|
|
|
|
private onMarkCallback?: () => void,
|
|
|
|
) {}
|
2020-07-09 20:52:54 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Resets the mark without calling the function.
|
|
|
|
*/
|
2023-01-12 13:25:14 +00:00
|
|
|
public reset(): void {
|
2021-06-29 02:40:11 +00:00
|
|
|
this.marked = false;
|
2020-07-09 20:52:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Marks the function to be called upon trigger().
|
|
|
|
*/
|
2023-01-12 13:25:14 +00:00
|
|
|
public mark(): void {
|
2021-06-29 02:40:11 +00:00
|
|
|
if (!this.marked) this.onMarkCallback?.();
|
|
|
|
this.marked = true;
|
2020-07-09 20:52:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If marked, the function will be called, otherwise this does nothing.
|
|
|
|
*/
|
2023-01-12 13:25:14 +00:00
|
|
|
public trigger(): void {
|
2021-06-29 02:40:11 +00:00
|
|
|
if (!this.marked) return;
|
2020-07-10 14:14:33 +00:00
|
|
|
this.reset(); // reset first just in case the fn() causes a trigger()
|
2020-07-09 20:52:54 +00:00
|
|
|
this.fn();
|
|
|
|
}
|
|
|
|
}
|