events.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. var { fromEvent } = require('rxjs');
  3. var { filter, map, share, takeUntil } = require('rxjs/operators');
  4. function normalizeKeypressEvents(value, key) {
  5. return { value: value, key: key || {} };
  6. }
  7. module.exports = function (rl) {
  8. var keypress = fromEvent(rl.input, 'keypress', normalizeKeypressEvents)
  9. .pipe(takeUntil(fromEvent(rl, 'close')))
  10. // Ignore `enter` key. On the readline, we only care about the `line` event.
  11. .pipe(filter(({ key }) => key.name !== 'enter' && key.name !== 'return'));
  12. return {
  13. line: fromEvent(rl, 'line'),
  14. keypress: keypress,
  15. normalizedUpKey: keypress.pipe(
  16. filter(
  17. ({ key }) =>
  18. key.name === 'up' || key.name === 'k' || (key.name === 'p' && key.ctrl)
  19. ),
  20. share()
  21. ),
  22. normalizedDownKey: keypress.pipe(
  23. filter(
  24. ({ key }) =>
  25. key.name === 'down' || key.name === 'j' || (key.name === 'n' && key.ctrl)
  26. ),
  27. share()
  28. ),
  29. numberKey: keypress.pipe(
  30. filter((e) => e.value && '123456789'.indexOf(e.value) >= 0),
  31. map((e) => Number(e.value)),
  32. share()
  33. ),
  34. spaceKey: keypress.pipe(
  35. filter(({ key }) => key && key.name === 'space'),
  36. share()
  37. ),
  38. aKey: keypress.pipe(
  39. filter(({ key }) => key && key.name === 'a'),
  40. share()
  41. ),
  42. iKey: keypress.pipe(
  43. filter(({ key }) => key && key.name === 'i'),
  44. share()
  45. ),
  46. };
  47. };