Angular vs Effect UI

Angular and Effect UI side by side: the same components written in both frameworks, from reactivity and templating to lifecycle, composition and forms.

Reactivity

Declare state

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-name",
  template: `<h1>Hello {{ name }}</h1>`,
})
export class NameComponent {
  name = "John";
}

@NgModule({
  declarations: [NameComponent],
  exports: [NameComponent],
})
export class NameModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"

export const Name = Html.component({
  name: "Name",
  model: Schema.Struct({ name: Schema.String }),
  message: Schema.Never
}).make({
  init: () => ({ name: "John" }),
  update: ($) => $.model,
  view: (h, model) => h.h1(`Hello ${model.name}`)
})

Update state

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-name",
  template: `<h1>Hello {{ name }}</h1>`,
})
export class NameComponent {
  name = "John";

  constructor() {
    this.name = "Jane";
  }
}

@NgModule({
  declarations: [NameComponent],
  exports: [NameComponent],
})
export class NameModule {}

logo of Effect UI Effect UI

import { Command, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Effect, Schema } from "effect"

const NameMessage = UiSchema.TaggedEnum({
  CompletedRename: { name: Schema.String }
})

const Rename = Command.make(
  "Rename",
  { args: {} },
  () => Effect.succeed(NameMessage.CompletedRename({ name: "Jane" }))
)

export const Name = Html.component({
  name: "Name",
  model: Schema.Struct({ name: Schema.String }),
  message: NameMessage
}).make({
  init: ($) => $.set({ name: "John" }).run(Rename.make({})),
  update: {
    CompletedRename: ($, { name }) => $.evolve({ name })
  },
  view: (h, model) => h.h1(`Hello ${model.name}`)
})

Computed state

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-doublecount",
  template: `<div>{{ doubleCount }}</div>`,
})
export class DoublecountComponent {
  count = 10;

  get doubleCount() {
    return this.count * 2;
  }
}

@NgModule({
  declarations: [DoublecountComponent],
  exports: [DoublecountComponent],
})
export class DoublecountModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"

export const DoubleCount = Html.component({
  name: "DoubleCount",
  model: Schema.Struct({ count: Schema.Number }),
  message: Schema.Never
}).make({
  init: () => ({ count: 10 }),
  update: ($) => $.model,
  view: (h, model) => {
    const doubleCount = model.count * 2
    return h.div(String(doubleCount))
  }
})

Templating

Minimal template

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-helloworld",
  template: `<h1>Hello world</h1>`,
})
export class HelloworldComponent {}

@NgModule({
  declarations: [HelloworldComponent],
  exports: [HelloworldComponent],
})
export class HelloworldModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"

export const HelloWorld = Html.component({
  name: "HelloWorld",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) => h.h1("Hello world")
})

Styling

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-cssstyle",
  template: `
    <h1 class="title">I am red</h1>
    <button style="font-size: 10rem">I am a button</button>
  `,
  styles: [
    `
      .title {
        color: red;
      }
    `,
  ],
})
export class CssStyleComponent {}

@NgModule({
  declarations: [CssStyleComponent],
  exports: [CssStyleComponent],
})
export class CssStyleModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import "./style.css"

export const CssStyle = Html.component({
  name: "CssStyle",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    h.div(
      h.h1.class("title").children("I am red"),
      h.button.style({ fontSize: "10rem" }).children("I am a button")
    )
})

Loop

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

@Component({
  selector: "app-colors",
  template: `
    <ul>
      <li *ngFor="let color of colors">{{ color }}</li>
    </ul>
  `,
})
export class ColorsComponent {
  colors = ["red", "green", "blue"];
}

@NgModule({
  declarations: [ColorsComponent],
  imports: [CommonModule],
  exports: [ColorsComponent],
})
export class ColorsModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const colors = ["red", "green", "blue"]

export const Colors = Html.component({
  name: "Colors",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    h.ul(colors.map((color) => h.li.key(color).children(color)))
})

