Repository navigation
feat: individual border side style - #176
grindlemire merged 29 commits into
Conversation
- Add tailwind border style classes for sides. For `t` (top): `border-t-single`, `border-t-double`, `border-t-rounded`, `border-t-thick` and `border-t-none` for empty border. - The same for the other «sides»: `r` (right), `b` (bottom), `l` (left), `x` (left and right), `y` (top and bottom). - `none` from completeness and because it's useful. For example, to set all borders except top: `<div class="border-thick border-t-none">`. - Also added properly `border-none` tailwind class (it was mentioned in some part of the codebase but not really implemented). - Class names loosely follow naming used in tailwind (just like other parts of `gsx`) for individual sides. See [Individual sides](https://tailwindcss.com/docs/border-color#individual-sides). - Add a `tui.WithBorderTRBL` option to set a border by its sides, plus other related functions to support this feature. And the equivalents for `textarea` and `input` built-in elements. - Update `lsp` and `tuigen` accordingly. **BREAKING** (potentially) - `border` changes from being a simple `tui.BorderStyle` to be a `tui.Borders`, to describe each side of a box individually. Externally it doesn't changes much, but internally it does a bit. `WithBorder()` keeps working but now it resolver to a `tui.Borders`, to ease things (like class accumulation). - Tailwind classes about border styles accumulate at end always. Instead of trying to keep some operations when resolving from a string literal of tailwind classes, we get one single operation in the end, which does just what we want and doesn't complicate things. I mean, with padding, all-sides padding alone stays positional, keeping 2 (or more) `Padding` ops when it could accumulate in just one `PaddingEdges` opt. For `Borders`, the equivalent is `BorderSides` and it just accumulates everything in one opt. I tried to follow and do it similarly to padding, but it just seemed it would overcomplicate the code.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #176 +/- ##
==========================================
+ Coverage 84.79% 84.97% +0.17%
==========================================
Files 169 169
Lines 21630 21756 +126
==========================================
+ Hits 18341 18487 +146
+ Misses 2630 2622 -8
+ Partials 659 647 -12 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
| // 0 is for all-sides border. | ||
| case 0: | ||
| s.top, s.right, s.bottom, s.left = b, b, b, b | ||
| case 't': |
There was a problem hiding this comment.
Side class removes other borders
When an element has WithBorder(BorderSingle) and then gets border-t-thick, the class leaves its other sides as BorderNone. WithBorderTRBL replaces all four sides, so the right, bottom, and left borders disappear instead of staying single.
Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/tailwind/tailwind.go
Line: 429
Comment:
**Side class removes other borders**
When an element has `WithBorder(BorderSingle)` and then gets `border-t-thick`, the class leaves its other sides as `BorderNone`. `WithBorderTRBL` replaces all four sides, so the right, bottom, and left borders disappear instead of staying single.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
I could try to fix this, but this complain is simply unfair: that's the same way padding or margin behaves.
Example:
e := New(
WithPadding(5),
WithClass("pt-4"), // its same than doing WithPaddingTRBL(4, 0, 0, 0) here
)
if e.style.Padding != EdgeAll(5) {
t.Errorf("Padding not set correctly: %+v", e.style.Padding)
}This will error. The class leaves its other padding sides as 0, replacing them, so «the right, bottom and left paddings disappear instead of staying 5.
Example:
e := New(
WithMargin(5),
WithClass("mt-4"), // its same than doing WithMarginTRBL(4, 0, 0, 0) here
)
if e.style.Margin != EdgeAll(5) {
t.Errorf("Margin not set correctly: %+v", e.style.Margin)
}This will error. The class leaves its other margin sides as 0, replacing them, so «the right, bottom and left margin disappear instead of staying 5.
That's not even tested (see element_options_test.go).
So, if this is a problem, we should patch everything else, @grindlemire . But I think we shouldn't, because this just complicates things/code. Library is assumed to be favoring .gsx. This only happens using Go code as an escape hatch. In such case, it almost not makes sense to just do the code that I did above, which is what triggers this and also happens, as ilustrated, with these other cases. We're assuming that the developer knows what is doing when using such escape class. When using .gsx and classes, per-side margin, padding and here borders, behave as they should (that is tested).
There was a problem hiding this comment.
You're right — this is consistent with the existing spacing semantics. pt-4 and mt-4 already resolve to complete edge values with unspecified sides set to zero, so a border-side class resolving to a complete Borders value is not a unique regression. Since classes are the intended styling path and Go options are an escape hatch, callers mixing them are already opting into that override behavior. I'll withdraw this finding; no border-specific merge is required here.
Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.
There was a problem hiding this comment.
You're right — this is consistent with the existing padding and margin behavior, where a per-side class supplies unspecified sides as zero rather than merging with an earlier Go option. Since WithClass is the escape hatch for explicitly applying Tailwind semantics, border-t-thick resolving to a complete BorderSides value with the other sides as BorderNone is expected. My comment was not a valid defect; the alternative would require changing the established spacing semantics as well.
There was a problem hiding this comment.
You're right — this is consistent with the existing WithPadding/WithPaddingTRBL and margin behavior. The class resolver's established contract is that a per-side utility produces the complete four-side value, with unspecified sides at zero, rather than merging with an independently applied Go option.
My comment incorrectly treated border sides as having different merge semantics from padding and margin. I’m withdrawing this finding; no change is required here.
| <div class="border-x-double border-y-thick p-1"> | ||
| <span>Lateral double borders and top and bottom with a thick one. Corners are not drawn.</span> | ||
| </div> | ||
| <div class="border-b-single p-1"> | ||
| <span>Just single bottom border. No corner is drawn.</span> | ||
| </div> | ||
| <div class="border-t-rounded border-r-rounded border-b-thick border-l-double p-1"> | ||
| <span>Border top and right rounded, border bottom thick and border left double. Only top right corner is drawn.</span> |
There was a problem hiding this comment.
Guide describes the wrong corners
These examples say mixed visible sides draw no corners, or only the top-right corner. Borders.Chars draws a corner wherever the adjoining sides are visible, so both examples lead readers to expect a different result. Update the descriptions to match what the code draws.
Prompt To Fix With AI
This is a comment left during a code review.
Path: docs/content/guides/03-styling.md
Line: 185-192
Comment:
**Guide describes the wrong corners**
These examples say mixed visible sides draw no corners, or only the top-right corner. `Borders.Chars` draws a corner wherever the adjoining sides are visible, so both examples lead readers to expect a different result. Update the descriptions to match what the code draws.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| "border-t-none", "border-t-single", "border-t-double", "border-t-rounded", | ||
| "border-t-thick", | ||
| "border-r-none", "border-r-single", "border-r-double", "border-r-rounded", | ||
| "border-r-thick", | ||
| "border-b-none", "border-b-single", "border-b-double", "border-b-rounded", | ||
| "border-b-thick", | ||
| "border-l-none", "border-l-single", "border-l-double", "border-l-rounded", | ||
| "border-l-thick", |
There was a problem hiding this comment.
Two-side typos lack suggestions
Completion offers the new border-x-* and border-y-* classes, but the list used for typo suggestions includes only individual sides. Add the two-side classes so a reader who mistypes one can get the intended correction.
Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/tuigen/tailwind_validation.go
Line: 166-173
Comment:
**Two-side typos lack suggestions**
Completion offers the new `border-x-*` and `border-y-*` classes, but the list used for typo suggestions includes only individual sides. Add the two-side classes so a reader who mistypes one can get the intended correction.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Comments Outside DiffThese findings could not be posted inline.
|
|
If I have the time, will check tomorrow morning the issues Note: I did a lot of comments to the code before sent, but seems like GitHub lost that :(. I will redo them tomorrow too, If I can. |
About this one, I can say the same. I don't see the error here. I'm expecting the developer knowing what is doing. That leaves only left this one:
Checked it and also don't understand this complain. So, just like before, if all sides are none → no box is drawn. I will check if if I can improve the codecov. And then commit the other change (I hold the other fix till then to avoid retriggering the CI). And also re-comment the code in several places (GitHub removed my comments on-side when I sent the PR last night). |
| | `BulletMarker` | The unordered-list marker string, e.g. `"• "` | | ||
|
|
||
| Tables draw as a full grid with an outer box, column separators, and a rule under the header. Blockquotes render a one-column glyph bar on the left rather than a box border, since a `BorderStyle` always draws a full box. | ||
| Tables draw as a full grid with an outer box, column separators, and a rule under the header. Blockquotes render a one-column glyph bar on the left rather than a box border. |
There was a problem hiding this comment.
Now that borders can be drawn per-side, I guess that Blockquote rendering could, maybe, be simplified on this, IDK. If this comes along, I would like to check that and maybe do a PR later.
There was a problem hiding this comment.
A separate PR for that works. A left border would replace the height measurement and the column of per-line bar children in renderBlockquote. The catch is that MarkdownTheme.BlockquoteBar is any rune, while a border only covers the four BorderStyle glyphs. So it either becomes a BorderStyle field, which is a theme API change, or the glyph path stays for custom runes.
| ``` | ||
|
|
||
| A caller then writes `@Card("Stats", tui.WithBorder(tui.BorderDouble))`, or for the dialog: | ||
| A caller then writes `@Card("Stats", tui.WithBorder(tui.BorderRounded))`, or for the dialog: |
There was a problem hiding this comment.
IDK why I changed this. Will revert the change in a commit.
| ) | ||
|
|
||
| // Borders represents border style values for the four sides of a box. | ||
| type Borders struct { |
There was a problem hiding this comment.
border changes from being a simple tui.BorderStyle to this, to describe each side of a box individually.
Externally it doesn't changes much, but internally it does a bit.
WithBorder() keeps working but now it resolves to a tui.Borders, to ease things (like class accumulation), border attribute also keeps behaving like before... For the «user», this just increase choice options. In general, I didn't see a perf penalty for this and I think this change was mandatory (to achieve this). Probably it could be even lighter if passed as reference in methods, but all the API seems to prefer to pass almost all data as value instead (in a lot of functions), so I followed what I saw it was common practice.
Borders could have been BorderSides, but I though this was more concise and clear enough. In fact, I have the same named as BorderSides in internal/tailwind/ops.go, just for internal/tailwind/tailwind.go: this is done in a similar way for padding, with PaddingEdges in the same file, to avoid importing there from tui package). I wanted to avoid the Edges nomenclature to avoid confussion: Edges here are used for spacing (are int), while this is used for BorderStyles.
| } | ||
|
|
||
| // BorderTRBL creates border styles following CSS order: Top, Right, Bottom, Left. | ||
| func BorderTRBL(t, r, b, l BorderStyle) Borders { |
There was a problem hiding this comment.
Here (and in a few other functions) I'm following some patterns/name conventions already in place in the project, this being kinda similar to the margin/padding per side feature.
| func renderHR(buf *Buffer, e *Element, textStyle Style) { | ||
| rect := e.ContentRect() | ||
| char := hrCharacter(e.border) | ||
| char := hrCharacter(firstVisibleBorder(e.border)) |
There was a problem hiding this comment.
As now border is made up with per-side styles, I came up with this solution, so it uses the first style border different than none that it encounters.
I can understand why hr built-in element was done this way, but probably its style shouldn't have been coupled to their parent element border style. If fact, if we resort to HTML, most of people would be used to hr to be a single line by default (instead a double, even if it's inside a box delimited by a double border) If this comes along, and if the idea is well received, I would like to write a feature in another moment to allow to choose the style of the hr element, independently from the box/element which contains it. I think it would be a fairly easy (and short) edit.
That way, this could be left as a fallback, but user could choose the desired style.
There was a problem hiding this comment.
The <hr> style already comes from its own border, not its parent's. <hr class="border-double" /> draws ═, and the default with no class is ─. Your element_render_hr_test.go cases set it the same way (WithHR(), WithBorder(BorderDouble)), so there's nothing to decouple.
| const ( | ||
| BorderSingle BorderStyle = iota | ||
| BorderRounded | ||
| BorderNone BorderStyle = iota |
There was a problem hiding this comment.
Added BorderNone for obvious reasons and reorder BorderDouble and BorderRounded, because its ordering was not consistent in some places of the project and that lead me to some issues.
| "text-right": {Ops: []Op{TextAlign{Value: TextRight}}}, | ||
|
|
||
| "border": {Ops: []Op{Border{Style: BorderSingle}}}, | ||
| "border-none": {Ops: []Op{Border{Style: BorderNone}}}, |
|
I think I resolved all the things that @greptile-apps arose (when legit) and reviewed codecov too. I think the rest of @codecov report says is redundant (code is indirectly checked in it's usage in other tests, just like other points that are already untested [directly, but just tested indirectly]). But, if required, I can dig deeper 👍. |
|
Thanks for following up. I agree the remaining Codecov entries are coverage guidance rather than correctness blockers, especially where the behavior is exercised indirectly by higher-level rendering and class-resolution tests. The border-side semantics are intentional: a |
|
Sorry I missed this! Taking a look now |
grindlemire
left a comment
There was a problem hiding this comment.
Thanks for the PR! I reviewed it and here are some thoughts.
I pulled the branch and rendered a few cases, and the single-side ones don't come out the way people will expect. Here's border-b-single and border-l-thick on a 12-wide text element (· is a blank cell):
border-b-single border-l-thick
|··············| |··············|
|·Header·······| |┃quote········|
|··············| |┃·············|
|·──────────···| |··············|
Two things are going on there.
1. Only visible sides should take up space. Right now if any side is set, the element reserves a cell on all four sides, so an underline costs a blank row above and a blank column on each side. The common reasons to reach for a single side (a header underline, a left accent bar, a divider between rows, the blockquote idea you mentioned) all need the other sides to take no space. It's also how CSS behaves, which is what the class names promise. I think the cleanest shape is a single borderInsets() Edges on Element that returns 1 for each visible side, and then the +2 / -2 arithmetic in element_layout.go, element_render.go, input.go and textarea.go goes through it. That also takes care of the ~40 repeated !e.border.All(BorderNone) checks.
2. Corners should continue the line when the neighboring side is off. A corner is blank unless both of its sides are visible, so the bottom line above is two cells short and the left bar skips its top and bottom rows. When only the top or bottom is set the corner should use that side's horizontal character, and when only the left or right is set it should use the vertical one. Once sides that are off take no space (point 1) the bar and underline will line up with the content.
A few smaller things:
- Blank sides paint over the background.
DrawBoxwrites spaces for sides that are off, so withbg-blue border-b-singlethe blue disappears around the other three edges. Skipping those sides instead of drawing spaces fixes it (this is what Greptile's "erases buffer content" comment was pointing at). With point 1 it mostly goes away anyway, but I'd still skip them. - Generated code uses raw numbers now. Every border class, including plain
border-rounded, compiles totui.WithBorderTRBL(3, 3, 3, 3). That only works becauseinternal/tailwind.BorderStyleandtui.BorderStylehappen to number their values the same way, which is easy to break silently. CouldrenderOpandclassOptionemittui.WithBorder(tui.BorderRounded)when all four sides match and named constants otherwise (tui.WithBorderTRBL(tui.BorderNone, tui.BorderNone, tui.BorderSingle, tui.BorderNone))? That keeps the generated output for existing classes the same as today, so the examples don't all churn on the next regenerate. - I'd drop the
bordersattribute on<input>/<textarea>.borders={a, b, c, d}only works because the text gets pasted into a four-argument call.borders={tui.Borders{...}}(what the LSP description suggests) generates code that doesn't compile, and the editor flags even the comma form because the LSP's virtual Go becomes_ = a, b, c, d. Sinceclassalready reaches input and textarea,class="border-b-single"covers this. Addingbordersto the sharedknownAttributesalso means<div borders={...}>passes the analyzer and is silently dropped. - Smaller API surface.
Bordersis comparable, soEqualBorderscan go in favor of==, andBorderTRBLis the same as the struct literal. ChangingElement.Border(), theDrawBox*signatures, and removingBorderStyle.Chars()is fine before 1.0, but please list those in the PR description so they make it into the release notes. - Nit:
parseBorderreturnsborderStyles["none"]on the failure path where0, 0, falseis clearer, and theclass == "border"check is already covered by the regex.
On the Greptile threads, I agree with you on the side-class one (it matches how padding and margin work) and on the title. A title sitting on a blank top edge is a reasonable thing to allow.
|
Thanks for the detailed reply and explanations and for giving me a chance to continue with this, @grindlemire 😊. |
Render border classes through named tui constants instead of raw integers: e.g. `WithBorder(tui.BorderRounded)` when all four sides match and named constants otherwise (`WithBorderTRBL(tui.BorderNone, ...)`).
- Clearer zero-value return for failure matching against regex for uniform border style classes. - Tiny change to cover the `class == "border"` case with the regex. Also added test to check such case.
`Borders` is comparable (has only comparable `BorderStyle`) fields, so the `EqualBorders` helpers adds no value and can be removed and switch all the call sites to the (in)equality operator.
`BorderTRBL` is the same as the struct literal, so remove it for an smaller API surface.
…rder sides Border sides that are set to `BorderNone` no longer take up space in layout calculations. Corners now render correctly when adjacent sides are missing: - When only top or bottom is set, corners use that side's horizontal char - When only left or right is set, corners use that side's vertical char This creates continuous lines instead of broken corners. Changes: - Added `Borders.insets()` to compute `Edges` based on visible sides. - Updated all layout calculations to use insets instead of harcoded values. - Modified `sideChars()` to set corner chars based on visible sides - Updated border drawing to only render visible sides - Changed `DrawBox*` functions to support single-row/column rendering This aligns with typical use cases for single-side borders like header underlines, left accent bars, and dividers between rows, where the other sides should take no space.
…ention Update documentation to clarify: - Borders only take space for the visible sides - `borders` attribute is no longer present - Corners continue the line when the neighboring side is off
- `TestDrawBox_MinimalCompleteRect` → `TestDrawBox_MinimalAllSidesRect` - `TestDrawBox_IncompleteRectsWithSideBorders` → `TestDrawBox_SingleRowAndColumnRects`
|
I think these new commits address all the points. I've updated the PR description above to mention the breaking changes and added a new example screenshot. A few notes:
|
|
Ok taking a look again! |
grindlemire
left a comment
There was a problem hiding this comment.
Here are a few more things I found.
1. border--none panics. borderSidePattern makes the side optional (([trblxy])?), so border--none or border--thick matches with an empty side and m[1][0] indexes an empty string. tui check on
<div class="border--none">x</div>panics in parseBorder (tailwind.go:459). WithClass and SetClass panic the same way when a class string built at runtime contains one of these. Dropping the ? fixes it. Please add a case for it to the tailwind tests.
2. Border classes move to the end of the option list. Parse now folds every border class into the trailing accumulator, so a plain border-rounded is emitted after the other class options instead of where it was written. Running tui generate ./examples/... on this branch reorders WithBorder in 24 generated files. Padding already handles this in the same function: p-2 stays positional unless a per-side class is present. Doing the same for borders keeps the generated output for existing classes unchanged.
| return tui("tui.WithBorder(tui." + [...]string{"BorderSingle", "BorderRounded", "BorderDouble", "BorderThick"}[op.Style] + ")") | ||
| return tui("tui.WithBorder(tui." + op.Style.String() + ")") | ||
| case tailwind.BorderSides: | ||
| return plain(fmt.Sprintf("tui.WithBorderTRBL(%s, %s, %s, %s)", "tui."+op.Top.String(), "tui."+op.Right.String(), "tui."+op.Bottom.String(), "tui."+op.Left.String())) |
There was a problem hiding this comment.
Nit: this should be tui(...) like the Border case above. Both emit tui. identifiers, and needsImport is documented as "" only for options that need none.
There was a problem hiding this comment.
I fixed it. But... it's true that I solved it this way because code I saw in this very file doing absolutely the same:
- Using
plain(...) - Mentioning
tui.Whateverstrings inside.
Are you telling me that these, out of the scope of my PR, cases are wrong too? If not, what's the difference?
There was a problem hiding this comment.
You're right, TextAlign and Scrollable have the same mismatch. It doesn't affect the output, since any file with a component already gets the tui import, so the distinction is only about matching the comment. Your change is fine as is.
…yword test(tailwind): include regression test too.
Also: remove redundant `buf.SetRune`.
|
Thanks! Fixed (I hope) all the points already, @grindlemire 👍. |
|
LGTM! I merged this and will cut a release for it. Thanks! |
|
Thanks to you 😊. |
First of all: sorry 🙇 for making such a big PR. When I started it, I didn't think it would need as much changes. But at the end there were a lot of tests and docs related to this too. To ease the review, I divided the code itself, the tests and the docs in separated commits. I will comment some parts of the code too (here, in GitHub).
Demo (Screenshot)
Description
Support for per-side border styles, so each side of a box can have its own
BorderStyle(or none).New tailwind classes (naming loosely follows Tailwind's individual sides, like the rest of our
gsxclasses):border-{t,r,b,l,x,y}-{none,single,double,rounded,thick}, e.g.border-t-none,border-x-double. Sides:ttop,rright,bbottom,lleft,xleft+right,ytop+bottom.border-none(all sides) — previously mentioned in the codebase but not actually implemented; now it works.<div class="border-thick border-t-none">.New API:
WithBorderTRBL(top, right, bottom, left)option andElement.SetBorderTRBL(...); equivalents for the built-in elements:WithInputBorderTRBLandWithTextAreaBorderTRBL(textarea one is less useful but kept for consistency).Borderstype withTop,Right,Bottom,Leftfields, plus helperstui.BorderAll(style),(Borders).All(s)and(Borders).Chars().lsp/tuigenupdated accordingly: generated code emitstui.WithBorder(...)when all four sides end up equal,tui.WithBorderTRBL(...)only for a mix of styles.Behavior (only reachable through per-side borders; uniform-border behavior is unchanged):
BorderNoneside).none.<hr>uses the first visible border side (CSS order: top, right, bottom, left) as its line style.│/║/┃), not╭/╔/┏. When both neighboring sides are visible but differ in style, the horizontal side decides the corner glyph (bottomthick+ leftsingle→┗, not└). With all four sides sharing one style this matches the previous uniform corners.Breaking changes
The per-side border feature reworks the public border API:
Element.Border()now returnsBorders(wasBorderStyle).DrawBox*signatures changed:DrawBox,DrawBoxGradient,DrawBoxClipped,DrawBoxGradientClipped, andDrawBoxWithTitlenow takeborders Bordersinstead ofborder BorderStyle(usetui.BorderAll(style)for a uniform border).DrawBox*no longer skips rectangles smaller than 2×2; sides render even in one-row/one-column rectangles (only empty rectangles are skipped).But why?
I really like
go-tuiover other more popular alternatives (and because of it I spend the time doing this), but in this specific matter, it lacks what others offer. A TUI is already not as «eye-candy» as a GUI, but having the chance to, at least, choose which borders to show or to mix their styles, has a positive impact. It's not so hard to accomplish and doesn't seem to bring a noticeable perf penalty (probably it would be even less if passingBorderspointers instead of values, but most of the current codebase seems to follow that pattern). I just started writing this the moment I noticed I was forced to choose between everything too boxy or no boxes at all.I know that probably there will be several mistakes or things that can be improved (I'm pretty new to go, still learning), but I hope we can work from here 🤞. I tried my best to have everything into account but there are a lot of things involved here 😅.
What is missing?
Probably also would need to review all the
/examples/and update them/adapt to reflect these changes. If this comes along, I could do that in another PR.