Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experiment] Separation of update-cycle through components #25

Open
TimLariviere opened this issue Jul 7, 2020 · 10 comments
Open

[Experiment] Separation of update-cycle through components #25

TimLariviere opened this issue Jul 7, 2020 · 10 comments

Comments

@TimLariviere
Copy link
Owner

TimLariviere commented Jul 7, 2020

One big issue with MVU is how it scales. A big application will do a lot of things, which implies a lot of Msg to implement and handle.
One could split up the application into smaller components and compose everyting, but the way MVU works means it's still up to the developer to manually wire all components messages into application messages. This leads to a lot of work.

Inspired by Feliz's UseElmish, I thought Fabulous could achieve the same use case by encapsulating the "runner" (responsible for the update-view loop) inside a ViewElement for making it transparent when declaring a view.

So, leveraging the (potential) new architecture of Fabulous, I wrote a ComponentViewElement that creates a runner for its child, just like Program.run creates a runner for the application.
This way, the component is isolated and has its own init/update/view & msgs that don't trigger a refresh of the parent.

It does support two-way communication with its parent.
A parent can pass down a state to the component (if the parent is updated, then the new state is pushed to the component) through the withState extension method.
A component can push an update to its parent through the withExternalMessages extension method.

Implementation:
https://github.com/TimLariviere/Fabulous/blob/play/Fabulous.XamarinForms/Fabulous.XamarinForms/Component.fs

This then allows to write independent components (can be pages, groups of controls, or even a single control).

module AboutCard =
type Model = { State: int; Text: string }
type Msg =
| StateChanged of int
| Toggle
type ExternalMsg =
| TextChanged of string
type CmdMsg = Nothing
let mapCmdMsg cmdMsg =
match cmdMsg with
| Nothing -> Cmd.none
let init() =
{ State = 0; Text = "Hello World!" }, [], []
let update msg model =
match msg with
| StateChanged state ->
{ model with State = state }, [], []
| Toggle ->
let newModel = { model with Text = model.Text + " It worked!" }
newModel, [], [ TextChanged newModel.Text ]
let view model =
StackLayout([
Button("Toggle", Toggle)
Label(sprintf "State is %i" model.State)
Label(model.Text)
])
let program = Program.forComponentWithCmdMsg init update view mapCmdMsg
let asComponent<'msg>(state, onExternalMsg: ExternalMsg -> 'msg) =
ComponentView(program)
//.withState(StateChanged, state)
.withExternalMessages(onExternalMsg)

You can write init/update/view functions with their own Model and Msg.
They are linked together into a program.
Then, a helper function will create a ComponentView taking the program definition.

The parent view can mix usual controls with components.

Label(sprintf "Step size: %d" model.Step)
.automationId("StepSizeLabel")
.alignment(horizontal = LayoutOptions.Center)
Button("Reset", Reset)
.isEnabled(model <> initModel())
.alignment(horizontal = LayoutOptions.Center)
AboutCard.asComponent(model.Count, CardChanged)

If a parent wants to listen to the component's external messages, it can simply add a new entry to its Msg union.

type Msg =
| Increment
| Decrement
| Reset
| SetStep of int
| TimerToggled of bool
| TimedTick
| CloseApp
| CardChanged of AboutCard.ExternalMsg

If a component wants to listen to the state its parent is giving it, it can also add a new entry to its Msg union.

type Msg =
| StateChanged of int
| Toggle

Note: I got a working sample of it. Though the implementation is awful and most likely not working in every cases.
I just wanted to prove that it was possible to achieve such behavior in a way that is idiomatic to Fabulous.
Put another way: Works on my machine™

@TimLariviere
Copy link
Owner Author

@vshapenko This might interest you.
If you could give me a feedback on it and let me know if it would support your use cases.

@vshapenko
Copy link

At first look, looks very promising. As external message i usually use navigation message in my project. Looks worth to try.

@vshapenko
Copy link

Do i understand correctly that such code lets us make independent mvu cycle for any chosen view element? @TimLariviere

@TimLariviere
Copy link
Owner Author

TimLariviere commented Jul 7, 2020

Yes, I've generalized the Program functions to accept any kind of view element (Application, ContentPage, Button, etc.).
And since ComponentView only takes a program definition, it works with anything.
So you can create components with their independent mvu cycle for any view element.

