scala.scalajs.js.typedarray.ArrayBuffer Scala Examples

The following examples show how to use scala.scalajs.js.typedarray.ArrayBuffer. 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: 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 3
Source File: Converters.scala    From RosHTTP   with MIT License 5 votes vote down vote up
package fr.hmil.roshttp

import java.nio.ByteBuffer

import fr.hmil.roshttp.node.buffer.Buffer

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

private object Converters {
  def byteArrayToUint8Array(arr: Array[Byte]): Uint8Array = {
    js.Dynamic.newInstance(js.Dynamic.global.Uint8Array)(arr.toJSArray).asInstanceOf[Uint8Array]
  }

  def byteBufferToNodeBuffer(buffer: ByteBuffer): Buffer = {
    if (buffer.isDirect) {
      js.Dynamic.newInstance(js.Dynamic.global.Buffer)(buffer.arrayBuffer).asInstanceOf[Buffer]
    } else if (buffer.hasArray) {
      js.Dynamic.newInstance(js.Dynamic.global.Buffer)(byteArrayToUint8Array(buffer.array())).asInstanceOf[Buffer]
    } else {
      val arr = new Int8Array(buffer.limit())
      var i = 0
      while (i < arr.length) {
        arr(i) = buffer.get(i)
        i += 1
      }
      js.Dynamic.newInstance(js.Dynamic.global.Buffer)(arr).asInstanceOf[Buffer]
    }
  }

  def nodeBufferToByteBuffer(buffer: Buffer): ByteBuffer = {
    TypedArrayBuffer.wrap(buffer.asInstanceOf[ArrayBuffer])
  }

  def arrayBufferToByteBuffer(buffer: ArrayBuffer): ByteBuffer = {
    TypedArrayBuffer.wrap(buffer)
  }
} 
Example 4
Source File: Global.scala    From Waves   with MIT License 5 votes vote down vote up
package com.wavesplatform.lang.impl

import com.wavesplatform.lang.v1.evaluator.ctx.impl.crypto.RSA.DigestAlgorithm

import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobalScope
import scala.scalajs.js.typedarray.ArrayBuffer
import scala.scalajs.js.{Object, Promise, UndefOr, native}

@native
@JSGlobalScope
object Global extends Object {
  def base58Encode(input: ArrayBuffer): String          = native
  def base58Decode(input: String): UndefOr[ArrayBuffer] = native
  def base64Encode(input: ArrayBuffer): String          = native
  def base64Decode(input: String): UndefOr[ArrayBuffer] = native

  def curve25519verify(message: ArrayBuffer, sig: ArrayBuffer, pub: ArrayBuffer): Boolean                = native
  def rsaVerify(alg: DigestAlgorithm, message: ArrayBuffer, sig: ArrayBuffer, pub: ArrayBuffer): Boolean = native
  def keccak256(message: ArrayBuffer): ArrayBuffer                                                       = native
  def blake2b256(message: ArrayBuffer): ArrayBuffer                                                      = native
  def sha256(message: ArrayBuffer): ArrayBuffer                                                          = native
  def merkleVerify(root: ArrayBuffer, proof: ArrayBuffer, data: ArrayBuffer): Boolean                    = native

  def httpGet(params: js.Dynamic): Promise[js.Dynamic] = native
} 
Example 5
Source File: PakoSuite.scala    From metabrowse   with Apache License 2.0 5 votes vote down vote up
package metabrowse

import metabrowse.schema.Workspace
import org.scalatest.FunSuite
import scala.meta.internal.io.PathIO
import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.typedarray.ArrayBuffer
import scala.scalajs.js.typedarray.TypedArrayBuffer
import scala.scalajs.js.typedarray.Uint8Array

