listview

package
v0.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2026 License: MIT Imports: 8 Imported by: 1

Documentation

Overview

Package listview provides a virtualized list widget that renders only visible items, enabling efficient display of large datasets.

Construction uses functional options for immutable configuration:

lv := listview.New(
    listview.ItemCount(len(data)),
    listview.FixedItemHeight(48),
    listview.BuildItem(func(ctx listview.ItemContext) widget.Widget {
        return primitives.NewText(data[ctx.Index].Name)
    }),
)

Height Modes

Three height modes are available, each with different performance characteristics:

  • FixedItemHeight -- O(1) fast path, all items share the same height
  • ItemHeightFn -- known heights via callback, O(log n) lookup
  • Default (lazy measurement) -- items measured on scroll, uses estimated average

ScrollView Composition

ListView composes an internal scrollview.Widget for scroll handling. All scroll features (wheel, keyboard PageUp/Down/Home/End, scrollbar thumb drag, momentum, signals) are provided automatically.

Selection

Optional item selection is supported via SelectedIndex or SelectedIndexSignal. Selection state is passed to the builder callback through [ItemContext.Selected].

Signal Binding

List properties can be bound to reactive signals from the state package. When a signal value changes, the list automatically reflects the new state.

Example with signals:

count := state.NewSignal(100)
selected := state.NewSignal(-1)

lv := listview.New(
    listview.ItemCountSignal(count),
    listview.FixedItemHeight(56),
    listview.SelectedIndexSignal(selected),
    listview.BuildItem(func(ctx listview.ItemContext) widget.Widget {
        return buildContactRow(contacts[ctx.Index], ctx.Selected)
    }),
    listview.OnEndReached(func() { loadMoreContacts() }),
    listview.Divider(true),
)

Visual Style

The visual rendering of list-specific elements (dividers, empty state, item backgrounds, selection highlights) is provided by a Painter implementation. Each design system (Material 3, Fluent, Cupertino) supplies its own painter.

If no painter is set, DefaultPainter is used, which draws minimal visuals suitable for testing and prototyping.

Accessibility

ListView implements a11y.Accessible with a11y.RoleList. Visible items are exposed as a11y.RoleListItem children. Keyboard navigation with arrow keys moves selection between items.

Focus

ListView implements widget.Focusable and participates in tab navigation. When focused, arrow keys move selection and Home/End jump to first/last item.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DefaultPainter

type DefaultPainter struct{}

DefaultPainter provides a minimal fallback painter with no design system styling. It draws simple list visuals -- useful for testing and as a base reference.

func (DefaultPainter) PaintDivider

func (p DefaultPainter) PaintDivider(canvas widget.Canvas, ds DividerState)

PaintDivider draws a thin horizontal line at the divider bounds.

func (DefaultPainter) PaintEmptyState

func (p DefaultPainter) PaintEmptyState(canvas widget.Canvas, bounds geometry.Rect)

PaintEmptyState draws a centered "No items" message.

func (DefaultPainter) PaintItemBackground

func (p DefaultPainter) PaintItemBackground(canvas widget.Canvas, ips ItemPaintState)

PaintItemBackground draws the background for a list item.

func (DefaultPainter) PaintSelection

func (p DefaultPainter) PaintSelection(canvas widget.Canvas, ips ItemPaintState)

PaintSelection draws the selection highlight for a selected item.

type DividerState

type DividerState struct {
	// Bounds is the rectangle for the divider (full width, typically 1px height).
	Bounds geometry.Rect

	// ItemIndex is the index of the item above the divider.
	ItemIndex int

	// ColorScheme provides theme-derived colors.
	ColorScheme ListColorScheme
}

DividerState provides context for divider painting.

type ItemContext

type ItemContext struct {
	// Index is the zero-based item index in the data source.
	Index int

	// Selected is true if this item is the currently selected item.
	Selected bool

	// Focused is true if this item has keyboard focus within the list.
	Focused bool

	// Hovered is true if the mouse cursor is over this item.
	Hovered bool
}

ItemContext provides contextual information to the item builder callback.

The builder receives an ItemContext for each visible item, allowing it to customize the returned widget based on selection, focus, and hover state.

type ItemPaintState

type ItemPaintState struct {
	// Bounds is the item's bounding rectangle.
	Bounds geometry.Rect

	// Index is the item's zero-based index in the data source.
	Index int

	// Selected is true if the item is selected.
	Selected bool

	// Focused is true if the item has keyboard focus within the list.
	Focused bool

	// Hovered is true if the mouse cursor is over this item.
	Hovered bool

	// Disabled is true if the list is disabled.
	Disabled bool

	// ColorScheme provides theme-derived colors.
	ColorScheme ListColorScheme
}

ItemPaintState provides context for item background and selection painting.

type ListColorScheme

type ListColorScheme struct {
	DividerColor      widget.Color // divider line color
	SelectionColor    widget.Color // selected item background
	HoverColor        widget.Color // hovered item background
	FocusColor        widget.Color // focused item border/background
	EmptyTextColor    widget.Color // empty state text color
	ItemBackground    widget.Color // alternating item background (even rows)
	ItemBackgroundAlt widget.Color // alternating item background (odd rows)
}

