Skip to content

Move UI Logic to a Builder #4

@andreamancuso

Description

@andreamancuso

Something like

public override IRenderable Render() =>
    UI.Build()
      .Button("Add todo", AppStateManager.OnClick, ButtonStyle)
      .ForEach(props.Value?.TodoItems ?? new(), todo => 
          UI.Text($"{todo.Text} ({(todo.Done ? "done" : "to do")}).", TextStyle))
      .Render();

Where UI is a helper with extension methods:

public static class UI
{
    public static UIBuilder Build() => new UIBuilder();

    public static UIBuilder ForEach<T>(this UIBuilder builder, IEnumerable<T> items, Func<T, IRenderable> render) 
        => builder.Add(items.Select(render));

    public static UIBuilder Button(this UIBuilder builder, string text, Action onClick, WidgetStyle style)
        => builder.Add(WidgetNodeFactory.Button(text, onClick, style));

    public static UIBuilder Text(this UIBuilder builder, string text, WidgetStyle style)
        => builder.Add(WidgetNodeFactory.UnformattedText(text, style));
}

public class UIBuilder
{
    private readonly List<IRenderable> _elements = new();

    public UIBuilder Add(IRenderable element)
    {
        _elements.Add(element);
        return this;
    }

    public UIBuilder Add(IEnumerable<IRenderable> elements)
    {
        _elements.AddRange(elements);
        return this;
    }

    public IRenderable Render() => WidgetNodeFactory.Node(_elements);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions