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 |
|---|---|---|---|---|---|
.page-container {
margin-top:60px;
width 50%;
} | 2303_806435pww/hexo-theme-wang | source/css/page.styl | Stylus | unlicense | 56 |
.post-article{
display: flex;
flex-direction: column;
justify-content: center;
margin-top:60px;
max-width: 60%;
margin: 52px 15px;
}
@media (max-width: 767px) {
.post-article{
min-width: 400px;
max-width: 100%;
margin: 52px 5px;
}
}
.post-header{
margin-top: 20px;
}
.post-content{
background-color: #3b3b3b;
margin:auto;
margin-top: 60px;
max-width: 100%;
}
.post-content>*{
margin-bottom: 20px;
margin-left:25px;
margin-right:25px;
}
.post-content>h2
{
border-bottom: 2px solid #fff;
}
.post-content>h3
{
border-bottom: 1px dashed #fff;
}
.post-content>h4
{
border-bottom: 5px dashed #fff;
}
.post-content>h5
{
border-bottom: 5px dashed #fff;
}
.post-content>h6
{
border-bottom: 5px dashed #fff;
}
.post-content .highlight{
background-color: #333;
}
figure.highlight {
position: relative;
overflow: auto;
}
figure.highlight tr{
}
// table{
// display block;
// }
.gutter{
width : 0.5em;
}
figure.highlight .gutter pre {
padding-right: 0; /* 右侧内边距,以确保有足够的空间 */
border-right: 1px solid #ccc; /* 分隔线,可选 */
display: inline-block;
text-align: right;
color: #999;
line-height: 1.7; /* 增加行高,使行号之间有更多空间 */
}
figure.highlight .code pre {
display:block;
min-width:50%;
max-width:100vh;/* 高度是视口高度的50% */
margin-left:0; /* 代码左侧的内边距,与行号保持一致 */
line-height: 1.7; /* 增加行高,使代码之间有更多空间 */
overflow: auto; /* 允许滚动条 */
}
.copy-btn,box{
position: absolute;
right: 0;
width :50px;
height: 30px;
border-radius: 5px;
}
.copy-btn{
background: #333
}
.post-content a{
text-decoration: underline;
}
.post-content a:not(.headerlink):not(:has(img))::after {
content: '\f08e'; /* Font Awesome 的外链图标 Unicode */
font-family: 'Font Awesome 5 Free'; /* 指定 Font Awesome 字体 */
font-weight: 900; /* 根据图标库的要求,通常使用 900 粗细 */
margin-left: 5px; /* 图标和链接之间的间距 */
font-size: 12px; /* 调整图标大小 */
}
.pre-next-container{
display: flex;
justify-content: space-around;
}
.pre-btn,.next-btn{
border:1px solid grey;
border-radius: 5px;
padding: 5px 10px;
}
.copyright-container{
display:flex
align-content: center
flex:1;
border:1px solid grey;
}
.copyright-author-container,.copyright-public-time-container,.copyright-license-container{
margin-right:15px;
margin-bottom:15px;
align-content: center
justify-content: space-around;
}
| 2303_806435pww/hexo-theme-wang | source/css/post.styl | Stylus | unlicense | 2,767 |
@import url('https://static.zeoseven.com/zsft/84/main/result.css');
img {
width: auto; /* 或者具体的像素值,比如300px */
height: auto; /* 保持图片的宽高比 */
object-fit: cover; /* 保持图片的宽高比,可能会裁剪图片 */
object-fit: contain;
//height: 500px; /* 保持图片完整显示,可能会有空白 */
max-width: 100%;
}
.box {
// width: 200px; /* 盒子宽度 */
// height: 200px; /* 盒子高度 */
background-color: #414141fd; /* 盒子背景颜色 */
//border: 1px solid #ccc; /* 盒子边框 */
border-radius: 15px; /* 圆角效果 */
transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; /* 平滑过渡效果 */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */
}
.box:hover {
transform: translateY(-2px); /* 鼠标悬停时向上移动 */
box-shadow: 0 12px 20px rgba(0, 0, 0, 0.2); /* 鼠标悬停时增加阴影 */
}
p{
padding auto;
}
h1, h2, h3, h4, h5, h6{
margin: auto;
}
a {
/* 去除下划线 */
text-decoration: none;
/* 去除点击时的焦点轮廓 */
outline: none;
/* 去除鼠标悬停时的颜色变化 */
color: inherit;
/* 去除点击时的背景颜色变化 */
background-color: transparent;
/* 去除点击时的边框 */
border: none;
/* 去除默认的字体颜色变化 */
color: initial;
/* 去除默认的字体样式变化 */
font-style: normal;
/* 去除默认的字体粗细变化 */
font-weight: normal;
}
// // fancybox
.markdown-section img
max-width: 100%;
padding: 0.5em 0;
margin: auto;
display: block;
// fancybox
.caption
color: #444;
display: block;
font-size: 0.9em;
margin-top: 0.1em;
position: relative;
text-align: center;
html {
font-family: "Douyin Sans";
font-weight: normal;
height: 100%;
}
* {
margin: 0;
padding: 0;
//box-sizing: border-box;
text-decoration: none;
font-family: "Douyin Sans";
font-weight: normal;
}
.excerpt{
margin-top:5px;
}
.fa{
margin: 2px;
}
html{
//display: flex;
//overflow: scroll;
}
.container{
display: flex;
justify-content: space-around; /* 子元素水平居中 */
min-height: 96vh; /* 容器高度 */
}
body {
color: rgb(34, 30, 30);
background-color: rgb(65, 65, 65);
height: 100%;
}
.hover-underline {
position: relative;
cursor: pointer;
text-decoration: none; /* 去除默认的下划线 */
display: inline-block;
padding-bottom: 2px; /* 为下划线留出空间 */
transition: all 0.3s ease-in-out; /* 过渡效果 */
}
.hover-underline::after {
content: '';
position: absolute;
left: 50%;
right: 50%;
bottom: 0;
height: 1px; /* 下划线高度 */
background: #D3D3D3; /* 灰白色 */
transition: all 0.3s ease-in-out; /* 过渡效果 */
}
.hover-underline:hover::after {
left: 0;
right: 0;
}
.page-all-minbox {
justify-content: center; /* 子元素水平居中 */
margin:auto;
margin-top: 60px;
margin-right: 20px;
margin-left: 20px;
padding: 10px;
//display: flex;
//display: flex;
flex-direction: column; /* 子元素垂直排列 */
//height: 100vh; /* 容器高度 */
}
.page-minbox{
// max-height: 900px;
// background-color: #33333367;
margin-bottom: 45px;
// max-width:800px;
// min-height:400px;
}
.page-minbox:hover{
background-color: #444;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.posts{
place-items: center;
}
.post{
display: grid;
height: 100%;
background-color: #33333367;
max-height: 900px;
max-width:800px;
min-height:400px;
}
.post-title{
text-align: center;
}
.post-title-link{
color: white;
margin:auto;
padding-top: 35px;
}
.post-meta{
display: flex;
justify-content: center;
}
.post-time{
display: flex;
}
.night{
color: #CECECE;
}
.night a{
color: #CECECE;
}
.night.excerpt p {
text-align: center; /* 文本居中 */
white-space: normal; /* 确保文本自动换行 */
//word-wrap: break-word; /* 长单词或URL在必要时可以换行 */
overflow-wrap: break-word; /* 同上,是 word-wrap 的新名称 */
}
.big_font_size{
font-size: 20px;
}
.readmore-box {
text-align: center; /* 使内容在水平方向上居中 */
display: flex; /* 使用flex布局 */
justify-content: center; /* 在主轴上居中 */
align-items: center; /* 在交叉轴上居中 */
}
.readmore {
display: inline-block; /* 使链接表现得像块级元素,但不会换行 */
white-space: nowrap; /* 防止文本换行 */
}
img{
margin: auto;
display: block;
}
.copy-btn{
}
.excerpt a{
text-decoration: underline;
}
.excerpt a:not(:has(img))::after {
content: '\f08e'; /* Font Awesome 的外链图标 Unicode */
font-family: 'Font Awesome 5 Free'; /* 指定 Font Awesome 字体 */
font-weight: 900; /* 根据图标库的要求,通常使用 900 粗细 */
margin-left: 5px; /* 图标和链接之间的间距 */
font-size: 12px; /* 调整图标大小 */
}
ul{
padding: 0;
margin: 0;
}
.caption{
background-color:
}
.center{
text-align: center;
justify-content: center;
align-content: center;
align-items: center;
}
.margin{
margin:15px;
}
@media (max-width: 767px) {
.container{
display:flex;
justify-content: flex-start
}
.page-all-minbox{
margin-top: 120px;
margin-right: 1px;
margin-left: 1px;
padding: 1px;
flex-direction: column; /* 子元素垂直排列 */
//height: 100vh; /* 容器高度 */
}
.page-minbox{
max-width:400px;
}
.posts{
margin: auto;
max-width: 400px;
}
.posts-container{
margin: auto;
max-width: 400px;
}
}
@import "_partial/header";
@import "post";
@import "a11y-dark"
@import "_partial/footer"
@import "_partial/pagination"
@import "_partial/sidebar"
@import "_partial/comments"
@import "_partial/search"
@import "archive"
@import "tags"
@import "page"
@import "category"
@import "links" | 2303_806435pww/hexo-theme-wang | source/css/style.styl | Stylus | unlicense | 6,121 |
element.style {
font-size: 12px;
color: none;
}
.tag-clouds {
width: 100%;
display: flex;
flex-wrap: wrap;
background-color: #33333367;
}
.tag-clouds a{
margin: 10px;
padding: 5px 10px;
}
.night a {
color: #cecece;
}
.tag-clouds a {
position: relative;
cursor: pointer;
text-decoration: none; /* 去除默认的下划线 */
display: grid;
place-items: center;
padding-bottom: 2px; /* 为下划线留出空间 */
transition: all 0.3s ease-in-out; /* 过渡效果 */
}
.tag-clouds a::after {
content: '';
position: absolute;
left: 50%;
right: 50%;
bottom: 0;
height: 1px; /* 下划线高度 */
background: #D3D3D3; /* 灰白色 */
transition: all 0.3s ease-in-out; /* 过渡效果 */
}
.tag-clouds a:hover::after {
left: 0;
right: 0;
}
.tag-cloud{
width: 50%;
display: flex;
flex-direction: column;
flex-wrap: wrap;
margin-top:60px;
background-color: #33333367;
}
.tagpost{
text-align: center;
width: auto;
margin: 10px;
padding: 10px;
border-radius: 5px;
border: 1px solid #D3D3D3;
}
.sidebar-tags{
display: flex;
flex-direction: row;
flex-wrap: wrap;
flex :1;
justify-content: space-around;
}
.rtag-link{
border: 1px outset #D3D3D3;
margin: 3px
padding : 2px;
}
ul{
padding: 0;
}
[class^="tag-cloud-"] {
display: inline-block;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 3px outset #D3D3D3;
margin: 5px;
padding: auto;
}
| 2303_806435pww/hexo-theme-wang | source/css/tags.styl | Stylus | unlicense | 1,557 |
// 监听复制事件
document.addEventListener('copy', function(event) {
// 创建copyNotice元素
const copyNotice = document.createElement('div');
copyNotice.id = 'copy-notice';
copyNotice.textContent = '复制成功,转载请标记出处';
copyNotice.style.position = 'fixed';
copyNotice.style.left = '50%';
copyNotice.style.top = '80%'; // 可以根据需要调整位置
copyNotice.style.transform = 'translate(-50%, -50%)';
copyNotice.style.whiteSpace = 'nowrap';
copyNotice.style.backgroundColor = '#fff';
copyNotice.style.border = '1px solid #ddd';
copyNotice.style.padding = '8px 16px';
copyNotice.style.boxShadow = '0 4px 6px rgba(0,0,0,0.1)';
copyNotice.style.zIndex = '1000';
copyNotice.style.fontSize = '14px';
copyNotice.style.color = '#333';
copyNotice.style.fontWeight = 'bold';
copyNotice.style.borderRadius = '4px';
// 将copyNotice添加到文档中
document.body.appendChild(copyNotice);
// 设置定时器,2秒后移除copyNotice
setTimeout(function() {
document.body.removeChild(copyNotice);
}, 2000);
});
// 获取所有class为code的元素
const codeElements = document.querySelectorAll('.code');
// 版权信息
const authorMeta = document.querySelector('meta[name="author"]');
const titleMeta = document.querySelector('meta[name="title"]');
const title = titleMeta? titleMeta.content : '';
const author = authorMeta ? authorMeta.content : '';
const url = window.location.href
const copyrightInfo = `© ${author} 保留所有权利。\n 复制自:${title} \nlink" ${url}。`;
codeElements.forEach((codeElement) => {
// 创建复制按钮
const copyBtn = document.createElement('button');
copyBtn.textContent = 'copy';
copyBtn.className = 'copy-btn night box';
// 将按钮添加到代码块的右上角
codeElement.insertBefore(copyBtn, codeElement.firstChild);
// 给按钮添加点击事件
copyBtn.addEventListener('click', () => {
// 创建一个临时的textarea元素来复制文本
const tempTextArea = document.createElement('textarea');
tempTextArea.value = codeElement.querySelector('code').textContent + '\n' + copyrightInfo;
document.body.appendChild(tempTextArea);
tempTextArea.select();
document.execCommand('copy');
document.body.removeChild(tempTextArea);
// 在控制台显示版权信息
console.log(copyrightInfo);
});
}); | 2303_806435pww/hexo-theme-wang | source/js/copyright.js | JavaScript | unlicense | 2,508 |
$(document).ready(function() {
$('img').each(function() {
if ($(this).parent().hasClass('fancybox')) return;
if ($(this).hasClass('nofancybox')) return;
var alt = this.alt;
//if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + ($(this).attr('data-src') == null ? this.src : $(this).attr('data-src')) + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article');
});
});
$(document).ready(function() {
$("a[href$='.jpg'],a[href$='.png'],a[href$='.gif'],a[href$='.webp']").attr('rel', 'gallery').fancybox({
helpers : {
title: { type: 'inside'}
}
});
});
| 2303_806435pww/hexo-theme-wang | source/js/fancybox.js | JavaScript | unlicense | 763 |
document.addEventListener('DOMContentLoaded', function() {
const header = document.getElementById('header');
let lastScrollTop = 0; // 上一次的滚动位置
// 监听滚动事件
window.addEventListener('scroll', function() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop; // 获取当前滚动位置
// 检查滚动方向
if (scrollTop > lastScrollTop) {
// 向下滚动
header.classList.add('hidden-header');
} else {
// 向上滚动
header.classList.remove('hidden-header');
}
// 更新上一次的滚动位置
lastScrollTop = scrollTop;
});
const mobieheader = document.getElementById('mobie-header');
let mobielastScrollTop = 0; // 上一次的滚动位置
// 监听滚动事件
window.addEventListener('scroll', function() {
let mobiescrollTop = window.pageYOffset || document.documentElement.scrollTop; // 获取当前滚动位置
// 检查滚动方向
if (mobiescrollTop > lastScrollTop) {
// 向下滚动
mobieheader.classList.add('hidden-header');
} else {
// 向上滚动
mobieheader.classList.remove('hidden-header');
}
// 更新上一次的滚动位置
lastScrollTop = mobiescrollTop;
});
}); | 2303_806435pww/hexo-theme-wang | source/js/header_hidden.js | JavaScript | unlicense | 1,424 |
// A local search script with the help of [hexo-generator-search](https://github.com/PaicHyperionDev/hexo-generator-search)
// Copyright (C) 2015
// Joseph Pan <http://github.com/wzpan>
// Shuhao Mao <http://github.com/maoshuhao>
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA
//
var searchFunc = function(path, search_id, content_id) {
'use strict';
$.ajax({
url: path,
dataType: "xml",
success: function( xmlResponse ) {
// get the contents from search data
var datas = $( "entry", xmlResponse ).map(function() {
return {
title: $( "title", this ).text(),
content: $("content",this).text(),
url: $( "url" , this).text()
};
}).get();
var $input = document.getElementById(search_id);
if (!$input) return;
var $resultContent = document.getElementById(content_id);
if ($("#local-search-input").length > 0) {
$input.addEventListener('input', function () {
var str = '<ul class=\"search-result-list\">';
var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
$resultContent.innerHTML = "";
if (this.value.trim().length <= 0) {
return;
}
// perform local searching
datas.forEach(function (data) {
var isMatch = true;
var content_index = [];
if (!data.title || data.title.trim() === '') {
data.title = "Untitled";
}
var data_title = data.title.trim().toLowerCase();
var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
var data_url = data.url;
var index_title = -1;
var index_content = -1;
var first_occur = -1;
// only match artiles with not empty contents
if (data_content !== '') {
keywords.forEach(function (keyword, i) {
index_title = data_title.indexOf(keyword);
index_content = data_content.indexOf(keyword);
if (index_title < 0 && index_content < 0) {
isMatch = false;
} else {
if (index_content < 0) {
index_content = 0;
}
if (i == 0) {
first_occur = index_content;
}
// content_index.push({index_content:index_content, keyword_len:keyword_len});
}
});
} else {
isMatch = false;
}
// show search results
if (isMatch) {
str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
var content = data.content.trim().replace(/<[^>]+>/g, "");
if (first_occur >= 0) {
// cut out 100 characters
var start = first_occur - 20;
var end = first_occur + 80;
if (start < 0) {
start = 0;
}
if (start == 0) {
end = 100;
}
if (end > content.length) {
end = content.length;
}
var match_content = content.substring(start, end);
// highlight all keywords
keywords.forEach(function (keyword) {
var regS = new RegExp(keyword, "gi");
match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
});
str += "<p class=\"search-result\">" + match_content + "...</p>"
}
str += "</li>";
}
});
str += "</ul>";
$resultContent.innerHTML = str;
});
}
}
});
} | 2303_806435pww/hexo-theme-wang | source/js/search.js | JavaScript | unlicense | 5,785 |
import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
markdown: {
math: true
},
head: [
// 设置 favor.ico,.vuepress/public 下
[
'link', { rel: 'icon', href: '/poached-eggs-svgrepo-com.svg' }
],
[
'meta', { name: 'keywords', content: '东北大学,新生,指南,手册,校园卡,校园网,浑南校区,南湖校区' }
],
[
'meta', { name: 'baidu-site-verification', content: 'codeva-r46gbVuad2' }
],
]
,
title: "NEU Survive Guide",
titleTemplate: 'NEU生存手册',
description: "一个是帮助东北大学的同学在生活、学习等方面提供帮助的网站",
themeConfig: {
nav: [
{ text: '主页', link: '/' },
{ text: '开始阅读', link: '/introduction' }
],
logo: '/poached-eggs-svgrepo-com.svg',
sidebar: [
{
text: '简介篇',
items: [
{
text: '写在前面',
link: '/introduction'
},
]
},
{
text: '贡献者寄语',
items: [
{
text: '23届自动化同学',
link: '/message/suli'
},
]
},
{
text: '校园生活',
items: [
{
text: '通用篇',
items: [
{ text: '医疗与报销', link: '/daily/tongyong/yiliao' },
{ text: '气候与穿衣', link: '/daily/tongyong/qihou' },
{ text: '诈骗防范', link: '/daily/tongyong/zhapian' },
{ text: '运动健身', link: '/daily/tongyong/yundong' },
{ text: '校园卡业务', link: '/daily/tongyong/xiaoyuanka' },
{ text: '校园网', link: '/daily/tongyong/xiaoyuanwang' },
]
},
{
text: '浑南校区篇',
items: [
{ text: '出行方式', link: '/daily/hunnan/chuxing' },
{ text: '周边娱乐', link: '/daily/hunnan/yuletuijian'},
],
},
{
text: '南湖校区篇',
items: [
{ text: '吃在南湖', link: '/daily/nanhu/yinshi' },
{ text: '校园日常', link: '/daily/nanhu/shenghuo' },
{ text: '出行方式', link: '/daily/nanhu/chuxing' },
{ text: '周边娱乐', link: '/daily/nanhu/yule' },
],
}
]
},
{
text: '学在东大',
items: [
{ text: '基础学业信息', link: '/learning/xueyexinxi' },
{ text: '机考指南', link: '/learning/jikao' },
{ text: '保研', link: '/learning/baoyan' },
{ text: '公共课', link: '/learning/gonggongke' },
{ text: '竞赛', link: '/learning/jingsai' },
{ text: '选调', link: '/learning/xuandiao' },
]
},
{
text: '学院攻略',
items: [
{ text: '写在前面', link: '/college/introduction' },
{
text: '软件学院', items: [
{ text: '学院简介', link: '/college/software/jianjie' },
{ text: '保研', link: '/college/software/baoyan' },
{ text: '创新创业与竞赛', link: '/college/software/chuangxin' },
{ text: '就业', link: '/college/software/jiuye' },
]
},
{
text: '信息学院', items: [
{ text: '学院简介', link: '/college/automation/jianjie' },
]
},
]
}
],
search: {
provider: 'local'
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/SugrSertraline/neu-survive-guide' }
]
},
// base: '/neu-survive-guide/'
// base: '/test/'
})
| 2303_806435pww/neu-survive-guide | .vitepress/config.mts | TypeScript | unknown | 3,813 |
<template>
<el-timeline style="max-width: 600px">
<el-timeline-item v-for="i in data" :key="i.id" :timestamp="i.timestamp" placement="top">
<el-card>
<p>{{ i.content }}</p>
</el-card>
</el-timeline-item>
</el-timeline>
</template>
<script setup>
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { ElTimelineItem ,ElTimeline,ElCard} from 'element-plus';
const props = defineProps(['data'])
</script> | 2303_806435pww/neu-survive-guide | components/TimeLineComponent.vue | Vue | unknown | 484 |
/* 提示框的CSS样式 */
#agplAlert {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: rgba(105, 105, 105, 0.9);
text-align: center;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
z-index: 1000;
animation-fill-mode: forwards;
opacity: 0;
}
/* 动画效果 */
@keyframes slideOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
/* 当提示框显示时添加动画 */
.showAlert {
animation: slideOut 7s forwards;
} | 2303_806435pww/hexo-theme-wang_moved | source/css/alert.styl | Stylus | agpl-3.0 | 539 |
.archives {
display: flex
flex-direction: column
align-items: center
width: 100%
max-width: 1200px
margin: 0 auto
min-height: 100vh
h1 {
font-size: 1.8em
text-align: center
margin-top: 4em
}
.archive-grid {
display: grid
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr))
gap: 30px
padding: 30px
width: 100%
justify-content: center
.archive-card {
background: rgba(255, 255, 255, 0.1) // 半透明背景
border-radius: 8px
padding: 15px
box-shadow: 0 2px 8px rgba(0,0,0,0.08)
transition: transform 0.2s, background 0.2s
border: 1px solid rgba(255, 255, 255, 0.2)
max-width: 350px
width: 100%
margin: 0 auto
max-height: 400px
display: flex
flex-direction: column
overflow: hidden
&:hover {
transform: translateY(-3px)
box-shadow: 0 4px 12px rgba(0,0,0,0.12)
background: rgba(255, 255, 255, 0.2) // 悬浮时加深背景透明度
}
.card-dates {
display: flex
justify-content: space-between
margin-bottom: 10px
}
.card-date, .card-update {
display: flex
align-items: center
color: #ccc // 调整文字颜色为浅灰色
font-size: 0.9em
margin-bottom: 10px
img {
margin-right: 5px
}
}
.card-title {
margin: 10px 0
font-size: 1.2em
a {
color: #fff // 调整链接颜色为白色
text-decoration: none
&:hover {
color: #ddd // 悬浮时颜色变浅
}
}
}
.card-excerpt {
color: #ccc // 调整文字颜色为浅灰色
font-size: 0.9em
margin: 10px 0
line-height: 1.5
overflow: hidden
display: -webkit-box
-webkit-line-clamp: 3
line-clamp: 3
-webkit-box-orient: vertical
max-height: 200px
overflow-y: auto
&::-webkit-scrollbar {
width: 4px
}
&::-webkit-scrollbar-thumb {
background: #555 // 调整滚动条颜色为深灰色
border-radius: 2px
}
img {
max-width: 100%
height: auto
display: block
margin: 10px auto
border-radius: 4px
max-height: 150px
object-fit: cover
}
}
.card-tags {
margin-top: 10px
.tag {
display: inline-block
padding: 2px 8px
margin: 0 4px 4px 0
background: rgba(255, 255, 255, 0.2) // 半透明背景
border-radius: 4px
font-size: 0.8em
color: #ccc // 调整文字颜色为浅灰色
text-decoration: none
&:hover {
background: rgba(255, 255, 255, 0.3) // 悬浮时加深背景透明度
}
}
}
}
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/archives.styl | Stylus | agpl-3.0 | 3,740 |
#starry-background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
pointer-events: none;
overflow: hidden;
background-color: transparent; // 确保背景透明
}
#stars-canvas {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
// 在低端设备上减少动画效果
@media (prefers-reduced-motion: reduce) {
#stars-canvas {
animation: none !important;
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/background.styl | Stylus | agpl-3.0 | 495 |
.categories-page {
max-width: 100%;
margin: 0 auto;
padding: 20px;
h1 {
text-align: center;
margin-top: 4em;
}
}
.categories-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 40px;
justify-content: center;
.category-item {
background: rgba(255, 255, 255, 0.1);
padding: 10px 15px;
border-radius: 10px;
transition: all 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.2);
color: #00ffff;
font-size: 1em;
text-align: center;
&:hover {
background: rgba(255, 255, 255, 0.2);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}
a {
color: #00ffff;
text-decoration: none;
span {
color: #00ffff;
margin-left: 5px;
}
}
}
}
.category-detail-page {
max-width: 800px;
margin: 40px auto;
padding: 20px;
.category-post-item {
display: flex;
align-items: center;
padding: 15px 0;
border-bottom: 1px solid #eee;
.post-date {
min-width: 100px;
color: #999;
font-size: 14px;
}
.post-title {
margin: 0;
a {
color: #fff;
text-decoration: none;
font-size: 16px;
&:hover {
color: #007bff;
}
}
}
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/categories.styl | Stylus | agpl-3.0 | 1,320 |
.ccbyncsa {
display: flex;
justify-content: space-between;
align-items: center;
text-align: center;
background: rgba(15, 15, 25, 0.13) // 降低不透明度
backdrop-filter: blur(15px) // 增加模糊效果
-webkit-backdrop-filter: blur(15px) // Safari 支持
border: 1px solid rgba(255, 255, 255, 0.1) // 添加微妙的边框
border-radius: 12px
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) // 增强阴影效果
}
.ccbyncsa .container {
width: 100%;
}
.ccbyncsa .row {
display: flex;
justify-content: space-between;
align-items: center;
}
.ccbyncsa .col-md-12 {
flex: 1;
}
.ccbyncsa .copyright {
display: flex;
justify-content: space-between;
align-items: center;
}
.ccbyncsa .author,
.ccbyncsa .title,
.ccbyncsa .publish,
.ccbyncsa .ccbyncsa-icon {
display: flex;
flex-direction: column;
align-items: center;
}
.ccbyncsa .author p:first-child,
.ccbyncsa .title p:first-child,
.ccbyncsa .publish p:first-child,
.ccbyncsa .ccbyncsa-icon p:first-child {
margin-bottom: 5px; /* 根据需要调整间距 */
}
.ccbyncsa .ccbyncsa-icon img {
width: 32px; /* 根据实际图标大小调整 */
height: auto;
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/ccbyncsa.styl | Stylus | agpl-3.0 | 1,212 |
// 代码块基础样式 - 优化
pre code.hljs {
display: block;
overflow-x: auto;
padding: 1.2em;
font-family: 'JetBrains Mono', Consolas, Monaco, 'Andale Mono', monospace !important;
font-size: 0.92em;
line-height: 1.5;
letter-spacing: 0.02em;
}
code.hljs {
padding: 2px 5px;
border-radius: 4px;
font-size: 0.92em;
}
// 代码框主结构 - 现代化外观
figure.highlight {
margin: 1.8em 0;
position: relative;
font-size: 0.92em;
border-radius: 12px;
background: rgba(30, 30, 40, 0.95); // 调整背景色
box-shadow:
0 8px 30px rgba(0, 0, 0, 0.3),
0 0 10px rgba(100, 100, 255, 0.1); // 双层阴影
border: 1px solid rgba(100, 100, 255, 0.15);
transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
overflow: hidden;
&:hover {
box-shadow:
0 12px 35px rgba(0, 0, 0, 0.4),
0 0 15px rgba(100, 100, 255, 0.15);
transform: translateY(-2px);
}
// 表格结构
table {
width: 100%;
border-spacing: 0;
margin: 0;
border: none;
}
td {
padding: 0;
border: none;
}
// 行号区域 - 改善对比度
.gutter {
width: 3.2em;
user-select: none;
background: rgba(20, 20, 30, 0.7); // 加深背景色
pre {
text-align: right;
padding: 1em 0.7em 1em 0;
margin: 0;
color: rgba(169, 183, 198, 0.6); // 提高可读性
font-family: 'JetBrains Mono', Consolas, Monaco, monospace !important;
}
// 删除垂直分隔线
&::after {
display: none; // 隐藏竖线
}
}
// 代码区域 - 添加内边距
.code {
width: calc(100% - 3.2em);
pre {
margin: 0;
padding: 1em 1.5em;
padding-left: 0.5em; // 添加左侧内边距
font-family: 'JetBrains Mono', Consolas, Monaco, monospace !important;
}
}
}
// 语言标签 - 增强显示效果
figure.highlight::before {
content: attr(data-lang);
position: absolute;
top: 0;
left: 0;
color: #e4e4e4;
background: rgba(60, 60, 120, 0.7); // 调整为蓝紫色调
padding: 0.3em 0.8em;
border-radius: 0 0 8px 0;
font-size: 0.75em;
font-weight: 500;
letter-spacing: 0.05em;
z-index: 2;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
// 复制按钮容器
.copy-btn-wrapper {
position: absolute;
top: 0;
right: 0;
z-index: 5;
}
// 复制按钮 - 现代化设计
.copy-btn {
background: rgba(80, 80, 180, 0.3); // 更加蓝紫的基调
border: 1px solid rgba(100, 100, 255, 0.25);
color: #e0e0ff;
padding: 0.35em 0.8em;
border-radius: 0 10px 0 10px;
font-size: 0.8em;
font-weight: 500;
cursor: pointer;
transition: all 0.25s ease;
outline: none;
&:hover {
background: rgba(100, 100, 200, 0.5);
color: white;
box-shadow: 0 0 10px rgba(100, 100, 255, 0.2);
}
&:active {
transform: translateY(1px);
}
}
/* Monokai风格代码高亮 */
.highlight {
color: #f8f8f2;
.comment, .quote {
color: #75715e;
font-style: italic;
}
.keyword, .selector-tag, .tag {
color: #f92672;
}
.builtin, .name, .built_in, .function, .attr {
color: #a6e22e;
}
.string, .title, .section, .attribute, .symbol, .literal {
color: #e6db74;
}
.number, .params {
color: #ae81ff;
}
.type, .class, .class .title {
color: #66d9ef;
font-style: italic;
}
.variable, .template-variable {
color: #fd971f;
}
.regexp, .addition, .link {
color: #a6e22e;
}
.deletion {
color: #f92672;
}
.meta {
color: #75715e;
}
}
// 移动端优化
@media (max-width: 768px) {
figure.highlight {
font-size: 0.85em;
.gutter {
width: 2.2em;
&::after {
left: 2.2em;
}
pre {
padding-right: 0.3em;
}
}
.code {
width: calc(100% - 2.2em);
pre {
padding: 1em 0.8em;
}
}
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/code.styl | Stylus | agpl-3.0 | 3,836 |
.copy-btn {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
padding: 5px 10px;
background-color: #282828; /* 按钮背景颜色 */
color: #fff; /* 按钮文本颜色 */
border: 1px solid #444; /* 按钮边框颜色 */
border-radius: 4px;
font-size: 12px; /* 按钮字体大小 */
z-index: 10; /* 确保按钮在代码块之上 */
}
.copy-btn:hover {
background-color: #383838; /* 按钮悬停背景颜色 */
} | 2303_806435pww/hexo-theme-wang_moved | source/css/copy.styl | Stylus | agpl-3.0 | 480 |
.site-date{
position: absolute;
top: 10%;
width : 100%;
min-height: 10%;
#date {
text-align: center;
margin:auto;
font-size: 4.2em;
color: #777777;
font-family: 'Arial', sans-serif;
z-index : 1000;
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/date.styl | Stylus | agpl-3.0 | 249 |
.first-screen {
position: sticky;
height: 100vh;
z-index: 1;
/* 通用容器样式 */
[class$="-container"] {
position: relative;
height: 50%;
z-index: 2;
/* 通过伪元素实现背景和剪裁 */
&::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
z-index: 1; /* 背景层 */
}
/* 内容容器始终在上层 */
.container {
position: absolute;
z-index: 2;
}
}
/* 左上角三角形容器 */
.lefttop-container {
&::before {
clip-path: polygon(100% 0, 0 0, 0 100%);
background: rgba(0, 0, 0, 0.342);
}
.container {
top: 15%;
left: 15%;
}
}
/* 右下角三角形容器 */
.rightbottom-container {
&::before {
clip-path: polygon(100% 0, 0 100%, 100% 100%);
background: rgba(129, 129, 129, 0.363);
}
.container {
bottom: 15%;
right: 15%;
/* 社交链接网格优化 */
.social_links {
display: grid;
gap: 15px; /* 增加间距 */
list-style: none;
margin: 0;
padding: 0;
/* 图片尺寸控制 */
img {
width: 35px;
height: 35px; /* 固定宽高比 */
object-fit: contain; /* 防止拉伸 */
transition: transform 0.3s; /* 悬停动效 */
}
/* 可选:悬停放大效果 */
a:hover img {
transform: scale(1.1);
}
}
}
}
.description-io {
position: absolute; // 确保其在父容器内绝对定位
z-index: 99; // 设置较高的z-index
left: 50%; // 水平居中
top: 50%; // 垂直居中
transform: translate(-50%, -50%); // 水平垂直居中
background-color: rgba(0, 0, 0, 0.205); // 添加半透明背景
padding: 1rem; // 添加内边距
border-radius: 8px; // 添加圆角
text-align: center; // 居中文本
color: #ffffff; // 设置文本颜色
}
.typed-cursor, .cursor {
font-size: 1.5rem;
color: #00ffff;
animation: blink 0.7s infinite;
}
@keyframes blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/first_screen.styl | Stylus | agpl-3.0 | 2,620 |
// 抖音美好体 - 全局字体
@font-face {
font-family: 'DouyinSans'
font-style: normal
font-weight: 700
font-display: swap
src: url(../fonts/DouyinSans/DouyinSansBold.ttf) format('truetype')
}
// JetBrains Mono - 仅用于代码
@font-face {
font-family: 'JetBrains Mono'
font-style: normal
font-weight: 400
font-display: swap
src: url(../fonts/JetBrainsMono/JetBrainsMono-Regular.woff2) format('woff2')
}
@font-face {
font-family: 'JetBrains Mono'
font-style: normal
font-weight: 700
font-display: swap
src: url(../fonts/JetBrainsMono/JetBrainsMono-Bold.woff2) format('woff2')
}
@font-face {
font-family: 'JetBrains Mono'
font-style: italic
font-weight: 400
font-display: swap
src: url(../fonts/JetBrainsMono/JetBrainsMono-Italic.woff2) format('woff2')
}
// 应用全局字体
html {
font-family: 'DouyinSans', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif
}
body, button, input, select, textarea {
font-family: inherit
}
// 专门为代码元素应用编程字体
code, pre, .highlight pre, .hljs, .gutter pre {
font-family: 'JetBrains Mono', Consolas, Monaco, monospace !important
font-feature-settings: "liga" 0 // 禁用连字以提高代码可读性
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/fonts.styl | Stylus | agpl-3.0 | 1,238 |
footer {
bottom: 0;
width: 100%;
padding: 1rem 0;
text-align: center;
margin-top: auto; // 确保在页面底部
.footer-links {
margin: 1rem auto;
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 1rem;
a {
text-decoration: none;
transition: opacity 0.3s;
&:hover {
opacity: 0.8;
}
img {
height: 30px;
width: auto;
vertical-align: middle;
}
}
}
.footer-text-links {
margin-top: 1rem;
a {
color: #666;
text-decoration: none;
margin: 0 0.5rem;
font-size: 0.9rem;
transition: color 0.3s;
&:hover {
color: #333;
text-decoration: underline;
}
}
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/footer.styl | Stylus | agpl-3.0 | 991 |
header {
position: fixed;
z-index: 1000;
top: 0; // 始终保持在顶部
left: 0;
right: 0;
width: 100%;
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
background-color: rgba(0, 0, 0, 0.11);
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
box-shadow: 0 2px 20px rgba(0, 0, 0, 0.15);
font-family: 'DouyinSans', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
transition: transform 0.3s ease;
height: 60px; // 固定高度
// 导航容器
nav {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
// 菜单列表 - 强制横向显示且不换行
ul {
list-style: none;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex-wrap: nowrap; // 修改:不允许换行
gap: 1rem;
padding: 0.5rem 1rem;
margin: 0;
overflow-x: auto; // 添加横向滚动以适应小屏幕
scrollbar-width: none; // 隐藏滚动条(Firefox)
-ms-overflow-style: none; // 隐藏滚动条(IE/Edge)
&::-webkit-scrollbar {
display: none; // 隐藏滚动条(Chrome/Safari)
}
}
li {
position: relative;
padding: 0.3rem 0.5rem; // 减小内边距
transition: all 0.3s ease;
flex-shrink: 0; // 防止项目被压缩
}
a, button.search-toggle-btn {
position: relative;
text-decoration: none;
color: #e1e1ff;
font-weight: 500;
padding: 0.25rem 0;
display: inline-flex;
align-items: center;
font-size: 1.1rem; // 稍微减小字体大小,方便移动端显示
white-space: nowrap; // 强制文字不换行
background: none;
border: none;
cursor: pointer;
&::before {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: linear-gradient(90deg, #00ffff, #66ffff);
transition: width 0.3s ease-in-out;
}
&:hover, &.active {
color: #fff;
&::before {
width: 100%;
}
}
}
.menu-icon {
width: 22px;
height: 22px;
vertical-align: middle;
margin-right: 8px;
}
// 汉堡菜单按钮调整
.hamburger {
display: none; // 大屏幕下隐藏
flex-direction: column;
justify-content: space-between;
width: 25px;
height: 18px;
position: absolute;
right: 20px;
top: 20px;
cursor: pointer;
z-index: 100;
padding: 10px;
background: none;
border: none;
span {
display: block;
height: 2px;
width: 100%;
background-color: #e1e1ff;
border-radius: 2px;
transition: all 0.3s ease;
}
&.active {
span:nth-child(1) {
transform: translateY(8px) rotate(45deg);
}
span:nth-child(2) {
opacity: 0;
}
span:nth-child(3) {
transform: translateY(-8px) rotate(-45deg);
}
}
}
}
// 修改响应式设计,保持菜单横向显示
@media (max-width: 768px) {
header {
ul {
flex-direction: column; // 垂直排列菜单项
position: fixed;
top: 0;
left: 0;
right: 0;
background-color: rgba(10, 10, 15, 0.95);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
padding: 4rem 1rem 2rem;
gap: 1.2rem;
transform: translateY(-100%);
transition: transform 0.3s ease;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
z-index: 5;
flex-wrap: nowrap; // 确保不换行
overflow-y: auto; // 添加纵向滚动以适应很多菜单项
max-height: 80vh; // 限制最大高度
}
ul.active {
transform: translateY(0);
}
.hamburger {
display: flex; // 小屏幕上显示汉堡菜单
top: 15px; // 位置调整
}
li {
width: 100%; // 每个菜单项占满宽度
text-align: center;
padding: 0.5rem 0;
}
a, button.search-toggle-btn {
justify-content: center; // 文字居中
width: auto; // 宽度自适应内容
display: inline-flex; // 内联弹性布局
font-size: 1.1rem; // 保持合适的字体大小
padding: 0.25rem 1rem; // 添加水平内边距
white-space: nowrap; // 再次确认文字不换行
.menu-icon {
width: 20px;
height: 20px;
margin-right: 8px;
}
&::before {
bottom: -3px;
}
}
}
}
// 滚动时隐藏导航
header.scroll-down {
transform: translateY(-100%);
}
// 搜索结果样式保持不变
#search-results {
position: absolute;
top: 60px;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-width: 600px;
background: rgba(0, 0, 0, 0.8);
border-radius: 5px;
padding: 1rem;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
z-index: 1000;
display: none;
}
.search-result-item {
margin-bottom: 1rem;
}
.search-result-item a {
color: #00ffff;
text-decoration: none;
}
.search-result-item a:hover {
text-decoration: underline;
}
@keyframes pulse {
0% {
transform: scale(1);
opacity: 0.8;
}
50% {
transform: scale(1.3); // 增大缩放比例
opacity: 1;
}
100% {
transform: scale(1);
opacity: 0.8;
}
}
@keyframes breathing {
0% {
filter: drop-shadow(0 0 3px rgba(66,185,231,0.3));
}
50% {
filter: drop-shadow(0 0 15px rgba(66,185,231,1)); // 增强发光效果
}
100% {
filter: drop-shadow(0 0 3px rgba(66,185,231,0.3));
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/header.styl | Stylus | agpl-3.0 | 6,268 |
.links-page {
max-width: 100%;
margin: 0 auto;
padding: 20px;
h1 {
text-align: center;
margin-top: 4em;
color: #fff;
}
}
.links-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 20px;
justify-content: center;
.link-item {
background: rgba(255, 255, 255, 0.1);
padding: 10px 15px;
border-radius: 10px;
transition: all 0.3s ease;
border: 1px solid rgba(255, 255, 255, 0.2);
color: #00ffff;
font-size: 1em;
text-align: center;
&:hover {
background: rgba(255, 255, 255, 0.2);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}
a {
color: #00ffff;
text-decoration: none;
img {
width: 50px;
height: 50px;
border-radius: 50%;
margin-bottom: 10px;
}
.link-name {
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.link-description {
color: #00ffff;
font-size: 0.9em;
}
}
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/links.styl | Stylus | agpl-3.0 | 1,061 |
.page-container {
max-width: 1200px
margin: 0 auto
padding: 20px
min-height: 100vh
h1 {
text-align: center
margin-bottom: 2em
}
}
// 分类列表样式
.categories-list {
display: flex
flex-direction: column
align-items: center
gap: 15px
.category-item {
background: rgba(255, 255, 255, 0.1)
padding: 10px 20px
border-radius: 8px
width: 80%
max-width: 600px
transition: all 0.3s ease
border: 1px solid rgba(255, 255, 255, 0.2)
a {
display: flex
justify-content: space-between
align-items: center
color: #00ffff
text-decoration: none
span {
opacity: 0.8
}
}
&:hover {
background: rgba(255, 255, 255, 0.2)
transform: translateY(-2px)
box-shadow: 0 4px 12px rgba(0,0,0,0.12)
}
}
}
// 关于页面样式
.about-content {
background: rgba(255, 255, 255, 0.1)
padding: 30px
border-radius: 12px
border: 1px solid rgba(255, 255, 255, 0.2)
line-height: 1.8
img {
max-width: 100%
border-radius: 8px
margin: 20px 0
}
}
// 默认页面样式
.page-content {
background: rgba(255, 255, 255, 0.1)
padding: 30px
border-radius: 12px
border: 1px solid rgba(255, 255, 255, 0.2)
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/page.styl | Stylus | agpl-3.0 | 1,269 |
.paginator {
display: flex
justify-content: center
padding: 30px 0
.page-number, .extend { // 匹配Hexo生成的类名
min-width: 45px
height: 45px
margin: 0 5px
display: flex
align-items: center
justify-content: center
background: rgba(255, 255, 255, 0.1)
border: 1px solid rgba(255, 255, 255, 0.2)
border-radius: 8px
color: #00ffff
text-decoration: none
transition: all 0.3s ease
font-size: 1.1em
&:hover {
background: rgba(255, 255, 255, 0.2)
color: #66ffff
transform: translateY(-2px)
box-shadow: 0 4px 12px rgba(0,0,0,0.12)
}
&.current { // 当前页样式
background: rgba(255, 255, 255, 0.25)
color: #ffffff
font-weight: bold
border-color: rgba(255, 255, 255, 0.3)
box-shadow: 0 2px 8px rgba(0,0,0,0.15)
&:hover {
transform: none
}
}
}
.space { // 省略号样式
padding: 0 10px
color: #ffffff
display: flex
align-items: center
}
.extend { // 上一页下一页按钮样式
font-weight: bold
min-width: 60px // 稍微加宽
&.prev {
margin-right: 10px
}
&.next {
margin-left: 10px
}
}
// 包装器样式
nav {
background: rgba(255, 255, 255, 0.05)
padding: 10px
border-radius: 12px
box-shadow: 0 2px 8px rgba(0,0,0,0.08)
display: flex
align-items: center
gap: 5px
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/paginator.styl | Stylus | agpl-3.0 | 1,467 |
.post-container {
max-width: 900px
margin: 2.5rem auto // 增加上下边距
padding: 2.5rem
background: rgba(15, 15, 25, 0.15) // 轻微调整透明度
backdrop-filter: blur(18px) // 增强模糊效果
-webkit-backdrop-filter: blur(18px)
border: 1px solid rgba(255, 255, 255, 0.12)
border-radius: 16px // 增大圆角
box-shadow:
0 10px 40px rgba(0, 0, 0, 0.15),
0 0 20px rgba(0, 0, 0, 0.1) // 双层阴影增强深度感
transition: transform 0.3s ease, box-shadow 0.3s ease
&:hover {
box-shadow:
0 15px 50px rgba(0, 0, 0, 0.2),
0 0 25px rgba(0, 0, 0, 0.15)
transform: translateY(-5px)
}
}
// 新增响应式设计
@media (max-width: 768px)
.post-container
max-width: 95%
padding: 1rem
.post-title {
color: #ffffff
font-size: 2.4rem
margin-bottom: 1.8rem
text-align: center
font-weight: 600
letter-spacing: 0.02em
text-shadow: 0 0 10px rgba(255, 255, 255, 0.1) // 添加微妙文字阴影
}
.post-meta {
color: #a8a8b8
text-align: center
margin-bottom: 2.5rem
font-size: 0.95rem
font-style: italic
}
.post-content {
color: #e4e4e4
line-height: 1.8
font-size: 1.1rem
letter-spacing: 0.01em
h1, h2, h3, h4, h5, h6 {
color: #ffffff
margin: 2.5rem 0 1.2rem
font-weight: 700
position: relative
letter-spacing: 0.02em
&::after {
content: ""
position: absolute
bottom: -6px
left: 0
width: 60px // 增加宽度
height: 3px // 增加高度
background: linear-gradient(90deg, rgba(127, 166, 255, 0.8), rgba(127, 166, 255, 0.2)) // 添加渐变
border-radius: 3px
}
}
p {
margin-bottom: 1.5rem
text-align: justify
code, pre {
text-align: left
}
}
blockquote {
margin: 1.5rem 0
padding: 1.2rem 1.5rem
border-left: 4px solid rgba(0, 255, 255, 0.3) // 使用青色边框
background: rgba(0, 0, 0, 0.25)
border-radius: 0 10px 10px 0
font-style: italic
p {
margin-bottom: 0
}
}
ul, ol {
padding-left: 1.5rem
margin: 1rem 0
li {
margin: 0.5rem 0
}
}
.highlight{
overflow-x: auto;
max-width: 100%;
border-radius: 10px;
margin: 1.5rem 0;
}
code {
background: rgba(40, 44, 68, 0.5)
color: #ff7edb
padding: 0.2em 0.4em
border-radius: 3px
font-family: 'JetBrains Mono', Consolas, Monaco, monospace
font-size: 0.9em
letter-spacing: 0
border: 1px solid rgba(100, 100, 255, 0.15)
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1)
}
// 确保行内代码与代码块区分
p > code, li > code, td > code {
font-size: 0.85em;
white-space: nowrap;
}
pre {
background: rgba(40, 44, 68, 0.3)
padding: 0
border-radius: 10px
overflow: hidden
margin: 1.5rem 0
border: 1px solid rgba(100, 100, 255, 0.12)
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25)
position: relative
transition: all 0.3s ease
&:hover {
box-shadow: 0 6px 25px rgba(0, 0, 0, 0.3)
}
&::before, &::after {
display: none
}
code {
background: none
padding: 0.5em
border: none
box-shadow: none
color: inherit
text-align: left // 确保代码是左对齐的
font-family: 'JetBrains Mono', Consolas, Monaco, monospace
}
}
// 确保highlight内的样式不受post-content影响
.highlight pre,
.highlight code,
.highlight .line {
text-align: left !important // 强制左对齐
justify-content: flex-start !important // 防止 justify 样式影响
}
img {
display: block
max-width: 100%
border-radius: 8px
margin: 1.5rem auto
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)
}
table {
width: 100%
border-collapse: collapse
margin: 1.5rem 0
th, td {
padding: 0.75rem
border: 1px solid rgba(255, 255, 255, 0.1)
background: rgba(255, 255, 255, 0.02)
text-align: center
}
th {
background: rgba(127, 166, 255, 0.1)
}
}
hr {
border: none
height: 1px
background: rgba(255, 255, 255, 0.1)
margin: 2rem 0
}
a {
color: #00ffff
text-decoration: none
border-bottom: 1px dashed rgba(0, 255, 255, 0.4)
transition: all 0.3s ease
position: relative
padding: 0 2px
&:hover {
color: #80ffff
border-bottom-style: solid
background: rgba(0, 255, 255, 0.08)
border-radius: 2px
}
}
strong, b {
color: #ffc66d // 为 strong/b 标签设置特殊的橙黄色调
}
em, i {
color: #8be9fd // 新增:为 emphasis / italic 标签着色
}
u {
text-decoration: underline
color: #e06c75 // 新增:为下划线文本设定红色调
}
mark {
background: #ffeb3b
color: #000
padding: 0.1em 0.3em
border-radius: 3px
}
del {
color: #f8f8f2
text-decoration: line-through
}
ins {
color: #50fa7b
text-decoration: none
}
sub, sup {
color: #bd93f9
}
strong, b {
color: #ffc66d // 为 strong/b 标签设置特殊的橙黄色调
}
}
// 新增:文章特殊标签样式,解决大部分文字都是白色的问题
.post-content .special-tag {
background: linear-gradient(45deg, #7fa6ff, #00ffff)
color: #000
padding: 0.2em 0.5em
border-radius: 4px
font-weight: bold
display: inline-block
margin: 0 0.2em
}
.post-content .tag {
background: linear-gradient(135deg, #7367f0, #4839eb)
color: #fff
padding: 0.2em 0.6em
border-radius: 20px
font-size: 0.85rem
display: inline-block
margin: 0 0.2em
font-weight: 500
box-shadow: 0 2px 5px rgba(115, 103, 240, 0.4)
border: none
}
.post-pagination {
margin-top: 3rem
padding-top: 2rem
border-top: 1px solid rgba(255, 255, 255, 0.1)
display: flex
justify-content: space-between
gap: 1rem
.post-prev, .post-next {
flex: 1
.nav-label {
display: block
font-size: 0.9rem
color: #7fa6ff
margin-bottom: 0.5rem
}
a {
color: #ffffff
text-decoration: none
font-size: 1.1rem
display: block
padding: 1rem
background: rgba(255, 255, 255, 0.05)
border-radius: 8px
transition: all 0.3s ease
&:hover {
background: rgba(255, 255, 255, 0.1)
transform: translateY(-2px)
}
}
}
.post-next {
text-align: right
}
}
a {
color: #00ffff;
text-decoration: none;
span {
color: #00ffff;
margin-left: 5px;
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/post.styl | Stylus | agpl-3.0 | 6,455 |
// 搜索输入框样式
#search-input
width 100%
padding 15px 50px 15px 20px
background rgba(0, 0, 0, 0.5)
border 2px solid rgba(0, 255, 255, 0.3)
border-radius 8px
color #00ffff
font-size 1.2rem
transition all 0.3s ease
&:focus
outline none
border-color rgba(0, 255, 255, 0.7)
box-shadow 0 0 15px rgba(0, 255, 255, 0.3)
&::placeholder
color rgba(0, 255, 255, 0.5)
// 搜索结果容器
#search-results
display none
position relative // 从fixed改为relative
width 100%
max-width 100%
max-height calc(100vh - 220px)
overflow-y auto
background rgba(0, 0, 0, 0.3)
backdrop-filter blur(10px)
border 1px solid rgba(0, 255, 255, 0.1)
border-radius 8px
box-shadow 0 0 20px rgba(0, 0, 0, 0.5)
z-index 1002
padding 15px
margin-top 20px // 增加顶部边距,与搜索框保持距离
&::-webkit-scrollbar
width 6px
height 6px
&::-webkit-scrollbar-thumb
background rgba(0, 255, 255, 0.3)
border-radius 3px
&::-webkit-scrollbar-track
background rgba(0, 0, 0, 0.2)
// 各种搜索相关组件样式
.search-results-inner
padding 20px
.search-grid
display grid
grid-template-columns repeat(auto-fill, minmax(300px, 1fr))
gap 20px
padding 20px
.search-card
background rgba(255, 255, 255, 0.1)
border-radius 10px
padding 20px
transition all 0.3s ease
border 1px solid rgba(255, 255, 255, 0.1)
&:hover
transform translateY(-5px)
background rgba(255, 255, 255, 0.15)
box-shadow 0 5px 15px rgba(0, 0, 0, 0.3)
.card-title
font-size 1.2em
margin-bottom 10px
a
color #00ffff
text-decoration none
&:hover
text-decoration underline
.card-excerpt
color rgba(255, 255, 255, 0.7)
font-size 0.9em
margin 10px 0
line-height 1.6
.card-tags
margin-top 15px
display flex
flex-wrap wrap
gap 8px
.tag
background rgba(0, 255, 255, 0.1)
color #00ffff
padding 4px 10px
border-radius 15px
font-size 0.8em
text-decoration none
transition all 0.3s ease
&:hover
background rgba(0, 255, 255, 0.2)
// 搜索结果列表 - 修改网格布局,避免错误嵌套
.search-results-list
display flex
flex-wrap wrap
gap 15px
padding 5px 0
@media (max-width: 768px)
flex-direction column
gap 10px
// 搜索结果项 - 调整为固定宽度,避免不合适的大小
.search-result-item
background rgba(255, 255, 255, 0.05)
border 1px solid rgba(0, 255, 255, 0.1)
border-radius 8px
padding 15px
margin-bottom 15px
transition all 0.3s ease
animation fadeInUp 0.5s ease forwards
opacity 0
width 100%
max-width 100%
box-sizing border-box
// 使用正确的 Stylus for 循环语法
for i in (1..20)
&:nth-child({i})
animation-delay (i * 0.05)s
&:hover
transform translateY(-5px)
background rgba(255, 255, 255, 0.1)
border-color rgba(0, 255, 255, 0.3)
box-shadow 0 10px 20px rgba(0, 0, 0, 0.2)
// 搜索结果的标题、元数据、摘要和标签样式
.result-title
font-size 1.2rem
margin-bottom 10px
white-space nowrap
overflow hidden
text-overflow ellipsis
a
color #00ffff
text-decoration none
&:hover
text-decoration underline
.result-meta
font-size 0.9rem
color rgba(255, 255, 255, 0.6)
margin-bottom 10px
.result-date
display flex
align-items center
img
margin-right 5px
width 16px
height 16px
.result-excerpt
font-size 0.95rem
line-height 1.6
color rgba(255, 255, 255, 0.7)
margin 10px 0
overflow hidden
display -webkit-box
-webkit-line-clamp 3
-webkit-box-orient vertical
max-height 72px // 限制最大高度,约为3行文字高度
mark
background-color rgba(0, 255, 255, 0.2)
color #fff
padding 0 3px
border-radius 2px
img
max-width 100%
height auto
max-height 200px
object-fit cover
margin 10px 0
border-radius 6px
display block
.result-tags
display flex
flex-wrap wrap
gap 8px
margin-top 10px
.tag
background rgba(0, 255, 255, 0.1)
color #00ffff
padding 3px 8px
font-size 0.8rem
border-radius 20px
text-decoration none
transition all 0.3s ease
&:hover
background rgba(0, 255, 255, 0.2)
// 加载动画
.search-loading
display flex
flex-direction column
align-items center
justify-content center
padding 30px
.loading-spinner
display inline-block
width 40px
height 40px
border 4px solid rgba(0, 255, 255, 0.3)
border-radius 50%
border-top-color #00ffff
animation spin 1s linear infinite
margin-bottom 10px
.loading-text
color rgba(0, 255, 255, 0.7)
font-size 1rem
// 加载中动画
.lds-ring
display inline-block
position relative
width 64px
height 64px
margin-bottom 15px
div
box-sizing border-box
display block
position absolute
width 51px
height 51px
margin 6px
border 6px solid #00ffff
border-radius 50%
animation lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite
border-color #00ffff transparent transparent transparent
div:nth-child(1)
animation-delay -0.45s
div:nth-child(2)
animation-delay -0.3s
div:nth-child(3)
animation-delay -0.15s
// 没有结果
.no-result, .no-results
color rgba(0, 255, 255, 0.7)
text-align center
padding 20px
font-style italic
font-size 1.1rem
// 搜索容器
.search-container
position relative
z-index 1001
max-width 900px
margin 80px auto 0
padding 0 20px
@media (max-width: 768px)
margin-top 60px
// 搜索遮罩
.search-overlay
display none
position fixed
top 0
left 0
right 0
bottom 0
background rgba(0, 0, 0, 0.8)
z-index 1001
// 搜索模态框,增强磨砂玻璃效果
.search-modal
display none // 初始为hidden而不是flex
position fixed
top 0
left 0
width 100%
height 100%
z-index 2000
// 增强磨砂玻璃效果
background-color rgba(0, 0, 0, 0.75)
backdrop-filter blur(15px)
-webkit-backdrop-filter blur(15px)
overflow-y auto
opacity 0
transition opacity 0.3s ease
&.active
display block
animation fadeIn 0.3s ease
opacity 1
// 搜索模态框内容
.search-modal-content
max-width 800px
width 90%
margin 80px auto 0
padding 20px
// 可选:为内容区域也添加微妙的磨砂玻璃效果
background rgba(0, 0, 0, 0.6)
border-radius 12px
box-shadow 0 5px 30px rgba(0, 0, 0, 0.4)
border 1px solid rgba(0, 255, 255, 0.15)
display flex // 添加flex布局
flex-direction column // 垂直排列子元素
@media (max-width: 768px)
margin-top 60px
padding 15px
width 92%
// 搜索头部
.search-header
position relative
margin-bottom 20px
width 100%
// 搜索表单
.search-form
display flex
align-items center
position relative
margin-bottom 20px
width 100%
// 搜索关闭按钮
.search-close, .search-close-btn
position absolute
right 15px
top 50%
transform translateY(-50%)
background transparent
border none
cursor pointer
color #00ffff
padding 5px
display flex
align-items center
justify-content center
transition all 0.2s ease
&:hover
color #fff
transform translateY(-50%) scale(1.1)
svg
width 20px
height 20px
transition transform 0.3s ease
&:hover
transform rotate(90deg)
// 搜索切换
.search-toggle
cursor pointer
display flex
align-items center
transition color 0.2s ease
&:hover
color #00ffff
img
margin-right 5px
// 搜索按钮
.search-toggle-btn
background none
border none
color #e1e1ff
font-size 1.25rem
font-weight 500
font-family 'Arial', sans-serif
display flex
align-items center
cursor pointer
padding 0.5rem 1rem
transition color 0.3s ease
&:hover
color #fff
img
width 32px
height 32px
vertical-align middle
margin-right 5px
// 结果内容过渡
.search-results-content
transition all 0.3s ease
// 错误消息
.error-message
text-align center
padding 15px
color #ff6b6b
font-size 0.95rem
background rgba(255, 30, 30, 0.1)
border-left 3px solid #ff5555
padding 15px
margin 10px 0
border-radius 4px
small
display block
margin-top 8px
opacity 0.8
// 键盘快捷键提示
.search-shortcuts, .search-shortcut-tips
display flex
justify-content center
padding 20px 0
color rgba(255, 255, 255, 0.5)
font-size 0.9rem
text-align center
margin-top 20px
.shortcut
display flex
align-items center
margin 0 10px
.key
display inline-block
background rgba(255, 255, 255, 0.1)
border-radius 3px
padding 2px 6px
margin 0 5px
font-family monospace
// 搜索结果区域
.search-results
overflow-y auto
max-height calc(100vh - 250px) // 减少最大高度,避免溢出视窗
width 100%
box-sizing border-box
padding 5px
&::-webkit-scrollbar
width 6px
&::-webkit-scrollbar-track
background rgba(0, 0, 0, 0.3)
&::-webkit-scrollbar-thumb
background rgba(0, 255, 255, 0.3)
border-radius 3px
// 搜索统计信息样式
.search-stats
text-align center
color rgba(0, 255, 255, 0.7)
font-size 0.9rem
margin-top 15px
padding 5px 0
border-top 1px dashed rgba(0, 255, 255, 0.2)
// 激活搜索时的body状态
body.search-active
overflow hidden
// 动画关键帧
@keyframes fadeIn
from
opacity 0
to
opacity 1
@keyframes fadeInUp
from
opacity 0
transform translateY(20px)
to
opacity 1
transform translateY(0)
@keyframes lds-ring
0%
transform rotate(0deg)
100%
transform rotate(360deg)
@keyframes spin
to
transform rotate(360deg)
// 增强高亮样式
mark
background rgba(0, 255, 255, 0.25)
color #ffffff
padding 0 2px
border-radius 2px
box-shadow 0 0 2px rgba(0, 255, 255, 0.4)
// 响应式调整
@media (max-width: 768px)
.search-results-list
flex-direction column
#search-input
padding 12px 15px
font-size 1rem
.search-close svg
width 20px
height 20px
.search-result-item
width 100%
margin-bottom 10px
padding 12px
// 增加额外的媒体查询以优化不同屏幕大小下的显示
@media (min-width: 769px) and (max-width: 1200px)
.search-result-item
width 100%
| 2303_806435pww/hexo-theme-wang_moved | source/css/search.styl | Stylus | agpl-3.0 | 10,349 |
.sidebar-container {
position: fixed;
top: 10%;
z-index: 100;
min-width: 300px; // 修正属性名 weight -> width
// 实现平滑过渡效果
transition: all 0.4s ease;
}
@media (max-width: 1624px) {
.sidebar-container {
display: none;
}
}
.sidebar-left {
left: 5%;
right: 80%;
text-align: center;
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
.sidebar-bg {
background: rgba(15, 15, 25, 0.2) // 轻微增加不透明度
backdrop-filter: blur(15px)
-webkit-backdrop-filter: blur(15px)
border: 1px solid rgba(255, 255, 255, 0.12)
border-radius: 16px // 墛大圆角
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3) // 增强阴影效果
text-align: center
margin-bottom: 1.8rem
padding: 1.2rem 1rem // 增加内边距
transition: transform 0.3s ease, box-shadow 0.3s ease
&:hover {
transform: translateY(-5px)
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35)
}
}
.avatar {
margin: 0 auto 1rem
transition: transform 0.3s ease
&:hover {
transform: scale(1.05)
}
}
.icon {
width: 32px
opacity: 0.8
transition: opacity 0.3s ease, transform 0.3s ease
&:hover {
opacity: 1
transform: translateY(-3px)
}
}
}
.sidebar-right {
right: 5%;
left: 80%;
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
ol {
list-style-type: none;
padding: 0;
margin-left: 16px;
}
.sidebar-bg {
background: rgba(15, 15, 25, 0.2)
backdrop-filter: blur(15px)
-webkit-backdrop-filter: blur(15px)
border: 1px solid rgba(255, 255, 255, 0.12)
border-radius: 16px
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3)
margin-bottom: 1.8rem
padding: 1.2rem 1rem
transition: transform 0.3s ease, box-shadow 0.3s ease
&:hover {
transform: translateY(-5px)
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35)
}
a {
color: #00ffff
text-decoration: none
transition: color 0.3s ease, text-shadow 0.3s ease
&:hover {
color: #7fffff
text-shadow: 0 0 8px rgba(0, 255, 255, 0.5)
}
span {
color: #00ffff
margin-left: 5px
transition: color 0.3s ease
}
}
}
.avatar {
margin-right: auto;
margin-left: auto;
}
#clock {
text-align: center;
margin:auto;
font-size: 2em;
color: #646464;
font-family: 'Arial', sans-serif;
z-index : 1000;
}
#date {
text-align: center;
margin:auto;
font-size: 2.5em;
color: #777777;
font-family: 'Arial', sans-serif;
z-index : 1000;
margin-bottom: 32px;
}
.icon {
width: 32px;
}
// 优化目录样式
.toc {
padding-left: 0.5rem
overflow: auto
max-height: 75vh // Limit height to 75% of viewport height
.toc-item {
margin: 0.6rem 0
transition: transform 0.2s ease
&:hover {
transform: translateX(3px)
}
}
.toc-link {
color: rgba(255, 255, 255, 0.7)
text-decoration: none
display: inline-block
padding: 0.2rem 0
transition: color 0.3s ease
&:hover {
color: rgba(0, 255, 255, 0.9)
}
}
.toc-number {
margin-right: 0.5rem
color: rgba(0, 255, 255, 0.6)
}
.toc-child {
padding-left: 1rem
list-style-type: none
border-left: 1px solid rgba(0, 255, 255, 0.15)
margin: 0.5rem 0 0.5rem 0.5rem
}
}
.card-tags {
margin-top: 10px
display: flex
flex-wrap: wrap
justify-content: center
.tag {
display: inline-block
padding: 0.3rem 0.8rem
margin: 0.3rem
background: rgba(0, 255, 255, 0.1)
border: 1px solid rgba(0, 255, 255, 0.2)
border-radius: 20px
font-size: 0.85em
color: #00ffff
text-decoration: none
transition: all 0.3s ease
&:hover {
background: rgba(0, 255, 255, 0.2)
transform: translateY(-3px)
box-shadow: 0 3px 10px rgba(0, 255, 255, 0.2)
}
}
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/sidebar.styl | Stylus | agpl-3.0 | 4,779 |
// 标签云样式
.tags-cloud {
display: flex
flex-wrap: wrap
justify-content: center
gap: 15px
padding: 20px
.tag-item {
background: rgba(255, 255, 255, 0.1)
padding: 8px 15px
border-radius: 20px
color: #00ffff
transition: all 0.3s ease
border: 1px solid rgba(255, 255, 255, 0.2)
&:hover {
background: rgba(255, 255, 255, 0.2)
transform: translateY(-2px)
box-shadow: 0 4px 12px rgba(0,0,0,0.12)
}
small {
opacity: 0.8
margin-left: 5px
}
}
}
.tags-page{
h1{
text-align: center;
margin-top:4em;
}
} | 2303_806435pww/hexo-theme-wang_moved | source/css/tags.styl | Stylus | agpl-3.0 | 609 |
.site-time {
position: absolute;
bottom: 15%;
width: 100%;
height: 10%;
text-align: center;
z-index: 100;
#clock {
display: inline-block;
font-size: 3.5em; // 稍微放大字体
font-family: 'JetBrains Mono', 'Consolas', monospace;
font-weight: 300;
color: rgba(0, 255, 255, 0.85); // 稍微提高亮度
text-shadow: 0 0 15px rgba(0, 255, 255, 0.5); // 增强光晕效果
background: rgba(15, 15, 25, 0.5); // 增加背景透明度
backdrop-filter: blur(10px); // 增强模糊效果
-webkit-backdrop-filter: blur(10px);
padding: 0.3em 1em; // 增加水平内边距
border-radius: 20px; // 更大的圆角
border: 1px solid rgba(0, 255, 255, 0.25); // 增强边框显示
box-shadow:
0 10px 30px rgba(0, 0, 0, 0.3),
0 0 15px rgba(0, 255, 255, 0.2); // 双重阴影效果
letter-spacing: 0.05em;
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); // 使用更平滑的动画曲线
&:hover {
color: rgba(0, 255, 255, 1);
text-shadow: 0 0 20px rgba(0, 255, 255, 0.8);
box-shadow:
0 15px 40px rgba(0, 0, 0, 0.4),
0 0 30px rgba(0, 255, 255, 0.3);
transform: translateY(-5px) scale(1.03);
}
}
}
// 为侧边栏添加时钟样式 - 增强版
.sidebar-bg {
#clock {
display: block;
text-align: center;
font-family: 'JetBrains Mono', 'Consolas', monospace;
font-weight: 300;
color: rgba(0, 255, 255, 0.85);
text-shadow: 0 0 12px rgba(0, 255, 255, 0.5);
background: rgba(15, 15, 25, 0.5);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-radius: 15px;
border: 1px solid rgba(0, 255, 255, 0.25);
box-shadow:
0 8px 25px rgba(0, 0, 0, 0.3),
0 0 10px rgba(0, 255, 255, 0.15);
letter-spacing: 0.05em;
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
// 自适应大小设置
font-size: calc(1.2vw + 1.1rem);
padding: 0.4em 0.8em;
max-width: 95%;
margin: 1em auto; // Centered horizontally with some top margin
&:hover {
color: rgba(0, 255, 255, 1);
text-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
box-shadow:
0 12px 30px rgba(0, 0, 0, 0.35),
0 0 20px rgba(0, 255, 255, 0.2);
transform: translateY(-3px) scale(1.02); // Simplified hover effect
}
}
}
// 响应式设计
@media (max-width: 768px) {
.site-time {
#clock {
font-size: 2.5em;
padding: 0.2em 0.6em;
}
}
.sidebar-bg {
#clock {
font-size: calc(2vw + 0.8rem); // 中等屏幕上的字体大小
padding: 0.2em 0.5em;
}
}
}
@media (max-width: 480px) {
.site-time {
#clock {
font-size: 2em;
padding: 0.2em 0.5em;
}
}
.sidebar-bg {
#clock {
font-size: calc(3vw + 0.7rem); // 小屏幕上的字体大小
padding: 0.2em 0.4em;
max-width: 95%;
}
}
}
| 2303_806435pww/hexo-theme-wang_moved | source/css/time.styl | Stylus | agpl-3.0 | 2,913 |
body{
margin: 0;
padding: 0;
height: 100%;
overflow-x: hidden;
background: radial-gradient(ellipse at bottom, #1c2331 0%, #090a0f 100%);
color: #ffffff; // 添加默认文字颜色
font-family: 'DouyinSans', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
.avatar-round {
border-radius: 25px;
width: 50px;
height: 50px;
overflow: hidden;
display: block;
}
// 添加文字相关的样式
h1, h2, h3, h4, h5, h6 {
color: #e1e1ff; // 标题使用略微偏紫的白色
}
a {
color: #00ffff; // 链接使用青色
list-style none;
&:hover {
color: #66ffff; // 悬停时颜色变亮
}
}
p {
color: #cccccc; // 段落文字使用浅灰色
}
p, h1, h2, h3, h4, h5, h6, span, div {
font-family: inherit;
}
.typed-cursor, .cursor {
font-size: 1.5rem;
color: #00ffff;
animation: blink 0.7s infinite;
}
@keyframes blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
.description-io {
position: relative;
z-index: 1000; // 设置最高的z-index
background-color: rgba(0, 0, 0, 0.7); // 添加半透明背景
padding: 1rem; // 添加内边距
border-radius: 8px; // 添加圆角
text-align: center; // 居中文本
color: #ffffff; // 设置文本颜色
}
// 滚动条样式
::-webkit-scrollbar {
width: 10px; // 稍微加宽滚动条
height: 10px;
}
::-webkit-scrollbar-track {
background: #2c2c2c; // 深灰色轨道
}
::-webkit-scrollbar-thumb {
background: #666; // 中灰色滑块
border-radius: 10px;
border: 2px solid #2c2c2c; // 添加边框营造立体感
&:hover {
background: #888; // 悬停时变亮
}
}
@import fonts
@import background
@import first_screen
@import header
@import footer
@import archives
@import paginator
@import page
@import tags
@import categories
@import links
@import search
@import post
@import time
@import date
@import sidebar
@import code
@import copy
@import ccbyncsa
@import alert
| 2303_806435pww/hexo-theme-wang_moved | source/css/wang.styl | Stylus | agpl-3.0 | 2,018 |
// 创建星空画布
const container = document.createElement('div');
container.id = 'starry-background';
document.body.appendChild(container);
// 创建Canvas元素
const canvas = document.createElement('canvas');
canvas.id = 'stars-canvas';
container.appendChild(canvas);
// 获取绘图上下文
const ctx = canvas.getContext('2d', { alpha: true });
let width = 0;
let height = 0;
let animationId = null;
// 星星和流星对象池
const stars = [];
const meteors = [];
const TOTAL_STARS = 300; // 保持星星数量稳定
const MAX_METEORS = 3; // 同时存在的最大流星数量
// 星星类 - 强化纯闪烁效果
class Star {
constructor() {
this.reset();
}
reset() {
// 随机位置
this.x = Math.random() * width;
this.y = Math.random() * height;
// 随机大小 - 减小星星尺寸
this.size = Math.random() * 1.8 + 0.4; // 改为更小的尺寸范围
// 基础亮度 - 更大亮度范围
this.baseAlpha = Math.random() * 0.7 + 0.2;
this.alpha = this.baseAlpha;
// 闪烁效果参数 - 大幅增强闪烁效果
this.twinkleMode = Math.floor(Math.random() * 3); // 0: 慢闪, 1: 中闪, 2: 快闪
// 根据模式设置速度
switch(this.twinkleMode) {
case 0: // 慢闪
this.twinkleSpeed = Math.random() * 0.007 + 0.003;
this.twinkleDepth = Math.random() * 0.3 + 0.2; // 深度闪烁
break;
case 1: // 中闪
this.twinkleSpeed = Math.random() * 0.02 + 0.01;
this.twinkleDepth = Math.random() * 0.25 + 0.15; // 中等闪烁
break;
case 2: // 快闪
this.twinkleSpeed = Math.random() * 0.04 + 0.02;
this.twinkleDepth = Math.random() * 0.2 + 0.1; // 轻微闪烁
break;
}
this.twinkleFactor = Math.random() * Math.PI * 2; // 随机起始相位
// 生命周期 (15-25秒)
this.lifespan = Math.random() * 10000 + 15000;
this.birth = Date.now();
// 是否处于消失状态
this.dying = false;
// 随机星星颜色
this.colorType = Math.random() > 0.8 ? Math.floor(Math.random() * 3) : -1;
// 添加额外的闪烁效果 - 偶尔的亮闪
this.flashInterval = Math.random() * 5000 + 3000; // 每3-8秒闪烁一次
this.lastFlash = Date.now() - Math.random() * this.flashInterval;
this.flashing = false;
this.flashDuration = 300; // 闪烁持续300毫秒
}
update(timestamp) {
const now = timestamp || Date.now();
const age = now - this.birth;
// 生命周期管理
if (age > this.lifespan && !this.dying) {
this.dying = true;
}
// 处理消失和出现的动画
if (this.dying) {
this.alpha -= 0.02; // 更快消失
if (this.alpha <= 0) {
this.reset();
this.dying = false;
}
return;
} else if (age < 1000) {
// 出生后1秒内渐变出现
this.alpha = Math.min(this.baseAlpha, age / 1000 * this.baseAlpha);
}
// 检查是否应该触发亮闪效果
if (!this.flashing && now - this.lastFlash > this.flashInterval) {
this.flashing = true;
this.flashStart = now;
this.lastFlash = now;
}
// 处理亮闪状态
if (this.flashing) {
const flashAge = now - this.flashStart;
if (flashAge < this.flashDuration) {
// 亮闪效果 - 快速变亮再变暗
const flashProgress = flashAge / this.flashDuration;
const flashBrightness = Math.sin(flashProgress * Math.PI) * 0.7;
this.alpha = Math.min(1, this.baseAlpha + flashBrightness);
} else {
this.flashing = false;
}
} else {
// 正常闪烁 - 使用不同模式的闪烁效果
this.twinkleFactor += this.twinkleSpeed;
const twinkle = Math.sin(this.twinkleFactor) * this.twinkleDepth;
this.alpha = Math.max(0.05, Math.min(0.95, this.baseAlpha + twinkle));
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
// 根据星星类型设置不同的颜色
let color;
switch(this.colorType) {
case 0: // 淡蓝色星星
color = `rgba(200, 220, 255, ${this.alpha})`;
break;
case 1: // 淡黄色星星
color = `rgba(255, 250, 220, ${this.alpha})`;
break;
case 2: // 淡红色星星
color = `rgba(255, 220, 220, ${this.alpha})`;
break;
default: // 普通白色星星
color = `rgba(255, 255, 255, ${this.alpha})`;
}
ctx.fillStyle = color;
ctx.fill();
// 为较大的星星添加更明显的光晕效果 - 调整光晕尺寸
if (this.size > 1.2) { // 降低光晕阈值以匹配更小的星星
// 内光晕 - 减小光晕大小
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 1.8, 0, Math.PI * 2);
ctx.fillStyle = color.replace(`, ${this.alpha})`, `, ${this.alpha * 0.18})`);
ctx.fill();
// 外光晕 - 仅适用于较大星星和闪烁状态
if (this.size > 1.5 || this.flashing) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 3, 0, Math.PI * 2);
ctx.fillStyle = color.replace(`, ${this.alpha})`, `, ${this.alpha * 0.08})`);
ctx.fill();
}
}
}
}
// 流星类
class Meteor {
constructor() {
this.reset();
}
reset() {
// 起始位置 - 从屏幕上方随机位置开始
this.x = Math.random() * width;
this.y = -20; // 稍微在屏幕外开始
// 速度和方向
const angle = Math.PI / 4 + (Math.random() * Math.PI / 4); // 60-90度角
const speed = 5 + Math.random() * 10; // 速度随机
this.vx = Math.cos(angle) * speed;
this.vy = Math.sin(angle) * speed;
// 尺寸和亮度
this.size = Math.random() * 2 + 1;
this.alpha = 0.7 + Math.random() * 0.3;
// 尾巴长度
this.tailLength = 80 + Math.random() * 60;
// 是否激活
this.active = true;
// 历史位置 - 用于绘制尾巴
this.positions = [];
// 消失状态
this.exiting = false;
this.exitStartIndex = 0; // 从哪个索引开始消失
this.exitSpeed = 2; // 每帧消失的段数
}
update() {
// 移动流星
this.x += this.vx;
this.y += this.vy;
// 如果流星还在活动状态,记录当前位置
if (!this.exiting) {
this.positions.unshift({ x: this.x, y: this.y, alpha: this.alpha });
// 只保留尾巴最近的部分
if (this.positions.length > this.tailLength) {
this.positions.pop();
}
// 检查流星是否离开屏幕 - 只有头部离开才开始消失
if (this.x > width || this.x < 0 || this.y > height || this.y < -50) {
this.exiting = true;
this.exitStartIndex = 0; // 从尾巴尖开始消失
}
} else {
// 流星已经开始消失过程
// 不再添加新的位置,只是让尾巴逐渐缩短
if (this.positions.length > 0) {
// 从尾巴尖开始逐渐删除段
this.exitStartIndex += this.exitSpeed;
// 删除应该消失的部分
while (this.positions.length > 0 &&
this.positions.length - this.exitStartIndex <= 0) {
this.positions.pop(); // 从尾部删除
}
} else {
// 尾巴完全消失了,标记为不活跃
this.active = false;
}
}
}
draw() {
// 如果已经开始退出且没有尾巴,不绘制
if (this.exiting && this.positions.length === 0) {
return;
}
// 如果还没开始退出,绘制流星头部
if (!this.exiting) {
// 绘制流星头部
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 1.5, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha})`;
ctx.fill();
// 绘制流星外部光晕
ctx.beginPath();
ctx.arc(this.x, this.y, this.size * 3, 0, Math.PI * 2);
ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha * 0.3})`;
ctx.fill();
}
// 绘制流星尾巴
for (let i = 1; i < this.positions.length; i++) {
const prev = this.positions[i-1];
const current = this.positions[i];
// 如果在退出状态,计算相对消失位置
let segmentAlpha;
if (this.exiting) {
// 计算这段是否需要消失
const relativeIndex = this.positions.length - i;
// 如果这段在消失范围内,减少它的透明度
if (relativeIndex <= this.exitStartIndex) {
// 已经完全消失的段
continue;
} else if (relativeIndex <= this.exitStartIndex + 10) {
// 正在消失的段 - 根据距离渐变
const fadeProgress = (relativeIndex - this.exitStartIndex) / 10;
segmentAlpha = fadeProgress * (1 - i / this.positions.length) * this.alpha * 0.8;
} else {
// 正常显示的段
segmentAlpha = (1 - i / this.positions.length) * this.alpha * 0.8;
}
} else {
// 正常状态下的透明度计算
segmentAlpha = (1 - i / this.positions.length) * this.alpha * 0.8;
}
// 绘制尾巴段
ctx.beginPath();
ctx.moveTo(prev.x, prev.y);
ctx.lineTo(current.x, current.y);
ctx.strokeStyle = `rgba(255, 255, 255, ${segmentAlpha})`;
ctx.lineWidth = this.size * (1 - i / this.positions.length) * 1.2;
ctx.stroke();
}
}
}
// 初始化画布大小
function resizeCanvas() {
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
// 调整现有星星位置
if (stars.length > 0) {
for (let star of stars) {
if (star.x > width || star.y > height) {
star.x = Math.random() * width;
star.y = Math.random() * height;
}
}
}
}
// 创建星星
function initStars() {
for (let i = 0; i < TOTAL_STARS; i++) {
const star = new Star();
// 初始化时分布在各个生命周期
star.birth = Date.now() - Math.random() * star.lifespan;
stars.push(star);
}
}
// 可能创建新流星 - 增加出现频率
function createMeteorIfNeeded() {
// 检查流星数量
const activeMeteors = meteors.filter(meteor => meteor.active).length;
// 随机决定是否创建新流星 (增加概率到0.5%)
if (activeMeteors < MAX_METEORS && Math.random() < 0.005) {
meteors.push(new Meteor());
}
// 移除不活跃的流星
for (let i = meteors.length - 1; i >= 0; i--) {
if (!meteors[i].active) {
meteors.splice(i, 1);
}
}
}
// 动画循环
function animate(timestamp) {
// 清空画布
ctx.clearRect(0, 0, width, height);
// 更新并绘制星星
for (let star of stars) {
star.update(timestamp);
star.draw();
}
// 可能创建新流星
createMeteorIfNeeded();
// 更新并绘制流星
for (let meteor of meteors) {
meteor.update();
meteor.draw();
}
animationId = requestAnimationFrame(animate);
}
// 性能优化:使用节流函数限制窗口大小调整的频率
function throttle(callback, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
callback(...args);
}
};
}
// 初始化
window.addEventListener('resize', throttle(resizeCanvas, 200));
// 页面可见性变化时优化性能
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
cancelAnimationFrame(animationId);
} else {
animationId = requestAnimationFrame(animate);
}
});
// 启动
resizeCanvas();
initStars();
animationId = requestAnimationFrame(animate); | 2303_806435pww/hexo-theme-wang_moved | source/js/background.js | JavaScript | agpl-3.0 | 13,231 |
// 添加代码复制功能
document.addEventListener('DOMContentLoaded', () => {
// 获取所有带有highlight类名的代码块
const codeBlocks = document.querySelectorAll('.highlight');
codeBlocks.forEach(block => {
// 创建复制按钮
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy';
copyButton.className = 'copy-btn';
// 创建按钮容器
const buttonWrapper = document.createElement('div');
buttonWrapper.className = 'copy-btn-wrapper';
buttonWrapper.appendChild(copyButton);
// 从代码块类名中提取语言
const classes = block.className.split(' ');
let lang = '';
for (const cls of classes) {
if (cls.startsWith('language-')) {
lang = cls.replace('language-', '');
break;
}
}
// 设置语言标签
if (lang) {
block.setAttribute('data-lang', lang);
}
// 将按钮容器添加到代码块
block.appendChild(buttonWrapper);
// 为按钮添加点击事件
copyButton.addEventListener('click', () => {
// 获取代码块中的代码内容,不包括行号
const codeLines = block.querySelectorAll('.code .line');
let codeText = '';
codeLines.forEach(line => {
codeText += line.textContent + '\n';
});
// 将文本复制到剪贴板
navigator.clipboard.writeText(codeText.trim()).then(() => {
// 替换为优雅的提示
const originalText = copyButton.textContent;
copyButton.innerHTML = '✓ Copied';
copyButton.style.background = 'rgba(80, 200, 120, 0.5)';
copyButton.style.borderColor = 'rgba(80, 200, 120, 0.7)';
setTimeout(() => {
copyButton.textContent = originalText;
copyButton.style.background = '';
copyButton.style.borderColor = '';
}, 2000);
}).catch(err => {
console.error('Failed to copy: ', err);
});
});
});
});
| 2303_806435pww/hexo-theme-wang_moved | source/js/copy.js | JavaScript | agpl-3.0 | 1,972 |
document.addEventListener('DOMContentLoaded', function() {
const header = document.querySelector('header');
// 添加汉堡菜单
function setupMobileMenu() {
if (!header) return;
// 检查是否已经存在汉堡菜单
if (header.querySelector('.hamburger')) return;
// 创建汉堡菜单按钮
const hamburger = document.createElement('div');
hamburger.className = 'hamburger';
hamburger.setAttribute('aria-label', '菜单'); // 添加无障碍标签
hamburger.innerHTML = `
<span></span>
<span></span>
<span></span>
`;
// 添加到header
header.appendChild(hamburger);
// 获取菜单列表
const menuList = header.querySelector('ul');
// 汉堡菜单点击事件
hamburger.addEventListener('click', function() {
this.classList.toggle('active');
menuList.classList.toggle('active');
// 切换无障碍属性
const expanded = this.classList.contains('active');
this.setAttribute('aria-expanded', expanded);
});
// 点击链接后关闭菜单
const menuLinks = menuList.querySelectorAll('a, button');
menuLinks.forEach(link => {
link.addEventListener('click', function() {
hamburger.classList.remove('active');
menuList.classList.remove('active');
hamburger.setAttribute('aria-expanded', 'false');
});
});
}
// 高亮当前页面
function highlightCurrentPage() {
const currentPath = window.location.pathname;
const menuLinks = document.querySelectorAll('header a');
menuLinks.forEach(link => {
const href = link.getAttribute('href');
// 处理首页特殊情况
if (href === '/' && (currentPath === '/' || currentPath === '/index.html')) {
link.classList.add('active');
}
// 处理其他页面
else if (href !== '/' && currentPath.startsWith(href)) {
link.classList.add('active');
}
});
}
// 滚动隐藏/显示导航
function setupScrollBehavior() {
let lastScrollTop = 0;
window.addEventListener('scroll', function() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
// 向下滚动超过100px时隐藏导航
if (scrollTop > lastScrollTop && scrollTop > 100) {
header.classList.add('scroll-down');
}
// 向上滚动时显示导航
else if (scrollTop < lastScrollTop) {
header.classList.remove('scroll-down');
}
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
});
}
// 初始化
setupMobileMenu();
highlightCurrentPage();
setupScrollBehavior();
// 确保汉堡菜单在窗口调整大小时正常显示
window.addEventListener('resize', function() {
setupMobileMenu(); // 每次调整大小都检查汉堡菜单
});
});
| 2303_806435pww/hexo-theme-wang_moved | source/js/header.js | JavaScript | agpl-3.0 | 3,172 |
document.addEventListener('DOMContentLoaded', function() {
console.log('搜索模块初始化开始');
// 检查DOM元素是否存在
const searchToggleBtn = document.querySelector('.search-toggle-btn');
const searchModal = document.getElementById('search-modal');
const searchInput = document.getElementById('search-input');
const searchCloseBtn = document.querySelector('.search-close-btn');
const searchResults = document.getElementById('search-results');
console.log('DOM元素检查:', {
searchToggleBtn: !!searchToggleBtn,
searchModal: !!searchModal,
searchInput: !!searchInput,
searchCloseBtn: !!searchCloseBtn,
searchResults: !!searchResults
});
if (!searchModal || !searchInput || !searchResults) {
console.error('搜索所需DOM元素不存在,请检查HTML结构');
return; // 如果关键元素不存在就退出
}
// 配置参数
const CONFIG = {
path: '/search.xml',
top_n_per_article: 3,
unescape: false,
};
// 获取翻译文本
const i18n = (window.WANG_THEME && window.WANG_THEME.i18n && window.WANG_THEME.i18n.search) || {
noResults: 'No results found',
loading: 'Loading...',
placeholder: 'Search articles...',
close: 'Close',
shortcut_tip: 'Press ESC to close',
error_loading: 'Failed to load search data'
};
console.log('搜索国际化配置:', i18n);
// 定义 debounce 函数
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// 初次加载搜索数据
let searchData = null;
let isSearchDataLoading = false;
// 打开搜索模态窗口
function openSearchModal() {
console.log('打开搜索模态框');
if (searchModal) {
// 设置显示样式
searchModal.style.display = 'block';
setTimeout(() => {
searchModal.classList.add('active');
}, 10);
document.body.style.overflow = 'hidden'; // 防止背景滚动
if (searchInput) {
setTimeout(() => {
searchInput.focus();
// 立即加载搜索数据
loadSearchData().then(data => {
const keyword = searchInput.value.trim();
if (keyword) performSearch(keyword);
});
}, 300);
}
}
}
// 关闭搜索模态窗口
function closeSearchModal() {
console.log('关闭搜索模态框');
if (searchModal) {
searchModal.classList.remove('active');
setTimeout(() => {
searchModal.style.display = 'none';
}, 300);
document.body.style.overflow = ''; // 恢复背景滚动
// 清空搜索内容和结果
if (searchInput) {
searchInput.value = '';
}
if (searchResults) {
searchResults.innerHTML = '';
}
}
}
// 绑定事件
if (searchToggleBtn) {
searchToggleBtn.addEventListener('click', function(e) {
console.log('搜索按钮点击');
e.preventDefault();
openSearchModal();
});
}
if (searchCloseBtn) {
searchCloseBtn.addEventListener('click', function(e) {
e.preventDefault();
closeSearchModal();
});
}
// ESC键关闭搜索
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && searchModal && searchModal.classList.contains('active')) {
closeSearchModal();
}
});
// 点击模态窗口背景关闭
if (searchModal) {
searchModal.addEventListener('click', function(e) {
if (e.target === searchModal) {
closeSearchModal();
}
});
}
// 加载搜索数据 - 使用最简单的方式,避免复杂解析可能导致的问题
async function loadSearchData() {
if (searchData) {
console.log('使用缓存的搜索数据');
return searchData;
}
if (isSearchDataLoading) {
console.log('搜索数据正在加载中...');
return new Promise(resolve => {
const checkInterval = setInterval(() => {
if (searchData) {
clearInterval(checkInterval);
resolve(searchData);
}
}, 100);
});
}
isSearchDataLoading = true;
try {
// 显示加载中
searchResults.innerHTML = `
<div class="search-loading">
<div class="loading-spinner"></div>
<div class="loading-text">${i18n.loading}</div>
</div>
`;
console.log('开始加载搜索数据:', CONFIG.path);
const response = await fetch(CONFIG.path);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// 获取XML文本
const xmlText = await response.text();
console.log('搜索数据加载成功,数据长度:', xmlText.length);
// 解析XML
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
// 检查解析错误
const parseError = xmlDoc.getElementsByTagName('parsererror');
if (parseError.length > 0) {
throw new Error('XML解析错误: ' + parseError[0].textContent);
}
// 提取搜索数据
const entries = xmlDoc.getElementsByTagName('entry');
console.log('找到文章条目:', entries.length);
const data = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
try {
const title = entry.getElementsByTagName('title')[0]?.textContent || '';
const content = entry.getElementsByTagName('content')[0]?.textContent || '';
const url = entry.getElementsByTagName('url')[0]?.textContent || '';
// 提取标签
const tags = [];
const tagElements = entry.getElementsByTagName('tag');
for (let j = 0; j < tagElements.length; j++) {
tags.push(tagElements[j].textContent);
}
data.push({
title,
content,
url,
tags
});
} catch (err) {
console.error('处理文章条目错误:', err);
}
}
console.log('搜索数据处理完成, 共', data.length, '条记录');
searchData = data;
// 清空加载提示
searchResults.innerHTML = '';
isSearchDataLoading = false;
return data;
} catch (error) {
console.error('搜索数据加载失败:', error);
searchResults.innerHTML = `
<div class="error-message">
${i18n.error_loading}<br>
<small>${error.message}</small><br>
<small>提示:请确认已安装 hexo-generator-searchdb 插件,并在站点配置文件中正确配置</small>
</div>`;
isSearchDataLoading = false;
return null;
}
}
// 简化的搜索匹配功能
function simpleSearch(keyword, data) {
console.log('执行搜索:', keyword);
if (!data || !data.length) return [];
const keywords = keyword.trim().toLowerCase().split(/\s+/);
return data.filter(item => {
return keywords.some(word => {
if (word.length === 0) return false;
return (
item.title.toLowerCase().includes(word) ||
item.content.toLowerCase().includes(word) ||
item.tags.some(tag => tag.toLowerCase().includes(word))
);
});
});
}
// 高亮显示搜索结果中的关键字
function highlightKeyword(text, keyword) {
if (!text || !keyword) return text;
const keywords = keyword.trim().toLowerCase().split(/\s+/);
let result = text;
keywords.forEach(word => {
if (word.length > 0) {
const regex = new RegExp(word, 'gi');
result = result.replace(regex, match => `<mark>${match}</mark>`);
}
});
return result;
}
// 显示搜索结果
function displayResults(results, keyword) {
console.log('显示搜索结果:', results.length, '条');
// 确保搜索结果区域可见
searchResults.style.display = 'block';
if (results.length === 0) {
searchResults.innerHTML = `
<div class="no-results">${i18n.noResults}</div>
<div class="search-shortcut-tips">
<span class="key">ESC</span> ${i18n.shortcut_tip}
</div>
`;
return;
}
// 创建结果列表HTML
let resultsHTML = '<div class="search-results-list">';
results.forEach(post => {
// 提取关键词上下文
let excerpt = '';
const position = post.content.toLowerCase().indexOf(keyword.toLowerCase());
if (position !== -1) {
const start = Math.max(position - 100, 0);
const end = Math.min(position + 100, post.content.length);
excerpt = (start > 0 ? '...' : '') + post.content.substring(start, end) + (end < post.content.length ? '...' : '');
} else {
excerpt = post.content.length > 200 ? post.content.substring(0, 200) + '...' : post.content;
}
// 高亮处理
const highlightedTitle = highlightKeyword(post.title, keyword);
const highlightedExcerpt = highlightKeyword(excerpt, keyword);
// 构建标签HTML
let tagsHTML = '';
if (post.tags && post.tags.length > 0) {
post.tags.forEach(tag => {
tagsHTML += `<a href="/tags/${encodeURIComponent(tag)}" class="tag">${highlightKeyword(tag, keyword)}</a>`;
});
}
// 添加结果项
resultsHTML += `
<article class="search-result-item">
<h2 class="result-title">
<a href="${post.url}">${highlightedTitle}</a>
</h2>
<div class="result-meta">
<span class="result-date">
<img src="/images/calendar.svg" alt="calendar">
${new Date().toLocaleDateString()}
</span>
</div>
<div class="result-excerpt">${highlightedExcerpt}</div>
<div class="result-tags">${tagsHTML}</div>
</article>
`;
});
resultsHTML += '</div>';
// 添加统计和提示信息
resultsHTML += `
<div class="search-stats">找到 ${results.length} 条结果</div>
<div class="search-shortcut-tips">
<span class="key">ESC</span> ${i18n.shortcut_tip}
</div>
`;
searchResults.innerHTML = resultsHTML;
}
// 执行搜索
function performSearch(keyword) {
if (!keyword) {
searchResults.innerHTML = '';
searchResults.style.display = 'none';
return;
}
if (!searchData) {
loadSearchData().then(data => {
if (data) {
const results = simpleSearch(keyword, data);
displayResults(results, keyword);
}
});
return;
}
const results = simpleSearch(keyword, searchData);
displayResults(results, keyword);
}
// 绑定搜索输入框事件 - 减少延迟
if (searchInput) {
searchInput.addEventListener('input', debounce(function() {
const keyword = this.value.trim();
performSearch(keyword);
}, 100));
// 添加提交表单事件处理
const form = searchInput.closest('form');
if (form) {
form.addEventListener('submit', function(e) {
e.preventDefault();
const keyword = searchInput.value.trim();
performSearch(keyword);
});
}
}
// "/"键快捷打开搜索
document.addEventListener('keydown', function(e) {
if (e.key === "/" &&
document.activeElement.tagName !== "INPUT" &&
document.activeElement.tagName !== "TEXTAREA") {
e.preventDefault();
openSearchModal();
}
});
// 如果URL中有搜索参数,自动打开搜索
try {
const urlParams = new URLSearchParams(window.location.search);
const searchQuery = urlParams.get('q');
if (searchQuery) {
setTimeout(() => {
openSearchModal();
if (searchInput) {
searchInput.value = searchQuery;
performSearch(searchQuery);
}
}, 500);
}
} catch (e) {
console.error('处理URL搜索参数错误:', e);
}
console.log('搜索模块初始化完成');
});
| 2303_806435pww/hexo-theme-wang_moved | source/js/search.js | JavaScript | agpl-3.0 | 14,579 |
document.addEventListener('DOMContentLoaded', function() {
const typedOutput = document.getElementById('typed-output');
// 支持多行文本,使用"|"分隔不同行
const textArray = typedOutput ? typedOutput.getAttribute('data-text').split('|') : [];
if (!textArray.length) return;
let lineIndex = 0;
let charIndex = 0;
let isDeleting = false;
// 改进速度设置,更接近自然打字节奏
const baseTypeSpeed = 80; // 降低基础打字速度,更自然
const baseDeleteSpeed = 30; // 加快删除速度
const pauseBeforeDelete = 2000; // 延长读取时间
const pauseBeforeType = 300; // 缩短准备时间
const pauseAfterPunctuation = 150; // 标点符号后额外暂停
// 需要额外暂停的标点符号
const punctuations = [',', '.', '!', '?', ';', ':', ',', '。', '!', '?', ';', ':'];
function getRandomSpeed(baseSpeed) {
// 更自然的随机速度变化,不同字符有不同的输入速度
return Math.floor(baseSpeed * (0.7 + Math.random() * 0.6));
}
function type() {
// 获取当前应该显示的文本行
const currentText = textArray[lineIndex];
// 根据当前状态截取要显示的文本
const displayText = currentText.substring(0, charIndex);
typedOutput.innerHTML = displayText + '<span class="cursor">|</span>';
// 计算下一步的速度
let speed;
if (!isDeleting && charIndex < currentText.length) {
// 正在打字
const nextChar = currentText[charIndex];
charIndex++;
// 如果是标点符号,适当延长暂停时间
if (punctuations.includes(nextChar)) {
speed = getRandomSpeed(baseTypeSpeed) + pauseAfterPunctuation;
} else {
speed = getRandomSpeed(baseTypeSpeed);
}
} else if (isDeleting && charIndex > 0) {
// 正在删除
charIndex--;
speed = getRandomSpeed(baseDeleteSpeed);
} else if (!isDeleting && charIndex === currentText.length) {
// 完成一行打字,准备删除
isDeleting = true;
speed = pauseBeforeDelete;
} else if (isDeleting && charIndex === 0) {
// 完成删除,准备下一行
isDeleting = false;
lineIndex = (lineIndex + 1) % textArray.length;
speed = pauseBeforeType;
}
setTimeout(type, speed);
}
// 添加初始延迟,让页面加载完全后再开始打字
setTimeout(type, 800);
});
| 2303_806435pww/hexo-theme-wang_moved | source/js/typed-effect.js | JavaScript | agpl-3.0 | 2,425 |
document.addEventListener('keydown', function(event) {
// 检查按下的是否是F12键
if (event.key === 'F12') {
// 显示提示框并添加动画
var alertDiv = document.getElementById('agplAlert');
alertDiv.style.display = 'block';
alertDiv.classList.add('showAlert');
setTimeout(function() {
alertDiv.style.display = 'none';
alertDiv.classList.remove('showAlert');
}, 15000); // 15S
}
});
| 2303_806435pww/hexo-theme-wang_moved | source/js/wang.js | JavaScript | agpl-3.0 | 479 |
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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Surface(modifier = Modifier.statusBarsPadding()) {
MainPage()
}
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/androidMain/kotlin/com/tencent/compose/MainActivity.kt | Kotlin | apache-2.0 | 1,352 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | composeApp/src/androidMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.android.kt | Kotlin | apache-2.0 | 917 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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.Compose1500Text
import com.tencent.compose.sample.LinearGradientLine
import com.tencent.compose.sample.MultiTouches
import com.tencent.compose.sample.PreviewAppTabScreen
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.ComposeLazy1500Image
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.composeView1500Page
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 = "Benchmark",
items = listOf(
DisplayItem("1500view", Res.drawable.text_field) { composeView1500Page() },
DisplayItem("1500text", Res.drawable.text_field) { Compose1500Text() },
DisplayItem("1500image", Res.drawable.text_field) { ComposeLazy1500Image() },
DisplayItem("Bouncing Balls", Res.drawable.text_field) { BouncingBallsApp() },
DisplayItem("帖子列表", Res.drawable.text_field) { PreviewAppTabScreen() },
)
),
)
}
internal expect fun platformSections() : List<DisplayItem>
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.kt | Kotlin | apache-2.0 | 5,368 |
/*
* 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.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) "Compose - Skia" else "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 = {
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/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/MainPage.kt | Kotlin | apache-2.0 | 7,452 |
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.ComposeLazyView1500Page
//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
) {
composeView1500Page()
}
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/NewMainPage.kt | Kotlin | apache-2.0 | 1,472 |
// 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.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.material.Button
import androidx.compose.material.Divider
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
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 = {}
) {
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
)
Box(modifier = Modifier.fillMaxSize()) {
when (currentIndex) {
0 -> FeedListPage(pageType = "follow")
else -> TrendingPage()
}
}
}
}
@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) {
Box(
modifier = Modifier
.size(22.dp)
.clip(CircleShape)
.background(Color(0xFFAAC7FF))
)
}
}
}
@Composable
internal fun FeedListPage(pageType: String) {
var isRefreshing by remember { mutableStateOf(false) }
var isLoadingMore by remember { mutableStateOf(false) }
val listState = rememberLazyListState()
val items = remember { mutableStateListOf<FeedItemModel>() }
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(pageType) {
items.clear()
items.addAll(generateSampleFeeds(start = 0, count = 100))
}
LaunchedEffect(listState) {
snapshotFlow {
val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
last
}.map { it ?: -1 }
.distinctUntilChanged()
.filter { idx -> idx >= 0 }
.collectLatest { lastIndex ->
val total = items.size
if (lastIndex >= total - 3 && !isLoadingMore) {
isLoadingMore = true
delay(700)
val newItems = generateSampleFeeds(start = items.size, count = 20)
if (newItems.isNotEmpty()) {
items.addAll(newItems)
}
isLoadingMore = false
}
}
}
Column(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Button(onClick = {
if (!isRefreshing) {
isRefreshing = true
coroutineScope.launch {
delay(800)
items.clear()
items.addAll(generateSampleFeeds(start = 0, count = 100))
isRefreshing = false
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))
}
}
}
}
@Composable
internal fun TrendingPage() {
val types = listOf(
"推荐", "附近", "榜单", "明星", "搞笑", "社会", "测试"
)
var selected by remember { mutableStateOf(0) }
Column(modifier = Modifier.fillMaxSize()) {
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
)
}
}
Box(modifier = Modifier.fillMaxSize()) {
when (selected) {
0 -> FeedListPage(pageType = "recommend")
1 -> FeedListPage(pageType = "nearby")
else -> FeedListPage(pageType = "other_$selected")
}
}
}
}
private data class FeedItemModel(
val id: String,
val nick: String,
val content: String
)
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))
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
)
}
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/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/AppHomePageView.kt | Kotlin | apache-2.0 | 12,844 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Checkbox.kt | Kotlin | apache-2.0 | 4,608 |
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 Compose1500Text() {
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(1500) { index ->
Text(
text = "Compose1500Text Item #$index",
fontSize = 16.sp,
modifier = Modifier
.width(300.dp)
.height(50.dp)
.border(1.dp, Color.Gray)
.padding(10.dp)
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Compose1500Text.kt | Kotlin | apache-2.0 | 1,076 |
/*
* 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.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
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.image_cat
import org.jetbrains.compose.resources.ExperimentalResourceApi
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun ComposeLazy1500Image() {
val gap = 12.dp
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.background(Color.White),
verticalArrangement = Arrangement.spacedBy(gap),
contentPadding = PaddingValues(vertical = gap)
) {
items(1500) {
FollowUserItem()
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
internal fun FollowUserItem() {
val bmp = rememberLocalImage(Res.drawable.image_cat)
val ratio = bmp.width.toFloat() / bmp.height.toFloat()
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.weight(1f)
.aspectRatio(ratio)
) {
Image(
bitmap = bmp,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Fit,
)
}
}
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/ComposeLazy1500Image.kt | Kotlin | apache-2.0 | 3,087 |
/*
* 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.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/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/CustomizeImageSnippets.kt | Kotlin | apache-2.0 | 14,122 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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.image_cat
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.image_cat),
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/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/Image.kt | Kotlin | apache-2.0 | 4,619 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.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.colors.background) {
Box(contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(text = title, fontSize = 24.sp, color = MaterialTheme.colors.onBackground)
Spacer(modifier = Modifier.height(6.dp))
Text(text = "Placeholder content", color = MaterialTheme.colors.onBackground.copy(alpha = 0.7f))
}
}
}
}
@Composable
internal fun AppTabScreen(
titles: List<String> = listOf("Home", "Video", "Discover", "Message", "Me"),
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)) }
val bgColor = MaterialTheme.colors.background
val tabBackground = MaterialTheme.colors.surface
val textFocused = MaterialTheme.colors.primary
val textUnfocused = MaterialTheme.colors.onSurface
Column(modifier = Modifier.fillMaxSize().background(bgColor)) {
Spacer(modifier = Modifier.height(0.dp))
Box(modifier = Modifier
.weight(1f)
.fillMaxSize()
) {
when (selectedIndex) {
0 -> AppHomePreview()
else -> AppEmptyScreen(title = titles.getOrNull(selectedIndex) ?: "Page ${selectedIndex + 1}")
}
}
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)
) {
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) {
val bg = if (isSelected) MaterialTheme.colors.primary else MaterialTheme.colors.onSurface.copy(alpha = 0.08f)
val fg = if (isSelected) Color.White else MaterialTheme.colors.onSurface
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
)
}
}
@Composable
internal fun AppHomeScreen() {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text("App Home", fontSize = 28.sp, color = MaterialTheme.colors.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.colors.onBackground
)
}
}
}
@Composable
internal fun PreviewAppTabScreen() {
AppTabScreen()
}
| 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/PreviewAppTabScreen.kt | Kotlin | apache-2.0 | 6,146 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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.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) }
Column(
modifier = Modifier
.verticalScroll(rememberScrollState())
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(1500) { index ->
Box(
modifier = Modifier
.size(300.dp, 100.dp)
.border(
width = 2.dp,
color = Color.Red,
)
.then(
if (index == 1499) Modifier.onGloballyPositioned {
loaded.value = true
//trace_tag_end()
} else Modifier
)
) {
Text(
text = "Item #$index",
)
}
}
}
if (loaded.value) {
println("页面加载完成 ✅")
}
} | 2201_76010299/Compose_huawei_benchmark | composeApp/src/commonMain/kotlin/com/tencent/compose/sample/mainpage/sectionItem/compose1500view.kt | Kotlin | apache-2.0 | 1,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.
*/
@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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | composeApp/src/iosMain/kotlin/com/tencent/compose/sample/mainpage/DisplaySections.ios.kt | Kotlin | apache-2.0 | 1,281 |
#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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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 <js_native_api.h>
#include <js_native_api_types.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
void crash_in_c();
int KotlinCallNative(int num, napi_env env, napi_callback_info info);
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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/cinterop/include/test_0725.h | C | apache-2.0 | 1,066 |
/*
* 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/Compose_huawei_benchmark | 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
import platform.ohos.napi_env
import platform.ohos.napi_callback_info
import kotlinx.cinterop.*
import test725.*
@OptIn(ExperimentalForeignApi::class)
@CName("kotlin_function2")
fun kotlinFunction2(input: Int, env: napi_env, info: napi_callback_info): Int {
println("KN: before KotlincallNative: $env , $info")
KotlinCallNative(10, env, info)
return input * 2
}
@OptIn(ExperimentalForeignApi::class)
@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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/ExportFunctions.kt | Kotlin | apache-2.0 | 968 |
/*
* 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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/MainArkUIViewController.kt | Kotlin | apache-2.0 | 1,643 |
/*
* 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/Compose_huawei_benchmark | 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 test725.native_register
import 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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ArkCallback.kt | Kotlin | apache-2.0 | 5,214 |
/*
* 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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 test725.native_register_simple_callback
import test725.native_trigger_simple_callback
import test725.native_cleanup_simple_callback
import 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调用)")
}
}
val memoryHolders = mutableListOf<ByteArray>()
fun allocateMemory(sizeInMB: Int): ByteArray {
val sizeInBytes = sizeInMB * 1024 * 1024
val byteArray = ByteArray(sizeInBytes)
byteArray.fill(1)
return byteArray
}
@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("重置所有")
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Button(onClick = {
memoryHolders.add(allocateMemory(256))
}) {
Text("分配256MB内存")
}
}
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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/CircleReference.kt | Kotlin | apache-2.0 | 13,340 |
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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | 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/Compose_huawei_benchmark | composeApp/src/ohosArm64Main/kotlin/com/tencent/compose/sample/ComposeLazyView1500.kt | Kotlin | apache-2.0 | 1,320 |