Event click

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-counter",
  template: `
    <p>Counter: {{ count }}</p>
    <button (click)="incrementCount()">+1</button>
  `,
})
export class CounterComponent {
  count = 0;

  incrementCount() {
    this.count++;
  }
}

@NgModule({
  declarations: [CounterComponent],
  exports: [CounterComponent],
})
export class CounterModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const CounterMessage = UiSchema.TaggedEnum({
  ClickedIncrement: {}
})

export const Counter = Html.component({
  name: "Counter",
  model: Schema.Struct({ count: Schema.Number }),
  message: CounterMessage
}).make({
  init: () => ({ count: 0 }),
  update: {
    ClickedIncrement: ($) => $.evolve({ count: (count) => count + 1 })
  },
  view: (h, model) =>
    h.div(
      h.p(`Counter: ${model.count}`),
      h.button.on("click", CounterMessage.ClickedIncrement()).children("+1")
    )
})

Dom ref

logo of Angular Angular

import {
  Component,
  ViewChild,
  ElementRef,
  OnInit,
  NgModule,
} from "@angular/core";

@Component({
  selector: "app-inputfocused",
  template: `<input type="text" #inputRef />`,
})
export class InputfocusedComponent implements OnInit {
  @ViewChild("inputRef", { static: true })
  inputRef!: ElementRef<HTMLInputElement>;

  ngOnInit() {
    this.inputRef.nativeElement.focus();
  }
}

@NgModule({
  declarations: [InputfocusedComponent],
  exports: [InputfocusedComponent],
})
export class InputfocusedModule {}

logo of Effect UI Effect UI

import { Component } from "@effect/ui"
import { Html, HtmlCommand } from "@effect/ui/html"
import { Schema } from "effect"

const InputElement = Html.ref("InputElement", "input")

export const InputFocused = Html.component({
  name: "InputFocused",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: ($) =>
    $.set(null).run(HtmlCommand.focus(InputElement, () => Component.noop)),
  update: ($) => $.model,
  view: (h) => h.input.ref(InputElement).attr("type", "text")
})

Conditional

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

const TRAFFIC_LIGHTS = ["red", "orange", "green"];

@Component({
  selector: "app-trafficlight",
  template: `
    <button (click)="nextLight()">Next light</button>
    <p>Light is: {{ light }}</p>
    <p>
      You must
      <ng-container [ngSwitch]="light">
        <span *ngSwitchCase="'red'">STOP</span>
        <span *ngSwitchCase="'orange'">SLOW DOWN</span>
        <span *ngSwitchCase="'green'">GO</span>
      </ng-container>
    </p>
  `,
})
export class TrafficlightComponent {
  lightIndex = 0;

  get light() {
    return TRAFFIC_LIGHTS[this.lightIndex];
  }

  nextLight() {
    this.lightIndex = (this.lightIndex + 1) % TRAFFIC_LIGHTS.length;
  }
}

@NgModule({
  declarations: [TrafficlightComponent],
  imports: [CommonModule],
  exports: [TrafficlightComponent],
})
export class TrafficlightModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const TRAFFIC_LIGHTS = ["red", "orange", "green"] as const

const TrafficLightMessage = UiSchema.TaggedEnum({
  ClickedNextLight: {}
})

export const TrafficLight = Html.component({
  name: "TrafficLight",
  model: Schema.Struct({ lightIndex: Schema.Number }),
  message: TrafficLightMessage
}).make({
  init: () => ({ lightIndex: 0 }),
  update: {
    ClickedNextLight: ($) =>
      $.evolve({
        lightIndex: (index) => (index + 1) % TRAFFIC_LIGHTS.length
      })
  },
  view: (h, model) => {
    const light = TRAFFIC_LIGHTS[model.lightIndex]
    return h.div(
      h.button.on("click", TrafficLightMessage.ClickedNextLight())
        .children("Next light"),
      h.p(`Light is: ${light}`),
      h.p(
        "You must ",
        light === "red" && h.span("STOP"),
        light === "orange" && h.span("SLOW DOWN"),
        light === "green" && h.span("GO")
      )
    )
  }
})

