scala.scalajs.js.annotation.JSExport Scala Examples

The following examples show how to use scala.scalajs.js.annotation.JSExport. 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: 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 3
Source File: JSLauncher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.todo

import io.udash.logging.CrossLogging
import io.udash.wrappers.jquery._
import org.scalajs.dom.Element

import scala.scalajs.js.annotation.JSExport

object JSLauncher extends CrossLogging {
  import ApplicationContext._

  @JSExport
  def main(args: Array[String]): Unit = {
    jQ((_: Element) => {
      jQ(".todoapp").get(0) match {
        case None =>
          logger.error("Application root element not found! Check your index.html file!")
        case Some(root) =>
          applicationInstance.run(root)
      }
    })
  }
} 
Example 4
Source File: JSLauncher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.rest

import io.udash.logging.CrossLogging
import io.udash.wrappers.jquery._
import org.scalajs.dom.Element

import scala.scalajs.js.annotation.JSExport

object JSLauncher extends CrossLogging {
  import ApplicationContext._

  @JSExport
  def main(args: Array[String]): Unit = {
    jQ((_: Element) => {
      jQ("#application").get(0) match {
        case None =>
          logger.error("Application root element not found! Check your index.html file!")
        case Some(root) =>
          applicationInstance.run(root)
      }
    })
  }
} 
Example 5
Source File: JSLauncher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.demos.files

import io.udash.logging.CrossLogging
import io.udash.wrappers.jquery._
import org.scalajs.dom.Element

import scala.scalajs.js.annotation.JSExport

object JSLauncher extends CrossLogging {
  @JSExport
  def main(args: Array[String]): Unit = {
    jQ((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check your index.html file!")
      } else {
        ApplicationContext.applicationInstance.run(appRoot.get)
      }
    })
  }
} 
Example 6
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 7
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 8
Source File: Main.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.web

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

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

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

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

    println("bootstrap")
    val bootstrap = Bootstrap

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

    println("Initializing")
    App.app()
      .renderIntoDOM(document.getElementById("demoContent"))
    println("Initialized")
  }
} 
Example 9
Source File: XOrder.scala    From topshell   with MIT License 5 votes vote down vote up
package com.github.ahnfelt.topshell.data

import scala.collection.immutable.TreeMap
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("XOrder")
object XOrder {

    val ordering : Ordering[Any] = (l : Any, r : Any) => (l, r) match {
        case (a : js.Array[_], b : js.Array[_]) =>
            a.zip(b).find { case (x, y) =>
                ordering.compare(x, y) != 0
            }.map { case (x, y) => ordering.compare(x, y) }.getOrElse {
                ordering.compare(a.length, b.length)
            }
        case (a : String, b : String) => a.compareTo(b)
        case (a : Double, b : Double) => a.compareTo(b)
        case (a : Int, b : Int) => a.compareTo(b)
        case _ =>
            val a = l.asInstanceOf[js.Dictionary[Any]]
            val b = r.asInstanceOf[js.Dictionary[Any]]
            var (key, result) = if(a.contains("_") && b.contains("_")) {
                ("_", ordering.compare(a("_"), b("_")))
            } else ("", 0)
            for((k, v) <- a; w <- b.get(k) if k != "_" && (result == 0 || k < key)) {
                val newResult = ordering.compare(v, w)
                if(newResult != 0) {
                    key = k
                    result = newResult
                }
            }
            result
    }

    @JSExport
    def min(a : Any, b : Any) : Any = ordering.min(a, b)

    @JSExport
    def max(a : Any, b : Any) : Any = ordering.max(a, b)

    @JSExport
    def equal(a : Any, b : Any) : Boolean = ordering.equiv(a, b)

    @JSExport
    def notEqual(a : Any, b : Any) : Boolean = !ordering.equiv(a, b)

    @JSExport
    def less(a : Any, b : Any) : Boolean = ordering.lt(a, b)

    @JSExport
    def lessEqual(a : Any, b : Any) : Boolean = ordering.lteq(a, b)

    @JSExport
    def greater(a : Any, b : Any) : Boolean = ordering.gt(a, b)

    @JSExport
    def greaterEqual(a : Any, b : Any) : Boolean = ordering.gteq(a, b)

} 
Example 10
Source File: XSet.scala    From topshell   with MIT License 5 votes vote down vote up
package com.github.ahnfelt.topshell.data

import scala.collection.immutable.{SortedSet, TreeMap, TreeSet}
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("XSet")
object XSet {

    private implicit val ordering : Ordering[Any] = XOrder.ordering

    type XSet = SortedSet[Any]
    type Fun[A, B] = js.Function1[A, B]

    @JSExport
    def isInstance(any : Any) : Boolean = any.isInstanceOf[scala.collection.immutable.SortedSet[_]]

    @JSExport
    def of(array : js.Array[Any]) : XSet = {
        TreeSet(array : _*)
    }

    @JSExport
    def toList(set : XSet) : js.Array[Any] = {
        js.Array(set.toList : _*)
    }

    @JSExport
    def toMap(f : Fun[Any, Any], set : XSet) : XMap.XMap = {
        set.foldLeft(XMap.empty) ( (m, v) => m + (v -> f(v)) )
    }

    @JSExport
    def add(value : Any, set : XSet) : XSet = {
        set + value
    }

    @JSExport
    def remove(value : Any, set : XSet) : XSet = {
        set - value
    }

    @JSExport
    def union(a : XSet, b : XSet) : XSet = {
        a ++ b
    }

    @JSExport
    def intersect(a : XSet, b : XSet) : XSet = {
        a.intersect(b)
    }

    @JSExport
    def exclude(a : XSet, b : XSet) : XSet = {
        b -- a
    }

    @JSExport
    def has(value : Any, set : XSet) : Boolean = {
        set.contains(value)
    }

    @JSExport
    def from(value : Any, set : XSet) : XSet = {
        set.from(value)
    }

    @JSExport
    def until(value : Any, set : XSet) : XSet = {
        set.until(value)
    }

    @JSExport
    def foldLeft(f : Fun[Any, Fun[Any, Any]], z : Any, set : XSet) : Any = {
        set.foldLeft(z) { (v, p) => f(p)(v) }
    }

    @JSExport
    def foldRight(f : Fun[Any, Fun[Any, Any]], z : Any, set : XSet) : Any = {
        set.foldRight(z) { (p, v) => f(p)(v) }
    }

    @JSExport
    def size(set : XSet) : Int = {
        set.size
    }

    @JSExport
    def isEmpty(set : XSet) : Boolean = {
        set.isEmpty
    }

    @JSExport
    val empty : XSet = TreeSet.empty

} 
Example 11
Source File: Main.scala    From hammock   with MIT License 5 votes vote down vote up
package examplejs

import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.util._
import scala.concurrent.ExecutionContext.Implicits.global
import org.scalajs.jquery.jQuery
import cats.effect._
import hammock._
import hammock.marshalling._
import hammock.js._
import hammock.circe.implicits._
import io.circe.generic.auto._
import Interpreter._

@JSExportTopLevel("Main")
object Main {
  implicit val cs = IO.contextShift(global)

  case class Resp(headers: Map[String, String], origin: String, url: String)
  case class Req(name: String, number: Int)

  @JSExport
  def main(): Unit = {

    val uri = uri"http://httpbin.org/post"

    val request: IO[Resp] = Hammock
      .request(Method.POST, uri, Map(), Some(Req("name", 4)))
      .as[Resp]
      .exec[IO]

    request.unsafeToFuture.onComplete {
      case Success(resp) =>
        jQuery("#result").append(s"""
<h3>Req you sent to the server:</h3>
<pre>$resp</pre>
""")
      case Failure(ex) => ex.printStackTrace()
    }
  }
} 
Example 12
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 13
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 14
Source File: Main.scala    From scala-game-library   with MIT License 5 votes vote down vote up
package com.regblanc.sgl.snake
package html5

import sgl._
import sgl.scene._
import sgl.html5._
import sgl.html5.themes._
import sgl.util._
import sgl.html5.util._

import scala.scalajs.js.annotation.JSExport

object Main extends Html5App with core.AbstractApp 
  with Html5VerboseConsoleLoggingProvider
  //with NoLoggingProvider
  with InputHelpersComponent {

  override val GameCanvasID: String = "my_canvas"

  //We should not force the fps on Html5 and just let
  //requestAnimationFrame do its best
  override val TargetFps: Option[Int] = None

  override val theme = new FixedWindowTheme {
    override val frameSize = (TotalWidth, TotalHeight)
  }

} 
Example 15
Source File: DemoSuccess.scala    From aws-lambda-scalajs   with MIT License 5 votes vote down vote up
package demo.awslambda

import scala.scalajs.js.annotation.JSExport

@JSExport
object DemoSuccess {
  @JSExport
  def apply(event: Object, context: Object): String = {
    println("Scala JS, Hello world!")
    println(event)
    println(context)
    "Completed Lambda Hello World"
  }
}

@JSExport
object DemoFail {
  @JSExport
  def apply(event: Object, context: Object): String = {
    println("This lambda will fail!")
    throw new IllegalArgumentException("failed from Scala")
  }
} 
Example 16
Source File: QueryParser.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql.js

import com.criteo.vizatra.vizsql.js.common._
import com.criteo.vizatra.vizsql.{DB, Query, VizSQL}

import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.JSExport

@JSExport("QueryParser")
object QueryParser {
  @JSExport
  def parse(query: String, db: DB): ParseResult =
    VizSQL.parseQuery(query, db) match {
      case Left(err) => new ParseResult(new ParseError(err.msg, err.pos))
      case Right(query) => convert(query)
    }

  def convert(query: Query): ParseResult = {
    val select = query.select
    val db = query.db
    val result = for {
      columns <- select.getColumns(db).right
      tables <- select.getTables(db).right
    } yield (columns, tables)
    result fold (
      err => new ParseResult(new ParseError(err.msg, err.pos)), { case (columns, tables) =>
        val cols = columns map Column.from
        val tbls = tables map { case (maybeSchema, table) => Table.from(table, maybeSchema) }
        new ParseResult(select = new Select(cols.toJSArray, tbls.toJSArray))
      }
    )
  }
} 
Example 17
Source File: Database.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql.js

import com.criteo.vizatra.vizsql.DB
import com.criteo.vizatra.vizsql.js.json.DBReader

import scala.scalajs.js.Dynamic
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, ScalaJSDefined}

@JSExport("Database")
object Database {
  
  @JSExport
  def from(input: Dynamic): Database = new Database(parse(input))
}

@ScalaJSDefined
class Database(db: DB) extends js.Object {
  def parse(query: String) = {
    QueryParser.parse(query, db)
  }
} 
Example 18
Source File: JSLauncher.scala    From udash-demos   with GNU General Public License v3.0 5 votes vote down vote up
package io.udash.todo

import io.udash.logging.CrossLogging
import io.udash.wrappers.jquery._
import org.scalajs.dom.Element

import scala.scalajs.js.annotation.JSExport

object JSLauncher extends CrossLogging {
  import ApplicationContext._

  @JSExport
  def main(args: Array[String]): Unit = {
    jQ((_: Element) => {
      jQ(".todoapp").get(0) match {
        case None =>
          logger.error("Application root element not found! Check your index.html file!")
        case Some(root) =>
          applicationInstance.run(root)
      }
    })
  }
} 
Example 19
Source File: SjsonnetMain.scala    From sjsonnet   with Apache License 2.0 5 votes vote down vote up
package sjsonnet

import scala.collection.mutable
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

@JSExportTopLevel("SjsonnetMain")
object SjsonnetMain {
  def createParseCache() = collection.mutable.Map[String, fastparse.Parsed[(Expr, Map[String, Int])]]()
  @JSExport
  def interpret(text: String,
                extVars: js.Any,
                tlaVars: js.Any,
                wd0: String,
                importer: js.Function2[String, String, js.Array[String]],
                preserveOrder: Boolean = false): js.Any = {
    val interp = new Interpreter(
      mutable.Map.empty,
      ujson.WebJson.transform(extVars, ujson.Value).obj.toMap,
      ujson.WebJson.transform(tlaVars, ujson.Value).obj.toMap,
      JsVirtualPath(wd0),
      importer = (wd, path) => {
        importer(wd.asInstanceOf[JsVirtualPath].path, path) match{
          case null => None
          case arr => Some((JsVirtualPath(arr(0)), arr(1)))
        }
      },
      preserveOrder
    )
    interp.interpret0(text, JsVirtualPath("(memory)"), ujson.WebJson.Builder) match{
      case Left(msg) => throw new js.JavaScriptException(msg)
      case Right(v) => v
    }
  }
}


case class JsVirtualPath(path: String) extends Path{
  def relativeToString(p: Path): String = p match{
    case other: JsVirtualPath if path.startsWith(other.path) => path.drop(other.path.length)
    case _ => path
  }

  def debugRead(): Option[String] = None

  def parent(): Path = JsVirtualPath(path.split('/').dropRight(1).mkString("/"))

  def segmentCount(): Int = path.split('/').length

  def last: String = path.split('/').last

  def /(s: String): Path = JsVirtualPath(path + "/" + s)
} 
Example 20
Source File: DirectiveTests.scala    From angulate2   with MIT License 5 votes vote down vote up
//     Project: angulate2 (https://github.com/jokade/angulate2)
// Description: Test cases for @Directive

// Copyright (c) 2015 Johannes.Kastner <[email protected]>
//               Distributed under the MIT License (see included LICENSE file)
package angulate2.test.directive

import angulate2._
import angulate2.core.Component
import angulate2.test.TestBase

import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport

object DirectiveTests extends TestBase {

  var data: Any = null

  ng.register[DirTest1]
  ng.register[Directive1]
  ng.register[DirTest2]
  ng.register[Directive2]

  val tests = TestSuite {
    data = null

    'simple-{
      withHtml("""<dirtest1 id="dir1"></dirtest1>""") {
        ng.bootstrapWith[DirTest1]
        invokeLater( assert( data == "dir1" ) )
      }
    }

  }
}

@JSExport
class TestService {

}

@Component(
  selector = "dirtest1",
  template = "<div directive1></div>",
  directives = js.Array( @@[Directive1] )
)
class DirTest1

@Directive(
  selector = "[directive1]"
)
class Directive1 {
  DirectiveTests.data = "dir1"
}


@Component(
  selector = "dirtest2",
  template = "<div directive2></div>",
  appInjector = js.Array( @@[TestService] ),
  directives = js.Array( @@[Directive2] )
)
class DirTest2

@Directive(
  selector = "[directive2]"
)
class Directive2(ts: TestService) {
  DirectiveTests.data = ts
} 
Example 21
Source File: AngulateRuntime.scala    From angulate2   with MIT License 5 votes vote down vote up
//     Project: angulate2 (https://github.com/jokade/angulate2)
// Description:

// Copyright (c) 2017 Johannes.Kastner <[email protected]>
//               Distributed under the MIT License (see included LICENSE file)
package angulate2.ext.rt

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel, ScalaJSDefined}

@ScalaJSDefined
trait AngulateRuntime extends js.Object {
  
//@JSExportTopLevel("AngulateRuntimeSJSXConfig")
@JSExport
object AngulateRuntimeSJSXConfig {
  @JSExport
  var decorate: js.UndefOr[js.Function2[js.Array[js.Any],js.Any,js.Any]] = js.undefined

//  @JSExport
//  var require: js.UndefOr[js.Function1[String,js.Any]] = js.undefined
} 
Example 22
Source File: JSLogger.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.log

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


@JSExportTopLevel("log")
object JSLogger {
  @JSExport
  def setDefaultLogLevel(level: String): Boolean = {
    Logger.setDefaultLogLevel(LogLevel(level))
    true
  }

  @JSExport
  def setLogLevel(loggerName: String, level: String): Boolean = {
    Logger(loggerName).setLogLevel(LogLevel(level))
    true
  }
} 
Example 23
Source File: MainJs.scala    From kaitai_struct_compiler   with GNU General Public License v3.0 5 votes vote down vote up
package io.kaitai.struct

import io.kaitai.struct.format.{JavaScriptKSYParser, KSVersion}
import io.kaitai.struct.languages.components.LanguageCompilerStatic

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.annotation.JSExport

@JSExport
object MainJs {
  KSVersion.current = Version.version

  @JSExport
  def compile(langStr: String, yaml: js.Object, importer: JavaScriptImporter, debug: Boolean = false): js.Promise[js.Dictionary[String]] = {
    try {
      // TODO: add proper enabled by a flag
      //Log.initFromVerboseFlag(Seq("file", "value", "parent", "type_resolve", "type_valid", "seq_sizes", "import"))
      val config = new RuntimeConfig(autoRead = !debug, readStoresPos = debug)
      val lang = LanguageCompilerStatic.byString(langStr)

      JavaScriptKSYParser.yamlToSpecs(yaml, importer, config).map { (specs) =>
        specs.flatMap({ case (_, spec) =>
          val files = Main.compile(specs, spec, lang, config).files
          files.map((x) => x.fileName -> x.contents).toMap
        }).toJSDictionary
      }.toJSPromise
    } catch {
      case err: Throwable => Future { throw err }.toJSPromise
    }
  }

  @JSExport
  lazy val languages: js.Array[String] = LanguageCompilerStatic.NAME_TO_CLASS.keys.toSeq.sorted.toJSArray

  @JSExport
  lazy val version = Version.version

  @JSExport
  lazy val buildDate = Version.gitTime
} 
Example 24
Source File: LedgerConfigurationConsoleInterface.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package co.ledger.manager.web.cli

import co.ledger.manager.web.core.utils.ChromeGlobalPreferences

import scala.scalajs.js.UndefOr
import scala.scalajs.js.annotation.JSExport


trait LedgerConfigurationConsoleInterface extends BaseConsoleInterface {
  private val preferences = new ChromeGlobalPreferences("ledger.manager.config")

  private var _factoryMode = preferences.boolean("factory_mode").getOrElse(false)
  @JSExport
  def enableFactoryMode() = {
    _factoryMode = true
    preferences.edit().putBoolean("factory_mode", _factoryMode).commit()
    reloadRoute()
  }
  @JSExport
  def disableFactoryMode() = {
    _factoryMode = false
    preferences.edit().putBoolean("factory_mode", _factoryMode).commit()
    reloadRoute()
  }
  def isInFactoryMode = _factoryMode


  private var _defaultProvider: Option[String] = preferences.string("default_provider")
  @JSExport
  def setDefaultProvider(provider: UndefOr[String]) = {
    _defaultProvider = provider.toOption
    if (_defaultProvider.isDefined && _defaultProvider.get.nonEmpty) {
      preferences.edit().putString("default_provider", _defaultProvider.get).commit()
    } else {
      preferences.edit().remove("default_provider").commit()
    }
  }
  @JSExport
  def getDefaultProvider(): UndefOr[String] = UndefOr.any2undefOrA[String](_defaultProvider.orNull)
  def defaultProvider = _defaultProvider


  var SELECTED_APPS = preferences.string("selected_app").map(_.split(",")).getOrElse(Array.empty[String])
  def saveSelectedApps(): Unit = {
    preferences.edit().putString("selected_app", SELECTED_APPS.mkString(",")).commit()
  }
} 
Example 25
Source File: init.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.web.homepage

import io.udash._
import io.udash.logging.CrossLogging
import io.udash.routing.WindowUrlPathChangeProvider
import io.udash.wrappers.jquery._
import org.scalajs.dom.Element

import scala.scalajs.js.annotation.JSExport

object Context {
  implicit val executionContext = scalajs.concurrent.JSExecutionContext.Implicits.queue
  private val routingRegistry = new RoutingRegistryDef
  private val viewFactoriesRegistry = new StatesToViewFactoryDef

  implicit val applicationInstance = new Application[RoutingState](routingRegistry, viewFactoriesRegistry, new WindowUrlPathChangeProvider)
}

object Init extends CrossLogging {
  import Context._

  @JSExport
  def main(args: Array[String]): Unit = {
    jQ((_: Element) => {
      val appRoot = jQ("#application").get(0)
      if (appRoot.isEmpty) {
        logger.error("Application root element not found! Check you index.html file!")
      } else applicationInstance.run(appRoot.get)
    })
  }
} 
Example 26
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 27
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 28
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 29
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 30
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 31
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 32
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 33
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

}