Label.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import {DisplayElement} from 'tui-lib/ui/primitives'
  2. import * as ansi from 'tui-lib/util/ansi'
  3. export default class Label extends DisplayElement {
  4. // A simple text display. Automatically adjusts size to fit text.
  5. //
  6. // Supports formatted text in two ways:
  7. // 1) Modify the textAttributes to be an array containing the ANSI numerical
  8. // codes for any wanted attributes, and/or
  9. // 2) Supply full ANSI escape codes within the text itself. (The reset
  10. // attributes code, ESC[0m, will be processed to reset to the provided
  11. // values in textAttributes.
  12. //
  13. // Subclasses overriding the writeTextTo function should be sure to call
  14. // processFormatting before actually writing text.
  15. constructor(text = '') {
  16. super()
  17. this.text = text
  18. this.textAttributes = []
  19. }
  20. fixLayout() {
  21. this.w = ansi.measureColumns(this.text)
  22. }
  23. drawTo(writable) {
  24. if (this.textAttributes.length) {
  25. writable.write(ansi.setAttributes(this.textAttributes))
  26. }
  27. this.writeTextTo(writable)
  28. if (this.textAttributes.length) {
  29. writable.write(ansi.resetAttributes())
  30. }
  31. super.drawTo(writable)
  32. }
  33. writeTextTo(writable) {
  34. writable.write(ansi.moveCursor(this.absTop, this.absLeft))
  35. writable.write(this.processFormatting(this.text))
  36. }
  37. processFormatting(text) {
  38. return text.replace(new RegExp(ansi.ESC + '\\[0m', 'g'),
  39. ansi.setAttributes([ansi.A_RESET, ...this.textAttributes]))
  40. }
  41. set text(newText) {
  42. const ret = this.setDep('text', newText)
  43. this.fixLayout()
  44. return ret
  45. }
  46. get text() {
  47. return this.getDep('text')
  48. }
  49. // Kinda bad, but works as long as you're overwriting the array instead of
  50. // mutating it.
  51. set textAttributes(val) { return this.setDep('textAttributes', val) }
  52. get textAttributes() { return this.getDep('textAttributes') }
  53. }