charmbracelet / huh

Build terminal forms and prompts πŸ€·πŸ»β€β™€οΈ
MIT License
3.72k stars 94 forks source link

feat: introduce accessor #263

Closed nervo closed 2 weeks ago

nervo commented 1 month ago

This pr introduce a new (and simple) Accessor interface to enhance the form field values handling in a fully backward compatible way.

This interface is generic and contains only two method Set (for - guess what - setting value) an Get (you got it, for getting value).

The Value method of fields is very limited, and give only one way to expose fields values - via a variable pointer - with no other possibilities. I propose to deprecate it in favor of an Accessor to define well... the field accessor :) I propose a new Accessor method to define well... the field accessor :) Under the hood, Value method still exists but makes usage of an accessor.

Two generics accessors are already available:

// Good ol' fashion
.Value(&foo)
// New shiny one
.Accessor(NewPointerAccessor(&foo))

Custom accessors can now be defined by end users :)

maaslalani commented 1 month ago

Hey I actually like the implementation more here but let's not deprecate Value as that API is much easier to use.

I like how currently the Value method simply is a shorthand for the proposed way of a pointer accessor.

nervo commented 1 month ago

@maaslalani ok, let's undeprecate Value, fine πŸ‘ What about wording ? Do you agree with Accessor, EmbeddedAccessor and PointerAccessor ?

Another point that bugs me is error handling :( In a perfect world, a setter/getter should return errors, but i can't see a way to handle them without breaking the current interfaces...

maaslalani commented 2 weeks ago

@maaslalani ok, let's undeprecate Value, fine πŸ‘ What about wording ? Do you agree with Accessor, EmbeddedAccessor and PointerAccessor ?

Another point that bugs me is error handling :( In a perfect world, a setter/getter should return errors, but i can't see a way to handle them without breaking the current interfaces...

You can have a Validator that wraps an accessor which does the error handling I believe.

maaslalani commented 2 weeks ago

Fantastic work @nervo. Thank you for this!

nervo commented 2 weeks ago

Wow, that was fast ❀️