asciitorium
Version:
an ASCII CLUI framework
54 lines (53 loc) • 2.16 kB
JavaScript
export class DOMRenderer {
constructor(screen, font) {
this.screen = screen;
this.charWidth = 0;
this.charHeight = 0;
if (font) {
this.screen.style.whiteSpace = 'pre';
this.screen.style.fontFamily = font;
}
// Delay measurement slightly to ensure CSS is applied
setTimeout(() => this.measureCharacterSize(), 10);
}
measureCharacterSize() {
// Create a temporary element to measure character dimensions
const measureElement = document.createElement('span');
measureElement.style.position = 'absolute';
measureElement.style.visibility = 'hidden';
measureElement.style.whiteSpace = 'pre';
measureElement.style.fontFamily = this.screen.style.fontFamily;
measureElement.style.fontSize =
getComputedStyle(this.screen).fontSize || '16px';
measureElement.textContent = 'M'; // Use 'M' as it's typically the widest character
document.body.appendChild(measureElement);
const rect = measureElement.getBoundingClientRect();
this.charWidth = rect.width;
this.charHeight = rect.height;
document.body.removeChild(measureElement);
// Fallback values if measurement fails
if (this.charWidth === 0)
this.charWidth = 8;
if (this.charHeight === 0)
this.charHeight = 16;
}
getScreenSize() {
if (this.charWidth === 0 || this.charHeight === 0) {
this.measureCharacterSize();
}
const rect = this.screen.getBoundingClientRect();
const availableWidth = rect.width || window.innerWidth;
const availableHeight = rect.height || window.innerHeight;
const width = Math.floor(availableWidth / this.charWidth);
const height = Math.floor(availableHeight / this.charHeight);
// Minimum size fallback
const result = {
width: Math.max(width, 80),
height: Math.max(height, 24),
};
return result;
}
render(buffer) {
this.screen.textContent = buffer.map((row) => row.join('')).join('\n');
}
}