Pre-beta, under heavy active development: the API changes often and nothing here is stable yet.

Spar

Recipes

A timer

Timers are Effect schedules. Turn the stream into a reactive value in the component's Effect; it stops when the component unmounts.

const everySecond = Reactive.fromStream(
  0,
  Stream.fromSchedule(Schedule.spaced("1 second")).pipe(Stream.map((count) => count + 1)),
)

(packages/spar/test/events.test.ts)

A websocket

Use effect/socket. Decode each message with a Schema, then either show it (Reactive.fromStream) or turn it into store commands (Effect.forkScoped(Stream.runForEach(messages, store.commands.received))). Reconnect with Stream.retry and a schedule. Spar adds nothing here.

Close something on Escape or an outside press

const closedOnEscapeOrOutside = Effect.fnUntraced(function* (open: UiState.UiState<boolean>) {
  yield* Events.onDocument("pointerdown", UiState.set(open, false))
  yield* Events.onDocument("keydown", (event) =>
    event.key === "Escape" ? UiState.set(open, false) : [],
  )
})

(apps/demo/src/mail/Thread.ts)

and stop presses inside from reaching the document: <span onPointerdown={Events.stop([])}>. For a layer above the page use View.portal with Overlay.dismissable.

A dialog with a form

Wrap the form component with the kit's Dialog and mount it while some UI state says so. The form is mounted fresh each time the dialog opens.

const dialogs = Effect.fnUntraced(function* (editing: UiState.UiState<Editing>) {
  const onClose = UiState.set(editing, { _tag: "Nothing" })
  const shared = { editing, onClose }
  const closing = { onClose }
  const when = (tag: Editing["_tag"]) => Reactive.map(editing, (now) => now._tag === tag)

  return [
    yield* pipe(
      when("Starting"),
      Reactive.when(
        Dialog({ id: "start", title: "Start an agent" }, View.child(StartForm, shared)),
        closing,
      ),
    ),
    yield* pipe(
      when("AddingProject"),
      Reactive.when(
        Dialog({ id: "project", title: "New project" }, View.child(ProjectForm, shared)),
        closing,
      ),
    ),
    yield* pipe(
      when("Tagging"),
      Reactive.when(
        Dialog({ id: "tags", title: "Edit tags" }, View.child(TagsForm, shared)),
        closing,
      ),
    ),
    yield* pipe(
      when("Moving"),
      Reactive.when(
        Dialog({ id: "move", title: "Move to a project" }, View.child(MoveForm, shared)),
        closing,
      ),
    ),
  ]
})

(apps/sidebar/src/Sidebar.ts)

Work that must reach the server

Queue it on an outbox channel from the service that changes the store. The item is saved on the device, sent with one idempotency key, and retried until it lands; the store is saved too, so a reload loses nothing.

export class AgentStarts extends Context.Service<
  AgentStarts,
  { readonly start: (name: string) => Effect.Effect<void> }
>()("sidebar/AgentStarts") {
  static readonly layer = Layer.effect(
    AgentStarts,
    Effect.gen(function* () {
      const store = yield* BoardStore
      const server = yield* Server
      const queued = yield* Outbox.channel("sidebar/agents/started", Started, ({ name }, key) =>
        server.start(name, key),
      )

      return AgentStarts.of({
        start: Effect.fn("AgentStarts.start")(function* (name: string) {
          yield* store.commands.started({ name })
          yield* queued({ name })
        }),
      })
    }),
  )
}

(apps/sidebar/src/BoardStore.ts)

Show outbox.pending and outbox.dead so the person can see what has not been sent.

Tracing

Every component mount is a span named after its view and every store command is a span named <store key>/<action>. Provide Effect's OTLP layer at the entry point:

const telemetry = Otlp.layerJson({
  baseUrl: `${location.origin}/otlp`,
  resource: { serviceName: "spar-sidebar" },
  tracerExportInterval: "1 second",
}).pipe(Layer.provide(Backend.layerTelemetry))

(apps/sidebar/src/main.ts)

