vendor/github.com/charmbracelet/lipgloss/borders.go

443 lines · 10375 bytes

  1package lipgloss
  2
  3import (
  4	"strings"
  5
  6	"github.com/charmbracelet/x/ansi"
  7	"github.com/muesli/termenv"
  8	"github.com/rivo/uniseg"
  9)
 10
 11// Border contains a series of values which comprise the various parts of a
 12// border.
 13type Border struct {
 14	Top          string
 15	Bottom       string
 16	Left         string
 17	Right        string
 18	TopLeft      string
 19	TopRight     string
 20	BottomLeft   string
 21	BottomRight  string
 22	MiddleLeft   string
 23	MiddleRight  string
 24	Middle       string
 25	MiddleTop    string
 26	MiddleBottom string
 27}
 28
 29// GetTopSize returns the width of the top border. If borders contain runes of
 30// varying widths, the widest rune is returned. If no border exists on the top
 31// edge, 0 is returned.
 32func (b Border) GetTopSize() int {
 33	return getBorderEdgeWidth(b.TopLeft, b.Top, b.TopRight)
 34}
 35
 36// GetRightSize returns the width of the right border. If borders contain
 37// runes of varying widths, the widest rune is returned. If no border exists on
 38// the right edge, 0 is returned.
 39func (b Border) GetRightSize() int {
 40	return getBorderEdgeWidth(b.TopRight, b.Right, b.BottomRight)
 41}
 42
 43// GetBottomSize returns the width of the bottom border. If borders contain
 44// runes of varying widths, the widest rune is returned. If no border exists on
 45// the bottom edge, 0 is returned.
 46func (b Border) GetBottomSize() int {
 47	return getBorderEdgeWidth(b.BottomLeft, b.Bottom, b.BottomRight)
 48}
 49
 50// GetLeftSize returns the width of the left border. If borders contain runes
 51// of varying widths, the widest rune is returned. If no border exists on the
 52// left edge, 0 is returned.
 53func (b Border) GetLeftSize() int {
 54	return getBorderEdgeWidth(b.TopLeft, b.Left, b.BottomLeft)
 55}
 56
 57func getBorderEdgeWidth(borderParts ...string) (maxWidth int) {
 58	for _, piece := range borderParts {
 59		w := maxRuneWidth(piece)
 60		if w > maxWidth {
 61			maxWidth = w
 62		}
 63	}
 64	return maxWidth
 65}
 66
 67var (
 68	noBorder = Border{}
 69
 70	normalBorder = Border{
 71		Top:          "─",
 72		Bottom:       "─",
 73		Left:         "│",
 74		Right:        "│",
 75		TopLeft:      "┌",
 76		TopRight:     "┐",
 77		BottomLeft:   "└",
 78		BottomRight:  "┘",
 79		MiddleLeft:   "├",
 80		MiddleRight:  "┤",
 81		Middle:       "┼",
 82		MiddleTop:    "┬",
 83		MiddleBottom: "┴",
 84	}
 85
 86	roundedBorder = Border{
 87		Top:          "─",
 88		Bottom:       "─",
 89		Left:         "│",
 90		Right:        "│",
 91		TopLeft:      "╭",
 92		TopRight:     "╮",
 93		BottomLeft:   "╰",
 94		BottomRight:  "╯",
 95		MiddleLeft:   "├",
 96		MiddleRight:  "┤",
 97		Middle:       "┼",
 98		MiddleTop:    "┬",
 99		MiddleBottom: "┴",
100	}
101
102	blockBorder = Border{
103		Top:         "█",
104		Bottom:      "█",
105		Left:        "█",
106		Right:       "█",
107		TopLeft:     "█",
108		TopRight:    "█",
109		BottomLeft:  "█",
110		BottomRight: "█",
111	}
112
113	outerHalfBlockBorder = Border{
114		Top:         "▀",
115		Bottom:      "▄",
116		Left:        "▌",
117		Right:       "▐",
118		TopLeft:     "▛",
119		TopRight:    "▜",
120		BottomLeft:  "▙",
121		BottomRight: "▟",
122	}
123
124	innerHalfBlockBorder = Border{
125		Top:         "▄",
126		Bottom:      "▀",
127		Left:        "▐",
128		Right:       "▌",
129		TopLeft:     "▗",
130		TopRight:    "▖",
131		BottomLeft:  "▝",
132		BottomRight: "▘",
133	}
134
135	thickBorder = Border{
136		Top:          "━",
137		Bottom:       "━",
138		Left:         "┃",
139		Right:        "┃",
140		TopLeft:      "┏",
141		TopRight:     "┓",
142		BottomLeft:   "┗",
143		BottomRight:  "┛",
144		MiddleLeft:   "┣",
145		MiddleRight:  "┫",
146		Middle:       "╋",
147		MiddleTop:    "┳",
148		MiddleBottom: "┻",
149	}
150
151	doubleBorder = Border{
152		Top:          "═",
153		Bottom:       "═",
154		Left:         "║",
155		Right:        "║",
156		TopLeft:      "╔",
157		TopRight:     "╗",
158		BottomLeft:   "╚",
159		BottomRight:  "╝",
160		MiddleLeft:   "╠",
161		MiddleRight:  "╣",
162		Middle:       "╬",
163		MiddleTop:    "╦",
164		MiddleBottom: "╩",
165	}
166
167	hiddenBorder = Border{
168		Top:          " ",
169		Bottom:       " ",
170		Left:         " ",
171		Right:        " ",
172		TopLeft:      " ",
173		TopRight:     " ",
174		BottomLeft:   " ",
175		BottomRight:  " ",
176		MiddleLeft:   " ",
177		MiddleRight:  " ",
178		Middle:       " ",
179		MiddleTop:    " ",
180		MiddleBottom: " ",
181	}
182)
183
184// NormalBorder returns a standard-type border with a normal weight and 90
185// degree corners.
186func NormalBorder() Border {
187	return normalBorder
188}
189
190// RoundedBorder returns a border with rounded corners.
191func RoundedBorder() Border {
192	return roundedBorder
193}
194
195// BlockBorder returns a border that takes the whole block.
196func BlockBorder() Border {
197	return blockBorder
198}
199
200// OuterHalfBlockBorder returns a half-block border that sits outside the frame.
201func OuterHalfBlockBorder() Border {
202	return outerHalfBlockBorder
203}
204
205// InnerHalfBlockBorder returns a half-block border that sits inside the frame.
206func InnerHalfBlockBorder() Border {
207	return innerHalfBlockBorder
208}
209
210// ThickBorder returns a border that's thicker than the one returned by
211// NormalBorder.
212func ThickBorder() Border {
213	return thickBorder
214}
215
216// DoubleBorder returns a border comprised of two thin strokes.
217func DoubleBorder() Border {
218	return doubleBorder
219}
220
221// HiddenBorder returns a border that renders as a series of single-cell
222// spaces. It's useful for cases when you want to remove a standard border but
223// maintain layout positioning. This said, you can still apply a background
224// color to a hidden border.
225func HiddenBorder() Border {
226	return hiddenBorder
227}
228
229func (s Style) applyBorder(str string) string {
230	var (
231		topSet    = s.isSet(borderTopKey)
232		rightSet  = s.isSet(borderRightKey)
233		bottomSet = s.isSet(borderBottomKey)
234		leftSet   = s.isSet(borderLeftKey)
235
236		border    = s.getBorderStyle()
237		hasTop    = s.getAsBool(borderTopKey, false)
238		hasRight  = s.getAsBool(borderRightKey, false)
239		hasBottom = s.getAsBool(borderBottomKey, false)
240		hasLeft   = s.getAsBool(borderLeftKey, false)
241
242		topFG    = s.getAsColor(borderTopForegroundKey)
243		rightFG  = s.getAsColor(borderRightForegroundKey)
244		bottomFG = s.getAsColor(borderBottomForegroundKey)
245		leftFG   = s.getAsColor(borderLeftForegroundKey)
246
247		topBG    = s.getAsColor(borderTopBackgroundKey)
248		rightBG  = s.getAsColor(borderRightBackgroundKey)
249		bottomBG = s.getAsColor(borderBottomBackgroundKey)
250		leftBG   = s.getAsColor(borderLeftBackgroundKey)
251	)
252
253	// If a border is set and no sides have been specifically turned on or off
254	// render borders on all sides.
255	if border != noBorder && !(topSet || rightSet || bottomSet || leftSet) {
256		hasTop = true
257		hasRight = true
258		hasBottom = true
259		hasLeft = true
260	}
261
262	// If no border is set or all borders are been disabled, abort.
263	if border == noBorder || (!hasTop && !hasRight && !hasBottom && !hasLeft) {
264		return str
265	}
266
267	lines, width := getLines(str)
268
269	if hasLeft {
270		if border.Left == "" {
271			border.Left = " "
272		}
273		width += maxRuneWidth(border.Left)
274	}
275
276	if hasRight && border.Right == "" {
277		border.Right = " "
278	}
279
280	// If corners should be rendered but are set with the empty string, fill them
281	// with a single space.
282	if hasTop && hasLeft && border.TopLeft == "" {
283		border.TopLeft = " "
284	}
285	if hasTop && hasRight && border.TopRight == "" {
286		border.TopRight = " "
287	}
288	if hasBottom && hasLeft && border.BottomLeft == "" {
289		border.BottomLeft = " "
290	}
291	if hasBottom && hasRight && border.BottomRight == "" {
292		border.BottomRight = " "
293	}
294
295	// Figure out which corners we should actually be using based on which
296	// sides are set to show.
297	if hasTop {
298		switch {
299		case !hasLeft && !hasRight:
300			border.TopLeft = ""
301			border.TopRight = ""
302		case !hasLeft:
303			border.TopLeft = ""
304		case !hasRight:
305			border.TopRight = ""
306		}
307	}
308	if hasBottom {
309		switch {
310		case !hasLeft && !hasRight:
311			border.BottomLeft = ""
312			border.BottomRight = ""
313		case !hasLeft:
314			border.BottomLeft = ""
315		case !hasRight:
316			border.BottomRight = ""
317		}
318	}
319
320	// For now, limit corners to one rune.
321	border.TopLeft = getFirstRuneAsString(border.TopLeft)
322	border.TopRight = getFirstRuneAsString(border.TopRight)
323	border.BottomRight = getFirstRuneAsString(border.BottomRight)
324	border.BottomLeft = getFirstRuneAsString(border.BottomLeft)
325
326	var out strings.Builder
327
328	// Render top
329	if hasTop {
330		top := renderHorizontalEdge(border.TopLeft, border.Top, border.TopRight, width)
331		top = s.styleBorder(top, topFG, topBG)
332		out.WriteString(top)
333		out.WriteRune('\n')
334	}
335
336	leftRunes := []rune(border.Left)
337	leftIndex := 0
338
339	rightRunes := []rune(border.Right)
340	rightIndex := 0
341
342	// Render sides
343	for i, l := range lines {
344		if hasLeft {
345			r := string(leftRunes[leftIndex])
346			leftIndex++
347			if leftIndex >= len(leftRunes) {
348				leftIndex = 0
349			}
350			out.WriteString(s.styleBorder(r, leftFG, leftBG))
351		}
352		out.WriteString(l)
353		if hasRight {
354			r := string(rightRunes[rightIndex])
355			rightIndex++
356			if rightIndex >= len(rightRunes) {
357				rightIndex = 0
358			}
359			out.WriteString(s.styleBorder(r, rightFG, rightBG))
360		}
361		if i < len(lines)-1 {
362			out.WriteRune('\n')
363		}
364	}
365
366	// Render bottom
367	if hasBottom {
368		bottom := renderHorizontalEdge(border.BottomLeft, border.Bottom, border.BottomRight, width)
369		bottom = s.styleBorder(bottom, bottomFG, bottomBG)
370		out.WriteRune('\n')
371		out.WriteString(bottom)
372	}
373
374	return out.String()
375}
376
377// Render the horizontal (top or bottom) portion of a border.
378func renderHorizontalEdge(left, middle, right string, width int) string {
379	if middle == "" {
380		middle = " "
381	}
382
383	leftWidth := ansi.StringWidth(left)
384	rightWidth := ansi.StringWidth(right)
385
386	runes := []rune(middle)
387	j := 0
388
389	out := strings.Builder{}
390	out.WriteString(left)
391	for i := leftWidth + rightWidth; i < width+rightWidth; {
392		out.WriteRune(runes[j])
393		j++
394		if j >= len(runes) {
395			j = 0
396		}
397		i += ansi.StringWidth(string(runes[j]))
398	}
399	out.WriteString(right)
400
401	return out.String()
402}
403
404// Apply foreground and background styling to a border.
405func (s Style) styleBorder(border string, fg, bg TerminalColor) string {
406	if fg == noColor && bg == noColor {
407		return border
408	}
409
410	style := termenv.Style{}
411
412	if fg != noColor {
413		style = style.Foreground(fg.color(s.r))
414	}
415	if bg != noColor {
416		style = style.Background(bg.color(s.r))
417	}
418
419	return style.Styled(border)
420}
421
422func maxRuneWidth(str string) int {
423	var width int
424
425	state := -1
426	for len(str) > 0 {
427		var w int
428		_, str, w, state = uniseg.FirstGraphemeClusterInString(str, state)
429		if w > width {
430			width = w
431		}
432	}
433
434	return width
435}
436
437func getFirstRuneAsString(str string) string {
438	if str == "" {
439		return str
440	}
441	r := []rune(str)
442	return string(r[0])
443}