scala.scalajs.js.Date Scala Examples

The following examples show how to use scala.scalajs.js.Date. 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: BlockView.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.app.views

import com.thoughtworks.binding
import com.thoughtworks.binding.Binding
import com.thoughtworks.binding.Binding.Var
import jbok.app.AppState
import jbok.app.components.{TabPane, Tabs}
import jbok.core.api.HistoryTransaction
import jbok.core.models._
import org.scalajs.dom._
import scodec.bits.ByteVector

import scala.scalajs.js.Date

final case class BlockView(state: AppState, block: Block) {
  val stxs: Var[List[HistoryTransaction]] = Var(List.empty)
  val stxsView                            = StxsView(state, stxs)

  private def fetch() = {
    val nodeId = state.activeNode.value.getOrElse("")
    val client = state.clients.value.get(nodeId)
    client.foreach { jbokClient =>
      val p = for {
        txs <- jbokClient.account.getTransactionsByNumber(block.header.number.toInt)
        _ = stxs.value = txs
      } yield ()

      p.unsafeToFuture()
    }
  }

  fetch()

  @binding.dom
  val overview: Binding[Element] =
    <div>
      <table class="table-view"> {
      val header = block.header
      val size   = block.body.transactionList.size
      <tr>
          <th>Height:</th>
          <td>{header.number.toString}</td>
        </tr>
        <tr>
          <th>TimeStamp:</th>
          <td>{new Date(header.unixTimestamp).toDateString()}</td>
        </tr>
        <tr>
          <th>Transactions:</th>
          <td>{s"${size.toLong} transactions in this Block"}</td>
        </tr>
        <tr>
          <th>This Block Hash:</th>
          <td>{header.hash.toHex}</td>
        </tr>
        <tr>
          <th>Parent Hash:</th>
          <td><a onclick={(e: Event) => state.searchBlockHash(header.parentHash.toHex)}>{header.parentHash.toHex}</a></td>
        </tr>
        <tr>
          <th>Mined By:</th>
          <td>{header.beneficiary.toHex}</td>
        </tr>
        <tr>
          <th>Difficulty:</th>
          <td>{header.difficulty.toString}</td>
        </tr>
        <tr>
          <th>Gas Used:</th>
          <td>{header.gasUsed.toString}</td>
        </tr>
        <tr>
          <th>Gas Limit:</th>
          <td>{header.gasLimit.toString}</td>
        </tr>
        <tr>
          <th>Extra Data:</th>
          <td>{header.extra.bytes.toHex}</td>
        </tr>
    }
      </table>
    </div>

  @binding.dom
  val txsView: Binding[Element] =
    <div>
      {stxsView.render.bind}
    </div>

  val tabView = Tabs(
    List(TabPane("Overview", overview), TabPane("Transactions", txsView)),
    className = "tab-small"
  )

  @binding.dom
  def render: Binding[Element] =
    <div>
      {tabView.render.bind}
    </div>
} 
Example 2
Source File: PrettyEnrichedTruckAndTrafficDataFactory.scala    From trucking-iot   with Apache License 2.0 5 votes vote down vote up
package com.orendainx.trucking.webapplication.models

import scala.scalajs.js.Date



object PrettyEnrichedTruckAndTrafficDataFactory {
  def apply(str: String): PrettyEnrichedTruckAndTrafficData = {
    // Parse message string and generate pretty versions of fields
    // TODO: DecimalFormat available in next version of scalajs
    val Array(eventTime, truckId, driverId, driverName, routeId, routeName, latitude, longitude, speed, eventType,
      foggy, rainy, windy, congestionLevel) = str.split("\\|")
    val prettyEventTime = new Date(eventTime.toLong).toLocaleTimeString()
    val prettyLatitude = (math.floor(latitude.toDouble * 100)/100).toString
    val prettyLongitude = (math.floor(longitude.toDouble * 100)/100).toString

    PrettyEnrichedTruckAndTrafficData(eventTime.toLong, truckId.toInt, driverId.toInt, driverName, routeId.toInt, routeName,
      latitude.toDouble, longitude.toDouble, speed.toInt, eventType, foggy.toInt, rainy.toInt, windy.toInt,
      congestionLevel.toInt, prettyEventTime, prettyLatitude, prettyLongitude)
  }
} 
Example 3
Source File: PrettyTruckAndTrafficDataFactory.scala    From trucking-iot   with Apache License 2.0 5 votes vote down vote up
package com.orendainx.trucking.webapplication.models

import scala.scalajs.js.Date



