Skip to main content
Version: ZIO 2.x

How to Interop with JavaScript?

Include ZIO in your Scala.js project by adding the following to your build.sbt:

scalaJSUseMainModuleInitializer := true
resolvers += Resolver.sonatypeRepo("snapshots")
libraryDependencies += "dev.zio" %%% "zio" % "2.0.0+156-8c573c46-SNAPSHOT"

Example

Your main function can extend App as follows. This example uses scala-js-dom to access the DOM; to run the example you will need to add that library as a dependency to your build.sbt.

import org.scalajs.dom.{document, raw}
import zio._
import zio.Clock._

object Main extends App {

def run(args: List[String]) = {
for {
_ <- Console.printLine("Starting progress bar demo.") // Outputs on browser console log.
target <- IO.succeed(document.createElement("pre"))
_ <- update(target).repeat(Schedule.spaced(1.seconds))
_ <- IO.succeed(node.appendChild(target)) // "node" is provided in this page by mdoc.
} yield ExitCode.success
}

def update(target: raw.Element) = {
for {
time <- currentTime(TimeUnit.SECONDS)
output <- ZIO.succeed(progress((time % 11).toInt, 10))
_ <- ZIO.succeed(target.innerHTML = output)
} yield ()
}

def progress(tick: Int, size: Int) = {
val bar_length = tick
val empty_length = size - tick
val bar = "#" * bar_length + " " * empty_length
s"$bar $bar_length%"
}

}