org.scalajs.dom.document Scala Examples

The following examples show how to use org.scalajs.dom.document. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Main.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.benchmarks

import io.udash.benchmarks.css.CssStylesApply
import io.udash.benchmarks.i18n.StaticTranslationBinding
import io.udash.benchmarks.properties._
import io.udash.benchmarks.serialization.SerializationBenchmarks
import japgolly.scalajs.benchmark.gui.BenchmarkGUI
import org.scalajs.dom.document

object Main {
  def main(args: Array[String]): Unit = {
    BenchmarkGUI.renderMenu(document.getElementById("body"))(
      SinglePropertyListeners.suite,
      ModelPropertyListeners.suite,
      ModelPropertyWithSeqListeners.suite,
      TransformedSeqPropertyListeners.suite,
      FilteredSeqPropertyListeners.suite,
      ReversedSeqPropertyListeners.suite,
      ZippedSeqPropertyListeners.suite,

      StaticTranslationBinding.suite,

      CssStylesApply.suite,

      SerializationBenchmarks.suite,

      PropertyParameters.suite
    )
  }
} 
Example 2
Source File: ExportedComponentTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.core

import slinky.core.facade.{React, ReactElement}
import slinky.web.ReactDOM

import scala.scalajs.js
import org.scalajs.dom.document

import org.scalatest.funsuite.AnyFunSuite

object TestExportedComponentWithState extends ComponentWrapper {
  case class Props(name: String)
  type State = Int

  class Def(jsProps: js.Object) extends Definition(jsProps) {
    override def initialState: Int = 1

    override def render(): ReactElement = {
      s"${props.name} $state"
    }
  }
}

object TestExportedComponentStateless extends StatelessComponentWrapper {
  case class Props(name: String)

  class Def(jsProps: js.Object) extends Definition(jsProps) {
    override def render(): ReactElement = {
      s"${props.name}"
    }
  }
}

object TestExportedExternalComponent extends ExternalComponentNoProps {
  case class Props(children: Seq[ReactElement])
  val component = "div"
}

class ExportedComponentTest extends AnyFunSuite {
  test("Can construct an instance of an exported component with JS-provided props") {
    val container = document.createElement("div")
    ReactDOM.render(React.createElement(
      TestExportedComponentWithState: ReactComponentClass[_],
      js.Dictionary(
        "name" -> "lol"
      )
    ), container)

    assert(container.innerHTML == "lol 1")
  }

  test("Can construct an instance of a stateless exported component with JS-provided props") {
    val container = document.createElement("div")
    ReactDOM.render(React.createElement(
      TestExportedComponentStateless: ReactComponentClass[_],
      js.Dictionary(
        "name" -> "lol"
      )
    ), container)

    assert(container.innerHTML == "lol")
  }

  test("Can construct an instance of an exported functional component with JS-provided props") {
    case class FunctionalProps(name: String)
    val TestExportedFunctionalComponent = FunctionalComponent((p: FunctionalProps) => {
      p.name
    })

    val container = document.createElement("div")
    ReactDOM.render(React.createElement(
      TestExportedFunctionalComponent: ReactComponentClass[_],
      js.Dictionary(
        "name" -> "lol"
      )
    ), container)

    assert(container.innerHTML == "lol")
  }

  test("Can construct an instance of an exported external component with JS-provided props") {
    val container = document.createElement("div")
    ReactDOM.render(React.createElement(
      TestExportedExternalComponent: ReactComponentClass[_],
      js.Dictionary(
        "children" -> js.Array("hello")
      )
    ), container)

    assert(container.innerHTML == "<div>hello</div>")
  }
} 
Example 3
Source File: ContextTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.core

import slinky.core.facade.React
import slinky.web.ReactDOM
import org.scalajs.dom.document
import slinky.web.html.div

import org.scalatest.funsuite.AnyFunSuite

class ContextTest extends AnyFunSuite {
  test("Can provide and read a simple context value") {
    val context = React.createContext(-1)
    var gotValue = 0

    ReactDOM.render(
      context.Provider(value = 2)(
        context.Consumer { value =>
          gotValue = value
          div()
        }
      ),
      document.createElement("div")
    )

    assert(gotValue == 2)
  }

  test("Can provide and read a case class context value") {
    case class Data(foo: Int)
    val context = React.createContext(Data(-1))
    var gotValue = 0

    ReactDOM.render(
      context.Provider(value = Data(3))(
        context.Consumer { value =>
          gotValue = value.foo
          div()
        }
      ),
      document.createElement("div")
    )

    assert(gotValue == 3)
  }

  test("Read a case class context value from default") {
    case class Data(foo: Int)
    val context = React.createContext(Data(3))
    var gotValue = 0

    ReactDOM.render(
      context.Consumer { value =>
        gotValue = value.foo
        div()
      },
      document.createElement("div")
    )

    assert(gotValue == 3)
  }
} 
Example 4
Source File: ReactDOMTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.web

import slinky.core.ComponentWrapper
import slinky.core.facade.ReactElement
import org.scalajs.dom.{Element, document}

import scala.scalajs.js
import html._

import org.scalatest.funsuite.AnyFunSuite

object TestComponent extends ComponentWrapper {
  type Props = Unit
  type State = Unit

  class Def(jsProps: js.Object) extends Definition(jsProps) {
    override def initialState: Unit = ()

    override def render(): ReactElement = {
      a()
    }
  }
}

class ReactDOMTest extends AnyFunSuite {
  test("Renders a single element into the DOM") {
    val target = document.createElement("div")
    ReactDOM.render(
      a(),
      target
    )

    assert(target.innerHTML == "<a></a>")
  }

