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

Support for EnvironmentContext inside Components #51

Merged
merged 7 commits into from
Dec 12, 2023
Merged

Conversation

TimLariviere
Copy link
Member

@TimLariviere TimLariviere commented Nov 26, 2023

type Container =
    { ServiceA: IServiceA
      ServiceB: IServiceB }

let ContainerKey = EnvironmentKey.Create<Container>("Container")

let grandChild() =
    Component() {
        // Retrieve the environment value for the key
        let! container = Environment.Get(ContainerKey)

        Button("Click me", fun () -> container.ServiceA.DoSomething())
    }

let child() =
    Component() {
        // Note here that the environment context can skip over several layers of component
        VStack() {
            grandChild()
        }
    }

let parent (container: Container) =
    Component() {
         // Define the environment value
         do! Environment.Set(ContainerKey, container)

         child()
    }

It is also possible to add more environment values down the hierarchy (only accessible to descendants) and override environment values down the hierarchy as well (still only for current level and descendants).

let EnvKey1 = EnvironmentKey.Create<int>("EnvKey1")
let EnvKey2 = EnvironmentKey.Create<int>("EnvKey2")

let grandChild() =
    Component() {
        let! envValue1 = Environment.Get(EnvKey1) // Will be 20
        let! envValue2 = Environment.Get(EnvKey2) // Will be 40

        (...)
    }

let child() =
    Component() {
        let! envValue1 = Environment.Get(EnvKey1) // Will be 10
        do! Environment.Set(EnvKey1, 20)
        do! Environment.Set(EnvKey2, 40)

        VStack() {
            grandChild()
        }
    }

let parent (container: Container) =
    Component() {
         // Define the environment value
         do! Environment.Set(EnvKey1, 10)

         child()
    }

@TimLariviere
Copy link
Member Author

@edgarfgp I couldn't do something like SwiftUI with the .environment(key, value) modifier because Fabulous doesn't allow for repeated modifiers (only the last one will be kept), and modifiers are evaluated only after the children have been evaluated, so the environment declarations would come too late anyway 😅

@TimLariviere TimLariviere merged commit 148d2d7 into main Dec 12, 2023
1 check failed
@TimLariviere TimLariviere deleted the environment branch December 12, 2023 14:25
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

Successfully merging this pull request may close these issues.

1 participant