diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/build.mill b/example/kotlinlib/web/4-webapp-kotlinjs/build.mill new file mode 100644 index 00000000000..c0500910326 --- /dev/null +++ b/example/kotlinlib/web/4-webapp-kotlinjs/build.mill @@ -0,0 +1,76 @@ +package build + +import mill._, kotlinlib._, kotlinlib.js._ + +object `package` extends RootModule with KotlinModule { + + def kotlinVersion = "1.9.24" + def ktorVersion = "2.3.12" + def kotlinHtmlVersion = "0.11.0" + + def mainClass = Some("webapp.WebApp") + + def ivyDeps = Agg( + ivy"io.ktor:ktor-server-core-jvm:$ktorVersion", + ivy"io.ktor:ktor-server-netty-jvm:$ktorVersion", + ivy"io.ktor:ktor-server-html-builder-jvm:$ktorVersion", + ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion", + ) + + def resources = Task { + os.makeDir(Task.dest / "webapp") + val jsPath = client.linkBinary().classes.path + // Move root.js[.map]into the proper filesystem position + // in the resource folder for the web server code to pick up + os.copy(jsPath / "client.js", Task.dest / "webapp/client.js") + os.copy(jsPath / "client.js.map", Task.dest / "webapp/client.js.map") + super.resources() ++ Seq(PathRef(Task.dest)) + } + + object test extends KotlinTests with TestModule.Junit5 { + def ivyDeps = super.ivyDeps() ++ Agg( + ivy"io.kotest:kotest-runner-junit5-jvm:5.9.1", + ivy"io.ktor:ktor-server-test-host-jvm:$ktorVersion" + ) + } + + object client extends KotlinJSModule { + def kotlinVersion = "1.9.24" + + override def splitPerModule = false + + def ivyDeps = Agg( + ivy"org.jetbrains.kotlinx:kotlinx-html-js:$kotlinHtmlVersion", + ) + } +} + +// A minimal example of a Kotlin backend server wired up with a Kotlin/JS +// front-end. The backend code is identical to the <<_todomvc_web_app>> example, but +// we replace the `main.js` client side code with the Javascript output of +// `ClientApp.kt`. +// +// Note that the client-side Kotlin code is the simplest 1-to-1 translation of +// the original Javascript, using `kotlinx.browser`, as this example is intended to +// demonstrate the `build.mill` config in Mill. A real codebase is likely to use +// Javascript or Kotlin/JS UI frameworks to manage the UI, but those are beyond the +// scope of this example. + +/** Usage + +> ./mill test +...webapp.WebAppTestssimpleRequest ... + +> ./mill runBackground + +> curl http://localhost:8082 +...What needs to be done... +... + +> curl http://localhost:8082/static/client.js +...bindEvent(this, 'todo-all', '/list/all', 'all')... +... + +> ./mill clean runBackground + +*/ diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/client/src/ClientApp.kt b/example/kotlinlib/web/4-webapp-kotlinjs/client/src/ClientApp.kt new file mode 100644 index 00000000000..8f2b7495358 --- /dev/null +++ b/example/kotlinlib/web/4-webapp-kotlinjs/client/src/ClientApp.kt @@ -0,0 +1,80 @@ +package client + +import kotlinx.browser.document +import kotlinx.browser.window +import org.w3c.dom.Element +import org.w3c.dom.HTMLInputElement +import org.w3c.dom.asList +import org.w3c.dom.events.KeyboardEvent +import org.w3c.dom.get +import org.w3c.fetch.RequestInit + +object ClientApp { + + private var state = "all" + + private val todoApp: Element + get() = checkNotNull(document.getElementsByClassName("todoApp")[0]) + + private fun postFetchUpdate(url: String) { + window + .fetch(url, RequestInit(method = "POST")) + .then { it.text() } + .then { text -> + todoApp.innerHTML = text + initListeners() + } + } + + private fun bindEvent(cls: String, url: String, endState: String? = null) { + document.getElementsByClassName(cls)[0] + ?.addEventListener("mousedown", { + postFetchUpdate(url) + if (endState != null) state = endState + } + ) + } + + private fun bindIndexedEvent(cls: String, block: (String) -> String) { + for (elem in document.getElementsByClassName(cls).asList()) { + elem.addEventListener( + "mousedown", + { postFetchUpdate(block(elem.getAttribute("data-todo-index")!!)) } + ) + } + } + + fun initListeners() { + bindIndexedEvent("destroy") { + "/delete/$state/$it" + } + bindIndexedEvent("toggle") { + "/toggle/$state/$it" + } + bindEvent("toggle-all", "/toggle-all/$state") + bindEvent("todo-all", "/list/all", "all") + bindEvent("todo-active", "/list/active", "active") + bindEvent("todo-completed", "/list/completed", "completed") + bindEvent("clear-completed", "/clear-completed/$state") + + val newTodoInput = document.getElementsByClassName("new-todo")[0] as HTMLInputElement + newTodoInput.addEventListener( + "keydown", + { + check(it is KeyboardEvent) + if (it.keyCode == 13) { + window + .fetch("/add/$state", RequestInit(method = "POST", body = newTodoInput.value)) + .then { it.text() } + .then { text -> + newTodoInput.value = "" + todoApp.innerHTML = text + initListeners() + } + } + } + ) + } +} + +fun main(args: Array) = ClientApp.initListeners() diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/resources/webapp/index.css b/example/kotlinlib/web/4-webapp-kotlinjs/resources/webapp/index.css new file mode 100644 index 00000000000..07ef4a160e3 --- /dev/null +++ b/example/kotlinlib/web/4-webapp-kotlinjs/resources/webapp/index.css @@ -0,0 +1,378 @@ +html, +body { + margin: 0; + padding: 0; +} + +button { + margin: 0; + padding: 0; + border: 0; + background: none; + font-size: 100%; + vertical-align: baseline; + font-family: inherit; + font-weight: inherit; + color: inherit; + -webkit-appearance: none; + appearance: none; + -webkit-font-smoothing: antialiased; + -moz-font-smoothing: antialiased; + font-smoothing: antialiased; +} + +body { + font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif; + line-height: 1.4em; + background: #f5f5f5; + color: #4d4d4d; + min-width: 230px; + max-width: 550px; + margin: 0 auto; + -webkit-font-smoothing: antialiased; + -moz-font-smoothing: antialiased; + font-smoothing: antialiased; + font-weight: 300; +} + +button, +input[type="checkbox"] { + outline: none; +} + +.hidden { + display: none; +} + +.todoapp { + background: #fff; + margin: 130px 0 40px 0; + position: relative; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 25px 50px 0 rgba(0, 0, 0, 0.1); +} + +.todoapp input::-webkit-input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp input::-moz-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp input::input-placeholder { + font-style: italic; + font-weight: 300; + color: #e6e6e6; +} + +.todoapp h1 { + position: absolute; + top: -155px; + width: 100%; + font-size: 100px; + font-weight: 100; + text-align: center; + color: rgba(175, 47, 47, 0.15); + -webkit-text-rendering: optimizeLegibility; + -moz-text-rendering: optimizeLegibility; + text-rendering: optimizeLegibility; +} + +.new-todo, +.edit { + position: relative; + margin: 0; + width: 100%; + font-size: 24px; + font-family: inherit; + font-weight: inherit; + line-height: 1.4em; + border: 0; + outline: none; + color: inherit; + padding: 6px; + border: 1px solid #999; + box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); + box-sizing: border-box; + -webkit-font-smoothing: antialiased; + -moz-font-smoothing: antialiased; + font-smoothing: antialiased; +} + +.new-todo { + padding: 16px 16px 16px 60px; + border: none; + background: rgba(0, 0, 0, 0.003); + box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); +} + +.main { + position: relative; + z-index: 2; + border-top: 1px solid #e6e6e6; +} + +label[for='toggle-all'] { + display: none; +} + +.toggle-all { + position: absolute; + top: -55px; + left: -12px; + width: 60px; + height: 34px; + text-align: center; + border: none; /* Mobile Safari */ +} + +.toggle-all:before { + content: '❯'; + font-size: 22px; + color: #e6e6e6; + padding: 10px 27px 10px 27px; +} + +.toggle-all:checked:before { + color: #737373; +} + +.todo-list { + margin: 0; + padding: 0; + list-style: none; +} + +.todo-list li { + position: relative; + font-size: 24px; + border-bottom: 1px solid #ededed; +} + +.todo-list li:last-child { + border-bottom: none; +} + +.todo-list li.editing { + border-bottom: none; + padding: 0; +} + +.todo-list li.editing .edit { + display: block; + width: 506px; + padding: 13px 17px 12px 17px; + margin: 0 0 0 43px; +} + +.todo-list li.editing .view { + display: none; +} + +.todo-list li .toggle { + text-align: center; + width: 40px; + /* auto, since non-WebKit browsers doesn't support input styling */ + height: auto; + position: absolute; + top: 0; + bottom: 0; + margin: auto 0; + border: none; /* Mobile Safari */ + -webkit-appearance: none; + appearance: none; +} + +.todo-list li .toggle:after { + content: url('data:image/svg+xml;utf8,'); +} + +.todo-list li .toggle:checked:after { + content: url('data:image/svg+xml;utf8,'); +} + +.todo-list li label { + white-space: pre-line; + word-break: break-all; + padding: 15px 60px 15px 15px; + margin-left: 45px; + display: block; + line-height: 1.2; + transition: color 0.4s; +} + +.todo-list li.completed label { + color: #d9d9d9; + text-decoration: line-through; +} + +.todo-list li .destroy { + display: none; + position: absolute; + top: 0; + right: 10px; + bottom: 0; + width: 40px; + height: 40px; + margin: auto 0; + font-size: 30px; + color: #cc9a9a; + margin-bottom: 11px; + transition: color 0.2s ease-out; +} + +.todo-list li .destroy:hover { + color: #af5b5e; +} + +.todo-list li .destroy:after { + content: '×'; +} + +.todo-list li:hover .destroy { + display: block; +} + +.todo-list li .edit { + display: none; +} + +.todo-list li.editing:last-child { + margin-bottom: -1px; +} + +.footer { + color: #777; + padding: 10px 15px; + height: 20px; + text-align: center; + border-top: 1px solid #e6e6e6; +} + +.footer:before { + content: ''; + position: absolute; + right: 0; + bottom: 0; + left: 0; + height: 50px; + overflow: hidden; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), + 0 8px 0 -3px #f6f6f6, + 0 9px 1px -3px rgba(0, 0, 0, 0.2), + 0 16px 0 -6px #f6f6f6, + 0 17px 2px -6px rgba(0, 0, 0, 0.2); +} + +.todo-count { + float: left; + text-align: left; +} + +.todo-count strong { + font-weight: 300; +} + +.filters { + margin: 0; + padding: 0; + list-style: none; + position: absolute; + right: 0; + left: 0; +} + +.filters li { + display: inline; +} + +.filters li a { + color: inherit; + margin: 3px; + padding: 3px 7px; + text-decoration: none; + border: 1px solid transparent; + border-radius: 3px; +} + +.filters li a.selected, +.filters li a:hover { + border-color: rgba(175, 47, 47, 0.1); +} + +.filters li a.selected { + border-color: rgba(175, 47, 47, 0.2); +} + +.clear-completed, +html .clear-completed:active { + float: right; + position: relative; + line-height: 20px; + text-decoration: none; + cursor: pointer; + position: relative; +} + +.clear-completed:hover { + text-decoration: underline; +} + +.info { + margin: 65px auto 0; + color: #bfbfbf; + font-size: 10px; + text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); + text-align: center; +} + +.info p { + line-height: 1; +} + +.info a { + color: inherit; + text-decoration: none; + font-weight: 400; +} + +.info a:hover { + text-decoration: underline; +} + +/* + Hack to remove background from Mobile Safari. + Can't use it globally since it destroys checkboxes in Firefox +*/ +@media screen and (-webkit-min-device-pixel-ratio:0) { + .toggle-all, + .todo-list li .toggle { + background: none; + } + + .todo-list li .toggle { + height: 40px; + } + + .toggle-all { + -webkit-transform: rotate(90deg); + transform: rotate(90deg); + -webkit-appearance: none; + appearance: none; + } +} + +@media (max-width: 430px) { + .footer { + height: 50px; + } + + .filters { + bottom: 10px; + } +} diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/src/WebApp.kt b/example/kotlinlib/web/4-webapp-kotlinjs/src/WebApp.kt new file mode 100644 index 00000000000..91652e2cb00 --- /dev/null +++ b/example/kotlinlib/web/4-webapp-kotlinjs/src/WebApp.kt @@ -0,0 +1,204 @@ +package webapp + +import io.ktor.server.application.* +import io.ktor.server.engine.* +import io.ktor.server.html.* +import io.ktor.server.http.content.* +import io.ktor.server.netty.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import io.ktor.server.util.* +import kotlinx.html.* +import kotlinx.html.stream.createHTML + +object WebApp { + data class Todo(val checked: Boolean, val text: String) + + private val todos = mutableListOf( + Todo(true, "Get started with Cask"), + Todo(false, "Profit!") + ) + + private fun FlowContent.list(state: String) = renderBody(state) + + private fun FlowContent.add(state: String, text: String) { + todos.add(Todo(false, text)) + renderBody(state) + } + + private fun FlowContent.delete(state: String, index: Int) { + todos.removeAt(index) + renderBody(state) + } + + private fun FlowContent.toggle(state: String, index: Int) { + todos[index] = todos[index].let { + it.copy(checked = !it.checked) + } + renderBody(state) + } + + private fun FlowContent.clearCompleted(state: String) { + todos.removeAll { it.checked } + renderBody(state) + } + + private fun FlowContent.toggleAll(state: String) { + val next = todos.any { it.checked } + for (item in todos.withIndex()) { + todos[item.index] = item.value.copy(checked = next) + } + renderBody(state) + } + + private fun FlowContent.renderBody(state: String) { + val filteredTodos = when (state) { + "all" -> todos.withIndex() + "active" -> todos.withIndex().filter { !it.value.checked } + "completed" -> todos.withIndex().filter { it.value.checked } + else -> throw IllegalStateException("Unknown state=$state") + } + div { + header(classes = "header") { + h1("todos") + input(classes = "new-todo") { + placeholder = "What needs to be done?" + } + } + section(classes = "main") { + input( + classes = "toggle-all", + type = InputType.checkBox + ) { + id = "toggle-all" + checked = todos.any { it.checked } + } + label { + htmlFor = "toggle-all" + +"Mark all as complete" + } + ul(classes = "todo-list") { + filteredTodos.forEach { (index, todo) -> + li(classes = if (todo.checked) "completed" else "") { + div(classes = "view") { + input(classes = "toggle", type = InputType.checkBox) { + checked = todo.checked + attributes["data-todo-index"] = index.toString() + } + label { +todo.text } + button(classes = "destroy") { + attributes["data-todo-index"] = index.toString() + } + } + input(classes = "edit") { + value = todo.text + } + } + } + } + } + footer(classes = "footer") { + span(classes = "todo-count") { + strong { + +todos.filter { !it.checked }.size.toString() + } + +" items left" + } + ul(classes = "filters") { + li(classes = "todo-all") { + a(classes = if (state == "all") "selected" else "") { +"All" } + } + li(classes = "todo-active") { + a(classes = if (state == "active") "selected" else "") { +"Active" } + } + li(classes = "todo-completed") { + a(classes = if (state == "completed") "selected" else "") { +"Completed" } + } + } + button(classes = "clear-completed") { +"Clear completed" } + } + } + } + + private fun HTML.renderIndex() { + head { + meta(charset = "utf-8") + meta(name = "viewport", content = "width=device-width, initial-scale=1") + title("Template • TodoMVC") + link(rel = "stylesheet", href = "/static/index.css") + } + body { + section(classes = "todoApp") { + renderBody("all") + } + footer(classes = "info") { + p { +"Double-click to edit a todo" } + p { + +"Created by " + a(href = "http://todomvc.com") { +"Li Haoyi" } + } + p { + +"Part of " + a(href = "http://todomvc.com") { +"TodoMVC" } + } + } + script(src = "/static/client.js", block = {}) + } + } + + fun configureRoutes(app: Application) { + with(app) { + routing { + get("/") { + call.respondHtml { + renderIndex() + } + } + post("/toggle-all/{state}") { + call.respondText { + createHTML().div { toggleAll(call.parameters.getOrFail("state")) } + } + } + post("/clear-completed/{state}") { + call.respondText { + createHTML().div { clearCompleted(call.parameters.getOrFail("state")) } + } + } + post("/toggle/{state}/{index}") { + call.parameters.run { + call.respondText { + createHTML().div { toggle(getOrFail("state"), getOrFail("index")) } + } + } + } + post("/delete/{state}/{index}") { + call.parameters.run { + call.respondText { + createHTML().div { delete(getOrFail("state"), getOrFail("index")) } + } + } + } + post("/add/{state}") { + val requestText = call.receiveText() + call.respondText { + createHTML().div { add(call.parameters.getOrFail("state"), requestText) } + } + } + post("/list/{state}") { + call.respondText { + createHTML().div { list(call.parameters.getOrFail("state")) } + } + } + staticResources("/static", "webapp") + } + } + } + + @JvmStatic + fun main(args: Array) { + embeddedServer(Netty, port = 8082, host = "0.0.0.0") { + configureRoutes(this) + }.start(wait = true) + } +} diff --git a/example/kotlinlib/web/4-webapp-kotlinjs/test/src/WebAppTests.kt b/example/kotlinlib/web/4-webapp-kotlinjs/test/src/WebAppTests.kt new file mode 100644 index 00000000000..0786f28c639 --- /dev/null +++ b/example/kotlinlib/web/4-webapp-kotlinjs/test/src/WebAppTests.kt @@ -0,0 +1,28 @@ +package webapp + +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.statement.bodyAsText +import io.ktor.http.HttpStatusCode +import io.ktor.server.testing.testApplication + +class WebAppTests : FunSpec({ + + suspend fun withServer(f: suspend HttpClient.() -> Unit) { + testApplication { + application { WebApp.configureRoutes(this) } + client.use { client -> f(client) } + } + } + + test("simpleRequest") { + withServer { + val response = get("/") + response.status shouldBe HttpStatusCode.OK + response.bodyAsText() shouldContain "What needs to be done?" + } + } +}) diff --git a/example/scalalib/web/4-webapp-scalajs/client/src/ClientApp.scala b/example/scalalib/web/4-webapp-scalajs/client/src/ClientApp.scala index f26a43f3409..77c4b4b6e7f 100644 --- a/example/scalalib/web/4-webapp-scalajs/client/src/ClientApp.scala +++ b/example/scalalib/web/4-webapp-scalajs/client/src/ClientApp.scala @@ -41,7 +41,7 @@ object ClientApp{ bindIndexedEvent("toggle", index => s"/toggle/$state/$index") bindEvent("toggle-all", s"/toggle-all/$state", None) bindEvent("todo-all", s"/list/all", Some("all")) - bindEvent("todo-active", s"/list/all", Some("active")) + bindEvent("todo-active", s"/list/active", Some("active")) bindEvent("todo-completed", s"/list/completed", Some("completed")) bindEvent("clear-completed", s"/clear-completed/$state", None)