textui/ui.ts

56 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-05-19 13:00:52 +00:00
import { BufferDrawing, BufferSize, CharBuffer } from "./base.ts";
2021-05-13 22:04:47 +00:00
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();
}
2021-05-19 13:00:52 +00:00
/**
* Get the current display size
*/
getSize(): BufferSize {
return this.screen.getSize();
}
2021-05-13 22:04:47 +00:00
/**
* 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 }));
}
}
}
2021-05-19 13:00:52 +00:00
/**
* 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));
}
}
2021-05-13 22:04:47 +00:00
}