1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
|
package main
import (
"context"
"fmt"
"image/color"
"log"
"os"
"strings"
"github.com/charmbracelet/lipgloss/v2"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/ultraviolet/screen"
"github.com/charmbracelet/x/ansi"
"github.com/lucasb-eyer/go-colorful"
"github.com/rivo/uniseg"
)
const (
// In real life situations we'd adjust the document to fit the width we've
// detected. In the case of this example we're hardcoding the width, and
// later using the detected width only to truncate in order to avoid jaggy
// wrapping.
width = 96
// How wide to render various columns in the layout.
columnWidth = 30
)
var (
// Whether the detected background color is dark. We detect this in init().
hasDarkBG bool
// A helper function for choosing either a light or dark color based on the
// detected background color. We create this in init().
lightDark lipgloss.LightDarkFunc
)
func init() {
// Detect the background color.
hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, os.Stdout)
// Create a new helper function for choosing either a light or dark color
// based on the detected background color.
lightDark = lipgloss.LightDark(hasDarkBG)
}
func main() {
// Style definitions.
var (
// General.
subtle = lightDark(lipgloss.Color("#D9DCCF"), lipgloss.Color("#383838"))
highlight = lightDark(lipgloss.Color("#874BFD"), lipgloss.Color("#7D56F4"))
special = lightDark(lipgloss.Color("#43BF6D"), lipgloss.Color("#73F59F"))
divider = lipgloss.NewStyle().
SetString("•").
Padding(0, 1).
Foreground(subtle).
String()
url = lipgloss.NewStyle().Foreground(special).Render
// Tabs.
activeTabBorder = lipgloss.Border{
Top: "─",
Bottom: " ",
Left: "│",
Right: "│",
TopLeft: "╭",
TopRight: "╮",
BottomLeft: "┘",
BottomRight: "└",
}
tabBorder = lipgloss.Border{
Top: "─",
Bottom: "─",
Left: "│",
Right: "│",
TopLeft: "╭",
TopRight: "╮",
BottomLeft: "┴",
BottomRight: "┴",
}
tab = lipgloss.NewStyle().
Border(tabBorder, true).
BorderForeground(highlight).
Padding(0, 1)
activeTab = tab.Border(activeTabBorder, true)
tabGap = tab.
BorderTop(false).
BorderLeft(false).
BorderRight(false)
// Title.
titleStyle = lipgloss.NewStyle().
MarginLeft(1).
MarginRight(5).
Padding(0, 1).
Italic(true).
Foreground(lipgloss.Color("#FFF7DB")).
SetString("Lip Gloss")
descStyle = lipgloss.NewStyle().MarginTop(1)
infoStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderTop(true).
BorderForeground(subtle)
// Dialog.
dialogBoxStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#874BFD")).
Padding(1, 0).
BorderTop(true).
BorderLeft(true).
BorderRight(true).
BorderBottom(true)
buttonStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFF7DB")).
Background(lipgloss.Color("#888B7E")).
Padding(0, 3).
MarginTop(1)
activeButtonStyle = buttonStyle.
Foreground(lipgloss.Color("#FFF7DB")).
Background(lipgloss.Color("#F25D94")).
MarginRight(2).
Underline(true)
// List.
list = lipgloss.NewStyle().
Border(lipgloss.NormalBorder(), false, true, false, false).
BorderForeground(subtle).
MarginRight(2).
Height(8).
Width(columnWidth + 1)
listHeader = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderBottom(true).
BorderForeground(subtle).
MarginRight(2).
Render
listItem = lipgloss.NewStyle().PaddingLeft(2).Render
checkMark = lipgloss.NewStyle().SetString("✓").
Foreground(special).
PaddingRight(1).
String()
listDone = func(s string) string {
return checkMark + lipgloss.NewStyle().
Strikethrough(true).
Foreground(lightDark(lipgloss.Color("#969B86"), lipgloss.Color("#696969"))).
Render(s)
}
// Paragraphs/History.
historyStyle = lipgloss.NewStyle().
Align(lipgloss.Left).
Foreground(lipgloss.Color("#FAFAFA")).
Background(highlight).
Margin(1, 3, 0, 0).
Padding(1, 2).
Height(19).
Width(columnWidth)
// Status Bar.
statusNugget = lipgloss.NewStyle().
Foreground(lipgloss.Color("#FFFDF5")).
Padding(0, 1)
statusBarStyle = lipgloss.NewStyle().
Foreground(lightDark(lipgloss.Color("#343433"), lipgloss.Color("#C1C6B2"))).
Background(lightDark(lipgloss.Color("#D9DCCF"), lipgloss.Color("#353533")))
statusStyle = lipgloss.NewStyle().
Inherit(statusBarStyle).
Foreground(lipgloss.Color("#FFFDF5")).
Background(lipgloss.Color("#FF5F87")).
Padding(0, 1).
MarginRight(1)
encodingStyle = statusNugget.
Background(lipgloss.Color("#A550DF")).
Align(lipgloss.Right)
statusText = lipgloss.NewStyle().Inherit(statusBarStyle)
fishCakeStyle = statusNugget.Background(lipgloss.Color("#6124DF"))
// Page.
docStyle = lipgloss.NewStyle().Padding(1, 2, 1, 2)
)
doc := strings.Builder{}
// Tabs.
{
row := lipgloss.JoinHorizontal(
lipgloss.Top,
activeTab.Render("Lip Gloss"),
tab.Render("Blush"),
tab.Render("Eye Shadow"),
tab.Render("Mascara"),
tab.Render("Foundation"),
)
gap := tabGap.Render(strings.Repeat(" ", max(0, width-lipgloss.Width(row)-2)))
row = lipgloss.JoinHorizontal(lipgloss.Bottom, row, gap)
doc.WriteString(row + "\n\n")
}
// Title.
{
var (
colors = colorGrid(1, 5)
title strings.Builder
)
for i, v := range colors {
const offset = 2
c := lipgloss.Color(v[0])
fmt.Fprint(&title, titleStyle.MarginLeft(i*offset).Background(c))
if i < len(colors)-1 {
title.WriteRune('\n')
}
}
desc := lipgloss.JoinVertical(lipgloss.Left,
descStyle.Render("Style Definitions for Nice Terminal Layouts"),
infoStyle.Render("From Charm"+divider+url("https://github.com/charmbracelet/lipgloss")),
)
row := lipgloss.JoinHorizontal(lipgloss.Top, title.String(), desc)
doc.WriteString(row + "\n\n")
}
// Dialog.
okButton := activeButtonStyle.Render("Yes")
cancelButton := buttonStyle.Render("Maybe")
grad := applyGradient(
lipgloss.NewStyle(),
"Are you sure you want to eat marmalade?",
lipgloss.Color("#EDFF82"),
lipgloss.Color("#F25D94"),
)
question := lipgloss.NewStyle().
Width(50).
Align(lipgloss.Center).
Render(grad)
buttons := lipgloss.JoinHorizontal(lipgloss.Top, okButton, cancelButton)
dialogUI := lipgloss.JoinVertical(lipgloss.Center, question, buttons)
dialog := lipgloss.Place(width, 9,
lipgloss.Center, lipgloss.Center,
"",
// dialogBoxStyle.Render(dialogUi),
lipgloss.WithWhitespaceChars("猫咪"),
lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Foreground(subtle)),
)
doc.WriteString(dialog + "\n\n")
// Color grid.
colors := func() string {
colors := colorGrid(14, 8)
b := strings.Builder{}
for _, x := range colors {
for _, y := range x {
s := lipgloss.NewStyle().SetString(" ").Background(lipgloss.Color(y))
b.WriteString(s.String())
}
b.WriteRune('\n')
}
return b.String()
}()
lists := lipgloss.JoinHorizontal(lipgloss.Top,
list.Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader("Citrus Fruits to Try"),
listDone("Grapefruit"),
listDone("Yuzu"),
listItem("Citron"),
listItem("Kumquat"),
listItem("Pomelo"),
),
),
list.Width(columnWidth).Render(
lipgloss.JoinVertical(lipgloss.Left,
listHeader("Actual Lip Gloss Vendors"),
listItem("Glossier"),
listItem("Claire‘s Boutique"),
listDone("Nyx"),
listItem("Mac"),
listDone("Milk"),
),
),
)
doc.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, lists, colors))
// Marmalade history.
{
const (
historyA = "The Romans learned from the Greeks that quinces slowly cooked with honey would “set” when cool. The Apicius gives a recipe for preserving whole quinces, stems and leaves attached, in a bath of honey diluted with defrutum: Roman marmalade. Preserves of quince and lemon appear (along with rose, apple, plum and pear) in the Book of ceremonies of the Byzantine Emperor Constantine VII Porphyrogennetos."
historyB = "Medieval quince preserves, which went by the French name cotignac, produced in a clear version and a fruit pulp version, began to lose their medieval seasoning of spices in the 16th century. In the 17th century, La Varenne provided recipes for both thick and clear cotignac."
historyC = "In 1524, Henry VIII, King of England, received a “box of marmalade” from Mr. Hull of Exeter. This was probably marmelada, a solid quince paste from Portugal, still made and sold in southern Europe today. It became a favourite treat of Anne Boleyn and her ladies in waiting."
)
doc.WriteString(lipgloss.JoinHorizontal(
lipgloss.Top,
historyStyle.Align(lipgloss.Right).Render(historyA),
historyStyle.Align(lipgloss.Center).Render(historyB),
historyStyle.MarginRight(0).Render(historyC),
))
doc.WriteString("\n\n")
}
// Status bar.
{
w := lipgloss.Width
lightDarkState := "Light"
if hasDarkBG {
lightDarkState = "Dark"
}
statusKey := statusStyle.Render("STATUS")
encoding := encodingStyle.Render("UTF-8")
fishCake := fishCakeStyle.Render("🍥 Fish Cake")
statusVal := statusText.
Width(width - w(statusKey) - w(encoding) - w(fishCake)).
Render("Ravishingly " + lightDarkState + "!")
bar := lipgloss.JoinHorizontal(lipgloss.Top,
statusKey,
statusVal,
encoding,
fishCake,
)
doc.WriteString(statusBarStyle.Width(width).Render(bar))
}
t := uv.DefaultTerminal()
// Set terminal to raw mode to read input events.
if err := t.Start(); err != nil {
log.Fatalf("starting program: %v", err)
}
t.SetLogger(log.Default())
physicalWidth, _, err := t.GetSize()
if err != nil {
log.Fatalf("getting size: %v", err)
}
if physicalWidth > 0 {
docStyle = docStyle.MaxWidth(physicalWidth)
}
// Use altscreen mode.
t.EnterAltScreen()
// Enable mouse events.
t.WriteString(ansi.SetButtonEventMouseMode + ansi.SetSgrExtMouseMode)
// Display the program.
dialogWidth := lipgloss.Width(dialogUI) + dialogBoxStyle.GetHorizontalFrameSize()
dialogHeight := lipgloss.Height(dialogUI) + dialogBoxStyle.GetVerticalFrameSize()
dialogX, dialogY := physicalWidth/2-dialogWidth/2-docStyle.GetVerticalFrameSize()-1, 12
mainDoc := docStyle.Render(doc.String())
display := func() {
screen.Clear(t)
mainSs := uv.NewStyledString(mainDoc)
mainSs.Draw(t, t.Bounds()) //nolint:errcheck
boxArea := uv.Rect(dialogX, dialogY, dialogWidth, dialogHeight)
box := uv.NewStyledString(dialogBoxStyle.Render(dialogUI))
box.Draw(t, boxArea) //nolint:errcheck
t.Display()
}
// First display.
display()
LOOP:
for ev := range t.Events() {
log.Printf("event: %T", ev)
switch ev := ev.(type) {
case uv.WindowSizeEvent:
t.Resize(ev.Width, ev.Height)
t.Erase()
case uv.MouseClickEvent:
dialogX, dialogY = ev.X-dialogWidth/2, ev.Y-dialogHeight/2
case uv.KeyPressEvent:
log.Printf("%T %q %q", ev, ev.String(), ev.Keystroke())
switch {
case ev.MatchString("ctrl+c", "q"):
break LOOP
case ev.MatchString("left", "h"):
dialogX--
case ev.MatchString("down", "j"):
dialogY++
case ev.MatchString("up", "k"):
dialogY--
case ev.MatchString("right", "l"):
dialogX++
}
}
// Update the display on any event.
display()
}
t.WriteString(ansi.ResetButtonEventMouseMode + ansi.ResetSgrExtMouseMode)
// Shutdown the program gracefully and exit.
if err := t.Shutdown(context.Background()); err != nil {
log.Fatalf("shutting down program: %v", err)
}
}
func colorGrid(xSteps, ySteps int) [][]string {
x0y0, _ := colorful.Hex("#F25D94")
x1y0, _ := colorful.Hex("#EDFF82")
x0y1, _ := colorful.Hex("#643AFF")
x1y1, _ := colorful.Hex("#14F9D5")
x0 := make([]colorful.Color, ySteps)
for i := range x0 {
x0[i] = x0y0.BlendLuv(x0y1, float64(i)/float64(ySteps))
}
x1 := make([]colorful.Color, ySteps)
for i := range x1 {
x1[i] = x1y0.BlendLuv(x1y1, float64(i)/float64(ySteps))
}
grid := make([][]string, ySteps)
for x := 0; x < ySteps; x++ {
y0 := x0[x]
grid[x] = make([]string, xSteps)
for y := 0; y < xSteps; y++ {
grid[x][y] = y0.BlendLuv(x1[x], float64(y)/float64(xSteps)).Hex()
}
}
return grid
}
func max(a, b int) int { //nolint:predeclared
if a > b {
return a
}
return b
}
// applyGradient applies a gradient to the given string string.
func applyGradient(base lipgloss.Style, input string, from, to color.Color) string {
// We want to get the graphemes of the input string, which is the number of
// characters as a human would see them.
//
// We definitely don't want to use len(), because that returns the
// bytes. The rune count would get us closer but there are times, like with
// emojis, where the rune count is greater than the number of actual
// characters.
g := uniseg.NewGraphemes(input)
var chars []string
for g.Next() {
chars = append(chars, g.Str())
}
// Genrate the blend.
a, _ := colorful.MakeColor(to)
b, _ := colorful.MakeColor(from)
var output strings.Builder
var hex string
for i := 0; i < len(chars); i++ {
hex = a.BlendLuv(b, float64(i)/float64(len(chars)-1)).Hex()
output.WriteString(base.Foreground(lipgloss.Color(hex)).Render(chars[i]))
}
return output.String()
}
func init() {
f, err := os.OpenFile("layout.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o666)
if err != nil {
log.Fatal(err)
}
log.SetOutput(f)
}
|