Skip to content

Instantly share code, notes, and snippets.

@edvin edvin/GitHub.kt
Last active Jul 24, 2016

Embed
What would you like to do?
package controller
import models.User
import tornadofx.Controller
import tornadofx.Rest
class GitHub : Controller() {
val api : Rest by inject()
init {
api.baseURI = "https://api.github.com"
}
fun login(user: User): Boolean {
api.setBasicAuth(user.usernameProperty.value, user.passwordProperty.value)
return api.get("user").consume().ok()
}
}
package view
import app.Styles.Companion.login
import controller.GitHub
import javafx.geometry.Orientation.VERTICAL
import javafx.scene.control.Alert.AlertType.WARNING
import javafx.scene.control.Button
import javafx.scene.control.ProgressIndicator
import models.User
import models.UserModel
import tornadofx.*
class LoginScreen : View() {
override val root = Form().addClass(login)
val model = UserModel(User())
val github: GitHub by inject()
init {
title = "GitHub Login"
with(root) {
fieldset {
labelPosition = VERTICAL
field("Username") {
textfield(model.username).required(message = "Input your user name")
}
field("Password") {
passwordfield(model.password).required()
}
}
button("Log in") {
setOnAction {
login()
}
}
}
}
private fun Button.login() {
if (model.commit()) {
graphic = ProgressIndicator()
runAsync {
github.login(model.user)
} ui { success ->
graphic = null
if (success) replaceWith(ProtectedScreen::class, ViewTransition.SlideIn)
else alert(WARNING, "Login failed", "Check your credentials")
}
}
}
}
package app
import app.Styles
import view.LoginScreen
import tornadofx.App
import tornadofx.importStylesheet
class MyApp: App() {
override val primaryView = LoginScreen::class
init {
importStylesheet(Styles::class)
}
}
package view
import javafx.scene.control.Label
import javafx.scene.layout.StackPane
import tornadofx.View
class ProtectedScreen : View() {
override val root = StackPane(Label("You are logged in"))
init {
title = "Protected Screen"
}
}
package app
import javafx.scene.text.FontWeight
import tornadofx.Stylesheet
import tornadofx.box
import tornadofx.cssclass
import tornadofx.px
class Styles : Stylesheet() {
companion object {
val login by cssclass()
val loginWidth = 300.px
}
init {
form and login {
padding = box(25.px)
fontSize = 20.px
fontWeight = FontWeight.BOLD
prefWidth = loginWidth
button { prefWidth = loginWidth }
progressIndicator {
prefWidth = 16.px
prefHeight = prefWidth
}
}
}
}
package models
import javafx.beans.property.SimpleStringProperty
import tornadofx.ViewModel
class User {
val usernameProperty = SimpleStringProperty()
val passwordProperty = SimpleStringProperty()
}
class UserModel(var user: User) : ViewModel() {
val username = bind { user.usernameProperty }
val password = bind { user.passwordProperty }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.