scala.scalajs.js.JSON Scala Examples

The following examples show how to use scala.scalajs.js.JSON. 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: ReactApolloTest.scala    From apollo-scalajs   with MIT License 5 votes vote down vote up
package com.apollographql.scalajs.react

import com.apollographql.scalajs.cache.InMemoryCache
import com.apollographql.scalajs.link.{HttpLink, HttpLinkOptions}
import com.apollographql.scalajs.{ApolloBoostClient, ApolloClient, CurrencyRatesQuery, UnfetchFetch}
import org.scalajs.dom.document
import org.scalatest.{Assertion, AsyncFunSuite}
import slinky.web.ReactDOM
import slinky.web.html.div

import scala.concurrent.Promise
import scala.scalajs.js
import scala.scalajs.js.JSON

class ReactApolloTest extends AsyncFunSuite {
  js.Dynamic.global.window.fetch = UnfetchFetch

  implicit override def executionContext =
    scala.concurrent.ExecutionContext.Implicits.global

  test("Can mount an ApolloProvider with a client instance") {
    assert(!js.isUndefined(
      ReactDOM.render(
        ApolloProvider(
          client = ApolloBoostClient(uri = "https://graphql-currency-rates.glitch.me")
        )(
          div()
        ),
        document.createElement("div")
      )
    ))
  }

  test("Can server-side render data to string based on a query") {
    val link = new HttpLink(options = HttpLinkOptions(uri = "https://graphql-currency-rates.glitch.me"))
    val cache = new InMemoryCache()
    val client = new ApolloClient(options = js.Dynamic.literal(ssrMode = true, link = link, cache = cache))

    ReactApolloServer.renderToStringWithData(
      ApolloProvider(ApolloProvider.Props(client = client))(
        Query(
          CurrencyRatesQuery,
          CurrencyRatesQuery.Variables("USD")
        ) { d =>
          if (d.data.isDefined) {
            div(d.data.get.rates.get.head.get.currency.get)
          } else ""
        }
      )
    ).toFuture.map { html =>
      assert(html == """<div data-reactroot="">AED</div>""")
    }
  }
} 
Example 2
Source File: ParseResultSpec.scala    From vizsql   with Apache License 2.0 5 votes vote down vote up
package com.criteo.vizatra.vizsql.js.common

import org.scalatest.{FunSpec, Matchers}
import com.criteo.vizatra.vizsql
import com.criteo.vizatra.vizsql.INTEGER

import scala.scalajs.js.JSON
class ParseResultSpec extends FunSpec with Matchers {
  describe("Column") {
    describe("from()") {
      it("converts scala Column to JS object") {
        val col = Column.from(vizsql.Column("col1", INTEGER(true)))
        JSON.stringify(col) shouldEqual """{"name":"col1","type":"integer","nullable":true}"""
      }
    }
  }

  describe("Table") {
    describe("from()") {
      it("converts scala Table to JS object") {
        val table = Table.from(vizsql.Table("table1", List(vizsql.Column("col1", INTEGER(true)))), Some("schema1"))
        JSON.stringify(table) shouldEqual """{"name":"table1","columns":[{"name":"col1","type":"integer","nullable":true}],"schema":"schema1"}"""
      }
    }
  }
} 
Example 3
Source File: AppCircuit.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
package scalafiddle.client

import diode.ActionResult.{ModelUpdate, ModelUpdateSilent}
import diode._
import diode.data.Empty
import diode.react.ReactConnector
import upickle.default._

import scala.scalajs.js
import scala.scalajs.js.JSON
import scalafiddle.client.AppRouter.Home
import scalafiddle.shared._

object AppCircuit extends Circuit[AppModel] with ReactConnector[AppModel] {
  // load from global config
  def fiddleData = read[FiddleData](JSON.stringify(js.Dynamic.global.ScalaFiddleData))

  override protected def initialModel =
    AppModel(Home, None, fiddleData, ScalaFiddleHelp(ScalaFiddleConfig.helpURL), LoginData(Empty, Empty))

  override protected def actionHandler = composeHandlers(
    new FiddleHandler(
      zoomRW(_.fiddleData)((m, v) => m.copy(fiddleData = v)),
      zoomRW(_.fiddleId)((m, v) => m.copy(fiddleId = v))
    ),
    new CompilerHandler(zoomRW(_.outputData)((m, v) => m.copy(outputData = v))),
    new LoginHandler(zoomRW(_.loginData)((m, v) => m.copy(loginData = v))),
    navigationHandler
  )

  override def handleFatal(action: Any, e: Throwable): Unit = {
    println(s"Error handling action: $action")
    println(e.toString)
  }

  override def handleError(e: String): Unit = {
    println(s"Error in circuit: $e")
  }

  val navigationHandler: (AppModel, Any) => Option[ActionResult[AppModel]] = (model, action) =>
    action match {
      case NavigateTo(page) =>
        Some(ModelUpdate(model.copy(navLocation = page)))
      case NavigateSilentTo(page) =>
        Some(ModelUpdateSilent(model.copy(navLocation = page)))
      case _ =>
        None
    }
} 
Example 4
Source File: LGeoJSONonEachFeature.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.leaflet

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.leaflet._
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g, literal => json}
import scala.scalajs.js.JSON


object LGeoJSONonEachFeature {
  val code =
    """
      |   div( id := "map", width := "600px", height := "285px")
      |  
      |  val geoJSONPointFeature = { "type": "Feature",
      |    "properties": {
      |        "name": "Tenali",
      |        "amenity": "Andhra Paris",
      |        "popupContent": "Cool town!"
      |    },
      |    "geometry": {
      |        "type": "Point",
      |        "coordinates": [80.6400 ,16.2428]
      |    }
      |    
      |   // define map
      |    val map = LMap("map").setView(MY_LOCATION, 10.0)
      |    map.addLayer(getTileLayer)
      |    LIconDefault.imagePath = "images/" // set images path
      |    //The onEachFeature option is a function that gets called on each feature before adding it to a GeoJSON layer.
      |    // A common reason to use this option is to attach a popup to features when they are clicked.
      |    val onEachFeatureFunc : OnEachFeatureType = (feature : js.Dynamic,layer : LFeatureGroup) => {
      |        layer.bindPopup(feature.properties.popupContent.toString)
      |
      |      }
      |    LGeoJson(JSON.parse(geoJSONPointFeature),
      |     LGeoJsonOptions(onEachFeature = onEachFeatureFunc)) //use onEachFeature func to set pop content for marker
      |      .addTo(map)
      |    
    """.stripMargin

  val component = ReactComponentB[Unit]("GeoJSON onEachFeature Option option ")

    .render(P => {
    div(
      h3("GeoJSON"),
      CodeExample(code)(
        div(key := "map", id := "map", width := "600px", height := "285px")
      )
    )

  })
    .componentDidMount(scope => {
    // define map 
    val map = LMap("map").setView(MY_LOCATION, 10.0)
    map.addLayer(getTileLayer)
    LIconDefault.imagePath = "images" // set images path
    //The onEachFeature option is a function that gets called on each feature before adding it to a GeoJSON layer. 
    // A common reason to use this option is to attach a popup to features when they are clicked.
    val onEachFeatureFunc: js.Function2[js.Dynamic, LFeatureGroup, Any] = (feature: js.Dynamic, layer: LFeatureGroup) => {
        layer.bindPopup(feature.properties.popupContent.toString)

      }
    LGeoJson(JSON.parse(geoJSONPointFeature),
      LGeoJsonOptions.onEachFeature(onEachFeatureFunc).result) //use onEachFeature func to set pop content for marker
      .addTo(map)
  })
    .buildU


