├── .gitignore ├── webpack.config.d └── filename.js ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── kotlin │ └── nl │ │ └── lawik │ │ └── poc │ │ └── frontend │ │ └── reactredux │ │ ├── entities │ │ └── Todo.kt │ │ ├── enums │ │ └── VisibilityFilter.kt │ │ ├── actions │ │ └── Actions.kt │ │ ├── reducers │ │ ├── VisiblityFilter.kt │ │ ├── Index.kt │ │ └── Todos.kt │ │ ├── components │ │ ├── Todo.kt │ │ ├── TodoList.kt │ │ ├── Footer.kt │ │ ├── Link.kt │ │ └── App.kt │ │ ├── Index.kt │ │ ├── util │ │ └── Util.kt │ │ └── containers │ │ ├── FilterLink.kt │ │ ├── VisibleTodoList.kt │ │ └── AddTodo.kt │ └── resources │ └── web │ └── index.html ├── settings.gradle ├── LICENSE ├── gradlew.bat ├── gradlew └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | .idea/ 4 | *.iml 5 | out/ 6 | /web/ -------------------------------------------------------------------------------- /webpack.config.d/filename.js: -------------------------------------------------------------------------------- 1 | config.output.filename = "kotlin-poc-frontend-react-redux.bundle.js" -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lawikayoub/kotlin-poc-frontend-react-redux/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/entities/Todo.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.entities 2 | 3 | data class Todo(val id: Int, val text: String, var completed: Boolean) 4 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/enums/VisibilityFilter.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.enums 2 | 3 | enum class VisibilityFilter { 4 | SHOW_ALL, 5 | SHOW_ACTIVE, 6 | SHOW_COMPLETED 7 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/main/resources/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Kotlin React + React-Dom + Redux + React-Redux + React-Router Example 6 | 7 | 8 |
9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/actions/Actions.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.actions 2 | 3 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 4 | import redux.RAction 5 | 6 | class SetVisibilityFilter(val filter: VisibilityFilter) : RAction 7 | 8 | class AddTodo(val text: String): RAction { 9 | private companion object { 10 | var nextTodoId = 1 11 | } 12 | val id = nextTodoId++ 13 | } 14 | 15 | class ToggleTodo(val id: Int): RAction 16 | 17 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/reducers/VisiblityFilter.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.reducers 2 | 3 | import nl.lawik.poc.frontend.reactredux.actions.SetVisibilityFilter 4 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 5 | import redux.RAction 6 | 7 | fun visibilityFilter( 8 | state: VisibilityFilter = VisibilityFilter.SHOW_ALL, 9 | action: RAction 10 | ): VisibilityFilter = when (action) { 11 | is SetVisibilityFilter -> action.filter 12 | else -> state 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/reducers/Index.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.reducers 2 | 3 | import nl.lawik.poc.frontend.reactredux.entities.Todo 4 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 5 | import nl.lawik.poc.frontend.reactredux.util.combineReducers 6 | 7 | 8 | data class State( 9 | val todos: Array = emptyArray(), 10 | val visibilityFilter: VisibilityFilter = VisibilityFilter.SHOW_ALL 11 | ) 12 | 13 | fun combinedReducers() = combineReducers( 14 | mapOf( 15 | State::todos to ::todos, 16 | State::visibilityFilter to ::visibilityFilter 17 | ) 18 | ) 19 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/components/Todo.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.components 2 | 3 | import kotlinx.css.properties.TextDecorationLine 4 | import kotlinx.css.properties.textDecoration 5 | import kotlinx.html.js.onClickFunction 6 | import nl.lawik.poc.frontend.reactredux.entities.Todo 7 | import react.RBuilder 8 | import styled.css 9 | import styled.styledLi 10 | 11 | fun RBuilder.todo(todo: Todo, onClick: () -> Unit) = 12 | styledLi { 13 | attrs.onClickFunction = { onClick() } 14 | css { 15 | if (todo.completed) textDecoration(TextDecorationLine.lineThrough) 16 | } 17 | +todo.text 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/components/TodoList.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.components 2 | 3 | import nl.lawik.poc.frontend.reactredux.entities.Todo 4 | import react.RBuilder 5 | import react.RComponent 6 | import react.RProps 7 | import react.RState 8 | import react.dom.ul 9 | 10 | interface TodoListProps : RProps { 11 | var todos: Array 12 | var toggleTodo: (Int) -> Unit 13 | } 14 | 15 | class TodoList(props: TodoListProps) : RComponent(props) { 16 | override fun RBuilder.render() { 17 | ul { 18 | props.todos.forEach { todo(it) { props.toggleTodo(it.id) } } 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' } 5 | } 6 | resolutionStrategy { 7 | eachPlugin { 8 | if (requested.id.id == "kotlin2js" || requested.id.id == "kotlin-dce-js") { 9 | useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}") 10 | } 11 | if (requested.id.id == "org.jetbrains.kotlin.frontend") { 12 | useModule("org.jetbrains.kotlin:kotlin-frontend-plugin:${requested.version}") 13 | } 14 | } 15 | } 16 | } 17 | 18 | rootProject.name = 'kotlin-poc-frontend-react-redux' 19 | 20 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/reducers/Todos.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.reducers 2 | 3 | import nl.lawik.poc.frontend.reactredux.actions.AddTodo 4 | import nl.lawik.poc.frontend.reactredux.actions.ToggleTodo 5 | import nl.lawik.poc.frontend.reactredux.entities.Todo 6 | import redux.RAction 7 | 8 | fun todos(state: Array = emptyArray(), action: RAction): Array = when (action) { 9 | is AddTodo -> state + Todo(action.id, action.text, false) 10 | is ToggleTodo -> state.map { 11 | if (it.id == action.id) { 12 | it.copy(completed = !it.completed) 13 | } else { 14 | it 15 | } 16 | }.toTypedArray() 17 | else -> state 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/components/Footer.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.components 2 | 3 | import nl.lawik.poc.frontend.reactredux.containers.filterLink 4 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 5 | import react.RBuilder 6 | import react.dom.div 7 | import react.dom.span 8 | 9 | fun RBuilder.footer() = 10 | div { 11 | span { +"Show: " } 12 | filterLink { 13 | attrs.filter = VisibilityFilter.SHOW_ALL 14 | +"All" 15 | } 16 | filterLink { 17 | attrs.filter = VisibilityFilter.SHOW_ACTIVE 18 | +"Active" 19 | } 20 | filterLink { 21 | attrs.filter = VisibilityFilter.SHOW_COMPLETED 22 | +"Completed" 23 | } 24 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/components/Link.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.components 2 | 3 | import kotlinx.css.px 4 | import kotlinx.html.js.onClickFunction 5 | import react.RBuilder 6 | import react.RComponent 7 | import react.RProps 8 | import react.RState 9 | import styled.css 10 | import styled.styledButton 11 | 12 | interface LinkProps : RProps { 13 | var active: Boolean 14 | var onClick: () -> Unit 15 | } 16 | 17 | class Link(props: LinkProps) : RComponent(props) { 18 | override fun RBuilder.render() { 19 | styledButton { 20 | attrs.onClickFunction = { props.onClick() } 21 | attrs.disabled = props.active 22 | css { 23 | marginLeft = 4.px 24 | } 25 | children() 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/Index.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux 2 | 3 | import nl.lawik.poc.frontend.reactredux.components.app 4 | import nl.lawik.poc.frontend.reactredux.reducers.State 5 | import nl.lawik.poc.frontend.reactredux.reducers.combinedReducers 6 | import react.dom.render 7 | import react.redux.provider 8 | import redux.RAction 9 | import redux.compose 10 | import redux.createStore 11 | import redux.rEnhancer 12 | import kotlin.browser.document 13 | 14 | val store = createStore( 15 | combinedReducers(), State(), compose( 16 | rEnhancer(), 17 | js("if(window.__REDUX_DEVTOOLS_EXTENSION__ )window.__REDUX_DEVTOOLS_EXTENSION__ ();else(function(f){return f;});") 18 | ) 19 | ) 20 | 21 | fun main() { 22 | val rootDiv = document.getElementById("root") 23 | render(rootDiv) { 24 | provider(store) { 25 | app() 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 lawik123 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/util/Util.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.util 2 | 3 | import redux.Reducer 4 | import redux.combineReducers 5 | import kotlin.reflect.KProperty1 6 | 7 | 8 | /** 9 | * Helper function that combines reducers using [combineReducers] where the keys in the map are 10 | * properties of the state object instead of strings with the name of the state's properties 11 | * this helper function has 2 advantages over the original: 12 | * 13 | * 1. It is less error-prone, when you change the name of the property of the state you must change the 14 | * corresponding key or you will get a compile error. 15 | * 2. The compiler is now able to infer the [S] type parameter which means it is no longer needed to provide the 2 type parameters explicitly. 16 | * 17 | * @param S state 18 | * @param A action 19 | * @param R state property type 20 | * 21 | * @param reducers map where the key is the state property and the value is the reducer for said property. 22 | * 23 | * @return the combined reducer. 24 | * 25 | */ 26 | fun combineReducers(reducers: Map, Reducer<*, A>>): Reducer { 27 | return combineReducers(reducers.mapKeys { it.key.name }) 28 | } -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/containers/FilterLink.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.containers 2 | 3 | import nl.lawik.poc.frontend.reactredux.actions.SetVisibilityFilter 4 | import nl.lawik.poc.frontend.reactredux.components.Link 5 | import nl.lawik.poc.frontend.reactredux.components.LinkProps 6 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 7 | import nl.lawik.poc.frontend.reactredux.reducers.State 8 | import react.RClass 9 | import react.RProps 10 | import react.invoke 11 | import react.redux.rConnect 12 | import redux.WrapperAction 13 | 14 | interface FilterLinkProps : RProps { 15 | var filter: VisibilityFilter 16 | } 17 | 18 | private interface LinkStateProps : RProps { 19 | var active: Boolean 20 | } 21 | 22 | private interface LinkDispatchProps : RProps { 23 | var onClick: () -> Unit 24 | } 25 | 26 | val filterLink: RClass = 27 | rConnect( 28 | { state, ownProps -> 29 | active = state.visibilityFilter == ownProps.filter 30 | }, 31 | { dispatch, ownProps -> 32 | onClick = { dispatch(SetVisibilityFilter(ownProps.filter)) } 33 | } 34 | )(Link::class.js.unsafeCast>()) 35 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/components/App.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.components 2 | 3 | import nl.lawik.poc.frontend.reactredux.containers.addTodo 4 | import nl.lawik.poc.frontend.reactredux.containers.visibleTodoList 5 | import react.RBuilder 6 | import react.dom.br 7 | import react.dom.div 8 | import react.dom.h1 9 | import react.router.dom.browserRouter 10 | import react.router.dom.navLink 11 | import react.router.dom.route 12 | import react.router.dom.switch 13 | 14 | private const val TODO_LIST_PATH = "/todolist" 15 | 16 | fun RBuilder.app() = 17 | browserRouter { 18 | switch { 19 | route("/", exact = true) { 20 | div { 21 | h1 { 22 | +"Kotlin React + React-Dom + Redux + React-Redux + React-Router Example" 23 | } 24 | navLink(TODO_LIST_PATH) { 25 | +"Go to todo list" 26 | } 27 | } 28 | } 29 | route(TODO_LIST_PATH) { 30 | div { 31 | addTodo {} 32 | visibleTodoList {} 33 | footer() 34 | br {} 35 | navLink("/") { 36 | +"Go back" 37 | } 38 | } 39 | } 40 | } 41 | } 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/containers/VisibleTodoList.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.containers 2 | 3 | import nl.lawik.poc.frontend.reactredux.actions.ToggleTodo 4 | import nl.lawik.poc.frontend.reactredux.components.TodoList 5 | import nl.lawik.poc.frontend.reactredux.components.TodoListProps 6 | import nl.lawik.poc.frontend.reactredux.entities.Todo 7 | import nl.lawik.poc.frontend.reactredux.enums.VisibilityFilter 8 | import nl.lawik.poc.frontend.reactredux.reducers.State 9 | import react.RClass 10 | import react.RProps 11 | import react.invoke 12 | import react.redux.rConnect 13 | import redux.WrapperAction 14 | 15 | private fun getVisibleTodos(todos: Array, filter: VisibilityFilter): Array = when (filter) { 16 | VisibilityFilter.SHOW_ALL -> todos 17 | VisibilityFilter.SHOW_ACTIVE -> todos.filter { !it.completed }.toTypedArray() 18 | VisibilityFilter.SHOW_COMPLETED -> todos.filter { it.completed }.toTypedArray() 19 | } 20 | 21 | private interface TodoListStateProps : RProps { 22 | var todos: Array 23 | } 24 | 25 | private interface TodoListDispatchProps : RProps { 26 | var toggleTodo: (Int) -> Unit 27 | } 28 | 29 | val visibleTodoList: RClass = 30 | rConnect( 31 | { state, _ -> 32 | todos = getVisibleTodos(state.todos, state.visibilityFilter) 33 | }, 34 | { dispatch, _ -> 35 | toggleTodo = { dispatch(ToggleTodo(it)) } 36 | } 37 | )(TodoList::class.js.unsafeCast>()) -------------------------------------------------------------------------------- /src/main/kotlin/nl/lawik/poc/frontend/reactredux/containers/AddTodo.kt: -------------------------------------------------------------------------------- 1 | package nl.lawik.poc.frontend.reactredux.containers 2 | 3 | import kotlinx.html.ButtonType 4 | import kotlinx.html.InputType 5 | import kotlinx.html.js.onSubmitFunction 6 | import nl.lawik.poc.frontend.reactredux.actions.AddTodo 7 | import nl.lawik.poc.frontend.reactredux.store 8 | import org.w3c.dom.HTMLInputElement 9 | import react.* 10 | import react.dom.button 11 | import react.dom.div 12 | import react.dom.form 13 | import react.dom.input 14 | import react.redux.rConnect 15 | import redux.WrapperAction 16 | 17 | 18 | class AddTodo(props: RProps) : RComponent(props) { 19 | private val inputRef = createRef() 20 | override fun RBuilder.render() { 21 | div { 22 | form { 23 | attrs.onSubmitFunction = { event -> 24 | event.preventDefault() 25 | inputRef.current!!.let { 26 | if (it.value.trim().isNotEmpty()) { 27 | store.dispatch(AddTodo(it.value)) 28 | it.value = "" 29 | } 30 | } 31 | } 32 | input(type = InputType.text) { 33 | ref = inputRef 34 | } 35 | button(type = ButtonType.submit) { 36 | +"Add Todo" 37 | } 38 | } 39 | } 40 | } 41 | } 42 | 43 | 44 | val addTodo: RClass = 45 | rConnect()(nl.lawik.poc.frontend.reactredux.containers.AddTodo::class.js.unsafeCast>()) -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kotlin React Redux PoC 2 | This project is a PoC of using Kotlin (JS) and React, React-Dom, React-Router, Redux and React-Redux. 3 | This project is an implementation/translation of the react-redux [Todo List example project](https://redux.js.org/basics/example) in Kotlin (with the addition of react-router). 4 | The project showcases the following features: 5 | * Using existing JavaScript libraries (react, react-dom, react-router, redux and react-redux) from npm with Kotlin. 6 | * The implementation/translation of the react-redux [Todo List example project](https://redux.js.org/basics/example) in Kotlin (with the addition of react-router). 7 | * Using Webpack to bundle (and minify)/run the project. 8 | * Removing unused code to reduce file size. 9 | 10 | NOTE: It is assumed that you have basic knowledge of Kotlin, npm, JavaScript, modules, Webpack, React(-Dom/Router), Redux, React-Redux. 11 | It is highly recommended that you read and understand the react-redux [Todo List example project](https://redux.js.org/basics/example) and its [tutorial](https://redux.js.org/basics/usage-with-react) first. 12 | 13 | # Installation 14 | 1. Clone this repository. 15 | 16 | ## Running the project 17 | Run the following command in the root directory of the project `gradlew -t run`. 18 | This will download gradle, download the required dependencies and run a webpack server for the project on port 8088 in continuous build mode (the browser will refresh automatically on code changes). 19 | 20 | ## Bundling for production 21 | Run the following command in the root directory of the project: `gradlew clean bundle -Pprod`. 22 | This will download gradle, download the required dependencies, compile(transpile) Kotlin to JavaScript, bundle the JavaScript code into a single file, minify it and remove unused code to reduce file size. 23 | The bundle and the HTML file in the `resources` folder will placed in a `web` folder in the root of the project. 24 | 25 | ## About 26 | 27 | ### Using existing JavaScript libraries from npm 28 | The kotlin-frontend-plugin allows you to add npm libraries from Gradle, after applying the plugin you can add npm dependencies in the following manner: 29 | ```groovy 30 | kotlinFrontend { 31 | npm { 32 | dependency "react" 33 | // other (dev)dependencies here 34 | } 35 | // ... 36 | } 37 | ``` 38 | Similarly you can add dev dependencies in the same npm block using a devDependency tag instead of dependency. To use JavaScript libraries in a type-safe manner, external declarations for the libraries are required. 39 | Thankfully there is a [repository](https://github.com/JetBrains/kotlin-wrappers) for kotlin wrappers for popular JavaScript, these are added via gradle in this project. 40 | 41 | ### Todo list example project 42 | NOTE: import statements are left out in the code examples below. 43 | 44 | #### React 45 | `RBuilder` allows you to create react components using type-safe builders. 46 | 47 | A simple component in javascript is written as follows: 48 | 49 | ```jsx harmony 50 | const HelloWorld = () => ( 51 |

Hello World!

52 | ) 53 | 54 | export default HelloWorld 55 | ``` 56 | In Kotlin it is written as follows: 57 | ```kotlin 58 | fun RBuilder.helloWorld() = 59 | h1 { 60 | + "Hello World!" 61 | } 62 | ``` 63 | 64 | This allows you to use the helloWorld component in another component as follows: 65 | ```kotlin 66 | fun RBuilder.app() = { 67 | helloWorld() 68 | } 69 | ``` 70 | 71 | A more complex example (with props) will be shown in the [react-redux section](#react-redux) 72 | #### Redux 73 | 74 | ##### Actions 75 | Actions are defined using classes which implement the `RAction` interface. 76 | In JavaScript the action which toggles the status of a todo is defined as follows: 77 | ```javascript 78 | export const toggleTodo = id => ({ 79 | type: 'TOGGLE_TODO', 80 | id 81 | }) 82 | ``` 83 | In Kotlin the action can written as follows: 84 | ```kotlin 85 | class ToggleTodo(val id: Int): RAction 86 | ``` 87 | As you can see the Kotlin version doesn't have an action 'type', this is because the class (object type) itself *is* the action type (this will become more clear when you read the reducers section below). 88 | 89 | (Under the hood, the Redux Kotlin wrapper turns the class into a JavaScript object which Redux is able to process.) 90 | 91 | ##### Reducers 92 | Just like in JavaScript reducers in Kotlin are functions which take two parameters, a state and an action. 93 | In JavaScript the todos reducer is defined as follows: 94 | ```javascript 95 | const todos = (state = [], action) => { 96 | switch (action.type) { 97 | case 'ADD_TODO': 98 | return [ 99 | ...state, 100 | { 101 | id: action.id, 102 | text: action.text, 103 | completed: false 104 | } 105 | ] 106 | case 'TOGGLE_TODO': 107 | return state.map(todo => 108 | (todo.id === action.id) 109 | ? {...todo, completed: !todo.completed} 110 | : todo 111 | ) 112 | default: 113 | return state 114 | } 115 | } 116 | 117 | export default todos 118 | ``` 119 | In Kotlin the reducer is written as follows: 120 | ```kotlin 121 | fun todos(state: Array = emptyArray(), action: RAction): Array = when (action) { 122 | is AddTodo -> state + Todo(action.id, action.text, false) 123 | is ToggleTodo -> state.map { 124 | if (it.id == action.id) { 125 | it.copy(completed = !it.completed) 126 | } else { 127 | it 128 | } 129 | }.toTypedArray() 130 | else -> state 131 | } 132 | ``` 133 | As you can see the action type is checked by checking the object type of `action` using `is`. 134 | 135 | Combining reducers in Kotlin (usually) goes as follows: 136 | ```kotlin 137 | data class State( 138 | val todos: Array = emptyArray(), 139 | val visibilityFilter: VisibilityFilter = VisibilityFilter.SHOW_ALL 140 | ) 141 | 142 | fun combinedReducers() = combineReducers( 143 | mapOf( 144 | "todos" to ::todos, 145 | "visibilityFilter" to ::visibilityFilter 146 | ) 147 | ) 148 | ``` 149 | As you can see you provide a map where the key is the name of your state property and the value is the reducer function for said state property. 150 | However, I have written the following function: 151 | ```kotlin 152 | fun combineReducers(reducers: Map, Reducer<*, A>>): Reducer { 153 | return combineReducers(reducers.mapKeys { it.key.name }) 154 | } 155 | ``` 156 | The key in this helper function is a property of your state class, this has 2 advantages: 157 | 1. It's less error-prone, when you change the name of your property without changing the corresponding key your code won't compile. 158 | 2. The compiler is now able to infer the `S` type parameter which means it is no longer needed to provide the 2 type parameters explicitly. 159 | 160 | The `combinedReducers` function can now be written as follows (the `State` data class remained the same): 161 | ```kotlin 162 | fun combinedReducers() = combineReducers( 163 | mapOf( 164 | State::todos to ::todos, 165 | State::visibilityFilter to ::visibilityFilter 166 | ) 167 | ) 168 | ``` 169 | 170 | #### React-Redux 171 | Connecting Redux state to React components' props is *somewhat* similar as in JavaScript. 172 | 173 | In JavaScript the `FilterLink` container component is connected to the `Link` component in the following manner: 174 | 175 | ```jsx harmony 176 | // components/Link.js 177 | 178 | const Link = ({ active, children, onClick }) => ( 179 | 188 | ) 189 | 190 | Link.propTypes = { 191 | active: PropTypes.bool.isRequired, 192 | children: PropTypes.node.isRequired, 193 | onClick: PropTypes.func.isRequired 194 | } 195 | 196 | export default Link 197 | ``` 198 | 199 | ```javascript 200 | // containers/FilterLink.js 201 | 202 | const mapStateToProps = (state, ownProps) => ({ 203 | active: ownProps.filter === state.visibilityFilter 204 | }) 205 | 206 | const mapDispatchToProps = (dispatch, ownProps) => ({ 207 | onClick: () => dispatch(setVisibilityFilter(ownProps.filter)) 208 | }) 209 | 210 | export default connect( 211 | mapStateToProps, 212 | mapDispatchToProps 213 | )(Link) 214 | ``` 215 | 216 | In Kotlin this is done in the following manner: 217 | ```kotlin 218 | // components/Link.kt 219 | 220 | interface LinkProps : RProps { 221 | var active: Boolean 222 | var onClick: () -> Unit 223 | } 224 | 225 | class Link(props: LinkProps) : RComponent(props) { 226 | override fun RBuilder.render() { 227 | styledButton { 228 | attrs.onClickFunction = { props.onClick() } 229 | attrs.disabled = props.active 230 | css { 231 | marginLeft = 4.px 232 | } 233 | children() 234 | } 235 | } 236 | } 237 | ``` 238 | ```kotlin 239 | // containers/FilterLink.kt 240 | 241 | interface FilterLinkProps : RProps { 242 | var filter: VisibilityFilter 243 | } 244 | 245 | private interface LinkStateProps : RProps { 246 | var active: Boolean 247 | } 248 | 249 | private interface LinkDispatchProps : RProps { 250 | var onClick: () -> Unit 251 | } 252 | 253 | val filterLink: RClass = 254 | rConnect( 255 | { state, ownProps -> 256 | active = state.visibilityFilter == props.filter 257 | }, 258 | { dispatch, ownProps -> 259 | onClick = { dispatch(SetVisibilityFilter(props.filter)) } 260 | } 261 | 262 | )(Link::class.js.unsafeCast>()) 263 | ``` 264 | To map the state and dispatch to props in a type-safe manner, two interfaces are defined `LinkStateProps` and `LinkDispatchProps`. 265 | 266 | As you can see, the rConnect function takes 7 type parameters: 267 | * `State` this is your root state class 268 | * `SetVisibilityFilter` this is the action that this component is able to dispatch, use inheritance to allow for more actions (or just put `RAction` here). 269 | * `WrapperAction` Interface used to wrap your action class into an action object that Redux understands (just use the provided WrapperAction interface). 270 | * `FilterLinkProps` Props of the *container* component, use `RProps` if the container has no props. 271 | * `LinkStateProps` These are the props from the connected component (in this case `Link`) that should be mapped to state. * 272 | * `LinkDispatchProps` These are the props from the connected component (in this case `Link`) that should be mapped to dispatch. * 273 | * `LinkProps` The props from the connected component (in this case `Link`). 274 | 275 | *These two combined usually form the props of the connected component. As you can see `LinkProps` has both the `active` and `onClick` props which are also in `LinkStateProps` and `LinkDispatchProps` 276 | 277 | The rConnect function has 2 lambda parameters, the first one is the equivalent of mapStateToProps and the second one is the equivalent of mapDispatchToProps. 278 | 279 | mapStateToProps: 280 | ```kotlin 281 | { state, ownProps -> 282 | active = state.visibilityFilter == ownProps.filter 283 | } 284 | ``` 285 | * `this` refers to `LinkStateProps`. 286 | * `state` refers to the state, this was provided by `State`. 287 | * `ownProps` refers to the props of the *container* component, in this case `FilterLinkProps` 288 | 289 | mapDispatchToProps: 290 | ```kotlin 291 | { dispatch, ownProps -> 292 | onClick = { dispatch(SetVisibilityFilter(props.filter)) } 293 | } 294 | ``` 295 | * `this` refers to `LinkDispatchProps` 296 | * `dispatch` dispatcher which can be used to dispatch actions of the provided type, in this case `SetVisibilityFilter`. 297 | * `ownProps` refers to the props of the *container* component, in this case `FilterLinkProps` 298 | 299 | #### React-Router 300 | The react-router Kotlin wrapper has support for `BrowserRouter` and `HashRouter`. 301 | The wrapper adds on to the type-safe builder used to create components which allow you to make use of the router in a similar manner as you would in JavaScript. 302 | 303 | See `App.kt` to see how it is implemented in this project, it's also possible to map a component to a route using the following syntax: 304 | ```kotlin 305 | fun RBuilder.render() = { 306 | hashRouter{ // or browserRouter 307 | switch { 308 | // ... 309 | route("/", Foo::class) 310 | } 311 | } 312 | } 313 | ``` 314 | 315 | ### Using webpack to bundle(and minify)/run the project 316 | The kotlin-frontend-plugin allows you to make use of Webpack, the configuration for this project looks like this: 317 | ```groovy 318 | kotlinFrontend { 319 | // ... 320 | webpackBundle { 321 | bundleName = "this-will-be-overwritten" // NOTE: for example purposes this is overwritten in `webpack.config.d/filename.js`. 322 | contentPath = file('src/main/resources/web') 323 | if(project.hasProperty('prod')){ 324 | mode = "production" 325 | } 326 | // ... 327 | } 328 | } 329 | ``` 330 | It's also possible to customize the Webpack configuration using JavaScript by adding additional scripts in the `webpack.config.d` folder. The scripts will be appended to the end of the generated Webpack config script (you can see the final output by viewing the `webpack.config.js` file in the generated build folder), the scripts are appended alphabetically, use numbers prefix to change the order. 331 | See the `filename.js` script for an example on how a script is used to set the name of the bundle(this is just a simple example, the use of scripts allow for full customization of Webpack). 332 | 333 | Using the `gradlew -t run` command runs the webpack dev server in continuous mode. 334 | 335 | Using the `gradlew bundle -Pprod` command will build the project for production, the Kotlin files will be compiled(transpiled) to JavaScript, the required JavaScript files will be bundled into a single JavaScript file, the bundle will be minified, and moved to the web folder in the root directory of the project (along with the HTML files in the `src/resources/web) folder. 336 | 337 | ### Removing unused code 338 | The `kotlin-dce-js` Gradle plugin automatically removes unused code from the compiled(transpiled) JavaScript file, this is especially useful due to the fact that the Kotlin standard library is rather big and has to be included with the app in order for it to run. 339 | Without the plugin, the production bundle (which is minified) is 2085KB, the plugin brings this down to 617KB. --------------------------------------------------------------------------------