Lifecycle

On mount

logo of Angular Angular

import { Component, NgModule, OnInit } from "@angular/core";

@Component({
  selector: "app-pagetitle",
  template: `<p>Page title: {{ pageTitle }}</p>`,
})
export class PagetitleComponent implements OnInit {
  pageTitle = "";

  ngOnInit() {
    this.pageTitle = document.title;
  }
}

@NgModule({
  declarations: [PagetitleComponent],
  exports: [PagetitleComponent],
})
export class PagetitleModule {}

logo of Effect UI Effect UI

import { Command, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Effect, Schema } from "effect"

const PageTitleMessage = UiSchema.TaggedEnum({
  CompletedReadTitle: { title: Schema.String }
})

const ReadTitle = Command.make(
  "ReadTitle",
  { args: {} },
  () =>
    Effect.sync(() =>
      PageTitleMessage.CompletedReadTitle({ title: document.title })
    )
)

export const PageTitle = Html.component({
  name: "PageTitle",
  model: Schema.Struct({ pageTitle: Schema.String }),
  message: PageTitleMessage
}).make({
  init: ($) => $.set({ pageTitle: "" }).run(ReadTitle.make({})),
  update: {
    CompletedReadTitle: ($, { title }) => $.evolve({ pageTitle: title })
  },
  view: (h, model) => h.p(`Page title: ${model.pageTitle}`)
})

On unmount

logo of Angular Angular

import { Component, NgModule, OnDestroy } from "@angular/core";

@Component({
  selector: "app-time",
  template: `<p>Current time: {{ time }}</p>`,
})
export class TimeComponent implements OnDestroy {
  time = new Date().toLocaleTimeString();

  timer = setInterval(() => {
    this.time = new Date().toLocaleTimeString();
  }, 1000);

  ngOnDestroy() {
    clearInterval(this.timer);
  }
}

@NgModule({
  declarations: [TimeComponent],
  exports: [TimeComponent],
})
export class TimeModule {}

logo of Effect UI Effect UI

import { Subscription, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Duration, Schema, Stream } from "effect"

const TimeMessage = UiSchema.TaggedEnum({
  Ticked: { time: Schema.String }
})

const now = () => new Date().toLocaleTimeString()

export const Time = Html.component({
  name: "Time",
  model: Schema.Struct({ time: Schema.String }),
  message: TimeMessage
}).make({
  init: () => ({ time: now() }),
  update: {
    Ticked: ($, { time }) => $.evolve({ time })
  },
  subscriptions: () => [
    Subscription.make(
      "clock",
      Stream.tick(Duration.seconds(1)).pipe(
        Stream.map(() => TimeMessage.Ticked({ time: now() }))
      )
    )
  ],
  view: (h, model) => h.p(`Current time: ${model.time}`)
})

Component composition

Props

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { UserprofileModule } from "./userprofile.component";

@Component({
  selector: "app-root",
  template: `
    <app-userprofile
      name="John"
      [age]="20"
      [favouriteColors]="['green', 'blue', 'red']"
      [isAvailable]="true"
    >
    </app-userprofile>
  `,
})
export class AppComponent {}