  def apply() = component()
} 
Example 5
Source File: LGeoJSONPointToLayer.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.leaflet

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.leaflet._
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g, literal => json}
import scala.scalajs.js.JSON


object LGeoJSONPointToLayer {
  val code =
    """
      |   div( id := "map", width := "600px", height := "285px")
      |  
      |  val geoJSONPointFeature = { "type": "Feature",
      |    "properties": {
      |        "name": "Tenali",
      |        "amenity": "Andhra Paris",
      |        "popupContent": "Cool town!"
      |    },
      |    "geometry": {
      |        "type": "Point",
      |        "coordinates": [80.6400 ,16.2428]
      |    }
      |    
      |   // define map
      |    val map = LMap("map").setView(MY_LOCATION, 10.0)
      |    map.addLayer(getTileLayer)
      |    LIconDefault.imagePath = "images/" // set images path
      |
      |    //Points are handled differently than polylines and polygons. By default simple markers are drawn for GeoJSON Points. We can alter this by passing a pointToLayer function in a GeoJSON options object when creating the GeoJSON layer.
      |    val pointToLayerFunc : js.Function2[js.Dynamic,LLatLng,js.Any]   = (feature : js.Dynamic,latlng : LLatLng) => {
      |         LCircleMarker(latlng,LCircleMarkerOptions(
      |         radius = 8.0,
      |          fillColor = "yellow",
      |          fill = true,
      |          weight = 1.0,
      |         opacity = 1.0,
      |         fillOpacity = 0.8,
      |         color = "orange"
      |         ))
      |      }
      |    LGeoJson(JSON.parse(geoJSONPointFeature),
      |     LGeoJsonOptions(pointToLayer = pointToLayerFunc)) //use pointToLayer func to set marker for geojson point
      |      .addTo(map)
      |    
    """.stripMargin

  val component = ReactComponentB[Unit]("GeoJSON pointToLayer option ")

    .render(P => {
    div(
      h3("GeoJSON"),
      CodeExample(code)(
        div(key := "map", id := "map", width := "600px", height := "285px")
      )
    )

  })
    .componentDidMount(scope => {
    // define map 
    val map = LMap("map").setView(MY_LOCATION, 10.0)
    map.addLayer(getTileLayer)
    LIconDefault.imagePath = "images" // set images path

    //Points are handled differently than polylines and polygons. By default simple markers are drawn for GeoJSON Points. We can alter this by passing a pointToLayer function in a GeoJSON options object when creating the GeoJSON layer.
    val pointToLayerFunc: js.Function2[js.Dynamic, LLatLng, js.Any] = (feature: js.Dynamic, latlng: LLatLng) => {
      LCircleMarker(latlng, LCircleMarkerOptions
        .radius(8.0)
        .fillColor("yellow")
        .fill(true)
        .weight(1.0)
        .opacity(1.0)
        .fillOpacity(0.8)
        .color("orange").result
      )
    }
    LGeoJson(JSON.parse(geoJSONPointFeature),
      LGeoJsonOptions.pointToLayer(pointToLayerFunc).result) //use pointToLayer func to set marker for geojson point
      .addTo(map)

  })
    .buildU


  def apply() = component()
} 
Example 6
Source File: LGeoJSONStyle.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.leaflet

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.leaflet._
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g, literal => json}
import scala.scalajs.js.JSON


object LGeoJSONStyle {
  val code =
    """
      |   div( id := "map", width := "600px", height := "285px")
      |  
      |   val geoJsonState =  [{
      |    "type": "Feature",
      |    "properties": {"party": "Republican"},
      |    "geometry": {
      |        "type": "Polygon",
      |        "coordinates": [[
      |            [-104.05, 48.99],
      |            [-97.22,  48.98],
      |            [-96.58,  45.94],
      |            [-104.03, 45.94],
      |            [-104.05, 48.99]
      |        ]]
      |    }
      |}, {
      |    "type": "Feature",
      |    "properties": {"party": "Democrat"},
      |    "geometry": {
      |        "type": "Polygon",
      |        "coordinates": [[
      |            [-109.05, 41.00],
      |            [-102.06, 40.99],
      |            [-102.03, 36.99],
      |            [-109.04, 36.99],
      |            [-109.05, 41.00]
      |        ]]
      |    }
      |}]
      |   // define map
      |    val map = LMap("map").setView(LLatLng(41.8369,-87.6847), 4.0)
      |    map.addLayer(getTileLayer)
      |    LIconDefault.imagePath = "images/" // set images path
      |    val styleFunction : js.Function1[js.Dynamic,js.Any] = (feature : js.Dynamic) => {
      |        if(feature.properties.party.toString == "Republican") json("color" -> "orange")
      |         else json("color" -> "green")
      |      }
      |    LGeoJson(JSON.parse(geoJsonStates),
      |    LGeoJsonOptions(
      |    style = styleFunction
      |    )
      |    ).addTo(map)
      
      |    
    """.stripMargin

  val component = ReactComponentB[Unit]("LGeoJSONStyle")

    .render(P => {
    div(
      h3("GeoJSON Style Option "),
      CodeExample(code)(
        div(key := "map", id := "map", width := "600px", height := "285px")
      )
    )

  })
    .componentDidMount(scope => {
    // define map 
    val map = LMap("map").setView(LLatLng(41.8369,-87.6847), 4.0)
    map.addLayer(getTileLayer)
    LIconDefault.imagePath = "images" // set images path
    val styleFunction : js.Function1[js.Dynamic,js.Any] = (feature : js.Dynamic) => {
        if(feature.properties.party.toString == "Republican") json("color" -> "orange")
         else json("color" -> "green")
      }
    LGeoJson(JSON.parse(geoJsonStates),
    LGeoJsonOptions.style(styleFunction).result
    ).addTo(map)
    
  })
    .buildU


  def apply() = component()
} 
Example 7
Source File: LGeoJSONDemo.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.leaflet

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.leaflet._
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.scalajs.js.Dynamic.{global => g, literal => json}
import scala.scalajs.js.JSON


object LGeoJSONDemo {
  val code =
    """
      |   div( id := "map", width := "600px", height := "285px")
      |  
      |  val geoJSONPointFeature = { "type": "Feature",
      |    "properties": {
      |        "name": "Tenali",
      |        "amenity": "Andhra Paris",
      |        "popupContent": "Cool town!"
      |    },
      |    "geometry": {
      |        "type": "Point",
      |        "coordinates": [80.6400 ,16.2428]
      |    }
      |    
      |   // define map
      |    val map = LMap("map").setView(MY_LOCATION, 10.0)
      |    map.addLayer(getTileLayer)
      |    LIconDefault.imagePath = "images/" // set images path
      |    LGeoJson(JSON.parse(geoJSONPointFeature)).addTo(map)
      |    
    """.stripMargin

  val component = ReactComponentB[Unit]("LGeoJSONDemo")

