placeholder.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const utils = require('./utils');
  3. /**
  4. * Render a placeholder value with cursor and styling based on the
  5. * position of the cursor.
  6. *
  7. * @param {Object} `prompt` Prompt instance.
  8. * @param {String} `input` Input string.
  9. * @param {String} `initial` The initial user-provided value.
  10. * @param {Number} `pos` Current cursor position.
  11. * @param {Boolean} `showCursor` Render a simulated cursor using the inverse primary style.
  12. * @return {String} Returns the styled placeholder string.
  13. * @api public
  14. */
  15. module.exports = (prompt, options = {}) => {
  16. prompt.cursorHide();
  17. let { input = '', initial = '', pos, showCursor = true, color } = options;
  18. let style = color || prompt.styles.placeholder;
  19. let inverse = utils.inverse(prompt.styles.primary);
  20. let blinker = str => inverse(prompt.styles.black(str));
  21. let output = input;
  22. let char = ' ';
  23. let reverse = blinker(char);
  24. if (prompt.blink && prompt.blink.off === true) {
  25. blinker = str => str;
  26. reverse = '';
  27. }
  28. if (showCursor && pos === 0 && initial === '' && input === '') {
  29. return blinker(char);
  30. }
  31. if (showCursor && pos === 0 && (input === initial || input === '')) {
  32. return blinker(initial[0]) + style(initial.slice(1));
  33. }
  34. initial = utils.isPrimitive(initial) ? `${initial}` : '';
  35. input = utils.isPrimitive(input) ? `${input}` : '';
  36. let placeholder = initial && initial.startsWith(input) && initial !== input;
  37. let cursor = placeholder ? blinker(initial[input.length]) : reverse;
  38. if (pos !== input.length && showCursor === true) {
  39. output = input.slice(0, pos) + blinker(input[pos]) + input.slice(pos + 1);
  40. cursor = '';
  41. }
  42. if (showCursor === false) {
  43. cursor = '';
  44. }
  45. if (placeholder) {
  46. let raw = prompt.styles.unstyle(output + cursor);
  47. return output + cursor + style(initial.slice(raw.length));
  48. }
  49. return output + cursor;
  50. };