rediscli.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. var RedisCli = function(postUrl) {
  2. // Constants
  3. var KEY_UP = 38;
  4. var KEY_DOWN = 40;
  5. var MAX_ITEMS = 128;
  6. var $con = $('.console');
  7. var $container = $con.find('.console-container');
  8. var $input = $con.find('input');
  9. var history = [];
  10. var historyPos = 0;
  11. function resizeConsole() {
  12. var height = $(window).height();
  13. var offset = $con.offset();
  14. $con.height(height - offset.top);
  15. }
  16. function scrollBottom() {
  17. $container.animate({scrollTop: $container[0].scrollHeight}, 100);
  18. }
  19. function createEntry(cmd) {
  20. var $entry = $('<div>').addClass('entry').appendTo($container);
  21. $entry.append($('<div>').addClass('cmd').html(cmd));
  22. if ($container.find('>div').length > MAX_ITEMS)
  23. $container.find('>div:first-child').remove();
  24. scrollBottom();
  25. return $entry;
  26. }
  27. function addResponse($entry, response) {
  28. $entry.append($('<div>').addClass('response').html(response));
  29. scrollBottom();
  30. }
  31. function addError($entry, response) {
  32. $entry.append($('<div>').addClass('response').addClass('error').html(response));
  33. scrollBottom();
  34. }
  35. function addHistory(cmd) {
  36. history.push(cmd);
  37. if (history > MAX_ITEMS)
  38. history.splice(0, 1);
  39. historyPos = history.length;
  40. }
  41. function sendCommand(val) {
  42. var $entry = createEntry('> ' + val);
  43. addHistory(val);
  44. $.ajax({
  45. type: 'POST',
  46. url: postUrl,
  47. data: {'cmd': val},
  48. success: function(response) {
  49. addResponse($entry, response);
  50. },
  51. error: function() {
  52. addError($entry, 'Failed to communicate with server.');
  53. }
  54. });
  55. return false;
  56. }
  57. function submitCommand() {
  58. var val = $input.val().trim();
  59. if (!val.length)
  60. return false;
  61. sendCommand(val);
  62. $input.val('');
  63. }
  64. function onKeyPress(e) {
  65. if (e.keyCode == KEY_UP) {
  66. historyPos -= 1;
  67. if (historyPos < 0)
  68. historyPos = 0;
  69. if (historyPos < history.length)
  70. $input.val(history[historyPos]);
  71. } else
  72. if (e.keyCode == KEY_DOWN) {
  73. historyPos += 1;
  74. if (historyPos >= history.length) {
  75. $input.val('');
  76. historyPos = history.length;
  77. } else {
  78. $input.val(history[historyPos]);
  79. }
  80. }
  81. }
  82. // Setup
  83. $con.find('form').submit(submitCommand);
  84. $input.keydown(onKeyPress);
  85. $(window).resize(resizeConsole);
  86. resizeConsole();
  87. $input.focus();
  88. sendCommand('ping');
  89. };