gridview

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package gridview provides a virtualized 2D grid widget that renders only visible cells, enabling efficient display of large datasets in a grid layout.

Construction uses functional options for immutable configuration:

gv := gridview.New(
    gridview.Columns(4),
    gridview.ItemCount(1000),
    gridview.ItemSize(120, 120),
    gridview.BuildCell(func(index int, ctx gridview.CellContext) widget.Widget {
        return primitives.NewText(fmt.Sprintf("Item %d", index))
    }),
)

Column Modes

Two column modes are available:

  • Columns -- fixed column count
  • ColumnsAuto -- auto-fit based on viewport width and cell size

ScrollView Composition

GridView 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. Scrolling is vertical only — columns are sized to fit within the viewport.

Selection

Optional cell selection is supported via SelectedIndex or SelectedIndexSignal. Selection state is passed to the builder callback through [CellContext.IsSelected].

Signal Binding

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

Example with signals:

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

gv := gridview.New(
    gridview.ItemCountSignal(count),
    gridview.ItemSize(120, 120),
    gridview.Columns(4),
    gridview.SelectedIndexSignal(selected),
    gridview.BuildCell(func(index int, ctx gridview.CellContext) widget.Widget {
        return buildThumbnail(images[index], ctx.IsSelected)
    }),
    gridview.Gap(8),
)

Visual Style

The visual rendering of grid-specific elements (cell backgrounds, selection highlights, hover effects, empty state) 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

GridView implements a11y.Accessible with a11y.RoleGrid. Visible cells are exposed as grid cell children. Keyboard navigation with arrow keys moves selection between cells in all four directions.

Focus

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CellContext

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

	// Row is the cell's row index (zero-based).
	Row int

	// Col is the cell's column index (zero-based).
	Col int

	// IsSelected is true if this cell is the currently selected cell.
	IsSelected bool

	// IsHovered is true if the mouse cursor is over this cell.
	IsHovered bool
}

CellContext provides contextual information to the cell builder callback.

The builder receives a CellContext for each visible cell, allowing it to customize the returned widget based on selection, hover, and position state.

type CellPaintState

type CellPaintState struct {
	// Bounds is the cell's bounding rectangle.
	Bounds geometry.Rect

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

	// Row is the cell's row index (zero-based).
	Row int

	// Col is the cell's column index (zero-based).
	Col int

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

	// Focused is true if the cell has keyboard focus within the grid.
	Focused bool

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

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

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

CellPaintState provides context for cell background and selection painting.

type DefaultPainter

type DefaultPainter struct{}

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

func (DefaultPainter) PaintCellBackground

func (p DefaultPainter) PaintCellBackground(canvas widget.Canvas, cps CellPaintState)

PaintCellBackground draws the background for a grid cell.

func (DefaultPainter) PaintEmptyState

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

PaintEmptyState draws a centered "No items" message.

func (DefaultPainter) PaintSelection

func (p DefaultPainter) PaintSelection(canvas widget.Canvas, cps CellPaintState)

PaintSelection draws the selection highlight for a selected cell.

type GridColorScheme

type GridColorScheme struct {
	SelectionColor widget.Color // selected cell background
	HoverColor     widget.Color // hovered cell background
	FocusColor     widget.Color // focused cell border/background
	EmptyTextColor widget.Color // empty state text color
	CellBackground widget.Color // cell background
}

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

type Option

type Option func(*config)

Option configures a grid view during construction.

func A11yLabel

func A11yLabel(label string) Option

A11yLabel sets the accessibility label for the grid.

func BuildCell

func BuildCell(fn func(index int, ctx CellContext) widget.Widget) Option

BuildCell sets the callback that creates a widget for each visible cell. The callback receives the item index and a CellContext with the cell's state. This is the primary convenience API for providing grid content.

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

func CellContent

func CellContent(content cdk.Content[CellContext]) Option

CellContent sets the cdk.Content used to render each visible cell. This is the enterprise API for providing grid content -- use it when you need reusable content implementations or progressive complexity.

For most use cases, BuildCell is simpler and sufficient.

func Columns

func Columns(n int) Option

Columns sets the fixed number of columns in the grid. Default: 4. See also ColumnsAuto for auto-fit mode.

func ColumnsAuto

func ColumnsAuto(enabled bool) Option

ColumnsAuto enables auto-fit column count based on viewport width. When enabled, the column count is calculated as floor(viewportWidth / (itemWidth + gap)).

func ColumnsReadonlySignal

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

ColumnsReadonlySignal binds the column count to a read-only signal. When set, this takes highest precedence. Ignored if ColumnsAuto is enabled.

func ColumnsSignal

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

ColumnsSignal binds the column count to a reactive signal. When set, the signal takes precedence over Columns but not over ColumnsReadonlySignal. Ignored if ColumnsAuto is enabled.

func Disabled

func Disabled(d bool) Option

Disabled sets the grid 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 Gap

func Gap(g float32) Option

Gap sets the spacing between cells in pixels. Default: 0.

func ItemCount

func ItemCount(n int) Option

ItemCount sets the total number of items in the grid.

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 ItemSize

func ItemSize(width, height float32) Option

ItemSize sets the fixed width and height for all grid cells. Default: 120x120.

func OnCellClick

func OnCellClick(fn func(index int)) Option

OnCellClick sets the callback invoked when a cell 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 cell changes.

func PainterOpt

func PainterOpt(p Painter) Option

PainterOpt sets the painter used to render grid-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 cell 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 a cell, the new index is written back.

func SelectionModeOpt

func SelectionModeOpt(mode SelectionMode) Option

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

type Painter

type Painter interface {
	// PaintCellBackground draws the background for a grid cell.
	// This is called before the cell widget's own Draw method.
	PaintCellBackground(canvas widget.Canvas, state CellPaintState)

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

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

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

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

type SelectionMode

type SelectionMode uint8

SelectionMode defines how cells can be selected in the grid.

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

	// SelectionSingle allows at most one cell 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 grid that renders only visible cells. It composes an internal scrollview.Widget for scroll handling and delegates cell rendering to a builder callback.

A grid view is created with New using functional options:

gv := gridview.New(
    gridview.Columns(4),
    gridview.ItemCount(1000),
    gridview.ItemSize(120, 120),
    gridview.BuildCell(func(index int, ctx gridview.CellContext) widget.Widget {
        return buildCell(index, ctx.IsSelected)
    }),
)

func New

func New(opts ...Option) *Widget

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

The returned widget is visible, enabled, and focusable by default. If no BuildCell callback is provided, the grid 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 grid 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 grid 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) GetColumns

func (w *Widget) GetColumns() int

GetColumns returns the current effective column count.

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 grid view can currently receive focus.

func (*Widget) Layout

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

Layout calculates the grid 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 cell at the given index visible. If the cell is already fully visible, this is a no-op.

func (*Widget) Unmount

func (w *Widget) Unmount()

Unmount is called when the grid 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 cells [start, end).

Jump to

Keyboard shortcuts

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