Skip to content

Refactor: Extract common viewport initialization pattern #87

@yimsk

Description

@yimsk

Summary

Extract duplicated viewport initialization code across 6 views into a shared utility.

Current Duplication

Exact same 8-line block in 6 views:

View Location
LogView log_view.go:411-419
DetailView detail_view.go:222-228
DiffView diff_view.go:108-114
HelpView help_view.go:177-183
MultiSelector multi_selector.go:370-376
ServiceBrowser service_browser.go:650-656
// Identical pattern in all views
if !v.ready {
    v.viewport = viewport.New(viewport.WithWidth(width), viewport.WithHeight(viewportHeight))
    v.ready = true
} else {
    v.viewport.SetWidth(width)
    v.viewport.SetHeight(viewportHeight)
}

Proposed Solution

New file: internal/view/viewport_helper.go

package view

import "charm.land/bubbles/v2/viewport"

// ViewportState wraps viewport with ready flag for safe initialization
type ViewportState struct {
    Viewport viewport.Model
    Ready    bool
}

// SetSize initializes or updates viewport dimensions
func (vs *ViewportState) SetSize(width, height int) {
    if !vs.Ready {
        vs.Viewport = viewport.New(viewport.WithWidth(width), viewport.WithHeight(height))
        vs.Ready = true
    } else {
        vs.Viewport.SetWidth(width)
        vs.Viewport.SetHeight(height)
    }
}

// MinHeight ensures viewport height is at least minHeight
func MinHeight(calculated, minHeight int) int {
    if calculated < minHeight {
        return minHeight
    }
    return calculated
}

Impact

  • Lines removed: ~48 lines of duplication
  • Files simplified: 6 view files
  • Maintainability: Single source of truth for viewport init pattern

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions