| 1 |
package huh |
| 2 |
|
| 3 |
import ( |
| 4 |
"time" |
| 5 |
|
| 6 |
"github.com/mitchellh/hashstructure/v2" |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
type Eval[T any] struct { |
| 15 |
val T |
| 16 |
fn func() T |
| 17 |
|
| 18 |
bindings any |
| 19 |
bindingsHash uint64 |
| 20 |
cache map[uint64]T |
| 21 |
|
| 22 |
loading bool |
| 23 |
loadingStart time.Time |
| 24 |
} |
| 25 |
|
| 26 |
const spinnerShowThreshold = 25 * time.Millisecond |
| 27 |
|
| 28 |
func hash(val any) uint64 { |
| 29 |
hash, _ := hashstructure.Hash(val, hashstructure.FormatV2, nil) |
| 30 |
return hash |
| 31 |
} |
| 32 |
|
| 33 |
func (e *Eval[T]) shouldUpdate() (bool, uint64) { |
| 34 |
if e.fn == nil { |
| 35 |
return false, 0 |
| 36 |
} |
| 37 |
newHash := hash(e.bindings) |
| 38 |
return e.bindingsHash != newHash, newHash |
| 39 |
} |
| 40 |
|
| 41 |
func (e *Eval[T]) loadFromCache() bool { |
| 42 |
val, ok := e.cache[e.bindingsHash] |
| 43 |
if ok { |
| 44 |
e.loading = false |
| 45 |
e.val = val |
| 46 |
} |
| 47 |
return ok |
| 48 |
} |
| 49 |
|
| 50 |
func (e *Eval[T]) update(val T) { |
| 51 |
e.val = val |
| 52 |
e.cache[e.bindingsHash] = val |
| 53 |
e.loading = false |
| 54 |
} |
| 55 |
|
| 56 |
type updateTitleMsg struct { |
| 57 |
id int |
| 58 |
hash uint64 |
| 59 |
title string |
| 60 |
} |
| 61 |
|
| 62 |
type updateDescriptionMsg struct { |
| 63 |
id int |
| 64 |
hash uint64 |
| 65 |
description string |
| 66 |
} |
| 67 |
|
| 68 |
type updatePlaceholderMsg struct { |
| 69 |
id int |
| 70 |
hash uint64 |
| 71 |
placeholder string |
| 72 |
} |
| 73 |
|
| 74 |
type updateSuggestionsMsg struct { |
| 75 |
id int |
| 76 |
hash uint64 |
| 77 |
suggestions []string |
| 78 |
} |
| 79 |
|
| 80 |
type updateOptionsMsg[T comparable] struct { |
| 81 |
id int |
| 82 |
hash uint64 |
| 83 |
options []Option[T] |
| 84 |
} |