events.js 1.3 KB

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