  test("Finds a dom node for a component") {
    val comp: ReactElement = TestComponent(())
    val target = document.createElement("div")
    val instance = ReactDOM.render(
      comp,
      target
    ).asInstanceOf[TestComponent.Def]

    assert(target.childNodes(0).asInstanceOf[Element] == ReactDOM.findDOMNode(instance))
  }

  test("Renders portals to the appropriate container DOM node") {
    val target = document.createElement("div")
    val container = document.createElement("div")
    ReactDOM.render(
      div(
        ReactDOM.createPortal(h1("hi"), container)
      ),
      target
    )

    assert(container.innerHTML == "<h1>hi</h1>")
    assert(target.innerHTML == "<div></div>")
  }

  test("unmountComponentAtNode clears out the container") {
    val container = document.createElement("div")
    ReactDOM.render(
      div("hello"),
      container
    )

    assert(container.innerHTML == "<div>hello</div>")

    ReactDOM.unmountComponentAtNode(container)

    assert(container.innerHTML.length == 0)
  }
} 
Example 5
Source File: InteropTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.scalajsreact

import org.scalatest.funsuite.AnyFunSuite
import slinky.web.ReactDOM
import org.scalajs.dom.document
import japgolly.scalajs.react.vdom.html_<^._
import Converters._
import slinky.web.html.div

class InteropTest extends AnyFunSuite {
  test("Can convert Scala.js React node to Slinky") {
    val target = document.createElement("div")
    ReactDOM.render(
      <.a().toSlinky,
      target
    )

    assert(target.innerHTML == "<a></a>")
  }

  test("Can convert Slinky element to Scala.js React node and render through Slinky") {
    val target = document.createElement("div")
    ReactDOM.render(
      <.a(
        div("hello!").toScalaJSReact
      ).toSlinky,
      target
    )

    assert(target.innerHTML == "<a><div>hello!</div></a>")
  }
} 
Example 6
Source File: ui.scala    From playground-binding.scala   with MIT License 5 votes vote down vote up
package com.ccm.me.playground.bindingscala.svgeditor

import com.ccm.me.playground.bindingscala.ShowCase
import com.thoughtworks.binding.Binding.{BindingSeq, Constants, Var}
import com.thoughtworks.binding.{Binding, dom}
import org.scalajs.dom.raw.{Event, MouseEvent, SVGElement, SVGTextElement}
import org.scalajs.dom.{Node, document}

import scala.language.implicitConversions

class ui extends ShowCase {
  implicit def makeIntellijHappy[T<:org.scalajs.dom.raw.Node](x: scala.xml.Node): Binding[T] = throw new AssertionError("This should never execute.")
  implicit def intToString(i: Int ) = i.toString
  implicit val events: Var[Option[Event]] = Var(None)

  val model: RectShape = RectShape(Var(250), Var(170), Var(300), Var(150), Var("Hello !"))
  val selected: Var[Option[RectShape]] = Var(None)

  @dom override def css: Binding[BindingSeq[Node]] =
      <style>
      </style>
      <!-- -->

  @dom override def render: Binding[Node] = {
    import View._
    implicit def toSvgTags(a: dom.Runtime.TagsAndTags2.type) = scalatags.JsDom.svgTags

    <div class="container" style="height:100%">
      <p>Select, move or resize the following rectangle:</p>

      <svg data:width="100%"
           data:height="600">

        <defs>
          <pattern data:id="smallGrid" data:width="10" data:height="10" data:patternUnits="userSpaceOnUse">
            <path data:d="M 10 0 L 0 0 0 10" data:fill="none" data:stroke="gray" data:stroke-width="0.5"/>
          </pattern>
          <pattern data:id="grid" data:width="100" data:height="100" data:patternUnits="userSpaceOnUse">
            <rect data:width="100" data:height="100" data:fill="url(#smallGrid)"/>
            <path data:d="M 100 0 L 0 0 0 100" data:fill="none" data:stroke="gray" data:stroke-width="1"/>
          </pattern>
        </defs>
        <rect data:width="100%" data:height="100%" data:fill="url(#grid)" />

        <g data:id="layers">
          <g data:id="layer-canvas">
            {
            model.draw().bind
            }
          </g>
          <g data:id="layer-graphics">
            {coords.bind}
          </g>
        </g>
      </svg>
    </div>
  }

  @dom def coords(): Binding[SVGElement] = {
    implicit def toSvgTags(a: dom.Runtime.TagsAndTags2.type) = scalatags.JsDom.svgTags

    val (x, y) = (Var(0), Var(0))

    @dom def render(): Binding[SVGTextElement] = {
      <text data:x="10"
            data:y="20">
        ({x.bind.toString}, {y.bind.toString})
      </text>
    }

    events.bind match {
      case Some(e:MouseEvent) ⇒
        x.value = e.pageX.toInt
        y.value = e.pageY.toInt

      case _ ⇒
    }

    <g data:id="coords">
      {render.bind}
    </g>
  }

  override def install() {
    def emit(e: Event) = {
      events.value = Some(e)
      events.value = None
    }

    document.onmousemove = emit _
    document.onmousedown = emit _
    document.onmousedown = emit _
  }

  override def name: String = "playground-binding.scala/svg-editor"
  @dom override def description: Binding[Node] = <div>SVG shapes resizable using mouse</div>
  override def link: String = s"#playground-binding.scala/svg-editor"
  override def scalaFiddle: Option[String] = None

} 
Example 7
Source File: ReactApolloTest.scala    From apollo-scalajs   with MIT License 5 votes vote down vote up
package com.apollographql.scalajs.react

