| ... | @@ -1,29 +1,83 @@ | ... | @@ -1,29 +1,83 @@ |
| 1 | // For those coming from my blog, check out this video | 1 | /** |
| 2 | // -> https://paperclover.net/file/2025/file%20scanner.mp4?view=embed | 2 | * a progress reporting API that allows creating CLI spinners and progress bars |
| 3 | // | 3 | * that can be easily nested to visualize complex, parallel work. in addition |
| 4 | // There is some massive rework pending on this file, check out the PR | 4 | * to providing rich feedback in the terminal, a headless {@linkcode Root} node |
| 5 | // -> https://git.paperclover.net/clo/sitegen/pulls/48 | 5 | * can be constructed, which can be used to bind to {@link formatHtml|the DOM} |
| 6 | // | 6 | * or transmit progress information {@link encodeStream|across a network}. |
| 7 | // This file is under heavy construction. | 7 | * |
| 8 | // - I am happy with the overall design | 8 | * the progress API takes advantage of the `using` keyword to make nodes |
| 9 | // - Will rename things | 9 | * scoped. the convention is to make functions take a {@linkcode Ref|progress.Ref}, |
| 10 | // - Will be re-working the entire module to have a headless | 10 | * to act as the destination for the sub-node. |
| 11 | // core, but still leaving the top level `start` function. | 11 | * |
| 12 | // - There are an overwhelming amount of bugs | 12 | * ```ts |
| 13 | // | 13 | * async function doSomething(p: progress.Ref) { |
| 14 | // a progress tree based on my past uses with clover console v3 and the Zig | 14 | * using node = p.start("my task"); |
| 15 | // `Progress` API. Pass `Ref` to functions which should track progress, calling | 15 | * // ... |
| 16 | // `.start()` to create child items. Or, multiple top-level progress bars can | 16 | * await doSomethingElse(node); // node satisfies progress.Ref |
| 17 | // be created with the singleton's `start()` function. | 17 | * // ... |
| | 18 | * } |
| | 19 | * async function doSomethingElse(p: progress.Ref) { |
| | 20 | * using node = p.start("my sub task"); |
| | 21 | * // ... |
| | 22 | * } |
| | 23 | * |
| | 24 | * doSomething(progress); // the progress module satisfies progress.Ref |
| | 25 | * |
| | 26 | * import * as progress from "@clo/lib/progress.ts"; |
| | 27 | * ``` |
| | 28 | * |
| | 29 | * in some cases, such as in `subprocess/ffmpeg.ts`, it may make more sense |
| | 30 | * to pass in a pre-started node. the `ffmpeg` module, for example, uses the |
| | 31 | * starting text as a base title and decorates it with encoding stats. |
| | 32 | * |
| | 33 | * when using the top-level {@linkcode start|progress.start}, proper |
| | 34 | * integration is made with `lib/log.ts` so that the progress tree does not |
| | 35 | * intersect with regular log messages, as well as forwarding each |
| | 36 | * {@linkcode Node} custom logging scope to the global log, including any |
| | 37 | * custom redirections. |
| | 38 | * |
| | 39 | * this module is under construction. while i am happy with the overall API, it |
| | 40 | * needs more work and feature development. |
| | 41 | * |
| | 42 | * inspired by the [Zig Progress API](https://andrewkelley.me/post/zig-new-cli-progress-bar-explained.html). |
| | 43 | * @module |
| | 44 | */ |
| 18 | | 45 | |
| 19 | /** | 46 | /** |
| 20 | * creates a new trackable unit of work as a child of this one. | 47 | * creates a new trackable unit of work, visible in the terminal as a spinner |
| 21 | * when given an estimate, a progress bar is rendered. | 48 | * that rests at the end of the log. if `estimate` is given, a progress bar is |
| | 49 | * shown. |
| 22 | */ | 50 | */ |
| 23 | export function start(text: string, opts?: StartOptions): Node { | 51 | export function start(text: string, opts?: StartOptions): Node { |
| 24 | return global.start(text, opts); | 52 | return global.start(text, opts); |
| 25 | } | 53 | } |
| 26 | | 54 | |
| | 55 | /** |
| | 56 | * a reference point to create sub-items. this interface is satisfied by |
| | 57 | * - the `progress` module itself |
| | 58 | * - a node recieved by `p.start("label")` |
| | 59 | * - a headless progress runner from `progress.headless()` |
| | 60 | * |
| | 61 | * prefer taking `Ref` as a function parameter, so that the function can be |
| | 62 | * started at the top level, or as a sub-task of an existing node. |
| | 63 | * |
| | 64 | * ```ts |
| | 65 | * function build(p: progress.Ref = progress) { |
| | 66 | * using _ = p.start("build process"); |
| | 67 | * // ... |
| | 68 | * } |
| | 69 | * ``` |
| | 70 | * |
| | 71 | * sometimes it makes sense to have an API recieve `Node` instead of `Ref`, |
| | 72 | * specifically if the caller should have some control over the node name. |
| | 73 | * |
| | 74 | * ```ts |
| | 75 | * await ffmpeg.spawn({ |
| | 76 | * cmd: ["-i", "hello.mov", "-c:v", "libsvtav1", "hello.mp4"], |
| | 77 | * progress: progress.start("encode hello.mov"), |
| | 78 | * }); |
| | 79 | * ``` |
| | 80 | */ |
| 27 | export interface Ref { | 81 | export interface Ref { |
| 28 | /** | 82 | /** |
| 29 | * creates a new trackable unit of work as a child of this one. | 83 | * creates a new trackable unit of work as a child of this one. |
| ... | @@ -32,139 +86,400 @@ export interface Ref { | ... | @@ -32,139 +86,400 @@ export interface Ref { |
| 32 | start(text: string, opts?: StartOptions): Node; | 86 | start(text: string, opts?: StartOptions): Node; |
| 33 | } | 87 | } |
| 34 | | 88 | |
| | 89 | /** |
| | 90 | * control for a progress nooe. all fields are primed with setters to trigger |
| | 91 | * ui dispatch automatically. to make tools that use `progress.ts` more |
| | 92 | * modular to a custom progress implementation, many fields are optional. |
| | 93 | */ |
| 35 | export interface Node extends Ref, Disposable { | 94 | export interface Node extends Ref, Disposable { |
| 36 | /** reactive */ | 95 | /** end this Node or RootNode. ending collapses children. */ |
| | 96 | end(this: Node): void; |
| | 97 | /** one line of text display. */ |
| 37 | text: string; | 98 | text: string; |
| 38 | /** reactive */ | 99 | /** |
| | 100 | * number of items completed. by default this is a count of items, but the |
| | 101 | * `units` property can be passed to `start` to change how the `value` is |
| | 102 | * interpretted when displaying this progress node. |
| | 103 | */ |
| 39 | value: number; | 104 | value: number; |
| 40 | /** reactive */ | | |
| 41 | estimate: number; | | |
| 42 | /** | 105 | /** |
| 43 | * reactive, default `true`. `false` will hides a bar + printing estimate, | 106 | * an estimate of how many items this task contains. |
| 44 | * but preseving auto-end behavior of `inc` | 107 | * when set above `0`, it is shown with a progress bar. |
| 45 | */ | 108 | */ |
| 46 | showEstimate: boolean; | 109 | total: number; |
| 47 | /** | 110 | /** |
| 48 | * reactive, default `false`. when true, this progress item is hidden if | 111 | * defaults to increasing by 1. if incrementing causes `value >= estimate`, |
| | 112 | * it also calls `end`. use `node.value += 1` if that behavior is not wanted. |
| | 113 | */ |
| | 114 | inc(this: Node, value?: number): void; |
| | 115 | /** a scoped logger set to output inline on this item. */ |
| | 116 | readonly log: log.Scope; |
| | 117 | |
| | 118 | /** |
| | 119 | * a time for when this node is estimated to be completed, in milliseconds |
| | 120 | * relative to the unix epoch. by default, this is automatically managed and |
| | 121 | * made read-only. if `StartOptions` specifies `estimateCompletions: false`, |
| | 122 | * this field may be mutated. |
| | 123 | */ |
| | 124 | estimatedTime?: number | null; |
| | 125 | /** |
| | 126 | * default `true`. `false` will hides a bar + printing total. this is useful |
| | 127 | * for preseving auto-end behavior of `inc` without showing the total. |
| | 128 | */ |
| | 129 | showTotal?: boolean; |
| | 130 | /** |
| | 131 | * default `false`. when true, this progress item is hidden if |
| 49 | * there are no children. | 132 | * there are no children. |
| 50 | */ | 133 | */ |
| 51 | passive: boolean; | 134 | passive?: boolean; |
| | 135 | /** default `false`. when true, this progress item is hidden */ |
| | 136 | hidden?: boolean; |
| | 137 | /** override sorting for children */ |
| | 138 | sortChildren?: ((a: ReadOnlyNode, b: ReadOnlyNode) => number) | null; |
| 52 | /** | 139 | /** |
| 53 | * reactive, default `false`. when true, this progress item is hidden | 140 | * specify how `value` and `total` is formed into text. |
| | 141 | * this has some discoverable presets on `StartOptions.units`. |
| 54 | */ | 142 | */ |
| 55 | hidden: boolean; | 143 | valueFormatter?: (value: number, total: number | null) => string; |
| 56 | /** reactive. null means decide based on nested depth + terminal height */ | | |
| 57 | maxHeight: null | number; | | |
| 58 | /** reactive. specify sorting for children */ | | |
| 59 | sortChildren: ((a: SortNode, b: SortNode) => number) | null; | | |
| 60 | | | |
| 61 | /** defaults to increasing by 1. hitting estimate calls end */ | | |
| 62 | inc(value?: number): void; | | |
| 63 | | | |
| 64 | /** A scoped logger set to output inline to this item. */ | | |
| 65 | log: log.Scope; | | |
| 66 | | | |
| 67 | /** end this Node or RootNode. ending collapses children */ | | |
| 68 | end(): void; | | |
| 69 | } | 144 | } |
| 70 | | 145 | |
| | 146 | /** override the default field values of {@link Node} on creation. */ |
| 71 | export interface StartOptions { | 147 | export interface StartOptions { |
| | 148 | /** number of items already completed. */ |
| 72 | value?: number | undefined | null; | 149 | value?: number | undefined | null; |
| 73 | estimate?: number | undefined | null; | 150 | /** when set above `0`, it is shown with a progress bar. */ |
| | 151 | total?: number | undefined | null; |
| | 152 | /** |
| | 153 | * presets for common formattings of `value` and `total`. |
| | 154 | * @default "count" |
| | 155 | */ |
| | 156 | units?: "count" | "bytes" | "percent"; |
| | 157 | /** |
| | 158 | * customize how an estimate is given for progress bars. to make |
| | 159 | * `Node.estimatedTime` mutable, pass `false` here. |
| | 160 | * @default `null`, which is equivilent to `new progress.Ema()` |
| | 161 | */ |
| | 162 | estimateCompletion?: EstimationAlgorithm | boolean | null; |
| | 163 | /** |
| | 164 | * when true, this progress item is hidden if there are no children. |
| | 165 | * this makes sense when scheduling items with a priority queue, where a |
| | 166 | * passive node is only used for grouping, but children are used for |
| | 167 | * indicating status. |
| | 168 | * @default false |
| | 169 | */ |
| 74 | passive?: boolean | undefined | null; | 170 | passive?: boolean | undefined | null; |
| | 171 | /** default `false`. when true, this progress item is hidden */ |
| 75 | hidden?: boolean | undefined | null; | 172 | hidden?: boolean | undefined | null; |
| 76 | showEstimate?: boolean | undefined | null; | 173 | /** |
| 77 | maxHeight?: number | undefined | null; | 174 | * default `true`. `false` will hides a bar + printing estimate, |
| | 175 | * but preseving auto-end behavior of `inc` |
| | 176 | */ |
| | 177 | showTotal?: boolean | undefined | null; |
| | 178 | /** specify sorting for children */ |
| 78 | sortChildren?: Node["sortChildren"] | undefined | null; | 179 | sortChildren?: Node["sortChildren"] | undefined | null; |
| | 180 | /** |
| | 181 | * specify how `value` and `total` is formed into text. |
| | 182 | * this has some discoverable presets on `StartOptions.units`. |
| | 183 | */ |
| | 184 | valueFormatter?: (value: number, total: number | null) => string; |
| | 185 | /** pre-fill the list of log messages */ |
| | 186 | messages?: log.Message[]; |
| | 187 | } |
| | 188 | |
| | 189 | /** |
| | 190 | * creates a function to use as a `Node.valueFormatter` by using a single |
| | 191 | * number formatter, and then joining the node's value and total with a "/", |
| | 192 | * but leaving it out if there is no total. |
| | 193 | */ |
| | 194 | export function slashValueFormatter(fmtNumber: (value: number) => string) { |
| | 195 | return (value: number, total: number | null) => |
| | 196 | value > 0 |
| | 197 | ? fmtNumber(value) + |
| | 198 | (total != null && total > 0 ? "/" + fmtNumber(total) : "") |
| | 199 | : ""; |
| | 200 | } |
| | 201 | |
| | 202 | /** the formatter used when passing `units: "count"` to {@linkcode start} */ |
| | 203 | export const defaultValueFormatter = /* @__PURE__ */ |
| | 204 | slashValueFormatter(String); |
| | 205 | |
| | 206 | /** the formatter used when passing `units: "bytes"` to {@linkcode start} */ |
| | 207 | export const bytesValueFormatter = /* @__PURE__ */ |
| | 208 | slashValueFormatter(string.formatByteSize); |
| | 209 | |
| | 210 | /** the formatter used when passing `units: "percent"` to {@linkcode start} */ |
| | 211 | export function percentValueFormatter(value: number, total: number | null) { |
| | 212 | if (total != null && total > 0) { |
| | 213 | value /= total; |
| | 214 | } |
| | 215 | return `${Math.round(value * 1000) / 10}%`; |
| | 216 | } |
| | 217 | |
| | 218 | /** |
| | 219 | * {@linkcode Root} allows overriding it's timing functions, which are used for |
| | 220 | * mostly for rendering and streaming adapters. |
| | 221 | */ |
| | 222 | export interface RootOptions { |
| | 223 | delay?: typeof async.delay; |
| | 224 | /** used for debouncing and UI. time estimation does NOT use this method */ |
| | 225 | now?: typeof performance.now; |
| 79 | } | 226 | } |
| 80 | | 227 | |
| 81 | /** a valid `Node` without any output */ | 228 | /** |
| 82 | const nullNode: Node = /* @__PURE__ */ | 229 | * a headless progress node. when the state of the tree changes, the `change` |
| 83 | (function start(text: string, opts?: StartOptions): Node { | 230 | * event is emitted (batched with many changes). the primary use case of using |
| 84 | const node = newNode(text, opts)[1]; | 231 | * a custom `Root`s is to stream a task's progress over a network or process |
| 85 | node.start = start; | 232 | * IPC using {@linkcode encodeByteStream}/{@linkcode encodeEventStream}. |
| 86 | node.log = log.scoped(""); | 233 | * another use case is to render a progress task differently. |
| | 234 | * |
| | 235 | * custom events may be dispatched on the `Root`, but this is only useful when |
| | 236 | * streaming, since the streams will carry any custom events. |
| | 237 | */ |
| | 238 | export class Root< |
| | 239 | Result = void, |
| | 240 | Map extends Events.Map = ts.EmptyObject, |
| | 241 | > extends Events<MergeRootEvents<Result, Map>> { |
| | 242 | delay: typeof async.delay; |
| | 243 | now: typeof performance.now; |
| | 244 | #status: "active" | "end" | "error" = "active"; |
| | 245 | #active: Internal[] = []; |
| | 246 | #debounce: async.Cancelable<void> | null = null; |
| | 247 | |
| | 248 | constructor({ delay, now }: RootOptions = {}) { |
| | 249 | super(); |
| | 250 | this.delay = delay ?? async.delay; |
| | 251 | this.now = now ?? performance.now.bind(performance); |
| | 252 | this.on("node-end", (state) => { |
| | 253 | if (state.parent) return; |
| | 254 | const i = this.#active.indexOf(state as Internal); |
| | 255 | ASSERT(i !== -1); |
| | 256 | this.#active.splice(i, 1); |
| | 257 | }); |
| | 258 | } |
| | 259 | |
| | 260 | /** the caller may not mutate `Root`'s state */ |
| | 261 | get active(): readonly ReadOnlyNode[] { |
| | 262 | return this.#active; |
| | 263 | } |
| | 264 | |
| | 265 | /** |
| | 266 | * creates a new trackable unit of work at the top level of this root. |
| | 267 | * when given an estimate, a progress bar is rendered. |
| | 268 | */ |
| | 269 | start(text: string, opts?: StartOptions): Node { |
| | 270 | const [state, node] = newNode(this, text, opts); |
| | 271 | this.#active.push(state); |
| | 272 | this.emit("node-start", state, null); |
| 87 | return node; | 273 | return node; |
| 88 | })("root"); | 274 | } |
| | 275 | |
| | 276 | /** |
| | 277 | * end this root, as well as all children nodes. this emits the `end` event |
| | 278 | * with the provided value, JSON-serializing it if connected via |
| | 279 | * `encodeEventStream` or `encodeByteStream`. |
| | 280 | * |
| | 281 | * this function is pre-bound so that it can be passed to `then`: |
| | 282 | * ```ts |
| | 283 | * const root = new Root(); |
| | 284 | * void asyncFunction().then(root.end, root.error); |
| | 285 | * ``` |
| | 286 | */ |
| | 287 | end = (result: Result): void => { |
| | 288 | this.emit("end", result); |
| | 289 | }; |
| | 290 | |
| | 291 | /** |
| | 292 | * end this root, as well as all children nodes. this emits the `error` event. |
| | 293 | */ |
| | 294 | error = (error: unknown): void => { |
| | 295 | this.emit("error", error); |
| | 296 | }; |
| | 297 | |
| | 298 | /** convert this root into a promise. */ |
| | 299 | asPromise(): Promise<Result> { |
| | 300 | return this.once("end").then((x) => x[0]); |
| | 301 | } |
| | 302 | |
| | 303 | /** |
| | 304 | * emit an event on the specified channel. behavior is not defined when manually |
| | 305 | * emitting one of `progress`'s built in events. |
| | 306 | */ |
| | 307 | override emit<C extends keyof MergeRootEvents<Result, Map>>( |
| | 308 | channel: C, |
| | 309 | ...args: MergeRootEvents<Result, Map>[C] |
| | 310 | ): void { |
| | 311 | ASSERT(this.#status === "active"); |
| | 312 | if (channel !== "change" && rootEvents.has(channel)) this.#emitChangeSoon(); |
| | 313 | if (channel === "error" || channel === "end") { |
| | 314 | this.#end(); |
| | 315 | this.#status = channel; |
| | 316 | } |
| | 317 | super.emit(channel, ...args); |
| | 318 | } |
| | 319 | |
| | 320 | #end() { |
| | 321 | const hasActive = this.#active.length > 0 || !this.#debounce; |
| | 322 | for (const active of this.#active) endNode(this, active); |
| | 323 | this.#active.splice(0, this.#active.length); |
| | 324 | this.#debounce?.cancel(); |
| | 325 | if (hasActive) this.emit("change", this.#active); |
| | 326 | } |
| | 327 | |
| | 328 | #emitChangeSoon = () => { |
| | 329 | if (this.#debounce) return; |
| | 330 | (this.#debounce = this.delay(1)) |
| | 331 | .then(() => { |
| | 332 | this.#debounce = null; |
| | 333 | this.emit("change", this.#active); |
| | 334 | }); |
| | 335 | }; |
| | 336 | } |
| | 337 | |
| | 338 | export type RootEventMap<Result = void> = { |
| | 339 | // this event is the debounced "ready to re-render" event. do not emit. |
| | 340 | "change": [rootNodes: readonly ReadOnlyNode[]]; |
| | 341 | // these events are emitted without a debounce, and are used for general |
| | 342 | // communication within `Root`'s implementation. do not emit. |
| | 343 | "node-start": [newNode: ReadOnlyNode, parentNode: ReadOnlyNode | null]; |
| | 344 | "node-change": [node: ReadOnlyNode, key: keyof ReadOnlyNode]; |
| | 345 | "node-end": [node: ReadOnlyNode]; |
| | 346 | "node-detached-log": [msg: log.Message]; |
| | 347 | // these events are used for result communication. they can be sent via |
| | 348 | // `emit` or the shorthand methods `end` and `error`. sending either will put |
| | 349 | // the `Root` into a "done" state. |
| | 350 | "end": [result: Result]; |
| | 351 | "error": [error: unknown]; |
| | 352 | }; |
| | 353 | |
| | 354 | const rootEvents: ReadonlySet<unknown> = new Set([ |
| | 355 | "change", |
| | 356 | "node-start", |
| | 357 | "node-change", |
| | 358 | "node-end", |
| | 359 | "node-detached-log", |
| | 360 | "end", |
| | 361 | "error", |
| | 362 | ]); |
| 89 | | 363 | |
| 90 | export { nullNode as null }; | 364 | type MergeRootEvents<Result, Map extends Events.Map> = { |
| | 365 | [K in keyof Map | keyof RootEventMap]: K extends keyof RootEventMap |
| | 366 | ? RootEventMap<Result>[K] |
| | 367 | : Map[K]; |
| | 368 | }; |
| 91 | | 369 | |
| 92 | export type SortNode = | 370 | /** a read-only version of {@linkcode Node}, provided to renderers. */ |
| | 371 | export type ReadOnlyNode = Readonly< |
| 93 | & Pick< | 372 | & Pick< |
| 94 | Node, | 373 | Required<Node>, |
| 95 | | "text" | 374 | | "text" |
| 96 | | "value" | 375 | | "value" |
| 97 | | "estimate" | 376 | | "total" |
| | 377 | | "estimatedTime" |
| 98 | | "passive" | 378 | | "passive" |
| 99 | | "hidden" | 379 | | "hidden" |
| 100 | | "showEstimate" | 380 | | "showTotal" |
| 101 | | "sortChildren" | 381 | | "sortChildren" |
| | 382 | | "valueFormatter" |
| 102 | > | 383 | > |
| 103 | & { children: SortNode[] }; | 384 | & { |
| | 385 | /** unique identifier. once {@linkcode Node} is disposed, the key is reused. */ |
| | 386 | key: number; |
| | 387 | logs: readonly log.Message[]; |
| | 388 | /** traverse down the tree. */ |
| | 389 | children: readonly ReadOnlyNode[]; |
| | 390 | /** traverse up the tree. */ |
| | 391 | parent: ReadOnlyNode | null; |
| | 392 | } |
| | 393 | >; |
| 104 | | 394 | |
| 105 | export interface Internal extends SortNode { | 395 | /** internal state is read-write. */ |
| 106 | logs: string[]; | 396 | interface Internal extends ts.Writeable<ReadOnlyNode> { |
| | 397 | logs: log.Message[]; |
| 107 | children: Internal[]; | 398 | children: Internal[]; |
| 108 | parent: Internal | null; | 399 | parent: Internal | null; |
| 109 | signal(msg: Signal): void; | 400 | detached: boolean; |
| 110 | } | 401 | } |
| 111 | | 402 | |
| 112 | type Signal = | 403 | // TypeScript Test |
| 113 | | "draw" | 404 | void function (unknown: unknown) { |
| 114 | | { type: "end"; title: string; logs: string[]; state: Internal } | 405 | (unknown as Internal) satisfies ReadOnlyNode; |
| 115 | | { type: "line"; line: string }; | 406 | }; |
| 116 | | 407 | |
| 117 | function newNode( | 408 | /** |
| | 409 | * constructs a linked `Node` and `Internal` that dispatches events to `owner`. |
| | 410 | * the `Internal` is the non-reactive source of truth that can be blindly cast |
| | 411 | * to `ReadOnlyNode`, and `Node` is the Node. |
| | 412 | */ |
| | 413 | function newNode<Result, EventMap extends Events.Map>( |
| | 414 | owner: Root<Result, EventMap>, |
| 118 | text: string, | 415 | text: string, |
| 119 | opts: StartOptions = {}, | 416 | opts: StartOptions = {}, |
| 120 | ): [Internal, Node] { | 417 | ): [Internal, Node] { |
| | 418 | let estimator: EstimationAlgorithm | null = null; |
| | 419 | |
| 121 | const state: Internal = { | 420 | const state: Internal = { |
| | 421 | key: globalKeyPool.get(), |
| 122 | text, | 422 | text, |
| 123 | value: opts.value ?? 0, | 423 | value: opts.value ?? 0, |
| 124 | estimate: opts.estimate ?? 0, | 424 | total: opts.total ?? 0, |
| 125 | showEstimate: opts.showEstimate ?? true, | 425 | estimatedTime: null, |
| | 426 | showTotal: opts.showTotal ?? true, |
| 126 | passive: opts.passive ?? false, | 427 | passive: opts.passive ?? false, |
| 127 | hidden: opts.hidden ?? false, | 428 | hidden: opts.hidden ?? false, |
| 128 | logs: [], | 429 | logs: [], |
| 129 | children: [], | 430 | children: [], |
| 130 | parent: null, | 431 | parent: null, |
| 131 | sortChildren: opts.sortChildren ?? null, | 432 | sortChildren: opts.sortChildren ?? null, |
| 132 | signal() { | 433 | valueFormatter: opts.valueFormatter ?? { |
| 133 | throw new Error("no signaler"); | 434 | count: defaultValueFormatter, |
| 134 | }, | 435 | bytes: bytesValueFormatter, |
| | 436 | percent: percentValueFormatter, |
| | 437 | }[opts.units ?? "count"], |
| | 438 | detached: false, |
| 135 | }; | 439 | }; |
| 136 | let detached = false; | 440 | |
| 137 | function end() { | 441 | if (opts.estimateCompletion !== false) { |
| 138 | if (detached) return; | 442 | const { estimateCompletion } = opts; |
| 139 | let title = state.text; | 443 | if (estimateCompletion && typeof estimateCompletion === "object") { |
| 140 | if (state.parent) { | 444 | estimator = estimateCompletion; |
| 141 | const i = state.parent.children.indexOf(state); | 445 | } else estimator = new Ema(); |
| 142 | ASSERT(i !== -1); | | |
| 143 | let p: Internal | null = state; | | |
| 144 | while (p = p.parent) title = p.text + " / " + title; | | |
| 145 | state.parent.children.splice(i, 1); | | |
| 146 | state.parent = null; | | |
| 147 | detached = true; | | |
| 148 | } | | |
| 149 | state.signal({ type: "end", title, logs: state.logs, state }); | | |
| 150 | state.logs = []; | | |
| 151 | } | 446 | } |
| 152 | function mutate() { | 447 | estimator?.sample(Date.now(), 0); |
| | 448 | |
| | 449 | function mutate(key: keyof ReadOnlyNode) { |
| | 450 | if (state.detached) return; |
| | 451 | if ( |
| | 452 | key === "value" && estimator && state.total > 0 && state.value > 0 && |
| | 453 | state.value < state.total |
| | 454 | ) { |
| | 455 | const time = estimator.sample(owner.now(), state.value / state.total); |
| | 456 | if ( |
| | 457 | time && (!state.estimatedTime || state.estimatedTime !== time) |
| | 458 | ) { |
| | 459 | state.estimatedTime = time; |
| | 460 | owner.emit("node-change", state, "estimatedTime"); |
| | 461 | } |
| | 462 | } |
| 153 | const { parent } = state; | 463 | const { parent } = state; |
| 154 | parent?.sortChildren && parent.children.sort(parent.sortChildren); | 464 | parent?.sortChildren && parent.children.sort(parent.sortChildren); |
| 155 | state.signal("draw"); | 465 | owner.emit("node-change", state, key); |
| 156 | } | 466 | } |
| 157 | // const scope = log.headlessScope((msg) => { | 467 | |
| 158 | // console.log("TODO"); | 468 | const scope = log.headlessScope((m) => { |
| 159 | // }); | 469 | if (state.detached) return owner.emit("node-detached-log", m); |
| | 470 | state.logs.push(m); |
| | 471 | owner.emit("node-change", state, "logs"); |
| | 472 | }); |
| | 473 | |
| 160 | const binding: Node = { | 474 | const binding: Node = { |
| 161 | start(text, opts) { | 475 | start(text, opts) { |
| 162 | const [child, node] = newNode(text, opts); | 476 | if (state.detached) return nullNode; |
| | 477 | const [child, node] = newNode(owner, text, opts); |
| 163 | state.children.push(child); | 478 | state.children.push(child); |
| 164 | state.sortChildren && state.children.sort(state.sortChildren); | | |
| 165 | child.parent = state; | 479 | child.parent = state; |
| 166 | child.signal = state.signal; | 480 | state.sortChildren && state.children.sort(state.sortChildren); |
| 167 | state.signal("draw"); | 481 | owner.emit("node-start", child, state); |
| | 482 | owner.emit("node-change", state, "children"); |
| 168 | return node; | 483 | return node; |
| 169 | }, | 484 | }, |
| 170 | get text() { | 485 | get text() { |
| ... | @@ -172,135 +487,186 @@ function newNode( | ... | @@ -172,135 +487,186 @@ function newNode( |
| 172 | }, | 487 | }, |
| 173 | set text(value) { | 488 | set text(value) { |
| 174 | state.text = value; | 489 | state.text = value; |
| 175 | mutate(); | 490 | mutate("text"); |
| 176 | }, | 491 | }, |
| 177 | get value() { | 492 | get value() { |
| 178 | return state.value; | 493 | return state.value; |
| 179 | }, | 494 | }, |
| 180 | set value(value) { | 495 | set value(value) { |
| 181 | state.value = value; | 496 | state.value = value; |
| 182 | mutate(); | 497 | mutate("value"); |
| 183 | }, | 498 | }, |
| 184 | get estimate() { | 499 | get total() { |
| 185 | return state.estimate; | 500 | return state.total; |
| 186 | }, | 501 | }, |
| 187 | set estimate(value) { | 502 | set total(value) { |
| 188 | state.estimate = value; | 503 | state.total = value; |
| 189 | mutate(); | 504 | mutate("total"); |
| 190 | }, | 505 | }, |
| 191 | get showEstimate() { | 506 | get showTotal() { |
| 192 | return state.showEstimate; | 507 | return state.showTotal; |
| 193 | }, | 508 | }, |
| 194 | set showEstimate(value) { | 509 | set showTotal(value) { |
| 195 | state.showEstimate = value; | 510 | state.showTotal = value; |
| 196 | mutate(); | 511 | mutate("showTotal"); |
| 197 | }, | 512 | }, |
| 198 | get passive() { | 513 | get passive() { |
| 199 | return state.passive; | 514 | return state.passive; |
| 200 | }, | 515 | }, |
| 201 | set passive(value) { | 516 | set passive(value) { |
| 202 | state.passive = value; | 517 | state.passive = value; |
| 203 | mutate(); | 518 | mutate("passive"); |
| 204 | }, | 519 | }, |
| 205 | get hidden() { | 520 | get hidden() { |
| 206 | return state.hidden; | 521 | return state.hidden; |
| 207 | }, | 522 | }, |
| 208 | set hidden(value) { | 523 | set hidden(value) { |
| 209 | state.hidden = value; | 524 | state.hidden = value; |
| 210 | mutate(); | 525 | mutate("hidden"); |
| 211 | }, | 526 | }, |
| 212 | maxHeight: null, | | |
| 213 | // get maxHeight() { | | |
| 214 | // return state.maxHeight; | | |
| 215 | // }, | | |
| 216 | // set maxHeight(value) { | | |
| 217 | // state.maxHeight = value; | | |
| 218 | // mutate(); | | |
| 219 | // }, | | |
| 220 | get sortChildren() { | 527 | get sortChildren() { |
| 221 | return state.sortChildren; | 528 | return state.sortChildren; |
| 222 | }, | 529 | }, |
| 223 | set sortChildren(value) { | 530 | set sortChildren(value) { |
| 224 | state.sortChildren = value; | 531 | state.sortChildren = value; |
| 225 | value && state.children.sort(value); | 532 | mutate("sortChildren"); |
| 226 | state.signal("draw"); | 533 | }, |
| | 534 | get estimatedTime() { |
| | 535 | return state.estimatedTime; |
| | 536 | }, |
| | 537 | set estimatedTime(date) { |
| | 538 | if (!estimator) { |
| | 539 | state.estimatedTime = date; |
| | 540 | mutate("estimatedTime"); |
| | 541 | } |
| | 542 | }, |
| | 543 | get valueFormatter() { |
| | 544 | return state.valueFormatter; |
| | 545 | }, |
| | 546 | set valueFormatter(value) { |
| | 547 | state.valueFormatter = value; |
| | 548 | mutate("valueFormatter"); |
| 227 | }, | 549 | }, |
| 228 | inc(delta = 1) { | 550 | inc(delta = 1) { |
| 229 | state.value += delta; | 551 | state.value += delta; |
| 230 | if (state.estimate > 0 && state.value >= state.estimate) { | 552 | if (state.total > 0 && state.value >= state.total) { |
| 231 | end(); | 553 | endNode(owner, state); |
| 232 | } else { | 554 | } else { |
| 233 | mutate(); | 555 | mutate("value"); |
| 234 | } | 556 | } |
| 235 | }, | 557 | }, |
| 236 | log: log.scoped(""), | 558 | log: scope, |
| 237 | end: () => void end(), | 559 | end: () => void endNode(owner, state), |
| 238 | [Symbol.dispose]: () => void end(), | 560 | [Symbol.dispose]: () => void endNode(owner, state), |
| 239 | }; | 561 | }; |
| 240 | return [state, binding]; | 562 | return [state, binding]; |
| 241 | } | 563 | } |
| 242 | | 564 | |
| 243 | function formatProgress(now: number, list: Internal[]): string { | 565 | const noop = () => {}; |
| | 566 | noop[Symbol.dispose] = noop; |
| | 567 | |
| | 568 | /** minimal implementation of {@linkcode Node} that has no I/O */ |
| | 569 | export const nullNode: Node = { |
| | 570 | start: () => nullNode, |
| | 571 | get text() { |
| | 572 | return "[detached]"; |
| | 573 | }, |
| | 574 | set text(_) { |
| | 575 | }, |
| | 576 | get value() { |
| | 577 | return 0; |
| | 578 | }, |
| | 579 | set value(_) { |
| | 580 | }, |
| | 581 | get total() { |
| | 582 | return 0; |
| | 583 | }, |
| | 584 | set total(_) { |
| | 585 | }, |
| | 586 | inc: noop, |
| | 587 | log: { |
| | 588 | info: noop, |
| | 589 | warn: noop, |
| | 590 | error: noop, |
| | 591 | log: noop, |
| | 592 | debug: noop, |
| | 593 | scoped() { |
| | 594 | return this; |
| | 595 | }, |
| | 596 | tee: () => noop, |
| | 597 | }, |
| | 598 | end: () => {}, |
| | 599 | [Symbol.dispose]: () => {}, |
| | 600 | }; |
| | 601 | |
| | 602 | function endNode<R, M extends Events.Map>(owner: Root<R, M>, state: Internal) { |
| | 603 | if (state.detached) return; |
| | 604 | state.children.forEach((child) => endNode(owner, child)); |
| | 605 | state.detached = true; |
| | 606 | globalKeyPool.recycle(state.key); |
| | 607 | let title = state.text; |
| | 608 | if (state.parent) { |
| | 609 | const i = state.parent.children.indexOf(state); |
| | 610 | ASSERT(i !== -1); |
| | 611 | let p: Internal | null = state; |
| | 612 | while (p = p.parent) title = p.text + " / " + title; |
| | 613 | state.parent.children.splice(i, 1); |
| | 614 | } |
| | 615 | owner.emit("node-end", state); |
| | 616 | state.logs = []; |
| | 617 | state.parent = null; |
| | 618 | } |
| | 619 | |
| | 620 | /** Convert the top level `ReadOnlyNode[]` into ANSI text. */ |
| | 621 | export function formatAnsi(now: number, list: readonly ReadOnlyNode[]): string { |
| 244 | let out = ""; | 622 | let out = ""; |
| 245 | for (const top of list) { | 623 | for (const top of list) { |
| 246 | if (top.passive && !hasChildren(top)) continue; | 624 | if (top.passive && !hasChildren(top)) continue; |
| 247 | out += renderMainLine(top, now, 0) + "\n"; | 625 | out += renderAnsiMainLine(top, now, 0) + "\n"; |
| 248 | out += renderChildren(top, now, []); | 626 | out += renderChildren(top, now, []); |
| 249 | } | 627 | } |
| 250 | return out.trimEnd(); | 628 | return out.trimEnd(); |
| 251 | } | 629 | } |
| 252 | | 630 | |
| 253 | /** These functions are used to test `lib/progress` */ | | |
| 254 | export namespace internals { | | |
| 255 | export function node( | | |
| 256 | text: string, | | |
| 257 | props: Partial<Internal>, | | |
| 258 | children: Internal[], | | |
| 259 | ): Internal { | | |
| 260 | const [node] = newNode(text); | | |
| 261 | Object.assign(node, props); | | |
| 262 | node.children.push(...children); | | |
| 263 | return node; | | |
| 264 | } | | |
| 265 | export const format = formatProgress; | | |
| 266 | } | | |
| 267 | | | |
| 268 | const spinnerFps = 12.5; | 631 | const spinnerFps = 12.5; |
| 269 | | 632 | const box = { tee: "├─ ", line: "│ ", langle: "└─ " }; |
| 270 | const box = { | | |
| 271 | tee: "├─ ", | | |
| 272 | line: "│ ", | | |
| 273 | langle: "└─ ", | | |
| 274 | }; | | |
| 275 | const barChars = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; | 633 | const barChars = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; |
| 276 | const fullBar = "█"; | 634 | const fullBar = "█"; |
| 277 | const spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] | 635 | const spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] |
| 278 | .map((frame) => ansi.style(ansi.fgBlue, frame)); | 636 | .map((frame) => ansi.style(ansi.fgBlue, frame)); |
| 279 | | 637 | |
| 280 | function renderMainLine(state: Internal, now: number, depth: number) { | 638 | function renderAnsiMainLine(state: ReadOnlyNode, now: number, depth: number) { |
| 281 | if (state.estimate && state.showEstimate) { | 639 | const { text, total, showTotal, value, estimatedTime } = state; |
| | 640 | const dateNow = Date.now(); |
| | 641 | const estimate = estimatedTime && (estimatedTime > dateNow + 1000) |
| | 642 | ? ", " + |
| | 643 | string.formatDurationLetters(Math.round((estimatedTime - dateNow) / 1000)) |
| | 644 | : ""; |
| | 645 | const valueFormatted = state.valueFormatter(value, total); |
| | 646 | if (total && showTotal) { |
| 282 | return ansi.style( | 647 | return ansi.style( |
| 283 | ansi.bgBrightBlack + ansi.fgBlue, | 648 | ansi.bgBrightBlack + ansi.fgBlue, |
| 284 | getUnicodeBar( | 649 | formatUnicodeBar( |
| 285 | state.value / state.estimate, | 650 | value / total, |
| 286 | Math.max(4, depth > 0 ? 12 : 25), | 651 | Math.max(4, depth > 0 ? 12 : 25), |
| 287 | ), | 652 | ), |
| 288 | ) + | 653 | ) + |
| 289 | ` [${state.value}/${state.estimate}] ` + state.text; | 654 | (valueFormatted || estimate ? ` [${valueFormatted}${estimate}] ` : " ") + |
| | 655 | text; |
| 290 | } | 656 | } |
| 291 | const frame = Math.floor(now / (1000 / spinnerFps)) % spinner.length; | 657 | const frame = Math.floor(now / (1000 / spinnerFps)) % spinner.length; |
| 292 | return (depth === 0 ? spinner[frame] + " " : "") + | 658 | return ((depth === 0 ? spinner[frame] + " " : "") + |
| 293 | (state.value > 0 ? `[${state.value}] ` : "") + state.text; | 659 | (valueFormatted ? `[${valueFormatted}] ` : "") + text); |
| 294 | } | 660 | } |
| 295 | | 661 | |
| 296 | function hasChildren(states: Internal): boolean { | 662 | function hasChildren(states: ReadOnlyNode): boolean { |
| 297 | return states.children.some((x) => | 663 | return states.children.some((x) => |
| 298 | !x.hidden && (!x.passive || hasChildren(x)) | 664 | !x.hidden && (!x.passive || hasChildren(x)) |
| 299 | ); | 665 | ); |
| 300 | } | 666 | } |
| 301 | | 667 | |
| 302 | function renderChildren(state: Internal, now: number, depth: boolean[]) { | 668 | function renderChildren(state: ReadOnlyNode, now: number, depth: boolean[]) { |
| 303 | let maxHeight = 50; // TODO: | 669 | let maxHeight = 50; // TODO: flexible layout |
| 304 | let truncated = 0; | 670 | let truncated = 0; |
| 305 | let out = ""; | 671 | let out = ""; |
| 306 | let { children } = state; | 672 | let { children } = state; |
| ... | @@ -313,7 +679,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { | ... | @@ -313,7 +679,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { |
| 313 | let item = ""; | 679 | let item = ""; |
| 314 | const left = depth.map((x) => x ? box.line : " ").join(""); | 680 | const left = depth.map((x) => x ? box.line : " ").join(""); |
| 315 | item += left + (i === length - 1 && !truncated ? box.langle : box.tee); | 681 | item += left + (i === length - 1 && !truncated ? box.langle : box.tee); |
| 316 | item += renderMainLine(child, now, 1 + depth.length) + "\n"; | 682 | item += renderAnsiMainLine(child, now, 1 + depth.length) + "\n"; |
| 317 | item += renderChildren(child, now, depth.concat(i < length - 1)); | 683 | item += renderChildren(child, now, depth.concat(i < length - 1)); |
| 318 | const h = string.countNewlines(item); | 684 | const h = string.countNewlines(item); |
| 319 | if (h > maxHeight) { | 685 | if (h > maxHeight) { |
| ... | @@ -323,7 +689,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { | ... | @@ -323,7 +689,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { |
| 323 | const logLines = child?.logs.slice(-Math.min(3, maxHeight)) ?? []; | 689 | const logLines = child?.logs.slice(-Math.min(3, maxHeight)) ?? []; |
| 324 | for (const line of logLines) { | 690 | for (const line of logLines) { |
| 325 | item += left + box.line + " " + ansi.style(ansi.fgBrightBlack, ">") + | 691 | item += left + box.line + " " + ansi.style(ansi.fgBrightBlack, ">") + |
| 326 | " " + line + "\n"; | 692 | " " + log.formatMessage(line, true) + "\n"; |
| 327 | } | 693 | } |
| 328 | maxHeight -= h + logLines.length; | 694 | maxHeight -= h + logLines.length; |
| 329 | out += item; | 695 | out += item; |
| ... | @@ -340,7 +706,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { | ... | @@ -340,7 +706,7 @@ function renderChildren(state: Internal, now: number, depth: boolean[]) { |
| 340 | * which did ffmpeg handling. It is probably one of the coolest progress bars | 706 | * which did ffmpeg handling. It is probably one of the coolest progress bars |
| 341 | * ever imagined. | 707 | * ever imagined. |
| 342 | */ | 708 | */ |
| 343 | export function getUnicodeBar(progress: number, width: number): string { | 709 | export function formatUnicodeBar(progress: number, width: number): string { |
| 344 | if (progress >= 1) return fullBar.repeat(width); | 710 | if (progress >= 1) return fullBar.repeat(width); |
| 345 | if (progress <= 0 || Number.isNaN(progress)) return " ".repeat(width); | 711 | if (progress <= 0 || Number.isNaN(progress)) return " ".repeat(width); |
| 346 | | 712 | |
| ... | @@ -356,58 +722,143 @@ export function getUnicodeBar(progress: number, width: number): string { | ... | @@ -356,58 +722,143 @@ export function getUnicodeBar(progress: number, width: number): string { |
| 356 | return fill + partChar + empty; | 722 | return fill + partChar + empty; |
| 357 | } | 723 | } |
| 358 | | 724 | |
| 359 | /** Run a progress tree without a dependency on a TTY */ | 725 | /** |
| 360 | export class Headless { | 726 | * configure a `Root` to display its contents to a `log.HeadlessWidgetHost`. |
| 361 | constructor( | 727 | * this is used by the global progress instance to output to the terminal |
| 362 | /** | 728 | * ```ts |
| 363 | * `startWidget` is only ever called from `start` | 729 | * const globalProgress = new progress.Root(); |
| 364 | * `writeLine` is used for logs from completed nodes | 730 | * progress.attachToScreen(log); |
| 365 | */ | 731 | * ``` |
| 366 | public env: Pick<headless.WidgetHost, "writeLine" | "startWidget">, | 732 | * unit tests use a mock screen instead of the terminal. |
| 367 | ) {} | 733 | * ```ts |
| | 734 | * const screen = new TestWidgetHost(); |
| | 735 | * const root = new progress.Root(screen.delay); |
| | 736 | * root.attachToScreen(screen); |
| | 737 | * // can use the progress API |
| | 738 | * root.start("hello"); |
| | 739 | * // and then examine the contents |
| | 740 | * screen.expectFrame(...); |
| | 741 | * ``` |
| | 742 | */ |
| | 743 | export function attachToScreen( |
| | 744 | root: Root, |
| | 745 | { writeLine, startWidget }: Pick< |
| | 746 | log.HeadlessWidgetHost, |
| | 747 | "writeLine" | "startWidget" |
| | 748 | >, |
| | 749 | ): ts.Dispose { |
| | 750 | const stack = new DisposableStack(); |
| 368 | | 751 | |
| 369 | active: Internal[] = []; | 752 | let rerender: (() => void) | null = null; |
| | 753 | const widget: log.Widget = { |
| | 754 | format: (now) => root.active ? formatAnsi(now, root.active) : null, |
| | 755 | onChange: (cb) => (rerender = cb, () => rerender = null), |
| | 756 | fps: spinnerFps, |
| | 757 | }; |
| 370 | | 758 | |
| 371 | start(text: string, opts?: StartOptions): Node { | 759 | stack.use(root.on("change", (items) => { |
| 372 | const [state, node] = newNode(text, opts); | | |
| 373 | this.active.push(state); | | |
| 374 | state.signal = this.#signal; | | |
| 375 | const rerender = this.#rerender; | | |
| 376 | if (rerender) rerender(); | 760 | if (rerender) rerender(); |
| 377 | else log.startWidget(this.widget); | 761 | else if (items.length > 0) startWidget(widget); |
| 378 | return node; | 762 | })); |
| | 763 | stack.use( |
| | 764 | root.on( |
| | 765 | "node-detached-log", |
| | 766 | (msg) => writeLine(log.formatMessage(msg, true)), |
| | 767 | ), |
| | 768 | ); |
| | 769 | stack.use(root.on("node-end", (node) => { |
| | 770 | let title = node.text; |
| | 771 | let p: ReadOnlyNode | null = node; |
| | 772 | while (p = p.parent) title = p.text + " / " + title; |
| | 773 | const { logs } = node; |
| | 774 | if (logs.length > 0) { |
| | 775 | const count = `${logs.length} line${logs.length === 1 ? "" : "s"}`; |
| | 776 | const header = `[${count} from ${title}]`; |
| | 777 | writeLine(ansi.style(ansi.fgBrightBlack, header)); |
| | 778 | writeLine(logs.map((msg) => log.formatMessage(msg, true)).join("\n")); |
| | 779 | } |
| | 780 | })); |
| | 781 | |
| | 782 | return ts.defer(() => stack[Symbol.dispose]); |
| | 783 | } |
| | 784 | |
| | 785 | class KeyPool<T extends number> { |
| | 786 | next = 1 as T; |
| | 787 | old: T[] = []; |
| | 788 | |
| | 789 | get() { |
| | 790 | const existing = this.old.shift(); |
| | 791 | if (existing) return existing as T; |
| | 792 | const next = this.next = this.next + 1 as T; |
| | 793 | return next as T; |
| 379 | } | 794 | } |
| 380 | | 795 | |
| 381 | widget: log.Widget = { | 796 | recycle(k: T) { |
| 382 | format: (now) => formatProgress(now, this.active), | 797 | this.old.push(k); |
| 383 | onChange: ( | 798 | } |
| 384 | rerender, | 799 | } |
| 385 | ) => (this.#rerender = rerender, () => this.#rerender = null), | | |
| 386 | }; | | |
| 387 | | 800 | |
| 388 | #rerender?: (() => void) | null; | 801 | /** stateful estimation by providing samples */ |
| 389 | #signal = (msg: Signal) => { | 802 | export interface EstimationAlgorithm { |
| 390 | if (msg === "draw") this.#rerender?.(); | 803 | /** |
| 391 | else if (msg.type === "line") this.env.writeLine(msg.line); | 804 | * given a timestamp `time` and a progress value `progress`, return the |
| 392 | else if (msg.type === "end") { | 805 | * timestamp that the action will be finished on. |
| 393 | const indexOfActive = this.active.indexOf(msg.state); | 806 | */ |
| 394 | if (indexOfActive !== -1) this.active.splice(indexOfActive, 1); | 807 | sample(time: number, progress: number): number | null; |
| 395 | if (msg.logs.length === 0) { | 808 | } |
| 396 | this.#rerender?.(); | 809 | |
| 397 | return; | 810 | /** |
| 398 | } | 811 | * Exponential Moving Average. |
| 399 | const { logs } = msg; | 812 | * this is the algorithm used for the default progress estimator. |
| 400 | const count = `${logs.length} line${logs.length === 1 ? "" : "s"}`; | 813 | * https://en.wikipedia.org/wiki/Exponential_smoothing |
| 401 | const header = `[${count} from ${msg.title}]`; | 814 | */ |
| 402 | this.env.writeLine(ansi.style(ansi.fgBrightBlack, header)); | 815 | export class Ema implements EstimationAlgorithm { |
| 403 | this.env.writeLine(msg.logs.join("\n")); | 816 | start: number | null = null; |
| | 817 | estimate: number | null = null; |
| | 818 | /** smoothing factor (0-1) */ |
| | 819 | alpha: number = 0.25; |
| | 820 | |
| | 821 | constructor(alpha: number = 0.1) { |
| | 822 | this.alpha = alpha; |
| | 823 | } |
| | 824 | |
| | 825 | /** |
| | 826 | * given a timestamp `time` and a progress value `progress`, return the |
| | 827 | * timestamp that the action will be finished on. |
| | 828 | */ |
| | 829 | sample(time: number, progress: number): number | null { |
| | 830 | ASSERT( |
| | 831 | progress >= 0 && progress < 1, |
| | 832 | `progress must be a number between 0 and 1, got ${progress}`, |
| | 833 | ); |
| | 834 | if (this.start == null) { |
| | 835 | this.start = time; |
| | 836 | return null; |
| 404 | } | 837 | } |
| 405 | }; | 838 | |
| | 839 | const value = (time - this.start) / progress; |
| | 840 | this.estimate = this.estimate != null |
| | 841 | ? ((1 - this.alpha) * this.estimate + |
| | 842 | this.alpha * value) |
| | 843 | : value; |
| | 844 | |
| | 845 | return time + (1 - progress) * this.estimate; |
| | 846 | } |
| | 847 | |
| | 848 | reset(): void { |
| | 849 | this.start = null; |
| | 850 | this.estimate = null; |
| | 851 | } |
| 406 | } | 852 | } |
| 407 | | 853 | |
| 408 | const global = /** @__PURE__ */ new Headless(log); | 854 | const globalKeyPool = new KeyPool<number>(); |
| | 855 | const global = |
| | 856 | /** @__PURE__ */ ((root = new Root()) => (attachToScreen(root, log), root))(); |
| 409 | | 857 | |
| | 858 | import * as async from "./async.ts"; |
| 410 | import * as log from "./log.ts"; | 859 | import * as log from "./log.ts"; |
| 411 | import * as ansi from "./string/ansi.ts"; | 860 | import * as ansi from "./string/ansi.ts"; |
| | 861 | import * as ts from "./ts.ts"; |
| 412 | import * as string from "./string.ts"; | 862 | import * as string from "./string.ts"; |
| 413 | import { ASSERT, UNWRAP } from "./assert.ts"; | 863 | import { ASSERT, UNWRAP } from "./assert.ts"; |
| | 864 | import { Events } from "./Events.ts"; |