github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/view/cli/render.go (about)

     1  package cli
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  
     8  	. "github.com/egonelbre/exp/view"
     9  )
    10  
    11  type Lay struct {
    12  	Node     *Node
    13  	Parent   *Lay
    14  	Children []*Lay
    15  }
    16  
    17  func Layout(node *Node) (*Lay, error) {
    18  	lay := &Lay{Node: node}
    19  	for _, child := range node.Children {
    20  		sub, err := Layout(child)
    21  		if err != nil {
    22  			return nil, err
    23  		}
    24  		sub.Parent = lay
    25  		lay.Children = append(lay.Children, sub)
    26  	}
    27  	return lay, nil
    28  }
    29  
    30  func (lay *Lay) render(w io.Writer, indent string) {
    31  	node := lay.Node
    32  
    33  	inslice := lay.Parent != nil && lay.Parent.Node.Slice
    34  	nested := (len(node.Children) > 0)
    35  
    36  	name := node.Name
    37  	if name == "" {
    38  		name = node.Type
    39  	}
    40  
    41  	switch {
    42  	case inslice:
    43  		fmt.Fprintf(w, "%s┌───────\n", indent)
    44  	case nested:
    45  		fmt.Fprintf(w, "%s┌─ %s ──\n", indent, name)
    46  	}
    47  
    48  	switch node.Type {
    49  	case "Field":
    50  		value, _ := node.Str("value")
    51  		back := strings.Repeat("▒", 20)
    52  		fmt.Fprintf(w, "%s%s\n", indent, back+value)
    53  	case "Checkbox":
    54  		value, _ := node.Bool("checked")
    55  		if value {
    56  			fmt.Fprintf(w, "%s│ │\n", indent)
    57  		} else {
    58  			fmt.Fprintf(w, "%s│X│\n", indent)
    59  		}
    60  	case "Button":
    61  		fmt.Fprintf(w, "%s[%s]\n", indent, node.Name)
    62  	}
    63  
    64  	for _, child := range lay.Children {
    65  		child.render(w, indent+"  ")
    66  	}
    67  
    68  	switch {
    69  	case inslice:
    70  	case nested:
    71  		fmt.Fprintf(w, "%s└──%s───\n", indent, strings.Repeat("─", len(name)))
    72  	}
    73  }
    74  
    75  func Render(lay *Lay, w io.Writer) error {
    76  	for _, child := range lay.Children {
    77  		child.render(w, "")
    78  		fmt.Println()
    79  	}
    80  	return nil
    81  }