/** * 第 10 章配套代码 · 笔记卡片可复用组件 * * 文件位置:shared/src/commonMain/kotlin/com/example/xhs/components/NoteCard.kt * * 演示如何把通用 UI 块抽成 ViewBuilder 函数复用。 */ package com.example.xhs.components import com.example.xhs.pages.Note import com.example.xhs.store.NoteStore import com.example.xhs.store.ThemeStore import com.tencent.kuikly.core.base.Color import com.tencent.kuikly.core.base.ViewBuilder import com.tencent.kuikly.core.views.Image import com.tencent.kuikly.core.views.Text import com.tencent.kuikly.core.views.View /** * 笔记卡片(瀑布流的 item) * @param note 笔记数据 * @param onClick 点击卡片回调(一般跳转详情) */ fun NoteCard(note: Note, onClick: () -> Unit): ViewBuilder = { View { attr { backgroundColor( if (ThemeStore.darkMode) Color(0xFF1E1E1EL) else Color.WHITE ) borderRadius(8f) } event { click { onClick() } } // ─── 封面图 ───── Image { attr { src(note.coverUrl) width(174f) height(note.coverHeight) backgroundColor(Color(0xFFE0E0E0L)) borderRadius(8f) } } // ─── 标题 ───── Text { attr { text(note.title) fontSize(13f) color(if (ThemeStore.darkMode) Color.WHITE else Color.BLACK) padding(8f) numberOfLines(2) lineHeight(18f) } } // ─── 底部:作者 + 点赞数 ───── View { attr { flexDirectionRow() alignItemsCenter() paddingHorizontal(8f) paddingBottom(8f) justifyContentSpaceBetween() } // 左:头像 + 昵称 View { attr { flexDirectionRow(); alignItemsCenter(); flex(1f) } Image { attr { src(note.authorAvatar) size(16f, 16f) borderRadius(8f) backgroundColor(Color(0xFFE0E0E0L)) marginRight(4f) } } Text { attr { text(note.authorName) fontSize(11f) color(Color(0xFF9E9E9EL)) flex(1f) numberOfLines(1) textOverFlowEllipsis() } } } // 右:点赞按钮(点击切换) View { attr { flexDirectionRow(); alignItemsCenter() } event { click { // ★ 阻止点击穿透到外层卡片 NoteStore.toggleLike(note.id) } } Text { attr { text(if (note.liked) "♥" else "♡") fontSize(13f) color(if (note.liked) Color(0xFFFF2442L) else Color(0xFF9E9E9EL)) marginRight(2f) } } Text { attr { text(formatCount(note.likes)) fontSize(11f) color(Color(0xFF9E9E9EL)) } } } } } } /** 格式化数字:1234 → 1.2k */ private fun formatCount(n: Int): String = when { n >= 10000 -> "${n / 1000 / 10.0}w" n >= 1000 -> "${n / 1000.0}k" else -> n.toString() }