Skip to content

Commit

Permalink
feat: add pause method for external output
Browse files Browse the repository at this point in the history
!break

- fix #906
  • Loading branch information
keindev committed Nov 26, 2022
1 parent 4dd0dcc commit 29d054d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class Task {
error(error?: string | Error | unknown, fail?: boolean): Task {
if (typeof error === 'string') this.#errors.push(error);
if (error instanceof Error && error.stack) this.#errors.push(error.stack);
if (fail) this.fail(error);
if (fail) this.fail();

return this;
}
Expand Down
32 changes: 24 additions & 8 deletions src/TaskTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class TaskTree {
#handle: NodeJS.Timeout | undefined;
#manager: UpdateManager;
#offset = 0;
#paused = false;
#silent = false;
#started = false;
#tasks: Task[];
Expand Down Expand Up @@ -141,6 +142,21 @@ export class TaskTree {
}
}

/**
* Pause tree render for external output
* @param cb - external output callback (runs after hook suspend) and returns count of rows to be erased
*/
async pause(cb: () => Promise<number | void>): Promise<void> {
this.#paused = true;
this.#manager.suspend();

const count = (await cb()) ?? 0;

this.#manager.resume(count);
this.#offset = 0;
this.#paused = false;
}

/** Render a task tree into a `string[]`. Returns strings with tasks hierarchy */
render(): string[] {
let updatable = false;
Expand Down Expand Up @@ -174,9 +190,7 @@ export class TaskTree {

if (!this.#handle && !this.#silent) {
this.#manager.hook();
this.#handle = setInterval((): void => {
this.log();
}, TaskTree.TIMEOUT);
this.#handle = setInterval(() => this.update(), TaskTree.TIMEOUT);
}

return this;
Expand All @@ -189,7 +203,7 @@ export class TaskTree {
if (this.#handle) {
clearInterval(this.#handle);

this.log();
this.update();
this.#manager.unhook();
this.#handle = undefined;
}
Expand All @@ -203,11 +217,13 @@ export class TaskTree {
return obj;
}

private log(): void {
const offset = this.#offset;
private update(): void {
if (!this.#paused || (this.#paused && !this.#started)) {
const offset = this.#offset;

this.#offset = 0;
this.#manager.update(this.render(), offset);
this.#offset = 0;
this.#manager.update(this.render(), offset);
}
}
}

Expand Down

0 comments on commit 29d054d

Please sign in to comment.