ListColorScheme provides theme-derived colors for list painting. Zero value means the painter should use its built-in defaults.

type Option

type Option func(*config)

Option configures a list view during construction.

func A11yLabel

func A11yLabel(label string) Option

A11yLabel sets the accessibility label for the list.

func BuildItem

func BuildItem(fn func(ctx ItemContext) widget.Widget) Option

BuildItem sets the callback that creates a widget for each visible item. The callback receives an ItemContext with the item's index and state. This is the primary convenience API for providing list content.

Internally, the function is wrapped into a cdk.FuncContent so that the list view uniformly operates on cdk.Content for item rendering.

func Disabled

func Disabled(d bool) Option

Disabled sets the list view's disabled state.

func DisabledFn

func DisabledFn(fn func() bool) Option

DisabledFn sets a dynamic function for the disabled state. When set, this takes precedence over Disabled but not over DisabledSignal.

func DisabledReadonlySignal

func DisabledReadonlySignal(sig state.ReadonlySignal[bool]) Option

DisabledReadonlySignal binds the disabled state to a read-only signal. When set, this takes highest precedence over all other disabled sources.

func DisabledSignal

func DisabledSignal(sig state.Signal[bool]) Option

DisabledSignal binds the disabled state to a reactive signal. When set, the signal takes precedence over DisabledFn and Disabled but not over DisabledReadonlySignal.

func Divider

func Divider(enabled bool) Option

Divider enables drawing a divider between list items. The divider is drawn by the Painter.

func EndReachedThreshold

func EndReachedThreshold(n int) Option

EndReachedThreshold sets how many items from the end triggers OnEndReached. Default: 5 items.

func EstimatedItemHeight

func EstimatedItemHeight(h float32) Option

EstimatedItemHeight sets the estimated height for items that have not been measured yet. Only used when neither FixedItemHeight nor ItemHeightFn is set. Default: 48 pixels.

func FixedItemHeight

func FixedItemHeight(h float32) Option

FixedItemHeight sets a uniform height for all items. This enables the O(1) fast path with no per-item measurement. Mutually exclusive with ItemHeightFn.

func ItemContent

func ItemContent(content cdk.Content[ItemContext]) Option

ItemContent sets the cdk.Content used to render each visible item. This is the enterprise API for providing list content — use it when you need reusable content implementations or progressive complexity (string → function → widget).

For most use cases, BuildItem is simpler and sufficient.

func ItemCount

func ItemCount(n int) Option

ItemCount sets the total number of items in the list.

func ItemCountFn

func ItemCountFn(fn func() int) Option

ItemCountFn sets a dynamic function that returns the item count. When set, this takes precedence over ItemCount but not over ItemCountSignal.

func ItemCountReadonlySignal

func ItemCountReadonlySignal(sig state.ReadonlySignal[int]) Option

ItemCountReadonlySignal binds the item count to a read-only signal. When set, this takes highest precedence over all other item count sources.

func ItemCountSignal

func ItemCountSignal(sig state.Signal[int]) Option

ItemCountSignal binds the item count to a reactive signal. When set, the signal takes precedence over ItemCountFn and ItemCount but not over ItemCountReadonlySignal.

func ItemHeightFn

func ItemHeightFn(fn func(index int) float32) Option

ItemHeightFn sets a callback that returns the height for the item at the given index. Heights are cached after first call, enabling O(log n) lookup via binary search on cumulative offsets. Mutually exclusive with FixedItemHeight.

func OnEndReached

func OnEndReached(fn func()) Option

OnEndReached sets the callback invoked when the user scrolls near the end of the list. Useful for infinite scroll / pagination. The threshold is configurable via EndReachedThreshold.

func OnItemClick

func OnItemClick(fn func(index int)) Option

OnItemClick sets the callback invoked when an item is clicked.

func OnScroll

func OnScroll(fn func(offset float32)) Option

OnScroll sets the callback invoked when the scroll position changes.

func OnSelectionChange

func OnSelectionChange(fn func(index int)) Option

OnSelectionChange sets the callback invoked when the selected item changes.

func Overscan

func Overscan(n int) Option

Overscan sets the number of extra items to render above and below the visible viewport. Higher values reduce blank flashes during fast scroll at the cost of rendering more items. Default: 3 items.

func PainterOpt

func PainterOpt(p Painter) Option

PainterOpt sets the painter used to render list-specific visuals. Each design system provides its own painter. If not set, DefaultPainter is used.

func ScrollYSignal

func ScrollYSignal(sig state.Signal[float32]) Option

ScrollYSignal binds the vertical scroll offset to a reactive signal. This is a TWO-WAY binding passed through to the internal ScrollView.

func SelectedIndex

func SelectedIndex(index int) Option

SelectedIndex sets the initially selected item index. Use -1 for no selection.

func SelectedIndexReadonlySignal

func SelectedIndexReadonlySignal(sig state.ReadonlySignal[int]) Option

