Skip to content

Commit

Permalink
🤖: clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
junerver committed May 10, 2024
1 parent e34db88 commit 7db630a
Show file tree
Hide file tree
Showing 19 changed files with 39 additions and 81 deletions.
12 changes: 0 additions & 12 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/ext/color.kt

This file was deleted.

18 changes: 0 additions & 18 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/ext/ex.kt

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import kotlin.reflect.KClass
object EventManager {
val subscriberMap = mutableMapOf<KClass<*>, MutableList<(Any) -> Unit>>()

@Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> register(noinline subscriber: (T) -> Unit): () -> Unit {
subscriberMap[T::class] ?: run { subscriberMap[T::class] = mutableListOf() }
subscriberMap[T::class]?.add(subscriber as (Any) -> Unit)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import xyz.junerver.kotlin.Tuple3
* there will be a problem of state loss.
*
* Now you can use [useGetState] to solve these problems and get the latest value
* through [getter] to avoid closure problems. The [setter] function also supports fast update.
* through `getter` to avoid closure problems. The `setter` function also supports fast update.
*
* @author Junerver
* date: 2024/5/10-9:31
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package xyz.junerver.compose.hooks

import androidx.compose.runtime.Composable
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import xyz.junerver.kotlin.Tuple2
import xyz.junerver.kotlin.tuple
Expand All @@ -13,7 +12,6 @@ import xyz.junerver.kotlin.tuple
* Email: [email protected]
* Version: v1.0
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun useKeyboard(): Tuple2<() -> Unit, () -> Unit> {
val keyboardController = LocalSoftwareKeyboardController.current
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ private typealias PersistentHookReturn<T> = Tuple3<T, SaveToPersistent<T>, Persi
/**
* By default, [memorySaveMap] is used for memory persistence.
* [usePersistent] is a lightweight encapsulation, you need to provide your own persistence solution
* globally through [PersistentContext.Provider];
* globally through `PersistentContext.Provider`;
*/
val PersistentContext =
createContext<Tuple3<PersistentGet, PersistentSave, PersistentClear>>((::memoryGetPersistent to ::memorySavePersistent) + ::memoryClearPersistent)

@Suppress("UNCHECKED_CAST")
@Composable
fun <T> usePersistent(key: String, defaultValue: T): PersistentHookReturn<T> {
val (get, set, clear) = useContext(context = PersistentContext)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import org.jetbrains.annotations.Nullable
* Email: [email protected]
* Version: v1.0
*/
@Suppress("UNCHECKED_CAST")
@Composable
fun <T> useState(default: T & Any): MutableState<T> {
return when (default) {
Expand Down
12 changes: 0 additions & 12 deletions hooks/src/main/kotlin/xyz/junerver/compose/hooks/useUndo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import xyz.junerver.kotlin.tuple
*/

data class UndoState<T>(
// 过去的状态
var past: List<T> = emptyList(),
var present: T,
var future: List<T> = emptyList(),
Expand All @@ -29,27 +28,19 @@ private data class Reset<S>(val payload: S) : UndoAction
private fun <T> undoReducer(preState: UndoState<T>, action: UndoAction): UndoState<T> {
val (past, present, future) = preState
return when (action) {
// 撤销
Undo -> {
if (past.isEmpty()) return preState
// 取出过去操作中的最后一个操作作为新的present
val newPresent = past[past.size - 1]
// 将最后一个操作从past中移除
val newPast = past.dropLast(1)
preState.copy(
// 将新的present和新的past设置到state中
past = newPast,
present = newPresent,
// 将旧的present放入到future数组的头部
future = listOf(present) + future
)
}
// 重做
Redo -> {
if (future.isEmpty()) return preState
// 取出第一个future
val newPresent = future[0]
// 将第一个future从future中删除 slice 函数可以用于剪裁\复制数组
val newFuture = future.drop(1)
preState.copy(
past = past + listOf(present),
Expand Down Expand Up @@ -82,11 +73,8 @@ private fun <T> undoReducer(preState: UndoState<T>, action: UndoAction): UndoSta
@Composable
fun <T> useUndo(initialPresent: T): Tuple7<UndoState<T>, (T) -> Unit, (T) -> Unit, () -> Unit, () -> Unit, Boolean, Boolean> {
val (state, dispatch) = useReducer(::undoReducer, UndoState(present = initialPresent))
// 是否可以撤销
val canUndo = state.past.isNotEmpty()
// 是否可以重做
val canRedo = state.future.isNotEmpty()
// undo相关的四个函数
val undo = { dispatch(Undo) }
val redo = { dispatch(Redo) }
val set = { newPresent: T -> dispatch(Set(newPresent)) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import kotlin.random.Random
* Email: [email protected]
* Version: v1.0
*/
@Suppress("UNUSED_VARIABLE")
@Composable
fun useUpdate(): () -> Unit {
val (state, setState) = useGetState(0.0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class FormScope private constructor(
val fieldState = _useState<T?>(default = null)
val (validate, _, set) = useBoolean()
val errMsg = useMap<KClass<*>, String>()
@Suppress("UNCHECKED_CAST")
ref.current.form[name] = fieldState as MutableState<Any>

useEffect(fieldState.value) {
Expand All @@ -46,6 +47,7 @@ class FormScope private constructor(
return false
}

@Suppress("RedundantNullableReturnType")
val fieldValue: Any? = fieldState.value
val isValidate =
validators.validateField(fieldValue, pass = Validator::pass, fail = Validator::fail)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,6 @@ fun List<Validator>.validateField(
is CustomValidator -> fieldValue.validate(it) {
it.validator(this)
}

else -> true
}
}.all { it }
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ data class Store(
}

class StoreScope private constructor(val list: MutableList<StoreRecord>) {

@Suppress("UNCHECKED_CAST")
inline fun <reified T : Any, reified A : Any> add(
pair: Tuple2<Reducer<T, A>, T>,
alias: String? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import xyz.junerver.compose.hooks.useContext
* @param A
* @return
*/
@Suppress("UNCHECKED_CAST")
@Composable
inline fun <reified A> useDispatch(alias: String? = null): Dispatch<A> =
alias?.let {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,12 @@ internal object FetchCacheManager : CoroutineScope {
cache[key] = tuple(cachedData, currentTime + cacheTime)
}

@Suppress("UNCHECKED_CAST")
fun <T> getCache(key: String): CachedData<T>? {
return if (isCacheValid(key)) {
cache[key]!!.first as CachedData<T>
} else {
null
}
}

fun clearCache(vararg cacheKeys: String) {
if (cacheKeys.isEmpty()) {
// 无参数全部清空
cache.clear()
} else {
cache.entries.removeIf {
cacheKeys.contains(it.key)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,12 @@ data class RequestOptions<TData> internal constructor(
*/
var ready: Boolean = true,
/**
* 通过设置 options.[refreshDeps],在依赖变化时, [useRequest] 会自动调用 [refresh] 方法,实现刷新(重复上一次请求)的效果。
* 通过设置 options.[refreshDeps],在依赖变化时, [useRequest] 会自动调用 [Fetch.refresh] 方法,实现刷新(重复上一次请求)的效果。
* 如果设置 options.[manual] = true,则 [refreshDeps] 不再生效
*/
var refreshDeps: Array<Any?> = emptyArray(),
/**
* 如果存在依赖刷新Action函数,则不执行默认的[refresh]函数,改为执行[refreshDepsAction]
* 如果存在依赖刷新Action函数,则不执行默认的[Fetch.refresh]函数,改为执行[refreshDepsAction]
*/
var refreshDepsAction: (() -> Unit)? = null,
/**
Expand All @@ -114,7 +114,7 @@ data class RequestOptions<TData> internal constructor(
var getCache: ((params: TParams) -> CachedData<TData>)? = null,

/**
* 通过设置 options.[loadingDelay] ,可以延迟 [loading] 变成 true 的时间,有效防止闪烁。
* 通过设置 options.[loadingDelay] ,可以延迟 [FetchState.loading] 变成 true 的时间,有效防止闪烁。
* 例如当一个接口正常会较快返回,我们如果常规使用会出现闪烁。从请求发起后,极快的从 false -> true ->false;
* 我们可以设置一个大于这个返回时长的[loadingDelay],例如[50.milliseconds],这样在50ms内返回的接口,
* 不会引起闪烁。这种闪烁其实还有一种变形场景,例如一个接口会极快返回,我们不希望用户继续快速点击,我们期望
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ import xyz.junerver.compose.hooks.SuspendNormalFunction
import xyz.junerver.compose.hooks.TParams
import xyz.junerver.compose.hooks.useCreation
import xyz.junerver.compose.hooks.userequest.plugins.useAutoRunPlugin
import xyz.junerver.compose.hooks.userequest.plugins.useDebouncePlugin
import xyz.junerver.kotlin.isNotNull

@Suppress("ConstPropertyName")
internal object Keys {
const val loading = "loading"
const val params = "params"
Expand All @@ -35,10 +37,6 @@ internal object Keys {
* Version: v1.0
*/
internal sealed interface Copyable<Self> {
/**
* [copy]函数是为了通过[reduce]实现类似js中解构赋值覆盖的效果,注意实现时必须是[that]覆盖[this]:
* `params = that.params ?: this.params,`
*/
fun copy(that: Self?): Self
operator fun plus(that: Self?) = this.copy(that)
}
Expand All @@ -54,6 +52,7 @@ internal fun <T : Copyable<T>> List<T>.cover(): T? {
* map中如果有这个key就取值,无论结果是否为null;
* 没有这个key则取旧值
*/
@Suppress("UNCHECKED_CAST")
internal fun <T> Map<String, Any?>.getOrElse(key: String, default: T?) = if (this.containsKey(key)) {
this[key] as? T
} else {
Expand Down Expand Up @@ -247,7 +246,7 @@ data class OnBeforeReturn<TData>(
/**
* 插件生命周期[PluginLifecycle.onRequest]的返回值类型,
* [Fetch._runAsync]会在调用[Fetch.requestFn]请求发生前回调所有插件的[PluginLifecycle.onRequest]函数。
* 插件可以通过[Fetch.requestFn]拿到原始的请求函数,通过返回值[requestDeferred]来[async]闭包的[await]
* 插件可以通过[Fetch.requestFn]拿到原始的请求函数,通过返回值[requestDeferred]来`async`闭包的`await`
* 来改变实际请求。
*/
data class OnRequestReturn<TData>(val requestDeferred: Deferred<TData>? = null) :
Expand Down Expand Up @@ -325,10 +324,10 @@ abstract class PluginLifecycle<TData> {
typealias GenPluginLifecycleFn<TData> = (Fetch<TData>, RequestOptions<TData>) -> PluginLifecycle<TData>

/**
* 插件函数[useXXXPlugin]的返回值是真实的插件[Plugin]对象,
* 插件函数 `useXXXPlugin` 的返回值是真实的插件[Plugin]对象,
* 可以通过在[useRequestPluginsImpl]中调用[onInit]函数,用来初始化 [Fetch.fetchState]状态。
* 插件对象自身实现了协程作用域[CoroutineScope],持有[Fetch]的实例、请求[RequestOptions]配置等内容。
* 按需实现[IFetch]对应[Fetch]中的各个函数调用,就可以在插件函数[useXXXPlugin]中需要使用副作用函数时,间接回调[Fetch]实例。
* 按需实现[IFetch]对应[Fetch]中的各个函数调用,就可以在插件函数`useXXXPlugin`中需要使用副作用函数时,间接回调[Fetch]实例。
* 具体用例可以参考:[useAutoRunPlugin]
*/
abstract class Plugin<TData : Any> : IFetch<TData>, Serializable, CoroutineScope {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,15 @@ typealias CancelFn = KFunction0<Unit>
* Description: 一个用来管理网络状态的Hook,它可以非常方便的接入到传统的 retrofit 网络请求模式中。
* 你几乎不需要做任何额外工作,就可以简单高效的在 Compose 中使用网络请求,并将请求数据作为状态,直接驱动UI。
*
* 重要:如果你使用例如 [GsonConverterFactory] 来反序列化你的响应,必须将反序列化后的对象设置成[Parcelable]!
* 重要:如果你使用例如 `GsonConverterFactory` 来反序列化你的响应,必须将反序列化后的对象设置成[Parcelable]!
*
* [noop] 是所有函数的抽象,我们最终通过函数拿到的手动执行函数也是[noop]类型的,调用时要传递的是[arrayOf]的参数。
* [SuspendNormalFunction] 是所有函数的抽象,我们最终通过函数拿到的手动执行函数也是[SuspendNormalFunction]类型的,
* 调用时要传递的是[arrayOf]的参数。
*
* 我还额外提供了两个方便的转换函数
* [asNoopFn]、[asSuspendNoopFn],这两个函数可以把任意的Kotlin函数转换成[useRequest]需要的函数。
* 需要注意区分,如果是挂起函数就需要调用[asSuspendNoopFn],否则就使用
* [asNoopFn],通过这个函数我们可以简化普通函数到[noop]的包装过程。
* [asNoopFn],通过这个函数我们可以简化普通函数到[SuspendNormalFunction]的包装过程。
*
* 示例代码:
*
Expand Down Expand Up @@ -85,8 +86,10 @@ typealias CancelFn = KFunction0<Unit>
* @param options
* 请求的配置项,参考[RequestOptions],以及[ahooks-useRequest](https://ahooks.gitee.io/zh-CN/hooks/use-request/index).
* @param plugins 自定义的插件,这是一个数组,请通过arrayOf传入
* @author Junerver date: 2024/1/25-8:11 Email: [email protected] Version:
* v1.0
* @author Junerver
* date: 2024/1/25-8:11
* Email: [email protected]
* Version: v1.0
*/
@Composable
fun <TData : Any> useRequest(
Expand Down Expand Up @@ -120,19 +123,19 @@ fun <TData : Any> useRequest(
/** 这样做的好处是方便添加与变更次序,而不用每次覆写componentN函数 */
return with(fetch) {
Tuple7(
/** 直接将[dataState.value]返回,避免拆包 */
/** 直接将`dataState.value`返回,避免拆包 */
first = dataState.value,
/** 返回[loadingState] */
/** 返回`loadingState` */
second = loadingState.value,
/** 返回原函数执行出错的异常[errorState] */
/** 返回原函数执行出错的异常`errorState` */
third = errorState.value,
/** 如果函数手动执行,则通过返回的[run]函数,进行执行。 如果配置了防抖、节流会按照优先防抖、其次节流的策略返回对应的函数。 */
/** 如果函数手动执行,则通过返回的`run`函数,进行执行。 如果配置了防抖、节流会按照优先防抖、其次节流的策略返回对应的函数。 */
fourth = run,
/** [mutate] 函数,用于直接修改当前状态值,目前缺少回溯 */
/** `mutate` 函数,用于直接修改当前状态值,目前缺少回溯 */
fifth = ::mutate,
/** [refresh] 函数 */
/** `refresh` 函数 */
sixth = ::refresh,
/** [cancel] 函数 */
/** `cancel` 函数 */
seventh = ::cancel
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import kotlinx.coroutines.Deferred

private val cachePromise: MutableMap<String, Deferred<*>> = mutableMapOf()

@Suppress("UNCHECKED_CAST")
internal fun <T> getCachePromise(cacheKey: String) = cachePromise[cacheKey] as? Deferred<T>

internal fun setCachePromise(cacheKey: String, promise: Deferred<*>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
@file:Suppress("unused")

package xyz.junerver.compose.hooks.utils

import xyz.junerver.compose.hooks.DependencyList
Expand Down

0 comments on commit 7db630a

Please sign in to comment.