object PrettyTruckAndTrafficDataFactory {
  def apply(str: String): PrettyTruckAndTrafficData = {
    // Parse message string and generate pretty versions of fields
    // TODO: DecimalFormat available in next version of scalajs
    val Array(eventTime, truckId, driverId, driverName, routeId, routeName, latitude, longitude, speed, eventType, congestionLevel) = str.split("\\|")
    val prettyEventTime = new Date(eventTime.toLong).toLocaleTimeString()
    val prettyLatitude = (math.floor(latitude.toDouble * 100)/100).toString
    val prettyLongitude = (math.floor(longitude.toDouble * 100)/100).toString

    PrettyTruckAndTrafficData(eventTime.toLong, truckId.toInt, driverId.toInt, driverName, routeId.toInt, routeName,
      latitude.toDouble, longitude.toDouble, speed.toInt, eventType, congestionLevel.toInt,
      prettyEventTime, prettyLatitude, prettyLongitude)
  }
} 
Example 4
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 5
Source File: JsDateInstance.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.lib.js

import cats.syntax.either._

import cron4s.CronField
import cron4s.datetime.{DateTimeError, DateTimeUnit, InvalidFieldValue, IsDateTime}

import scala.scalajs.js.Date


private[js] final class JsDateInstance extends IsDateTime[Date] {
  import CronField._
  import DateTimeUnit._

  val DaysInWeek = 7

  @inline
  override def supportedFields(dateTime: Date): List[CronField] = CronField.All

  override def plus(
      dateTime: Date,
      amount: Int,
      unit: DateTimeUnit
  ): Option[Date] = {
    def setter(set: Date => Unit): Date = {
      val newDateTime = new Date(dateTime.getTime())
      set(newDateTime)
      newDateTime
    }

    unit match {
      case Seconds =>
        Some(setter(d => d.setUTCSeconds(d.getUTCSeconds() + amount)))
      case Minutes =>
        Some(setter(d => d.setUTCMinutes(d.getUTCMinutes() + amount)))
      case Hours  => Some(setter(d => d.setUTCHours(d.getUTCHours() + amount)))
      case Days   => Some(setter(d => d.setUTCDate(d.getUTCDate() + amount)))
      case Months => Some(setter(d => d.setUTCMonth(d.getUTCMonth() + amount)))
      case Weeks =>
        Some(setter(d => d.setUTCDate(d.getUTCDate() + (amount * DaysInWeek))))
    }
  }

  override def get[F <: CronField](dateTime: Date, field: F): Either[DateTimeError, Int] = {
    val value = field match {
      case Second     => dateTime.getUTCSeconds()
      case Minute     => dateTime.getUTCMinutes()
      case Hour       => dateTime.getUTCHours()
      case DayOfMonth => dateTime.getUTCDate()
      case Month      => dateTime.getUTCMonth() + 1
      case DayOfWeek =>
        val dayOfWeek = {
          val idx = dateTime.getUTCDay() - 1
          if (idx < 0) DaysInWeek + idx
          else idx
        }
        dayOfWeek
    }

    Right(value)
  }

  override def set[F <: CronField](
      dateTime: Date,
      field: F,
      value: Int
  ): Either[DateTimeError, Date] = {
    def setter(setter: Date => Unit): Date = {
      val newDateTime = new Date(dateTime.getTime())
      setter(newDateTime)
      newDateTime
    }

    def assignFieldValue: Date = field match {
      case Second     => setter(_.setUTCSeconds(value, 0))
      case Minute     => setter(_.setUTCMinutes(value))
      case Hour       => setter(_.setUTCHours(value))
      case DayOfMonth => setter(_.setUTCDate(value))
      case Month =>
        val monthToSet = value - 1
        setter(_.setUTCMonth(monthToSet))
      case DayOfWeek =>
        val dayToSet = (value % DaysInWeek) + 1
        val offset   = dayToSet - dateTime.getUTCDay()
        setter(d => d.setUTCDate(d.getUTCDate() + offset))
    }

    def assignmentSucceeded(date: Date) =
      get[F](date, field).toOption.contains(value)

    val modifiedDate = assignFieldValue
    if (assignmentSucceeded(modifiedDate)) Right(modifiedDate)
    else Left(InvalidFieldValue(field, value))
  }
} 
Example 6
Source File: package.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.lib

import cats.{Eq, Show}

import cron4s.datetime.IsDateTime

import scala.scalajs.js.Date


package object js {
  implicit val jsDateEq: Eq[Date] = Eq.instance { (lhs, rhs) =>
    lhs.getUTCFullYear() == rhs.getUTCFullYear() &&
    lhs.getUTCMonth() == rhs.getUTCMonth() &&
    lhs.getUTCDate() == rhs.getUTCDate() &&
    lhs.getUTCHours() == rhs.getUTCHours() &&
    lhs.getUTCMinutes() == rhs.getUTCMinutes() &&
    lhs.getUTCSeconds() == rhs.getUTCSeconds() &&
    lhs.getUTCMilliseconds() == rhs.getUTCMilliseconds()
  }

  implicit val jsDateShow: Show[Date] =
    Show.show(_.toUTCString())

  implicit val jsDateInstance: IsDateTime[Date] = new JsDateInstance
} 
Example 7
Source File: JSTestBase.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s.lib.js

