Skip to content

Commit

Permalink
Inline useState result operators (#458)
Browse files Browse the repository at this point in the history
  • Loading branch information
turansky authored May 30, 2021
1 parent eeab570 commit 67f85d0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 31 deletions.
9 changes: 7 additions & 2 deletions kotlin-react/src/main/kotlin/react/Imports.kt
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,13 @@ external interface ProfilerProps : RProps {
external val Profiler: RClass<ProfilerProps>

// State Hook (16.8+)
@JsName("useState")
external fun <T> rawUseState(initValue: T): RDependenciesArray
external fun <T> useState(
initValue: T,
): RStateDelegate<T>

external fun <T> useState(
valueInitializer: () -> T,
): RStateDelegate<T>

// Reducer Hook (16.8+)
@JsName("useReducer")
Expand Down
38 changes: 9 additions & 29 deletions kotlin-react/src/main/kotlin/react/hooks.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

package react

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

typealias RDependenciesArray = Array<dynamic>
Expand All @@ -14,43 +13,24 @@ typealias RSetState<T> = (value: T) -> Unit
* Only works inside [functionalComponent]
* @see https://reactjs.org/docs/hooks-state.html
*/
inline fun <T> useState(initValue: T): RStateDelegate<T> {
val (state, setState) = rawUseState(initValue)
return RStateDelegate(state as T, setState as RSetState<T>)
}
// TODO: make external in IR
class RStateDelegate<T>
private constructor() {
inline operator fun component1(): T = asDynamic()[0]
inline operator fun component2(): RSetState<T> = asDynamic()[1]

/**
* Only works inside [functionalComponent]
* @see https://reactjs.org/docs/hooks-state.html
*/
inline fun <T> useState(noinline valueInitializer: () -> T): RStateDelegate<T> {
val (state, setState) = rawUseState(valueInitializer)
return RStateDelegate(state as T, setState as RSetState<T>)
}

/**
* Only works inside [functionalComponent]
* @see https://reactjs.org/docs/hooks-state.html
*/
class RStateDelegate<T>(
private val state: T,
private val setState: RSetState<T>
) : ReadWriteProperty<Nothing?, T> {
operator fun component1(): T = state
operator fun component2(): RSetState<T> = setState

override operator fun getValue(
inline operator fun getValue(
thisRef: Nothing?,
property: KProperty<*>
): T =
state
asDynamic()[0]

override operator fun setValue(
inline operator fun setValue(
thisRef: Nothing?,
property: KProperty<*>,
value: T
) {
setState(value)
asDynamic()[1](value)
}
}

Expand Down

0 comments on commit 67f85d0

Please sign in to comment.