    .render(P => {
    div(
      h3("GeoJSON"),
      CodeExample(code)(
        div(key := "map", id := "map", width := "600px", height := "285px")
      )
    )

  })
    .componentDidMount(scope => {
    // define map 
    val map = LMap("map").setView(MY_LOCATION, 10.0)
    map.addLayer(getTileLayer)
    LIconDefault.imagePath = "images" // set images path
    LGeoJson(JSON.parse(geoJSONPointFeature)).addTo(map)
    
  })
    .buildU


  def apply() = component()
} 
Example 8
Source File: PCompact.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.PouchDB
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSON


object PCompact {

  val code =
    """
      |  // create or get db
      |     val db = PouchDB.create("scalajs")
      |     db.compact().onSuccess {
      |       case (resp : js.Dynamic) => println(s"Compact Success :  ${JSON.stringify(resp)}")
      |     }
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PCompact")

    .render(P => {
    div(
      h3("All Documents"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    // create or get db
     val db = PouchDB.create("scalajs") 
     db.compact().onSuccess {
       case (resp : js.Dynamic) => println(s"Compact Success :  ${JSON.stringify(resp)}")
     }
  })
    .buildU



  def apply() = component()
} 
Example 9
Source File: PSync.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{PouchDB, ReplicateOptions}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PSync {

  val code =
    """
      | val sync = PouchDB.sync("scalajs","scalajs2",ReplicateOptions.live(true).result)
      |               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
      | val db = PouchDB.create("scalajs")
      | val db2 = PouchDB.create("scalajs2")
      | db.post(json("sync1" -> "fromdb1"))
      | db2.post(json("sync2" -> "fromdb2"))
      | dom.setTimeout(() => sync.cancel(),2000)
      | 
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PReplicate")
    .render(P => {
    div(
      h3("Replicate a Database"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    val sync = PouchDB.sync("scalajs","scalajs2",ReplicateOptions.live(true).result)
               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
     val db = PouchDB.create("scalajs")
     val db2 = PouchDB.create("scalajs2")
     db.post(json("sync1" -> "fromdb1"))
     db2.post(json("sync2" -> "fromdb2"))
     dom.setTimeout(() => sync.cancel(),2000)
  })
    .buildU



  def apply() = component()
} 
Example 10
Source File: PAllDocs.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{AllDocsOptions, PouchDB}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSON


object PAllDocs {

  val code =
    """
      |   // create or get db
      |     val db = PouchDB.create("scalajs") 
      |     // getting all docs (by default we'll only get id and rev of each doc
      |     db.allDocs().onSuccess {
      |      case (resp : js.Dynamic) => println(s"All Docs from without any options ${JSON.stringify(resp)}")
      |     }
      |     // to get doc fields included in results we must pass AllDocsOptions
      |    db.allDocs(AllDocsOptions(include_docs = true)).onSuccess {
      |      case (resp : js.Dynamic) => println(s"All Docs with doc content included ${JSON.stringify(resp)}")
      |    }
      |    
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PAllDocs")

    .render(P => {
    div(
      h3("All Documents"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    // create or get db
     val db = PouchDB.create("scalajs") 
     // getting all docs (by default we'll only get id and rev of each doc
     db.allDocs().onSuccess {
      case (resp : js.Dynamic) => println(s"All Docs from without any options ${JSON.stringify(resp)}")
     }
     // to get doc fields included in results we must pass AllDocsOptions
    db.allDocs(AllDocsOptions.include_docs(true).result).onSuccess {
      case (resp : js.Dynamic) => println(s"All Docs with doc content included ${JSON.stringify(resp)}")
    }
  })
    .buildU



  def apply() = component()
} 
Example 11
Source File: PChanges.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{ChangesOptions, PouchDB}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PChanges {

  val code =
    """
      |    // create or get db
      |    val db = PouchDB.create("scalajs")
      |    val changes = db.changes(ChangesOptions.since("now").live(true).result)
      |      .onChange((resp: js.Any) => println(s"changes response ${JSON.stringify(resp)} "))
      |    db.allDocs()
      |    db.post(json("check" -> "changes"))
      |    dom.setTimeout(() => changes.cancel(), 2000)
      |
    """.stripMargin

  val component = ReactComponentB[Unit]("PChanges")
    .render(P => {
    div(
      h3("All Documents"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    // create or get db
    val db = PouchDB.create("scalajs")
    val changes = db.changes(ChangesOptions.since("now").live(true).result)
      .onChange((resp: js.Any) => println(s"changes response ${JSON.stringify(resp)} "))
    db.allDocs()
    db.post(json("check" -> "changes"))
    dom.setTimeout(() => changes.cancel(), 2000)
  })
    .buildU


  def apply() = component()
} 
Example 12
Source File: PGetDoc.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.pouchdb.{PouchDB, PouchDBException}
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}


object PGetDoc {

  val code =
    """
      |    val db =  PouchDB.create("scalajs")
      |     db.get("bpt-rice").onComplete {
      |       case Success(resp : js.Dynamic) => println(s"doc with id bpt-rice is : ${JSON.stringify(resp)}")
      |       case Failure(ex) => println(s"Error while fetching doc with id bpt-rice : ${ex.asInstanceOf[PouchDBException].err}")
      |     }
    """.stripMargin

  val component = ReactComponentB[Unit]("PGetDoc")

    .render(P => {
    div(
      h3("Get Documents"),
      CodeExample(code)(
        p(key := "yeah", "Below code is executed , to verify this go to " +
          "developer tools -> Resources -> IndexedDB/Web SQL check _pouch_scaljs")
      )
    )

  })
    .componentWillMount(scope => {

    val db = PouchDB.create("scalajs")
    db.get("bpt-rice").onComplete {
      case Success(resp: js.Dynamic) => println(s"doc with id bpt-rice is : ${JSON.stringify(resp)}")
      case Failure(ex) => println(s"Error while fetching doc with id bpt-rice : ${ex.asInstanceOf[PouchDBException].err}")
    }

  })
    .buildU


  def apply() = component()
} 
Example 13
Source File: PReplicate.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.examples.util.Constants._
import chandu0101.scalajs.facades.pouchdb.{PouchDB, ReplicateOptions}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PReplicate {

  val code =
    """
      | val rep = PouchDB.replicate("scalajs","scalajs2",ReplicateOptions.live(true).result)
      |               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
      | val db = PouchDB.create("scalajs")
      | db.post(json("checkrep" -> "chnagesrep"))
      | dom.setTimeout(() => rep.cancel(),2000)
      |
    """.stripMargin
  
  val component = ReactComponentB[Unit]("PReplicate")
    .render(P => {
    div(
      h3("Replicate a Database"),
      CodeExample(code)(
        p(key := "yeah", DB_PATH)
      )
    )

  })
    .componentWillMount(scope => {
    val rep = PouchDB.replicate("scalajs","scalajs2",ReplicateOptions.live(true).result)
               .onChange((resp : js.Dynamic) => println(s" Replicate DB Chnages ${JSON.stringify(resp)}"))
     val db = PouchDB.create("scalajs")
     db.post(json("checkrep" -> "chnagesrep"))
     dom.setTimeout(() => rep.cancel(),2000)
  })
    .buildU



  def apply() = component()
} 
Example 14
Source File: PCreateUpdateDoc.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.components.pouchdb

import chandu0101.scalajs.facades.examples.pages.common.CodeExample
import chandu0101.scalajs.facades.pouchdb.PouchDB
import japgolly.scalajs.react.ReactComponentB
import japgolly.scalajs.react.vdom.all._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{literal => json}
import scala.scalajs.js.JSON


object PCreateUpdateDoc {

  val code =
    """
      |
      | case class Seed(name : String,category :String,duration : Int) {
      |      def toJson = json("name" -> name,"category" -> category, "duration" -> duration)
      |      def _id = s"$name-$category"
      |    }
      |
      |    //create DB
      |    val db =   PouchDB.create("scalajs")
      |    var rev = ""
      |    val seed1 = Seed("sonamsuri","rice",120)
      |    //inserting seed1
      |    db.put(doc = seed1.toJson,docId = seed1._id).onSuccess {
      |      case (response : js.Dynamic) => println(s"seed1 put response ${JSON.stringify(response)}")
      |        rev = response.rev.toString
      |    }
      |    val seed2 = Seed("bpt","rice",117)
      |    //inserting seed2
      |    db.put(doc = seed2.toJson , docId = seed2._id)
      |
      |    // updating seed1 you must specify its revision _rev, otherwise a conflict will occur.
      |    db.put(doc = seed1.copy(duration = 125).toJson,docId = seed1._id, docRev = rev)
      |
      |    val seed3 = Seed("bt","cotton",180)
      |    //insert new doc without an id using post , its not recommended way for prod
      |    db.post(doc = seed3.toJson)
      |    
    """.stripMargin

  val component = ReactComponentB[Unit]("PCreateUpdateDoc")
    .render(P => {
    div(
      h3("Create Document"),
      CodeExample(code)(
        p(key := "yeah", "Below code is executed , to verify this go to " +
          "developer tools -> Resources -> IndexedDB/Web SQL check  _pouch_scalajs store for real data."),
       p(key := "yeah2" , "The basic rule of thumb is: put() new documents with an _id, post() new documents without an _id. ")
      )
    )

  })
    .componentWillMount(scope => {

    case class Seed(name : String,category :String,duration : Int) {
      def toJson = json("name" -> name,"category" -> category, "duration" -> duration)
      def _id = s"$name-$category"
    }
    
    //create DB
    val db =   PouchDB.create("scalajs")
    var rev = ""
    val seed1 = Seed("sonamsuri","rice",120)
    //inserting seed1
    db.put(doc = seed1.toJson,docId = seed1._id).onSuccess {
      case (response : js.Dynamic) => println(s"seed1 put response ${JSON.stringify(response)}")
        rev = response.rev.toString
    }
    val seed2 = Seed("bpt","rice",117)
    //inserting seed2
    db.put(doc = seed2.toJson , docId = seed2._id)
    
    // updating seed1 you must specify its revision _rev, otherwise a conflict will occur.
    db.put(doc = seed1.copy(duration = 125).toJson,docId = seed1._id, docRev = rev)
    
    val seed3 = Seed("bt","cotton",180)
    //insert new doc without an id using post , its not recommended way for prod
    db.post(doc = seed3.toJson)
    
  })
    .buildU

  def apply() = component()
} 
Example 15
Source File: ComponentCredits.scala    From scalajs-facades   with MIT License 5 votes vote down vote up
package chandu0101.scalajs.facades.examples.pages.common

import chandu0101.scalajs.react.components.models.Github
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import org.scalajs.dom.ext.Ajax

import scala.scalajs.concurrent.JSExecutionContext.Implicits.runNow
import scala.scalajs.js
import scala.scalajs.js.JSON


object ComponentCredits {


  case class State(users : Set[Github])

  class Backend(t: BackendScope[Props, State]) {

  }

  val component = ReactComponentB[Props]("ComponentCredits")
    .initialState(State(Set()))
    .backend(new Backend(_))
    .render((P,S,B) => {
      if(S.users.isEmpty) div("Loading Credits ...")
      else
       div(
        h4("Author : "),
        GithubUser(S.users.last),
        h4("Contributors : "),
        div(marginRight := "10px")(S.users.init.map(u => GithubUser(user = u , key = u.login)))
       )
    })
    .componentDidMount(scope => {
        val url = s"https://api.github.com/repos/chandu0101/scalajs-facades/commits?path=core/src/main/scala/chandu0101/scalajs/facades/${scope.props.filePath}"
         Ajax.get(url).onSuccess {
          case xhr => {
               if(xhr.status == 200) {
                  val rawUsers = JSON.parse(xhr.responseText).asInstanceOf[js.Array[js.Dynamic]]
                  val users = rawUsers.map(u => Github(login = u.author.login.toString,html_url = u.author.html_url.toString , avatar_url = u.author.avatar_url.toString)).toSet
                  scope.modState(_.copy(users= users))
               }
          }
        }
    })
    .build


  case class Props(filePath : String)

  def apply(filePath : String,ref: js.UndefOr[String] = "", key: js.Any = {}) = component.set(key, ref)(Props(filePath))
} 
Example 16
Source File: SdkClient.scala    From iotchain   with MIT License 5 votes vote down vote up
package jbok.sdk

import java.net.URI

import cats.effect.{Clock, IO}
import io.circe.Json
import io.circe.syntax._
import io.circe.parser._
import jbok.network.http.HttpTransport
import jbok.network.rpc.{RpcClient, RpcRequest}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.Promise
import scala.scalajs.js.annotation.{JSExportAll, JSExportTopLevel}
import scala.scalajs.js.JSON

@JSExportAll
final class SdkClient(val uri: URI, val client: RpcClient[IO, Json]) {
  def fetch(api: String, method: String, params: js.UndefOr[js.Any]): Promise[String] = {
    val json = params.toOption match {
      case Some(a) => parse(JSON.stringify(a)).getOrElse(Json.Null)
      case None => Json.Null
    }
    val request = RpcRequest(List(api, method), json)
    client.transport.fetch(request).map(_.asJson.spaces2).unsafeToFuture().toJSPromise
  }
}

@JSExportTopLevel("SdkClient")
@JSExportAll
object SdkClient {
  implicit val clock: Clock[IO] = Clock.create[IO]

  def http(url: String): SdkClient = {
    val transport = HttpTransport[IO](url)
    val client    = RpcClient(transport)
    new SdkClient(new URI(url), client)
  }
} 
Example 17
Source File: ScalaJSExample.scala    From Full-Stack-Scala-Starter   with Apache License 2.0 5 votes vote down vote up
package example

import com.thoughtworks.binding.Binding.Var
import com.thoughtworks.binding.{Binding, dom}
import org.scalajs.dom.document
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.raw.{Event, HTMLElement}

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.JSON



object ScalaJSExample extends js.JSApp {

  implicit def makeIntellijHappy(x: scala.xml.Elem): Binding[HTMLElement] = ???

  
  def countRequest(data: Var[String]) = {
    val url = "http://localhost:9000/count"
    Ajax.get(url).foreach { case xhr =>
      data.value = JSON.parse(xhr.responseText).count.toString
    }
  }

  @dom
  def render = {
    val data = Var("")
    countRequest(data) // initial population
    <div>
      <button onclick={event: Event => countRequest(data) }>
        Boop
      </button>
      From Play: The server has been booped { data.bind } times. Shared Message: {shared.SharedMessages.itWorks}.
    </div>
  }

  def main(): Unit = {
    dom.render(document.body, render)
  }
} 
Example 18
Source File: IntroductionHandler.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package synereo.client.handlers

import diode.{ActionHandler, ActionResult, ModelRW}
import shared.dtos._
import synereo.client.rootmodels.IntroRootModel
import synereo.client.utils.ContentUtils

import concurrent._
import ExecutionContext.Implicits._
import scala.scalajs.js.JSON

// scalastyle:off


case class AddNotification(introconfirmSeq: Seq[Introduction])

case class UpdateIntroductionsModel(introConfirmReq: IntroConfirmReq)

case class PostIntroSuccess(beginIntroductionRes: BeginIntroductionRes)

case class AcceptIntroductionConfirmationResponse(introductionConfirmationResponse: IntroductionConfirmationResponse)

class IntroductionHandler[M](modelRW: ModelRW[M, IntroRootModel]) extends ActionHandler(modelRW) {
  override def handle: PartialFunction[Any, ActionResult[M]] = {

    case AddNotification(introconfirmSeq: Seq[Introduction]) =>
      val modelMod =if (value.introResponse.nonEmpty) {
        value.introResponse ++ introconfirmSeq.filterNot(e=>
          value.introResponse.exists(p=>JSON.parse(p.introProfile).name.asInstanceOf[String] ==  JSON.parse(e.introProfile).name.asInstanceOf[String]))
      } else {
        introconfirmSeq
      }

      updated(IntroRootModel(modelMod))

    case UpdateIntroductionsModel(introConfirmReq: IntroConfirmReq) =>
      ContentUtils.updateIntroductionsModel(introConfirmReq)
      val newList = value.introResponse.filterNot( _.introSessionId.equals(introConfirmReq.introSessionId))
      updated(IntroRootModel(newList))
  }
} 
Example 19
Source File: SearchesHandler.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package synereo.client.handlers

import diode.{ActionHandler, ActionResult, ModelRW}
import shared.models.Label
import synereo.client.rootmodels.SearchesRootModel
import shared.dtos.{Connection, LabelPost, SubscribeRequest}
import synereo.client.logger
import synereo.client.services.{CoreApi, SYNEREOCircuit}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}
import diode.AnyAction._
import synereo.client.facades.PrologParser

object SearchesModelHandler {
  def getSearchesModel(listOfLabels: Seq[String]): SearchesRootModel = {

    try {
      val labelsArray = PrologParser.StringToLabel(listOfLabels.toJSArray)
      val model = upickle.default.read[Seq[Label]](JSON.stringify(labelsArray))
      SearchesRootModel(searchesModel = model)
    } catch {
      case e: Exception =>
        logger.log.error("error in method getsearchesModel")
        SearchesRootModel(Nil)
    }
  }

  def leaf(text: String ) = "\"leaf(text(\\\"" + s"${text}" + "\\\"),display(color(\\\"\\\"),image(\\\"\\\")))\""

}

case class CreateLabels(labelStrSeq: Seq[String])

case class AddLabel(label: Label)

case class UpdatePrevSearchLabel(labelStr: String)

case class UpdatePrevSearchCnxn(cnxns: Seq[Connection])


// scalastyle:off
class SearchesHandler[M](modelRW: ModelRW[M, SearchesRootModel]) extends ActionHandler(modelRW) {
  override def handle: PartialFunction[Any, ActionResult[M]] = {
    case CreateLabels(labelStrSeq: Seq[String]) =>
      try {
        updated(SearchesModelHandler.getSearchesModel(labelStrSeq))
        //        noChange
      } catch {
        case e: Exception =>
          println(s" exception in Create Label action $e")
          noChange
      }

    case AddLabel(label: Label) =>
      updated(value.copy(searchesModel = value.searchesModel :+ label))

    case UpdatePrevSearchLabel(labelStr) =>
      updated(value.copy(previousSearchLabel = labelStr))

    case UpdatePrevSearchCnxn(cnxns) =>
      updated(value.copy(previousSearchCnxn = cnxns))

  }

} 
Example 20
Source File: IntroductionHandler.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package client.handler


import java.util.UUID

import diode.{ActionHandler, ActionResult, ModelRW}
import client.rootmodel.IntroRootModel
import client.logger
import client.services.{CoreApi, LGCircuit}
import shared.dtos._

import concurrent._
import ExecutionContext.Implicits._
import diode.AnyAction._

import scala.scalajs.js.JSON
import scala.util.{Failure, Success}

 LGCircuit.dispatch(ShowServerError(response.getMessage))
      }
      val newList = value.introResponse.filterNot(
        _.introSessionId.equals(introConfirmReq.introSessionId)
      )
      updated(IntroRootModel(newList))

    case AcceptConnectNotification(connectNotification: ConnectNotification) =>
      updated(IntroRootModel(Nil))

    case AcceptIntroductionConfirmationResponse(introductionConfirmationResponse: IntroductionConfirmationResponse) =>
      //      if (introductionConfirmationResponse.sessionURI.length != 0) {
      //        updated(IntroRootModel(Nil))
      //      } else
      noChange
    case AddNotification(introconfirmSeq: Seq[Introduction]) =>
      val modelMod =if (value.introResponse.nonEmpty) {
        value.introResponse ++ introconfirmSeq.filterNot(e=>
          value.introResponse.exists(p=>JSON.parse(p.introProfile).name.asInstanceOf[String] ==  JSON.parse(e.introProfile).name.asInstanceOf[String]))
      } else {
        introconfirmSeq
      }

      updated(IntroRootModel(modelMod))
  }

} 
Example 21
Source File: SearchesHandler.scala    From ProductWebUI   with Apache License 2.0 5 votes vote down vote up
package client.handler

import client.rootmodel.SearchesRootModel
import client.modules.AppModule
import client.services.{CoreApi, LGCircuit}
import client.utils.PrologParser
import diode.{ActionHandler, ActionResult, ModelRW}
import shared.models.Label

import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}
import diode.AnyAction._
import shared.dtos.{Connection, LabelPost, SubscribeRequest}

object SearchesModelHandler {
  def getSearchesModel(listOfLabels: Seq[String]): SearchesRootModel = {

    try {
      val labelsArray = PrologParser.StringToLabel(listOfLabels.toJSArray)
      val model = upickle.default.read[Seq[Label]](JSON.stringify(labelsArray))
      // logger.log.debug(s"searchesModel = ${model}")
      SearchesRootModel(model)
    } catch {
      case e: Exception =>
        SearchesRootModel(Nil)
    }
  }
  def leaf(text: String) = "leaf(text(\"" + s"${text}" + "\"),display(color(\"\"),image(\"\")))"

}

case class CreateLabels(labelStrSeq: Seq[String])

case class AddLabel(label: Label)

case class UpdatePrevSearchLabel(labelStr: String, viewName: String)

case class UpdatePrevSearchCnxn(cnxns: Seq[Connection], viewName: String)

case class PostLabelsAndMsg(labelNames: Seq[String], subscribeReq: SubscribeRequest)

case class UpdateLabel(label: Label)

case class UpdateLabels(labels: Seq[Label])

// scalastyle:off
class SearchesHandler[M](modelRW: ModelRW[M, SearchesRootModel]) extends ActionHandler(modelRW) {
  override def handle: PartialFunction[Any, ActionResult[M]] = {
    case CreateLabels(labelStrSeq: Seq[String]) =>
      try {
        updated(SearchesModelHandler.getSearchesModel(labelStrSeq))
      } catch {
        case e:Exception =>
          noChange
      }

    case AddLabel(label: Label) =>
      updated(value.copy(searchesModel = value.searchesModel ++ Seq(label)))

    case UpdatePrevSearchLabel(labelStr, viewName) =>
      viewName match {
        case AppModule.MESSAGES_VIEW => updated(value.copy(previousMsgSearchLabel = labelStr))
        case AppModule.PROFILES_VIEW => updated(value.copy(previousProfileSearchLabel = labelStr))
        case AppModule.PROJECTS_VIEW => updated(value.copy(previousProjectSearchLabel = labelStr))
      }

    case UpdatePrevSearchCnxn(cnxns, viewName) =>
      viewName match {
        case AppModule.MESSAGES_VIEW => updated(value.copy(previousMsgSearchCnxn = cnxns))
        case AppModule.PROFILES_VIEW => updated(value.copy(previousProfileSearchCnxn = cnxns))
        case AppModule.PROJECTS_VIEW => updated(value.copy(previousProjectSearchCnxn = cnxns))
      }

    case UpdateLabel(label) =>
      updated(value.copy(searchesModel = value.searchesModel.map(e => if (e.uid == label.uid) label else e)))

//    case UpdateLabels(labels: Seq[label])

  }

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

import client.components.{ConnectionsSelectize, LabelsSelectize}
import client.handler._
import client.modules.AppModule
import client.services.{CoreApi, LGCircuit}
import shared.dtos._
import shared.models._
import org.scalajs.dom._
import client.sessionitems.SessionItems.{MessagesViewItems, ProfilesViewItems, ProjectsViewItems}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.scalajs.js.timers._
import scala.util.{Failure, Success}
import diode.AnyAction._
import client.sessionitems.SessionItems

import scala.scalajs.js.JSON

//scalastyle:off
object ConnectionsUtils {

  



  def getCnxnForReq(cnxn: Seq[Connection], viewName: String): Seq[Connection] = {
    if (cnxn.isEmpty) {
      LGCircuit.zoom(_.connections.connectionsResponse).value.map(_.connection) ++ Seq(getSelfConnnection(viewName))
    } else {
      cnxn ++ Seq(getSelfConnnection(viewName))
    }
  }

  def getNameImgFromJson (jsonBlob: String) :(String, String) = {
    val json = JSON.parse(jsonBlob)
    val name = json.name.asInstanceOf[String]
    val imgSrc = if (jsonBlob.contains("imgSrc")) json.imgSrc.asInstanceOf[String] else ""
    (name, imgSrc)
  }

  def getCnxnFromRes (cnxn: ConnectionProfileResponse): ConnectionsModel = {
    val (name, imgSrc) = getNameImgFromJson(cnxn.jsonBlob)
    ConnectionsModel(cnxn.sessionURI, cnxn.connection,
      name, imgSrc)
  }

  def getConnectionsModel(response: String): Seq[ConnectionsModel] = {

    try {
      val connections = upickle.default.read[Seq[ApiResponse[ConnectionProfileResponse]]](response)
      connections.map(e => getCnxnFromRes(e.content))
        .sortBy(_.name)
    } catch {
      case e:Exception =>
        Nil
    }
  }

  def getCnxnFromNot (cnxn: ConnectNotification): ConnectionsModel = {
    val (name, imgSrc) = ConnectionsUtils.getNameImgFromJson(cnxn.introProfile)
    ConnectionsModel("", cnxn.connection, name, imgSrc)
  }

  // #todo think about better structure for the label prolog
  //

} 
Example 23
Source File: JsonParser.scala    From pushka   with Apache License 2.0 5 votes vote down vote up
package pushka.json

import pushka.{Parser, PushkaException, Ast}

import scala.scalajs.js
import scala.scalajs.js.JSON

final class JsonParser extends Parser[String] {

  private[this] def readAst(value: Any): Ast = value match{
    case s: String => Ast.Str(s)
    case n: Double => Ast.Num(n.toString)
    case true => Ast.True
    case false => Ast.False
    case null => Ast.Null
    case s: js.Array[_] => Ast.Arr(s.map(readAst(_: Any)).toList)
    case s: js.Object => Ast.Obj(s.asInstanceOf[js.Dictionary[_]].mapValues(readAst).toMap)
  }

  def parse(data: String): Ast = {
    val parsed = try {
      JSON.parse(data)
    } catch{ case js.JavaScriptException(e: js.SyntaxError) =>
      throw PushkaException(s"Error while parsing JSON $data: ${e.message}")
    }
    readAst(parsed)
  }

} 
Example 24
Source File: Http.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 de.surfice.smacrotools.JSOptionsObject
import rxjs.Observable

import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.JSImport

@js.native
@JSImport("@angular/http","Http")
class Http extends js.Object {
  def get(url: String, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] = js.native
  def post(url: String, body: js.Any, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] = js.native
  def put(url: String, body: js.Any, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] = js.native
  def delete(url: String, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] = js.native
}

object Http {
//  type RequestOptionsArgs = js.Dynamic

  implicit final class RichHttp(val http: Http) extends AnyVal {
    @inline
    def putJson(url: String, data: js.Any, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] =
      http.put(url,JSON.stringify(data),options)

    @inline
    def postJson(url: String, data: js.Any, options: js.UndefOr[RequestOptionsArgs] = js.undefined): Observable[Response] =
      http.post(url,JSON.stringify(data),options)
  }
}

@JSOptionsObject
case class RequestOptionsArgs(url: js.UndefOr[String] = js.undefined,
                              method: js.UndefOr[String] = js.undefined,
                              search: js.UndefOr[String] = js.undefined,
                              headers: js.UndefOr[Headers] = js.undefined,
                              body: js.UndefOr[js.Any] = js.undefined,
                              withCredentials: js.UndefOr[Boolean] = js.undefined,
                              responseType: js.UndefOr[ResponseContentType] = js.undefined
                              )

@JSImport("@angular/http","Headers")
@js.native
class Headers(headers: js.UndefOr[js.Dynamic] = js.undefined) extends js.Object {
  def append(name: String, value: String): Unit = js.native
  def delete(name: String): Unit = js.native
  def forEach(fn: js.Function): Unit = js.native
  def get(name: String): String = js.native
  def has(name: String): Boolean = js.native
  def keys(): js.Array[String] = js.native
  def set(name: String, value: String): Unit = js.native
}

object Headers {
  def apply(): Headers = new Headers()
  implicit final class RichHeaders(val h: Headers) extends AnyVal {
    def accept(mimeTypes: String): Headers = {
      h.set("Accept",mimeTypes)
      h
    }
    def contentType(mimeType: String): Headers = {
      h.set("Content-Type",mimeType)
      h
    }
  }
}

@js.native
trait ResponseContentType extends js.Object

@js.native
@JSImport("@angular/http","ResponseContentType")
object ResponseContentType extends js.Object {
  val Text: ResponseContentType = js.native
  val Json: ResponseContentType = js.native
  val ArrayBuffer: ResponseContentType = js.native
  val Blob: ResponseContentType = js.native
} 
Example 25
Source File: JSONArray.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package org.json

import scala.scalajs.js
import scala.scalajs.js.JSON


// Minimalistic version of the Android JSON library
class JSONArray(private[json] val array: js.Array[js.Any]) {
  def this() = this(js.Array[js.Any]())
  def this(json: String) = this(JSON.parse(json).asInstanceOf[js.Array[js.Any]])

  def length() = array.length

  def put(value: Boolean) = {
    array.push(value)
    this
  }

  def put(value: Int) = {
    array.push(value)
    this
  }

  def put(value: Long) = {
    array.push(value)
    this
  }

  def put(value: String) = {
    array.push(value)
    this
  }

  def put(value: JSONObject) = {
    array.push(value.obj)
    this
  }

  def put(value: JSONArray) = {
    array.push(value.array)
    this
  }

  @throws(classOf[JSONException])
  def getBoolean(index: Int) = array.lift(index).map(_.asInstanceOf[Boolean]).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getInt(index: Int) = array.lift(index).map(_.asInstanceOf[Int]).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getLong(index: Int) = array.lift(index).map(_.asInstanceOf[Long]).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getDouble(index: Int) = array.lift(index).map(_.asInstanceOf[Double]).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getString(index: Int) = array.lift(index).map(_.toString).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getJSONObject(index: Int) = array.lift(index).map({(o) => new JSONObject(o.asInstanceOf[js.Dynamic])}).getOrElse(throw new JSONException(""))
  @throws(classOf[JSONException])
  def getJSONArray(index: Int) = array.lift(index).map({(o) => new JSONArray(o.asInstanceOf[js.Array[js.Any]])}).getOrElse(throw new JSONException(""))

  def toString(indent: Int) = js.Dynamic.global.JSON.stringify(array, null, indent).asInstanceOf[String]
  override def toString: String = toString(0)
} 
Example 26
Source File: JSONObject.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package org.json

import scala.scalajs.js
import scala.scalajs.js.JSON


// Minimalistic version of the Android JSON library
class JSONObject(private[json] val obj: js.Dynamic) {

  def this(json: String) = this(JSON.parse(json))
  def this() = this(js.Dynamic.newInstance(js.Dynamic.global.Object)())

  def length() = obj.length.asInstanceOf[Int]

  def put(name: String, value: Boolean) = {
    obj.updateDynamic(name)(value)
    this
  }

  def put(name: String, value: Int) = {
    obj.updateDynamic(name)(value)
    this
  }

  def put(name: String, value: Long) = {
    obj.updateDynamic(name)(value)
    this
  }

  def put(name: String, value: Double) = {
    obj.updateDynamic(name)(value)
    this
  }

  def put(name: String, value: String) = {
    obj.updateDynamic(name)(value)
    this
  }

  def put(name: String, value: JSONObject) = {
    obj.updateDynamic(name)(value.obj)
    this
  }

  def put(name: String, value: JSONArray) = {
    obj.updateDynamic(name)(value.array)
    this
  }

  def has(name: String) = !js.isUndefined(obj.selectDynamic(name))

  def optBoolean(name: String, fallBack: Boolean): Boolean = Option(obj.selectDynamic(name).asInstanceOf[Boolean]).getOrElse(fallBack)
  def optInt(name: String, fallBack: Int): Int = Option(obj.selectDynamic(name).asInstanceOf[Int]).getOrElse(fallBack)
  def optLong(name: String, fallBack: Long): Long = Option(obj.selectDynamic(name).asInstanceOf[Long]).getOrElse(fallBack)
  def optDouble(name: String, fallBack: Double) = Option(obj.selectDynamic(name).asInstanceOf[Double]).getOrElse(fallBack)
  def optString(name: String, fallBack: String) = Option(obj.selectDynamic(name)).map(_.toString).getOrElse(fallBack)
  def optJSONObject(name: String, fallBack: JSONObject = null) = Option(obj.selectDynamic(name)).map(new JSONObject(_)).getOrElse(fallBack)
  def optJSONArray(name: String, fallBack: JSONArray = null) = Option(obj.selectDynamic(name).asInstanceOf[js.Array[js.Any]]).map(new JSONArray(_)).getOrElse(fallBack)

  @throws(classOf[JSONException])
  def getBoolean(name: String) = Option(obj.selectDynamic(name).asInstanceOf[Boolean]).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getInt(name: String) = Option(obj.selectDynamic(name).asInstanceOf[Int]).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getLong(name: String) = Option(obj.selectDynamic(name).asInstanceOf[Double].toLong).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getDouble(name: String) = Option(obj.selectDynamic(name).asInstanceOf[Double]).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getString(name: String) = Option(obj.selectDynamic(name)).map(_.toString).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getJSONObject(name: String) = Option(obj.selectDynamic(name)).map(new JSONObject(_)).getOrElse(throw new JSONException("No value for " + name))
  @throws(classOf[JSONException])
  def getJSONArray(name: String) = Option(obj.selectDynamic(name).asInstanceOf[js.Array[js.Any]]).map(new JSONArray(_)).getOrElse(throw new JSONException("No value for " + name))

  def names() = new JSONArray(js.Dynamic.global.Object.keys(obj).asInstanceOf[js.Array[js.Any]])
  def toString(indent: Int) = js.Dynamic.global.JSON.stringify(obj, null, indent).asInstanceOf[String]
  override def toString: String = toString(0)
  def toJavascript: js.Dynamic = obj
} 
Example 27
Source File: BatchAppListController.scala    From ledger-manager-chrome   with MIT License 5 votes vote down vote up
package co.ledger.manager.web.controllers.manager



import biz.enef.angulate.Module.RichModule
import biz.enef.angulate.{Controller, Scope}
import biz.enef.angulate.core.Location
import co.ledger.manager.web.Application
import co.ledger.manager.web.services.{DeviceService, WindowService}

import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

class BatchAppListController(val windowService: WindowService,
                             deviceService: DeviceService,
                             override val $scope: Scope,
                             $route: js.Dynamic,
                             $location: Location,
                             $routeParams: js.Dictionary[String]) extends Controller with ManagerController {

  var applications = js.Array[js.Dictionary[js.Any]]()

  def fetchApplications(): Future[Unit] = {
    val provider =
      if (!js.isUndefined(js.Dynamic.global.LEDGER) && js.Dynamic.global.LEDGER.asInstanceOf[Boolean] == true)
        "?provider=ledger"
      else
        ""
    Application.httpClient.get("/applications" + provider).json map {
      case (json, _) =>
        if (json.has("nanos")) {
          val apps = json.getJSONArray("nanos")
          applications = JSON.parse(apps.toString).asInstanceOf[js.Array[js.Dictionary[js.Any]]]
        }
    }
  }

  def isChecked(application: js.Dynamic): Boolean = {
    BatchAppListController.SELECTED_APPS.contains(application.identifier.asInstanceOf[String])
  }

  def toggle(application: js.Dynamic): Unit = {
    if (isChecked(application)) {
      BatchAppListController.SELECTED_APPS = BatchAppListController.SELECTED_APPS.filter(_ != application.identifier.asInstanceOf[String])
    } else {
      BatchAppListController.SELECTED_APPS = BatchAppListController.SELECTED_APPS :+ application.identifier.asInstanceOf[String]
    }
  }

  def back(): Unit = {
    $location.path("/applist/")
    $route.reload()
  }

  def installBatch(): Unit = {
    val apps = applications.filter({(item) => isChecked(item.asInstanceOf[js.Dynamic])}).map(_.asInstanceOf[js.Dynamic])
    ApplyUpdateController.APP_BATCH = apps.toArray
    $location.path(s"/apply/batch/application/${js.Dynamic.global.encodeURIComponent(apps(0).name)}/${JSON.stringify(apps(0).app)}/")
  }

  def refresh(): Unit = {
    applications = js.Array[js.Dictionary[js.Any]]()
    fetchApplications()  onComplete {
      case Success(_) => $scope.$apply()
      case Failure(ex) =>
        ex.printStackTrace()
    }
  }

  refresh()

}

object BatchAppListController {

  // Don't do that
  var SELECTED_APPS = Array[String]()

  def init(module: RichModule) = {
    module.controllerOf[BatchAppListController]("BatchAppListController")
  }

} 
Example 28
Source File: NativeJsonOutput.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.rpc.serialization

import com.avsystem.commons.serialization._

import scala.scalajs.js
import scala.scalajs.js.JSON

class NativeJsonOutput(valueConsumer: js.Any => Unit) extends OutputAndSimpleOutput {
  override def writeNull(): Unit =
    valueConsumer(null)

  override def writeString(str: String): Unit =
    valueConsumer(str)

  override def writeDouble(double: Double): Unit =
    valueConsumer(double)

  override def writeInt(int: Int): Unit =
    valueConsumer(int)

  override def writeLong(long: Long): Unit =
    writeString(long.toString)

  override def writeBigInt(bigInt: BigInt): Unit =
    writeString(bigInt.toString)

  override def writeBigDecimal(bigDecimal: BigDecimal): Unit =
    writeString(bigDecimal.toString)

  override def writeBoolean(boolean: Boolean): Unit =
    valueConsumer(boolean)

  override def writeList(): ListOutput =
    new NativeJsonListOutput(valueConsumer)

  override def writeObject(): ObjectOutput =
    new NativeJsonObjectOutput(valueConsumer)

  override def writeBinary(binary: Array[Byte]): Unit = {
    val l = writeList()
    binary.foreach(b => l.writeElement().writeSimple().writeInt(b))
    l.finish()
  }

  def writeRaw(raw: js.Any): Unit = valueConsumer(raw)
}

class NativeJsonListOutput(valueConsumer: js.Any => Unit) extends ListOutput {
  private val builder = new js.Array[js.Any]()
  override def writeElement(): Output =
    new NativeJsonOutput(el => builder.append(el))
  override def finish(): Unit =
    valueConsumer(builder)
}

class NativeJsonObjectOutput(valueConsumer: js.Any => Unit) extends ObjectOutput {
  private val builder = js.Dictionary.empty[js.Any]
  override def writeField(key: String): Output =
    new NativeJsonOutput(el => builder(key) = el)
  override def finish(): Unit =
    valueConsumer(builder)
}

object NativeJsonOutput {
  def write[T: GenCodec](value: T): String = {
    var result = ""
    GenCodec.write(new NativeJsonOutput(value => result = JSON.stringify(value)), value)
    result
  }
} 
Example 29
Source File: HTTPLogger.scala    From zio-logging   with Apache License 2.0 5 votes vote down vote up
package zio.logging.js

import java.time.OffsetDateTime
import java.util.UUID

import org.scalajs.dom.ext.Ajax
import zio.{ ZIO, ZLayer }
import zio.clock.{ currentDateTime, Clock }
import zio.logging.Logging
import zio.logging.{ LogAnnotation, LogContext, LogLevel, Logging }

import scala.scalajs.js
import scala.scalajs.js.JSON

object HTTPLogger {

  private def sendMessage(url: String, msg: js.Object) =
    Ajax.post(url, JSON.stringify(msg), headers = Map("Content-Type" -> "application/json"))

  
  type MessageFormatter = (OffsetDateTime, String, LogLevel, String, String, Throwable) => js.Object

  val defaultFormatter: MessageFormatter = (date, clientId, level, name, msg, cause) =>
    js.Dynamic.literal(
      date = date.toString,
      clientId = clientId,
      level = level match {
        case LogLevel.Fatal => "fatal"
        case LogLevel.Error => "error"
        case LogLevel.Warn  => "warn"
        case LogLevel.Info  => "info"
        case LogLevel.Debug => "debug"
        case LogLevel.Trace => "trace"
        case LogLevel.Off   => ""
      },
      name = name,
      msg = msg,
      cause = if (cause == null) "" else cause.toString
    )

  def makeWithName(
    url: String,
    clientId: String = UUID.randomUUID().toString,
    formatter: MessageFormatter = defaultFormatter
  )(name: String)(logFormat: (LogContext, => String) => String): ZLayer[Clock, Nothing, Logging] =
    make(url, clientId, formatter)((context, line) =>
      logFormat(context.annotate(LogAnnotation.Name, name :: Nil), line)
    )

  def make(url: String, clientId: String = UUID.randomUUID().toString, formatter: MessageFormatter = defaultFormatter)(
    logFormat: (LogContext, => String) => String
  ): ZLayer[Clock, Nothing, Logging] =
    Logging.make { (context, line) =>
      for {
        date      <- currentDateTime.orDie
        level      = context.get(LogAnnotation.Level)
        loggerName = LogAnnotation.Name.render(context.get(LogAnnotation.Name))
        msg        = formatter(date, clientId, level, loggerName, logFormat(context, line), null)
        _         <- ZIO.effectTotal(sendMessage(url, msg))
      } yield ()
    }

} 
Example 30
Source File: GeoLocationExample.scala    From scalajs-react-native   with Apache License 2.0 5 votes vote down vote up
package chandu0101.scalajs.rn.examples.uiexplorer.apis

import chandu0101.scalajs.rn.ReactNativeComponentB
import chandu0101.scalajs.rn.components.{Text, View}
import chandu0101.scalajs.rn.examples.uiexplorer.{UIExample, UIExplorerBlock, UIExplorerPage}
import japgolly.scalajs.react.BackendScope
import chandu0101.scalajs.rn.styles.NativeStyleSheet
import org.scalajs.dom
import org.scalajs.dom.raw.{Position, PositionError}

import scala.scalajs.js.JSON


object GeoLocationExample extends UIExample {

  case class State(initialPoistion : Position = null,lastPosition : Position = null )

  class Backend(t: BackendScope[_, State]) {

    var watchID : Int = 0

  }

  val component = ReactNativeComponentB[Unit]("GeoLocationExample")
    .initialState(State())
    .backend(new Backend(_))
    .render((P,S,B) => {
      UIExplorerPage(
       UIExplorerBlock("navigator.geolocation")(
         View()(
           Text()(
             Text(style = styles.title)("Initial Position : "),
             JSON.stringify(S.initialPoistion)
           ),
           Text()(
             Text(style = styles.title)("Current Position : "),
             JSON.stringify(S.lastPosition)
           )
         )
       )
      )
    })
    .componentDidMount(scope => {
      dom.window.navigator.geolocation.getCurrentPosition((pos : Position) => {
        scope.modState(_.copy(initialPoistion = pos))
      },(error : PositionError) => println(s"Error getting geo data ${error}"))
     scope.backend.watchID = dom.window.navigator.geolocation.watchPosition(
       (pos : Position) => scope.modState(_.copy(lastPosition = pos))
     )
    })
    .componentWillMount(scope => {
      dom.window.navigator.geolocation.clearWatch(scope.backend.watchID)
    })
    .buildNative

  object styles extends NativeStyleSheet {
  val title = style(fontWeight._500)

  }

  override def title: String = "Geolocation"

  override def description: String = "Examples of using the Geolocation API."
}