Post to your own origin and forward from the server, so the browser needs no cross-origin access to the collector. apps/demo/scripts/site.ts forwards /otlp to OTLP_ENDPOINT when it is set and drops traces otherwise.

Testing a component with fixture layers

Mount the real component and provide test layers for its services.

const failedLoadIsShown = Effect.gen(function* () {
  const probe = yield* Probe

  yield* mount(LoaderPage)
  yield* Deferred.fail(probe.loaded, new LoadFailed({ message: "The report is missing." }))

  expect((yield* find("alert")).textContent).toBe("The report is missing.")
}).pipe(Effect.provide(layer))

describe("rendering", () => {
  it.live("a component's pure view can be taken back out and shown with sample props", () =>
    Effect.gen(function* () {
      yield* mount(LoaderStory)

      expect((yield* find("heading", "Sample title")).textContent).toBe("Sample title")
      expect(LoaderPage.view).toBe(LoadedView)
    }),
  )

  it.live("a store change updates the bound text and keeps the surrounding nodes", () =>
    Effect.gen(function* () {
      const board = yield* Board
      const probe = yield* Probe

      yield* mount(BoardPanel)

      const total = yield* find("status", "Total")
      const button = yield* find("button", "Add item")

      yield* board.commands.added({ label: "From a command" })
      yield* Effect.sync(() => button.click())
      yield* findText("From the button")

      expect(total.textContent).toBe("2")
      expect(yield* find("status", "Total")).toBe(total)
      expect(yield* Ref.get(probe.mounts)).toBe(1)
    }).pipe(Effect.provide(layer)),
  )

  it.live("a keyed list keeps each row's node through renames, reorders and removals", () =>
    Effect.gen(function* () {
      const board = yield* Board

      yield* mount(BoardPanel)
      yield* board.commands.added({ label: "Alpha" })
      yield* board.commands.added({ label: "Beta" })

      const alpha = yield* findText("Alpha")
      const beta = yield* findText("Beta")

      yield* board.commands.renamed({ id: "item-1", label: "Alpha, renamed" })
      yield* board.commands.reversed()
      yield* findText("Alpha, renamed")

      expect(yield* labels).toEqual(["Beta", "Alpha, renamed"])
      expect(screen.getAllByRole("listitem")).toEqual([beta, alpha])

      yield* board.commands.removed({ id: "item-2" })
      yield* eventually(() => expect(screen.getAllByRole("listitem")).toEqual([alpha]))
    }).pipe(Effect.provide(layer)),
  )

  it.live("a conditional mounts its component when shown and cancels its scope when hidden", () =>
    Effect.gen(function* () {
      const probe = yield* Probe

      yield* mount(Disclosure)

      const toggle = yield* find("button", "Toggle details")

      expect(screen.queryByRole("note")).toBeNull()

      yield* Effect.sync(() => toggle.click())

      expect((yield* find("note")).textContent).toBe("Now you see me")

      yield* Effect.sync(() => toggle.click())
      yield* gone("note")

      expect(yield* Ref.get(probe.mounts)).toBe(1)
      expect(yield* Ref.get(probe.unmounts)).toBe(1)
    }).pipe(Effect.provide(layer)),
  )

  it.live("a pending component shows its placeholder until the load succeeds", () =>
    Effect.gen(function* () {
      const probe = yield* Probe

      yield* mount(LoaderPage)

      expect((yield* find("status")).textContent).toBe("Loading report")

      yield* Deferred.succeed(probe.loaded, "Quarterly report")

      expect((yield* find("heading", "Quarterly report")).textContent).toBe("Quarterly report")
      expect(screen.queryByRole("status")).toBeNull()
    }).pipe(Effect.provide(layer)),
  )

  it.live("a failed load is shown by the view that recovers its error", () => failedLoadIsShown)
})

(packages/spar/test/render.test.ts)

A long action

A handler's actions start in event order and may overlap if they wait on something. Keep handlers short: a store command, a UI state change, a navigation. Put slow work in an Effect on a service, run by a FiberHandle so a repeat is ignored while it runs, or on an outbox channel for what must reach the server. A form's submit already ignores a second submit while the first is running.