import com.apollographql.scalajs.cache.InMemoryCache
import com.apollographql.scalajs.link.{HttpLink, HttpLinkOptions}
import com.apollographql.scalajs.{ApolloBoostClient, ApolloClient, CurrencyRatesQuery, UnfetchFetch}
import org.scalajs.dom.document
import org.scalatest.{Assertion, AsyncFunSuite}
import slinky.web.ReactDOM
import slinky.web.html.div

import scala.concurrent.Promise
import scala.scalajs.js
import scala.scalajs.js.JSON

class ReactApolloTest extends AsyncFunSuite {
  js.Dynamic.global.window.fetch = UnfetchFetch

  implicit override def executionContext =
    scala.concurrent.ExecutionContext.Implicits.global

  test("Can mount an ApolloProvider with a client instance") {
    assert(!js.isUndefined(
      ReactDOM.render(
        ApolloProvider(
          client = ApolloBoostClient(uri = "https://graphql-currency-rates.glitch.me")
        )(
          div()
        ),
        document.createElement("div")
      )
    ))
  }

  test("Can server-side render data to string based on a query") {
    val link = new HttpLink(options = HttpLinkOptions(uri = "https://graphql-currency-rates.glitch.me"))
    val cache = new InMemoryCache()
    val client = new ApolloClient(options = js.Dynamic.literal(ssrMode = true, link = link, cache = cache))

    ReactApolloServer.renderToStringWithData(
      ApolloProvider(ApolloProvider.Props(client = client))(
        Query(
          CurrencyRatesQuery,
          CurrencyRatesQuery.Variables("USD")
        ) { d =>
          if (d.data.isDefined) {
            div(d.data.get.rates.get.head.get.currency.get)
          } else ""
        }
      )
    ).toFuture.map { html =>
      assert(html == """<div data-reactroot="">AED</div>""")
    }
  }
} 
Example 8
Source File: Main.scala    From apollo-scalajs   with MIT License 5 votes vote down vote up
package com.apollographql.scalajs

import com.apollographql.scalajs.react.ApolloProvider
import slinky.web.ReactDOM
import slinky.web.html._
import slinky.hot
import org.scalajs.dom.{document, html}

import scala.scalajs.js
import scala.scalajs.js.annotation.JSExportTopLevel
import scala.scalajs.LinkingInfo

object Main {
  @JSExportTopLevel("entrypoint.main")
  def main(): Unit = {
    if (LinkingInfo.developmentMode) {
      hot.initialize()
    }

    if (js.typeOf(js.Dynamic.global.reactContainer) == "undefined") {
      js.Dynamic.global.reactContainer = document.createElement("div")
      document.body.appendChild(js.Dynamic.global.reactContainer.asInstanceOf[html.Element])
    }

    val client = ApolloBoostClient(
      uri = "https://1jzxrj179.lp.gql.zone/graphql"
    )

    ReactDOM.render(
      ApolloProvider(client)(
        div(
          PostsView(),
          AuthorView(1)
        )
      ),
      js.Dynamic.global.reactContainer.asInstanceOf[html.Element]
    )
  }
} 
Example 9
Source File: ScalaJSExample.scala    From Full-Stack-Scala-Starter   with Apache License 2.0 5 votes vote down vote up
package example

import com.thoughtworks.binding.Binding.Var
import com.thoughtworks.binding.{Binding, dom}
import org.scalajs.dom.document
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.raw.{Event, HTMLElement}

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.JSON



object ScalaJSExample extends js.JSApp {

  implicit def makeIntellijHappy(x: scala.xml.Elem): Binding[HTMLElement] = ???

  
  def countRequest(data: Var[String]) = {
    val url = "http://localhost:9000/count"
    Ajax.get(url).foreach { case xhr =>
      data.value = JSON.parse(xhr.responseText).count.toString
    }
  }

  @dom
  def render = {
    val data = Var("")
    countRequest(data) // initial population
    <div>
      <button onclick={event: Event => countRequest(data) }>
        Boop
      </button>
      From Play: The server has been booped { data.bind } times. Shared Message: {shared.SharedMessages.itWorks}.
    </div>
  }

  def main(): Unit = {
    dom.render(document.body, render)
  }
} 
Example 10
Source File: Main.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.web

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel, JSImport}
import org.scalajs.dom.document

// Initializing bootstrap, like
// https://getbootstrap.com/docs/4.0/getting-started/webpack/#importing-javascript
// but from scala-js, see e.g.
// https://github.com/scalacenter/scalajs-bundler/issues/62#issuecomment-266695471
@js.native
@JSImport("bootstrap", JSImport.Namespace)
object Bootstrap extends js.Object

@js.native
@JSImport("bootstrap-treeview", JSImport.Namespace)
object BootstrapTreeView extends js.Object

@JSExportTopLevel("CoursierWeb")
object Main {
  @JSExport
  def main(args: Array[String]): Unit = {

    println("bootstrap")
    val bootstrap = Bootstrap

    println("bootstrap-treeview")
    val bootstrapTreeView = BootstrapTreeView

    println("Initializing")
    App.app()
      .renderIntoDOM(document.getElementById("demoContent"))
    println("Initialized")
  }
} 
Example 11
Source File: Dom.scala    From scaladex   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package ch.epfl.scala.index.client

import ch.epfl.scala.index.api.SearchRequest
import org.scalajs.dom.raw.{Element, HTMLInputElement}
import org.scalajs.dom.{Node, document}

