Skip to content

feat: render element expressions with @expr - #156

Merged
grindlemire merged 13 commits into
mainfrom
feat/element-expressions
Sep 16, 2026
Merged

grindlemire merged 13 commits into
mainfrom
feat/element-expressions

Conversation

@grindlemire

@grindlemire grindlemire commented Sep 15, 2026 •

Copy link
Copy Markdown
Owner

Using an indexed field as a child, like {c.content[c.active]}, compiled to a text option. The generator has no type information, so it treated the expression as a string and go build failed on the generated code.

@expr now renders any Go expression whose value is an element or component, the same way templ does. The lexer accepts [...] after the dotted name in @ expressions, so @c.content[c.active] and @c.m["key"] both parse. To make a plain element usable there, Element.Render(buf, width, height) is renamed RenderTo, and a new Element.Render(app) returns the element itself so *tui.Element satisfies tui.Component. An element passed straight to SetRootComponent or Mount now starts its watchers once instead of twice. Components held in a slice or map field and rendered through an index, a map key, or a for loop over the field now get BindApp and UnbindApp forwarded, the same as a field used as @c.field. When a cached component receives new props, the previous values of those fields are unbound first, so a component dropped from the collection stops receiving events.

templ (c *component) Render() {
    <div>@c.content[c.active]</div>
}

Out of scope: element literals inside Go slice literals, and the per-file := binding scope bug tracked in #155.

Fixes #154
Fixes #157
Fixes #159

Rename Element.Render(buf, width, height) to RenderTo and add
Render(app) *Element, which returns the element itself. A prebuilt
element can now be used wherever a Component is accepted.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
The lexer now consumes balanced [...] segments after the dotted name
in an @ expression, so @c.content[c.active], @c.items[i].view and
@c.m["key"] lex as a single TokenAtExpr. String and rune literals
inside brackets are skipped when balancing. Any bracketed form is an
expression, never a call, so @widgets[0] is TokenAtExpr too.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
Pins that @c.content[c.active] parses as a ComponentExpr as a child,
inside for/if, and as a := binding; that the generator emits
c.content[c.active].Render(app); that the formatter leaves it
unchanged; and that function templs still reject it. Indexed
expressions are no longer tracked as bindable struct fields.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
Adds an examples/13-testing fixture that renders @p.content[p.active],
a loop of @el and @p.footer, with a buffer-render test, plus a
cmd/tui/testdata golden case. Documents element expressions in the
gsx syntax reference, components guide, llm.md, element reference
(RenderTo and Render(app)), and CLAUDE.md.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.01493% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.49%. Comparing base (2393426) to head (8a0dc4c).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/tuigen/generator_component.go 95.50% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #156      +/-   ##
==========================================
+ Coverage   84.35%   84.49%   +0.14%     
==========================================
  Files         166      169       +3     
  Lines       21150    21535     +385     
==========================================
+ Hits        17841    18197     +356     
- Misses       2638     2669      +31     
+ Partials      671      669       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; the previously reported lifecycle gaps are fixed and no actionable new regressions were identified.

Summary

This PR adds GSX @expr support for indexed element and component expressions and completes their lifecycle integration.

  • Extends lexing and generation for indexed, keyed, and loop-variable component expressions.
  • Makes Element implement Component while moving buffer drawing to RenderTo.
  • Forwards app binding and unbinding through rendered slice and map fields.
  • Unbinds replaced component-expression props before cached instances receive new values.
  • Prevents element watchers from starting twice when an element is used directly as a component.
  • Updates generated fixtures, examples, tests, and public documentation.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A["GSX @expr"] --> B["Lexer parses indexed expression"]
    B --> C["Generator emits expr.Render(app)"]
    C --> D["Element child tree"]
    E["Cached component update"] --> F["Unbind old @expr props"]
    F --> G["Copy fresh props"]
    G --> H["Bind new @expr props"]
    H --> C
    D --> I["Element.RenderTo(buffer, width, height)"]
Loading

Reviews (3) · Last reviewed commit: "docs: state the rebind contract for @exp..."

