bubbles icon indicating copy to clipboard operation
bubbles copied to clipboard

Feat(list): enable filtering programmatically

Open fkhadra opened this issue 3 years ago • 3 comments

Hey! This PR aims to address #85. The names for the method I've added are coming from #129.

  • set filter value programmatically
  • enable filtering programmatically. Apply filter if needed

https://user-images.githubusercontent.com/5574267/183026053-8169a28c-b862-467b-bdf6-d538769148df.mov

Below is the code used in the video. I tried to keep it as simple as possible

package main

import (
	"github.com/charmbracelet/bubbles/list"
	tea "github.com/charmbracelet/bubbletea"
)

type item struct {
	title string
}

func (i item) Title() string       { return i.title }
func (i item) Description() string { return i.title }
func (i item) FilterValue() string { return i.title }

type Model struct {
	list list.Model
}

func New() Model {
	items := []list.Item{
		item{title: "red"},
		item{title: "blue"},
		item{title: "orange"},
		item{title: "purple"},
		item{title: "green"},
		item{title: "magenta"},
	}
	l := list.New(items, list.NewDefaultDelegate(), 100, 100)

	// uncomment to set default filter value
	// l.SetFilterValue("purple")

	return Model{
		list: l,
	}
}

func (m Model) Init() tea.Cmd {
	// used to enable filtering programmatically
	return list.EnableLiveFiltering
}

func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var (
		cmd  tea.Cmd
		cmds []tea.Cmd
	)

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.list.SetSize(msg.Width, msg.Height)
	}

	m.list, cmd = m.list.Update(msg)
	cmds = append(cmds, cmd)

	return m, tea.Batch(cmds...)
}

func (m Model) View() string {
	return m.list.View()
}

I did not implement a way to disable the filter programmatically as I believe this can already be done using ResetFilter.

I've also tested my implementation with a custom input by setting l.SetShowFilter(false).

fkhadra avatar Aug 05 '22 07:08 fkhadra

Hi! This is awesome and I'm waiting for this anxiously! Currently thinking about using raw FZF but a bubble with default fuzzy search would be SO GOOD TO HAVE!

omerxx avatar Aug 25 '23 09:08 omerxx

Hey @omerxx, it's quick handy idd, you can see it in action here https://github.com/fkhadra/caniuse. But I think my PR will be superseded by https://github.com/charmbracelet/bubbles/pull/201. Let's wait for the maintainers :)

fkhadra avatar Sep 03 '23 08:09 fkhadra

This is excellent! I want to this feature too.

reiki4040 avatar May 05 '24 06:05 reiki4040