@AngelMunoz
Copy link

AngelMunoz commented Aug 5, 2020

I like this experiment, FuncUI does something like this as well, provides a Component host as well as the Window host, I like the addition here of an external message (which is missing in FuncUI I think) I believe this could open a (perhaps small) window to let some users author component libraries entirely in F#

@JordanMarr
Copy link

I like this experiment, FuncUI does something like this as well, provides a Component host as well as the Window host, I like the addition here of an external message (which is missing in FuncUI I think) I believe this could open a (perhaps small) window to let some users author component libraries entirely in F#

Are there any samples showing the FuncUI Component host vs Window host?

@AngelMunoz
Copy link

AngelMunoz commented Aug 8, 2020

@JordanMarr
they are included in the dotnet templates the quickstart one I think has the most complete out of the box example here are some links to the code

HostControl

HostWindow

ViewBuilder.create

Basically the HostWindow is a simple class that inherits from Avalonia's Window and ensures to call the proper functions to integrate the window into the Elmish loop the same goes for HostControl but that one inherits from ContentControl instead source

@JordanMarr
Copy link

Thanks! Trying it out now. That is definitely the idea I had in mind.

@Dolfik1
Copy link

Dolfik1 commented Jan 2, 2021

I looked at the examples above and I have a couple of comments.

  1. In your example you have statically created AboutCard component. But what if we want to use a component inside a list? I think that components should be contextually independent. It would be cool if we can use same component inside a list, collection or another component. If I understand correctly we can't do that at this moment without storing program somewhere in parent's model.

  2. Also based on your example it looks like we can't pass message directly to parent. This can cause unnecessary redraw loops. For example: we want to notify parent if component's text field is changed/button is pressed, but we do not need to change component's model. At the moment, I have two solutions to the problem: 1. Use function ('msg -> 'externalMsg option) to extract external message from component's message; 2. Do not call view if component's model is not changed by reference.

I also recommend to take a look at MVI architecture. It is very similar to MVU architecture and also have components.

Anyway, it looks very promising. Thank you for your work! I think with components architecture we won't need FSharp.Data.Adaptive anymore. Ofcourse data adaptive is very useful in many cases but in case of Fabulous, a lot of boilerplate code is required.

@TimLariviere
Copy link
Owner Author

TimLariviere commented Jan 8, 2021

@Dolfik1

In your example you have statically created AboutCard component. But what if we want to use a component inside a list?

The AboutCard I created returns a ComponentViewModel which is a specific implementation of the current ViewElement.
So it will be exactly like any control today. It's only a definition. If Fabulous wants to load that component, it will call the Create method which will create a new program along a new control.
The program itself is not stored in the ComponentViewElement, instead it's stored in an attached property on the Xamarin.Forms control instance. So it will be kept alive while the control is displayed.
All subsequent AboutCard.asComponent will declare a new state, which Fabulous will use while retrieving the existing program's from the attached property of the reused control. Then it will call the Update method which will send the new state to the program.

So nothing prevents to use components in list like this:

View.ListView([
    for item in model.Items ->
        AboutCard.asComponent(item, ItemDeleted)
])

Also based on your example it looks like we can't pass message directly to parent.

In my example, I do have support for passing message to parent through the external msg pattern.

let asComponent<'msg>(state, onExternalMsg: ExternalMsg -> 'msg) =
ComponentView(program)
//.withState(StateChanged, state)
.withExternalMessages(onExternalMsg)

Here AboutCard.asComponent(model.Count, CardChanged) indicates that the component might send a CardChanged message to the parent.

In this instance, when the user clicks the button inside the component, the component will receive a Toggle message which will force it to send a ExternalMsg.TextChanged in return.
That TextChanged will be received by the parent, wrapped inside Parent.Msg.CardChanged of AboutCard.ExternalMsg.

let update msg model =
match msg with
| StateChanged state ->
{ model with State = state }, [], []
| Toggle ->
let newModel = { model with Text = model.Text + " It worked!" }
newModel, [], [ TextChanged newModel.Text ]

The other way is also supported (see the commented line from the 1st example). A parent can pass a state to the component.

I also recommend to take a look at MVI architecture. It is very similar to MVU architecture and also have components.

Thanks for the link! I'm taking a look at it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants