LogDraft.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict'
  2. const util = require('util')
  3. const defaults = require('./defaults')
  4. const CSIHelper = require('./CSIHelper')
  5. // Expose
  6. module.exports = LogDraft
  7. /*
  8. * This is a single Line object, that saves it's relative position
  9. * in terminal. It is responsible by updating itself.
  10. */
  11. function LogDraft(console, methodName) {
  12. this._stream = console._stdout
  13. this._styleFn = console[methodName]
  14. // Valid flag. If set to false, should NOT write anymore
  15. this.valid = true
  16. // Save line where content will be saved
  17. this.saveLine()
  18. }
  19. /*
  20. * After creating a draft, you can call as many times as you want to update it
  21. */
  22. LogDraft.prototype.update = function update(/* log arguments */) {
  23. // Get line difference
  24. var linesUp = this.linesUp()
  25. // Check if is offscreen
  26. if (this.isOffScreen()) {
  27. if (defaults.canReWrite) {
  28. // It can be rewritten, move line to current cursor line, and keep updating
  29. this.saveLine(-1)
  30. } else {
  31. // Invalidate and prevent writting
  32. this.valid = false
  33. return;
  34. }
  35. }
  36. // Start editing stream
  37. this._stream.stopLineCount()
  38. // Save state (if content is not null)
  39. this._stream.write(CSIHelper.save())
  40. // Move up cursor up
  41. this._stream.write(CSIHelper.up(linesUp))
  42. // Clear line
  43. this._stream.write(CSIHelper.clearLine())
  44. // Call write function
  45. this.write.apply(this, arguments)
  46. // Restore state
  47. this._stream.write(CSIHelper.restore())
  48. // Resume counting lines
  49. this._stream.resumeLineCount()
  50. }
  51. /*
  52. * Returns true if line is out of screen
  53. */
  54. LogDraft.prototype.isOffScreen = function isOffScren() {
  55. var rows = this._stream.rows() || defaults.maximumLinesUp
  56. return this._stream.rows() <= this.linesUp()
  57. }
  58. /*
  59. * Return how many lines past our current log
  60. */
  61. LogDraft.prototype.linesUp = function linesUp() {
  62. return this._stream.line() - this._line
  63. }
  64. /*
  65. * Writes to the stream by calling the writeFn.
  66. * Will not print if it's invalid
  67. * Defaults to `_stream.write` (set on constructor)
  68. */
  69. LogDraft.prototype.write = function write() {
  70. this.valid && this._styleFn.apply(this._styleFn, arguments)
  71. }
  72. /*
  73. * Saves current line number as the insertion point
  74. */
  75. LogDraft.prototype.saveLine = function saveLine(relative) {
  76. relative = relative || 0
  77. this._line = this._stream.line() + relative
  78. }