github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/dos/ui/logic.go (about)

     1  package ui
     2  
     3  import termbox "github.com/nsf/termbox-go"
     4  
     5  func (form *Form) Show() {
     6  	// initial load
     7  	err := form.Record.Load()
     8  	if err != nil {
     9  		//TODO: handle error properly
    10  		panic(err)
    11  	}
    12  
    13  	// init all components, layouts
    14  	form.Init()
    15  
    16  	// save if needed
    17  	defer func() {
    18  		if form.Save {
    19  			if err := form.Record.Save(); err != nil {
    20  				//TODO: handle error properly
    21  				panic(err)
    22  			}
    23  		}
    24  	}()
    25  
    26  	// update global forms list
    27  	form.Screen.Push(form)
    28  	defer form.Screen.Pop()
    29  
    30  	// initial render
    31  	if len(form.Screen.Actions) == 0 {
    32  		form.Render()
    33  	}
    34  	defer form.Erase()
    35  
    36  	// handle actions
    37  	for action := range form.Screen.Actions {
    38  		form.Handle(action)
    39  
    40  		if len(form.Screen.Actions) == 0 {
    41  			form.Render()
    42  		}
    43  
    44  		if form.Close {
    45  			break
    46  		}
    47  	}
    48  }
    49  
    50  func (form *Form) TabFocus(delta int) {
    51  	base := form.FocusedIndex
    52  	if base < 0 {
    53  		base = 0
    54  	}
    55  
    56  	for _, component := range form.Components {
    57  		component.Focused = false
    58  	}
    59  
    60  	for offset := 0; offset < len(form.Components); offset++ {
    61  		k := (base + delta*offset + len(form.Components)) % len(form.Components)
    62  		if k == form.FocusedIndex {
    63  			continue
    64  		}
    65  
    66  		component := form.Components[k]
    67  		if component.Widget.Focusable() {
    68  			form.FocusedIndex = k
    69  			component.Focused = true
    70  			return
    71  		}
    72  	}
    73  
    74  	form.FocusedIndex = -1
    75  }
    76  
    77  func (form *Form) Handle(action Action) {
    78  	switch action := action.(type) {
    79  	case KeyPress:
    80  		switch action.Key {
    81  		// focus handling
    82  		case termbox.KeyArrowUp:
    83  			form.TabFocus(-1)
    84  			return
    85  		case termbox.KeyTab, termbox.KeyArrowDown: // TODO: add ShiftTab
    86  			form.TabFocus(1)
    87  			return
    88  
    89  		// closing/saving
    90  		case termbox.KeyEsc:
    91  			form.Close = true
    92  			return
    93  		case termbox.KeyCtrlS:
    94  			form.Close = true
    95  			form.Save = true
    96  			return
    97  		}
    98  	}
    99  
   100  	if 0 <= form.FocusedIndex && form.FocusedIndex < len(form.Components) {
   101  		focused := form.Components[form.FocusedIndex]
   102  		focused.Widget.Handle(form, action)
   103  	}
   104  }