object Dom {
  def getSearchRequest: Option[SearchRequest] = {
    for (query <- getSearchQuery)
      yield
        SearchRequest(
          query = query,
          you = getElementById("you")
            .map(_.asInput.value)
            .contains("✓"),
          topics = getSearchFilter("topics"),
          targetTypes = getSearchFilter("targetTypes"),
          scalaVersions = getSearchFilter("scalaVersions"),
          scalaJsVersions = getSearchFilter("scalaJsVersions"),
          scalaNativeVersions = getSearchFilter("scalaNativeVersions"),
          sbtVersions = getSearchFilter("sbtVersions"),
          contributingSearch = getElementById("contributing-search")
            .map(_.asInput.value)
            .contains("true")
        )
  }

  def getSearchQuery: Option[String] =
    getSearchInput.map(_.value).filter(_.length > 0)

  def getSearchInput: Option[HTMLInputElement] = getSearchBox.map(_.asInput)

  def getResultList: Option[Element] = getElementById("list-result")

  def getSearchBox: Option[Element] = getElementById("search")

  def getElementById(id: String): Option[Element] =
    Option(document.getElementById(id))

  private def getSearchFilter(name: String) = {
    getElementsByName(name)
      .map(_.asInput)
      .filter(_.checked)
      .map(_.value)
  }

  private def getElementsByName(name: String): Seq[Element] = {
    val nodeList = document.getElementsByName(name)
    0.until(nodeList.length).map(nodeList(_).asElement)
  }

  implicit class ElementOps(e: Element) {
    def asInput: HTMLInputElement = as[HTMLInputElement]
    def as[A <: Element]: A = e.asInstanceOf[A]
  }

  private implicit class NodeOps(n: Node) {
    def asElement: Element = n.asInstanceOf[Element]
  }
} 
Example 12
Source File: CopyModal.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie
package client
package components

import japgolly.scalajs.react._, vdom.all._, extra._

import org.scalajs.dom

import org.scalajs.dom.html
import org.scalajs.dom.{window, document}

final case class CopyModal(title: String, subtitle: String, content: String, modalId: String, isClosed: Boolean, close: Reusable[Callback]) {
  @inline def render: VdomElement =
    new CopyModal.ShareModalComponent().build(this)
}

object CopyModal {

  implicit val reusability: Reusability[CopyModal] =
    Reusability.derive[CopyModal]

  private class ShareModalComponent() {
    private val divRef = Ref[html.Div]

    private def render(props: CopyModal): VdomElement = {
      def copyLink: Callback = divRef.get.map { divRef =>
        val range = dom.document.createRange()
        val selection = dom.window.getSelection()
        range.selectNodeContents(divRef)
        selection.addRange(range)
        if (!document.execCommand("copy")) {
          window.alert("cannot copy link")
        }
      }

      Modal(
        title = props.title,
        isClosed = props.isClosed,
        close = props.close,
        modalCss = TagMod(cls := "modal-share"),
        modalId = props.modalId,
        content = TagMod(
          p(cls := "modal-intro")(
            props.subtitle
          ),
          div(cls := "snippet-link")(
            div.withRef(divRef)(cls := "link-to-copy", onClick --> copyLink)(
              props.content
            ),
            div(onClick --> copyLink, title := "Copy to Clipboard", cls := "snippet-clip clipboard-copy")(
              i(cls := "fa fa-clipboard")
            )
          )
        )
      ).render
    }

    private val component =
      ScalaComponent
        .builder[CopyModal]("CopyModal")
        .render_P(render)
        .configure(Reusability.shouldComponentUpdate)
        .build

    def build(props: CopyModal): VdomElement = component(props)
  }
} 
Example 13
Source File: Main.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package sample

import endpoints4s.algebra.BasicAuthentication.Credentials
import org.scalajs.dom.document
import org.scalajs.dom.AudioContext

import scala.scalajs.js

object Main {

  def main(args: Array[String]): Unit = {
    Api
      .index(("Julien", 30, "foo&bar+baz"))
      .`then`[Unit](
        { user =>
          val p = document.createElement("p")
          p.textContent = s"User(${user.name}, ${user.age})"
          document.body.appendChild(p)
          ()
        },
        js.undefined
      )

    Api
      .action(ActionParameter())
      .`then`[Unit](
        { result =>
          val p = document.createElement("p")
          p.textContent = s"Result = $result"
          document.body.appendChild(p)
          ()
        },
        js.undefined
      )

    Api
      .assets(Api.asset("medias", "chopin--funeral-march.mp3"))
      .`then`[Unit](
        { arrayBuffer =>
          val audioCtx = new AudioContext
          audioCtx.decodeAudioData(arrayBuffer).`then`[Unit] { audioBuffer =>
            val source = audioCtx.createBufferSource()
            source.buffer = audioBuffer
            source.connect(audioCtx.destination)
            source.start()
            source.stop(audioCtx.currentTime + 10)
            ()
          }
        },
        js.undefined
      )

    Api
      .auth(Credentials("foo", "bar"))
      .`then`[Unit](
        { maybeResponse =>
          println(s"Access granted: ${maybeResponse.isDefined}")
        },
        js.undefined
      )
    ()
  }

} 
Example 14
Source File: ContainedModal.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package demo.examples

import com.acework.js.components.bootstrap.Modal.{N, B, S, P}
import com.acework.js.components.bootstrap._
import japgolly.scalajs.react.ReactComponentC.{ReqProps, ConstProps}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom.raw.HTMLElement
import org.scalajs.dom.{Node, document}


object ContainedModal {

  val containerRef: RefSimple[TopNode] = Ref[HTMLElement]("container")

