From 154dd2f631edc9f46ff73e80b54d48f0ccdf049a Mon Sep 17 00:00:00 2001 From: Florrie Date: Thu, 16 Jul 2020 14:05:54 -0300 Subject: support mixed textAttributes & ANSI format labels --- ui/Label.js | 17 ++++++++++++++++- ui/WrapLabel.js | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) (limited to 'ui') diff --git a/ui/Label.js b/ui/Label.js index f2cd405..b5828cb 100644 --- a/ui/Label.js +++ b/ui/Label.js @@ -4,6 +4,16 @@ const DisplayElement = require('./DisplayElement') module.exports = class Label extends DisplayElement { // A simple text display. Automatically adjusts size to fit text. + // + // Supports formatted text in two ways: + // 1) Modify the textAttributes to be an array containing the ANSI numerical + // codes for any wanted attributes, and/or + // 2) Supply full ANSI escape codes within the text itself. (The reset + // attributes code, ESC[0m, will be processed to reset to the provided + // values in textAttributes. + // + // Subclasses overriding the writeTextTo function should be sure to call + // processFormatting before actually writing text. constructor(text = '') { super() @@ -32,7 +42,12 @@ module.exports = class Label extends DisplayElement { writeTextTo(writable) { writable.write(ansi.moveCursor(this.absTop, this.absLeft)) - writable.write(this.text) + writable.write(this.processFormatting(this.text)) + } + + processFormatting(text) { + return text.replace(new RegExp(ansi.ESC + '\\[0m', 'g'), + ansi.setAttributes([ansi.A_RESET, ...this.textAttributes])) } set text(newText) { diff --git a/ui/WrapLabel.js b/ui/WrapLabel.js index 7036908..d40b29d 100644 --- a/ui/WrapLabel.js +++ b/ui/WrapLabel.js @@ -20,7 +20,7 @@ module.exports = class WrapLabel extends Label { const lines = this.getWrappedLines() for (let i = 0; i < lines.length; i++) { writable.write(ansi.moveCursor(this.absTop + i, this.absLeft)) - writable.write(lines[i]) + writable.write(this.processFormatting(lines[i])) } } -- cgit 1.3.0-6-gf8a5