Comment thread internal/tuigen/generator_component.go Resolved
Comment thread internal/tuigen/lexer_utils.go Resolved
Comment thread element_render.go Resolved
An Element passed straight to SetRootComponent or Mount is reached by both
the element tree walk and the component walk, so its watchers were started
twice. Skip *Element in collectComponentWatchers; the tree walk owns them.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
…utput

Replace the generated-output test for indexed @expr with a direct table
test of trackComponentExprField. The `[` guard in trackComponentExprField
only keeps index tails out of componentExprFields; generated
BindApp/UnbindApp output was already unaffected because the list is
intersected with struct field names. Commit 5f04312 described this as a
behavior change; it is not.

An unterminated string literal inside an @expr index now stops at the end
of the line instead of swallowing the following lines into the error.

Also restrict the `@badge` doc note to struct components and point the
Element.Render reference at the element-expressions anchor.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
Struct fields rendered as @c.items[i], @c.m["k"], or through a for loop
over the field (for _, it := range c.items { @it }) are now tracked as
indexed component fields. When the field is declared with a literal []T
or map[K]V type, the generated bindAppFields and unbindAppFields range
over it and assert each value against tui.AppBinder / tui.AppUnbinder,
so components held in a slice or map get bound without hand-written
BindApp code. Named collection types, arrays, and pointers to slices are
left alone.

Regenerates the example and testdata fixtures, extends the panes example
with a []tui.Component field and a forwarding test, and documents the
behavior in the gsx syntax reference and components guide.

Closes #157

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
…ld tests

The two generated helper doc comments (bindAppFields and unbindAppFields)
return to their pre-d929759 wording and the fixtures were regenerated, so
only elementexpr_gsx.go and panes_gsx.go still differ from 6e88798.

The two trackComponentExprField tables are merged into
TestGenerator_TrackComponentExprField. The "unterminated index" row is the
one that pins the "[" guard now that indexed tails are consumed by
indexedFieldName first.

The gsx-syntax reference now says "a single index" since @t.grid[i][j] is
not forwarded.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
…ate loop stack

Generated output is unchanged; the hand-rolled bracket scanner, isIdentifier, skipStringLiteral, and loopIndexStack are removed.

trackComponentExprField now uses strings.CutPrefix, token.IsIdentifier, and parser.ParseExpr to recognize ident[...] tails, and pushLoopIndex derives synthetic index names from loopVarStack depth. The watcher collector handles *Element as a switch case instead of an early return, and the Element.Render and indexedComponentFields doc comments are shortened.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
Every removed case names a surviving test or golden covering the same shape; no input form loses coverage.

The parser index walk is covered by the lexer and formatter cases; the lexer keeps the whitespace-stop row; the generator bind test keeps the named-collection row and asserts only the loop header; the indexed function-templ rejection moves into TestAnalyzer_ComponentExprRequiresReceiver; the formatter golden folds the binding form into one case. The panes example drops the redundant items loop, and the docs describe @expr binding without restating the generator rules.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
@grindlemire

Copy link
Copy Markdown
Owner Author

@greptileai please review again

Comment thread internal/tuigen/generator_component.go Resolved
The generated updatePropsFields now unbinds the current values of prop
fields rendered through @expr (plain and ranged slice/map) before copying
the fresh ones, so a component dropped by a prop swap releases its Events
listeners instead of firing until the host is evicted. A prop swap counts
as an unmount for the replaced value; instances shared across renders
pay a resubscribe on each cached render. Rolls #159 into #156.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
The AppUnbinder docs now state that a prop swap on a cached host unbinds and rebinds surviving @expr instances, so a hand-written UnbindApp must only release what BindApp reacquires; the generator test rename and the updatePropsFields comment trim ride along.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
@grindlemire

Copy link
Copy Markdown
Owner Author

@greptileai please review again

The gsx syntax guide now has an Element Expressions subsection linking to the
components guide and the reference, and the VS Code README construct table
lists the @expr form.

Claude-Session: https://claude.ai/code/session_011xMYx7mkByXxvFdJvxzhxX
@grindlemire
grindlemire merged commit 64e001a into main Sep 16, 2026
9 checks passed
@grindlemire
grindlemire deleted the feat/element-expressions branch September 16, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant