### Hello World with Calico and Scala Source: https://github.com/armanbilge/calico/blob/main/docs/demos/hello-world.md A complete Calico application that creates a reactive input field and displays a greeting. It uses SignallingRef to hold the name state, pipes input events through a given Pipe, and renders the app into a DOM node. The example is intended for mdoc:js execution and requires the calico, cats-effect, fs2, and fs2.dom imports. ```scala import calico.* import calico.html.io.{*, given} import calico.unsafe.given import calico.syntax.* import cats.effect.* import fs2.* import fs2.concurrent.* import fs2.dom.* val app: Resource[IO, HtmlDivElement[IO]] = SignallingRef[IO].of("world").toResource.flatMap { name => div( label("Your name: "), input.withSelf { self => ( placeholder := "Enter your name here", // here, input events are run through the given Pipe // this starts background fibers within the lifecycle of the element onInput --> (_.foreach(_ => self.value.get.flatMap(name.set))) ) }, span(" Hello, ", name.map(_.toUpperCase)) ) } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Render the component into the DOM Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Runs the component's Resource and renders it into an existing DOM node. This is the invisible setup code that makes the interactive example run in the documentation. ```scala import calico.unsafe.given component.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Enable Scala.js main module initializer in build.sbt Source: https://github.com/armanbilge/calico/blob/main/docs/iowebapp.md Required build.sbt setting to make the Scala.js application start automatically when the page loads. Without this, the IOWebApp entry point will not be invoked. ```scala scalaJSUseMainModuleInitializer := true ``` -------------------------------- ### Access window.location.href in render method Source: https://github.com/armanbilge/calico/blob/main/docs/iowebapp.md Uses the window: fs2.dom.Window[IO] provided by IOWebApp to access Web APIs. This example retrieves the current page URL and displays it in a div. ```scala def render = window.location.href.get.toResource.flatMap { location => div(s"Welcome to $location") } ``` -------------------------------- ### Add http4s-dom dependency Source: https://github.com/armanbilge/calico/blob/main/docs/demos/http4s.md Adds the http4s-dom library as a dependency for Scala.js projects using sbt. ```scala libraryDependencies += "org.http4s" %%% "http4s-dom" % "@HTTP4S_DOM_VERSION@" ``` -------------------------------- ### App composition and rendering Source: https://github.com/armanbilge/calico/blob/main/docs/demos/counter.md Creates the main app resource with a heading and a Counter instance labeled 'Sheep' with initial step 3. Renders the app into the provided DOM node and runs it forever, ignoring the result. ```scala val app: Resource[IO, HtmlDivElement[IO]] = div( h1("Let's count!"), Counter("Sheep", initialStep = 3) ) app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### HTTP Request with http4s-dom Source: https://github.com/armanbilge/calico/blob/main/docs/demos/http4s.md Creates a UI that fetches GitHub star counts using http4s-dom's FetchClientBuilder. The button click triggers a request, and switchMap cancels any ongoing request if clicked again. Displays the star count or 'Not found :(' on failure. ```scala import calico.html.io.{*, given} import calico.syntax.* import calico.unsafe.given import cats.effect.* import cats.syntax.all.* import fs2.Stream import fs2.concurrent.* import fs2.dom.* import io.circe.* import org.http4s.* import org.http4s.circe.* import org.http4s.dom.* case class Repo(stargazers_count: Int) derives Decoder object Repo: given EntityDecoder[IO, Repo] = jsonOf val client = FetchClientBuilder[IO].create val app: Resource[IO, HtmlDivElement[IO]] = ( input(size := 36, typ := "text", value := "armanbilge/calico"), SignallingRef[IO].of("").toResource ).flatMapN { (repoInput, starsResult) => val countStars: IO[Unit] = starsResult.set(" counting ... ") *> repoInput.value.get .flatMap { repo => client.expect[Repo](s"https://api.github.com/repos/$repo").attempt } .flatMap { case Right(Repo(stars)) => starsResult.set(s"$stars ★") case Left(_) => starsResult.set(s"Not found :(") } div( h3("How many stars?"), repoInput, button( // switchMap cancels an ongoing request if the button is clicked again onClick --> (_.switchMap(_ => Stream.exec(countStars))), "Count" ), span( styleAttr := "margin-left: 1em; color: var(--secondary-color)", starsResult ) ) } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Counter component with SignallingRef and Channel Source: https://github.com/armanbilge/calico/blob/main/docs/demos/counter.md Defines a Counter component that displays a step selector and increment/decrement buttons. Uses SignallingRef for the current step and Channel for diff events. The step selector allows choosing from allowed steps (1, 2, 3, 5, 10) and updates the step on change. The displayed value is the accumulated sum of diffs via scanMonoid. ```scala import calico.* import calico.html.io.{*, given} import calico.syntax.* import calico.unsafe.given import cats.effect.* import cats.syntax.all.* import fs2.* import fs2.concurrent.* import fs2.dom.* def Counter(label: String, initialStep: Int): Resource[IO, HtmlDivElement[IO]] = SignallingRef[IO].of(initialStep).product(Channel.unbounded[IO, Int]) .toResource.flatMap { (step, diff) => val allowedSteps = List(1, 2, 3, 5, 10) div( p( "Step: ", select.withSelf { self => ( allowedSteps.map(step => option(value := step.toString, step.toString)), value <-- step.map(_.toString), onChange --> { _.evalMap(_ => self.value.get).map(_.toIntOption).unNone.foreach(step.set) } ) } ), p( label + ": ", b(diff.stream.scanMonoid.map(_.toString).holdOptionResource), " ", button( "-", onClick --> { _.evalMap(_ => step.get).map(-1 * _).foreach(diff.send(_).void) } ), button( "+", onClick --> (_.evalMap(_ => step.get).foreach(diff.send(_).void)) ) ) ) } ``` -------------------------------- ### Composing Signals with SignallingRef in Calico Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Shows how to create and compose multiple SignallingRef instances as Signals in a Calico UI component. Uses transformation and composition to derive a Signal that contains the data of interest. The example includes a select element that updates a cardinal signal and composes it with input signals. ```scala import cats.syntax.all.* import calico.frp.given enum Cardinal: case North, South val signals = ( SignallingRef[IO].of(Option.empty[Cardinal]), SignallingRef[IO].of(""), SignallingRef[IO].of(""), ).tupled.toResource val app: Resource[IO, HtmlDivElement[IO]] = signals.flatMap { (cardinalSig, northSig, southSig) => div( div( label("North input: "), input.withSelf { self => onInput(self.value.get.flatMap(northSig.set)) }, ), br(()), div( select.withSelf { self => ( option(disabled := true, selected := true, "Select input"), option(value := "north", "North"), option(value := "south", "South"), onChange { self.value.get.map { case "north" => Some(Cardinal.North) case "south" => Some(Cardinal.South) case _ => None }.flatMap(cardinalSig.set(_)) } ) }, " ", // compose cardinal signal with appropriate input signal (cardinalSig: Signal[IO, Option[Cardinal]]).flatMap { case Some(Cardinal.North) => northSig case Some(Cardinal.South) => southSig case None => Signal.constant("") } ), br(()), div( label("South input: "), input.withSelf { self => onInput(self.value.get.flatMap(southSig.set)) }, ), ) } ``` ```scala import calico.unsafe.given app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Define an IOWebApp entry point with render method Source: https://github.com/armanbilge/calico/blob/main/docs/iowebapp.md Defines the main entry point for a Calico web application by extending IOWebApp and implementing the render method, which returns a Resource that produces an HtmlElement. This is the browser analog to Cats Effect IOApp. ```scala import calico.* import calico.html.io.{*, given} import cats.effect.* import fs2.dom.* object MyCalicoApp extends IOWebApp: def render: Resource[IO, HtmlElement[IO]] = div("Toto, I've a feeling we're not in Kansas anymore.") ``` -------------------------------- ### Basic index.html with app root div and main.js script Source: https://github.com/armanbilge/calico/blob/main/docs/iowebapp.md HTML page that hosts the Calico application. The div with id 'app' is the default root element where the application is mounted, and main.js is the compiled Scala.js output. ```html
``` -------------------------------- ### Router demo with Routes.one and dispatch Source: https://github.com/armanbilge/calico/blob/main/docs/router.md Full demo showing how to create a Router, define routes with Routes.one, combine them with |+|, and dispatch them. It uses query parameters for routing and demonstrates component reuse via Signals. ```scala import calico.html.io.{*, given} import calico.router.* import calico.syntax.* import calico.unsafe.given import cats.effect.* import cats.syntax.all.* import fs2.* import fs2.concurrent.* import fs2.dom.* import org.http4s.* import org.http4s.syntax.all.* val app: Resource[IO, HtmlDivElement[IO]] = Router(Window[IO]).toResource.flatMap { router => (SignallingRef[IO].of(0), SignallingRef[IO].of(0)).tupled.toResource.flatMap { (helloCounter, countCounter) => def helloUri(who: String) = uri"" +? ("page" -> "hello") +? ("who" -> who) def countUri(n: Int) = uri"" +? ("page" -> "count") +? ("n" -> n) val helloRoute = Routes.one[IO] { case uri if uri.query.params.get("page").contains("hello") => uri.query.params.getOrElse("who", "world") } { who => helloCounter.update(_ + 1).toResource *> div("Hello, ", who) } val countRoute = Routes.one[IO] { case uri if uri.query.params.get("page").contains("count") => uri.query.params.get("n").flatMap(_.toIntOption).getOrElse(0) } { n => countCounter.update(_ + 1).toResource *> p( "Sheep: ", n.map(_.toString), " ", button( "+", onClick(n.get.map(i => countUri(i + 1)).flatMap(router.navigate)) ) ) } val content = (helloRoute |+| countRoute).toResource.flatMap(router.dispatch) div( p("Created hello page ", helloCounter.map(_.toString), " times."), p("Created count page ", countCounter.map(_.toString), " times."), h3("Navigation"), p("Watch the URL change in your browser address bar!"), ul( List("Shaun", "Shirley", "Timmy", "Nuts").map { who => li( a( href := "#", onClick(router.navigate(helloUri(who))), s"Hello, $who" ) ) }, li( a( href := "#", onClick(router.navigate(countUri(0))), "Let's count!" ) ) ), h3("Content"), content ) } } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Create a SignallingRef with an initial value Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Shows how to create a SignallingRef with an initial value, which is also a Signal. ```scala SignallingRef[IO].of("initial value") ``` -------------------------------- ### Interactive Hello World with SignallingRef and input events Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Builds a self-contained component that manages an input element, a signal for the name, and background fibers for event handling and rendering. The onInput operator runs a Pipe that updates the signal, and the span renders the signal's value in uppercase. The commented lines show equivalent simpler syntax for the input handler. ```scala import calico.* import calico.html.io.{*, given} import calico.syntax.* import cats.effect.* import fs2.* import fs2.concurrent.* import fs2.dom.* val component: Resource[IO, HtmlDivElement[IO]] = SignallingRef[IO].of("world").toResource.flatMap { name => div( label("Your name: "), input.withSelf { self => ( placeholder := "Enter your name here", // here, input events are run through the given Pipe // this starts background fibers within the lifecycle of the element onInput --> (_.foreach(_ => self.value.get.flatMap(name.set))) // You can also use simpler syntax - these are all equivalent to a foreach: // onInput(_ => self.value.get.flatMap(name.set)) // onInput(self.value.get.flatMap(name.set)) ) }, span( " Hello, ", // here, a Signal is rendered into the HTML // this starts background fibers within the life cycle of the element name.map(_.toUpperCase) ) ) } ``` -------------------------------- ### Basic Interval Stream with fixedRate and scanMonoid Source: https://github.com/armanbilge/calico/blob/main/docs/demos/time.md Creates a tick stream at 1-second intervals, counts ticks using scanMonoid, and displays the count along with a random number updated on each tick. Uses holdOptionResource to manage the latest values. ```scala import calico.* import calico.html.io.{*, given} import calico.syntax.* import calico.unsafe.given import cats.effect.* import cats.effect.std.Random import cats.syntax.all.* import fs2.* import fs2.concurrent.* import fs2.dom.* import scala.concurrent.duration.* val app: Resource[IO, HtmlDivElement[IO]] = Stream.fixedRate[IO](1.second).as(1).scanMonoid.map(_.toString).holdOptionResource .flatMap { tick => div( div("Tick #: ", tick), div( "Random #: ", Random.scalaUtilRandom[IO].toResource.flatMap { random => tick.discrete .evalMap(_ => random.nextInt.map(i => (i % 100).toString)) .holdOptionResource } ) ) } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Create a simple component with div, i, and b Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Uses Calico's HTML DSL to describe a component with standard tags. The div, i, and b calls each return Resources that compose monadically; no HtmlElement is created until the Resource is allocated. ```scala import calico.html.io.{*, given} import cats.effect.* import fs2.dom.* val component: Resource[IO, HtmlElement[IO]] = div(i("hello"), " ", b("world")) ``` -------------------------------- ### Derive a Signal from a Stream using holdResource Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Shows how to derive a Signal from a Stream by holding its latest value. Includes both holdResource with an initial value and holdOptionResource which uses None for the initial value. ```scala def stringStream: Stream[IO, String] = ??? stringStream.holdResource("initial value") stringStream.holdOptionResource // use None for the intitial value ``` -------------------------------- ### Customize root element id in IOWebApp Source: https://github.com/armanbilge/calico/blob/main/docs/iowebapp.md Overrides the default root element id ('app') to a custom value. The HTML page must contain a div with the matching id for the application to mount correctly. ```scala override def rootElementId = "somewhere-over-the-rainbow" ``` -------------------------------- ### Define a component as Resource[IO, HtmlElement[IO]] Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Shows the core Calico pattern where every component is expressed as a Resource that manages the element's lifecycle. The first definition is a placeholder, and the second shows a more general form using the Dom typeclass. No Calico imports are needed yet. ```scala import cats.effect.* import fs2.dom.* // note: no calico import yet! val component: Resource[IO, HtmlElement[IO]] = ??? // or more generally: def component[F[_]: Dom]: Resource[F, HtmlElement[F]] = ??? ``` -------------------------------- ### Add Calico dependency with sbt Source: https://github.com/armanbilge/calico/blob/main/docs/index.md Adds the Calico library as an sbt dependency for Scala.js projects. Replace @PRERELEASE_VERSION@ with the actual version number. ```scala libraryDependencies += "com.armanbilge" %%% "calico" % "@PRERELEASE_VERSION@" ``` -------------------------------- ### Debounce with Channel and debounce Source: https://github.com/armanbilge/calico/blob/main/docs/demos/time.md Validates an email input with a 1-second debounce, showing error or success messages. Uses a Channel to stream input values and Nested to conditionally apply CSS classes. ```scala import calico.* import calico.html.io.{*, given} import calico.syntax.* import calico.unsafe.given import cats.data.* import cats.effect.* import cats.syntax.all.* import fs2.* import fs2.concurrent.* import fs2.dom.* import scala.concurrent.duration.given def validateEmail(email: String): Either[String, Unit] = if email.isEmpty then Left("Please fill out email") else if !email.contains('@') then Left("Invalid email!") else Right(()) val app: Resource[IO, HtmlDivElement[IO]] = Channel.unbounded[IO, String].toResource.flatMap { emailCh => val validated = emailCh.stream.debounce(1.second).map(validateEmail) validated.holdOptionResource.flatMap { validatedSig => div( span( label("Your email: "), input.withSelf { self => onInput --> (_.evalMap(_ => self.value.get).through(emailCh.sendAll)) } ), span( cls <-- Nested(validatedSig).map { case Left(_) => List("-error") case Right(_) => List("-success") }.value, Nested(validatedSig).map { case Left(err) => s"Error: $err" case Right(()) => "Email ok!" }.value ) ) } } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Insert IO.cede to re-render mid-task Source: https://github.com/armanbilge/calico/blob/main/docs/concepts.md Use this snippet when you need the browser to re-render before completing all work in a task. By default, Calico schedules tasks as microtasks, so the UI won't re-render until all microtasks finish. Inserting IO.cede yields control to the browser to re-render immediately, improving responsiveness. ```scala updateComponentA *> // doesn't render yet updateComponentB *> // still didn't render IO.cede *> // re-render now doOtherStuff *> ... // do non-view-related work ``` -------------------------------- ### Delay with Channel and Stream.sleep_ Source: https://github.com/armanbilge/calico/blob/main/docs/demos/time.md Shows a button that, when clicked, displays a temporary message 'Just clicked!' for 500 milliseconds before clearing. Uses a Channel to trigger the alert stream and holdResource to manage the current message. ```scala import calico.* import calico.html.io.{*, given} import calico.syntax.* import calico.unsafe.given import cats.effect.* import cats.syntax.all.* import fs2.* import fs2.concurrent.* import fs2.dom.* import scala.concurrent.duration.* val app: Resource[IO, HtmlDivElement[IO]] = Channel.unbounded[IO, Unit].toResource.flatMap { clickCh => val alert = clickCh.stream >> (Stream.emit("Just clicked!") ++ Stream.sleep_[IO](500.millis) ++ Stream.emit("")) div( button(onClick --> (_.void.through(clickCh.sendAll)), "Click me"), alert.holdResource("") ) } app.renderInto(node.asInstanceOf[fs2.dom.Node[IO]]).useForever.unsafeRunAndForget() ``` -------------------------------- ### Add Calico dependency to sbt build Source: https://github.com/armanbilge/calico/blob/main/README.md Adds the Calico library as a dependency for a Scala.js project. Use this in your build.sbt to include Calico version 0.2.3. ```scala libraryDependencies += "com.armanbilge" %%% "calico" % "0.2.3" ``` -------------------------------- ### Add calico-router dependency Source: https://github.com/armanbilge/calico/blob/main/docs/router.md Adds the calico-router module to your build. It is built only with Cats Effect, FS2-DOM, and http4s, and has no dependency on calico core. ```scala libraryDependencies += "com.armanbilge" %%% "calico-router" % "@VERSION@" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.