import cron4s.testkit.DateTimeTestKitBase

import scala.scalajs.js.Date


trait JSTestBase extends DateTimeTestKitBase[Date] {
  protected def createDateTime(
      seconds: Int,
      minutes: Int,
      hours: Int,
      dayOfMonth: Int,
      month: Int,
      year: Int
  ): Date =
    new Date(Date.UTC(year, month - 1, dayOfMonth, hours, minutes, seconds, ms = 0))
} 
Example 8
Source File: AppUtils.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package client.utils

import java.util.UUID

import client.handler.AcceptNotification
import client.logger
import client.modules.AppModule
import client.services.{ApiTypes, LGCircuit}
import shared.dtos.{Connection, Expression, ExpressionContent, SubscribeRequest}
import shared.models._

import scala.scalajs.js.Date
import shared.dtos.{ApiResponse, ConnectionProfileResponse, Introduction}
import shared.models.ConnectionsModel
import client.handler._
import client.logger._
import client.services.LGCircuit
import diode.AnyAction._



object AppUtils {
  val MESSAGE_POST_LABEL = "MESSAGEPOSTLABEL"
  val PROJECT_POST_LABEL = "PROJECTPOSTLABEL"
  val PROFILE_POST_LABEL = "PROFILESPOSTLABEL"

  def getSessionUri (viewName: String): String = {
    viewName match {
      case AppModule.MESSAGES_VIEW => LGCircuit.zoom(_.session.messagesSessionUri).value
      case AppModule.PROFILES_VIEW => LGCircuit.zoom(_.session.profileSessionUri).value
      case AppModule.PROJECTS_VIEW => LGCircuit.zoom(_.session.projectSessionUri).value
    }
  }

  def getContentToPost(postContent: PostContent, cnxns: Seq[Connection], uid:String, viewName: String): String = {
    viewName match {
      case AppModule.MESSAGES_VIEW => upickle.default.write(MessagePost(uid, new Date().toISOString(), new Date().toISOString(), "", cnxns, postContent.asInstanceOf[MessagePostContent]))
      case AppModule.PROFILES_VIEW => upickle.default.write(ProfilesPost(uid, new Date().toISOString(), new Date().toISOString(), "", cnxns, postContent.asInstanceOf[ProfilePostContent]))
      case AppModule.PROJECTS_VIEW => upickle.default.write(ProjectsPost(uid, new Date().toISOString(), new Date().toISOString(), "", cnxns, postContent.asInstanceOf[ProjectPostContent]))

    }

  }

  def getPostData(postContent: PostContent, cnxns: Seq[Connection], labels: Seq[Label], viewName: String): SubscribeRequest = {
    val uid = UUID.randomUUID().toString.replaceAll("-", "")
    val labelToPost = Seq(LabelsUtils.getSystemLabelModel(viewName)) ++ labels
    val contentToPost = getContentToPost(postContent, cnxns,uid,viewName)
    val prolog = LabelsUtils.buildProlog(labelToPost, LabelsUtils.PrologTypes.Each)
    logger.log.debug(s"prolog = $prolog")
    SubscribeRequest(AppUtils.getSessionUri(viewName),
      Expression(ApiTypes.requestTypes.INSERT_CONTENT,
        ExpressionContent(cnxns, prolog, contentToPost, uid)))
  }

    def handleInitialSessionPingRes(response: String): Unit = {
      var cnxnSeq: Seq[ConnectionsModel] = Nil
      var introSeq: Seq[Introduction] = Nil
      val responseArray = upickle.json.read(response)
      responseArray.arr.foreach {
        obj =>
          try {
            val jsonObj = upickle.json.write(obj)
            if(jsonObj.contains("connectionProfileResponse")) {
              val apiRes = upickle.default.read[ApiResponse[ConnectionProfileResponse]](upickle.json.write(obj))
              cnxnSeq :+= ConnectionsUtils.getCnxnFromRes(apiRes.content)
            }
            if (jsonObj.contains("introductionNotification")) {
              val apiRes = upickle.default.read[ApiResponse[Introduction]](upickle.json.write(obj))
              introSeq :+= apiRes.content
            }

          } catch {
            case e: Exception =>
              logger.log.error(e.toString)

          }
      }
      LGCircuit.dispatch(UpdateConnections(cnxnSeq))
      LGCircuit.dispatch(AcceptNotification(introSeq))

  }



} 
Example 9
Source File: MessagesUtils.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package synereo.client.utils

