1、添加banner功能
This commit is contained in:
Elemt 2026-11-02 12:01:12 +08:00
parent 0268068f86
commit b52f631643
7 changed files with 233 additions and 19 deletions

View File

@ -21,6 +21,7 @@ object ReportType {
} }
object ReportKey { object ReportKey {
const val EVENT_CLIENT_HOME_BANNER_CLICK = "client.home.banner.click"
const val EVENT_CLIENT_OPEN_WX_UNIMP = "event_client_open_wx_unimp" const val EVENT_CLIENT_OPEN_WX_UNIMP = "event_client_open_wx_unimp"
const val EVENT_CLIENT_OPEN_ALIPAY_UNIMP = "event_client_open_alipay_unimp" const val EVENT_CLIENT_OPEN_ALIPAY_UNIMP = "event_client_open_alipay_unimp"
const val EVENT_CLIENT_UNI_FAIL = "client.uni.fail" const val EVENT_CLIENT_UNI_FAIL = "client.uni.fail"

View File

@ -5,6 +5,8 @@ import kotlinx.serialization.Serializable
@Serializable @Serializable
class ConfigEntity { class ConfigEntity {
@SerializedName("client.banner.home") //首页轮播图
var homeBanners: List<HomeBannerEntity?>? = emptyList()
@SerializedName("client.version.upgrade") //版本更新 @SerializedName("client.version.upgrade") //版本更新
var versionEntity: VersionEntity? = null var versionEntity: VersionEntity? = null
@SerializedName("client.uni.version.upgrade") //小程序模拟器 @SerializedName("client.uni.version.upgrade") //小程序模拟器

View File

@ -0,0 +1,21 @@
package com.img.rabbit.bean.response
import kotlinx.serialization.Serializable
/** client.banner.home,与 flaunt-android 的 HomeBannerBean 字段一致。 */
@Serializable
data class HomeBannerEntity(
val img: String? = null,
val url: String? = null,
val type: String? = null,
val enable: Boolean? = null,
val text: String? = null,
) {
companion object {
fun visibleItems(items: List<HomeBannerEntity?>?): List<HomeBannerEntity> =
items.orEmpty().filterNotNull().filter {
it.enable == true && !it.img.isNullOrBlank() &&
it.type in setOf("wx", "alipay", "app", "web")
}
}
}

View File

@ -0,0 +1,121 @@
package com.img.rabbit.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.repeatOnLifecycle
import coil3.compose.AsyncImage
import com.img.rabbit.R
import com.img.rabbit.bean.response.HomeBannerEntity
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
@Composable
fun HomeBanner(
banners: List<HomeBannerEntity>,
onClick: (HomeBannerEntity) -> Unit,
modifier: Modifier = Modifier,
) {
val fallback = painterResource(R.mipmap.ic_home_top_mask)
// 保持原顶部图片的宽高比,远程图片加载前后及兜底时布局不跳动。
val aspectRatio = fallback.intrinsicSize.width / fallback.intrinsicSize.height
if (banners.isEmpty()) {
Image(
painter = fallback,
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio),
)
return
}
// 配置更新时重新建立页码,避免数量减少后仍访问旧页面。
key(banners) {
val count = banners.size
val pageCount = if (count > 1) Int.MAX_VALUE else 1
val startPage = if (count > 1) Int.MAX_VALUE / 2 / count * count else 0
val pagerState = rememberPagerState(initialPage = startPage) { pageCount }
val pressSource = remember { MutableInteractionSource() }
val isPressed by pressSource.collectIsPressedAsState()
val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
val lifecycleOwner = LocalLifecycleOwner.current
LaunchedEffect(pagerState, lifecycleOwner, isPressed, isDragged) {
if (count <= 1 || isPressed || isDragged) return@LaunchedEffect
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
while (isActive) {
delay(3000)
if (!pagerState.isScrollInProgress) {
pagerState.animateScrollToPage((pagerState.currentPage + 1) % pageCount)
}
}
}
}
Box(modifier = modifier.fillMaxWidth().aspectRatio(aspectRatio)) {
HorizontalPager(
state = pagerState,
userScrollEnabled = count > 1,
modifier = Modifier.fillMaxSize(),
) { page ->
val item = banners[page % count]
AsyncImage(
model = item.img,
contentDescription = item.text,
placeholder = fallback,
error = fallback,
fallback = fallback,
contentScale = ContentScale.FillWidth,
modifier = Modifier.fillMaxSize().clickable(
interactionSource = pressSource,
indication = null,
) { onClick(item) },
)
}
Row(
modifier = Modifier.align(Alignment.BottomCenter)
// 下方内容有 18dp 的圆角重叠区,圆点放在其上方。
.padding(bottom = 30.dp)
.background(Color.Black.copy(alpha = 0.15f), CircleShape)
.padding(horizontal = 8.dp, vertical = 6.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
repeat(count) { index ->
Box(
modifier = Modifier.size(6.dp).background(
if (pagerState.currentPage % count == index) Color.White else Color.White.copy(alpha = 0.45f),
CircleShape,
)
)
}
}
}
}
}

View File

@ -32,7 +32,6 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@ -56,15 +55,21 @@ import androidx.navigation.compose.rememberNavController
import coil3.compose.AsyncImage import coil3.compose.AsyncImage
import com.img.rabbit.R import com.img.rabbit.R
import com.img.rabbit.bean.local.UIItemBean import com.img.rabbit.bean.local.UIItemBean
import com.img.rabbit.bean.request.ReportKey
import com.img.rabbit.bean.request.ReportRequest
import com.img.rabbit.bean.request.ReportType
import com.img.rabbit.bean.response.HomeBannerEntity
import com.img.rabbit.bean.response.UniVersionEntity import com.img.rabbit.bean.response.UniVersionEntity
import com.img.rabbit.components.CenterToast import com.img.rabbit.components.CenterToast
import com.img.rabbit.components.HomeBanner
import com.img.rabbit.pages.LoadingCallback import com.img.rabbit.pages.LoadingCallback
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.route.ScreenRoute import com.img.rabbit.route.ScreenRoute
import com.img.rabbit.route.HomeBannerRoutes
import com.img.rabbit.utils.GlobalEvent import com.img.rabbit.utils.GlobalEvent
import com.img.rabbit.utils.GlobalEventBus import com.img.rabbit.utils.GlobalEventBus
import com.img.rabbit.utils.UniAppUtils import com.img.rabbit.utils.UniAppUtils
import com.img.rabbit.utils.UniMpUpdate import com.img.rabbit.utils.UniMpUpdate
import com.img.rabbit.utils.UrlLinkUtils
import com.img.rabbit.viewmodel.GeneralViewModel import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel import com.img.rabbit.viewmodel.LoginViewModel
import com.img.rabbit.viewmodel.ReportViewModel import com.img.rabbit.viewmodel.ReportViewModel
@ -72,6 +77,7 @@ import io.dcloud.feature.sdk.DCUniMPSDK
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.json.JSONObject import org.json.JSONObject
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import kotlin.collections.chunked import kotlin.collections.chunked
/** /**
@ -153,13 +159,11 @@ fun HomeScreen(
} }
} }
var homeIconConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.homeIconEntity) } val userConfig = loginViewModel.userConfig.value?.config
var uniVersionConfig by remember { mutableStateOf(PreferenceUtil.getUserConfig()?.config?.uniVersionEntity) } val homeIconConfig = userConfig?.homeIconEntity
LaunchedEffect(loginViewModel.userConfigResult.value) { val uniVersionConfig = userConfig?.uniVersionEntity
if(loginViewModel.userConfigResult.value != null){ val homeBanners = remember(userConfig?.homeBanners) {
homeIconConfig = PreferenceUtil.getUserConfig()?.config?.homeIconEntity HomeBannerEntity.visibleItems(userConfig?.homeBanners)
uniVersionConfig = PreferenceUtil.getUserConfig()?.config?.uniVersionEntity
}
} }
Column( Column(
@ -177,13 +181,59 @@ fun HomeScreen(
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp) shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp)
) )
){ ){
// 顶部mask // 顶部轮播,无配置和加载失败时使用原顶部图片兜底。
item { item(key = "home_banner") {
Image( HomeBanner(
painter = painterResource(id = R.mipmap.ic_home_top_mask), banners = homeBanners,
contentDescription = null, onClick = { banner ->
contentScale = ContentScale.FillWidth, val type = banner.type.orEmpty()
modifier = Modifier.fillMaxWidth() val url = banner.url.orEmpty()
reportViewModel.requestReport(ReportRequest(
type = ReportType.CLICK,
key = ReportKey.EVENT_CLIENT_HOME_BANNER_CLICK,
value = type,
extra = url,
))
when (type) {
"wx", "alipay" -> {
if (loginViewModel.requiredLogin()) {
val version = uniVersionConfig?.firstOrNull { it.unimp_type == type }
if (version == null) {
CenterToast.show("功能暂不可用,请稍后重试")
} else {
dealUniMpDownloadLaunch(
context, scope, version, progressPair,
reportViewModel, loadingCallback,
pagePath = url.takeIf { it.isNotBlank() },
itemName = banner.text?.takeIf { it.isNotBlank() } ?: "home",
)
}
}
}
"web" -> {
if (url.isNotBlank()) {
if (url.toHttpUrlOrNull() != null) {
UrlLinkUtils.openAgreement(context, banner.text.orEmpty(), url)
} else {
CenterToast.show("链接暂不可用")
}
}
}
"app" -> {
if (url.isNotBlank()) {
val route = HomeBannerRoutes.resolve(url)
if (route == null) {
CenterToast.show("功能暂不可用,请稍后重试")
} else {
generalViewModel.setNavigationBarVisible(
route == ScreenRoute.Home.route || route == ScreenRoute.Mine.route
)
navController.navigate(route) { launchSingleTop = true }
}
}
}
}
},
) )
Column( Column(
modifier = Modifier modifier = Modifier
@ -199,7 +249,7 @@ fun HomeScreen(
} }
// 当配置开启模拟器时,展示模拟器部分 // 当配置开启模拟器时,展示模拟器部分
if(PreferenceUtil.getUserConfig()?.config?.isUniMpOpen?:false){ if(userConfig?.isUniMpOpen == true){
//模拟器部分,大于9时,每排展示3个,否则每排展示4个 //模拟器部分,大于9时,每排展示3个,否则每排展示4个
val columnsCount = if((homeIconConfig?.size?:0) >= 9){ 3 }else{ 4 } val columnsCount = if((homeIconConfig?.size?:0) >= 9){ 3 }else{ 4 }
val rows = homeIconConfig?.chunked(columnsCount)?:emptyList() val rows = homeIconConfig?.chunked(columnsCount)?:emptyList()
@ -406,7 +456,7 @@ fun HomeScreen(
} }
val uniVersion = val uniVersion =
PreferenceUtil.getUserConfig()?.config?.uniVersionEntity?.firstOrNull { it.unimp_type == item.type } uniVersionConfig?.firstOrNull { it.unimp_type == item.type }
if(uniVersion == null){ if(uniVersion == null){
CenterToast.show("无可用资源...") CenterToast.show("无可用资源...")
return@clickable return@clickable

View File

@ -0,0 +1,15 @@
package com.img.rabbit.route
/** 仅允许跳转宿主已注册的原生页面,未知配置不传给 NavController。 */
internal object HomeBannerRoutes {
private val routes = setOf(
ScreenRoute.Home.route, ScreenRoute.Mine.route,
ScreenRoute.Cutout.route, ScreenRoute.Resize.route, ScreenRoute.Format.route,
ScreenRoute.CameraGuide.route, ScreenRoute.LongImage.route,
ScreenRoute.Feedback.route, ScreenRoute.Login.route, ScreenRoute.Setting.route,
ScreenRoute.BindAccount.route, ScreenRoute.ManagerAccount.route,
ScreenRoute.AboutMine.route, ScreenRoute.DeleteAccount.route,
)
fun resolve(route: String?): String? = route?.takeIf { it in routes }
}

View File

@ -83,6 +83,9 @@ class LoginViewModel : BaseViewModel() {
val loginResult = mutableStateOf<ResultVo<LoginInfoEntity>?>(null) val loginResult = mutableStateOf<ResultVo<LoginInfoEntity>?>(null)
// 用户配置获取结果 // 用户配置获取结果
val userConfigResult = mutableStateOf<ResultVo<UserConfigEntity>?>(null) val userConfigResult = mutableStateOf<ResultVo<UserConfigEntity>?>(null)
// 保留最新配置供首页观察;userConfigResult 作为请求完成事件会被 Activity 清空。
private val _userConfig = mutableStateOf(PreferenceUtil.getUserConfig())
val userConfig: State<UserConfigEntity?> = _userConfig
// 用户信息获取结果 // 用户信息获取结果
val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null) val userInfoResult = mutableStateOf<ResultVo<UserInfoEntity>?>(null)
// 错误状态 // 错误状态
@ -113,6 +116,7 @@ class LoginViewModel : BaseViewModel() {
PreferenceUtil.saveXToken(response.data.token) PreferenceUtil.saveXToken(response.data.token)
PreferenceUtil.setTimeDiff(response.data.nowtime.toLong() - System.currentTimeMillis() / 1000) PreferenceUtil.setTimeDiff(response.data.nowtime.toLong() - System.currentTimeMillis() / 1000)
PreferenceUtil.saveUserConfig(response.data) PreferenceUtil.saveUserConfig(response.data)
_userConfig.value = response.data
userConfigResult.value = response userConfigResult.value = response
if(isInitConfig){ if(isInitConfig){
@ -435,4 +439,4 @@ class LoginViewModel : BaseViewModel() {
FROM_ADD(1,"添加账号"), FROM_ADD(1,"添加账号"),
FROM_LOGOUT(2,"退出登录") FROM_LOGOUT(2,"退出登录")
} }
} }