class PakoSuite extends FunSuite {
  test("deflate") {
    val path = PathIO.workingDirectory
      .resolve("target")
      .resolve("metabrowse")
      .resolve("index.workspace.gz")
    val in = path.readAllBytes
    val input = new ArrayBuffer(in.length)
    val bbuf = TypedArrayBuffer.wrap(input)
    bbuf.put(in)
    val output = Pako.inflate(input)
    val out = Array.ofDim[Byte](output.byteLength)
    TypedArrayBuffer.wrap(output).get(out)
    val workspace = Workspace.parseFrom(out)
    val obtained =
      workspace.toProtoString.linesIterator.toList.sorted.mkString("\n").trim
    val expected =
      """
        |filenames: "paiges/core/src/main/scala/org/typelevel/paiges/Chunk.scala"
        |filenames: "paiges/core/src/main/scala/org/typelevel/paiges/Doc.scala"
        |filenames: "paiges/core/src/main/scala/org/typelevel/paiges/Document.scala"
        |filenames: "paiges/core/src/main/scala/org/typelevel/paiges/package.scala"
        |filenames: "paiges/core/src/test/scala/org/typelevel/paiges/DocumentTests.scala"
        |filenames: "paiges/core/src/test/scala/org/typelevel/paiges/Generators.scala"
        |filenames: "paiges/core/src/test/scala/org/typelevel/paiges/JsonTest.scala"
        |filenames: "paiges/core/src/test/scala/org/typelevel/paiges/PaigesTest.scala"
      """.stripMargin.trim
    assert(obtained == expected)
  }
} 
Example 6
Source File: NativeUtils.scala    From akka-viz   with MIT License 5 votes vote down vote up
package akkaviz.frontend

import scala.scalajs.js
import scala.scalajs.js.typedarray.{ArrayBufferView, Uint8Array, ArrayBuffer}

object NativeUtils {

  val encoder = new TextEncoder("utf-8")
  val decoder = new TextDecoder("utf-8")

  def ab2str(ab: ArrayBuffer): String = {
    decoder.decode(new Uint8Array(ab))
  }

  def str2ab(str: String): Uint8Array = {
    encoder.encode(str)
  }

}

@js.native
class TextEncoder(utfLabel: js.UndefOr[String]) extends js.Object {
  def encode(buffer: String): Uint8Array = js.native
}

@js.native
class TextDecoder(utfLabel: js.UndefOr[String]) extends js.Object {
  def decode(buffer: Uint8Array): String = js.native
} 
Example 7
Source File: TCP.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.sockets.tcp.bindings

import chrome.events.bindings.Event

import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.typedarray.ArrayBuffer
import scala.scalajs.js.{UndefOr, native, undefined}

@js.native
@JSGlobal("chrome.sockets.tcp")
object TCP extends js.Object {

  val onReceive: Event[js.Function1[ReceiveEvent, _]] = native
  val onReceiveError: Event[js.Function1[ReceiveErrorEvent, _]] = native

  def create(properties: UndefOr[SocketProperties] = undefined,
             callback: js.Function1[CreateInfo, _]): Unit = native

  def update(socketId: SocketId,
             properties: SocketProperties,
             callback: UndefOr[js.Function0[_]] = undefined): Unit = native

  def setPaused(socketId: SocketId,
                paused: Boolean,
                callback: UndefOr[js.Function0[_]] = undefined): Unit = native

  def setKeepAlive(socketId: SocketId,
                   enable: Boolean,
                   delay: UndefOr[Int] = undefined,
                   callback: js.Function1[Int, _]): Unit = native

  def setNoDelay(socketId: SocketId,
                 noDelay: Boolean,
                 callback: js.Function1[Int, _]): Unit = native

  def connect(socketId: SocketId,
              peerAddress: String,
              peerPort: Int,
              callback: js.Function1[Int, _]): Unit = native

  def disconnect(socketId: SocketId,
                 callback: UndefOr[js.Function0[_]] = undefined): Unit = native

  def secure(socketId: SocketId,
             options: UndefOr[SecureOptions] = undefined,
             callback: js.Function0[_]): Unit = native

  def send(socketId: SocketId,
           data: ArrayBuffer,
           callback: js.Function1[SendInfo, _]): Unit = native

  def close(socketId: SocketId, callback: js.Function0[_]): Unit = native

  def getInfo(socketId: SocketId,
              callback: js.Function1[SocketInfo, _]): Unit = native

  def getSockets(callback: js.Function1[js.Array[SocketInfo], _]): Unit =
    native

} 
Example 8
Source File: Socket.scala    From scala-js-chrome   with MIT License 5 votes vote down vote up
package chrome.sockets.tcp

import chrome.events.EventSource
import chrome.sockets.tcp.bindings._

import scala.concurrent.Future
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.typedarray.ArrayBuffer

class Socket(val socketId: SocketId) {

  val onReceive = TCP.onReceive
    .filter(_.socketId == socketId)
    .map((event) => Socket.Received(event.data))
  val onReceiveError = TCP.onReceiveError
    .filter(_.socketId == socketId)
    .map((event) => Socket.Error(event.resultCode))
  val all: EventSource[Socket.ReceiveEvent] = onReceive.merge(onReceiveError)

  def update(properties: SocketProperties): Future[Unit] = {
    TCP.update(socketId, properties)
  }