import java.util.UUID

import shared.dtos.{Connection, Expression, ExpressionContent, SubscribeRequest}
import shared.models.{Label, MessagePost, MessagePostContent, PostContent}
import synereo.client.services.{ApiTypes, SYNEREOCircuit}

import scala.scalajs.js.Date


  def getPostData(postContent: PostContent, cnxns: Seq[Connection], labels: Seq[Label]): SubscribeRequest = {
    val uid = UUID.randomUUID().toString.replaceAll("-", "")
    val labelToPost = Seq(LabelsUtils.getLabelModel(AppUtils.MESSAGE_POST_LABEL)) ++ labels
    val contentToPost = upickle.default.write(MessagePost(uid, new Date().toISOString(),
      new Date().toISOString(), "", cnxns, postContent.asInstanceOf[MessagePostContent]))
    val prolog = LabelsUtils.buildProlog(labelToPost, LabelsUtils.PrologTypes.Each)
    // logger.log.debug(s"prolog = $prolog")
    SubscribeRequest(SYNEREOCircuit.zoom(_.sessionRootModel.sessionUri).value,
      Expression(ApiTypes.requestTypes.INSERT_CONTENT,
        ExpressionContent(cnxns, prolog, contentToPost, uid)))
  }
} 
Example 10
Source File: ActorRepository.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.frontend

import rx.Var

import scala.scalajs.js
import scala.scalajs.js.Date

class ActorRepository {

  import ActorRepository._

  private[this] val currentActorState = js.Dictionary[Var[ActorState]]()

  //TODO: make it visible on the outside as Rx[Set[String]] just in case
  val newActors = Var[Set[String]](Set())
  val seenActors = Var[Set[String]](Set())

  def state(actor: String): Var[ActorState] = currentActorState.getOrElseUpdate(
    actor,
    Var(ActorState(actor, FrontendUtil.shortActorName(actor), FrontendUtil.systemName(actor)))
  )

  def mutateActor(actor: String)(fn: ActorState => ActorState) = {
    state(actor)() = fn(state(actor).now.copy(lastUpdatedAt = new js.Date()))
    addActorsToSeen(actor)
  }

  @inline
  final def addActorsToSeen(actors: String*): Unit = {
    addActorsToSeen(actors)
  }

  def addActorsToSeen(actors: Iterable[String]): Unit = {
    val previouslySeen = seenActors.now
    val newSeen = previouslySeen ++ actors
    if (previouslySeen.size != newSeen.size) {
      newActors() = newSeen -- previouslySeen
      seenActors() = newSeen
    }
  }

}

case object ActorRepository {

  case class FSMState(currentState: String, currentData: String)

  case class ActorState(
    path: String,
    label: String,
    system: String,
    isDead: Boolean = false,
    mailboxSize: js.UndefOr[Int] = js.undefined,
    internalState: js.UndefOr[String] = js.undefined,
    className: js.UndefOr[String] = js.undefined,
    fsmState: js.UndefOr[FSMState] = js.undefined,
    fsmTransitions: Set[(String, String)] = Set(),
    lastUpdatedAt: js.Date = new Date()
  )

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

import scala.scalajs.js
import scala.scalajs.js.Date

class JavaScriptCrossDate(val date: Date) extends AnyVal with CrossDate {
  override def milliseconds: Long = date.getTime().toLong
  override def hour24: Int = date.getHours().toInt
  override def minuteOfHour: Int = date.getMinutes().toInt
  override def secondOfMinute: Int = date.getSeconds().toInt
  override def milliOfSecond: Int = date.getMilliseconds().toInt
  override def isAM: Boolean = hour24 < 12
  override def timeZoneOffsetMillis: Int = (-date.getTimezoneOffset() * 60 * 1000).toInt
  override def year: Int = date.getFullYear().toInt
  override def month: Int = date.getMonth().toInt
  override def dayOfWeek: Int = date.getDay().toInt + 1
  override def dayOfMonth: Int = date.getDate().toInt
  override def dayOfYear: Int = {
    val beginning = new Date(date.getFullYear().toInt, 0, 0)
    val diff = date.getTime() - beginning.getTime()
    val oneDay = 1000.0 * 60.0 * 60.0 * 24.0
    math.floor(diff / oneDay).toInt - 1
  }
  override def timeZone: String = {
    val s = date.asInstanceOf[js.Dynamic].toLocaleString("en", js.Dynamic.literal("timeZoneName" -> "short")).asInstanceOf[String]
    s.split(' ').last
  }
}