« get me outta code hell

tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--ui/Label.js17
-rw-r--r--ui/WrapLabel.js2
2 files changed, 17 insertions, 2 deletions
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]))
     }
   }