  def containedModel = {
    Modal.Modal(bsStyle = Styles.primary, title = "Contained Modal": ReactNode, animation = true,
      onRequestHide = () => ())(
        <.div(^.className := "modal-body",
          <.h4("Text in a modal"),
          <.p("Elit est explicabo ipsum eaque dolorem blanditiis doloribus sed id ipsam, beatae, rem fuga id earum? Inventore et facilis obcaecati.")
        ),
        <.div(^.className := "modal-footer",
          // FIXME link onClick to onRequestHide
          Button(Button.Button(), "Close"))
      )
  }

  class Backend(val scope: BackendScope[Unit, Unit])

  val trigger = ReactComponentB[Unit]("Trigger")
    .stateless
    .backend(new Backend(_))
    .render((_, _, B) => {

    <.div(^.className := "modal-container", ^.height := 300, ^.ref := containerRef,
      ModalTrigger.ModalTrigger(modal = containedModel,
        container = new ReferencedContainer(containerRef, B.scope))(
          Button(Button.Button(bsStyle = Styles.primary, bsSize = Sizes.lg), "Launch contained modal")
        )
    )
  }).
    buildU

} 
Example 15
Source File: OutwatchSpec.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch

import scala.concurrent.Future
import cats.effect.ContextShift
import cats.effect.IO
import monix.execution.Ack.Continue
import monix.execution.ExecutionModel.SynchronousExecution
import monix.execution.schedulers.TrampolineScheduler
import monix.execution.{Cancelable, Scheduler}
import monix.reactive.Observable
import org.scalajs.dom.{document, window}
import org.scalatest.BeforeAndAfterEach
import org.scalatest._
import outwatch.Deprecated.IgnoreWarnings.initEvent
import org.scalatest.flatspec.{ AnyFlatSpec, AsyncFlatSpec }
import org.scalatest.matchers.should.Matchers

trait EasySubscribe {

  implicit class Subscriber[T](obs: Observable[T]) {
    def apply(next: T => Unit)(implicit s: Scheduler): Cancelable = obs.subscribe { t =>
      next(t)
      Continue
    }
  }
}

// TODO: We need this mock until localStorage is implemented in jsdom (https://github.com/tmpvar/jsdom/pull/2076)
trait LocalStorageMock {
  import scala.collection.mutable
  import scala.scalajs.js


  if (js.isUndefined(window.localStorage)) {
    val storageObject = new js.Object {
      private val map = new mutable.HashMap[String, String]

      def getItem(key: String): String = map.getOrElse(key, null)

      def setItem(key: String, value: String): Unit = {
        map += key -> value
      }

      def removeItem(key: String): Unit = {
        map -= key
      }

      def clear(): Unit = map.clear()
    }

    js.Dynamic.global.window.updateDynamic("localStorage")(storageObject)
  }

  def dispatchStorageEvent(key: String, newValue: String, oldValue: String): Unit = {
    if (key == null) window.localStorage.clear()
    else window.localStorage.setItem(key, newValue)

    val event = document.createEvent("Events")
    initEvent(event)("storage", canBubbleArg = true, cancelableArg = false)
    event.asInstanceOf[js.Dynamic].key = key
    event.asInstanceOf[js.Dynamic].newValue = newValue
    event.asInstanceOf[js.Dynamic].oldValue = oldValue
    event.asInstanceOf[js.Dynamic].storageArea = window.localStorage
    window.dispatchEvent(event)
    ()
  }
}

trait OutwatchSpec extends Matchers with BeforeAndAfterEach with EasySubscribe with LocalStorageMock { self: Suite =>

  implicit val scheduler: TrampolineScheduler = TrampolineScheduler(Scheduler.global, SynchronousExecution)
  implicit val cs: ContextShift[IO] = IO.contextShift(scheduler)

  override def beforeEach(): Unit = {

    document.body.innerHTML = ""

    window.localStorage.clear()

    // prepare body with <div id="app"></div>
    val root = document.createElement("div")
    root.id = "app"
    document.body.appendChild(root)
    ()
  }

}

abstract class JSDomSpec extends AnyFlatSpec with OutwatchSpec {
  implicit def executionContext = scheduler
}
abstract class JSDomAsyncSpec extends AsyncFlatSpec with OutwatchSpec {
  override def executionContext = scheduler

  implicit def ioAssertionToFutureAssertion(io: IO[Assertion]): Future[Assertion] = io.unsafeToFuture()
} 
Example 16
Source File: DomLiteralBenchmark.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch

import outwatch._
import outwatch.dsl._
import monix.execution.ExecutionModel.SynchronousExecution
import monix.execution.schedulers.TrampolineScheduler
import monix.execution.Scheduler

import org.scalajs.dom.{ document, window }
import scala.scalajs.js
import scala.scalajs.js.annotation._
import bench._

object DomLiteralBenchmark extends js.JSApp {
  def main(): Unit = {
    import scala.concurrent.duration._

    bench.util.runComparison(domLiterals, List(1), 60.seconds)
  }

  val domLiterals = Comparison("Dom Literals", Seq(
    BenchmarkWithoutInit(
      "10 literal tags",
      { _ =>
        div(span(), a(), img(), hr(), button(), input(), form(), label(), b(), i())
      }
    ),
    BenchmarkWithoutInit(
      "10 literal attrs",
      { size =>
        div(
          id := "a",
          min := "wo",
          max := "wa",
          src := "x",
          href := "k",
          target := "j",
          value := "jo",
          contentEditable := true,
          name := "hui",
          autoComplete := "true"
        )
      }
    )
  ))

} 
Example 17
Source File: VNodeConstructionBenchmark.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch

import outwatch._
import outwatch.dsl._
import monix.execution.ExecutionModel.SynchronousExecution
import monix.execution.schedulers.TrampolineScheduler
import monix.execution.Scheduler
import outwatch.interpreter.SnabbdomOps

