textui/ui.ts

55 lines
1.2 KiB
TypeScript

import { BufferDrawing, BufferSize, CharBuffer } from "./base.ts";
import { Display } from "./display.ts";
/**
* Common abstraction for a textual UI
*/
export class TextUI {
private screen = new CharBuffer({ w: 1, h: 1 });
constructor(private display: Display) {
}
get drawing(): BufferDrawing {
return new BufferDrawing(this.screen);
}
/**
* Initializes the display
*/
async init(): Promise<void> {
var size = await this.display.getSize();
this.screen = new CharBuffer(size);
await this.display.clear();
}
/**
* Get the current display size
*/
getSize(): BufferSize {
return this.screen.getSize();
}
/**
* Flush the internal buffer to the display
*/
async flush(): Promise<void> {
// TODO only dirty chars
const { w, h } = this.screen.getSize();
for (let x = 0; x < w; x++) {
for (let y = 0; y < h; y++) {
await this.display.setChar({ x, y }, this.screen.get({ x, y }));
}
}
}
/**
* Start the event loop, waiting for input
*/
async loop(refresh = 1000): Promise<void> {
while (true) {
await this.flush();
await new Promise((resolve) => setTimeout(resolve, refresh));
}
}
}