  def setPaused(paused: Boolean): Future[Unit] = {
    TCP.setPaused(socketId, paused)
  }

  def setKeepAlive(enable: Boolean,
                   delay: js.UndefOr[Int] = js.undefined): Future[Int] = {
    TCP.setKeepAlive(socketId, enable, delay)
  }

  def setNoDelay(noDelay: Boolean): Future[Int] = {
    TCP.setNoDelay(socketId, noDelay)
  }

  def connect(peerAddress: String, peerPort: Int): Future[Int] = {
    TCP.connect(socketId, peerAddress, peerPort)
  }

  def disconnect: Future[Unit] = {
    TCP.disconnect(socketId)
  }

  def secure(options: js.UndefOr[SecureOptions]): Future[Unit] = {
    TCP.secure(socketId, options)
  }

  def send(data: ArrayBuffer): Future[SendInfo] = {
    TCP.send(socketId, data)
  }

  def close: Future[Unit] = {
    TCP.close(socketId)
  }

  def getInfo: Future[SocketInfo] = {
    TCP.getInfo(socketId)
  }

}

object Socket {

  sealed trait ReceiveEvent
  case class Received(data: ArrayBuffer) extends ReceiveEvent
  case class Error(code: Int) extends ReceiveEvent

  def apply(id: SocketId): Socket = new Socket(id)

  def apply(name: String = "",
            persistent: Boolean,
            bufferSize: Int): Future[Socket] = {
    TCP
      .create(SocketProperties(persistent, name, bufferSize))
      .map(i => Socket(i.socketId))
  }

} 
Example 9
Source File: Assets.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.xhr

import endpoints4s.algebra
import endpoints4s.algebra.Documentation
import org.scalajs.dom.XMLHttpRequest

import scala.scalajs.js
import scala.scalajs.js.typedarray.ArrayBuffer


  def assetsEndpoint(
      url: Url[AssetPath],
      docs: Documentation,
      notFoundDocs: Documentation
  ): Endpoint[AssetRequest, AssetResponse] =
    endpoint(arrayBufferGet(url), arrayBufferResponse)

  private def arrayBufferGet(url: Url[AssetPath]): Request[AssetRequest] =
    new Request[AssetRequest] {
      def apply(
          assetRequest: AssetRequest
      ): (XMLHttpRequest, Option[js.Any]) = {
        val xhr = new XMLHttpRequest
        xhr.open("GET", url.encode(assetRequest))
        xhr.responseType = "arraybuffer"
        (xhr, None)
      }
      def href(assetRequest: AssetRequest): String = url.encode(assetRequest)
    }

  private def arrayBufferResponse: Response[ArrayBuffer] =
    ok { xhr =>
      try {
        Right(xhr.response.asInstanceOf[ArrayBuffer])
      } catch {
        case exn: Exception => Left(exn)
      }
    }

} 
Example 10
Source File: Response.scala    From angulate2   with MIT License 5 votes vote down vote up
//     Project: angulate2 (https://github.com/jokade/angulate2)
// Description:

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

import org.scalajs.dom.Blob

import scala.scalajs.js
import scala.scalajs.js.typedarray.ArrayBuffer

@js.native
trait Body extends js.Object {
  def json(): js.Dynamic = js.native
  def text(): String = js.native
  def arrayBuffer(): ArrayBuffer = js.native
  def blob(): Blob = js.native
}

@js.native
trait Response extends Body {
  def ok: Boolean = js.native
  def url: String = js.native
  def status: Int = js.native
  def statusText: String = js.native
  def bytesLoaded: Int = js.native
  def totalBytes: Int = js.native
}

object Response {

  implicit final class RichResponse(val r: Response) extends AnyVal {
    def jsonData[T<:js.Any]: T = r.json().data.asInstanceOf[T]
  }
} 
Example 11
Source File: WebWorkerTransport.scala    From suzaku   with Apache License 2.0 5 votes vote down vote up
package suzaku.platform.web

import java.nio.ByteBuffer

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

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

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

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

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

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

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

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

import scala.scalajs.js.typedarray.ArrayBuffer

abstract class AppEntry {
  import DedicatedWorkerGlobalScope.self

  private var transport: WebWorkerTransport = _

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

  def start(transport: Transport): Any

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

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

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

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

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

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

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

    new WebDemoUI(transport)
  }

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

  def onMessage(msg: dom.MessageEvent) = {
    msg.data match {
      case buffer: ArrayBuffer =>
        
        transport.receive(buffer)
      case _ => // ignore other messages
    }
  }
} 
Example 16
Source File: 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 17
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
    }
  }
}