import org.scalajs.dom.{ document, window }
import scala.scalajs.js
import scala.scalajs.js.annotation._
import bench._

object VNodeConstructionBenchmark extends js.JSApp {

  implicit val scheduler: Scheduler = TrampolineScheduler(Scheduler.global, SynchronousExecution)

  def main(): Unit = {
    import scala.concurrent.duration._

    bench.util.runComparison(vnodes, List(1), 60.seconds)
  }

  val vnodes = Comparison("VNode Construction", Seq(
    BenchmarkWithoutInit(
      "10 literal tags",
      { _ =>
        SnabbdomOps.toSnabbdom(div(span(), a(), img(), hr(), button(), input(), form(), label(), b(), i()))
      }
    ),
    BenchmarkWithoutInit(
      "10 literal attrs",
      { size =>
        SnabbdomOps.toSnabbdom(div(
          id := "a",
          min := "wo",
          max := "wa",
          src := "x",
          href := "k",
          target := "j",
          value := "jo",
          contentEditable := true,
          name := "hui",
          autoComplete := "true"
        ))
      }
    )
  ))

} 
Example 18
Source File: Demo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalajs.dom.document
import org.scalajs.dom.raw.Element
import typings.googlemaps.google.maps.{MapOptions, ReadonlyMarkerOptions}
import typings.googlemaps.global.google.maps

object Demo {
  val beaches: Map[String, maps.LatLng] =
    Map(
      "Bondi Beach" -> new maps.LatLng(-33.890542, 151.274856),
      "Coogee Beach" -> new maps.LatLng(-33.923036, 151.259052),
      "Cronulla Beach" -> new maps.LatLng(-34.028249, 151.157507),
      "Manly Beach" -> new maps.LatLng(-33.80010128657071, 151.28747820854187)
    )

  def main(argv: scala.Array[String]): Unit = {
    val container = document.getElementById("content")
    val m: maps.Map[Element] = new maps.Map(
      container,
      MapOptions().setCenter(new maps.LatLng(-33.9, 151.2)).setZoom(4)
    )

    val info = new maps.InfoWindow

    beaches.foreach {
      case (beach, pos) =>
        val marker = new maps.Marker(ReadonlyMarkerOptions().setPosition(pos).setTitle(beach).setMap(m))

        maps.event.addListener(marker, "click", _ => {
          info.setContent(s"<h3>This is $beach </h3>")
          info.open(m, marker)
        })
    }
  }
} 
Example 19
Source File: JQueryDemo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalajs.dom.html.{Button, Label}
import org.scalajs.dom.document
import org.scalajs.dom.raw.Element
import typings.jquery.{JQueryEventObject, JQuery_, mod => $}
import typings.jqueryui.jqueryuiRequire

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|

object JQueryDemo {
  @JSImport("jqueryui/jquery-ui.css", JSImport.Namespace)
  @js.native
  object JqueryUiCss extends js.Object

   JQueryEventObject, scala.Unit] = eo => {
      counter += 1
      $[Label]("#label").text(s"Value is $counter")
    }

    $[Button]("#button")
      .text("bumpit")
      .on("click", renderLabel)

    isJQueryUi($("#accordion")).accordion()
  }
} 
Example 20
Source File: Main.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalajs.dom.{document, html}
import typings.leaflet.{mod => L}

import scala.scalajs.js

object Main {
  val TileLayerUri =
    "https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZmFuY2VsbHUiLCJhIjoiY2oxMHRzZm5zMDAyMDMycndyaTZyYnp6NSJ9.AJ3owakJtFAJaaRuYB7Ukw"

  def main(argv: Array[String]): Unit = {
    val el  = document.getElementById("content").asInstanceOf[html.Element]
    val map = L.map(el).setView(L.LatLngLiteral(51.505, -0.09), zoom = 13)

    L.tileLayer(
        TileLayerUri,
        L.TileLayerOptions()
          .setId("mapbox.streets")
          .setMaxZoom(19)
          .setAttribution(
            """Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,
                        |<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>,
                        |Imagery © <a href="http://mapbox.com">Mapbox</a>""".stripMargin
          )
      )
      .addTo(map)

    L.marker(L.LatLngLiteral(51.5, -0.09), L.MarkerOptions().setTitle("I am a marker"))
      .bindPopup("I am a popup")
      .addTo(map)

    L.circle(
        L.LatLngLiteral(51.508, -0.11),
        L.CircleMarkerOptions().setColor("red").setFillColor("#f03").setFillOpacity(0.5).setRadius(500)
      )
      .bindPopup("I am a circle")
      .addTo(map)

    L.circle(
        L.LatLngLiteral(51.516, -0.11),
        L.CircleMarkerOptions().setColor("green").setFillColor("#f03").setFillOpacity(0.5).setRadius(200)
      )
      .addTo(map)

    L.polygon(js.Array(L.LatLngLiteral(51.509, -0.08), L.LatLngLiteral(51.503, -0.06), L.LatLngLiteral(51.51, -0.047)))
      .bindPopup("I am a polygon")
      .addTo(map)

    L.popup()
      .setLatLng(L.LatLngLiteral(51.5, -0.09))
      .setContent("I am a <b>standalone</b> popup.")
      .openOn(map)
  }
} 
Example 21
Source File: Render.scala    From didactic-computing-machine   with GNU Affero General Public License v3.0 5 votes vote down vote up
package me.benetis.visual

import me.benetis.initial_states.RandomState
import me.benetis.{GameOfLifeRules, LifeState, Point}
import org.scalajs.dom
import org.scalajs.dom.{CanvasRenderingContext2D, document, html}
import scala.util.Random
import zio.clock.Clock
import zio.{IO, Ref, Schedule, Task, UIO, ZIO}
import zio.duration._

