Compare commits

..

7 Commits

Author SHA1 Message Date
ebbf66e76e docs(docs): update docs to get rid of gopls warnings. update some code to newer standards 2026-06-14 20:15:21 +02:00
aa34043e9b feat(tuie): drive roast meter from product roast_level field (#48) 2026-06-11 16:28:04 +02:00
5dd22fb8be style(tui): update rest of tui to new ui pattern (#47) 2026-06-11 15:53:48 +02:00
52d533703b feat(tui): remake parts of the tui (#46)
* feat(tui): remake parts of the tui

* chore(tui): remove unused newViewport helper
2026-06-11 11:24:56 +02:00
c9f8b1e674 test(test): smoke test deploy script with dirty box tree (#44) 2026-06-09 19:39:09 +02:00
d592249efb fix: fail deploy loudly on stale pull or HEAD mismatch (#43) 2026-06-09 19:20:08 +02:00
cfc97eb1ff fix/temp disable sshCardAdd button (#42)
* fix: disable add-card-via-ssh, mark coming soo, skip in cursor nav

* style(tui): reword (coming soon) to (WIP)
2026-06-09 14:33:09 +02:00
40 changed files with 765 additions and 317 deletions

View File

@@ -22,6 +22,15 @@ jobs:
key: ${{ secrets.SERVER_SSH_KEY }} key: ${{ secrets.SERVER_SSH_KEY }}
port: ${{ secrets.SERVER_PORT }} port: ${{ secrets.SERVER_PORT }}
script: | script: |
set -euo pipefail
cd ~/terminalShop cd ~/terminalShop
git pull git fetch origin master
git reset --hard origin/master
deployed=$(git rev-parse HEAD)
expected="${{ github.sha }}"
if [ "$deployed" != "$expected" ]; then
echo "::error::deploy HEAD mismatch: box=$deployed expected=$expected"
exit 1
fi
docker compose -f docker-compose.prod.yml up -d --build docker compose -f docker-compose.prod.yml up -d --build
echo "deploy verified: HEAD=$deployed"

1
.gitignore vendored
View File

@@ -7,6 +7,7 @@
docs/sca-psd2-compliance.md docs/sca-psd2-compliance.md
accept-a-payment/ accept-a-payment/
codemap/
FULFILLMENT.md FULFILLMENT.md

View File

@@ -71,3 +71,4 @@ uses SQLite by default so there's nothing to spin up.
## inspiration ## inspiration
[terminal.shop](https://terminal.shop) for the original idea and most of the patterns in `pkg/tui/`. their source is open and worth reading. [terminal.shop](https://terminal.shop) for the original idea and most of the patterns in `pkg/tui/`. their source is open and worth reading.
# something

3
api/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Command api is the HTTP backend: it boots the router, bolts on all the
// middleware, and answers the requests the TUI throws at it.
package main

3
api/handlers/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package handlers is where the real work happens, one function per endpoint:
// carts, orders, products, addresses, cards, webhooks, and the rest.
package handlers

4
api/middleware/doc.go Normal file
View File

@@ -0,0 +1,4 @@
// Package middleware holds the stuff that runs on every request before a
// handler ever sees it: auth, CORS, logging, rate limiting, metrics, and a
// recovery net for panics.
package middleware

3
api/routes/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package routes is the switchboard: it maps every URL to the handler that
// knows what to do with it.
package routes

View File

@@ -0,0 +1,3 @@
// Command reconcile-cards hunts down saved cards that Stripe no longer knows
// about and detaches them. Run it with -dry-run first if you're nervous.
package main

3
pkg/api/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package api is the client side of the house: it talks to our HTTP backend
// so other Go code doesn't have to hand-roll requests.
package api

3
pkg/auth/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package auth sorts out who you are: logging in with an SSH key and minting
// the JWT you carry around afterwards.
package auth

3
pkg/bring/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package bring talks to Bring, the Norwegian postal service, for booking
// shipments and printing labels.
package bring

3
pkg/config/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package config reads everything out of the environment so secrets and
// settings stay out of the source code.
package config

3
pkg/database/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package database opens the SQLite connection, runs the migrations, and
// drops in some seed data so the shop isn't empty on a fresh boot.
package database

View File

@@ -26,6 +26,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Espresso", Name: "Espresso",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 5,
Ounces: 2, Ounces: 2,
BeanType: "Arabica", BeanType: "Arabica",
Price: 1800, // $18.00 Price: 1800, // $18.00
@@ -35,6 +36,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Americano", Name: "Americano",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 3,
Ounces: 8, Ounces: 8,
BeanType: "Arabica", BeanType: "Arabica",
Price: 2200, // $22.00 Price: 2200, // $22.00
@@ -44,6 +46,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Cappuccino", Name: "Cappuccino",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 3,
Ounces: 6, Ounces: 6,
BeanType: "Arabica", BeanType: "Arabica",
Price: 2200, // $22.00 Price: 2200, // $22.00
@@ -53,6 +56,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Latte", Name: "Latte",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 2,
Ounces: 12, Ounces: 12,
BeanType: "Arabica", BeanType: "Arabica",
Price: 2500, // $25.00 Price: 2500, // $25.00
@@ -62,6 +66,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Mocha", Name: "Mocha",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 4,
Ounces: 12, Ounces: 12,
BeanType: "Arabica", BeanType: "Arabica",
Price: 3000, // $30.00 Price: 3000, // $30.00
@@ -71,6 +76,7 @@ func Seed(db *gorm.DB) error {
{ {
Name: "Macchiato", Name: "Macchiato",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 4,
Ounces: 3, Ounces: 3,
BeanType: "Robusta Blend", BeanType: "Robusta Blend",
Price: 1800, // $18.00 Price: 1800, // $18.00

View File

@@ -11,6 +11,7 @@ type Coffee struct {
ID uint `gorm:"primaryKey" json:"id"` ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:255;not null" json:"name"` Name string `gorm:"size:255;not null" json:"name"`
RoastType string `gorm:"size:100" json:"roast_type"` RoastType string `gorm:"size:100" json:"roast_type"`
RoastLevel int `json:"roast_level"` // 1-5 roast-intensity
Ounces int `json:"ounces"` Ounces int `json:"ounces"`
BeanType string `gorm:"size:100" json:"bean_type"` BeanType string `gorm:"size:100" json:"bean_type"`
Price int `gorm:"not null" json:"price"` Price int `gorm:"not null" json:"price"`

3
pkg/models/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package models is the shared vocabulary of the app: coffee, carts, orders,
// addresses, cards, users, and the other nouns everything passes around.
package models

3
pkg/observability/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package observability sets up tracing and structured logs so that when
// something breaks at 3am you stand a chance of figuring out why.
package observability

3
pkg/shipping/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package shipping holds the plain shipping types that the rest of the app
// passes back and forth.
package shipping

2
pkg/shippo/doc.go Normal file
View File

@@ -0,0 +1,2 @@
// Package shippo talks to the Shippo API for shipping rates and labels.
package shippo

3
pkg/stripeclient/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package stripeclient wires up the Stripe SDK once at startup (with tracing
// baked in) so everyone else can just make calls.
package stripeclient

View File

@@ -1,6 +1,8 @@
package tui package tui
import ( import (
"strings"
"charm.land/bubbles/v2/viewport" "charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2" "charm.land/lipgloss/v2"
@@ -8,36 +10,54 @@ import (
"terminalShop/pkg/models" "terminalShop/pkg/models"
) )
// updateAccountViewport initializes or resizes the detail viewport for the account page. // accountBodyHeight returns the inner content height of the account body
// Follows the reference pattern: each page owns its own viewport(s). // panels. The body is quantized to whole order cards so the menu panel's
func (m Model) updateAccountViewport() Model { // bottom border lines up exactly with the last visible card; the two gap
// Match the reference: only subtract header + footer, no extra margins // rows around the body host the up/down scroll arrows.
// (account is a viewport page — views.go renders it without margin padding) func (m Model) accountBodyHeight() int {
headerHeight := lipgloss.Height(m.BuildHeader()) headerHeight := lipgloss.Height(m.BuildHeader())
footerHeight := lipgloss.Height(m.BuildFooter()) footerHeight := lipgloss.Height(m.BuildFooter())
verticalMarginHeight := headerHeight + footerHeight budget := m.heightContainer - headerHeight - footerHeight - 2
cards := budget / orderCardHeight
availableHeight := m.heightContainer - verticalMarginHeight if cards < 1 {
cards = 1
leftWidth := 18
rightWidth := m.widthContent - leftWidth - 2
detailWidth := rightWidth
if m.size < large {
detailWidth = m.widthContent
// In stacked mode, reduce available height by the left panel
leftPanelHeight := len(models.AccountMenuItems) + 1
availableHeight -= leftPanelHeight
} }
if availableHeight < 3 { return cards*orderCardHeight - 2
availableHeight = 3 }
// accountDetailWidth returns the width of the unboxed detail area: the chrome
// width minus the menu panel and the gap. The detail side has no outer panel
// (its content draws its own boxes), so it reclaims the border + padding.
func (m Model) accountDetailWidth() int {
contentW, menuW, _, _ := m.shopLayout()
if m.size < large {
return contentW
}
return contentW - (menuW + 4) - 1
}
// updateAccountViewport initializes or resizes the detail viewport for the account page.
// The viewport spans the unboxed detail area to the right of the menu panel.
func (m Model) updateAccountViewport() Model {
detailW := m.accountDetailWidth()
// +2: no panel on the detail side, so the viewport spans the same rows
// as the menu panel including its border rows — tops and bottoms align.
availableHeight := m.accountBodyHeight() + 2
if m.size < large {
// Stacked: the menu panel sits above the detail area
menuPanelHeight := len(models.AccountMenuItems) + 2
availableHeight -= menuPanelHeight
if availableHeight < 3 {
availableHeight = 3
}
} }
if !m.account.viewportReady { if !m.account.viewportReady {
m.account.detailViewport = viewport.New(viewport.WithWidth(detailWidth), viewport.WithHeight(availableHeight)) m.account.detailViewport = viewport.New(viewport.WithWidth(detailW), viewport.WithHeight(availableHeight))
m.account.detailViewport.KeyMap = modifiedKeyMap m.account.detailViewport.KeyMap = modifiedKeyMap
m.account.viewportReady = true m.account.viewportReady = true
} else { } else {
m.account.detailViewport.SetWidth(detailWidth) m.account.detailViewport.SetWidth(detailW)
m.account.detailViewport.SetHeight(availableHeight) m.account.detailViewport.SetHeight(availableHeight)
} }
@@ -46,12 +66,7 @@ func (m Model) updateAccountViewport() Model {
// getAccountDetailContent generates the content string for the current detail panel. // getAccountDetailContent generates the content string for the current detail panel.
func (m Model) getAccountDetailContent() string { func (m Model) getAccountDetailContent() string {
leftWidth := 18 detailContentWidth := m.accountDetailWidth()
rightWidth := m.widthContent - leftWidth - 2
detailContentWidth := rightWidth - 2
if m.size < large {
detailContentWidth = m.widthContent - 2
}
if m.account.cursor < 0 || m.account.cursor >= len(models.AccountMenuItems) { if m.account.cursor < 0 || m.account.cursor >= len(models.AccountMenuItems) {
return "" return ""
@@ -68,7 +83,6 @@ func (m Model) getAccountDetailContent() string {
case "cards": case "cards":
return m.CardsView(detailContentWidth) return m.CardsView(detailContentWidth)
case "faq": case "faq":
titleStyle := m.theme.TextAccent().Bold(true).MarginBottom(2)
questionStyle := m.theme.TextHighlight().Bold(true) questionStyle := m.theme.TextHighlight().Bold(true)
contentStyle := m.theme.TextBody().Width(detailContentWidth) contentStyle := m.theme.TextBody().Width(detailContentWidth)
faqContent := "" faqContent := ""
@@ -79,7 +93,7 @@ func (m Model) getAccountDetailContent() string {
faqContent += "\n\n" faqContent += "\n\n"
} }
} }
detailView := titleStyle.Render("FAQ") + "\n\n" + faqContent detailView := faqContent
if !m.account.faqFocused { if !m.account.faqFocused {
hintStyle := m.theme.TextDim() hintStyle := m.theme.TextDim()
detailView += "\n\n" + hintStyle.Render("enter: scroll faq") detailView += "\n\n" + hintStyle.Render("enter: scroll faq")
@@ -103,19 +117,25 @@ func (m Model) scrollToAccountDetailItem() Model {
switch { switch {
case m.account.orderViewState == 1: case m.account.orderViewState == 1:
// No title in list mode, cards joined with JoinVertical (no gaps) // Order list uses whole-card windowing instead of viewport scroll:
// Card: border(2) + content(2) + PaddingLeft only = 4 lines // shift the window just enough to keep the cursor's card visible.
headerOffset = 0 page := m.orderListPageSize()
itemHeight = 4 if m.account.orderCursor < m.account.orderWindowStart {
itemCount = len(m.currentOrderList()) m.account.orderWindowStart = m.account.orderCursor
selectedIndex = m.account.orderCursor }
if m.account.orderCursor >= m.account.orderWindowStart+page {
m.account.orderWindowStart = m.account.orderCursor - page + 1
}
m.account.detailViewport.GotoTop()
return m
case m.account.addressListFocused: case m.account.addressListFocused:
headerOffset = 3 // Titles were removed from the detail views, lists start at the top
headerOffset = 0
itemHeight = 5 itemHeight = 5
itemCount = len(m.SavedAddresses) itemCount = len(m.SavedAddresses)
selectedIndex = m.account.addressCursor selectedIndex = m.account.addressCursor
case m.account.cardListFocused: case m.account.cardListFocused:
headerOffset = 3 headerOffset = 0
itemHeight = 4 itemHeight = 4
itemCount = len(m.SavedCards) itemCount = len(m.SavedCards)
selectedIndex = m.account.cardCursor selectedIndex = m.account.cardCursor
@@ -143,23 +163,30 @@ func (m Model) scrollToAccountDetailItem() Model {
return m return m
} }
func (m Model) BuildAccountView(availableHeight int) string { func (m Model) BuildAccountView() string {
leftWidth := 18 _, menuW, _, _ := m.shopLayout()
// Build the left panel (menu items) // Left panel: menu items. The highlight is blue while the user navigates
leftPanel := "" // the menu, and falls back to the gray pill when focus has moved into the
// detail area (browsing orders, managing addresses/cards, scrolling faq).
focusedInside := m.account.orderViewState > 0 || m.account.addressListFocused ||
m.account.cardListFocused || m.account.faqFocused
pillBg := m.theme.Highlight()
if focusedInside {
pillBg = cPill
}
var menu []string
for i, item := range models.AccountMenuItems { for i, item := range models.AccountMenuItems {
if m.account.cursor == i { if m.account.cursor == i {
style := m.theme.Base().Background(m.theme.Highlight()).Foreground(m.theme.Accent()).Padding(0, 1).Width(leftWidth - 2).Align(lipgloss.Left) menu = append(menu, lipgloss.NewStyle().Width(menuW).
leftPanel += style.Render(item) + "\n" Background(pillBg).Foreground(cWhite).Bold(true).
Render(" "+item))
} else { } else {
style := m.theme.TextBody().Padding(0, 1).Width(leftWidth - 2).Align(lipgloss.Left) menu = append(menu, lipgloss.NewStyle().Width(menuW).
leftPanel += style.Render(item) + "\n" Render(" "+pBody.Render(item)))
} }
} }
menuContent := lipgloss.JoinVertical(lipgloss.Left, menu...)
leftContainer := m.theme.Base().
Width(leftWidth)
// Generate detail content and set it on the viewport // Generate detail content and set it on the viewport
detailContent := m.getAccountDetailContent() detailContent := m.getAccountDetailContent()
@@ -168,25 +195,43 @@ func (m Model) BuildAccountView(availableHeight int) string {
// Viewport handles scrolling/clipping — no manual line-slicing needed // Viewport handles scrolling/clipping — no manual line-slicing needed
detailRendered := m.account.detailViewport.View() detailRendered := m.account.detailViewport.View()
// Responsive layout: side-by-side on large, stacked on small/medium // Responsive layout: menu panel beside the unboxed detail area on large,
// stacked on small/medium. The detail side draws its own item boxes.
var body string
if m.size < large { if m.size < large {
return lipgloss.JoinVertical( body = lipgloss.JoinVertical(
lipgloss.Left, lipgloss.Left,
leftContainer.Render(leftPanel), panel(menuW, 0, menuContent),
detailRendered,
)
} else {
bodyH := m.accountBodyHeight()
body = lipgloss.JoinHorizontal(
lipgloss.Top,
panel(menuW, bodyH, menuContent),
" ",
detailRendered, detailRendered,
) )
} }
return lipgloss.JoinHorizontal( // Blank rows separate the body from the header and footer boxes. When the
lipgloss.Top, // windowed order list has hidden items, the arrows occupy those gap rows,
leftContainer.Render(leftPanel), // centered over the card column, so the cards themselves always span
" ", // exactly the menu panel's rows — top and bottom borders aligned.
detailRendered, topGap := ""
) if above := m.orderHiddenAbove(); above > 0 && m.size >= large {
topGap = strings.Repeat(" ", menuW+5) +
orderScrollIndicator("↑", above, m.accountDetailWidth())
}
bottomGap := ""
if below := m.orderHiddenBelow(); below > 0 && m.size >= large {
bottomGap = strings.Repeat(" ", menuW+5) +
orderScrollIndicator("↓", below, m.accountDetailWidth())
}
return topGap + "\n" + body + "\n" + bottomGap
} }
func (m Model) AboutView(width int) string { func (m Model) AboutView(width int) string {
titleStyle := m.theme.TextAccent().Bold(true).MarginBottom(2)
contentStyle := m.theme.TextBody().Width(width) contentStyle := m.theme.TextBody().Width(width)
// USE this if wanting to add a corp name later // USE this if wanting to add a corp name later
// accentStyle := m.theme.TextHighlight().Bold(true) // accentStyle := m.theme.TextHighlight().Bold(true)
@@ -208,7 +253,7 @@ func (m Model) AboutView(width int) string {
width, width,
)) + "\n" )) + "\n"
return titleStyle.Render("About") + "\n\n" + aboutContent return aboutContent
} }
func (m Model) AccountUpdate(msg tea.Msg) (Model, tea.Cmd) { func (m Model) AccountUpdate(msg tea.Msg) (Model, tea.Cmd) {
@@ -335,6 +380,7 @@ func (m Model) AccountUpdate(msg tea.Msg) (Model, tea.Cmd) {
case 0: case 0:
m.account.orderViewState = 1 m.account.orderViewState = 1
m.account.orderCursor = 0 m.account.orderCursor = 0
m.account.orderWindowStart = 0
m.account.detailViewport.GotoTop() m.account.detailViewport.GotoTop()
m.footer = []footerCommand{ m.footer = []footerCommand{
{key: "j/k", value: "orders"}, {key: "j/k", value: "orders"},

View File

@@ -1,10 +1,9 @@
package tui package tui
func (m Model) AddressesView(width int) string { func (m Model) AddressesView(width int) string {
titleStyle := m.theme.TextAccent().Bold(true).MarginBottom(2)
contentStyle := m.theme.TextBody().Width(width) contentStyle := m.theme.TextBody().Width(width)
lines := titleStyle.Render("Address") + "\n\n" lines := ""
if len(m.SavedAddresses) == 0 { if len(m.SavedAddresses) == 0 {
lines += contentStyle.Render("No saved addresses") lines += contentStyle.Render("No saved addresses")
} else { } else {

View File

@@ -5,10 +5,9 @@ import (
) )
func (m Model) CardsView(width int) string { func (m Model) CardsView(width int) string {
titleSTyle := m.theme.TextAccent().Bold(true).MarginBottom(2)
contentStyle := m.theme.TextBody().Width(width) contentStyle := m.theme.TextBody().Width(width)
lines := titleSTyle.Render("Cards") + "\n\n" lines := ""
if m.SavedCardsIsEmpty() { if m.SavedCardsIsEmpty() {
lines += contentStyle.Render("No saved cards") lines += contentStyle.Render("No saved cards")
} else { } else {

View File

@@ -10,11 +10,11 @@ import (
) )
func (m Model) OrdersView(width int) string { func (m Model) OrdersView(width int) string {
return m.orderListView("Order History", m.HistoryOrders(), width) return m.orderListView(m.HistoryOrders(), width)
} }
func (m Model) ActiveOrdersView(width int) string { func (m Model) ActiveOrdersView(width int) string {
return m.orderListView("Active Orders", m.ActiveOrders(), width) return m.orderListView(m.ActiveOrders(), width)
} }
func (m Model) ActiveOrders() []models.Order { func (m Model) ActiveOrders() []models.Order {
@@ -65,41 +65,95 @@ func (m Model) currentOrderList() []models.Order {
return nil return nil
} }
func (m Model) orderListView(title string, orders []models.Order, width int) string { // orderCardHeight is the rendered height of one order card:
titleStyle := m.theme.TextAccent().Bold(true).MarginBottom(1) // border (2) + content lines (2), no vertical padding.
const orderCardHeight = 4
// orderListPageSize returns how many whole order cards fit in the detail
// area. Both scroll arrows render outside the list, in the gap rows above
// and below the body, so the cards use the full viewport height.
func (m Model) orderListPageSize() int {
n := m.account.detailViewport.Height() / orderCardHeight
if n < 1 {
n = 1
}
return n
}
// orderHiddenAbove returns how many order cards are scrolled off above the
// windowed list, or 0 when the windowed order list isn't showing.
func (m Model) orderHiddenAbove() int {
if m.account.orderViewState != 1 || !m.OrdersLoaded {
return 0
}
orders := m.currentOrderList()
if len(orders) == 0 {
return 0
}
page := m.orderListPageSize()
start := m.account.orderWindowStart
if start > len(orders)-page {
start = len(orders) - page
}
if start < 0 {
start = 0
}
return start
}
// orderHiddenBelow returns how many order cards are scrolled off below the
// windowed list, or 0 when the windowed order list isn't showing.
func (m Model) orderHiddenBelow() int {
if m.account.orderViewState == 2 || !m.OrdersLoaded {
return 0
}
orders := m.currentOrderList()
if len(orders) == 0 {
return 0
}
below := len(orders) - (m.orderHiddenAbove() + m.orderListPageSize())
if below < 0 {
below = 0
}
return below
}
// orderScrollIndicator renders the dim "more items" arrow row, centered
// across the card width.
func orderScrollIndicator(arrow string, count, width int) string {
return pDim.Width(width).Align(lipgloss.Center).
Render(fmt.Sprintf("%s %d more", arrow, count))
}
func (m Model) orderListView(orders []models.Order, width int) string {
contentStyle := m.theme.TextBody().Width(width) contentStyle := m.theme.TextBody().Width(width)
if !m.OrdersLoaded { if !m.OrdersLoaded {
return titleStyle.Render(title) + "\n" + contentStyle.Render("Loading orders...") return contentStyle.Render("Loading orders...")
} }
if len(orders) == 0 { if len(orders) == 0 {
return titleStyle.Render(title) + "\n" + contentStyle.Render("No orders yet") return contentStyle.Render("No orders yet")
} }
if m.account.orderViewState == 2 { if m.account.orderViewState == 2 {
return m.buildOrderDetailView(orders[m.account.orderCursor], width) return m.buildOrderDetailView(orders[m.account.orderCursor], width)
} }
boxWidth := width - 2 // Whole-card windowing: render only fully-visible cards, never clipping a
// card mid-border. Both scroll arrows render in BuildAccountView's gap
// rows, so the cards span exactly the menu panel's rows.
page := m.orderListPageSize()
start := m.orderHiddenAbove()
end := start + page
if end > len(orders) {
end = len(orders)
}
// Build cards and join vertically — no manual "\n" gaps means fixed spacing var rows []string
var cards []string for i := start; i < end; i++ {
for i, order := range orders {
isSelected := m.account.orderViewState == 1 && i == m.account.orderCursor isSelected := m.account.orderViewState == 1 && i == m.account.orderCursor
cards = append(cards, m.buildOrderCard(order, boxWidth, isSelected)) rows = append(rows, m.buildOrderCard(orders[i], width, isSelected))
} }
cardList := lipgloss.JoinVertical(lipgloss.Left, cards...) return lipgloss.JoinVertical(lipgloss.Left, rows...)
// In preview mode (viewState 0), show title + hint
if m.account.orderViewState == 0 {
hintStyle := m.theme.TextDim()
return titleStyle.Render(title) + "\n" +
cardList + "\n" +
hintStyle.Render("enter: browse orders")
}
// In list browsing mode (viewState 1), just show cards — no title
// (the left panel menu already shows "order history" as selected)
return cardList
} }
// buildOrderCard renders a single order as a bordered box with fixed height. // buildOrderCard renders a single order as a bordered box with fixed height.

View File

@@ -9,36 +9,42 @@ import (
) )
func (m Model) updateCartViewport() Model { func (m Model) updateCartViewport() Model {
contentW, _, _, _ := m.shopLayout()
headerH := lipgloss.Height(m.BuildHeader()) headerH := lipgloss.Height(m.BuildHeader())
breadH := lipgloss.Height(m.BuildBreadcrumbs()) breadH := lipgloss.Height(m.BuildBreadcrumbs())
footerH := lipgloss.Height(m.BuildFooter()) footerH := lipgloss.Height(m.BuildFooter())
availH := m.heightContainer - headerH - footerH - breadH // 2 = blank gap rows around the cart list
availH := m.heightContainer - headerH - footerH - breadH - 2
if availH < 1 { if availH < 1 {
availH = 1 availH = 1
} }
if !m.cart.viewportReady { if !m.cart.viewportReady {
m.cart.viewport = viewport.New(viewport.WithWidth(m.widthContent), viewport.WithHeight(availH)) m.cart.viewport = viewport.New(viewport.WithWidth(contentW), viewport.WithHeight(availH))
m.cart.viewport.KeyMap = viewport.KeyMap{} m.cart.viewport.KeyMap = viewport.KeyMap{}
m.cart.viewportReady = true m.cart.viewportReady = true
} else { } else {
m.cart.viewport.SetWidth(m.widthContent) m.cart.viewport.SetWidth(contentW)
m.cart.viewport.SetHeight(availH) m.cart.viewport.SetHeight(availH)
} }
return m return m
} }
func (m Model) generateCartContent() string { func (m Model) generateCartContent() string {
contentW, _, _, _ := m.shopLayout()
if m.IsCartEmpty() { if m.IsCartEmpty() {
emptyStyle := m.theme.TextDim(). emptyStyle := m.theme.TextDim().
Align(lipgloss.Center). Align(lipgloss.Center).
Width(m.widthContent). Width(contentW).
Padding(2, 0) Padding(2, 0)
render := emptyStyle.Render("Your cart is empty\n\nPress s to go back to shop") render := emptyStyle.Render("Your cart is empty\n\nPress s to go back to shop")
return render return render
} }
cartItems := "" cartItems := ""
boxWidth := m.widthContent - 4 // Cart cards span the full chrome width so they line up with the
// header and footer boxes.
boxWidth := contentW
itemSlice := m.GetCartItemsSlice() itemSlice := m.GetCartItemsSlice()
boxPadding := 0 boxPadding := 0
@@ -94,7 +100,7 @@ func (m Model) generateCartContent() string {
boxContent = m.theme.TextAccent().Render(boxContent) boxContent = m.theme.TextAccent().Render(boxContent)
} }
box := m.createBoxInner(boxContent, isSelected, lipgloss.Left, 2, boxPadding, boxWidth) box := m.createBoxInner(boxContent, isSelected, lipgloss.Left, 2, boxPadding, boxWidth)
cartItems += m.theme.Base().Width(m.widthContent).Align(lipgloss.Center).Render(box) cartItems += box
if idx < len(itemSlice)-1 { if idx < len(itemSlice)-1 {
cartItems += "\n" cartItems += "\n"
@@ -123,12 +129,9 @@ func (m Model) CartView() string {
m.cart.viewport.SetYOffset(targetY - m.cart.viewport.Height() + itemHeight) m.cart.viewport.SetYOffset(targetY - m.cart.viewport.Height() + itemHeight)
} }
} }
return lipgloss.Place( // Blank rows separate the list from the chrome; no Place wrapper so the
m.widthContainer, // cards stay left-aligned with the header and footer boxes.
lipgloss.Height(m.cart.viewport.View()), return "\n" + m.cart.viewport.View() + "\n"
lipgloss.Center, lipgloss.Center,
m.cart.viewport.View(),
)
} }
func (m Model) CartUpdate(msg tea.Msg) (Model, tea.Cmd) { func (m Model) CartUpdate(msg tea.Msg) (Model, tea.Cmd) {

3
pkg/tui/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package tui is the terminal UI you see over SSH: the shop, the cart, your
// account, and the checkout flow, all drawn with Bubbletea.
package tui

View File

@@ -6,20 +6,26 @@ import (
"charm.land/lipgloss/v2" "charm.land/lipgloss/v2"
) )
// BuildFooter renders the bottom chrome bar with the current page keybinds.
// Layout ported from the design prototype at ~/programming/test/shop.go.
func (m Model) BuildFooter() string { func (m Model) BuildFooter() string {
keybindStyle := m.theme.TextDim().Bold(true) _, _, _, wideW := m.shopLayout()
descStyle := m.theme.TextDim()
item := func(k, v string) string {
return pBody.Render(k) + " " + pDim.Render(v)
}
var keys string
if m.size == small { if m.size == small {
footerText := keybindStyle.Render("m") + " " + descStyle.Render("menu") keys = item("m", "menu")
return lipgloss.NewStyle().Align(lipgloss.Center).Width(m.widthContainer).Render(footerText) } else {
parts := make([]string, 0, len(m.footer))
for _, cmd := range m.footer {
parts = append(parts, item(cmd.key, cmd.value))
}
keys = strings.Join(parts, pDim.Render(" · "))
} }
parts := []string{} row := lipgloss.NewStyle().Width(wideW).Align(lipgloss.Center).Render(keys)
for _, cmd := range m.footer { return panel(wideW, 0, row)
parts = append(parts, keybindStyle.Render(cmd.key)+" "+descStyle.Render(cmd.value))
}
footerText := strings.Join(parts, " ")
return lipgloss.NewStyle().Align(lipgloss.Center).Width(m.widthContainer).Render(footerText)
} }

View File

@@ -2,57 +2,72 @@ package tui
import ( import (
"fmt" "fmt"
"image/color"
"strings"
"charm.land/lipgloss/v2" "charm.land/lipgloss/v2"
"charm.land/lipgloss/v2/table"
) )
func (m Model) BuildHeader() string { // cartBlendColor mixes the colors of all cart items, weighted by quantity,
bold := m.theme.TextAccent().Bold(true).Render // so the header price tints toward whatever dominates the cart.
accent := m.theme.TextAccent().Render func (m Model) cartBlendColor() color.Color {
base := m.theme.Base().Render var rSum, gSum, bSum, n int
cursor := m.theme.Base().Background(m.theme.Brand()).Render(" ") for _, item := range m.Cart {
r, g, b, ok := parseHexColor(item.Coffee.Color)
mark := bold("t") + cursor if !ok {
logo := bold("terminal") continue
menu := bold("m") + base(" ☰")
tab := func(key, name string, active bool) string {
if active {
return accent(key + " " + name)
} }
return accent(key) + base(" "+name) rSum += r * item.Quantity
gSum += g * item.Quantity
bSum += b * item.Quantity
n += item.Quantity
} }
shop := tab("s", "shop", m.currentPage == shopPage) if n == 0 {
account := tab("a", "account", m.currentPage == accountPage) return cWhite
priceStr := fmt.Sprintf(" $%2v", m.CalculateSubtotal()/100)
countStr := fmt.Sprintf(" [%d]", m.CartItemCount())
cartLabel := base(" cart")
if m.inCartFlow() {
cartLabel = accent(" cart")
} }
cart := accent("c") + cartLabel + accent(priceStr) + base(countStr) return lipgloss.Color(fmt.Sprintf("#%02X%02X%02X", rSum/n, gSum/n, bSum/n))
}
var tabs []string
switch m.size { // BuildHeader renders the top chrome bar: brand, tab pills, and cart summary.
case small: // Layout ported from the design prototype at ~/programming/test/shop.go.
tabs = []string{mark, cart} func (m Model) BuildHeader() string {
case medium: _, _, _, wideW := m.shopLayout()
tabs = []string{menu, logo, cart}
default: brand := pWht.Bold(true).Render("terminal")
tabs = []string{logo, shop, account, cart}
} pill := lipgloss.NewStyle().Background(cPill).Foreground(cWhite).Bold(true).Padding(0, 1)
tab := func(key, label string, active bool) string {
tbl := table.New().Border(lipgloss.NormalBorder()).BorderStyle(lipgloss.NewStyle().Foreground(m.theme.Border())).Row(tabs...).Width(m.widthContent).StyleFunc(func(row, col int) lipgloss.Style { if active {
return m.theme.Base().Padding(0, 1).AlignHorizontal(lipgloss.Center) return pill.Render(label)
}).Render() }
return pDim.Render(key+" ") + pBody.Render(label)
return lipgloss.Place( }
m.widthContainer,
lipgloss.Height(tbl), var left string
lipgloss.Center, if m.size == small {
lipgloss.Center, left = brand
tbl, } else {
) left = strings.Join([]string{
brand,
tab("s", "shop", m.currentPage == shopPage),
tab("a", "account", m.currentPage == accountPage),
}, " ")
}
cartLabel := pDim.Render("cart ")
if m.inCartFlow() {
cartLabel = pWht.Bold(true).Render("cart ")
}
cart := cartLabel +
lipgloss.NewStyle().Foreground(m.cartBlendColor()).Bold(true).
Render(fmt.Sprintf("$%d", m.CalculateSubtotal()/100)) +
pDim.Render(fmt.Sprintf(" · %d", m.CartItemCount()))
gap := wideW - lipgloss.Width(left) - lipgloss.Width(cart)
if gap < 1 {
gap = 1
}
row := left + strings.Repeat(" ", gap) + cart
return panel(wideW, 0, row)
} }

View File

@@ -142,10 +142,7 @@ type Model struct {
} }
type shopState struct { type shopState struct {
selected int selected int
menuViewport viewport.Model
detailViewport viewport.Model
viewportsReady bool
} }
type splashState struct { type splashState struct {
@@ -185,6 +182,7 @@ type accountState struct {
cursor int cursor int
orderViewState int orderViewState int
orderCursor int orderCursor int
orderWindowStart int // first fully-visible card in the windowed order list
orderYOffset int // saved scroll pos when entering order detail orderYOffset int // saved scroll pos when entering order detail
faqFocused bool faqFocused bool
addressListFocused bool addressListFocused bool
@@ -240,7 +238,6 @@ func (m Model) SwitchPage(p page) Model {
func (m Model) ShopSwitch() (Model, tea.Cmd) { func (m Model) ShopSwitch() (Model, tea.Cmd) {
m = m.SwitchPage(shopPage) m = m.SwitchPage(shopPage)
m = m.updateShopViewports()
m.footer = []footerCommand{ m.footer = []footerCommand{
{key: "j/k", value: "products"}, {key: "j/k", value: "products"},
{key: "+/-", value: "qty"}, {key: "+/-", value: "qty"},
@@ -265,13 +262,12 @@ func (m Model) CartSwitch() (Model, tea.Cmd) {
{key: "q", value: "quit"}, {key: "q", value: "quit"},
} }
} else { } else {
// Keep this list short enough to fit on one footer line.
m.footer = []footerCommand{ m.footer = []footerCommand{
{key: "j/k", value: "items"}, {key: "j/k", value: "items"},
{key: "+/-", value: "qty"}, {key: "+/-", value: "qty"},
{key: "p/enter", value: "checkout"}, {key: "enter", value: "checkout"},
{key: "s", value: "shop"}, {key: "s", value: "shop"},
{key: "a", value: "account"},
{key: "pgup/pgdn", value: "scroll"},
{key: "?", value: "help"}, {key: "?", value: "help"},
{key: "q", value: "quit"}, {key: "q", value: "quit"},
} }
@@ -841,6 +837,7 @@ func NewModel(username string) Model {
{ {
Name: "Espresso", Name: "Espresso",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 5,
Ounces: 2, Ounces: 2,
BeanType: "Arabica", BeanType: "Arabica",
Price: 350, // $3.50 Price: 350, // $3.50
@@ -850,6 +847,7 @@ func NewModel(username string) Model {
{ {
Name: "Latte", Name: "Latte",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 2,
Ounces: 12, Ounces: 12,
BeanType: "Arabica Blend", BeanType: "Arabica Blend",
Price: 500, // $5.00 Price: 500, // $5.00
@@ -859,6 +857,7 @@ func NewModel(username string) Model {
{ {
Name: "Cappuccino", Name: "Cappuccino",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 3,
Ounces: 8, Ounces: 8,
BeanType: "Italian Blend", BeanType: "Italian Blend",
Price: 450, // $4.50 Price: 450, // $4.50
@@ -868,6 +867,7 @@ func NewModel(username string) Model {
{ {
Name: "Americano", Name: "Americano",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 4,
Ounces: 16, Ounces: 16,
BeanType: "Arabica", BeanType: "Arabica",
Price: 400, // $4.00 Price: 400, // $4.00
@@ -877,6 +877,7 @@ func NewModel(username string) Model {
{ {
Name: "Mocha", Name: "Mocha",
RoastType: "Medium Roast", RoastType: "Medium Roast",
RoastLevel: 3,
Ounces: 16, Ounces: 16,
BeanType: "Colombian", BeanType: "Colombian",
Price: 550, // $5.50 Price: 550, // $5.50
@@ -886,6 +887,7 @@ func NewModel(username string) Model {
{ {
Name: "Macchiato", Name: "Macchiato",
RoastType: "Dark Roast", RoastType: "Dark Roast",
RoastLevel: 4,
Ounces: 3, Ounces: 3,
BeanType: "Robusta Blend", BeanType: "Robusta Blend",
Price: 425, // $4.25 Price: 425, // $4.25
@@ -930,10 +932,6 @@ func NewModelWithAuth(fingerprint string, pubKeyStr string, apiURL string, clien
return m return m
} }
func newViewport(w, h int) viewport.Model {
return viewport.New(viewport.WithWidth(w), viewport.WithHeight(h))
}
func (m Model) collectCardCmd() tea.Cmd { func (m Model) collectCardCmd() tea.Cmd {
return func() tea.Msg { return func() tea.Msg {
if m.APIClient == nil { if m.APIClient == nil {

70
pkg/tui/palette.go Normal file
View File

@@ -0,0 +1,70 @@
package tui
import (
"image/color"
"strconv"
"strings"
"charm.land/lipgloss/v2"
)
// Palette and base styles for the boxed shop chrome.
// Ported from the design prototype at ~/programming/test/shop.go.
var (
cWhite = lipgloss.Color("#EAEAEA")
cBody = lipgloss.Color("#9A9A9A")
cDim = lipgloss.Color("#5A5A5A")
cLine = lipgloss.Color("#3A3A3A")
cInk = lipgloss.Color("#161616") // text on a light colored block
cGreen = lipgloss.Color("#4FB477")
cRed = lipgloss.Color("#E06C6C")
cGold = lipgloss.Color("#D0962E") // single accent
cPill = lipgloss.Color("#2E2E2E") // active-tab pill bg
pBody = lipgloss.NewStyle().Foreground(cBody)
pDim = lipgloss.NewStyle().Foreground(cDim)
pWht = lipgloss.NewStyle().Foreground(cWhite)
)
// parseHexColor splits a "#RRGGBB" string into its channel values.
func parseHexColor(s string) (r, g, b int, ok bool) {
s = strings.TrimPrefix(s, "#")
if len(s) != 6 {
return 0, 0, 0, false
}
v, err := strconv.ParseUint(s, 16, 32)
if err != nil {
return 0, 0, 0, false
}
return int(v >> 16), int((v >> 8) & 0xFF), int(v & 0xFF), true
}
// contrastColor returns ink for light backgrounds and white for dark ones,
// using perceived luminance so text stays readable on any product color.
func contrastColor(hex string) color.Color {
r, g, b, ok := parseHexColor(hex)
if !ok {
return cWhite
}
lum := (299*r + 587*g + 114*b) / 1000
if lum > 140 {
return cInk
}
return cWhite
}
// panel wraps content in a rounded box. textW is the inner text width and
// innerH the inner content height; the total render size is textW+4 by
// innerH+2. Ported from the design prototype at ~/programming/test/shop.go,
// adjusted for lipgloss v2 where Width/Height include the border.
func panel(textW, innerH int, content string) string {
s := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(cLine).
Padding(0, 1).
Width(textW + 4)
if innerH > 0 {
s = s.Height(innerH + 2)
}
return s.Render(content)
}

View File

@@ -276,9 +276,7 @@ func (m Model) updatePaymentViewport() Model {
breadH := lipgloss.Height(m.BuildBreadcrumbs()) breadH := lipgloss.Height(m.BuildBreadcrumbs())
footerH := lipgloss.Height(m.BuildFooter()) footerH := lipgloss.Height(m.BuildFooter())
availH := m.heightContainer - headerH - footerH - breadH availH := m.heightContainer - headerH - footerH - breadH
if availH < 1 { availH = max(availH, 1)
availH = 1
}
if !m.payment.viewportReady { if !m.payment.viewportReady {
m.payment.viewport = viewport.New(viewport.WithWidth(m.widthContent), viewport.WithHeight(availH)) m.payment.viewport = viewport.New(viewport.WithWidth(m.widthContent), viewport.WithHeight(availH))
m.payment.viewport.KeyMap = viewport.KeyMap{} m.payment.viewport.KeyMap = viewport.KeyMap{}
@@ -303,7 +301,7 @@ func (m Model) PaymentPageView() string {
m.widthContainer, m.widthContainer,
m.payment.viewport.Height(), m.payment.viewport.Height(),
lipgloss.Center, lipgloss.Center, lipgloss.Center, lipgloss.Center,
m.renderPaymentHttpsView(), m.renderPaymentHTTPSView(),
) )
} else if m.payment.view == 0 && m.payment.form == nil { } else if m.payment.view == 0 && m.payment.form == nil {
content = m.RenderCardList() content = m.RenderCardList()
@@ -374,7 +372,7 @@ func (m Model) RenderCardList() string {
return lipgloss.JoinVertical(lipgloss.Left, parts...) return lipgloss.JoinVertical(lipgloss.Left, parts...)
} }
func (m Model) renderPaymentHttpsView() string { func (m Model) renderPaymentHTTPSView() string {
baseStyle := m.theme.TextLabel() baseStyle := m.theme.TextLabel()
accentStyle := m.theme.TextHighlight() accentStyle := m.theme.TextHighlight()

3
pkg/tui/qrfefe/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package qrfefe turns text into a QR code drawn with terminal block
// characters, handy for showing links you can scan right off the screen.
package qrfefe

View File

@@ -0,0 +1,194 @@
package tui
import (
"regexp"
"strings"
"testing"
"terminalShop/pkg/models"
)
var ansiRE = regexp.MustCompile("\x1b\\[[0-9;]*m")
// TestRenderShopSmoke prints the rendered shop frame so chrome alignment can
// be inspected, and asserts that the header, body, and footer boxes share the
// same left and right edges.
func TestRenderShopSmoke(t *testing.T) {
m := NewModel("smoke")
m.Loading = false
m.Cart[m.Coffees[0].ID] = &models.CartItem{CoffeeID: m.Coffees[0].ID, Coffee: m.Coffees[0], Quantity: 4}
m = m.updateLayout(100, 40)
m, _ = m.ShopSwitch()
out := m.renderString()
plain := ansiRE.ReplaceAllString(out, "")
t.Log("\n" + plain)
// Collect left/right border columns of every box-drawing row.
var lefts, rights []int
for _, line := range strings.Split(plain, "\n") {
runes := []rune(line)
first, last := -1, -1
for i, r := range runes {
if strings.ContainsRune("╭╮╰╯│", r) {
if first == -1 {
first = i
}
last = i
}
}
if first != -1 {
lefts = append(lefts, first)
rights = append(rights, last)
}
}
if len(lefts) == 0 {
t.Fatal("no box-drawing rows found")
}
for i := range lefts {
if lefts[i] != lefts[0] {
t.Errorf("left edge misaligned: row %d at col %d, expected %d", i, lefts[i], lefts[0])
break
}
if rights[i] != rights[0] {
t.Errorf("right edge misaligned: row %d at col %d, expected %d", i, rights[i], rights[0])
break
}
}
}
// TestRenderAccountSmoke verifies the account page boxes stay within the
// header/footer chrome bounds. The detail area is unboxed, so inner boxes may
// be narrower than the chrome but must never poke outside it.
func TestRenderAccountSmoke(t *testing.T) {
m := NewModel("smoke")
m.Loading = false
m = m.updateLayout(100, 40)
m, _ = m.AccountSwitch()
plain := ansiRE.ReplaceAllString(m.renderString(), "")
t.Log("\n" + plain)
var lefts, rights []int
for _, line := range strings.Split(plain, "\n") {
runes := []rune(line)
first, last := -1, -1
for i, r := range runes {
if strings.ContainsRune("╭╮╰╯│", r) {
if first == -1 {
first = i
}
last = i
}
}
if first != -1 {
lefts = append(lefts, first)
rights = append(rights, last)
}
}
if len(lefts) == 0 {
t.Fatal("no box-drawing rows found")
}
// Row 0 is the header box: it defines the chrome bounds.
for i := range lefts {
if lefts[i] < lefts[0] || rights[i] > rights[0] {
t.Errorf("box outside chrome: row %d spans %d-%d, chrome is %d-%d",
i, lefts[i], rights[i], lefts[0], rights[0])
break
}
}
}
// TestRenderOrderWindowing verifies the windowed order list: whole cards
// only, with ↑/↓ arrow rows marking hidden items.
func TestRenderOrderWindowing(t *testing.T) {
m := NewModel("smoke")
m.Loading = false
m.OrdersLoaded = true
for i := 1; i <= 9; i++ {
m.Orders = append(m.Orders, models.Order{
ID: uint(9000 + i),
Status: models.OrderStatusPaid,
Total: 1000 + i*100,
})
}
m = m.updateLayout(100, 40)
m, _ = m.AccountSwitch()
// Preview mode: window starts at the top, arrow only below.
plain := ansiRE.ReplaceAllString(m.renderString(), "")
t.Log("\n" + plain)
if !strings.Contains(plain, "↓ 4 more") {
t.Errorf("preview mode: expected '↓ 4 more' indicator")
}
if strings.Contains(plain, "↑") {
t.Errorf("preview mode: unexpected up arrow")
}
// Browse mode scrolled to the middle: arrows on both ends.
m.account.orderViewState = 1
m.account.orderCursor = 6
m = m.scrollToAccountDetailItem()
plain = ansiRE.ReplaceAllString(m.renderString(), "")
t.Log("\n" + plain)
if !strings.Contains(plain, "↑ 2 more") || !strings.Contains(plain, "↓ 2 more") {
t.Errorf("browse mode: expected '↑ 2 more' and '↓ 2 more' indicators")
}
}
// TestRenderCartSmoke verifies the cart page cards line up with the chrome.
func TestRenderCartSmoke(t *testing.T) {
m := NewModel("smoke")
m.Loading = false
// Seed coffees carry no IDs, so assign them for distinct cart keys
for i := range m.Coffees {
m.Coffees[i].ID = uint(i + 1)
}
m.Cart[m.Coffees[0].ID] = &models.CartItem{CoffeeID: m.Coffees[0].ID, Coffee: m.Coffees[0], Quantity: 2}
m.Cart[m.Coffees[1].ID] = &models.CartItem{CoffeeID: m.Coffees[1].ID, Coffee: m.Coffees[1], Quantity: 1}
m = m.updateLayout(100, 40)
m, _ = m.CartSwitch()
plain := ansiRE.ReplaceAllString(m.renderString(), "")
t.Log("\n" + plain)
var lefts, rights []int
for _, line := range strings.Split(plain, "\n") {
runes := []rune(line)
first, last := -1, -1
for i, r := range runes {
if strings.ContainsRune("╭╮╰╯│", r) {
if first == -1 {
first = i
}
last = i
}
}
if first != -1 {
lefts = append(lefts, first)
rights = append(rights, last)
}
}
if len(lefts) == 0 {
t.Fatal("no box-drawing rows found")
}
// Every box row (header, cards, footer) must share the chrome edges.
for i := range lefts {
if lefts[i] != lefts[0] || rights[i] != rights[0] {
t.Errorf("box edge misaligned: row %d spans %d-%d, expected %d-%d",
i, lefts[i], rights[i], lefts[0], rights[0])
break
}
}
}
// TestRenderShopSmokeStacked prints the stacked (medium/small) layouts.
func TestRenderShopSmokeStacked(t *testing.T) {
for _, size := range [][2]int{{60, 32}, {45, 30}} {
m := NewModel("smoke")
m.Loading = false
m = m.updateLayout(size[0], size[1])
m, _ = m.ShopSwitch()
t.Logf("--- %dx%d ---\n%s", size[0], size[1], ansiRE.ReplaceAllString(m.renderString(), ""))
}
}

View File

@@ -4,163 +4,173 @@ import (
"fmt" "fmt"
"strings" "strings"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2" "charm.land/lipgloss/v2"
"terminalShop/pkg/models" "terminalShop/pkg/models"
) )
func (m Model) calculateShopWidths() (int, int) { const (
menuWidth := 14 // shopBodyInnerHeight fixes the inner height of the shop body panels so
if len(m.Coffees) == 0 { // the detail box never resizes with the description.
if m.size < large { shopBodyInnerHeight = 13
return m.widthContent, m.widthContent // shopDescLines pins the description region to an exact line count.
} shopDescLines = 3
return menuWidth, m.widthContent - menuWidth )
}
for _, c := range m.Coffees { // shopLayout returns the shared chrome widths, all derived from one content
if w := lipgloss.Width(c.Name); w > menuWidth { // width so the header, body panels, and footer line up exactly.
menuWidth = w // Math ported from the design prototype at ~/programming/test/shop.go:
} // menu(menuW+4) + gap(1) + detail(detailW+4) = contentW = wideW + 4.
} func (m Model) shopLayout() (contentW, menuW, detailW, wideW int) {
if menuWidth > 0 { contentW = m.widthContent
menuWidth += 4 contentW = min(contentW, 74)
} wideW = contentW - 4
if m.size < large { if m.size < large {
menuWidth = m.widthContent // Stacked layout: both panels span the full content width.
return contentW, wideW, wideW, wideW
} }
detailWidth := m.widthContent - menuWidth menuW = 16
if m.size < large { detailW = contentW - 25
detailWidth = m.widthContent return contentW, menuW, detailW, wideW
}
return menuWidth, detailWidth
} }
func (m Model) updateShopViewports() Model { // roastLevel maps a roast type to a 1-5 intensity for the roast meter.
headerHeight := lipgloss.Height(m.BuildHeader()) // It is the fallback for products stored before the roast_level column existed.
footerHeight := lipgloss.Height(m.BuildFooter()) func roastLevel(roastType string) int {
availableHeight := m.heightContainer - headerHeight - footerHeight rt := strings.ToLower(roastType)
switch {
if len(m.Coffees) == 0 { case strings.Contains(rt, "dark"):
return m return 5
case strings.Contains(rt, "light"):
return 2
default:
return 3
} }
menuWidth, detailWidth := m.calculateShopWidths()
if !m.shop.viewportsReady {
m.shop.menuViewport = newViewport(menuWidth, availableHeight)
m.shop.menuViewport.KeyMap = viewport.KeyMap{} // menu nav is manual
m.shop.detailViewport = newViewport(detailWidth, availableHeight)
m.shop.detailViewport.KeyMap = modifiedKeyMap
m.shop.viewportsReady = true
} else {
m.shop.menuViewport.SetWidth(menuWidth)
m.shop.menuViewport.SetHeight(availableHeight)
m.shop.detailViewport.SetWidth(detailWidth)
m.shop.detailViewport.SetHeight(availableHeight)
}
return m
} }
func (m Model) getShopMenuContent() string { // clampLines pads or truncates rendered text to exactly n lines so regions
menuWidth, _ := m.calculateShopWidths() // like the description never change the panel height.
func clampLines(s string, n int) string {
selectedColor := m.theme.Highlight() lines := strings.Split(s, "\n")
if m.shop.selected >= 0 && m.shop.selected < len(m.Coffees) { if len(lines) > n {
if c := m.Coffees[m.shop.selected].Color; c != "" { lines = lines[:n]
selectedColor = lipgloss.Color(c)
}
} }
for len(lines) < n {
var normal, highlighted lipgloss.Style lines = append(lines, "")
if m.size < large {
menuWidth = m.widthContent
normal = m.theme.TextBody().
Width(menuWidth - 1).Align(lipgloss.Center)
highlighted = m.theme.TextAccent().
Width(menuWidth - 1).Align(lipgloss.Center).
Background(selectedColor).Bold(true)
} else {
normal = m.theme.TextBody().
Width(menuWidth+2).Padding(0, 1)
highlighted = m.theme.TextAccent().
Width(menuWidth+2).Padding(0, 1).
Background(selectedColor).Bold(true)
} }
return strings.Join(lines, "\n")
}
// roastMeter renders the strength dots, e.g. ● ● ● ○ ○
func roastMeter(n int) string {
n = max(0, min(n, 5))
on := lipgloss.NewStyle().Foreground(cGold).Render(strings.Repeat("● ", n))
off := pDim.Render(strings.Repeat("○ ", 5-n))
return strings.TrimRight(on+off, " ")
}
func (m Model) shopMenuContent(w int) string {
var b strings.Builder var b strings.Builder
for i, c := range m.Coffees { for i, c := range m.Coffees {
if i == m.shop.selected { if i == m.shop.selected {
b.WriteString(highlighted.Render(c.Name) + "\n") b.WriteString(lipgloss.NewStyle().Width(w).
Background(lipgloss.Color(c.Color)).
Foreground(contrastColor(c.Color)).
Bold(true).
Render(" · " + c.Name))
} else { } else {
b.WriteString(normal.Render(c.Name) + "\n") dot := lipgloss.NewStyle().Foreground(lipgloss.Color(c.Color)).Render("·")
b.WriteString(lipgloss.NewStyle().Width(w).
Render(" " + dot + " " + pBody.Render(c.Name)))
}
if i < len(m.Coffees)-1 {
b.WriteString("\n")
} }
} }
return lipgloss.NewStyle().Padding(0, 1).Render(b.String()) return b.String()
} }
func (m Model) getShopDetailContent() string { func (m Model) shopDetailContent(w int) string {
if len(m.Coffees) == 0 {
return ""
}
coffee := m.Coffees[m.shop.selected] coffee := m.Coffees[m.shop.selected]
_, detailWidth := m.calculateShopWidths()
if m.size >= large {
detailWidth -= 2
}
quantity := 0 quantity := 0
if item, exists := m.Cart[coffee.ID]; exists { if item, exists := m.Cart[coffee.ID]; exists {
quantity = item.Quantity quantity = item.Quantity
} }
detail := lipgloss.JoinVertical(lipgloss.Left, name := pWht.Bold(true).Render(coffee.Name)
m.theme.TextAccent().Bold(true).Render(coffee.Name),
m.theme.TextBody().Render( sep := pDim.Render(" · ")
fmt.Sprintf("%s | %doz | %s", coffee.RoastType, coffee.Ounces, coffee.BeanType), spec := pBody.Render(strings.ToUpper(coffee.RoastType)) + sep +
), pDim.Render(fmt.Sprintf("%dOZ", coffee.Ounces)) + sep +
pDim.Render(strings.ToUpper(coffee.BeanType))
level := coffee.RoastLevel
if level < 1 || level > 5 {
level = roastLevel(coffee.RoastType)
}
strength := pDim.Render("roast ") + roastMeter(level)
price := lipgloss.NewStyle().Foreground(lipgloss.Color(coffee.Color)).Bold(true).
Render(fmt.Sprintf("$%d.%02d", coffee.Price/100, coffee.Price%100)) +
pDim.Render(" usd")
// Stock is not modeled in the backend yet, so the indicator is static.
stock := lipgloss.NewStyle().Foreground(cGreen).Render("● in stock")
desc := clampLines(pBody.Width(w).Render(coffee.Description), shopDescLines)
// stepper: git-diff coloring — red minus, green plus
minus := lipgloss.NewStyle().Foreground(cRed).Bold(true).Render("−")
plus := lipgloss.NewStyle().Foreground(cGreen).Bold(true).Render("+")
count := lipgloss.NewStyle().Foreground(cWhite).Bold(true).
Padding(0, 2).Render(fmt.Sprintf("%d", quantity))
stepper := pDim.Render("qty ") + minus + count + plus
return lipgloss.JoinVertical(lipgloss.Left,
name,
spec,
strength,
"", "",
lipgloss.NewStyle().Foreground(lipgloss.Color(coffee.Color)).Bold(true).Render( price+" "+stock,
fmt.Sprintf("$%.2f", float64(coffee.Price)/100),
),
"", "",
m.theme.TextAccent().Width(detailWidth).Render(coffee.Description), desc,
"", "",
fmt.Sprintf("- %d +", quantity), stepper,
) )
return lipgloss.NewStyle().Width(detailWidth).Render(detail)
} }
func (m Model) ShopView() string { func (m Model) ShopView() string {
if !m.shop.viewportsReady {
m = m.updateShopViewports()
}
if len(m.Coffees) == 0 { if len(m.Coffees) == 0 {
return lipgloss.Place(m.widthContent, m.heightContainer, return lipgloss.Place(m.widthContent, m.heightContainer,
lipgloss.Center, lipgloss.Center, "No products available.") lipgloss.Center, lipgloss.Center, "No products available.")
} }
m.shop.menuViewport.SetContent(m.getShopMenuContent()) _, menuW, detailW, _ := m.shopLayout()
m.shop.detailViewport.SetContent(m.getShopDetailContent())
mc := m.shopMenuContent(menuW)
dc := m.shopDetailContent(detailW)
var body string
if m.size < large { if m.size < large {
return lipgloss.JoinVertical(lipgloss.Top, body = lipgloss.JoinVertical(lipgloss.Left,
m.shop.menuViewport.View(), panel(menuW, 0, mc),
m.shop.detailViewport.View(), panel(detailW, 0, dc),
)
} else {
bodyH := max(shopBodyInnerHeight, lipgloss.Height(mc), lipgloss.Height(dc))
body = lipgloss.JoinHorizontal(lipgloss.Top,
panel(menuW, bodyH, mc),
" ",
panel(detailW, bodyH, dc),
) )
} }
return lipgloss.JoinHorizontal(lipgloss.Top,
m.shop.menuViewport.View(), // Blank rows separate the body from the header and footer boxes.
" ", return "\n" + body + "\n"
m.shop.detailViewport.View(),
)
} }
func (m Model) ShopUpdate(msg tea.Msg) (Model, tea.Cmd) { func (m Model) ShopUpdate(msg tea.Msg) (Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
if len(m.Coffees) == 0 { if len(m.Coffees) == 0 {
return m, nil return m, nil
} }
@@ -197,16 +207,7 @@ func (m Model) ShopUpdate(msg tea.Msg) (Model, tea.Cmd) {
} }
} }
// Pass messages to the detail viewport so pgup/pgdn scroll works return m, nil
m.shop.detailViewport, cmd = m.shop.detailViewport.Update(msg)
cmds = append(cmds, cmd)
if m.shop.viewportsReady {
m.shop.menuViewport.SetContent(m.getShopMenuContent())
m.shop.detailViewport.SetContent(m.getShopDetailContent())
}
return m, tea.Batch(cmds...)
} }
func (m Model) shopMoveSelected(previous bool) Model { func (m Model) shopMoveSelected(previous bool) Model {
@@ -216,18 +217,8 @@ func (m Model) shopMoveSelected(previous bool) Model {
} else { } else {
next++ next++
} }
if next < 0 { next = max(next, 0)
next = 0 next = min(next, len(m.Coffees)-1)
}
if next >= len(m.Coffees) {
next = len(m.Coffees) - 1
}
m.shop.selected = next m.shop.selected = next
if m.shop.viewportsReady {
targetY := (m.shop.selected + 2) * 1
m.shop.menuViewport.SetYOffset(targetY - m.shop.menuViewport.Height()/2)
m.shop.detailViewport.GotoTop()
}
return m return m
} }

View File

@@ -8,13 +8,13 @@ import (
func (m Model) createBoxInner(content string, selected bool, position lipgloss.Position, paddingH int, paddingV int, totalWidth int) string { func (m Model) createBoxInner(content string, selected bool, position lipgloss.Position, paddingH int, paddingV int, totalWidth int) string {
padded := lipgloss.PlaceHorizontal(totalWidth, position, content) padded := lipgloss.PlaceHorizontal(totalWidth, position, content)
base := m.theme.Base().Border(lipgloss.NormalBorder()).Width(totalWidth) base := m.theme.Base().Border(lipgloss.RoundedBorder()).Width(totalWidth)
var style lipgloss.Style var style lipgloss.Style
if selected { if selected {
style = base.BorderForeground(m.theme.Highlight()) style = base.BorderForeground(cWhite)
} else { } else {
style = base.BorderForeground(m.theme.Border()) style = base.BorderForeground(cLine)
} }
return style.Padding(paddingV, paddingH).Render(padded) return style.Padding(paddingV, paddingH).Render(padded)
} }

3
pkg/tui/theme/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package theme keeps the colors and styles in one spot so the whole UI
// looks like it was built by the same person.
package theme

View File

@@ -16,8 +16,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if tick.seq == m.resizeSeq { if tick.seq == m.resizeSeq {
m = m.updateLayout(m.pendingWidth, m.pendingHeight) m = m.updateLayout(m.pendingWidth, m.pendingHeight)
switch m.currentPage { switch m.currentPage {
case shopPage:
m = m.updateShopViewports()
case cartPage: case cartPage:
m = m.updateCartViewport() m = m.updateCartViewport()
case shippingPage: case shippingPage:

View File

@@ -62,7 +62,8 @@ func (m Model) renderString() string {
if breadcrumbs != "" { if breadcrumbs != "" {
breadcrumbsHeight = lipgloss.Height(breadcrumbs) breadcrumbsHeight = lipgloss.Height(breadcrumbs)
} }
footerHeight := 1 footer := m.BuildFooter()
footerHeight := lipgloss.Height(footer)
marginTop := 1 marginTop := 1
marginBottom := 1 marginBottom := 1
bufferSpace := 1 bufferSpace := 1
@@ -87,17 +88,15 @@ func (m Model) renderString() string {
errorStyle = errorStyle.Width(m.widthContent - 4) errorStyle = errorStyle.Width(m.widthContent - 4)
} }
errorBanner := errorStyle.Render(m.error.message) errorBanner := errorStyle.Render(m.error.message)
content = errorBanner + "\n" + m.buildPageContent(availableContentHeight) content = errorBanner + "\n" + m.buildPageContent()
} else if m.notice != nil { } else if m.notice != nil {
noticeStyle := m.theme.TextSuccess().Border(lipgloss.NormalBorder()).BorderForeground(m.theme.Success()).Padding(0, 1).MarginBottom(1) noticeStyle := m.theme.TextSuccess().Border(lipgloss.NormalBorder()).BorderForeground(m.theme.Success()).Padding(0, 1).MarginBottom(1)
noticeBanner := noticeStyle.Render(m.notice.message) noticeBanner := noticeStyle.Render(m.notice.message)
content = noticeBanner + "\n" + m.buildPageContent(availableContentHeight) content = noticeBanner + "\n" + m.buildPageContent()
} else { } else {
content = m.buildPageContent(availableContentHeight) content = m.buildPageContent()
} }
footer := m.BuildFooter()
isViewportPage := m.currentPage == shopPage || m.currentPage == cartPage || isViewportPage := m.currentPage == shopPage || m.currentPage == cartPage ||
m.currentPage == shippingPage || m.currentPage == paymentPage || m.currentPage == shippingPage || m.currentPage == paymentPage ||
m.currentPage == confirmPage || m.currentPage == accountPage m.currentPage == confirmPage || m.currentPage == accountPage
@@ -137,10 +136,10 @@ func (m Model) renderString() string {
) )
} }
func (m Model) buildPageContent(height int) string { func (m Model) buildPageContent() string {
switch m.currentPage { switch m.currentPage {
case accountPage: case accountPage:
return m.BuildAccountView(height) return m.BuildAccountView()
case shippingPage: case shippingPage:
return m.ShippingPageView() return m.ShippingPageView()
case paymentPage: case paymentPage:

3
pkg/utils/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package utils is the catch-all drawer for tiny HTTP helpers that didn't
// earn a package of their own.
package utils

3
pkg/validate/doc.go Normal file
View File

@@ -0,0 +1,3 @@
// Package validate gives user input a once-over before the rest of the app
// trusts it.
package validate