« get me outta code hell

Form.js « form « ui - tui-lib - Pure Node.js library for making visual command-line programs (ala vim, ncdu)
about summary refs log tree commit diff
path: root/ui/form/Form.js
blob: cf94978bc87d8f0434cc8fcbd135c978a8fa7f30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const telc = require('../../util/telchars')

const FocusElement = require('./FocusElement')

module.exports = class Form extends FocusElement {
  constructor() {
    super()

    this.inputs = []
    this.curIndex = 0
  }

  addInput(input, asChild = true) {
    // Adds the given input as a child element and pushes it to the input
    // list. If the second optional, asChild, is false, it won't add the
    // input element as a child of the form.

    this.inputs.push(input)

    if (asChild) {
      this.addChild(input)
    }
  }

  keyPressed(keyBuf) {
    if (telc.isTab(keyBuf) || telc.isBackTab(keyBuf)) {
      // No inputs to tab through, so do nothing.
      if (this.inputs.length < 2) {
        return
      }

      if (telc.isTab(keyBuf)) {
        this.nextInput()
      } else {
        this.previousInput()
      }

      return false
    }
  }

  updateSelectedElement() {
    this.root.select(this.inputs[this.curIndex])
  }

  previousInput() {
    this.curIndex = (this.curIndex - 1)
    if (this.curIndex < 0) {
      this.curIndex = (this.inputs.length - 1)
    }

    this.updateSelectedElement()
  }

  nextInput() {
    this.curIndex = (this.curIndex + 1) % this.inputs.length

    this.updateSelectedElement()
  }
  
  focused() {
    this.root.select(this.inputs[this.curIndex])
  }
}