SelectedIndexReadonlySignal binds the selected index to a read-only signal. When set, this takes highest precedence over all other selection sources.

func SelectedIndexSignal

func SelectedIndexSignal(sig state.Signal[int]) Option

SelectedIndexSignal binds the selected index to a reactive signal. This is a TWO-WAY binding: the widget reads from the signal, and when the user selects an item, the new index is written back.

func SelectionModeOpt

func SelectionModeOpt(mode SelectionMode) Option

SelectionModeOpt sets the selection mode for the list. Default is SelectionNone.

type Painter

type Painter interface {
	// PaintDivider draws a divider line between items.
	PaintDivider(canvas widget.Canvas, state DividerState)

	// PaintEmptyState draws the empty state when ItemCount is 0.
	PaintEmptyState(canvas widget.Canvas, bounds geometry.Rect)

	// PaintItemBackground draws the background for a list item.
	// This is called before the item widget's own Draw method.
	PaintItemBackground(canvas widget.Canvas, state ItemPaintState)

	// PaintSelection draws the selection highlight for a selected item.
	// This is called before the item widget's own Draw method.
	PaintSelection(canvas widget.Canvas, state ItemPaintState)
}

Painter draws list-specific visual elements. Each design system (Material 3, Fluent, Cupertino) provides its own Painter implementation to render the list in its visual style.

If no Painter is set, the list view uses DefaultPainter.

type SelectionMode

type SelectionMode uint8

SelectionMode defines how items can be selected in the list.

const (
	// SelectionNone disables item selection. This is the default.
	SelectionNone SelectionMode = iota

	// SelectionSingle allows at most one item to be selected at a time.
	SelectionSingle
)

SelectionMode constants.

func (SelectionMode) String

func (m SelectionMode) String() string

String returns a human-readable name for the selection mode.

type Widget

type Widget struct {
	widget.WidgetBase
	// contains filtered or unexported fields
}

Widget implements a virtualized list that renders only visible items. It composes an internal scrollview.Widget for scroll handling and delegates item rendering to a builder callback.

A list view is created with New using functional options:

lv := listview.New(
    listview.ItemCount(len(data)),
    listview.FixedItemHeight(48),
    listview.BuildItem(func(ctx listview.ItemContext) widget.Widget {
        return buildRow(data[ctx.Index])
    }),
)

func New

func New(opts ...Option) *Widget

New creates a new list view Widget with the given options.

The returned widget is visible, enabled, and focusable by default. If no BuildItem callback is provided, the list renders empty.

func (*Widget) AccessibilityActions

func (w *Widget) AccessibilityActions() []a11y.Action

AccessibilityActions returns the list of supported actions.

func (*Widget) AccessibilityHint

func (w *Widget) AccessibilityHint() string

AccessibilityHint returns the accessibility hint.

func (*Widget) AccessibilityLabel

func (w *Widget) AccessibilityLabel() string

AccessibilityLabel returns the accessibility label.

func (*Widget) AccessibilityRole

func (w *Widget) AccessibilityRole() a11y.Role

AccessibilityRole returns the ARIA role for this widget.

func (*Widget) AccessibilityState

func (w *Widget) AccessibilityState() a11y.State

AccessibilityState returns the current accessibility state.

func (*Widget) AccessibilityValue

func (w *Widget) AccessibilityValue() string

AccessibilityValue returns the current list state as a string.

func (*Widget) Children

func (w *Widget) Children() []widget.Widget

Children returns the internal scroll view as the single child.

func (*Widget) Draw

func (w *Widget) Draw(ctx widget.Context, canvas widget.Canvas)

Draw renders the list view to the canvas.

func (*Widget) Event

func (w *Widget) Event(ctx widget.Context, e event.Event) bool

Event handles an input event and returns true if consumed.

func (*Widget) GetItemCount

func (w *Widget) GetItemCount() int

GetItemCount returns the current item count.

func (*Widget) InvalidateData

func (w *Widget) InvalidateData()

InvalidateData signals that the underlying data has changed. This invalidates the widget cache and triggers re-layout.

func (*Widget) IsFocusable

func (w *Widget) IsFocusable() bool

IsFocusable reports whether the list view can currently receive focus.

func (*Widget) Layout

func (w *Widget) Layout(ctx widget.Context, constraints geometry.Constraints) geometry.Size

Layout calculates the list view's size within the given constraints.

func (*Widget) Mount

func (w *Widget) Mount(ctx widget.Context)

Mount creates signal bindings for push-based invalidation. Implements widget.Lifecycle.

func (*Widget) ScrollToIndex

func (w *Widget) ScrollToIndex(index int)

ScrollToIndex scrolls to make the item at the given index visible. If the item is already fully visible, this is a no-op.

func (*Widget) Unmount

func (w *Widget) Unmount()

Unmount is called when the list view is removed from the widget tree. Implements widget.Lifecycle.

func (*Widget) VisibleRange

func (w *Widget) VisibleRange() (start, end int)

VisibleRange returns the indices of currently visible items [start, end).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL