本文整理汇总了Scala中scala.scalajs.js类的典型用法代码示例。如果您正苦于以下问题:Scala js类的具体用法?Scala js怎么用?Scala js使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了js类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DocumentTest
//设置package包名称以及导入依赖的类
package ch.epfl.callgraph.visualization
import ch.epfl.callgraph.utils.Utils.CallGraph
import ch.epfl.callgraph.visualization.view.{D3GraphView, HtmlView}
import org.junit.Assert._
import org.junit.{Before, Test}
import org.scalajs.dom.html._
import org.scalajs.{dom => sdom}
import upickle.{default => upickle}
import scala.scalajs
import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
class DocumentTest {
val $ = global.jQuery
@Before
def setupDocument() : Unit = {
$("body").html("")
$("body")
.append(
global.jQuery("<div id=\"header\"><h1>Scala.js Call Graph Visualization</h1></div>" +
"<div id=\"nav\" style=\"overflow:auto\"></div>" +
"<div id=\"main\" style=\"overflow:auto\"></div>"))
HtmlView.main() // setup the file upload button
D3GraphView.setCallGraph(upickle.read[CallGraph](generateGraph))
HtmlView.updateHtmlAfterLoad(sdom.document.getElementById("nav").asInstanceOf[Div])
D3GraphView.renderGraph()
}
def generateGraph = {
"""{"classes":[{"encodedName":"s_Predef$Triple$2","displayName":"scala.Predef$Triple$2","isExported":true,"superClass":[],"interfaces":[],"methods":[]}]}"""
}
@Test def testInitialDOM(): Unit = {
assertEquals(1, $("#header").length)
assertEquals(1, $("#nav").length)
assertEquals(1, $("#main").length)
}
@Test def testInitialLayer : Unit = {
HtmlView.showLayers
assertEquals(1, $("li > a.active").length)
}
@Test def testSvgSingleNode : Unit = {
println($("svg").html())
$("svg").find("circle").each({(li: Html) => {
println($(li).attr("class"))
// $(li).contextmenu()
}}: scalajs.js.ThisFunction)
assertEquals(1, $("svg").find("circle").length)
}
}
示例2: UserAgentService
//设置package包名称以及导入依赖的类
package org.danielnixon.progressive.services
import org.danielnixon.progressive.shared.Wart
import org.scalajs.dom.Window
import org.danielnixon.saferdom.implicits._
import scala.scalajs.js
class UserAgentService(window: Window) {
val isTouchDevice: Boolean = window.document.documentElementOpt.exists(d => isDefined(d, "ontouchstart"))
val meetsRequirements: Boolean = {
isDefined(window, "WeakMap") &&
isDefined(window, "history") &&
isDefined(window.history, "pushState") &&
isDefined(window.document, "querySelector") &&
window.document.bodyOpt.exists(b => isDefined(b, "matches")) &&
window.document.bodyOpt.exists(b => isDefined(b, "closest"))
}
@SuppressWarnings(Array(Wart.AsInstanceOf))
private def isDefined(obj: js.Object, prop: String): Boolean = {
!js.isUndefined(obj.asInstanceOf[js.Dynamic].selectDynamic(prop))
}
}
示例3: VariantBrowser
//设置package包名称以及导入依赖的类
package variantBrowser
import org.scalajs.dom
import variantBrowser.components.VariantBrowserClient
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
import japgolly.scalajs.react.extra.router.StaticDsl.Route
import japgolly.scalajs.react.{Callback, ReactDOM}
import japgolly.scalajs.react.extra.router._
@JSExport
object VariantBrowser extends js.JSApp{
val baseUrl = BaseUrl("http://bioinfo01-ingemm.salud.madrid.org:9000")
// Define the locations (pages) used in this application
sealed trait Loc
case class Home() extends Loc
val routerConfig = RouterConfigDsl[Loc].buildConfig { dsl =>
import dsl._
( emptyRule
| dynamicRouteCT( ("/").caseClass[Home] ) ~> dynRenderR( (page,ctl) => VariantBrowserClient(ctl, page))
).notFound(redirectToPath(root)(Redirect.Replace))
}
@JSExport
def main() : Unit = {
dom.console.info(s"Initializing scalajs VariantBrowser lab")
val router = Router( baseUrl, routerConfig.logToConsole)
ReactDOM.render( router(), dom.document.getElementById("wrapper"))
}
}
示例4: identify
//设置package包名称以及导入依赖的类
package slate
import monix.eval.Task
import monix.execution.Cancelable
import slate.chrome._
import scala.scalajs.js
import scala.scalajs.js.UndefOr
object identify {
def chromeCallbackToTask[T](callbackTaker: (T => Unit) => Unit): Task[T] = {
Task.create[T] { (_, callback) =>
callbackTaker { result =>
ChromeRuntime.lastError.fold(callback.onSuccess(result)) { ex =>
callback.onError(ChromeErrorException(ex.message))
}
}
Cancelable.empty
}
}
def getAuthToken(interactive: Boolean = false, accountInfo: UndefOr[String] = js.undefined, scopes: UndefOr[js.Array[String]] = js.undefined): Task[String] =
chromeCallbackToTask(ChromeIdentity.fetchAuthToken(new GetAuthTokenOptions(interactive, accountInfo.map(new AccountInfo(_)), scopes), _))
def launchWebAuthFlow(interactive: Boolean = false, url: String): Task[String] =
chromeCallbackToTask(ChromeIdentity.launchWebAuthFlow(new LaunchWebAuthFlowOptions(url, interactive), _))
def removeCachedAuthToken(token: String): Task[Unit] =
chromeCallbackToTask(ChromeIdentity.removeCachedAuthToken(new RemoveCachedAuthTokenOptions(token), _))
case class ChromeErrorException(message: UndefOr[String]) extends Exception(message.getOrElse("No error message"))
}
示例5: DatedAppContent
//设置package包名称以及导入依赖的类
package slate
package models
import upickle.Js
import scala.scalajs.js
case class DatedAppContent(content: List[ExpandableContentModel], date: js.Date)
object DatedAppContent {
implicit val pkl: upickle.default.Reader[DatedAppContent] with upickle.default.Writer[DatedAppContent] =
new upickle.default.Reader[DatedAppContent] with upickle.default.Writer[DatedAppContent] {
override def read0: PartialFunction[Js.Value, DatedAppContent] = Function.unlift[Js.Value, DatedAppContent] {
case Js.Obj([email protected]_*) =>
for {
content <- values.find(_._1 == "content").flatMap(t => ExpandableContentModel.pkls.read.lift(t._2))
date <- values.find(_._1 == "date").flatMap {
case (_, Js.Num(n)) => Some(new js.Date(n))
case _ => None
}
} yield DatedAppContent(content, date)
case _ => None
}
override def write0: DatedAppContent => Js.Value = { m =>
Js.Obj("date" -> Js.Num(m.date.getTime()), "content" -> ExpandableContentModel.pkls.write(m.content))
}
}
}
示例6: LZString
//设置package包名称以及导入依赖的类
package slate.bindings
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
import scala.scalajs.js.typedarray.Uint8Array
@js.native
@JSName("LZString")
object LZString extends js.Any {
@js.native
def compressToUint8Array(str: String): Uint8Array = js.native
@js.native
def decompressFromUint8Array(buf: Uint8Array): String = js.native
@js.native
def compressToUTF16(str: String): String = js.native
@js.native
def decompressFromUTF16(str: String): String = js.native
@js.native
def compress(str: String): String = js.native
@js.native
def decompress(str: String): String = js.native
}
示例7: Application
//设置package包名称以及导入依赖的类
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)
}
}
示例8: now
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client.util
import java.util.Date
import scala.scalajs.js
package time {
trait Clock { def now(): Date }
object SystemClock extends Clock { def now(): Date = new Date() }
case class Duration(milliseconds: Long) extends AnyVal
object Duration {
def seconds(s: Long): Duration = Duration(s * 1000)
def minutes(m: Long): Duration = Duration(m * 60 * 1000)
def hours(h: Long): Duration = Duration(h * 3600 * 1000)
def days(d: Long): Duration = Duration(d * 24 * 3600 * 1000)
}
}
package object time {
val MomentShortLocale: js.Dictionary[js.Any] = js.Dictionary(
"parentLocale" -> "en",
"relativeTime" -> js.Dictionary(
"future" -> "in %s",
"past" -> "%s ago",
"s" -> "now",
"ss" -> "%ss",
"m" -> "1m",
"mm" -> "%dm",
"h" -> "1h",
"hh" -> "%dh",
"d" -> "1d",
"dd" -> "%dd",
"M" -> "1M",
"MM" -> "%dM",
"y" -> "1Y",
"yy" -> "%dY"
)
)
}
示例9: NotificationSound
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client
import org.scalajs.dom.raw.HTMLAudioElement
import scala.scalajs.js
package audio {
case class NotificationSound(id: NotificationSoundId, fileName: String) {
def play(): Unit = {
NotificationSounds.audioCache.getOrElseUpdate(fileName, {
js.Dynamic
.newInstance(js.Dynamic.global.Audio)(pathPrefix + fileName)
.asInstanceOf[HTMLAudioElement]
}).play()
}
}
}
package object audio {
type NotificationSoundId = Int
private[audio] val pathPrefix = "audio/"
object NotificationSounds {
// When adding new items, don't change the numeric IDs
val all: Seq[NotificationSound] = Seq(
1 -> "oh-finally.ogg",
2 -> "oringz-w425.ogg",
3 -> "pedantic.ogg",
4 -> "suppressed.ogg",
5 -> "system.ogg",
6 -> "tweet.ogg",
7 -> "you-wouldnt-believe.ogg",
8 -> "youve-been-informed.ogg"
).map { case (id, fileName) => NotificationSound(id, fileName) }.sortBy(_.fileName)
val findById: NotificationSoundId => Option[NotificationSound] =
all.map(n => n.id -> n).toMap.get _
private[audio] var audioCache: js.Dictionary[HTMLAudioElement] = js.Dictionary()
}
}
示例10: binding
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.client.views
import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding._
import org.scalajs.dom.raw._
import scala.scalajs.js
import walfie.gbf.raidfinder.client.syntax.HTMLElementOps
trait Notification {
def binding: Binding[Element]
def enqueue(message: String): Unit
}
class SnackbarNotification extends Notification {
@binding.dom
val binding: Binding[Element] = {
<div class="mdl-js-snackbar mdl-snackbar">
<div class="mdl-snackbar__text"></div>
<button class="mdl-snackbar__action" type="button"></button>
</div>
}.mdl
def enqueue(message: String): Unit = {
val data = js.Dictionary("message" -> message, "timeout" -> "1000")
Binding {
binding.bind.asInstanceOf[js.Dynamic].MaterialSnackbar.showSnackbar(data)
}
}
}
示例11: HTMLElementOps
//设置package包名称以及导入依赖的类
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
}
}
}
示例12: Moment
//设置package包名称以及导入依赖的类
package com.momentjs
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
@js.native
@JSName("moment")
object Moment extends js.Object {
def apply(millis: Double): Date = js.native
def locale(localeName: String): Unit = js.native
def defineLocale(localeName: String, settings: js.Dictionary[js.Any]): Unit = js.native
}
@js.native
trait Date extends js.Object {
def fromNow(): String = js.native
def fromNow(withoutSuffix: Boolean): String = js.native
def from(millis: Double, withoutSuffix: Boolean): String = js.native
def format(stringFormat: String): String = js.native
}
示例13: HttpConfig
//设置package包名称以及导入依赖的类
package io.scalajs.npm.angularjs.http
import scala.scalajs.js
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.|
@ScalaJSDefined
class HttpConfig(var method: js.UndefOr[String] = js.undefined,
var url: js.UndefOr[String] = js.undefined,
var params: js.UndefOr[js.Dictionary[js.Any]] = js.undefined,
var data: js.Any = js.undefined,
var headers: js.UndefOr[js.Dictionary[js.Any]] = js.undefined,
var xsrfHeaderName: js.UndefOr[String] = js.undefined,
var xsrfCookieName: js.UndefOr[String] = js.undefined,
var transformResponse: js.UndefOr[js.Array[js.Function]] = js.undefined,
// js.Function2[js.Any = js.undefined, js.Any, js.Any]
var transformRequest: js.UndefOr[js.Array[js.Function]] = js.undefined,
// js.Function2[js.Any, js.Any, js.Any]
var cache: js.Any = js.undefined,
var withCredentials: js.UndefOr[Boolean] = js.undefined,
var timeout: js.UndefOr[Int | Double] = js.undefined,
var responseType: js.UndefOr[String] = js.undefined)
extends js.Object
示例14: KaTex
//设置package包名称以及导入依赖的类
package codes.mark.geilematte.facades
import org.scalajs.dom
import scala.scalajs.js
import scala.scalajs.js.JavaScriptException
import scala.scalajs.js.annotation.JSName
@JSName("katex")
@js.native
object KaTex extends js.Object {
def render(latex: String, target: dom.Element, config:js.Object = new KaTexConfig(true)): Unit = js.native
}
@js.native
class KaTexConfig(var displayMode:Boolean) extends js.Object
object SafeKaTex {
def render(latex: String, target: dom.Element): Option[String] =
try {
KaTex.render(latex, target)
Option.empty
} catch {
case (e: JavaScriptException) =>
Option(e.getMessage)
}
}
示例15: Client
//设置package包名称以及导入依赖的类
package kartograffel.client
import eu.timepit.refined.api.RefType
import io.circe.syntax._
import kartograffel.shared.model.Position
import kartograffel.shared.model.Position.{Latitude, Longitude}
import org.scalajs.dom
import org.scalajs.dom.{window, Coordinates, PositionError, PositionOptions}
import org.scalajs.jquery.jQuery
import scala.scalajs.js
object Client {
def main(args: Array[String]): Unit = {
jQuery("body").append("<p>Hallo!</p>")
val opts = js.Object().asInstanceOf[PositionOptions]
opts.timeout = 50000
opts.enableHighAccuracy = true
window.navigator.geolocation.getCurrentPosition(
{ pos: dom.Position =>
val loc = locationFrom(pos.coords).get
println("Location" + locationFrom(pos.coords))
println(pos)
jQuery.post(url = "/api/post",
data = loc.asJson.spaces2,
success = null,
dataType = null)
}, { err: PositionError =>
println(err.code)
println(err.message)
},
opts
)
println("Hello, world!1111")
}
def locationFrom(coordinates: Coordinates): Option[Position] = {
val location = for {
latitude <- RefType.applyRef[Latitude](coordinates.latitude)
longitude <- RefType.applyRef[Longitude](coordinates.longitude)
} yield Position(latitude, longitude)
location.toOption
}
}