object Render {
  case class RenderConfig(scale: Int,
                          blobSize: Int,
                          browserWidth: Double,
                          browserHeight: Double)

  val config =
    RenderConfig(15, 10, dom.window.innerWidth, dom.window.innerHeight)

  val rng = new Random()

  val program: ZIO[Clock, Throwable, Unit] = {
    for {
      renderer <- prepareScreen(config)
      refState <- Ref.make(RandomState.randomCenter(config))
      _ <- (render(renderer, config, refState) *> updateState(refState) *> UIO(
        dom.console.log("tick")
      )).repeat(Schedule.fixed(1.second)).forever
    } yield ()
  }

  private def render(renderer: CanvasRenderingContext2D,
                     config: RenderConfig,
                     ref: Ref[LifeState]): ZIO[Any, Nothing, Unit] = {
    for {
      _ <- clearCanvas(renderer, config)
      state <- ref.get
      _ = state.foreach(p => renderPoint(renderer, config, p))
    } yield ()
  }

  private def updateState(ref: Ref[LifeState]): ZIO[Any, Nothing, Unit] =
    for {
      _ <- ref.update(state => GameOfLifeRules.nextState(state))
    } yield ()

  private def clearCanvas(renderer: CanvasRenderingContext2D,
                          config: RenderConfig): UIO[Unit] = UIO {
    renderer.fillStyle = "black"
    renderer.fillRect(0, 0, config.browserWidth, config.browserHeight)
  }

  private def renderPoint(renderer: CanvasRenderingContext2D,
                          config: RenderConfig,
                          point: Point): Unit = {

    val colors = Vector("red", "yellow")

    val randomColor: String = colors(rng.nextInt(colors.length))
    renderer.fillStyle = randomColor
    renderer.fillRect(
      point.x * config.scale,
      point.y * config.scale,
      config.scale,
      config.scale
    )
  }

  private def prepareScreen(
    config: RenderConfig
  ): UIO[CanvasRenderingContext2D] = UIO {
    val canvas: html.Canvas =
      document.querySelector("#canvas").asInstanceOf[html.Canvas]

    canvas.width = config.browserWidth.toInt
    canvas.height = config.browserHeight.toInt

    val renderer = canvas
      .getContext("2d")
      .asInstanceOf[dom.CanvasRenderingContext2D]

    renderer
  }

} 
Example 22
Source File: DropdownStateMixin.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package com.acework.js.components.bootstrap

import com.acework.js.utils.EventListener
import japgolly.scalajs.react.{BackendScope, ReactEvent}
import org.scalajs.dom.document
import org.scalajs.dom.raw.{KeyboardEvent, Node}


  def isNodeInRoot(node: Node, root: Node): Boolean = {
    var aNode = node
    var done = false
    var result = false
    while (aNode != null && !done) {
      if (aNode == root) {
        done = true
        result = true
      }
      else
        aNode = aNode.parentNode
    }
    result
  }

  def setDropdownState(newState: Boolean, onStateChangeComplete: () => Unit = () => ()) = {
    if (newState)
      bindRootCloseHandlers()
    else
      unBindRootCloseHandlers()

    scope.modState(s => s.copy(open = newState), onStateChangeComplete)
  }

  def bindRootCloseHandlers(): Unit = {
    _onDocumentClickListener = Some(EventListener.listen(document, "click", handleDocumentClick(_: ReactEvent)))
    _onDocumentKeyUpListener = Some(EventListener.listen(document, "keyup", handleDocumentKeyUp(_: KeyboardEvent)))
  }

  def unBindRootCloseHandlers(): Unit = {
    _onDocumentClickListener.map(_.remove())
    _onDocumentClickListener = None
    _onDocumentKeyUpListener.map(_.remove())
    _onDocumentKeyUpListener = None
  }

  def handleDocumentKeyUp(e: KeyboardEvent) = {
    if (e.keyCode == 27)
      setDropdownState(false)
  }

  def handleDocumentClick(e: ReactEvent) = {
    if (!isNodeInRoot(e.target, scope.getDOMNode()))
      setDropdownState(false)
  }

  def onComponentWillUnmount() = unBindRootCloseHandlers()

} 
Example 23
Source File: FadeMixin.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package com.acework.js.components.bootstrap

import japgolly.scalajs.react.{BackendScope, TopNode}
import org.scalajs.dom.raw.HTMLElement
import org.scalajs.dom.{document, raw}

import scala.scalajs.js


trait FadeMixin[P <: OverlayProps, S] {

  def scope: BackendScope[P, S]

  var fadeOutEl: Option[raw.Element] = None

  def getElementAndSelf(root: TopNode, classes: Array[String]): Array[TopNode] = {
    val elements = root.querySelectorAll("." + classes.mkString("."))

    val els = (for (i <- 0 until elements.length) yield elements(i).asInstanceOf[TopNode]).toArray

    var matched = true
    for (i <- 0 until classes.length if matched) {
      val Pattern = "\\b${classes(i)}\\b".r
      root.className match {
        case Pattern() =>
        case _ =>
          matched = false
      }
    }
    if (matched)
      root +: els
    else
      els
  }

  def _fadeIn() = {
    if (scope.isMounted()) {
      val elements = getElementAndSelf(scope.getDOMNode(), Array("fade"))
      elements.foreach { el =>
        val classes = el.className.split(" ").filter(_ != "in") ++ Seq("in")
        el.className = classes.mkString(" ")
      }
    }
  }

