code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
import request from '@/utils/request'
export const userRegisterService = ({ username, password, repassword }) =>
request.post('/api/reg', { username, password, repassword })
export const userLoginService = ({ username, password }) =>
request.post('/api/login', { username, password })
export const userGetInfoService = () => request.get('/my/userinfo')
| 2302_81331056/big-event | src/api/user.js | JavaScript | unknown | 360 |
body {
margin: 0;
background-color: #f5f5f5;
}
/* fade-slide */
.fade-slide-leave-active,
.fade-slide-enter-active {
transition: all 0.3s;
}
.fade-slide-enter-from {
transform: translateX(-30px);
opacity: 0;
}
.fade-slide-leave-to {
transform: translateX(30px);
opacity: 0;
} | 2302_81331056/big-event | src/assets/main.scss | SCSS | unknown | 292 |
<script setup>
defineProps({
title: {
required: true,
type: String
}
})
</script>
<template>
<el-card class="page-container">
<template #header>
<div class="header">
<span>{{ title }}</span>
<div class="extra">
<slot name="extra"></slot>
</div>
</div>
</template>
<slot></slot>
</el-card>
</template>
<style lang="scss" scoped>
.page-container {
min-height: 100%;
box-sizing: border-box;
.header {
display: flex;
justify-content: space-between;
align-items: center;
}
}
</style>
| 2302_81331056/big-event | src/components/PageContainer.vue | Vue | unknown | 575 |
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from '@/stores/index'
import '@/assets/main.scss'
const app = createApp(App)
app.use(pinia)
app.use(router)
app.mount('#app')
| 2302_81331056/big-event | src/main.js | JavaScript | unknown | 231 |
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
const router = createRouter({
// 不带# 另一个是哈希模式带#
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: '/login', component: () => import('@/views/login/loginPage.vue') },
{
path: '/',
component: () => import('@/views/layout/layoutContainer.vue'),
redirect: '/article/manage',
children: [
{
path: '/article/manage',
component: () => import('@/views/article/articleManage.vue')
},
{
path: '/article/channel',
component: () => import('@/views/article/articleChannel.vue')
},
{
path: '/user/profile',
component: () => import('@/views/user/userProfile.vue')
},
{
path: '/user/password',
component: () => import('@/views/user/userPassword.vue')
},
{
path: '/user/avatar',
component: () => import('@/views/user/userAvatar.vue')
}
]
}
]
})
// 访问拦截
router.beforeEach((to) => {
const userStore = useUserStore()
if (!userStore.token && to.path !== '/login') return '/login'
})
export default router
| 2302_81331056/big-event | src/router/index.js | JavaScript | unknown | 1,271 |
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(persist)
export default pinia
export * from './modules/user'
| 2302_81331056/big-event | src/stores/index.js | JavaScript | unknown | 188 |
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoService } from '@/api/user'
export const useUserStore = defineStore(
'big-user',
() => {
const token = ref('')
const setToken = (newToken) => {
token.value = newToken
}
const removeToken = () => {
token.value = ''
}
const user = ref({})
const getUser = async () => {
const res = await userGetInfoService()
user.value = res.data.data
}
const setUser = (obj) => {
user.value = obj
}
return {
token,
setToken,
removeToken,
user,
getUser,
setUser
}
},
{
persist: true
}
)
| 2302_81331056/big-event | src/stores/modules/user.js | JavaScript | unknown | 681 |
import { dayjs } from 'element-plus'
export const formatTime = (time) => dayjs(time).format('YYYY年MM月DD日')
| 2302_81331056/big-event | src/utils/format.js | JavaScript | unknown | 114 |
import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'
const baseURL = 'http://big-event-vue-api-t.itheima.net'
const instance = axios.create({
// TODO 1. 基础地址,超时时间
baseURL,
timeout: 10000
})
instance.interceptors.request.use(
(config) => {
// TODO 2. 携带token
const userStore = useUserStore()
if (userStore.token) {
config.headers.Authorization = userStore.token
}
return config
},
(err) => Promise.reject(err)
)
instance.interceptors.response.use(
(res) => {
// TODO 3. 处理业务失败
// TODO 4. 摘取核心响应数据
if (res.data.code === 0) {
return res
}
ElMessage.error(res.data.message || '服务异常')
return Promise.reject(res.data)
},
(err) => {
// TODO 5. 处理401错误
if (err.response?.status === 401) {
router.push('/login')
}
ElMessage.error(err.response.value.message || '服务异常')
return Promise.reject(err)
}
)
export default instance
export { baseURL }
| 2302_81331056/big-event | src/utils/request.js | JavaScript | unknown | 1,099 |
<script setup>
import { ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import { artDelChannelService, artGetChannelsService } from '@/api/article'
import ChannelEdit from './components/ChannelEdit.vue'
const loading = ref(false)
const channelList = ref([])
const dialog = ref()
const getChannelList = async () => {
loading.value = true
const res = await artGetChannelsService()
channelList.value = res.data.data
loading.value = false
}
getChannelList()
const onDelChannel = async (row) => {
await ElMessageBox.confirm('你确认删除该分类吗?', '温馨提示', {
type: 'warning',
confirmButtonText: '确认',
cancelButtonText: '取消'
})
await artDelChannelService(row.id)
ElMessage.success('删除成功')
getChannelList()
}
const onEditChannel = (row) => {
dialog.value.open(row)
}
const onAddChannel = () => {
dialog.value.open({})
}
getChannelList()
const onSuccess = () => [getChannelList()]
</script>
<template>
<page-container title="文章分类">
<template #extra>
<el-button type="primary" @click="onAddChannel">添加分类</el-button>
</template>
<el-table v-loading="loading" :data="channelList" style="width: 100%">
<el-table-column type="index" label="序号" width="100"></el-table-column>
<el-table-column prop="cate_name" label="分类名称"></el-table-column>
<el-table-column prop="cate_alias" label="分类别名"></el-table-column>
<el-table-column label="操作" width="100">
<template #default="{ row, $index }">
<el-button
:icon="Edit"
circle
plain
type="primary"
@click="onEditChannel(row, $index)"
></el-button>
<el-button
:icon="Delete"
circle
plain
type="danger"
@click="onDelChannel(row, $index)"
></el-button>
</template>
</el-table-column>
<template #empty>
<el-empty description="没有数据"></el-empty>
</template>
</el-table>
<channel-edit ref="dialog" @success="onSuccess"></channel-edit>
</page-container>
</template>
<style></style>
| 2302_81331056/big-event | src/views/article/articleChannel.vue | Vue | unknown | 2,202 |
<script setup>
import { ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import ChannelSelect from './components/ChannelSelect.vue'
import ArticleEdit from './components/ArticleEdit.vue'
import { artDelService, artGetListService } from '@/api/article.js'
import { formatTime } from '@/utils/format'
const articleList = ref([])
const total = ref(0)
const loading = ref(false)
const params = ref({
pagenum: 1,
pagesize: 5,
cate_id: '',
state: ''
})
defineProps({
modelValue: {
type: [Number, String]
},
width: {
type: String
}
})
const getArticleList = async () => {
loading.value = true
const res = await artGetListService(params.value)
articleList.value = res.data.data
total.value = res.data.total
loading.value = false
}
getArticleList()
const onSizeChange = (size) => {
params.value.pagenum = 1
params.value.pagesize = size
getArticleList()
}
const onCurrentChange = (page) => {
params.value.pagenum = page
getArticleList()
}
const onSearch = () => {
params.value.pagenum = 1
getArticleList()
}
const onReset = () => {
params.value.pagenum = 1
params.value.cate_id = ''
params.value.state = ''
getArticleList()
}
const articleEditRef = ref()
const onAddArticle = () => {
articleEditRef.value.open({})
}
const onEditArticle = (row) => {
articleEditRef.value.open(row)
}
const onSuccess = (type) => {
if (type === 'add') {
const lastPage = Math.ceil((total.value + 1) / params.value.pagesize)
params.value.pagenum = lastPage
}
getArticleList()
}
// 删除
const onDeleteArticle = async (row) => {
await ElMessageBox.confirm('你确认删除该文章信息吗?', '温馨提示', {
type: 'waring',
confirmButtonText: '确认',
cancelButtonText: '取消'
})
await artDelService(row.id)
ElMessage({ type: 'success', message: '删除成功' })
getArticleList()
}
</script>
<template>
<page-container title="文章管理">
<template #extra>
<el-button type="primary" @click="onAddArticle">添加文章</el-button>
</template>
<!-- 表单区域 -->
<el-form inline>
<el-form-item label="文章分类:">
<!-- Vue2 => v-model :value 和 @input 的简写 -->
<!-- Vue3 => v-model :modelValue 和 @update:modelValue 的简写 -->
<channel-select v-model="params.cate_id"></channel-select>
<!-- Vue3 => v-model:cid :cid 和 @update:cid 的简写 -->
<!-- <channel-select v-model:cid="params.cate_id"></channel-select> -->
</el-form-item>
<el-form-item label="发布状态:">
<!-- 这里后台标记发布状态,就是通过中文标记的,已发布 / 草稿 -->
<el-select v-model="params.state">
<el-option label="已发布" value="已发布"></el-option>
<el-option label="草稿" value="草稿"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button @click="onSearch" type="primary">搜索</el-button>
<el-button @click="onReset">重置</el-button>
</el-form-item>
</el-form>
<!-- 表格区域 -->
<el-table :data="articleList" v-loading="loading">
<el-table-column label="文章标题" prop="title">
<template #default="{ row }">
<el-link type="primary" :underline="false">{{ row.title }}</el-link>
</template>
</el-table-column>
<el-table-column label="分类" prop="cate_name"></el-table-column>
<el-table-column label="发表时间" prop="pub_date">
<template #default="{ row }">
{{ formatTime(row.pub_date) }}
</template>
</el-table-column>
<el-table-column label="状态" prop="state"></el-table-column>
<!-- 利用作用域插槽 row 可以获取当前行的数据 => v-for 遍历 item -->
<el-table-column label="操作">
<template #default="{ row }">
<el-button
circle
plain
type="primary"
:icon="Edit"
@click="onEditArticle(row)"
></el-button>
<el-button
circle
plain
type="danger"
:icon="Delete"
@click="onDeleteArticle(row)"
></el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页区域 -->
<el-pagination
v-model:current-page="params.pagenum"
v-model:page-size="params.pagesize"
:page-sizes="[2, 3, 5, 10]"
:background="true"
layout="jumper, total, sizes, prev, pager, next"
:total="total"
@size-change="onSizeChange"
@current-change="onCurrentChange"
style="margin-top: 20px; justify-content: flex-end"
/>
<!-- 添加编辑的抽屉 -->
<article-edit ref="articleEditRef" @success="onSuccess"></article-edit>
</page-container>
</template>
<style lang="scss" scoped></style>
| 2302_81331056/big-event | src/views/article/articleManage.vue | Vue | unknown | 4,883 |
<script setup>
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { artPublishService, artGetDetailService } from '@/api/article'
import { baseURL } from '@/utils/request'
import axios from 'axios'
const visibleDrawer = ref(false)
const defaultForm = {
title: '',
cate_id: '',
cover_img: '',
content: '',
state: ''
}
const formModel = ref({ ...defaultForm })
// 上传部分
const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
imgUrl.value = URL.createObjectURL(uploadFile.raw)
formModel.value.cover_img = uploadFile.raw
}
const emit = defineEmits(['success'])
const onPublish = async (state) => {
formModel.value.state = state
const fd = new FormData()
for (let key in formModel.value) {
fd.append(key, formModel.value[key])
}
if (formModel.value.id) {
console.log('编辑操作')
} else {
await artPublishService(fd)
ElMessage.success('添加成功')
visibleDrawer.value = false
emit('success', 'add')
}
}
// 向外暴露
const editorRef = ref()
const open = async (row) => {
visibleDrawer.value = true
if (row.id) {
console.log('编辑回显')
const res = await artGetDetailService(row.id)
formModel.value = res.data.data
imgUrl.value = baseURL + formModel.value.cover_img
const file = await imageUrlToFileObject(
imgUrl.value,
formModel.value.cover_img
)
formModel.value.cover_img = file
} else {
formModel.value = { ...defaultForm }
imgUrl.value = ''
editorRef.value.setHTML('')
}
}
// 将网络图片地址转换为 File 对象的函数
async function imageUrlToFileObject(imageUrl, filename) {
try {
// 使用 Axios 下载图片数据
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' })
// 将下载的数据转换成 Blob 对象
const blob = new Blob([response.data], {
type: response.headers['content-type']
})
// 创建 File 对象
const file = new File([blob], filename, {
type: response.headers['content-type']
})
return file
} catch (error) {
console.error('Error converting image URL to File object:', error)
return null
}
}
defineExpose({
open
})
</script>
<template>
<el-drawer
v-model="visibleDrawer"
:title="formModel.id ? '编辑文章' : '添加文章'"
direction="rtl"
size="50%"
>
<!-- 发表文章表单 -->
<el-form :model="formModel" ref="formRef" label-width="100px">
<el-form-item label="文章标题" prop="title">
<el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
</el-form-item>
<el-form-item label="文章分类" prop="cate_id">
<channel-select
v-model="formModel.cate_id"
width="100%"
></channel-select>
</el-form-item>
<el-form-item label="文章封面" prop="cover_img">
<el-upload
class="avatar-uploader"
:auto-upload="false"
:show-file-list="false"
:on-change="onUploadFile"
>
<img v-if="imgUrl" :src="imgUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</el-form-item>
<el-form-item label="文章内容" prop="content">
<div class="editor">
<quill-editor
ref="editorRef"
theme="snow"
v-model:content="formModel.content"
contentType="html"
>
</quill-editor>
</div>
</el-form-item>
<el-form-item>
<el-button @click="onPublish('已发布')" type="primary">发布</el-button>
<el-button @click="onPublish('草稿')" type="info">草稿</el-button>
</el-form-item>
</el-form>
</el-drawer>
</template>
<style lang="scss" scoped>
.avatar-uploader {
:deep() {
.avatar {
width: 178px;
height: 178px;
display: block;
}
.el-upload {
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.el-upload:hover {
border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
text-align: center;
}
}
}
.editor {
width: 100%;
:deep(.ql-editor) {
min-height: 200px;
}
}
</style>
| 2302_81331056/big-event | src/views/article/components/ArticleEdit.vue | Vue | unknown | 4,625 |
<script setup>
import { ref } from 'vue'
import { artAddChannelService, artEditChannelService } from '@/api/article'
const dialogVisible = ref(false)
const formRef = ref()
const open = async (row) => {
dialogVisible.value = true
formModel.value = { ...row }
}
defineExpose({
open
})
const formModel = ref({
cate_name: '',
cate_alias: ''
})
const rules = {
cate_name: [
{ required: true, message: '请输入分类名称', trigger: 'blur' },
{
pattern: /^\S{1,10}$/,
message: '分类名必须是1~10位的非空字符',
trigger: 'blur'
}
],
cate_alias: [
{ required: true, message: '请输入分类别名', trigger: 'blur' },
{
pattern: /^[a-zA-Z0-9]{1,15}$/,
message: '分类别名必须是1-15位的数字或字母',
trigger: 'blur'
}
]
}
const emit = defineEmits(['success'])
const onSubmit = async () => {
await formRef.value.validate()
formModel.value.id
? await artEditChannelService(formModel.value)
: await artAddChannelService(formModel.value)
ElMessage({
type: 'success',
message: formModel.value.id ? '编辑成功' : '添加成功'
})
dialogVisible.value = false
emit('success')
}
</script>
<template>
<el-dialog
v-model="dialogVisible"
:title="formModel.id ? '编辑分类' : '添加分类'"
width="30%"
>
<el-form
ref="formRef"
:model="formModel"
:rules="rules"
label-width="100px"
style="padding-right: 30px"
>
<el-form-item label="分类名称" prop="cate_name">
<el-input v-model="formModel.cate_name" placeholder="请输入分类名称:">
</el-input>
</el-form-item>
<el-form-item label="分类别名" prop="cate_alias">
<el-input v-model="formModel.cate_alias" placeholder="请输入分类别名:">
</el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="onSubmit"> 确认 </el-button>
</span>
</template>
</el-dialog>
</template>
| 2302_81331056/big-event | src/views/article/components/ChannelEdit.vue | Vue | unknown | 2,135 |
<script setup>
import { artGetChannelsService } from '@/api/article.js'
import { ref } from 'vue'
defineProps({
modelValue: {
type: [Number, String]
}
})
const emit = defineEmits(['update:modelValue'])
const channelList = ref([])
const getChannelList = async () => {
const res = await artGetChannelsService()
channelList.value = res.data.data
}
getChannelList()
</script>
<template>
<el-select
style="width: 200px"
:modelValue="modelValue"
@update:modelValue="emit('update:modelValue', $event)"
>
<el-option
v-for="channel in channelList"
:key="channel.id"
:label="channel.cate_name"
:value="channel.id"
></el-option>
</el-select>
</template>
<style></style>
| 2302_81331056/big-event | src/views/article/components/ChannelSelect.vue | Vue | unknown | 724 |
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { userRegisterService, userLoginService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const isRegister = ref(true)
const form = ref()
const router = useRouter()
const userStore = useUserStore()
const formModel = ref({
username: '',
password: '',
repassword: ''
})
const register = async () => {
await form.value.validate()
await userRegisterService(formModel.value)
ElMessage.success('注册成功')
isRegister.value = false
}
watch(isRegister, () => {
formModel.value = {
username: '',
password: '',
repassword: ''
}
})
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{
pattern: /^\S{6,15}$/,
message: '密码必须是6-15位的非空字符',
trigger: 'blur'
}
],
repassword: [
{ required: true, message: '请再次输入密码', trigger: 'blur' },
{
pattern: /^\S{6,15}$/,
message: '密码必须是6-15的非空字符',
trigger: 'blur'
},
{
validator: (rule, value, callback) => {
if (value !== formModel.value.password) {
callback(new Error('两次输入不一致'))
} else {
callback()
}
},
trigger: 'blur'
}
]
}
const login = async () => {
await form.value.validate()
const res = await userLoginService(formModel.value)
console.log(res.data.token)
userStore.setToken(res.data.token)
ElMessage.success('登录成功')
router.push('/')
}
</script>
<template>
<el-row class="login-page">
<el-col :span="12" class="bg"></el-col>
<el-col :span="6" :offset="3" class="form">
<el-form
size="large"
autocomplete="off"
v-if="isRegister"
:model="formModel"
:rules="rules"
ref="form"
>
<el-form-item>
<h1>注册</h1>
</el-form-item>
<el-form-item prop="username">
<el-input
:prefix-icon="User"
placeholder="请输入用户名"
v-model="formModel.username"
></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
v-model="formModel.password"
></el-input>
</el-form-item>
<el-form-item prop="repassword">
<el-input
:prefix-icon="Lock"
type="password"
placeholder="请输入再次密码"
v-model="formModel.repassword"
></el-input>
</el-form-item>
<el-form-item>
<el-button
class="button"
type="primary"
auto-insert-space
@click="register"
>
注册
</el-button>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = false">
← 返回
</el-link>
</el-form-item>
</el-form>
<el-form
ref="form"
size="large"
autocomplete="off"
v-else
:model="formModel"
:rules="rules"
>
<el-form-item>
<h1>登录</h1>
</el-form-item>
<el-form-item prop="username">
<el-input
:prefix-icon="User"
placeholder="请输入用户名"
v-model="formModel.username"
></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
name="password"
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
v-model="formModel.password"
></el-input>
</el-form-item>
<el-form-item class="flex">
<div class="flex">
<el-checkbox>记住我</el-checkbox>
<el-link type="primary" :underline="false">忘记密码?</el-link>
</div>
</el-form-item>
<el-form-item>
<el-button
class="button"
type="primary"
auto-insert-space
@click="login"
>登录</el-button
>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = true">
注册 →
</el-link>
</el-form-item>
</el-form>
</el-col>
</el-row>
</template>
<style lang="scss" scoped>
.login-page {
height: 100vh;
background-color: #fff;
.bg {
background:
url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
url('@/assets/login_bg.jpg') no-repeat center / cover;
border-radius: 0 20px 20px 0;
}
.form {
display: flex;
flex-direction: column;
justify-content: center;
user-select: none;
.title {
margin: 0 auto;
}
.button {
width: 100%;
}
.flex {
width: 100%;
display: flex;
justify-content: space-between;
}
}
}
</style>
| 2302_81331056/big-event | src/views/login/loginPage.vue | Vue | unknown | 5,358 |
<script setup></script>
<template>
<div>个人页面</div>
</template>
<style></style>
| 2302_81331056/big-event | src/views/user/userAvatar.vue | Vue | unknown | 91 |
<script setup></script>
<template>
<div>个人密码</div>
</template>
<style></style>
| 2302_81331056/big-event | src/views/user/userPassword.vue | Vue | unknown | 91 |
<script setup></script>
<template>
<div>个人信息</div>
</template>
<style></style>
| 2302_81331056/big-event | src/views/user/userProfile.vue | Vue | unknown | 91 |
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()]
}),
Components({
resolvers: [ElementPlusResolver()]
})
],
base: '/',
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
| 2302_81331056/big-event | vite.config.js | JavaScript | unknown | 631 |
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轻松一刻 - 动态风景</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background: linear-gradient(to bottom, #87CEEB, #E0F7FF);
font-family: "Microsoft YaHei", sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
display: block;
max-width: 100%;
max-height: 100%;
}
.container {
position: relative;
width: 100%;
height: 100%;
}
.message {
position: absolute;
top: 20px;
left: 0;
width: 100%;
text-align: center;
color: white;
font-size: 18px;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
z-index: 10;
opacity: 0.8;
}
</style>
</head>
<body>
<div class="container">
<div class="message">轻松一刻 · 动态风景</div>
<canvas id="landscape"></canvas>
</div>
<script>
const canvas = document.getElementById('landscape');
const ctx = canvas.getContext('2d');
// 设置画布尺寸
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// 云朵类
class Cloud {
constructor(x, y, size, speed) {
this.x = x;
this.y = y;
this.size = size;
this.speed = speed;
this.opacity = 0.7 + Math.random() * 0.3;
}
update() {
this.x += this.speed;
if (this.x > canvas.width + this.size * 100) {
this.x = -this.size * 100;
}
}
draw() {
ctx.save();
ctx.globalAlpha = this.opacity;
ctx.fillStyle = '#ffffff';
// 绘制云朵形状
for (let i = 0; i < 3; i++) {
ctx.beginPath();
ctx.arc(
this.x + i * this.size * 20,
this.y,
this.size * 15 + i * 5,
0,
Math.PI * 2
);
ctx.fill();
}
for (let i = 0; i < 2; i++) {
ctx.beginPath();
ctx.arc(
this.x + this.size * 20 + i * this.size * 15,
this.y - this.size * 10,
this.size * 12 + i * 3,
0,
Math.PI * 2
);
ctx.fill();
}
ctx.restore();
}
}
// 草地类
class Grass {
constructor(x, baseY, height, waveSpeed, waveAmplitude) {
this.x = x;
this.baseY = baseY;
this.height = height;
this.waveSpeed = waveSpeed;
this.waveAmplitude = waveAmplitude;
this.time = Math.random() * Math.PI * 2;
}
update(deltaTime) {
this.time += this.waveSpeed * deltaTime;
}
draw() {
const sway = Math.sin(this.time) * this.waveAmplitude;
ctx.beginPath();
ctx.moveTo(this.x, this.baseY);
ctx.quadraticCurveTo(
this.x + sway,
this.baseY - this.height / 2,
this.x + sway * 2,
this.baseY - this.height
);
ctx.strokeStyle = '#2d5a2d';
ctx.lineWidth = 2;
ctx.stroke();
// 添加草叶顶部
ctx.beginPath();
ctx.arc(this.x + sway * 2, this.baseY - this.height, 2, 0, Math.PI * 2);
ctx.fillStyle = '#3a7a3a';
ctx.fill();
}
}
// 初始化云朵
const clouds = [];
for (let i = 0; i < 5; i++) {
clouds.push(new Cloud(
Math.random() * canvas.width,
50 + Math.random() * 150,
0.5 + Math.random() * 0.5,
0.2 + Math.random() * 0.3
));
}
// 初始化草地
const grasses = [];
const grassBaseY = canvas.height * 0.7;
for (let i = 0; i < canvas.width; i += 3) {
grasses.push(new Grass(
i,
grassBaseY + Math.random() * 50,
30 + Math.random() * 40,
0.5 + Math.random() * 0.5,
3 + Math.random() * 5
));
}
// 动画循环
let lastTime = 0;
function animate(currentTime) {
const deltaTime = (currentTime - lastTime) / 1000;
lastTime = currentTime;
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制天空渐变
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, '#87CEEB');
gradient.addColorStop(0.7, '#E0F7FF');
gradient.addColorStop(1, '#ffffff');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制太阳
ctx.beginPath();
ctx.arc(canvas.width * 0.8, canvas.height * 0.2, 40, 0, Math.PI * 2);
ctx.fillStyle = '#FFD700';
ctx.fill();
// 太阳光晕
ctx.beginPath();
ctx.arc(canvas.width * 0.8, canvas.height * 0.2, 60, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(255, 215, 0, 0.3)';
ctx.fill();
// 更新和绘制云朵
clouds.forEach(cloud => {
cloud.update();
cloud.draw();
});
// 绘制地面
ctx.fillStyle = '#8B7355';
ctx.fillRect(0, grassBaseY, canvas.width, canvas.height - grassBaseY);
// 绘制草地底色
ctx.fillStyle = '#4a7c4a';
ctx.fillRect(0, grassBaseY - 20, canvas.width, 30);
// 更新和绘制草地
grasses.forEach(grass => {
grass.update(deltaTime);
grass.draw();
});
// 绘制远山轮廓
ctx.fillStyle = '#6B8E6B';
ctx.beginPath();
ctx.moveTo(0, grassBaseY - 50);
for (let x = 0; x <= canvas.width; x += 50) {
const height = 30 + Math.sin(x * 0.01) * 20;
ctx.lineTo(x, grassBaseY - 50 - height);
}
ctx.lineTo(canvas.width, grassBaseY);
ctx.lineTo(0, grassBaseY);
ctx.fill();
requestAnimationFrame(animate);
}
// 启动动画
animate(0);
</script>
</body>
</html>
| 2302_81448387/aa | index.html | HTML | unknown | 7,577 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
def assign_cluster(x, c):
"""
将样本 x 分配到最近的聚类中心
"""
distances = np.linalg.norm(x[:, np.newaxis] - c, axis=2) # shape: (n_samples, K)
y = np.argmin(distances, axis=1)
return y
def Kmean(data, K, epsilon=1e-4, max_iteration=100):
"""
K-Means 聚类算法
"""
n_samples, n_features = data.shape
np.random.seed(42)
centers = data[np.random.choice(n_samples, K, replace=False)]
for i in range(max_iteration):
# Step 1: 分配簇
labels = assign_cluster(data, centers)
# Step 2: 更新中心
new_centers = np.array([
data[labels == k].mean(axis=0) if np.any(labels == k) else centers[k]
for k in range(K)
])
# Step 3: 判断收敛
shift = np.linalg.norm(new_centers - centers)
if shift < epsilon:
print(f"第 {i+1} 次迭代后收敛,中心移动量 {shift:.6f}")
break
centers = new_centers
return centers, labels
if __name__ == "__main__":
# 生成二维数据
data, _ = make_blobs(n_samples=200, centers=3, n_features=2, random_state=42)
centers, labels = Kmean(data, K=3)
print("最终聚类中心:\n", centers)
# ======================
# 可视化
# ======================
plt.figure(figsize=(8, 6))
# 绘制每个簇的样本点
for k in range(3):
plt.scatter(data[labels == k, 0], data[labels == k, 1], label=f'Cluster {k}', alpha=0.6)
# 绘制中心点
plt.scatter(centers[:, 0], centers[:, 1], c='black', s=200, marker='X', label='Centers')
plt.title("K-Means Clustering Result")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.grid(True)
plt.show()
| 2302_81501109/machine-learning-course | assignment3/2班70.py | Python | mit | 1,862 |
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # 兼容 PyCharm 绘图后端
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 解决中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# =======================
# 距离函数:闵可夫斯基距离
# =======================
def minkowski_distance(a, b, p=2):
return np.sum(np.abs(a - b) ** p) ** (1 / p)
# =======================
# 自定义 KNN 分类器
# =======================
class KNN:
def __init__(self, k=3, label_num=None, p=2):
self.k = k
self.label_num = label_num
self.p = p # p=1 曼哈顿距离, p=2 欧氏距离
def fit(self, x_train, y_train):
self.x_train = x_train
self.y_train = y_train
if self.label_num is None:
self.label_num = len(np.unique(y_train))
def get_knn_indices(self, x):
distances = [minkowski_distance(a, x, self.p) for a in self.x_train]
knn_indices = np.argsort(distances)[:self.k]
return knn_indices
def get_label(self, x):
knn_indices = self.get_knn_indices(x)
label_count = np.zeros(self.label_num)
for idx in knn_indices:
label = int(self.y_train[idx])
label_count[label] += 1
return np.argmax(label_count)
def predict(self, x_test):
predictions = np.zeros(len(x_test), dtype=int)
for i, x in enumerate(x_test):
predictions[i] = self.get_label(x)
return predictions
# =======================
# 主程序入口
# =======================
if __name__ == "__main__":
# 使用 Iris 数据集
iris = load_iris()
X = iris.data[:, :2] # 取前两个特征便于可视化
y = iris.target
# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 实例化并训练模型
knn = KNN(k=5, p=2)
knn.fit(X_train, y_train)
# 预测
y_pred = knn.predict(X_test)
# 计算精度
accuracy = np.mean(y_pred == y_test)
print(f"预测准确率: {accuracy * 100:.2f}%")
# ============ 可视化 ============
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
# 网格点预测
grid_points = np.c_[xx.ravel(), yy.ravel()]
Z = knn.predict(grid_points)
Z = Z.reshape(xx.shape)
# 绘图
plt.figure(figsize=(8, 6))
plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.rainbow)
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, edgecolors='k', cmap=plt.cm.rainbow)
plt.title(f"KNN 分类结果 (k={knn.k}, p={knn.p}, 准确率={accuracy:.2f})")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
| 2302_81501109/machine-learning-course | assignment4/2班70.py | Python | mit | 3,109 |
package com.tjf;
/**
* @author 陶锦锋
* @version 1.0
*/
public class Main {
public static void main(String[] args) {
System.out.println("删除部分文件");
// 添加注释:打印文字
System.out.println("这里进行第四次提交,以测试Git的版本控制");
// 添加注释:打印文字
System.out.println("继续");
// 添加注释:打印文字
System.out.println("第五次提交");
}
}
| 2302_81918214/air_master | src/com/tjf/Main.java | Java | unknown | 489 |
Pod::Spec.new do |spec|
spec.name = 'composeApp'
spec.version = '1.0'
spec.homepage = 'something must not be null'
spec.source = { :http=> ''}
spec.authors = ''
spec.license = ''
spec.summary = 'something must not be null'
spec.vendored_frameworks = 'build/cocoapods/framework/ComposeApp.framework'
spec.libraries = 'c++'
spec.ios.deployment_target = '13.0'
if !Dir.exist?('build/cocoapods/framework/ComposeApp.framework') || Dir.empty?('build/cocoapods/framework/ComposeApp.framework')
raise "
Kotlin framework 'ComposeApp' doesn't exist yet, so a proper Xcode project can't be generated.
'pod install' should be executed after running ':generateDummyFramework' Gradle task:
./gradlew :composeApp:generateDummyFramework
Alternatively, proper pod installation is performed during Gradle sync in the IDE (if Podfile location is set)"
end
spec.xcconfig = {
'ENABLE_USER_SCRIPT_SANDBOXING' => 'NO',
}
spec.pod_target_xcconfig = {
'KOTLIN_PROJECT_PATH' => ':composeApp',
'PRODUCT_MODULE_NAME' => 'ComposeApp',
}
spec.script_phases = [
{
:name => 'Build composeApp',
:execution_position => :before_compile,
:shell_path => '/bin/sh',
:script => <<-SCRIPT
if [ "YES" = "$OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED" ]; then
echo "Skipping Gradle build task invocation due to OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED environment variable set to \"YES\""
exit 0
fi
set -ev
REPO_ROOT="$PODS_TARGET_SRCROOT"
"$REPO_ROOT/../gradlew" -p "$REPO_ROOT" $KOTLIN_PROJECT_PATH:syncFramework \
-Pkotlin.native.cocoapods.platform=$PLATFORM_NAME \
-Pkotlin.native.cocoapods.archs="$ARCHS" \
-Pkotlin.native.cocoapods.configuration="$CONFIGURATION"
SCRIPT
}
]
spec.resources = ['build/compose/ios/ComposeApp/compose-resources']
end | 2201_76010299/ovCompose-sample | composeApp/composeApp.podspec | Ruby | apache-2.0 | 2,324 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
| 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/App.android.kt | Kotlin | apache-2.0 | 765 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material.Surface
import androidx.compose.ui.Modifier
import com.tencent.compose.sample.mainpage.MainPage
import com.tencent.compose.sample.mainpage.NewMainPage
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Surface(modifier = Modifier.statusBarsPadding()) {
MainPage()
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/MainActivity.kt | Kotlin | apache-2.0 | 1,407 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
import android.os.Build
internal class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
internal actual fun getPlatform(): Platform = AndroidPlatform() | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/Platform.android.kt | Kotlin | apache-2.0 | 967 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.ImageBitmap
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.imageResource
@OptIn(ExperimentalResourceApi::class)
@Composable
actual fun rememberLocalImage(id: DrawableResource): ImageBitmap {
return imageResource(resource = id)
} | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/sample/Images.android.kt | Kotlin | apache-2.0 | 1,195 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.backhandler
import androidx.compose.runtime.Composable
@Composable
actual fun BackHandler(enable: Boolean, onBack: () -> Unit) =
androidx.activity.compose.BackHandler(enable, onBack) | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.android.kt | Kotlin | apache-2.0 | 959 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage
import com.tencent.compose.sample.data.DisplayItem
internal actual fun platformSections(): List<DisplayItem> {
return emptyList()
} | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.android.kt | Kotlin | apache-2.0 | 917 |
package net
import io.ktor.client.engine.HttpClientEngineFactory
actual fun ktorEngine(): HttpClientEngineFactory<*> {
TODO("Not yet implemented")
} | 2201_76010299/ovCompose-sample | composeApp/src/androidMain/kotlin/net/Net.android.kt | Kotlin | apache-2.0 | 154 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/Greeting.kt | Kotlin | apache-2.0 | 899 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
internal interface Platform {
val name: String
}
internal expect fun getPlatform(): Platform | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/Platform.kt | Kotlin | apache-2.0 | 862 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.ImageBitmap
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
internal expect fun rememberLocalImage(id: DrawableResource): ImageBitmap | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/Images.kt | Kotlin | apache-2.0 | 1,107 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.dp
@Composable
internal fun LinearGradientLine() {
Box(modifier = Modifier.fillMaxSize().padding(50.dp).background(Color.Gray.copy(0.5f))) {
Column(modifier = Modifier.wrapContentSize()) {
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 80f,
color = Color.Red,
start = Offset(0f, 0.0f),
end = Offset(0.0f, 0.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 80f,
color = Color.Blue,
start = Offset(0f, 0.0f),
end = Offset(0.0f, 300.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 80f,
color = Color.Green,
start = Offset(0f, 0.0f),
end = Offset(300.0f, 300.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 80f,
color = Color.Cyan,
start = Offset(0f, 0.0f),
end = Offset(300.0f, 0.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(50.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 80f,
color = Color.Magenta,
start = Offset(300f, 0.0f),
end = Offset(0.0f, 300.0f)
)
}
}
}
Column(modifier = Modifier.wrapContentSize()) {
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 40f,
brush = Brush.linearGradient(
0.1f to Color(0xFFBF230F),
0.3f to Color(0xFFFFC885),
0.6f to Color(0xFFE8912D),
start = Offset(0.0f, 0.0f),
end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp
),
start = Offset(0f, 0.0f),
end = Offset(0.0f, 0.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 40f,
brush = Brush.linearGradient(
0.1f to Color(0xFFBF230F),
0.3f to Color(0xFFFFC885),
0.6f to Color(0xFFE8912D),
start = Offset(0.0f, 0.0f),
end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp
),
start = Offset(0f, 0.0f),
end = Offset(0.0f, 300.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 40f,
brush = Brush.linearGradient(
0.1f to Color(0xFFBF230F),
0.3f to Color(0xFFFFC885),
0.6f to Color(0xFFE8912D),
start = Offset(0.0f, 0.0f),
end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp
),
start = Offset(0f, 0.0f),
end = Offset(300.0f, 300.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(100.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 40f,
brush = Brush.linearGradient(
0.1f to Color(0xFFBF230F),
0.3f to Color(0xFFFFC885),
0.6f to Color(0xFFE8912D),
start = Offset(0.0f, 0.0f),
end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp
),
start = Offset(0f, 0.0f),
end = Offset(300.0f, 0.0f)
)
}
}
Spacer(modifier = Modifier.size(20.dp))
Box(
modifier = Modifier.size(50.dp)
) {
Canvas(modifier = Modifier.fillMaxSize()) {
drawLine(
strokeWidth = 40f,
brush = Brush.linearGradient(
0.1f to Color(0xFFBF230F),
0.3f to Color(0xFFFFC885),
0.6f to Color(0xFFE8912D),
start = Offset(0.0f, 0.0f),
end = Offset(600.0f, 0.0f), tileMode = TileMode.Clamp
),
start = Offset(300f, 0.0f),
end = Offset(0.0f, 300.0f)
)
}
}
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/LinearGradientLine.kt | Kotlin | apache-2.0 | 8,151 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
@Composable
internal fun MultiTouches() {
var rotationZ by remember { mutableFloatStateOf(0f) }
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize().pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, rotation ->
rotationZ += rotation
scale *= zoom
offset += pan
}
}) {
Box(
modifier = Modifier.graphicsLayer(
scaleX = scale,
scaleY = scale,
translationX = offset.x,
translationY = offset.y,
rotationZ = rotationZ
).size(100.dp).background(color = Color.Blue)
)
Text("scale and rotation me")
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/MultiTouches.kt | Kotlin | apache-2.0 | 2,513 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.backhandler
import androidx.compose.runtime.Composable
@Composable
internal expect fun BackHandler(enable: Boolean, onBack: () -> Unit) | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.kt | Kotlin | apache-2.0 | 908 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.data
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
internal data class DisplaySection(
val sectionTitle: String,
val items: List<DisplayItem>
)
@OptIn(ExperimentalResourceApi::class)
@Immutable
internal data class DisplayItem(
val title: String,
val img: DrawableResource,
val content: @Composable () -> Unit
) | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/data/DisplayItem.kt | Kotlin | apache-2.0 | 1,262 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage
import com.tencent.compose.sample.LinearGradientLine
import com.tencent.compose.sample.MultiTouches
import com.tencent.compose.sample.data.DisplayItem
import com.tencent.compose.sample.data.DisplaySection
import com.tencent.compose.sample.mainpage.sectionItem.BouncingBallsApp
import com.tencent.compose.sample.mainpage.sectionItem.CarouselTransition
import com.tencent.compose.sample.mainpage.sectionItem.CheckboxExamples
import com.tencent.compose.sample.mainpage.sectionItem.DialogExamples
import com.tencent.compose.sample.mainpage.sectionItem.DropdownMenu
import com.tencent.compose.sample.mainpage.sectionItem.FallingBalls
import com.tencent.compose.sample.mainpage.sectionItem.GestureDemo
import com.tencent.compose.sample.mainpage.sectionItem.ImageExamplesScreen
import com.tencent.compose.sample.mainpage.sectionItem.NestedScrollDemo
import com.tencent.compose.sample.mainpage.sectionItem.ProgressIndicatorExamples
import com.tencent.compose.sample.mainpage.sectionItem.SimpleImage
import com.tencent.compose.sample.mainpage.sectionItem.SimpleTextPage
import com.tencent.compose.sample.mainpage.sectionItem.SliderExamples
import com.tencent.compose.sample.mainpage.sectionItem.SwitchExamples
import com.tencent.compose.sample.mainpage.sectionItem.TextField2
import com.tencent.compose.sample.mainpage.sectionItem.TextField3
import com.tencent.compose.sample.mainpage.sectionItem.ManyViewsPage
import com.tencent.compose.sample.mainpage.sectionItem.ManyViewsPage2
import com.tencent.compose.sample.mainpage.sectionItem.The300Threads
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.balls
import composesample.composeapp.generated.resources.carousel
import composesample.composeapp.generated.resources.cat
import composesample.composeapp.generated.resources.checkbox
import composesample.composeapp.generated.resources.dialog
import composesample.composeapp.generated.resources.dog
import composesample.composeapp.generated.resources.falling
import composesample.composeapp.generated.resources.gesture
import composesample.composeapp.generated.resources.gradient
import composesample.composeapp.generated.resources.layers
import composesample.composeapp.generated.resources.menu
import composesample.composeapp.generated.resources.multi_touch
import composesample.composeapp.generated.resources.progress
import composesample.composeapp.generated.resources.scroll
import composesample.composeapp.generated.resources.simple_text
import composesample.composeapp.generated.resources.sliders
import composesample.composeapp.generated.resources.switch
import composesample.composeapp.generated.resources.text_field
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
internal fun displaySections(): List<DisplaySection> {
return listOf(
DisplaySection(
sectionTitle = "Compose Component",
items = listOf(
DisplayItem("dialog", Res.drawable.dialog) { DialogExamples() },
DisplayItem("switch", Res.drawable.switch) { SwitchExamples() },
DisplayItem("sliders", Res.drawable.sliders) { SliderExamples() },
DisplayItem("checkbox", Res.drawable.checkbox) { CheckboxExamples() },
DisplayItem("progress", Res.drawable.progress) { ProgressIndicatorExamples() },
DisplayItem("simple-text", Res.drawable.simple_text) { SimpleTextPage() },
DisplayItem("image-cat", Res.drawable.cat) { SimpleImage() },
DisplayItem("image-dog", Res.drawable.dog) { ImageExamplesScreen() },
DisplayItem("carousel", Res.drawable.carousel) { CarouselTransition() },
)
),
DisplaySection(
sectionTitle = "Input Box",
items = listOf(
DisplayItem("keyboard-type", Res.drawable.text_field) { TextField2() },
DisplayItem("alert-type", Res.drawable.text_field) { TextField3() },
)
),
DisplaySection(
sectionTitle = "Mixed native UI & Gesture",
items = listOf(
DisplayItem("NestedScrollDemo", Res.drawable.scroll) { NestedScrollDemo() },
DisplayItem("MultiTouches", Res.drawable.multi_touch) { MultiTouches() },
DisplayItem("drag", Res.drawable.gesture) { GestureDemo() }
) + platformSections()
),
DisplaySection(
sectionTitle = "Others",
items = listOf(
DisplayItem("Bouncing Balls", Res.drawable.balls) { BouncingBallsApp() },
DisplayItem("Falling Balls", Res.drawable.falling) { FallingBalls() },
DisplayItem("DropdownMenu", Res.drawable.menu) { DropdownMenu() },
DisplayItem("GradientLine", Res.drawable.gradient) { LinearGradientLine() },
DisplayItem("ManyViewsPage", Res.drawable.layers) { ManyViewsPage(1500) },
DisplayItem("ManyViewsPage2", Res.drawable.layers) { ManyViewsPage2(1500) },
DisplayItem("The300threads", Res.drawable.layers) { The300Threads() }
)
)
)
}
internal expect fun platformSections() : List<DisplayItem>
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.kt | Kotlin | apache-2.0 | 6,037 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tencent.compose.sample.backhandler.BackHandler
import com.tencent.compose.sample.data.DisplayItem
import com.tencent.compose.sample.data.DisplaySection
import com.tencent.compose.sample.rememberLocalImage
import org.jetbrains.compose.resources.ExperimentalResourceApi
private fun appBarTitle(openedExample: DisplayItem?, skiaRender: Boolean = true): String {
val title =
if (skiaRender) "Tencent Video Compose - Skia" else "Tencent Video Compose - UIKit"
val childTitle =
if (skiaRender) "${openedExample?.title} - Skia" else "${openedExample?.title} - UIKit"
return if (openedExample != null) childTitle else title
}
@Composable
internal fun MainPage(skiaRender: Boolean = true) {
val displayItems by remember { mutableStateOf(displaySections()) }
var openedExample: DisplayItem? by remember { mutableStateOf(null) }
val listState = rememberLazyListState()
BackHandler(openedExample != null) {
openedExample = null
}
Column {
TopAppBar(
navigationIcon = {
if (openedExample == null) return@TopAppBar
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "Back",
modifier = Modifier.clickable { openedExample = null }
)
},
title = {
val title = appBarTitle(openedExample, skiaRender)
Text(title)
}
)
AnimatedContent(
targetState = openedExample,
transitionSpec = {
// EnterTransition.None togetherWith ExitTransition.None
(EnterTransition.None togetherWith ExitTransition.None)
.using (SizeTransform(false))
// val slideDirection =
// if (targetState != null) AnimatedContentTransitionScope.SlideDirection.Start
// else AnimatedContentTransitionScope.SlideDirection.End
//
// slideIntoContainer(
// animationSpec = tween(250, easing = FastOutSlowInEasing),
// towards = slideDirection
// ) + fadeIn(animationSpec = tween(250)) togetherWith
// slideOutOfContainer(
// animationSpec = tween(250, easing = FastOutSlowInEasing),
// towards = slideDirection
// ) + fadeOut(animationSpec = tween(250))
}
) { target ->
if (target == null) {
LazyColumn(state = listState) {
items(displayItems) { displayItem ->
Section(displayItem) { clickItem ->
openedExample = clickItem
}
}
item {
Spacer(Modifier.fillMaxWidth().height(20.dp))
}
}
} else {
Box(Modifier.fillMaxSize()) {
target.content()
}
}
}
}
}
@Composable
private fun Section(displaySection: DisplaySection, itemClick: (displayItem: DisplayItem) -> Unit) {
Column {
SectionTitle(displaySection.sectionTitle)
val chunkedItems = displaySection.items.chunked(3)
chunkedItems.forEach { rowItems ->
Row(verticalAlignment = Alignment.CenterVertically) {
rowItems.forEach { BoxItem(it, itemClick) }
repeat(3 - rowItems.size) {
Spacer(Modifier.weight(0.33f))
}
}
}
}
}
@Composable
private fun SectionTitle(title: String) {
Row(
Modifier.fillMaxWidth().height(34.dp).background(Color.Black.copy(alpha = 0.11f)),
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(Modifier.fillMaxHeight().width(10.dp))
Text(
text = title,
fontSize = 16.sp,
color = Color.Black.copy(alpha = 0.7f),
fontWeight = FontWeight.Medium
)
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
private fun RowScope.BoxItem(
displayItem: DisplayItem,
itemClick: (displayItem: DisplayItem) -> Unit
) {
Column(
Modifier.weight(0.33f)
.height(86.dp)
.border(0.3.dp, color = Color.LightGray)
.clickable {
itemClick(displayItem)
},
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Image(
modifier = Modifier.width(34.dp).size(28.dp),
bitmap = rememberLocalImage(displayItem.img),
contentDescription = null
)
Spacer(Modifier.fillMaxWidth().height(10.dp))
Text(text = displayItem.title, fontSize = 14.sp, color = Color.Black.copy(alpha = 0.7f))
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/MainPage.kt | Kotlin | apache-2.0 | 7,858 |
package com.tencent.compose.sample.mainpage
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import com.tencent.compose.sample.mainpage.sectionItem.BigImage
import com.tencent.compose.sample.mainpage.sectionItem.composeView1500Page
import com.tencent.compose.sample.AppTabScreen
import com.tencent.compose.sample.mainpage.sectionItem.The300Threads
@Composable
internal fun NewMainPage() {
var showBig by remember { mutableStateOf(false) }
Column(Modifier.fillMaxSize()) {
TopAppBar(
navigationIcon = {
if (showBig) {
IconButton(onClick = { showBig = false }) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = "Back"
)
}
}
},
title = {
Text(if (showBig) "Big Image" else "Demo")
}
)
Box(
Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
if (!showBig) {
Button(onClick = { showBig = true }) {
Text("300 Threads")
}
} else {
// 真正的“跳转效果”:只渲染 BigImage 页面
//BigImage()
//composeView1500Page()
//The300Threads()
AppTabScreen()
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/NewMainPage.kt | Kotlin | apache-2.0 | 1,740 |
// AppHomeCompose.kt
package com.tencent.compose.sample
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlin.random.Random
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import androidx.compose.foundation.Image
import androidx.compose.ui.layout.ContentScale
// 如果你的 rememberLocalImage 与 Res 在别的包,请改成对应包名
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
//import composesample.composeapp.generated.resources.cat1
//import composesample.composeapp.generated.resources.cat2
import composesample.composeapp.generated.resources.image_cat
import composesample.composeapp.generated.resources.image_dog
import org.jetbrains.compose.resources.ExperimentalResourceApi
/**
* Single-file Compose implementation of:
* - Home with top tabs (Follow/Trend)
* - Follow feed list with refresh & load more
* - Trending with nested tabs (Recommend / Nearby / ...)
*
* Focused on UI only; replace placeholders (images, real data) as needed.
*/
/* ------------------------------
Top-level screen
------------------------------ */
@Composable
internal fun AppHomeScreen(
modifier: Modifier = Modifier,
onSettingsClick: () -> Unit = {}
) {
// Localization placeholders (replace with your lang manager)
val resFollow = "关注"
val resTrend = "热门"
val titles = listOf(resFollow, resTrend)
var currentIndex by remember { mutableStateOf(0) }
Column(modifier = modifier.fillMaxSize()) {
TopTabs(
titles = titles,
selectedIndex = currentIndex,
onTabSelected = { idx -> currentIndex = idx },
onSettingsClick = onSettingsClick
)
// pages
Box(modifier = Modifier.fillMaxSize()) {
when (currentIndex) {
0 -> FeedListPage(pageType = "follow")
else -> TrendingPage()
}
}
}
}
/* ------------------------------
Top tabs (simple)
------------------------------ */
@Composable
private fun TopTabs(
titles: List<String>,
selectedIndex: Int,
onTabSelected: (Int) -> Unit,
onSettingsClick: () -> Unit
) {
val background = Color(0xFFF7F7F7)
val textFocused = Color(0xFF111111)
val textUnfocused = Color(0xFF888888)
val indicatorColor = Color(0xFFFF3B30)
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.background(background)
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier.weight(1f),
verticalAlignment = Alignment.CenterVertically
) {
titles.forEachIndexed { i, title ->
val selected = i == selectedIndex
val textColor by animateColorAsState(if (selected) textFocused else textUnfocused)
Column(
modifier = Modifier
.padding(horizontal = 10.dp)
.clickable { onTabSelected(i) },
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = title,
fontSize = 17.sp,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
color = textColor
)
Spacer(modifier = Modifier.height(6.dp))
Box(
modifier = Modifier
.height(3.dp)
.widthIn(min = 24.dp)
) {
if (selected) {
Box(
modifier = Modifier
.height(3.dp)
.fillMaxWidth()
.background(indicatorColor)
)
}
}
}
}
}
IconButton(onClick = onSettingsClick) {
// placeholder settings circle
Box(
modifier = Modifier
.size(22.dp)
.clip(CircleShape)
.background(Color(0xFFAAC7FF))
)
}
}
}
/* ------------------------------
Feed list page (Follow / can be reused)
- supports manual refresh (button) and auto load more
------------------------------ */
@Composable
internal fun FeedListPage(pageType: String) {
// local states
var isRefreshing by remember { mutableStateOf(false) }
var isLoadingMore by remember { mutableStateOf(false) }
val listState = rememberLazyListState()
val items = remember { mutableStateListOf<FeedItemModel>() }
// coroutine scope for event callbacks
val coroutineScope = rememberCoroutineScope()
// initial load: 改为 100 条
LaunchedEffect(pageType) {
// load initial page
items.clear()
items.addAll(generateSampleFeeds(start = 0, count = 100))
}
// auto load more when scrolled near end
LaunchedEffect(listState) {
snapshotFlow {
// index of last visible item
val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
last
}.map { it ?: -1 }
.distinctUntilChanged()
.filter { idx -> idx >= 0 } // only when visible items present
.collectLatest { lastIndex ->
val total = items.size
// when last visible >= total - 3 and not already loading
if (lastIndex >= total - 3 && !isLoadingMore) {
// load more
isLoadingMore = true
// simulate network delay
delay(700)
// 从当前已有数量开始追加,避免重复
val newItems = generateSampleFeeds(start = items.size, count = 20)
if (newItems.isNotEmpty()) {
items.addAll(newItems)
}
isLoadingMore = false
}
}
}
Column(modifier = Modifier.fillMaxSize()) {
// simple refresh control row
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Button(onClick = {
if (!isRefreshing) {
isRefreshing = true
// properly launch coroutine from non-composable lambda
coroutineScope.launch {
// simulate refresh
delay(800)
items.clear()
items.addAll(generateSampleFeeds(start = 0, count = 100))
isRefreshing = false
// yield to ensure UI updates quickly
yield()
}
}
}) {
Text(text = if (isRefreshing) "正在刷新..." else "刷新")
}
Spacer(modifier = Modifier.width(12.dp))
Text(text = "共 ${items.size} 条", color = Color(0xFF666666))
}
Divider(color = Color(0xFFECECEC))
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = listState,
contentPadding = PaddingValues(vertical = 8.dp)
) {
items(items, key = { it.id }) { item ->
FeedCard(item = item)
}
item {
Spacer(modifier = Modifier.height(8.dp))
if (isLoadingMore) {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(text = "加载中...", color = Color(0xFF777777))
}
} else {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(text = "上滑加载更多", color = Color(0xFFAAAAAA))
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
}
/* ------------------------------
Trending page (nested tabs + pages)
------------------------------ */
@Composable
internal fun TrendingPage() {
val types = listOf(
"推荐", "附近", "榜单", "明星", "搞笑", "社会", "测试"
)
var selected by remember { mutableStateOf(0) }
Column(modifier = Modifier.fillMaxSize()) {
// horizontal scrollable tabs
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color(0xFFF2F2F2))
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
val density = LocalDensity.current
types.forEachIndexed { i, t ->
val selectedColor by animateColorAsState(if (i == selected) Color.Black else Color(0xFF777777))
Text(
text = t,
modifier = Modifier
.padding(horizontal = 12.dp, vertical = 8.dp)
.clickable { selected = i },
color = selectedColor,
fontSize = 15.sp
)
}
}
// page content
Box(modifier = Modifier.fillMaxSize()) {
when (selected) {
0 -> FeedListPage(pageType = "recommend")
1 -> FeedListPage(pageType = "nearby")
else -> FeedListPage(pageType = "other_$selected")
}
}
}
}
/* ------------------------------
Feed item UI
------------------------------ */
private data class FeedItemModel(
val id: String,
val nick: String,
val content: String
)
// 修改:第一个参数改为 start(起始 id)
private fun generateSampleFeeds(start: Int, count: Int): List<FeedItemModel> {
return (start until start + count).map {
FeedItemModel(
id = it.toString(),
nick = "用户_$it",
content = "这是示例内容($it),用于展示 Feed 列表。随机一句话:${sampleSentence()}"
)
}
}
private fun sampleSentence(): String {
val samples = listOf(
"今天天气不错。",
"刚刚吃了个好吃的午餐。",
"去看了一场电影,推荐!",
"学习 Compose 中……",
"这是一个示例条目。",
"音乐让人放松。"
)
return samples[Random.nextInt(samples.size)]
}
@OptIn(ExperimentalResourceApi::class)
@Composable
private fun FeedCard(item: FeedItemModel) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp)
.background(Color.White)
.padding(12.dp)
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Avatar(size = 40.dp)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(text = item.nick, fontWeight = FontWeight.SemiBold, fontSize = 15.sp)
Spacer(modifier = Modifier.height(4.dp))
Text(text = "来自 · 手机", color = Color(0xFF777777), fontSize = 12.sp)
}
}
Spacer(modifier = Modifier.height(8.dp))
Text(text = item.content, fontSize = 14.sp, color = Color(0xFF222222))
Spacer(modifier = Modifier.height(8.dp))
// simple image placeholder
Row(modifier = Modifier.fillMaxWidth()) {
Image(
bitmap = rememberLocalImage(Res.drawable.image_cat),
contentDescription = null,
modifier = Modifier
.weight(1f)
.height(160.dp),
contentScale = ContentScale.Crop
)
Spacer(modifier = Modifier.width(8.dp))
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = null,
modifier = Modifier
.weight(1f)
.height(160.dp),
contentScale = ContentScale.Crop
)
}
// Box(
// modifier = Modifier
// .fillMaxWidth()
// .height(160.dp)
// .background(Color(0xFFE9E9E9))
// )
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = "转发 12", fontSize = 12.sp, color = Color(0xFF666666))
Text(text = "评论 34", fontSize = 12.sp, color = Color(0xFF666666))
Text(text = "点赞 56", fontSize = 12.sp, color = Color(0xFF666666))
}
}
}
@Composable
private fun Avatar(size: androidx.compose.ui.unit.Dp) {
Box(
modifier = Modifier
.size(size)
.clip(CircleShape)
.background(Color(0xFFCCCCCC))
)
}
@Composable
internal fun AppHomePreview() {
MaterialTheme {
AppHomeScreen(modifier = Modifier.fillMaxSize())
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/AppHomePageView.kt | Kotlin | apache-2.0 | 14,303 |
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.big_image
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun BigImage() {
Box(
modifier = Modifier
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
bitmap = rememberLocalImage(Res.drawable.big_image),
contentDescription = null,
modifier = Modifier
.width(350.dp)
.height(350.dp)
.padding(5.dp)
)
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/BigImage.kt | Kotlin | apache-2.0 | 1,189 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import com.tencent.compose.sample.mainpage.sectionItem.BouncingBall.Companion.setCount
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.math.sin
import kotlin.random.Random
private fun Modifier.noRippleClickable(onClick: (Offset) -> Unit): Modifier =
composed {
clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }) {
}.pointerInput(Unit) {
detectTapGestures(onTap = {
println("tap offset = $it")
onClick(it)
})
}
}
private var areaWidth = 0
private var areaHeight = 0
@Composable
internal fun BouncingBallsApp(initialBallsCount: Int = 10) {
val items = remember {
val list = mutableStateListOf<BouncingBall>()
list.addAll(generateSequence {
BouncingBall.createBouncingBall()
}.take(initialBallsCount))
list
}
BoxWithConstraints(
modifier = Modifier.fillMaxWidth()
.fillMaxHeight()
.border(width = 1.dp, color = Color.Black)
.noRippleClickable {
items += BouncingBall.createBouncingBall(offset = it)
}
) {
areaWidth = maxWidth.value.roundToInt()
areaHeight = maxHeight.value.roundToInt()
Balls(items)
Column {
Row {
Text("count: ${items.size}")
Spacer(Modifier.width(16.dp))
Button(onClick = { items.setCount(10) }) { Text("10") }
Spacer(Modifier.width(16.dp))
Button(onClick = { items.setCount(items.size + 10) }) { Text("+10") }
Spacer(Modifier.width(16.dp))
Button(onClick = { items.setCount(items.size + 100) }) { Text("+100") }
}
}
}
LaunchedEffect(Unit) {
var lastTime = 0L
var dt = 0L
while (true) {
withFrameNanos { time ->
dt = time - lastTime
if (lastTime == 0L) {
dt = 0
}
lastTime = time
items.forEach {
it.recalculate(areaWidth, areaHeight, dt.toFloat())
}
}
}
}
}
@Composable
private fun Balls(items: List<BouncingBall>) {
items.forEachIndexed { ix, ball ->
key(ix) {
Box(
modifier = Modifier
.offset(
x = (ball.circle.x.value - ball.circle.r).dp,
y = (ball.circle.y.value - ball.circle.r).dp
).size((2 * ball.circle.r).dp)
.background(ball.color, CircleShape)
)
}
}
}
private class Circle(
var x: MutableState<Float>,
var y: MutableState<Float>,
val r: Float
) {
constructor(x: Float, y: Float, r: Float) : this(
mutableStateOf(x), mutableStateOf(y), r
)
fun moveCircle(s: Float, angle: Float, width: Int, height: Int, r: Float) {
x.value = (x.value + s * sin(angle)).coerceAtLeast(r).coerceAtMost(width.toFloat() - r)
y.value = (y.value + s * cos(angle)).coerceAtLeast(r).coerceAtMost(height.toFloat() - r)
}
}
private fun calculatePosition(circle: Circle, boundingWidth: Int, boundingHeight: Int): Position {
val southmost = circle.y.value + circle.r
val northmost = circle.y.value - circle.r
val westmost = circle.x.value - circle.r
val eastmost = circle.x.value + circle.r
return when {
southmost >= boundingHeight -> Position.TOUCHES_SOUTH
northmost <= 0 -> Position.TOUCHES_NORTH
eastmost >= boundingWidth -> Position.TOUCHES_EAST
westmost <= 0 -> Position.TOUCHES_WEST
else -> Position.INSIDE
}
}
private enum class Position {
INSIDE,
TOUCHES_SOUTH,
TOUCHES_NORTH,
TOUCHES_WEST,
TOUCHES_EAST
}
private class BouncingBall(
val circle: Circle,
val velocity: Float,
var angle: Double,
val color: Color = Color.Red
) {
fun recalculate(width: Int, height: Int, dt: Float) {
val position = calculatePosition(circle, width, height)
val dtMillis = dt / 1000000
when (position) {
Position.TOUCHES_SOUTH -> angle = PI - angle
Position.TOUCHES_EAST -> angle = -angle
Position.TOUCHES_WEST -> angle = -angle
Position.TOUCHES_NORTH -> angle = PI - angle
Position.INSIDE -> angle
}
circle.moveCircle(
velocity * (dtMillis.coerceAtMost(500f) / 1000),
angle.toFloat(),
width,
height,
circle.r
)
}
companion object {
private val random = Random(100)
private val angles = listOf(PI / 4, -PI / 3, 3 * PI / 4, -PI / 6, -1.1 * PI)
private val colors = listOf(Color.Red, Color.Black, Color.Green, Color.Magenta)
private fun randomOffset(): Offset {
return Offset(
x = random.nextInt(100, 700).toFloat(),
y = random.nextInt(100, 500).toFloat()
)
}
fun createBouncingBall(offset: Offset = randomOffset()): BouncingBall {
return BouncingBall(
circle = Circle(x = offset.x, y = offset.y, r = random.nextInt(10, 50).toFloat()),
velocity = random.nextInt(100, 200).toFloat(),
angle = angles.random(),
color = colors.random().copy(alpha = max(0.3f, random.nextFloat()))
)
}
fun SnapshotStateList<BouncingBall>.setCount(count: Int) {
when {
size > count -> removeRange(count - 1, lastIndex)
size < count -> addAll(generateSequence { createBouncingBall() }.take(count - size))
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/BouncingBalls.kt | Kotlin | apache-2.0 | 8,259 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp
import kotlin.math.absoluteValue
@OptIn(ExperimentalFoundationApi::class)
internal fun Modifier.carouselTransition(
start: Float,
stop: Float,
index: Int,
pagerState: PagerState
) = graphicsLayer {
val pageOffset =
((pagerState.currentPage - index) + pagerState.currentPageOffsetFraction).absoluteValue
val transformation = androidx.compose.ui.util.lerp(
start = start,
stop = stop,
fraction = 1f - pageOffset.coerceIn(
0f,
1f
)
)
alpha = transformation
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun CarouselTransition() {
val pageCount = 3
val pagerState: PagerState = rememberPagerState(pageCount = { pageCount })
Column(
Modifier.width(300.dp).height(300.dp).background(Color.Green),
horizontalAlignment = Alignment.CenterHorizontally
) {
HorizontalPager(
modifier = Modifier.fillMaxSize().background(Color.Blue),
state = pagerState,
contentPadding = PaddingValues(horizontal = 10.dp),
pageSpacing = 20.dp
) { page: Int ->
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text("文本:${page}", color = Color.White)
Box(
modifier = Modifier
.fillMaxSize()
.carouselTransition(
start = 0.6f,
stop = 0.0f,
index = page,
pagerState = pagerState
).background(Color.Black)
) {}
Box(Modifier
.align(Alignment.BottomEnd)
.height(16.dp)
.width(16.dp).background(Color.Green)
.carouselTransition(
start = .0f,
stop = 1.0f,
index = page,
pagerState = pagerState
))
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/CarouselTransition.kt | Kotlin | apache-2.0 | 3,813 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Checkbox
import androidx.compose.material.Text
import androidx.compose.material.TriStateCheckbox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
@Preview
@Composable
internal fun CheckboxExamples() {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Column {
Text("Minimal checkbox example")
CheckboxMinimalExample()
}
Column {
Text("Parent checkbox example")
CheckboxParentExample()
}
}
}
@Preview
// [START android_compose_components_checkbox_minimal]
@Composable
private fun CheckboxMinimalExample() {
var checked by remember { mutableStateOf(true) }
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"Minimal checkbox"
)
Checkbox(
checked = checked,
onCheckedChange = { checked = it }
)
}
Text(
if (checked) "Checkbox is checked" else "Checkbox is unchecked"
)
}
// [END android_compose_components_checkbox_minimal]
@Preview
// [START android_compose_components_checkbox_parent]
@Composable
private fun CheckboxParentExample() {
// Initialize states for the child checkboxes
val childCheckedStates = remember { mutableStateListOf(false, false, false) }
// Compute the parent state based on children's states
val parentState = when {
childCheckedStates.all { it } -> ToggleableState.On
childCheckedStates.none { it } -> ToggleableState.Off
else -> ToggleableState.Indeterminate
}
Column {
// Parent TriStateCheckbox
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text("Select all")
TriStateCheckbox(
state = parentState,
onClick = {
// Determine new state based on current state
val newState = parentState != ToggleableState.On
childCheckedStates.forEachIndexed { index, _ ->
childCheckedStates[index] = newState
}
}
)
}
// Child Checkboxes
childCheckedStates.forEachIndexed { index, checked ->
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text("Option ${index + 1}")
Checkbox(
checked = checked,
onCheckedChange = { isChecked ->
// Update the individual child state
childCheckedStates[index] = isChecked
},
modifier = Modifier.testTag("checkbox${index + 1}"),
)
}
}
}
if (childCheckedStates.all { it }) {
Text("All options selected")
}
}
// [END android_compose_components_checkbox_parent]
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Checkbox.kt | Kotlin | apache-2.0 | 4,608 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalResourceApi::class, ExperimentalResourceApi::class)
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
//import composesample.composeapp.generated.resources.big_image
import composesample.composeapp.generated.resources.home_icon
import composesample.composeapp.generated.resources.image_dog
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.ui.tooling.preview.Preview
private val examples: List<ItemTitle> = listOf(
ItemTitle("ContentScaleExample") {
ContentScaleExample()
},
ItemTitle("ClipImageExample") {
ClipImageExample()
},
ItemTitle("ClipRoundedCorner") {
ClipRoundedCorner()
},
ItemTitle("CustomClippingShape") {
CustomClippingShape()
},
ItemTitle("ImageWithBorder") {
ImageWithBorder()
},
ItemTitle("ImageRainbowBorder") {
ImageRainbowBorder()
},
ItemTitle("ImageAspectRatio") {
ImageAspectRatio()
},
ItemTitle("ImageColorFilter") {
ImageColorFilter()
},
ItemTitle("ImageBlendMode") {
ImageBlendMode()
},
ItemTitle("ImageColorMatrix") {
ImageColorMatrix()
},
ItemTitle("ImageAdjustBrightnessContrast") {
ImageAdjustBrightnessContrast()
},
ItemTitle("ImageInvertColors") {
ImageInvertColors()
},
ItemTitle("ImageBlur") {
ImageBlur()
},
ItemTitle("ImageBlurBox") {
ImageBlurBox()
},
ItemTitle("ImageBlurEdgeTreatment") {
ImageBlurEdgeTreatment()
}
)
private class ItemTitle(
val name: String,
val content: @Composable () -> Unit
)
@Preview
@Composable
internal fun ImageExamplesScreen(start: Int = 0, end: Int = examples.size) {
if (start < 0 || end > examples.size) {
throw RuntimeException("ImageExamplesScreen input error, start=$start, end=$end")
}
val items = examples.subList(start, end)
LazyColumn(Modifier.padding(top = 15.dp, bottom = 15.dp)) {
items(items) { item ->
Column(modifier = Modifier.fillMaxWidth()) {
Text(
text = item.name,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
item.content()
}
}
}
}
@Composable
private fun ContentScaleExample() {
// [START android_compose_content_scale]
val imageModifier = Modifier
.size(150.dp)
.border(BorderStroke(1.dp, Color.Black))
.background(Color.Yellow)
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Fit,
modifier = imageModifier
)
// [END android_compose_content_scale]
}
@Preview
@Composable
private fun ClipImageExample() {
// [START android_compose_clip_image]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(200.dp)
.clip(CircleShape)
)
// [END android_compose_clip_image]
}
@Preview
@Composable
private fun ClipRoundedCorner() {
// [START android_compose_clip_image_rounded_corner]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(200.dp)
.clip(RoundedCornerShape(16.dp))
)
// [END android_compose_clip_image_rounded_corner]
}
@Preview
@Composable
private fun CustomClippingShape() {
// [START android_compose_custom_clipping_shape]
class SquashedOval : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
val path = Path().apply {
// We create an Oval that starts at ¼ of the width, and ends at ¾ of the width of the container.
addOval(
Rect(
left = size.width / 4f,
top = 0f,
right = size.width * 3 / 4f,
bottom = size.height
)
)
}
return Outline.Generic(path = path)
}
}
Box(modifier = Modifier.background(Color.Green)) {
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(200.dp)
.clip(SquashedOval())
)
}
// [END android_compose_custom_clipping_shape]
}
@Preview
@Composable
private fun ImageWithBorder() {
// [START android_compose_image_border]
val borderWidth = 4.dp
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(150.dp)
.border(
BorderStroke(borderWidth, Color.Yellow),
CircleShape
)
.padding(borderWidth)
.clip(CircleShape)
)
// [END android_compose_image_border]
}
@Preview
@Composable
private fun ImageRainbowBorder() {
// [START android_compose_image_rainbow_border]
val rainbowColorsBrush = remember {
Brush.sweepGradient(
listOf(
Color(0xFF9575CD),
Color(0xFFBA68C8),
Color(0xFFE57373),
Color(0xFFFFB74D),
Color(0xFFFFF176),
Color(0xFFAED581),
Color(0xFF4DD0E1),
Color(0xFF9575CD)
)
)
}
val borderWidth = 15.dp
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(150.dp)
.border(
BorderStroke(borderWidth, rainbowColorsBrush),
CircleShape
)
.padding(borderWidth)
.clip(CircleShape)
)
val density = LocalDensity.current.density
val pxValue = borderWidth * density
println("ImageRainbowBorder to px$pxValue")
Box(
modifier = Modifier.size(100.dp).background(Color.Black).border(
BorderStroke(borderWidth, rainbowColorsBrush),
CircleShape
)
) {
}
// [END android_compose_image_rainbow_border]
}
@Composable
@Preview
private fun ImageAspectRatio() {
// [START android_compose_image_aspect_ratio]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
modifier = Modifier.aspectRatio(16f / 9f)
)
// [END android_compose_image_aspect_ratio]
}
@Composable
@Preview
private fun ImageColorFilter() {
// [START android_compose_image_color_filter]
Column {
Image(
modifier = Modifier.size(32.dp),
bitmap = rememberLocalImage(Res.drawable.home_icon),
contentDescription = "",
colorFilter = ColorFilter.tint(Color.Red, BlendMode.SrcAtop)
)
Text(text = "首页")
}
// [END android_compose_image_color_filter]
}
@Preview
@Composable
private fun ImageBlendMode() {
// [START android_compose_image_blend_mode]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
colorFilter = ColorFilter.tint(Color.Green, blendMode = BlendMode.Darken)
)
// [END android_compose_image_blend_mode]
}
@Preview
@Composable
private fun ImageColorMatrix() {
// [START android_compose_image_colormatrix]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
colorFilter = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })
)
// [END android_compose_image_colormatrix]
}
@Preview
@Composable
private fun ImageAdjustBrightnessContrast() {
// [START android_compose_image_brightness]
val contrast = 2f // 0f..10f (1 should be default)
val brightness = -180f // -255f..255f (0 should be default)
val colorMatrix = floatArrayOf(
contrast, 0f, 0f, 0f, brightness,
0f, contrast, 0f, 0f, brightness,
0f, 0f, contrast, 0f, brightness,
0f, 0f, 0f, 1f, 0f
)
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix))
)
// [END android_compose_image_brightness]
}
@Preview
@Composable
private fun ImageInvertColors() {
// [START android_compose_image_invert_colors]
val colorMatrix = floatArrayOf(
-1f, 0f, 0f, 0f, 255f,
0f, -1f, 0f, 0f, 255f,
0f, 0f, -1f, 0f, 255f,
0f, 0f, 0f, 1f, 0f
)
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix))
)
// [END android_compose_image_invert_colors]
}
@Preview
@Composable
private fun ImageBlur() {
var blurRadius by remember { mutableStateOf(40.dp) }
// [START android_compose_image_blur]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.clickable {
blurRadius = if (blurRadius == 40.dp) {
0.dp
} else {
40.dp
}
}
.blur(
radiusX = blurRadius,
radiusY = blurRadius,
edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp))
)
)
// [END android_compose_image_blur]
}
@Preview
@Composable
private fun ImageBlurBox() {
// [START android_compose_image_blur]
var blurRadius by remember { mutableStateOf(40.dp) }
// [START android_compose_image_blur]
Box(
modifier = Modifier
.background(Color.Black)
.size(150.dp)
.blur(blurRadius).clickable {
blurRadius = if (blurRadius == 40.dp) {
0.dp
} else {
40.dp
}
}
) {
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(150.dp)
)
}
// [END android_compose_image_blur]
}
@Preview
@Composable
private fun ImageBlurEdgeTreatment() {
// [START android_compose_image_blur_edge_treatment]
Image(
bitmap = rememberLocalImage(Res.drawable.image_dog),
contentDescription = "",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(150.dp)
.blur(
radiusX = 10.dp,
radiusY = 10.dp,
edgeTreatment = BlurredEdgeTreatment.Unbounded
)
.clip(RoundedCornerShape(8.dp))
)
// / [END android_compose_image_blur_edge_treatment]
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/CustomizeImageSnippets.kt | Kotlin | apache-2.0 | 14,186 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.feathertop
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.ui.tooling.preview.Preview
@OptIn(ExperimentalResourceApi::class)
@Preview
// [START android_compose_components_dialogparent]
@Composable
internal fun DialogExamples() {
// [START_EXCLUDE]
val openMinimalDialog = remember { mutableStateOf(false) }
val openDialogWithImage = remember { mutableStateOf(false) }
val openFullScreenDialog = remember { mutableStateOf(false) }
// [END_EXCLUDE]
val openAlertDialog = remember { mutableStateOf(false) }
// [START_EXCLUDE]
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Click the following button to toggle the given dialog example.")
Button(
onClick = { openMinimalDialog.value = !openMinimalDialog.value }
) {
Text("Minimal dialog component")
}
Button(
onClick = { openDialogWithImage.value = !openDialogWithImage.value }
) {
Text("Dialog component with an image")
}
Button(
onClick = { openAlertDialog.value = !openAlertDialog.value }
) {
Text("Alert dialog component with buttons")
}
Button(
onClick = { openFullScreenDialog.value = !openFullScreenDialog.value }
) {
Text("Full screen dialog")
}
// [END_EXCLUDE]
when {
// [START_EXCLUDE]
openMinimalDialog.value -> {
MinimalDialog(
onDismissRequest = { openMinimalDialog.value = false },
)
}
openDialogWithImage.value -> {
DialogWithImage(
onDismissRequest = { openDialogWithImage.value = false },
onConfirmation = {
openDialogWithImage.value = false
println("Confirmation registered") // Add logic here to handle confirmation.
},
bitmap = rememberLocalImage(Res.drawable.feathertop),
imageDescription = "",
)
}
openFullScreenDialog.value -> {
FullScreenDialog(
onDismissRequest = { openFullScreenDialog.value = false },
)
}
// [END_EXCLUDE]
openAlertDialog.value -> {
AlertDialogExample(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = {
openAlertDialog.value = false
println("Confirmation registered") // Add logic here to handle confirmation.
},
dialogTitle = "Alert dialog example",
dialogText = "This is an example of an alert dialog with buttons.",
icon = Icons.Default.Info
)
}
}
}
}
// [END android_compose_components_dialogparent]
// [START android_compose_components_minimaldialog]
@Composable
private fun MinimalDialog(onDismissRequest: () -> Unit) {
Dialog(onDismissRequest = { onDismissRequest() }) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.padding(16.dp)
.clickable {
onDismissRequest()
},
shape = RoundedCornerShape(16.dp),
) {
Text(
text = "This is a minimal dialog",
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center),
textAlign = TextAlign.Center,
)
}
}
}
// [END android_compose_components_minimaldialog]
// [START android_compose_components_dialogwithimage]
@Composable
private fun DialogWithImage(
onDismissRequest: () -> Unit,
onConfirmation: () -> Unit,
bitmap: ImageBitmap,
imageDescription: String,
) {
Dialog(onDismissRequest = { onDismissRequest() }) {
// Draw a rectangle shape with rounded corners inside the dialog
Card (
modifier = Modifier
.fillMaxWidth()
.height(375.dp)
.padding(16.dp),
shape = RoundedCornerShape(16.dp),
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
bitmap = bitmap,
contentDescription = imageDescription,
contentScale = ContentScale.Fit,
modifier = Modifier
.height(160.dp)
)
Text(
text = "This is a dialog with buttons and an image.",
modifier = Modifier.padding(16.dp),
)
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
) {
TextButton(
onClick = { onDismissRequest() },
modifier = Modifier.padding(8.dp),
) {
Text("Dismiss")
}
TextButton(
onClick = { onConfirmation() },
modifier = Modifier.padding(8.dp),
) {
Text("Confirm")
}
}
}
}
}
}
// [END android_compose_components_dialogwithimage]
// [START android_compose_components_alertdialog]
@Composable
private fun AlertDialogExample(
onDismissRequest: (() -> Unit)? = null,
onConfirmation: (() -> Unit)? = null,
dialogTitle: String = "dialogTitle",
dialogText: String = "dialogText",
icon: ImageVector = Icons.Default.Info,
) {
AlertDialog(
title = {
Text(text = dialogTitle)
},
text = {
Text(text = dialogText)
},
onDismissRequest = {
onDismissRequest?.invoke()
},
confirmButton = {
TextButton(
onClick = {
onConfirmation?.invoke()
}
) {
Text("Confirm")
}
},
dismissButton = {
TextButton(
onClick = {
onDismissRequest?.invoke()
}
) {
Text("Dismiss")
}
}
)
}
// [END android_compose_components_alertdialog]
// [START android_compose_components_fullscreendialog]
@Composable
private fun FullScreenDialog(onDismissRequest: () -> Unit) {
Dialog(
onDismissRequest = { onDismissRequest() },
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnBackPress = true,
),
) {
Surface (
modifier = Modifier
.fillMaxSize(),
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "This is a full screen dialog",
textAlign = TextAlign.Center,
)
TextButton(onClick = { onDismissRequest() }) {
Text("Dismiss")
}
}
}
}
}
// [END android_compose_components_fullscreendialog]
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Dialog.kt | Kotlin | apache-2.0 | 10,400 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Card
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
@Composable
internal fun DropdownMenu(
name: String = "点我的任意位置",
dropdownMenuItems: List<DropdownItem> = List(10) { DropdownItem("DropdownItem$it") },
modifier: Modifier = Modifier,
onItemClick: (DropdownItem) -> Unit = {}
) {
var isContextMenuVisible by rememberSaveable {
mutableStateOf(false)
}
var pressOffset by remember {
mutableStateOf(0.dp)
}
var itemHeight by remember {
mutableStateOf(0.dp)
}
val density = LocalDensity.current
val interactionSource = remember {
MutableInteractionSource()
}
Card(
elevation = 40.dp,
modifier = modifier
.onSizeChanged {
itemHeight = with(density) {
it.height.toDp()
}
}
) {
Box(
modifier = Modifier
.fillMaxWidth()
.indication(interactionSource, LocalIndication.current)
.pointerInput(true) {
detectTapGestures(
onLongPress = {
isContextMenuVisible = true
},
onPress = {
isContextMenuVisible = true
val press = PressInteraction.Press(it)
interactionSource.emit(press)
tryAwaitRelease()
interactionSource.emit(PressInteraction.Release(press))
},
onTap = {
isContextMenuVisible = true
},
onDoubleTap = {
isContextMenuVisible = true
}
)
}
.padding(16.dp)
) {
Text(text = name)
}
DropdownMenu(
expanded = isContextMenuVisible,
offset = DpOffset(x = 0.dp, y = 0.dp),
onDismissRequest = {
isContextMenuVisible = false
}) {
dropdownMenuItems.forEach { item ->
run {
DropdownMenuItem(
onClick = {
onItemClick(item)
isContextMenuVisible = false
}
) {
Text(text = item.text)
}
}
}
}
}
}
internal data class DropdownItem(
val text: String
) | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/DropdownMenu.kt | Kotlin | apache-2.0 | 4,535 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Button
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.random.Random
@Composable
internal fun FallingBalls() {
val game = remember { Game() }
val density = LocalDensity.current
Column {
Text(
"Catch balls!${if (game.finished) " Game over!" else ""}",
fontSize = 20.sp,
color = Color(218, 120, 91)
)
Text(
"Score: ${game.score} Time: ${game.elapsed / 1_000_000} Blocks: ${game.numBlocks.toInt()}",
fontSize = 20.sp
)
Row {
if (!game.started) {
Slider(
value = game.numBlocks / 20f,
onValueChange = { game.numBlocks = (it * 20f).coerceAtLeast(1f) },
modifier = Modifier.width(250.dp)
)
}
Button(
onClick = {
game.started = !game.started
if (game.started) {
game.start()
}
}
) {
Text(if (game.started) "Stop" else "Start", fontSize = 25.sp)
}
}
if (game.started) {
Box(modifier = Modifier.height(20.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(1f)
.onSizeChanged {
with(density) {
game.width = it.width.toDp()
game.height = it.height.toDp()
}
}
) {
game.pieces.forEachIndexed { index, piece -> Piece(index, piece) }
}
}
LaunchedEffect(Unit) {
while (true) {
var previousTimeNanos = withFrameNanos { it }
withFrameNanos {
if (game.started && !game.paused && !game.finished) {
game.update((it - previousTimeNanos).coerceAtLeast(0))
previousTimeNanos = it
}
}
}
}
}
}
@Composable
internal fun Piece(index: Int, piece: PieceData) {
val boxSize = 40.dp
Box(
Modifier
.offset(boxSize * index * 5 / 3, piece.position.dp)
.shadow(30.dp)
.clip(CircleShape)
) {
Box(
Modifier
.size(boxSize, boxSize)
.background(if (piece.clicked) Color.Gray else piece.color)
.clickable(onClick = { piece.click() })
)
}
}
data class PieceData(val game: Game, val velocity: Float, val color: Color) {
var clicked by mutableStateOf(false)
var position by mutableStateOf(0f)
fun update(dt: Long) {
if (clicked) return
val delta = (dt / 1E8 * velocity).toFloat()
position = if (position < game.height.value) position + delta else 0f
}
fun click() {
if (!clicked && !game.paused) {
clicked = true
game.clicked(this)
}
}
}
class Game {
private val colors = arrayOf(
Color.Red, Color.Blue, Color.Cyan,
Color.Magenta, Color.Yellow, Color.Black
)
var width by mutableStateOf(0.dp)
var height by mutableStateOf(0.dp)
var pieces = mutableStateListOf<PieceData>()
private set
var elapsed by mutableStateOf(0L)
var score by mutableStateOf(0)
private var clicked by mutableStateOf(0)
var started by mutableStateOf(false)
var paused by mutableStateOf(false)
var finished by mutableStateOf(false)
var numBlocks by mutableStateOf(5f)
fun start() {
clicked = 0
started = true
finished = false
paused = false
pieces.clear()
repeat(numBlocks.toInt()) { index ->
pieces.add(
PieceData(
this,
index * 1.5f + 5f,
colors[index % colors.size]
).also { piece ->
piece.position = Random.nextDouble(0.0, 100.0).toFloat()
})
}
}
fun update(deltaTimeNanos: Long) {
elapsed += deltaTimeNanos
pieces.forEach { it.update(deltaTimeNanos) }
}
fun clicked(piece: PieceData) {
score += piece.velocity.toInt()
clicked++
if (clicked == numBlocks.toInt()) {
finished = true
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/FallingBalls.kt | Kotlin | apache-2.0 | 6,620 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FractionalThreshold
import androidx.compose.material.Text
import androidx.compose.material.rememberSwipeableState
import androidx.compose.material.swipeable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
import kotlin.math.roundToInt
@Composable
internal fun GestureDemo() {
Column {
DraggableText()
DraggableTextLowLevel()
}
}
@Composable
internal fun NestedScrollDemo() {
AutomaticNestedScroll()
}
@Preview
// [START android_compose_touchinput_gestures_clickable]
@Composable
private fun ClickableSample() {
val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(
text = count.value.toString(),
modifier = Modifier.clickable { count.value += 1 }
)
}
// [END android_compose_touchinput_gestures_clickable]
@Preview
@Composable
private fun WithPointerInput() {
val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(
text = count.value.toString(),
modifier =
// [START android_compose_touchinput_gestures_pointerinput]
Modifier.pointerInput(Unit) {
detectTapGestures(
onPress = {},
onDoubleTap = {},
onLongPress = {},
onTap = {}
)
}
// [END android_compose_touchinput_gestures_pointerinput]
)
}
@Preview
// [START android_compose_touchinput_gestures_vertical_scroll]
@Composable
private fun ScrollBoxes() {
Column(
modifier = Modifier
.background(Color.LightGray)
.size(100.dp)
.verticalScroll(rememberScrollState())
) {
repeat(10) {
Text("Item $it", modifier = Modifier.padding(2.dp))
}
}
}
// [END android_compose_touchinput_gestures_vertical_scroll]
@Preview
// [START android_compose_touchinput_gestures_smooth_scroll]
@Composable
private fun ScrollBoxesSmooth() {
// Smoothly scroll 100px on first composition
val state = rememberScrollState()
LaunchedEffect(Unit) { state.animateScrollTo(100) }
Column(
modifier = Modifier
.background(Color.LightGray)
.size(100.dp)
.padding(horizontal = 8.dp)
.verticalScroll(state)
) {
repeat(10) {
Text("Item $it", modifier = Modifier.padding(2.dp))
}
}
}
// [END android_compose_touchinput_gestures_smooth_scroll]
@Preview
// [START android_compose_touchinput_gestures_scrollable]
@Composable
private fun ScrollableSample() {
// actual composable state
var offset by remember { mutableStateOf(0f) }
Box(
Modifier
.size(150.dp)
.scrollable(
orientation = Orientation.Vertical,
// Scrollable state: describes how to consume
// scrolling delta and update offset
state = rememberScrollableState { delta ->
offset += delta
delta
}
)
.background(Color.LightGray),
contentAlignment = Alignment.Center
) {
Text(offset.toString())
}
}
// [END android_compose_touchinput_gestures_scrollable]
// [START android_compose_touchinput_gestures_nested_scroll]
@Composable
private fun AutomaticNestedScroll() {
val gradient = Brush.verticalGradient(0f to Color.Gray, 1000f to Color.White)
Box(
modifier = Modifier
// .background(Color.LightGray)
.verticalScroll(rememberScrollState())
.padding(32.dp)
) {
Column {
repeat(6) {
Box(
modifier = Modifier
.height(128.dp)
.verticalScroll(rememberScrollState())
) {
Text(
"Scroll here",
modifier = Modifier
.border(12.dp, Color.DarkGray)
.background(brush = gradient)
.padding(24.dp)
.height(150.dp)
)
}
}
}
}
}
// [START android_compose_touchinput_gestures_draggable]
@Composable
private fun DraggableText() {
var offsetX by remember { mutableStateOf(0f) }
Text(
modifier = Modifier
.offset { IntOffset(offsetX.roundToInt(), 0) }
.draggable(
orientation = Orientation.Horizontal,
state = rememberDraggableState { delta ->
offsetX += delta
}
),
text = "Drag me!"
)
}
// [END android_compose_touchinput_gestures_draggable]
// [START android_compose_touchinput_gestures_draggable_pointerinput]
@Composable
private fun DraggableTextLowLevel() {
Box(modifier = Modifier.fillMaxSize()) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
Box(
Modifier
.offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
.background(Color.Blue)
.size(50.dp)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consume()
offsetX += dragAmount.x
offsetY += dragAmount.y
}
}
)
}
}
// [END android_compose_touchinput_gestures_draggable_pointerinput]
// [START android_compose_touchinput_gestures_swipeable]
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun SwipeableSample() {
val width = 96.dp
val squareSize = 48.dp
val swipeableState = rememberSwipeableState(0)
val sizePx = with(LocalDensity.current) { squareSize.toPx() }
val anchors = mapOf(0f to 0, sizePx to 1) // Maps anchor points (in px) to states
Box(
modifier = Modifier
.width(width)
.swipeable(
state = swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
.background(Color.LightGray)
) {
Box(
Modifier
.offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
.size(squareSize)
.background(Color.DarkGray)
)
}
}
// [END android_compose_touchinput_gestures_swipeable]
// [START android_compose_touchinput_gestures_transformable]
@Composable
private fun TransformableSample() {
// set up all transformation states
var scale by remember { mutableStateOf(1f) }
var rotation by remember { mutableStateOf(0f) }
var offset by remember { mutableStateOf(Offset.Zero) }
val state = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
scale *= zoomChange
rotation += rotationChange
offset += offsetChange
}
Box(
Modifier
// apply other transformations like rotation and zoom
// on the pizza slice emoji
.graphicsLayer(
scaleX = scale,
scaleY = scale,
rotationZ = rotation,
translationX = offset.x,
translationY = offset.y
)
// add transformable to listen to multitouch transformation events
// after offset
.transformable(state = state)
.background(Color.Blue)
.fillMaxSize()
)
}
// [END android_compose_touchinput_gestures_transformable] | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/GesturesSnippets.kt | Kotlin | apache-2.0 | 10,550 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.big_image
import composesample.composeapp.generated.resources.image_cat
import composesample.composeapp.generated.resources.image_dog
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun SimpleImage() {
// Column {
Column(modifier = Modifier.verticalScroll(rememberScrollState()).fillMaxWidth()) {
Spacer(modifier = Modifier.fillMaxWidth().height(1.dp).background(Color.Red))
val contentScaleOptions = listOf(
"ContentScale.Crop" to ContentScale.Crop, // 1
"ContentScale.Fit" to ContentScale.Fit, // 2
"ContentScale.FillBounds" to ContentScale.FillBounds, // 3
"ContentScale.FillWidth" to ContentScale.FillWidth, // 4
"ContentScale.FillHeight" to ContentScale.FillHeight, // 5
"ContentScale.Inside" to ContentScale.Inside, // 6
"ContentScale.None" to ContentScale.None // 7
)
val alignmentsList = listOf(
listOf(Alignment.TopCenter, Alignment.TopEnd, Alignment.BottomStart), // 1
listOf(Alignment.CenterStart, Alignment.Center, Alignment.BottomEnd), // 2
listOf(Alignment.TopStart, Alignment.BottomCenter, Alignment.BottomStart), // 3
listOf(Alignment.TopStart, Alignment.CenterStart, Alignment.BottomStart), // 4
listOf(Alignment.CenterStart, Alignment.Center, Alignment.BottomEnd), // 5
listOf(Alignment.TopStart, Alignment.BottomCenter, Alignment.BottomStart), // 6
listOf(Alignment.TopCenter, Alignment.TopEnd, Alignment.BottomStart), // 7
)
val clips = listOf(
CircleShape
)
for ((index, pair) in contentScaleOptions.withIndex()) {
val (title, scale) = pair
val clipShape = clips.getOrNull(index)
Text(title)
Row(modifier = Modifier.fillMaxWidth()) {
val customAlignments = alignmentsList[index]
for (alignment in customAlignments) {
Image(
bitmap = rememberLocalImage(Res.drawable.big_image),
contentDescription = null,
alignment = alignment,
contentScale = scale,
modifier = Modifier
.size(100.dp)
.background(Color.Yellow)
.padding(1.dp)
.graphicsLayer(
shape = clipShape ?: RectangleShape,
clip = clipShape != null
)
)
}
}
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Image.kt | Kotlin | apache-2.0 | 4,743 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
internal fun ManyViewsPage(count: Int) {
// val startTime = remember { getTimeMillis() }
// LaunchedEffect(Unit) {
// val endTime = getTimeMillis()
// println("ManyViewsPage 渲染耗时: ${endTime - startTime} ms")
// }
Column(
// LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.verticalScroll(rememberScrollState()) // Enable vertical scrolling
) {
repeat(count) { index ->
// items(count) { index ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.padding(vertical = 2.dp)
.background(if (index % 2 == 0) Color.LightGray else Color.White)
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ManyViewsPage.kt | Kotlin | apache-2.0 | 2,140 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
internal fun ManyViewsPage2(count: Int) {
// Column(
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
// .verticalScroll(rememberScrollState()) // Enable vertical scrolling
) {
// repeat(count) { index ->
items(count) { index ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.padding(vertical = 2.dp)
.background(if (index % 2 == 0) Color.LightGray else Color.White)
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ManyViewsPage2.kt | Kotlin | apache-2.0 | 1,946 |
// AppTabScreen.kt
package com.tencent.compose.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.* // remember, mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/**
* Compose implementation of AppTabPage (simplified).
*
* - AppHomeScreen is used for tab 0.
* - Other tabs show AppEmptyScreen (with title).
* - Icons are simple placeholder circles with the icon name as text.
*
* Replace placeholder image drawing with your own image loader (painterResource, AsyncImage, etc).
*/
/** Empty page shown for non-home tabs. */
@Composable
internal fun AppEmptyScreen(title: String) {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Box(contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = title, fontSize = 24.sp, color = MaterialTheme.colorScheme.onBackground)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Placeholder content", color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f))
}
}
}
}
@Composable
internal fun AppTabScreen(
// titles for bottom tab bar
titles: List<String> = listOf("Home", "Video", "Discover", "Message", "Me"),
// icon names (strings) for placeholders; you can map to actual resource ids in real app
icons: List<String> = listOf("home", "video", "discover", "msg", "me"),
initialSelectedIndex: Int = 0,
tabBarHeightDp: Int = 80,
onTabSelected: ((index: Int) -> Unit)? = null
) {
var selectedIndex by remember { mutableStateOf(initialSelectedIndex.coerceIn(0, titles.size - 1)) }
// Simple theme colors (use MaterialTheme in real app)
val bgColor = MaterialTheme.colorScheme.background
val tabBackground = MaterialTheme.colorScheme.surface
val textFocused = MaterialTheme.colorScheme.primary
val textUnfocused = MaterialTheme.colorScheme.onSurfaceVariant
Column(modifier = Modifier.fillMaxSize().background(bgColor)) {
// status bar spacer (you can adjust or remove)
Spacer(modifier = Modifier.height(0.dp))
// Content area (page)
Box(modifier = Modifier
.weight(1f)
.fillMaxSize()
) {
when (selectedIndex) {
0 -> AppHomePreview()
else -> AppEmptyScreen(title = titles.getOrNull(selectedIndex) ?: "Page ${selectedIndex + 1}")
}
}
// Bottom tab bar
Row(
modifier = Modifier
.height(tabBarHeightDp.dp)
.fillMaxSize()
.background(tabBackground),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically
) {
val count = titles.size.coerceAtLeast(icons.size)
for (i in 0 until count) {
val title = titles.getOrNull(i) ?: "Tab $i"
val iconName = icons.getOrNull(i) ?: title.lowercase()
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.weight(1f)
.clickable {
selectedIndex = i
onTabSelected?.invoke(i)
}
.padding(vertical = 6.dp)
) {
// placeholder icon (circle with text). Replace with real Image painter in production.
PlaceholderIcon(
text = iconName,
isSelected = (i == selectedIndex),
sizeDp = 30
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = title,
fontSize = 12.sp,
color = if (i == selectedIndex) textFocused else textUnfocused,
textAlign = TextAlign.Center
)
}
}
}
}
}
@Composable
private fun PlaceholderIcon(text: String, isSelected: Boolean, sizeDp: Int = 30) {
// if in preview or without resources, show simple circle with text
val bg = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f)
val fg = if (isSelected) Color.White else MaterialTheme.colorScheme.onSurfaceVariant
Box(
modifier = Modifier
.size(sizeDp.dp)
.clip(CircleShape)
.background(bg),
contentAlignment = Alignment.Center
) {
Text(
text = text.take(2).uppercase(),
color = fg,
fontSize = 12.sp,
textAlign = TextAlign.Center
)
}
}
/** A simple placeholder for the Home page. Replace with your real AppHomeScreen implementation. */
@Composable
internal fun AppHomeScreen() {
// simple static content to represent home screen
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text("App Home", fontSize = 28.sp, color = MaterialTheme.colorScheme.primary)
Spacer(modifier = Modifier.height(8.dp))
Text(
"This is the placeholder for the original AppHomePage.\nReplace with your real Compose content.",
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onBackground
)
}
}
}
/** Preview (Android Studio) */
@Composable
internal fun PreviewAppTabScreen() {
// When previewing, MaterialTheme may not be set, but it's okay.
AppTabScreen()
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/PreviewAppTabScreen.kt | Kotlin | apache-2.0 | 6,966 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.compose.ui.tooling.preview.Preview
@Preview
@Composable
internal fun ProgressIndicatorExamples() {
Column(
modifier = Modifier
.padding(48.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Determinate linear indicator:")
LinearDeterminateIndicator()
Text("Indeterminate linear indicator:")
IndeterminateLinearIndicator()
Text("Determinate circular indicator:")
CircularDeterminateIndicator()
Text("Indeterminate circular indicator:")
IndeterminateCircularIndicator()
}
}
@Preview
// [START android_compose_components_determinateindicator]
@Composable
private fun LinearDeterminateIndicator() {
var currentProgress by remember { mutableStateOf(0f) }
var loading by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope() // Create a coroutine scope
Column(
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = {
loading = true
scope.launch {
loadProgress { progress ->
currentProgress = progress
}
loading = false // Reset loading when the coroutine finishes
}
}, enabled = !loading) {
Text("Start loading")
}
if (loading) {
LinearProgressIndicator(
progress = currentProgress,
modifier = Modifier.fillMaxWidth(),
)
}
}
}
/** Iterate the progress value */
private suspend fun loadProgress(updateProgress: (Float) -> Unit) {
for (i in 1..100) {
updateProgress(i.toFloat() / 100)
delay(100)
}
}
// [END android_compose_components_determinateindicator]
@Preview
@Composable
private fun CircularDeterminateIndicator() {
var currentProgress by remember { mutableStateOf(0f) }
var loading by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope() // Create a coroutine scope
Column(
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = {
loading = true
scope.launch {
loadProgress { progress ->
currentProgress = progress
}
loading = false // Reset loading when the coroutine finishes
}
}, enabled = !loading) {
Text("Start loading")
}
if (loading) {
CircularProgressIndicator(
progress = currentProgress,
modifier = Modifier.width(64.dp),
)
}
}
}
@Preview
@Composable
private fun IndeterminateLinearIndicator() {
var loading by remember { mutableStateOf(false) }
Button(onClick = { loading = true }, enabled = !loading) {
Text("Start loading")
}
if (!loading) return
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth()
)
}
@Preview
// [START android_compose_components_indeterminateindicator]
@Composable
private fun IndeterminateCircularIndicator() {
var loading by remember { mutableStateOf(false) }
Button(onClick = { loading = true }, enabled = !loading) {
Text("Start loading")
}
if (!loading) return
CircularProgressIndicator(
modifier = Modifier.width(64.dp)
)
}
// [END android_compose_components_indeterminateindicator]
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ProgressIndicator.kt | Kotlin | apache-2.0 | 5,483 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.RangeSlider
import androidx.compose.material.Slider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
@Preview
@Composable
internal fun SliderExamples() {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Minimal slider component")
SliderMinimalExample()
Text("Advanced slider component")
SliderAdvancedExample()
Text("Range slider component")
RangeSliderExample()
}
}
// [START android_compose_components_sliderminimal]
@Preview
@Composable
private fun SliderMinimalExample() {
var sliderPosition by remember { mutableFloatStateOf(0f) }
Column {
Slider(
value = sliderPosition,
onValueChange = { sliderPosition = it },
modifier = Modifier.testTag("minimalSlider"),
)
Text(text = sliderPosition.toString())
}
}
// [END android_compose_components_sliderminimal]
// [START android_compose_components_slideradvanced]
@Preview
@Composable
private fun SliderAdvancedExample() {
var sliderPosition by remember { mutableFloatStateOf(0f) }
Column {
Slider(
value = sliderPosition,
onValueChange = { sliderPosition = it },
steps = 3,
valueRange = 0f..50f,
modifier = Modifier.testTag("advancedSlider")
)
Text(text = sliderPosition.toString())
}
}
// [END android_compose_components_slideradvanced]
// [START android_compose_components_rangeslider]
@OptIn(ExperimentalMaterialApi::class)
@Preview
@Composable
internal fun RangeSliderExample() {
var sliderPosition by remember { mutableStateOf(0f..100f) }
Column {
RangeSlider(
value = sliderPosition,
steps = 5,
onValueChange = { range -> sliderPosition = range },
valueRange = 0f..100f,
onValueChangeFinished = {
// launch some business logic update with the state you hold
// viewModel.updateSelectedSliderValue(sliderPosition)
},
modifier = Modifier.testTag("rangeSlider")
)
Text(text = sliderPosition.toString())
}
}
// [END android_compose_components_rangeslider]
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Slider.kt | Kotlin | apache-2.0 | 3,915 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Switch
import androidx.compose.material.SwitchDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
@Preview
@Composable
internal fun SwitchExamples() {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text("Minimal switch component")
SwitchMinimalExample()
Text("Switch with label")
SwitchWithLabelMinimalExample()
Text("Switch with custom colors")
SwitchWithCustomColors()
}
}
@Preview
// [START android_compose_components_switchminimal]
@Composable
private fun SwitchMinimalExample() {
var checked by remember { mutableStateOf(true) }
Switch(
checked = checked,
onCheckedChange = {
checked = it
}, modifier = Modifier.testTag("minimalSwitch")
)
}
// [END android_compose_components_switchminimal]
@Preview
// [START android_compose_components_switchwithlabel]
@Composable
private fun SwitchWithLabelMinimalExample() {
var checked by remember { mutableStateOf(true) }
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.padding(8.dp),
text = if (checked) "Checked" else "Unchecked",
)
Switch(
checked = checked,
onCheckedChange = {
checked = it
}, modifier = Modifier.testTag("minimalLabelSwitch")
)
}
}
// [END android_compose_components_switchwithlabel]
@Preview
// [START android_compose_components_switchwithcustomcolors]
@Composable
private fun SwitchWithCustomColors() {
var checked by remember { mutableStateOf(true) }
Switch(
checked = checked,
onCheckedChange = {
checked = it
},
modifier = Modifier.testTag("customSwitch"),
colors = SwitchDefaults.colors(
checkedThumbColor = Color(0.4f, 0.3137255f, 0.6431373f, 1.0f),
checkedTrackColor = Color(0.91764706f, 0.8666667f, 1.0f, 1.0f),
uncheckedThumbColor = Color(0.38431373f, 0.35686275f, 0.44313726f, 1.0f),
uncheckedTrackColor = Color(0.9098039f, 0.87058824f, 0.972549f, 1.0f),
)
)
}
// [END android_compose_components_switchwithcustomcolors]
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Switch.kt | Kotlin | apache-2.0 | 3,903 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
internal fun SimpleTextPage() {
val textContent = "Compose Text 文本 & AnnotatedString 多种样式的文本的基本数据结构"
LazyColumn(modifier = Modifier.fillMaxSize().fillMaxHeight()) {
item {
AnnotatedStringTextPage()
}
item {
Text(
text = "fontSize = 16.sp color = Red $textContent",
color = Color.Red,
fontSize = 16.sp
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "fontSize = 18.sp color = Blue, $textContent",
color = Color.Blue,
fontSize = 18.sp
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "FontWeight.Light, $textContent",
fontWeight = FontWeight.Light
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "FontWeight.Bold, $textContent",
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "FontWeight.Black, $textContent",
fontWeight = FontWeight.Black
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "FontFamily.Cursive, $textContent",
fontFamily = FontFamily.Cursive
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "FontFamily.Serif, $textContent",
fontFamily = FontFamily.Serif
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "letterSpacing = 4.sp, $textContent",
letterSpacing = 4.sp
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextDecoration.Underline, $textContent",
textDecoration = TextDecoration.Underline
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextDecoration.LineThrough, $textContent",
textDecoration = TextDecoration.LineThrough
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextAlign.Left, $textContent",
textAlign = TextAlign.Left,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextAlign.Center, $textContent",
textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextAlign.Right, $textContent",
textAlign = TextAlign.Right,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextAlign.Justify, $textContent",
textAlign = TextAlign.Justify,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "lineHeight = 40.sp, $textContent",
lineHeight = 40.sp,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextOverflow.Clip, $textContent",
overflow = TextOverflow.Clip,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "softWrap = false, $textContent $textContent",
softWrap = false,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "TextOverflow.Ellipsis, $textContent $textContent",
overflow = TextOverflow.Ellipsis,
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "style = background:Color.Gray, $textContent",
style = TextStyle(background = Color.Gray)
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
item {
Text(
text = "style = Brush.linearGradient, $textContent",
style = TextStyle(
brush = Brush.linearGradient(
colors = listOf(Color.Red, Color.Blue)
), alpha = 0.8f
)
)
Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
}
}
}
@Composable
private fun AnnotatedStringTextPage() {
val annotatedString3 = buildAnnotatedString {
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Blue)) {
append("Compose Text ")
}
withStyle(style = SpanStyle()) {
append("通过")
}
withStyle(style = SpanStyle(fontStyle = FontStyle.Italic, color = Color.Red)) {
append(" AnnotatedString ")
}
withStyle(style = SpanStyle()) {
append("设置富文本效果!")
}
withStyle(style = SpanStyle(color = Color.Red)) {
append("点击 www.qq.com")
}
addStringAnnotation(
tag = "URL",
annotation = "https://v.qq.com",
start = 40,
end = 55
)
}
Column(modifier = Modifier.fillMaxSize()) {
Text(text = annotatedString3, modifier = Modifier.clickable {
annotatedString3.getStringAnnotations("URL", 7, 14)
.firstOrNull()?.let { it ->
println("jump to v.qq.com $it")
}
})
ClickableText(
text = AnnotatedString("ClickableText ") + annotatedString3,
onClick = { integer ->
annotatedString3.getStringAnnotations("URL", integer, integer).firstOrNull()?.let {
println("jump to v.qq.com $it")
}
})
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Text.kt | Kotlin | apache-2.0 | 8,778 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
@Composable
internal fun TextField2() {
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var age by remember { mutableStateOf("") }
var email by remember { mutableStateOf("") }
Column(modifier = Modifier.fillMaxWidth()) {
Text("用户名")
TextField(
value = username,
placeholder = { Text("请输入用户名") },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone,
imeAction = ImeAction.Next
),
onValueChange = {
username = it
},
modifier = Modifier.fillMaxWidth()
)
Text("密码")
TextField(
value = password,
placeholder = { Text("请输入密码") },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.NumberPassword,
imeAction = ImeAction.Next
),
onValueChange = {
password = it
},
modifier = Modifier.fillMaxWidth()
)
Text("年龄")
TextField(
value = age,
placeholder = { Text("请输入年龄") },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
onValueChange = {
age = it
},
modifier = Modifier.fillMaxWidth()
)
Text("邮箱")
TextField(
value = email,
placeholder = { Text("请输入邮箱") },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next
),
onValueChange = {
email = it
},
modifier = Modifier.fillMaxWidth()
)
val focusManager = LocalFocusManager.current
Button(onClick = {
focusManager.clearFocus()
}, modifier = Modifier.fillMaxWidth()) {
Text("注册")
}
DisposableEffect(Unit) {
onDispose {
focusManager.clearFocus()
}
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/TextField2.kt | Kotlin | apache-2.0 | 3,880 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
@Composable
internal fun TextField3() {
var mobile by remember { mutableStateOf("") }
var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
Dialog(
onDismissRequest = { showDialog = false },
content = {
Column(Modifier.fillMaxWidth().background(Color.White).padding(30.dp)) {
Text("手机号")
TextField(
value = mobile,
placeholder = { Text("请输入手机号") },
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone,
imeAction = ImeAction.Next
),
onValueChange = {
mobile = it
},
modifier = Modifier.fillMaxWidth()
)
Button(onClick = {}, modifier = Modifier.fillMaxWidth()) {
Text("注册")
}
}
}
)
}
Column(Modifier.fillMaxWidth()) {
Row {
Button(onClick = {
showDialog = true
}, modifier = Modifier.padding(20.dp)) {
Text("注册")
}
}
}
val focusManager = LocalFocusManager.current
DisposableEffect(Unit) {
onDispose {
focusManager.clearFocus()
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/TextField3.kt | Kotlin | apache-2.0 | 3,288 |
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.round
import kotlin.random.Random
import kotlin.time.TimeSource
data class Sample(val tMs: Long, val all: Int, val normal: Int, val video: Int)
@Composable
internal fun The300Threads() {
val scope = rememberCoroutineScope()
var running by remember { mutableStateOf(false) }
var progress by remember { mutableStateOf(0) }
val total = 300
val logs = remember { mutableStateListOf<String>() }
val logClock = remember { TimeSource.Monotonic }
val samples = remember { mutableStateListOf<Sample>() }
var runStart by remember { mutableStateOf(TimeSource.Monotonic.markNow()) }
fun pushLog(line: String) {
val ts = logClock.markNow().elapsedNow().inWholeMilliseconds
val msg = "[$ts] $line"
println(msg)
logs += msg
if (logs.size > 2000) logs.removeFirst()
}
fun pushSample(all: Int, normal: Int, video: Int) {
val t = runStart.elapsedNow().inWholeMilliseconds
samples += Sample(t, all, normal, video)
if (samples.size > 4000) samples.removeFirst()
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
// 顶部操作区
Row(verticalAlignment = Alignment.CenterVertically) {
Button(
enabled = !running,
onClick = {
running = true
progress = 0
logs.clear()
samples.clear()
runStart = TimeSource.Monotonic.markNow()
scope.launch {
val totalTimer = TimeSource.Monotonic.markNow()
pushLog("LAUNCH mixed tasks: 299 normal + 1 video")
val specialIndex = total - 1
runNCoroutinesMixedVerbose(
total = total,
specialIndex = specialIndex,
onProgress = { v ->
withContext(Dispatchers.Main) { progress = v }
},
onLog = { line ->
withContext(Dispatchers.Main) { pushLog(line) }
},
onActiveChange = { all, normal, video ->
withContext(Dispatchers.Main) { pushSample(all, normal, video) }
},
doNormalWork = { simulateNormalWork() },
doVideoWork = { simulateVideoWork() }
)
val cost = totalTimer.elapsedNow().inWholeMilliseconds
pushLog("ALL DONE in ${cost}ms")
running = false
}
}
) { Text(if (running) "运行中…" else "Run 300 Mixed Tasks") }
Spacer(Modifier.width(12.dp))
Button(enabled = !running, onClick = {
logs.clear(); samples.clear()
}) { Text("清空") }
}
Spacer(Modifier.height(8.dp))
Text("进度:$progress / $total", fontWeight = FontWeight.Medium)
Spacer(Modifier.height(12.dp))
ConcurrencyChart(
samples = samples.toList(),
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.border(1.dp, Color(0x22000000))
.background(Color(0xFFF9FAFB))
.padding(8.dp)
)
Spacer(Modifier.height(12.dp))
val scroll = rememberScrollState()
LaunchedEffect(logs.size) { scroll.animateScrollTo(scroll.maxValue) }
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.verticalScroll(scroll)
.padding(8.dp)
.background(Color(0xFFF3F4F6))
) {
Text(logs.joinToString("\n"))
}
}
}
}
suspend fun runNCoroutinesMixedVerbose(
total: Int,
specialIndex: Int,
onProgress: suspend (Int) -> Unit,
onLog: suspend (String) -> Unit,
onActiveChange: suspend (all: Int, normal: Int, video: Int) -> Unit,
doNormalWork: suspend () -> Unit,
doVideoWork: suspend () -> Unit
) = coroutineScope {
val progressMutex = Mutex()
var counter = 0
val activeMutex = Mutex()
var activeAll = 0
var activeNormal = 0
var activeVideo = 0
suspend fun reportActive() {
val (a, n, v) = activeMutex.withLock { Triple(activeAll, activeNormal, activeVideo) }
onActiveChange(a, n, v)
}
suspend fun inc(isVideo: Boolean) {
activeMutex.withLock {
activeAll++
if (isVideo) activeVideo++ else activeNormal++
}
reportActive()
}
suspend fun dec(isVideo: Boolean) {
activeMutex.withLock {
activeAll--
if (isVideo) activeVideo-- else activeNormal--
}
reportActive()
}
repeat(total) { id ->
val isVideo = (id == specialIndex)
val name = if (isVideo) "video-$id" else "normal-$id"
val dispatcher = if (isVideo) Dispatchers.IO else Dispatchers.Default
launch(dispatcher + CoroutineName(name)) {
val coName = coroutineContext[CoroutineName]?.name ?: name
onLog("LAUNCH $coName")
inc(isVideo)
val t = TimeSource.Monotonic.markNow()
onLog("START $coName")
try {
if (isVideo) doVideoWork() else doNormalWork()
val elapsed = t.elapsedNow().inWholeMilliseconds
val v = progressMutex.withLock { ++counter }
onLog("END $coName elapsed=${elapsed}ms progress=$v/$total")
onProgress(v)
} catch (e: CancellationException) {
onLog("CANCEL $coName")
throw e
} catch (e: Throwable) {
val v = progressMutex.withLock { ++counter }
onLog("ERROR $coName -> ${e::class.simpleName}: ${e.message} progress=$v/$total")
onProgress(v)
} finally {
dec(isVideo)
}
}
}
}
private suspend fun simulateNormalWork() {
delay(Random.nextLong(1000, 5000))
}
private suspend fun simulateVideoWork() {
delay(1500)
delay(2000)
repeat(5) { delay(1200) }
}
@Composable
private fun ConcurrencyChart(
samples: List<Sample>,
modifier: Modifier = Modifier
) {
if (samples.isEmpty()) {
Box(modifier, contentAlignment = Alignment.Center) {
androidx.compose.material.Text("等待任务开始…")
}
return
}
val maxAll = (samples.maxOfOrNull { it.all } ?: 0).coerceAtLeast(1)
val t0 = samples.first().tMs
val timeMax = (samples.last().tMs - t0).coerceAtLeast(1L)
val xTicks = buildNiceTimeTicks(0.0, timeMax.toDouble(), targetTickCount = 6)
val textMeasurer = rememberTextMeasurer()
val tickTextStyle = TextStyle(fontSize = 10.sp, color = Color(0xFF374151)) // gray-700
Canvas(modifier = modifier) {
val w = size.width
val h = size.height
val padL = 52f
val padR = 12f
val padT = 12f
val padB = 30f
val chartW = w - padL - padR
val chartH = h - padT - padB
fun xAt(tRelMs: Long): Float {
val ratio = tRelMs / timeMax.toFloat()
return padL + chartW * ratio.coerceIn(0f, 1f)
}
fun yAt(v: Int): Float {
val ratio = v / maxAll.toFloat()
return padT + chartH * (1f - ratio)
}
val ySteps = 5
for (i in 0..ySteps) {
val v = maxAll * i / ySteps
val y = yAt(v)
drawLine(
start = Offset(padL, y),
end = Offset(padL + chartW, y),
color = Color(0x22000000),
strokeWidth = 1f
)
val layout = textMeasurer.measure(AnnotatedString(v.toString()), style = tickTextStyle)
drawText(
textLayoutResult = layout,
topLeft = Offset(8f, y - layout.size.height / 2f)
)
}
for (tick in xTicks) {
val x = xAt(tick.toLong())
drawLine(
start = Offset(x, padT),
end = Offset(x, padT + chartH),
color = Color(0x22000000),
strokeWidth = 1f
)
val label = formatDurationShort(tick.toLong()) // 如 0ms / 200ms / 1.2s
val layout = textMeasurer.measure(AnnotatedString(label), style = tickTextStyle)
drawText(
textLayoutResult = layout,
topLeft = Offset(x - layout.size.width / 2f, h - layout.size.height - 4f)
)
}
drawLine(
start = Offset(padL, padT),
end = Offset(padL, padT + chartH),
color = Color(0x99000000),
strokeWidth = 2f
)
drawLine(
start = Offset(padL, padT + chartH),
end = Offset(padL + chartW, padT + chartH),
color = Color(0x99000000),
strokeWidth = 2f
)
fun drawSeries(selector: (Sample) -> Int, color: Color, stroke: Float) {
val path = Path()
val first = samples.first()
path.moveTo(xAt(first.tMs - t0), yAt(selector(first)))
for (i in 1 until samples.size) {
val s = samples[i]
path.lineTo(xAt(s.tMs - t0), yAt(selector(s)))
}
drawPath(path, color = color, style = Stroke(width = stroke))
}
drawSeries({ it.all }, Color(0xFF2563EB), 3f) // blue-600
drawSeries({ it.normal }, Color(0xFF16A34A), 2f) // green-600
drawSeries({ it.video }, Color(0xFFDC2626), 2.5f) // red-600
}
}
private fun buildNiceTimeTicks(
min: Double,
max: Double,
targetTickCount: Int = 6
): List<Double> {
val range = (max - min).coerceAtLeast(1.0)
val rawStep = range / targetTickCount
val mag = 10.0.pow(floor(ln(rawStep) / ln(10.0)))
val candidates = doubleArrayOf(1.0, 2.0, 5.0, 10.0) // 1/2/5 系列
val step = candidates.minByOrNull { kotlin.math.abs(rawStep - it * mag) }!! * mag
val start = floor(min / step) * step
val end = round(max / step) * step
val ticks = ArrayList<Double>()
var v = start
while (v <= end + step * 0.5) {
ticks += v
v += step
}
return ticks
}
private fun formatDurationShort(ms: Long): String {
return if (ms < 1000L) {
"${ms}ms"
} else {
val s = ms / 1000.0
val rounded = round(s * 10) / 10.0
"${rounded}s"
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/The300Threads.kt | Kotlin | apache-2.0 | 12,480 |
package com.tencent.compose.sample.mainpage.sectionItem
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
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.onGloballyPositioned
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun composeView1500Page() {
val loaded = remember { mutableStateOf(false) }
// val startTime = remember { getTimeMillis() }
//
// LaunchedEffect(Unit) {
// trace_tag_begin()
// val duration = getTimeMillis() - startTime
// println("dzy Compose 页面构建 + 渲染耗时:${duration}ms")
// }
// SideEffect {
// trace_tag_end()
// }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
// trace_tag_begin()
// 创建1500个Box
repeat(1500) { index ->
Box(
modifier = Modifier
.size(300.dp, 100.dp) // 设置宽高均为300dp
.border(
width = 2.dp, // 边框宽度
color = Color.Red, // 边框颜色为红色
)
.then(
if (index == 1499) Modifier.onGloballyPositioned {
// 最后一个 Box 被布局 -> 页面“加载完成”
loaded.value = true
//trace_tag_end()
} else Modifier
)
) {
Text(
text = "Item #$index",
)
}
}
// trace_tag_end()
}
if (loaded.value) {
// 可以做其它“加载完成”后的逻辑
println("页面加载完成 ✅")
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/compose1500view.kt | Kotlin | apache-2.0 | 2,534 |
package concurrency
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.time.TimeSource
import net.Net
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
private fun isHttpSuccess(code: Int?) = code != null && code in 200..299
private fun pickUrlByModulo(dispatchMs: Long, urls: List<String>): String {
require(urls.isNotEmpty()) { "requestUrls must not be empty" }
val idx = ((dispatchMs % urls.size).toInt() + urls.size) % urls.size
return urls[idx]
}
suspend fun runNCoroutinesMixedVerbose(
total: Int,
specialIndex: Int,
onProgress: suspend (Int) -> Unit,
onLog: suspend (String) -> Unit,
onActiveChange: suspend (all: Int, normal: Int, video: Int) -> Unit,
doNormalWork: suspend () -> Unit,
doVideoWork: suspend () -> Unit,
requestUrl: String,
requestGroupA: Set<Int>,
requestGroupB: Set<Int>,
requestGroupC: Set<Int>,
periodAms: Long,
periodBms: Long,
periodCms: Long,
jitterMs: Long,
requestRunMs: Long,
onRequestResult: suspend (
id: Int,
group: Char,
attempt: Int,
ok: Boolean,
code: Int?,
error: String?
) -> Unit,
requestUrls: List<String>? = null
) = coroutineScope {
val progressMutex = Mutex()
var counter = 0
val activeMutex = Mutex()
var activeAll = 0
var activeNormal = 0
var activeVideo = 0
suspend fun reportActive() {
val (a, n, v) = activeMutex.withLock { Triple(activeAll, activeNormal, activeVideo) }
onActiveChange(a, n, v)
}
suspend fun inc(isVideo: Boolean) {
activeMutex.withLock { activeAll++; if (isVideo) activeVideo++ else activeNormal++ }
reportActive()
}
suspend fun dec(isVideo: Boolean) {
activeMutex.withLock { activeAll--; if (isVideo) activeVideo-- else activeNormal-- }
reportActive()
}
fun pickUrlByModulo(dispatchMs: Long, urls: List<String>): String {
require(urls.size == 5) { "requestUrls must contain exactly 5 urls (index 0..4)" }
val idx = ((dispatchMs % urls.size).toInt() + urls.size) % urls.size
return urls[idx]
}
val producerIdsAll: List<Int> = (requestGroupA + requestGroupB + requestGroupC).toList()
val producers: List<Int> = if (producerIdsAll.size > 100) producerIdsAll.take(100) else producerIdsAll
val normalAll = (0 until total).filter { it != specialIndex }
val consumerCandidates = normalAll.filter { it !in producers }
val consumers: List<Int> = consumerCandidates.take(minOf(100, consumerCandidates.size))
val resultBoxes: Array<CompletableDeferred<String>?> = Array(total) { null }
producers.forEach { pid -> resultBoxes[pid] = CompletableDeferred() }
fun mapConsumerToProducer(consumerId: Int): Int? {
if (producers.isEmpty()) return null
val idx = ((consumerId % producers.size) + producers.size) % producers.size
return producers[idx]
}
repeat(total) { id ->
val isVideo = (id == specialIndex)
val name = if (isVideo) "video-$id" else "normal-$id"
val dispatcher = if (isVideo) Dispatchers.IO else Dispatchers.Default
launch(dispatcher + CoroutineName(name)) {
val coName = coroutineContext[CoroutineName]?.name ?: name
onLog("LAUNCH $coName"); inc(isVideo)
val t = TimeSource.Monotonic.markNow()
onLog("START $coName")
try {
if (isVideo) {
doVideoWork()
} else {
val inA = id in requestGroupA
val inB = id in requestGroupB
val inC = id in requestGroupC
if (!inA && !inB && !inC && id in consumers) {
val producerId = mapConsumerToProducer(id)
if (producerId == null) {
onLog("CONS id=$id no-producer-available -> fallback doNormalWork()")
doNormalWork()
} else {
val box = resultBoxes[producerId]
if (box == null) {
onLog("CONS id=$id mapped producer=$producerId but no box -> fallback doNormalWork()")
doNormalWork()
} else {
// 等待生产者的首个字符串结果(最多等 requestRunMs)
val text = withTimeoutOrNull(requestRunMs) { box.await() }
if (text == null) {
onLog("CONS id=$id -> producer=$producerId timeout (${requestRunMs}ms) no result")
} else {
val size = text.length
onLog("CONS id=$id <- producer=$producerId got size=$size")
}
doNormalWork()
}
}
} else if (inA || inB || inC) {
val base: Long = when {
inA -> periodAms
inB -> periodBms
else -> periodCms
}
val group = when {
inA -> 'A'
inB -> 'B'
else -> 'C'
}
val start = TimeSource.Monotonic.markNow()
var loops = 0
var producedOnce = false
while (isActive && start.elapsedNow().inWholeMilliseconds < requestRunMs) {
val delayMs: Long = nextPeriodWithJitter(base, jitterMs)
val finalUrl = requestUrls?.let { pickUrlByModulo(delayMs, it) } ?: requestUrl
val routeIdx = requestUrls?.let { ((delayMs % it.size).toInt() + it.size) % it.size } ?: 0
try {
val code = Net.getStatus(finalUrl)
val ok = isHttpSuccess(code)
val text = "id=$id group=$group loop=${loops + 1} url[$routeIdx]=$finalUrl HTTP $code"
onLog("REQ id=$id group=$group delay=${delayMs}ms routeIdx=$routeIdx url=$finalUrl -> HTTP $code")
onRequestResult(id, group, loops + 1, ok, code, null)
if (!producedOnce && id in producers) {
resultBoxes[id]?.let { box ->
if (!box.isCompleted) {
box.complete(text)
producedOnce = true
onLog("PROD id=$id -> box completed (len=${text.length})")
}
}
}
} catch (e: Throwable) {
onLog("REQ id=$id group=$group delay=${delayMs}ms routeIdx=$routeIdx url=$finalUrl " +
"ERROR ${e::class.simpleName}: ${e.message}")
onRequestResult(id, group, loops + 1, false, null, e.message)
if (!producedOnce && id in producers) {
val errText = "id=$id group=$group ERROR ${e::class.simpleName}: ${e.message ?: "unknown"}"
resultBoxes[id]?.let { box ->
if (!box.isCompleted) {
box.complete(errText)
producedOnce = true
onLog("PROD id=$id -> box completed with error text (len=${errText.length})")
}
}
}
}
loops++
delay(delayMs)
}
onLog("REQ id=$id finished loops=$loops run=${start.elapsedNow().inWholeMilliseconds}ms")
if (!producedOnce && id in producers) {
val fallback = "NO_RESULT id=$id group=$group"
resultBoxes[id]?.let { box ->
if (!box.isCompleted) {
box.complete(fallback)
onLog("PROD id=$id -> box fallback text (len=${fallback.length})")
}
}
}
} else {
doNormalWork()
}
}
val elapsed = t.elapsedNow().inWholeMilliseconds
val v = progressMutex.withLock { ++counter }
onLog("END $coName elapsed=${elapsed}ms progress=$v/$total")
onProgress(v)
} catch (e: CancellationException) {
onLog("CANCEL $coName"); throw e
} catch (e: Throwable) {
val v = progressMutex.withLock { ++counter }
onLog("ERROR $coName -> ${e::class.simpleName}: ${e.message} progress=$v/$total")
onProgress(v)
} finally {
dec(isVideo)
}
}
}
}
private fun nextPeriodWithJitter(baseMs: Long, jitterMs: Long): Long {
val delta = kotlin.random.Random.nextLong(-jitterMs, jitterMs + 1L)
return (baseMs + delta).coerceAtLeast(0L)
}
| 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/concurrency/Runner.kt | Kotlin | apache-2.0 | 9,971 |
package net
import io.ktor.client.HttpClient
import io.ktor.client.network.sockets.ConnectTimeoutException
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.HttpRequestTimeoutException
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.network.sockets.SocketTimeoutException
object Net {
val client = HttpClient {
install(HttpTimeout) {
connectTimeoutMillis = 8_000
socketTimeoutMillis = 10_000
requestTimeoutMillis = 15_000
}
install(HttpRequestRetry) {
maxRetries = 2
retryIf { request, cause ->
cause is ConnectTimeoutException ||
cause is HttpRequestTimeoutException ||
cause is SocketTimeoutException
}
constantDelay(300)
}
}
suspend fun getStatus(url: String): Int {
val resp: HttpResponse = client.get(url)
return resp.status.value
}
} | 2201_76010299/ovCompose-sample | composeApp/src/commonMain/kotlin/net/Net.kt | Kotlin | apache-2.0 | 1,070 |
package net
import io.ktor.client.HttpClient
val client = HttpClient() { /* 配置 */ }
| 2201_76010299/ovCompose-sample | composeApp/src/iosArm64Main/kotlin/net/Net.iosArm64.kt | Kotlin | apache-2.0 | 90 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package com.tencent.compose
import androidx.compose.ui.uikit.OnFocusBehavior
import androidx.compose.ui.uikit.RenderBackend
import androidx.compose.ui.window.ComposeUIViewController
import com.tencent.compose.sample.mainpage.MainPage
import kotlin.experimental.ExperimentalObjCName
@OptIn(ExperimentalObjCName::class)
@ObjCName("MainViewController")
fun MainViewController() = ComposeUIViewController(
configure = { onFocusBehavior = OnFocusBehavior.DoNothing }
) {
MainPage(false)
}
@OptIn(ExperimentalObjCName::class)
@ObjCName("SkiaRenderViewController")
fun SkiaRenderMainViewController() = ComposeUIViewController(
configure = {
onFocusBehavior = OnFocusBehavior.DoNothing
renderBackend = RenderBackend.Skia
}
) {
MainPage(true)
}
| 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/MainViewController.kt | Kotlin | apache-2.0 | 1,537 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
import platform.UIKit.UIDevice
internal class IOSPlatform : Platform {
override val name: String =
UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
internal actual fun getPlatform(): Platform = IOSPlatform() | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/Platform.ios.kt | Kotlin | apache-2.0 | 1,020 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.UikitImageBitmap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import platform.Foundation.NSBundle
import platform.UIKit.UIImage
private val emptyImageBitmap: ImageBitmap by lazy { ImageBitmap(1, 1) }
private val imageFolderPath:String by lazy { "${NSBundle.mainBundle().bundlePath}/compose-resources/" }
@OptIn(ExperimentalResourceApi::class)
@Composable
actual fun rememberLocalImage(id: DrawableResource): ImageBitmap {
var imageBitmap: ImageBitmap by remember { mutableStateOf(emptyImageBitmap) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val imagePath = "$imageFolderPath/${id.resourceItemPath()}"
val image = UIImage.imageNamed(imagePath) ?: return@withContext
imageBitmap = UikitImageBitmap(image)
}
}
return imageBitmap
} | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/Images.ios.kt | Kotlin | apache-2.0 | 2,150 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.interop.UIKitView2
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun Vertical2Vertical() {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
val scrollState = rememberScrollState()
Column {
Text(
"Compose 不可滚动区域顶部",
Modifier.fillMaxWidth().height(40.dp).background(Color.Yellow)
)
Column(
Modifier.fillMaxWidth().background(Color.LightGray).height(300.dp)
.verticalScroll(scrollState),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Compose 可滚动区域顶部",
Modifier.fillMaxWidth().height(80.dp).background(Color.Cyan)
)
UIKitView2(
factory = {
allocObject("ComposeSample.ImagesScrollView")
},
modifier = Modifier.width(260.dp).height(440.dp)
)
Text(
"Compose 可滚动区域底部",
Modifier.fillMaxWidth().height(80.dp).background(Color.Cyan)
)
}
Text(
"Compose 不可滚动区域底部",
color = Color.White,
modifier = Modifier.fillMaxWidth().height(40.dp).background(Color.Blue)
)
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/Vectical2Vectical.kt | Kotlin | apache-2.0 | 3,001 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import kotlinx.cinterop.ExperimentalForeignApi
import platform.Foundation.CFBridgingRelease
import platform.Foundation.CFBridgingRetain
import platform.Foundation.NSClassFromString
import platform.Foundation.NSSelectorFromString
import platform.darwin.NSObject
@OptIn(ExperimentalForeignApi::class)
internal inline fun <reified T> allocObject(className: String): T {
val cls = NSClassFromString(className) as NSObject
val obj = cls.performSelector(NSSelectorFromString("new")) as T
val cfObj = CFBridgingRetain(obj)
CFBridgingRelease(cfObj)
CFBridgingRelease(cfObj)
return obj
} | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/allocObject.kt | Kotlin | apache-2.0 | 1,375 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.backhandler
import androidx.compose.runtime.Composable
@Composable
actual fun BackHandler(enable: Boolean, onBack: () -> Unit) {
} | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/backhandler/BackHandler.ios.kt | Kotlin | apache-2.0 | 903 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample.mainpage
import com.tencent.compose.sample.Vertical2Vertical
import com.tencent.compose.sample.data.DisplayItem
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.swipedown
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
internal actual fun platformSections(): List<DisplayItem> {
return listOf(
DisplayItem("嵌套原生滑动", Res.drawable.swipedown) { Vertical2Vertical() }
)
} | 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.ios.kt | Kotlin | apache-2.0 | 1,281 |
package net
| 2201_76010299/ovCompose-sample | composeApp/src/iosMain/kotlin/net/Net.ios.kt | Kotlin | apache-2.0 | 13 |
package net
| 2201_76010299/ovCompose-sample | composeApp/src/iosSimulatorArm64Main/kotlin/net/Net.iosSimulatorArm64.kt | Kotlin | apache-2.0 | 13 |
package net
| 2201_76010299/ovCompose-sample | composeApp/src/iosX64Main/kotlin/net/Net.iosX64.kt | Kotlin | apache-2.0 | 13 |
#ifndef GLOBAL_RAW_FILE_H
#define GLOBAL_RAW_FILE_H
#ifdef __cplusplus
extern "C" {
#endif
struct RawFile;
typedef struct RawFile RawFile;
int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length);
long OH_ResourceManager_GetRawFileSize(RawFile *rawFile);
void OH_ResourceManager_CloseRawFile(RawFile *rawFile);
#ifdef __cplusplus
};
#endif
/** @} */
#endif // GLOBAL_RAW_FILE_H
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/cinterop/include/raw_file.h | C | apache-2.0 | 414 |
#ifndef GLOBAL_NATIVE_RESOURCE_MANAGER_H
#define GLOBAL_NATIVE_RESOURCE_MANAGER_H
#include "napi/native_api.h"
#include "raw_file.h"
#ifdef __cplusplus
extern "C" {
#endif
struct NativeResourceManager;
typedef struct NativeResourceManager NativeResourceManager;
NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr);
void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr);
RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName);
#ifdef __cplusplus
};
#endif
/** @} */
#endif // GLOBAL_NATIVE_RESOURCE_MANAGER_H
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/cinterop/include/raw_file_manager.h | C | apache-2.0 | 639 |
#ifndef GLOBAL_TEST_0725_H
#define GLOBAL_TEST_0725_H
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
int testNum(int num);
void print_string(char* msg);
void print_const_string(const char* msg);
void trace_tag_begin();
void trace_tag_end();
void trace_tag_cnt(int num);
typedef void (*register_callback_holder)(int, void*);
void native_register(void* kotlin_obj, register_callback_holder callback, bool holdRef);
void native_trigger(void);
void native_register_plain_holder(void* ptr, bool holdRef);
void native_register_simple_callback(const char* id, void* stable_ref, void (*callback)(void*));
void native_trigger_simple_callback(const char* id);
void native_cleanup_simple_callback(const char* id);
void native_cleanup_all_simple_callbacks();
int native_get_simple_callback_count();
void native_print_simple_callback_status();
#ifdef __cplusplus
};
#endif
/** @} */
#endif // GLOBAL_TEST_0725_H
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/cinterop/include/test_0725.h | C | apache-2.0 | 918 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/App.ohosArm64.kt | Kotlin | apache-2.0 | 764 |
@file:OptIn(ExperimentalNativeApi::class)
package com.tencent.compose
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.StableRef
import kotlinx.cinterop.invoke
import kotlin.experimental.ExperimentalNativeApi
@CName("kotlin_function")
fun kotlinFunction(input: Int): Int {
return input * 2
}
@OptIn(ExperimentalForeignApi::class)
@CName("kotlin_callback")
fun callback(data: Int, handler: CPointer<CFunction<(Int) -> Unit>>) {
handler.invoke(data * 2)
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/ExportFunctions.kt | Kotlin | apache-2.0 | 555 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
import androidx.compose.ui.window.ComposeArkUIViewController
import com.tencent.compose.sample.NativeResourceManager
import com.tencent.compose.sample.mainpage.MainPage
import com.tencent.compose.sample.mainpage.NewMainPage
import com.tencent.compose.sample.nativeResourceManager
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.initMainHandler
import platform.ohos.napi_env
import platform.ohos.napi_value
import kotlin.experimental.ExperimentalNativeApi
@OptIn(ExperimentalNativeApi::class, ExperimentalForeignApi::class)
@CName("MainArkUIViewController")
fun MainArkUIViewController(env: napi_env): napi_value {
initMainHandler(env)
return ComposeArkUIViewController(env) { MainPage() }
}
@OptIn(ExperimentalForeignApi::class)
fun initResourceManager(resourceManager: NativeResourceManager) {
nativeResourceManager = resourceManager
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/MainArkUIViewController.kt | Kotlin | apache-2.0 | 1,642 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.toKString
import platform.ohos.OH_GetOSFullName
internal class OHOSPlatform : Platform {
@OptIn(ExperimentalForeignApi::class)
override val name: String = OH_GetOSFullName()?.toKString().orEmpty()
}
internal actual fun getPlatform(): Platform = OHOSPlatform() | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/Platform.ohos.kt | Kotlin | apache-2.0 | 1,105 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.*
import platform.test725.native_register
import platform.test725.native_trigger
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.runtime.GC
import kotlin.native.ref.WeakReference
import kotlin.native.runtime.NativeRuntimeApi
import kotlin.time.TimeSource
object LogBuffer {
val logs = mutableStateListOf<String>()
fun log(msg: String) {
println(msg)
logs += msg
}
fun clear() {
logs.clear()
}
}
object LeakTracker {
@OptIn(ExperimentalNativeApi::class)
val holders = mutableListOf<WeakReference<CallbackHolder>>()
@OptIn(ExperimentalNativeApi::class)
fun collectStatus(): List<Unit> {
return holders.mapIndexed { index, ref ->
val obj = ref.get()
if (obj != null) {
LogBuffer.log("dzy $index -> ${obj.name} ✅ 活跃")
} else {
LogBuffer.log("dzy $index -> 已被 GC 回收")
}
}
}
}
object RefManager {
@OptIn(ExperimentalForeignApi::class)
private val refs = mutableListOf<StableRef<CallbackHolder>>()
@OptIn(ExperimentalForeignApi::class)
fun register(ref: StableRef<CallbackHolder>) {
refs += ref
}
@OptIn(ExperimentalForeignApi::class)
fun disposeAll() {
refs.forEach {
it.dispose()
}
refs.clear()
LogBuffer.log("dzy 所有未释放 StableRef 已 dispose()")
}
}
@OptIn(NativeRuntimeApi::class)
fun forceGC() {
LogBuffer.log("dzy 手动触发 GC ...")
GC.collect()
}
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun CallbackLeakTestScreen() {
val triggered = remember { mutableStateOf(false) }
var holdInC by remember { mutableStateOf(true) }
var disposeAfterRegister by remember { mutableStateOf(false) }
Column(Modifier
.padding(16.dp)
.fillMaxSize()) {
Column {
Button(onClick = {
LogBuffer.log("dzy Click: 创建并注册 CallbackHolder...")
val holder = CallbackHolder("Holder-${TimeSource.Monotonic.markNow()}")
val ref = StableRef.create(holder)
val cb = staticCFunction { x: Int, ptr: COpaquePointer? ->
val obj = ptr!!.asStableRef<CallbackHolder>().get()
obj.onResult(x)
}
native_register(ref.asCPointer(), cb, holdInC)
// native_trigger()
if (disposeAfterRegister) {
ref.dispose()
LogBuffer.log("dzy StableRef disposed")
} else {
RefManager.register(ref)
}
triggered.value = true
}) {
Text("创建 CallbackHolder")
}
Button(onClick = {
LeakTracker.collectStatus()
}) {
Text("查看状态")
}
Button(onClick = {
forceGC()
}) {
Text("GC")
}
Button(onClick = {
LogBuffer.clear()
}) {
Text("清空日志")
}
// ✅ 新增:手动释放所有未 dispose 的引用
Button(onClick = {
RefManager.disposeAll()
}) {
Text("释放所有未释放的引用")
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = disposeAfterRegister,
onCheckedChange = { disposeAfterRegister = it }
)
Text("创建后立即 dispose()(避免引用环)")
}
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = holdInC,
onCheckedChange = { holdInC = it }
)
Text("C 侧是否持有 Kotlin 对象")
}
Spacer(Modifier.height(8.dp))
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
items(LogBuffer.logs) { log ->
Text(log)
}
}
}
}
@OptIn(ExperimentalForeignApi::class)
class CallbackHolder(val name: String) {
init {
@OptIn(ExperimentalNativeApi::class)
LeakTracker.holders += WeakReference(this)
@OptIn(kotlin.experimental.ExperimentalNativeApi::class)
LogBuffer.log("dzy 创建 Holder: $name, 当前数量: ${LeakTracker.holders.size}")
}
fun onResult(x: Int) {
LogBuffer.log("dzy [$name] called with $x")
}
protected fun finalize() {
LogBuffer.log("dzy CallbackHolder [$name] finalized, 已被 GC 回收")
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ArkCallback.kt | Kotlin | apache-2.0 | 5,232 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.arkui.ArkUIView
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.interop.AdaptiveParams
import androidx.compose.ui.interop.InteropContainer
import androidx.compose.ui.napi.JsObject
import androidx.compose.ui.napi.js
private val NoOp: Any.() -> Unit = {}
@Composable
internal fun ArkUIView(
name: String,
modifier: Modifier,
parameter: JsObject = js(),
update: (JsObject) -> Unit = NoOp,
background: Color = Color.Unspecified,
updater: (ArkUIView) -> Unit = NoOp,
onCreate: (ArkUIView) -> Unit = NoOp,
onRelease: (ArkUIView) -> Unit = NoOp,
interactive: Boolean = true,
adaptiveParams: AdaptiveParams? = null,
tag: String? = null,
container: InteropContainer = InteropContainer.BACK
) = androidx.compose.ui.interop.ArkUIView(
name = name,
modifier = modifier,
parameter = parameter,
update = update,
background = background,
updater = updater,
onCreate = onCreate,
onRelease = onRelease,
interactive = interactive,
adaptiveParams = adaptiveParams,
tag = tag,
container = container,
) | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ArkUIView.kt | Kotlin | apache-2.0 | 1,978 |
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
@Composable
internal fun AutoScrollingInfiniteList() {
val items = remember { mutableStateListOf<Int>() }
val coroutineScope = rememberCoroutineScope()
val listState = rememberLazyListState()
// 初始填充大量数据
LaunchedEffect(Unit) {
repeat(10000) { items += it }
}
LaunchedEffect(Unit) {
while (true) {
delay(16)
val nextIndex = (listState.firstVisibleItemIndex + 1).coerceAtMost(items.lastIndex)
listState.scrollToItem(nextIndex)
}
}
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize()
) {
items(items.size) { index ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(80.dp)
.padding(4.dp)
.border(1.dp, Color.DarkGray)
) {
Text("Item $index", modifier = Modifier.align(Alignment.Center))
}
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/AutoScrollInfiniteList.kt | Kotlin | apache-2.0 | 2,066 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.fillMaxHeight
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun CApiView1500Image() {
Column(
modifier = Modifier
// .verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(1) { index ->
ArkUIView(
name = "cApiImageView1500",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/CApiImage1500.kt | Kotlin | apache-2.0 | 938 |
package com.tencent.compose.sample
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.runtime.*
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
@Composable
internal fun CApiView1500Text() {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
// .verticalScroll(scrollState) // 启用垂直滚动
) {
ArkUIView(
name = "cApiTextView1500",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/CApiText1500.kt | Kotlin | apache-2.0 | 1,800 |
package com.tencent.compose.sample
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.runtime.*
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.ExperimentalForeignApi
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun CApiView1500Page() {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
ArkUIView(
name = "cApiStackView1500",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/CApiView1500.kt | Kotlin | apache-2.0 | 1,821 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.cinterop.*
import platform.test725.native_register_simple_callback
import platform.test725.native_trigger_simple_callback
import platform.test725.native_cleanup_simple_callback
import platform.test725.native_cleanup_all_simple_callbacks
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.runtime.GC
import kotlin.native.ref.WeakReference
import kotlin.native.runtime.NativeRuntimeApi
import kotlin.time.TimeSource
object MemoryLogger {
val logs = mutableStateListOf<String>()
fun log(msg: String) {
println(msg)
logs += "[${TimeSource.Monotonic.markNow()}] $msg"
}
fun clear() {
logs.clear()
}
}
// 全局存储,模拟环状引用
object CallbackRegistry {
// 这个Map会持有对象引用,阻止GC
private val activeCallbacks = mutableMapOf<String, LeakyCallbackHolder>()
fun register(id: String, holder: LeakyCallbackHolder) {
activeCallbacks[id] = holder
MemoryLogger.log("dzy 注册到全局Registry: $id (当前数量: ${activeCallbacks.size})")
}
fun getCallback(id: String): LeakyCallbackHolder? {
return activeCallbacks[id]
}
fun remove(id: String) {
activeCallbacks.remove(id)
MemoryLogger.log("dzy 从Registry移除: $id (剩余: ${activeCallbacks.size})")
}
fun clear() {
val count = activeCallbacks.size
activeCallbacks.clear()
MemoryLogger.log("dzy 清空Registry,释放了 $count 个引用")
}
fun getActiveCount(): Int = activeCallbacks.size
}
// 对象追踪器
object ObjectTracker {
@OptIn(ExperimentalNativeApi::class)
private val trackedObjects = mutableListOf<WeakReference<LeakyCallbackHolder>>()
@OptIn(ExperimentalNativeApi::class)
fun track(obj: LeakyCallbackHolder) {
trackedObjects += WeakReference(obj)
MemoryLogger.log("dzy 开始追踪对象: ${obj.id}")
}
@OptIn(ExperimentalNativeApi::class)
fun checkStatus() {
var aliveCount = 0
var gcCount = 0
MemoryLogger.log("dzy 检查所有追踪的对象状态...")
trackedObjects.forEachIndexed { index, ref ->
val obj = ref.get()
if (obj != null) {
aliveCount++
MemoryLogger.log("dzy 对象 ${obj.id} 仍然存活")
} else {
gcCount++
MemoryLogger.log("dzy 对象已被GC回收")
}
}
MemoryLogger.log("dzy 统计结果: 存活 $aliveCount 个, 已回收 $gcCount 个")
MemoryLogger.log("dzy Registry中还有 ${CallbackRegistry.getActiveCount()} 个引用")
if (aliveCount > 0 && CallbackRegistry.getActiveCount() > 0) {
MemoryLogger.log("dzy 检测到可能的内存泄漏!对象无法被GC")
}
}
@OptIn(ExperimentalNativeApi::class)
fun reset() {
trackedObjects.clear()
}
}
// 会产生环状引用的回调持有者
@OptIn(ExperimentalForeignApi::class)
class LeakyCallbackHolder(val id: String) {
private var stableRef: StableRef<LeakyCallbackHolder>? = null
private var isRegistered = false
init {
ObjectTracker.track(this)
MemoryLogger.log("dzy 创建 LeakyCallbackHolder: $id")
}
fun registerToC(createCircularRef: Boolean = true) {
if (!isRegistered) {
stableRef = StableRef.create(this)
val callback:CPointer<CFunction<(COpaquePointer?) -> Unit>> = staticCFunction { ptr: COpaquePointer? ->
try {
ptr?.asStableRef<LeakyCallbackHolder>()?.get()?.let { obj ->
obj.handleCallback("dzy 来自C层的数据")
// 关键:同时通过Registry也能获取到同一个对象
// 这证明了环状引用的存在
val registryObj = CallbackRegistry.getCallback(obj.id)
if (registryObj === obj) {
MemoryLogger.log("dzy 确认环状引用:Registry和StableRef指向同一对象")
}
}
} catch (e: Exception) {
MemoryLogger.log("dzy 回调执行出错: ${e.message}")
}
}
// 注册到C层 - 使用简化的接口
native_register_simple_callback(id, stableRef!!.asCPointer(), callback)
if (createCircularRef) {
// 关键步骤:将自己注册到全局Registry
// 这创建了环状引用:
// 1. 这个对象持有StableRef
// 2. C层通过StableRef持有这个对象
// 3. 全局Registry也持有这个对象
// 4. 即使C层释放了StableRef,Registry仍然持有引用阻止GC
CallbackRegistry.register(id, this)
MemoryLogger.log("dzy 创建环状引用: $id")
}
isRegistered = true
}
}
fun handleCallback(data: String) {
MemoryLogger.log("dzy [$id] 收到回调: $data")
}
fun dispose() {
if (isRegistered) {
// 1. 清理C层注册
native_cleanup_simple_callback(id)
// 2. 释放StableRef
stableRef?.dispose()
stableRef = null
// 3. 从Registry移除(解除环状引用)
CallbackRegistry.remove(id)
isRegistered = false
MemoryLogger.log("dzy 正确清理对象: $id")
}
}
// 只清理C层和StableRef,但不清理Registry引用(保持环状引用)
fun partialDispose() {
if (isRegistered) {
native_cleanup_simple_callback(id)
stableRef?.dispose()
stableRef = null
isRegistered = false
MemoryLogger.log("dzy 部分清理对象: $id (Registry引用仍存在)")
}
}
fun cleanupOnlyRegistry() {
CallbackRegistry.remove(id)
stableRef?.dispose()
stableRef = null
MemoryLogger.log("dzy 部分清理对象 Registry引用 和 stableRef: $id")
}
protected fun finalize() {
MemoryLogger.log("dzy 对象 $id 被GC回收(finalize调用)")
}
}
@OptIn(NativeRuntimeApi::class)
@Composable
internal fun CircularReferenceDemo() {
var objectCounter by remember { mutableStateOf(0) }
var createCircularRef by remember { mutableStateOf(true) }
var usePartialDispose by remember { mutableStateOf(false) }
// 存储创建的对象,用于手动清理测试
val createdObjects = remember { mutableListOf<LeakyCallbackHolder>() }
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxSize()
) {
Text(
text = "KMP 环状引用演示",
style = MaterialTheme.typography.h6
)
Spacer(modifier = Modifier.height(8.dp))
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = createCircularRef,
onCheckedChange = { createCircularRef = it }
)
Text("创建环状引用(Registry持有对象)")
}
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = usePartialDispose,
onCheckedChange = { usePartialDispose = it }
)
Text("使用部分清理(保持环状引用)")
}
}
Spacer(modifier = Modifier.height(16.dp))
// 第一行按钮
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = {
objectCounter++
val obj = LeakyCallbackHolder("Holder-$objectCounter")
obj.registerToC(createCircularRef)
createdObjects.add(obj)
if (createCircularRef) {
MemoryLogger.log("dzy 创建了可能泄漏的对象(有环状引用)")
} else {
MemoryLogger.log("dzy 创建了正常的对象(无环状引用)")
}
}
) {
Text("创建对象")
}
Button(
onClick = {
if (createdObjects.isNotEmpty()) {
val obj = createdObjects.removeLastOrNull()
obj?.let {
if (usePartialDispose) {
it.partialDispose() // 保持环状引用
}
else {
it.dispose() // 完全清理
}
}
}
}
) {
Text("清理最后对象")
}
}
// 第二行按钮
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = {
val id = "Holder-$objectCounter"
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
native_trigger_simple_callback(id)
MemoryLogger.log("🚀 触发回调: $id")
}
) {
Text("触发回调")
}
Button(
onClick = {
MemoryLogger.log("dzy 开始强制GC...")
GC.collect()
MemoryLogger.log("dzy GC完成")
}
) {
Text("强制GC")
}
}
// 第三行按钮
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = {
ObjectTracker.checkStatus()
}
) {
Text("检查内存")
}
Button(
onClick = {
// 清理所有Registry引用,解除环状引用
CallbackRegistry.clear()
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
native_cleanup_all_simple_callbacks()
}
) {
Text("解除环状引用")
}
}
// 第四行按钮
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(
onClick = {
createdObjects.clear()
ObjectTracker.reset()
CallbackRegistry.clear()
MemoryLogger.clear()
}
) {
Text("重置所有")
}
}
Spacer(modifier = Modifier.height(16.dp))
// 说明卡片
Card(
modifier = Modifier.fillMaxWidth(),
backgroundColor = MaterialTheme.colors.surface
) {
Column(modifier = Modifier.padding(8.dp)) {
Text(
text = "观察步骤:",
style = MaterialTheme.typography.subtitle2
)
Text(
text = "1️⃣ 勾选'创建环状引用',创建几个对象\n" +
"2️⃣ 点击'强制GC',然后'检查内存'\n" +
"3️⃣ 观察对象无法被GC回收(Registry持有引用)\n" +
"4️⃣ 点击'解除环状引用',再次GC\n" +
"5️⃣ 观察对象现在可以被GC回收了\n\n" +
"🔴 环状引用路径:\n" +
"Kotlin对象 → StableRef → C层 → 回调 → Registry → Kotlin对象",
style = MaterialTheme.typography.caption
)
}
}
Spacer(modifier = Modifier.height(8.dp))
// 日志显示
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
verticalArrangement = Arrangement.spacedBy(2.dp)
) {
items(MemoryLogger.logs) { log ->
Text(
text = log,
style = MaterialTheme.typography.caption
)
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/CircleReference.kt | Kotlin | apache-2.0 | 12,890 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeImage1500CApi() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(500) { index ->
ArkUIView(
name = "cApiSingleImage",
modifier = Modifier
.fillMaxWidth()
.height(220.dp),
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeImage1500CApi.kt | Kotlin | apache-2.0 | 1,344 |
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
internal fun ComposeLazy1500ViewWithString() {
val totalCount = 1500
val items = remember { List(totalCount) { it } }
val listState = rememberLazyListState()
val allocSizesBytes = remember { listOf(100, 200, 500, 1000, 2_000, 5_000) }
LaunchedEffect(listState) {
var idx = 0
var lastIndex = 0
var lastOffset = 0
var accumPx = 0
snapshotFlow { listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset }
.collect { (i, off) ->
val dy = when {
i == lastIndex -> off - lastOffset
else -> (off - lastOffset) + (i - lastIndex) * 100 // 100 近似 item 高
}
lastIndex = i
lastOffset = off
accumPx += kotlin.math.abs(dy)
if (accumPx >= 8) {
accumPx = 0
val bytes = allocSizesBytes[idx % allocSizesBytes.size]
val s = createStringOfApproxBytes(bytes)
if (idx % 50 == 0) {
println("onScroll alloc -> ${bytes}B (len=${s.length}) @index=$i, off=$off")
}
idx++
}
}
}
LazyColumn(
state = listState,
modifier = Modifier.fillMaxWidth()
) {
itemsIndexed(items) { _, item ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(vertical = 4.dp, horizontal = 8.dp)
.border(2.dp, Color.Red),
contentAlignment = Alignment.Center
) {
Text("Item #$item")
}
}
}
}
private fun createStringOfApproxBytes(bytes: Int): String {
val chars = (bytes / 2).coerceAtLeast(1)
return buildString(chars) {
repeat(chars) { append('a') }
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeLazy1500ViewWithString.kt | Kotlin | apache-2.0 | 2,478 |
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.unit.dp
@Composable
internal fun ComposeLazyView1500Page() {
val totalCount = 1500
val items = remember { List(totalCount) { it } }
LazyColumn(
modifier = Modifier.fillMaxWidth()
) {
itemsIndexed(items) { index, item ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(vertical = 4.dp, horizontal = 8.dp)
.border(2.dp, Color.Red),
contentAlignment = Alignment.Center
) {
Text("Item #$item")
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeLazyView1500.kt | Kotlin | apache-2.0 | 1,320 |
package com.tencent.compose.sample
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
internal fun ComposeView1500Text() {
// val startTime = remember { getTimeMillis() }
//
// // 等待首帧绘制完毕后输出耗时
// LaunchedEffect(Unit) {
// val duration = getTimeMillis() - startTime
// println("dzy Compose 页面构建 + 渲染耗时:${duration}ms")
// }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(1500) { index ->
Text(
text = "Item #$index",
fontSize = 16.sp,
modifier = Modifier
.width(300.dp)
.height(50.dp)
.border(1.dp, Color.Gray)
.padding(10.dp)
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeText1500.kt | Kotlin | apache-2.0 | 1,335 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeText1500CApi() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(500) { index ->
ArkUIView(
name = "cApiSingleText",
modifier = Modifier
.width(300.dp)
.height(50.dp),
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeText1500CApi.kt | Kotlin | apache-2.0 | 1,437 |
package com.tencent.compose.sample
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
//import androidx.compose.ui.Modifier
import kotlinx.cinterop.ExperimentalForeignApi
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.runtime.*
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import platform.test725.print_const_string
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun ComposeToCPage() {
// 创建滚动状态
val scrollState = rememberScrollState()
// 存储滚动距离(像素)
var scrollPosition by remember { mutableStateOf(0) }
// 使用dp单位记录滚动距离
val scrollPositionDp = with(LocalDensity.current) { scrollPosition.toDp() }
var count = 0;
// 监听滚动状态变化
LaunchedEffect(scrollState.value) {
count = count + 1;
print_const_string("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789")
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.verticalScroll(scrollState) // 启用垂直滚动
) {
// 生成长列表(100个条目)
repeat(100) { index ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(4.dp)
.background(Color.LightGray),
contentAlignment = Alignment.Center
) {
Text("列表项 #$index")
}
}
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeToC.kt.kt | Kotlin | apache-2.0 | 3,658 |
package com.tencent.compose.sample
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import com.tencent.compose.sample.rememberLocalImage
import composesample.composeapp.generated.resources.Res
import composesample.composeapp.generated.resources.image_cat
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.layout.onGloballyPositioned
import platform.test725.trace_tag_begin
import platform.test725.trace_tag_end
import platform.test725.trace_tag_cnt
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.cstr
@OptIn(ExperimentalForeignApi::class)
@Composable
internal fun ComposeView1500Page() {
val loaded = remember { mutableStateOf(false) }
// val startTime = remember { getTimeMillis() }
//
// LaunchedEffect(Unit) {
// trace_tag_begin()
// val duration = getTimeMillis() - startTime
// println("dzy Compose 页面构建 + 渲染耗时:${duration}ms")
// }
// SideEffect {
// trace_tag_end()
// }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
// trace_tag_begin()
// 创建1500个Box
repeat(1500) { index ->
Box(
modifier = Modifier
.size(300.dp, 100.dp) // 设置宽高均为300dp
.border(
width = 2.dp, // 边框宽度
color = Color.Red, // 边框颜色为红色
)
.then(
if (index == 1499) Modifier.onGloballyPositioned {
// 最后一个 Box 被布局 -> 页面“加载完成”
loaded.value = true
trace_tag_end()
} else Modifier
)
) {
Text(
text = "Item #$index",
)
}
}
// trace_tag_end()
}
if (loaded.value) {
// 可以做其它“加载完成”后的逻辑
println("页面加载完成 ✅")
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeView1500.kt | Kotlin | apache-2.0 | 3,603 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeView1500CApi() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState()) // 启用垂直滚动
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally // 水平居中所有子项
) {
repeat(1500) { index ->
ArkUIView(
name = "cApiStackSingleView",
modifier = Modifier
.size(300.dp, 100.dp)
)
}
}
}
| 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeView1500CApi.kt | Kotlin | apache-2.0 | 1,316 |
package com.tencent.compose.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
internal fun FfiBenchmark() {
Column() {
ArkUIView(
name = "FfiBenchmark",
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
)
}
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/FfiBenchmark.kt | Kotlin | apache-2.0 | 501 |
/*
* Tencent is pleased to support the open source community by making ovCompose available.
* Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalForeignApi::class, ExperimentalResourceApi::class)
package com.tencent.compose.sample
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.skia.Image
import platform.resource.OH_ResourceManager_CloseRawFile
import platform.resource.OH_ResourceManager_GetRawFileSize
import platform.resource.OH_ResourceManager_OpenRawFile
import platform.resource.OH_ResourceManager_ReadRawFile
typealias NativeResourceManager = CPointer<cnames.structs.NativeResourceManager>?
var nativeResourceManager: NativeResourceManager = null
private val emptyImageBitmap: ImageBitmap by lazy { ImageBitmap(1, 1) }
@Composable
internal actual fun rememberLocalImage(id: DrawableResource): ImageBitmap {
var imageBitmap: ImageBitmap by remember { mutableStateOf(emptyImageBitmap) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
val rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, id.resourceItemPath())
val size = OH_ResourceManager_GetRawFileSize(rawFile)
val buffer = ByteArray(size.toInt())
buffer.usePinned { pinnedBuffer ->
OH_ResourceManager_ReadRawFile(rawFile, pinnedBuffer.addressOf(0), size.toULong())
}
OH_ResourceManager_CloseRawFile(rawFile)
imageBitmap = Image.makeFromEncoded(buffer).toComposeImageBitmap()
}
}
return imageBitmap
} | 2201_76010299/ovCompose-sample | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/Images.ohosArm64.kt | Kotlin | apache-2.0 | 2,846 |