spinner.go

 1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: AGPL-3.0-or-later
 4
 5package ui
 6
 7import (
 8	"fmt"
 9
10	"github.com/charmbracelet/huh/spinner"
11)
12
13// Spin executes fn while displaying a spinner with the given title.
14// Uses generics to preserve the return type of the wrapped function.
15func Spin[T any](title string, fn func() (T, error)) (T, error) {
16	var result T
17
18	var fnErr error
19
20	spinErr := spinner.New().
21		Title(title).
22		Action(func() {
23			result, fnErr = fn()
24		}).
25		Run()
26	if spinErr != nil {
27		return result, fmt.Errorf("spinner: %w", spinErr)
28	}
29
30	return result, fnErr
31}
32
33// SpinVoid executes fn while displaying a spinner with the given title.
34// Use for functions that only return an error.
35func SpinVoid(title string, fn func() error) error {
36	var fnErr error
37
38	spinErr := spinner.New().
39		Title(title).
40		Action(func() {
41			fnErr = fn()
42		}).
43		Run()
44	if spinErr != nil {
45		return fmt.Errorf("spinner: %w", spinErr)
46	}
47
48	return fnErr
49}