  def _fadeOut() = {
    val elements = getElementAndSelf(scope.getDOMNode(), Array("fade", "in"))
    elements.foreach { el =>
      el.className = el.className.replace("\\bin\\b", "")
    }
    js.timers.setTimeout(300)(handleFadeOutEnd())
  }

  def handleFadeOutEnd(): Unit = {
    fadeOutEl.map { fadeout =>
      if (fadeout.parentNode != null)
        fadeout.parentNode.removeChild(fadeout)
    }
  }

  def onComponentDidMount() = {
    // FIXME what does this mean? -- if(document.querySelectorAll)
    //val nodes = document.querySelectorAll("")
    if (true) {
      // Firefox needs delay for transition to be triggered
      js.timers.setTimeout(20)(_fadeIn())
    }
  }

  def onComponentWillUnmount(): Unit = {
    val elements = getElementAndSelf(scope.getDOMNode(), Array("fade"))
    // TODO container
    val container = scope.props.container.getDOMNode
    if (elements.length > 0) {
      val fadeOut = document.createElement("div")
      container.appendChild(fadeOut)
      fadeOut.appendChild(scope.getDOMNode().cloneNode(deep = true))
      fadeOutEl = Some(fadeOut)
      js.timers.setTimeout(20)(_fadeOut())
    }
  }
} 
Example 24
Source File: OverlayMixin.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package com.acework.js.components.bootstrap

import japgolly.scalajs.react._
import org.scalajs.dom.raw.HTMLElement
import org.scalajs.dom.{Node, document}




trait OverlayContainer {
  // Provide `getDOMNode` fn mocking a React component API. The `document.body`
  // reference needs to be contained within this function so that it is not accessed
  // in environments where it would not be defined, e.g. nodejs. Equally this is needed
  // before the body is defined where `document.body === null`, this ensures
  // `document.body` is only accessed after componentDidMount.
  def getDOMNode: HTMLElement = document.body
}

class ReferencedContainer[P, S](ref: RefSimple[TopNode], scope: BackendScope[P, S]) extends OverlayContainer {
  override def getDOMNode = {
    val refNode = ref(scope)
    if (refNode != null)
      refNode.get.getDOMNode()
    else
      super.getDOMNode
  }
}

trait OverlayProps {
  val container: OverlayContainer
}

trait OverlayMixin[P <: OverlayProps, S] {

  val scope: BackendScope[P, S]

  var _overlayTarget: Option[Node] = None
  var _overlayInstance: Option[ReactComponentM_[TopNode]] = None

  def onComponentWillUnmount() = {
    _unrenderOverlay()
    _overlayTarget match {
      case Some(target) =>
        getContainerDOMNode.removeChild(target)
        _overlayTarget = None
      case None =>
    }
  }

  def onComponentDidUpdate() = {
    _renderOverlay()
  }

  def onComponentDidMount() = {
    _renderOverlay()
  }

  def _renderOverlay() = {
    _overlayTarget match {
      case None =>
        _mountOverlayTarget()
      case Some(_) =>
    }

    renderOverlay() match {
      case Some(overlay) =>
        _overlayInstance = Some(React.render(overlay, _overlayTarget.get))
      case None =>
        // unreder if the componet is null or transitions to null
        _unrenderOverlay()
    }
  }

  def _unrenderOverlay() = {
    _overlayTarget map { target =>
      React.unmountComponentAtNode(target)
      _overlayTarget = None
    }
  }

  def _mountOverlayTarget() = {
    _overlayTarget = Some(document.createElement("div"))
    getContainerDOMNode.appendChild(_overlayTarget.get)
  }

  def getOverlayDOMNode: Option[TopNode] = {
    var node: Option[TopNode] = None
    if (scope.isMounted()) {
      if (_overlayInstance.isDefined)
        node = Some(_overlayInstance.get.getDOMNode())
    }
    node
  }

  def getContainerDOMNode: HTMLElement = {
    scope.props.container.getDOMNode
  }

  def renderOverlay(): Option[ReactElement]

} 
Example 25
Source File: CodeContent.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package demo.examples.util

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._

import org.scalajs.dom.document
import org.scalajs.dom.ext.PimpedNodeList


object CodeContent {

  case class Content(scalaSource: String, el: ReactNode, exampleClasses: String = "") {
    def apply() = component(this)
  }

  case class State(showCode: Boolean = false)

  class Backend(scope: BackendScope[Content, State]) {

    def toggleCodeMode(e: ReactEvent) = {
      e.preventDefault()
      scope.modState(s => s.copy(showCode = !s.showCode))
    }
  }

  def installSyntaxHighlighting[P, S, B] =
    (_: ReactComponentB[P, S, B])
      .componentDidMount(_ => applySyntaxHighlight())
      .componentDidUpdate((_, _, _) => applySyntaxHighlight())


  def applySyntaxHighlight() = {
    import scala.scalajs.js.Dynamic.{global => g}
    val nodeList = document.querySelectorAll("pre code").toArray
    nodeList.foreach(n => g.hljs.highlightBlock(n))
  }

  val component = ReactComponentB[Content]("CodeContent")
    .initialState(State())
    .backend(new Backend(_))
    .render((P, C, S, B) => {
    <.div(^.className := "playground",
      <.div(^.className := s"bs-example ${P.exampleClasses}",
        <.div(P.el)),
      if (S.showCode)
        <.div(
          <.pre(<.code(P.scalaSource.trim)),
          <.a(^.className := "code-toggle", ^.onClick ==> B.toggleCodeMode, ^.href := "#", "Hide code")
        )
      else
        <.a(^.className := "code-toggle", ^.onClick ==> B.toggleCodeMode, ^.href := "#", "Show code")

    )
  }).configure(installSyntaxHighlighting)
    .build
}