org.scalajs.dom Scala Examples

The following examples show how to use org.scalajs.dom. 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: TodosUIEntry.scala    From suzaku   with Apache License 2.0 6 votes vote down vote up
package todos

import org.scalajs.dom
import org.scalajs.dom.raw.Worker
import suzaku.platform.web.{WebWorkerTransport, WorkerClientTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("TodosUIEntry")
object TodosUIEntry {
  var transport: WebWorkerTransport = _

  @JSExport
  def entry(workerScript: String): Unit = {
    // create the worker to run our application in
    val worker = new Worker(workerScript)

    // create the transport
    transport = new WorkerClientTransport(worker)

    // listen to messages from worker
    worker.onmessage = onMessage _

    new TodosUI(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 2
Source File: GeoLocationExample.scala    From scalajs-react-native   with Apache License 2.0 5 votes vote down vote up
package chandu0101.scalajs.rn.examples.uiexplorer.apis

import chandu0101.scalajs.rn.ReactNativeComponentB
import chandu0101.scalajs.rn.components.{Text, View}
import chandu0101.scalajs.rn.examples.uiexplorer.{UIExample, UIExplorerBlock, UIExplorerPage}
import japgolly.scalajs.react.BackendScope
import chandu0101.scalajs.rn.styles.NativeStyleSheet
import org.scalajs.dom
import org.scalajs.dom.raw.{Position, PositionError}

import scala.scalajs.js.JSON


object GeoLocationExample extends UIExample {

  case class State(initialPoistion : Position = null,lastPosition : Position = null )

  class Backend(t: BackendScope[_, State]) {

    var watchID : Int = 0

  }

  val component = ReactNativeComponentB[Unit]("GeoLocationExample")
    .initialState(State())
    .backend(new Backend(_))
    .render((P,S,B) => {
      UIExplorerPage(
       UIExplorerBlock("navigator.geolocation")(
         View()(
           Text()(
             Text(style = styles.title)("Initial Position : "),
             JSON.stringify(S.initialPoistion)
           ),
           Text()(
             Text(style = styles.title)("Current Position : "),
             JSON.stringify(S.lastPosition)
           )
         )
       )
      )
    })
    .componentDidMount(scope => {
      dom.window.navigator.geolocation.getCurrentPosition((pos : Position) => {
        scope.modState(_.copy(initialPoistion = pos))
      },(error : PositionError) => println(s"Error getting geo data ${error}"))
     scope.backend.watchID = dom.window.navigator.geolocation.watchPosition(
       (pos : Position) => scope.modState(_.copy(lastPosition = pos))
     )
    })
    .componentWillMount(scope => {
      dom.window.navigator.geolocation.clearWatch(scope.backend.watchID)
    })
    .buildNative

  object styles extends NativeStyleSheet {
  val title = style(fontWeight._500)

  }

  override def title: String = "Geolocation"

  override def description: String = "Examples of using the Geolocation API."
} 
Example 3
Source File: BossSelectMenu.scala    From gbf-raidfinder   with MIT License 5 votes vote down vote up
package walfie.gbf.raidfinder.client.views

import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.scalajs.js
import walfie.gbf.raidfinder.client._
import walfie.gbf.raidfinder.client.ViewModel._
import walfie.gbf.raidfinder.client.syntax.{ElementOps, EventOps, HTMLElementOps, StringOps}
import walfie.gbf.raidfinder.protocol._

object BossSelectMenu {
  @binding.dom
  def content(
    client:       RaidFinderClient,
    closeModal:   Event => Unit,
    currentTab:   Binding[DialogTab],
    imageQuality: Binding[ImageQuality]
  ): Binding[Element] = {
    val isFollowing = client.state.followedBossNames
    val bossListElement = bossList(client, imageQuality).bind

    // TODO: Write a more generic event delegation helper
    bossListElement.addEventListener("click", { e: Event =>
      for {
        target <- e.targetElement
        element <- target.findParent(_.classList.contains("gbfrf-js-bossSelect"))
        bossName <- Option(element.getAttribute("data-bossName"))
      } yield client.toggleFollow(bossName)
    })

    <section lang="ja" id="gbfrf-dialog__follow" class={
      val isActive = currentTab.bind == DialogTab.Follow
      "gbfrf-dialog__content mdl-layout__tab-panel".addIf(isActive, "is-active")
    }>
      { bossListElement }
    </section>
  }

  @binding.dom
  def bossList(client: RaidFinderClient, imageQuality: Binding[ImageQuality]): Binding[HTMLUListElement] = {
    <ul class="mdl-list" style="padding: 0; margin: 0;">
      {
        for {
          bossColumn <- client.state.allBosses
          boss = bossColumn.raidBoss
          isFollowing = Binding { client.state.followedBossNames.bind(boss.bind.name) }

          // Only show Japanese bosses unless there is no translation
          // TODO: This is kinda hacky, maybe think of a better way
          if (boss.bind.language == Language.JAPANESE || boss.bind.translatedName.isEmpty || isFollowing.bind)
        } yield bossListItem(boss, isFollowing, imageQuality).bind
      }
    </ul>
  }

  @binding.dom
  def bossListItem(
    boss: Binding[RaidBoss], isFollowing: Binding[Boolean], imageQuality: Binding[ImageQuality]
  ): Binding[HTMLLIElement] = {
    val elem =
      <li class={
        "gbfrf-js-bossSelect gbfrf-follow__boss-box mdl-list__item".addIf(
          imageQuality.bind != ImageQuality.Off,
          "gbfrf-follow__boss-box--with-image mdl-shadow--2dp"
        ).addIf(boss.bind.translatedName.nonEmpty, "mdl-list__item--two-line")
      } data:data-bossName={ boss.bind.name }>
        <span class="mdl-list__item-primary-content">
          <span>{ boss.bind.name }</span>
          {
            boss.bind.translatedName match {
              case Some(translatedName) => Constants(
                <span class="gbfrf-follow__boss-box-subtitle mdl-list__item-sub-title">{ translatedName }</span>
              )
              case None => Constants()
            }
          }
        </span>
        <div class="mdl-layout-spacer"></div>
        {
          if (isFollowing.bind) Constants(<div class="mdl-badge mdl-badge--overlap" data:data-badge="★"></div>)
          else Constants()
        }
      </li>

    elem.backgroundImageQuality(boss.bind.image, 0.25, imageQuality.bind)
  }
} 
Example 4
Source File: MainDialog.scala    From gbf-raidfinder   with MIT License 5 votes vote down vote up
package walfie.gbf.raidfinder.client.views

import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.scalajs.js
import walfie.gbf.raidfinder.client._
import walfie.gbf.raidfinder.client.syntax.{ElementOps, EventOps, HTMLElementOps, StringOps}
import walfie.gbf.raidfinder.client.ViewModel._
import walfie.gbf.raidfinder.protocol._

object MainDialog {
  @binding.dom
  def element(client: RaidFinderClient, viewState: ViewModel.State): Binding[HTMLElement] = {
    val dialog = dom.document.createElement("dialog").asInstanceOf[HTMLElement]
    dialog.classList.add("mdl-dialog")
    dialog.classList.add("gbfrf-dialog")
    val dynamicDialog = dialog.asInstanceOf[js.Dynamic]

    if (js.isUndefined(dynamicDialog.showModal)) {
      js.Dynamic.global.dialogPolyfill.registerDialog(dialog)
    }

    val closeModal = { (e: Event) => dynamicDialog.close(); () }
    val reloadBosses = { (e: Event) => client.resetBossList() }

    val onTabChange = () => ViewModel.persistState(viewState)

    val currentTab = viewState.currentTab

    val inner =
      <div class="gbfrf-main-dialog gbfrf-dialog__container mdl-layout mdl-js-layout mdl-layout--fixed-header mdl-layout--fixed-tabs">
        { dialogHeader(viewState.currentTab, onClose = closeModal, onTabChange = onTabChange).bind }
        { BossSelectMenu.content(client, closeModal, currentTab, viewState.imageQuality).bind }
        { SettingsMenu.content(client, viewState).bind }
        <hr style="margin: 0;"/>
        { dialogFooter(viewState.currentTab, closeModal = closeModal, reloadBosses = reloadBosses).bind }
      </div>

    dialog.appendChild(inner)
    dialog.mdl
  }

  @binding.dom
  def dialogHeader(currentTab: Var[ViewModel.DialogTab], onClose: Event => Unit, onTabChange: () => Unit): Binding[HTMLElement] = {
    <header class="mdl-layout__header">
      <div class="mdl-layout__header-row gbfrf-column__header-row">
        {
          Constants(DialogTab.all: _*).map { tab =>
            val classList = "gbfrf-dialog__tab-bar-item mdl-layout__tab".addIf(currentTab.bind == tab, "is-active")
            val onClick = { (e: Event) => currentTab := tab; onTabChange() }
            <div class={ classList } onclick={ onClick }>{ tab.label }</div>
          }
        }
        <div class="mdl-layout-spacer"></div>
        <div class="mdl-button mdl-js-button mdl-button--icon material-icons js-close-dialog" onclick={ onClose }>
          <i class="material-icons">clear</i>
        </div>
      </div>
    </header>
  }

  @binding.dom
  def dialogFooter(
    currentTab:   Binding[ViewModel.DialogTab],
    closeModal:   Event => Unit,
    reloadBosses: Event => Unit
  ): Binding[HTMLDivElement] = {
    <div class="mdl-dialog__actions">
      <button type="button" class="mdl-button gbfrf-dialog__button" onclick={ closeModal }>Close</button>
      <button type="button" class={
        "gbfrf-dialog__button mdl-button".addIf(currentTab.bind != DialogTab.Follow, "is-hidden")
      } onclick={ reloadBosses }>
        <i class="material-icons">refresh</i>
        Reload Bosses
      </button>
    </div>
  }

} 
Example 5
Source File: package.scala    From gbf-raidfinder   with MIT License 5 votes vote down vote up
package walfie.gbf.raidfinder.client

import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.collection.mutable.Buffer
import scala.scalajs.js
import walfie.gbf.raidfinder.client.ViewModel.ImageQuality
import walfie.gbf.raidfinder.protocol._

import js.Dynamic.global

package object syntax {
  implicit class HTMLElementOps[T <: HTMLElement](val elem: T) extends AnyVal {
    
    def :=(elements: TraversableOnce[T]): Buffer[T] = {
      buffer.clear()
      buffer ++= elements
    }
  }

  implicit class StringOps(val string: String) extends AnyVal {
    def addIf(condition: Boolean, s: String): String =
      if (condition) s"$string $s" else string
  }

  implicit class LanguageOps(val language: Language) extends AnyVal {
    def shortName: Option[String] = language match {
      case Language.JAPANESE => Some("JP")
      case Language.ENGLISH => Some("EN")
      case _ => None
    }
  }
} 
Example 6
Source File: Application.scala    From gbf-raidfinder   with MIT License 5 votes vote down vote up
package walfie.gbf.raidfinder.client

import com.momentjs.Moment
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom
import org.scalajs.dom.raw._
import scala.scalajs.js
import scala.scalajs.js.annotation._
import walfie.gbf.raidfinder.client.util.time._
import walfie.gbf.raidfinder.client.ViewModel.TimeFormat
import walfie.gbf.raidfinder.protocol._

@JSExport("GbfRaidFinder")
object Application {
  @JSExport
  def init(url: String): Unit = {
    val maxReconnectInterval = Duration.seconds(10)

    val websocket = new BinaryProtobufWebSocketClient(url, maxReconnectInterval)

    val client: RaidFinderClient = new WebSocketRaidFinderClient(
      websocket, dom.window.localStorage, SystemClock
    )

    Moment.defineLocale("en-short", MomentShortLocale)

    val notification = new views.SnackbarNotification

    val viewState = ViewModel.loadState()

    // Update currentTime every 30 seconds
    val currentTime: Var[Double] = Var(js.Date.now())
    js.timers.setInterval(Duration.seconds(30).milliseconds) {
      client.truncateColumns(50)
      currentTime := js.Date.now()
    }

    val div = dom.document.createElement("div")
    div.classList.add("gbfrf-container")
    val mainContent = views.MainContent.mainContent(
      client, ViewModel.loadState(), notification, currentTime, client.isConnected
    )

    binding.dom.render(div, mainContent)
    dom.document.body.appendChild(div)
  }
} 
Example 7
Source File: Main.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.example.e2e.websocket

import java.io.IOException

import io.github.shogowada.scala.jsonrpc.JSONRPCServerAndClient
import io.github.shogowada.scala.jsonrpc.Types.JSONSender
import io.github.shogowada.scala.jsonrpc.client.JSONRPCClient
import io.github.shogowada.scala.jsonrpc.serializers.UpickleJSONSerializer
import io.github.shogowada.scala.jsonrpc.server.JSONRPCServer
import io.github.shogowada.scalajs.reactjs.ReactDOM
import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import org.scalajs.dom
import org.scalajs.dom.WebSocket

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.scalajs.js.JSApp
import scala.util.{Failure, Try}

object Main extends JSApp {
  override def main(): Unit = {
    val futureWebSocket = createFutureWebSocket()
    val serverAndClient = createServerAndClient(futureWebSocket)

    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render(
      <((new TodoListView(serverAndClient.createAPI[TodoRepositoryAPI])) ()).empty,
      mountNode
    )
  }

  private def createFutureWebSocket(): Future[WebSocket] = {
    val promisedWebSocket: Promise[WebSocket] = Promise()
    val webSocket = new dom.WebSocket(webSocketUrl)

    webSocket.onopen = (_: dom.Event) => {
      promisedWebSocket.success(webSocket)
    }

    webSocket.onerror = (event: dom.Event) => {
      promisedWebSocket.failure(new IOException(event.toString))
    }

    promisedWebSocket.future
  }

  private def webSocketUrl: String = {
    val location = dom.window.location
    val protocol = location.protocol match {
      case "http:" => "ws:"
      case "https:" => "wss:"
    }
    s"$protocol//${location.host}/jsonrpc"
  }

  private def createServerAndClient(futureWebSocket: Future[WebSocket]): JSONRPCServerAndClient[UpickleJSONSerializer] = {
    val jsonSerializer = UpickleJSONSerializer()

    val server = JSONRPCServer(jsonSerializer)

    val jsonSender: JSONSender = (json: String) => {
      futureWebSocket
          .map(webSocket => Try(webSocket.send(json)))
          .flatMap(tried => tried.fold(
            throwable => Future.failed(throwable),
            _ => Future(None)
          ))
    }
    val client = JSONRPCClient(jsonSerializer, jsonSender)

    val serverAndClient = JSONRPCServerAndClient(server, client)

    futureWebSocket.foreach(webSocket => {
      webSocket.onmessage = (event: dom.MessageEvent) => {
        val message = event.data.toString
        serverAndClient.receiveAndSend(message).onComplete {
          case Failure(throwable) => {
            println("Failed to send response", throwable)
          }
          case _ =>
        }
      }
    })

    serverAndClient
  }
} 
Example 8
Source File: Main.scala    From scala-json-rpc   with MIT License 5 votes vote down vote up
package io.github.shogowada.scala.jsonrpc.example.e2e

import io.github.shogowada.scala.jsonrpc.client.JSONRPCClient
import io.github.shogowada.scala.jsonrpc.serializers.CirceJSONSerializer
import io.github.shogowada.scalajs.reactjs.ReactDOM
import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.elements.ReactElement
import org.scalajs.dom

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js.JSApp

class App(
    calculatorAPI: CalculatorAPI,
    echoAPI: EchoAPI,
    loggerAPI: LoggerAPI
) {
  def apply(): ReactElement =
    <.div()(
      <((new Calculator(calculatorAPI)) ()).empty,
      <((new Echo(echoAPI)) ()).empty,
      <((new Logger(loggerAPI)) ()).empty
    )
}

object Main extends JSApp {
  override def main(): Unit = {
    val jsonSender: (String) => Future[Option[String]] =
      (json: String) => {
        val NoContentStatus = 204
        dom.ext.Ajax
            .post(url = "/jsonrpc", data = json)
            .map(response => {
              if (response.status == NoContentStatus) {
                None
              } else {
                Option(response.responseText)
              }
            })
      }

    val client = JSONRPCClient(CirceJSONSerializer(), jsonSender)

    val calculatorAPI = client.createAPI[CalculatorAPI]
    val echoAPI = client.createAPI[EchoAPI]
    val loggerAPI = client.createAPI[LoggerAPI]

    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render((new App(calculatorAPI, echoAPI, loggerAPI)) (), mountNode)
  }
} 
Example 9
Source File: ReactApp.scala    From scalajs-react-bootstrap   with MIT License 5 votes vote down vote up
package demo



import com.acework.js.components.bootstrap.Nav.Nav
import com.acework.js.components.bootstrap.NavBar.NavBar
import demo.pages.Components
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import org.scalajs.dom
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport

object ReactApp extends JSApp {

  case class State(index: Int)

  class Backend(scope: BackendScope[_, State]) {
    def onMenuClick(newIndex: Int) = scope.modState(_.copy(index = newIndex))
  }

  val navMenu = ReactComponentB[(List[String], Backend)]("appMenu")
    .render(P => {
    val (data, backend) = P
    def element(name: String, index: Int) =
      <.li(^.cls := "navbar-brand", ^.onClick --> backend.onMenuClick(index), name)

    NavBar(componentClass = "header", staticTop = true, addClasses = "bs-docs-nav", role = "banner", toggleNavKey = "0")(
      Nav(addClasses = "bs-navbar-collapse", role = "navigation", eventKey = "0", id = "top")(
        data.zipWithIndex.map { case (name, index) => element(name, index)}
      )
    )
  }).build

  val container = ReactComponentB[String]("appMenu")
    .render(P => {
    <.div(^.cls := "container",
      P match {
        case "Home" => <.div("home")
        case "Components" => Components.content()
        case "Getting Started" => <.div("Getting started")
      }
    )
  }).build

  val app = ReactComponentB[List[String]]("app")
    .initialState(State(0))
    .backend(new Backend(_))
    .render((P, S, B) => {
    <.div(
      navMenu((P, B)),
      container(P(S.index))
    )

  }).build

  @JSExport
  override def main(): Unit =
    app(List("Home", "Getting Started", "Components")) render dom.document.body

} 
Example 10
Source File: RandomState.scala    From didactic-computing-machine   with GNU Affero General Public License v3.0 5 votes vote down vote up
package me.benetis.initial_states

import me.benetis.visual.Render.RenderConfig
import me.benetis.{LifeState, Point}
import org.scalajs.dom

object RandomState {

  def randomCenter(renderConfig: RenderConfig): LifeState = {

    val maxX: Int = (renderConfig.browserWidth / renderConfig.scale).round.toInt
    val maxY: Int =
      (renderConfig.browserHeight / renderConfig.scale).round.toInt

    val columns = Range.inclusive(
      (maxX / 2) - renderConfig.blobSize,
      (maxX / 2) + renderConfig.blobSize
    )
    val rows = Range.inclusive(
      (maxY / 2) - renderConfig.blobSize,
      (maxY / 2) + renderConfig.blobSize
    )

    randomState(rows = rows, columns = columns)

  }

  private def randomState(rows: Range, columns: Range): LifeState = {
    rows.flatMap(i => columns.map(j => Point(j, i))).toSet
  }

} 
Example 11
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 12
Source File: Demo.scala    From Demos   with MIT License 5 votes vote down vote up
package demo

import org.scalajs.dom
import typings.highlightJs.mod.initHighlightingOnLoad
import typings.reveal.{RevealOptions, RevealStatic}

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

object Demo {
  def main(args: Array[String]): Unit = {
    // Touch to load
    Includes.HighlightingCss
    Includes.WhiteThemeCss
    Includes.RevealCss
    Includes.Reveal
    Includes.ZoomJs

    
  @JSImport("reveal.js/js/reveal.js", JSImport.Namespace)
  @js.native
  object Reveal extends RevealStatic

  @JSImport("reveal.js/plugin/zoom-js/zoom.js", JSImport.Namespace)
  @js.native
  object ZoomJs extends RevealStatic

  @JSImport("reveal.js/lib/css/zenburn.css", JSImport.Namespace)
  @js.native
  object HighlightingCss extends js.Object

  @JSImport("reveal.js/css/theme/white.css", JSImport.Namespace)
  @js.native
  object WhiteThemeCss extends js.Object

  @JSImport("reveal.js/css/reveal.css", JSImport.Namespace)
  @js.native
  object RevealCss extends js.Object
} 
Example 13
Source File: TodosAppEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package todos

import org.scalajs.dom
import org.scalajs.dom.raw.DedicatedWorkerGlobalScope
import suzaku.platform.web.{WebWorkerTransport, WorkerTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("TodosAppEntry")
object TodosAppEntry {
  import DedicatedWorkerGlobalScope.self

  var transport: WebWorkerTransport = _

  @JSExport
  def entry(): Unit = {
    // create transport
    transport = new WorkerTransport(self)
    // receive WebWorker messages
    self.onmessage = onMessage _
    // create the actual application
    val app = new TodosApp(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 14
Source File: WebDemoAppEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package webdemo

import org.scalajs.dom
import org.scalajs.dom.raw.DedicatedWorkerGlobalScope
import suzaku.platform.web.{WebWorkerTransport, WorkerTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("WebDemoAppEntry")
object WebDemoAppEntry {
  import DedicatedWorkerGlobalScope.self

  var transport: WebWorkerTransport = _

  @JSExport
  def entry(): Unit = {
    // create transport
    transport = new WorkerTransport(self)
    // receive WebWorker messages
    self.onmessage = onMessage _
    // create the actual application
    val app = new WebDemoApp(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 15
Source File: WebDemoUIEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package webdemo

import org.scalajs.dom
import org.scalajs.dom.raw.Worker
import suzaku.platform.web.{WebWorkerTransport, WorkerClientTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("WebDemoUIEntry")
object WebDemoUIEntry {
  var transport: WebWorkerTransport = _

  @JSExport
  def entry(workerScript: String): Unit = {
    // create the worker to run our application in
    val worker = new Worker(workerScript)

    // create the transport
    transport = new WorkerClientTransport(worker)

    // listen to messages from worker
    worker.onmessage = onMessage _

    new WebDemoUI(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 16
Source File: PerfUIEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package perftest

import org.scalajs.dom
import org.scalajs.dom.raw.Worker
import suzaku.platform.web.{WebWorkerTransport, WorkerClientTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("PerfUIEntry")
object PerfUIEntry {
  var transport: WebWorkerTransport = _

  @JSExport
  def entry(workerScript: String): Unit = {
    // create the worker to run our application in
    val worker = new Worker(workerScript)

    // create the transport
    transport = new WorkerClientTransport(worker)

    // listen to messages from worker
    worker.onmessage = onMessage _

    new PerfUI(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 17
Source File: PerfAppEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package perftest

import org.scalajs.dom
import org.scalajs.dom.raw.DedicatedWorkerGlobalScope
import suzaku.platform.web.{WebWorkerTransport, WorkerTransport}

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.typedarray.ArrayBuffer

@JSExportTopLevel("PerfAppEntry")
object PerfAppEntry {
  import DedicatedWorkerGlobalScope.self

  var transport: WebWorkerTransport = _

  @JSExport
  def entry(): Unit = {
    // create transport
    transport = new WorkerTransport(self)
    // receive WebWorker messages
    self.onmessage = onMessage _
    // create the actual application
    val app = new PerfApp(transport)
  }

  private def debugPrint(data: Array[Byte]): Unit = {
    data.grouped(16).foreach { d =>
      val hex = d.map(c => "%02X " format (c & 0xFF)).mkString
      val str = d
        .collect {
          case ascii if ascii >= 0x20 && ascii < 0x80 => ascii
          case _                                      => '.'.toByte
        }
        .map(_.toChar)
        .mkString
      println(hex.padTo(16 * 3, ' ') + str)
    }
  }

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 18
Source File: AppEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web

import org.scalajs.dom
import org.scalajs.dom.raw.DedicatedWorkerGlobalScope
import suzaku.platform.Transport

import scala.scalajs.js.typedarray.ArrayBuffer

abstract class AppEntry {
  import DedicatedWorkerGlobalScope.self

  private var transport: WebWorkerTransport = _

  def main(args: Array[String]): Unit = {
    // create transport
    transport = new WorkerTransport(self)
    // receive WebWorker messages
    self.onmessage = onMessage _
    // create the actual application
    start(transport)
  }

  def start(transport: Transport): Any

  private def onMessage(msg: dom.MessageEvent): Unit = {
    msg.data match {
      case buffer: ArrayBuffer =>
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 19
Source File: DOMTextField.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web.widget

import org.scalajs.dom
import suzaku.platform.web._
import suzaku.ui.WidgetBuilder
import suzaku.ui.style.Palette
import suzaku.widget.TextFieldProtocol

class DOMTextField(widgetId: Int, context: TextFieldProtocol.ChannelContext)(implicit uiManager: DOMUIManager)
    extends DOMWidget[TextFieldProtocol.type, dom.html.Input](widgetId, uiManager) {
  import TextFieldProtocol._

  val artifact = {
    val el = tag[dom.html.Input]("input")
    uiManager.addListener(ChangeEvent)(widgetId, el, onChange)
    el.setAttribute("type", "text")
    el.value = context.initialValue
    DOMWidgetArtifact(el)
  }

  override protected def baseStyleClasses = List(DOMTextField.style.base)

  private def onChange(e: DOMEvent[ChangeEvent.Event]): Unit = {
    channel.send(ValueChanged(artifact.el.value))
  }

  override def process = {
    case SetValue(text) =>
      modifyDOM { node =>
        // save cursor/selection
        val start = node.selectionStart
        val end   = node.selectionEnd
        node.value = text
        // restore
        node.setSelectionRange(start, end)
      }
    case msg =>
      super.process(msg)
  }

}

class DOMTextFieldBuilder(widgetManager: DOMUIManager) extends WidgetBuilder(TextFieldProtocol) {
  import TextFieldProtocol._

  override protected def create(widgetId: Int, context: ChannelContext) =
    new DOMTextField(widgetId, context)(widgetManager)
}

object DOMTextField extends WidgetStyleProvider {
  class Style(uiManager: DOMUIManager) extends WidgetStyle()(uiManager) {
    import DOMWidget._

    val base = uiManager.registerCSSClass(palette => s"""
        |width: 100%;
        |height: ${show(styleConfig.inputHeight)};
        |line-height: ${show(styleConfig.inputHeight)};
        |border: solid ${show(styleConfig.inputBorderWidth)} ${show(styleConfig.inputBorderColor)};
        |border-radius: ${show(styleConfig.inputBorderRadius)};
        |padding-left: 0.5rem;
        |padding-right: 0.5rem;
        |color: ${show(palette(Palette.Base).color.foregroundColor)};
        |background-color: ${show(palette(Palette.Base).color.backgroundColor)};
        |font-family: ${styleConfig.fontFamily};
        |font-size: ${show(styleConfig.fontSize)};
        |font-weight: ${show(styleConfig.fontWeight)};
        """.stripMargin)
  }

  override def buildStyle(implicit uiManager: DOMUIManager) = new Style(uiManager)
} 
Example 20
Source File: DOMText.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web.widget

import org.scalajs.dom
import suzaku.platform.web.{DOMUIManager, DOMWidget, DOMWidgetArtifact}
import suzaku.ui.WidgetBuilder
import suzaku.widget.TextProtocol

class DOMText(widgetId: Int, context: TextProtocol.ChannelContext, widgetManager: DOMUIManager)
    extends DOMWidget[TextProtocol.type, dom.html.Span](widgetId, widgetManager) {
  import TextProtocol._

  val innerText = textNode(context.text)

  val artifact = {
    val span = dom.document.createElement("span").asInstanceOf[dom.html.Span]
    span.appendChild(innerText)
    DOMWidgetArtifact(span)
  }

  override def process = {
    case SetText(text) =>
      modifyDOM(_ => innerText.data = text)
    case msg =>
      super.process(msg)
  }
}

class DOMTextBuilder(widgetManager: DOMUIManager) extends WidgetBuilder(TextProtocol) {
  import TextProtocol._

  override protected def create(widgetId: Int, context: ChannelContext) =
    new DOMText(widgetId, context, widgetManager)
} 
Example 21
Source File: DOMCheckbox.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web.widget

import org.scalajs.dom
import suzaku.platform.web.{DOMUIManager, DOMWidget, DOMWidgetArtifact}
import suzaku.ui.WidgetBuilder
import suzaku.widget.CheckboxProtocol

class DOMCheckbox(widgetId: Int, context: CheckboxProtocol.ChannelContext)(implicit uiManager: DOMUIManager)
    extends DOMWidget[CheckboxProtocol.type, dom.html.Label](widgetId, uiManager) {
  import CheckboxProtocol._

  val input     = tag[dom.html.Input]("input")
  val labelText = textNode(context.label.getOrElse(""))

  val artifact = {
    val el = tag[dom.html.Label]("label")
    input.addEventListener("click", onChange _)
    input.setAttribute("type", "checkbox")
    input.checked = context.checked
    el.appendChild(input)
    el.appendChild(labelText)
    DOMWidgetArtifact(el)
  }

  override protected def baseStyleClasses = List(DOMCheckbox.style.base)

  def onChange(e: dom.Event): Unit = {
    channel.send(ValueChanged(input.checked))
  }

  override def process = {
    case SetValue(checked) =>
      modifyDOM(_ => input.checked = checked)
    case SetLabel(label) =>
      modifyDOM(_ => labelText.data = label.getOrElse(""))
    case msg =>
      super.process(msg)
  }
}

class DOMCheckboxBuilder(widgetManager: DOMUIManager) extends WidgetBuilder(CheckboxProtocol) {
  import CheckboxProtocol._

  override protected def create(widgetId: Int, context: ChannelContext) =
    new DOMCheckbox(widgetId, context)(widgetManager)
}

object DOMCheckbox extends WidgetStyleProvider {
  class Style(uiManager: DOMUIManager) extends WidgetStyle()(uiManager) {
    val base = uiManager.registerCSSClass(palette => s"""
         |display: inline-block;
         |margin-bottom: .25rem;
        """.stripMargin)
  }

  override def buildStyle(implicit uiManager: DOMUIManager) = new Style(uiManager)
} 
Example 22
Source File: DOMButton.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web.widget

import org.scalajs.dom
import suzaku.platform.web._
import suzaku.ui.WidgetBuilder
import suzaku.ui.style.Palette
import suzaku.widget.ButtonProtocol

class DOMButton(widgetId: Int, context: ButtonProtocol.ChannelContext)(implicit uiManager: DOMUIManager)
    extends DOMWidget[ButtonProtocol.type, dom.html.Button](widgetId, uiManager) {
  import ButtonProtocol._

  val labelNode = textNode(context.label)
  val iconNode  = context.icon.map(image => imageNode(image, Some("1em"), Some("1em"), Some("currentColor")))

  val artifact = {
    val el = tag[dom.html.Button]("button")
    uiManager.addListener(ClickEvent)(widgetId, el, onClick)

    el.appendChild(labelNode)
    iconNode.foreach(el.appendChild)

    DOMWidgetArtifact(el)
  }

  override protected def baseStyleClasses = List(DOMButton.style.base)

  def onClick(e: DOMEvent[dom.MouseEvent]): Unit = {
    channel.send(Click)
  }

  override def process = {
    case SetLabel(label) =>
      modifyDOM(_ => labelNode.data = label)
    case SetIcon(icon) =>
    case msg =>
      super.process(msg)
  }

  override def closed(): Unit = {
    uiManager.removeListener(ClickEvent, widgetId, artifact.el)
  }
}

class DOMButtonBuilder(uiManager: DOMUIManager) extends WidgetBuilder(ButtonProtocol) {
  import ButtonProtocol._

  override protected def create(widgetId: Int, context: ChannelContext) =
    new DOMButton(widgetId, context)(uiManager)
}

object DOMButton extends WidgetStyleProvider {
  class Style(uiManager: DOMUIManager) extends WidgetStyle()(uiManager) {
    import DOMWidget._
    val base = uiManager.registerCSSClass(palette => s"""text-align: center;
         |text-decoration: none;
         |user-select: none;
         |vertical-align: middle;
         |white-space: nowrap;
         |padding: 0 .75em;
         |margin: 0 .25em 0 0;
         |border: none;
         |cursor: pointer;
         |display: inline-block;
         |height: ${show(styleConfig.buttonHeight)};
         |line-height: ${show(styleConfig.buttonHeight)};
         |border-radius: ${show(styleConfig.buttonBorderRadius)};
         |box-shadow: ${styleConfig.buttonBoxShadow};
         |color: ${show(palette(Palette.Primary).color.foregroundColor)};
         |background-color: ${show(palette(Palette.Primary).color.backgroundColor)};
         |font-family: ${styleConfig.buttonFontFamily};
         |font-size: ${show(styleConfig.buttonFontSize)};
         |font-weight: ${show(styleConfig.buttonFontWeight)};
        """.stripMargin)
    uiManager.addCSS(s".$base:hover", s"""box-shadow: ${styleConfig.buttonBoxShadowHover};""".stripMargin)
    uiManager.addCSS(s".$base:active", s"""box-shadow: ${styleConfig.buttonBoxShadowActive};""".stripMargin)
  }

  override def buildStyle(implicit uiManager: DOMUIManager) = new Style(uiManager)
} 
Example 23
Source File: WebWorkerTransport.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web

import java.nio.ByteBuffer

import suzaku.platform.Transport
import org.scalajs.dom
import org.scalajs.dom.webworkers.{DedicatedWorkerGlobalScope, Worker}

import scala.scalajs.js
import scala.scalajs.js.typedarray.TypedArrayBufferOps._
import scala.scalajs.js.typedarray.{ArrayBuffer, TypedArrayBuffer}

abstract class WebWorkerTransport extends Transport {
  private val emptyHandler                    = (data: ByteBuffer) => ()
  private var dataHandler: ByteBuffer => Unit = emptyHandler

  override def subscribe(handler: ByteBuffer => Unit): () => Unit = {
    dataHandler = handler
    // return an unsubscribing function
    () =>
      {
        // restore our empty handler when called
        dataHandler = emptyHandler
      }
  }

  def receive(data: ArrayBuffer): Unit = dataHandler(TypedArrayBuffer.wrap(data))
}

class WorkerTransport(worker: DedicatedWorkerGlobalScope) extends WebWorkerTransport {
  override def send(data: ByteBuffer): Unit = {
    assert(data.hasTypedArray())
    val out = data.typedArray.buffer.slice(0, data.limit())
    worker.postMessage(out, js.Array(out).asInstanceOf[js.UndefOr[js.Array[dom.raw.Transferable]]])
  }
}

class WorkerClientTransport(worker: Worker) extends WebWorkerTransport {
  override def send(data: ByteBuffer): Unit = {
    assert(data.hasTypedArray())
    val out = data.typedArray.buffer.slice(0, data.limit())
    worker.postMessage(out, js.Array(out).asInstanceOf[js.UndefOr[js.Array[dom.raw.Transferable]]])
  }
} 
Example 24
Source File: DOMLayout.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web.ui

import org.scalajs.dom
import suzaku.platform.web.DOMWidget
import suzaku.ui.layout._
import suzaku.ui.{Widget, WidgetParent}

trait DOMLayout extends WidgetParent { self: DOMWidget[_, _] =>
  private val commonPropNames = List(
    "z-index"
  )

  protected val layoutPropNames: List[String]

  protected def resolveLayout(modWidget: (dom.html.Element => Unit) => Unit, layoutProperty: LayoutProperty): Unit

  override def resolveLayout(w: Widget, layoutProperties: List[LayoutProperty]): Unit = {
    val widget    = w.asInstanceOf[DOMWidget[_, _ <: dom.html.Element]]
    val modWidget = (f: dom.html.Element => Unit) => widget.modifyDOM(f)

    // println(s"Resolving layout: $layoutProperties")
    // only for real HTML elements
    if (!scalajs.js.isUndefined(widget.artifact.el.style)) {
      // first remove all layout properties
      modWidget { el =>
        commonPropNames.foreach(el.style.removeProperty)
        layoutPropNames.foreach(el.style.removeProperty)
      }
      layoutProperties foreach {
        case ZOrder(n) =>
          modWidget { el =>
            el.style.setProperty("z-index", n.toString)
          }

        case other =>
          resolveLayout(modWidget, other)
      }
    }
  }
} 
Example 25
Source File: UIEntry.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web

import org.scalajs.dom
import org.scalajs.dom.raw.Worker
import suzaku.app.UIBase
import suzaku.platform.Transport

import scala.scalajs.js.annotation.JSExport
import scala.scalajs.js.typedarray.ArrayBuffer

abstract class UIEntry {
  private var transport: WebWorkerTransport = _

  @JSExport
  def entry(workerScript: String): Unit = {
    // create the worker to run our application in
    val worker = new Worker(workerScript)

    // create the transport
    transport = new WorkerClientTransport(worker)

    // listen to messages from worker
    worker.onmessage = onMessage _

    start(transport)
  }

  def start(transport: Transport): UIBase

  private def onMessage(msg: dom.MessageEvent): Unit = {
    msg.data match {
      case buffer: ArrayBuffer =>
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 26
Source File: DOMScheduler.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web

import org.scalajs.dom
import suzaku.platform.{Cancellable, Scheduler}

import scala.concurrent.duration.FiniteDuration
import scala.scalajs.js.timers._

class DOMScheduler extends Scheduler {

  private class TimeoutCancellable(handle: SetTimeoutHandle) extends Cancellable {
    var isCancelled = false

    override def cancel(): Unit = {
      isCancelled = true
      clearTimeout(handle)
    }
  }

  private class IntervalCancellable(handle: SetIntervalHandle) extends Cancellable {
    var isCancelled = false

    override def cancel(): Unit = {
      isCancelled = true
      clearInterval(handle)
    }
  }

  private class FrameCancellable extends Cancellable {
    var isCancelled = false

    override def cancel(): Unit = {
      isCancelled = true
    }
  }

  override def scheduleOnce(after: FiniteDuration, callback: ScheduleCB): Cancellable = {
    new TimeoutCancellable(setTimeout(after) {
      val time = (dom.window.performance.now() * 1e6).toLong
      callback(time)
    })
  }

  override def schedule(interval: FiniteDuration, callback: ScheduleCB): Cancellable = {
    new IntervalCancellable(setInterval(interval) {
      val time = (dom.window.performance.now() * 1e6).toLong
      callback(time)
    })
  }

  private def frameCB(cancellable: FrameCancellable, callback: ScheduleCB)(time: Double): Unit = {
    if (!cancellable.isCancelled) {
      callback((time * 1e6).toLong)
      dom.window.requestAnimationFrame(frameCB(cancellable, callback) _)
    }
  }

  override def scheduleFrame(callback: ScheduleCB): Cancellable = {
    val cancellable = new FrameCancellable
    dom.window.requestAnimationFrame(frameCB(cancellable, callback) _)
    cancellable
  }
} 
Example 27
Source File: Main.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example.lifecycle

import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.{React, ReactDOM}
import org.scalajs.dom

import scala.scalajs.js.JSApp

object App {
  case class State(
      componentDidMountCalled: Boolean,
      componentDidUpdateCalled: Boolean
  )

  type Self = React.Self[Unit, State]

  def apply() = reactClass

  private lazy val reactClass = React.createClass[Unit, State](
    componentWillMount = (self) => println("componentWillMount()"),
    componentDidMount = (self) => {
      println("componentDidMount()")
      self.setState(_.copy(componentDidMountCalled = true))
    },
    shouldComponentUpdate = (self, nextProps, nextState) => {
      println(s"shouldComponentUpdate($nextProps, $nextState)")
      nextState != self.state
    },
    componentWillReceiveProps = (self, nextProps) => {
      println(s"componentWillReceiveProps($nextProps)")
    },
    componentWillUpdate = (self, nextProps, nextState) => {
      println(s"componentWillUpdate($nextProps, $nextState)")
    },
    componentDidUpdate = (self, prevProps, prevState) => {
      println(s"componentDidUpdate($prevProps, $prevState)")
      self.setState(_.copy(componentDidUpdateCalled = true))
    },
    componentWillUnmount = (self) => {
      println("componentWillUnmount()")
    },
    getInitialState = (self) => State(
      componentDidMountCalled = false,
      componentDidUpdateCalled = false
    ),
    render = (self) =>
      <.div()(
        <.label(^.`for` := "component-did-mount")("Component Did Mount: "),
        <.input(^.id := "component-did-mount", ^.`type`.checkbox, ^.checked := self.state.componentDidMountCalled)(),
        <.label(^.`for` := "component-did-update")("Component Did Update: "),
        <.input(^.id := "component-did-update", ^.`type`.checkbox, ^.checked := self.state.componentDidUpdateCalled)()
      )
  )
}

object Main extends JSApp {
  override def main(): Unit = {
    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render(<(App()).empty, mountNode)
  }
} 
Example 28
Source File: Main.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example.helloworld

import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.{React, ReactDOM}
import org.scalajs.dom

import scala.scalajs.js.JSApp

object Main extends JSApp {
  def main(): Unit = {
    case class WrappedProps(name: String)

    val reactClass = React.createClass[WrappedProps, Unit](
      (self) => <.div(^.id := "hello-world")(s"Hello, ${self.props.wrapped.name}!")
    )

    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render(<(reactClass)(^.wrapped := WrappedProps("World"))(), mountNode)
  }
} 
Example 29
Source File: Main.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example.style

import io.github.shogowada.scalajs.reactjs.ReactDOM
import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.elements.ReactElement
import org.scalajs.dom

import scala.scalajs.js.JSApp

object Main extends JSApp {
  override def main(): Unit = {
    val mountNode = dom.document.createElement("div")
    dom.document.body.appendChild(mountNode)
    ReactDOM.render(Main(), mountNode)
  }

  def apply(): ReactElement = <.div()(
    <.div(^.id := "green-text", ^.className := Seq("green"))("Green text!"),
    <.div(^.id := "big-blue-text", ^.className := Seq("big", "blue"))(" Big blue text !"),
    <.div(^.id := "red-text", ^.style := Map("color" -> "red"))("Red text!")
  )
} 
Example 30
Source File: Main.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example.redux.devtools

import io.github.shogowada.scalajs.reactjs.React.Props
import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.classes.ReactClass
import io.github.shogowada.scalajs.reactjs.events.FormSyntheticEvent
import io.github.shogowada.scalajs.reactjs.redux.ReactRedux._
import io.github.shogowada.scalajs.reactjs.redux.Redux.Dispatch
import io.github.shogowada.scalajs.reactjs.redux.devtools.ReduxDevTools
import io.github.shogowada.scalajs.reactjs.redux.{Action, ReactRedux, Redux}
import io.github.shogowada.scalajs.reactjs.{React, ReactDOM}
import org.scalajs.dom
import org.scalajs.dom.raw.HTMLInputElement

import scala.scalajs.js.JSApp

object Main extends JSApp {
  override def main(): Unit = {
    val store = Redux.createStore[State](
      Reducer(_, _),
      ReduxDevTools.devToolsEnhancer() // Just add the enhancer
    )

    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render(
      <.Provider(^.store := store)(
        <(TextContainerComponent()).empty
      ),
      mountNode
    )
  }
}

case class State(text: String)

case class SetText(text: String) extends Action

object Reducer {
  def apply(maybeState: Option[State], action: Any): State =
    action match {
      case action: SetText => State(text = action.text)
      case _ => State(text = "")
    }
}

object TextContainerComponent {

  import TextComponent._

  def apply(): ReactClass = ReactRedux.connectAdvanced(
    (dispatch: Dispatch) => {
      val onTextChange = (text: String) => dispatch(SetText(text))
      (state: State, ownProps: Props[Unit]) => {
        WrappedProps(
          text = state.text,
          onTextChange = onTextChange
        )
      }
    }
  )(TextComponent())
}

object TextComponent {
  case class WrappedProps(text: String, onTextChange: (String) => _)

  def apply() = reactClass

  private lazy val reactClass = React.createClass[WrappedProps, Unit](
    (self) =>
      <.div()(
        <.input(
          ^.value := self.props.wrapped.text,
          ^.onChange := ((event: FormSyntheticEvent[HTMLInputElement]) => {
            self.props.wrapped.onTextChange(event.target.value)
          })
        )()
      )
  )
} 
Example 31
Source File: Main.scala    From scalajs-reactjs   with MIT License 5 votes vote down vote up
package io.github.shogowada.scalajs.reactjs.example.todoapp

import io.github.shogowada.scalajs.reactjs.VirtualDOM._
import io.github.shogowada.scalajs.reactjs.elements.ReactElement
import io.github.shogowada.scalajs.reactjs.events.{FormSyntheticEvent, SyntheticEvent}
import io.github.shogowada.scalajs.reactjs.{React, ReactDOM}
import org.scalajs.dom
import org.scalajs.dom.raw.HTMLInputElement

import scala.scalajs.js
import scala.scalajs.js.JSApp



object Main extends JSApp {
  def main(): Unit = {
    val mountNode = dom.document.getElementById("mount-node")
    ReactDOM.render(
      <(TodoApp()).empty,
      mountNode
    )
  }
}

case class Item(id: String, text: String)

object TodoApp {
  case class State(items: Seq[Item], text: String)

  type Self = React.Self[Unit, State]

  def apply() = reactClass

  private lazy val reactClass = React.createClass[Unit, State](
    getInitialState = (self) => State(items = Seq.empty, text = ""),
    render = (self) =>
      <.div()(
        <.h3()("TODO"),
        TodoList(self.state.items),
        <.form(^.onSubmit := handleSubmit(self))(
          <.input(^.onChange := handleChange(self), ^.value := self.state.text)(),
          <.button()(s"Add #${self.state.items.size + 1}")
        )
      )
  )

  private def handleChange(self: Self) =
    (e: FormSyntheticEvent[HTMLInputElement]) => {
      // Cache the value because React reuses the event object.
      val newText = e.target.value
      // It is a syntactic sugar for setState((prevState: State) => prevState.copy(text = newText))
      self.setState(_.copy(text = newText))
    }

  private def handleSubmit(self: Self) =
    (e: SyntheticEvent) => {
      e.preventDefault()
      val newItem = Item(text = self.state.text, id = js.Date.now().toString)
      self.setState((prevState: State) => State(
        items = prevState.items :+ newItem,
        text = ""
      ))
    }
}

object TodoList {
  // Use a function to render
  def apply(items: Seq[Item]): ReactElement =
    <.ul()(items.map(item => <.li(^.key := item.id)(item.text)))
} 
Example 32
Source File: OutwatchTracing.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch.helpers

import colibri._
import colibri.helpers.UnhandledErrorReporter
import snabbdom.VNodeProxy
import org.scalajs.dom

object OutwatchTracing {
  private[outwatch] val patchSubject = Subject.publish[VNodeProxy]
  private[outwatch] val errorSubject = Subject.publish[Throwable]

  // a stream to be notified about snabbdom patches
  def patch: Observable[VNodeProxy] = patchSubject

  // a stream about unhandled errors in the reactive part of outwatch, with a
  // default subscription that will print the error to notify the user.
  def error: Observable[Throwable] = Observable.merge(errorSubject, UnhandledErrorReporter.error).withDefaultSubscription(Observer.create[Throwable](reportError, reportError))

  private def reportError(error: Throwable): Unit =
    dom.console.error(error.getMessage + "\n" + error.getStackTrace.mkString("\n"))
} 
Example 33
Source File: OutWatch.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch

import cats.effect.Sync
import cats.implicits._
import org.scalajs.dom
import org.scalajs.dom._
import outwatch.interpreter.SnabbdomOps
import snabbdom.{VNodeProxy, patch}

object OutWatch {
  def toSnabbdom[F[_]](vNode: VNode)(implicit F: Sync[F]): F[VNodeProxy] = F.delay {
    SnabbdomOps.toSnabbdom(vNode)
  }

  def renderInto[F[_]](element: dom.Element, vNode: VNode)(implicit F: Sync[F]): F[Unit] =
    toSnabbdom(vNode).map { node =>
      val elem = dom.document.createElement("div")
      element.appendChild(elem)
      patch(elem, node)
    }.void

  def renderReplace[F[_]: Sync](element: dom.Element, vNode: VNode): F[Unit] =
    toSnabbdom(vNode).map { node =>
      val elementNode = snabbdom.tovnode(element)
      patch(elementNode, node)
    }.void

  def renderInto[F[_]: Sync](querySelector: String, vNode: VNode): F[Unit] =
    renderInto(document.querySelector(querySelector), vNode)

  def renderReplace[F[_]: Sync](querySelector: String, vNode: VNode): F[Unit] =
    renderReplace(document.querySelector(querySelector), vNode)
} 
Example 34
Source File: ManagedSubscriptions.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch

import cats.{Applicative, Functor, Monoid}
import cats.implicits._
import org.scalajs.dom
import scala.scalajs.js
import colibri._
import colibri.effect.RunSyncEffect

trait ManagedSubscriptions {

  @inline def managed[F[_] : RunSyncEffect, T : CanCancel](subscription: F[T]): VDomModifier = managedFunction(() => RunSyncEffect[F].unsafeRun(subscription))

  def managed[F[_] : RunSyncEffect : Applicative : Functor, T : CanCancel : Monoid](sub1: F[T], sub2: F[T], subscriptions: F[T]*): VDomModifier = {
    val composite = (sub1 :: sub2 :: subscriptions.toList).sequence.map[T](subs => Monoid[T].combineAll(subs))
    managed(composite)
  }

  @inline def managedFunction[T : CanCancel](subscription: () => T): VDomModifier = CancelableModifier(() => Cancelable.lift(subscription()))

  object managedElement {
    def apply[T : CanCancel](subscription: dom.Element => T): VDomModifier = VDomModifier.delay {
      var lastSub: js.UndefOr[T] = js.undefined
      VDomModifier(
        dsl.onDomMount foreach { elem => lastSub = subscription(elem) },
        dsl.onDomUnmount foreach { lastSub.foreach(CanCancel[T].cancel) }
      )
    }

    def asHtml[T : CanCancel](subscription: dom.html.Element => T): VDomModifier = apply(elem => subscription(elem.asInstanceOf[dom.html.Element]))

    def asSvg[T : CanCancel](subscription: dom.svg.Element => T): VDomModifier = apply(elem => subscription(elem.asInstanceOf[dom.svg.Element]))
  }
}

object ManagedSubscriptions extends ManagedSubscriptions 
Example 35
Source File: LocalStorage.scala    From outwatch   with Apache License 2.0 5 votes vote down vote up
package outwatch.util

import cats.effect.Sync
import cats.implicits._
import org.scalajs.dom
import org.scalajs.dom.StorageEvent
import org.scalajs.dom.window.{localStorage, sessionStorage}

import outwatch.dsl.events
import outwatch.reactive.handler._
import colibri._

class Storage(domStorage: dom.Storage) {
  private def handlerWithTransform[F[_]: Sync](key: String, transform: Observable[Option[String]] => Observable[Option[String]]): F[Handler[Option[String]]] = {
    val storage = new dom.ext.Storage(domStorage)

    for {
      h <- Handler.createF[F](storage(key))
    } yield {
      // We execute the write-action to the storage
      // and pass the written value through to the underlying subject h
      h.transformSubject[Option[String]] { o =>
        val c = o.redirect((o: Observable[Option[String]]) => transform(o).distinct)
        c.connect()
        c.sink
      } { input =>
        input.doOnNext {
          case Some(data) => storage.update(key, data)
          case None => storage.remove(key)
        }
      }
    }
  }

  private def storageEventsForKey[F[_]: Sync](key: String): Observable[Option[String]] =
    // StorageEvents are only fired if the localStorage was changed in another window
    events.window.onStorage.collect {
      case e: StorageEvent if e.storageArea == domStorage && e.key == key =>
        // newValue is either String or null if removed or cleared
        // Option() transformes this to Some(string) or None
        Option(e.newValue)
      case e: StorageEvent if e.storageArea == domStorage && e.key == null =>
        // storage.clear() emits an event with key == null
        None
    }

  def handlerWithoutEvents[F[_]: Sync](key: String): F[Handler[Option[String]]] = {
    handlerWithTransform(key, identity)
  }

  def handlerWithEventsOnly[F[_]: Sync](key: String): F[Handler[Option[String]]] = {
    val storageEvents = storageEventsForKey(key)
    handlerWithTransform(key, _ => storageEvents)
  }

  def handler[F[_]: Sync](key: String): F[Handler[Option[String]]] = {
    val storageEvents = storageEventsForKey(key)
    handlerWithTransform(key, Observable.merge(_, storageEvents))
  }
}

object LocalStorage extends Storage(localStorage)
object SessionStorage extends Storage(sessionStorage) 
Example 36
Source File: CheckersMain.scala    From checkers   with Apache License 2.0 5 votes vote down vote up
package checkers

import checkers.logger._
import checkers.modules.{BasicsModule, CoreModule, UserInterfaceModule}
import checkers.style.GlobalStyles
import org.scalajs.dom
import org.scalajs.dom.UIEvent

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scalacss.ProdDefaults._
import scalacss.ScalaCssReact._

@JSExportTopLevel("CheckersMain")
object CheckersMain {

  @JSExport
  def main(args: Array[String]): Unit = {
    log.warn("Application starting")

    // create stylesheet
    GlobalStyles.addToDocument()

    val host = dom.document.getElementById("root")
    val dialogHost = dom.document.getElementById("dialog-root")
    bootstrap(host, dialogHost)
  }

  private def bootstrap(host: dom.Element, dialogHost: dom.Element): Unit = {
    val module = new BasicsModule with CoreModule with UserInterfaceModule { }
    val application = module.application

    val session = application.start(host, dialogHost)

    dom.window.onresize = { _: UIEvent =>
      session.windowResized()
    }
  }

} 
Example 37
Source File: SceneContainer.scala    From checkers   with Apache License 2.0 5 votes vote down vote up
package checkers.userinterface

import checkers.core.{GameModelReader, ScreenLayoutSettings}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.vdom.{svg_<^ => svg}
import org.scalajs.dom
import org.scalajs.dom.raw.SVGSVGElement

import scala.scalajs.js


object SceneContainer {

  type Callbacks = BoardCallbacks

  case class Props(gameModel: GameModelReader,
                   screenLayoutSettings: ScreenLayoutSettings,
                   callbacks: Callbacks)

}

class SceneContainer(sceneFrame: SceneFrame) {

  import SceneContainer._

  class Backend($: BackendScope[Props, SceneContainerContext]) {

    def start: Callback = for {
      target <- $.getDOMNode
      sceneContainerContext = new MountedSceneContainerContext(target.asInstanceOf[SVGSVGElement])
      cb <- $.setState(sceneContainerContext)
    } yield cb

    def render(props: Props, state: SceneContainerContext): VdomElement = {
      val gameSceneWidth = props.screenLayoutSettings.GameSceneWidthPixels
      val gameSceneHeight = props.screenLayoutSettings.GameSceneHeightPixels
      val sceneFrameProps = SceneFrame.Props(props.gameModel, props.callbacks, state, gameSceneWidth, gameSceneHeight)
      svg.<.svg(
        ^.id := "game-scene",
        svg.^.width := s"${gameSceneWidth}px",
        svg.^.height := s"${gameSceneHeight}px",
        //^.onMouseMove ==> handleMouseMove,
        sceneFrame.create(sceneFrameProps)
      )
    }
  }

  val create = ScalaComponent.builder[Props]("SceneContainer")
    .initialState[SceneContainerContext](NullSceneContainerContext)
    .renderBackend[Backend]
    .componentDidMount(_.backend.start)
    .build

} 
Example 38
Source File: GameFactory.scala    From checkers   with Apache License 2.0 5 votes vote down vote up
package checkers.core

import checkers.computer.{MentorFactory, Program, ProgramRegistry}
import checkers.userinterface.GameScreen
import org.scalajs.dom

class GameFactory(programRegistry: ProgramRegistry,
                  gameLogicModuleFactory: GameLogicModuleFactory,
                  mentorFactory: MentorFactory,
                  scheduler: Scheduler,
                  applicationSettingsProvider: ApplicationSettingsProvider,
                  screenLayoutSettingsProvider: ScreenLayoutSettingsProvider,
                  gameScreen: GameScreen) {

  def create(settings: NewGameSettings, initialSeeds: InitialSeeds, host: dom.Element): Game = {
    val darkEntry = for {
      id <- settings.darkProgramId
      entry <- programRegistry.findEntry(id)
    } yield entry

    val lightEntry = for {
      id <- settings.lightProgramId
      entry <- programRegistry.findEntry(id)
    } yield entry

    val gameLogicModule = gameLogicModuleFactory.apply(settings.rulesSettings)

    val darkComputer = for {
      entry <- darkEntry
    } yield entry.makeComputerPlayer(gameLogicModule, initialSeeds.darkPlayer)

    val lightComputer = for {
      entry <- lightEntry
    } yield entry.makeComputerPlayer(gameLogicModule, initialSeeds.lightPlayer)

    val darkPlayer = darkComputer.getOrElse(Human)
    val lightPlayer = lightComputer.getOrElse(Human)

    val darkMentor = createMentor(gameLogicModule, darkPlayer, initialSeeds.darkMentor)
    val lightMentor = createMentor(gameLogicModule, lightPlayer, initialSeeds.lightMentor)

    val mentorConfig = MentorConfig(darkMentor, lightMentor)

    val gameConfig = GameConfig(settings.rulesSettings, PlayerConfig(darkPlayer, lightPlayer), mentorConfig)
    createGame(gameLogicModule, gameConfig, host)
  }


  private def createMentor(gameLogicModule: GameLogicModule, player: Player, initialSeed: Option[Long]): Option[Program] = {
    if(player.isComputer) None
    else {
      Option(mentorFactory.makeProgram(gameLogicModule, initialSeed))
    }
  }

  private def createGame(gameLogicModule: GameLogicModule, gameConfig: GameConfig, host: dom.Element): Game = {
    val driver = new GameDriver(gameLogicModule)(gameConfig.playerConfig, gameConfig.mentorConfig)
    new Game(driver, scheduler, applicationSettingsProvider, screenLayoutSettingsProvider, gameScreen)(host)
  }

} 
Example 39
Source File: Mdl.scala    From outwatch-extras   with Apache License 2.0 5 votes vote down vote up
package outwatch.extras.mdl

import monix.execution.Ack.Continue
import monix.execution.Scheduler
import org.scalajs.dom
import outwatch.Sink
import outwatch.dom.VDomModifier
import outwatch.dom.dsl.attributes.lifecycle._

import scala.scalajs.js


trait Mdl {

  implicit def scheduler: Scheduler

  private def componentHandler = js.Dynamic.global.componentHandler

  private def updateElement(e: dom.Element): Unit = {
    e.removeAttribute("data-upgraded")
    if (!js.isUndefined(componentHandler)) componentHandler.upgradeElement(e).asInstanceOf[Unit]
  }

  private val insertHook = Sink.create[dom.Element] { e =>
    updateElement(e)
    Continue
  }

  private val postPatchHook = Sink.create[(dom.Element, dom.Element)] { case (_, e) =>
    updateElement(e)
    Continue
  }

  val material: VDomModifier = VDomModifier(
    insertHook.flatMap(sink => onInsert --> sink),
    postPatchHook.flatMap(sink => onPostPatch --> sink)
  )

  def material(id: String): VDomModifier = {

    val update = () => {
      Option(dom.document.getElementById(id)).foreach(updateElement)
      Continue
    }

    val insertHook = Sink.create[dom.Element](_ => update())
    val postPatchHook = Sink.create[(dom.Element, dom.Element)](_ => update() )

    VDomModifier(
      insertHook.flatMap(sink => onInsert --> sink),
      postPatchHook.flatMap(sink => onPostPatch --> sink)
    )
  }

} 
Example 40
Source File: RpcLoggingDemo.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.guide.views.ext.demo

import io.udash._
import io.udash.bootstrap.utils.BootstrapStyles
import io.udash.bootstrap.utils.BootstrapStyles.Color
import io.udash.web.guide.demos.activity.Call
import io.udash.web.guide.styles.partials.GuideStyles
import org.scalajs.dom
import org.scalajs.dom._
import scalatags.JsDom.all._

object RpcLoggingDemo {
  import io.udash.css.CssView._
  def apply(model: ReadableSeqProperty[Call], loadCalls: () => Any): dom.Element =
    span(GuideStyles.frame, GuideStyles.useBootstrap)(
      button(
        id := "call-logging-demo", BootstrapStyles.Button.btn, BootstrapStyles.Button.color(Color.Primary),
        onclick :+= ((_: MouseEvent) => loadCalls(), true)
      )("Load call list"),
      produce(model)(seq => ul(seq.map(call => li(call.toString))).render)
    ).render
} 
Example 41
Source File: ImageFactory.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.commons.views

import org.scalajs.dom
import org.scalajs.dom.raw.Element
import scalatags.JsDom
import scalatags.JsDom.all._
import scalatags.generic.Namespace

class ImageFactoryPrefix(val value: String)
object ImageFactoryPrefixSet {
  case object Intro extends ImageFactoryPrefix(value = "/assets/images/quick")
  case object Boostrapping extends ImageFactoryPrefix(value = "/assets/images/views/bootstrapping")
  case object Frontend extends ImageFactoryPrefix(value = "/assets/images/views/frontend")
}

object ClickableImageFactory {
  def apply(prefix: ImageFactoryPrefix, name: String, altText: String, xs: Modifier*): JsDom.TypedTag[dom.html.Anchor] =
    a(href := prefix.value + "/" + name, target := "_blank", rel := "external", xs)(
      (new ImageFactory(prefix.value))(name, altText)
    )
}

class ImageFactory(prefix: String) {
  import scalatags.JsDom.all._
  def apply(name: String, altText: String, xs: Modifier*): JsDom.TypedTag[dom.html.Image] = {
    img(src := s"$prefix/$name", alt := altText, xs)
  }
}

object Image extends ImageFactory("/assets/images")

object SVG {
  import scalatags.JsDom.{svgAttrs, svgTags}
  def apply(name: String, size: Size, xs: Modifier*): JsDom.TypedTag[Element] = {
    div(style := s"position: relative; width: 100%; padding-top: ${100 * size.height / size.width}%")(
      svgTags.svg(xmlns := Namespace.svgNamespaceConfig.uri, svgAttrs.viewBox := s"0 0 ${size.width} ${size.height}", style := "position: absolute; top: 0; left: 0; width: 100%; height: 100%;")(
        svgTags.use(svgAttrs.xmlnsXlink := Namespace.svgXlinkNamespaceConfig.uri, svgAttrs.xLinkHref := s"/assets/svg/$name")
      )
    )
  }
}

case class Size(width: Int, height: Int) 
Example 42
Source File: UsesServerRPC.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.rpc.internals

import com.avsystem.commons.SharedExtensions._
import io.udash.rpc._
import io.udash.utils.{CallbacksHandler, Registration}
import org.scalajs.dom

import scala.concurrent.duration.{Duration, DurationInt}
import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import scala.scalajs.js.Dictionary


  def onCallFailure(callback: exceptionCallbacks.CallbackType): Registration =
    exceptionCallbacks.register(callback)

  private def handleException(ex: Throwable): Unit =
    exceptionCallbacks.fire(ex)

  def handleResponse(response: RpcResponse): Unit = {
    pendingCalls.remove(response.callId)
      .foreach { promise =>
        response match {
          case RpcResponseSuccess(r, _) =>
            promise.success(r)
          case RpcResponseException(_, exception, _) =>
            handleException(exception)
            promise.failure(exception)
          case RpcResponseFailure(cause, error, _) =>
            val exception = RpcFailure(cause, error)
            handleException(exception)
            promise.failure(exception)
        }
      }
  }

  override protected[rpc] def fireRemote(getterChain: List[RpcInvocation], invocation: RpcInvocation): Unit =
    sendRpcRequest(RpcFire(invocation, getterChain))

  protected[rpc] def callRemote(callId: String, getterChain: List[RpcInvocation], invocation: RpcInvocation): Unit =
    sendRpcRequest(RpcCall(invocation, getterChain, callId))

  private def sendRpcRequest(request: RpcRequest): Unit =
    connector.sendRpcRequest(request)

  protected class RawRemoteRPC(getterChain: List[RpcInvocation]) extends ServerRawRpc {
    def fire(invocation: RpcInvocation): Unit =
      fireRemote(getterChain, invocation)

    def call(invocation: RpcInvocation): Future[JsonStr] =
      Promise[JsonStr]().setup { promise =>
        val callId = newCallId()
        callRemote(callId, getterChain, invocation)
        pendingCalls.put(callId, promise)
        dom.window.setTimeout(
          () => handleResponse(RpcResponseException("Request timeout", UsesServerRPC.CallTimeout(callTimeout), callId)),
          callTimeout.toMillis.toDouble
        )
      }.future

    def get(invocation: RpcInvocation): ServerRawRpc =
      new RawRemoteRPC(invocation :: getterChain)
  }
}

object UsesServerRPC {
  case class CallTimeout(callTimeout: Duration) extends RuntimeException(s"Response missing after $callTimeout.")
} 
Example 43
Source File: UdashPopover.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap
package tooltip

import io.udash.bootstrap.utils.BootstrapStyles
import io.udash.wrappers.jquery._
import org.scalajs.dom
import org.scalajs.dom.Element

import scala.scalajs.js

final class UdashPopover(selector: UdashPopover.UdashPopoverJQuery) extends Tooltip {

  
  def destroy(): Unit = {
    off(selector)
    selector.popover("dispose")
  }

  private[tooltip] def reloadContent(): Unit =
    selector.popover("setContent")

  on(selector, "show.bs.popover", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Show)))
  on(selector,"shown.bs.popover", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Shown)))
  on(selector,"hide.bs.popover", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Hide)))
  on(selector,"hidden.bs.popover", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Hidden)))
  on(selector,"inserted.bs.popover", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Inserted)))
}

object UdashPopover extends TooltipUtils[UdashPopover] {
  override protected def initTooltip(options: js.Dictionary[Any])(el: dom.Node): UdashPopover = {
    val tp: UdashPopoverJQuery = jQ(el).asInstanceOf[UdashPopoverJQuery]
    tp.popover(options)
    new UdashPopover(tp)
  }

  override protected val defaultPlacement = Placement.Right
  override protected val defaultTemplate: String = {
    import io.udash.css.CssView._
    import scalatags.Text.all._
    div(BootstrapStyles.Popover.popover, role := "tooltip")(
      div(BootstrapStyles.arrow),
      h3(BootstrapStyles.Popover.header),
      div(BootstrapStyles.Popover.body)
    ).render
  }
  override protected val defaultTrigger: Seq[Trigger] = Seq(Trigger.Click)

  @js.native
  private trait UdashPopoverJQuery extends JQuery {
    def popover(arg: js.Any): UdashPopoverJQuery = js.native
  }
} 
Example 44
Source File: UdashTooltip.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap
package tooltip

import io.udash.bootstrap.utils.BootstrapStyles
import io.udash.wrappers.jquery._
import org.scalajs.dom
import org.scalajs.dom.Element

import scala.scalajs.js

final class UdashTooltip private(selector: UdashTooltip.UdashTooltipJQuery) extends Tooltip {

  
  def destroy(): Unit = {
    off(selector)
    selector.tooltip("dispose")
  }

  private[tooltip] def reloadContent(): Unit =
    selector.tooltip("setContent")

  on(selector,"show.bs.tooltip", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Show)))
  on(selector,"shown.bs.tooltip", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Shown)))
  on(selector,"hide.bs.tooltip", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Hide)))
  on(selector,"hidden.bs.tooltip", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Hidden)))
  on(selector,"inserted.bs.tooltip", (_: Element, _: JQueryEvent) => fire(TooltipEvent(this, TooltipEvent.EventType.Inserted)))
}

object UdashTooltip extends TooltipUtils[UdashTooltip] {
  override protected def initTooltip(options: js.Dictionary[Any])(el: dom.Node): UdashTooltip = {
    val tp: UdashTooltipJQuery = jQ(el).asInstanceOf[UdashTooltipJQuery]
    tp.tooltip(options)
    new UdashTooltip(tp)
  }

  override protected val defaultPlacement = Placement.Top
  override protected val defaultTemplate: String = {
    import io.udash.css.CssView._
    import scalatags.Text.all._
    div(BootstrapStyles.Tooltip.tooltip, role := "tooltip")(
      div(BootstrapStyles.Tooltip.arrow),
      div(BootstrapStyles.Tooltip.inner)
    ).render
  }
  override protected val defaultTrigger: Seq[Trigger] = Seq(Trigger.Hover, Trigger.Focus)

  @js.native
  private trait UdashTooltipJQuery extends JQuery {
    def tooltip(arg: js.Any): UdashTooltipJQuery = js.native
  }
} 
Example 45
Source File: TooltipUtils.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap
package tooltip

import com.avsystem.commons.misc.{AbstractValueEnum, AbstractValueEnumCompanion, EnumCtx}
import io.udash.wrappers.jquery._
import org.scalajs.dom

import scala.collection.mutable
import scala.concurrent.duration.{Duration, DurationInt}
import scala.scalajs.js
import scala.scalajs.js.|

trait Tooltip extends Listenable {

  override final type EventType = TooltipEvent

  
  def apply(
    animation: Boolean = true,
    boundary: String | dom.Node = "scrollParent",
    container: Option[String | dom.Node] = None,
    content: js.Function1[dom.Node, String] | dom.Node = io.udash.emptyStringNode(),
    delay: Delay | Long = Delay(0 millis, 0 millis),
    html: Boolean = false,
    offset: Int | String = "0",
    placement: Placement = defaultPlacement,
    template: Option[String] = None,
    title: String | js.Function1[dom.Node, String] | dom.Node = "",
    trigger: Seq[Trigger] = defaultTrigger
  )(el: dom.Node): TooltipType =
    initTooltip(
      js.Dictionary(
        "animation" -> animation,
        "boundary" -> boundary,
        "container" -> container.getOrElse(false),
        "content" -> content,
        "delay" -> delay,
        "html" -> html,
        "offset" -> offset,
        "placement" -> placement.jsValue,
        "template" -> template.getOrElse(defaultTemplate),
        "title" -> title,
        "trigger" -> trigger.map(_.jsValue).mkString(" ")
      )
    )(el)

  protected def initTooltip(options: js.Dictionary[Any])(el: dom.Node): TooltipType
  protected val defaultPlacement: Placement
  protected val defaultTemplate: String
  protected val defaultTrigger: Seq[Trigger]
} 
Example 46
Source File: UdashButton.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.bootstrap
package button

import com.avsystem.commons.misc.{AbstractCase, AbstractValueEnum, AbstractValueEnumCompanion, EnumCtx}
import io.udash._
import io.udash.bindings.modifiers.Binding
import io.udash.bootstrap.button.UdashButton.{ButtonClickEvent, UdashButtonJQuery}
import io.udash.bootstrap.utils._
import io.udash.wrappers.jquery.{JQuery, jQ}
import org.scalajs.dom
import org.scalajs.dom._
import scalatags.JsDom
import scalatags.JsDom.TypedTag
import scalatags.JsDom.all._

import scala.scalajs.js

final class UdashButton private(
  buttonStyle: ReadableProperty[BootstrapStyles.Color],
  size: ReadableProperty[Option[BootstrapStyles.Size]],
  outline: ReadableProperty[Boolean],
  block: ReadableProperty[Boolean],
  active: ReadableProperty[Boolean],
  disabled: ReadableProperty[Boolean],
  override val componentId: ComponentId,
  tag: UdashButton.ButtonTag
)(content: Binding.NestedInterceptor => Modifier) extends UdashBootstrapComponent with Listenable {

  import io.udash.css.CssView._

  override type EventType = ButtonClickEvent

  private val classes: List[Modifier] = {
    (BootstrapStyles.Button.btn: Modifier) ::
      nestedInterceptor(
        ((data: (BootstrapStyles.Color, Boolean)) => data match {
          case (style, false) =>
            BootstrapStyles.Button.color(style)
          case (style, true) =>
            BootstrapStyles.Button.outline(style)
        }).reactiveApply(buttonStyle.combine(outline)((_, _)))
      ) ::
      nestedInterceptor((BootstrapStyles.Button.size _).reactiveOptionApply(size)) ::
      nestedInterceptor(BootstrapStyles.Button.block.styleIf(block)) ::
      nestedInterceptor(BootstrapStyles.active.styleIf(active)) ::
      nestedInterceptor(BootstrapStyles.disabled.styleIf(disabled)) ::
      nestedInterceptor(JsDom.all.disabled.attrIf(disabled)) :: Nil
  }

  override val render: dom.html.Element = {
    tag.value(componentId, tpe := "button")(classes: _*)(
      //condition to support non-button tags
      onclick :+= ((me: MouseEvent) => if (!disabled.get) fire(ButtonClickEvent(this, me)))
    )(content(nestedInterceptor)).render
  }

  override def kill(): Unit = {
    super.kill()
    jQSelector().button("dispose")
  }

  private def jQSelector(): UdashButtonJQuery =
    jQ(s"#$componentId").asInstanceOf[UdashButtonJQuery]
}

object UdashButton {
  final case class ButtonClickEvent(source: UdashButton, mouseEvent: MouseEvent) extends AbstractCase with ListenableEvent

  
  def toggle(
    active: Property[Boolean],
    buttonStyle: ReadableProperty[BootstrapStyles.Color] = UdashBootstrap.ColorSecondary,
    size: ReadableProperty[Option[BootstrapStyles.Size]] = UdashBootstrap.None,
    outline: ReadableProperty[Boolean] = UdashBootstrap.False,
    block: ReadableProperty[Boolean] = UdashBootstrap.False,
    disabled: ReadableProperty[Boolean] = UdashBootstrap.False,
    componentId: ComponentId = ComponentId.generate(),
    tag: ButtonTag = ButtonTag.Button
  )(content: Binding.NestedInterceptor => Modifier): UdashButton = {
    val button = new UdashButton(buttonStyle, size, outline, block, active, disabled, componentId, tag)(content)
    button.listen { case _ => active.set(!active.get) }
    button
  }

  @js.native
  private trait UdashButtonJQuery extends JQuery {
    def button(cmd: String): UdashButtonJQuery = js.native
  }
} 
Example 47
Source File: AsyncUdashSharedTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.testing

import org.scalactic.source.Position
import org.scalajs.dom
import org.scalatest.{Assertion, Succeeded}

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.scalajs.concurrent.JSExecutionContext
import scala.scalajs.js.Date
import scala.util.{Failure, Success}

trait AsyncUdashSharedTest extends AsyncUdashSharedTestBase {
  override implicit def executionContext: ExecutionContext = JSExecutionContext.queue

  override def retrying(code: => Any)(implicit patienceConfig: PatienceConfig, pos: Position): Future[Assertion] = {
    val start = Date.now()
    val p = Promise[Assertion]
    var lastEx: Option[Throwable] = None
    def startTest(): Unit = {
      dom.window.setTimeout(() => {
        if (patienceConfig.timeout.toMillis > Date.now() - start) {
          try {
            code
            p.complete(Success(Succeeded))
          } catch {
            case ex: Throwable =>
              lastEx = Some(ex)
              startTest()
          }
        } else {
          p.complete(Failure(lastEx.getOrElse(RetryingTimeout())))
        }
      }, patienceConfig.interval.toMillis.toDouble)
    }
    startTest()
    p.future
  }
} 
Example 48
Source File: UdashFrontendTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.testing

import com.avsystem.commons._
import org.scalajs.dom
import org.scalajs.dom.Element
import org.scalajs.dom.raw.DOMTokenList
import org.scalatest.enablers.Containing

trait FrontendTestUtils {
  def emptyComponent(): Element = dom.document.createElement("div")

  implicit val DOMTokensListContains: Containing[DOMTokenList] = new Containing[DOMTokenList] {
    override def contains(container: DOMTokenList, element: Any): Boolean = element match {
      case s: String => container.contains(s)
      case _ => false
    }

    override def containsOneOf(container: DOMTokenList, elements: BSeq[Any]): Boolean = elements.exists {
      case s: String => container.contains(s)
      case _ => false
    }

    override def containsNoneOf(container: DOMTokenList, elements: BSeq[Any]): Boolean = elements.forall {
      case s: String => container.contains(s)
      case _ => false
    }
  }
}

trait UdashFrontendTest extends UdashSharedTest with FrontendTestUtils

trait AsyncUdashFrontendTest extends AsyncUdashSharedTest with FrontendTestUtils 
Example 49
Source File: UrlChangeProvider.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.routing

import com.avsystem.commons._
import io.udash.core.Url
import io.udash.properties.MutableBufferRegistration
import io.udash.utils.Registration
import org.scalajs.dom
import org.scalajs.dom.raw.{HTMLAnchorElement, HashChangeEvent}
import org.scalajs.dom.{Element, Location}

import scala.scalajs.js


final class WindowUrlPathChangeProvider extends UrlChangeProvider {

  import dom.window
  import org.scalajs.dom.experimental.{URL => JSUrl}
  import org.scalajs.dom.raw.{MouseEvent, Node, PopStateEvent}

  private val callbacks: js.Array[Url => Unit] = js.Array()

  @inline
  private def isSameOrigin(loc: Location, url: JSUrl): Boolean =
    loc.protocol == url.protocol && loc.hostname == url.hostname && loc.port == url.port

  @inline
  private def isSamePath(loc: Location, url: JSUrl): Boolean =
    loc.pathname == url.pathname && loc.search == url.search

  @inline
  private def isSameHash(loc: Location, url: JSUrl): Boolean =
    loc.hash == url.hash

  @inline
  private def shouldIgnoreClick(
    event: MouseEvent, target: Element, href: String,
    samePath: Boolean, sameHash: Boolean, sameOrigin: Boolean
  ): Boolean = {
    // handle only links in the same browser card
    event.button != 0 || event.metaKey || event.ctrlKey || event.shiftKey ||
      // ignore click if default already prevented
      event.defaultPrevented ||
      // ignore special link types
      target.hasAttribute("download") || target.getAttribute("rel") == "external" || href.contains("mailto:") ||
      // ignore if links to different domain
      !sameOrigin ||
      // ignore if only the URL fragment changed, but path is the same
      (samePath && !sameHash)
  }

  override def initialize(): Unit = {
    window.document.addEventListener("click", (event: MouseEvent) => {
      event.target.opt
        .collect { case node: Node => node }
        .flatMap(Iterator.iterate(_)(_.parentNode).takeWhile(_ != null).collectFirstOpt { case a: HTMLAnchorElement => a })
        .filter(_.getAttribute("href") != null)
        .foreach { target =>
          val href = target.getAttribute("href")
          val location = window.location
          val newUrl = new JSUrl(href, location.toString)
          val (samePath, sameHash, sameOrigin) =
            (isSamePath(location, newUrl), isSameHash(location, newUrl), isSameOrigin(location, newUrl))
          if (!shouldIgnoreClick(event, target, href, samePath, sameHash, sameOrigin)) {
            if (!samePath) changeFragment(Url(href))
            event.preventDefault()
          }
        }
    })

    window.addEventListener("popstate", (_: PopStateEvent) => callbacks.foreach(_.apply(currentFragment)))
  }

  override def onFragmentChange(callback: Url => Unit): Registration = {
    callbacks.push(callback)
    new MutableBufferRegistration(callbacks, callback, Opt.Empty)
  }

  override def changeFragment(url: Url, replaceCurrent: Boolean): Unit = {
    (null, "", url.value) |> (
      if (replaceCurrent) window.history.replaceState(_: js.Any, _: String, _: String)
      else window.history.pushState(_: js.Any, _: String, _: String)
      ).tupled
    val withoutHash = Url(url.value.takeWhile(_ != '#'))
    callbacks.foreach(_.apply(withoutHash))
  }

  override def currentFragment: Url =
    Url(window.history.state.opt.map(_.asInstanceOf[js.Dynamic].url.toString).getOrElse(window.location.pathname))
} 
Example 50
Source File: WindowUrlPathChangeProviderTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package routing

import io.udash.testing.AsyncUdashFrontendTest
import org.scalajs.dom

class WindowUrlPathChangeProviderTest extends AsyncUdashFrontendTest {
  "WindowUrlPathChangeProvider" should {
    val provider = new routing.WindowUrlPathChangeProvider()

    "modify history on fragment change" in {
      val historyLength = dom.window.history.length
      val originalHref = dom.window.location.href
      val originalFragment = provider.currentFragment
      val fragment = "lol"

      provider.changeFragment(Url(fragment), replaceCurrent = false)

      provider.currentFragment.value should endWith(s"/$fragment")
      dom.window.location.pathname should endWith(s"/$fragment")
      retrying {
        //sometimes history takes time to catch up here
        dom.window.history.length shouldBe historyLength + 1
      }

      dom.window.history.back()

      retrying {
        provider.currentFragment shouldBe originalFragment
        dom.window.location.href shouldBe originalHref
      }
    }

    "not modify history on fragment change" in {
      val historyLength = dom.window.history.length
      val fragment = "lol"

      provider.changeFragment(Url(fragment), replaceCurrent = true)

      retrying {
        provider.currentFragment.value should endWith(s"/$fragment")
        dom.window.location.pathname should endWith(s"/$fragment")
        dom.window.history.length shouldBe historyLength
      }
    }
  }
} 
Example 51
Source File: WindowUrlFragmentChangeProviderTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package routing

import io.udash.testing.AsyncUdashFrontendTest
import org.scalajs.dom

class WindowUrlFragmentChangeProviderTest extends AsyncUdashFrontendTest {
  "WindowUrlFragmentChangeProvider" should {
    val provider = new routing.WindowUrlFragmentChangeProvider()

    "modify history on fragment change" in {
      val historyLength = dom.window.history.length
      val originalFragment = provider.currentFragment
      val originalHref = dom.window.location.href
      val fragment = "lol"

      provider.changeFragment(Url(fragment), replaceCurrent = false)

      provider.currentFragment.value shouldBe fragment
      dom.window.location.hash shouldBe "#" + fragment
      retrying {
        //sometimes history takes time to catch up here
        dom.window.history.length shouldBe historyLength + 1
      }

      dom.window.history.back()

      retrying {
        provider.currentFragment shouldBe originalFragment
        dom.window.location.href shouldBe originalHref
      }
    }

    "not modify history on fragment change" in {
      val historyLength = dom.window.history.length
      val fragment = "lol"

      provider.changeFragment(Url(fragment), replaceCurrent = true)

      retrying {
        provider.currentFragment.value shouldBe fragment
        dom.window.location.hash shouldBe "#" + fragment
        dom.window.history.length shouldBe historyLength
      }
    }
  }
} 
Example 52
Source File: TestViewFactory.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.testing

import io.udash._
import org.scalajs.dom

class TestViewFactory[T <: TestState] extends ViewFactory[T] {
  val view = new TestView
  val presenter = new TestPresenter[T]
  var count = 0

  override def create(): (View, Presenter[T]) = {
    count += 1
    (view, presenter)
  }
}

class TestView extends ContainerView {
  import scalatags.JsDom.all._
  var lastChild: View = _
  var renderingCounter = 0
  var closed = false

  override def renderChild(view: Option[View]): Unit = {
    super.renderChild(view)
    lastChild = view.orNull
  }

  override def getTemplate: Modifier = {
    renderingCounter += 1
    Seq[Modifier](
      div(
        toString,
        childViewContainer
      ),
      dom.document.createTextNode(toString),
    )
  }

  override def onClose(): Unit = {
    closed = true
  }
}

class TestFinalView extends View {
  import scalatags.JsDom.all._
  var renderingCounter = 0

  override def getTemplate: Modifier = {
    renderingCounter += 1
    span(toString)
  }
}

class TestPresenter[T <: TestState] extends Presenter[T] {
  var lastHandledState: T = _
  var closed = false

  override def handleState(state: T): Unit = lastHandledState = state
  override def onClose(): Unit = closed = true
} 
Example 53
Source File: ModuleTest.scala    From scalajs-angulate   with MIT License 5 votes vote down vote up
// -   Project: scalajs-angulate (https://github.com/jokade/scalajs-angulate)
// Description:
//
// Distributed under the MIT License (see included file LICENSE)
package test

import biz.enef.angulate._
import biz.enef.angulate.ext.{Route, RouteProvider}
import utest._

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

object ModuleTest extends AngulateTestSuite {
  override val tests = TestSuite {
    'new-{
      val module1 = angular.createModule("module1")
      assert( module1.name == "module1" )

      val module2 = angular.createModule("module2", Seq("module1"))
      assert( module2.name == "module2" )

    }

    'newWithConfig-{
      var configFnCalled = false
      val module3 = angular.createModule("module3", Nil, ($logProvider: js.Dynamic) => {
        $logProvider.debugEnabled(true)
        configFnCalled = true
      })
      angular.bootstrap(dom.document.body, Seq("module3"))
      assert( module3.name == "module3" )
      assert( configFnCalled )
    }

    'xx-{
      val module4 = angular.createModule("module4", Nil)
      module4.config( ($routeProvider:RouteProvider)=> {
        $routeProvider
          .when("/frontend/search",
            Route(templateUrl = "search.html", controller = "SearchCtrl"))
      })
    }
  }
} 
Example 54
Source File: ContactFormPresenter.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.rest.views.contact

import io.udash._
import io.udash.core.Presenter
import io.udash.demos.rest.model.{Contact, ContactId}
import io.udash.demos.rest.{ContactFormState, ApplicationContext, IndexState}
import org.scalajs.dom

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

class ContactFormPresenter(model: ModelProperty[ContactEditorModel]) extends Presenter[ContactFormState] {
  import ApplicationContext._

  override def handleState(state: ContactFormState): Unit = {
    state match {
      case ContactFormState(None) =>
        model.subProp(_.loaded).set(true)
        model.subProp(_.loadingText).set("")

        model.subProp(_.isNewContact).set(true)
        model.subProp(_.firstName).set("")
        model.subProp(_.lastName).set("")
        model.subProp(_.phone).set("")
        model.subProp(_.email).set("")
      case ContactFormState(Some(id)) =>
        model.subProp(_.loaded).set(false)
        model.subProp(_.loadingText).set("Loading contact data...")
        model.subProp(_.isNewContact).set(false)

        loadContactData(id)
    }
  }

  def loadContactData(id: ContactId): Unit = {
    restServer.contacts(id).load() onComplete {
      case Success(contact) =>
        model.subProp(_.loaded).set(true)
        model.subProp(_.id).set(id)
        model.subProp(_.firstName).set(contact.firstName)
        model.subProp(_.lastName).set(contact.lastName)
        model.subProp(_.phone).set(contact.phone)
        model.subProp(_.email).set(contact.email)
      case Failure(ex) =>
        model.subProp(_.loadingText).set(s"Problem with contact details loading: $ex")
    }
  }

  def createContact(): Unit = {
    restServer.contacts().create(Contact(
      ContactId(-1),
      model.subProp(_.firstName).get,
      model.subProp(_.lastName).get,
      model.subProp(_.phone).get,
      model.subProp(_.email).get
    )) onComplete {
      case Success(contact) =>
        applicationInstance.goTo(IndexState)
      case Failure(ex) =>
        dom.window.alert(s"Contact creation failed: $ex")
    }
  }

  def updateContact(): Unit =
    restServer.contacts(model.subProp(_.id).get).update(Contact(
      model.subProp(_.id).get,
      model.subProp(_.firstName).get,
      model.subProp(_.lastName).get,
      model.subProp(_.phone).get,
      model.subProp(_.email).get
    )) onComplete {
      case Success(contact) =>
        applicationInstance.goTo(IndexState)
      case Failure(ex) =>
        dom.window.alert(s"Contact update failed: $ex")
    }
} 
Example 55
Source File: IndexPresenter.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.rest.views.index

import io.udash._
import io.udash.demos.rest.IndexState
import io.udash.demos.rest.model.{Contact, ContactId, PhoneBookId, PhoneBookInfo}
import org.scalajs.dom

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

class IndexPresenter(model: ModelProperty[IndexViewModel]) extends Presenter[IndexState.type] {
  import io.udash.demos.rest.ApplicationContext._

  override def handleState(state: IndexState.type): Unit =
    refresh()

  def removeContact(id: ContactId): Unit = {
    restServer.contacts(id).remove() onComplete {
      case Success(removedContact) =>
        model.subSeq(_.contacts.elements).remove(removedContact)
        refreshPhoneBooksSizes(model.subModel(_.books))
      case Failure(ex) =>
        dom.window.alert(s"Contact removing failed! ($ex)")
    }
  }

  def removePhoneBook(id: PhoneBookId): Unit = {
    restServer.phoneBooks(id).remove() onComplete {
      case Success(_) =>
        val elements = model.subSeq(_.books.elements)
        val removed = elements.get.find(_.id == id)
        removed.foreach(elements.remove)
      case Failure(ex) =>
        dom.window.alert(s"Phone book removing failed! ($ex)")
    }
  }

  def refresh(): Unit = {
    refreshPhoneBooks(model.subModel(_.books), restServer.phoneBooks().load(), "Loading phone books...")
    refreshContacts(model.subModel(_.contacts), restServer.contacts().load(), "Loading contacts...")
  }

  private def refreshContacts(model: ModelProperty[DataLoadingModel[Contact]], elements: Future[Seq[Contact]], loadingText: String) : Unit = {
    model.subProp(_.loaded).set(false)
    model.subProp(_.loadingText).set(loadingText)

    elements onComplete {
      case Success(elems) =>
        model.subProp(_.loaded).set(true)
        model.subSeq(_.elements).set(elems)
      case Failure(ex) =>
        model.subProp(_.loadingText).set(s"Error: $ex")
    }
  }

  private def refreshPhoneBooks(model: ModelProperty[DataLoadingModel[PhoneBookExtInfo]], elements: Future[Seq[PhoneBookInfo]], loadingText: String) : Unit = {
    model.subProp(_.loaded).set(false)
    model.subProp(_.loadingText).set(loadingText)

    elements onComplete {
      case Success(elems) =>
        model.subProp(_.loaded).set(true)
        model.subSeq(_.elements).clear()

        elems.foreach { el =>
          model.subSeq(_.elements).append(
            PhoneBookExtInfo(el.id, el.name, el.description, 0)
          )
        }

        refreshPhoneBooksSizes(model)
      case Failure(ex) =>
        model.subProp(_.loadingText).set(s"Error: $ex")
    }
  }

  private def refreshPhoneBooksSizes(model: ModelProperty[DataLoadingModel[PhoneBookExtInfo]]): Unit = {
    model.subSeq(_.elements).elemProperties.foreach { el =>
      val element = el.asModel
      restServer.phoneBooks(el.get.id).contacts().count() onComplete {
        case Success(count) =>
          element.subProp(_.contactsCount).set(count)
        case Failure(ex) =>
          dom.window.alert(s"Contacts count for book ${el.get.id} loading failed: $ex")
          element.subProp(_.contactsCount).set(-1)
      }
    }
  }
} 
Example 56
Source File: FrontEnd.scala    From threejs-facade   with Mozilla Public License 2.0 5 votes vote down vote up
package org.denigma.preview

import org.denigma.binding.binders.GeneralBinder
import org.denigma.binding.extensions.sq
import org.denigma.binding.views.BindableView
import org.querki.jquery._
import org.scalajs.dom
import org.scalajs.dom.raw.HTMLElement
import org.denigma.binding.extensions._

import scala.collection.immutable.Map
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
import scala.util.Try


@JSExport("FrontEnd")
object FrontEnd extends BindableView with scalajs.js.JSApp
{

  lazy val elem: HTMLElement = dom.document.body

  val sidebarParams = js.Dynamic.literal(
    exclusive = false,
    dimPage = false,
    closable = false,
    useLegacy = true
  )


  override lazy val injector = defaultInjector.register("sidebar")((el, params) => new SidebarView(el).withBinder(new GeneralBinder(_)))


  @JSExport
  def main(): Unit = {
    this.bindView()
    Example.activate() //activate examples
  }

  @JSExport
  def showLeftSidebar() = {
    $(".left.sidebar").dyn.sidebar(sidebarParams).sidebar("show")
  }

  @JSExport
  def load(content: String, into: String): Unit = {
    dom.document.getElementById(into).innerHTML = content
  }

  @JSExport
  def moveInto(from: String, into: String): Unit = {
    for {
      ins <- sq.byId(from)
      intoElement <- sq.byId(into)
    } {
      this.loadElementInto(intoElement, ins.innerHTML)
      ins.parentNode.removeChild(ins)
    }
  }

  withBinder(new GeneralBinder(_))

} 
Example 57
Source File: Animation.scala    From threejs-facade   with Mozilla Public License 2.0 5 votes vote down vote up
package org.denigma.threejs.extensions.animations

import java.util.Date

import org.scalajs.dom
import Animation.{Started, AniState}
import scala.concurrent.duration.Duration
import scala.scalajs.js


class Scheduler
{
  def current: Double = js.Date.now
  var animations = List.empty[Animation]

  def add(ani: Animation): Unit = {
    this.animations = ani :: animations
    ani.state = Animation.Running(current)
  }

  def tick(): Unit =   {
    val now = current
    animations.foreach{ani=>
      ani.state match {
        case Animation.Running(start)=> ani(now)
        case _ =>
        // dom.console.info(other.toString)
        // do nothing
      }
    }
  }

  protected def onEnterFrameFunction(double: Double): Unit = {
    this.tick()
    start()
  }

  def start(): Scheduler = {
    dom.window.requestAnimationFrame(onEnterFrameFunction _ )
    this
  }


}

object Easings {

  val linear: Double=>Double = i=>i

}


object Animation{
  trait AniState
  trait Started extends AniState{
    def start: Double

  }
  case object Stopped extends AniState
  case class Finished(start: Double) extends Started
  case class Paused(start: Double) extends Started
  case class Running(start: Double) extends Started
  case class Backward(start: Double, finished: Double) extends Started

}


class Animation(val length: Duration, easing: Double=>Double = Easings.linear)(fun: (Double=>Unit)){

  lazy val lengthMillis: Long = length.toMillis

  var state: AniState = Animation.Stopped

  def apply(current: Double): Unit =    state match {
    case st: Started=>
      val finish: Double = st.start + this.lengthMillis
      easing(1.0-(finish-current)/length.toMillis) match{
        case p: Double if p>=1.0=>
          fun(1.0)
          this.state = Animation.Finished(current)
        case p: Double if p < 0.0=>
          dom.console.error(s"animation percent is $p that is below zero!\n " +
            s"Current time is $current, start is ${st.start} and length is $lengthMillis")
          this.state = Animation.Finished(current)

        case p: Double=>
          fun(p)
        // dom.console.info( s"Current time is $current, start is ${st.start} and length is $lengthMillis and percent is $p")

      }

    case _=> dom.console.error("trying to run an operation that has not started")
  }

  def go(implicit scheduler: Scheduler): Unit = {
    scheduler.add(this)
  }

} 
Example 58
Source File: JumpCameraControls.scala    From threejs-facade   with Mozilla Public License 2.0 5 votes vote down vote up
package org.denigma.threejs.extensions.controls

import org.denigma.threejs.extensions.animations.{Animation, Scheduler}
import org.denigma.threejs.{Camera, Scene, Vector3}
import org.scalajs.dom
import org.scalajs.dom.raw.{Element, HTMLElement}
import org.scalajs.dom.MouseEvent

import scala.concurrent.duration
import scala.concurrent.duration.Duration
import scala.concurrent.duration.MILLISECONDS
import scala.language.postfixOps


class JumpCameraControls(val camera: Camera,
  val element: Element, //scalastyle:ignore
  val scene: Scene,
  val width: Double, val height: Double,
  center: Vector3 = new Vector3())
  extends HoverControls(camera, element, center) with IntersectionControls {

  implicit val scheduler = new Scheduler().start()

  override def onMouseMove(event: MouseEvent)= {
    this.onCursorMove(event.clientX, event.clientY, width, height)
    rotateOnMove(event)
  }

  def moveTo(position: Vector3): Unit = {
    val start = center.clone()
    val dp = new Vector3().subVectors(position, center)
    dom.console.info(dp)

    new Animation(Duration(1, duration.SECONDS))(p => {

      val m = dp.clone().multiplyScalar(p)
      val cur = start.clone().add(m)
      // dom.console.info(cur)
      center.copy(cur)
    }).go(scheduler)
    // center.copy(position)
  }

  override def onMouseDown(event: MouseEvent): Unit = {
    this.intersections.headOption match {
      case Some(obj) => obj.`object`.position match {
        case p: Vector3 if p.equals(center) => super.onMouseDown(event)
        case p: Vector3 => moveTo(p)
      }
      case None => super.onMouseDown(event)
    }

  }

} 
Example 59
Source File: IntersectionControls.scala    From threejs-facade   with Mozilla Public License 2.0 5 votes vote down vote up
package org.denigma.threejs.extensions.controls

import org.denigma.threejs._
import org.scalajs.dom

trait IntersectionControls {
  def camera: Camera
  def scene: Object3D

  lazy val raycaster = new Raycaster()

  var intersections = List.empty[Intersection]
  var underMouse = Map.empty[Object3D, List[Intersection]]
  var last = Map.empty[Object3D, List[Intersection]]
  var exit = Map.empty[Object3D, List[Intersection]]
  var enter = Map.empty[Object3D, List[Intersection]]

  def findIntersections(x: Double, y: Double): List[Intersection] =
    {
      val vector = new Vector3(x, y, 1)
      raycaster.setFromCamera(vector, camera)
      raycaster.intersectObjects(scene.children).sortWith((a, b) => a.point.distanceTo(vector) < b.point.distanceTo(vector)).toList
    }

  def onCursorMove(cordX: Double, cordY: Double, width: Double, height: Double): Unit = {
    val mouseX = 2 * cordX / width - 1
    val mouseY = -2 * cordY / height + 1 // scalastyle:ignore
    intersections = findIntersections(mouseX, mouseY)
    underMouse = intersections.groupBy(_.`object`)
    val l = last // if I do not do this assigment and use last instead of l I get into trouble
    this.exit = l.filterKeys(!underMouse.contains(_))
    this.enter = underMouse.filterKeys(!l.contains(_))
    // if(exit.exists{case (key,value)=>enter.contains(key)}) dom.console.error("same enterexit")
    val s = enter.size
    last = underMouse
    if (s != enter.size) dom.console.error("ScalaJS error with immutable collections")
  }

} 
Example 60
Source File: GraphiQLClient.scala    From tap   with Apache License 2.0 5 votes vote down vote up
package io.heta.tap.client

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

@JSExportTopLevel("io.heta.tap.client.GraphiQLClient")
object GraphiQLClient {

  @JSExport
  def run(): Unit = {
    println("Loading GraphiQLClient...")

    val graphiqlDiv = dom.document.getElementById("graphiql")
    val result  = GraphiqlSetup.load(GraphiQLQueries.allQueries, GraphiQLQueries.allParams)
    println(s"Load result: $result")
  }

} 
Example 61
Source File: oscilloscope.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
// see https://scastie.scala-lang.org/004L3z36R6e55O5BvBab7Q
// source: https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/Splash.scala

import java.lang.Math._

import org.scalajs.dom
import org.scalajs.dom.html.{Canvas => JsCanvas}
import dom.html
import scalajs.js.annotation.JSExport

val canvas = dom.document.createElement("canvas").asInstanceOf[JsCanvas]


canvas

def clear() = {
  canvas.width = 400
  canvas.height = 400
}
clear()

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

def h = canvas.height
def w = canvas.width

var x = 0.0
type Graph = (String, Double => Double)
val graphs = Seq[Graph](
  ("red", sin),
  ("green", x => abs(x % 4 - 2) - 1),
  ("blue", x => sin(x/12) * sin(x))
).zipWithIndex
dom.window.setInterval(() => {
  x = (x + 1) % w; if (x == 0) clear()
  for (((color, f), i) <- graphs) {
    val offset = h / 3 * (i + 0.5)
    val y = f(x / w * 75) * h / 30
    brush.fillStyle = color
    brush.fillRect(x, y + offset, 3, 3)
  }
}, 20) 
Example 62
Source File: LocalStorage.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie
package client

import play.api.libs.json.Json

import org.scalajs.dom
import org.scalajs.dom.window.localStorage

object LocalStorage {
  private val stateKey = "state"

  def save(state: ScastieState): Unit = {
    localStorage.setItem(stateKey, Json.stringify(Json.toJson(state)))
  }

  def load: Option[ScastieState] = {
    try {
      Option(localStorage.getItem(stateKey))
        .flatMap(raw => Json.fromJson[ScastieState](Json.parse(raw)).asOpt)
    } catch {
      case e: Exception =>
        dom.console.log(e.toString)
        None
    }
  }
} 
Example 63
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 64
Source File: EmbeddedMenu.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components

import com.olegych.scastie.api._
import com.olegych.scastie.client.View

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

import org.scalajs.dom

final case class EmbeddedMenu(isRunning: Boolean,
                              inputs: Inputs,
                              inputsHasChanged: Boolean,
                              embeddedSnippetId: Option[SnippetId],
                              serverUrl: Option[String],
                              run: Reusable[Callback],
                              save: Reusable[CallbackTo[Option[SnippetId]]],
                              setView: View ~=> Callback) {
  @inline def render: VdomElement = EmbeddedMenu.component(this)
}

object EmbeddedMenu {

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

  private def render(props: EmbeddedMenu): VdomElement = {

    val urlBase = props.serverUrl.getOrElse("")

    def openScastie: Callback = {

      def open(snippetId: SnippetId): Callback = {
        Callback(
          dom.window
            .open(
              urlBase + "/" + snippetId.url,
              "_blank"
            )
            .focus()
        )

      }

      println("props.embeddedSnippetId: " + props.embeddedSnippetId)
      println("props.inputsHasChanged: " + props.inputsHasChanged)

      props.embeddedSnippetId match {
        case Some(snippetId) if !props.inputsHasChanged => {
          open(snippetId)
        }

        case _ => {
          props.save.asCBO.flatMap(open)
        }
      }

    }

    ul(cls := "embedded-menu")(
      RunButton(
        isRunning = props.isRunning,
        isStatusOk = true,
        save = props.run,
        setView = props.setView
      ).render,
      li(cls := "logo")(
        img(src := urlBase + Assets.logoUrl),
        span("to Scastie"),
        onClick --> openScastie
      )
    )
  }

  private val component =
    ScalaComponent
      .builder[EmbeddedMenu]("EmbeddedMenu")
      .render_P(render)
      .configure(Reusability.shouldComponentUpdate)
      .build
} 
Example 65
Source File: RenderAnnotations.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import com.olegych.scastie.api

import japgolly.scalajs.react.Callback

import codemirror.{TextAreaEditor, CodeMirror, modeScala}

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLElement

object RenderAnnotations {
  def apply(editor: TextAreaEditor,
            currentProps: Option[Editor],
            nextProps: Editor,
            state: EditorState,
            modState: (EditorState => EditorState) => Callback): Callback = {

    val doc = editor.getDoc()

    AnnotationDiff.setAnnotations[api.Instrumentation](
      currentProps,
      nextProps,
      state,
      modState,
      (props, _) => props.instrumentations, {
        case api.Instrumentation(api.Position(start, end), api.Value(value, tpe)) => {

          val startPos = doc.posFromIndex(start)
          val endPos = doc.posFromIndex(end)

          val process = (node: HTMLElement) => {
            CodeMirror.runMode(s"$value: $tpe", modeScala, node)
            node.title = tpe
            ()
          }

          val nl = '\n'

          if (value.contains(nl))
            Annotation.nextline(editor, endPos, value, process)
          else Annotation.inline(editor, startPos, value, process)
        }

        case api.Instrumentation(api.Position(start, end), api.Html(content, folded)) => {

          val startPos = doc.posFromIndex(start)
          val endPos = doc.posFromIndex(end)

          val process: (HTMLElement => Unit) = _.innerHTML = content
          if (!folded) Annotation.nextline(editor, endPos, content, process)
          else Annotation.fold(editor, startPos, endPos, content, process)
        }

        case instrumentation @ api.Instrumentation(
              api.Position(start, end),
              api.AttachedDom(uuid, folded)
            ) => {

          val startPos = doc.posFromIndex(start)
          val endPos = doc.posFromIndex(end)

          val domNode = nextProps.attachedDoms.get(uuid)

          if (!domNode.isEmpty) {
            val process: (HTMLElement => Unit) = element => {
              domNode.foreach(element.appendChild)
              ()
            }

            if (!folded) Annotation.nextline(editor, endPos, "", process)
            else Annotation.fold(editor, startPos, endPos, "", process)

          } else {
            dom.console.log("cannot find dom element uuid: " + uuid)
            Empty
          }
        }

      },
      _.renderAnnotations,
      (state, annotations) => state.copy(renderAnnotations = annotations)
    )
  }
} 
Example 66
Source File: CodeFolds.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import codemirror.TextAreaEditor

import japgolly.scalajs.react.Callback

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLElement

object CodeFoldingAnnotations {
  private def findFolds(code: String): Set[RangePosititon] = {
    val (folds, _, _) = {
      val lines = code.split("\n").toList

      lines.foldLeft((Set.empty[RangePosititon], Option.empty[Int], 0)) {
        case ((folds, open, indexTotal), line) => {
          val (folds0, open0) =
            if (line == "// fold") {
              if (open.isEmpty) (folds, Some(indexTotal))
              else (folds, open)
            } else if (line == "// end-fold") {
              open match {
                case Some(start) =>
                  (folds + RangePosititon(start, indexTotal + line.length), None)

                case None => (folds, None)
              }
            } else {
              (folds, open)
            }

          (folds0, open0, indexTotal + line.length + 1)
        }
      }
    }

    folds
  }

  def apply(editor: TextAreaEditor, props: Editor): Callback = {
    Callback {
      val doc = editor.getDoc()
      findFolds(props.code).foreach { range =>
        val posStart = doc.posFromIndex(range.indexStart)
        val posEnd = doc.posFromIndex(range.indexEnd)

        var annotRef: Option[Annotation] = None
        val unfold: (HTMLElement => Unit) = { element =>
          def clear(event: dom.Event): Unit = {
            annotRef.foreach(_.clear())
          }

          element.className = element.className + " code-fold"
          element.addEventListener("touchstart", clear _, false)
          element.addEventListener("dblclick", clear _, false)
          element.addEventListener("click", clear _, false)
        }
        val annot = Annotation.fold(
          editor,
          posStart,
          posEnd,
          "-- Click to unfold --",
          unfold
        )

        annotRef = Some(annot)

        (range, annot)
      }
    }
  }
} 
Example 67
Source File: RuntimeErrorAnnotations.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import com.olegych.scastie.api.RuntimeError

import japgolly.scalajs.react.Callback

import codemirror.TextAreaEditor

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLDivElement

object RuntimeErrorAnnotations {
  def apply(editor: TextAreaEditor,
            currentProps: Option[Editor],
            nextProps: Editor,
            state: EditorState,
            modState: (EditorState => EditorState) => Callback): Callback = {

    val doc = editor.getDoc()

    AnnotationDiff.setAnnotations[RuntimeError](
      currentProps,
      nextProps,
      state,
      modState,
      (props, _) => props.runtimeError.toSet,
      runtimeError => {
        val line = runtimeError.line.getOrElse(0)

        val icon =
          dom.document.createElement("i").asInstanceOf[HTMLDivElement]

        icon.className = "fa fa-times-circle"

        val el =
          dom.document.createElement("div").asInstanceOf[HTMLDivElement]
        el.className = "runtime-error"

        val msg = dom.document.createElement("pre")
        msg.textContent = if (runtimeError.fullStack.nonEmpty) runtimeError.fullStack else runtimeError.message

        el.appendChild(icon)
        el.appendChild(msg)

        Line(doc.addLineWidget(line - 1, el))
      },
      _.runtimeErrorAnnotations,
      (state, annotations) => state.copy(runtimeErrorAnnotations = annotations)
    )
  }
} 
Example 68
Source File: EditorOptions.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import com.olegych.scastie.client.isMac
import com.olegych.scastie.client.isMobile
import scala.scalajs.js
import org.scalajs.dom

import codemirror.{Editor => CodeMirrorEditor2, CodeMirror => CM}

import japgolly.scalajs.react.BackendScope

object EditorOptions {
  object Keys {
    val ctrl = if (isMac) "Cmd" else "Ctrl"

    val saveOrUpdate = ctrl + "-Enter"
    val openNew = ctrl + "-M"
    val clear = "Esc"
    val help = "F1"
    val console = "F3"
    val format = "F6"
    val lineNumbers = "F7"
    val presentation = "F8"
  }

  def apply(props: Editor, scope: BackendScope[Editor, EditorState]): codemirror.Options = {
    val theme =
      if (props.isDarkTheme) "dark"
      else "light"

    val highlightSelectionMatches =
      if (isMobile) false
      else
        js.Dictionary(
          //messes up input on mobile browsers
          "showToken" -> js.Dynamic.global.RegExp("\\w")
        )

    def command(f: => Unit): js.Function1[CodeMirrorEditor2, Unit] = { ((editor: CodeMirrorEditor2) => f)
    }

    def commandE(
        f: CodeMirrorEditor2 => Unit
    ): js.Function1[CodeMirrorEditor2, Unit] = { ((editor: CodeMirrorEditor2) => f(editor))
    }

    import Keys._
    val indentWithTabs = false
    js.Dictionary[Any](
        "autoRefresh" -> props.isEmbedded,
        "mode" -> "text/x-scala",
        "autofocus" -> !props.isEmbedded,
        "lineNumbers" -> props.showLineNumbers,
        "lineWrapping" -> false,
        "tabSize" -> 2,
        "tabindex" -> 1,
        "indentWithTabs" -> indentWithTabs,
        "theme" -> s"solarized $theme",
        "smartIndent" -> true,
        "keyMap" -> "sublime",
        "scrollPastEnd" -> false,
        "scrollbarStyle" -> "simple",
        "autoCloseBrackets" -> true,
        "matchBrackets" -> true,
        "showCursorWhenSelecting" -> true,
        "highlightSelectionMatches" -> highlightSelectionMatches,
        "extraKeys" -> js.Dictionary(
          "Tab" -> commandE { e =>
            if (e.somethingSelected()) e.indentSelection("add")
            else e.execCommand(if (indentWithTabs) "insertTab" else "insertSoftTab")
          },
          saveOrUpdate -> command(props.saveOrUpdate.runNow()),
          ctrl + "-S" -> command(props.saveOrUpdate.runNow()),
          openNew -> command(props.openNewSnippetModal.runNow()),
          ctrl + "-L" -> CM.Pass,
          clear -> command(props.clear.runNow()),
          help -> command(props.toggleHelp.runNow()),
          console -> command(props.toggleConsole.runNow()),
          format -> command(props.formatCode.runNow()),
          lineNumbers -> command(props.toggleLineNumbers.runNow()),
          presentation -> command {
            if (!props.isEmbedded) {
              props.togglePresentationMode.runNow()
              if (!props.isPresentationMode) {
                dom.window
                  .alert("Press F8 again to leave the presentation mode")
              }
            }
          }
        )
      )
      .asInstanceOf[codemirror.Options]
  }
} 
Example 69
Source File: ProblemAnnotations.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import com.olegych.scastie.api
import com.olegych.scastie.client.AnsiColorFormatter

import codemirror.TextAreaEditor

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLDivElement

import japgolly.scalajs.react.Callback

object ProblemAnnotations {

  def apply(editor: TextAreaEditor,
            currentProps: Option[Editor],
            nextProps: Editor,
            state: EditorState,
            modState: (EditorState => EditorState) => Callback): Callback = {

    val doc = editor.getDoc()

    AnnotationDiff.setAnnotations[api.Problem](
      currentProps,
      nextProps,
      state,
      modState,
      (props, _) => props.compilationInfos,
      info => {
        val line = info.line.getOrElse(0)

        val icon =
          dom.document.createElement("i").asInstanceOf[HTMLDivElement]

        val iconSeverity =
          info.severity match {
            case api.Info    => "fa fa-info"
            case api.Warning => "fa fa-exclamation-triangle"
            case api.Error   => "fa fa-times-circle"
          }

        val classSeverity =
          info.severity match {
            case api.Info    => "info"
            case api.Warning => "warning"
            case api.Error   => "error"
          }

        icon.className = iconSeverity

        val el =
          dom.document.createElement("div").asInstanceOf[HTMLDivElement]
        el.className = s"compilation-info $classSeverity"

        val msg = dom.document.createElement("pre")

        msg.innerHTML = AnsiColorFormatter.formatToHtml(info.message)

        el.appendChild(icon)
        el.appendChild(msg)

        Line(doc.addLineWidget(line - 1, el))
      },
      _.problemAnnotations,
      (state, annotations) => state.copy(problemAnnotations = annotations)
    )
  }
} 
Example 70
Source File: Annotation.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.client.components.editor

import codemirror.{TextMarker, TextMarkerOptions, LineWidget, TextAreaEditor}
import codemirror.CodeMirror.{Pos => CMPosition}

import org.scalajs.dom
import org.scalajs.dom.raw.{HTMLElement, HTMLPreElement, HTMLDivElement}

import scala.scalajs.js

private[editor] sealed trait Annotation {
  def clear(): Unit
}

private[editor] case class Line(lw: LineWidget) extends Annotation {
  def clear(): Unit = lw.clear()
}

private[editor] case class Marked(tm: TextMarker) extends Annotation {
  def clear(): Unit = tm.clear()
}

private[editor] case object Empty extends Annotation {
  def clear(): Unit = ()
}

object Annotation {
  def nextline(editor: TextAreaEditor,
               endPos: CMPosition,
               content: String,
               process: (HTMLElement => Unit),
               options: js.Any = null): Annotation = {
    val node =
      dom.document.createElement("pre").asInstanceOf[HTMLPreElement]
    node.className = "line"
    node.innerHTML = content

    process(node)
    Line(editor.addLineWidget(endPos.line, node, options))
  }

  def inline(editor: TextAreaEditor, startPos: CMPosition, content: String, process: (HTMLElement => Unit)): Annotation = {

    // inspired by blink/devtools WebInspector.JavaScriptSourceFrame::_renderDecorations

    val node =
      dom.document.createElement("pre").asInstanceOf[HTMLPreElement]

    node.className = "inline"

    def updateLeft(editor2: codemirror.Editor): Unit = {
      val doc2 = editor2.getDoc()
      val lineNumber = startPos.line
      doc2.getLine(lineNumber).toOption match {
        case Some(line) =>
          val basePos = new CMPosition { line = lineNumber; ch = 0 }
          val offsetPos = new CMPosition {
            line = lineNumber
            ch = doc2.getLine(lineNumber).map(_.length).getOrElse(0)
          }
          val mode = "local"
          val base = editor2.cursorCoords(basePos, mode)
          val offset = editor2.cursorCoords(offsetPos, mode)
          node.style.left = (offset.left - base.left).toString + "px"
        case _ =>
          // the line was deleted
          node.innerHTML = null
      }
    }
    updateLeft(editor)
    editor.onChange((editor, _) => updateLeft(editor))

    node.innerHTML = content
    process(node)

    Line(editor.addLineWidget(startPos.line, node, null))
  }

  def fold(editor: TextAreaEditor, startPos: CMPosition, endPos: CMPosition, content: String, process: (HTMLElement => Unit)): Annotation = {

    val node =
      dom.document.createElement("div").asInstanceOf[HTMLDivElement]
    node.className = "fold"
    node.innerHTML = content
    process(node)
    Marked(
      editor
        .getDoc()
        .markText(
          startPos,
          endPos,
          js.Dictionary[Any](
              "replacedWith" -> node,
              "handleMouseEvents" -> true
            )
            .asInstanceOf[TextMarkerOptions]
        )
    )
  }
} 
Example 71
Source File: instrumented.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
import _root_.com.olegych.scastie.api.runtime._
object Playground extends _root_.com.olegych.scastie.api.runtime.DomHook { private val instrumentationMap$ = _root_.scala.collection.mutable.Map.empty[_root_.com.olegych.scastie.api.Position, _root_.com.olegych.scastie.api.Render];def instrumentations$ = instrumentationMap$.toList.map{ case (pos, r) => _root_.com.olegych.scastie.api.Instrumentation(pos, r) };
import org.scalajs.dom
import org.scalajs.dom.html.Canvas

scala.Predef.locally {val $t = dom.document.createElement("canvas").asInstanceOf[Canvas]; instrumentationMap$(_root_.com.olegych.scastie.api.Position(59, 116)) = _root_.com.olegych.scastie.api.runtime.Runtime.render($t, attach _);$t} 
}
@_root_.scala.scalajs.js.annotation.JSExportTopLevel("ScastiePlaygroundMain") class ScastiePlaygroundMain {
  def suppressUnusedWarnsScastie = Html
  val playground = _root_.com.olegych.scastie.api.RuntimeError.wrap(Playground)
  @_root_.scala.scalajs.js.annotation.JSExport def result = _root_.com.olegych.scastie.api.runtime.Runtime.write(playground.map(_.instrumentations$))
  @_root_.scala.scalajs.js.annotation.JSExport def attachedElements: _root_.scala.scalajs.js.Array[_root_.org.scalajs.dom.raw.HTMLElement] =
    playground match {
      case Right(p) => p.attachedElements
      case Left(_) => _root_.scala.scalajs.js.Array[_root_.org.scalajs.dom.raw.HTMLElement]()
    }
} 
Example 72
Source File: AjaxClient.scala    From scalajs-spa-tutorial   with Apache License 2.0 5 votes vote down vote up
package spatutorial.client.services

import java.nio.ByteBuffer

import boopickle.Default._
import org.scalajs.dom

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.typedarray._

object AjaxClient extends autowire.Client[ByteBuffer, Pickler, Pickler] {
  override def doCall(req: Request): Future[ByteBuffer] = {
    dom.ext.Ajax.post(
      url = "/api/" + req.path.mkString("/"),
      data = Pickle.intoBytes(req.args),
      responseType = "arraybuffer",
      headers = Map("Content-Type" -> "application/octet-stream")
    ).map(r => TypedArrayBuffer.wrap(r.response.asInstanceOf[ArrayBuffer]))
  }

  override def read[Result: Pickler](p: ByteBuffer) = Unpickle[Result].fromBytes(p)
  override def write[Result: Pickler](r: Result) = Pickle.intoBytes(r)
} 
Example 73
Source File: ConfirmAccountCreation.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package client.modals

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import client.components.Bootstrap._
import client.components._
import client.css.DashBoardCSS
import client.sessionitems.SessionItems
import shared.models.EmailValidationModel

import scala.language.reflectiveCalls
import scalacss.ScalaCssReact._
import org.querki.jquery._
import diode.AnyAction._
import org.querki.jquery._
import org.scalajs.dom
import org.scalajs.dom._

object ConfirmAccountCreation {
  @inline private def bss = GlobalStyles.bootstrapStyles

  case class Props(submitHandler: (EmailValidationModel, Boolean) => Callback)

  case class State(emailValidationModel: EmailValidationModel, accountValidationFailed: Boolean = false,
                   hostName: String = s"https://${dom.window.location.hostname}:9876")

  class Backend(t: BackendScope[Props, State]) {
    def submitForm(e: ReactEventI) = {
      e.preventDefault()
      window.sessionStorage.setItem(SessionItems.ApiDetails.API_URL, t.state.runNow().hostName)
      // mark it as NOT cancelled (which is the default)
      t.modState(s => s.copy(accountValidationFailed = true))
    }


    def updateIp(e: ReactEventI) = {
      val value = e.target.value
      //      println(s"value:$value")
      t.modState(s => s.copy(hostName = value))
    }

    def hide = {
      // instruct Bootstrap to hide the modal
      $(t.getDOMNode()).modal("hide")
    }

    def updateToken(e: ReactEventI) = {
      // update TodoItem content
      val value = e.target.value
      t.modState(s => s.copy(emailValidationModel = s.emailValidationModel.copy(token = value)))
    }

    def formClosed(state: State, props: Props): Callback = {
      // call parent handler with the new item and whether form was OK or cancelled
      props.submitHandler(state.emailValidationModel, state.accountValidationFailed)
    }

    def render(s: State, p: Props) = {
      // log.debug(s"User is ${if (s.item.id == "") "adding" else "editing"} a todo")
      val headerText = "Confirm Account Creation"
      Modal(
        Modal.Props(
          // header contains a cancel button (X)
          header = hide => <.span(<.button(^.tpe := "button", bss.close, ^.onClick --> hide, Icon.close), <.div(DashBoardCSS.Style.modalHeaderText)(headerText)),
          closed = () => formClosed(s, p)
        ),
        <.form(^.onSubmit ==> submitForm)(
          <.div(^.className := "row")(
            <.div(^.className := "col-md-12 col-sm-12 col-xs-12")(
              <.div(DashBoardCSS.Style.scltInputModalContainerMargin)(
                // <.div(DashBoardCSS.Style.modalHeaderFont)("Confirm Account Creation"),
                <.h5("After registration, you were emailed a confirmation code. Please enter the code below"),
                <.div(^.className := "form-group")(
                  <.input(^.tpe := "text", bss.formControl, DashBoardCSS.Style.inputModalMargin, ^.id := "Name",
                    ^.placeholder := "username", ^.value := s.hostName, ^.onChange ==> updateIp, ^.required := true)),
                <.input(^.tpe := "text", bss.formControl, DashBoardCSS.Style.inputModalMargin, DashBoardCSS.Style.marginTop10px,
                  ^.id := "Name", ^.placeholder := "Enter validation code", ^.value := s.emailValidationModel.token, ^.onChange ==> updateToken),
                <.button(^.tpe := "submit", ^.className := "btn", DashBoardCSS.Style.btnWidth, DashBoardCSS.Style.btnBackground, "Confirm")
              ),
              <.div(bss.modal.footer, DashBoardCSS.Style.marginTop5p, DashBoardCSS.Style.marginLeftRight)()
            )
          )
        )
      )
    }
  }

  private val component = ReactComponentB[Props]("ConfirmAccountCreation")
    .initialState_P(p => State(new EmailValidationModel("")))
    .renderBackend[Backend]
    .componentDidUpdate(scope => Callback {
      if (scope.currentState.accountValidationFailed) {
        scope.$.backend.hide
      }
    })
    .build

  def apply(props: Props) = component(props)
} 
Example 74
Source File: playajaxclient.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package synereo.client.services

import boopickle.Pickler
import java.nio.ByteBuffer

import boopickle.Default._
import org.scalajs.dom

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.typedarray._



object PlayAjaxClient extends autowire.Client[ByteBuffer, Pickler, Pickler] {
  override def doCall(req: Request): Future[ByteBuffer] = {
    dom.ext.Ajax.post(
      url = "/api/" + req.path.mkString("/"),
      data = Pickle.intoBytes(req.args),
      responseType = "arraybuffer",
      headers = Map("Content-Type" -> "application/octet-stream")
    ).map(r => TypedArrayBuffer.wrap(r.response.asInstanceOf[ArrayBuffer]))
  }

  override def read[Result: Pickler](p: ByteBuffer) = Unpickle[Result].fromBytes(p)
  override def write[Result: Pickler](r: Result) = Pickle.intoBytes(r)
} 
Example 75
Source File: SearchComponent.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package synereo.client.components

import synereo.client.handlers._
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import synereo.client.css.SynereoCommanStylesCSS
import synereo.client.services.SYNEREOCircuit
import diode.AnyAction._
import shared.dtos._
import shared.models.Label
import synereo.client.sessionitems.SessionItems
import org.scalajs.dom

import scalacss.ScalaCssReact._
import synereo.client.utils
import synereo.client.utils.{AppUtils, ConnectionsUtils, ContentUtils, LabelsUtils}

import scala.language.reflectiveCalls

//scalastyle:off
object SearchComponent {

  case class Props()

  case class State(connectionsSelectizeInputId: String = "SearchComponentCnxnSltz" )

  val searchesProxy = SYNEREOCircuit.connect(_.searches)

  class Backend(t: BackendScope[Props, State]) {
    def mounted(props: Props) = Callback {
    }

    def fromSelecize(): Callback = Callback {}

    def searchWithLblAndCnxn(e: ReactEventI) = Callback {
      val (cnxns, labels) = ConnectionsLabelsSelectize
        .getCnxnsAndLabelsFromSelectize(t.state.runNow().connectionsSelectizeInputId)
      val cnxnToPost = ConnectionsUtils.getCnxnForReq(cnxns)
      val searchLabels = LabelsUtils.buildProlog(
        Seq(Label(text = AppUtils.MESSAGE_POST_LABEL)) ++ labels.map(currentLabel => Label(text = currentLabel)
        ), LabelsUtils.PrologTypes.Each)
      val expr = Expression("feedExpr", ExpressionContent(cnxnToPost, searchLabels))
      //      SYNEREOCircuit.dispatch(CancelPreviousAndSubscribeNew(SubscribeRequest(SYNEREOCircuit.zoom(_.sessionRootModel.sessionUri).value, expr)))
      ContentUtils.cancelPreviousAndSubscribeNew(SubscribeRequest(SYNEREOCircuit.zoom(_.sessionRootModel.sessionUri).value, expr))
    }

    def render(s: State, p: Props) = {
      <.div(
        <.div(^.id := s.connectionsSelectizeInputId, SynereoCommanStylesCSS.Style.searchBoxContainer)(
          ConnectionsLabelsSelectize(ConnectionsLabelsSelectize.Props(s.connectionsSelectizeInputId))
        ),
        <.div(SynereoCommanStylesCSS.Style.displayInline)(
          <.button(^.className := "btn btn-primary", SynereoCommanStylesCSS.Style.searchBtn, ^.onClick ==> searchWithLblAndCnxn)(MIcon.apply("search", "24")
          ))
      )
    }
  }

  val component = ReactComponentB[Props]("SearchComponent")
    .initialState_P(p => State())
    .renderBackend[Backend]
    .componentDidMount(scope => scope.backend.mounted(scope.props))
    .build

  def apply(props: Props) = component(props)
} 
Example 76
Source File: DemoInteraction.scala    From evilplot   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.cibo.evilplot

import java.util.UUID

import com.cibo.evilplot.geometry.{CanvasRenderContext, Disc, IEInfo, Interaction, OnClick, OnHover, Text}
import com.cibo.evilplot.interaction.CanvasInteractionContext
import com.cibo.evilplot.numeric.Point3d
import com.cibo.evilplot.plot.CartesianPlot
import org.scalajs.dom

object DemoInteraction {
  import com.cibo.evilplot.plot.aesthetics.DefaultTheme._

  // Crappy way to maintain state
  private var activePoint: Option[Point3d[Int]] = None
  private var hoveredPoint: Option[Point3d[Int]] = None

  def scatter(ctx: CanvasRenderContext, interactionMaskContext: CanvasInteractionContext, screenWidth: Double, screenHeight: Double) = {

    val anchors = Seq((10.0, 10.0), (0.0, 10.0), (10.0, 0.0), (0.0, 0.0))
    val data = (Seq.fill(300)(Math.random() * 10, Math.random() * 10) ++ anchors).zipWithIndex.map(x => Point3d[Int](x._1._1, x._1._2, x._2))
    val canvasId = UUID.randomUUID().toString

    // Rerender plot to draw updated state
    def renderPlot() = {
      dom.window.requestAnimationFrame { d: Double =>

        val updatedPlot = CartesianPlot(data){
          _.scatter({x: Point3d[Int] =>
            if(hoveredPoint.map(_.z).getOrElse(-1) == x.z) {  // if hovered

              Disc(5).translate(-5, -5).filled(colors.DefaultColors.lightPalette(1))
            } else if(activePoint.map(_.z).getOrElse(-1) == x.z){  // if active

              Disc(5).translate(-5, -5).filled(colors.DefaultColors.lightPalette(4))
            } else Disc(5).translate(-5, -5).filled(colors.DefaultColors.lightPalette(2))
          })
        }

        // Clear the canvas, otherwise new rendering will overlay with old
        ctx.clear()
        (Text(s"Active Point: ${activePoint.map(_.z)}, Hovered Point: ${hoveredPoint.map(_.z)}", size = 16)
          .padBottom(20) above updatedPlot.standard().render()).padAll(10).draw(ctx)
      }
    }

    def onHover(point3d: Point3d[Int]) = {
      if(point3d.z != hoveredPoint.getOrElse(-1)){
        hoveredPoint = Some(point3d)
        renderPlot() // rerender
      }
    }

    def onClick(point3d: Point3d[Int]): Unit ={
      activePoint = Some(point3d)
      renderPlot() // rerender
    }

    // define default move, to clear hovered point if there is none being hovered
    val defaultMove: IEInfo => Unit = _ => {
      hoveredPoint = None
      renderPlot() // rerender
    }

    // Initial plot
    val plot = CartesianPlot(data){
      _.scatter({x: Point3d[Int] => Interaction( // attach interaction events, in non interaction context, this will be ignored
        Disc(5).filled(colors.DefaultColors.lightPalette(2))
          .translate(-5, -5), OnHover(_ => onHover(x)), OnClick{ info =>
            println("inner location", info.innerLocation.x, info.innerLocation.y)
            println("client location", info.clientLocation.x, info.clientLocation.y)
            onClick(x)
         }
      )})
    }.standard()

    //Attach event handlers to the canvas that is displayed
    interactionMaskContext.attachToMainCanvas(ctx.canvas.canvas, defaultMove = defaultMove, mouseLeaveCanvas = _ => println("Mouse left canvas"))

    //Render the "virtual" interaction mask
    (Text(s"Active Point: ${activePoint.map(_.z)}, Hovered Point: ${hoveredPoint.map(_.z)}", size = 16)
      .padBottom(20) above plot.render()).padAll(10).draw(interactionMaskContext)

    //Render displayed plot
    renderPlot()
  }
} 
Example 77
Source File: Utils.scala    From evilplot   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.cibo.evilplot

import org.scalajs.dom
import org.scalajs.dom.CanvasRenderingContext2D

object Utils {
  val canvas: String = "canvas"
  val measureBuffer: String = "measureBuffer"

  def getCanvasFromElementId(id: String): CanvasRenderingContext2D = {
    // Muuuuuwahahahaha
    dom.window.document
      .getElementById(id)
      .asInstanceOf[dom.html.Canvas]
      .getContext("2d")
      .asInstanceOf[dom.CanvasRenderingContext2D]
  }

} 
Example 78
Source File: DomSvgApi.scala    From reftree   with GNU General Public License v3.0 5 votes vote down vote up
package reftree.svg

import monocle.macros.GenPrism
import monocle.{Getter, Lens, Optional}
import org.scalajs.dom
import org.scalajs.dom.ext.PimpedNodeList
import reftree.svg.api.SimpleSvgApi


object DomSvgApi extends SimpleSvgApi[dom.Node] {
  val elementName = Getter[dom.Node, String](_.nodeName)

  lazy val element = GenPrism[dom.Node, dom.Element]

  def optAttr(attr: String): Optional[dom.Node, Option[String]] =
    element composeLens
    Lens[dom.Element, Option[String]] { elem ⇒
      Option(elem.getAttribute(attr))
    } { value ⇒ elem ⇒
      val clone = elem.cloneNode(deep = true).asInstanceOf[dom.Element]
      value.fold(clone.removeAttribute(attr))(clone.setAttribute(attr, _))
      clone
    }

  def attr(attr: String): Optional[dom.Node, String] =
    element composeLens
    Lens[dom.Element, String] { elem ⇒
      elem.getAttribute(attr)
    } { value ⇒ elem ⇒
      val clone = elem.cloneNode(deep = true).asInstanceOf[dom.Element]
      clone.setAttribute(attr, value)
      clone
    }

  def prefixedAttr(uri: String, attr: String): Optional[dom.Node, Option[String]] =
    element composeLens
    Lens[dom.Element, Option[String]] { elem ⇒
      Option(elem.getAttributeNS(uri, attr))
    } { value ⇒ elem ⇒
      val clone = elem.cloneNode(deep = true).asInstanceOf[dom.Element]
      value.fold(clone.removeAttributeNS(uri, attr))(clone.setAttributeNS(uri, attr, _))
      clone
    }

  def immediateChildren: Optional[dom.Node, List[dom.Node]] =
    element composeLens
    Lens[dom.Element, List[dom.Node]](_.childNodes.toList) { children ⇒ elem ⇒
      val clone = elem.cloneNode(deep = false).asInstanceOf[dom.Element]
      children.foreach(clone.appendChild)
      clone
    }
} 
Example 79
Source File: Js.scala    From pine   with Apache License 2.0 5 votes vote down vote up
package pine.dom

import org.scalajs.dom
import pine._

trait Js[T <: Singleton] { type X <: dom.Element }

trait JsSvg [T <: Singleton] extends Js[T] { override type X <: dom.svg.Element  }
trait JsHtml[T <: Singleton] extends Js[T] { override type X <: dom.html.Element }

trait JsLowPrio {
  implicit object JsTag extends Js[Singleton] { override type X = dom.Element }
}

object Js extends JsLowPrio {
  implicit object JsA extends JsHtml[tag.A] { override type X = dom.html.Anchor }
  implicit object JsB extends JsHtml[tag.B] { override type X = dom.html.Span }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsApplet extends JsHtml[tag.Applet] { override type X = dom.html.Applet }
  implicit object JsArea extends JsHtml[tag.Area] { override type X = dom.html.Area }
  implicit object JsAudio extends JsHtml[tag.Audio] { override type X = dom.html.Audio }
  implicit object JsBR extends JsHtml[tag.Br] { override type X = dom.html.BR }
  implicit object JsBase extends JsHtml[tag.Base] { override type X = dom.html.Base }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsBaseFont extends JsHtml[tag.Basefont] { override type X = dom.html.BaseFont }
  implicit object JsBody extends JsHtml[tag.Body] { override type X = dom.html.Body }
  implicit object JsButton extends JsHtml[tag.Button] { override type X = dom.html.Button }
  implicit object JsCanvas extends JsHtml[tag.Canvas] { override type X = dom.html.Canvas }
  // implicit object JsCollection extends JsHtml[tag.Col] { override type X = dom.html.Collection }
  implicit object JsDD extends JsHtml[tag.Dd] { override type X = dom.html.DD }
  implicit object JsDList extends JsHtml[tag.Dl] { override type X = dom.html.DList }
  implicit object JsDT extends JsHtml[tag.Dt] { override type X = dom.html.DT }
  implicit object JsDataList extends JsHtml[tag.Datalist] { override type X = dom.html.DataList }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsDirectory extends JsHtml[tag.Dir] { override type X = dom.html.Directory }
  implicit object JsDiv extends JsHtml[tag.Div] { override type X = dom.html.Div }
  implicit object JsEmbed extends JsHtml[tag.Embed] { override type X = dom.html.Embed }
  implicit object JsFieldSet extends JsHtml[tag.Fieldset] { override type X = dom.html.FieldSet }
  implicit object JsForm extends JsHtml[tag.Form] { override type X = dom.html.Form }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsFrame extends JsHtml[tag.Frame] { override type X = dom.html.Frame }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsFrameSet extends JsHtml[tag.Frameset] { override type X = dom.html.FrameSet }
  implicit object JsH1 extends JsHtml[tag.H1] { override type X = dom.html.Heading }
  implicit object JsH2 extends JsHtml[tag.H2] { override type X = dom.html.Heading }
  implicit object JsH3 extends JsHtml[tag.H3] { override type X = dom.html.Heading }
  implicit object JsH4 extends JsHtml[tag.H4] { override type X = dom.html.Heading }
  implicit object JsH5 extends JsHtml[tag.H5] { override type X = dom.html.Heading }
  implicit object JsH6 extends JsHtml[tag.H6] { override type X = dom.html.Heading }
  implicit object JsHR extends JsHtml[tag.Hr] { override type X = dom.html.HR }
  implicit object JsHead extends JsHtml[tag.Head] { override type X = dom.html.Head }
  implicit object JsHtml extends JsHtml[tag.Html] { override type X = dom.html.Html }
  implicit object JsI extends JsHtml[tag.I] { override type X = dom.html.Span }
  implicit object JsIFrame extends JsHtml[tag.Iframe] { override type X = dom.html.IFrame }
  implicit object JsImage extends JsHtml[tag.Img] { override type X = dom.html.Image }
  implicit object JsInput extends JsHtml[tag.Input] { override type X = dom.html.Input }
  @deprecated("Element is deprecated", since = "html5")
  implicit object JsIsIndex extends JsHtml[tag.Isindex] { override type X = dom.html.IsIndex }
  implicit object JsLabel extends JsHtml[tag.Label] { override type X = dom.html.Label }
  implicit object JsLegend extends JsHtml[tag.Legend] { override type X = dom.html.Legend }
  implicit object JsLi extends JsHtml[tag.Li] { override type X = dom.html.LI }
  implicit object JsLink extends JsHtml[tag.Link] { override type X = dom.html.Link }
  implicit object JsMapJS extends JsHtml[tag.Map] { override type X = dom.html.Map }
  implicit object JsMenu extends JsHtml[tag.Menu] { override type X = dom.html.Menu }
  implicit object JsMeta extends JsHtml[tag.Meta] { override type X = dom.html.Meta }
  implicit object JsOList extends JsHtml[tag.Ol] { override type X = dom.html.OList }
  implicit object JsObject extends JsHtml[tag.Object] { override type X = dom.html.Object }
  implicit object JsOptGroup extends JsHtml[tag.Optgroup] { override type X = dom.html.OptGroup }
  implicit object JsOpt extends JsHtml[tag.Option] { override type X = dom.html.Option }
  implicit object JsParagraph extends JsHtml[tag.P] { override type X = dom.html.Paragraph }
  implicit object JsParam extends JsHtml[tag.Param] { override type X = dom.html.Param }
  implicit object JsPre extends JsHtml[tag.Pre] { override type X = dom.html.Pre }
  implicit object JsProgress extends JsHtml[tag.Progress] { override type X = dom.html.Progress }
  implicit object JsScript extends JsHtml[tag.Script] { override type X = dom.html.Script }
  implicit object JsSelect extends JsHtml[tag.Select] { override type X = dom.html.Select }
  implicit object JsSource extends JsHtml[tag.Source] { override type X = dom.html.Source }
  implicit object JsSpan extends JsHtml[tag.Span] { override type X = dom.html.Span }
  implicit object JsStrong extends JsHtml[tag.Strong] { override type X = dom.html.Span }
  implicit object JsStrike extends JsHtml[tag.Strike] { override type X = dom.html.Span }
  implicit object JsStyle extends JsHtml[tag.Style] { override type X = dom.html.Style }
  implicit object JsTable extends JsHtml[tag.Table] { override type X = dom.html.Table }
  implicit object JsTableRow extends JsHtml[tag.Tr] { override type X = dom.html.TableRow }
  implicit object JsTableDataCell extends JsHtml[tag.Td] { override type X = dom.html.TableDataCell }
  implicit object JsTableHeadCell extends JsHtml[tag.Th] { override type X = dom.html.TableHeaderCell }
  implicit object JsTextArea extends JsHtml[tag.Textarea] { override type X = dom.html.TextArea }
  implicit object JsTitle extends JsHtml[tag.Title] { override type X = dom.html.Title }
  implicit object JsTrack extends JsHtml[tag.Track] { override type X = dom.html.Track }
  implicit object JsUl extends JsHtml[tag.Ul] { override type X = dom.html.UList }
  implicit object JsVideo extends JsHtml[tag.Video] { override type X = dom.html.Video }

  implicit object JsSvg extends JsSvg[tag.Svg] { override type X = dom.svg.SVG }
} 
Example 80
Source File: NodeRender.scala    From pine   with Apache License 2.0 5 votes vote down vote up
package pine.dom

import org.scalajs.dom

import pine._

object NodeRender extends TagRender[Tag[_], dom.Element] {
  trait Implicit {
    implicit class TextToDom(node: Text) {
      def toDom: dom.raw.Text = renderText(node)
    }

    implicit class TagToDom[T <: Singleton](node: Tag[T]) {
      def toDom(implicit js: Js[T]): js.X = renderTag(node).asInstanceOf[js.X]
    }
  }

  override def render(tag: Tag[_]): dom.Element = renderTag(tag)

  @inline def renderChild(node: Node): dom.Node =
    node match {
      case n @ Tag(_, _, _) => renderTag(n)
      case n @ Text(_)      => renderText(n)
    }

  @inline def renderChildWithNamespace(node: Node, xmlns: String): dom.Node =
    node match {
      case n @ Tag(_, _, _) => renderTagWithNamespace(n, xmlns)
      case n @ Text(_)      => renderText(n)
    }

  def renderTagWithNamespace(node: Tag[_], xmlns: String): dom.Element = {
    val element = dom.document.createElementNS(xmlns, node.tagName)
    node.attributes.foreach { case (k, v) =>
      if (k == "xmlns" || k.contains(":")) element.setAttribute(k, v.toString)
      else element.setAttributeNS(null, k, v.toString)
    }

    node
      .children.map(renderChildWithNamespace(_, xmlns))
      .foreach(element.appendChild)
    element
  }

  def renderTag(node: Tag[_]): dom.Element = {
    val element =
      node.attr("xmlns") match {
        case Some(xmlns) => renderTagWithNamespace(node, xmlns)
        case None        =>
          val element = dom.document.createElement(node.tagName)
          node.attributes.foreach { case (k, v) =>
            element.setAttribute(k, v.toString)
          }
          element
      }

    node.children.map(renderChild).foreach(element.appendChild)
    element
  }

  @inline def renderText(node: Text): dom.raw.Text =
    dom.document.createTextNode(node.text)
} 
Example 81
Source File: Main.scala    From topshell   with MIT License 5 votes vote down vote up
package com.github.ahnfelt.topshell

import com.github.ahnfelt.react4s._
import com.github.ahnfelt.topshell.language._
import com.github.ahnfelt.topshell.worker.Processor
import org.scalajs.dom
import org.scalajs.dom.raw.{DedicatedWorkerGlobalScope, WorkerGlobalScope}
import org.scalajs.dom.webworkers.Worker

import scala.scalajs.js

object Main {
    var worker : Worker = _
    var codeVersion : Double = 0

    def main(arguments : Array[String]) : Unit = {
        if(!js.isUndefined(js.Dynamic.global.window)) {
            var symbols : List[(String, Loader.Loaded[js.Any])] = List()
            var types : Map[String, String] = Map()
            var implied : Set[String] = Set()
            var error : Option[String] = None
            var resultTimeouts = Map[String, js.timers.SetTimeoutHandle]()
            def update() : Unit = {
                val component = Component(MainComponent, symbols, implied, types, error)
                ReactBridge.renderToDomById(component, "main")
            }
            worker = new Worker("worker.js")
            worker.onmessage = m => {
                val data = m.data.asInstanceOf[js.Dynamic]
                if(data.codeVersion.asInstanceOf[Double] == codeVersion) {
                    data.event.asInstanceOf[String] match {
                        case "symbols" =>
                            val cached = data.cached.asInstanceOf[js.Array[String]]
                            symbols = data.symbols.asInstanceOf[js.Array[String]].map(s =>
                                if(cached.contains(s)) symbols.find(_._1 == s).getOrElse(s -> Loader.Loading())
                                else s -> Loader.Loading()
                            ).toList
                            types = data.types.asInstanceOf[js.Dictionary[String]].toMap
                            implied = data.implied.asInstanceOf[js.Array[String]].toSet
                            update()
                        case "error" =>
                            val name = data.name.asInstanceOf[String]
                            for(handle <- resultTimeouts.get(name)) js.timers.clearTimeout(handle)
                            resultTimeouts += (name -> js.timers.setTimeout(50.0) {
                                val index = symbols.indexWhere(_._1 == name)
                                symbols = symbols.updated(
                                    index,
                                    name -> Loader.Error(new RuntimeException(data.error.asInstanceOf[String]))
                                )
                                update()
                            })
                        case "result" =>
                            val name = data.name.asInstanceOf[String]
                            for(handle <- resultTimeouts.get(name)) js.timers.clearTimeout(handle)
                            resultTimeouts += (name -> js.timers.setTimeout(50.0) {
                                val index = symbols.indexWhere(_._1 == name)
                                symbols = symbols.updated(
                                    index,
                                    name -> Loader.Result(data.html)
                                )
                                update()
                            })
                        case e =>
                            println("Not handled: " + e)
                    }
                }
            }
            dom.window.onload = _ => update()
        } else {
            DedicatedWorkerGlobalScope.self.onmessage = m => {
                val data = m.data.asInstanceOf[js.Dynamic]
                if(data.event.asInstanceOf[String] == "code") {
                    codeVersion = data.codeVersion.asInstanceOf[Double]
                    Processor.process(data.asInstanceOf[js.Dynamic].code.asInstanceOf[String])
                } else if(data.event.asInstanceOf[String] == "start") {
                    Processor.start(data.fromLine.asInstanceOf[Int], data.toLine.asInstanceOf[Int])
                } else {
                    println("Could not understand message to worker: " + m)
                }
            }
        }
    }
} 
Example 82
Source File: DataConsumer.scala    From monix-sample   with Apache License 2.0 5 votes vote down vote up
package client

import monix.execution.Cancelable
import monix.reactive.Observable
import monix.reactive.OverflowStrategy.DropNew
import monix.reactive.observers.Subscriber
import org.scalajs.dom
import shared.models.{Event, OverflowEvent, Signal}
import scala.concurrent.duration.FiniteDuration
import scala.scalajs.js.Dynamic.global

final class DataConsumer(interval: FiniteDuration, seed: Long, doBackPressure: Boolean)
  extends Observable[Event] {

  override def unsafeSubscribeFn(subscriber: Subscriber[Event]): Cancelable = {
    val host = dom.window.location.host
    val protocol = if (dom.document.location.protocol == "https:") "wss:" else "ws:"

    val source = if (doBackPressure) {
      val url = s"$protocol//$host/back-pressured-stream?periodMillis=${interval.toMillis}&seed=$seed"
      BackPressuredWebSocketClient(url)
    }
    else {
      val url = s"$protocol//$host/simple-stream?periodMillis=${interval.toMillis}&seed=$seed"
      SimpleWebSocketClient(url, DropNew(1000))
    }

    source
      .collect { case IsEvent(e) => e }
      .unsafeSubscribeFn(subscriber)
  }

  object IsEvent {
    def unapply(message: String) = {
      val json = global.JSON.parse(message)

      json.event.asInstanceOf[String] match {
        case "point" =>
          Some(Signal(
            value = json.value.asInstanceOf[Number].doubleValue(),
            timestamp = json.timestamp.asInstanceOf[Number].longValue()
          ))
        case "overflow" =>
          Some(OverflowEvent(
            dropped = json.dropped.asInstanceOf[Number].longValue(),
            timestamp = json.timestamp.asInstanceOf[Number].longValue()
          ))
        case "error" =>
          val errorType = json.`type`.asInstanceOf[String]
          val message = json.message.asInstanceOf[String]
          throw new BackPressuredWebSocketClient.Exception(
            s"Server-side error throw - $errorType: $message")
        case _ =>
          None
      }
    }
  }
} 
Example 83
Source File: Main.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
import components.LayoutComponent
import japgolly.scalajs.react._
import japgolly.scalajs.react.extra.router.{BaseUrl, Redirect, Router, RouterConfig, RouterConfigDsl}
import models.Locs._
import org.scalajs.dom
import screens.HomeScreen
import shared.utils.UpickleCodecs

import scala.scalajs.js.JSApp

object Main extends JSApp with UpickleCodecs {
  val regExRoute = "[a-zA-Z0-9_-]+"

  def main(): Unit = {
    println("Application starting..")

    val routerConfig: RouterConfig[Loc] = RouterConfigDsl[Loc]
      .buildConfig { dsl =>
        import dsl._

        (
          staticRoute(root, HomeLoc) ~> renderR(ctl => HomeScreen(ctl).vdomElement)
        ).notFound(redirectToPage(HomeLoc)(Redirect.Replace))
      }
      .renderWith((ctl, res) => LayoutComponent(ctl, res).vdomElement)

    val routerComponent = Router(BaseUrl.fromWindowOrigin_/, routerConfig)

    val appComponent = ScalaComponent.builder[Unit]("App").render(_ => routerComponent().vdomElement).build

    appComponent().renderIntoDOM(dom.document.getElementById("root"))
  }

} 
Example 84
Source File: AjaxClient.scala    From bay-scalajs.g8   with Apache License 2.0 5 votes vote down vote up
package services

import org.scalajs.dom
import org.scalajs.dom.FormData
import org.scalajs.dom.ext.AjaxException
import org.scalajs.dom.raw.{File, XMLHttpRequest}

import scala.concurrent.{Future, Promise}

class AjaxClient(files: Map[String, File])
  extends autowire.Client[String,
    upickle.default.Reader,
    upickle.default.Writer] {

  override def doCall(req: Request): Future[String] = {

    val promise = Promise[XMLHttpRequest]
    val xhr     = new dom.XMLHttpRequest
    xhr.onreadystatechange = (e: dom.Event) => {
      if (xhr.readyState == dom.XMLHttpRequest.DONE) {
        promise.success(xhr)
      }
    }

    xhr.onerror = { e: dom.ErrorEvent =>
      promise.failure(AjaxException(xhr))
    }

    //start upload
    val formData = new FormData()

    formData.append("data", upickle.default.write(req.args))
    files.foreach {
      case (key, file) => formData.append(key, file)
    }
    xhr.open("POST", "/wired/" + req.path.mkString("/"), true)
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
    xhr.send(formData)

    promise.future.map(_.responseText)
  }

  def write[Result: upickle.default.Writer](r: Result): String =
    upickle.default.write(r)

  def read[Result: upickle.default.Reader](p: String): Result =
    upickle.default.read[Result](p)
}

object AjaxClient {
  def apply[Trait]                           = new AjaxClient(Map.empty)[Trait]
  def apply[Trait](files: Map[String, File]) = new AjaxClient(files)[Trait]
  def apply[Trait](files: (String, File)*)   = new AjaxClient(files.toMap)[Trait]
} 
Example 85
Source File: NavigationBar.scala    From scalajs-highcharts   with MIT License 5 votes vote down vote up
package com.highcharts.test.frontend

import org.scalajs.dom

import scalatags.JsDom.all._

case class NavigationTab(name: String, id: String, icon: String, content: dom.Element, active: Boolean = false)


final class NavigationBar(barId: String, tabs: NavigationTab*) {
  private val nav = tag("nav")
  private val `data-toggle` = attr("data-toggle")
  private val `data-target` = attr("data-target")

  def navbar(brand: String): Tag = {
    def renderTab(tab: NavigationTab): Tag = {
      li(
        `class` := (if (tab.active) "active" else ""),
        a(href := s"#$barId-${tab.id}-tab", role := "tab", `data-toggle` := "tab")(
          span(`class` := s"glyphicon glyphicon-${tab.icon}"),
          raw("&nbsp;"),
          tab.name
        )
      )
    }

    nav(`class` := "navbar navbar-default navbar-fixed-top")(
      div(`class` := "container")(
        // Header
        div(`class` := "navbar-header")(
          button(`type` := "button", `data-toggle` := "collapse", `data-target` := s"#$barId", `class` := "navbar-toggle collapsed")(
            span(`class` := "sr-only", "Toggle navigation"),
            span(`class` := "icon-bar"),
            span(`class` := "icon-bar"),
            span(`class` := "icon-bar")
          ),
          a(href := "#", `class` := "navbar-brand", brand)
        ),
        div(id := barId, `class` := "navbar-collapse collapse")(
          ul(`class` := "nav navbar-nav")(
            tabs.map(renderTab)
          )
        )
      )
    )
  }

  def content: Tag = {
    div(id := s"$barId-tabcontent", `class` := "tab-content")(
      for (NavigationTab(name, tabId, _, content, active) <- tabs) yield {
        div(id := s"$barId-$tabId-tab", role := "tabpanel", `class` := (if (active) "tab-pane active fade in" else "tab-pane fade"))(
          content
        )
      }
    )
  }
} 
Example 86
Source File: HighchartsTestApp.scala    From scalajs-highcharts   with MIT License 5 votes vote down vote up
package com.highcharts.test.frontend

import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
import com.highcharts.test.frontend.charts.{Test3dPieChartConfig, TestBarChartConfig, TestCombinationChartConfig, TestStockChartConfig}
import org.scalajs.dom
import org.scalajs.jquery._

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scalatags.JsDom.all._

@JSExport
object HighchartsTestApp extends JSApp {
  private def renderChart(chartConfig: CleanJsObject[js.Object]): dom.Element = {
    dom.console.log(chartConfig)
    val container = div().render
    jQuery(container).highcharts(chartConfig)
    container
  }

  private def fixChartSizes(): Unit = {
    jQuery("div[data-highcharts-chart]").each { (_: Int, e: dom.Element) ⇒
      jQuery(e).highcharts().foreach(_.reflow()).asInstanceOf[js.Any]
    }
  }

  @JSExport
  override def main(): Unit = {
    jQuery(() ⇒ {
      // Create charts
      val barChart = renderChart(new TestBarChartConfig)
      val pieChart = renderChart(new Test3dPieChartConfig)
      val comboChart = renderChart(new TestCombinationChartConfig)
      val stockChart = div().render

      // Create navigation elements
      val tabs = new NavigationBar("highcharts-test",
        NavigationTab("Bar chart", "bar", "briefcase", barChart, active = true),
        NavigationTab("Pie chart", "pie", "adjust", pieChart),
        NavigationTab("Combination chart", "combo", "tasks", comboChart),
        NavigationTab("Stock chart", "stock", "usd", stockChart)
      )

      // Bootstrap container
      val container = div(id := "main-container", `class` := "container")(
        div(`class` := "row", div(`class` := "col-md-12")(
          tabs.content
        ))
      ).render

      // Render page
      val body = dom.document.body
      body.appendChild(tabs.navbar("Scala.js Highcharts Test").render)
      body.appendChild(container)

      TestStockChartConfig.loadSampleData().foreach { data ⇒
        val config: CleanJsObject[TestStockChartConfig] = new TestStockChartConfig(data)
        dom.console.log(config)
        jQuery(stockChart).highstock(config)
      }

      // Size fix
      jQuery(dom.document).on("shown.bs.tab", "a[data-toggle=\"tab\"]", (_: JQueryEventObject) ⇒ fixChartSizes())
      fixChartSizes()
    })
  }
} 
Example 87
Source File: ArchiveTab.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.frontend.components

import akkaviz.frontend.FrontendUtil
import akkaviz.rest
import org.scalajs.dom
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element => domElement}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.Date
import scalatags.JsDom.all._

trait ArchiveTab extends ClosableTab {

  import akkaviz.frontend.PrettyJson._

  def loadUrl: String

  private[this] var loading: js.UndefOr[Future[dom.XMLHttpRequest]] = js.undefined

  private[this] def loadBetween(): Unit = {
    if (loading.isEmpty) {
      messagesTbody.innerHTML = ""
      messagesTbody.appendChild(loadingTbodyContent)
      val f = Ajax.get(loadUrl)
      f.onComplete(_ => loading = js.undefined)
      f.onSuccess {
        case req: dom.XMLHttpRequest =>
          val content = upickle.default.read[List[rest.Received]](req.responseText)
          messagesTbody.innerHTML = ""
          content.sortBy(_.timestamp).foreach { rcv =>
            messagesTbody.appendChild(messageRow(rcv).render)
          }
      }
      f.onFailure {
        case _ =>
          messagesTbody.innerHTML = ""
          messagesTbody.appendChild(
            tr(td(colspan := 3, "Unable to download archive, please check server is connected to Cassandra.")).render
          )
      }
      loading = f
    }
  }

  private[this] def messageRow(rcv: rest.Received): Seq[Frag] = {
    val date = new Date(rcv.timestamp.toDouble)
    Seq(
      tr(
        td(FrontendUtil.shortActorName(rcv.from)),
        td(rcv.direction),
        td(FrontendUtil.shortActorName(rcv.to)),
        td(date.toISOString())
      ),
      tr(
        td(colspan := 4)(pre(prettyPrintJson(rcv.payload)))
      )
    )
  }

  private[this] val refreshButton = a(
    cls := "btn btn-default", href := "#", role := "button", float.right,
    span(
      `class` := "imgbtn glyphicon glyphicon-refresh", " "
    ),
    onclick := { () =>
      loadBetween()
    },
    "Refresh view"
  )

  private[this] val loadingTbodyContent = tr(td(colspan := 4, "Loading...")).render
  private[this] val messagesTbody = tbody(loadingTbodyContent).render
  private[this] val rendered = div(
    cls := "panel-body",
    div(
      refreshButton,
      clear.both
    ),
    div(cls := "panel-body", id := "messagespanelbody",
      table(
        cls := "table table-striped table-hover",
        thead(
          tr(th("From"), th(""), th("To"), th("Time"))
        ), messagesTbody
      ))
  ).render

  override def onCreate(): Unit = {
    tabBody.appendChild(rendered)

    loadBetween()
  }
} 
Example 88
Source File: nodes.scala    From akka-viz   with MIT License 5 votes vote down vote up
package scalatags.rx

import java.util.concurrent.atomic.AtomicReference

import org.scalajs.dom
import org.scalajs.dom.Element
import org.scalajs.dom.ext._
import org.scalajs.dom.raw.Comment
import rx._

import scala.collection.immutable
import scala.language.implicitConversions
import scalatags.JsDom.all._
import scalatags.jsdom
import scalatags.rx.ext._

trait RxNodeInstances {

  implicit class rxStringFrag(v: Rx[String])(implicit val ctx: Ctx.Owner) extends jsdom.Frag {
    def render: dom.Text = {
      val node = dom.document.createTextNode(v.now)
      v foreach { s => node.replaceData(0, node.length, s) } attachTo node
      node
    }
  }

  implicit class bindRxElement[T <: dom.Element](e: Rx[T])(implicit val ctx: Ctx.Owner) extends Modifier {
    def applyTo(t: Element) = {
      val element = new AtomicReference(e.now)
      t.appendChild(element.get())
      e.triggerLater {
        val current = e.now
        val previous = element getAndSet current
        t.replaceChild(current, previous)
      } attachTo t
    }
  }

  implicit class bindRxElements(e: Rx[immutable.Iterable[Element]])(implicit val ctx: Ctx.Owner) extends Modifier {
    def applyTo(t: Element) = {
      val nonEmpty = e.map { t => if (t.isEmpty) List(new Comment) else t }
      val fragments = new AtomicReference(nonEmpty.now)
      nonEmpty.now foreach t.appendChild
      nonEmpty triggerLater {
        val current = e.now
        val previous = fragments getAndSet current
        val i = t.childNodes.indexOf(previous.head)
        if (i < 0) throw new IllegalStateException("Children changed")
        0 to (previous.size - 1) foreach (_ => t.removeChild(t.childNodes.item(i)))
        if (t.childNodes.length > i) {
          val next = t.childNodes.item(i)
          current foreach (t.insertBefore(_, next))
        } else {
          current foreach t.appendChild
        }
      }
    }
  }

} 
Example 89
Source File: FrontEnd.scala    From akka-http-extensions   with Mozilla Public License 2.0 5 votes vote down vote up
package org.denigma.preview.views

import org.denigma.binding.views.BindableView
import org.denigma.controls.login.{LoginView, AjaxSession}
import org.scalajs.dom
import org.scalajs.dom.raw.Element
import org.denigma.binding.binders._
import org.denigma.binding.extensions._
import org.semantic.SidebarConfig
import org.semantic._
import org.semantic.ui._

import org.querki.jquery._
import scala.scalajs.js.annotation.JSExport

@JSExport("FrontEnd")
object FrontEnd extends BindableView with scalajs.js.JSApp
{

  lazy val elem: Element = dom.document.body

  val sidebarParams = SidebarConfig.exclusive(false).dimPage(false).closable(false).useLegacy(false)

  val session = new AjaxSession()

  
  override lazy val injector = defaultInjector
    .register("menu"){
      case (el, args) =>
        new MenuView(el,args).withBinders(menu=>List(new GeneralBinder(menu),new NavigationBinder(menu)))
    }
    .register("sidebar"){ case (el, args) => new SidebarView(el,args).withBinder(new GeneralBinder(_)) }
    .register("login"){ case (el, args) => new LoginView(el,session).withBinder(new GeneralBinder(_)) }


  this.withBinder(new GeneralBinder(_))

  @JSExport
  def main(): Unit = {
    this.bindElement(viewElement)
    this.login("guest") //TODO: change it when session mechanism will work well
  }

  @JSExport
  def login(username:String): Unit = session.setUsername(username)

  @JSExport
  def showLeftSidebar() = {
    $(".left.sidebar").sidebar(sidebarParams).show()
  }

  @JSExport
  def load(content: String, into: String): Unit = {
    dom.document.getElementById(into).innerHTML = content
  }

  @JSExport
  def moveInto(from: String, into: String): Unit = {
    for {
      ins <- sq.byId(from)
      intoElement <- sq.byId(into)
    } {
      this.loadElementInto(intoElement, ins.innerHTML)
      ins.parentNode.removeChild(ins)
    }
  }
} 
Example 90
Source File: Frontend.scala    From akka-http-scala-js-websocket-chat   with MIT License 5 votes vote down vote up
package example.akkawschat

import org.scalajs.dom.raw._

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

import upickle.default._
import shared.Protocol

object Frontend extends js.JSApp {
  val joinButton = dom.document.getElementById("join").asInstanceOf[HTMLButtonElement]
  val sendButton = dom.document.getElementById("send").asInstanceOf[HTMLButtonElement]

  def main(): Unit = {
    val nameField = dom.document.getElementById("name").asInstanceOf[HTMLInputElement]
    joinButton.onclick = { (event: MouseEvent) ⇒
      joinChat(nameField.value)
      event.preventDefault()
    }
    nameField.focus()
    nameField.onkeypress = { (event: KeyboardEvent) ⇒
      if (event.keyCode == 13) {
        joinButton.click()
        event.preventDefault()
      }
    }
  }

  def joinChat(name: String): Unit = {
    joinButton.disabled = true
    val playground = dom.document.getElementById("playground")
    playground.innerHTML = s"Trying to join chat as '$name'..."
    val chat = new WebSocket(getWebsocketUri(dom.document, name))
    chat.onopen = { (event: Event) ⇒
      playground.insertBefore(p("Chat connection was successful!"), playground.firstChild)
      sendButton.disabled = false

      val messageField = dom.document.getElementById("message").asInstanceOf[HTMLInputElement]
      messageField.focus()
      messageField.onkeypress = { (event: KeyboardEvent) ⇒
        if (event.keyCode == 13) {
          sendButton.click()
          event.preventDefault()
        }
      }
      sendButton.onclick = { (event: Event) ⇒
        chat.send(messageField.value)
        messageField.value = ""
        messageField.focus()
        event.preventDefault()
      }

      event
    }
    chat.onerror = { (event: Event) ⇒
      playground.insertBefore(p(s"Failed: code: ${event.asInstanceOf[ErrorEvent].colno}"), playground.firstChild)
      joinButton.disabled = false
      sendButton.disabled = true
    }
    chat.onmessage = { (event: MessageEvent) ⇒
      val wsMsg = read[Protocol.Message](event.data.toString)

      wsMsg match {
        case Protocol.ChatMessage(sender, message) ⇒ writeToArea(s"$sender said: $message")
        case Protocol.Joined(member, _)            ⇒ writeToArea(s"$member joined!")
        case Protocol.Left(member, _)              ⇒ writeToArea(s"$member left!")
      }
    }
    chat.onclose = { (event: Event) ⇒
      playground.insertBefore(p("Connection to chat lost. You can try to rejoin manually."), playground.firstChild)
      joinButton.disabled = false
      sendButton.disabled = true
    }

    def writeToArea(text: String): Unit =
      playground.insertBefore(p(text), playground.firstChild)
  }

  def getWebsocketUri(document: Document, nameOfChatParticipant: String): String = {
    val wsProtocol = if (dom.document.location.protocol == "https:") "wss" else "ws"

    s"$wsProtocol://${dom.document.location.host}/chat?name=$nameOfChatParticipant"
  }

  def p(msg: String) = {
    val paragraph = dom.document.createElement("p")
    paragraph.innerHTML = msg
    paragraph
  }
} 
Example 91
Source File: Drag.scala    From scala-js-d3v4   with MIT License 5 votes vote down vote up
package d3v4

import scalajs.js
import scalajs.js.{ undefined, `|` }
import scala.scalajs.js.annotation._
import org.scalajs.dom
import d3._

// https://github.com/d3/d3-drag
@JSImport("d3-drag", JSImport.Namespace)
@js.native
object d3drag extends js.Object {
  def drag[Datum](): DragBehavior[Datum] = js.native

  @js.native
  trait DragEvent extends BaseEvent {
    var x: Double = js.native
    var y: Double = js.native
    var dx: Double = js.native
    var dy: Double = js.native
  }

  @js.native
  trait DragBehavior[Datum] extends js.Function1[Selection[Datum], Unit] {
    def on(typenames: String, listener: ListenerFunction0): DragBehavior[Datum] = js.native
    def on(typenames: String, listener: ListenerFunction1[Datum]): DragBehavior[Datum] = js.native
    def on(typenames: String, listener: ListenerFunction2[Datum]): DragBehavior[Datum] = js.native
    def on[E <: CurrentDom](typenames: String, listener: ListenerThisFunction2[E, Datum]): DragBehavior[Datum] = js.native

    type DragSubject = js.Object // {def x:Double; def y:Double}
    def subject(subject: ValueFunction2[Datum, DragSubject]): DragBehavior[Datum] = js.native

    def subject[E <: CurrentDom](subject: ValueThisFunction0[E, DragSubject]): DragBehavior[Datum] = js.native
    def subject[E <: CurrentDom](subject: ValueThisFunction1[E, Datum, DragSubject]): DragBehavior[Datum] = js.native
    def subject[E <: CurrentDom](subject: ValueThisFunction2[E, Datum, DragSubject]): DragBehavior[Datum] = js.native

    def clickDistance(distance: Double): DragBehavior[Datum] = js.native
    def clickDistance(): Double = js.native
  }
} 
Example 92
Source File: Quadtree.scala    From scala-js-d3v4   with MIT License 5 votes vote down vote up
package d3v4

import scalajs.js
import scalajs.js.{ undefined, `|` }
import scala.scalajs.js.annotation._
import org.scalajs.dom

// https://github.com/d3/d3-quadtree
@JSImport("d3-quadtree", JSImport.Namespace)
@js.native
object d3quadtree extends js.Object {
  def quadtree[Datum](): Quadtree[Datum] = js.native
  def quadtree[Datum](data: js.Array[Datum]): Quadtree[Datum] = js.native
  def quadtree[Datum](data: js.Array[Datum], x: js.Function1[Datum, Double], y: js.Function1[Datum, Double]): Quadtree[Datum] = js.native

  @js.native
  trait Quadtree[Datum] extends js.Object {
    def x(x: js.Function1[Datum, Double]): Quadtree[Datum] = js.native
    def x(): js.Function1[Datum, Double] = js.native
    def y(y: js.Function1[Datum, Double]): Quadtree[Datum] = js.native
    def y(): js.Function1[Datum, Double] = js.native
    def add(datum: Datum): Quadtree[Datum] = js.native
    def addAll[NewDatum](data: js.Array[NewDatum]): Quadtree[NewDatum] = js.native
    def remove(datum: Datum): Quadtree[Datum] = js.native
    def root: QuadtreeNode[Datum] = js.native
    def data: js.Array[Datum] = js.native
    def size: Int = js.native
    def find(x: Double, y: Double): Datum = js.native
    def find(x: Double, y: Double, radius: Double): Datum = js.native
    def visit(callback: js.Function5[QuadtreeNode[Datum], Double, Double, Double, Double, Boolean]): Quadtree[Datum] = js.native
    def visitAfter(callback: js.Function5[QuadtreeNode[Datum], Double, Double, Double, Double, Any]): Quadtree[Datum] = js.native
    def copy: Quadtree[Datum] = js.native
  }

  @js.native
  sealed trait QuadtreeNode[Datum] extends js.Any {
    def length: js.UndefOr[Int] = js.native
    def apply(index: Int): QuadtreeNode[Datum] = js.native
    def data: Datum = js.native
    def next: js.UndefOr[QuadtreeNode[Datum]] = js.native
  }
} 
Example 93
Source File: Zoom.scala    From scala-js-d3v4   with MIT License 5 votes vote down vote up
package d3v4

import scalajs.js
import scalajs.js.{ undefined, `|` }
import scala.scalajs.js.annotation._
import org.scalajs.dom
import d3._

// https://github.com/d3/d3-zoom
@JSImport("d3-zoom", JSImport.Namespace)
@js.native
object d3zoom extends js.Object {
  def zoomIdentity: Transform = js.native
  def zoom[Datum](): ZoomBehavior[Datum] = js.native

  @js.native
  trait Transform extends js.Object {
    def x: Double = js.native
    def y: Double = js.native
    def k: Double = js.native
    override def toString: String = js.native

    def scale(k: Double | js.UndefOr[Double]): Transform
    def translate(x: Double | js.UndefOr[Double], y: Double | js.UndefOr[Double]): Transform
    def apply(point: js.Array[Double]): js.Array[Double] = js.native
    def applyX(x: Double | js.UndefOr[Double]): Double = js.native
    def applyY(x: Double | js.UndefOr[Double]): Double = js.native
    def invert(point: js.Array[Double]): js.Array[Double] = js.native
    def invertX(x: Double | js.UndefOr[Double]): Double = js.native
    def invertY(x: Double | js.UndefOr[Double]): Double = js.native
    def rescaleX[S <: ContinuousScale[S]](x: ContinuousScale[S]): S = js.native
    def rescaleY[S <: ContinuousScale[S]](y: ContinuousScale[S]): S = js.native
  }

  @js.native
  trait ZoomEvent extends BaseEvent {
    def transform: Transform = js.native
  }

  @js.native
  trait ZoomBehavior[Datum] extends js.Function1[Selection[Datum], Unit] {
    def on(typenames: String, listener: ListenerFunction0): ZoomBehavior[Datum] = js.native
    def scaleExtent(extent: js.Array[Double]): ZoomBehavior[Datum] = js.native
    def scaleExtent(): js.Array[Double] = js.native
    def transform(selection: Selection[Datum], transform: Transform): Transform = js.native
    def translateBy(selection: Selection[Datum], x: Double, y: Double): Transform = js.native
    def scaleBy(selection: Selection[Datum], k: Double): Transform = js.native
    def scaleTo(selection: Selection[Datum], k: Double): Transform = js.native
    def clickDistance(distance: Double): ZoomBehavior[Datum] = js.native
    def clickDistance(): Double = js.native
  }
} 
Example 94
Source File: D3.scala    From scala-js-d3v4   with MIT License 5 votes vote down vote up
import scalajs.js.`|`
import scalajs.js
import scala.scalajs.js.annotation._
import org.scalajs.dom

package d3v4 {
  object d3 {
    @inline implicit def d3toD3Array(d3t: d3.type): d3array.type = d3array
    @inline implicit def d3toD3Axis(d3t: d3.type): d3axis.type = d3axis
    @inline implicit def d3toD3Color(d3t: d3.type): d3color.type = d3color
    @inline implicit def d3toD3Drag(d3t: d3.type): d3drag.type = d3drag
    @inline implicit def d3toD3Force(d3t: d3.type): d3force.type = d3force
    @inline implicit def d3toD3Polygon(d3t: d3.type): d3polygon.type = d3polygon
    @inline implicit def d3toD3Scale(d3t: d3.type): d3scale.type = d3scale
    @inline implicit def d3toD3Selection(d3t: d3.type): d3selection.type = d3selection
    @inline implicit def d3toD3Shape(d3t: d3.type): d3shape.type = d3shape
    @inline implicit def d3toD3Time(d3t: d3.type): d3time.type = d3time
    @inline implicit def d3toD3Quadtree(d3t: d3.type): d3quadtree.type = d3quadtree
    @inline implicit def d3toD3Zoom(d3t: d3.type): d3zoom.type = d3zoom

    @js.native
    trait BaseEvent extends js.Object {
      var `type`: String = js.native
      var sourceEvent: dom.Event = js.native
    }

    type DragEvent = d3drag.DragEvent
    type ZoomEvent = d3zoom.ZoomEvent
    type ZoomBehavior[Datum] = d3zoom.ZoomBehavior[Datum]
    type Transform = d3zoom.Transform
    type Selection[Datum] = d3selection.Selection[Datum]
    type Interval = d3time.Interval
    type Scale = d3scale.Scale
    type ContinuousScale[S <: ContinuousScale[S]] = d3scale.ContinuousScale[S]
    type TimeScale = d3scale.TimeScale
    type Force[N <: SimulationNode] = d3force.Force[N]
    type Simulation[N <: SimulationNode] = d3force.Simulation[N]
    type Quadtree[Datum] = d3quadtree.Quadtree[Datum]
    type QuadtreeNode[Datum] = d3quadtree.QuadtreeNode[Datum]
  }
}

package object d3v4 {
  import d3._
  // type Primitive = Double | String | Boolean
  //
  // type DatumThisFunction3[Return] = js.ThisFunction3[CurrentDom, Datum, Index, Group, Return]
  // type DatumThisFunction2[Return] = js.ThisFunction2[CurrentDom, Datum, Index, Return]
  // type DatumThisFunction1[Return] = js.ThisFunction1[CurrentDom, Datum, Return]
  // type DatumThisFunction0[Return] = js.ThisFunction0[CurrentDom, Return]

  type CurrentDom = dom.EventTarget
  type Index = Int
  type Group = js.UndefOr[Int]

  type ValueFunction0[Return] = js.Function0[Return]
  type ValueFunction1[Datum, Return] = js.Function1[Datum, Return]
  type ValueFunction2[Datum, Return] = js.Function2[Datum, Index, Return]
  type ValueFunction3[Datum, Return] = js.Function3[Datum, Index, Group, Return]

  type ValueThisFunction0[C <: CurrentDom, Return] = js.ThisFunction0[C, Return]
  type ValueThisFunction1[C <: CurrentDom, Datum, Return] = js.ThisFunction1[C, Datum, Return]
  type ValueThisFunction2[C <: CurrentDom, Datum, Return] = js.ThisFunction2[C, Datum, Index, Return]
  type ValueThisFunction3[C <: CurrentDom, Datum, Return] = js.ThisFunction3[C, Datum, Index, Group, Return]

  type ListenerFunction0 = ValueFunction0[Unit]
  type ListenerFunction1[Datum] = ValueFunction1[Datum, Unit]
  type ListenerFunction2[Datum] = ValueFunction2[Datum, Unit]
  type ListenerFunction3[Datum] = ValueFunction3[Datum, Unit]

  type ListenerThisFunction0[C <: CurrentDom] = ValueThisFunction0[C, Unit]
  type ListenerThisFunction1[C <: CurrentDom, Datum] = ValueThisFunction1[C, Datum, Unit]
  type ListenerThisFunction2[C <: CurrentDom, Datum] = ValueThisFunction2[C, Datum, Unit]
  type ListenerThisFunction3[C <: CurrentDom, Datum] = ValueThisFunction3[C, Datum, Unit]

  implicit class SelectionExtensions[Datum](val s: Selection[Datum]) extends AnyVal {
    def nodeAs[T <: dom.EventTarget] = s.node().asInstanceOf[T]
  }

  implicit class SimulationExtensions[N <: SimulationNode](val s: Simulation[N]) extends AnyVal {
    def forceAs[F <: Force[N]](name: String) = s.force(name).asInstanceOf[F]
  }

  implicit def baseEventToZoomEvent(e: BaseEvent): ZoomEvent = e.asInstanceOf[ZoomEvent]
  implicit def baseEventToDragEvent(e: BaseEvent): DragEvent = e.asInstanceOf[DragEvent]
} 
Example 95
Source File: BooApp.scala    From boopickle   with Apache License 2.0 5 votes vote down vote up
package boopickle.perftests

import boopickle.BufferPool
import org.scalajs.dom
import org.scalajs.dom.html

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel, JSGlobal, JSName}
import scala.scalajs.js.typedarray.Uint8Array
import scalatags.JsDom.all._

@JSGlobal("Zlib.Gzip")
@js.native
class Gzip(data: js.Array[Byte]) extends js.Object {
  def compress(): Uint8Array = js.native
}

@JSExportTopLevel("BooApp")
object BooApp {

  import scala.scalajs.js.JSConverters._

  def runTests(resultsDiv: html.Div) = {
    val resView = pre.render
    resultsDiv.innerHTML = ""
    resultsDiv.appendChild(div(cls := "bold", s"Running ${Tests.suites.size} tests").render)
    resultsDiv.appendChild(resView)
    def runNext(suites: Seq[PerfTestSuite]): Unit = {
      val suite  = suites.head
      val header = s"${1 + Tests.suites.size - suites.size}/${Tests.suites.size} : ${suite.name}"
      resView.innerHTML = resView.innerHTML + header + "\n"
      resView.innerHTML = resView.innerHTML + "=" * header.length + "\n"
      resView.innerHTML = resView.innerHTML + f"${"Library"}%-10s ${"ops/s"}%-10s ${"%"}%-10s ${"size"}%-10s ${"%"}%-10s ${"size.gz"}%-10s ${"%"}%-10s" + "\n"
      val tester = new PerfTester(suite)
      val res    = tester.runSuite
      // zip result data to see how small it gets
      val resSizes = res.results.map { r =>
        val rawSize = r.data.length
        val gz      = new Gzip(r.data.toJSArray)
        (r, rawSize, gz.compress().length)
      }
      val maxCount  = resSizes.map(_._1.count).max
      val minSize   = resSizes.map(_._2).min
      val minGZSize = resSizes.map(_._3).min
      resSizes.foreach { r =>
        resView.innerHTML = resView.innerHTML + f"${r._1.name}%-10s ${r._1.count}%-10d ${f"${r._1.count * 100.0 / maxCount}%.1f%%"}%-10s ${r._2}%-10d ${f"${r._2 * 100.0 / minSize}%.0f%%"}%-10s ${r._3}%-10d ${f"${r._3 * 100.0 / minGZSize}%.0f%%"}%-10s" + "\n"
      }
      resView.innerHTML = resView.innerHTML + "\n"
      if (suites.tail.nonEmpty)
        dom.window.setTimeout(() => runNext(suites.tail), 100)
      else {
        resultsDiv.appendChild(h4("Completed!").render)
      }
      // print out buffer pool usage
      println(s"""BufferPool:
            |  allocations = ${BufferPool.allocOk}
            |  misses      = ${BufferPool.allocMiss}
            """.stripMargin)
      ()
    }
    dom.window.setTimeout(() => runNext(Tests.suites), 10)
  }

  @JSExport
  def main(): Unit = {
    val contentRoot = dom.document.getElementById("contentRoot")
    val runButton   = button(cls := "waves-effect waves-light btn", i(cls := "mdi-av-play-arrow right"), "Run tests").render
    val results     = div(cls := "row").render
    runButton.onclick = (e: dom.Event) => runTests(results)

    contentRoot.appendChild(div(cls := "row", runButton).render)
    contentRoot.appendChild(results)
    ()
  }
} 
Example 96
Source File: CodeExample.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.common

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom
import org.scalajs.dom.ext.PimpedNodeList

import scala.scalajs.js


object CodeExample {


  object Style {

    val pageBodyContent = Seq( borderRadius := "2px" ,
      
      boxShadow := "0 1px 4px rgba(223, 228, 228, 0.79)" ,
      maxWidth := "1024px" )

    val contentDemo = Seq(padding := "30px",
     fontSize := "14px"
    )

    val contentCode =Seq( borderTop := "solid 1px #8B8888" ,
      padding := "20px"
    )

  }

  val component = ReactComponentB[Props]("codeexample")
    .render((P,C) => {
       div(Style.pageBodyContent)(
         div(Style.contentDemo ,key := "dan" )(
           C
         ),
         pre(Style.contentCode ,key := "code")(
          code(P.code)
         )
       )
    })
    .configure(installSyntaxHighlighting)
    .build

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

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

  def apply(code: String ,ref: js.UndefOr[String] = "", key: js.Any = {})(children : ReactNode *) = component.set(key,ref)(Props(code),children)

} 
Example 97
Source File: PReplicate.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{PouchDB, ReplicateOptions}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PReplicate {

  val code =
    """
      | val rep = PouchDB.replicate("scalajs","scalajs2",ReplicateOptions.live(true).result)
      |               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
      | val db = PouchDB.create("scalajs")
      | db.post(json("checkrep" -> "chnagesrep"))
      | dom.setTimeout(() => rep.cancel(),2000)
      |
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PReplicate")
    .render(P => {
    div(
      h3("Replicate a Database"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    val rep = PouchDB.replicate("scalajs","scalajs2",ReplicateOptions.live(true).result)
               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
     val db = PouchDB.create("scalajs")
     db.post(json("checkrep" -> "chnagesrep"))
     dom.setTimeout(() => rep.cancel(),2000)
  })
    .buildU



  def apply() = component()
} 
Example 98
Source File: PChanges.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{ChangesOptions, PouchDB}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PChanges {

  val code =
    """
      |    // create or get db
      |    val db = PouchDB.create("scalajs")
      |    val changes = db.changes(ChangesOptions.since("now").live(true).result)
      |      .onChange((resp: js.Any) => println(s"changes response ${JSON.stringify(resp)} "))
      |    db.allDocs()
      |    db.post(json("check" -> "changes"))
      |    dom.setTimeout(() => changes.cancel(), 2000)
      |
    """.stripMargin

  val component = ReactComponentB[Unit]("PChanges")
    .render(P => {
    div(
      h3("All Documents"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    // create or get db
    val db = PouchDB.create("scalajs")
    val changes = db.changes(ChangesOptions.since("now").live(true).result)
      .onChange((resp: js.Any) => println(s"changes response ${JSON.stringify(resp)} "))
    db.allDocs()
    db.post(json("check" -> "changes"))
    dom.setTimeout(() => changes.cancel(), 2000)
  })
    .buildU


  def apply() = component()
} 
Example 99
Source File: PSync.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{PouchDB, ReplicateOptions}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PSync {

  val code =
    """
      | val sync = PouchDB.sync("scalajs","scalajs2",ReplicateOptions.live(true).result)
      |               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
      | val db = PouchDB.create("scalajs")
      | val db2 = PouchDB.create("scalajs2")
      | db.post(json("sync1" -> "fromdb1"))
      | db2.post(json("sync2" -> "fromdb2"))
      | dom.setTimeout(() => sync.cancel(),2000)
      | 
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PReplicate")
    .render(P => {
    div(
      h3("Replicate a Database"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    val sync = PouchDB.sync("scalajs","scalajs2",ReplicateOptions.live(true).result)
               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
     val db = PouchDB.create("scalajs")
     val db2 = PouchDB.create("scalajs2")
     db.post(json("sync1" -> "fromdb1"))
     db2.post(json("sync2" -> "fromdb2"))
     dom.setTimeout(() => sync.cancel(),2000)
  })
    .buildU



  def apply() = component()
} 
Example 100
Source File: AjaxClient.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client

import org.scalajs.dom
import upickle.Js
import upickle.default._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object AjaxClient extends autowire.Client[Js.Value, Reader, Writer] {
  override def doCall(req: Request): Future[Js.Value] = {
    dom.ext.Ajax
      .post(
        url = "/api/" + req.path.mkString("/"),
        data = upickle.json.write(Js.Obj(req.args.toSeq: _*))
      )
      .map(_.responseText)
      .map(upickle.json.read)
  }

  def read[Result: Reader](p: Js.Value) = readJs[Result](p)
  def write[Result: Writer](r: Result)  = writeJs(r)
} 
Example 101
Source File: AppRouter.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client

import diode._
import japgolly.scalajs.react.extra.router._
import org.scalajs.dom

import scala.util.Try
import scalafiddle.client.component.FiddleEditor
import scalafiddle.shared.FiddleId

sealed trait Page

object AppRouter {

  case object Home extends Page

  case class EditorPage(id: String, version: Int) extends Page

  val fiddleData = AppCircuit.connect(_.fiddleData)

  val config = RouterConfigDsl[Page]
    .buildConfig { dsl =>
      import dsl._
      import japgolly.scalajs.react.vdom.Implicits._

      (staticRoute(root, Home) ~> render(
        fiddleData(d => FiddleEditor(d, None, AppCircuit.zoom(_.outputData), AppCircuit.zoom(_.loginData)))
      )
        | dynamicRouteF(("sf" / string("\\w+") / string(".+")).pmap[EditorPage] { path =>
          Some(EditorPage(path._1, Try(path._2.takeWhile(_.isDigit).toInt).getOrElse(0)))
        }(page => (page.id, page.version.toString)))(p => Some(p.asInstanceOf[EditorPage])) ~> dynRender((p: EditorPage) => {
          val fid = FiddleId(p.id, p.version)
          AppCircuit.dispatch(UpdateId(fid, silent = true))
          fiddleData(d => FiddleEditor(d, Some(fid), AppCircuit.zoom(_.outputData), AppCircuit.zoom(_.loginData)))
        }))
        .notFound(p => redirectToPage(Home)(Redirect.Replace))
    }
    .renderWith(layout)

  val baseUrl = BaseUrl.fromWindowOrigin_/

  val (router, routerLogic) = Router.componentAndLogic(baseUrl, config)

  def layout(c: RouterCtl[Page], r: Resolution[Page]) = {
    import japgolly.scalajs.react.vdom.all._

    div(r.render()).render
  }

  def navigated(page: ModelRO[Page]): Unit = {
    // scalajs.js.timers.setTimeout(0)(routerLogic.ctl.set(page.value).runNow())
    page() match {
      case Home =>
        scalajs.js.timers.setTimeout(0)(dom.window.location.assign("/"))
      case EditorPage(id, version) =>
        scalajs.js.timers.setTimeout(0)(dom.window.location.assign(s"/sf/$id/$version"))
    }
  }

  // subscribe to navigation changes
  AppCircuit.subscribe(AppCircuit.zoom(_.navLocation))(navigated)
} 
Example 102
Source File: Dropdown.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client.component

import japgolly.scalajs.react._
import org.scalajs.dom
import org.scalajs.dom.raw.{HTMLElement, MouseEvent}
import scalajs.js

object Dropdown {
  import japgolly.scalajs.react.vdom.all._

  case class State(isOpen: Boolean = false)

  case class Props(classes: String, buttonContent: VdomNode, content: (() => Callback) => VdomNode)

  case class Backend($ : BackendScope[Props, State]) {
    def render(props: Props, state: State) = {
      div(cls := s"ui dropdown ${props.classes} ${if (state.isOpen) "active visible" else ""}", onClick ==> {
        (e: ReactEventFromHtml) =>
          dropdownClicked(e, state.isOpen)
      })(
        props.buttonContent,
        props.content(() => closeDropdown()).when(state.isOpen)
      )
    }

    val closeFn: js.Function1[MouseEvent, _] = (e: MouseEvent) => closeDropdown(e)

    def dropdownClicked(e: ReactEventFromHtml, isOpen: Boolean): Callback = {
      if (!isOpen) {
        Callback {
          dom.document.addEventListener("click", closeFn)
        } >> $.modState(s => s.copy(isOpen = true))
      } else {
        Callback.empty
      }
    }

    def closeDropdown(e: MouseEvent): Unit = {
      val state = $.state.runNow()
      val node  = $.getDOMNode.runNow().asInstanceOf[HTMLElement]
      if (state.isOpen && !node.contains(e.target.asInstanceOf[HTMLElement])) {
        closeDropdown().runNow()
      }
    }

    def closeDropdown(): Callback = {
      dom.document.removeEventListener("click", closeFn)
      $.modState(s => s.copy(isOpen = false))
    }
  }

  val component = ScalaComponent
    .builder[Props]("FiddleEditor")
    .initialState(State())
    .renderBackend[Backend]
    .build

  def apply(classes: String, buttonContent: VdomNode)(content: (() => Callback) => VdomNode) =
    component(Props(classes, buttonContent, content))
} 
Example 103
Source File: Utils.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client

import org.scalajs.dom

import scala.language.implicitConversions
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.typedarray.Uint8Array
import scala.scalajs.js.|

class JsVal(val value: js.Dynamic) {
  def get(name: String): Option[JsVal] = {
    (value.selectDynamic(name): Any) match {
      case () => None
      case v  => Some(JsVal(v.asInstanceOf[js.Dynamic]))
    }
  }

  def apply(name: String): JsVal = get(name).get
  def apply(index: Int): JsVal   = value.asInstanceOf[js.Array[JsVal]](index)

  def keys: Seq[String]  = js.Object.keys(value.asInstanceOf[js.Object]).toSeq.map(x => x: String)
  def values: Seq[JsVal] = keys.map(x => JsVal(value.selectDynamic(x)))

  def isDefined: Boolean = !js.isUndefined(value)
  def isNull: Boolean    = value eq null

  def asDouble: Double   = value.asInstanceOf[Double]
  def asBoolean: Boolean = value.asInstanceOf[Boolean]
  def asString: String   = value.asInstanceOf[String]

  override def toString: String = js.JSON.stringify(value)
}

object JsVal {
  implicit def jsVal2jsAny(v: JsVal): js.Any = v.value

  implicit def jsVal2String(v: JsVal): js.Any = v.toString

  def parse(value: String) = new JsVal(js.JSON.parse(value))

  def apply(value: js.Any) = new JsVal(value.asInstanceOf[js.Dynamic])

  def obj(keyValues: (String, js.Any)*) = {
    val obj = new js.Object().asInstanceOf[js.Dynamic]
    for ((k, v) <- keyValues) {
      obj.updateDynamic(k)(v.asInstanceOf[js.Any])
    }
    new JsVal(obj)
  }

  def arr(values: js.Any*) = {
    new JsVal(values.toJSArray.asInstanceOf[js.Dynamic])
  }
}

@JSGlobal("Zlib.Gzip")
@js.native
class Gzip(data: js.Array[Byte]) extends js.Object {
  def compress(): Uint8Array = js.native
}

@JSGlobal("Zlib.Gunzip")
@js.native
class Gunzip(data: js.Array[Byte]) extends js.Object {
  def decompress(): Uint8Array = js.native
}

@JSGlobal("sha1")
@js.native
object SHA1 extends js.Object {
  def apply(s: String): String = js.native
}

@js.native
@JSGlobal("ScalaFiddleConfig")
object ScalaFiddleConfig extends js.Object {
  val compilerURL: String               = js.native
  val helpURL: String                   = js.native
  val scalaVersions: js.Array[String]   = js.native
  val scalaJSVersions: js.Array[String] = js.native
}

@js.native
@JSGlobal
object Mousetrap extends js.Object {
  def bind(key: String | js.Array[String], f: js.Function1[dom.KeyboardEvent, Boolean], event: String = js.native): Unit =
    js.native

  def bindGlobal(
      key: String | js.Array[String],
      f: js.Function1[dom.KeyboardEvent, Boolean],
      event: String = js.native
  ): Unit = js.native

  def unbind(key: String): Unit = js.native

  def reset(): Unit = js.native
} 
Example 104
Source File: MetabrowseEditorService.scala    From metabrowse   with Apache License 2.0 5 votes vote down vote up
package metabrowse

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import monaco.Range
import monaco.Promise
import monaco.Uri
import monaco.editor.IActionDescriptor
import monaco.editor.IEditor
import monaco.editor.IEditorConstructionOptions
import monaco.editor.IEditorOverrideServices
import monaco.editor.IStandaloneCodeEditor
import monaco.services.IResourceInput
import monaco.services.IEditorService
import org.scalajs.dom

class MetabrowseEditorService(index: MetabrowseSemanticdbIndex)
    extends IEditorService {
  private lazy val editor: IStandaloneCodeEditor = {
    val app = dom.document.getElementById("editor")
    app.innerHTML = ""
    val options = jsObject[IEditorConstructionOptions]
    options.readOnly = true
    options.scrollBeyondLastLine = false

    val overrides = jsObject[IEditorOverrideServices]
    overrides("textModelService") = MetabrowseTextModelService
    overrides("editorService") = this

    val editor = monaco.editor.Editor.create(app, options, overrides)
    editor.asInstanceOf[js.Dynamic].getControl = { () =>
      // NOTE: getControl() is defined on SimpleEditor and is called when changing files.
      editor
    }

    editor
  }

  def addAction(action: IActionDescriptor): Unit =
    editor.addAction(action)

  def resize(): Unit =
    editor.layout()

  def open(input: IResourceInput): Future[IStandaloneCodeEditor] = {
    val selection = input.options.selection
    for {
      MetabrowseMonacoDocument(document, model) <- MetabrowseTextModelService
        .modelDocument(
          input.resource
        )
    } yield {
      editor.setModel(model.`object`.textEditorModel)
      index.dispatch(MetabrowseEvent.SetDocument(document))
      selection.foreach { irange =>
        val range = Range.lift(irange)
        editor.setSelection(range)
        editor.revealPositionInCenter(range.getStartPosition())
        editor.focus()
      }
      editor
    }
  }

  override def openEditor(
      input: IResourceInput,
      sideBySide: js.UndefOr[Boolean] = js.undefined
  ): Promise[IEditor] =
    open(input).toMonacoPromise
} 
Example 105
Source File: JSCallbacks.scala    From scalajs-bootstrap   with MIT License 5 votes vote down vote up
package com.karasiq.bootstrap.context

import scala.language.postfixOps
import scala.scalajs.js
import scalatags.generic.{Attr, AttrValue}

import org.scalajs.dom
import org.scalajs.dom.raw.MouseEvent

trait JSCallbacks extends Callbacks { self: JSRenderingContext ⇒
  type Callback = js.Function
  type ClickElement = dom.html.Element
  type InputElement = dom.html.Input
  type FormElement = dom.html.Form

  object Callback extends CallbackFactory {
    def onClick(f: ClickElement ⇒ Unit): js.Function = {
      js.ThisFunction.fromFunction2 { (element: dom.html.Element, ev: MouseEvent) ⇒
        if (ev.button == 0 && !(ev.shiftKey || ev.altKey || ev.metaKey || ev.ctrlKey)) {
          ev.preventDefault()
          f(element)
        }
      }
    }

    def onInput(f: InputElement ⇒ Unit): js.Function = {
      js.ThisFunction.fromFunction2 { (element: dom.html.Input, ev: Event) ⇒
        // ev.preventDefault()
        f(element)
      }
    }

    def onSubmit(f: FormElement ⇒ Unit): js.Function = {
      js.ThisFunction.fromFunction2 { (element: dom.html.Form, ev: Event) ⇒
        ev.preventDefault()
        f(element)
      }
    }
  }

  implicit def callbackValue: AttrValue[Element, js.Function] = new AttrValue[Element, js.Function] {
    def apply(t: Element, a: Attr, v: js.Function): Unit = {
      scalatags.JsDom.all.bindJsAny.apply(t, a, v)
    }
  }
} 
Example 106
Source File: BootstrapTestApp.scala    From scalajs-bootstrap   with MIT License 5 votes vote down vote up
package com.karasiq.bootstrap.test.frontend

import scala.language.postfixOps

import org.scalajs.dom
import org.scalajs.dom.window
import rx._

import com.karasiq.bootstrap.Bootstrap.default._
import scalaTags.all._

import com.karasiq.bootstrap.jquery.BootstrapJQueryContext

object BootstrapTestApp {
  def main(args: Array[String]): Unit = {
    BootstrapJQueryContext.useNpmImports()
    jQuery(() ⇒ {
      // Table tab will appear after 3 seconds
      val tableVisible = Var(false)
      val tabTitle = Var("Wait...")

      // Show table tab in 3 seconds
      window.setTimeout(() ⇒ {
        tableVisible.update(true)
        window.setTimeout(() ⇒ { tabTitle() = "Table" }, 1000)
      }, 3000)
      
      val tabs = Var(Seq[NavigationTab](
        NavigationTab(tabTitle, "table", "table".faFwIcon, TestTable(), tableVisible.reactiveShow),
        NavigationTab("Carousel", "carousel", "picture".glyphicon, TestCarousel("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Big_Wood%2C_N2.JPG/1280px-Big_Wood%2C_N2.JPG")),
        NavigationTab("ToDo list", "todo", "fort-awesome".faFwIcon, TodoList()),
        NavigationTab("Text rendering", "text", "envelope".glyphicon, Bootstrap.jumbotron(
          FormInput.textArea(a("Text rendering", href := "./serverside.html"), rows := 30, readonly, TestHtmlPage())
        ))
      ))

      val navigationBar = NavigationBar()
        .withBrand("Scala.js Bootstrap Test", href := "https://github.com/Karasiq/scalajs-bootstrap")
        .withTabs(tabs)
        .withContentContainer(content ⇒ GridSystem.container(id := "main-container", GridSystem.mkRow(content)))
        .withStyles(NavigationBarStyle.inverse, NavigationBarStyle.fixedTop)
        .build()

      // Render page
      navigationBar.applyTo(dom.document.body)

      // Reactive navbar test
      tabs() = tabs.now :+ NavigationTab("Buttons", "buttons", "log-in".glyphicon, TestPanel("Serious business panel", PanelStyle.warning))
      navigationBar.selectTab(2)
    })
  }
} 
Example 107
Source File: BootstrapTestApp.scala    From scalajs-bootstrap   with MIT License 5 votes vote down vote up
package com.karasiq.bootstrap4.test.frontend

import scala.language.postfixOps

import org.scalajs.dom
import org.scalajs.dom.window
import rx._

import com.karasiq.bootstrap4.Bootstrap.default._
import scalaTags.all._

import com.karasiq.bootstrap.jquery.BootstrapJQueryContext

object BootstrapTestApp {
  def main(args: Array[String]): Unit = {
    BootstrapJQueryContext.useNpmImports()
    jQuery(() ⇒ {
      // Table tab will appear after 3 seconds
      val tableVisible = Var(false)
      val tabTitle = Var("Wait...")

      // Show table tab in 3 seconds
      window.setTimeout(() ⇒ {
        tableVisible.update(true)
        window.setTimeout(() ⇒ { tabTitle() = "Table" }, 1000)
      }, 3000)
      
      val tabs = Var(Seq[NavigationTab](
        NavigationTab(tabTitle, "table", "table".faFwIcon, TestTable(), tableVisible.reactiveShow),
        NavigationTab("Carousel", "carousel", "file-image-o".faFwIcon, TestCarousel("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Big_Wood%2C_N2.JPG/1280px-Big_Wood%2C_N2.JPG")),
        NavigationTab("ToDo list", "todo", "fort-awesome".faFwIcon, TodoList()),
        NavigationTab("Text rendering", "text", "file-text-o".faFwIcon, Bootstrap.jumbotron(
          FormInput.textArea(a("Text rendering", href := "./serverside.html"), rows := 30, readonly, TestHtmlPage())
        ))
      ))

      val navigationBar = NavigationBar()
        .withBrand("Scala.js Bootstrap Test", href := "https://github.com/Karasiq/scalajs-bootstrap")
        .withTabs(tabs)
        .withContentContainer(content ⇒ GridSystem.container(id := "main-container", GridSystem.mkRow(content)))
        .build()

      // Render page
      navigationBar.applyTo(dom.document.body)

      // Reactive navbar test
      tabs() = tabs.now :+ NavigationTab("Buttons", "buttons", "hand-o-right".faFwIcon, TestPanel("Serious business panel"))
      navigationBar.selectTab(2)
    })
  }
} 
Example 108
Source File: Html5SystemProvider.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package sgl
package html5

import java.net.URI

import org.scalajs.dom
import scala.scalajs.js
import js.typedarray.{ArrayBuffer, TypedArrayBuffer}

import sgl.util._

trait Html5SystemProvider extends SystemProvider with PartsResourcePathProvider {

  object Html5System extends System {

    override def exit(): Unit = {}

    override def currentTimeMillis: Long = js.Date.now.toLong

    // Note that there is no way to get nanosecond precision in Javascript, so we
    // have to do with microsecond granularity.
    override def nanoTime: Long = (dom.window.performance.now()*1000l*1000l).toLong

    //probably cleaner to return lazily and block only when iterator is called
    //class LazyTextResource(rawFile: dom.XMLHttpRequest) extends Iterator[String] = {

    //}
    //but the best would be to redefine these loading APIs to be async

    override def loadText(path: ResourcePath): Loader[Array[String]] = {
      val p = new DefaultLoader[Array[String]]()
      val rawFile = new dom.XMLHttpRequest()
      rawFile.open("GET", path.path, true)
      rawFile.onreadystatechange = (event: dom.Event) => {
        if(rawFile.readyState == 4) {
          if(rawFile.status == 200 || rawFile.status == 0) {
            p.success(rawFile.responseText.split("\n").toArray)
          } else {
            p.failure(new RuntimeException("file: " + path + " failed to load"))
          }
        }
      }
      rawFile.send(null)
      p.loader
    }

    override def loadBinary(path: ResourcePath): Loader[Array[Byte]] = {
      val p = new DefaultLoader[Array[Byte]]()
      val fileReq = new dom.XMLHttpRequest()
      fileReq.open("GET", path.path, true)
      fileReq.responseType = "arraybuffer"
      fileReq.onreadystatechange = (event: dom.Event) => {
        if(fileReq.readyState == 4) {
          if(fileReq.status == 200 || fileReq.status == 0) {
            val responseBuffer: ArrayBuffer = fileReq.response.asInstanceOf[ArrayBuffer]
            val bb: java.nio.ByteBuffer = TypedArrayBuffer.wrap(responseBuffer)
            val array: Array[Byte] = new Array(bb.remaining)
            bb.get(array)
            p.success(array)
          } else {
            p.failure(new RuntimeException("file: " + path + " failed to load"))
          }
        }
      }
      fileReq.send(null)
      p.loader
    }

    override def openWebpage(uri: URI): Unit = {
      dom.window.open(uri.toString)
    }

  }
  val System = Html5System

  
  override val ResourcesRoot = PartsResourcePath(Vector("static"))
  final override val MultiDPIResourcesRoot = PartsResourcePath(Vector())

} 
Example 109
Source File: FixedWindowTheme.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package sgl.html5
package themes

import org.scalajs.dom
import dom.html


    val windowWidth = dom.document.body.clientWidth.toInt
    val windowHeight = dom.document.body.clientHeight.toInt

    if(windowWidth < frameSize._1)
      canvas.style.left = "0"
    else {
      val left: Int = (windowWidth - canvas.width)/2
      canvas.style.left = left + "px"
    }

    if(windowHeight < frameSize._2)
      canvas.style.top = "0"
    else {
      val top: Int = (windowHeight - canvas.height)/2
      canvas.style.top = top + "px"
    }
  }
} 
Example 110
Source File: FullScreenTheme.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package sgl.html5
package themes

import org.scalajs.dom
import dom.html


class FullScreenTheme extends Theme {

  override def init(canvas: html.Canvas): Unit = {
    dom.document.body.style.margin = "0"
    dom.document.body.style.padding = "0"
    dom.document.body.style.overflow = "hidden"

    // prevent highlight on click on canvas.
    dom.document.onselectstart = (e: dom.Event) => false

    canvas.style.margin = "0"
    canvas.style.padding = "0"
    canvas.style.display = "block"
    canvas.style.position = "absolute"
    canvas.style.left = "0"
    canvas.style.top = "0"

    canvas.width = dom.window.innerWidth.toInt
    canvas.height = dom.window.innerHeight.toInt
  }

  override def onResize(canvas: html.Canvas): Unit = {
    canvas.width = dom.window.innerWidth.toInt
    canvas.height = dom.window.innerHeight.toInt
  }

} 
Example 111
Source File: LocalStorageSave.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package sgl
package html5

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


object LocalStorageSave extends AbstractSave {

  val localStorageSupported = !js.isUndefined(js.Dynamic.global.localStorage)

  // One idea could be to fallback on cookies for the implementation, although
  // I think we should be able to assume support for local storage, as our other
  // dependencies are probably stronger.

  override def putString(name: String, value: String): Unit = {
    if(localStorageSupported) {
      dom.window.localStorage.setItem(name, value)
    }
  }
  override def getString(name: String): Option[String] = {
    if(localStorageSupported) {
      val res = dom.window.localStorage.getItem(name)
      if(res == null) None else Some(res)
    } else None
  }

  override def putInt(name: String, value: Int): Unit = {
    putString(name, value.toString)
  }

  override def getInt(name: String): Option[Int] = {
    getString(name).flatMap(v => try {
      Some(v.toInt)
    } catch {
      case (_: Exception) => None
    })
  }

  override def putLong(name: String, value: Long): Unit = {
    putString(name, value.toString)
  }

  override def getLong(name: String): Option[Long] = {
    getString(name).flatMap(v => try {
      Some(v.toLong)
    } catch {
      case (_: Exception) => None
    })
  }
    
  override def putBoolean(name: String, value: Boolean): Unit = {
    putString(name, value.toString)
  }
  override def getBoolean(name: String): Option[Boolean] = {
    getString(name).flatMap(v => try {
      Some(v.toBoolean)
    } catch {
      case (_: Exception) => None
    })
  }

}

trait LocalStorageSaveComponent extends SaveComponent {
  type Save = LocalStorageSave.type
  override val Save = LocalStorageSave
} 
Example 112
Source File: Html5ConsoleLoggingProvider.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package sgl.html5
package util

import sgl.util._

import org.scalajs.dom



trait Html5ConsoleLoggingProvider extends LoggingProvider {

  import Logger._

  abstract class ConsoleLogger extends Logger {
    private def format(tag: Tag, msg: String): String = {
      val prefix = s"[ ${tag.name} ]"
      val alignedMsg = msg.trim.replaceAll("\n", "\n" + (" " * prefix.length))
      s"${prefix} $alignedMsg"
    }

    override protected def log(level: LogLevel, tag: Tag, msg: String): Unit = level match {
      case NoLogging => ()
      case Error => dom.console.error(format(tag, msg))
      case Warning => dom.console.warn(format(tag, msg))
      case Info => dom.console.info(format(tag, msg))
      case Debug => dom.console.log(format(tag, msg))
      case Trace => dom.console.log(format(tag, msg))
    }
  }
}


trait Html5DefaultConsoleLoggingProvider extends Html5ConsoleLoggingProvider {
  case object DefaultConsoleLogger extends ConsoleLogger {
    override val logLevel: Logger.LogLevel = Logger.Warning
  }
  override val logger = DefaultConsoleLogger
}

trait Html5InfoConsoleLoggingProvider extends Html5ConsoleLoggingProvider {
  case object InfoConsoleLogger extends ConsoleLogger {
    override val logLevel: Logger.LogLevel = Logger.Info
  }
  override val logger = InfoConsoleLogger
}

trait Html5VerboseConsoleLoggingProvider extends Html5ConsoleLoggingProvider {
  case object VerboseConsoleLogger extends ConsoleLogger {
    override val logLevel: Logger.LogLevel = Logger.Debug
  }
  override val logger = VerboseConsoleLogger
} 
Example 113
Source File: Homepage.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.docs.homepage

import slinky.core.StatelessComponent
import slinky.core.annotations.react
import slinky.docs.MainPageContent
import slinky.web.html._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.literal
import scala.scalajs.js.annotation.JSImport

import org.scalajs.dom

@JSImport("resources/slinky-logo-horizontal.svg", JSImport.Default)
@js.native
object SlinkyHorizontalLogo extends js.Object

@JSImport("resources/slinky-logo.svg", JSImport.Default)
@js.native
object SlinkyLogo extends js.Object

@react class Homepage extends StatelessComponent {
  type Props = Unit

  override def componentDidMount(): Unit = {
    dom.window.scrollTo(0, 0)
  }

  def render() = {
    div(
      Jumbotron(()),
      MainPageContent(Seq(
        div(style := literal(
          width = "100%",
          overflow = "auto",
          marginTop = "40px"
        ))(
          div(style := literal(
            width = "100%",
            minWidth = "800px",
            display = "flex",
            flexDirection = "row",
            justifyContent = "space-around",
          ))(
            div(style := literal(width = "33%"))(
              h3(style := literal(fontWeight = 100))("Just like ES6"),
              p("Slinky has a strong focus on mirroring the ES6 API. This means that any documentation or examples for ES6 React can be easily applied to your Scala code."),
              p("There are no new patterns involved with using Slinky. Just write React apps like you would in any other language!")
            ),
            div(style := literal(width = "33%"))(
              h3(style := literal(fontWeight = 100))("Complete Interop"),
              p("Slinky provides straightforward APIs for using external components. Simply define the component's properties using standard Scala types and you're good to go!"),
              p("In addition, Slinky components can be used from JavaScript code, thanks to a built in Scala to JS mappings. This means that your favorite libraries like React Router work out of the box with Slinky!")
            ),
            div(style := literal(width = "33%"))(
              h3(style := literal(fontWeight = 100))("First-Class Dev Experience"),
              p("Writing web applications with Scala doesn't have to feel like a degraded development experience. Slinky comes ready with full integration with familiar tools like Webpack and React DevTools."),
              p("Slinky also comes with built-in support for hot-loading via Webpack, allowing you to make your code-test-repeat flow even faster!")
            )
          )
        ),
        hr(style := literal(
          height = "1px",
          marginBottom = "-1px",
          border = "none",
          borderBottom = "1px solid #ececec",
          marginTop = "40px"
        )),
        Examples(())
      )),
      div(style := literal(
        width = "100%",
        backgroundColor = "#282c34",
        padding = "30px",
        boxSizing = "border-box",
        display = "flex",
        flexDirection = "column",
        alignItems = "center"
      ))(
        a(href := "https://www.netlify.com")(
          img(src := "https://www.netlify.com/img/global/badges/netlify-color-bg.svg")
        )
      )
    )
  }
} 
Example 114
Source File: ReactRefTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.core

import org.scalajs.dom
import org.scalajs.dom.html

import slinky.core.facade.React
import slinky.web.ReactDOM
import slinky.web.html.{div, ref}

import scala.concurrent.Promise

import org.scalatest.Assertion
import org.scalatest.funsuite.AsyncFunSuite

class ReactRefTest extends AsyncFunSuite {
  test("Can pass in a ref object to an HTML tag and use it") {
    val elemRef = React.createRef[html.Div]
    ReactDOM.render(
      div(ref := elemRef)("hello!"),
      dom.document.createElement("div")
    )

    assert(elemRef.current.innerHTML == "hello!")
  }

  test("Can pass in a ref object to a Slinky component and use it") {
    val promise: Promise[Assertion] = Promise()
    val ref = React.createRef[TestForceUpdateComponent.Def]

    ReactDOM.render(
      TestForceUpdateComponent(() => promise.success(assert(true))).withRef(ref),
      dom.document.createElement("div")
    )

    ref.current.forceUpdate()

    promise.future
  }

  test("Can use forwardRef to pass down a ref to a lower element") {
    val forwarded = React.forwardRef[String, html.Div](FunctionalComponent((props, rf) => {
      div(ref := rf)(props)
    }))

    val divRef = React.createRef[html.Div]
    ReactDOM.render(
      forwarded("hello").withRef(divRef),
      dom.document.createElement("div")
    )

    assert(divRef.current.innerHTML == "hello")
  }
} 
Example 115
Source File: ProfilerTest.scala    From slinky   with MIT License 5 votes vote down vote up
package slinky.core

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

import org.scalatest.funsuite.AnyFunSuite

class ProfilerTest extends AnyFunSuite {
  test("Can render a Profiler component with children") {
    val target = dom.document.createElement("div")
    ReactDOM.render(
      Profiler(id = "profiler", onRender = (_, _, _, _, _, _, _) => {})(
        div("hello!")
      ),
      target
    )

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

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

import org.scalatest.funsuite.AnyFunSuite

class SuspenseTest extends AnyFunSuite {
  test("Can render a Suspense component with children") {
    val target = dom.document.createElement("div")
    ReactDOM.render(
      Suspense(fallback = div())(
        div("hello!")
      ),
      target
    )

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

import slinky.core.facade.StrictMode
import slinky.web.ReactDOM
import slinky.web.html.div

import org.scalajs.dom

import org.scalatest.funsuite.AnyFunSuite

class StrictModeTest extends AnyFunSuite {
  test("Can render a StrictMode component with children") {
    val target = dom.document.createElement("div")
    ReactDOM.render(
      StrictMode(
        div()
      ),
      target
    )

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

import slinky.core.facade.{Fragment, ReactElement}
import slinky.web.ReactDOM
import slinky.web.html._
import org.scalajs.dom

import org.scalatest.funsuite.AnyFunSuite

class ComponentReturnTypeTests extends AnyFunSuite {
  def testElement(elem: ReactElement): Unit = {
    assert((div(elem): ReactElement) != null) // test use in another element
    ReactDOM.render(div(elem), dom.document.createElement("div")) // test rendering to DOM
    ()
  }

  test("Components can return - arrays") {
    testElement(Seq(h1("a"), h1("b")))
  }

  test("Components can return - strings") {
    testElement("hello")
  }

  test("Components can return - numbers") {
    testElement(1)
    testElement(1D)
    testElement(1F)
  }

  test("Components can return - portals") {
    testElement(ReactDOM.createPortal(null, dom.document.createElement("div")))
  }

  test("Components can return - null") {
    testElement(null)
  }

  test("Components can return - booleans") {
    testElement(true)
    testElement(false)
  }

  test("Components can return - options") {
    testElement(Some(h1("hi")))
    testElement(Some(NoPropsComponent()))
    testElement(None)
  }

  test("Components can return - fragments") {
    testElement(Fragment(h1("hi")))
  }
} 
Example 119
Source File: ShowcaseApp.scala    From scalajs-react-bridge   with MIT License 5 votes vote down vote up
package com.payalabs.scalajs.react.bridge.showcase

import com.payalabs.scalajs.react.bridge.elements.{Button, FormControl, ReactMediumEditor, TagsInput}
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import org.scalajs.dom

import scala.scalajs.js

object ShowcaseApp extends js.JSApp {
  def main(): Unit = {
    ShowcaseComponent().renderIntoDOM(dom.document.getElementById("app-container"))
  }
}

object ShowcaseComponent {
  case class State(tags: Seq[String])
  type Props = Unit

  class Backend(scope: BackendScope[Props, State]) {
    def updateTags(value: js.Array[String]) = scope.modState(s =>
      s.copy(tags = value.toSeq)
    )

    def validateLength(value: String) = CallbackTo { value.length <= 7 }

    def render(state: State): VdomElement = {
      div(className := "col-sm-10 col-sm-offset-1")(
        h1()(
          "Example components created with ",
          a(href := "https://github.com/payalabs/scalajs-react-bridge")("scalajs-react-bridge")
        ),
        div(className := "well")(
          b("Tags input. Values with size > 7 considered invalid"),
          TagsInput(value = state.tags, onChange = updateTags _, validate = validateLength _)
        ),
        div(className := "well")(
          ReactMediumEditor(text =
            """
              | <h1>Medium Editor</h1>
              |
              | <p>Click here and start editing.</p>
              |
              | <b>Select some text to see the editor toolbar pop up.</b>
            """.stripMargin, options = Map("buttons" -> js.Array("bold", "italic", "underline", "anchor", "header1", "header2", "quote", "orderedlist", "unorderedlist")))
        ),
        div(className := "well")(
          b("Bootstrap"),
          FormControl(placeholder = "This is a bootstrap input", `type` = "text"),
          Button()("Bootstrap Button")
        )
      )

    }
  }

  val component =
    ScalaComponent.builder[Props](this.getClass.getSimpleName).
      initialState(State(tags = Seq("some", "default", "tags"))).
      renderBackend[Backend].
      build

  def apply(): VdomElement = component()

} 
Example 120
Source File: AutowireClient.scala    From scala-clippy   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.clippy

import org.scalajs.dom
import scala.concurrent.Future
import scalajs.concurrent.JSExecutionContext.Implicits.queue
import upickle.default._
import upickle.Js

object AutowireClient extends autowire.Client[Js.Value, Reader, Writer] {
  override def doCall(req: Request): Future[Js.Value] =
    dom.ext.Ajax
      .post(
        url = "/ui-api/" + req.path.mkString("/"),
        data = upickle.json.write(Js.Obj(req.args.toSeq: _*))
      )
      .map(_.responseText)
      .map(upickle.json.read)

  def read[Result: Reader](p: Js.Value) = readJs[Result](p)
  def write[Result: Writer](r: Result)  = writeJs(r)
} 
Example 121
Source File: Example.scala    From scalajs-react-mdl   with MIT License 5 votes vote down vote up
package com.payalabs.scalajs.react.mdl

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react.vdom.all
import org.scalajs.dom

import scala.scalajs.js

object Example extends js.JSApp {
  def main(): Unit = {
    val component = ReactComponentB[Unit]("ShowcaseApp").render { _ =>
      div(
        a(href := "https://github.com/payalabs/scalajs-react-mdl")(
          img(
            position := "absolute",
            top := "0px",
            right := "0px",
            border := "0px",
            zIndex := "1000",
            src := "https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67",
            alt := "Fork me on GitHub",
            "data-canonical-src".reactAttr := "https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"
          )
        ),
        div(className := "mdl-layout mdl-js-layout mdl-layout--fixed-header")(
          header(className := "mdl-layout__header")(
            div(className := "mdl-layout__header-row")(
              span(className := "mdl-layout-title")("scalajs-react-mdl"),
              div(className := "mdl-layout-spacer")
            )
          ),
          all.main(className := "mdl-layout__content")(
            div(className := "mdl-grid")(
              div(className := "mdl-cell mdl-cell--2-col"),
              div(className := "mdl-cell mdl-cell--8-col")(
                h2(
                  "Examples components using ",
                  a(href := "http://github.com/payalabs/scalajs-react-mdl")("scalajs-react-mdl")
                ),
                h3("FAB with ripple"),
                button(className := "mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored")(
                  i(className := "material-icons")("add")
                ).material,
                h3("Accent colored button with ripple"),
                button(className := "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent")(
                  "I am a button"
                ).material,
                h3("Indeterminate progress bar"),
                div(className := "mdl-progress mdl-js-progress mdl-progress__indeterminate progress-demo").material,
                h3("Default spinner"),
                div(className := "mdl-spinner mdl-js-spinner is-active").material,
                h3("Slider"),
                input(className := "mdl-slider mdl-js-slider", `type` := "range",
                  "min".reactAttr := "0", "max".reactAttr := "100").material,
                h3("Numeric textfield with floating label"),
                div(className := "mdl-textfield mdl-js-textfield mdl-textfield--floating-label", width := "100px")(
                  input(className := "mdl-textfield__input", `type` := "number", id := "sample-textfield-number"),
                  label(className := "mdl-textfield__label", `for` := "sample-textfield-number")("Number...")
                ).material,
                h3("Email textfield with floating label"),
                div(className := "mdl-textfield mdl-js-textfield mdl-textfield--floating-label", width := "100px")(
                  input(className := "mdl-textfield__input", `type` := "email", id := "sample-textfield-email"),
                  label(className := "mdl-textfield__label", `for` := "sample-textfield-email")("Email..."),
                  span(className := "mdl-textfield__error", display := "flex")("Not an email!")
                ).material
              )
            )
          )
        ).material
      )
    }.build()

    ReactDOM.render(component, dom.document.getElementById("main-content"))
  }
}