scala.scalajs.js.JSApp Scala Examples

The following examples show how to use scala.scalajs.js.JSApp. 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: NativeApp.scala    From scalajs-react-native   with Apache License 2.0 5 votes vote down vote up
package chandu0101.scalajs.rn.examples

import chandu0101.scalajs.rn._
import chandu0101.scalajs.rn.examples.movies.MoviesApp
import chandu0101.scalajs.rn.examples.uiexplorer.UIExplorerApp
import chandu0101.scalajs.rn.examples.uiexplorer.components.navigator.NavigationBarSample

import scala.scalajs.js.Dynamic.{literal => lit}
import scala.scalajs.js.JSApp


object NativeApp extends JSApp {
  def main() = {
    val ScalaJSReactNative = ReactNativeComponentB[Unit]("ScalaJSReactNative")
      .render((P) => {
//      HelloNative()
//      MoviesApp()
       UIExplorerApp()
    }).buildNative

    ReactNative.AppRegistry.registerComponent("ScalaJSReactNative", () => ScalaJSReactNative)
  }
} 
Example 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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()
    })
  }
}