bar.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. var Bar = module.exports = function (charm, x, y, params) {
  2. this.charm = charm;
  3. this.x = x;
  4. this.y = y;
  5. this.width = params.width || 10;
  6. this.offset = params.offset || 0;
  7. this.before = params.before || '[';
  8. this.after = params.after || '] ';
  9. this.solid = params.solid || {
  10. background : 'blue',
  11. foreground : 'white',
  12. text : '|'
  13. };
  14. this.empty = params.empty || {
  15. background : null,
  16. foreground : null,
  17. text : ' '
  18. };
  19. this.progress = {
  20. percent : 0,
  21. ratio : 0
  22. };
  23. }
  24. Bar.prototype.draw = function (bars, msg) {
  25. bars = Math.floor(bars);
  26. this.charm.push(true);
  27. if (this.y.toString().match(/^[+-]/)) {
  28. if (this.y.toString().match(/^-/)) {
  29. this.charm.up(-this.y + this.offset);
  30. }
  31. else if (this.y.toString().match(/^\+/)) {
  32. this.charm.down(+this.y - this.offset);
  33. }
  34. this.charm.column(+this.x);
  35. }
  36. else {
  37. this.charm.position(this.x, this.y);
  38. }
  39. this.charm.write(this.before);
  40. if (this.solid.background) {
  41. this.charm.background(this.solid.background);
  42. }
  43. if (this.solid.foreground) {
  44. this.charm.foreground(this.solid.foreground);
  45. }
  46. this.charm
  47. .write(Array(bars + 1).join(this.solid.text))
  48. .display('reset')
  49. ;
  50. if (this.empty.background) {
  51. this.charm.background(this.empty.background);
  52. }
  53. if (this.empty.foreground) {
  54. this.charm.foreground(this.empty.foreground);
  55. }
  56. this.charm
  57. .write(Array(this.width - bars + 1).join(this.empty.text))
  58. .write(this.after + msg)
  59. ;
  60. this.charm.pop(true);
  61. return this;
  62. };
  63. Bar.prototype.percent = function (p, msg) {
  64. if (p === undefined) {
  65. return this.progress.percent;
  66. }
  67. else {
  68. p = Math.min(100, p);
  69. this.progress.percent = p;
  70. this.progress.ratio = [ p, 100 ];
  71. this.draw(
  72. this.width * p / 100,
  73. msg || (Math.floor(p) + ' %')
  74. );
  75. return this;
  76. }
  77. };
  78. Bar.prototype.ratio = function (n, d, msg) {
  79. if (n === undefined && d === undefined) {
  80. return this.progress.ratio;
  81. }
  82. else {
  83. var f = n / d;
  84. this.progress.ratio = [ n, d ];
  85. this.progress.percent = f * 100;
  86. this.draw(
  87. this.width * f,
  88. msg || (n + ' / ' + d)
  89. );
  90. return this;
  91. }
  92. };