@NgModule({
  declarations: [AppComponent],
  imports: [UserprofileModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { UserProfile } from "./UserProfile.ts"

export const App = Html.component({
  name: "App",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    UserProfile(h, {
      props: {
        name: "John",
        age: 20,
        favouriteColors: ["green", "blue", "red"],
        isAvailable: true
      }
    })
})

Emit to parent

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { AnswerButtonModule } from "./answer-button.component";

@Component({
  selector: "app-root",
  template: `
    <p>Are you happy?</p>

    <app-answer-button (yes)="onAnswerYes()" (no)="onAnswerNo()">
    </app-answer-button>

    <p style="font-size: 50px">{{ isHappy ? "😀" : "😥" }}</p>
  `,
})
export class AppComponent {
  isHappy = true;

  onAnswerYes() {
    this.isHappy = true;
  }

  onAnswerNo() {
    this.isHappy = false;
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [AnswerButtonModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { AnswerButton } from "./AnswerButton.ts"

const AppMessage = UiSchema.TaggedEnum({
  AnsweredYesAnswerButton: {},
  AnsweredNoAnswerButton: {}
})

export const App = Html.component({
  name: "App",
  model: Schema.Struct({ isHappy: Schema.Boolean }),
  message: AppMessage
}).make({
  init: () => ({ isHappy: true }),
  update: {
    AnsweredYesAnswerButton: ($) => $.evolve({ isHappy: true }),
    AnsweredNoAnswerButton: ($) => $.evolve({ isHappy: false })
  },
  view: (h, model) =>
    h.div(
      h.p("Are you happy?"),
      AnswerButton(h, {
        onEmit: {
          AnsweredYes: () => AppMessage.AnsweredYesAnswerButton(),
          AnsweredNo: () => AppMessage.AnsweredNoAnswerButton()
        }
      }),
      h.p.style({ fontSize: "50px" }).children(model.isHappy ? "😀" : "😥")
    )
})

Slot

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { FunnyButtonModule } from "./funny-button.component";

@Component({
  selector: "app-root",
  template: `<app-funny-button>Click me!</app-funny-button>`,
})
export class AppComponent {}

@NgModule({
  declarations: [AppComponent],
  imports: [FunnyButtonModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { FunnyButton } from "./FunnyButton.ts"

export const App = Html.component({
  name: "App",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) => FunnyButton(h, { slots: { children: "Click me!" } })
})

Slot fallback

logo of Angular Angular

import { Component, NgModule } from "@angular/core";

@Component({
  selector: "app-root",
  template: `
    <app-funny-button></app-funny-button>

    <app-funny-button>
      <ng-template #content>I got content!</ng-template>
    </app-funny-button>
  `,
})
export class AppComponent {}

@NgModule({
  declarations: [AppComponent],
  imports: [FunnyButtonModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

logo of Effect UI Effect UI

import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { FunnyButton } from "./FunnyButton.ts"

export const App = Html.component({
  name: "App",
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    h.div(
      FunnyButton(h),
      FunnyButton(h, { children: ["I got content!"] })
    )
})

Context

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { UserService } from "./user.service";
import { UserProfileModule } from "./user-profile.component";

@Component({
  providers: [UserService],
  selector: "app-root",
  template: `
    <h1>Welcome back, {{ userService.user.username }}</h1>
    <app-user-profile />
  `,
})
export class AppComponent {
  constructor(public userService: UserService) {}
}

@NgModule({
  declarations: [AppComponent],
  imports: [UserProfileModule],
  bootstrap: [AppComponent],
})
export class AppModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { UserProfile } from "./UserProfile.ts"
import { User, UserProvider } from "./UserProvider.ts"

const AppMessage = UiSchema.TaggedEnum({
  RequestedUsernameUserProvider: { username: Schema.String }
})

export const App = Html.component({
  name: "App",
  model: Schema.Struct({ user: User }),
  message: AppMessage
}).make({
  init: () => ({
    user: { id: 1, username: "unicorn42", email: "unicorn42@example.com" }
  }),
  update: {
    RequestedUsernameUserProvider: ($, { username }) =>
      $.evolve({ user: (user) => ({ ...user, username }) })
  },
  view: (h, model) =>
    h.div(
      h.h1(`Welcome back, ${model.user.username}`),
      UserProvider(h, {
        props: { user: model.user },
        onEmit: {
          RequestedUsername: ({ username }) =>
            AppMessage.RequestedUsernameUserProvider({ username })
        },
        view: () => UserProfile(h, {})
      })
    )
})

Form input

Input text

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

@Component({
  selector: "app-input-hello",
  template: `
    <p>{{ text }}</p>
    <input [(ngModel)]="text" />
  `,
})
export class InputHelloComponent {
  text = "";
}

@NgModule({
  declarations: [InputHelloComponent],
  imports: [FormsModule],
  exports: [InputHelloComponent],
})
export class InputHelloModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const InputHelloMessage = UiSchema.TaggedEnum({
  UpdatedText: { text: Schema.String }
})

export const InputHello = Html.component({
  name: "InputHello",
  model: Schema.Struct({ text: Schema.String }),
  message: InputHelloMessage
}).make({
  init: () => ({ text: "Hello World" }),
  update: {
    UpdatedText: ($, { text }) => $.evolve({ text })
  },
  view: (h, model) =>
    h.div(
      h.p(model.text),
      h.input
        .value(model.text)
        .on("input", ({ value }) => InputHelloMessage.UpdatedText({ text: value }))
    )
})

Checkbox

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

@Component({
  selector: "app-is-available",
  template: `
    <input id="is-available" type="checkbox" [(ngModel)]="isAvailable" />
    <label for="is-available">Is available</label>
  `,
})
export class IsAvailableComponent {
  isAvailable = false;
}

@NgModule({
  declarations: [IsAvailableComponent],
  imports: [FormsModule],
  exports: [IsAvailableComponent],
})
export class IsAvailableModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const IsAvailableMessage = UiSchema.TaggedEnum({
  ToggledIsAvailable: { checked: Schema.Boolean }
})

export const IsAvailable = Html.component({
  name: "IsAvailable",
  model: Schema.Struct({ isAvailable: Schema.Boolean }),
  message: IsAvailableMessage
}).make({
  init: () => ({ isAvailable: false }),
  update: {
    ToggledIsAvailable: ($, { checked }) => $.evolve({ isAvailable: checked })
  },
  view: (h, model) =>
    h.div(
      h.input
        .id("is-available")
        .attr("type", "checkbox")
        .checked(model.isAvailable)
        .on("change", ({ checked }) =>
          IsAvailableMessage.ToggledIsAvailable({ checked })
        ),
      h.label.attr("for", "is-available").children("Is available")
    )
})

Radio

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

@Component({
  selector: "app-pick-pill",
  template: `
    <div>Picked: {{ picked }}</div>

    <input id="blue-pill" type="radio" value="blue" [(ngModel)]="picked" />
    <label for="blue-pill">Blue pill</label>

    <input id="red-pill" type="radio" value="red" [(ngModel)]="picked" />
    <label for="red-pill">Red pill</label>
  `,
})
export class PickPillComponent {
  picked = "red";
}

@NgModule({
  declarations: [PickPillComponent],
  imports: [FormsModule],
  exports: [PickPillComponent],
})
export class PickPillModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const PickPillMessage = UiSchema.TaggedEnum({
  PickedPill: { pill: Schema.String }
})

export const PickPill = Html.component({
  name: "PickPill",
  model: Schema.Struct({ picked: Schema.String }),
  message: PickPillMessage
}).make({
  init: () => ({ picked: "red" }),
  update: {
    PickedPill: ($, { pill }) => $.evolve({ picked: pill })
  },
  view: (h, model) => {
    const Pill = (pill: string, label: string) => [
      h.input
        .id(`${pill}-pill`)
        .attrs({ type: "radio", value: pill })
        .checked(model.picked === pill)
        .on("change", () => PickPillMessage.PickedPill({ pill })),
      h.label.attr("for", `${pill}-pill`).children(label)
    ]
    return h.div(
      h.div(`Picked: ${model.picked}`),
      ...Pill("blue", "Blue pill"),
      ...Pill("red", "Red pill")
    )
  }
})

Select

logo of Angular Angular

import { Component, NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

@Component({
  selector: "app-color-select",
  template: `
    <select [(ngModel)]="selectedColorId">
      <option
        *ngFor="let color of colors"
        [value]="color.id"
        [disabled]="color.isDisabled"
      >
        {{ color.text }}
      </option>
    </select>
  `,
})
export class ColorSelectComponent {
  selectedColorId = 2;

  colors = [
    { id: 1, text: "red" },
    { id: 2, text: "blue" },
    { id: 3, text: "green" },
    { id: 4, text: "gray", isDisabled: true },
  ];
}

@NgModule({
  declarations: [ColorSelectComponent],
  imports: [FormsModule],
  exports: [ColorSelectComponent],
})
export class ColorSelectModule {}

logo of Effect UI Effect UI

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true }
]

const ColorSelectMessage = UiSchema.TaggedEnum({
  PickedColor: { id: Schema.Number }
})

export const ColorSelect = Html.component({
  name: "ColorSelect",
  model: Schema.Struct({ selectedColorId: Schema.Number }),
  message: ColorSelectMessage
}).make({
  init: () => ({ selectedColorId: 2 }),
  update: {
    PickedColor: ($, { id }) => $.evolve({ selectedColorId: id })
  },
  view: (h, model) =>
    h.select
      .value(String(model.selectedColorId))
      .on("change", ({ value }) =>
        ColorSelectMessage.PickedColor({ id: Number(value) })
      )
      .children(
        colors.map((color) =>
          h.option
            .key(String(color.id))
            .attr("value", String(color.id))
            .disabled(color.isDisabled === true)
            .children(color.text)
        )
      )
})

Webapp features

Render app

logo of Angular Angular

<!doctype html>
<html>
  <body>
    <app-root></app-root>
  </body>
</html>

logo of Effect UI Effect UI

<!doctype html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.ts"></script>
  </body>
</html>

Fetch data

logo of Angular Angular

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";

export interface UsersState {
  users: User[];
  error: string | null;
  loading: boolean;
}

export const initialState: UsersState = {
  users: [],
  error: null,
  loading: false,
};

@Injectable({ providedIn: "root" })
export class UserService {
  private state = new BehaviorSubject<UsersState>(initialState);
  state$ = this.state.asObservable();

  constructor(private http: HttpClient) {}

  loadUsers() {
    this.state.next({ ...initialState, loading: true });

    this.http
      .get<UserResponse>("https://randomuser.me/api/?results=3")
      .subscribe({
        next: ({ results }) =>
          this.state.next({ ...initialState, users: results }),
        error: (error) => this.state.next({ ...initialState, error }),
      });
  }
}

export interface UserResponse {
  results: User[];
  info: any;
}

export interface User {
  name: {
    title: string;
    first: string;
    last: string;
  };
  picture: {
    large: string;
    medium: string;
    thumbnail: string;
  };
}

logo of Effect UI Effect UI

import { Component } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Layer, Schema } from "effect"
import { FetchHttpClient } from "effect/http"
import { AsyncResult } from "effect/reactivity"
import { FetchUsers } from "./FetchUsers.ts"

export const App = Html.component({
  name: "App",
  model: Schema.Null,
  message: Schema.Never,
  queries: { users: { query: FetchUsers, args: () => ({}) } }
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    AsyncResult.match(h.queries.users, {
      onInitial: () => h.p("Fetching users..."),
      onFailure: () => h.p("An error occurred while fetching users"),
      onSuccess: ({ value: users }) =>
        h.ul(
          users.map((user) =>
            h.li.key(user.login.uuid).children(
              h.img.attrs({ src: user.picture.thumbnail, alt: "user" }),
              h.p(`${user.name.first} ${user.name.last}`)
            )
          )
        )
    })
}).pipe(
  Component.provide(FetchUsers.layer.pipe(Layer.provide(FetchHttpClient.layer)))
)