github.com/oam-dev/kubevela@v1.9.11/references/cli/top/model/key_actions.go (about)

     1  /*
     2  Copyright 2022 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package model
    18  
    19  import (
    20  	"sort"
    21  
    22  	"github.com/gdamore/tcell/v2"
    23  )
    24  
    25  // KeyAction is key action struct
    26  type KeyAction struct {
    27  	Description string
    28  	Action      func(*tcell.EventKey) *tcell.EventKey
    29  	Visible     bool
    30  	Shared      bool
    31  }
    32  
    33  // KeyActions is a map from key to action
    34  type KeyActions map[tcell.Key]KeyAction
    35  
    36  // Hint convert key action map to menu hints
    37  func (ka KeyActions) Hint() []MenuHint {
    38  	tmp := make([]int, 0)
    39  	for k := range ka {
    40  		tmp = append(tmp, int(k))
    41  	}
    42  	sort.Ints(tmp)
    43  	hints := make([]MenuHint, 0)
    44  
    45  	for _, key := range tmp {
    46  		if name, ok := tcell.KeyNames[tcell.Key(key)]; ok {
    47  			hints = append(hints,
    48  				MenuHint{
    49  					Key:         name,
    50  					Description: ka[tcell.Key(key)].Description,
    51  				},
    52  			)
    53  		}
    54  	}
    55  	return hints
    56  }
    57  
    58  // Add a key action to key action map
    59  func (ka KeyActions) Add(actions KeyActions) {
    60  	for k, v := range actions {
    61  		ka[k] = v
    62  	}
    63  }
    64  
    65  // Set a key action to key action map
    66  func (ka KeyActions) Set(actions KeyActions) {
    67  	for k, v := range actions {
    68  		ka[k] = v
    69  	}
    70  }
    71  
    72  // Delete aim key from key action map
    73  func (ka KeyActions) Delete(kk []tcell.Key) {
    74  	for _, k := range kk {
    75  		delete(ka, k)
    76  	}
    77  }
    78  
    79  // Clear key action map clear up
    80  func (ka KeyActions) Clear() {
    81  	for k := range ka {
    82  		delete(ka, k)
    83  	}
    84  }