Skip to content
Myr

main.go

This file

Path

examples/clickable/main.go

369 lines · 7.7 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23import (4	"fmt"5	"os"67	tea "charm.land/bubbletea/v2"8	"charm.land/lipgloss/v2"9	"github.com/segmentio/ksuid"10)1112// LayerHitMsg is a message that is sent to the program when a layer is hit by13// a mouse event. This is used to determine which layer in a compostable view14// was hit by the mouse event. The layer is identified by its ID, which is a15// string that is unique to the layer.16type LayerHitMsg struct {17	ID    string18	Mouse tea.MouseMsg19}2021const maxDialogs = 9992223// Styles24var (25	bgTextStyle = lipgloss.NewStyle().26			Foreground(lipgloss.Color("239")).27			Padding(1, 2)2829	bgWhitespace = []lipgloss.WhitespaceOption{30		lipgloss.WithWhitespaceChars("/"),31		lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("238"))),32	}3334	dialogWordStyle = lipgloss.NewStyle().35			Foreground(lipgloss.Color("#E7E1CC"))3637	dialogStyle = dialogWordStyle.38			Width(36).39			Height(8).40			Padding(1, 3).41			Border(lipgloss.RoundedBorder()).42			BorderForeground(lipgloss.Color("#874BFD"))4344	hoveredDialogStyle = dialogStyle.45				BorderForeground(lipgloss.Color("#F25D94"))4647	specialWordLightColor = lipgloss.Color("#43BF6D")48	specialWordDarkColor  = lipgloss.Color("#73F59F")4950	buttonStyle = lipgloss.NewStyle().51			Padding(0, 3).52			Foreground(lipgloss.Color("#FFF7DB")).53			Background(lipgloss.Color("#6124DF"))5455	hoveredButtonStyle = buttonStyle.56				Background(lipgloss.Color("#FF5F87"))57)5859// Model6061type model struct {62	specialWordStyle lipgloss.Style63	width, height    int64	dialogs          []dialog65	mouseDown        bool66	pressID          string67	dragID           string68	dragOffsetX      int69	dragOffsetY      int70}7172func (m model) Init() tea.Cmd {73	return tea.Batch(74		tea.RequestBackgroundColor,75	)76}7778func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {79	switch msg := msg.(type) {80	case tea.WindowSizeMsg:81		m.width, m.height = msg.Width, msg.Height8283	case tea.BackgroundColorMsg:84		if msg.IsDark() {85			m.specialWordStyle = m.specialWordStyle.Foreground(specialWordDarkColor)86		} else {87			m.specialWordStyle = m.specialWordStyle.Foreground(specialWordLightColor)88		}8990	case tea.KeyPressMsg:91		switch msg.String() {92		case "q", "ctrl+c", "esc":93			return m, tea.Quit94		}9596	case LayerHitMsg:97		mouse := msg.Mouse.Mouse()9899		switch msg.Mouse.(type) {100		case tea.MouseClickMsg:101			if mouse.Button != tea.MouseLeft {102				break103			}104105			// Initial press106			if !m.mouseDown {107				m.mouseDown = true108				m.pressID = msg.ID109110				// Did we press on a dialog box?111				for i, d := range m.dialogs {112					if d.id != msg.ID {113						continue114					}115116					// Init drag117					m.dragID = msg.ID118					m.dragOffsetX = mouse.X - d.x119					m.dragOffsetY = mouse.Y - d.y120121					if len(m.dialogs) < 2 {122						break123					}124125					// Move the one we're going to drag to the end of the slice126					// so that it gets the highest z-index when we do127					// compositing later. There are, of course, lots of other128					// ways you could manage the z-index, too.129					m.dialogs = m.removeDialog(i)130					m.dialogs = append(m.dialogs, d)131					break132				}133134				break135			}136137		// MouseMotion events are send when the mouse has moved and a mouse138		// button is not pressed.139		case tea.MouseMotionMsg:140			// Dragging141			if m.mouseDown && m.dragID != "" {142				// Find the dialog box we're dragging143				for i := range m.dialogs {144					d := &m.dialogs[i]145					if d.id != m.dragID {146						continue147					}148149					// Move the dialog box with the cursor150					if m.dragID == d.id {151						d.x = clamp(mouse.X-(m.dragOffsetX), 0, m.width-lipgloss.Width(d.windowView()))152						d.y = clamp(mouse.Y-(m.dragOffsetY), 0, m.height-lipgloss.Height(d.windowView()))153					}154155					break156				}157			}158159			// Are we hoving over a dialog box?160			for i := range m.dialogs {161162				d := &m.dialogs[i]163				d.hovering = false164				d.hoveringButton = false165166				if d.id == msg.ID {167					d.hovering = true168					continue169				}170				if d.buttonID == msg.ID {171					d.hovering = true172					d.hoveringButton = true173					continue174				}175			}176177		case tea.MouseReleaseMsg:178179			// Make sure we're releasing on something with an ID. A successful180			// click is a press and release.181			if m.pressID == "" {182				break183			}184185			// Did we click a button?186			for i, d := range m.dialogs {187				if msg.ID == d.buttonID && m.pressID == d.buttonID {188					// "Close" the window189					m.dialogs = m.removeDialog(i)190					break191				}192			}193194			// Clicking the background spawns a new dialog195			if msg.ID == "bg" && m.pressID == "bg" {196				if len(m.dialogs) < maxDialogs {197					m.dialogs = append(m.dialogs, m.newDialog(mouse.X, mouse.Y))198				}199			}200201			m.mouseDown = false202			m.dragID = ""203			m.pressID = ""204		}205	}206207	return m, nil208}209210func (m model) View() tea.View {211	var v tea.View212	var body string213214	n := len(m.dialogs)215	if n > 0 {216		body += "Drag to move. "217	}218	if n == 0 && n < maxDialogs {219		body += "Click to spawn."220	} else if n >= 1 && n < maxDialogs {221		body += fmt.Sprintf("Click to spawn up to %d more.", maxDialogs-len(m.dialogs))222	}223	body += "\n\nPress q to quit."224225	bg := lipgloss.Place(226		m.width,227		m.height,228		lipgloss.Top,229		lipgloss.Left,230		bgTextStyle.Render(body),231		bgWhitespace...,232	)233234	root := lipgloss.NewLayer(bg).ID("bg")235	for i, d := range m.dialogs {236		root.AddLayers(d.view().Z(i + 1))237	}238239	comp := lipgloss.NewCompositor(root)240241	v.MouseMode = tea.MouseModeAllMotion242	v.AltScreen = true243	v.OnMouse = func(msg tea.MouseMsg) tea.Cmd {244		return func() tea.Msg {245			mouse := msg.Mouse()246			x, y := mouse.X, mouse.Y247			if id := comp.Hit(x, y).ID(); id != "" {248				return LayerHitMsg{249					ID:    id,250					Mouse: msg,251				}252			}253			return nil254		}255	}256	v.SetContent(comp.Render())257258	return v259}260261func (m *model) newDialog(x, y int) (d dialog) {262	d.specialWordStyle = &m.specialWordStyle263	dummyView := d.windowView()264	w := lipgloss.Width(dummyView)265	h := lipgloss.Height(dummyView)266	d.x = clamp(x-w/2, 0, m.width-w)267	d.y = clamp(y-h/2, 0, m.height-h)268	d.text = nextRandomWord()269	d.id = ksuid.New().String()270	d.buttonID = ksuid.New().String()271	return d272}273274func (m model) removeDialog(index int) []dialog {275	d := m.dialogs276277	if len(d) <= index {278		return m.dialogs279	}280281	copy(d[index:], d[index+1:]) // shift282	d[len(d)-1] = dialog{}       // nullify283	return d[:len(d)-1]          // truncate284}285286// Dialog Windows287288type dialog struct {289	specialWordStyle *lipgloss.Style290	id               string291	buttonID         string292	x, y             int293	text             string294	hovering         bool295	hoveringButton   bool296}297298func (d dialog) buttonView() string {299	const label = "Run Away"300301	if d.hoveringButton {302		return hoveredButtonStyle.Render(label)303	}304	return buttonStyle.Render(label)305}306307func (d dialog) windowView() string {308	var style lipgloss.Style309	if d.hovering {310		style = hoveredDialogStyle311	} else {312		style = dialogStyle313	}314315	s := d.specialWordStyle.Render(d.text) + dialogWordStyle.Render(" draws near. Command?")316	return style.Render(s)317}318319func (d dialog) view() *lipgloss.Layer {320	const hGap, vGap = 3, 1321322	window := d.windowView()323	button := d.buttonView()324325	buttonX := lipgloss.Width(window) - lipgloss.Width(button) - 1 - hGap326	buttonY := lipgloss.Height(window) - lipgloss.Height(button) - 1 - vGap327328	buttonLayer := lipgloss.NewLayer(button).329		ID(d.buttonID).330		X(buttonX).331		Y(buttonY)332333	return lipgloss.NewLayer(window).334		ID(d.id).335		X(d.x).336		Y(d.y).337		AddLayers(buttonLayer)338}339340// Main341342func main() {343	ksuid.SetRand(ksuid.FastRander)344345	path := os.Getenv("TEA_LOGFILE")346	if path != "" {347		f, err := tea.LogToFile(path, "layers")348		if err != nil {349			fmt.Println("could not open logfile:", err)350			os.Exit(1)351		}352		defer f.Close()353	}354355	if _, err := tea.NewProgram(model{}).Run(); err != nil {356		fmt.Println("Error while running program:", err)357		os.Exit(1)358	}359}360361func clamp(n, min, max int) int {362	if n < min {363		return min364	}365	if n > max {366		return max367	}368	return n369}