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
|
|---|---|---|---|---|---|
<template>
<view class="monitor-page">
<!-- 顶部状态卡片 -->
<view class="status-header">
<view class="status-card" :class="serverStatus">
<view class="status-icon">
<text>{{ serverStatus === 'online' ? '✓' : '!' }}</text>
</view>
<view class="status-info">
<text class="status-title">服务器状态</text>
<text class="status-value">{{ serverStatus === 'online' ? '运行正常' : '异常' }}</text>
</view>
<view class="refresh-btn" @click="refreshStatus">
<text>刷新</text>
</view>
</view>
</view>
<!-- 标签页 -->
<view class="tabs">
<view class="tab" :class="{ active: currentTab === 'logs' }" @click="currentTab = 'logs'">
<text>运行日志</text>
</view>
<view class="tab" :class="{ active: currentTab === 'errors' }" @click="currentTab = 'errors'">
<text>异常记录</text>
<view class="badge" v-if="errorCount > 0">{{ errorCount }}</view>
</view>
<view class="tab" :class="{ active: currentTab === 'security' }" @click="switchToSecurity">
<text>安全防护</text>
<view class="badge warning" v-if="securityStats.recent_events > 0">{{ securityStats.recent_events }}</view>
</view>
<view class="tab" :class="{ active: currentTab === 'stats' }" @click="currentTab = 'stats'">
<text>系统状态</text>
</view>
</view>
<!-- 日志列表 -->
<scroll-view class="log-list" scroll-y v-if="currentTab === 'logs'">
<view class="log-item" v-for="(log, index) in logs" :key="index" :class="log.level">
<view class="log-header">
<text class="log-level">{{ log.level.toUpperCase() }}</text>
<text class="log-time">{{ log.time }}</text>
</view>
<text class="log-message">{{ log.message }}</text>
</view>
<view class="empty" v-if="logs.length === 0">
<text>暂无日志</text>
</view>
<view class="load-more" @click="loadMoreLogs" v-if="hasMoreLogs">
<text>加载更多</text>
</view>
</scroll-view>
<!-- 异常列表 -->
<scroll-view class="log-list" scroll-y v-if="currentTab === 'errors'">
<view class="error-item" v-for="(err, index) in errors" :key="index">
<view class="error-header">
<text class="error-type">{{ err.type }}</text>
<text class="error-time">{{ err.time }}</text>
</view>
<text class="error-message">{{ err.message }}</text>
<view class="error-stack" v-if="err.stack" @click="toggleStack(index)">
<text class="stack-toggle">{{ expandedStacks.includes(index) ? '收起' : '展开' }}堆栈</text>
<text class="stack-content" v-if="expandedStacks.includes(index)">{{ err.stack }}</text>
</view>
</view>
<view class="empty" v-if="errors.length === 0">
<text>🎉 暂无异常,系统运行正常</text>
</view>
</scroll-view>
<!-- 系统状态 -->
<view class="stats-panel" v-if="currentTab === 'stats'">
<view class="stat-row">
<text class="stat-label">CPU 使用率</text>
<view class="stat-bar">
<view class="bar-fill" :style="{ width: systemStats.cpu + '%' }"></view>
</view>
<text class="stat-value">{{ systemStats.cpu }}%</text>
</view>
<view class="stat-row">
<text class="stat-label">内存使用</text>
<view class="stat-bar">
<view class="bar-fill" :style="{ width: systemStats.memory + '%' }"></view>
</view>
<text class="stat-value">{{ systemStats.memory }}%</text>
</view>
<view class="stat-row">
<text class="stat-label">磁盘使用</text>
<view class="stat-bar">
<view class="bar-fill" :style="{ width: systemStats.disk + '%' }"></view>
</view>
<text class="stat-value">{{ systemStats.disk }}%</text>
</view>
<view class="stat-row">
<text class="stat-label">运行时间</text>
<text class="stat-value">{{ systemStats.uptime }}</text>
</view>
<view class="stat-row">
<text class="stat-label">数据库连接</text>
<text class="stat-value status-ok">正常</text>
</view>
<view class="stat-row">
<text class="stat-label">Redis 连接</text>
<text class="stat-value status-ok">正常</text>
</view>
</view>
<!-- 安全防护 -->
<view class="security-panel" v-if="currentTab === 'security'">
<!-- 安全统计卡片 -->
<view class="security-stats">
<view class="security-stat-card">
<text class="stat-number">{{ securityStats.blacklist_count }}</text>
<text class="stat-desc">黑名单 IP</text>
</view>
<view class="security-stat-card warning" v-if="securityStats.locked_ips > 0">
<text class="stat-number">{{ securityStats.locked_ips }}</text>
<text class="stat-desc">已锁定</text>
</view>
<view class="security-stat-card" :class="{ warning: securityStats.rate_limit_hits > 0 }">
<text class="stat-number">{{ securityStats.rate_limit_hits }}</text>
<text class="stat-desc">频率限制</text>
</view>
<view class="security-stat-card" :class="{ danger: securityStats.login_failures > 0 }">
<text class="stat-number">{{ securityStats.login_failures }}</text>
<text class="stat-desc">登录失败</text>
</view>
</view>
<!-- IP 黑名单管理 -->
<view class="section-card">
<view class="section-header">
<text class="section-title">IP 黑名单</text>
<view class="add-btn" @click="showAddBlacklist">
<text>+ 添加</text>
</view>
</view>
<view class="blacklist-list" v-if="blacklist.length > 0">
<view class="blacklist-item" v-for="ip in blacklist" :key="ip">
<text class="ip-text">{{ ip }}</text>
<text class="remove-btn" @click="removeBlacklist(ip)">移除</text>
</view>
</view>
<view class="empty-small" v-else>
<text>暂无黑名单 IP</text>
</view>
</view>
<!-- 安全事件列表 -->
<view class="section-card">
<view class="section-header">
<text class="section-title">安全事件</text>
<text class="section-hint">最近1小时</text>
</view>
<scroll-view class="security-events" scroll-y>
<view class="event-item" v-for="(event, index) in securityEvents" :key="index" :class="getEventLevel(event.type)">
<view class="event-header">
<text class="event-type">{{ getEventTypeName(event.type) }}</text>
<text class="event-time">{{ formatEventTime(event.time) }}</text>
</view>
<view class="event-body">
<text class="event-ip">{{ event.ip }}</text>
<text class="event-message">{{ event.message }}</text>
</view>
</view>
<view class="empty-small" v-if="securityEvents.length === 0">
<text>🛡️ 暂无安全事件,一切正常</text>
</view>
</scroll-view>
</view>
</view>
<!-- 操作按钮 -->
<view class="action-bar">
<view class="action-btn" @click="clearLogs">
<text>清空日志</text>
</view>
<view class="action-btn primary" @click="exportLogs">
<text>导出日志</text>
</view>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { get, post, del } from '@/api/request'
const currentTab = ref('logs')
const serverStatus = ref('online')
const errorCount = ref(0)
const logs = ref([])
const errors = ref([])
const expandedStacks = ref([])
const hasMoreLogs = ref(true)
const logPage = ref(1)
const systemStats = ref({
cpu: 0,
memory: 0,
disk: 0,
uptime: '-'
})
// 安全相关数据
const securityStats = ref({
blacklist_count: 0,
locked_ips: 0,
recent_events: 0,
rate_limit_hits: 0,
login_failures: 0
})
const securityEvents = ref([])
const blacklist = ref([])
onMounted(() => {
checkServerStatus()
loadLogs()
loadErrors()
loadSystemStats()
loadSecurityStats()
})
const checkServerStatus = async () => {
try {
const res = await uni.request({ url: 'http://localhost:8080/health', method: 'GET' })
serverStatus.value = (res.data && res.data.status === 'ok') ? 'online' : 'offline'
} catch (e) {
serverStatus.value = 'offline'
}
}
const refreshStatus = async () => {
try {
const res = await uni.request({ url: 'http://localhost:8080/health', method: 'GET' })
if (res.data && res.data.status === 'ok') {
serverStatus.value = 'online'
uni.showToast({ title: '服务正常', icon: 'success' })
} else {
serverStatus.value = 'offline'
uni.showToast({ title: '服务异常', icon: 'none' })
}
} catch (e) {
serverStatus.value = 'offline'
uni.showToast({ title: '服务异常', icon: 'none' })
}
}
const loadLogs = async () => {
try {
const res = await get('/api/monitor/logs', { page: logPage.value, limit: 50 })
if (res.code === 0) {
if (logPage.value === 1) {
logs.value = res.data.logs || []
} else {
logs.value = [...logs.value, ...(res.data.logs || [])]
}
hasMoreLogs.value = (res.data.logs || []).length === 50
}
} catch (e) {
// 使用模拟数据
logs.value = [
{ level: 'info', time: formatNow(), message: '服务启动成功' },
{ level: 'info', time: formatNow(), message: '数据库连接成功' },
{ level: 'info', time: formatNow(), message: 'Redis 连接成功' }
]
}
}
const loadMoreLogs = () => {
logPage.value++
loadLogs()
}
const loadErrors = async () => {
try {
const res = await get('/api/monitor/errors', { limit: 20 })
if (res.code === 0) {
errors.value = res.data.errors || []
errorCount.value = errors.value.length
}
} catch (e) {
errors.value = []
errorCount.value = 0
}
}
const loadSystemStats = async () => {
try {
const res = await get('/api/monitor/stats')
if (res.code === 0) {
systemStats.value = res.data
}
} catch (e) {
// 使用默认值
systemStats.value = {
cpu: 15,
memory: 45,
disk: 32,
uptime: '运行中'
}
}
}
const toggleStack = (index) => {
const idx = expandedStacks.value.indexOf(index)
if (idx === -1) {
expandedStacks.value.push(index)
} else {
expandedStacks.value.splice(idx, 1)
}
}
const clearLogs = () => {
uni.showModal({
title: '确认清空',
content: '确定清空所有日志吗?',
success: (res) => {
if (res.confirm) {
logs.value = []
uni.showToast({ title: '已清空' })
}
}
})
}
const exportLogs = () => {
const content = logs.value.map(l => `[${l.level}] ${l.time} ${l.message}`).join('\n')
// #ifdef H5
const blob = new Blob([content], { type: 'text/plain' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `logs_${Date.now()}.txt`
a.click()
// #endif
// #ifndef H5
uni.showToast({ title: '已复制到剪贴板', icon: 'none' })
uni.setClipboardData({ data: content })
// #endif
}
const formatNow = () => {
const d = new Date()
return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}
// ============ 安全相关方法 ============
const switchToSecurity = () => {
currentTab.value = 'security'
loadSecurityStats()
loadSecurityEvents()
loadBlacklist()
}
const loadSecurityStats = async () => {
try {
const res = await get('/api/monitor/security/stats')
if (res.code === 0) {
securityStats.value = res.data
}
} catch (e) {
console.log('加载安全统计失败', e)
}
}
const loadSecurityEvents = async () => {
try {
const res = await get('/api/monitor/security/events', { limit: 50 })
if (res.code === 0) {
securityEvents.value = res.data || []
}
} catch (e) {
securityEvents.value = []
}
}
const loadBlacklist = async () => {
try {
const res = await get('/api/monitor/security/blacklist')
if (res.code === 0) {
blacklist.value = res.data || []
}
} catch (e) {
blacklist.value = []
}
}
const showAddBlacklist = () => {
uni.showModal({
title: '添加黑名单 IP',
editable: true,
placeholderText: '请输入 IP 地址',
success: async (res) => {
if (res.confirm && res.content) {
const ip = res.content.trim()
if (!/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(ip)) {
uni.showToast({ title: 'IP 格式不正确', icon: 'none' })
return
}
try {
await post('/api/monitor/security/blacklist', { ip })
uni.showToast({ title: '已添加', icon: 'success' })
loadBlacklist()
loadSecurityStats()
} catch (e) {
uni.showToast({ title: '添加失败', icon: 'none' })
}
}
}
})
}
const removeBlacklist = async (ip) => {
uni.showModal({
title: '确认移除',
content: `确定从黑名单移除 ${ip} 吗?`,
success: async (res) => {
if (res.confirm) {
try {
await del(`/api/monitor/security/blacklist/${ip}`)
uni.showToast({ title: '已移除', icon: 'success' })
loadBlacklist()
loadSecurityStats()
} catch (e) {
uni.showToast({ title: '移除失败', icon: 'none' })
}
}
}
})
}
const getEventTypeName = (type) => {
const names = {
'login_success': '登录成功',
'login_failure': '登录失败',
'login_locked': '账号锁定',
'login_lockout': '登录锁定',
'rate_limit': '频率限制',
'blacklist_add': '加入黑名单',
'blacklist_block': '黑名单拦截'
}
return names[type] || type
}
const getEventLevel = (type) => {
if (['login_locked', 'blacklist_block'].includes(type)) return 'danger'
if (['login_failure', 'rate_limit', 'login_lockout'].includes(type)) return 'warning'
return 'info'
}
const formatEventTime = (isoTime) => {
if (!isoTime) return ''
const d = new Date(isoTime)
return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}
</script>
<style scoped>
.monitor-page {
min-height: 100vh;
background: #f5f5f5;
}
/* 状态头部 */
.status-header {
padding: 24rpx;
}
.status-card {
display: flex;
align-items: center;
padding: 32rpx;
background: #fff;
border-radius: 20rpx;
box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
}
.status-card.online .status-icon {
background: #07C160;
}
.status-card.offline .status-icon {
background: #ff4d4f;
}
.status-icon {
width: 64rpx;
height: 64rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 32rpx;
margin-right: 24rpx;
}
.status-info {
flex: 1;
}
.status-title {
font-size: 26rpx;
color: #999;
display: block;
}
.status-value {
font-size: 32rpx;
color: #333;
font-weight: 600;
}
.refresh-btn {
padding: 16rpx 28rpx;
background: #f5f5f5;
border-radius: 24rpx;
font-size: 26rpx;
color: #666;
}
/* 标签页 */
.tabs {
display: flex;
background: #fff;
border-bottom: 1rpx solid #eee;
}
.tab {
flex: 1;
padding: 28rpx;
text-align: center;
font-size: 28rpx;
color: #666;
position: relative;
}
.tab.active {
color: #07C160;
font-weight: 600;
}
.tab.active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 48rpx;
height: 6rpx;
background: #07C160;
border-radius: 3rpx;
}
.badge {
position: absolute;
top: 16rpx;
right: 40rpx;
min-width: 32rpx;
height: 32rpx;
background: #ff4d4f;
color: #fff;
font-size: 20rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
padding: 0 8rpx;
}
/* 日志列表 */
.log-list {
height: calc(100vh - 420rpx);
padding: 24rpx;
}
.log-item {
background: #fff;
border-radius: 12rpx;
padding: 20rpx;
margin-bottom: 16rpx;
border-left: 6rpx solid #07C160;
}
.log-item.warning {
border-left-color: #faad14;
}
.log-item.error {
border-left-color: #ff4d4f;
}
.log-header {
display: flex;
justify-content: space-between;
margin-bottom: 8rpx;
}
.log-level {
font-size: 22rpx;
color: #07C160;
font-weight: 600;
}
.log-item.warning .log-level { color: #faad14; }
.log-item.error .log-level { color: #ff4d4f; }
.log-time {
font-size: 22rpx;
color: #999;
}
.log-message {
font-size: 26rpx;
color: #333;
line-height: 1.5;
word-break: break-all;
}
/* 异常列表 */
.error-item {
background: #fff;
border-radius: 12rpx;
padding: 20rpx;
margin-bottom: 16rpx;
border-left: 6rpx solid #ff4d4f;
}
.error-header {
display: flex;
justify-content: space-between;
margin-bottom: 8rpx;
}
.error-type {
font-size: 24rpx;
color: #ff4d4f;
font-weight: 600;
}
.error-time {
font-size: 22rpx;
color: #999;
}
.error-message {
font-size: 26rpx;
color: #333;
line-height: 1.5;
display: block;
}
.error-stack {
margin-top: 16rpx;
padding-top: 16rpx;
border-top: 1rpx solid #f0f0f0;
}
.stack-toggle {
font-size: 24rpx;
color: #07C160;
}
.stack-content {
display: block;
margin-top: 12rpx;
font-size: 22rpx;
color: #666;
background: #f9f9f9;
padding: 16rpx;
border-radius: 8rpx;
white-space: pre-wrap;
word-break: break-all;
}
/* 系统状态 */
.stats-panel {
padding: 24rpx;
}
.stat-row {
display: flex;
align-items: center;
background: #fff;
padding: 28rpx;
border-radius: 12rpx;
margin-bottom: 16rpx;
}
.stat-label {
width: 180rpx;
font-size: 28rpx;
color: #333;
}
.stat-bar {
flex: 1;
height: 16rpx;
background: #f0f0f0;
border-radius: 8rpx;
margin: 0 24rpx;
overflow: hidden;
}
.bar-fill {
height: 100%;
background: linear-gradient(90deg, #07C160, #06AD56);
border-radius: 8rpx;
transition: width 0.3s;
}
.stat-value {
width: 100rpx;
text-align: right;
font-size: 28rpx;
color: #333;
font-weight: 600;
}
.status-ok {
color: #07C160;
}
/* 空状态 */
.empty {
text-align: center;
padding: 80rpx;
color: #999;
font-size: 28rpx;
}
.load-more {
text-align: center;
padding: 24rpx;
color: #07C160;
font-size: 26rpx;
}
/* 操作栏 */
.action-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
padding: 24rpx;
background: #fff;
border-top: 1rpx solid #eee;
gap: 24rpx;
}
.action-btn {
flex: 1;
padding: 24rpx;
text-align: center;
background: #f5f5f5;
border-radius: 12rpx;
font-size: 28rpx;
color: #666;
}
.action-btn.primary {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
}
/* 安全防护面板 */
.security-panel {
padding: 24rpx;
padding-bottom: 160rpx;
}
.security-stats {
display: flex;
gap: 16rpx;
margin-bottom: 24rpx;
}
.security-stat-card {
flex: 1;
background: #fff;
border-radius: 12rpx;
padding: 20rpx;
text-align: center;
}
.security-stat-card.warning {
background: #fffbe6;
border: 1rpx solid #ffe58f;
}
.security-stat-card.danger {
background: #fff2f0;
border: 1rpx solid #ffccc7;
}
.stat-number {
font-size: 40rpx;
font-weight: 600;
color: #333;
display: block;
}
.security-stat-card.warning .stat-number {
color: #faad14;
}
.security-stat-card.danger .stat-number {
color: #ff4d4f;
}
.stat-desc {
font-size: 22rpx;
color: #999;
}
.section-card {
background: #fff;
border-radius: 12rpx;
padding: 20rpx;
margin-bottom: 24rpx;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16rpx;
}
.section-title {
font-size: 28rpx;
font-weight: 600;
color: #333;
}
.section-hint {
font-size: 22rpx;
color: #999;
}
.add-btn {
padding: 8rpx 20rpx;
background: #07C160;
border-radius: 20rpx;
font-size: 24rpx;
color: #fff;
}
/* 黑名单列表 */
.blacklist-list {
max-height: 300rpx;
overflow-y: auto;
}
.blacklist-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16rpx 0;
border-bottom: 1rpx solid #f0f0f0;
}
.blacklist-item:last-child {
border-bottom: none;
}
.ip-text {
font-size: 28rpx;
color: #333;
font-family: monospace;
}
.remove-btn {
font-size: 24rpx;
color: #ff4d4f;
}
.empty-small {
text-align: center;
padding: 32rpx;
color: #999;
font-size: 26rpx;
}
/* 安全事件列表 */
.security-events {
max-height: 500rpx;
}
.event-item {
padding: 16rpx;
margin-bottom: 12rpx;
background: #f9f9f9;
border-radius: 8rpx;
border-left: 4rpx solid #07C160;
}
.event-item.warning {
border-left-color: #faad14;
background: #fffbe6;
}
.event-item.danger {
border-left-color: #ff4d4f;
background: #fff2f0;
}
.event-header {
display: flex;
justify-content: space-between;
margin-bottom: 8rpx;
}
.event-type {
font-size: 24rpx;
font-weight: 600;
color: #07C160;
}
.event-item.warning .event-type {
color: #faad14;
}
.event-item.danger .event-type {
color: #ff4d4f;
}
.event-time {
font-size: 22rpx;
color: #999;
}
.event-body {
display: flex;
gap: 16rpx;
}
.event-ip {
font-size: 24rpx;
color: #666;
font-family: monospace;
background: rgba(0,0,0,0.05);
padding: 4rpx 12rpx;
border-radius: 4rpx;
}
.event-message {
font-size: 24rpx;
color: #666;
flex: 1;
}
.badge.warning {
background: #faad14;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/server-monitor.vue
|
Vue
|
unknown
| 20,541
|
<template>
<view class="account-page">
<view class="page-header">
<text class="page-title">账号设置</text>
</view>
<!-- 头像设置 -->
<view class="section">
<view class="section-title">头像</view>
<view class="avatar-row" @click="chooseAvatar">
<view class="current-avatar">
<image v-if="userAvatar && typeof userAvatar === 'string'" :src="userAvatar" class="avatar-img" mode="aspectFill" />
<view v-else class="avatar-placeholder">
<text>{{ userName ? userName[0] : 'U' }}</text>
</view>
</view>
<text class="change-text">点击更换头像</text>
<text class="arrow">›</text>
</view>
</view>
<!-- 基本信息 -->
<view class="section">
<view class="section-title">基本信息</view>
<view class="card">
<view class="field">
<text class="label">用户名</text>
<input class="input" v-model="username" placeholder="登录账号" />
</view>
<view class="field">
<text class="label">昵称</text>
<input class="input" v-model="nickname" placeholder="显示名称" />
</view>
</view>
<text class="hint">* 修改用户名后需用新用户名登录</text>
<view class="btn primary" @click="saveProfile">保存修改</view>
</view>
<!-- 修改密码 -->
<view class="section">
<view class="section-title">修改密码</view>
<view class="card">
<view class="field">
<text class="label">原密码</text>
<input class="input" type="password" v-model="oldPassword" placeholder="请输入原密码" />
</view>
<view class="field">
<text class="label">新密码</text>
<input class="input" type="password" v-model="newPassword" placeholder="至少6位" />
</view>
<view class="field">
<text class="label">确认密码</text>
<input class="input" type="password" v-model="confirmPassword" placeholder="再次输入新密码" />
</view>
</view>
<view class="btn danger" @click="changePassword">修改密码</view>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { getUserInfo, updateProfile, changePassword as changePasswordApi } from '@/api/user'
import { uploadFile } from '@/api/upload'
const username = ref('')
const nickname = ref('')
const userAvatar = ref('')
const userName = ref('')
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
onMounted(() => {
loadUserInfo()
})
const loadUserInfo = async () => {
try {
const res = await getUserInfo()
if (res.code === 0) {
username.value = res.data.username || ''
nickname.value = res.data.nickname || res.data.name || ''
// 确保 avatar 是字符串
const avatar = res.data.avatar
userAvatar.value = (typeof avatar === 'string') ? avatar : ''
userName.value = res.data.name || ''
}
} catch (e) {
console.log('加载用户信息失败', e)
}
}
const chooseAvatar = () => {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempPath = res.tempFilePaths[0]
uni.showLoading({ title: '上传中...' })
try {
const uploadRes = await uploadFile(tempPath, 'avatar')
uni.hideLoading()
if (uploadRes.code === 0 && uploadRes.data?.url) {
userAvatar.value = uploadRes.data.url
// 保存到服务器
try {
await updateProfile({ avatar: uploadRes.data.url })
} catch (e) {
console.log('保存头像失败', e)
}
// 同时保存到本地
uni.setStorageSync('customUserAvatar', uploadRes.data.url)
uni.showToast({ title: '头像已更新', icon: 'success' })
} else {
uni.showToast({ title: '上传失败', icon: 'none' })
}
} catch (e) {
uni.hideLoading()
uni.showToast({ title: '上传失败', icon: 'none' })
}
}
})
}
const saveProfile = async () => {
if (!username.value.trim()) {
uni.showToast({ title: '请输入用户名', icon: 'none' })
return
}
if (!nickname.value.trim()) {
uni.showToast({ title: '请输入昵称', icon: 'none' })
return
}
try {
const res = await updateProfile({
username: username.value.trim(),
nickname: nickname.value.trim()
})
if (res.code === 0) {
uni.showToast({ title: '保存成功', icon: 'success' })
} else {
uni.showToast({ title: res.message || '保存失败', icon: 'none' })
}
} catch (e) {
uni.showToast({ title: e.message || '保存失败', icon: 'none' })
}
}
const changePassword = async () => {
if (!oldPassword.value) {
uni.showToast({ title: '请输入原密码', icon: 'none' })
return
}
if (!newPassword.value || newPassword.value.length < 6) {
uni.showToast({ title: '新密码至少6位', icon: 'none' })
return
}
if (newPassword.value !== confirmPassword.value) {
uni.showToast({ title: '两次密码不一致', icon: 'none' })
return
}
try {
const res = await changePasswordApi({
old_password: oldPassword.value,
new_password: newPassword.value
})
if (res.code === 0) {
uni.showToast({ title: '密码修改成功', icon: 'success' })
oldPassword.value = ''
newPassword.value = ''
confirmPassword.value = ''
} else {
uni.showToast({ title: res.message || '修改失败', icon: 'none' })
}
} catch (e) {
uni.showToast({ title: e.message || '修改失败', icon: 'none' })
}
}
</script>
<style scoped>
.account-page {
min-height: 100vh;
background: #f5f5f5;
padding: 24rpx;
}
.page-header {
padding: 24rpx 0 32rpx;
}
.page-title {
font-size: 36rpx;
font-weight: 600;
color: #333;
}
.section {
margin-bottom: 32rpx;
}
.section-title {
font-size: 26rpx;
color: #999;
margin-bottom: 16rpx;
padding-left: 8rpx;
}
.avatar-row {
display: flex;
align-items: center;
background: #fff;
padding: 24rpx;
border-radius: 16rpx;
}
.current-avatar {
width: 100rpx;
height: 100rpx;
border-radius: 50%;
overflow: hidden;
margin-right: 24rpx;
}
.avatar-img {
width: 100%;
height: 100%;
}
.avatar-placeholder {
width: 100%;
height: 100%;
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 40rpx;
font-weight: 600;
}
.change-text {
flex: 1;
font-size: 28rpx;
color: #666;
}
.arrow {
font-size: 32rpx;
color: #ccc;
}
.card {
background: #fff;
border-radius: 16rpx;
padding: 8rpx 24rpx;
margin-bottom: 24rpx;
}
.field {
display: flex;
align-items: center;
padding: 24rpx 0;
border-bottom: 1rpx solid #f0f0f0;
}
.field:last-child {
border-bottom: none;
}
.label {
width: 160rpx;
font-size: 28rpx;
color: #333;
}
.value {
flex: 1;
font-size: 28rpx;
color: #333;
text-align: right;
}
.value.readonly {
color: #999;
}
.input {
flex: 1;
font-size: 28rpx;
color: #333;
text-align: right;
}
.hint {
font-size: 24rpx;
color: #999;
margin: 16rpx 0;
display: block;
}
.btn {
padding: 24rpx;
text-align: center;
border-radius: 12rpx;
font-size: 28rpx;
font-weight: 500;
}
.btn.primary {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
}
.btn.danger {
background: #fff;
color: #ff4d4f;
border: 1rpx solid #ff4d4f;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/settings/account.vue
|
Vue
|
unknown
| 7,195
|
<template>
<view class="ai-page">
<!-- 标题 -->
<view class="page-header">
<text class="page-title">AI 配置</text>
<text class="page-desc">分别配置各个 AI 服务</text>
</view>
<!-- Tab 切换 -->
<view class="tabs">
<view
class="tab"
:class="{ active: activeTab === 'chat' }"
@click="activeTab = 'chat'"
>
<text class="tab-icon">💬</text>
<text class="tab-text">聊天</text>
</view>
<view
class="tab"
:class="{ active: activeTab === 'vision' }"
@click="activeTab = 'vision'"
>
<text class="tab-icon">👁️</text>
<text class="tab-text">图片</text>
</view>
<view
class="tab"
:class="{ active: activeTab === 'file' }"
@click="activeTab = 'file'"
>
<text class="tab-icon">📄</text>
<text class="tab-text">文件</text>
</view>
<view
class="tab"
:class="{ active: activeTab === 'embedding' }"
@click="activeTab = 'embedding'"
>
<text class="tab-icon">🔍</text>
<text class="tab-text">向量</text>
</view>
<view
class="tab"
:class="{ active: activeTab === 'search' }"
@click="activeTab = 'search'"
>
<text class="tab-icon">🌐</text>
<text class="tab-text">搜索</text>
</view>
</view>
<!-- 聊天AI配置 -->
<view class="config-section" v-show="activeTab === 'chat'">
<view class="section-header">
<text class="section-title">聊天 AI</text>
<text class="section-desc">用于普通对话和知识库问答</text>
</view>
<view class="card">
<view class="field">
<text class="label">服务商</text>
<view class="picker" @click="showPicker('chat')">
<text class="picker-text">{{ getProviderName(config.chat.provider) }}</text>
<text class="picker-arrow">›</text>
</view>
</view>
<view class="field">
<text class="label">API Base URL</text>
<input class="input" v-model="config.chat.baseUrl" placeholder="https://api.example.com/v1" />
</view>
<view class="field">
<text class="label">API Key</text>
<view class="input-group">
<input
class="input flex-1"
:type="showKeys.chat ? 'text' : 'password'"
v-model="config.chat.apiKey"
placeholder="sk-xxxxxxxx"
/>
<view class="toggle-btn" @click="showKeys.chat = !showKeys.chat">
<text>{{ showKeys.chat ? '隐藏' : '显示' }}</text>
</view>
</view>
</view>
<view class="field">
<text class="label">模型名称</text>
<input class="input" v-model="config.chat.model" placeholder="glm-4-flash" />
<text class="hint">推荐: glm-4.5-flash(免费), qwen-turbo, deepseek-chat</text>
</view>
</view>
</view>
<!-- 联网搜索AI配置 -->
<view class="config-section" v-show="activeTab === 'search'">
<view class="section-header">
<text class="section-title">联网搜索 AI</text>
<text class="section-desc">用于实时网络搜索功能</text>
</view>
<view class="card">
<view class="field">
<text class="label">服务商</text>
<view class="picker" @click="showPicker('search')">
<text class="picker-text">{{ getProviderName(config.search.provider) }}</text>
<text class="picker-arrow">›</text>
</view>
</view>
<view class="field">
<text class="label">API Base URL</text>
<input class="input" v-model="config.search.baseUrl" placeholder="https://dashscope.aliyuncs.com/compatible-mode/v1" />
</view>
<view class="field">
<text class="label">API Key</text>
<view class="input-group">
<input
class="input flex-1"
:type="showKeys.search ? 'text' : 'password'"
v-model="config.search.apiKey"
placeholder="sk-xxxxxxxx"
/>
<view class="toggle-btn" @click="showKeys.search = !showKeys.search">
<text>{{ showKeys.search ? '隐藏' : '显示' }}</text>
</view>
</view>
</view>
<view class="field">
<text class="label">模型名称</text>
<input class="input" v-model="config.search.model" placeholder="qwen-turbo" />
<text class="hint">推荐: qwen-turbo(免费联网), qwen-plus</text>
</view>
</view>
</view>
<!-- Embedding配置 -->
<view class="config-section" v-show="activeTab === 'embedding'">
<view class="section-header">
<text class="section-title">向量 Embedding</text>
<text class="section-desc">用于知识库语义搜索</text>
</view>
<view class="card">
<view class="field">
<text class="label">服务商</text>
<view class="picker" @click="showPicker('embedding')">
<text class="picker-text">{{ getProviderName(config.embedding.provider) }}</text>
<text class="picker-arrow">›</text>
</view>
</view>
<view class="field">
<text class="label">API Base URL</text>
<input class="input" v-model="config.embedding.baseUrl" placeholder="https://open.bigmodel.cn/api/paas/v4" />
</view>
<view class="field">
<text class="label">API Key</text>
<view class="input-group">
<input
class="input flex-1"
:type="showKeys.embedding ? 'text' : 'password'"
v-model="config.embedding.apiKey"
placeholder="xxxxxxxx.xxxxxxxx"
/>
<view class="toggle-btn" @click="showKeys.embedding = !showKeys.embedding">
<text>{{ showKeys.embedding ? '隐藏' : '显示' }}</text>
</view>
</view>
</view>
<view class="field">
<text class="label">模型名称</text>
<input class="input" v-model="config.embedding.model" placeholder="embedding-2" />
<text class="hint">推荐: embedding-2(智谱), text-embedding-v3(通义)</text>
</view>
<view class="field">
<text class="label">向量维度</text>
<input class="input" type="number" v-model="config.embedding.dimension" placeholder="1024" />
<text class="hint">embedding-2: 1024, text-embedding-v3: 1024</text>
</view>
</view>
</view>
<!-- 视觉/图片识别AI配置 -->
<view class="config-section" v-show="activeTab === 'vision'">
<view class="section-header">
<text class="section-title">图片识别 AI</text>
<text class="section-desc">用于识别图片内容(GLM视觉模型轮换)</text>
</view>
<view class="card">
<view class="field">
<text class="label">服务商</text>
<view class="picker" @click="showPicker('vision')">
<text class="picker-text">{{ getProviderName(config.vision.provider) }}</text>
<text class="picker-arrow">›</text>
</view>
</view>
<view class="field">
<text class="label">API Base URL</text>
<input class="input" v-model="config.vision.baseUrl" placeholder="https://open.bigmodel.cn/api/paas/v4" />
</view>
<view class="field">
<text class="label">API Key</text>
<view class="input-group">
<input
class="input flex-1"
:type="showKeys.vision ? 'text' : 'password'"
v-model="config.vision.apiKey"
placeholder="xxxxxxxx.xxxxxxxx"
/>
<view class="toggle-btn" @click="showKeys.vision = !showKeys.vision">
<text>{{ showKeys.vision ? '隐藏' : '显示' }}</text>
</view>
</view>
</view>
<view class="field">
<text class="label">模型列表(逗号分隔,轮换使用)</text>
<input class="input" v-model="config.vision.models" placeholder="glm-4v-flash,glm-4.1v-thinking-flash" />
<text class="hint">免费: glm-4v-flash, glm-4.1v-thinking-flash</text>
</view>
</view>
</view>
<!-- 文件解析AI配置 -->
<view class="config-section" v-show="activeTab === 'file'">
<view class="section-header">
<text class="section-title">文件解析 AI</text>
<text class="section-desc">用于解析 PDF/Word/Excel/图片</text>
</view>
<view class="card">
<view class="field">
<text class="label">服务商</text>
<view class="picker" @click="showPicker('file')">
<text class="picker-text">{{ getProviderName(config.file.provider) }}</text>
<text class="picker-arrow">›</text>
</view>
</view>
<view class="field">
<text class="label">API Base URL</text>
<input class="input" v-model="config.file.baseUrl" placeholder="https://api.moonshot.cn/v1" />
</view>
<view class="field">
<text class="label">API Key</text>
<view class="input-group">
<input
class="input flex-1"
:type="showKeys.file ? 'text' : 'password'"
v-model="config.file.apiKey"
placeholder="sk-xxxxxxxx"
/>
<view class="toggle-btn" @click="showKeys.file = !showKeys.file">
<text>{{ showKeys.file ? '隐藏' : '显示' }}</text>
</view>
</view>
</view>
<view class="field">
<text class="label">模型名称</text>
<input class="input" v-model="config.file.model" placeholder="moonshot-v1-auto" />
<text class="hint">推荐: moonshot-v1-auto(Kimi免费), qwen-vl-max</text>
</view>
</view>
</view>
<!-- 通用设置 -->
<view class="card" style="margin-top: 24rpx;">
<view class="card-header">
<text class="card-title">通用设置</text>
</view>
<view class="field">
<text class="label">系统提示词</text>
<textarea
class="textarea"
v-model="config.systemPrompt"
placeholder="你是一个知识库助手..."
:maxlength="500"
/>
</view>
<view class="switch-item">
<view class="switch-info">
<text class="switch-label">智能知识库检索</text>
<text class="switch-desc">说"查找/搜索"时自动检索知识库</text>
</view>
<switch :checked="config.enableRAG" @change="config.enableRAG = $event.detail.value" color="#07C160" />
</view>
</view>
<!-- 操作按钮 -->
<view class="btn-group">
<view class="btn primary" @click="saveConfig">保存全部配置</view>
<view class="btn" @click="testCurrent">测试当前服务</view>
<view class="btn danger" @click="resetConfig">恢复默认</view>
</view>
<!-- 服务商选择弹窗 -->
<view class="modal-mask" v-if="pickerVisible" @click="pickerVisible = false">
<view class="modal" @click.stop>
<view class="modal-header">
<text class="modal-title">选择服务商</text>
</view>
<view class="provider-list">
<view
class="provider-item"
:class="{ active: isProviderSelected(item) }"
v-for="item in currentProviders"
:key="item.id"
@click="selectProvider(item)"
>
<view class="provider-info">
<text class="provider-name">{{ item.name }}</text>
<text class="provider-desc">{{ item.desc }}</text>
</view>
<text class="check-icon" v-if="isProviderSelected(item)">✓</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { saveAIConfig, getAIConfig } from '@/api/user'
const STORAGE_KEY = 'ai_config_v2'
const providers = {
chat: [
{ id: 'zhipu', name: '智谱 AI', desc: 'GLM-4-Flash-250414 免费', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', model: 'glm-4-flash-250414' },
{ id: 'qwen', name: '通义千问', desc: 'qwen-turbo 超便宜', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', model: 'qwen-turbo' },
{ id: 'deepseek', name: 'DeepSeek', desc: '性价比高', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat' },
{ id: 'openai', name: 'OpenAI', desc: 'GPT-4o', baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini' },
{ id: 'custom', name: '自定义', desc: '自定义URL和模型', baseUrl: '', model: '' }
],
vision: [
{ id: 'zhipu', name: '智谱 AI', desc: 'GLM-4V 视觉模型(免费轮换)', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', models: 'glm-4v-flash,glm-4.1v-thinking-flash' },
{ id: 'qwen', name: '通义千问', desc: 'qwen-vl-plus 视觉', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', models: 'qwen-vl-plus' },
{ id: 'custom', name: '自定义', desc: '自定义URL和模型', baseUrl: '', models: '' }
],
file: [
{ id: 'qwen', name: '通义千问', desc: 'qwen-doc-turbo 文档解析', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', model: 'qwen-doc-turbo' },
{ id: 'kimi', name: 'Kimi (月之暗面)', desc: '文件解析限时免费', baseUrl: 'https://api.moonshot.cn/v1', model: 'moonshot-v1-auto' },
{ id: 'custom', name: '自定义', desc: '自定义URL和模型', baseUrl: '', model: '' }
],
embedding: [
{ id: 'zhipu', name: '智谱 AI', desc: 'embedding-2', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', model: 'embedding-2', dimension: 1024 },
{ id: 'qwen', name: '通义千问', desc: 'text-embedding-v3', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', model: 'text-embedding-v3', dimension: 1024 },
{ id: 'openai', name: 'OpenAI', desc: 'text-embedding-3-small', baseUrl: 'https://api.openai.com/v1', model: 'text-embedding-3-small', dimension: 1536 },
{ id: 'custom', name: '自定义', desc: '自定义URL和模型', baseUrl: '', model: '', dimension: 1024 }
],
search: [
{ id: 'qwen', name: '通义千问', desc: '联网搜索限时免费', baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1', model: 'qwen-turbo' },
{ id: 'zhipu', name: '智谱 AI', desc: '联网搜索', baseUrl: 'https://open.bigmodel.cn/api/paas/v4', model: 'glm-4-flash-250414' },
{ id: 'custom', name: '自定义', desc: '自定义URL和模型', baseUrl: '', model: '' }
]
}
const defaultConfig = {
chat: {
provider: 'zhipu',
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
apiKey: '',
model: 'glm-4-flash-250414'
},
vision: {
provider: 'zhipu',
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
apiKey: '',
models: 'glm-4v-flash,glm-4.1v-thinking-flash'
},
file: {
provider: 'qwen',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
apiKey: '',
model: 'qwen-doc-turbo'
},
embedding: {
provider: 'zhipu',
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
apiKey: '',
model: 'embedding-2',
dimension: 1024
},
search: {
provider: 'qwen',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
apiKey: '',
model: 'qwen-turbo'
},
systemPrompt: '你是一个智能知识库助手,帮助用户管理、检索和整理知识。回答问题时尽量简洁准确。',
enableRAG: true
}
const activeTab = ref('chat')
const config = ref(JSON.parse(JSON.stringify(defaultConfig)))
const showKeys = ref({ chat: false, vision: false, file: false, embedding: false, search: false })
const pickerVisible = ref(false)
const pickerType = ref('chat')
const currentProviders = computed(() => providers[pickerType.value] || [])
onMounted(() => {
loadConfig()
})
onShow(() => {
loadConfig()
})
const loadConfig = async () => {
try {
const saved = uni.getStorageSync(STORAGE_KEY)
if (saved) {
const data = typeof saved === 'string' ? JSON.parse(saved) : saved
config.value = mergeConfig(defaultConfig, data)
}
const res = await getAIConfig()
if (res?.data) {
config.value = mergeConfig(config.value, mapServerConfig(res.data))
uni.setStorageSync(STORAGE_KEY, JSON.stringify(config.value))
}
} catch (e) {
console.log('加载配置失败', e)
}
}
const mergeConfig = (base, update) => {
const result = JSON.parse(JSON.stringify(base))
for (const key in update) {
if (typeof update[key] === 'object' && !Array.isArray(update[key]) && update[key] !== null) {
result[key] = { ...result[key], ...update[key] }
} else if (update[key] !== undefined && update[key] !== '') {
result[key] = update[key]
}
}
return result
}
const mapServerConfig = (data) => {
return {
chat: {
provider: data.chat_provider || defaultConfig.chat.provider,
baseUrl: data.chat_base_url || defaultConfig.chat.baseUrl,
apiKey: data.chat_api_key || '',
model: data.chat_model || defaultConfig.chat.model
},
vision: {
provider: data.vision_provider || defaultConfig.vision.provider,
baseUrl: data.vision_base_url || defaultConfig.vision.baseUrl,
apiKey: data.vision_api_key || '',
models: data.vision_models || defaultConfig.vision.models
},
file: {
provider: data.file_provider || defaultConfig.file.provider,
baseUrl: data.file_base_url || defaultConfig.file.baseUrl,
apiKey: data.file_api_key || '',
model: data.file_model || defaultConfig.file.model
},
embedding: {
provider: data.embedding_provider || defaultConfig.embedding.provider,
baseUrl: data.embedding_base_url || defaultConfig.embedding.baseUrl,
apiKey: data.embedding_api_key || '',
model: data.embedding_model || defaultConfig.embedding.model,
dimension: data.embedding_dimension || defaultConfig.embedding.dimension
},
search: {
provider: data.search_provider || defaultConfig.search.provider,
baseUrl: data.search_base_url || defaultConfig.search.baseUrl,
apiKey: data.search_api_key || '',
model: data.search_model || defaultConfig.search.model
},
systemPrompt: data.system_prompt || defaultConfig.systemPrompt,
enableRAG: data.enable_rag !== undefined ? data.enable_rag : defaultConfig.enableRAG
}
}
const getProviderName = (id) => {
for (const type in providers) {
const found = providers[type].find(p => p.id === id)
if (found) return found.name
}
return '自定义'
}
const showPicker = (type) => {
pickerType.value = type
pickerVisible.value = true
}
const isProviderSelected = (item) => {
return config.value[pickerType.value]?.provider === item.id
}
const selectProvider = (item) => {
const type = pickerType.value
config.value[type].provider = item.id
if (item.id !== 'custom') {
config.value[type].baseUrl = item.baseUrl
if (item.model !== undefined) {
config.value[type].model = item.model
}
if (item.models !== undefined) {
config.value[type].models = item.models
}
if (item.dimension !== undefined) {
config.value[type].dimension = item.dimension
}
}
pickerVisible.value = false
}
const saveConfig = async () => {
uni.setStorageSync(STORAGE_KEY, JSON.stringify(config.value))
try {
await saveAIConfig({
chat_provider: config.value.chat.provider,
chat_base_url: config.value.chat.baseUrl,
chat_api_key: config.value.chat.apiKey,
chat_model: config.value.chat.model,
vision_provider: config.value.vision.provider,
vision_base_url: config.value.vision.baseUrl,
vision_api_key: config.value.vision.apiKey,
vision_models: config.value.vision.models,
file_provider: config.value.file.provider,
file_base_url: config.value.file.baseUrl,
file_api_key: config.value.file.apiKey,
file_model: config.value.file.model,
embedding_provider: config.value.embedding.provider,
embedding_base_url: config.value.embedding.baseUrl,
embedding_api_key: config.value.embedding.apiKey,
embedding_model: config.value.embedding.model,
embedding_dimension: config.value.embedding.dimension,
search_provider: config.value.search.provider,
search_base_url: config.value.search.baseUrl,
search_api_key: config.value.search.apiKey,
search_model: config.value.search.model,
system_prompt: config.value.systemPrompt,
enable_rag: config.value.enableRAG
})
uni.showToast({ title: '配置已保存', icon: 'success' })
} catch (e) {
console.log('保存失败', e)
uni.showToast({ title: '本地已保存,云端同步失败', icon: 'none' })
}
}
const testCurrent = async () => {
const type = activeTab.value
const cfg = config.value[type]
if (!cfg.apiKey) {
uni.showToast({ title: '请先填写 API Key', icon: 'none' })
return
}
uni.showLoading({ title: '测试中...' })
try {
let testData = {}
if (type === 'embedding') {
testData = {
model: cfg.model,
input: '测试'
}
const res = await uni.request({
url: `${cfg.baseUrl}/embeddings`,
method: 'POST',
header: {
'Authorization': `Bearer ${cfg.apiKey}`,
'Content-Type': 'application/json'
},
data: testData,
timeout: 15000
})
uni.hideLoading()
if (res.statusCode === 200 && res.data.data) {
uni.showToast({ title: '连接成功', icon: 'success' })
} else {
uni.showToast({ title: res.data.error?.message || '连接失败', icon: 'none' })
}
} else {
testData = {
model: cfg.model,
messages: [{ role: 'user', content: 'Hi' }],
max_tokens: 10
}
const res = await uni.request({
url: `${cfg.baseUrl}/chat/completions`,
method: 'POST',
header: {
'Authorization': `Bearer ${cfg.apiKey}`,
'Content-Type': 'application/json'
},
data: testData,
timeout: 15000
})
uni.hideLoading()
if (res.statusCode === 200 && res.data.choices) {
uni.showToast({ title: '连接成功', icon: 'success' })
} else {
uni.showToast({ title: res.data.error?.message || '连接失败', icon: 'none' })
}
}
} catch (e) {
uni.hideLoading()
uni.showToast({ title: '连接失败: ' + (e.errMsg || '网络错误'), icon: 'none' })
}
}
const resetConfig = () => {
uni.showModal({
title: '确认重置',
content: '将恢复为默认配置,是否继续?',
success: (res) => {
if (res.confirm) {
config.value = JSON.parse(JSON.stringify(defaultConfig))
uni.setStorageSync(STORAGE_KEY, JSON.stringify(config.value))
uni.showToast({ title: '已重置', icon: 'none' })
}
}
})
}
</script>
<style scoped>
.ai-page {
min-height: 100vh;
background-color: #f5f5f5;
padding: 32rpx;
padding-bottom: 120rpx;
}
.page-header {
margin-bottom: 24rpx;
}
.page-title {
font-size: 44rpx;
font-weight: 700;
color: #333;
display: block;
}
.page-desc {
font-size: 26rpx;
color: #999;
margin-top: 8rpx;
display: block;
}
/* Tabs */
.tabs {
display: flex;
background: #fff;
border-radius: 16rpx;
padding: 8rpx;
margin-bottom: 24rpx;
box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
}
.tab {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 20rpx 8rpx;
border-radius: 12rpx;
transition: all 0.3s;
}
.tab.active {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
}
.tab-icon {
font-size: 36rpx;
margin-bottom: 8rpx;
}
.tab-text {
font-size: 24rpx;
color: #666;
}
.tab.active .tab-text {
color: #fff;
font-weight: 500;
}
/* Section */
.config-section {
margin-bottom: 24rpx;
}
.section-header {
margin-bottom: 16rpx;
padding: 0 8rpx;
}
.section-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
display: block;
}
.section-desc {
font-size: 24rpx;
color: #999;
margin-top: 4rpx;
display: block;
}
/* Card */
.card {
background: #fff;
border-radius: 20rpx;
padding: 32rpx;
box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
}
.card-header {
margin-bottom: 24rpx;
padding-bottom: 16rpx;
border-bottom: 1rpx solid #f0f0f0;
}
.card-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
}
/* Field */
.field {
margin-bottom: 28rpx;
}
.field:last-child {
margin-bottom: 0;
}
.label {
font-size: 28rpx;
color: #333;
margin-bottom: 12rpx;
display: block;
font-weight: 500;
}
.input {
width: 100%;
height: 88rpx;
background: #f8f8f8;
border-radius: 12rpx;
padding: 0 24rpx;
font-size: 28rpx;
color: #333;
box-sizing: border-box;
}
.input-group {
display: flex;
align-items: center;
gap: 16rpx;
}
.flex-1 {
flex: 1;
}
.toggle-btn {
padding: 16rpx 24rpx;
background: #f0f0f0;
border-radius: 8rpx;
}
.toggle-btn text {
font-size: 24rpx;
color: #666;
}
.picker {
display: flex;
align-items: center;
justify-content: space-between;
height: 88rpx;
background: #f8f8f8;
border-radius: 12rpx;
padding: 0 24rpx;
}
.picker-text {
font-size: 28rpx;
color: #333;
}
.picker-arrow {
font-size: 32rpx;
color: #999;
}
.hint {
font-size: 24rpx;
color: #999;
margin-top: 8rpx;
display: block;
}
.textarea {
width: 100%;
height: 160rpx;
background: #f8f8f8;
border-radius: 12rpx;
padding: 20rpx 24rpx;
font-size: 28rpx;
color: #333;
box-sizing: border-box;
}
/* Switch */
.switch-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 0;
border-top: 1rpx solid #f5f5f5;
margin-top: 16rpx;
}
.switch-info {
flex: 1;
}
.switch-label {
font-size: 28rpx;
color: #333;
display: block;
}
.switch-desc {
font-size: 24rpx;
color: #999;
margin-top: 4rpx;
display: block;
}
/* Buttons */
.btn-group {
display: flex;
flex-direction: column;
gap: 20rpx;
margin-top: 32rpx;
}
.btn {
height: 96rpx;
display: flex;
align-items: center;
justify-content: center;
border-radius: 16rpx;
font-size: 32rpx;
font-weight: 500;
}
.btn.primary {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
}
.btn:not(.primary):not(.danger) {
background: #fff;
color: #333;
border: 2rpx solid #ddd;
}
.btn.danger {
background: #fff;
color: #ff4d4f;
border: 2rpx solid #ffccc7;
}
/* Modal */
.modal-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
display: flex;
align-items: flex-end;
z-index: 1000;
}
.modal {
width: 100%;
background: #fff;
border-radius: 32rpx 32rpx 0 0;
padding-bottom: env(safe-area-inset-bottom);
}
.modal-header {
padding: 32rpx;
text-align: center;
border-bottom: 1rpx solid #f0f0f0;
}
.modal-title {
font-size: 34rpx;
font-weight: 600;
color: #333;
}
.provider-list {
max-height: 60vh;
overflow-y: auto;
}
.provider-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx;
border-bottom: 1rpx solid #f5f5f5;
}
.provider-item.active {
background: #f0fff4;
}
.provider-info {
flex: 1;
}
.provider-name {
font-size: 32rpx;
color: #333;
font-weight: 500;
display: block;
}
.provider-desc {
font-size: 26rpx;
color: #999;
margin-top: 8rpx;
display: block;
}
.check-icon {
font-size: 36rpx;
color: #07C160;
font-weight: bold;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/settings/ai.vue
|
Vue
|
unknown
| 26,046
|
<template>
<view class="avatar-page">
<view class="section">
<text class="section-title">AI 头像</text>
<view class="avatar-card" @click="chooseAIAvatar">
<view class="avatar-preview">
<image v-if="aiAvatar && !aiAvatar.startsWith('emoji:')" class="avatar-img" :src="aiAvatar" mode="aspectFill" />
<text v-else-if="aiAvatar && aiAvatar.startsWith('emoji:')" class="avatar-emoji">{{ aiAvatar.replace('emoji:', '') }}</text>
<view v-else class="avatar-default ai">
<text class="avatar-icon">🤖</text>
</view>
</view>
<view class="avatar-info">
<text class="avatar-label">点击更换 AI 头像</text>
<text class="avatar-tip">支持从相册选择或拍照</text>
</view>
<text class="arrow">›</text>
</view>
<view class="reset-btn" @click="resetAIAvatar" v-if="aiAvatar">
<text>恢复默认</text>
</view>
</view>
<view class="section">
<text class="section-title">预设 AI 头像</text>
<view class="preset-grid">
<view
class="preset-item"
v-for="(item, index) in presetAvatars"
:key="index"
@click="selectPreset(item)"
:class="{ active: aiAvatar === 'emoji:' + item.emoji }"
>
<text class="preset-emoji">{{ item.emoji }}</text>
<text class="preset-name">{{ item.name }}</text>
</view>
</view>
</view>
<view class="preview-section">
<text class="section-title">预览效果</text>
<view class="chat-preview">
<view class="preview-msg user-msg">
<view class="preview-avatar">
<image v-if="userAvatar" class="avatar-img" :src="userAvatar" mode="aspectFill" />
<view v-else class="avatar-default user small">
<text class="avatar-icon">👤</text>
</view>
</view>
<view class="preview-bubble user-bubble">
<text>你好,这是用户消息</text>
</view>
</view>
<view class="preview-msg ai-msg">
<view class="preview-avatar">
<image v-if="aiAvatar && !aiAvatar.startsWith('emoji:')" class="avatar-img" :src="aiAvatar" mode="aspectFill" />
<text v-else-if="aiAvatar && aiAvatar.startsWith('emoji:')" class="avatar-emoji-small">{{ aiAvatar.replace('emoji:', '') }}</text>
<view v-else class="avatar-default ai small">
<text class="avatar-icon">🤖</text>
</view>
</view>
<view class="preview-bubble ai-bubble">
<text>你好,这是 AI 回复</text>
</view>
</view>
</view>
</view>
<view class="tip-section">
<text class="tip">💡 用户头像请在「账号设置」中修改</text>
</view>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { uploadFile } from '@/api/upload'
const AVATAR_KEY = 'custom_avatars'
const userAvatar = ref('')
const aiAvatar = ref('')
const presetAvatars = [
{ emoji: '🤖', name: '机器人' },
{ emoji: '🧠', name: '大脑' },
{ emoji: '✨', name: '闪亮' },
{ emoji: '🎯', name: '目标' },
{ emoji: '🌟', name: '星星' },
{ emoji: '💡', name: '灵感' },
{ emoji: '🔮', name: '水晶球' },
{ emoji: '🎨', name: '艺术' },
]
onMounted(() => {
loadAvatars()
})
onShow(() => {
loadAvatars()
})
const loadAvatars = () => {
try {
// 用户头像从账号设置获取
userAvatar.value = uni.getStorageSync('customUserAvatar') || ''
// AI头像
const saved = uni.getStorageSync(AVATAR_KEY)
if (saved) {
const data = typeof saved === 'string' ? JSON.parse(saved) : saved
aiAvatar.value = data.aiAvatar || ''
}
} catch (e) {}
}
const saveAIAvatar = () => {
try {
uni.setStorageSync(AVATAR_KEY, { aiAvatar: aiAvatar.value })
} catch (e) {}
}
const chooseAIAvatar = () => {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
uni.showLoading({ title: '上传中...' })
try {
const uploadRes = await uploadFile(res.tempFilePaths[0], 'avatar')
uni.hideLoading()
if (uploadRes.code === 0 && uploadRes.data?.url) {
aiAvatar.value = uploadRes.data.url
saveAIAvatar()
uni.showToast({ title: '已保存', icon: 'success' })
} else {
uni.showToast({ title: '上传失败', icon: 'none' })
}
} catch (e) {
uni.hideLoading()
uni.showToast({ title: '上传失败', icon: 'none' })
}
}
})
}
const selectPreset = (item) => {
aiAvatar.value = 'emoji:' + item.emoji
saveAIAvatar()
uni.showToast({ title: '已保存', icon: 'success' })
}
const resetAIAvatar = () => {
aiAvatar.value = ''
saveAIAvatar()
uni.showToast({ title: '已恢复默认', icon: 'success' })
}
</script>
<style scoped>
.avatar-page {
min-height: 100vh;
background: #f5f5f5;
padding: 24rpx;
}
.section {
margin-bottom: 32rpx;
}
.section-title {
font-size: 28rpx;
color: #666;
margin-bottom: 16rpx;
display: block;
padding-left: 8rpx;
}
.avatar-card {
background: #fff;
border-radius: 16rpx;
padding: 24rpx;
display: flex;
align-items: center;
}
.avatar-preview {
width: 100rpx;
height: 100rpx;
border-radius: 50%;
overflow: hidden;
margin-right: 24rpx;
flex-shrink: 0;
}
.avatar-img {
width: 100%;
height: 100%;
}
.avatar-emoji {
width: 100rpx;
height: 100rpx;
font-size: 60rpx;
display: flex;
align-items: center;
justify-content: center;
background: #e8f5e9;
border-radius: 50%;
}
.avatar-default {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
}
.avatar-default.ai {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
}
.avatar-default.user {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.avatar-icon {
font-size: 48rpx;
}
.avatar-info {
flex: 1;
}
.avatar-label {
font-size: 30rpx;
color: #333;
display: block;
margin-bottom: 8rpx;
}
.avatar-tip {
font-size: 24rpx;
color: #999;
}
.arrow {
font-size: 36rpx;
color: #ccc;
}
.reset-btn {
margin-top: 16rpx;
text-align: center;
}
.reset-btn text {
font-size: 26rpx;
color: #999;
}
.preset-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16rpx;
background: #fff;
border-radius: 16rpx;
padding: 24rpx;
}
.preset-item {
display: flex;
flex-direction: column;
align-items: center;
padding: 16rpx;
border-radius: 12rpx;
background: #f8f8f8;
}
.preset-item.active {
background: #e8f5e9;
border: 2rpx solid #07C160;
}
.preset-emoji {
font-size: 48rpx;
margin-bottom: 8rpx;
}
.preset-name {
font-size: 22rpx;
color: #666;
}
.preview-section {
margin-top: 32rpx;
}
.chat-preview {
background: #fff;
border-radius: 16rpx;
padding: 24rpx;
}
.preview-msg {
display: flex;
align-items: flex-start;
margin-bottom: 20rpx;
}
.preview-msg:last-child {
margin-bottom: 0;
}
.user-msg {
flex-direction: row-reverse;
}
.preview-avatar {
width: 64rpx;
height: 64rpx;
border-radius: 50%;
overflow: hidden;
flex-shrink: 0;
}
.preview-avatar .avatar-img {
width: 100%;
height: 100%;
}
.avatar-emoji-small {
width: 64rpx;
height: 64rpx;
font-size: 36rpx;
display: flex;
align-items: center;
justify-content: center;
background: #e8f5e9;
border-radius: 50%;
}
.avatar-default.small {
width: 64rpx;
height: 64rpx;
}
.avatar-default.small .avatar-icon {
font-size: 32rpx;
}
.preview-bubble {
max-width: 60%;
padding: 16rpx 20rpx;
border-radius: 16rpx;
margin: 0 16rpx;
}
.preview-bubble text {
font-size: 26rpx;
}
.user-bubble {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
border-top-right-radius: 4rpx;
}
.ai-bubble {
background: #f0f0f0;
color: #333;
border-top-left-radius: 4rpx;
}
.tip-section {
margin-top: 40rpx;
text-align: center;
}
.tip {
font-size: 24rpx;
color: #999;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/settings/avatar.vue
|
Vue
|
unknown
| 7,754
|
<template>
<view class="bg-page" :style="pageStyle">
<view class="card">
<text class="title">背景设置</text>
<text class="desc">支持输入颜色(#ffffff)、CSS 渐变(linear-gradient)或图片 URL</text>
<input
class="input"
v-model="backgroundInput"
placeholder="示例:#ffffff 或 linear-gradient(...) 或 https://xxx.jpg"
/>
<view class="btn-row">
<view class="btn primary" @click="applyBackground">应用</view>
<view class="btn" @click="resetBackground">恢复默认</view>
</view>
<view class="btn-row">
<view class="btn" @click="pickImage">上传图片</view>
</view>
<view class="preview" :style="previewStyle">
<text class="preview-text">预览</text>
</view>
</view>
</view>
</template>
<script setup>
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { getBackgroundStyle, getBackgroundSetting, setBackgroundSetting, applyGlobalBackground } from '@/utils/theme'
const backgroundInput = ref('')
const pageStyle = ref(getBackgroundStyle())
onShow(() => {
const bg = getBackgroundSetting()
backgroundInput.value = bg.value || ''
pageStyle.value = getBackgroundStyle()
applyGlobalBackground()
})
const previewStyle = computed(() => {
const val = backgroundInput.value.trim()
if (!val) return { background: '#ffffff' }
if (/^https?:\/\//.test(val) || val.startsWith('data:')) {
return {
backgroundImage: `url(${val})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundColor: '#ffffff'
}
}
return { background: val }
})
const applyBackground = () => {
const val = backgroundInput.value.trim()
if (!val) {
uni.showToast({ title: '请输入背景值', icon: 'none' })
return
}
const type = /^https?:\/\//.test(val) || val.startsWith('data:') ? 'image' : 'color'
setBackgroundSetting({ type, value: val })
pageStyle.value = getBackgroundStyle()
uni.showToast({ title: '背景已应用', icon: 'none' })
}
const resetBackground = () => {
const setting = setBackgroundSetting({ type: 'color', value: '#ffffff' })
backgroundInput.value = setting.value
pageStyle.value = getBackgroundStyle()
uni.showToast({ title: '已恢复默认', icon: 'none' })
}
const pickImage = () => {
uni.chooseImage({
count: 1,
success: async (res) => {
const filePath = res.tempFilePaths?.[0]
if (!filePath) {
uni.showToast({ title: '选择失败', icon: 'none' })
return
}
try {
const dataUrl = await toBase64(filePath)
backgroundInput.value = dataUrl
} catch (e) {
backgroundInput.value = filePath
}
applyBackground()
},
fail: () => {
uni.showToast({ title: '选择失败', icon: 'none' })
}
})
}
const toBase64 = (filePath) => {
return new Promise((resolve, reject) => {
// H5: 直接用 fetch 转 base64
// #ifdef H5
fetch(filePath)
.then(res => res.blob())
.then(blob => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
})
.catch(reject)
// #endif
// 小程序/App
// #ifndef H5
try {
const fs = uni.getFileSystemManager()
fs.readFile({
filePath,
encoding: 'base64',
success: (res) => {
const ext = filePath.split('.').pop() || 'jpg'
resolve(`data:image/${ext};base64,${res.data}`)
},
fail: reject
})
} catch (e) {
reject(e)
}
// #endif
})
}
</script>
<style scoped>
.bg-page {
min-height: 100vh;
padding: 16px;
background: transparent;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: var(--shadow-plain);
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.title {
font-size: 18px;
font-weight: 700;
color: var(--brand-ink);
}
.desc {
font-size: 13px;
color: var(--brand-muted);
}
.input {
width: 100%;
height: 44px;
border-radius: 10px;
border: 1px solid var(--border);
padding: 0 12px;
font-size: 14px;
color: var(--brand-ink);
background-color: #f8fafc;
}
.btn-row {
display: flex;
gap: 12px;
}
.btn {
flex: 1;
text-align: center;
padding: 12px 0;
border-radius: 10px;
border: 1px solid var(--border);
color: var(--brand-ink);
background-color: #f5f7fa;
font-size: 14px;
}
.btn.primary {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #ffffff;
border: none;
box-shadow: 0 10px 24px rgba(16, 240, 194, 0.25);
}
.preview {
margin-top: 8px;
height: 140px;
border-radius: 12px;
border: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.preview-text {
color: var(--brand-muted);
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/settings/background.vue
|
Vue
|
unknown
| 4,723
|
<template>
<view class="settings-page" :style="pageStyle">
<view class="section">
<text class="section-title">通用</text>
<view class="card">
<view class="row" @click="goAvatar">
<view class="row-texts">
<text class="row-title">头像设置</text>
<text class="row-desc">自定义用户和 AI 头像</text>
</view>
<text class="row-arrow">›</text>
</view>
<view class="row" @click="goBackground">
<view class="row-texts">
<text class="row-title">背景设置</text>
<text class="row-desc">自定义页面背景颜色/渐变/图片</text>
</view>
<text class="row-arrow">›</text>
</view>
</view>
</view>
<view class="section">
<text class="section-title">AI</text>
<view class="card">
<view class="row" @click="goAI">
<view class="row-texts">
<text class="row-title">AI 配置</text>
<text class="row-desc">模型、温度、接口 Key 等</text>
</view>
<text class="row-arrow">›</text>
</view>
</view>
</view>
</view>
</template>
<script setup>
import { ref } from 'vue'
import { getBackgroundStyle, applyGlobalBackground } from '@/utils/theme'
const pageStyle = ref(getBackgroundStyle())
applyGlobalBackground()
const goAvatar = () => {
uni.navigateTo({
url: '/pages/mine/settings/avatar'
})
}
const goBackground = () => {
uni.navigateTo({
url: '/pages/mine/settings/background'
})
}
const goAI = () => {
uni.navigateTo({
url: '/pages/mine/settings/ai'
})
}
</script>
<style scoped>
.settings-page {
min-height: 100vh;
padding: 16px;
background: transparent;
}
.section {
margin-bottom: 18px;
}
.section-title {
font-size: 14px;
color: var(--brand-muted);
margin-bottom: 8px;
display: block;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: var(--shadow-plain);
overflow: hidden;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid var(--border);
}
.row:last-child {
border-bottom: none;
}
.row-texts {
display: flex;
flex-direction: column;
gap: 4px;
}
.row-title {
font-size: 16px;
color: var(--brand-ink);
font-weight: 600;
}
.row-desc {
font-size: 13px;
color: var(--brand-muted);
}
.row-arrow {
font-size: 20px;
color: var(--brand-muted);
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/mine/settings.vue
|
Vue
|
unknown
| 2,373
|
<template>
<view class="files-page" :style="pageStyle">
<!-- 顶部标题 -->
<view class="page-header">
<text class="page-title">云端文件</text>
<text class="file-count">共 {{ totalCount }} 个文件</text>
</view>
<!-- 分类标签 -->
<view class="type-tabs">
<view
class="type-tab"
:class="{ active: currentType === 'all' }"
@click="changeType('all')"
>
<text class="tab-text">全部</text>
</view>
<view
class="type-tab"
:class="{ active: currentType === 'image' }"
@click="changeType('image')"
>
<Icon name="image" size="16" />
<text class="tab-text">图片</text>
</view>
<view
class="type-tab"
:class="{ active: currentType === 'document' }"
@click="changeType('document')"
>
<Icon name="file" size="16" />
<text class="tab-text">文档</text>
</view>
</view>
<!-- 文件列表 -->
<scroll-view class="files-list" scroll-y @scrolltolower="loadMore">
<!-- 图片类型:网格布局 -->
<view class="image-grid" v-if="currentType === 'image' || (currentType === 'all' && imageFiles.length > 0)">
<view class="grid-header" v-if="currentType === 'all'">
<text class="grid-title">图片 ({{ imageFiles.length }})</text>
</view>
<view class="grid-content">
<view
class="image-item"
v-for="file in (currentType === 'all' ? imageFiles : files)"
:key="file.id"
@click="previewImage(file)"
@longpress="showFileActions(file)"
>
<image class="image-thumb" :src="file.url" mode="aspectFill" />
<view class="image-overlay">
<text class="image-name">{{ file.filename }}</text>
</view>
</view>
</view>
</view>
<!-- 文档类型:列表布局 -->
<view class="doc-list" v-if="currentType === 'document' || (currentType === 'all' && docFiles.length > 0)">
<view class="list-header" v-if="currentType === 'all'">
<text class="list-title">文档 ({{ docFiles.length }})</text>
</view>
<view
class="doc-item"
v-for="file in (currentType === 'all' ? docFiles : files)"
:key="file.id"
@click="showFileDetail(file)"
@longpress="showFileActions(file)"
>
<view class="doc-icon" :class="getFileTypeClass(file.filename)">
<text class="doc-ext">{{ getFileExt(file.filename) }}</text>
</view>
<view class="doc-info">
<text class="doc-name">{{ file.filename }}</text>
<view class="doc-meta">
<text class="doc-size">{{ formatSize(file.file_size) }}</text>
<text class="doc-time">{{ formatTime(file.created_at) }}</text>
</view>
</view>
<view class="doc-actions">
<view class="action-btn download" @click.stop="downloadFile(file)">
<Icon name="download" size="18" />
</view>
<view class="action-btn delete" @click.stop="confirmDelete(file)">
<Icon name="trash" size="18" />
</view>
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="files.length === 0 && !loading">
<Icon name="cloud" size="64" class="empty-icon" />
<text class="empty-text">暂无{{ currentType === 'image' ? '图片' : currentType === 'document' ? '文档' : '文件' }}</text>
<text class="empty-tip">在聊天中上传文件后点击"上传云端"即可保存</text>
</view>
<!-- 加载中 -->
<view class="loading-more" v-if="loading">
<text class="loading-text">加载中...</text>
</view>
<view class="bottom-spacer"></view>
</scroll-view>
<!-- 图片预览弹窗 -->
<view class="preview-modal" v-if="previewFile" @click="previewFile = null">
<view class="preview-content" @click.stop>
<image class="preview-image" :src="previewFile.url" mode="aspectFit" />
<view class="preview-info">
<text class="preview-name">{{ previewFile.filename }}</text>
<text class="preview-meta">{{ formatSize(previewFile.file_size) }} · {{ formatTime(previewFile.created_at) }}</text>
</view>
<view class="preview-actions">
<view class="preview-btn" @click="downloadFile(previewFile)">
<Icon name="download" size="20" />
<text>下载</text>
</view>
<view class="preview-btn delete" @click="confirmDelete(previewFile)">
<Icon name="trash" size="20" />
<text>删除</text>
</view>
</view>
</view>
<view class="preview-close" @click="previewFile = null">
<Icon name="close" size="24" />
</view>
</view>
<CustomTabBar :currentTab="2" />
</view>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import Icon from '@/components/Icon.vue'
import CustomTabBar from '@/components/CustomTabBar.vue'
import { getBackgroundStyle, applyGlobalBackground } from '@/utils/theme'
import { get, del } from '@/api/request'
const pageStyle = ref(getBackgroundStyle())
const files = ref([])
const currentType = ref('all')
const loading = ref(false)
const page = ref(1)
const hasMore = ref(true)
const previewFile = ref(null)
const totalCount = ref(0)
// 按类型筛选
const imageFiles = computed(() => files.value.filter(f => f.file_type === 'image'))
const docFiles = computed(() => files.value.filter(f => f.file_type !== 'image'))
onMounted(() => {
loadFiles()
applyGlobalBackground()
})
onShow(() => {
pageStyle.value = getBackgroundStyle()
// 刷新列表
page.value = 1
files.value = []
loadFiles()
applyGlobalBackground()
})
const loadFiles = async () => {
if (loading.value) return
loading.value = true
try {
const params = { page: page.value, page_size: 20 }
if (currentType.value !== 'all') {
params.file_type = currentType.value
}
const res = await get('/api/upload/files', params)
if (res.code === 0) {
const list = res.data.list || []
if (page.value === 1) {
files.value = list
} else {
files.value = [...files.value, ...list]
}
hasMore.value = list.length === 20
totalCount.value = files.value.length
}
} catch (e) {
uni.showToast({ title: '加载失败', icon: 'none' })
} finally {
loading.value = false
}
}
const loadMore = () => {
if (hasMore.value && !loading.value) {
page.value++
loadFiles()
}
}
const changeType = (type) => {
if (currentType.value === type) return
currentType.value = type
page.value = 1
files.value = []
loadFiles()
}
const previewImage = (file) => {
if (file.file_type === 'image') {
previewFile.value = file
}
}
const showFileDetail = (file) => {
uni.showActionSheet({
itemList: ['在线预览', '下载文件', '删除'],
success: (res) => {
if (res.tapIndex === 0) {
previewDocument(file)
} else if (res.tapIndex === 1) {
downloadFile(file)
} else if (res.tapIndex === 2) {
confirmDelete(file)
}
}
})
}
// 在线预览文档
const previewDocument = (file) => {
const ext = file.filename.split('.').pop().toLowerCase()
const url = encodeURIComponent(file.url)
let previewUrl = ''
if (ext === 'pdf') {
// PDF 直接打开
previewUrl = file.url
} else if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(ext)) {
// Office 文件用微软在线预览
previewUrl = `https://view.officeapps.live.com/op/view.aspx?src=${url}`
} else {
uni.showToast({ title: '该文件类型暂不支持预览', icon: 'none' })
return
}
// #ifdef H5
window.open(previewUrl, '_blank')
// #endif
// #ifndef H5
uni.navigateTo({
url: `/pages/webview/index?url=${encodeURIComponent(previewUrl)}&title=${encodeURIComponent(file.filename)}`
})
// #endif
}
const showFileActions = (file) => {
uni.showActionSheet({
itemList: ['下载', '删除'],
success: (res) => {
if (res.tapIndex === 0) {
downloadFile(file)
} else if (res.tapIndex === 1) {
confirmDelete(file)
}
}
})
}
const downloadFile = (file) => {
// #ifdef H5
// H5 直接打开新窗口下载
window.open(file.url, '_blank')
// #endif
// #ifndef H5
// 小程序下载
uni.showLoading({ title: '下载中...' })
uni.downloadFile({
url: file.url,
success: (res) => {
if (res.statusCode === 200) {
if (file.file_type === 'image') {
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: () => {
uni.showToast({ title: '已保存到相册' })
},
fail: () => {
uni.showToast({ title: '保存失败', icon: 'none' })
}
})
} else {
uni.openDocument({
filePath: res.tempFilePath,
showMenu: true,
success: () => {
uni.hideLoading()
},
fail: () => {
uni.showToast({ title: '打开失败', icon: 'none' })
}
})
}
}
},
fail: () => {
uni.showToast({ title: '下载失败', icon: 'none' })
},
complete: () => {
uni.hideLoading()
}
})
// #endif
}
const confirmDelete = (file) => {
previewFile.value = null
uni.showModal({
title: '确认删除',
content: `确定删除 "${file.filename}" 吗?删除后无法恢复。`,
confirmColor: '#ff4d4f',
success: async (res) => {
if (res.confirm) {
try {
const result = await del(`/api/upload/files/${file.id}`)
if (result.code === 0) {
files.value = files.value.filter(f => f.id !== file.id)
totalCount.value = files.value.length
uni.showToast({ title: '已删除' })
} else {
uni.showToast({ title: result.message || '删除失败', icon: 'none' })
}
} catch (e) {
uni.showToast({ title: '删除失败', icon: 'none' })
}
}
}
})
}
const formatSize = (bytes) => {
if (!bytes) return '0 B'
const units = ['B', 'KB', 'MB', 'GB']
let i = 0
while (bytes >= 1024 && i < units.length - 1) {
bytes /= 1024
i++
}
return bytes.toFixed(i > 0 ? 1 : 0) + ' ' + units[i]
}
const formatTime = (dateStr) => {
if (!dateStr) return ''
const date = new Date(dateStr)
const now = new Date()
const diff = now - date
if (diff < 60000) return '刚刚'
if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'
return `${date.getMonth() + 1}/${date.getDate()}`
}
const getFileExt = (filename) => {
const ext = filename.split('.').pop().toUpperCase()
return ext.length > 4 ? ext.substring(0, 4) : ext
}
const getFileTypeClass = (filename) => {
const ext = filename.split('.').pop().toLowerCase()
if (['pdf'].includes(ext)) return 'pdf'
if (['doc', 'docx'].includes(ext)) return 'word'
if (['xls', 'xlsx'].includes(ext)) return 'excel'
if (['ppt', 'pptx'].includes(ext)) return 'ppt'
return 'other'
}
</script>
<style scoped>
.files-page {
min-height: 100vh;
background-color: #f5f5f5;
padding-bottom: 120rpx;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 32rpx;
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
}
.page-title {
font-size: 36rpx;
color: #fff;
font-weight: 600;
}
.file-count {
font-size: 26rpx;
color: rgba(255, 255, 255, 0.8);
}
.type-tabs {
display: flex;
padding: 20rpx 24rpx;
gap: 20rpx;
background: #fff;
}
.type-tab {
display: flex;
align-items: center;
gap: 8rpx;
padding: 16rpx 32rpx;
background: #f5f5f5;
border-radius: 32rpx;
color: #666;
}
.type-tab.active {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
}
.tab-text {
font-size: 26rpx;
}
.files-list {
height: calc(100vh - 280rpx);
}
/* 图片网格 */
.image-grid {
padding: 24rpx;
}
.grid-header, .list-header {
margin-bottom: 20rpx;
}
.grid-title, .list-title {
font-size: 28rpx;
color: #333;
font-weight: 500;
}
.grid-content {
display: flex;
flex-wrap: wrap;
gap: 16rpx;
}
.image-item {
width: 216rpx;
height: 216rpx;
border-radius: 12rpx;
overflow: hidden;
position: relative;
background: #f0f0f0;
}
.image-thumb {
width: 216rpx;
height: 216rpx;
}
.image-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 12rpx;
background: linear-gradient(transparent, rgba(0,0,0,0.6));
}
.image-name {
font-size: 20rpx;
color: #fff;
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 文档列表 */
.doc-list {
padding: 24rpx;
}
.doc-item {
display: flex;
align-items: center;
padding: 24rpx;
background: #fff;
border-radius: 16rpx;
margin-bottom: 16rpx;
}
.doc-icon {
width: 80rpx;
height: 80rpx;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: center;
margin-right: 20rpx;
}
.doc-icon.pdf { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a5a 100%); }
.doc-icon.word { background: linear-gradient(135deg, #4a90d9 0%, #357abd 100%); }
.doc-icon.excel { background: linear-gradient(135deg, #27ae60 0%, #219a52 100%); }
.doc-icon.ppt { background: linear-gradient(135deg, #e67e22 0%, #d35400 100%); }
.doc-icon.other { background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%); }
.doc-ext {
font-size: 20rpx;
color: #fff;
font-weight: 600;
}
.doc-info {
flex: 1;
min-width: 0;
}
.doc-name {
font-size: 28rpx;
color: #333;
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 8rpx;
}
.doc-meta {
display: flex;
gap: 20rpx;
}
.doc-size, .doc-time {
font-size: 24rpx;
color: #999;
}
.doc-actions {
display: flex;
gap: 16rpx;
}
.action-btn {
width: 64rpx;
height: 64rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.action-btn.download {
background: #e8f5e9;
color: #07C160;
}
.action-btn.delete {
background: #ffebee;
color: #ff4d4f;
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 120rpx 40rpx;
}
.empty-icon {
color: #ddd;
margin-bottom: 24rpx;
}
.empty-text {
font-size: 32rpx;
color: #999;
margin-bottom: 12rpx;
}
.empty-tip {
font-size: 26rpx;
color: #ccc;
text-align: center;
}
.loading-more {
text-align: center;
padding: 32rpx;
}
.loading-text {
font-size: 26rpx;
color: #999;
}
.bottom-spacer {
height: 120rpx;
}
/* 图片预览弹窗 */
.preview-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
}
.preview-content {
width: 100%;
max-width: 700rpx;
}
.preview-image {
width: 100%;
max-height: 70vh;
}
.preview-info {
padding: 24rpx;
text-align: center;
}
.preview-name {
font-size: 28rpx;
color: #fff;
display: block;
margin-bottom: 8rpx;
}
.preview-meta {
font-size: 24rpx;
color: rgba(255, 255, 255, 0.6);
}
.preview-actions {
display: flex;
justify-content: center;
gap: 48rpx;
padding: 24rpx;
}
.preview-btn {
display: flex;
flex-direction: column;
align-items: center;
gap: 8rpx;
color: #fff;
font-size: 24rpx;
}
.preview-btn.delete {
color: #ff4d4f;
}
.preview-close {
position: absolute;
top: 60rpx;
right: 32rpx;
width: 64rpx;
height: 64rpx;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/monitor/index.vue
|
Vue
|
unknown
| 15,172
|
<template>
<view>
<page-head :title="title"></page-head>
<image :src="logo" mode="aspectFit" style="width: 100%;"></image>
</view>
</template>
<script>
import { getLogoPath } from '../../uni_modules/uts-advance'
export default {
data() {
return {
title: '资源加载示例',
logo:""
}
},
onLoad:function(){
this.logo = getLogoPath()
}
}
</script>
<style>
</style>
|
2201_75827989/zhi_shi_ku
|
pages/resource/resource.vue
|
Vue
|
unknown
| 420
|
<template>
<view class="stats" :style="pageStyle">
<!-- 时间选择 -->
<view class="time-tabs">
<view
class="tab-item"
:class="{ 'active': timeRange === 'week' }"
@click="timeRange = 'week'"
>本周</view>
<view
class="tab-item"
:class="{ 'active': timeRange === 'month' }"
@click="timeRange = 'month'"
>本月</view>
<view
class="tab-item"
:class="{ 'active': timeRange === 'year' }"
@click="timeRange = 'year'"
>本年</view>
</view>
<!-- 概览卡片 -->
<view class="overview-card">
<view class="overview-item">
<text class="overview-num">{{ overview.knowledge }}</text>
<text class="overview-label">知识总数</text>
<text class="overview-trend up">↑ {{ overview.knowledgeTrend }}%</text>
</view>
<view class="overview-divider"></view>
<view class="overview-item">
<text class="overview-num">{{ overview.conversation }}</text>
<text class="overview-label">对话次数</text>
<text class="overview-trend up">↑ {{ overview.conversationTrend }}%</text>
</view>
<view class="overview-divider"></view>
<view class="overview-item">
<text class="overview-num">{{ overview.aiCalls }}</text>
<text class="overview-label">AI调用</text>
<text class="overview-trend" :class="overview.aiTrend >= 0 ? 'up' : 'down'">
{{ overview.aiTrend >= 0 ? '↑' : '↓' }} {{ Math.abs(overview.aiTrend) }}%
</text>
</view>
</view>
<!-- 知识来源分布 -->
<view class="chart-card">
<text class="chart-title">知识来源分布</text>
<view class="pie-chart">
<view class="pie-item" v-for="item in sourceData" :key="item.name">
<view class="pie-bar" :style="{ width: item.percent + '%', backgroundColor: item.color }"></view>
<view class="pie-info">
<view class="pie-dot" :style="{ backgroundColor: item.color }"></view>
<text class="pie-name">{{ item.name }}</text>
<text class="pie-value">{{ item.value }} ({{ item.percent }}%)</text>
</view>
</view>
</view>
</view>
<!-- 每日新增趋势 -->
<view class="chart-card">
<text class="chart-title">每日新增知识</text>
<view class="bar-chart">
<view class="bar-item" v-for="item in dailyData" :key="item.date">
<view class="bar" :style="{ height: item.height + '%' }">
<text class="bar-value">{{ item.value }}</text>
</view>
<text class="bar-label">{{ item.label }}</text>
</view>
</view>
</view>
<!-- 热门标签 -->
<view class="chart-card">
<text class="chart-title">热门标签 TOP10</text>
<view class="tag-list">
<view class="tag-item" v-for="(item, index) in hotTags" :key="item.name">
<text class="tag-rank" :class="{ 'top3': index < 3 }">{{ index + 1 }}</text>
<text class="tag-name">{{ item.name }}</text>
<view class="tag-bar-wrapper">
<view class="tag-bar" :style="{ width: item.percent + '%' }"></view>
</view>
<text class="tag-count">{{ item.count }}</text>
</view>
</view>
</view>
<!-- AI使用统计 -->
<view class="chart-card">
<text class="chart-title">AI功能使用</text>
<view class="ai-stats">
<view class="ai-item" v-for="item in aiStats" :key="item.name">
<view class="ai-icon">
<Icon :name="item.icon" size="20" />
</view>
<view class="ai-info">
<text class="ai-name">{{ item.name }}</text>
<view class="ai-bar-wrapper">
<view class="ai-bar" :style="{ width: item.percent + '%' }"></view>
</view>
</view>
<text class="ai-count">{{ item.count }}次</text>
</view>
</view>
</view>
<view class="bottom-spacer" style="height: 120rpx;"></view>
<CustomTabBar :currentTab="3" />
</view>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import Icon from '@/components/Icon.vue'
import CustomTabBar from '@/components/CustomTabBar.vue'
import { getStats } from '@/api/user'
import { getKnowledgeList } from '@/api/knowledge'
import { getBackgroundStyle, applyGlobalBackground } from '@/utils/theme'
const timeRange = ref('week')
const loading = ref(false)
const overview = ref({
knowledge: 0,
knowledgeTrend: 0,
conversation: 0,
conversationTrend: 0,
aiCalls: 0,
aiTrend: 0
})
const sourceData = ref([])
const dailyData = ref([])
const hotTags = ref([])
const aiStats = ref([])
const pageStyle = ref(getBackgroundStyle())
onMounted(() => {
loadStats(timeRange.value)
applyGlobalBackground()
})
onShow(() => {
pageStyle.value = getBackgroundStyle()
applyGlobalBackground()
})
watch(timeRange, (val) => {
loadStats(val)
})
const loadStats = async (range) => {
loading.value = true
try {
const [statsRes, knowledgeRes] = await Promise.allSettled([
getStats(),
getKnowledgeList({ page: 1, size: 100 })
])
if (statsRes.status === 'fulfilled' && statsRes.value.data) {
const s = statsRes.value.data
overview.value = {
knowledge: s.knowledge || 0,
knowledgeTrend: 0,
conversation: s.conversation || 0,
conversationTrend: 0,
aiCalls: s.aiCalls || 0,
aiTrend: 0
}
}
const list = (knowledgeRes.status === 'fulfilled' && knowledgeRes.value.data) ? knowledgeRes.value.data : []
buildSourceData(list)
buildDailyData(list, range)
buildTags(list)
buildAIStats()
} catch (e) {
uni.showToast({ title: '统计获取失败', icon: 'none' })
} finally {
loading.value = false
}
}
const buildSourceData = (list) => {
const map = {
chat: { name: '聊天提取', color: '#07C160', value: 0 },
manual: { name: '手动添加', color: '#1890ff', value: 0 },
import: { name: '文件导入', color: '#06AD56', value: 0 },
monitor: { name: '监控入库', color: '#10b981', value: 0 }
}
list.forEach(item => {
const key = item.source || 'manual'
if (map[key]) {
map[key].value += 1
} else {
map.manual.value += 1
}
})
const total = Object.values(map).reduce((s, i) => s + i.value, 0) || 1
sourceData.value = Object.values(map)
.filter(i => i.value > 0)
.map(i => ({ ...i, percent: Math.round((i.value / total) * 100) }))
}
const buildDailyData = (list, range) => {
const daysMap = {}
list.forEach(item => {
if (!item.createdAt) return
const d = new Date(item.createdAt)
const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
daysMap[key] = (daysMap[key] || 0) + 1
})
const limit = range === 'week' ? 7 : range === 'month' ? 30 : 90
const today = new Date()
const data = []
for (let i = limit - 1; i >= 0; i--) {
const d = new Date(today.getTime() - i * 86400000)
const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
const label = `${(d.getMonth() + 1)}/${d.getDate()}`
data.push({ date: key, label, value: daysMap[key] || 0 })
}
const max = Math.max(...data.map(d => d.value), 1)
dailyData.value = data.map(d => ({ ...d, height: Math.round((d.value / max) * 100) }))
}
const buildTags = (list) => {
const counter = {}
list.forEach(item => {
(item.tags || []).forEach(tag => {
if (!tag) return
counter[tag] = (counter[tag] || 0) + 1
})
})
const sorted = Object.entries(counter)
.sort((a, b) => b[1] - a[1])
.slice(0, 10)
const max = sorted.length ? sorted[0][1] : 1
hotTags.value = sorted.map(([name, count]) => ({
name,
count,
percent: Math.round((count / max) * 100)
}))
}
const buildAIStats = () => {
const items = [
{ name: '智能对话', icon: 'robot', count: overview.value.aiCalls || 0 },
{ name: '知识检索', icon: 'search', count: overview.value.knowledge || 0 },
{ name: '自动总结', icon: 'note', count: 0 },
{ name: '标签生成', icon: 'tag', count: 0 },
{ name: '内容整理', icon: 'clipboard', count: 0 }
]
const max = Math.max(...items.map(i => i.count), 1)
aiStats.value = items.map(i => ({
...i,
percent: max ? Math.round((i.count / max) * 100) : 0
}))
}
</script>
<style scoped>
.stats {
min-height: 100vh;
background-color: transparent;
padding-bottom: 48rpx;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
.time-tabs {
display: flex;
background-color: #fff;
padding: 24rpx 32rpx;
}
.tab-item {
flex: 1;
text-align: center;
padding: 16rpx;
font-size: 28rpx;
color: #666;
border-radius: 8rpx;
}
.tab-item.active {
background: linear-gradient(135deg, #07C160 0%, #06AD56 100%);
color: #fff;
}
.overview-card {
display: flex;
margin: 24rpx;
padding: 32rpx;
background-color: #fff;
border-radius: 16rpx;
}
.overview-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.overview-num {
font-size: 48rpx;
color: #333;
font-weight: 600;
}
.overview-label {
font-size: 24rpx;
color: #999;
margin: 8rpx 0;
}
.overview-trend {
font-size: 22rpx;
padding: 4rpx 12rpx;
border-radius: 16rpx;
}
.overview-trend.up {
color: #07C160;
background-color: #e8f5e9;
}
.overview-trend.down {
color: #ff4d4f;
background-color: #fff2f0;
}
.overview-divider {
width: 1rpx;
background-color: #f0f0f0;
margin: 0 16rpx;
}
.chart-card {
margin: 24rpx;
padding: 32rpx;
background-color: #fff;
border-radius: 16rpx;
}
.chart-title {
font-size: 30rpx;
color: #333;
font-weight: 500;
margin-bottom: 32rpx;
display: block;
}
/* 饼图样式 */
.pie-chart {
display: flex;
flex-direction: column;
gap: 20rpx;
}
.pie-item {
display: flex;
flex-direction: column;
gap: 12rpx;
}
.pie-bar {
height: 24rpx;
border-radius: 12rpx;
}
.pie-info {
display: flex;
align-items: center;
}
.pie-dot {
width: 16rpx;
height: 16rpx;
border-radius: 50%;
margin-right: 12rpx;
}
.pie-name {
font-size: 26rpx;
color: #666;
margin-right: 16rpx;
}
.pie-value {
font-size: 26rpx;
color: #999;
}
/* 柱状图 */
.bar-chart {
display: flex;
justify-content: space-between;
align-items: flex-end;
height: 300rpx;
padding-top: 40rpx;
}
.bar-item {
display: flex;
flex-direction: column;
align-items: center;
width: 60rpx;
}
.bar {
width: 40rpx;
background: linear-gradient(180deg, #07C160 0%, #06AD56 100%);
border-radius: 8rpx 8rpx 0 0;
display: flex;
justify-content: center;
min-height: 20rpx;
}
.bar-value {
font-size: 22rpx;
color: #fff;
margin-top: -32rpx;
}
.bar-label {
font-size: 22rpx;
color: #999;
margin-top: 12rpx;
}
/* 热门标签 */
.tag-list {
display: flex;
flex-direction: column;
gap: 20rpx;
}
.tag-item {
display: flex;
align-items: center;
}
.tag-rank {
width: 40rpx;
font-size: 26rpx;
color: #999;
font-weight: 500;
}
.tag-rank.top3 {
color: #07C160;
}
.tag-name {
width: 140rpx;
font-size: 26rpx;
color: #333;
}
.tag-bar-wrapper {
flex: 1;
height: 20rpx;
background-color: #f5f5f5;
border-radius: 10rpx;
margin: 0 20rpx;
overflow: hidden;
}
.tag-bar {
height: 100%;
background: linear-gradient(90deg, #07C160 0%, #06AD56 100%);
border-radius: 10rpx;
}
.tag-count {
width: 60rpx;
font-size: 26rpx;
color: #999;
text-align: right;
}
/* AI统计 */
.ai-stats {
display: flex;
flex-direction: column;
gap: 24rpx;
}
.ai-item {
display: flex;
align-items: center;
}
.ai-icon {
width: 60rpx;
height: 60rpx;
background-color: #f5f5f5;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: center;
margin-right: 16rpx;
color: #07C160;
}
.ai-info {
flex: 1;
}
.ai-name {
font-size: 28rpx;
color: #333;
display: block;
margin-bottom: 8rpx;
}
.ai-bar-wrapper {
height: 12rpx;
background-color: #f5f5f5;
border-radius: 6rpx;
overflow: hidden;
}
.ai-bar {
height: 100%;
background: linear-gradient(90deg, #059669 0%, #047857 100%);
border-radius: 6rpx;
}
.ai-count {
width: 100rpx;
font-size: 26rpx;
color: #666;
text-align: right;
}
</style>
|
2201_75827989/zhi_shi_ku
|
pages/stats/index.vue
|
Vue
|
unknown
| 11,801
|
from fastapi import APIRouter
from .user import router as user_router
from .chat import router as chat_router
from .knowledge import router as knowledge_router
from .ai import router as ai_router
from .category import router as category_router
from .monitor import router as monitor_router
from .upload import router as upload_router
api_router = APIRouter()
api_router.include_router(user_router, prefix="/user", tags=["用户"])
api_router.include_router(chat_router, prefix="/chat", tags=["对话"])
api_router.include_router(knowledge_router, prefix="/knowledge", tags=["知识库"])
api_router.include_router(ai_router, prefix="/ai", tags=["AI"])
api_router.include_router(category_router, prefix="/categories", tags=["分类"])
api_router.include_router(monitor_router, prefix="/monitor", tags=["监控"])
api_router.include_router(upload_router, prefix="/upload", tags=["上传"])
|
2201_75827989/zhi_shi_ku
|
server/app/api/__init__.py
|
Python
|
unknown
| 890
|
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
from typing import Optional
from app.core.database import get_db
from app.core.security import get_current_user_id
from app.services.ai_service import ai_service
router = APIRouter()
class ContentRequest(BaseModel):
content: str
class SearchRequest(BaseModel):
query: str
@router.post("/summarize")
async def summarize(
data: ContentRequest,
user_id: int = Depends(get_current_user_id)
):
"""AI总结内容"""
result = await ai_service.summarize(data.content)
return {"code": 0, "data": result}
@router.post("/generate-tags")
async def generate_tags(
data: ContentRequest,
user_id: int = Depends(get_current_user_id)
):
"""AI生成标签"""
tags = await ai_service.generate_tags(data.content)
return {"code": 0, "data": {"tags": tags}}
@router.post("/search")
async def ai_search(
data: SearchRequest,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""AI语义搜索"""
results = await ai_service.search_knowledge(db, user_id, data.query)
return {"code": 0, "data": results}
|
2201_75827989/zhi_shi_ku
|
server/app/api/ai.py
|
Python
|
unknown
| 1,213
|
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, func
from pydantic import BaseModel
from typing import Optional
from app.core.database import get_db
from app.core.security import get_current_user_id
from app.models.knowledge import Category, Knowledge
router = APIRouter()
class CategoryCreate(BaseModel):
name: str
icon: Optional[str] = "folder"
color: Optional[str] = "#07C160"
sort_order: Optional[int] = 0
class CategoryUpdate(BaseModel):
name: Optional[str] = None
icon: Optional[str] = None
color: Optional[str] = None
sort_order: Optional[int] = None
@router.get("")
async def list_categories(
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取分类列表"""
count_result = await db.execute(
select(Knowledge.category_id, func.count().label("cnt"))
.where(Knowledge.user_id == user_id, Knowledge.status == 1)
.group_by(Knowledge.category_id)
)
count_map = {row[0]: row[1] for row in count_result.all() if row[0] is not None}
result = await db.execute(
select(Category)
.where(Category.user_id == user_id)
.order_by(Category.sort_order.desc(), Category.created_at.desc())
)
items = result.scalars().all()
return {
"code": 0,
"data": [
{
"id": c.id,
"name": c.name,
"icon": c.icon,
"color": c.color,
"sortOrder": c.sort_order or 0,
"count": count_map.get(c.id, c.count or 0),
}
for c in items
],
}
@router.post("")
async def create_category(
data: CategoryCreate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""创建分类"""
category = Category(
user_id=user_id,
name=data.name,
icon=data.icon or "folder",
color=data.color or "#07C160",
sort_order=data.sort_order or 0,
)
db.add(category)
await db.commit()
await db.refresh(category)
return {"code": 0, "data": {"id": category.id}}
@router.put("/{category_id}")
async def update_category(
category_id: int,
data: CategoryUpdate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""更新分类"""
result = await db.execute(
select(Category).where(Category.id == category_id, Category.user_id == user_id)
)
category = result.scalar_one_or_none()
if not category:
raise HTTPException(status_code=404, detail="分类不存在")
update_data = data.dict(exclude_unset=True)
await db.execute(
update(Category)
.where(Category.id == category_id, Category.user_id == user_id)
.values(
name=update_data.get("name", category.name),
icon=update_data.get("icon", category.icon),
color=update_data.get("color", category.color),
sort_order=update_data.get("sort_order", category.sort_order),
)
)
await db.commit()
return {"code": 0, "message": "更新成功"}
@router.delete("/{category_id}")
async def delete_category(
category_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""删除分类"""
result = await db.execute(
select(Category).where(Category.id == category_id, Category.user_id == user_id)
)
category = result.scalar_one_or_none()
if not category:
raise HTTPException(status_code=404, detail="分类不存在")
await db.execute(
update(Category)
.where(Category.id == category_id, Category.user_id == user_id)
.values(name=f"{category.name}-已删除", sort_order=-1)
)
await db.commit()
return {"code": 0, "message": "删除成功"}
|
2201_75827989/zhi_shi_ku
|
server/app/api/category.py
|
Python
|
unknown
| 3,929
|
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from pydantic import BaseModel
from typing import Optional, List
import re
from app.core.database import get_db
from app.core.security import get_current_user_id
from app.models.conversation import Conversation, Message
from app.models.knowledge import Knowledge
from app.services.ai_service import ai_service
# 保存指令(必须是短消息且主要是保存意图)
SAVE_COMMANDS = [
'保存', '存一下', '存下', '记一下', '记下', '收藏', '入库',
'帮我存', '帮我保存', '帮忙保存', '帮忙存', '存到知识库',
'保存到知识库', '存入知识库', '这个保存', '保存这个',
'记录一下', '记录下来', '存下来', '保存下来'
]
router = APIRouter()
class ConversationCreate(BaseModel):
title: Optional[str] = "新对话"
class ChatMessage(BaseModel):
conversationId: Optional[int] = None
message: str
webSearch: Optional[bool] = False
saveOnly: Optional[bool] = False # 只保存到上下文,不调用AI
aiReply: Optional[str] = None # 文件解析时,同时保存AI回复
fileUrl: Optional[str] = None # 文件/图片的 COS URL
fileType: Optional[str] = None # 文件类型:image/document
class MessageResponse(BaseModel):
id: int
role: str
content: str
created_at: str
@router.get("/conversations")
async def get_conversations(
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取会话列表"""
result = await db.execute(
select(Conversation)
.where(Conversation.user_id == user_id, Conversation.status == 1)
.order_by(Conversation.updated_at.desc())
.limit(50)
)
conversations = result.scalars().all()
return {
"code": 0,
"data": [
{
"id": c.id,
"title": c.title,
"lastMessage": c.last_message or "",
"updatedAt": c.updated_at.isoformat() if c.updated_at else None
}
for c in conversations
]
}
@router.post("/conversations")
async def create_conversation(
data: ConversationCreate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""创建会话"""
conversation = Conversation(
user_id=user_id,
title=data.title
)
db.add(conversation)
await db.commit()
await db.refresh(conversation)
return {"code": 0, "data": {"id": conversation.id}}
@router.delete("/conversations/{conversation_id}")
async def delete_conversation(
conversation_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""删除会话"""
await db.execute(
update(Conversation)
.where(Conversation.id == conversation_id, Conversation.user_id == user_id)
.values(status=0)
)
await db.commit()
return {"code": 0, "message": "删除成功"}
@router.delete("/messages/{message_id}")
async def delete_message(
message_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""删除单条消息"""
from sqlalchemy import delete
result = await db.execute(
delete(Message)
.where(Message.id == message_id, Message.user_id == user_id)
)
await db.commit()
if result.rowcount > 0:
return {"code": 0, "message": "删除成功"}
else:
return {"code": -1, "message": "消息不存在或无权限"}
class UpdateMessageFile(BaseModel):
fileUrl: str
fileType: str = "image"
@router.put("/messages/{message_id}/file")
async def update_message_file(
message_id: int,
data: UpdateMessageFile,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""更新消息的文件URL(上传云端后调用)"""
result = await db.execute(
select(Message).where(Message.id == message_id, Message.user_id == user_id)
)
message = result.scalar_one_or_none()
if not message:
return {"code": -1, "message": "消息不存在"}
# 更新 extra_data
extra_data = message.extra_data or {}
extra_data["fileUrl"] = data.fileUrl
extra_data["fileType"] = data.fileType
message.extra_data = extra_data
await db.commit()
return {"code": 0, "message": "更新成功"}
@router.get("/conversations/{conversation_id}/messages")
async def get_messages(
conversation_id: int,
page: int = Query(1, ge=1),
size: int = Query(50, ge=1, le=200),
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取会话消息(分页,按时间升序返回)"""
result = await db.execute(
select(Message)
.where(Message.conversation_id == conversation_id)
.order_by(Message.created_at.desc())
.offset((page - 1) * size)
.limit(size)
)
rows = result.scalars().all()
messages = list(reversed(rows)) # 转为时间升序
return {
"code": 0,
"data": [
{
"id": m.id,
"role": m.role,
"content": m.content,
"references": m.extra_data.get("references", []) if m.extra_data else [],
"fileUrl": m.extra_data.get("fileUrl") if m.extra_data else None,
"fileType": m.extra_data.get("fileType") if m.extra_data else None
}
for m in messages
],
"hasMore": len(rows) == size # 可能还有更多
}
def check_save_intent(message: str) -> dict:
"""
检查消息是否是保存指令,返回解析结果
返回: {"is_save": bool, "type": str, "content": str}
- type: "specific" (有具体内容), "vague" (模糊指令), "last_reply" (保存上一条)
"""
import re
msg = message.strip()
# 检查是否包含保存关键词
save_keywords = ['保存', '记录', '记住', '存一下', '存下', '储存']
has_save_keyword = any(kw in msg for kw in save_keywords)
if not has_save_keyword:
return {"is_save": False, "type": None, "content": None}
# 包含查询相关词,不是保存指令
query_words = ['查', '找', '搜', '问', '什么', '怎么', '如何', '哪', '吗', '?', '?']
if any(word in msg for word in query_words):
return {"is_save": False, "type": None, "content": None}
# 模式1: "帮我保存:xxx" 或 "保存:xxx" - 有具体内容
match = re.search(r'(?:帮我)?(?:保存|记录|记住|储存)[::]\s*(.+)', msg, re.DOTALL)
if match:
content = match.group(1).strip()
if content and len(content) > 2: # 内容足够长
return {"is_save": True, "type": "specific", "content": content}
# 模式2: 模糊指令 - "保存以上内容"、"帮我记录这个"、"把这个存下"
vague_patterns = ['以上', '这个', '这些', '那个', '上面', '刚才', '这段']
if any(p in msg for p in vague_patterns):
return {"is_save": True, "type": "vague", "content": None}
# 模式3: 简单保存指令 - "保存"、"帮我保存"、"保存上条"
last_reply_cmds = ['保存上条', '保存上一条', '存上条', '存上一条']
if any(cmd in msg for cmd in last_reply_cmds):
return {"is_save": True, "type": "last_reply", "content": None}
if len(msg) <= 15:
for cmd in SAVE_COMMANDS:
if cmd in msg:
return {"is_save": True, "type": "last_reply", "content": None}
return {"is_save": False, "type": None, "content": None}
@router.post("")
async def chat(
data: ChatMessage,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""发送消息(AI对话)"""
conversation_id = data.conversationId
# 如果没有会话ID,创建新会话
if not conversation_id:
conversation = Conversation(user_id=user_id, title="新对话")
db.add(conversation)
await db.commit()
await db.refresh(conversation)
conversation_id = conversation.id
# 检查是否是保存指令
save_intent = check_save_intent(data.message)
if save_intent["is_save"]:
content_to_save = None
save_title = None
reply = None
if save_intent["type"] == "specific":
# 有具体内容,直接保存
content_to_save = save_intent["content"]
save_title = content_to_save[:50] + "..." if len(content_to_save) > 50 else content_to_save
elif save_intent["type"] == "vague":
# 模糊指令,询问用户
reply = """请问您要保存什么内容?
1. 上一条 AI 回复 - 回复"保存上条"
2. 选择聊天记录 - 长按消息进入多选,选好后点"存知识库"
3. 指定内容 - 回复"保存:你要保存的具体内容"
请告诉我您的选择~"""
elif save_intent["type"] == "last_reply":
# 保存上一条 AI 回复
result = await db.execute(
select(Message)
.where(
Message.conversation_id == conversation_id,
Message.role == "assistant"
)
.order_by(Message.created_at.desc())
.limit(1)
)
last_ai_message = result.scalar_one_or_none()
if last_ai_message:
content_to_save = last_ai_message.content
save_title = content_to_save[:50] + "..." if len(content_to_save) > 50 else content_to_save
else:
reply = "没有找到可保存的内容,请先和我聊天~"
# 如果是询问用户,直接返回
if reply and not content_to_save:
user_message = Message(conversation_id=conversation_id, user_id=user_id, role="user", content=data.message)
ai_message = Message(conversation_id=conversation_id, user_id=user_id, role="assistant", content=reply)
db.add(user_message)
db.add(ai_message)
await db.commit()
return {"code": 0, "data": {"conversationId": conversation_id, "reply": reply, "references": []}}
# 保存到知识库
if content_to_save:
try:
embedding = await ai_service.get_embedding(content_to_save[:1000])
knowledge = Knowledge(
user_id=user_id,
title=save_title,
content=content_to_save,
source="chat",
tags=["AI对话"],
embedding=embedding
)
db.add(knowledge)
user_message = Message(conversation_id=conversation_id, user_id=user_id, role="user", content=data.message)
reply = f"已保存到知识库!\n内容:{save_title}"
ai_message = Message(conversation_id=conversation_id, user_id=user_id, role="assistant", content=reply)
db.add(user_message)
db.add(ai_message)
await db.commit()
return {"code": 0, "data": {"conversationId": conversation_id, "reply": reply, "references": []}}
except Exception as e:
print(f"保存知识库失败: {e}")
# 如果没有上一条消息,提示用户
reply = "没有找到可保存的内容"
user_message = Message(
conversation_id=conversation_id,
user_id=user_id,
role="user",
content=data.message
)
db.add(user_message)
ai_message = Message(
conversation_id=conversation_id,
user_id=user_id,
role="assistant",
content=reply
)
db.add(ai_message)
await db.commit()
return {
"code": 0,
"data": {
"conversationId": conversation_id,
"reply": reply,
"references": []
}
}
# 保存用户消息(如果有文件,存到 extra_data)
extra_data = None
if data.fileUrl:
extra_data = {
"fileUrl": data.fileUrl,
"fileType": data.fileType or "image"
}
user_message = Message(
conversation_id=conversation_id,
user_id=user_id,
role="user",
content=data.message,
extra_data=extra_data
)
db.add(user_message)
# 如果只保存(用于文件解析记录),不调用AI
if data.saveOnly:
# 保存到 Redis 上下文
from app.core.redis import redis_client
await redis_client.add_chat_message(user_id, conversation_id, {
"role": "user",
"content": data.message
})
# 如果有AI回复,也保存AI消息
if data.aiReply:
ai_message = Message(
conversation_id=conversation_id,
user_id=user_id,
role="assistant",
content=data.aiReply
)
db.add(ai_message)
await redis_client.add_chat_message(user_id, conversation_id, {
"role": "assistant",
"content": data.aiReply
})
# 同时保存到数据库(这样页面刷新后消息不会丢失)
await db.flush() # 获取消息ID
user_msg_id = user_message.id
await db.commit()
return {
"code": 0,
"data": {
"conversationId": conversation_id,
"userMessageId": user_msg_id,
"reply": data.aiReply or "",
"references": []
}
}
# 调用AI服务
ai_response = await ai_service.chat(
db=db,
user_id=user_id,
conversation_id=conversation_id,
message=data.message,
web_search=data.webSearch or False
)
# 保存AI回复(含详细统计)
ai_message = Message(
conversation_id=conversation_id,
user_id=user_id,
role="assistant",
content=ai_response["reply"],
tokens_used=ai_response.get("tokens_used", 0),
input_tokens=ai_response.get("input_tokens", 0),
output_tokens=ai_response.get("output_tokens", 0),
cached_tokens=ai_response.get("cached_tokens", 0),
model_name=ai_response.get("model_name", ""),
provider=ai_response.get("provider", ""),
cost=ai_response.get("cost", 0),
extra_data={"references": ai_response.get("references", [])}
)
db.add(ai_message)
# 更新会话
await db.execute(
update(Conversation)
.where(Conversation.id == conversation_id)
.values(
last_message=ai_response["reply"][:100],
message_count=Conversation.message_count + 2
)
)
await db.commit()
return {
"code": 0,
"data": {
"conversationId": conversation_id,
"reply": ai_response["reply"],
"references": ai_response.get("references", [])
}
}
|
2201_75827989/zhi_shi_ku
|
server/app/api/chat.py
|
Python
|
unknown
| 15,526
|
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, func, or_, text
from pydantic import BaseModel
from typing import Optional, List
from app.core.database import get_db
from app.core.security import get_current_user_id
from app.models.knowledge import Knowledge, Category
from app.services.ai_service import ai_service
router = APIRouter()
class KnowledgeCreate(BaseModel):
title: str
content: str
summary: Optional[str] = None
source: Optional[str] = "manual"
tags: Optional[List[str]] = []
category_id: Optional[int] = None
class KnowledgeUpdate(BaseModel):
title: Optional[str] = None
content: Optional[str] = None
summary: Optional[str] = None
tags: Optional[List[str]] = None
category_id: Optional[int] = None
class SearchRequest(BaseModel):
query: Optional[str] = None
keyword: Optional[str] = None
type: Optional[str] = "semantic" # semantic / keyword
@router.get("")
async def get_knowledge_list(
category: Optional[str] = None,
page: int = Query(1, ge=1),
size: int = Query(20, ge=1, le=100),
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取知识列表"""
query = select(Knowledge).where(Knowledge.user_id == user_id, Knowledge.status == 1)
if category and category != "all":
if category == "favorites":
query = query.where(Knowledge.is_favorite == 1)
elif category == "uncategorized":
query = query.where(Knowledge.category_id.is_(None))
elif category.isdigit():
query = query.where(Knowledge.category_id == int(category))
else:
query = query.where(Knowledge.source == category)
query = query.order_by(Knowledge.created_at.desc()).offset((page - 1) * size).limit(size)
result = await db.execute(query)
items = result.scalars().all()
return {
"code": 0,
"data": [
{
"id": k.id,
"title": k.title,
"summary": k.summary or (k.content[:100] + "..." if len(k.content) > 100 else k.content),
"source": k.source,
"tags": k.tags or [],
"createdAt": k.created_at.isoformat() if k.created_at else None
}
for k in items
]
}
@router.get("/{knowledge_id}")
async def get_knowledge_detail(
knowledge_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取知识详情"""
result = await db.execute(
select(Knowledge).where(
Knowledge.id == knowledge_id,
Knowledge.user_id == user_id,
Knowledge.status == 1
)
)
knowledge = result.scalar_one_or_none()
if not knowledge:
raise HTTPException(status_code=404, detail="知识不存在")
# 更新浏览次数
await db.execute(
update(Knowledge).where(Knowledge.id == knowledge_id).values(view_count=Knowledge.view_count + 1)
)
await db.commit()
return {
"code": 0,
"data": {
"id": knowledge.id,
"title": knowledge.title,
"content": knowledge.content,
"summary": knowledge.summary,
"source": knowledge.source,
"tags": knowledge.tags or [],
"is_favorite": knowledge.is_favorite,
"createdAt": knowledge.created_at.strftime("%Y-%m-%d") if knowledge.created_at else None
}
}
@router.post("")
async def create_knowledge(
data: KnowledgeCreate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""创建知识"""
# 生成向量
embedding = await ai_service.get_embedding(data.title + " " + data.content)
knowledge = Knowledge(
user_id=user_id,
title=data.title,
content=data.content,
summary=data.summary,
source=data.source,
tags=data.tags,
category_id=data.category_id,
embedding=embedding,
token_count=len(data.content)
)
db.add(knowledge)
await db.commit()
await db.refresh(knowledge)
return {"code": 0, "data": {"id": knowledge.id}, "message": "创建成功"}
@router.put("/{knowledge_id}")
async def update_knowledge(
knowledge_id: int,
data: KnowledgeUpdate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""更新知识"""
update_data = data.dict(exclude_unset=True)
# 如果内容变化,重新生成向量
if "content" in update_data or "title" in update_data:
result = await db.execute(select(Knowledge).where(Knowledge.id == knowledge_id))
knowledge = result.scalar_one_or_none()
if knowledge:
new_title = update_data.get("title", knowledge.title)
new_content = update_data.get("content", knowledge.content)
update_data["embedding"] = await ai_service.get_embedding(new_title + " " + new_content)
await db.execute(
update(Knowledge)
.where(Knowledge.id == knowledge_id, Knowledge.user_id == user_id)
.values(**update_data)
)
await db.commit()
return {"code": 0, "message": "更新成功"}
@router.delete("/{knowledge_id}")
async def delete_knowledge(
knowledge_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""删除知识"""
await db.execute(
update(Knowledge)
.where(Knowledge.id == knowledge_id, Knowledge.user_id == user_id)
.values(status=0)
)
await db.commit()
return {"code": 0, "message": "删除成功"}
@router.post("/search")
async def search_knowledge(
data: SearchRequest,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""搜索知识"""
keyword = data.query or data.keyword
if not keyword:
return {"code": 0, "data": []}
# 直接搜索(向量 + 关键词)
results = await ai_service.search_knowledge(db, user_id, keyword, limit=10)
return {
"code": 0,
"data": [
{
"id": r["id"],
"title": r["title"],
"content": r["content"],
"similarity": r.get("similarity", 0)
}
for r in results
]
}
@router.post("/{knowledge_id}/favorite")
async def toggle_favorite(
knowledge_id: int,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""收藏/取消收藏"""
result = await db.execute(
select(Knowledge).where(Knowledge.id == knowledge_id, Knowledge.user_id == user_id)
)
knowledge = result.scalar_one_or_none()
if not knowledge:
raise HTTPException(status_code=404, detail="知识不存在")
new_status = 0 if knowledge.is_favorite else 1
await db.execute(
update(Knowledge).where(Knowledge.id == knowledge_id).values(is_favorite=new_status)
)
await db.commit()
return {"code": 0, "data": {"is_favorite": new_status}}
@router.post("/from-chat")
async def create_from_chat(
data: KnowledgeCreate,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""从聊天创建知识"""
data.source = "chat"
return await create_knowledge(data, user_id, db)
|
2201_75827989/zhi_shi_ku
|
server/app/api/knowledge.py
|
Python
|
unknown
| 7,586
|
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional
import json
import uuid
import psutil
import os
from datetime import datetime
from app.core.redis import redis_client
from app.core.security import get_current_user_id
from app.core.security_middleware import (
get_security_events, get_security_stats,
get_blacklist, add_to_blacklist, remove_from_blacklist
)
router = APIRouter()
# 系统日志存储(内存中,重启后清空)
system_logs = []
system_errors = []
MAX_LOGS = 500
LIST_LIMIT = 200
class MonitorMessage(BaseModel):
source: str
content: str
status: Optional[str] = "pending" # pending/saved/ignored
time: Optional[str] = None
class UpdateStatus(BaseModel):
status: str
def _key(user_id: int) -> str:
return f"monitor:messages:{user_id}"
@router.get("/messages")
async def get_messages(user_id: int = Depends(get_current_user_id)):
key = _key(user_id)
data = await redis_client.lrange(key, 0, LIST_LIMIT - 1)
items = []
for item in data:
try:
items.append(json.loads(item))
except Exception:
continue
return {"code": 0, "data": items}
@router.post("/messages")
async def add_message(
message: MonitorMessage,
user_id: int = Depends(get_current_user_id),
):
key = _key(user_id)
item = {
"id": str(uuid.uuid4()),
"source": message.source,
"content": message.content,
"status": message.status or "pending",
"time": message.time or datetime.now().strftime("%H:%M")
}
await redis_client.lpush(key, json.dumps(item))
await redis_client.ltrim(key, 0, LIST_LIMIT - 1)
return {"code": 0, "data": item}
@router.put("/messages/{message_id}")
async def update_message(
message_id: str,
update: UpdateStatus,
user_id: int = Depends(get_current_user_id),
):
key = _key(user_id)
data = await redis_client.lrange(key, 0, LIST_LIMIT - 1)
updated = False
new_list = []
for raw in data:
try:
obj = json.loads(raw)
if obj.get("id") == message_id:
obj["status"] = update.status
updated = True
new_list.append(json.dumps(obj))
except Exception:
new_list.append(raw)
if updated:
if new_list:
await redis_client.delete(key)
await redis_client.lpush(key, *new_list)
return {"code": 0, "message": "updated"}
raise HTTPException(status_code=404, detail="消息不存在")
@router.post("/messages/clear")
async def clear_messages(user_id: int = Depends(get_current_user_id)):
key = _key(user_id)
await redis_client.delete(key)
return {"code": 0, "message": "cleared"}
# ============ 系统监控 API ============
def add_log(level: str, message: str):
"""添加系统日志"""
global system_logs
log = {
"level": level,
"message": message,
"time": datetime.now().strftime("%H:%M:%S")
}
system_logs.insert(0, log)
if len(system_logs) > MAX_LOGS:
system_logs = system_logs[:MAX_LOGS]
def add_error(error_type: str, message: str, stack: str = None):
"""添加异常记录"""
global system_errors
err = {
"type": error_type,
"message": message,
"stack": stack,
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
system_errors.insert(0, err)
if len(system_errors) > 100:
system_errors = system_errors[:100]
# 初始化一些默认日志
if not system_logs:
system_logs = [
{"level": "info", "message": "服务启动成功", "time": datetime.now().strftime("%H:%M:%S")},
{"level": "info", "message": "数据库连接成功", "time": datetime.now().strftime("%H:%M:%S")},
{"level": "info", "message": "Redis 连接成功", "time": datetime.now().strftime("%H:%M:%S")},
]
@router.get("/logs")
async def get_logs(page: int = 1, limit: int = 50):
"""获取系统日志"""
start = (page - 1) * limit
end = start + limit
logs = system_logs[start:end]
return {"code": 0, "data": {"logs": logs, "total": len(system_logs)}}
@router.get("/errors")
async def get_errors(limit: int = 20):
"""获取异常记录"""
errors = system_errors[:limit]
return {"code": 0, "data": {"errors": errors, "total": len(system_errors)}}
@router.get("/stats")
async def get_system_stats():
"""获取系统状态"""
try:
cpu_percent = psutil.cpu_percent(interval=0.1)
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
# 计算运行时间
import time
boot_time = psutil.boot_time()
uptime_seconds = time.time() - boot_time
days = int(uptime_seconds // 86400)
hours = int((uptime_seconds % 86400) // 3600)
if days > 0:
uptime = f"{days}天{hours}小时"
else:
uptime = f"{hours}小时"
return {
"code": 0,
"data": {
"cpu": round(cpu_percent, 1),
"memory": round(memory.percent, 1),
"disk": round(disk.percent, 1),
"uptime": uptime
}
}
except Exception as e:
return {
"code": 0,
"data": {
"cpu": 0,
"memory": 0,
"disk": 0,
"uptime": "未知"
}
}
@router.delete("/logs")
async def clear_logs():
"""清空日志"""
global system_logs
system_logs = []
return {"code": 0, "message": "日志已清空"}
# ============ 安全监控 API ============
@router.get("/security/events")
async def get_security_events_api(limit: int = 100):
"""获取安全事件"""
events = get_security_events(limit)
return {"code": 0, "data": events}
@router.get("/security/stats")
async def get_security_stats_api():
"""获取安全统计"""
stats = get_security_stats()
return {"code": 0, "data": stats}
@router.get("/security/blacklist")
async def get_blacklist_api():
"""获取IP黑名单"""
return {"code": 0, "data": get_blacklist()}
class IPRequest(BaseModel):
ip: str
@router.post("/security/blacklist")
async def add_blacklist_api(req: IPRequest):
"""添加IP到黑名单"""
add_to_blacklist(req.ip)
return {"code": 0, "message": f"IP {req.ip} 已加入黑名单"}
@router.delete("/security/blacklist/{ip}")
async def remove_blacklist_api(ip: str):
"""从黑名单移除IP"""
remove_from_blacklist(ip)
return {"code": 0, "message": f"IP {ip} 已从黑名单移除"}
|
2201_75827989/zhi_shi_ku
|
server/app/api/monitor.py
|
Python
|
unknown
| 6,723
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import Optional
from pydantic import BaseModel
import os
import uuid
import base64
from app.core.database import get_db
from app.core.security import get_current_user_id
from app.services.ai_service import ai_service
from app.services.cos_service import cos_service
from app.models.file_storage import FileStorage
router = APIRouter()
class UploadToCOSRequest(BaseModel):
"""上传到云端请求"""
file_data: str # base64 编码的文件数据
filename: str
file_type: str # image/document
description: Optional[str] = None
message_id: Optional[int] = None
UPLOAD_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "uploads")
os.makedirs(UPLOAD_DIR, exist_ok=True)
@router.post("/image")
async def upload_and_parse_image(
file: UploadFile = File(...),
prompt: str = Form(default="请描述这张图片的内容"),
user_id: int = Depends(get_current_user_id)
):
"""上传图片并用 AI 解析"""
# 检查文件类型
allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
if file.content_type not in allowed_types:
raise HTTPException(status_code=400, detail="只支持 JPG/PNG/GIF/WebP 图片")
# 读取文件内容
content = await file.read()
# 检查文件大小 (最大 10MB)
if len(content) > 10 * 1024 * 1024:
raise HTTPException(status_code=400, detail="图片不能超过 10MB")
# 转换为 base64
b64_data = base64.b64encode(content).decode('utf-8')
# 获取 MIME 类型
mime_type = file.content_type
data_url = f"data:{mime_type};base64,{b64_data}"
# 调用 AI 解析图片
result = await ai_service.parse_image(data_url, prompt)
if result.get("success"):
return {
"code": 0,
"data": {
"content": result["content"],
"model": result.get("model", ""),
"provider": result.get("provider", ""),
"input_tokens": result.get("input_tokens", 0),
"output_tokens": result.get("output_tokens", 0)
}
}
else:
return {
"code": -1,
"message": result.get("error", "图片解析失败")
}
@router.post("/file")
async def upload_and_parse_file(
file: UploadFile = File(...),
prompt: str = Form(default="请描述这个文件的内容"),
user_id: int = Depends(get_current_user_id)
):
"""上传文档并用 AI 解析 (PDF/Word/Excel)"""
# 检查文件类型
allowed_extensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']
filename = file.filename or ""
ext = os.path.splitext(filename)[1].lower()
if ext not in allowed_extensions:
raise HTTPException(status_code=400, detail="只支持 PDF/Word/Excel/PPT 文档")
# 读取文件内容
content = await file.read()
# 检查文件大小 (最大 30MB)
if len(content) > 30 * 1024 * 1024:
raise HTTPException(status_code=400, detail="文件不能超过 30MB")
# 调用文档解析
result = await ai_service.parse_document(content, filename, prompt)
if result.get("success"):
return {
"code": 0,
"data": {
"content": result["content"],
"model": result.get("model", ""),
"provider": result.get("provider", ""),
"input_tokens": result.get("input_tokens", 0),
"output_tokens": result.get("output_tokens", 0)
}
}
else:
return {
"code": -1,
"message": result.get("error", "文档解析失败")
}
@router.post("/to-cos")
async def upload_to_cos(
request: UploadToCOSRequest,
db: AsyncSession = Depends(get_db),
user_id: int = Depends(get_current_user_id)
):
"""上传文件到腾讯云 COS 并保存记录"""
try:
# 解码 base64 数据
file_data = base64.b64decode(request.file_data)
# 确定文件夹
folder = "images" if request.file_type == "image" else "files"
# 上传到 COS
result = cos_service.upload_file(
file_data=file_data,
filename=request.filename,
user_id=user_id,
folder=folder
)
if not result.get("success"):
return {"code": -1, "message": result.get("error", "上传失败")}
# 保存文件记录到数据库
ext = os.path.splitext(request.filename)[1].lower()
file_record = FileStorage(
user_id=user_id,
filename=request.filename,
file_type=request.file_type,
file_ext=ext,
file_size=result["size"],
cos_key=result["key"],
cos_url=result["url"],
message_id=request.message_id,
description=request.description,
is_permanent=1,
status=1
)
db.add(file_record)
await db.commit()
await db.refresh(file_record)
return {
"code": 0,
"data": {
"id": file_record.id,
"url": result["url"],
"filename": request.filename,
"size": result["size"]
},
"message": "上传成功"
}
except Exception as e:
return {"code": -1, "message": f"上传失败: {str(e)}"}
@router.get("/files")
async def get_user_files(
file_type: str = None,
page: int = 1,
page_size: int = 20,
db: AsyncSession = Depends(get_db),
user_id: int = Depends(get_current_user_id)
):
"""获取用户上传的文件列表"""
query = select(FileStorage).where(
FileStorage.user_id == user_id,
FileStorage.status == 1
)
if file_type:
if file_type == 'document':
# document 类型匹配所有非图片文件
query = query.where(FileStorage.file_type != 'image')
else:
query = query.where(FileStorage.file_type == file_type)
query = query.order_by(FileStorage.created_at.desc())
query = query.offset((page - 1) * page_size).limit(page_size)
result = await db.execute(query)
files = result.scalars().all()
# 如果存储桶是公有读,直接用原始 URL
# 如果是私有存储桶,需要生成签名 URL
file_list = []
for f in files:
file_list.append({
"id": f.id,
"filename": f.filename,
"file_type": f.file_type,
"file_size": f.file_size,
"url": f.cos_url, # 公有读存储桶直接用原始 URL
"cos_key": f.cos_key,
"description": f.description,
"created_at": f.created_at.isoformat() if f.created_at else None
})
return {
"code": 0,
"data": {
"list": file_list
}
}
@router.delete("/files/{file_id}")
async def delete_file(
file_id: int,
db: AsyncSession = Depends(get_db),
user_id: int = Depends(get_current_user_id)
):
"""删除文件"""
result = await db.execute(
select(FileStorage).where(
FileStorage.id == file_id,
FileStorage.user_id == user_id
)
)
file_record = result.scalar_one_or_none()
if not file_record:
return {"code": -1, "message": "文件不存在"}
# 从 COS 删除
cos_service.delete_file(file_record.cos_key)
# 标记为已删除
file_record.status = 0
await db.commit()
return {"code": 0, "message": "删除成功"}
@router.post("/file-to-cos")
async def upload_file_to_cos(
file: UploadFile = File(...),
folder: str = Form(default="uploads"),
user_id: int = Depends(get_current_user_id)
):
"""直接上传文件到 COS(头像等)"""
# 读取文件内容
content = await file.read()
# 检查文件大小 (最大 5MB)
if len(content) > 5 * 1024 * 1024:
raise HTTPException(status_code=400, detail="文件不能超过 5MB")
# 上传到 COS
result = cos_service.upload_file(content, file.filename or 'file.jpg', user_id, folder)
if not result or not result.get('success'):
raise HTTPException(status_code=500, detail="上传失败")
return {
"code": 0,
"data": {
"url": result['url'],
"filename": result.get('key', '')
}
}
|
2201_75827989/zhi_shi_ku
|
server/app/api/upload.py
|
Python
|
unknown
| 8,699
|
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from pydantic import BaseModel
from typing import Optional
from datetime import datetime, timedelta
from app.core.database import get_db
from app.core.security import verify_password, get_password_hash, create_access_token, get_current_user_id
from app.core.security_middleware import record_login_attempt, get_client_ip
from app.models.user import User
from app.models.knowledge import Knowledge
from app.models.conversation import Conversation, Message
router = APIRouter()
class UserCreate(BaseModel):
username: str
password: str
nickname: Optional[str] = None
class UserResponse(BaseModel):
id: int
username: str
nickname: Optional[str]
avatar: Optional[str]
class Config:
from_attributes = True
class StatsResponse(BaseModel):
knowledge: int
conversation: int
aiCalls: int
class AIConfigUpdate(BaseModel):
# 聊天AI
chat_provider: Optional[str] = None
chat_base_url: Optional[str] = None
chat_api_key: Optional[str] = None
chat_model: Optional[str] = None
# 联网搜索AI
search_provider: Optional[str] = None
search_base_url: Optional[str] = None
search_api_key: Optional[str] = None
search_model: Optional[str] = None
# Embedding
embedding_provider: Optional[str] = None
embedding_base_url: Optional[str] = None
embedding_api_key: Optional[str] = None
embedding_model: Optional[str] = None
embedding_dimension: Optional[int] = 1024
# 文件解析AI (qwen-doc-turbo)
file_provider: Optional[str] = None
file_base_url: Optional[str] = None
file_api_key: Optional[str] = None
file_model: Optional[str] = None
# 视觉/图片识别AI (GLM-4V-Flash / GLM-4.1V-Thinking-Flash)
vision_provider: Optional[str] = None
vision_base_url: Optional[str] = None
vision_api_key: Optional[str] = None
vision_models: Optional[str] = None # 逗号分隔的模型列表,用于轮换
# 通用设置
system_prompt: Optional[str] = None
enable_rag: Optional[bool] = True
@router.post("/register")
async def register(user: UserCreate, db: AsyncSession = Depends(get_db)):
"""用户注册"""
# 检查用户名是否存在
result = await db.execute(select(User).where(User.username == user.username))
if result.scalar_one_or_none():
raise HTTPException(status_code=400, detail="用户名已存在")
new_user = User(
username=user.username,
password_hash=get_password_hash(user.password),
nickname=user.nickname or user.username
)
db.add(new_user)
await db.commit()
await db.refresh(new_user)
return {"code": 0, "message": "注册成功", "data": {"id": new_user.id}}
@router.post("/login")
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
"""用户登录"""
ip = get_client_ip(request)
result = await db.execute(select(User).where(User.username == form_data.username))
user = result.scalar_one_or_none()
if not user or not verify_password(form_data.password, user.password_hash):
# 记录登录失败
record_login_attempt(ip, success=False)
raise HTTPException(status_code=401, detail="用户名或密码错误")
if user.status != 1:
raise HTTPException(status_code=403, detail="账号已被禁用")
# 登录成功,清除失败记录
record_login_attempt(ip, success=True)
token = create_access_token(data={"sub": str(user.id)})
return {
"code": 0,
"data": {
"access_token": token,
"token_type": "bearer",
"user": {
"id": user.id,
"username": user.username,
"nickname": user.nickname
}
}
}
@router.get("/info")
async def get_user_info(user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
"""获取用户信息"""
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
# 获取知识数量
knowledge_count = await db.scalar(
select(func.count()).select_from(Knowledge).where(Knowledge.user_id == user_id, Knowledge.status == 1)
)
return {
"code": 0,
"data": {
"id": user.id,
"username": user.username,
"name": user.nickname or user.username,
"nickname": user.nickname,
"avatar": user.avatar,
"desc": f"累计收集 {knowledge_count} 条知识"
}
}
@router.get("/stats")
async def get_stats(user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
"""获取统计数据"""
knowledge_count = await db.scalar(
select(func.count()).select_from(Knowledge).where(Knowledge.user_id == user_id, Knowledge.status == 1)
)
conversation_count = await db.scalar(
select(func.count()).select_from(Conversation).where(Conversation.user_id == user_id, Conversation.status == 1)
)
message_count = await db.scalar(
select(func.count()).select_from(Message).where(Message.user_id == user_id, Message.role == "assistant")
)
return {
"code": 0,
"data": {
"knowledge": knowledge_count or 0,
"conversation": conversation_count or 0,
"aiCalls": message_count or 0
}
}
@router.post("/ai-config")
async def save_ai_config(config: AIConfigUpdate, user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
"""保存用户 AI 配置"""
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
# 保存到用户的 settings 字段
import json
current_settings = {}
if user.settings:
try:
current_settings = json.loads(user.settings) if isinstance(user.settings, str) else user.settings
except:
current_settings = {}
current_settings['ai_config'] = config.dict()
user.settings = json.dumps(current_settings)
await db.commit()
return {"code": 0, "message": "配置已保存"}
@router.get("/ai-config")
async def get_ai_config(user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
"""获取用户 AI 配置"""
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
import json
ai_config = {}
if user.settings:
try:
settings = json.loads(user.settings) if isinstance(user.settings, str) else user.settings
ai_config = settings.get('ai_config', {})
except:
pass
return {"code": 0, "data": ai_config}
@router.get("/ai-usage")
async def get_ai_usage(
days: int = 1,
user_id: int = Depends(get_current_user_id),
db: AsyncSession = Depends(get_db)
):
"""获取AI调用使用情况(支持查询多天)"""
# 计算时间范围(naive datetime,与数据库一致)
now = datetime.utcnow()
start_date = (now - timedelta(days=days-1)).replace(hour=0, minute=0, second=0, microsecond=0)
# 总体统计
total_result = await db.execute(
select(
func.count().label("calls"),
func.coalesce(func.sum(Message.tokens_used), 0).label("tokens"),
func.coalesce(func.sum(Message.input_tokens), 0).label("input_tokens"),
func.coalesce(func.sum(Message.output_tokens), 0).label("output_tokens"),
func.coalesce(func.sum(Message.cached_tokens), 0).label("cached_tokens"),
func.coalesce(func.sum(Message.cost), 0).label("cost")
)
.where(
Message.user_id == user_id,
Message.role == "assistant",
Message.created_at >= start_date
)
)
total_row = total_result.first()
# 按模型分组统计
model_result = await db.execute(
select(
Message.model_name,
Message.provider,
func.count().label("calls"),
func.coalesce(func.sum(Message.tokens_used), 0).label("tokens"),
func.coalesce(func.sum(Message.input_tokens), 0).label("input_tokens"),
func.coalesce(func.sum(Message.output_tokens), 0).label("output_tokens"),
func.coalesce(func.sum(Message.cached_tokens), 0).label("cached_tokens"),
func.coalesce(func.sum(Message.cost), 0).label("cost")
)
.where(
Message.user_id == user_id,
Message.role == "assistant",
Message.created_at >= start_date
)
.group_by(Message.model_name, Message.provider)
.order_by(func.count().desc())
)
model_rows = model_result.fetchall()
# 构建模型列表
models = []
for row in model_rows:
model_name = row.model_name or "未知模型"
provider = row.provider or "unknown"
models.append({
"model": model_name,
"provider": provider,
"calls": row.calls or 0,
"tokens": row.tokens or 0,
"inputTokens": row.input_tokens or 0,
"outputTokens": row.output_tokens or 0,
"cachedTokens": row.cached_tokens or 0,
"cost": round((row.cost or 0) / 10000, 4) # 转换为元
})
# 如果没有数据,添加默认空项
if not models:
models = []
return {
"code": 0,
"data": {
"period": f"近{days}天" if days > 1 else "今日",
"summary": {
"calls": total_row.calls or 0,
"tokens": total_row.tokens or 0,
"inputTokens": total_row.input_tokens or 0,
"outputTokens": total_row.output_tokens or 0,
"cachedTokens": total_row.cached_tokens or 0,
"cost": round((total_row.cost or 0) / 10000, 4) # 转换为元
},
"models": models
}
}
class UpdateProfile(BaseModel):
username: Optional[str] = None
nickname: Optional[str] = None
avatar: Optional[str] = None
class Config:
extra = 'ignore' # 忽略额外字段
class ChangePassword(BaseModel):
old_password: str
new_password: str
class Config:
extra = 'ignore'
@router.post("/profile")
async def update_profile(
data: UpdateProfile,
db: AsyncSession = Depends(get_db),
user_id: int = Depends(get_current_user_id)
):
"""更新用户资料(用户名、昵称、头像)"""
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
# 修改用户名需要检查是否重复
if data.username is not None and data.username != user.username:
existing = await db.execute(select(User).where(User.username == data.username))
if existing.scalar_one_or_none():
raise HTTPException(status_code=400, detail="用户名已存在")
user.username = data.username
if data.nickname is not None:
user.nickname = data.nickname
if data.avatar is not None:
user.avatar = data.avatar
await db.commit()
return {
"code": 0,
"message": "更新成功",
"data": {
"nickname": user.nickname,
"avatar": user.avatar
}
}
@router.post("/password")
async def change_password(data: ChangePassword, user_id: int = Depends(get_current_user_id), db: AsyncSession = Depends(get_db)):
"""修改密码"""
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
# 验证旧密码
if not verify_password(data.old_password, user.password_hash):
raise HTTPException(status_code=400, detail="原密码错误")
# 检查新密码长度
if len(data.new_password) < 6:
raise HTTPException(status_code=400, detail="新密码长度至少6位")
# 更新密码
user.password_hash = get_password_hash(data.new_password)
await db.commit()
return {"code": 0, "message": "密码修改成功"}
|
2201_75827989/zhi_shi_ku
|
server/app/api/user.py
|
Python
|
unknown
| 12,942
|
from pydantic_settings import BaseSettings
from functools import lru_cache
class Settings(BaseSettings):
# 应用配置
APP_NAME: str = "知识库API"
DEBUG: bool = True
# 数据库
DATABASE_URL: str = "postgresql+asyncpg://postgres:password@localhost:5432/knowledge_db"
REDIS_URL: str = "redis://localhost:6379/0"
# JWT
SECRET_KEY: str = "your-secret-key-change-this"
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60
# 智谱AI (聊天 + Embedding + 视觉) - 免费模型
ZHIPU_API_KEY: str = ""
ZHIPU_BASE_URL: str = "https://open.bigmodel.cn/api/paas/v4"
CHAT_MODEL: str = "glm-4.5-flash"
EMBEDDING_MODEL: str = "embedding-2"
EMBEDDING_DIMENSION: int = 1024
VISION_MODELS: str = "glm-4v-flash"
# 通义千问 (联网搜索 + 文件解析)
QWEN_API_KEY: str = ""
QWEN_BASE_URL: str = "https://dashscope.aliyuncs.com/compatible-mode/v1"
QWEN_CHAT_MODEL: str = "qwen-turbo"
QWEN_DOC_MODEL: str = "qwen-doc-turbo"
# 腾讯云 COS (文件存储)
COS_SECRET_ID: str = ""
COS_SECRET_KEY: str = ""
COS_BUCKET: str = ""
COS_REGION: str = "ap-guangzhou"
class Config:
env_file = ".env"
@lru_cache()
def get_settings():
return Settings()
settings = get_settings()
|
2201_75827989/zhi_shi_ku
|
server/app/core/config.py
|
Python
|
unknown
| 1,331
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy import text
from .config import settings
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_pre_ping=True,
pool_size=10,
max_overflow=20
)
AsyncSessionLocal = async_sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False
)
Base = declarative_base()
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def init_db():
# 先尝试创建 pgvector 扩展
try:
async with engine.begin() as conn:
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
print("✅ pgvector 扩展已启用")
except Exception as e:
print(f"⚠️ pgvector 扩展未安装,向量搜索功能将不可用")
# 再创建表
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
print("✅ 数据库表创建完成")
|
2201_75827989/zhi_shi_ku
|
server/app/core/database.py
|
Python
|
unknown
| 1,140
|
import redis.asyncio as redis
import json
from typing import Optional, List
from .config import settings
class RedisClient:
def __init__(self):
self.redis = None
async def connect(self):
self.redis = redis.from_url(settings.REDIS_URL, decode_responses=True)
async def close(self):
if self.redis:
await self.redis.close()
# 会话上下文缓存
async def get_chat_context(self, user_id: int, conversation_id: int, limit: int = 10) -> List[dict]:
key = f"chat:context:{user_id}:{conversation_id}"
data = await self.redis.lrange(key, -limit, -1)
return [json.loads(item) for item in data]
async def add_chat_message(self, user_id: int, conversation_id: int, message: dict):
key = f"chat:context:{user_id}:{conversation_id}"
await self.redis.rpush(key, json.dumps(message, ensure_ascii=False))
await self.redis.ltrim(key, -20, -1) # 只保留最近20条
await self.redis.expire(key, 3600) # 1小时过期
async def clear_chat_context(self, user_id: int, conversation_id: int):
key = f"chat:context:{user_id}:{conversation_id}"
await self.redis.delete(key)
# 通用缓存
async def get(self, key: str) -> Optional[str]:
return await self.redis.get(key)
async def set(self, key: str, value: str, ex: int = 300):
await self.redis.set(key, value, ex=ex)
async def delete(self, key: str):
await self.redis.delete(key)
# 列表操作(用于监控消息)
async def lrange(self, key: str, start: int, end: int):
return await self.redis.lrange(key, start, end)
async def lpush(self, key: str, *values):
return await self.redis.lpush(key, *values)
async def ltrim(self, key: str, start: int, end: int):
return await self.redis.ltrim(key, start, end)
redis_client = RedisClient()
|
2201_75827989/zhi_shi_ku
|
server/app/core/redis.py
|
Python
|
unknown
| 1,935
|
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
import bcrypt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from .config import settings
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/user/login")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
def get_password_hash(password: str) -> str:
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
async def get_current_user_id(token: str = Depends(oauth2_scheme)) -> int:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无效的认证凭据",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
return int(user_id)
except JWTError:
raise credentials_exception
|
2201_75827989/zhi_shi_ku
|
server/app/core/security.py
|
Python
|
unknown
| 1,512
|
"""
安全中间件 - 请求频率限制、IP黑名单、安全日志
"""
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
import time
import hashlib
import logging
from typing import Dict, Tuple, List
from collections import defaultdict
from datetime import datetime
import re
# 配置安全日志
security_logger = logging.getLogger('security')
security_logger.setLevel(logging.INFO)
if not security_logger.handlers:
handler = logging.FileHandler('security.log', encoding='utf-8')
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
security_logger.addHandler(handler)
# 内存存储(生产环境建议用 Redis)
rate_limit_store: Dict[str, list] = defaultdict(list)
ip_blacklist: set = set()
login_attempts: Dict[str, Tuple[int, float]] = {} # IP -> (失败次数, 最后尝试时间)
security_events: List[Dict] = [] # 安全事件记录
# 配置
RATE_LIMIT_WINDOW = 60 # 时间窗口(秒)
RATE_LIMIT_MAX_REQUESTS = 100 # 普通接口每分钟最大请求数
RATE_LIMIT_STRICT = 10 # 敏感接口每分钟最大请求数
LOGIN_MAX_ATTEMPTS = 5 # 最大登录失败次数
LOGIN_LOCKOUT_TIME = 300 # 锁定时间(秒)
# 敏感接口(需要更严格的限制)
STRICT_RATE_LIMIT_PATHS = [
'/api/user/login',
'/api/user/register',
'/api/chat',
]
# XSS 危险模式
XSS_PATTERNS = [
r'<script[^>]*>',
r'javascript:',
r'on\w+\s*=',
r'<iframe',
r'<object',
r'<embed',
]
def get_client_ip(request: Request) -> str:
"""获取客户端真实 IP"""
# 优先从代理头获取
forwarded = request.headers.get('X-Forwarded-For')
if forwarded:
return forwarded.split(',')[0].strip()
real_ip = request.headers.get('X-Real-IP')
if real_ip:
return real_ip
return request.client.host if request.client else '127.0.0.1'
def check_rate_limit(ip: str, path: str) -> bool:
"""检查请求频率限制,返回 True 表示允许,False 表示超限"""
now = time.time()
key = f"{ip}:{path}"
# 清理过期记录
rate_limit_store[key] = [t for t in rate_limit_store[key] if now - t < RATE_LIMIT_WINDOW]
# 确定限制数量
is_strict = any(path.startswith(p) for p in STRICT_RATE_LIMIT_PATHS)
max_requests = RATE_LIMIT_STRICT if is_strict else RATE_LIMIT_MAX_REQUESTS
# 检查是否超限
if len(rate_limit_store[key]) >= max_requests:
return False
# 记录请求
rate_limit_store[key].append(now)
return True
def check_login_lockout(ip: str) -> Tuple[bool, int]:
"""检查登录锁定状态,返回 (是否锁定, 剩余锁定时间)"""
if ip not in login_attempts:
return False, 0
attempts, last_time = login_attempts[ip]
now = time.time()
# 如果超过锁定时间,重置
if now - last_time > LOGIN_LOCKOUT_TIME:
del login_attempts[ip]
return False, 0
# 如果达到最大尝试次数
if attempts >= LOGIN_MAX_ATTEMPTS:
remaining = int(LOGIN_LOCKOUT_TIME - (now - last_time))
return True, remaining
return False, 0
def record_login_attempt(ip: str, success: bool):
"""记录登录尝试"""
now = time.time()
if success:
# 登录成功,清除记录
if ip in login_attempts:
del login_attempts[ip]
log_security_event('login_success', ip, '登录成功', 'info')
else:
# 登录失败,增加计数
if ip in login_attempts:
attempts, _ = login_attempts[ip]
login_attempts[ip] = (attempts + 1, now)
if attempts + 1 >= LOGIN_MAX_ATTEMPTS:
log_security_event('login_locked', ip, f'登录失败次数过多({attempts + 1}次),已锁定', 'error')
else:
log_security_event('login_failure', ip, f'登录失败,第 {attempts + 1} 次', 'warning')
else:
login_attempts[ip] = (1, now)
log_security_event('login_failure', ip, '登录失败,第 1 次', 'warning')
def check_xss(content: str) -> bool:
"""检查是否包含 XSS 攻击模式,返回 True 表示安全"""
if not content:
return True
content_lower = content.lower()
for pattern in XSS_PATTERNS:
if re.search(pattern, content_lower, re.IGNORECASE):
return False
return True
def sanitize_input(content: str) -> str:
"""清理输入内容,移除危险字符"""
if not content:
return content
# HTML 转义
content = content.replace('<', '<').replace('>', '>')
return content
class SecurityMiddleware(BaseHTTPMiddleware):
"""安全中间件"""
async def dispatch(self, request: Request, call_next):
ip = get_client_ip(request)
path = request.url.path
# 1. 检查 IP 黑名单
if ip in ip_blacklist:
log_security_event('blacklist_block', ip, f'黑名单IP尝试访问: {path}', 'warning')
return JSONResponse(
status_code=403,
content={"code": 403, "message": "访问被拒绝"}
)
# 2. 检查请求频率
if not check_rate_limit(ip, path):
log_security_event('rate_limit', ip, f'请求频率超限: {path}', 'warning')
return JSONResponse(
status_code=429,
content={"code": 429, "message": "请求过于频繁,请稍后再试"}
)
# 3. 登录接口特殊处理
if path == '/api/user/login':
is_locked, remaining = check_login_lockout(ip)
if is_locked:
log_security_event('login_lockout', ip, f'登录锁定中,剩余 {remaining} 秒', 'warning')
return JSONResponse(
status_code=423,
content={"code": 423, "message": f"登录失败次数过多,请 {remaining} 秒后再试"}
)
# 4. 执行请求
response = await call_next(request)
# 5. 添加安全响应头
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
return response
# 工具函数:添加 IP 到黑名单
def add_to_blacklist(ip: str):
ip_blacklist.add(ip)
log_security_event('blacklist_add', ip, f'IP {ip} 已加入黑名单')
# 工具函数:从黑名单移除 IP
def remove_from_blacklist(ip: str):
ip_blacklist.discard(ip)
# 工具函数:获取当前黑名单
def get_blacklist():
return list(ip_blacklist)
# 安全事件记录
def log_security_event(event_type: str, ip: str, message: str, level: str = 'warning'):
"""记录安全事件"""
event = {
'time': datetime.now().isoformat(),
'type': event_type,
'ip': ip,
'message': message
}
security_events.append(event)
# 只保留最近 1000 条记录
if len(security_events) > 1000:
security_events.pop(0)
# 写入日志文件
if level == 'warning':
security_logger.warning(f"[{event_type}] {ip} - {message}")
elif level == 'error':
security_logger.error(f"[{event_type}] {ip} - {message}")
else:
security_logger.info(f"[{event_type}] {ip} - {message}")
# 获取安全事件
def get_security_events(limit: int = 100):
"""获取最近的安全事件"""
return security_events[-limit:][::-1]
# 获取安全统计
def get_security_stats():
"""获取安全统计信息"""
now = time.time()
# 统计最近1小时的事件
recent_events = [e for e in security_events if datetime.fromisoformat(e['time']).timestamp() > now - 3600]
stats = {
'blacklist_count': len(ip_blacklist),
'locked_ips': sum(1 for attempts, last_time in login_attempts.values() if attempts >= LOGIN_MAX_ATTEMPTS and now - last_time < LOGIN_LOCKOUT_TIME),
'recent_events': len(recent_events),
'rate_limit_hits': sum(1 for e in recent_events if e['type'] == 'rate_limit'),
'login_failures': sum(1 for e in recent_events if e['type'] == 'login_failure'),
}
return stats
|
2201_75827989/zhi_shi_ku
|
server/app/core/security_middleware.py
|
Python
|
unknown
| 8,457
|
from .user import User
from .conversation import Conversation, Message
from .knowledge import Knowledge, Category, Tag
from .file_storage import FileStorage
__all__ = ["User", "Conversation", "Message", "Knowledge", "Category", "Tag", "FileStorage"]
|
2201_75827989/zhi_shi_ku
|
server/app/models/__init__.py
|
Python
|
unknown
| 251
|
from sqlalchemy import Column, Integer, String, Text, DateTime, SmallInteger, ForeignKey, JSON
from sqlalchemy.sql import func
from app.core.database import Base
class Conversation(Base):
__tablename__ = "conversations"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
title = Column(String(255), default="新对话")
last_message = Column(Text)
message_count = Column(Integer, default=0)
status = Column(SmallInteger, default=1) # 1:正常 0:已删除
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
class Message(Base):
__tablename__ = "messages"
id = Column(Integer, primary_key=True, index=True)
conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
role = Column(String(20), nullable=False) # user/assistant/system
content = Column(Text, nullable=False)
tokens_used = Column(Integer, default=0)
input_tokens = Column(Integer, default=0) # 输入token
output_tokens = Column(Integer, default=0) # 输出token
cached_tokens = Column(Integer, default=0) # 缓存命中token
model_name = Column(String(100)) # 使用的模型名称
provider = Column(String(50)) # 服务商(zhipu/qwen/deepseek等)
cost = Column(Integer, default=0) # 成本(单位:0.0001元,即万分之一元)
extra_data = Column(JSON) # 扩展字段(引用的知识ID、AI模型信息等)
created_at = Column(DateTime, server_default=func.now(), index=True)
|
2201_75827989/zhi_shi_ku
|
server/app/models/conversation.py
|
Python
|
unknown
| 1,736
|
"""文件存储模型"""
from sqlalchemy import Column, Integer, String, Text, DateTime, SmallInteger, ForeignKey, BigInteger
from sqlalchemy.sql import func
from app.core.database import Base
class FileStorage(Base):
"""文件存储表 - 记录上传到 COS 的文件"""
__tablename__ = "file_storage"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
# 文件信息
filename = Column(String(255), nullable=False) # 原始文件名
file_type = Column(String(20), nullable=False) # image/document/other
file_ext = Column(String(10)) # 扩展名
file_size = Column(BigInteger, default=0) # 文件大小(字节)
# COS 存储信息
cos_key = Column(String(500), nullable=False, unique=True) # COS 对象键
cos_url = Column(String(1000), nullable=False) # 访问 URL
# 关联信息
message_id = Column(Integer, nullable=True) # 关联的消息ID
knowledge_id = Column(Integer, ForeignKey("knowledge.id"), nullable=True) # 关联的知识ID
# 状态
status = Column(SmallInteger, default=1) # 1:正常 0:已删除
is_permanent = Column(SmallInteger, default=1) # 1:永久 0:临时(3天清理)
# 描述(AI解析结果)
description = Column(Text)
created_at = Column(DateTime, server_default=func.now(), index=True)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
2201_75827989/zhi_shi_ku
|
server/app/models/file_storage.py
|
Python
|
unknown
| 1,502
|
from sqlalchemy import Column, Integer, String, Text, DateTime, SmallInteger, ForeignKey, JSON
from sqlalchemy.sql import func
from app.core.database import Base
from app.core.config import settings
# pgvector 向量类型
from pgvector.sqlalchemy import Vector
VECTOR_TYPE = Vector(settings.EMBEDDING_DIMENSION)
class Knowledge(Base):
__tablename__ = "knowledge"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
title = Column(String(255), nullable=False)
content = Column(Text, nullable=False)
summary = Column(Text)
source = Column(String(50), default="manual", index=True) # chat/manual/import
source_id = Column(String(100))
tags = Column(JSON, default=[])
embedding = Column(VECTOR_TYPE) # 向量(需要 pgvector 扩展)
token_count = Column(Integer, default=0)
view_count = Column(Integer, default=0)
is_favorite = Column(SmallInteger, default=0) # 收藏
status = Column(SmallInteger, default=1) # 1:正常 0:已删除
created_at = Column(DateTime, server_default=func.now(), index=True)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
class Category(Base):
__tablename__ = "categories"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
name = Column(String(50), nullable=False)
icon = Column(String(20), default="folder")
color = Column(String(20), default="#07C160")
count = Column(Integer, default=0)
sort_order = Column(Integer, default=0)
created_at = Column(DateTime, server_default=func.now())
class Tag(Base):
__tablename__ = "tags"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
name = Column(String(50), nullable=False)
count = Column(Integer, default=0)
created_at = Column(DateTime, server_default=func.now())
|
2201_75827989/zhi_shi_ku
|
server/app/models/knowledge.py
|
Python
|
unknown
| 2,133
|
from sqlalchemy import Column, Integer, String, DateTime, SmallInteger, Text
from sqlalchemy.sql import func
from app.core.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String(64), unique=True, nullable=False, index=True)
password_hash = Column(String(255), nullable=False)
nickname = Column(String(64))
avatar = Column(String(255))
phone = Column(String(20), index=True)
email = Column(String(100))
settings = Column(Text) # JSON 格式存储用户设置(包括 AI 配置)
status = Column(SmallInteger, default=1) # 1:正常 0:禁用
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
2201_75827989/zhi_shi_ku
|
server/app/models/user.py
|
Python
|
unknown
| 817
|
from typing import List, Optional, Dict, Any
from openai import AsyncOpenAI
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, text
from app.core.config import settings
from app.core.redis import redis_client
from app.models.knowledge import Knowledge
from app.models.user import User
from app.services.web_scraper import web_scraper
import json
import httpx
import base64
import re
class AIService:
def __init__(self):
# 默认客户端 - 智谱AI(普通聊天 + Embedding + 视觉)
self.client = AsyncOpenAI(
api_key=settings.ZHIPU_API_KEY,
base_url=settings.ZHIPU_BASE_URL
)
# 默认客户端 - 通义千问(联网搜索 + 文件解析)
self.qwen_client = AsyncOpenAI(
api_key=settings.QWEN_API_KEY,
base_url=settings.QWEN_BASE_URL
)
# 视觉模型列表(轮换使用)
self.vision_models = settings.VISION_MODELS.split(',')
self.vision_model_index = 0
def get_next_vision_model(self) -> str:
"""获取下一个视觉模型(轮换)"""
model = self.vision_models[self.vision_model_index]
self.vision_model_index = (self.vision_model_index + 1) % len(self.vision_models)
return model
async def get_user_ai_config(self, db: AsyncSession, user_id: int) -> Dict[str, Any]:
"""获取用户AI配置"""
try:
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if user and user.settings:
settings_data = json.loads(user.settings) if isinstance(user.settings, str) else user.settings
return settings_data.get('ai_config', {})
except Exception as e:
print(f"获取用户配置失败: {e}")
return {}
def get_client(self, base_url: str, api_key: str) -> AsyncOpenAI:
"""根据配置创建客户端"""
return AsyncOpenAI(api_key=api_key, base_url=base_url)
def calculate_cost(self, provider: str, model: str, input_tokens: int, output_tokens: int, cached_tokens: int = 0) -> int:
"""计算成本(返回单位:万分之一元)
价格表(每百万token):
- 智谱 glm-4.5-flash: 免费
- 智谱 glm-4-flash: 免费
- 智谱 embedding-2: 0.5元/M
- 通义 qwen-turbo: 输入0.3元/M 输出0.6元/M 缓存0.06元/M
- 通义 qwen-flash: 输入0.15元/M 输出1.5元/M
- DeepSeek chat: 输入1元/M 输出2元/M 缓存0.1元/M
"""
# 价格配置(单位:元/百万token)
PRICES = {
'zhipu': {
'glm-4.5-flash': {'input': 0, 'output': 0, 'cached': 0},
'glm-4-flash': {'input': 0, 'output': 0, 'cached': 0},
'glm-4-flash-250414': {'input': 0, 'output': 0, 'cached': 0},
'glm-4v-flash': {'input': 0, 'output': 0, 'cached': 0},
'glm-4.1v-thinking-flash': {'input': 0, 'output': 0, 'cached': 0},
'embedding-2': {'input': 0.5, 'output': 0, 'cached': 0},
'default': {'input': 0, 'output': 0, 'cached': 0}
},
'qwen': {
'qwen-turbo': {'input': 0.3, 'output': 0.6, 'cached': 0.06},
'qwen-flash': {'input': 0.15, 'output': 1.5, 'cached': 0.03},
'qwen-plus': {'input': 0.8, 'output': 2, 'cached': 0.16},
'qwen-max': {'input': 2, 'output': 6, 'cached': 0.4},
'qwen-doc-turbo': {'input': 0.6, 'output': 1, 'cached': 0},
'qwen-long': {'input': 0.5, 'output': 2, 'cached': 0},
'qwen-vl-plus': {'input': 1.5, 'output': 1.5, 'cached': 0},
'qwen-vl-max': {'input': 3, 'output': 3, 'cached': 0},
'text-embedding-v3': {'input': 0.7, 'output': 0, 'cached': 0},
'default': {'input': 0.3, 'output': 0.6, 'cached': 0.06}
},
'deepseek': {
'deepseek-chat': {'input': 1, 'output': 2, 'cached': 0.1},
'deepseek-reasoner': {'input': 4, 'output': 16, 'cached': 0.4},
'default': {'input': 1, 'output': 2, 'cached': 0.1}
},
'openai': {
'gpt-4o-mini': {'input': 1.1, 'output': 4.4, 'cached': 0.55},
'gpt-4o': {'input': 18, 'output': 72, 'cached': 9},
'text-embedding-3-small': {'input': 0.15, 'output': 0, 'cached': 0},
'default': {'input': 1.1, 'output': 4.4, 'cached': 0.55}
},
'kimi': {
'moonshot-v1-auto': {'input': 0, 'output': 0, 'cached': 0}, # 限时免费
'default': {'input': 12, 'output': 12, 'cached': 0}
}
}
# 获取价格
provider_prices = PRICES.get(provider, PRICES.get('zhipu'))
model_price = provider_prices.get(model, provider_prices.get('default'))
# 计算非缓存的输入token
non_cached_input = max(0, input_tokens - cached_tokens)
# 计算成本(元)
cost_yuan = (
non_cached_input * model_price['input'] / 1000000 +
output_tokens * model_price['output'] / 1000000 +
cached_tokens * model_price['cached'] / 1000000
)
# 转换为万分之一元(保留精度)
return int(cost_yuan * 10000)
async def get_embedding(self, text: str, user_config: Dict[str, Any] = None) -> Optional[List[float]]:
"""获取文本的向量表示"""
try:
# 使用用户配置或默认配置
if user_config and user_config.get('embedding_api_key'):
client = self.get_client(
user_config.get('embedding_base_url', settings.ZHIPU_BASE_URL),
user_config.get('embedding_api_key')
)
model = user_config.get('embedding_model', settings.EMBEDDING_MODEL)
else:
client = self.client
model = settings.EMBEDDING_MODEL
response = await client.embeddings.create(
model=model,
input=text
)
return response.data[0].embedding
except Exception as e:
print(f"Embedding API 错误: {e}")
return None
async def search_knowledge(
self,
db: AsyncSession,
user_id: int,
query: str,
limit: int = 5
) -> List[dict]:
"""搜索知识库(向量搜索 + 关键词搜索)"""
results = []
# 尝试向量搜索
query_embedding = await self.get_embedding(query)
if query_embedding is not None:
try:
embedding_str = '[' + ','.join(map(str, query_embedding)) + ']'
sql = text("""
SELECT id, title, content, summary, tags,
1 - (embedding <=> cast(:embedding as vector)) as similarity
FROM knowledge
WHERE user_id = :user_id AND status = 1 AND embedding IS NOT NULL
ORDER BY embedding <=> cast(:embedding as vector)
LIMIT :limit
""")
result = await db.execute(sql, {
"embedding": embedding_str,
"user_id": user_id,
"limit": limit
})
rows = result.fetchall()
for row in rows:
if row.similarity > 0.7:
results.append({
"id": row.id,
"title": row.title,
"content": row.content,
"similarity": round(row.similarity, 3)
})
except Exception as e:
print(f"向量搜索失败: {e}")
await db.rollback()
# 关键词搜索作为补充
if len(results) < limit:
try:
# 提取关键词
keywords = [w for w in query.replace('?', '').replace('?', '').split() if len(w) >= 2]
if not keywords:
keywords = [query[:10]]
keyword_sql = text("""
SELECT id, title, content, summary, tags
FROM knowledge
WHERE user_id = :user_id AND status = 1
AND (title ILIKE :kw OR content ILIKE :kw)
LIMIT :limit
""")
for kw in keywords[:3]:
result = await db.execute(keyword_sql, {
"user_id": user_id,
"kw": f"%{kw}%",
"limit": limit
})
rows = result.fetchall()
for row in rows:
if not any(r["id"] == row.id for r in results):
results.append({
"id": row.id,
"title": row.title,
"content": row.content,
"similarity": 0.8
})
except Exception as e:
print(f"关键词搜索失败: {e}")
await db.rollback()
return results[:limit]
async def chat(
self,
db: AsyncSession,
user_id: int,
conversation_id: int,
message: str,
use_knowledge: bool = False,
web_search: bool = False
) -> dict:
"""AI对话(带知识库RAG + 可选联网搜索 + 网页抓取)"""
# 获取用户AI配置
user_config = await self.get_user_ai_config(db, user_id)
# 0. 检测是否包含URL,如果有则抓取网页内容
url = web_scraper.extract_url(message)
web_content = ""
if url:
print(f"[DEBUG] 检测到URL: {url}")
result = await web_scraper.fetch_url(url)
print(f"[DEBUG] 抓取结果: success={result['success']}, title={result.get('title', '')}, content_len={len(result.get('content', ''))}")
if result['success']:
web_content = f"\n\n【网页内容】\n标题: {result['title']}\n网址: {result['url']}\n\n{result['content']}"
print(f"[DEBUG] web_content 长度: {len(web_content)}")
# 检查是否包含免费模型关键词
if 'GLM-4.5-Flash' in result.get('content', ''):
print("[DEBUG] ✅ 内容包含 GLM-4.5-Flash")
else:
print("[DEBUG] ❌ 内容不包含 GLM-4.5-Flash")
else:
web_content = f"\n\n【网页抓取失败】{result['error']}"
print(f"[DEBUG] 抓取失败: {result['error']}")
# 1. 获取聊天上下文
context_messages = await redis_client.get_chat_context(user_id, conversation_id)
# 2. 检索知识库
references = []
knowledge_context = ""
should_search = False
# 检测是否包含查找关键词
search_keywords = ['查找', '查一下', '帮我查', '搜索', '搜一下', '找一下', '找找', '查询', '检索', '有没有保存', '保存过']
has_search_keyword = any(kw in message for kw in search_keywords)
if not web_search and not url:
if use_knowledge:
# 用户点了知识库按钮 → 强制检索
should_search = True
elif user_config.get('enable_rag', False) and has_search_keyword:
# 开启了自动检索 + 包含查找关键词 → 检索
should_search = True
if should_search:
try:
references = await self.search_knowledge(db, user_id, message)
if references:
knowledge_context = "\n\n相关知识参考:\n" + "\n".join([
f"- {ref['title']}: {ref['content']}"
for ref in references[:3]
])
except Exception as e:
print(f"知识库检索失败: {e}")
# 3. 构建消息
if url and web_content:
# 预处理:提取免费模型信息
free_models_hint = ""
if '免费' in message or 'free' in message.lower():
# 查找所有包含"免费模型"的行
lines = web_content.split('\n')
free_models = []
for line in lines:
if '免费模型' in line and '|' in line:
# 提取模型名称
match = re.search(r'\[([^\]]+)\]', line)
if match:
free_models.append(match.group(1))
if free_models:
free_models_hint = f"\n\n=== 免费模型列表(已从网页提取)===\n" + "\n".join([f"• {m}" for m in free_models]) + "\n=== 以上是免费模型 ==="
print(f"[DEBUG] 提取到免费模型: {free_models}")
# 如果提取到了免费模型,直接告诉 AI 答案
if free_models_hint:
system_prompt = f"""你是一个智能助手。用户问的是免费模型,我已经从网页中提取出来了:
{free_models_hint}
请直接把上面的免费模型列表告诉用户,并简单介绍每个模型的用途。"""
else:
system_prompt = f"""你是一个智能助手。我已经抓取了用户发送的网页内容:
{web_content}
请根据上述内容回答用户的问题。直接给出答案,不要说"没有找到"或"建议访问网页"。"""
elif web_search:
system_prompt = "你是一个智能助手,可以联网搜索最新信息来回答用户问题。请根据搜索结果给出准确、有用的回答。"
elif message.startswith("[转发的聊天记录]"):
# 处理转发的聊天记录
system_prompt = """你是用户的私人AI助手。用户转发了一段聊天记录给你。
请仔细阅读这段聊天记录,然后询问用户需要什么帮助:
- 总结这段对话的主要内容
- 分析对话中提到的关键信息
- 保存到知识库
- 回答关于这段对话的问题
- 继续聊这个话题
请先简要说明你看到了什么内容,然后询问用户需要你做什么。"""
else:
if should_search and knowledge_context:
# 开启了知识库模式,且找到了内容
system_prompt = f"""你是用户的私人AI助手。我从知识库中搜索到以下内容:
{knowledge_context}
请直接把找到的内容告诉用户。"""
elif should_search and not knowledge_context:
# 开启了知识库模式,但没有找到
system_prompt = """你是用户的私人AI助手。当前开启了知识库检索模式,但没有找到相关记录。
请告诉用户"知识库中暂无此记录",建议用户可以先保存相关内容,或者关闭知识库模式进行普通对话。"""
else:
# 普通聊天模式
system_prompt = """你是用户的私人AI助手。你可以:
1. 回答问题、聊天
2. 帮用户保存信息到知识库(用户说"帮我保存:xxx")
3. 分析用户上传的文件
如果用户想查找知识库内容,需要先点击"知识库"按钮开启检索模式。
请根据对话历史给出有帮助的回答。"""
messages = [
{"role": "system", "content": system_prompt}
]
# 添加历史上下文
for ctx in context_messages[-6:]:
messages.append({"role": ctx["role"], "content": ctx["content"]})
# 添加当前消息
messages.append({"role": "user", "content": message})
# 4. 调用AI(优先使用用户配置)
if web_search:
# 联网搜索
if user_config.get('search_api_key'):
search_client = self.get_client(
user_config.get('search_base_url', settings.QWEN_BASE_URL),
user_config.get('search_api_key')
)
search_model = user_config.get('search_model', settings.QWEN_CHAT_MODEL)
else:
search_client = self.qwen_client
search_model = settings.QWEN_CHAT_MODEL
response = await search_client.chat.completions.create(
model=search_model,
messages=messages,
extra_body={"enable_search": True},
temperature=0.7,
max_tokens=2000
)
else:
# 普通聊天
if user_config.get('chat_api_key'):
chat_client = self.get_client(
user_config.get('chat_base_url', settings.ZHIPU_BASE_URL),
user_config.get('chat_api_key')
)
chat_model = user_config.get('chat_model', settings.CHAT_MODEL)
else:
chat_client = self.client
chat_model = settings.CHAT_MODEL
response = await chat_client.chat.completions.create(
model=chat_model,
messages=messages,
temperature=0.7,
max_tokens=2000
)
reply = response.choices[0].message.content
# 解析token使用详情
usage = response.usage
tokens_used = usage.total_tokens if usage else 0
input_tokens = usage.prompt_tokens if usage else 0
output_tokens = usage.completion_tokens if usage else 0
# 解析缓存命中(不同服务商格式不同)
cached_tokens = 0
if usage:
# 通义千问格式
if hasattr(usage, 'prompt_tokens_details') and usage.prompt_tokens_details:
cached_tokens = getattr(usage.prompt_tokens_details, 'cached_tokens', 0) or 0
# 智谱AI格式 - prompt_cache
elif hasattr(usage, 'prompt_cache'):
cached_tokens = getattr(usage, 'prompt_cache', 0) or 0
# 确定使用的模型和服务商
if web_search:
used_model = search_model
used_provider = 'qwen'
else:
used_model = chat_model
used_provider = 'zhipu'
# 计算成本(单位:万分之一元)
cost = self.calculate_cost(used_provider, used_model, input_tokens, output_tokens, cached_tokens)
# 5. 缓存到Redis
await redis_client.add_chat_message(user_id, conversation_id, {
"role": "user",
"content": message
})
await redis_client.add_chat_message(user_id, conversation_id, {
"role": "assistant",
"content": reply
})
return {
"reply": reply,
"references": references,
"tokens_used": tokens_used,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cached_tokens": cached_tokens,
"model_name": used_model,
"provider": used_provider,
"cost": cost
}
async def summarize(self, content: str) -> dict:
"""AI总结内容"""
response = await self.client.chat.completions.create(
model=settings.CHAT_MODEL,
messages=[
{
"role": "system",
"content": "你是一个内容总结专家。请为以下内容生成一个简洁的标题(不超过20字)和摘要(不超过100字)。以JSON格式返回:{\"title\": \"标题\", \"summary\": \"摘要\"}"
},
{"role": "user", "content": content}
],
temperature=0.3
)
import json
try:
result = json.loads(response.choices[0].message.content)
return result
except:
return {"title": content[:20], "summary": content[:100]}
async def generate_tags(self, content: str) -> List[str]:
"""AI生成标签"""
response = await self.chat_client.chat.completions.create(
model=settings.CHAT_MODEL,
messages=[
{
"role": "system",
"content": "你是一个内容分析专家。请为以下内容生成3-5个相关标签,以JSON数组格式返回,如:[\"标签1\", \"标签2\"]"
},
{"role": "user", "content": content}
],
temperature=0.3
)
import json
try:
tags = json.loads(response.choices[0].message.content)
return tags[:5]
except:
return []
async def parse_file(self, file_url: str, prompt: str = "描述这个文件的内容") -> dict:
"""使用 Qwen-Doc-Turbo 解析文件(图片/PDF/Word/Excel)
需要使用 DashScope 原生协议
"""
try:
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
"https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
headers={
"Authorization": f"Bearer {settings.QWEN_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": settings.QWEN_DOC_MODEL,
"input": {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "doc_url", "doc_url": [file_url]}
]
}
]
}
}
)
result = response.json()
if "output" in result and "choices" in result["output"]:
content = result["output"]["choices"][0]["message"]["content"]
usage = result.get("usage", {})
return {
"success": True,
"content": content,
"input_tokens": usage.get("input_tokens", 0),
"output_tokens": usage.get("output_tokens", 0),
"model": settings.QWEN_DOC_MODEL,
"provider": "qwen"
}
else:
error_msg = result.get("message", "未知错误")
return {"success": False, "error": error_msg}
except Exception as e:
return {"success": False, "error": str(e)}
async def parse_file_base64(self, file_data: bytes, file_type: str, prompt: str = "描述这个文件的内容") -> dict:
"""使用 base64 编码解析本地文件"""
try:
# 转换为 base64
b64_data = base64.b64encode(file_data).decode('utf-8')
# 根据文件类型构建 data URL
mime_types = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'pdf': 'application/pdf',
'doc': 'application/msword',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xls': 'application/vnd.ms-excel',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
mime_type = mime_types.get(file_type.lower(), 'application/octet-stream')
data_url = f"data:{mime_type};base64,{b64_data}"
# 对于图片,可以用 image_url 方式
if file_type.lower() in ['jpg', 'jpeg', 'png', 'gif']:
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
headers={
"Authorization": f"Bearer {settings.QWEN_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "qwen-vl-plus",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": data_url}}
]
}
]
}
)
result = response.json()
if "choices" in result:
return {
"success": True,
"content": result["choices"][0]["message"]["content"],
"model": "qwen-vl-plus",
"provider": "qwen"
}
else:
return {"success": False, "error": result.get("error", {}).get("message", "未知错误")}
else:
# 非图片文件暂不支持 base64 方式,需要先上传
return {"success": False, "error": "非图片文件请先上传到服务器获取URL"}
except Exception as e:
return {"success": False, "error": str(e)}
async def parse_document(self, file_data: bytes, filename: str, prompt: str = "请描述这个文件的内容") -> dict:
"""使用 qwen-doc-turbo 解析文档(支持 PDF/Word/Excel/PPT/图片)
步骤:1. 通过 OpenAI 兼容接口上传文件获取 file_id 2. 调用 qwen-doc-turbo 解析
"""
try:
async with httpx.AsyncClient(timeout=120.0) as client:
# 步骤1:通过 OpenAI 兼容接口上传文件
upload_response = await client.post(
"https://dashscope.aliyuncs.com/compatible-mode/v1/files",
headers={
"Authorization": f"Bearer {settings.QWEN_API_KEY}"
},
files={
"file": (filename, file_data),
},
data={
"purpose": "file-extract"
}
)
upload_result = upload_response.json()
# OpenAI 兼容接口返回格式:{"id": "file-xxx", "object": "file", ...}
file_id = upload_result.get("id")
if not file_id:
error_msg = upload_result.get("error", {}).get("message", "文件上传失败")
return {"success": False, "error": error_msg}
# 步骤2:等待文件解析完成后调用 qwen-doc-turbo (OpenAI 兼容接口)
import asyncio
max_retries = 5
for retry in range(max_retries):
response = await client.post(
"https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
headers={
"Authorization": f"Bearer {settings.QWEN_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "qwen-doc-turbo",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "system", "content": f"fileid://{file_id}"},
{"role": "user", "content": prompt}
]
}
)
result = response.json()
# 检查是否文件还在解析中
error_msg = result.get("error", {}).get("message", "")
if "File parsing in progress" in error_msg:
await asyncio.sleep(2)
continue
if "choices" in result:
usage = result.get("usage", {})
return {
"success": True,
"content": result["choices"][0]["message"]["content"],
"model": "qwen-doc-turbo",
"provider": "qwen",
"input_tokens": usage.get("prompt_tokens", 0),
"output_tokens": usage.get("completion_tokens", 0)
}
else:
return {"success": False, "error": error_msg or "文档解析失败"}
return {"success": False, "error": "文件解析超时,请稍后重试"}
except Exception as e:
return {"success": False, "error": str(e)}
async def parse_image(self, image_data_url: str, prompt: str = "请描述这张图片的内容") -> dict:
"""使用智谱 GLM 视觉模型解析图片(GLM-4V-Flash / GLM-4.1V-Thinking-Flash 轮换)"""
try:
# 获取下一个视觉模型
vision_model = self.get_next_vision_model()
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
f"{settings.ZHIPU_BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {settings.ZHIPU_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": vision_model,
"messages": [
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": image_data_url}},
{"type": "text", "text": prompt}
]
}
],
"max_tokens": 2000
}
)
result = response.json()
print(f"[DEBUG] 图片解析API响应 model={vision_model}: {result}")
if "choices" in result:
usage = result.get("usage", {})
return {
"success": True,
"content": result["choices"][0]["message"]["content"],
"model": vision_model,
"provider": "zhipu",
"input_tokens": usage.get("prompt_tokens", 0),
"output_tokens": usage.get("completion_tokens", 0)
}
else:
error_msg = result.get("error", {}).get("message", "图片解析失败")
print(f"[ERROR] 图片解析失败: {result}")
return {"success": False, "error": f"图片解析失败: {error_msg}"}
except Exception as e:
print(f"[ERROR] 图片解析异常: {e}")
return {"success": False, "error": str(e)}
async def parse_image_with_model(self, image_data_url: str, prompt: str, model: str = None) -> dict:
"""使用指定的视觉模型解析图片"""
try:
vision_model = model or self.get_next_vision_model()
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.post(
f"{settings.ZHIPU_BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {settings.ZHIPU_API_KEY}",
"Content-Type": "application/json"
},
json={
"model": vision_model,
"messages": [
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": image_data_url}},
{"type": "text", "text": prompt}
]
}
],
"max_tokens": 2000
}
)
result = response.json()
if "choices" in result:
usage = result.get("usage", {})
return {
"success": True,
"content": result["choices"][0]["message"]["content"],
"model": vision_model,
"provider": "zhipu",
"input_tokens": usage.get("prompt_tokens", 0),
"output_tokens": usage.get("completion_tokens", 0)
}
else:
error_msg = result.get("error", {}).get("message", "图片解析失败")
return {"success": False, "error": error_msg}
except Exception as e:
return {"success": False, "error": str(e)}
ai_service = AIService()
|
2201_75827989/zhi_shi_ku
|
server/app/services/ai_service.py
|
Python
|
unknown
| 34,817
|
"""腾讯云 COS 文件存储服务"""
from qcloud_cos import CosConfig, CosS3Client
from app.core.config import settings
import uuid
from datetime import datetime
import os
class COSService:
def __init__(self):
config = CosConfig(
Region=settings.COS_REGION,
SecretId=settings.COS_SECRET_ID,
SecretKey=settings.COS_SECRET_KEY,
)
self.client = CosS3Client(config)
self.bucket = settings.COS_BUCKET
self.base_url = f"https://{settings.COS_BUCKET}.cos.{settings.COS_REGION}.myqcloud.com"
def upload_file(self, file_data: bytes, filename: str, user_id: int, folder: str = "files") -> dict:
"""上传文件到 COS
Args:
file_data: 文件二进制数据
filename: 原始文件名
user_id: 用户ID
folder: 存储文件夹 (files/images)
Returns:
{"success": True, "url": "...", "key": "..."}
"""
try:
# 生成唯一文件名
ext = os.path.splitext(filename)[1].lower()
date_path = datetime.now().strftime("%Y/%m/%d")
unique_name = f"{uuid.uuid4().hex}{ext}"
key = f"{folder}/user_{user_id}/{date_path}/{unique_name}"
# 上传到 COS
self.client.put_object(
Bucket=self.bucket,
Body=file_data,
Key=key,
ContentType=self._get_content_type(ext)
)
# 返回访问 URL
url = f"{self.base_url}/{key}"
return {
"success": True,
"url": url,
"key": key,
"filename": filename,
"size": len(file_data)
}
except Exception as e:
return {"success": False, "error": str(e)}
def delete_file(self, key: str) -> bool:
"""删除 COS 文件"""
try:
self.client.delete_object(
Bucket=self.bucket,
Key=key
)
return True
except Exception:
return False
def get_presigned_url(self, key: str, expires: int = 3600) -> str:
"""获取临时下载 URL(私有读取时使用)"""
try:
url = self.client.get_presigned_download_url(
Bucket=self.bucket,
Key=key,
Expired=expires
)
return url
except Exception:
return ""
def _get_content_type(self, ext: str) -> str:
"""根据扩展名获取 Content-Type"""
content_types = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.bmp': 'image/bmp',
'.webp': 'image/webp',
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.ppt': 'application/vnd.ms-powerpoint',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'.txt': 'text/plain',
'.md': 'text/markdown',
}
return content_types.get(ext, 'application/octet-stream')
cos_service = COSService()
|
2201_75827989/zhi_shi_ku
|
server/app/services/cos_service.py
|
Python
|
unknown
| 3,554
|
import re
import httpx
from bs4 import BeautifulSoup
from typing import Optional, Dict
from urllib.parse import urlparse
class WebScraper:
"""网页抓取服务"""
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
}
self.timeout = 15.0
@staticmethod
def is_valid_url(text: str) -> bool:
"""检查是否为有效URL"""
url_pattern = re.compile(
r'^https?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|'
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return bool(url_pattern.match(text.strip()))
@staticmethod
def extract_url(text: str) -> Optional[str]:
"""从文本中提取URL"""
# 更完善的URL匹配,支持路径中的各种字符
url_pattern = re.compile(
r'https?://'
r'[^\s<>\"\'\u4e00-\u9fff]+', # 匹配到空格、引号或中文前
re.IGNORECASE)
match = url_pattern.search(text)
if match:
url = match.group(0)
# 清理末尾可能的标点符号
url = url.rstrip('.,;:!?')
return url
return None
async def fetch_url(self, url: str) -> Dict:
"""抓取网页内容(使用 Jina Reader API 支持 JS 渲染)"""
try:
# 优先使用 Jina Reader API(支持 JS 渲染,免费)
jina_url = f"https://r.jina.ai/{url}"
async with httpx.AsyncClient(
timeout=30.0,
follow_redirects=True
) as client:
response = await client.get(jina_url)
if response.status_code == 200:
content = response.text
# 解析 Jina 返回的 Markdown 格式
lines = content.split('\n')
title = ""
body_lines = []
in_content = False
for line in lines:
if line.startswith('Title:'):
title = line[6:].strip()
elif line.startswith('Markdown Content:'):
in_content = True
elif in_content:
body_lines.append(line)
body = '\n'.join(body_lines).strip()
if len(body) > 8000:
body = body[:8000] + "\n\n[内容已截断...]"
return {
'success': True,
'title': title,
'url': url,
'content': body
}
# Jina 失败则回退到原始方法
return await self._fetch_url_fallback(url)
except Exception as e:
# 出错时回退到原始方法
return await self._fetch_url_fallback(url)
async def _fetch_url_fallback(self, url: str) -> Dict:
"""回退:直接抓取网页"""
try:
async with httpx.AsyncClient(
headers=self.headers,
timeout=self.timeout,
follow_redirects=True
) as client:
response = await client.get(url)
response.raise_for_status()
content_type = response.headers.get('content-type', '')
if 'text/html' not in content_type and 'text/plain' not in content_type:
return {
'success': False,
'error': f'不支持的内容类型: {content_type}'
}
html = response.text
return self._parse_html(html, url)
except httpx.TimeoutException:
return {'success': False, 'error': '请求超时'}
except httpx.HTTPStatusError as e:
return {'success': False, 'error': f'HTTP错误: {e.response.status_code}'}
except Exception as e:
return {'success': False, 'error': f'抓取失败: {str(e)}'}
def _parse_html(self, html: str, url: str) -> Dict:
"""解析HTML内容"""
soup = BeautifulSoup(html, 'html.parser')
# 移除脚本和样式
for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside', 'noscript', 'iframe']):
tag.decompose()
# 获取标题
title = ''
if soup.title:
title = soup.title.string or ''
if not title:
h1 = soup.find('h1')
if h1:
title = h1.get_text(strip=True)
# 获取正文内容
content = ''
# 尝试找到主要内容区域
main_content = (
soup.find('article') or
soup.find('main') or
soup.find(class_=re.compile(r'(content|article|post|entry|main)', re.I)) or
soup.find(id=re.compile(r'(content|article|post|entry|main)', re.I)) or
soup.body
)
if main_content:
# 获取所有段落文本
paragraphs = main_content.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'li', 'td', 'th', 'span', 'div'])
texts = []
for p in paragraphs:
text = p.get_text(strip=True)
if text and len(text) > 10:
texts.append(text)
content = '\n\n'.join(texts)
if not content:
content = soup.get_text(separator='\n', strip=True)
# 清理内容
content = re.sub(r'\n{3,}', '\n\n', content)
content = re.sub(r' {2,}', ' ', content)
# 限制长度(避免token过多)
max_length = 8000
if len(content) > max_length:
content = content[:max_length] + '\n\n[内容已截断...]'
# 获取域名
domain = urlparse(url).netloc
return {
'success': True,
'url': url,
'domain': domain,
'title': title.strip(),
'content': content.strip(),
'length': len(content)
}
web_scraper = WebScraper()
|
2201_75827989/zhi_shi_ku
|
server/app/services/web_scraper.py
|
Python
|
unknown
| 6,738
|
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import os
from app.core.config import settings
from app.core.database import init_db
from app.core.redis import redis_client
from app.core.security_middleware import SecurityMiddleware
from app.api import api_router
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时
await redis_client.connect()
await init_db()
print("✅ 数据库和Redis连接成功")
print("🛡️ 安全防护已启用")
yield
# 关闭时
await redis_client.close()
print("👋 服务已关闭")
app = FastAPI(
title=settings.APP_NAME,
description="知识库API - 支持AI对话、知识检索、智能总结",
version="1.0.0",
lifespan=lifespan
)
# 安全中间件(放在 CORS 之前)
app.add_middleware(SecurityMiddleware)
# CORS配置(生产环境请配置具体域名)
ALLOWED_ORIGINS = os.getenv('ALLOWED_ORIGINS', '*').split(',')
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS if ALLOWED_ORIGINS != ['*'] else ["*"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"],
)
# 验证错误处理器(打印详细错误)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
print(f"[VALIDATION ERROR] URL: {request.url}")
print(f"[VALIDATION ERROR] Errors: {exc.errors()}")
return JSONResponse(
status_code=422,
content={"detail": exc.errors()}
)
# 注册路由
app.include_router(api_router, prefix="/api")
@app.get("/")
async def root():
return {
"name": settings.APP_NAME,
"version": "1.0.0",
"docs": "/docs"
}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=3000, reload=True)
|
2201_75827989/zhi_shi_ku
|
server/main.py
|
Python
|
unknown
| 2,117
|
/**
* 这里是uni-app内置的常用样式变量
*
* uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
* 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
*
*/
/**
* 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能
*
* 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件
*/
/* 颜色变量 - Modern Enterprise SaaS */
/* 主色调 - 微信绿 */
$uni-color-primary: #07C160;
$uni-color-primary-hover: #06AD56;
$uni-color-primary-light: #E8F5E9;
/* 功能色 */
$uni-color-success: #2BA471;
$uni-color-warning: #E37318;
$uni-color-error: #D54941;
$uni-color-info: #0052D9;
/* 文字颜色 - 强调层级与理性 */
$uni-text-color:#1D2129; //主要文字,深黑
$uni-text-color-inverse:#fff;
$uni-text-color-grey:#4E5969; // 次要文字,冷灰
$uni-text-color-placeholder: #86909C;
$uni-text-color-disable:#C9CDD4;
/* 背景颜色 */
$uni-bg-color:#ffffff;
$uni-bg-color-grey:#F2F3F5; // 全局背景冷灰
$uni-bg-color-hover:#F7F8FA;
$uni-bg-color-mask:rgba(0, 0, 0, 0.6);
/* 边框颜色 - 细腻的分割 */
$uni-border-color:#E5E6EB;
/* 尺寸变量 */
/* 文字尺寸 */
$uni-font-size-sm:12px;
$uni-font-size-base:14px;
$uni-font-size-lg:16px;
$uni-font-size-xl: 20px;
/* 图片尺寸 */
$uni-img-size-sm:20px;
$uni-img-size-base:26px;
$uni-img-size-lg:40px;
/* Border Radius - 微圆角,严谨 */
$uni-border-radius-sm: 2px;
$uni-border-radius-base: 4px;
$uni-border-radius-lg: 8px;
$uni-border-radius-circle: 50%;
/* 间距 - 适度宽松 */
$uni-spacing-row-sm: 8px;
$uni-spacing-row-base: 16px;
$uni-spacing-row-lg: 24px;
$uni-spacing-col-sm: 8px;
$uni-spacing-col-base: 16px;
$uni-spacing-col-lg: 24px;
/* 透明度 */
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */
$uni-color-title: #2C405A; // 文章标题颜色
$uni-font-size-title:20px;
$uni-color-subtitle: #555555; // 二级标题颜色
$uni-font-size-subtitle:26px;
$uni-color-paragraph: #3F536E; // 文章段落颜色
$uni-font-size-paragraph:15px;
|
2201_75827989/zhi_shi_ku
|
uni.scss
|
SCSS
|
unknown
| 2,409
|
<template>
<view class="defaultStyles">
</view>
</template>
<script lang="uts">
import Animator from 'android.animation.Animator'
import TextUtils from 'android.text.TextUtils'
import View from 'android.view.View'
import LottieAnimationView from 'com.airbnb.lottie.LottieAnimationView'
import LottieDrawable from 'com.airbnb.lottie.LottieDrawable'
import FileInputStream from 'java.io.FileInputStream'
class CustomAnimListener implements Animator.AnimatorListener {
comp: UTSComponent < LottieAnimationView >
constructor(com: UTSComponent < LottieAnimationView > ) {
super();
this.comp = com
}
override onAnimationStart(animation: Animator) {}
override onAnimationEnd(animation: Animator, isReverse: Boolean) {
this.comp.$emit("bindended")
}
override onAnimationEnd(animation: Animator) {}
override onAnimationCancel(animation: Animator) {}
override onAnimationRepeat(animation: Animator) {}
}
//原生提供以下属性或方法的实现
export default {
name: "uts-animation-view",
/**
* 当播放到末尾时触发 ended 事件(自然播放结束会触发回调,循环播放结束及手动停止动画不会触发)
*/
emits: ['bindended'],
props: {
/**
* 动画资源地址,目前只支持绝对路径
*/
"path": {
type: String,
default: ""
},
/**
* 动画是否自动播放
*/
"autoplay": {
type: Boolean,
default: false
},
/**
* 动画是否循环播放
*/
"loop": {
type: Boolean,
default: false
},
/**
* 是否隐藏动画
*/
"hidden": {
type: Boolean,
default: false
},
/**
* 动画操作,可取值 play、pause、stop
*/
"action": {
type: String,
default: "stop"
}
},
data() {
return {
}
},
watch: {
"path": {
handler(newPath: string) {
if(this.$el != null){
let lottieAnimationView = this.$el!
if (!TextUtils.isEmpty(newPath)) {
if (newPath.startsWith("http://") || newPath.startsWith("https://")) {
lottieAnimationView.setAnimationFromUrl(newPath)
} else {
// 正式打包会放在asset中,需要特殊处理
let realJsonPath = UTSAndroid.getResourcePath(newPath)
if(realJsonPath.startsWith("/android_asset")){
lottieAnimationView.setAnimation(realJsonPath.substring(15))
}else{
lottieAnimationView.setAnimation(new FileInputStream(realJsonPath),newPath)
}
}
}
if (this.autoplay) {
lottieAnimationView.playAnimation()
}
}
},
immediate: false
},
"loop": {
handler(newLoop: Boolean) {
if(this.$el != null){
if (newLoop) {
this.$el!.repeatCount = Int.MAX_VALUE
} else {
// 不循环则设置成1次
this.$el!.repeatCount = 0
}
if (this.autoplay) {
this.$el!.playAnimation()
}
}
},
immediate: false
},
"autoplay": {
handler(newValue: boolean) {
if(this.$el != null){
if (newValue) {
this.$el!.playAnimation()
}
}
},
immediate: false
},
"action": {
handler(newAction: string) {
if (newAction == "play" || newAction == "pause" || newAction == "stop") {
if(this.$el != null){
if (this.action == "play") {
this.$el!.playAnimation()
} else if (this.action == "pause") {
this.$el!.pauseAnimation()
} else if (this.action == "stop") {
this.$el!.cancelAnimation()
this.$el!.clearAnimation()
}
}
} else {
// 非法入参,不管
}
},
immediate: false
},
"hidden": {
handler(newValue: boolean) {
if(this.$el != null){
if (newValue) {
this.$el!.visibility = View.GONE
} else {
this.$el!.visibility = View.VISIBLE
}
}
},
immediate: false
},
},
methods: {
setRepeatMode(repeat: string) {
if(this.$el != null){
if ("RESTART" == repeat) {
this.$el!.repeatMode = LottieDrawable.RESTART
} else if ("REVERSE" == repeat) {
this.$el!.repeatMode = LottieDrawable.RESTART
}
}
},
},
NVLoad(): LottieAnimationView {
let lottieAnimationView = new LottieAnimationView($androidContext)
return lottieAnimationView
},
NVLoaded() {
if(this.$el != null){
this.$el!.repeatMode = LottieDrawable.RESTART;
this.$el!.visibility = View.GONE
this.$el!.repeatCount = 0
this.$el!.addAnimatorListener(new CustomAnimListener(this))
}
}
}
</script>
<style>
/* 定义默认样式值, 组件使用者没有配置时使用 */
.defaultStyles {
width: 750rpx;
height: 240rpx;
}
</style>
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-android/index.vue
|
Vue
|
unknown
| 5,921
|
<template>
<view class="defaultStyles">
</view>
</template>
<script lang="uts">
// import {
// LottieAnimationView,
// LottieAnimation,
// LottieLoopMode
// } from 'Lottie'
import {
URL
} from 'Foundation'
// import {
// UTSiOS
// } from "DCloudUTSFoundation"
//原生提供以下属性或方法的实现
export default {
/**
* 组件名称,也就是开发者使用的标签
*/
name: "uts-animation-view",
/**
* 组件涉及的事件声明,只有声明过的事件,才能被正常发送
*/
emits: ['bindended'], // 当播放到末尾时触发 ended 事件(自然播放结束会触发回调,循环播放结束及手动停止动画不会触发)
/**
* 属性声明,组件的使用者会传递这些属性值到组件
*/
props: {
/**
* 动画资源地址,支持远程 URL 地址和本地绝对路径
*/
"path": {
type: String,
default: ""
},
/**
* 动画是否循环播放
*/
"autoplay": {
type: Boolean,
default: false
},
/**
* 动画是否自动播放
*/
"loop": {
type: Boolean,
default: false
},
/**
* 是否隐藏动画
*/
"hidden": {
type: Boolean,
default: false
},
/**
* 动画操作,可取值 play、pause、stop
*/
"action": {
type: String,
default: "stop"
}
},
data() {
return {
}
},
watch: {
"path": {
handler(newValue: string, oldValue: string) {
if (this.autoplay) {
this.playAnimation()
}
},
immediate: false //创建时是否通过此方法更新属性,默认值为false
},
"loop": {
handler(newValue: boolean, oldValue: boolean) {
if (newValue) {
this.$el.loopMode = LottieLoopMode.loop
} else {
this.$el.loopMode = LottieLoopMode.playOnce
}
},
immediate: false //创建时是否通过此方法更新属性,默认值为false
},
"autoplay": {
handler(newValue: boolean, oldValue: boolean) {
if (newValue) {
this.playAnimation()
}
},
immediate: false //创建时是否通过此方法更新属性,默认值为false
},
"action": {
handler(newValue: string, oldValue: string) {
const action = newValue
if (action == "play" || action == "pause" || action == "stop") {
switch (action) {
case "play":
this.playAnimation()
break;
case "pause":
this.$el.pause()
break;
case "stop":
this.$el.stop()
break;
default:
break;
}
} else {
// 非法入参,不管
}
},
immediate: false //创建时是否通过此方法更新属性,默认值为false
},
"hidden": {
handler(newValue: boolean, oldValue: boolean) {
this.$el.isHidden = this.hidden
},
immediate: false //创建时是否通过此方法更新属性,默认值为false
},
},
expose: ['setRepeatMode'],
methods: {
// 需要对外暴露的方法
// 设置 RepeatMode
setRepeatMode(repeatMode: string) {
if (repeatMode == "RESTART") {
if (this.loop) {
this.$el.loopMode = LottieLoopMode.loop
} else {
this.$el.loopMode = LottieLoopMode.playOnce
}
} else if (repeatMode == "REVERSE") {
if (this.loop) {
this.$el.loopMode = LottieLoopMode.autoReverse
} else {
this.$el.loopMode = LottieLoopMode.repeatBackwards(1)
}
}
},
// 不对外暴露的方法
// 播放动画
playAnimation() {
// 构建动画资源 url
var animationUrl: URL | null
if (this.path.hasPrefix("http")) {
animationUrl = new URL(string = this.path)
} else {
const filePath = UTSiOS.getResourcePath(this.path)
animationUrl = new URL(fileURLWithPath = filePath)
}
if (animationUrl != null) {
// 加载动画 LottieAnimation
LottieAnimation.loadedFrom(url = animationUrl!, closure = (animation: LottieAnimation | null):
void => {
if (animation != null) {
// 加载成功开始播放
this.$el.animation = animation
this.$el.play(completion = (isFinish: boolean): void => {
if (isFinish) {
// 播放完成回调事件
this.fireEvent("bindended")
}
})
}
})
} else {
console.log("url 构建失败,请检查 path 是否正确")
}
}
},
created() { //创建组件,替换created
},
NVBeforeLoad() { //组件将要创建,对应前端beforeMount
//可选实现,这里可以提前做一些操作
},
NVLoad(): LottieAnimationView { //创建原生View,必须定义返回值类型(Android需要明确知道View类型,需特殊校验)
// 初始化 Lottie$el
const animationView = new LottieAnimationView()
// 默认只播放一次动画
animationView.loopMode = LottieLoopMode.playOnce
return animationView
},
NVLoaded() { //原生View已创建
/// 更新 props 中定义的属性值
if (this.loop) {
this.$el.loopMode = LottieLoopMode.loop
}
this.$el.isHidden = this.hidden
if (this.autoplay) {
this.playAnimation()
}
},
NVLayouted() { //原生View布局完成
//可选实现,这里可以做布局后续操作
},
NVBeforeUnload() { //原生View将释放
//可选实现,这里可以做释放View之前的操作
},
NVUnloaded() { //原生View已释放
//可选实现,这里可以做释放View之后的操作
},
unmounted() { //组件销毁
//可选实现
}
}
</script>
<style>
/* 定义默认样式值, 组件使用者没有配置时使用 */
.defaultStyles {
width: 750rpx;
height: 240rpx;
}
</style>
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/index.vue
|
Vue
|
unknown
| 5,958
|
// Created by Cal Stephens on 1/6/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAAnimation {
/// Creates a `CAAnimation` that wraps this animation,
/// applying timing-related configuration from the given `LayerAnimationContext`.
/// - This animation should start at the beginning of the animation and
/// last the entire duration of the animation. It will be trimmed and retimed
/// to match the current playback state / looping configuration of the animation view.
@nonobjc
func timed(with context: LayerAnimationContext, for layer: CALayer) -> CAAnimation {
// The base animation always has the duration of the full animation,
// since that's the time space where keyframing and interpolating happens.
// So we start with a simple animation timeline from 0% to 100%:
//
// ┌──────────────────────────────────┐
// │ baseAnimation │
// └──────────────────────────────────┘
// 0% 100%
//
let baseAnimation = self
baseAnimation.duration = context.animationDuration
baseAnimation.speed = (context.endFrame < context.startFrame) ? -1 : 1
// To select the subrange of the `baseAnimation` that should be played,
// we create a parent animation with the duration of that subrange
// to clip the `baseAnimation`. This parent animation can then loop
// and/or autoreverse over the clipped subrange.
//
// ┌────────────────────┬───────►
// │ clippingParent │ ...
// └────────────────────┴───────►
// 25% 75%
// ┌──────────────────────────────────┐
// │ baseAnimation │
// └──────────────────────────────────┘
// 0% 100%
//
let clippingParent = CAAnimationGroup()
clippingParent.animations = [baseAnimation]
clippingParent.duration = Double(abs(context.endFrame - context.startFrame)) / context.animation.framerate
baseAnimation.timeOffset = context.animation.time(forFrame: context.startFrame)
clippingParent.autoreverses = context.timingConfiguration.autoreverses
clippingParent.repeatCount = context.timingConfiguration.repeatCount
clippingParent.timeOffset = context.timingConfiguration.timeOffset
// Once the animation ends, it should pause on the final frame
clippingParent.fillMode = .both
clippingParent.isRemovedOnCompletion = false
// We can pause the animation on a specific frame by setting the root layer's
// `speed` to 0, and then setting the `timeOffset` for the given frame.
// - For that setup to work properly, we have to set the `beginTime`
// of this animation to a time slightly before the current time.
// - It's not really clear why this is necessary, but `timeOffset`
// is not applied correctly without this configuration.
// - We can't do this when playing the animation in real time,
// because it can cause keyframe timings to be incorrect.
if context.timingConfiguration.speed == 0 {
let currentTime = layer.convertTime(CACurrentMediaTime(), from: nil)
clippingParent.beginTime = currentTime - .leastNonzeroMagnitude
}
return clippingParent
}
}
extension CALayer {
/// Adds the given animation to this layer, timed with the given timing configuration
/// - The given animation should start at the beginning of the animation and
/// last the entire duration of the animation. It will be trimmed and retimed
/// to match the current playback state / looping configuration of the animation view.
@nonobjc
func add(_ animation: CAPropertyAnimation, timedWith context: LayerAnimationContext) {
add(animation.timed(with: context, for: self), forKey: animation.keyPath)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/CAAnimation+TimingConfiguration.swift
|
Swift
|
unknown
| 4,275
|
// Created by Cal Stephens on 12/14/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
extension CALayer {
// MARK: Internal
/// Constructs a `CAKeyframeAnimation` that reflects the given keyframes,
/// and adds it to this `CALayer`.
@nonobjc
func addAnimation<KeyframeValue: AnyInterpolatable, ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
keyframes: KeyframeGroup<KeyframeValue>,
value keyframeValueMapping: (KeyframeValue) throws -> ValueRepresentation,
context: LayerAnimationContext)
throws
{
if let customAnimation = try customizedAnimation(for: property, context: context) {
add(customAnimation, timedWith: context)
}
else if
let defaultAnimation = try defaultAnimation(
for: property,
keyframes: keyframes,
value: keyframeValueMapping,
context: context)
{
let timedAnimation = defaultAnimation.timed(with: context, for: self)
add(timedAnimation, forKey: property.caLayerKeypath)
}
}
// MARK: Private
/// Constructs a `CAAnimation` that reflects the given keyframes
/// - If the value can be applied directly to the CALayer using KVC,
/// then no `CAAnimation` will be created and the value will be applied directly.
@nonobjc
private func defaultAnimation<KeyframeValue: AnyInterpolatable, ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
keyframes keyframeGroup: KeyframeGroup<KeyframeValue>,
value keyframeValueMapping: (KeyframeValue) throws -> ValueRepresentation,
context: LayerAnimationContext)
throws -> CAAnimation?
{
let keyframes = keyframeGroup.keyframes
guard !keyframes.isEmpty else { return nil }
// Check if this set of keyframes uses After Effects expressions, which aren't supported.
// - We only log this once per `CoreAnimationLayer` instance.
if keyframeGroup.unsupportedAfterEffectsExpression != nil, !context.loggingState.hasLoggedAfterEffectsExpressionsWarning {
context.loggingState.hasLoggedAfterEffectsExpressionsWarning = true
context.logger.info("""
`\(property.caLayerKeypath)` animation for "\(context.currentKeypath.fullPath)" \
includes an After Effects expression (https://helpx.adobe.com/after-effects/using/expression-language.html), \
which is not supported by lottie-ios (expressions are only supported by lottie-web). \
This animation may not play correctly.
""")
}
// If there is exactly one keyframe value that doesn't animate,
// we can improve performance by applying that value directly to the layer
// instead of creating a relatively expensive `CAKeyframeAnimation`.
if keyframes.count == 1 {
return singleKeyframeAnimation(
for: property,
keyframeValue: try keyframeValueMapping(keyframes[0].value),
writeDirectlyToPropertyIfPossible: true)
}
/// If we're required to use the `complexTimeRemapping` from some parent `PreCompLayer`,
/// we have to manually interpolate the keyframes with the time remapping applied.
if context.mustUseComplexTimeRemapping {
return try defaultAnimation(
for: property,
keyframes: Keyframes.manuallyInterpolatedWithTimeRemapping(keyframeGroup, context: context),
value: keyframeValueMapping,
context: context.withoutTimeRemapping())
}
// Split the keyframes into segments with the same `CAAnimationCalculationMode` value
// - Each of these segments will become their own `CAKeyframeAnimation`
let animationSegments = keyframes.segmentsSplitByCalculationMode()
// If we only have a single segment, we can just create a single `CAKeyframeAnimation`
// instead of wrapping it in a `CAAnimationGroup` -- this reduces allocation overhead a bit.
if animationSegments.count == 1 {
return try keyframeAnimation(
for: property,
keyframes: animationSegments[0],
value: keyframeValueMapping,
context: context)
} else {
return try animationGroup(
for: property,
animationSegments: animationSegments,
value: keyframeValueMapping,
context: context)
}
}
/// A `CAAnimation` that applies the custom value from the `AnyValueProvider`
/// registered for this specific property's `AnimationKeypath`,
/// if one has been registered using `LottieAnimationView.setValueProvider(_:keypath:)`.
@nonobjc
private func customizedAnimation<ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
context: LayerAnimationContext)
throws -> CAPropertyAnimation?
{
guard
let customizableProperty = property.customizableProperty,
let customKeyframes = try context.valueProviderStore.customKeyframes(
of: customizableProperty,
for: AnimationKeypath(keys: context.currentKeypath.keys + customizableProperty.name.map { $0.rawValue }),
context: context)
else { return nil }
// Since custom animations are overriding an existing animation,
// we always have to create a CAAnimation and can't write directly
// to the layer property
if
customKeyframes.keyframes.count == 1,
let singleKeyframeAnimation = singleKeyframeAnimation(
for: property,
keyframeValue: customKeyframes.keyframes[0].value,
writeDirectlyToPropertyIfPossible: false)
{
return singleKeyframeAnimation
}
return try keyframeAnimation(
for: property,
keyframes: Array(customKeyframes.keyframes),
value: { $0 },
context: context)
}
/// Creates an animation that applies a single keyframe to this layer property
/// - In many cases this animation can be omitted entirely, and the underlying
/// property can be set directly. In that case, no animation will be created.
private func singleKeyframeAnimation<ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
keyframeValue: ValueRepresentation,
writeDirectlyToPropertyIfPossible: Bool)
-> CABasicAnimation?
{
if writeDirectlyToPropertyIfPossible {
// If the keyframe value is the same as the layer's default value for this property,
// then we can just ignore this set of keyframes.
if property.isDefaultValue(keyframeValue) {
return nil
}
// If the property on the CALayer being animated hasn't been modified from the default yet,
// then we can apply the keyframe value directly to the layer using KVC instead
// of creating a `CAAnimation`.
let currentValue = value(forKey: property.caLayerKeypath) as? ValueRepresentation
if property.isDefaultValue(currentValue) {
setValue(keyframeValue, forKeyPath: property.caLayerKeypath)
return nil
}
}
// Otherwise, we still need to create a `CAAnimation`, but we can
// create a simple `CABasicAnimation` that is still less expensive
// than computing a `CAKeyframeAnimation`.
let animation = CABasicAnimation(keyPath: property.caLayerKeypath)
animation.fromValue = keyframeValue
animation.toValue = keyframeValue
return animation
}
/// Creates a `CAAnimationGroup` that wraps a `CAKeyframeAnimation` for each
/// of the given `animationSegments`
private func animationGroup<KeyframeValue, ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
animationSegments: [[Keyframe<KeyframeValue>]],
value keyframeValueMapping: (KeyframeValue) throws -> ValueRepresentation,
context: LayerAnimationContext)
throws -> CAAnimationGroup
{
// Build the `CAKeyframeAnimation` for each segment of keyframes
// with the same `CAAnimationCalculationMode`.
// - Here we have a non-zero number of animation segments,
// all of which have a non-zero number of keyframes.
let segmentAnimations: [CAKeyframeAnimation] = try animationSegments.indices.map { index in
let animationSegment = animationSegments[index]
var segmentStartTime = try context.time(forFrame: animationSegment.first!.time)
var segmentEndTime = try context.time(forFrame: animationSegment.last!.time)
// Every portion of the animation timeline has to be covered by a `CAKeyframeAnimation`,
// so if this is the first or last segment then the start/end time should be exactly
// the start/end time of the animation itself.
let isFirstSegment = (index == animationSegments.indices.first!)
let isLastSegment = (index == animationSegments.indices.last!)
if isFirstSegment {
segmentStartTime = min(
try context.time(forFrame: context.animation.startFrame),
segmentStartTime)
}
if isLastSegment {
segmentEndTime = max(
try context.time(forFrame: context.animation.endFrame),
segmentEndTime)
}
let segmentDuration = segmentEndTime - segmentStartTime
// We're building `CAKeyframeAnimation`s, so the `keyTimes` are expressed
// relative to 0 (`segmentStartTime`) and 1 (`segmentEndTime`). This is different
// from the default behavior of the `keyframeAnimation` method, where times
// are expressed relative to the entire animation duration.
let customKeyTimes = try animationSegment.map { keyframeModel -> NSNumber in
let keyframeTime = try context.time(forFrame: keyframeModel.time)
let segmentProgressTime = ((keyframeTime - segmentStartTime) / segmentDuration)
return segmentProgressTime as NSNumber
}
let animation = try keyframeAnimation(
for: property,
keyframes: animationSegment,
value: keyframeValueMapping,
customKeyTimes: customKeyTimes,
context: context)
animation.duration = segmentDuration
animation.beginTime = segmentStartTime
return animation
}
let fullAnimation = CAAnimationGroup()
fullAnimation.animations = segmentAnimations
return fullAnimation
}
/// Creates and validates a `CAKeyframeAnimation` for the given keyframes
private func keyframeAnimation<KeyframeValue, ValueRepresentation>(
for property: LayerProperty<ValueRepresentation>,
keyframes: [Keyframe<KeyframeValue>],
value keyframeValueMapping: (KeyframeValue) throws -> ValueRepresentation,
customKeyTimes: [NSNumber]? = nil,
context: LayerAnimationContext)
throws
-> CAKeyframeAnimation
{
// Convert the list of `Keyframe<T>` into
// the representation used by `CAKeyframeAnimation`
var keyTimes = try customKeyTimes ?? keyframes.map { keyframeModel -> NSNumber in
NSNumber(value: Float(try context.progressTime(for: keyframeModel.time)))
}
var timingFunctions = timingFunctions(for: keyframes)
let calculationMode = calculationMode(for: keyframes)
let animation = CAKeyframeAnimation(keyPath: property.caLayerKeypath)
// Position animations define a `CGPath` curve that should be followed,
// instead of animating directly between keyframe point values.
if property.caLayerKeypath == LayerProperty<CGPoint>.position.caLayerKeypath {
animation.path = try path(keyframes: keyframes, value: { value in
guard let point = try keyframeValueMapping(value) as? CGPoint else {
context.logger.assertionFailure("Cannot create point from keyframe with value \(value)")
return .zero
}
return point
})
}
// All other types of keyframes provide individual values that are interpolated by Core Animation
else {
var values = try keyframes.map { keyframeModel in
try keyframeValueMapping(keyframeModel.value)
}
validate(
values: &values,
keyTimes: &keyTimes,
timingFunctions: &timingFunctions,
for: calculationMode,
context: context)
animation.values = values
}
animation.calculationMode = calculationMode
animation.keyTimes = keyTimes
animation.timingFunctions = timingFunctions
return animation
}
/// The `CAAnimationCalculationMode` that should be used for a `CAKeyframeAnimation`
/// animating the given keyframes
private func calculationMode<KeyframeValue>(
for keyframes: [Keyframe<KeyframeValue>])
-> CAAnimationCalculationMode
{
// At this point we expect all of the animations to have been split in
// to segments based on the `CAAnimationCalculationMode`, so we can just
// check the first keyframe.
if keyframes[0].isHold {
return .discrete
} else {
return .linear
}
}
/// `timingFunctions` to apply to a `CAKeyframeAnimation` animating the given keyframes
private func timingFunctions<KeyframeValue>(
for keyframes: [Keyframe<KeyframeValue>])
-> [CAMediaTimingFunction]
{
// Compute the timing function between each keyframe and the subsequent keyframe
var timingFunctions: [CAMediaTimingFunction] = []
for (index, keyframe) in keyframes.enumerated()
where index != keyframes.indices.last
{
let nextKeyframe = keyframes[index + 1]
let controlPoint1 = keyframe.outTangent?.pointValue ?? .zero
let controlPoint2 = nextKeyframe.inTangent?.pointValue ?? CGPoint(x: 1, y: 1)
timingFunctions.append(CAMediaTimingFunction(
controlPoints:
Float(controlPoint1.x),
Float(controlPoint1.y),
Float(controlPoint2.x),
Float(controlPoint2.y)))
}
return timingFunctions
}
/// Creates a `CGPath` for the given `position` keyframes,
/// which accounts for `spatialInTangent`s and `spatialOutTangents`
private func path<KeyframeValue>(
keyframes positionKeyframes: [Keyframe<KeyframeValue>],
value keyframeValueMapping: (KeyframeValue) throws -> CGPoint) rethrows
-> CGPath
{
let path = CGMutablePath()
for (index, keyframe) in positionKeyframes.enumerated() {
if index == positionKeyframes.indices.first {
path.move(to: try keyframeValueMapping(keyframe.value))
}
if index != positionKeyframes.indices.last {
let nextKeyframe = positionKeyframes[index + 1]
if
let controlPoint1 = keyframe.spatialOutTangent?.pointValue,
let controlPoint2 = nextKeyframe.spatialInTangent?.pointValue,
!(controlPoint1 == .zero && controlPoint2 == .zero)
{
path.addCurve(
to: try keyframeValueMapping(nextKeyframe.value),
control1: try keyframeValueMapping(keyframe.value) + controlPoint1,
control2: try keyframeValueMapping(nextKeyframe.value) + controlPoint2)
}
else {
path.addLine(to: try keyframeValueMapping(nextKeyframe.value))
}
}
}
path.closeSubpath()
return path
}
/// Validates that the requirements of the `CAKeyframeAnimation` API are met correctly
private func validate<ValueRepresentation>(
values: inout [ValueRepresentation],
keyTimes: inout [NSNumber],
timingFunctions: inout [CAMediaTimingFunction],
for calculationMode: CAAnimationCalculationMode,
context: LayerAnimationContext)
{
// Validate that we have correct start (0.0) and end (1.0) keyframes.
// From the documentation of `CAKeyframeAnimation.keyTimes`:
// - The first value in the `keyTimes` array must be 0.0 and the last value must be 1.0.
if keyTimes.first != 0.0 {
keyTimes.insert(0.0, at: 0)
values.insert(values[0], at: 0)
timingFunctions.insert(CAMediaTimingFunction(name: .linear), at: 0)
}
if keyTimes.last != 1.0 {
keyTimes.append(1.0)
values.append(values.last!)
timingFunctions.append(CAMediaTimingFunction(name: .linear))
}
switch calculationMode {
case .linear, .cubic:
// From the documentation of `CAKeyframeAnimation.keyTimes`:
// - The number of elements in the keyTimes array
// should match the number of elements in the values property
context.logger.assert(
values.count == keyTimes.count,
"`values.count` must exactly equal `keyTimes.count`")
context.logger.assert(
timingFunctions.count == (values.count - 1),
"`timingFunctions.count` must exactly equal `values.count - 1`")
case .discrete:
// From the documentation of `CAKeyframeAnimation.keyTimes`:
// - If the calculationMode is set to discrete... the keyTimes array
// should have one more entry than appears in the values array.
values.removeLast()
context.logger.assert(
keyTimes.count == values.count + 1,
"`keyTimes.count` must exactly equal `values.count + 1`")
default:
context.logger.assertionFailure("""
Unexpected keyframe calculation mode \(calculationMode)
""")
}
}
}
extension RandomAccessCollection {
/// Splits this array of `Keyframe`s into segments with the same `CAAnimationCalculationMode`
/// - Keyframes with `isHold=true` become `discrete`, and keyframes with `isHold=false`
/// become linear. Each `CAKeyframeAnimation` can only be one or the other, so each
/// `calculationModeSegment` becomes its own `CAKeyframeAnimation`.
func segmentsSplitByCalculationMode<KeyframeValue>() -> [[Element]]
where Element == Keyframe<KeyframeValue>, Index == Int
{
var segments: [[Element]] = []
var currentSegment: [Element] = []
for keyframe in self {
guard let mostRecentKeyframe = currentSegment.last else {
currentSegment.append(keyframe)
continue
}
// When `isHold` changes between any two given keyframes, we have to create a new segment
if keyframe.isHold != mostRecentKeyframe.isHold {
// Add this keyframe to both the existing segment that is ending,
// so we know how long that segment is, and the new segment,
// so we know when that segment starts.
currentSegment.append(keyframe)
segments.append(currentSegment)
currentSegment = [keyframe]
}
else {
currentSegment.append(keyframe)
}
}
segments.append(currentSegment)
return segments
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/CALayer+addAnimation.swift
|
Swift
|
unknown
| 18,201
|
// Created by Cal Stephens on 1/28/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds animations for the given `CombinedShapeItem` to this `CALayer`
@nonobjc
func addAnimations(
for combinedShapes: CombinedShapeItem,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
try addAnimation(
for: .path,
keyframes: combinedShapes.shapes,
value: { paths in
let combinedPath = CGMutablePath()
for path in paths {
combinedPath.addPath(path.cgPath().duplicated(times: pathMultiplier))
}
return combinedPath
},
context: context)
}
}
// MARK: - CombinedShapeItem
/// A custom `ShapeItem` subclass that combines multiple `Shape`s into a single `KeyframeGroup`
final class CombinedShapeItem: ShapeItem {
// MARK: Lifecycle
init(shapes: KeyframeGroup<[BezierPath]>, name: String) {
self.shapes = shapes
super.init(name: name, type: .shape, hidden: false)
}
required init(from _: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
required init(dictionary _: [String: Any]) throws {
fatalError("init(dictionary:) has not been implemented")
}
// MARK: Internal
let shapes: KeyframeGroup<[BezierPath]>
}
extension CombinedShapeItem {
/// Manually combines the given shape keyframes by manually interpolating at each frame
static func manuallyInterpolating(
shapes: [KeyframeGroup<BezierPath>],
name: String)
-> CombinedShapeItem
{
let interpolators = shapes.map { shape in
KeyframeInterpolator(keyframes: shape.keyframes)
}
let times = shapes.flatMap { $0.keyframes.map { $0.time } }
let minimumTime = times.min() ?? 0
let maximumTime = times.max() ?? 0
let animationLocalTimeRange = Int(minimumTime)...Int(maximumTime)
let interpolatedKeyframes = animationLocalTimeRange.map { localTime in
Keyframe(
value: interpolators.compactMap { interpolator in
interpolator.value(frame: AnimationFrameTime(localTime)) as? BezierPath
},
time: AnimationFrameTime(localTime))
}
return CombinedShapeItem(
shapes: KeyframeGroup(keyframes: ContiguousArray(interpolatedKeyframes)),
name: name)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/CombinedShapeAnimation.swift
|
Swift
|
unknown
| 2,330
|
// Created by Cal Stephens on 12/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds animations for the given `BezierPath` keyframes to this `CALayer`
@nonobjc
func addAnimations(
for customPath: KeyframeGroup<BezierPath>,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier = 1,
transformPath: (CGPath) -> CGPath = { $0 },
roundedCorners: RoundedCorners? = nil)
throws
{
let combinedKeyframes = try BezierPathKeyframe.combining(
path: customPath,
cornerRadius: roundedCorners?.radius)
try addAnimation(
for: .path,
keyframes: combinedKeyframes,
value: { pathKeyframe in
var path = pathKeyframe.path
if let cornerRadius = pathKeyframe.cornerRadius {
path = path.roundCorners(radius: cornerRadius.cgFloatValue)
}
return transformPath(path.cgPath().duplicated(times: pathMultiplier))
},
context: context)
}
}
extension CGPath {
/// Duplicates this `CGPath` so that it is repeated the given number of times
func duplicated(times: Int) -> CGPath {
if times <= 1 {
return self
}
let cgPath = CGMutablePath()
for _ in 0..<times {
cgPath.addPath(self)
}
return cgPath
}
}
// MARK: - BezierPathKeyframe
/// Data that represents how to render a bezier path at a specific point in time
struct BezierPathKeyframe: Interpolatable {
let path: BezierPath
let cornerRadius: LottieVector1D?
/// Creates a single array of animatable keyframes from the given sets of keyframes
/// that can have different counts / timing parameters
static func combining(
path: KeyframeGroup<BezierPath>,
cornerRadius: KeyframeGroup<LottieVector1D>?) throws
-> KeyframeGroup<BezierPathKeyframe>
{
guard
let cornerRadius,
cornerRadius.keyframes.contains(where: { $0.value.cgFloatValue > 0 })
else {
return path.map { path in
BezierPathKeyframe(path: path, cornerRadius: nil)
}
}
return Keyframes.combined(
path, cornerRadius,
makeCombinedResult: BezierPathKeyframe.init)
}
func interpolate(to: BezierPathKeyframe, amount: CGFloat) -> BezierPathKeyframe {
BezierPathKeyframe(
path: path.interpolate(to: to.path, amount: amount),
cornerRadius: cornerRadius.interpolate(to: to.cornerRadius, amount: amount))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/CustomPathAnimation.swift
|
Swift
|
unknown
| 2,432
|
// Created by Cal Stephens on 8/15/23.
// Copyright © 2023 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - DropShadowModel
protocol DropShadowModel {
/// The opacity of the drop shadow, from 0 to 100.
var _opacity: KeyframeGroup<LottieVector1D>? { get }
/// The shadow radius of the blur
var _radius: KeyframeGroup<LottieVector1D>? { get }
/// The color of the drop shadow
var _color: KeyframeGroup<LottieColor>? { get }
/// The angle of the drop shadow, in degrees,
/// with "90" resulting in a shadow directly beneath the layer.
/// Combines with the `distance` to form the `shadowOffset`.
var _angle: KeyframeGroup<LottieVector1D>? { get }
/// The distance of the drop shadow offset.
/// Combines with the `angle` to form the `shadowOffset`.
var _distance: KeyframeGroup<LottieVector1D>? { get }
}
// MARK: - DropShadowStyle + DropShadowModel
extension DropShadowStyle: DropShadowModel {
var _opacity: KeyframeGroup<LottieVector1D>? { opacity }
var _color: KeyframeGroup<LottieColor>? { color }
var _angle: KeyframeGroup<LottieVector1D>? { angle }
var _distance: KeyframeGroup<LottieVector1D>? { distance }
var _radius: KeyframeGroup<LottieVector1D>? {
size.map { sizeValue in
// After Effects shadow softness uses a different range of values than CALayer.shadowRadius,
// so shadows render too softly if we directly use the value from After Effects. We find that
// dividing this value from After Effects by 2 produces results that are visually similar.
LottieVector1D(sizeValue.cgFloatValue / 2)
}
}
}
// MARK: - DropShadowEffect + DropShadowModel
extension DropShadowEffect: DropShadowModel {
var _color: KeyframeGroup<LottieColor>? { color?.value }
var _distance: KeyframeGroup<LottieVector1D>? { distance?.value }
var _radius: KeyframeGroup<LottieVector1D>? {
softness?.value?.map { softnessValue in
// After Effects shadow softness uses a different range of values than CALayer.shadowRadius,
// so shadows render too softly if we directly use the value from After Effects. We find that
// dividing this value from After Effects by 5 produces results that are visually similar.
LottieVector1D(softnessValue.cgFloatValue / 5)
}
}
var _opacity: KeyframeGroup<LottieVector1D>? {
opacity?.value?.map { originalOpacityValue in
// `DropShadowEffect.opacity` is a value between 0 and 255,
// but `DropShadowModel._opacity` expects a value between 0 and 100.
LottieVector1D((originalOpacityValue.value / 255.0) * 100)
}
}
var _angle: KeyframeGroup<LottieVector1D>? {
direction?.value?.map { originalAngleValue in
// `DropShadowEffect.distance` is rotated 90º from the
// angle value representation expected by `DropShadowModel._angle`
LottieVector1D(originalAngleValue.value - 90)
}
}
}
// MARK: - CALayer + DropShadowModel
extension CALayer {
// MARK: Internal
/// Adds drop shadow animations from the given `DropShadowModel` to this layer
@nonobjc
func addDropShadowAnimations(
for dropShadowModel: DropShadowModel,
context: LayerAnimationContext)
throws
{
try addShadowOpacityAnimation(from: dropShadowModel, context: context)
try addShadowColorAnimation(from: dropShadowModel, context: context)
try addShadowRadiusAnimation(from: dropShadowModel, context: context)
try addShadowOffsetAnimation(from: dropShadowModel, context: context)
}
// MARK: Private
private func addShadowOpacityAnimation(from model: DropShadowModel, context: LayerAnimationContext) throws {
guard let opacityKeyframes = model._opacity else { return }
try addAnimation(
for: .shadowOpacity,
keyframes: opacityKeyframes,
value: {
// Lottie animation files express opacity as a numerical percentage value
// (e.g. 0%, 50%, 100%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.0, 0.5, 1.0).
$0.cgFloatValue / 100
},
context: context)
}
private func addShadowColorAnimation(from model: DropShadowModel, context: LayerAnimationContext) throws {
guard let shadowColorKeyframes = model._color else { return }
try addAnimation(
for: .shadowColor,
keyframes: shadowColorKeyframes,
value: \.cgColorValue,
context: context)
}
private func addShadowRadiusAnimation(from model: DropShadowModel, context: LayerAnimationContext) throws {
guard let shadowSizeKeyframes = model._radius else { return }
try addAnimation(
for: .shadowRadius,
keyframes: shadowSizeKeyframes,
value: \.cgFloatValue,
context: context)
}
private func addShadowOffsetAnimation(from model: DropShadowModel, context: LayerAnimationContext) throws {
guard
let angleKeyframes = model._angle,
let distanceKeyframes = model._distance
else { return }
let offsetKeyframes = Keyframes.combined(angleKeyframes, distanceKeyframes) { angleDegrees, distance -> CGSize in
// Lottie animation files express rotation in degrees
// (e.g. 90º, 180º, 360º) so we convert to radians to get the
// values expected by Core Animation (e.g. π/2, π, 2π)
let angleRadians = (angleDegrees.cgFloatValue * .pi) / 180
// Lottie animation files express the `shadowOffset` as (angle, distance) pair,
// which we convert to the expected x / y offset values:
let offsetX = distance.cgFloatValue * cos(angleRadians)
let offsetY = distance.cgFloatValue * sin(angleRadians)
return CGSize(width: offsetX, height: offsetY)
}
try addAnimation(
for: .shadowOffset,
keyframes: offsetKeyframes,
value: { $0 },
context: context)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/DropShadowAnimation.swift
|
Swift
|
unknown
| 5,785
|
// Created by Cal Stephens on 12/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds animations for the given `Ellipse` to this `CALayer`
@nonobjc
func addAnimations(
for ellipse: Ellipse,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
try addAnimation(
for: .path,
keyframes: ellipse.combinedKeyframes(),
value: { keyframe in
BezierPath.ellipse(
size: keyframe.size.sizeValue,
center: keyframe.position.pointValue,
direction: ellipse.direction)
.cgPath()
.duplicated(times: pathMultiplier)
},
context: context)
}
}
extension Ellipse {
/// Data that represents how to render an ellipse at a specific point in time
struct Keyframe: Interpolatable {
let size: LottieVector3D
let position: LottieVector3D
func interpolate(to: Ellipse.Keyframe, amount: CGFloat) -> Ellipse.Keyframe {
Keyframe(
size: size.interpolate(to: to.size, amount: amount),
position: position.interpolate(to: to.position, amount: amount))
}
}
/// Creates a single array of animatable keyframes from the separate arrays of keyframes in this Ellipse
func combinedKeyframes() throws -> KeyframeGroup<Ellipse.Keyframe> {
Keyframes.combined(
size, position,
makeCombinedResult: Ellipse.Keyframe.init)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/EllipseAnimation.swift
|
Swift
|
unknown
| 1,445
|
// Created by Cal Stephens on 1/7/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - GradientShapeItem
/// A `ShapeItem` that represents a gradient
protocol GradientShapeItem: OpacityAnimationModel {
var startPoint: KeyframeGroup<LottieVector3D> { get }
var endPoint: KeyframeGroup<LottieVector3D> { get }
var gradientType: GradientType { get }
var numberOfColors: Int { get }
var colors: KeyframeGroup<[Double]> { get }
}
// MARK: - GradientFill + GradientShapeItem
extension GradientFill: GradientShapeItem { }
// MARK: - GradientStroke + GradientShapeItem
extension GradientStroke: GradientShapeItem { }
// MARK: - GradientRenderLayer + GradientShapeItem
extension GradientRenderLayer {
// MARK: Internal
/// Adds gradient-related animations to this layer, from the given `GradientFill`
/// - The RGB components and alpha components can have different color stops / locations,
/// so have to be rendered in separate `CAGradientLayer`s.
func addGradientAnimations(
for gradient: GradientShapeItem,
type: GradientContentType,
context: LayerAnimationContext)
throws
{
// We have to set `colors` and `locations` to non-nil values
// for the animations below to actually take effect
locations = []
// The initial value for `colors` must be an array with the exact same number of colors
// as the gradient that will be applied in the `CAAnimation`
switch type {
case .rgb:
colors = .init(
repeating: CGColor.rgb(0, 0, 0),
count: gradient.numberOfColors)
case .alpha:
colors = .init(
repeating: CGColor.rgb(0, 0, 0),
count: gradient.colorConfiguration(from: gradient.colors.keyframes[0].value, type: .alpha).count)
}
try addAnimation(
for: .colors,
keyframes: gradient.colors,
value: { colorComponents in
gradient.colorConfiguration(from: colorComponents, type: type).map { $0.color }
},
context: context)
try addAnimation(
for: .locations,
keyframes: gradient.colors,
value: { colorComponents in
gradient.colorConfiguration(from: colorComponents, type: type).map { $0.location }
},
context: context)
try addOpacityAnimation(for: gradient, context: context)
switch gradient.gradientType {
case .linear:
try addLinearGradientAnimations(for: gradient, context: context)
case .radial:
try addRadialGradientAnimations(for: gradient, context: context)
case .none:
break
}
}
// MARK: Private
private func addLinearGradientAnimations(
for gradient: GradientShapeItem,
context: LayerAnimationContext)
throws
{
type = .axial
try addAnimation(
for: .startPoint,
keyframes: gradient.startPoint,
value: { absoluteStartPoint in
percentBasedPointInBounds(from: absoluteStartPoint.pointValue)
},
context: context)
try addAnimation(
for: .endPoint,
keyframes: gradient.endPoint,
value: { absoluteEndPoint in
percentBasedPointInBounds(from: absoluteEndPoint.pointValue)
},
context: context)
}
private func addRadialGradientAnimations(for gradient: GradientShapeItem, context: LayerAnimationContext) throws {
type = .radial
let combinedKeyframes = Keyframes.combined(
gradient.startPoint, gradient.endPoint,
makeCombinedResult: { absoluteStartPoint, absoluteEndPoint -> RadialGradientKeyframes in
// Convert the absolute start / end points to the relative structure used by Core Animation
let relativeStartPoint = percentBasedPointInBounds(from: absoluteStartPoint.pointValue)
let radius = absoluteStartPoint.pointValue.distanceTo(absoluteEndPoint.pointValue)
let relativeEndPoint = percentBasedPointInBounds(
from: CGPoint(
x: absoluteStartPoint.x + radius,
y: absoluteStartPoint.y + radius))
return RadialGradientKeyframes(startPoint: relativeStartPoint, endPoint: relativeEndPoint)
})
try addAnimation(
for: .startPoint,
keyframes: combinedKeyframes,
value: \.startPoint,
context: context)
try addAnimation(
for: .endPoint,
keyframes: combinedKeyframes,
value: \.endPoint,
context: context)
}
}
// MARK: - RadialGradientKeyframes
private struct RadialGradientKeyframes: Interpolatable {
let startPoint: CGPoint
let endPoint: CGPoint
func interpolate(to: RadialGradientKeyframes, amount: CGFloat) -> RadialGradientKeyframes {
RadialGradientKeyframes(
startPoint: startPoint.interpolate(to: to.startPoint, amount: amount),
endPoint: endPoint.interpolate(to: to.endPoint, amount: amount))
}
}
// MARK: - GradientContentType
/// Each type of gradient that can be constructed from a `GradientShapeItem`
enum GradientContentType {
case rgb
case alpha
}
/// `colors` and `locations` configuration for a `CAGradientLayer`
typealias GradientColorConfiguration = [(color: CGColor, location: CGFloat)]
extension GradientShapeItem {
// MARK: Internal
/// Whether or not this `GradientShapeItem` includes an alpha component
/// that has to be rendered as a separate `CAGradientLayer` from the
/// layer that renders the rgb color components
var hasAlphaComponent: Bool {
for colorComponentsKeyframe in colors.keyframes {
let colorComponents = colorComponentsKeyframe.value
let alphaConfiguration = colorConfiguration(from: colorComponents, type: .alpha)
let notFullyOpaque = alphaConfiguration.contains(where: { color, _ in
color.alpha < 0.999
})
if notFullyOpaque {
return true
}
}
return false
}
// MARK: Fileprivate
/// Converts the compact `[Double]` color components representation
/// into an array of `CGColor`s and the location of those colors within the gradient.
/// - The color components array is a repeating list of `[location, red, green, blue]` values
/// for each color in the gradient, followed by an optional repeating list of
/// `[location, alpha]` values that control the colors' alpha values.
/// - The RGB and alpha values can have different color stops / locations,
/// so each has to be rendered in a separate `CAGradientLayer`.
fileprivate func colorConfiguration(
from colorComponents: [Double],
type: GradientContentType)
-> GradientColorConfiguration
{
switch type {
case .rgb:
precondition(
colorComponents.count >= numberOfColors * 4,
"Each color must have RGB components and a location component")
// Each group of four `Double` values represents a single `CGColor`,
// and its relative location within the gradient.
var colors = GradientColorConfiguration()
for colorIndex in 0..<numberOfColors {
let colorStartIndex = colorIndex * 4
let colorLocation = CGFloat(colorComponents[colorStartIndex])
let color = CGColor.rgb(
CGFloat(colorComponents[colorStartIndex + 1]),
CGFloat(colorComponents[colorStartIndex + 2]),
CGFloat(colorComponents[colorStartIndex + 3]))
colors.append((color: color, location: colorLocation))
}
return colors
case .alpha:
// After the rgb color components, there can be arbitrary number of repeating
// `[alphaLocation, alphaValue]` pairs that define a separate alpha gradient.
var alphaValues = GradientColorConfiguration()
for alphaIndex in stride(from: numberOfColors * 4, to: colorComponents.endIndex, by: 2) {
let alphaLocation = CGFloat(colorComponents[alphaIndex])
let alphaValue = CGFloat(colorComponents[alphaIndex + 1])
alphaValues.append((color: .rgba(0, 0, 0, alphaValue), location: alphaLocation))
}
return alphaValues
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/GradientAnimations.swift
|
Swift
|
unknown
| 7,911
|
// Created by Cal Stephens on 1/11/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - LayerProperty
/// A strongly typed value that can be used as the `keyPath` of a `CAAnimation`
///
/// Supported key paths and their expected value types are described
/// at https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreAnimation_guide/AnimatableProperties/AnimatableProperties.html#//apple_ref/doc/uid/TP40004514-CH11-SW1
/// and https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreAnimation_guide/Key-ValueCodingExtensions/Key-ValueCodingExtensions.html
struct LayerProperty<ValueRepresentation> {
/// The `CALayer` KVC key path that this value should be assigned to
let caLayerKeypath: String
/// Whether or not the given value is the default value for this property
/// - If the keyframe values are just equal to the default value,
/// then we can improve performance a bit by just not creating
/// a CAAnimation (since it would be redundant).
let isDefaultValue: (ValueRepresentation?) -> Bool
/// A description of how this property can be customized dynamically
/// at runtime using `AnimationView.setValueProvider(_:keypath:)`
let customizableProperty: CustomizableProperty<ValueRepresentation>?
}
extension LayerProperty where ValueRepresentation: Equatable {
/// Initializes a `LayerProperty` that corresponds to a property on `CALayer`
/// or some other `CALayer` subclass like `CAShapeLayer`.
/// - Parameters:
/// - caLayerKeypath: The Objective-C `#keyPath` to the `CALayer` property,
/// e.g. `#keyPath(CALayer.opacity)` or `#keyPath(CAShapeLayer.path)`.
/// - defaultValue: The default value of the property (e.g. the value of the
/// property immediately after calling `CALayer.init()`). Knowing this value
/// lets us perform some optimizations in `CALayer+addAnimation`.
/// - customizableProperty: A description of how this property can be customized
/// dynamically at runtime using `AnimationView.setValueProvider(_:keypath:)`.
init(
caLayerKeypath: String,
defaultValue: ValueRepresentation?,
customizableProperty: CustomizableProperty<ValueRepresentation>?)
{
self.init(
caLayerKeypath: caLayerKeypath,
isDefaultValue: { $0 == defaultValue },
customizableProperty: customizableProperty)
}
}
// MARK: - CustomizableProperty
/// A description of how a `CALayer` property can be customized dynamically
/// at runtime using `LottieAnimationView.setValueProvider(_:keypath:)`
struct CustomizableProperty<ValueRepresentation> {
/// The name that `AnimationKeypath`s can use to refer to this property
/// - When building an animation for this property that will be applied
/// to a specific layer, this `name` is appended to the end of that
/// layer's `AnimationKeypath`. The combined keypath is used to query
/// the `ValueProviderStore`.
let name: [PropertyName]
/// A closure that coverts the type-erased value of an `AnyValueProvider`
/// to the strongly-typed representation used by this property, if possible.
/// - `value` is the value for the current frame that should be converted,
/// as returned by `AnyValueProvider.typeErasedStorage`.
/// - `valueProvider` is the `AnyValueProvider` that returned the type-erased value.
let conversion: (_ value: Any, _ valueProvider: AnyValueProvider) -> ValueRepresentation?
}
// MARK: - PropertyName
/// The name of a customizable property that can be used in an `AnimationKeypath`
/// - These values should be shared between the two rendering engines,
/// since they form the public API of the `AnimationKeypath` system.
enum PropertyName: String, CaseIterable {
case color = "Color"
case opacity = "Opacity"
case scale = "Scale"
case position = "Position"
case rotation = "Rotation"
case strokeWidth = "Stroke Width"
case gradientColors = "Colors"
}
// MARK: CALayer properties
extension LayerProperty {
static var position: LayerProperty<CGPoint> {
.init(
caLayerKeypath: "transform.translation",
defaultValue: CGPoint(x: 0, y: 0),
customizableProperty: .position)
}
static var positionX: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.translation.x",
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var positionY: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.translation.y",
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var scale: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.scale",
defaultValue: 1,
customizableProperty: nil /* currently unsupported */ )
}
static var scaleX: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.scale.x",
defaultValue: 1,
customizableProperty: .scaleX)
}
static var scaleY: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.scale.y",
defaultValue: 1,
customizableProperty: .scaleY)
}
static var rotationX: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.rotation.x",
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var rotationY: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.rotation.y",
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var rotationZ: LayerProperty<CGFloat> {
.init(
caLayerKeypath: "transform.rotation.z",
defaultValue: 0,
customizableProperty: .rotation)
}
static var anchorPoint: LayerProperty<CGPoint> {
.init(
caLayerKeypath: #keyPath(CALayer.anchorPoint),
// This is intentionally not `GGPoint(x: 0.5, y: 0.5)` (the actual default)
// to opt `anchorPoint` out of the KVC `setValue` flow, which causes issues.
defaultValue: nil,
customizableProperty: nil /* currently unsupported */ )
}
static var opacity: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CALayer.opacity),
defaultValue: 1,
customizableProperty: .opacity)
}
static var isHidden: LayerProperty<Bool> {
.init(
caLayerKeypath: #keyPath(CALayer.isHidden),
defaultValue: false,
customizableProperty: nil /* unsupported */ )
}
static var transform: LayerProperty<CATransform3D> {
.init(
caLayerKeypath: #keyPath(CALayer.transform),
isDefaultValue: { transform in
guard let transform else { return false }
return CATransform3DIsIdentity(transform)
},
customizableProperty: nil /* currently unsupported */ )
}
static var shadowOpacity: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CALayer.shadowOpacity),
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var shadowColor: LayerProperty<CGColor> {
.init(
caLayerKeypath: #keyPath(CALayer.shadowColor),
defaultValue: .rgb(0, 0, 0),
customizableProperty: nil /* currently unsupported */ )
}
static var shadowRadius: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CALayer.shadowRadius),
defaultValue: 3.0,
customizableProperty: nil /* currently unsupported */ )
}
static var shadowOffset: LayerProperty<CGSize> {
.init(
caLayerKeypath: #keyPath(CALayer.shadowOffset),
defaultValue: CGSize(width: 0, height: -3.0),
customizableProperty: nil /* currently unsupported */ )
}
}
// MARK: CAShapeLayer properties
extension LayerProperty {
static var path: LayerProperty<CGPath> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.path),
defaultValue: nil,
customizableProperty: nil /* currently unsupported */ )
}
static var fillColor: LayerProperty<CGColor> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.fillColor),
defaultValue: nil,
customizableProperty: .color)
}
static var lineWidth: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.lineWidth),
defaultValue: 1,
customizableProperty: .floatValue(.strokeWidth))
}
static var lineDashPhase: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.lineDashPhase),
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var strokeColor: LayerProperty<CGColor> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.strokeColor),
defaultValue: nil,
customizableProperty: .color)
}
static var strokeStart: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.strokeStart),
defaultValue: 0,
customizableProperty: nil /* currently unsupported */ )
}
static var strokeEnd: LayerProperty<CGFloat> {
.init(
caLayerKeypath: #keyPath(CAShapeLayer.strokeEnd),
defaultValue: 1,
customizableProperty: nil /* currently unsupported */ )
}
}
// MARK: CAGradientLayer properties
extension LayerProperty {
static var colors: LayerProperty<[CGColor]> {
.init(
caLayerKeypath: #keyPath(CAGradientLayer.colors),
defaultValue: nil,
customizableProperty: .gradientColors)
}
static var locations: LayerProperty<[CGFloat]> {
.init(
caLayerKeypath: #keyPath(CAGradientLayer.locations),
defaultValue: nil,
customizableProperty: .gradientLocations)
}
static var startPoint: LayerProperty<CGPoint> {
.init(
caLayerKeypath: #keyPath(CAGradientLayer.startPoint),
defaultValue: nil,
customizableProperty: nil /* currently unsupported */ )
}
static var endPoint: LayerProperty<CGPoint> {
.init(
caLayerKeypath: #keyPath(CAGradientLayer.endPoint),
defaultValue: nil,
customizableProperty: nil /* currently unsupported */ )
}
}
// MARK: - CustomizableProperty types
extension CustomizableProperty {
static var color: CustomizableProperty<CGColor> {
.init(
name: [.color],
conversion: { typeErasedValue, _ in
guard let color = typeErasedValue as? LottieColor else {
return nil
}
return .rgba(CGFloat(color.r), CGFloat(color.g), CGFloat(color.b), CGFloat(color.a))
})
}
static var opacity: CustomizableProperty<CGFloat> {
.init(
name: [.opacity],
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector1D else { return nil }
// Lottie animation files express opacity as a numerical percentage value
// (e.g. 50%, 100%, 200%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.5, 1.0, 2.0).
return vector.cgFloatValue / 100
})
}
static var scaleX: CustomizableProperty<CGFloat> {
.init(
name: [.scale],
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector3D else { return nil }
// Lottie animation files express scale as a numerical percentage value
// (e.g. 50%, 100%, 200%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.5, 1.0, 2.0).
return vector.pointValue.x / 100
})
}
static var scaleY: CustomizableProperty<CGFloat> {
.init(
name: [.scale],
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector3D else { return nil }
// Lottie animation files express scale as a numerical percentage value
// (e.g. 50%, 100%, 200%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.5, 1.0, 2.0).
return vector.pointValue.y / 100
})
}
static var rotation: CustomizableProperty<CGFloat> {
.init(
name: [.rotation],
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector1D else { return nil }
// Lottie animation files express rotation in degrees
// (e.g. 90º, 180º, 360º) so we covert to radians to get the
// values expected by Core Animation (e.g. π/2, π, 2π)
return vector.cgFloatValue * .pi / 180
})
}
static var position: CustomizableProperty<CGPoint> {
.init(
name: [.position],
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector3D else { return nil }
return vector.pointValue
})
}
static var gradientColors: CustomizableProperty<[CGColor]> {
.init(
name: [.gradientColors],
conversion: { _, typeErasedValueProvider in
guard let gradientValueProvider = typeErasedValueProvider as? GradientValueProvider else { return nil }
return gradientValueProvider.colors.map { $0.cgColorValue }
})
}
static var gradientLocations: CustomizableProperty<[CGFloat]> {
.init(
name: [.gradientColors],
conversion: { _, typeErasedValueProvider in
guard let gradientValueProvider = typeErasedValueProvider as? GradientValueProvider else { return nil }
return gradientValueProvider.locations.map { CGFloat($0) }
})
}
static func floatValue(_ name: PropertyName...) -> CustomizableProperty<CGFloat> {
.init(
name: name,
conversion: { typeErasedValue, _ in
guard let vector = typeErasedValue as? LottieVector1D else { return nil }
return vector.cgFloatValue
})
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/LayerProperty.swift
|
Swift
|
unknown
| 13,566
|
// Created by Cal Stephens on 5/17/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - OpacityAnimationModel
protocol OpacityAnimationModel {
/// The opacity animation to apply to a `CALayer`
var opacity: KeyframeGroup<LottieVector1D> { get }
}
// MARK: - Transform + OpacityAnimationModel
extension Transform: OpacityAnimationModel { }
// MARK: - ShapeTransform + OpacityAnimationModel
extension ShapeTransform: OpacityAnimationModel { }
// MARK: - Fill + OpacityAnimationModel
extension Fill: OpacityAnimationModel { }
// MARK: - GradientFill + OpacityAnimationModel
extension GradientFill: OpacityAnimationModel { }
// MARK: - Stroke + OpacityAnimationModel
extension Stroke: OpacityAnimationModel { }
// MARK: - GradientStroke + OpacityAnimationModel
extension GradientStroke: OpacityAnimationModel { }
extension CALayer {
/// Adds the opacity animation from the given `OpacityAnimationModel` to this layer
@nonobjc
func addOpacityAnimation(for opacity: OpacityAnimationModel, context: LayerAnimationContext) throws {
try addAnimation(
for: .opacity,
keyframes: opacity.opacity,
value: {
// Lottie animation files express opacity as a numerical percentage value
// (e.g. 0%, 50%, 100%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.0, 0.5, 1.0).
$0.cgFloatValue / 100
},
context: context)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/OpacityAnimation.swift
|
Swift
|
unknown
| 1,464
|
// Created by Cal Stephens on 12/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds animations for the given `Rectangle` to this `CALayer`
@nonobjc
func addAnimations(
for rectangle: Rectangle,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier,
roundedCorners: RoundedCorners?)
throws
{
try addAnimation(
for: .path,
keyframes: try rectangle.combinedKeyframes(roundedCorners: roundedCorners),
value: { keyframe in
BezierPath.rectangle(
position: keyframe.position.pointValue,
size: keyframe.size.sizeValue,
cornerRadius: keyframe.cornerRadius.cgFloatValue,
direction: rectangle.direction)
.cgPath()
.duplicated(times: pathMultiplier)
},
context: context)
}
}
extension Rectangle {
/// Data that represents how to render a rectangle at a specific point in time
struct Keyframe: Interpolatable {
let size: LottieVector3D
let position: LottieVector3D
let cornerRadius: LottieVector1D
func interpolate(to: Rectangle.Keyframe, amount: CGFloat) -> Rectangle.Keyframe {
Rectangle.Keyframe(
size: size.interpolate(to: to.size, amount: amount),
position: position.interpolate(to: to.position, amount: amount),
cornerRadius: cornerRadius.interpolate(to: to.cornerRadius, amount: amount))
}
}
/// Creates a single array of animatable keyframes from the separate arrays of keyframes in this Rectangle
func combinedKeyframes(roundedCorners: RoundedCorners?) throws -> KeyframeGroup<Rectangle.Keyframe> {
let cornerRadius = roundedCorners?.radius ?? cornerRadius
return Keyframes.combined(
size, position, cornerRadius,
makeCombinedResult: Rectangle.Keyframe.init)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/RectangleAnimation.swift
|
Swift
|
unknown
| 1,849
|
// Created by Cal Stephens on 1/7/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds a `path` animation for the given `ShapeItem`
@nonobjc
func addAnimations(
for shape: ShapeItem,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier,
roundedCorners: RoundedCorners?)
throws
{
switch shape {
case let customShape as Shape:
try addAnimations(
for: customShape.path,
context: context,
pathMultiplier: pathMultiplier,
roundedCorners: roundedCorners)
case let combinedShape as CombinedShapeItem:
try addAnimations(for: combinedShape, context: context, pathMultiplier: pathMultiplier)
try context.compatibilityAssert(roundedCorners == nil, """
Rounded corners support is not currently implemented for combined shape items
""")
case let ellipse as Ellipse:
try addAnimations(for: ellipse, context: context, pathMultiplier: pathMultiplier)
case let rectangle as Rectangle:
try addAnimations(
for: rectangle,
context: context,
pathMultiplier: pathMultiplier,
roundedCorners: roundedCorners)
case let star as Star:
try addAnimations(for: star, context: context, pathMultiplier: pathMultiplier)
try context.compatibilityAssert(roundedCorners == nil, """
Rounded corners support is currently not implemented for polygon items
""")
default:
// None of the other `ShapeItem` subclasses draw a `path`
try context.logCompatibilityIssue("Unexpected shape type \(type(of: shape))")
return
}
}
/// Adds a `fillColor` animation for the given `Fill` object
@nonobjc
func addAnimations(for fill: Fill, context: LayerAnimationContext) throws {
fillRule = fill.fillRule.caFillRule
try addAnimation(
for: .fillColor,
keyframes: fill.color,
value: \.cgColorValue,
context: context)
try addOpacityAnimation(for: fill, context: context)
}
/// Adds animations for `strokeStart` and `strokeEnd` from the given `Trim` object
@nonobjc
func addAnimations(for trim: Trim, context: LayerAnimationContext) throws -> PathMultiplier {
let (strokeStartKeyframes, strokeEndKeyframes, pathMultiplier) = try trim.caShapeLayerKeyframes()
try addAnimation(
for: .strokeStart,
keyframes: strokeStartKeyframes,
value: { strokeStart in
// Lottie animation files express stoke trims as a numerical percentage value
// (e.g. 25%, 50%, 100%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.25, 0.5, 1.0).
CGFloat(strokeStart.cgFloatValue) / CGFloat(pathMultiplier) / 100
}, context: context)
try addAnimation(
for: .strokeEnd,
keyframes: strokeEndKeyframes,
value: { strokeEnd in
// Lottie animation files express stoke trims as a numerical percentage value
// (e.g. 25%, 50%, 100%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.25, 0.5, 1.0).
CGFloat(strokeEnd.cgFloatValue) / CGFloat(pathMultiplier) / 100
}, context: context)
return pathMultiplier
}
}
/// The number of times that a `CGPath` needs to be duplicated in order to support the animation's `Trim` keyframes
typealias PathMultiplier = Int
extension Trim {
// MARK: Fileprivate
/// The `strokeStart` and `strokeEnd` keyframes to apply to a `CAShapeLayer`,
/// plus a `pathMultiplier` that should be applied to the layer's `path` so that
/// trim values larger than 100% can be displayed properly.
fileprivate func caShapeLayerKeyframes()
throws
-> (strokeStart: KeyframeGroup<LottieVector1D>, strokeEnd: KeyframeGroup<LottieVector1D>, pathMultiplier: PathMultiplier)
{
let strokeStart: KeyframeGroup<LottieVector1D>
let strokeEnd: KeyframeGroup<LottieVector1D>
// CAShapeLayer requires strokeStart to be less than strokeEnd. This
// isn't required by the Lottie schema, so some animations may have
// strokeStart and strokeEnd flipped.
if startValueIsAlwaysLessOrEqualToThanEndValue() {
// If the start value is always _less than_ or equal to the end value
// then we can use the given values without any modifications
strokeStart = start
strokeEnd = end
} else if startValueIsAlwaysGreaterThanOrEqualToEndValue() {
// If the start value is always _greater than_ or equal to the end value,
// then we can just swap the start / end keyframes. This lets us avoid
// manually interpolating the keyframes values at each frame, which
// would be more expensive.
strokeStart = end
strokeEnd = start
} else {
// Otherwise if the start / end values ever swap places we have to
// fix the order on a per-keyframe basis, which may require manually
// interpolating the keyframe values at each frame.
(strokeStart, strokeEnd) = interpolatedAtEachFrame()
}
// If there are no offsets, then the stroke values can be used as-is
guard
!offset.keyframes.isEmpty,
offset.keyframes.contains(where: { $0.value.cgFloatValue != 0 })
else {
return (strokeStart, strokeEnd, 1)
}
// Apply the offset to the start / end values at each frame
let offsetStrokeKeyframes = Keyframes.combined(
strokeStart,
strokeEnd,
offset,
makeCombinedResult: { start, end, offset -> (start: LottieVector1D, end: LottieVector1D) in
// Compute the adjusted value by converting the offset value to a stroke value
let offsetStart = start.cgFloatValue + (offset.cgFloatValue / 360 * 100)
let offsetEnd = end.cgFloatValue + (offset.cgFloatValue / 360 * 100)
return (start: LottieVector1D(offsetStart), end: LottieVector1D(offsetEnd))
})
var adjustedStrokeStart = offsetStrokeKeyframes.map { $0.start }
var adjustedStrokeEnd = offsetStrokeKeyframes.map { $0.end }
// If maximum stroke value is larger than 100%, then we have to create copies of the path
// so the total path length includes the maximum stroke
let startStrokes = adjustedStrokeStart.keyframes.map { $0.value.cgFloatValue }
let endStrokes = adjustedStrokeEnd.keyframes.map { $0.value.cgFloatValue }
let minimumStrokeMultiplier = Double(floor((startStrokes.min() ?? 0) / 100.0))
let maximumStrokeMultiplier = Double(ceil((endStrokes.max() ?? 100) / 100.0))
if minimumStrokeMultiplier < 0 {
// Core Animation doesn't support negative stroke offsets, so we have to
// shift all of the offset values up by the minimum
adjustedStrokeStart = adjustedStrokeStart.map { LottieVector1D($0.value + (abs(minimumStrokeMultiplier) * 100.0)) }
adjustedStrokeEnd = adjustedStrokeEnd.map { LottieVector1D($0.value + (abs(minimumStrokeMultiplier) * 100.0)) }
}
return (
strokeStart: adjustedStrokeStart,
strokeEnd: adjustedStrokeEnd,
pathMultiplier: Int(abs(maximumStrokeMultiplier) + abs(minimumStrokeMultiplier)))
}
// MARK: Private
/// Checks whether or not the value for `trim.start` is less than
/// or equal to the value for every `trim.end` at every frame.
private func startValueIsAlwaysLessOrEqualToThanEndValue() -> Bool {
startAndEndValuesAllSatisfy { startValue, endValue in
startValue <= endValue
}
}
/// Checks whether or not the value for `trim.start` is greater than
/// or equal to the value for every `trim.end` at every frame.
private func startValueIsAlwaysGreaterThanOrEqualToEndValue() -> Bool {
startAndEndValuesAllSatisfy { startValue, endValue in
startValue >= endValue
}
}
private func startAndEndValuesAllSatisfy(_ condition: (_ start: CGFloat, _ end: CGFloat) -> Bool) -> Bool {
let keyframeTimes = Set(start.keyframes.map { $0.time } + end.keyframes.map { $0.time })
let startInterpolator = KeyframeInterpolator(keyframes: start.keyframes)
let endInterpolator = KeyframeInterpolator(keyframes: end.keyframes)
for keyframeTime in keyframeTimes {
guard
let startAtTime = startInterpolator.value(frame: keyframeTime) as? LottieVector1D,
let endAtTime = endInterpolator.value(frame: keyframeTime) as? LottieVector1D
else { continue }
if !condition(startAtTime.cgFloatValue, endAtTime.cgFloatValue) {
return false
}
}
return true
}
/// Interpolates the start and end keyframes, at each frame if necessary,
/// so that the value of `strokeStart` is always less than `strokeEnd`.
private func interpolatedAtEachFrame()
-> (strokeStart: KeyframeGroup<LottieVector1D>, strokeEnd: KeyframeGroup<LottieVector1D>)
{
let combinedKeyframes = Keyframes.combined(
start,
end,
makeCombinedResult: { startValue, endValue -> (start: LottieVector1D, end: LottieVector1D) in
if startValue.cgFloatValue < endValue.cgFloatValue {
return (start: startValue, end: endValue)
} else {
return (start: endValue, end: startValue)
}
})
return (
strokeStart: combinedKeyframes.map { $0.start },
strokeEnd: combinedKeyframes.map { $0.end })
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/ShapeAnimation.swift
|
Swift
|
unknown
| 9,284
|
// Created by Cal Stephens on 1/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
// MARK: Internal
/// Adds animations for the given `Rectangle` to this `CALayer`
@nonobjc
func addAnimations(
for star: Star,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
switch star.starType {
case .star:
try addStarAnimation(for: star, context: context, pathMultiplier: pathMultiplier)
case .polygon:
try addPolygonAnimation(for: star, context: context, pathMultiplier: pathMultiplier)
case .none:
break
}
}
// MARK: Private
@nonobjc
private func addStarAnimation(
for star: Star,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
try addAnimation(
for: .path,
keyframes: try star.combinedKeyframes(),
value: { keyframe in
BezierPath.star(
position: keyframe.position.pointValue,
outerRadius: keyframe.outerRadius.cgFloatValue,
innerRadius: keyframe.innerRadius.cgFloatValue,
outerRoundedness: keyframe.outerRoundness.cgFloatValue,
innerRoundedness: keyframe.innerRoundness.cgFloatValue,
numberOfPoints: keyframe.points.cgFloatValue,
rotation: keyframe.rotation.cgFloatValue,
direction: star.direction)
.cgPath()
.duplicated(times: pathMultiplier)
},
context: context)
}
@nonobjc
private func addPolygonAnimation(
for star: Star,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
try addAnimation(
for: .path,
keyframes: try star.combinedKeyframes(),
value: { keyframe in
BezierPath.polygon(
position: keyframe.position.pointValue,
numberOfPoints: keyframe.points.cgFloatValue,
outerRadius: keyframe.outerRadius.cgFloatValue,
outerRoundedness: keyframe.outerRoundness.cgFloatValue,
rotation: keyframe.rotation.cgFloatValue,
direction: star.direction)
.cgPath()
.duplicated(times: pathMultiplier)
},
context: context)
}
}
extension Star {
/// Data that represents how to render a star at a specific point in time
struct Keyframe: Interpolatable {
let position: LottieVector3D
let outerRadius: LottieVector1D
let innerRadius: LottieVector1D
let outerRoundness: LottieVector1D
let innerRoundness: LottieVector1D
let points: LottieVector1D
let rotation: LottieVector1D
func interpolate(to: Star.Keyframe, amount: CGFloat) -> Star.Keyframe {
Star.Keyframe(
position: position.interpolate(to: to.position, amount: amount),
outerRadius: outerRadius.interpolate(to: to.outerRadius, amount: amount),
innerRadius: innerRadius.interpolate(to: to.innerRadius, amount: amount),
outerRoundness: outerRoundness.interpolate(to: to.outerRoundness, amount: amount),
innerRoundness: innerRoundness.interpolate(to: to.innerRoundness, amount: amount),
points: points.interpolate(to: to.points, amount: amount),
rotation: rotation.interpolate(to: to.rotation, amount: amount))
}
}
/// Creates a single array of animatable keyframes from the separate arrays of keyframes in this star/polygon
func combinedKeyframes() throws -> KeyframeGroup<Keyframe> {
Keyframes.combined(
position,
outerRadius,
innerRadius ?? KeyframeGroup(LottieVector1D(0)),
outerRoundness,
innerRoundness ?? KeyframeGroup(LottieVector1D(0)),
points,
rotation,
makeCombinedResult: Star.Keyframe.init)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/StarAnimation.swift
|
Swift
|
unknown
| 3,717
|
// Created by Cal Stephens on 2/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - StrokeShapeItem
/// A `ShapeItem` that represents a stroke
protocol StrokeShapeItem: ShapeItem, OpacityAnimationModel {
var strokeColor: KeyframeGroup<LottieColor>? { get }
var width: KeyframeGroup<LottieVector1D> { get }
var lineCap: LineCap { get }
var lineJoin: LineJoin { get }
var miterLimit: Double { get }
var dashPattern: [DashElement]? { get }
func copy(width: KeyframeGroup<LottieVector1D>) -> StrokeShapeItem
}
// MARK: - Stroke + StrokeShapeItem
extension Stroke: StrokeShapeItem {
var strokeColor: KeyframeGroup<LottieColor>? { color }
func copy(width: KeyframeGroup<LottieVector1D>) -> StrokeShapeItem {
// Type-erase the copy from `Stroke` to `StrokeShapeItem`
let copy: Stroke = copy(width: width)
return copy
}
}
// MARK: - GradientStroke + StrokeShapeItem
extension GradientStroke: StrokeShapeItem {
var strokeColor: KeyframeGroup<LottieColor>? { nil }
func copy(width: KeyframeGroup<LottieVector1D>) -> StrokeShapeItem {
// Type-erase the copy from `GradientStroke` to `StrokeShapeItem`
let copy: GradientStroke = copy(width: width)
return copy
}
}
// MARK: - CAShapeLayer + StrokeShapeItem
extension CAShapeLayer {
/// Adds animations for properties related to the given `Stroke` object (`strokeColor`, `lineWidth`, etc)
@nonobjc
func addStrokeAnimations(for stroke: StrokeShapeItem, context: LayerAnimationContext) throws {
lineJoin = stroke.lineJoin.caLineJoin
lineCap = stroke.lineCap.caLineCap
miterLimit = CGFloat(stroke.miterLimit)
if let strokeColor = stroke.strokeColor {
try addAnimation(
for: .strokeColor,
keyframes: strokeColor,
value: \.cgColorValue,
context: context)
}
try addAnimation(
for: .lineWidth,
keyframes: stroke.width,
value: \.cgFloatValue,
context: context)
try addOpacityAnimation(for: stroke, context: context)
if let (dashPattern, dashPhase) = stroke.dashPattern?.shapeLayerConfiguration {
let lineDashPattern = try dashPattern.map {
try KeyframeGroup(keyframes: $0)
.exactlyOneKeyframe(context: context, description: "stroke dashPattern").cgFloatValue
}
if lineDashPattern.isSupportedLayerDashPattern {
self.lineDashPattern = lineDashPattern as [NSNumber]
}
try addAnimation(
for: .lineDashPhase,
keyframes: KeyframeGroup(keyframes: dashPhase),
value: \.cgFloatValue,
context: context)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/StrokeAnimation.swift
|
Swift
|
unknown
| 2,626
|
// Created by Cal Stephens on 12/17/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - TransformModel
/// This protocol mirrors the interface of `Transform`,
/// but is also implemented by `ShapeTransform` to allow
/// both transform types to share the same animation implementation.
protocol TransformModel {
/// The anchor point of the transform.
var anchorPoint: KeyframeGroup<LottieVector3D> { get }
/// The position of the transform. This is nil if the position data was split.
var _position: KeyframeGroup<LottieVector3D>? { get }
/// The positionX of the transform. This is nil if the position property is set.
var _positionX: KeyframeGroup<LottieVector1D>? { get }
/// The positionY of the transform. This is nil if the position property is set.
var _positionY: KeyframeGroup<LottieVector1D>? { get }
/// The scale of the transform
var scale: KeyframeGroup<LottieVector3D> { get }
/// The rotation of the transform on X axis.
var rotationX: KeyframeGroup<LottieVector1D> { get }
/// The rotation of the transform on Y axis.
var rotationY: KeyframeGroup<LottieVector1D> { get }
/// The rotation of the transform on Z axis.
var rotationZ: KeyframeGroup<LottieVector1D> { get }
/// The skew of the transform (only present on `ShapeTransform`s)
var _skew: KeyframeGroup<LottieVector1D>? { get }
/// The skew axis of the transform (only present on `ShapeTransform`s)
var _skewAxis: KeyframeGroup<LottieVector1D>? { get }
}
// MARK: - Transform + TransformModel
extension Transform: TransformModel {
var _position: KeyframeGroup<LottieVector3D>? { position }
var _positionX: KeyframeGroup<LottieVector1D>? { positionX }
var _positionY: KeyframeGroup<LottieVector1D>? { positionY }
var _skew: KeyframeGroup<LottieVector1D>? { nil }
var _skewAxis: KeyframeGroup<LottieVector1D>? { nil }
}
// MARK: - ShapeTransform + TransformModel
extension ShapeTransform: TransformModel {
var anchorPoint: KeyframeGroup<LottieVector3D> { anchor }
var _position: KeyframeGroup<LottieVector3D>? { position }
var _positionX: KeyframeGroup<LottieVector1D>? { nil }
var _positionY: KeyframeGroup<LottieVector1D>? { nil }
var _skew: KeyframeGroup<LottieVector1D>? { skew }
var _skewAxis: KeyframeGroup<LottieVector1D>? { skewAxis }
}
// MARK: - CALayer + TransformModel
extension CALayer {
// MARK: Internal
/// Adds transform-related animations from the given `TransformModel` to this layer
/// - This _doesn't_ apply `transform.opacity`, which has to be handled separately
/// since child layers don't inherit the `opacity` of their parent.
@nonobjc
func addTransformAnimations(
for transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
if
// CALayers don't support animating skew with its own set of keyframes.
// If the transform includes a skew, we have to combine all of the transform
// components into a single set of keyframes.
transformModel.hasSkew
// Negative `scale.x` values aren't applied correctly by Core Animation when animating
// `transform.scale.x` and `transform.scale.y` using separate `CAKeyframeAnimation`s
// (https://openradar.appspot.com/FB9862872). If the transform includes negative `scale.x`
// values, we have to combine all of the transform components into a single set of keyframes.
|| transformModel.hasNegativeXScaleValues
{
try addCombinedTransformAnimation(for: transformModel, context: context)
}
else {
try addPositionAnimations(from: transformModel, context: context)
try addAnchorPointAnimation(from: transformModel, context: context)
try addScaleAnimations(from: transformModel, context: context)
try addRotationAnimations(from: transformModel, context: context)
}
}
// MARK: Private
@nonobjc
private func addPositionAnimations(
from transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
if let positionKeyframes = transformModel._position {
try addAnimation(
for: .position,
keyframes: positionKeyframes,
value: \.pointValue,
context: context)
} else if
let xKeyframes = transformModel._positionX,
let yKeyframes = transformModel._positionY
{
try addAnimation(
for: .positionX,
keyframes: xKeyframes,
value: \.cgFloatValue,
context: context)
try addAnimation(
for: .positionY,
keyframes: yKeyframes,
value: \.cgFloatValue,
context: context)
} else {
try context.logCompatibilityIssue("""
`Transform` values must provide either `position` or `positionX` / `positionY` keyframes
""")
}
}
@nonobjc
private func addAnchorPointAnimation(
from transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
try addAnimation(
for: .anchorPoint,
keyframes: transformModel.anchorPoint,
value: { absoluteAnchorPoint in
guard bounds.width > 0, bounds.height > 0 else {
context.logger.assertionFailure("Size must be non-zero before an animation can be played")
return .zero
}
// Lottie animation files express anchorPoint as an absolute point value,
// so we have to divide by the width/height of this layer to get the
// relative decimal values expected by Core Animation.
return CGPoint(
x: CGFloat(absoluteAnchorPoint.x) / bounds.width,
y: CGFloat(absoluteAnchorPoint.y) / bounds.height)
},
context: context)
}
@nonobjc
private func addScaleAnimations(
from transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
try addAnimation(
for: .scaleX,
keyframes: transformModel.scale,
value: { scale in
// Lottie animation files express scale as a numerical percentage value
// (e.g. 50%, 100%, 200%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.5, 1.0, 2.0).
CGFloat(scale.x) / 100
},
context: context)
try addAnimation(
for: .scaleY,
keyframes: transformModel.scale,
value: { scale in
// Lottie animation files express scale as a numerical percentage value
// (e.g. 50%, 100%, 200%) so we divide by 100 to get the decimal values
// expected by Core Animation (e.g. 0.5, 1.0, 2.0).
CGFloat(scale.y) / 100
},
context: context)
}
private func addRotationAnimations(
from transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
let containsXRotationValues = transformModel.rotationX.keyframes.contains(where: { $0.value.cgFloatValue != 0 })
let containsYRotationValues = transformModel.rotationY.keyframes.contains(where: { $0.value.cgFloatValue != 0 })
// When `rotation.x` or `rotation.y` is used, it doesn't render property in test snapshots
// but do renders correctly on the simulator / device
if TestHelpers.snapshotTestsAreRunning {
if containsXRotationValues {
context.logger.warn("""
`rotation.x` values are not displayed correctly in snapshot tests
""")
}
if containsYRotationValues {
context.logger.warn("""
`rotation.y` values are not displayed correctly in snapshot tests
""")
}
}
// Lottie animation files express rotation in degrees
// (e.g. 90º, 180º, 360º) so we convert to radians to get the
// values expected by Core Animation (e.g. π/2, π, 2π)
try addAnimation(
for: .rotationX,
keyframes: transformModel.rotationX,
value: { rotationDegrees in
rotationDegrees.cgFloatValue * .pi / 180
},
context: context)
try addAnimation(
for: .rotationY,
keyframes: transformModel.rotationY,
value: { rotationDegrees in
rotationDegrees.cgFloatValue * .pi / 180
},
context: context)
try addAnimation(
for: .rotationZ,
keyframes: transformModel.rotationZ,
value: { rotationDegrees in
// Lottie animation files express rotation in degrees
// (e.g. 90º, 180º, 360º) so we convert to radians to get the
// values expected by Core Animation (e.g. π/2, π, 2π)
rotationDegrees.cgFloatValue * .pi / 180
},
context: context)
}
/// Adds an animation for the entire `transform` key by combining all of the
/// position / size / rotation / skew animations into a single set of keyframes.
/// This is more expensive that animating each component separately, since
/// it may require manually interpolating the keyframes at each frame.
private func addCombinedTransformAnimation(
for transformModel: TransformModel,
context: LayerAnimationContext)
throws
{
let requiresManualInterpolation =
// Core Animation doesn't animate skew changes properly. If the skew value
// changes over the course of the animation then we have to manually
// compute the `CATransform3D` for each frame individually.
transformModel.hasSkewAnimation
// `addAnimation` requires that we use an `Interpolatable` value, but we can't interpolate a `CATransform3D`.
// Since this is only necessary when using `complexTimeRemapping`, we can avoid this by manually interpolating
// when `context.mustUseComplexTimeRemapping` is true and just returning a `Hold` container.
// Since our keyframes are already manually interpolated, they won't need to be interpolated again.
|| context.mustUseComplexTimeRemapping
let combinedTransformKeyframes = Keyframes.combined(
transformModel.anchorPoint,
transformModel._position ?? KeyframeGroup(LottieVector3D(x: 0.0, y: 0.0, z: 0.0)),
transformModel._positionX ?? KeyframeGroup(LottieVector1D(0)),
transformModel._positionY ?? KeyframeGroup(LottieVector1D(0)),
transformModel.scale,
transformModel.rotationX,
transformModel.rotationY,
transformModel.rotationZ,
transformModel._skew ?? KeyframeGroup(LottieVector1D(0)),
transformModel._skewAxis ?? KeyframeGroup(LottieVector1D(0)),
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: {
anchor, position, positionX, positionY, scale, rotationX, rotationY, rotationZ, skew, skewAxis
-> Hold<CATransform3D> in
let transformPosition: CGPoint
if transformModel._positionX != nil, transformModel._positionY != nil {
transformPosition = CGPoint(x: positionX.cgFloatValue, y: positionY.cgFloatValue)
} else {
transformPosition = position.pointValue
}
let transform = CATransform3D.makeTransform(
anchor: anchor.pointValue,
position: transformPosition,
scale: scale.sizeValue,
rotationX: rotationX.cgFloatValue,
rotationY: rotationY.cgFloatValue,
rotationZ: rotationZ.cgFloatValue,
skew: skew.cgFloatValue,
skewAxis: skewAxis.cgFloatValue)
return Hold(value: transform)
})
try addAnimation(
for: .transform,
keyframes: combinedTransformKeyframes,
value: { $0.value },
context: context)
}
}
extension TransformModel {
/// Whether or not this transform has a non-zero skew value
var hasSkew: Bool {
guard
let _skew,
let _skewAxis,
!_skew.keyframes.isEmpty,
!_skewAxis.keyframes.isEmpty
else {
return false
}
return _skew.keyframes.contains(where: { $0.value.cgFloatValue != 0 })
}
/// Whether or not this transform has a non-zero skew value which animates
var hasSkewAnimation: Bool {
guard
hasSkew,
let _skew,
let _skewAxis
else { return false }
return _skew.keyframes.count > 1
|| _skewAxis.keyframes.count > 1
}
/// Whether or not this `TransformModel` has any negative X scale values
var hasNegativeXScaleValues: Bool {
scale.keyframes.contains(where: { $0.value.x < 0 })
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/TransformAnimations.swift
|
Swift
|
unknown
| 12,198
|
// Created by Cal Stephens on 12/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
extension CALayer {
/// Adds an animation for the given `inTime` and `outTime` to this `CALayer`
@nonobjc
func addVisibilityAnimation(
inFrame: AnimationFrameTime,
outFrame: AnimationFrameTime,
context: LayerAnimationContext)
throws
{
/// If this layer uses `complexTimeRemapping`, use the `addAnimation` codepath
/// which uses `Keyframes.manuallyInterpolatedWithTimeRemapping`.
if context.mustUseComplexTimeRemapping {
let isHiddenKeyframes = KeyframeGroup(keyframes: [
Keyframe(value: true, time: 0, isHold: true), // hidden, before `inFrame`
Keyframe(value: false, time: inFrame, isHold: true), // visible
Keyframe(value: true, time: outFrame, isHold: true), // hidden, after `outFrame`
])
try addAnimation(
for: .isHidden,
keyframes: isHiddenKeyframes.map { Hold(value: $0) },
value: { $0.value },
context: context)
}
/// Otherwise continue using the legacy codepath that doesn't support complex time remapping.
/// - TODO: We could remove this codepath in favor of always using the simpler codepath above,
/// but would have to solve https://github.com/airbnb/lottie-ios/pull/2254 for that codepath.
else {
let animation = CAKeyframeAnimation(keyPath: #keyPath(isHidden))
animation.calculationMode = .discrete
animation.values = [
true, // hidden, before `inFrame`
false, // visible
true, // hidden, after `outFrame`
]
// From the documentation of `keyTimes`:
// - If the calculationMode is set to discrete, the first value in the array
// must be 0.0 and the last value must be 1.0. The array should have one more
// entry than appears in the values array. For example, if there are two values,
// there should be three key times.
animation.keyTimes = [
NSNumber(value: 0.0),
NSNumber(value: max(Double(try context.progressTime(for: inFrame)), 0)),
// Anything visible during the last frame should stay visible until the absolute end of the animation.
// - This matches the behavior of the main thread rendering engine.
context.simpleTimeRemapping(outFrame) == context.animation.endFrame
? NSNumber(value: Double(1.0))
: NSNumber(value: min(Double(try context.progressTime(for: outFrame)), 1)),
NSNumber(value: 1.0),
]
add(animation, timedWith: context)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Animations/VisibilityAnimation.swift
|
Swift
|
unknown
| 2,601
|
// Created by Cal Stephens on 5/4/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
// MARK: - CompatibilityIssue
/// A compatibility issue that was encountered while setting up an animation with the Core Animation engine
struct CompatibilityIssue: CustomStringConvertible {
let message: String
let context: String
var description: String {
"[\(context)] \(message)"
}
}
// MARK: - CompatibilityTracker
/// A type that tracks whether or not an animation is compatible with the Core Animation engine
final class CompatibilityTracker {
// MARK: Lifecycle
init(mode: Mode, logger: LottieLogger) {
self.mode = mode
self.logger = logger
}
// MARK: Internal
/// How compatibility issues should be handled
enum Mode {
/// When a compatibility issue is encountered, an error will be thrown immediately,
/// aborting the animation setup process as soon as possible.
case abort
/// When a compatibility issue is encountered, it is stored in `CompatibilityTracker.issues`
case track
}
enum Error: Swift.Error {
case encounteredCompatibilityIssue(CompatibilityIssue)
}
/// Records a compatibility issue that will be reported according to `CompatibilityTracker.Mode`
func logIssue(message: String, context: String) throws {
logger.assert(!context.isEmpty, "Compatibility issue context is unexpectedly empty")
let issue = CompatibilityIssue(
// Compatibility messages are usually written in source files using multi-line strings,
// but converting them to be a single line makes it easier to read the ultimate log output.
message: message.replacingOccurrences(of: "\n", with: " "),
context: context)
switch mode {
case .abort:
throw CompatibilityTracker.Error.encounteredCompatibilityIssue(issue)
case .track:
issues.append(issue)
}
}
/// Asserts that a condition is true, otherwise logs a compatibility issue that will be reported
/// according to `CompatibilityTracker.Mode`
func assert(
_ condition: Bool,
_ message: @autoclosure () -> String,
context: @autoclosure () -> String)
throws
{
if !condition {
try logIssue(message: message(), context: context())
}
}
/// Reports the compatibility issues that were recorded when setting up the animation,
/// and clears the set of tracked issues.
func reportCompatibilityIssues(_ handler: ([CompatibilityIssue]) -> Void) {
handler(issues)
issues = []
}
// MARK: Private
private let mode: Mode
private let logger: LottieLogger
/// Compatibility issues encountered while setting up the animation
private var issues = [CompatibilityIssue]()
}
// MARK: - CompatibilityTrackerProviding
protocol CompatibilityTrackerProviding {
var compatibilityTracker: CompatibilityTracker { get }
var compatibilityIssueContext: String { get }
}
extension CompatibilityTrackerProviding {
/// Records a compatibility issue that will be reported according to `CompatibilityTracker.Mode`
func logCompatibilityIssue(_ message: String) throws {
try compatibilityTracker.logIssue(message: message, context: compatibilityIssueContext)
}
/// Asserts that a condition is true, otherwise logs a compatibility issue that will be reported
/// according to `CompatibilityTracker.Mode`
func compatibilityAssert(
_ condition: Bool,
_ message: @autoclosure () -> String)
throws
{
try compatibilityTracker.assert(condition, message(), context: compatibilityIssueContext)
}
}
// MARK: - LayerContext + CompatibilityTrackerProviding
extension LayerContext: CompatibilityTrackerProviding {
var compatibilityIssueContext: String {
layerName
}
}
// MARK: - LayerAnimationContext + CompatibilityTrackerProviding
extension LayerAnimationContext: CompatibilityTrackerProviding {
var compatibilityIssueContext: String {
currentKeypath.fullPath
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/CompatibilityTracker.swift
|
Swift
|
unknown
| 3,920
|
// Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - CoreAnimationLayer
/// The root `CALayer` of the Core Animation rendering engine
final class CoreAnimationLayer: BaseAnimationLayer {
// MARK: Lifecycle
/// Initializes a `CALayer` that renders the given animation using `CAAnimation`s.
/// - This initializer is throwing, but will only throw when using
/// `CompatibilityTracker.Mode.abort`.
init(
animation: LottieAnimation,
imageProvider: AnimationImageProvider,
textProvider: AnimationKeypathTextProvider,
fontProvider: AnimationFontProvider,
maskAnimationToBounds: Bool,
compatibilityTrackerMode: CompatibilityTracker.Mode,
logger: LottieLogger)
throws
{
self.animation = animation
self.imageProvider = imageProvider
self.textProvider = textProvider
self.fontProvider = fontProvider
self.logger = logger
compatibilityTracker = CompatibilityTracker(mode: compatibilityTrackerMode, logger: logger)
valueProviderStore = ValueProviderStore(logger: logger)
super.init()
masksToBounds = maskAnimationToBounds
setup()
try setupChildLayers()
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("init(layer:) incorrectly called with \(type(of: layer))")
}
animation = typedLayer.animation
currentAnimationConfiguration = typedLayer.currentAnimationConfiguration
imageProvider = typedLayer.imageProvider
textProvider = typedLayer.textProvider
fontProvider = typedLayer.fontProvider
didSetUpAnimation = typedLayer.didSetUpAnimation
compatibilityTracker = typedLayer.compatibilityTracker
logger = typedLayer.logger
valueProviderStore = typedLayer.valueProviderStore
super.init(layer: typedLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
/// Timing-related configuration to apply to this layer's child `CAAnimation`s
/// - This is effectively a configurable subset of `CAMediaTiming`
struct CAMediaTimingConfiguration: Equatable {
var autoreverses = false
var repeatCount: Float = 0
var speed: Float = 1
var timeOffset: TimeInterval = 0
}
enum PlaybackState: Equatable {
/// The animation is has started playing, and may still be playing.
/// - When animating with a finite duration (e.g. `playOnce`), playback
/// state will still be `playing` when the animation completes.
/// To check if the animation is currently playing, prefer `isAnimationPlaying`.
case playing
/// The animation is statically displaying a specific frame
case paused(frame: AnimationFrameTime)
}
/// Configuration used by the `playAnimation` method
struct AnimationConfiguration: Equatable {
var animationContext: AnimationContext
var timingConfiguration: CAMediaTimingConfiguration
var recordHierarchyKeypath: ((String) -> Void)?
static func ==(_ lhs: AnimationConfiguration, _ rhs: AnimationConfiguration) -> Bool {
lhs.animationContext == rhs.animationContext
&& lhs.timingConfiguration == rhs.timingConfiguration
&& ((lhs.recordHierarchyKeypath == nil) == (rhs.recordHierarchyKeypath == nil))
}
}
/// The parent `LottieAnimationLayer` that manages this layer
weak var lottieAnimationLayer: LottieAnimationLayer?
/// A closure that is called after this layer sets up its animation.
/// If the animation setup was unsuccessful and encountered compatibility issues,
/// those issues are included in this call.
var didSetUpAnimation: (([CompatibilityIssue]) -> Void)?
/// The `AnimationImageProvider` that `ImageLayer`s use to retrieve images,
/// referenced by name in the animation json.
var imageProvider: AnimationImageProvider {
didSet { reloadImages() }
}
/// The `AnimationKeypathTextProvider` that `TextLayer`'s use to retrieve texts,
/// that they should use to render their text context
var textProvider: AnimationKeypathTextProvider {
didSet {
// We need to rebuild the current animation after updating the text provider,
// since this is used in `TextLayer.setupAnimations(context:)`
rebuildCurrentAnimation()
}
}
/// The `FontProvider` that `TextLayer`s use to retrieve the `CTFont`
/// that they should use to render their text content
var fontProvider: AnimationFontProvider {
didSet { reloadFonts() }
}
/// Queues the animation with the given timing configuration
/// to begin playing at the next `display()` call.
/// - This batches together animations so that even if `playAnimation`
/// is called multiple times in the same run loop cycle, the animation
/// will only be set up a single time.
func playAnimation(
configuration: AnimationConfiguration,
playbackState: PlaybackState = .playing)
{
pendingAnimationConfiguration = (
animationConfiguration: configuration,
playbackState: playbackState)
setNeedsDisplay()
}
override func layoutSublayers() {
super.layoutSublayers()
// If no animation has been set up yet, display the first frame
// now that the layer hierarchy has been setup and laid out
if
pendingAnimationConfiguration == nil,
currentAnimationConfiguration == nil,
bounds.size != .zero
{
currentFrame = animation.frameTime(forProgress: animationProgress)
}
}
override func display() {
// We intentionally don't call `super.display()`, since this layer
// doesn't directly render any content.
// - This fixes an issue where certain animations would unexpectedly
// allocate a very large amount of memory (400mb+).
// - Alternatively this layer could subclass `CATransformLayer`,
// but this causes Core Animation to emit unnecessary logs.
if var pendingAnimationConfiguration {
pendingAnimationConfigurationModification?(&pendingAnimationConfiguration.animationConfiguration)
pendingAnimationConfigurationModification = nil
self.pendingAnimationConfiguration = nil
do {
try setupAnimation(for: pendingAnimationConfiguration.animationConfiguration)
} catch {
if case CompatibilityTracker.Error.encounteredCompatibilityIssue(let compatibilityIssue) = error {
// Even though the animation setup failed, we still update the layer's playback state
// so it can be read by the parent `LottieAnimationView` when handling this error
currentPlaybackState = pendingAnimationConfiguration.playbackState
didSetUpAnimation?([compatibilityIssue])
return
}
}
currentPlaybackState = pendingAnimationConfiguration.playbackState
compatibilityTracker.reportCompatibilityIssues { compatibilityIssues in
didSetUpAnimation?(compatibilityIssues)
}
}
}
// MARK: Private
/// The configuration for the most recent animation which has been
/// queued by calling `playAnimation` but not yet actually set up
private var pendingAnimationConfiguration: (
animationConfiguration: AnimationConfiguration,
playbackState: PlaybackState)?
/// A modification that should be applied to the next animation configuration
private var pendingAnimationConfigurationModification: ((inout AnimationConfiguration) -> Void)?
/// Configuration for the animation that is currently setup in this layer
private var currentAnimationConfiguration: AnimationConfiguration?
/// The current progress of the placeholder `CAAnimation`,
/// which is also the realtime animation progress of this layer's animation
@objc private var animationProgress: CGFloat = 0
private let animation: LottieAnimation
private let valueProviderStore: ValueProviderStore
private let compatibilityTracker: CompatibilityTracker
private let logger: LottieLogger
private let loggingState = LoggingState()
/// The current playback state of the animation that is displayed in this layer
private var currentPlaybackState: PlaybackState? {
didSet {
guard playbackState != oldValue else { return }
switch playbackState {
case .playing, nil:
timeOffset = 0
case .paused(let frame):
timeOffset = animation.time(forFrame: frame)
}
}
}
/// The current or pending playback state of the animation displayed in this layer
private var playbackState: PlaybackState? {
pendingAnimationConfiguration?.playbackState ?? currentPlaybackState
}
/// Context used when setting up and configuring sublayers
private var layerContext: LayerContext {
LayerContext(
animation: animation,
imageProvider: imageProvider,
textProvider: textProvider,
fontProvider: fontProvider,
compatibilityTracker: compatibilityTracker,
layerName: "root layer")
}
private func setup() {
bounds = animation.bounds
}
private func setupChildLayers() throws {
try setupLayerHierarchy(
for: animation.layers,
context: layerContext)
try validateReasonableNumberOfTimeRemappingLayers()
}
/// Immediately builds and begins playing `CAAnimation`s for each sublayer
private func setupAnimation(for configuration: AnimationConfiguration) throws {
// Remove any existing animations from the layer hierarchy
removeAnimations()
currentAnimationConfiguration = configuration
let layerContext = LayerAnimationContext(
animation: animation,
timingConfiguration: configuration.timingConfiguration,
startFrame: configuration.animationContext.playFrom,
endFrame: configuration.animationContext.playTo,
valueProviderStore: valueProviderStore,
compatibilityTracker: compatibilityTracker,
logger: logger,
loggingState: loggingState,
currentKeypath: AnimationKeypath(keys: []),
textProvider: textProvider,
recordHierarchyKeypath: configuration.recordHierarchyKeypath)
// Perform a layout pass if necessary so all of the sublayers
// have the most up-to-date sizing information
layoutIfNeeded()
// Set the speed of this layer, which will be inherited
// by all sublayers and their animations.
// - This is required to support scrubbing with a speed of 0
speed = configuration.timingConfiguration.speed
// Setup a placeholder animation to let us track the realtime animation progress
setupPlaceholderAnimation(context: layerContext)
// Set up the new animations with the current `TimingConfiguration`
for animationLayer in sublayers ?? [] {
try (animationLayer as? AnimationLayer)?.setupAnimations(context: layerContext)
}
}
/// Sets up a placeholder `CABasicAnimation` that tracks the current
/// progress of this animation (between 0 and 1). This lets us provide
/// realtime animation progress via `self.currentFrame`.
private func setupPlaceholderAnimation(context: LayerAnimationContext) {
let animationProgressTracker = CABasicAnimation(keyPath: #keyPath(animationProgress))
animationProgressTracker.fromValue = 0
animationProgressTracker.toValue = 1
let timedProgressAnimation = animationProgressTracker.timed(with: context, for: self)
timedProgressAnimation.delegate = currentAnimationConfiguration?.animationContext.closure
// Remove the progress animation once complete so we know when the animation
// has finished playing (if it doesn't loop infinitely)
timedProgressAnimation.isRemovedOnCompletion = true
add(timedProgressAnimation, forKey: #keyPath(animationProgress))
}
// Removes the current `CAAnimation`s, and rebuilds new animations
// using the same configuration as the previous animations.
private func rebuildCurrentAnimation() {
guard
// Don't replace any pending animations that are queued to begin
// on the next run loop cycle, since an existing pending animation
// will cause the animation to be rebuilt anyway.
pendingAnimationConfiguration == nil
else { return }
if isAnimationPlaying == true {
lottieAnimationLayer?.updateInFlightAnimation()
} else {
let currentFrame = currentFrame
removeAnimations()
self.currentFrame = currentFrame
}
}
}
// MARK: RootAnimationLayer
extension CoreAnimationLayer: RootAnimationLayer {
var primaryAnimationKey: AnimationKey {
.specific(#keyPath(animationProgress))
}
/// Whether or not the animation is currently playing.
/// - Handles case where CAAnimations with a finite duration animation (e.g. `playOnce`)
/// have finished playing but still present on this layer.
var isAnimationPlaying: Bool? {
switch pendingAnimationConfiguration?.playbackState {
case .playing:
return true
case .paused:
return false
case nil:
switch playbackState {
case .playing:
return animation(forKey: #keyPath(animationProgress)) != nil
case nil, .paused:
return false
}
}
}
/// The current frame of the animation being displayed,
/// accounting for the realtime progress of any active CAAnimations.
var currentFrame: AnimationFrameTime {
get {
switch playbackState {
case .paused(let frame):
return frame
case .playing, nil:
// When in the `playing` state, the animation is either actively playing
// or is completed on the final frame of a non-repeating animation.
// When a non-repeating animation is complete, `animation(forKey: #keyPath(animationProgress))`
// is no longer present and the Core-Animation-managed `animationProgress` value is just 0.
// In that case, since the animation is complete, we just return the final frame that was played to.
let animationCurrentlyPlaying = animation(forKey: #keyPath(animationProgress)) != nil
if !animationCurrentlyPlaying, let configuration = currentAnimationConfiguration {
return configuration.animationContext.playTo
} else {
return animation.frameTime(forProgress: (presentation() ?? self).animationProgress)
}
}
}
set {
// We can display a specific frame of the animation by setting
// `timeOffset` of this layer. This requires setting up the layer hierarchy
// with a specific configuration (speed=0, etc) at least once. But if
// the layer hierarchy is already set up correctly, we can update the
// `timeOffset` very cheaply.
let requiredAnimationConfiguration = AnimationConfiguration(
animationContext: AnimationContext(
playFrom: animation.startFrame,
// Normal animation playback (like when looping) skips the last frame.
// However when the animation is paused, we need to be able to render the final frame.
// To allow this we have to extend the length of the animation by one frame.
playTo: animation.endFrame + 1,
closure: nil),
timingConfiguration: CAMediaTimingConfiguration(speed: 0))
if
pendingAnimationConfiguration == nil,
currentAnimationConfiguration == requiredAnimationConfiguration
{
currentPlaybackState = .paused(frame: newValue)
}
else {
playAnimation(
configuration: requiredAnimationConfiguration,
playbackState: .paused(frame: newValue))
}
}
}
var renderScale: CGFloat {
get { contentsScale }
set {
contentsScale = newValue
for sublayer in allSublayers {
sublayer.contentsScale = newValue
}
}
}
var respectAnimationFrameRate: Bool {
get { false }
set {
logger.assertionFailure("""
The Core Animation rendering engine currently doesn't support `respectAnimationFrameRate`)
""")
}
}
var _animationLayers: [CALayer] {
(sublayers ?? []).filter { $0 is AnimationLayer }
}
func reloadImages() {
// When the image provider changes, we have to update all `ImageLayer`s
// so they can query the most up-to-date image from the new image provider.
for sublayer in allSublayers {
if let imageLayer = sublayer as? ImageLayer {
imageLayer.setupImage(context: layerContext)
}
}
}
func reloadFonts() {
// When the text provider changes, we have to update all `TextLayer`s
// so they can query the most up-to-date font from the new font provider.
for sublayer in allSublayers {
if let textLayer = sublayer as? TextLayer {
try? textLayer.configureRenderLayer(with: layerContext)
}
}
}
func forceDisplayUpdate() {
// Unimplemented
// - We can't call `display()` here, because it would cause unexpected frame animations:
// https://github.com/airbnb/lottie-ios/issues/2193
}
func logHierarchyKeypaths() {
for keypath in allHierarchyKeypaths() {
logger.info(keypath)
}
}
func allHierarchyKeypaths() -> [String] {
guard pendingAnimationConfiguration?.animationConfiguration ?? currentAnimationConfiguration != nil else {
logger.info("Cannot log hierarchy keypaths until animation has been set up at least once")
return []
}
logger.info("Lottie: Rebuilding animation with hierarchy keypath logging enabled")
var allAnimationKeypaths = [String]()
pendingAnimationConfigurationModification = { configuration in
configuration.recordHierarchyKeypath = { keypath in
allAnimationKeypaths.append(keypath)
}
}
rebuildCurrentAnimation()
displayIfNeeded()
return allAnimationKeypaths
}
func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
valueProviderStore.setValueProvider(valueProvider, keypath: keypath)
// We need to rebuild the current animation after registering a value provider,
// since any existing `CAAnimation`s could now be out of date.
rebuildCurrentAnimation()
}
func getValue(for _: AnimationKeypath, atFrame _: AnimationFrameTime?) -> Any? {
logger.assertionFailure("""
The Core Animation rendering engine doesn't support querying values for individual frames
""")
return nil
}
func getOriginalValue(for _: AnimationKeypath, atFrame _: AnimationFrameTime?) -> Any? {
logger.assertionFailure("""
The Core Animation rendering engine doesn't support querying values for individual frames
""")
return nil
}
func layer(for _: AnimationKeypath) -> CALayer? {
logger.assertionFailure("""
The Core Animation rendering engine doesn't support retrieving `CALayer`s by keypath
""")
return nil
}
func animatorNodes(for _: AnimationKeypath) -> [AnimatorNode]? {
logger.assertionFailure("""
The Core Animation rendering engine does not use `AnimatorNode`s
""")
return nil
}
func removeAnimations() {
currentAnimationConfiguration = nil
currentPlaybackState = nil
removeAllAnimations()
for sublayer in allSublayers {
sublayer.removeAllAnimations()
}
}
/// Time remapping in the Core Animation rendering engine requires manually interpolating
/// every frame of every animation. For very large animations with a huge number of layers,
/// this can be prohibitively expensive.
func validateReasonableNumberOfTimeRemappingLayers() throws {
try layerContext.compatibilityAssert(
numberOfLayersWithTimeRemapping < 500,
"""
This animation has a very large number of layers with time remapping (\(numberOfLayersWithTimeRemapping)),
so will perform poorly with the Core Animation rendering engine.
""")
}
}
// MARK: - CALayer + allSublayers
extension CALayer {
/// All of the layers in the layer tree that are descendants from this later
@nonobjc
var allSublayers: [CALayer] {
var allSublayers: [CALayer] = []
for sublayer in sublayers ?? [] {
allSublayers.append(sublayer)
allSublayers.append(contentsOf: sublayer.allSublayers)
}
return allSublayers
}
/// The number of layers in this layer hierarchy that have a time remapping applied
@nonobjc
var numberOfLayersWithTimeRemapping: Int {
var numberOfSublayersWithTimeRemapping = 0
for sublayer in sublayers ?? [] {
if
let preCompLayer = sublayer as? PreCompLayer,
preCompLayer.preCompLayer.timeRemapping != nil
{
numberOfSublayersWithTimeRemapping += preCompLayer.allSublayers.count
} else {
numberOfSublayersWithTimeRemapping += sublayer.numberOfLayersWithTimeRemapping
}
}
return numberOfSublayersWithTimeRemapping
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/CoreAnimationLayer.swift
|
Swift
|
unknown
| 20,875
|
// Created by Cal Stephens on 12/15/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - CALayer + fillBoundsOfSuperlayer
extension CALayer {
/// Updates the `bounds` of this layer to fill the bounds of its `superlayer`
/// without setting `frame` (which is not permitted if the layer can rotate)
@nonobjc
func fillBoundsOfSuperlayer() {
guard let superlayer else { return }
if let customLayerLayer = self as? CustomLayoutLayer {
customLayerLayer.layout(superlayerBounds: superlayer.bounds)
}
else {
// By default the `anchorPoint` of a layer is `CGPoint(x: 0.5, y: 0.5)`.
// Setting it to `.zero` makes the layer have the same coordinate space
// as its superlayer, which lets use use `superlayer.bounds` directly.
anchorPoint = .zero
bounds = superlayer.bounds
}
}
}
// MARK: - CustomLayoutLayer
/// A `CALayer` that sets a custom `bounds` and `anchorPoint` relative to its superlayer
protocol CustomLayoutLayer: CALayer {
func layout(superlayerBounds: CGRect)
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Extensions/CALayer+fillBounds.swift
|
Swift
|
unknown
| 1,075
|
// Created by Cal Stephens on 1/11/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
// MARK: - KeyframeGroup + exactlyOneKeyframe
extension KeyframeGroup {
/// Retrieves the first `Keyframe` from this group,
/// and asserts that there are not any extra keyframes that would be ignored
/// - This should only be used in cases where it's fundamentally not possible to
/// support animating a given property (e.g. if Core Animation itself doesn't
/// support the property).
func exactlyOneKeyframe(
context: CompatibilityTrackerProviding,
description: String,
fileID _: StaticString = #fileID,
line _: UInt = #line)
throws
-> T
{
try context.compatibilityAssert(
keyframes.count == 1,
"""
The Core Animation rendering engine does not support animating multiple keyframes
for \(description) values, due to limitations of Core Animation.
""")
return keyframes[0].value
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Extensions/KeyframeGroup+exactlyOneKeyframe.swift
|
Swift
|
unknown
| 965
|
// Created by Cal Stephens on 1/28/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
// MARK: - Keyframes
enum Keyframes {
// MARK: Internal
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T>(
_ allGroups: [KeyframeGroup<T>],
requiresManualInterpolation: Bool = false)
-> KeyframeGroup<[T]>
where T: AnyInterpolatable
{
Keyframes.combined(
allGroups,
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
untypedValues.compactMap { $0 as? T }
})
}
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T1, T2, CombinedResult>(
_ k1: KeyframeGroup<T1>,
_ k2: KeyframeGroup<T2>,
requiresManualInterpolation: Bool = false,
makeCombinedResult: (T1, T2) throws -> CombinedResult)
rethrows
-> KeyframeGroup<CombinedResult>
where T1: AnyInterpolatable, T2: AnyInterpolatable
{
try Keyframes.combined(
[k1, k2],
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
guard
let t1 = untypedValues[0] as? T1,
let t2 = untypedValues[1] as? T2
else { return nil }
return try makeCombinedResult(t1, t2)
})
}
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T1, T2, T3, CombinedResult>(
_ k1: KeyframeGroup<T1>,
_ k2: KeyframeGroup<T2>,
_ k3: KeyframeGroup<T3>,
requiresManualInterpolation: Bool = false,
makeCombinedResult: (T1, T2, T3) -> CombinedResult)
-> KeyframeGroup<CombinedResult>
where T1: AnyInterpolatable, T2: AnyInterpolatable, T3: AnyInterpolatable
{
Keyframes.combined(
[k1, k2, k3],
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
guard
let t1 = untypedValues[0] as? T1,
let t2 = untypedValues[1] as? T2,
let t3 = untypedValues[2] as? T3
else { return nil }
return makeCombinedResult(t1, t2, t3)
})
}
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T1, T2, T3, T4, T5, T6, T7, CombinedResult>(
_ k1: KeyframeGroup<T1>,
_ k2: KeyframeGroup<T2>,
_ k3: KeyframeGroup<T3>,
_ k4: KeyframeGroup<T4>,
_ k5: KeyframeGroup<T5>,
_ k6: KeyframeGroup<T6>,
_ k7: KeyframeGroup<T7>,
requiresManualInterpolation: Bool = false,
makeCombinedResult: (T1, T2, T3, T4, T5, T6, T7) -> CombinedResult)
-> KeyframeGroup<CombinedResult>
where T1: AnyInterpolatable, T2: AnyInterpolatable, T3: AnyInterpolatable, T4: AnyInterpolatable,
T5: AnyInterpolatable, T6: AnyInterpolatable, T7: AnyInterpolatable
{
Keyframes.combined(
[k1, k2, k3, k4, k5, k6, k7],
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
guard
let t1 = untypedValues[0] as? T1,
let t2 = untypedValues[1] as? T2,
let t3 = untypedValues[2] as? T3,
let t4 = untypedValues[3] as? T4,
let t5 = untypedValues[4] as? T5,
let t6 = untypedValues[5] as? T6,
let t7 = untypedValues[6] as? T7
else { return nil }
return makeCombinedResult(t1, t2, t3, t4, t5, t6, t7)
})
}
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T1, T2, T3, T4, T5, T6, T7, T8, CombinedResult>(
_ k1: KeyframeGroup<T1>,
_ k2: KeyframeGroup<T2>,
_ k3: KeyframeGroup<T3>,
_ k4: KeyframeGroup<T4>,
_ k5: KeyframeGroup<T5>,
_ k6: KeyframeGroup<T6>,
_ k7: KeyframeGroup<T7>,
_ k8: KeyframeGroup<T8>,
requiresManualInterpolation: Bool = false,
makeCombinedResult: (T1, T2, T3, T4, T5, T6, T7, T8) -> CombinedResult)
-> KeyframeGroup<CombinedResult>
where T1: AnyInterpolatable, T2: AnyInterpolatable, T3: AnyInterpolatable, T4: AnyInterpolatable,
T5: AnyInterpolatable, T6: AnyInterpolatable, T7: AnyInterpolatable, T8: AnyInterpolatable
{
Keyframes.combined(
[k1, k2, k3, k4, k5, k6, k7, k8],
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
guard
let t1 = untypedValues[0] as? T1,
let t2 = untypedValues[1] as? T2,
let t3 = untypedValues[2] as? T3,
let t4 = untypedValues[3] as? T4,
let t5 = untypedValues[4] as? T5,
let t6 = untypedValues[5] as? T6,
let t7 = untypedValues[6] as? T7,
let t8 = untypedValues[7] as? T8
else { return nil }
return makeCombinedResult(t1, t2, t3, t4, t5, t6, t7, t8)
})
}
/// Combines the given keyframe groups of `Keyframe<T>`s into a single keyframe group of of `Keyframe<[T]>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
static func combined<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, CombinedResult>(
_ k1: KeyframeGroup<T1>,
_ k2: KeyframeGroup<T2>,
_ k3: KeyframeGroup<T3>,
_ k4: KeyframeGroup<T4>,
_ k5: KeyframeGroup<T5>,
_ k6: KeyframeGroup<T6>,
_ k7: KeyframeGroup<T7>,
_ k8: KeyframeGroup<T8>,
_ k9: KeyframeGroup<T9>,
_ k10: KeyframeGroup<T10>,
requiresManualInterpolation: Bool = false,
makeCombinedResult: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> CombinedResult)
-> KeyframeGroup<CombinedResult>
where T1: AnyInterpolatable, T2: AnyInterpolatable, T3: AnyInterpolatable, T4: AnyInterpolatable,
T5: AnyInterpolatable, T6: AnyInterpolatable, T7: AnyInterpolatable, T8: AnyInterpolatable,
T9: AnyInterpolatable, T10: AnyInterpolatable
{
Keyframes.combined(
[k1, k2, k3, k4, k5, k6, k7, k8, k9, k10],
requiresManualInterpolation: requiresManualInterpolation,
makeCombinedResult: { untypedValues in
guard
let t1 = untypedValues[0] as? T1,
let t2 = untypedValues[1] as? T2,
let t3 = untypedValues[2] as? T3,
let t4 = untypedValues[3] as? T4,
let t5 = untypedValues[4] as? T5,
let t6 = untypedValues[5] as? T6,
let t7 = untypedValues[6] as? T7,
let t8 = untypedValues[7] as? T8,
let t9 = untypedValues[8] as? T9,
let t10 = untypedValues[9] as? T10
else { return nil }
return makeCombinedResult(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10)
})
}
// MARK: Private
/// Combines the given `[KeyframeGroup]` of `Keyframe<T>`s into a single `KeyframeGroup` of `Keyframe<CombinedResult>`s
/// - If all of the `KeyframeGroup`s have the exact same animation timing, the keyframes are merged
/// - Otherwise, the keyframes are manually interpolated at each frame in the animation
///
/// `makeCombinedResult` is a closure that takes an array of keyframe values (with the exact same length as `AnyKeyframeGroup`),
/// casts them to the expected type, and combined them into the final resulting keyframe.
///
/// `requiresManualInterpolation` determines whether the keyframes must be computed using `Keyframes.manuallyInterpolated`,
/// which interpolates the value at each frame, or if the keyframes can simply be combined.
private static func combined<CombinedResult>(
_ allGroups: [AnyKeyframeGroup],
requiresManualInterpolation: Bool,
makeCombinedResult: ([Any]) throws -> CombinedResult?)
rethrows
-> KeyframeGroup<CombinedResult>
{
let untypedGroups = allGroups.map { $0.untyped }
// Animations with no timing information (e.g. with just a single keyframe)
// can be trivially combined with any other set of keyframes, so we don't need
// to check those.
let animatingKeyframes = untypedGroups.filter { $0.keyframes.count > 1 }
guard
!requiresManualInterpolation,
!allGroups.isEmpty,
animatingKeyframes.allSatisfy({ $0.hasSameTimingParameters(as: animatingKeyframes[0]) })
else {
// If the keyframes don't all share the same timing information,
// we have to interpolate the value at each individual frame
return try Keyframes.manuallyInterpolated(allGroups, makeCombinedResult: makeCombinedResult)
}
var combinedKeyframes = ContiguousArray<Keyframe<CombinedResult>>()
let baseKeyframes = (animatingKeyframes.first ?? untypedGroups[0]).keyframes
for index in baseKeyframes.indices {
let baseKeyframe = baseKeyframes[index]
let untypedValues = untypedGroups.map { $0.valueForCombinedKeyframes(at: index) }
if let combinedValue = try makeCombinedResult(untypedValues) {
combinedKeyframes.append(baseKeyframe.withValue(combinedValue))
} else {
LottieLogger.shared.assertionFailure("""
Failed to cast untyped keyframe values to expected type. This is an internal error.
""")
}
}
return KeyframeGroup(keyframes: combinedKeyframes)
}
private static func manuallyInterpolated<CombinedResult>(
_ allGroups: [AnyKeyframeGroup],
makeCombinedResult: ([Any]) throws -> CombinedResult?)
rethrows
-> KeyframeGroup<CombinedResult>
{
let untypedGroups = allGroups.map { $0.untyped }
let untypedInterpolators = allGroups.map { $0.interpolator }
let times = untypedGroups.flatMap { $0.keyframes.map { $0.time } }
let minimumTime = times.min() ?? 0
let maximumTime = times.max() ?? 0
// We disable Core Animation interpolation when using manually interpolated keyframes,
// so we don't animate between these values. To prevent the animation from being choppy
// even at low playback speed, we have to interpolate at a very high fidelity.
let animationLocalTimeRange = stride(from: minimumTime, to: maximumTime, by: 0.1)
let interpolatedKeyframes = try animationLocalTimeRange.compactMap { localTime -> Keyframe<CombinedResult>? in
let interpolatedValues = untypedInterpolators.map { interpolator in
interpolator.value(frame: AnimationFrameTime(localTime))
}
guard let combinedResult = try makeCombinedResult(interpolatedValues) else {
LottieLogger.shared.assertionFailure("""
Failed to cast untyped keyframe values to expected type. This is an internal error.
""")
return nil
}
return Keyframe(
value: combinedResult,
time: AnimationFrameTime(localTime),
// Since we already manually interpolated the keyframes, have Core Animation display
// each value as a static keyframe rather than trying to interpolate between them.
isHold: true)
}
return KeyframeGroup(keyframes: ContiguousArray(interpolatedKeyframes))
}
}
extension KeyframeGroup {
/// Whether or not all of the keyframes in this `KeyframeGroup` have the same
/// timing parameters as the corresponding keyframe in the other given `KeyframeGroup`
func hasSameTimingParameters<U>(as other: KeyframeGroup<U>) -> Bool {
guard keyframes.count == other.keyframes.count else {
return false
}
return zip(keyframes, other.keyframes).allSatisfy {
$0.hasSameTimingParameters(as: $1)
}
}
}
extension Keyframe {
/// Whether or not this keyframe has the same timing parameters as the given keyframe,
/// excluding `spatialInTangent` and `spatialOutTangent`.
fileprivate func hasSameTimingParameters<U>(as other: Keyframe<U>) -> Bool {
time == other.time
&& isHold == other.isHold
&& inTangent == other.inTangent
&& outTangent == other.outTangent
// We intentionally don't compare spatial in/out tangents,
// since those values are only used in very specific cases
// (animating the x/y position of a layer), which aren't ever
// combined in this way.
}
}
extension KeyframeGroup {
/// The value to use for a combined set of keyframes, for the given index
fileprivate func valueForCombinedKeyframes(at index: Int) -> T {
if keyframes.count == 1 {
return keyframes[0].value
} else {
return keyframes[index].value
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Extensions/Keyframes+combined.swift
|
Swift
|
unknown
| 13,451
|
// Created by Cal Stephens on 1/8/24.
// Copyright © 2024 Airbnb Inc. All rights reserved.
extension Keyframes {
/// Manually interpolates the given keyframes, and applies `context.complexTimeRemapping`.
/// - Since `complexTimeRemapping` is a mapping from "global time" to "local time",
/// we have to manually interpolate the keyframes at every frame in the animation.
static func manuallyInterpolatedWithTimeRemapping<T: AnyInterpolatable>(
_ keyframes: KeyframeGroup<T>,
context: LayerAnimationContext)
-> KeyframeGroup<T>
{
let minimumTime = context.animation.startFrame
let maximumTime = context.animation.endFrame
let animationLocalTimeRange = stride(from: minimumTime, to: maximumTime, by: 1.0)
let interpolator = keyframes.interpolator
// Since potentially many global times can refer to the same local time,
// we can cache and reused these local-time values.
var localTimeCache = [AnimationFrameTime: T]()
let interpolatedRemappedKeyframes = animationLocalTimeRange.compactMap { globalTime -> Keyframe<T>? in
let remappedLocalTime = context.complexTimeRemapping(globalTime)
let valueAtRemappedTime: T
if let cachedValue = localTimeCache[remappedLocalTime] {
valueAtRemappedTime = cachedValue
} else if let interpolatedValue = interpolator.value(frame: remappedLocalTime) as? T {
valueAtRemappedTime = interpolatedValue
localTimeCache[remappedLocalTime] = interpolatedValue
} else {
LottieLogger.shared.assertionFailure("""
Failed to cast untyped keyframe values to expected type. This is an internal error.
""")
return nil
}
return Keyframe(
value: valueAtRemappedTime,
time: AnimationFrameTime(globalTime))
}
return KeyframeGroup(keyframes: ContiguousArray(interpolatedRemappedKeyframes))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Extensions/Keyframes+timeRemapping.swift
|
Swift
|
unknown
| 1,899
|
// Created by Cal Stephens on 12/14/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - AnimationLayer
/// A type of `CALayer` that can be used in a Lottie animation
/// - Layers backed by a `LayerModel` subclass should subclass `BaseCompositionLayer`
protocol AnimationLayer: CALayer {
/// Instructs this layer to setup its `CAAnimation`s
/// using the given `LayerAnimationContext`
func setupAnimations(context: LayerAnimationContext) throws
}
// MARK: - LayerAnimationContext
// Context describing the timing parameters of the current animation
struct LayerAnimationContext {
/// The animation being played
let animation: LottieAnimation
/// The timing configuration that should be applied to `CAAnimation`s
let timingConfiguration: CoreAnimationLayer.CAMediaTimingConfiguration
/// The absolute frame number that this animation begins at
let startFrame: AnimationFrameTime
/// The absolute frame number that this animation ends at
let endFrame: AnimationFrameTime
/// The set of custom Value Providers applied to this animation
let valueProviderStore: ValueProviderStore
/// Information about whether or not an animation is compatible with the Core Animation engine
let compatibilityTracker: CompatibilityTracker
/// The logger that should be used for assertions and warnings
let logger: LottieLogger
/// Mutable state related to log events, stored on the `CoreAnimationLayer`.
let loggingState: LoggingState
/// The AnimationKeypath represented by the current layer
var currentKeypath: AnimationKeypath
/// The `AnimationKeypathTextProvider`
var textProvider: AnimationKeypathTextProvider
/// Records the given animation keypath so it can be logged or collected into a list
/// - Used for `CoreAnimationLayer.logHierarchyKeypaths()` and `allHierarchyKeypaths()`
var recordHierarchyKeypath: ((String) -> Void)?
/// A closure that remaps the given frame in the child layer's local time to a frame
/// in the animation's overall global time.
/// - This time remapping is simple and only used `preCompLayer.timeStretch` and `preCompLayer.startTime`,
/// so is a trivial function and is invertible. This allows us to invert the time remapping from
/// "global time to local time" to instead be "local time to global time".
private(set) var simpleTimeRemapping: ((_ localTime: AnimationFrameTime) -> AnimationFrameTime) = { $0 }
/// A complex time remapping closure that remaps the given frame in the animation's overall global time
/// into the child layer's local time.
/// - This time remapping is arbitrarily complex because it includes the full `preCompLayer.timeRemapping`.
/// - Since it isn't possible to invert the time remapping function, this can only be applied by converting
/// from global time to local time. This requires using `Keyframes.manuallyInterpolatedWithTimeRemapping`.
private(set) var complexTimeRemapping: ((_ globalTime: AnimationFrameTime) -> AnimationFrameTime) = { $0 }
/// Whether or not this layer is required to use the `complexTimeRemapping` via
/// the more expensive `Keyframes.manuallyInterpolatedWithTimeRemapping` codepath.
var mustUseComplexTimeRemapping = false
/// The duration of the animation
var animationDuration: AnimationFrameTime {
// Normal animation playback (like when looping) skips the last frame.
// However when the animation is paused, we need to be able to render the final frame.
// To allow this we have to extend the length of the animation by one frame.
let animationEndFrame: AnimationFrameTime
if timingConfiguration.speed == 0 {
animationEndFrame = animation.endFrame + 1
} else {
animationEndFrame = animation.endFrame
}
return Double(animationEndFrame - animation.startFrame) / animation.framerate
}
/// Adds the given component string to the `AnimationKeypath` stored
/// that describes the current path being configured by this context value
func addingKeypathComponent(_ component: String) -> LayerAnimationContext {
var context = self
context.currentKeypath.keys.append(component)
return context
}
/// The `AnimationProgressTime` for the given `AnimationFrameTime` within this layer,
/// accounting for the `simpleTimeRemapping` applied to this layer.
func progressTime(for frame: AnimationFrameTime) throws -> AnimationProgressTime {
try compatibilityAssert(
!mustUseComplexTimeRemapping,
"LayerAnimationContext.time(forFrame:) does not support complex time remapping")
let animationFrameCount = animationDuration * animation.framerate
return (simpleTimeRemapping(frame) - animation.startFrame) / animationFrameCount
}
/// The real-time `TimeInterval` for the given `AnimationFrameTime` within this layer,
/// accounting for the `simpleTimeRemapping` applied to this layer.
func time(forFrame frame: AnimationFrameTime) throws -> TimeInterval {
try compatibilityAssert(
!mustUseComplexTimeRemapping,
"LayerAnimationContext.time(forFrame:) does not support complex time remapping")
return animation.time(forFrame: simpleTimeRemapping(frame))
}
/// Chains an additional time remapping closure onto the `simpleTimeRemapping` closure
func withSimpleTimeRemapping(
_ additionalSimpleTimeRemapping: @escaping (_ localTime: AnimationFrameTime) -> AnimationFrameTime)
-> LayerAnimationContext
{
var copy = self
copy.simpleTimeRemapping = { [existingSimpleTimeRemapping = simpleTimeRemapping] time in
existingSimpleTimeRemapping(additionalSimpleTimeRemapping(time))
}
return copy
}
/// Chains an additional time remapping closure onto the `complexTimeRemapping` closure.
/// - If `required` is `true`, all subsequent child layers will be required to use the expensive
/// `complexTimeRemapping` / `Keyframes.manuallyInterpolatedWithTimeRemapping` codepath.
/// - `required: true` is necessary when this time remapping is not available via `simpleTimeRemapping`.
func withComplexTimeRemapping(
required: Bool,
_ additionalComplexTimeRemapping: @escaping (_ globalTime: AnimationFrameTime) -> AnimationFrameTime)
-> LayerAnimationContext
{
var copy = self
copy.mustUseComplexTimeRemapping = copy.mustUseComplexTimeRemapping || required
copy.complexTimeRemapping = { [existingComplexTimeRemapping = complexTimeRemapping] time in
additionalComplexTimeRemapping(existingComplexTimeRemapping(time))
}
return copy
}
/// Returns a copy of this context with time remapping removed
func withoutTimeRemapping() -> LayerAnimationContext {
var copy = self
copy.simpleTimeRemapping = { $0 }
copy.complexTimeRemapping = { $0 }
copy.mustUseComplexTimeRemapping = false
return copy
}
}
// MARK: - LoggingState
/// Mutable state related to log events, stored on the `CoreAnimationLayer`.
final class LoggingState {
// MARK: Lifecycle
init() { }
// MARK: Internal
/// Whether or not the warning about unsupported After Effects expressions
/// has been logged yet for this layer.
var hasLoggedAfterEffectsExpressionsWarning = false
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/AnimationLayer.swift
|
Swift
|
unknown
| 7,206
|
// Created by Cal Stephens on 1/27/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
/// A base `CALayer` that manages the frame and animations
/// of its `sublayers` and `mask`
class BaseAnimationLayer: CALayer, AnimationLayer {
// MARK: Internal
override func layoutSublayers() {
super.layoutSublayers()
for sublayer in managedSublayers {
sublayer.fillBoundsOfSuperlayer()
}
}
func setupAnimations(context: LayerAnimationContext) throws {
for childAnimationLayer in managedSublayers {
try (childAnimationLayer as? AnimationLayer)?.setupAnimations(context: context)
}
}
// MARK: Private
/// All of the sublayers managed by this container
private var managedSublayers: [CALayer] {
(sublayers ?? []) + [mask].compactMap { $0 }
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/BaseAnimationLayer.swift
|
Swift
|
unknown
| 819
|
// Created by Cal Stephens on 12/20/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - BaseCompositionLayer
/// The base type of `AnimationLayer` that can contain other `AnimationLayer`s
class BaseCompositionLayer: BaseAnimationLayer {
// MARK: Lifecycle
init(layerModel: LayerModel) {
baseLayerModel = layerModel
super.init()
setupSublayers()
compositingFilter = layerModel.blendMode.filterName
name = layerModel.name
contentsLayer.name = "\(layerModel.name) (Content)"
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
baseLayerModel = typedLayer.baseLayerModel
super.init(layer: typedLayer)
}
// MARK: Internal
/// The layer that content / sublayers should be rendered in.
/// This is the layer that transform animations are applied to.
let contentsLayer = BaseAnimationLayer()
/// Whether or not this layer render should render any visible content
var renderLayerContents: Bool { true }
/// Sets up the base `LayerModel` animations for this layer,
/// and all child `AnimationLayer`s.
/// - Can be overridden by subclasses, which much call `super`.
override func setupAnimations(context: LayerAnimationContext) throws {
let layerContext = context.addingKeypathComponent(baseLayerModel.name)
let childContext = renderLayerContents ? layerContext : context
try setupLayerAnimations(context: layerContext)
try setupChildAnimations(context: childContext)
}
func setupLayerAnimations(context: LayerAnimationContext) throws {
let transformContext = context.addingKeypathComponent("Transform")
try contentsLayer.addTransformAnimations(for: baseLayerModel.transform, context: transformContext)
if renderLayerContents {
try contentsLayer.addOpacityAnimation(for: baseLayerModel.transform, context: transformContext)
try contentsLayer.addVisibilityAnimation(
inFrame: CGFloat(baseLayerModel.inFrame),
outFrame: CGFloat(baseLayerModel.outFrame),
context: context)
// There are two different drop shadow schemas, either using `DropShadowEffect` or `DropShadowStyle`.
// If both happen to be present, prefer the `DropShadowEffect` (which is the drop shadow schema
// supported on other platforms).
let dropShadowEffect = baseLayerModel.effects.first(where: { $0 is DropShadowEffect }) as? DropShadowModel
let dropShadowStyle = baseLayerModel.styles.first(where: { $0 is DropShadowStyle }) as? DropShadowModel
if let dropShadowModel = dropShadowEffect ?? dropShadowStyle {
try contentsLayer.addDropShadowAnimations(for: dropShadowModel, context: context)
}
}
}
func setupChildAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
}
override func addSublayer(_ layer: CALayer) {
if layer === contentsLayer {
super.addSublayer(contentsLayer)
} else {
contentsLayer.addSublayer(layer)
}
}
// MARK: Private
private let baseLayerModel: LayerModel
private func setupSublayers() {
addSublayer(contentsLayer)
if
renderLayerContents,
let masks = baseLayerModel.masks?.filter({ $0.mode != .none }),
!masks.isEmpty
{
contentsLayer.mask = MaskCompositionLayer(masks: masks)
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/BaseCompositionLayer.swift
|
Swift
|
unknown
| 3,716
|
// Created by Cal Stephens on 1/11/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CALayer {
// MARK: Internal
/// Sets up an `AnimationLayer` / `CALayer` hierarchy in this layer,
/// using the given list of layers.
@nonobjc
func setupLayerHierarchy(
for layers: [LayerModel],
context: LayerContext)
throws
{
// A `LottieAnimation`'s `LayerModel`s are listed from front to back,
// but `CALayer.sublayers` are listed from back to front.
// We reverse the layer ordering to match what Core Animation expects.
// The final view hierarchy must display the layers in this exact order.
let layersInZAxisOrder = layers.reversed()
let layersByIndex = Dictionary(grouping: layersInZAxisOrder, by: \.index)
.compactMapValues(\.first)
/// Layers specify a `parent` layer. Child layers inherit the `transform` of their parent.
/// - We can't add the child as a sublayer of the parent `CALayer`, since that would
/// break the ordering specified in `layersInZAxisOrder`.
/// - Instead, we create an invisible `TransformLayer` to handle the parent
/// transform animations, and add the child layer to that `TransformLayer`.
func makeParentTransformLayer(
childLayerModel: LayerModel,
childLayer: CALayer,
name: (LayerModel) -> String)
-> CALayer
{
guard
let parentIndex = childLayerModel.parent,
let parentLayerModel = layersByIndex[parentIndex]
else { return childLayer }
let parentLayer = TransformLayer(layerModel: parentLayerModel)
parentLayer.name = name(parentLayerModel)
parentLayer.addSublayer(childLayer)
return makeParentTransformLayer(
childLayerModel: parentLayerModel,
childLayer: parentLayer,
name: name)
}
// Create an `AnimationLayer` for each `LayerModel`
for (layerModel, mask) in try layersInZAxisOrder.pairedLayersAndMasks() {
guard let layer = try layerModel.makeAnimationLayer(context: context) else {
continue
}
// If this layer has a `parent`, we create an invisible `TransformLayer`
// to handle displaying / animating the parent transform.
let parentTransformLayer = makeParentTransformLayer(
childLayerModel: layerModel,
childLayer: layer,
name: { parentLayerModel in
"\(layerModel.name) (parent, \(parentLayerModel.name))"
})
// Create the `mask` layer for this layer, if it has a `MatteType`
if
let mask,
let maskLayer = try maskLayer(for: mask.model, type: mask.matteType, context: context)
{
let maskParentTransformLayer = makeParentTransformLayer(
childLayerModel: mask.model,
childLayer: maskLayer,
name: { parentLayerModel in
"\(mask.model.name) (mask of \(layerModel.name)) (parent, \(parentLayerModel.name))"
})
// Set up a parent container to host both the layer
// and its mask in the same coordinate space
let maskContainer = BaseAnimationLayer()
maskContainer.name = "\(layerModel.name) (parent, masked)"
maskContainer.addSublayer(parentTransformLayer)
// Core Animation will silently fail to apply a mask if a `mask` layer
// itself _also_ has a `mask`. As a workaround, we can wrap this layer's
// mask in an additional container layer which never has its own `mask`.
let additionalMaskParent = BaseAnimationLayer()
additionalMaskParent.addSublayer(maskParentTransformLayer)
maskContainer.mask = additionalMaskParent
addSublayer(maskContainer)
}
else {
addSublayer(parentTransformLayer)
}
}
}
// MARK: Fileprivate
/// Creates a mask `CALayer` from the given matte layer model, using the `MatteType`
/// from the layer that is being masked.
fileprivate func maskLayer(
for matteLayerModel: LayerModel,
type: MatteType,
context: LayerContext)
throws -> CALayer?
{
switch type {
case .add:
return try matteLayerModel.makeAnimationLayer(context: context)
case .invert:
guard let maskLayer = try matteLayerModel.makeAnimationLayer(context: context) else {
return nil
}
// We can invert the mask layer by having a large solid black layer with the
// given mask layer subtracted out using the `xor` blend mode. When applied to the
// layer being masked, this creates an inverted mask where only areas _outside_
// of the mask layer are visible.
// https://developer.apple.com/documentation/coregraphics/cgblendmode/xor
// - The inverted mask is supposed to expand infinitely around the shape,
// so we use `InfiniteOpaqueAnimationLayer`
let base = InfiniteOpaqueAnimationLayer()
base.backgroundColor = .rgb(0, 0, 0)
base.addSublayer(maskLayer)
maskLayer.compositingFilter = "xor"
return base
case .none, .unknown:
return nil
}
}
}
extension Collection<LayerModel> {
/// Pairs each `LayerModel` within this array with
/// a `LayerModel` to use as its mask, if applicable
/// based on the layer's `MatteType` configuration.
/// - Assumes the layers are sorted in z-axis order.
fileprivate func pairedLayersAndMasks() throws
-> [(layer: LayerModel, mask: (model: LayerModel, matteType: MatteType)?)]
{
var layersAndMasks = [(layer: LayerModel, mask: (model: LayerModel, matteType: MatteType)?)]()
var unprocessedLayers = reversed()
while let layer = unprocessedLayers.popLast() {
/// If a layer has a `MatteType`, then the next layer will be used as its `mask`
if
let matteType = layer.matte,
matteType != .none,
let maskLayer = unprocessedLayers.popLast()
{
layersAndMasks.append((layer: layer, mask: (model: maskLayer, matteType: matteType)))
}
else {
layersAndMasks.append((layer: layer, mask: nil))
}
}
return layersAndMasks
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/CALayer+setupLayerHierarchy.swift
|
Swift
|
unknown
| 6,090
|
// Created by Cal Stephens on 1/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - GradientRenderLayer
/// A `CAGradientLayer` subclass used to render a gradient _outside_ the normal layer bounds
///
/// - `GradientFill.startPoint` and `GradientFill.endPoint` are expressed
/// with respect to the `bounds` of the `ShapeItemLayer`.
///
/// - The gradient itself is supposed to be rendered infinitely in all directions
/// (e.g. including outside of `bounds`). This is because `ShapeItemLayer` paths
/// don't necessarily sit within the layer's `bounds`.
///
/// - To support this, `GradientRenderLayer` tracks a `gradientReferenceBounds`
/// that `startPoint` / `endPoint` are calculated relative to.
/// The _actual_ `bounds` of this layer is padded by a large amount so that
/// the gradient can be drawn outside of the `gradientReferenceBounds`.
///
final class GradientRenderLayer: CAGradientLayer {
// MARK: Internal
/// The reference bounds within this layer that the gradient's
/// `startPoint` and `endPoint` should be calculated relative to
var gradientReferenceBounds: CGRect = .zero {
didSet {
if oldValue != gradientReferenceBounds {
updateLayout()
}
}
}
/// Converts the given `CGPoint` within `gradientReferenceBounds`
/// to a percentage value relative to the full `bounds` of this layer
/// - This converts absolute `startPoint` and `endPoint` values into
/// the percent-based values expected by Core Animation,
/// with respect to the custom bounds geometry used by this layer type.
func percentBasedPointInBounds(from referencePoint: CGPoint) -> CGPoint {
guard bounds.width > 0, bounds.height > 0 else {
LottieLogger.shared.assertionFailure("Size must be non-zero before an animation can be played")
return .zero
}
let pointInBounds = CGPoint(
x: referencePoint.x + CALayer.veryLargeLayerPadding,
y: referencePoint.y + CALayer.veryLargeLayerPadding)
return CGPoint(
x: CGFloat(pointInBounds.x) / bounds.width,
y: CGFloat(pointInBounds.y) / bounds.height)
}
// MARK: Private
private func updateLayout() {
anchorPoint = .zero
bounds = CGRect(
x: gradientReferenceBounds.origin.x,
y: gradientReferenceBounds.origin.y,
width: CALayer.veryLargeLayerPadding + gradientReferenceBounds.width + CALayer.veryLargeLayerPadding,
height: CALayer.veryLargeLayerPadding + gradientReferenceBounds.height + CALayer.veryLargeLayerPadding)
// Align the center of this layer to be at the center point of its parent layer
let superlayerSize = superlayer?.frame.size ?? gradientReferenceBounds.size
transform = CATransform3DMakeTranslation(
(superlayerSize.width - bounds.width) / 2,
(superlayerSize.height - bounds.height) / 2,
0)
}
}
// MARK: CustomLayoutLayer
extension GradientRenderLayer: CustomLayoutLayer {
func layout(superlayerBounds: CGRect) {
gradientReferenceBounds = superlayerBounds
if let gradientMask = mask as? GradientRenderLayer {
gradientMask.layout(superlayerBounds: superlayerBounds)
}
}
}
extension CALayer {
/// Extra padding to add around layers that should be very large or "infinite" in size.
/// Examples include `GradientRenderLayer` and `InfiniteOpaqueAnimationLayer`.
/// - This specific value is arbitrary and can be increased if necessary.
/// - Theoretically this should be "infinite", to match the behavior of
/// `CGContext.drawLinearGradient` with `[.drawsAfterEndLocation, .drawsBeforeStartLocation]` etc.
static let veryLargeLayerPadding: CGFloat = 10_000
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/GradientRenderLayer.swift
|
Swift
|
unknown
| 3,691
|
// Created by Cal Stephens on 1/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ImageLayer
/// The `CALayer` type responsible for rendering `ImageLayerModel`s
final class ImageLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(
imageLayer: ImageLayerModel,
context: LayerContext)
{
self.imageLayer = imageLayer
super.init(layerModel: imageLayer)
setupImage(context: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
imageLayer = typedLayer.imageLayer
super.init(layer: typedLayer)
}
// MARK: Internal
func setupImage(context: LayerContext) {
guard
let imageAsset = context.animation.assetLibrary?.imageAssets[imageLayer.referenceID],
let image = context.imageProvider.imageForAsset(asset: imageAsset)
else {
self.imageAsset = nil
contentsLayer.contents = nil
return
}
self.imageAsset = imageAsset
contentsLayer.contents = image
contentsLayer.contentsGravity = context.imageProvider.contentsGravity(for: imageAsset)
setNeedsLayout()
}
// MARK: Private
private let imageLayer: ImageLayerModel
private var imageAsset: ImageAsset?
}
// MARK: CustomLayoutLayer
extension ImageLayer: CustomLayoutLayer {
func layout(superlayerBounds: CGRect) {
anchorPoint = .zero
guard let imageAsset else {
bounds = superlayerBounds
return
}
// Image layers specifically need to use the size of the image itself
bounds = CGRect(
x: superlayerBounds.origin.x,
y: superlayerBounds.origin.y,
width: CGFloat(imageAsset.width),
height: CGFloat(imageAsset.height))
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/ImageLayer.swift
|
Swift
|
unknown
| 2,067
|
// Created by Cal Stephens on 10/10/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ExpandedAnimationLayer
/// A `BaseAnimationLayer` subclass that renders its background color
/// as if the layer is infinitely large, without affecting its bounds
/// or the bounds of its sublayers
final class InfiniteOpaqueAnimationLayer: BaseAnimationLayer {
// MARK: Lifecycle
override init() {
super.init()
addSublayer(additionalPaddingLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
super.init(layer: layer)
}
// MARK: Internal
override func layoutSublayers() {
super.layoutSublayers()
masksToBounds = false
additionalPaddingLayer.backgroundColor = backgroundColor
// Scale `additionalPaddingLayer` to be larger than this layer
// by `additionalPadding` at each size, and centered at the center
// of this layer. Since `additionalPadding` is very large, this has
// the affect of making `additionalPaddingLayer` appear infinite.
let scaleRatioX = (bounds.width + (CALayer.veryLargeLayerPadding * 2)) / bounds.width
let scaleRatioY = (bounds.height + (CALayer.veryLargeLayerPadding * 2)) / bounds.height
additionalPaddingLayer.transform = CATransform3DScale(
CATransform3DMakeTranslation(-CALayer.veryLargeLayerPadding, -CALayer.veryLargeLayerPadding, 0),
scaleRatioX,
scaleRatioY,
1)
}
// MARK: Private
private let additionalPaddingLayer = CALayer()
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/InfiniteOpaqueAnimationLayer.swift
|
Swift
|
unknown
| 1,739
|
// Created by Cal Stephens on 12/20/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
// MARK: - LayerContext
/// Context available when constructing an `AnimationLayer`
struct LayerContext {
let animation: LottieAnimation
let imageProvider: AnimationImageProvider
let textProvider: AnimationKeypathTextProvider
let fontProvider: AnimationFontProvider
let compatibilityTracker: CompatibilityTracker
var layerName: String
func forLayer(_ layer: LayerModel) -> LayerContext {
var context = self
context.layerName = layer.name
return context
}
}
// MARK: - LayerModel + makeAnimationLayer
extension LayerModel {
/// Constructs an `AnimationLayer` / `CALayer` that represents this `LayerModel`
func makeAnimationLayer(context: LayerContext) throws -> BaseCompositionLayer? {
let context = context.forLayer(self)
if hidden {
return TransformLayer(layerModel: self)
}
switch (type, self) {
case (.precomp, let preCompLayerModel as PreCompLayerModel):
let preCompLayer = PreCompLayer(preCompLayer: preCompLayerModel)
try preCompLayer.setup(context: context)
return preCompLayer
case (.solid, let solidLayerModel as SolidLayerModel):
return SolidLayer(solidLayerModel)
case (.shape, let shapeLayerModel as ShapeLayerModel):
return try ShapeLayer(shapeLayer: shapeLayerModel, context: context)
case (.image, let imageLayerModel as ImageLayerModel):
return ImageLayer(imageLayer: imageLayerModel, context: context)
case (.text, let textLayerModel as TextLayerModel):
return try TextLayer(textLayerModel: textLayerModel, context: context)
case (.null, _):
return TransformLayer(layerModel: self)
case (.unknown, _), (.precomp, _), (.solid, _), (.image, _), (.shape, _), (.text, _):
return nil
}
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/LayerModel+makeAnimationLayer.swift
|
Swift
|
unknown
| 1,852
|
// Created by Cal Stephens on 1/6/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - MaskCompositionLayer
/// The CALayer type responsible for rendering the `Mask` of a `BaseCompositionLayer`
final class MaskCompositionLayer: CALayer {
// MARK: Lifecycle
init(masks: [Mask]) {
maskLayers = masks.map(MaskLayer.init(mask:))
super.init()
var containerLayer = BaseAnimationLayer()
var firstObject = true
for maskLayer in maskLayers {
if maskLayer.maskModel.mode.usableMode == .none {
continue
} else if maskLayer.maskModel.mode.usableMode == .add || firstObject {
firstObject = false
containerLayer.addSublayer(maskLayer)
} else {
containerLayer.mask = maskLayer
let newContainer = BaseAnimationLayer()
newContainer.addSublayer(containerLayer)
containerLayer = newContainer
}
}
addSublayer(containerLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
maskLayers = typedLayer.maskLayers
super.init(layer: typedLayer)
}
// MARK: Internal
override func layoutSublayers() {
super.layoutSublayers()
for sublayer in sublayers ?? [] {
sublayer.fillBoundsOfSuperlayer()
}
}
// MARK: Private
private let maskLayers: [MaskLayer]
}
// MARK: AnimationLayer
extension MaskCompositionLayer: AnimationLayer {
func setupAnimations(context: LayerAnimationContext) throws {
for maskLayer in maskLayers {
try maskLayer.setupAnimations(context: context)
}
}
}
// MARK: MaskCompositionLayer.MaskLayer
extension MaskCompositionLayer {
final class MaskLayer: CAShapeLayer {
// MARK: Lifecycle
init(mask: Mask) {
maskModel = mask
super.init()
fillRule = .evenOdd
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
maskModel = typedLayer.maskModel
super.init(layer: typedLayer)
}
// MARK: Internal
let maskModel: Mask
}
}
// MARK: - MaskCompositionLayer.MaskLayer + AnimationLayer
extension MaskCompositionLayer.MaskLayer: AnimationLayer {
func setupAnimations(context: LayerAnimationContext) throws {
let shouldInvertMask = (maskModel.mode.usableMode == .subtract && !maskModel.inverted)
|| (maskModel.mode.usableMode == .add && maskModel.inverted)
try addAnimations(
for: maskModel.shape,
context: context,
transformPath: { maskPath in
// If the mask is using `MaskMode.subtract` or has `inverted: true`,
// we have to invert the area filled by the path. We can do that by
// drawing a rectangle, and then adding a path (which is subtracted
// from the rectangle based on the .evenOdd fill mode).
if shouldInvertMask {
let path = CGMutablePath()
path.addRect(.veryLargeRect)
path.addPath(maskPath)
return path
} else {
return maskPath
}
})
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/MaskCompositionLayer.swift
|
Swift
|
unknown
| 3,754
|
// Created by Cal Stephens on 12/14/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - PreCompLayer
/// The `CALayer` type responsible for rendering `PreCompLayerModel`s
final class PreCompLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(preCompLayer: PreCompLayerModel) {
self.preCompLayer = preCompLayer
super.init(layerModel: preCompLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
preCompLayer = typedLayer.preCompLayer
super.init(layer: typedLayer)
}
// MARK: Internal
let preCompLayer: PreCompLayerModel
/// Post-init setup for `PreCompLayer`s.
/// Should always be called after `PreCompLayer.init(preCompLayer:)`.
///
/// This is a workaround for a hard-to-reproduce crash that was
/// triggered when `PreCompLayer.init` was called reentantly. We didn't
/// have any consistent repro steps for this crash (it happened 100% of
/// the time for some testers, and 0% of the time for other testers),
/// but moving this code out of `PreCompLayer.init` does seem to fix it.
///
/// The stack trace looked like:
/// - `_os_unfair_lock_recursive_abort`
/// - `-[CALayerAccessibility__UIKit__QuartzCore dealloc]`
/// - `PreCompLayer.__allocating_init(preCompLayer:context:)` <- reentrant init call
/// - ...
/// - `CALayer.setupLayerHierarchy(for:context:)`
/// - `PreCompLayer.init(preCompLayer:context:)`
///
func setup(context: LayerContext) throws {
try setupLayerHierarchy(
for: context.animation.assetLibrary?.precompAssets[preCompLayer.referenceID]?.layers ?? [],
context: context)
}
override func setupAnimations(context: LayerAnimationContext) throws {
var context = context
context = context.addingKeypathComponent(preCompLayer.name)
try setupLayerAnimations(context: context)
let timeRemappingInterpolator = preCompLayer.timeRemapping.flatMap { KeyframeInterpolator(keyframes: $0.keyframes) }
let contextForChildren = context
// `timeStretch` and `startTime` are a simple linear function so can be inverted from a
// "global time to local time" function into the simpler "local time to global time".
.withSimpleTimeRemapping { [preCompLayer] layerLocalFrame in
(layerLocalFrame * AnimationFrameTime(preCompLayer.timeStretch)) + AnimationFrameTime(preCompLayer.startTime)
}
// `timeRemappingInterpolator` is arbitrarily complex and cannot be inverted,
// so can only be applied via `complexTimeRemapping` from global time to local time.
.withComplexTimeRemapping(required: preCompLayer.timeRemapping != nil) { [preCompLayer] globalTime in
if let timeRemappingInterpolator {
let remappedLocalTime = timeRemappingInterpolator.value(frame: globalTime) as! LottieVector1D
return remappedLocalTime.cgFloatValue * context.animation.framerate
} else {
return (globalTime - preCompLayer.startTime) / preCompLayer.timeStretch
}
}
try setupChildAnimations(context: contextForChildren)
}
}
// MARK: CustomLayoutLayer
extension PreCompLayer: CustomLayoutLayer {
func layout(superlayerBounds: CGRect) {
anchorPoint = .zero
// Pre-comp layers use a size specified in the layer model,
// and clip the composition to that bounds
bounds = CGRect(
x: superlayerBounds.origin.x,
y: superlayerBounds.origin.y,
width: CGFloat(preCompLayer.width),
height: CGFloat(preCompLayer.height))
contentsLayer.masksToBounds = true
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/PreCompLayer.swift
|
Swift
|
unknown
| 3,940
|
// Created by Cal Stephens on 8/1/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - RepeaterLayer
/// A layer that renders a child layer at some offset using a `Repeater`
final class RepeaterLayer: BaseAnimationLayer {
// MARK: Lifecycle
init(repeater: Repeater, childLayer: CALayer, index: Int) {
repeaterTransform = RepeaterTransform(repeater: repeater, index: index)
super.init()
addSublayer(childLayer)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
repeaterTransform = typedLayer.repeaterTransform
super.init(layer: typedLayer)
}
// MARK: Internal
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
try addTransformAnimations(for: repeaterTransform, context: context)
}
// MARK: Private
private let repeaterTransform: RepeaterTransform
}
// MARK: - RepeaterTransform
/// A transform model created from a `Repeater`
private struct RepeaterTransform {
// MARK: Lifecycle
init(repeater: Repeater, index: Int) {
anchorPoint = repeater.anchorPoint
scale = repeater.scale
rotationX = repeater.rotationX.map { rotation in
LottieVector1D(rotation.value * Double(index))
}
rotationY = repeater.rotationY.map { rotation in
LottieVector1D(rotation.value * Double(index))
}
rotationZ = repeater.rotationZ.map { rotation in
LottieVector1D(rotation.value * Double(index))
}
position = repeater.position.map { position in
LottieVector3D(
x: position.x * Double(index),
y: position.y * Double(index),
z: position.z * Double(index))
}
}
// MARK: Internal
let anchorPoint: KeyframeGroup<LottieVector3D>
let position: KeyframeGroup<LottieVector3D>
let rotationX: KeyframeGroup<LottieVector1D>
let rotationY: KeyframeGroup<LottieVector1D>
let rotationZ: KeyframeGroup<LottieVector1D>
let scale: KeyframeGroup<LottieVector3D>
}
// MARK: TransformModel
extension RepeaterTransform: TransformModel {
var _position: KeyframeGroup<LottieVector3D>? { position }
var _positionX: KeyframeGroup<LottieVector1D>? { nil }
var _positionY: KeyframeGroup<LottieVector1D>? { nil }
var _skew: KeyframeGroup<LottieVector1D>? { nil }
var _skewAxis: KeyframeGroup<LottieVector1D>? { nil }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/RepeaterLayer.swift
|
Swift
|
unknown
| 2,737
|
// Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ShapeItemLayer
/// A CALayer type that renders an array of `[ShapeItem]`s,
/// from a `Group` in a `ShapeLayerModel`.
final class ShapeItemLayer: BaseAnimationLayer {
// MARK: Lifecycle
/// Initializes a `ShapeItemLayer` that renders a `Group` from a `ShapeLayerModel`
/// - Parameters:
/// - shape: The `ShapeItem` in this group that renders a `GGPath`
/// - otherItems: Other items in this group that affect the appearance of the shape
init(shape: Item, otherItems: [Item], context: LayerContext) throws {
self.shape = shape
self.otherItems = otherItems
try context.compatibilityAssert(
shape.item.drawsCGPath,
"`ShapeItemLayer` must contain exactly one `ShapeItem` that draws a `GPPath`")
try context.compatibilityAssert(
!otherItems.contains(where: { $0.item.drawsCGPath }),
"`ShapeItemLayer` must contain exactly one `ShapeItem` that draws a `GPPath`")
super.init()
setupLayerHierarchy()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
shape = typedLayer.shape
otherItems = typedLayer.otherItems
super.init(layer: typedLayer)
}
// MARK: Internal
/// An item that can be displayed by this layer
struct Item {
/// A `ShapeItem` that should be rendered by this layer
let item: ShapeItem
/// The set of groups that this item descends from
/// - Due to the way `GroupLayer`s are setup, the original `ShapeItem`
/// hierarchy from the `ShapeLayer` data model may no longer exactly
/// match the hierarchy of `GroupLayer` / `ShapeItemLayer`s constructed
/// at runtime. Since animation keypaths need to match the original
/// structure of the `ShapeLayer` data model, we track that info here.
let groupPath: [String]
}
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
guard let sublayerConfiguration else { return }
switch sublayerConfiguration.fill {
case .solidFill(let shapeLayer):
try setupSolidFillAnimations(shapeLayer: shapeLayer, context: context)
case .gradientFill(let gradientLayers):
try setupGradientFillAnimations(layers: gradientLayers, context: context)
}
if let gradientStrokeConfiguration = sublayerConfiguration.gradientStroke {
try setupGradientStrokeAnimations(layers: gradientStrokeConfiguration, context: context)
}
}
// MARK: Private
private struct GradientLayers {
/// The `CALayer` that renders the RGB components of the gradient
let gradientColorLayer: GradientRenderLayer
/// The `CALayer` that renders the alpha components of the gradient,
/// masking the `gradientColorLayer`
let gradientAlphaLayer: GradientRenderLayer?
/// The `CAShapeLayer` that clips the gradient layers to the expected shape
let shapeMaskLayer: CAShapeLayer
/// The top-most `CAShapeLayer` used to render `Stroke`s over the gradient if necessary
let overlayLayer: CAShapeLayer?
}
/// The configuration of this layer's `fill` sublayers
private enum FillLayerConfiguration {
/// This layer displays a single `CAShapeLayer`
case solidFill(CAShapeLayer)
/// This layer displays a `GradientRenderLayer` masked by a `CAShapeLayer`.
case gradientFill(GradientLayers)
}
/// The `ShapeItem` in this group that renders a `GGPath`
private let shape: Item
/// Other items in this group that affect the appearance of the shape
private let otherItems: [Item]
/// The current configuration of this layer's sublayer(s)
private var sublayerConfiguration: (fill: FillLayerConfiguration, gradientStroke: GradientLayers?)?
private func setupLayerHierarchy() {
// We have to build a different layer hierarchy depending on if
// we're rendering a gradient (a `CAGradientLayer` masked by a `CAShapeLayer`)
// or a solid shape (a simple `CAShapeLayer`).
let fillLayerConfiguration: FillLayerConfiguration
if let gradientFill = otherItems.first(GradientFill.self) {
fillLayerConfiguration = setupGradientFillLayerHierarchy(for: gradientFill)
} else {
fillLayerConfiguration = setupSolidFillLayerHierarchy()
}
let gradientStrokeConfiguration: GradientLayers?
if let gradientStroke = otherItems.first(GradientStroke.self) {
gradientStrokeConfiguration = setupGradientStrokeLayerHierarchy(for: gradientStroke)
} else {
gradientStrokeConfiguration = nil
}
sublayerConfiguration = (fillLayerConfiguration, gradientStrokeConfiguration)
}
private func setupSolidFillLayerHierarchy() -> FillLayerConfiguration {
let shapeLayer = CAShapeLayer()
addSublayer(shapeLayer)
// `CAShapeLayer.fillColor` defaults to black, so we have to
// nil out the background color if there isn't an expected fill color
if !otherItems.contains(where: { $0.item is Fill }) {
shapeLayer.fillColor = nil
}
return .solidFill(shapeLayer)
}
private func setupGradientFillLayerHierarchy(
for gradientFill: GradientFill)
-> FillLayerConfiguration
{
let container = BaseAnimationLayer()
let pathContainer = BaseAnimationLayer()
let pathMask = CAShapeLayer()
pathMask.fillColor = .rgb(0, 0, 0)
pathContainer.mask = pathMask
let rgbGradientLayer = GradientRenderLayer()
pathContainer.addSublayer(rgbGradientLayer)
container.addSublayer(pathContainer)
let overlayLayer = CAShapeLayer()
overlayLayer.fillColor = nil
container.addSublayer(overlayLayer)
addSublayer(container)
let alphaGradientLayer: GradientRenderLayer?
if gradientFill.hasAlphaComponent {
alphaGradientLayer = GradientRenderLayer()
rgbGradientLayer.mask = alphaGradientLayer
} else {
alphaGradientLayer = nil
}
return .gradientFill(GradientLayers(
gradientColorLayer: rgbGradientLayer,
gradientAlphaLayer: alphaGradientLayer,
shapeMaskLayer: pathMask,
overlayLayer: overlayLayer))
}
private func setupGradientStrokeLayerHierarchy(
for gradientStroke: GradientStroke)
-> GradientLayers
{
let container = BaseAnimationLayer()
let pathMask = CAShapeLayer()
pathMask.fillColor = nil
pathMask.strokeColor = .rgb(0, 0, 0)
container.mask = pathMask
let rgbGradientLayer = GradientRenderLayer()
container.addSublayer(rgbGradientLayer)
addSublayer(container)
let alphaGradientLayer: GradientRenderLayer?
if gradientStroke.hasAlphaComponent {
alphaGradientLayer = GradientRenderLayer()
rgbGradientLayer.mask = alphaGradientLayer
} else {
alphaGradientLayer = nil
}
return GradientLayers(
gradientColorLayer: rgbGradientLayer,
gradientAlphaLayer: alphaGradientLayer,
shapeMaskLayer: pathMask,
overlayLayer: nil)
}
private func setupSolidFillAnimations(
shapeLayer: CAShapeLayer,
context: LayerAnimationContext)
throws
{
var trimPathMultiplier: PathMultiplier? = nil
if let (trim, context) = otherItems.first(Trim.self, where: { !$0.isEmpty }, context: context) {
trimPathMultiplier = try shapeLayer.addAnimations(for: trim, context: context)
try context.compatibilityAssert(
otherItems.first(Fill.self) == nil,
"""
The Core Animation rendering engine doesn't currently support applying
trims to filled shapes (only stroked shapes).
""")
}
try shapeLayer.addAnimations(
for: shape.item,
context: context.for(shape),
pathMultiplier: trimPathMultiplier ?? 1,
roundedCorners: otherItems.first(RoundedCorners.self))
if let (fill, context) = otherItems.first(Fill.self, context: context) {
try shapeLayer.addAnimations(for: fill, context: context)
}
if let (stroke, context) = otherItems.first(Stroke.self, context: context) {
try shapeLayer.addStrokeAnimations(for: stroke, context: context)
}
}
private func setupGradientFillAnimations(
layers: GradientLayers,
context: LayerAnimationContext)
throws
{
let pathLayers = [layers.shapeMaskLayer, layers.overlayLayer]
for pathLayer in pathLayers {
try pathLayer?.addAnimations(
for: shape.item,
context: context.for(shape),
pathMultiplier: 1,
roundedCorners: otherItems.first(RoundedCorners.self))
}
if let (gradientFill, context) = otherItems.first(GradientFill.self, context: context) {
layers.shapeMaskLayer.fillRule = gradientFill.fillRule.caFillRule
try layers.gradientColorLayer.addGradientAnimations(for: gradientFill, type: .rgb, context: context)
try layers.gradientAlphaLayer?.addGradientAnimations(for: gradientFill, type: .alpha, context: context)
}
if let (stroke, context) = otherItems.first(Stroke.self, context: context) {
try layers.overlayLayer?.addStrokeAnimations(for: stroke, context: context)
}
}
private func setupGradientStrokeAnimations(
layers: GradientLayers,
context: LayerAnimationContext)
throws
{
var trimPathMultiplier: PathMultiplier? = nil
if let (trim, context) = otherItems.first(Trim.self, context: context) {
trimPathMultiplier = try layers.shapeMaskLayer.addAnimations(for: trim, context: context)
}
try layers.shapeMaskLayer.addAnimations(
for: shape.item,
context: context.for(shape),
pathMultiplier: trimPathMultiplier ?? 1,
roundedCorners: otherItems.first(RoundedCorners.self))
if let (gradientStroke, context) = otherItems.first(GradientStroke.self, context: context) {
try layers.gradientColorLayer.addGradientAnimations(for: gradientStroke, type: .rgb, context: context)
try layers.gradientAlphaLayer?.addGradientAnimations(for: gradientStroke, type: .alpha, context: context)
try layers.shapeMaskLayer.addStrokeAnimations(for: gradientStroke, context: context)
}
}
}
// MARK: - [ShapeItem] helpers
extension [ShapeItemLayer.Item] {
/// The first `ShapeItem` in this array of the given type
func first<ItemType: ShapeItem>(
_: ItemType.Type,
where condition: (ItemType) -> Bool = { _ in true },
context: LayerAnimationContext)
-> (item: ItemType, context: LayerAnimationContext)?
{
for item in self {
if let match = item.item as? ItemType, condition(match) {
return (match, context.for(item))
}
}
return nil
}
/// The first `ShapeItem` in this array of the given type
func first<ItemType: ShapeItem>(_: ItemType.Type) -> ItemType? {
for item in self {
if let match = item.item as? ItemType {
return match
}
}
return nil
}
}
extension LayerAnimationContext {
/// An updated `LayerAnimationContext` with the`AnimationKeypath`
/// that refers to this specific `ShapeItem`.
func `for`(_ item: ShapeItemLayer.Item) -> LayerAnimationContext {
var context = self
for parentGroupName in item.groupPath {
context.currentKeypath.keys.append(parentGroupName)
}
context.currentKeypath.keys.append(item.item.name)
return context
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/ShapeItemLayer.swift
|
Swift
|
unknown
| 11,617
|
// Created by Cal Stephens on 12/14/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ShapeLayer
/// The CALayer type responsible for rendering `ShapeLayerModel`s
final class ShapeLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(shapeLayer: ShapeLayerModel, context: LayerContext) throws {
self.shapeLayer = shapeLayer
super.init(layerModel: shapeLayer)
try setUpGroups(context: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
shapeLayer = typedLayer.shapeLayer
super.init(layer: typedLayer)
}
// MARK: Private
private let shapeLayer: ShapeLayerModel
private func setUpGroups(context: LayerContext) throws {
let shapeItems = shapeLayer.items.map { ShapeItemLayer.Item(item: $0, groupPath: []) }
try setupGroups(from: shapeItems, parentGroup: nil, parentGroupPath: [], context: context)
}
}
// MARK: - GroupLayer
/// The CALayer type responsible for rendering `Group`s
final class GroupLayer: BaseAnimationLayer {
// MARK: Lifecycle
init(group: Group, items: [ShapeItemLayer.Item], groupPath: [String], context: LayerContext) throws {
self.group = group
self.items = items
self.groupPath = groupPath
super.init()
try setupLayerHierarchy(context: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
group = typedLayer.group
items = typedLayer.items
groupPath = typedLayer.groupPath
super.init(layer: typedLayer)
}
// MARK: Internal
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
if let (shapeTransform, context) = nonGroupItems.first(ShapeTransform.self, context: context) {
try addTransformAnimations(for: shapeTransform, context: context)
try addOpacityAnimation(for: shapeTransform, context: context)
}
}
// MARK: Private
private let group: Group
/// `ShapeItemLayer.Item`s rendered by this `Group`
/// - In the original `ShapeLayer` data model, these items could have originated from a different group
private let items: [ShapeItemLayer.Item]
/// The keypath that represents this group, with respect to the parent `ShapeLayer`
/// - Due to the way `GroupLayer`s are setup, the original `ShapeItem`
/// hierarchy from the `ShapeLayer` data model may no longer exactly
/// match the hierarchy of `GroupLayer` / `ShapeItemLayer`s constructed
/// at runtime. Since animation keypaths need to match the original
/// structure of the `ShapeLayer` data model, we track that info here.
private let groupPath: [String]
/// Child group items contained in this group. Correspond to a child `GroupLayer`
private lazy var childGroups = items.filter { $0.item is Group }
/// `ShapeItem`s (other than nested `Group`s) that are rendered by this layer
private lazy var nonGroupItems = items.filter { !($0.item is Group) }
private func setupLayerHierarchy(context: LayerContext) throws {
// Groups can contain other groups, so we may have to continue
// recursively creating more `GroupLayer`s
try setupGroups(from: items, parentGroup: group, parentGroupPath: groupPath, context: context)
// Create `ShapeItemLayer`s for each subgroup of shapes that should be rendered as a single unit
// - These groups are listed from front-to-back, so we have to add the sublayers in reverse order
let renderGroups = items.shapeRenderGroups(groupHasChildGroupsToInheritUnusedItems: !childGroups.isEmpty)
for shapeRenderGroup in renderGroups.validGroups.reversed() {
// When there are multiple path-drawing items, they're supposed to be rendered
// in a single `CAShapeLayer` (instead of rendering them in separate layers) so
// `CAShapeLayerFillRule.evenOdd` can be applied correctly if the paths overlap.
// Since a `CAShapeLayer` only supports animating a single `CGPath` from a single `KeyframeGroup<BezierPath>`,
// this requires combining all of the path-drawing items into a single set of keyframes.
if
shapeRenderGroup.pathItems.count > 1,
// We currently only support this codepath for `Shape` items that directly contain bezier path keyframes.
// We could also support this for other path types like rectangles, ellipses, and polygons with more work.
shapeRenderGroup.pathItems.allSatisfy({ $0.item is Shape }),
// `Trim`s are currently only applied correctly using individual `ShapeItemLayer`s,
// because each path has to be trimmed separately.
!shapeRenderGroup.otherItems.contains(where: { $0.item is Trim })
{
let allPathKeyframes = shapeRenderGroup.pathItems.compactMap { ($0.item as? Shape)?.path }
let combinedShape = CombinedShapeItem(
shapes: Keyframes.combined(allPathKeyframes),
name: group.name)
let sublayer = try ShapeItemLayer(
shape: ShapeItemLayer.Item(item: combinedShape, groupPath: shapeRenderGroup.pathItems[0].groupPath),
otherItems: shapeRenderGroup.otherItems,
context: context)
addSublayer(sublayer)
}
// Otherwise, if each `ShapeItem` that draws a `GGPath` animates independently,
// we have to create a separate `ShapeItemLayer` for each one. This may render
// incorrectly if there are multiple paths that overlap with each other.
else {
for pathDrawingItem in shapeRenderGroup.pathItems {
let sublayer = try ShapeItemLayer(
shape: pathDrawingItem,
otherItems: shapeRenderGroup.otherItems,
context: context)
addSublayer(sublayer)
}
}
}
}
}
extension CALayer {
// MARK: Fileprivate
/// Sets up `GroupLayer`s for each `Group` in the given list of `ShapeItem`s
/// - Each `Group` item becomes its own `GroupLayer` sublayer.
/// - Other `ShapeItem` are applied to all sublayers
fileprivate func setupGroups(
from items: [ShapeItemLayer.Item],
parentGroup: Group?,
parentGroupPath: [String],
context: LayerContext)
throws
{
// If the layer has any `Repeater`s, set up each repeater
// and then handle any remaining groups like normal.
if items.contains(where: { $0.item is Repeater }) {
let repeaterGroupings = items.split(whereSeparator: { $0.item is Repeater })
// Iterate through the groupings backwards to preserve the expected rendering order
for repeaterGrouping in repeaterGroupings.reversed() {
// Each repeater applies to the previous items in the list
if let repeater = repeaterGrouping.trailingSeparator?.item as? Repeater {
try setUpRepeater(
repeater,
items: repeaterGrouping.grouping,
parentGroupPath: parentGroupPath,
context: context)
}
// Any remaining items after the last repeater are handled like normal
else {
try setupGroups(
from: repeaterGrouping.grouping,
parentGroup: parentGroup,
parentGroupPath: parentGroupPath,
context: context)
}
}
}
else {
let groupLayers = try makeGroupLayers(
from: items,
parentGroup: parentGroup,
parentGroupPath: parentGroupPath,
context: context)
for groupLayer in groupLayers {
addSublayer(groupLayer)
}
}
}
// MARK: Private
/// Sets up this layer using the given `Repeater`
private func setUpRepeater(
_ repeater: Repeater,
items allItems: [ShapeItemLayer.Item],
parentGroupPath: [String],
context: LayerContext)
throws
{
let items = allItems.filter { !($0.item is Repeater) }
let copyCount = Int(try repeater.copies.exactlyOneKeyframe(context: context, description: "repeater copies").value)
for index in 0..<copyCount {
let groupLayers = try makeGroupLayers(
from: items,
parentGroup: nil, // The repeater layer acts as the parent of its sublayers
parentGroupPath: parentGroupPath,
context: context)
for groupLayer in groupLayers {
let repeatedLayer = RepeaterLayer(repeater: repeater, childLayer: groupLayer, index: index)
addSublayer(repeatedLayer)
}
}
}
/// Creates a `GroupLayer` for each `Group` in the given list of `ShapeItem`s
/// - Each `Group` item becomes its own `GroupLayer` sublayer.
/// - Other `ShapeItem` are applied to all sublayers
private func makeGroupLayers(
from items: [ShapeItemLayer.Item],
parentGroup: Group?,
parentGroupPath: [String],
context: LayerContext)
throws -> [GroupLayer]
{
var groupItems = items.compactMap { $0.item as? Group }.filter { !$0.hidden }
var otherItems = items.filter { !($0.item is Group) && !$0.item.hidden }
// Handle the top-level `shapeLayer.items` array. This is typically just a single `Group`,
// but in practice can be any combination of items. The implementation expects all path-drawing
// shape items to be managed by a `GroupLayer`, so if there's a top-level path item we
// have to create a placeholder group.
if parentGroup == nil, otherItems.contains(where: { $0.item.drawsCGPath }) {
groupItems = [Group(items: items.map { $0.item }, name: "")]
otherItems = []
}
// Any child items that wouldn't be included in a valid shape render group
// need to be applied to child groups (otherwise they'd be silently ignored).
let inheritedItemsForChildGroups = otherItems
.shapeRenderGroups(groupHasChildGroupsToInheritUnusedItems: !groupItems.isEmpty)
.unusedItems
// Groups are listed from front to back,
// but `CALayer.sublayers` are listed from back to front.
let groupsInZAxisOrder = groupItems.reversed()
return try groupsInZAxisOrder.compactMap { group in
var pathForChildren = parentGroupPath
if !group.name.isEmpty {
pathForChildren.append(group.name)
}
let childItems = group.items
.filter { !$0.hidden }
.map { ShapeItemLayer.Item(item: $0, groupPath: pathForChildren) }
// Some shape item properties are affected by scaling (e.g. stroke width).
// The child group may have a `ShapeTransform` that affects the scale of its items,
// but shouldn't affect the scale of any inherited items. To prevent this scale
// from affecting inherited items, we have to apply an inverse scale to them.
let inheritedItems = try inheritedItemsForChildGroups.map { item in
ShapeItemLayer.Item(
item: try item.item.scaledCopyForChildGroup(group, context: context),
groupPath: item.groupPath)
}
return try GroupLayer(
group: group,
items: childItems + inheritedItems,
groupPath: pathForChildren,
context: context)
}
}
}
extension ShapeItem {
/// Whether or not this `ShapeItem` is responsible for rendering a `CGPath`
var drawsCGPath: Bool {
switch type {
case .ellipse, .rectangle, .shape, .star:
return true
case .fill, .gradientFill, .group, .gradientStroke, .merge,
.repeater, .round, .stroke, .trim, .transform, .unknown:
return false
}
}
/// Whether or not this `ShapeItem` provides a fill for a set of shapes
var isFill: Bool {
switch type {
case .fill, .gradientFill:
return true
case .ellipse, .rectangle, .shape, .star, .group, .gradientStroke,
.merge, .repeater, .round, .stroke, .trim, .transform, .unknown:
return false
}
}
/// Whether or not this `ShapeItem` provides a stroke for a set of shapes
var isStroke: Bool {
switch type {
case .stroke, .gradientStroke:
return true
case .ellipse, .rectangle, .shape, .star, .group, .gradientFill,
.merge, .repeater, .round, .fill, .trim, .transform, .unknown:
return false
}
}
// For any inherited shape items that are affected by scaling (e.g. strokes but not fills),
// any `ShapeTransform` in the given child group isn't supposed to be applied to the item.
// To cancel out the effect of the transform, we can apply an inverse transform to the
// shape item.
func scaledCopyForChildGroup(_ childGroup: Group, context: LayerContext) throws -> ShapeItem {
guard
// Path-drawing items aren't inherited by child groups in this way
!drawsCGPath,
// Stroke widths are affected by scaling, but fill colors aren't.
// We can expand this to other types of items in the future if necessary.
let stroke = self as? StrokeShapeItem,
// We only need to handle scaling if there's a `ShapeTransform` present
let transform = childGroup.items.first(where: { $0 is ShapeTransform }) as? ShapeTransform
else { return self }
let newWidth = try Keyframes.combined(stroke.width, transform.scale) { strokeWidth, scale -> LottieVector1D in
// Since we're applying this scale to a scalar value rather than to a layer,
// we can only handle cases where the scale is also a scalar (e.g. the same for both x and y)
try context.compatibilityAssert(scale.x == scale.y, """
The Core Animation rendering engine doesn't support applying separate x/y scale values \
(x: \(scale.x), y: \(scale.y)) to this stroke item (\(self.name)).
""")
return LottieVector1D(strokeWidth.value * (100 / scale.x))
}
return stroke.copy(width: newWidth)
}
}
extension Collection {
/// Splits this collection into two groups, based on the given predicate
func grouped(by predicate: (Element) -> Bool) -> (trueElements: [Element], falseElements: [Element]) {
var trueElements = [Element]()
var falseElements = [Element]()
for element in self {
if predicate(element) {
trueElements.append(element)
} else {
falseElements.append(element)
}
}
return (trueElements, falseElements)
}
/// Splits this collection into an array of grouping separated by the given separator.
/// For example, `[A, B, C]` split by `B` returns an array with two elements:
/// 1. `(grouping: [A], trailingSeparator: B)`
/// 2. `(grouping: [C], trailingSeparator: nil)`
func split(whereSeparator separatorPredicate: (Element) -> Bool)
-> [(grouping: [Element], trailingSeparator: Element?)]
{
guard !isEmpty else { return [] }
var groupings: [(grouping: [Element], trailingSeparator: Element?)] = []
for element in self {
if groupings.isEmpty || groupings.last?.trailingSeparator != nil {
groupings.append((grouping: [], trailingSeparator: nil))
}
if separatorPredicate(element) {
groupings[groupings.indices.last!].trailingSeparator = element
} else {
groupings[groupings.indices.last!].grouping.append(element)
}
}
return groupings
}
}
// MARK: - ShapeRenderGroup
/// A group of `ShapeItem`s that should be rendered together as a single unit
struct ShapeRenderGroup {
/// The items in this group that render `CGPath`s.
/// Valid shape render groups must have at least one path-drawing item.
var pathItems: [ShapeItemLayer.Item] = []
/// Shape items that modify the appearance of the shapes rendered by this group
var otherItems: [ShapeItemLayer.Item] = []
}
extension [ShapeItemLayer.Item] {
/// Splits this list of `ShapeItem`s into groups that should be rendered together as individual units,
/// plus the remaining items that were not included in any group.
/// - groupHasChildGroupsToInheritUnusedItems: whether or not this group has child groups
/// that will inherit any items that aren't used as part of a valid render group
func shapeRenderGroups(groupHasChildGroupsToInheritUnusedItems: Bool)
-> (validGroups: [ShapeRenderGroup], unusedItems: [ShapeItemLayer.Item])
{
var renderGroups = [ShapeRenderGroup()]
for item in self {
// `renderGroups` is non-empty, so is guaranteed to have a valid end index
var lastIndex: Int {
renderGroups.indices.last!
}
if item.item.drawsCGPath {
// Trims should only affect paths that precede them in the group,
// so if the existing group already has a trim we create a new group for this path item.
if renderGroups[lastIndex].otherItems.contains(where: { $0.item is Trim }) {
renderGroups.append(ShapeRenderGroup())
}
renderGroups[lastIndex].pathItems.append(item)
}
// `Fill` items are unique, because they specifically only apply to _previous_ shapes in a `Group`
// - For example, with [Rectangle, Fill(Red), Circle, Fill(Blue)], the Rectangle should be Red
// but the Circle should be Blue.
// - To handle this, we create a new `ShapeRenderGroup` when we encounter a `Fill` item
else if item.item.isFill {
renderGroups[lastIndex].otherItems.append(item)
// There are cases where the current render group doesn't have a path-drawing
// shape item yet, and could just contain this fill. Some examples:
// - `[Circle, Fill(Red), Fill(Green)]`: In this case, the second fill would
// be unused and silently ignored. To avoid this we render the fill using
// the shape items from the previous group.
// - `[Circle, Fill(Red), Group, Fill(Green)]`: In this case, the second fill
// is inherited and rendered by the child group.
if
renderGroups[lastIndex].pathItems.isEmpty,
!groupHasChildGroupsToInheritUnusedItems,
lastIndex != renderGroups.indices.first
{
renderGroups[lastIndex].pathItems = renderGroups[lastIndex - 1].pathItems
}
// Finalize the group so the fill item doesn't affect following shape items
renderGroups.append(ShapeRenderGroup())
}
// Other items in the list are applied to all subgroups
else {
for index in renderGroups.indices {
renderGroups[index].otherItems.append(item)
}
}
}
/// The main thread rendering engine draws each Stroke and Fill as a separate `CAShapeLayer`.
/// As an optimization, we can combine them into a single shape layer when a few conditions are met:
/// 1. There is at most one stroke and one fill (a `CAShapeLayer` can only render one of each)
/// 2. The stroke is drawn on top of the fill (the behavior of a `CAShapeLayer`)
/// 3. The fill and stroke have the same `opacity` animations (since a `CAShapeLayer` can only render
/// a single set of `opacity` animations).
/// Otherwise, each stroke / fill needs to be split into a separate layer.
renderGroups = renderGroups.flatMap { group -> [ShapeRenderGroup] in
let (strokesAndFills, otherItems) = group.otherItems.grouped(by: { $0.item.isFill || $0.item.isStroke })
let (strokes, fills) = strokesAndFills.grouped(by: { $0.item.isStroke })
// A `CAShapeLayer` can only draw a single fill and a single stroke
let hasAtMostOneFill = fills.count <= 1
let hasAtMostOneStroke = strokes.count <= 1
// A `CAShapeLayer` can only draw a stroke on top of a fill -- if the fill is supposed to be
// drawn on top of the stroke, then they have to be rendered as separate layers.
let strokeDrawnOnTopOfFill: Bool
if
let strokeIndex = strokesAndFills.firstIndex(where: { $0.item.isStroke }),
let fillIndex = strokesAndFills.firstIndex(where: { $0.item.isFill })
{
strokeDrawnOnTopOfFill = strokeIndex < fillIndex
} else {
strokeDrawnOnTopOfFill = false
}
// `Fill` and `Stroke` items have an `alpha` property that can be animated separately,
// but each layer only has a single `opacity` property. We can only use a single `CAShapeLayer`
// when the items have the same `alpha` animations.
let allAlphaAnimationsAreIdentical = {
strokesAndFills.allSatisfy { item in
(item.item as? OpacityAnimationModel)?.opacity
== (strokesAndFills.first?.item as? OpacityAnimationModel)?.opacity
}
}
// If all the required conditions are met, this group can be rendered using a single `ShapeItemLayer`
if
hasAtMostOneFill,
hasAtMostOneStroke,
strokeDrawnOnTopOfFill,
allAlphaAnimationsAreIdentical()
{
return [group]
}
// Otherwise each stroke / fill needs to be rendered as a separate `ShapeItemLayer`
return strokesAndFills.map { strokeOrFill in
ShapeRenderGroup(
pathItems: group.pathItems,
otherItems: [strokeOrFill] + otherItems)
}
}
// All valid render groups must have a path, otherwise the items wouldn't be rendered
renderGroups = renderGroups.filter { renderGroup in
!renderGroup.pathItems.isEmpty
}
let itemsInValidRenderGroups = NSSet(
array: renderGroups.lazy
.flatMap { $0.pathItems + $0.otherItems }
.map { $0.item })
// `unusedItems` should only include each original item a single time,
// and should preserve the existing order
let itemsNotInValidRenderGroups = filter { item in
!itemsInValidRenderGroups.contains(item.item)
}
return (validGroups: renderGroups, unusedItems: itemsNotInValidRenderGroups)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/ShapeLayer.swift
|
Swift
|
unknown
| 22,166
|
// Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - SolidLayer
final class SolidLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(_ solidLayer: SolidLayerModel) {
self.solidLayer = solidLayer
super.init(layerModel: solidLayer)
setupContentLayer()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
solidLayer = typedLayer.solidLayer
super.init(layer: typedLayer)
}
// MARK: Internal
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
var context = context
context = context.addingKeypathComponent(solidLayer.name)
// Even though the Lottie json schema provides a fixed `solidLayer.colorHex` value,
// we still need to create a set of keyframes and go through the standard `CAAnimation`
// codepath so that this value can be customized using the custom `ValueProvider`s API.
try shapeLayer.addAnimation(
for: .fillColor,
keyframes: KeyframeGroup(solidLayer.colorHex.lottieColor),
value: { $0.cgColorValue },
context: context)
}
// MARK: Private
private let solidLayer: SolidLayerModel
/// Render the fill color in a child `CAShapeLayer`
/// - Using a `CAShapeLayer` specifically, instead of a `CALayer` with a `backgroundColor`,
/// allows the size of the fill shape to be different from `contentsLayer.size`.
private let shapeLayer = CAShapeLayer()
private func setupContentLayer() {
shapeLayer.path = CGPath(rect: .init(x: 0, y: 0, width: solidLayer.width, height: solidLayer.height), transform: nil)
addSublayer(shapeLayer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/SolidLayer.swift
|
Swift
|
unknown
| 2,084
|
// Created by Cal Stephens on 2/9/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
/// The `CALayer` type responsible for rendering `TextLayer`s
final class TextLayer: BaseCompositionLayer {
// MARK: Lifecycle
init(
textLayerModel: TextLayerModel,
context: LayerContext)
throws
{
self.textLayerModel = textLayerModel
super.init(layerModel: textLayerModel)
setupSublayers()
try configureRenderLayer(with: context)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Called by CoreAnimation to create a shadow copy of this layer
/// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init
override init(layer: Any) {
guard let typedLayer = layer as? Self else {
fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))")
}
textLayerModel = typedLayer.textLayerModel
super.init(layer: typedLayer)
}
// MARK: Internal
override func setupAnimations(context: LayerAnimationContext) throws {
try super.setupAnimations(context: context)
let textAnimationContext = context.addingKeypathComponent(textLayerModel.name)
let sourceText = try textLayerModel.text.exactlyOneKeyframe(
context: textAnimationContext,
description: "text layer text")
// Prior to Lottie 4.3.0 the Core Animation rendering engine always just used `LegacyAnimationTextProvider`
// but incorrectly called it with the full keypath string, unlike the Main Thread rendering engine
// which only used the last component of the keypath. Starting in Lottie 4.3.0 we use `AnimationKeypathTextProvider`
// instead if implemented.
if let keypathTextValue = context.textProvider.text(for: textAnimationContext.currentKeypath, sourceText: sourceText.text) {
renderLayer.text = keypathTextValue
} else if let legacyTextProvider = context.textProvider as? LegacyAnimationTextProvider {
renderLayer.text = legacyTextProvider.textFor(
keypathName: textAnimationContext.currentKeypath.fullPath,
sourceText: sourceText.text)
} else {
renderLayer.text = sourceText.text
}
renderLayer.sizeToFit()
}
func configureRenderLayer(with context: LayerContext) throws {
// We can't use `CATextLayer`, because it doesn't support enough features we use.
// Instead, we use the same `CoreTextRenderLayer` (with a custom `draw` implementation)
// used by the Main Thread rendering engine. This means the Core Animation engine can't
// _animate_ text properties, but it can display static text without any issues.
let text = try textLayerModel.text.exactlyOneKeyframe(context: context, description: "text layer text")
// The Core Animation engine doesn't currently support `TextAnimator`s.
// - We could add support for animating the transform-related properties without much trouble.
// - We may be able to support animating `fillColor` by getting clever with layer blend modes
// or masks (e.g. use `CoreTextRenderLayer` to draw black glyphs, and then fill them in
// using a `CAShapeLayer`).
if !textLayerModel.animators.isEmpty {
try context.logCompatibilityIssue("""
The Core Animation rendering engine currently doesn't support text animators.
""")
}
renderLayer.font = context.fontProvider.fontFor(family: text.fontFamily, size: CGFloat(text.fontSize))
renderLayer.alignment = text.justification.textAlignment
renderLayer.lineHeight = CGFloat(text.lineHeight)
renderLayer.tracking = (CGFloat(text.fontSize) * CGFloat(text.tracking)) / 1000
renderLayer.fillColor = text.fillColorData?.cgColorValue
renderLayer.strokeColor = text.strokeColorData?.cgColorValue
renderLayer.strokeWidth = CGFloat(text.strokeWidth ?? 0)
renderLayer.strokeOnTop = text.strokeOverFill ?? false
renderLayer.preferredSize = text.textFrameSize?.sizeValue
renderLayer.sizeToFit()
renderLayer.transform = CATransform3DIdentity
renderLayer.position = text.textFramePosition?.pointValue ?? .zero
}
// MARK: Private
private let textLayerModel: TextLayerModel
private let renderLayer = CoreTextRenderLayer()
private func setupSublayers() {
// Place the text render layer in an additional container
// - Direct sublayers of a `BaseCompositionLayer` always fill the bounds
// of their superlayer -- so this container will be the bounds of self,
// and the text render layer can be positioned anywhere.
let textContainerLayer = CALayer()
textContainerLayer.addSublayer(renderLayer)
addSublayer(textContainerLayer)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/TextLayer.swift
|
Swift
|
unknown
| 4,716
|
// Created by Cal Stephens on 12/21/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
/// The CALayer type responsible for only rendering the `transform` of a `LayerModel`
final class TransformLayer: BaseCompositionLayer {
/// `TransformLayer`s don't render any visible content,
/// they just `transform` their sublayers
override var renderLayerContents: Bool { false }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/Layers/TransformLayer.swift
|
Swift
|
unknown
| 389
|
// Created by Cal Stephens on 1/13/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
// MARK: - ValueProviderStore
/// Registration and storage for `AnyValueProvider`s that can dynamically
/// provide custom values for `AnimationKeypath`s within a `LottieAnimation`.
final class ValueProviderStore {
// MARK: Lifecycle
init(logger: LottieLogger) {
self.logger = logger
}
// MARK: Internal
/// Registers an `AnyValueProvider` for the given `AnimationKeypath`
func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
logger.assert(
valueProvider.typeErasedStorage.isSupportedByCoreAnimationRenderingEngine,
"""
The Core Animation rendering engine doesn't support Value Providers that vend a closure,
because that would require calling the closure on the main thread once per frame.
""")
let supportedProperties = PropertyName.allCases.map { $0.rawValue }
let propertyBeingCustomized = keypath.keys.last ?? ""
logger.assert(
supportedProperties.contains(propertyBeingCustomized),
"""
The Core Animation rendering engine currently doesn't support customizing "\(propertyBeingCustomized)" \
properties. Supported properties are: \(supportedProperties.joined(separator: ", ")).
""")
valueProviders.removeAll(where: { $0.keypath == keypath })
valueProviders.append((keypath: keypath, valueProvider: valueProvider))
}
// Retrieves the custom value keyframes for the given property,
// if an `AnyValueProvider` was registered for the given keypath.
func customKeyframes<Value>(
of customizableProperty: CustomizableProperty<Value>,
for keypath: AnimationKeypath,
context: LayerAnimationContext)
throws -> KeyframeGroup<Value>?
{
context.recordHierarchyKeypath?(keypath.fullPath)
guard let anyValueProvider = valueProvider(for: keypath) else {
return nil
}
// Retrieve the type-erased keyframes from the custom `ValueProvider`
let typeErasedKeyframes: [Keyframe<Any>]
switch anyValueProvider.typeErasedStorage {
case .singleValue(let typeErasedValue):
typeErasedKeyframes = [Keyframe(typeErasedValue)]
case .keyframes(let keyframes, _):
typeErasedKeyframes = keyframes
case .closure:
try context.logCompatibilityIssue("""
The Core Animation rendering engine doesn't support Value Providers that vend a closure,
because that would require calling the closure on the main thread once per frame.
""")
return nil
}
// Convert the type-erased keyframe values using this `CustomizableProperty`'s conversion closure
let typedKeyframes = typeErasedKeyframes.compactMap { typeErasedKeyframe -> Keyframe<Value>? in
guard let convertedValue = customizableProperty.conversion(typeErasedKeyframe.value, anyValueProvider) else {
logger.assertionFailure("""
Could not convert value of type \(type(of: typeErasedKeyframe.value)) from \(anyValueProvider) to expected type \(
Value
.self)
""")
return nil
}
return typeErasedKeyframe.withValue(convertedValue)
}
// Verify that all of the keyframes were successfully converted to the expected type
guard typedKeyframes.count == typeErasedKeyframes.count else {
return nil
}
return KeyframeGroup(keyframes: ContiguousArray(typedKeyframes))
}
// MARK: Private
private let logger: LottieLogger
private var valueProviders = [(keypath: AnimationKeypath, valueProvider: AnyValueProvider)]()
/// Retrieves the most-recently-registered Value Provider that matches the given keypath.
private func valueProvider(for keypath: AnimationKeypath) -> AnyValueProvider? {
// Find the last keypath matching the given keypath,
// so we return the value provider that was registered most-recently
valueProviders.last(where: { registeredKeypath, _ in
keypath.matches(registeredKeypath)
})?.valueProvider
}
}
extension AnyValueProviderStorage {
/// Whether or not this type of value provider is supported
/// by the new Core Animation rendering engine
var isSupportedByCoreAnimationRenderingEngine: Bool {
switch self {
case .singleValue, .keyframes:
return true
case .closure:
return false
}
}
}
extension AnimationKeypath {
/// Whether or not this keypath from the animation hierarchy
/// matches the given keypath (which may contain wildcards)
func matches(_ keypath: AnimationKeypath) -> Bool {
var regex = "^" // match the start of the string
+ keypath.keys.joined(separator: "\\.") // match this keypath, escaping "." characters
+ "$" // match the end of the string
// Replace the ** and * wildcards with markers that are guaranteed to be unique
// and won't conflict with regex syntax (e.g. `.*`).
let doubleWildcardMarker = UUID().uuidString
let singleWildcardMarker = UUID().uuidString
regex = regex.replacingOccurrences(of: "**", with: doubleWildcardMarker)
regex = regex.replacingOccurrences(of: "*", with: singleWildcardMarker)
// "**" wildcards match zero or more path segments separated by "\\."
// - "**.Color" matches any of "Color", "Layer 1.Color", and "Layer 1.Layer 2.Color"
regex = regex.replacingOccurrences(of: "\(doubleWildcardMarker)\\.", with: ".*")
regex = regex.replacingOccurrences(of: doubleWildcardMarker, with: ".*")
// "*" wildcards match exactly one path component
// - "*.Color" matches "Layer 1.Color" but not "Layer 1.Layer 2.Color"
regex = regex.replacingOccurrences(of: singleWildcardMarker, with: "[^.]+")
return fullPath.range(of: regex, options: .regularExpression) != nil
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/CoreAnimation/ValueProviderStore.swift
|
Swift
|
unknown
| 5,784
|
// Created by Laura Skelton on 11/25/16.
// Copyright © 2016 Airbnb. All rights reserved.
// MARK: - Collection
extension Collection where Element: Diffable, Index == Int {
/// Diffs two collections (e.g. `Array`s) of `Diffable` items, returning an `IndexChangeset`
/// representing the minimal set of changes to get from the other collection to this collection.
///
/// - Parameters:
/// - from other: The collection of old data.
func makeChangeset(from other: Self) -> IndexChangeset {
// Arranging the elements contiguously prior to diffing improves performance by ~40%.
let new = ContiguousArray(self)
let old = ContiguousArray(other)
/// The entries in both this and the other collection, keyed by their `dataID`s.
var entries = [AnyHashable: EpoxyEntry](minimumCapacity: new.count)
var duplicates = [EpoxyEntry]()
var newResults = ContiguousArray<NewRecord>()
newResults.reserveCapacity(new.count)
for index in new.indices {
let id = new[index].diffIdentifier
let entry = entries[id, default: EpoxyEntry()]
if entry.trackNewIndex(index) {
duplicates.append(entry)
}
entries[id] = entry
newResults.append(NewRecord(entry: entry))
}
var oldResults = ContiguousArray<OldRecord>()
oldResults.reserveCapacity(old.count)
for index in old.indices {
let id = old[index].diffIdentifier
let entry = entries[id]
entry?.pushOldIndex(index)
oldResults.append(OldRecord(entry: entry))
}
for newIndex in new.indices {
let entry = newResults[newIndex].entry
if let oldIndex = entry.popOldIndex() {
let newItem = new[newIndex]
let oldItem = other[oldIndex]
if !oldItem.isDiffableItemEqual(to: newItem) {
entry.isUpdated = true
}
newResults[newIndex].correspondingOldIndex = oldIndex
oldResults[oldIndex].correspondingNewIndex = newIndex
}
}
var deletes = [Int]()
var deleteOffsets = [Int]()
deleteOffsets.reserveCapacity(old.count)
var runningDeleteOffset = 0
for index in old.indices {
deleteOffsets.append(runningDeleteOffset)
let record = oldResults[index]
if record.correspondingNewIndex == nil {
deletes.append(index)
runningDeleteOffset += 1
}
}
var inserts = [Int]()
var updates = [(Int, Int)]()
var moves = [(Int, Int)]()
var insertOffsets = [Int]()
insertOffsets.reserveCapacity(new.count)
var runningInsertOffset = 0
for index in new.indices {
insertOffsets.append(runningInsertOffset)
let record = newResults[index]
if let oldArrayIndex = record.correspondingOldIndex {
if record.entry.isUpdated {
updates.append((oldArrayIndex, index))
}
let insertOffset = insertOffsets[index]
let deleteOffset = deleteOffsets[oldArrayIndex]
if (oldArrayIndex - deleteOffset + insertOffset) != index {
moves.append((oldArrayIndex, index))
}
} else {
inserts.append(index)
runningInsertOffset += 1
}
}
EpoxyLogger.shared.assert(
old.count + inserts.count - deletes.count == new.count,
"Failed sanity check for old count with changes matching new count.")
return IndexChangeset(
inserts: inserts,
deletes: deletes,
updates: updates,
moves: moves,
newIndices: oldResults.map { $0.correspondingNewIndex },
duplicates: duplicates.map { $0.newIndices })
}
/// Diffs between two collections (eg. `Array`s) of `Diffable` items, and returns an `IndexPathChangeset`
/// representing the minimal set of changes to get from the other collection to this collection.
///
/// - Parameters:
/// - from other: The collection of old data.
/// - fromSection: The section the other collection's data exists within. Defaults to `0`.
/// - toSection: The section this collection's data exists within. Defaults to `0`.
func makeIndexPathChangeset(
from other: Self,
fromSection: Int = 0,
toSection: Int = 0)
-> IndexPathChangeset
{
let indexChangeset = makeChangeset(from: other)
return IndexPathChangeset(
inserts: indexChangeset.inserts.map { index in
[toSection, index]
},
deletes: indexChangeset.deletes.map { index in
[fromSection, index]
},
updates: indexChangeset.updates.map { fromIndex, toIndex in
([fromSection, fromIndex], [toSection, toIndex])
},
moves: indexChangeset.moves.map { fromIndex, toIndex in
([fromSection, fromIndex], [toSection, toIndex])
},
duplicates: indexChangeset.duplicates.map { duplicate in
duplicate.map { index in
[toSection, index]
}
})
}
/// Diffs between two collections (e.g. `Array`s) of `Diffable` items, returning an
/// `IndexSetChangeset` representing the minimal set of changes to get from the other collection
/// to this collection.
///
/// - Parameters:
/// - from other: The collection of old data.
func makeIndexSetChangeset(from other: Self) -> IndexSetChangeset {
let indexChangeset = makeChangeset(from: other)
return IndexSetChangeset(
inserts: .init(indexChangeset.inserts),
deletes: .init(indexChangeset.deletes),
updates: indexChangeset.updates,
moves: indexChangeset.moves,
newIndices: indexChangeset.newIndices,
duplicates: indexChangeset.duplicates.map { .init($0) })
}
}
extension Collection where Element: DiffableSection, Index == Int {
/// Diffs between two collections (e.g. `Array`s) of `DiffableSection` items, returning an
/// `SectionedChangeset` representing the minimal set of changes to get from the other collection
/// to this collection.
///
/// - Parameters:
/// - from other: The collection of old data.
func makeSectionedChangeset(from other: Self) -> SectionedChangeset {
let sectionChangeset = makeIndexSetChangeset(from: other)
var itemChangeset = IndexPathChangeset()
for fromSectionIndex in other.indices {
guard let toSectionIndex = sectionChangeset.newIndices[fromSectionIndex] else {
continue
}
let fromItems = other[fromSectionIndex].diffableItems
let toItems = self[toSectionIndex].diffableItems
let itemIndexChangeset = toItems.makeIndexPathChangeset(
from: fromItems,
fromSection: fromSectionIndex,
toSection: toSectionIndex)
itemChangeset += itemIndexChangeset
}
return SectionedChangeset(sectionChangeset: sectionChangeset, itemChangeset: itemChangeset)
}
}
// MARK: - EpoxyEntry
/// A bookkeeping refrence type for the diffing algorithm.
private final class EpoxyEntry {
// MARK: Internal
private(set) var oldIndices = [Int]()
private(set) var newIndices = [Int]()
var isUpdated = false
/// Tracks an index from the new indices, returning `true` if this entry has previously tracked
/// a new index as a means to identify duplicates and `false` otherwise.
func trackNewIndex(_ index: Int) -> Bool {
let previouslyEmpty = newIndices.isEmpty
newIndices.append(index)
// We've encountered a duplicate, return true so we can track it.
if !previouslyEmpty, newIndices.count == 2 {
return true
}
return false
}
func pushOldIndex(_ index: Int) {
oldIndices.append(index)
}
func popOldIndex() -> Int? {
guard currentOldIndex < oldIndices.endIndex else {
return nil
}
defer {
currentOldIndex += 1
}
return oldIndices[currentOldIndex]
}
// MARK: Private
private var currentOldIndex = 0
}
// MARK: - OldRecord
/// A bookkeeping type for pairing up an old element with its new index.
private struct OldRecord {
var entry: EpoxyEntry?
var correspondingNewIndex: Int? = nil
}
// MARK: - NewRecord
/// A bookkeeping type for pairing up a new element with its old index.
private struct NewRecord {
var entry: EpoxyEntry
var correspondingOldIndex: Int? = nil
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Diffing/Collection+Diff.swift
|
Swift
|
unknown
| 8,094
|
// Created by Laura Skelton on 5/11/17.
// Copyright © 2017 Airbnb. All rights reserved.
// MARK: - Diffable
/// A protocol that allows us to check identity and equality between items for the purposes of
/// diffing.
protocol Diffable {
/// Checks for equality between items when diffing.
///
/// - Parameters:
/// - otherDiffableItem: The other item to check equality against while diffing.
func isDiffableItemEqual(to otherDiffableItem: Diffable) -> Bool
/// The identifier to use when checking identity while diffing.
var diffIdentifier: AnyHashable { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Diffing/Diffable.swift
|
Swift
|
unknown
| 588
|
// Created by eric_horacek on 12/9/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - DiffableSection
/// A protocol that allows us to check identity and equality between sections of `Diffable` items
/// for the purposes of diffing.
protocol DiffableSection: Diffable {
/// The diffable items in this section.
associatedtype DiffableItems: Collection where
DiffableItems.Index == Int,
DiffableItems.Element: Diffable
/// The diffable items in this section.
var diffableItems: DiffableItems { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Diffing/DiffableSection.swift
|
Swift
|
unknown
| 537
|
// Created by Laura Skelton on 11/25/16.
// Copyright © 2016 Airbnb. All rights reserved.
import Foundation
// MARK: - IndexChangeset
/// A set of inserts, deletes, updates, and moves that define the changes between two collections.
struct IndexChangeset {
// MARK: Lifecycle
init(
inserts: [Int] = [],
deletes: [Int] = [],
updates: [(old: Int, new: Int)] = [],
moves: [(old: Int, new: Int)] = [],
newIndices: [Int?] = [],
duplicates: [[Int]] = [])
{
self.inserts = inserts
self.deletes = deletes
self.updates = updates
self.moves = moves
self.newIndices = newIndices
self.duplicates = duplicates
}
// MARK: Internal
/// The inserted indices needed to get from the old collection to the new collection.
var inserts: [Int]
/// The deleted indices needed to get from the old collection to the new collection.
var deletes: [Int]
/// The updated indices needed to get from the old collection to the new collection.
var updates: [(old: Int, new: Int)]
/// The moved indices needed to get from the old collection to the new collection.
var moves: [(old: Int, new: Int)]
/// A record for each old collection item to its index (if any) is in the new collection.
///
/// The indexes of this `Array` represent the indexes old collection, with elements of the
/// corresponding index of the same item in the new collection it exists, else `nil`.
var newIndices: [Int?]
/// A record of each element in the new collection that has an identical `diffIdentifier` with
/// another element in the same collection.
///
/// Each element in the outer `Array` corresponds to a duplicated identifier, with each inner
/// `[Int]` containing the indexes that share a duplicate identifier in the new collection.
///
/// While the diffing algorithm makes a best effort to handle duplicates, they can lead to
/// unexpected behavior since identity of elements cannot be established and should be avoided if
/// possible.
var duplicates: [[Int]]
/// Whether there are any inserts, deletes, moves, or updates in this changeset.
var isEmpty: Bool {
inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty
}
}
// MARK: - IndexPathChangeset
/// A set of inserts, deletes, updates, and moves that define the changes between two collections
/// with indexes stored as `IndexPath`s.
struct IndexPathChangeset {
// MARK: Lifecycle
init(
inserts: [IndexPath] = [],
deletes: [IndexPath] = [],
updates: [(old: IndexPath, new: IndexPath)] = [],
moves: [(old: IndexPath, new: IndexPath)] = [],
duplicates: [[IndexPath]] = [])
{
self.inserts = inserts
self.deletes = deletes
self.updates = updates
self.moves = moves
self.duplicates = duplicates
}
// MARK: Internal
/// The inserted `IndexPath`s needed to get from the old collection to the new collection.
var inserts: [IndexPath]
/// The deleted `IndexPath`s needed to get from the old collection to the new collection.
var deletes: [IndexPath]
/// The updated `IndexPath`s needed to get from the old collection to the new collection.
var updates: [(old: IndexPath, new: IndexPath)]
/// The moved `IndexPath`s needed to get from the old collection to the new collection.
var moves: [(old: IndexPath, new: IndexPath)]
/// A record for each element in the new collection that has an identical `diffIdentifier` with
/// another element in the same collection.
///
/// Each element in the outer `Array` corresponds to a duplicated identifier, with each inner
/// `[IndexPath]` corresponding to the indexes that share a duplicate identifier in the new
/// collection.
///
/// While the diffing algorithm makes a best effort to handle duplicates, they can lead to
/// unexpected behavior since identity of elements cannot be established and should be avoided if
/// possible.
var duplicates: [[IndexPath]]
/// Whether there are any inserts, deletes, moves, or updates in this changeset.
var isEmpty: Bool {
inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty
}
static func += (left: inout IndexPathChangeset, right: IndexPathChangeset) {
left.inserts += right.inserts
left.deletes += right.deletes
left.updates += right.updates
left.moves += right.moves
left.duplicates += right.duplicates
}
}
// MARK: - IndexSetChangeset
/// A set of inserts, deletes, updates, and moves that define the changes between two collections
/// with indexes stored as `IndexSet`.
struct IndexSetChangeset {
// MARK: Lifecycle
init(
inserts: IndexSet = [],
deletes: IndexSet = [],
updates: [(old: Int, new: Int)] = [],
moves: [(old: Int, new: Int)] = [],
newIndices: [Int?] = [],
duplicates: [IndexSet] = [])
{
self.inserts = inserts
self.deletes = deletes
self.updates = updates
self.moves = moves
self.newIndices = newIndices
self.duplicates = duplicates
}
// MARK: Internal
/// An `IndexSet` of inserts needed to get from the old collection to the new collection.
var inserts: IndexSet
/// An `IndexSet` of deletes needed to get from the old collection to the new collection.
var deletes: IndexSet
/// The updated indices needed to get from the old collection to the new collection.
var updates: [(old: Int, new: Int)]
/// The moved indices needed to get from the old collection to the new collection.
var moves: [(old: Int, new: Int)]
/// A record for each old collection item of what its index (if any) is in the new collection.
///
/// The indexes of this `Array` represent the indexes old collection, with elements of the
/// corresponding index of the same item in the new collection it exists, else `nil`.
var newIndices: [Int?]
/// A record for each element in the new collection that has an identical `diffIdentifier` with
/// another element in the same collection.
///
/// Each element in the `Array` corresponds to a duplicated identifier, with each `IndexSet`
/// containing the indexes that share a duplicate identifier in the new collection.
///
/// While the diffing algorithm makes a best effort to handle duplicates, they can lead to
/// unexpected behavior since identity of elements cannot be established and should be avoided if
/// possible.
var duplicates: [IndexSet]
/// Whether there are any inserts, deletes, moves, or updates in this changeset.
var isEmpty: Bool {
inserts.isEmpty && deletes.isEmpty && updates.isEmpty && moves.isEmpty
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Diffing/IndexChangeset.swift
|
Swift
|
unknown
| 6,576
|
// Created by Laura Skelton on 5/11/17.
// Copyright © 2017 Airbnb. All rights reserved.
/// A set of the minimum changes to get from one array of `DiffableSection`s to another, used for
/// diffing.
struct SectionedChangeset {
// MARK: Lifecycle
init(
sectionChangeset: IndexSetChangeset,
itemChangeset: IndexPathChangeset)
{
self.sectionChangeset = sectionChangeset
self.itemChangeset = itemChangeset
}
// MARK: Internal
/// A set of the minimum changes to get from one set of sections to another.
var sectionChangeset: IndexSetChangeset
/// A set of the minimum changes to get from one set of items to another, aggregated across all
/// sections.
var itemChangeset: IndexPathChangeset
/// Whether there are any inserts, deletes, moves, or updates in this changeset.
var isEmpty: Bool {
sectionChangeset.isEmpty && itemChangeset.isEmpty
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Diffing/SectionedChangeset.swift
|
Swift
|
unknown
| 900
|
// Created by eric_horacek on 12/9/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
/// A shared logger that allows consumers to intercept Epoxy assertions and warning messages to pipe
/// into their own logging systems.
final class EpoxyLogger {
// MARK: Lifecycle
init(
assert: @escaping Assert = { condition, message, file, line in
// If we default to `Swift.assert` directly with `assert: Assert = Swift.assert`,
// the call will unexpectedly not respect the -O flag and will crash in release
// https://github.com/apple/swift/issues/60249
Swift.assert(condition(), message(), file: file, line: line)
},
assertionFailure: @escaping AssertionFailure = { message, file, line in
// If we default to `Swift.assertionFailure` directly with
// `assertionFailure: AssertionFailure = Swift.assertionFailure`,
// the call will unexpectedly not respect the -O flag and will crash in release
// https://github.com/apple/swift/issues/60249
Swift.assertionFailure(message(), file: file, line: line)
},
warn: @escaping Warn = { message, _, _ in
#if DEBUG
// swiftlint:disable:next no_direct_standard_out_logs
print(message())
#endif
})
{
_assert = assert
_assertionFailure = assertionFailure
_warn = warn
}
// MARK: Internal
/// Logs that an assertion occurred.
typealias Assert = (
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String,
_ fileID: StaticString,
_ line: UInt)
-> Void
/// Logs that an assertion failure occurred.
typealias AssertionFailure = (
_ message: @autoclosure () -> String,
_ fileID: StaticString,
_ line: UInt)
-> Void
/// Logs a warning message.
typealias Warn = (
_ message: @autoclosure () -> String,
_ fileID: StaticString,
_ line: UInt)
-> Void
/// The shared instance used to log Epoxy assertions and warnings.
///
/// Set this to a new logger instance to intercept assertions and warnings logged by Epoxy.
static var shared = EpoxyLogger()
/// Logs that an assertion occurred.
func assert(
_ condition: @autoclosure () -> Bool,
_ message: @autoclosure () -> String = String(),
fileID: StaticString = #fileID,
line: UInt = #line)
{
_assert(condition(), message(), fileID, line)
}
/// Logs that an assertion failure occurred.
func assertionFailure(
_ message: @autoclosure () -> String = String(),
fileID: StaticString = #fileID,
line: UInt = #line)
{
_assertionFailure(message(), fileID, line)
}
/// Logs a warning message.
func warn(
_ message: @autoclosure () -> String = String(),
fileID: StaticString = #fileID,
line: UInt = #line)
{
_warn(message(), fileID, line)
}
// MARK: Private
private let _assert: Assert
private let _assertionFailure: AssertionFailure
private let _warn: Warn
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Logging/EpoxyLogger.swift
|
Swift
|
unknown
| 2,935
|
// Created by eric_horacek on 12/15/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
/// An Epoxy model with an associated context type that's passed into callback closures.
protocol CallbackContextEpoxyModeled: EpoxyModeled {
/// A context type that's passed into callback closures.
associatedtype CallbackContext
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/CallbackContextEpoxyModeled.swift
|
Swift
|
unknown
| 331
|
// Created by eric_horacek on 3/15/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
/// A generic result builder that enables a DSL for building arrays of Epoxy models.
@resultBuilder
enum EpoxyModelArrayBuilder<Model> {
typealias Expression = Model
typealias Component = [Model]
static func buildExpression(_ expression: Expression) -> Component {
[expression]
}
static func buildExpression(_ expression: Component) -> Component {
expression
}
static func buildExpression(_ expression: Expression?) -> Component {
if let expression {
return [expression]
}
return []
}
static func buildBlock(_ children: Component...) -> Component {
children.flatMap { $0 }
}
static func buildBlock(_ component: Component) -> Component {
component
}
static func buildOptional(_ children: Component?) -> Component {
children ?? []
}
static func buildEither(first child: Component) -> Component {
child
}
static func buildEither(second child: Component) -> Component {
child
}
static func buildArray(_ components: [Component]) -> Component {
components.flatMap { $0 }
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/EpoxyModelArrayBuilder.swift
|
Swift
|
unknown
| 1,162
|
// Created by eric_horacek on 11/18/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - EpoxyModelProperty
/// A property that can be stored in any concrete `EpoxyModeled` type.
///
/// Custom model properties can be declared in any module. It's recommended that properties are
/// declared as `var`s in extensions to `EpoxyModeled` with a `*Property` suffix.
///
/// For example, to declare a `EpoxyModelProperty` that fulfills the `TitleProviding` protocol:
///
/// ````
/// internal protocol TitleProviding {
/// var title: String? { get }
/// }
///
/// extension EpoxyModeled where Self: TitleProviding {
/// internal var title: String? {
/// get { self[titleProperty] }
/// set { self[titleProperty] = newValue }
/// }
///
/// internal func title(_ value: String?) -> Self {
/// copy(updating: titleProperty, to: value)
/// }
///
/// private var titleProperty: EpoxyModelProperty<String?> {
/// .init(keyPath: \TitleProviding.title, defaultValue: nil, updateStrategy: .replace)
/// }
/// }
/// ````
struct EpoxyModelProperty<Value> {
// MARK: Lifecycle
/// Creates a property identified by a `KeyPath` to its provided `value` and with its default
/// value if not customized in content by consumers.
///
/// The `updateStrategy` is used to update the value when updating from an old value to a new
/// value.
init<Model>(
keyPath: KeyPath<Model, Value>,
defaultValue: @escaping @autoclosure () -> Value,
updateStrategy: UpdateStrategy)
{
self.keyPath = keyPath
self.defaultValue = defaultValue
self.updateStrategy = updateStrategy
}
// MARK: Internal
/// The `KeyPath` that uniquely identifies this property.
let keyPath: AnyKeyPath
/// A closure that produces the default property value when called.
let defaultValue: () -> Value
/// A closure used to update an `EpoxyModelProperty` from an old value to a new value.
let updateStrategy: UpdateStrategy
}
// MARK: EpoxyModelProperty.UpdateStrategy
extension EpoxyModelProperty {
/// A closure used to update an `EpoxyModelProperty` from an old value to a new value.
struct UpdateStrategy {
// MARK: Lifecycle
init(update: @escaping (Value, Value) -> Value) {
self.update = update
}
// MARK: Public
/// A closure used to update an `EpoxyModelProperty` from an old value to a new value.
var update: (_ old: Value, _ new: Value) -> Value
}
}
// MARK: Defaults
extension EpoxyModelProperty.UpdateStrategy {
/// Replaces the old value with the new value when an update occurs.
static var replace: Self {
.init { _, new in new }
}
/// Chains the new closure value onto the old closure value, returning a new closure that first
/// calls the old closure and then subsequently calls the new closure.
static func chain() -> EpoxyModelProperty<(() -> Void)?>.UpdateStrategy {
.init { old, new in
guard let new else { return old }
guard let old else { return new }
return {
old()
new()
}
}
}
/// Chains the new closure value onto the old closure value, returning a new closure that first
/// calls the old closure and then subsequently calls the new closure.
static func chain<A>() -> EpoxyModelProperty<((A) -> Void)?>.UpdateStrategy {
.init { old, new in
guard let new else { return old }
guard let old else { return new }
return { a in
old(a)
new(a)
}
}
}
/// Chains the new closure value onto the old closure value, returning a new closure that first
/// calls the old closure and then subsequently calls the new closure.
static func chain<A, B>() -> EpoxyModelProperty<((A, B) -> Void)?>.UpdateStrategy {
.init { old, new in
guard let new else { return old }
guard let old else { return new }
return { a, b in
old(a, b)
new(a, b)
}
}
}
/// Chains the new closure value onto the old closure value, returning a new closure that first
/// calls the old closure and then subsequently calls the new closure.
static func chain<A, B, C>() -> EpoxyModelProperty<((A, B, C) -> Void)?>.UpdateStrategy {
.init { old, new in
guard let new else { return old }
guard let old else { return new }
return { a, b, c in
old(a, b, c)
new(a, b, c)
}
}
}
/// Chains the new closure value onto the old closure value, returning a new closure that first
/// calls the old closure and then subsequently calls the new closure.
static func chain<A, B, C, D>() -> EpoxyModelProperty<((A, B, C, D) -> Void)?>.UpdateStrategy {
.init { old, new in
guard let new else { return old }
guard let old else { return new }
return { a, b, c, d in
old(a, b, c, d)
new(a, b, c, d)
}
}
}
// Add more arities as needed
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/EpoxyModelProperty.swift
|
Swift
|
unknown
| 4,880
|
// Created by eric_horacek on 11/18/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - EpoxyModelStorage
/// The underlying storage for an `EpoxyModeled` model that is capable of storing any
/// `EpoxyModelProperty`.
///
/// Supports being extended with additional storage capabilities in other modules and conditionally
/// based on the provider capabilities that the content containing this storage conforms to.
struct EpoxyModelStorage {
// MARK: Lifecycle
init() { }
// MARK: Internal
/// Stores or retrieves the value of the specified property.
subscript<Property>(property: EpoxyModelProperty<Property>) -> Property {
get {
guard let propertyStorage = storage[property.keyPath] else {
return property.defaultValue()
}
// This cast will never fail as the storage is only settable via this subscript and the
// `KeyPath` key is unique for any provider and value type pair.
// swiftlint:disable:next force_cast
return propertyStorage.value as! Property
}
set {
// We first update the value without using the `updateStrategy` since the likely scenario
// is that there won't be a collision that requires the `updateStrategy`, and we'll be able to
// return without incurring the cost of another write.
let propertyStorage = PropertyStorage(value: newValue, property: property)
guard var replaced = storage.updateValue(propertyStorage, forKey: property.keyPath) else {
return
}
// This cast will never fail as the storage is only settable via this subscript and the
// `KeyPath` key is unique for any provider and value type pair.
// swiftlint:disable:next force_cast
replaced.value = property.updateStrategy.update(replaced.value as! Property, newValue)
storage[property.keyPath] = replaced
}
}
/// Merges the given storage into this storage.
///
/// In the case of a collision, the `UpdateStrategy` of the property is used to determine the
/// resulting value in this storage.
mutating func merge(_ other: Self) {
for (key, otherValue) in other.storage {
// We first update the value without using the `updateStrategy` since the likely scenario
// is that there won't be a collision that requires the `updateStrategy`, and we'll be able to
// return without incurring the cost of another write.
guard var replaced = storage.updateValue(otherValue, forKey: key) else {
continue
}
replaced.value = replaced.property.update(old: replaced.value, new: otherValue.value)
storage[key] = replaced
}
}
// MARK: Private
/// The underlying storage for the properties, with a key of the `EpoxyModelProperty.keyPath` and
/// a value of the property's `PropertyStorage`.
///
/// Does not include default values.
private var storage = [AnyKeyPath: PropertyStorage]()
}
// MARK: - PropertyStorage
/// A value stored within an `EpoxyModelStorage`.
private struct PropertyStorage {
/// The type-erased value of the `EpoxyModelProperty`.
var value: Any
/// The property's corresponding `EpoxyModelProperty`, erased to an `AnyEpoxyModelProperty`.
var property: AnyEpoxyModelProperty
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/EpoxyModelStorage.swift
|
Swift
|
unknown
| 3,241
|
// Created by eric_horacek on 11/18/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - EpoxyModeled
/// A protocol that all concrete Epoxy declarative UI model types conform to.
///
/// This protocol should be conditionally extended to fulfill provider protocols and with chainable
/// setters for those providers that concrete model types can receive by declaring conformance to
/// provider protocols.
protocol EpoxyModeled {
/// The underlying storage of this model that stores the current property values.
var storage: EpoxyModelStorage { get set }
}
// MARK: Extensions
extension EpoxyModeled {
/// Stores or retrieves a value of the specified property in `storage`.
///
/// If the value was set previously for the given `property`, the conflict is resolved using the
/// `EpoxyModelProperty.UpdateStrategy` of the `property`.
subscript<Property>(property: EpoxyModelProperty<Property>) -> Property {
get { storage[property] }
set { storage[property] = newValue }
}
/// Returns a copy of this model with the given property updated to the provided value.
///
/// Typically called from within the context of a chainable setter to allow fluent setting of a
/// property, e.g.:
///
/// ````
/// internal func title(_ value: String?) -> Self {
/// copy(updating: titleProperty, to: value)
/// }
/// ````
///
/// If a `value` was set previously for the given `property`, the conflict is resolved using the
/// `EpoxyModelProperty.UpdateStrategy` of the `property`.
func copy<Value>(updating property: EpoxyModelProperty<Value>, to value: Value) -> Self {
var copy = self
copy.storage[property] = value
return copy
}
/// Returns a copy of this model produced by merging the given `other` model's storage into this
/// model's storage.
func merging(_ other: EpoxyModeled) -> Self {
var copy = self
copy.storage.merge(other.storage)
return copy
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/EpoxyModeled.swift
|
Swift
|
unknown
| 1,957
|
// Created by eric_horacek on 12/1/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - AnyEpoxyModelProperty
/// An erased `EpoxyModelProperty`, with the ability to call the `UpdateStrategy` even when the type
/// has been erased.
protocol AnyEpoxyModelProperty {
/// Returns the updated property from updating from given old to new property.
func update(old: Any, new: Any) -> Any
}
// MARK: - EpoxyModelProperty + AnyEpoxyModelProperty
extension EpoxyModelProperty: AnyEpoxyModelProperty {
func update(old: Any, new: Any) -> Any {
guard let typedOld = old as? Value else {
EpoxyLogger.shared.assertionFailure(
"Expected old to be of type \(Value.self), instead found \(old). This is programmer error.")
return defaultValue()
}
guard let typedNew = new as? Value else {
EpoxyLogger.shared.assertionFailure(
"Expected new to be of type \(Value.self), instead found \(old). This is programmer error.")
return defaultValue()
}
return updateStrategy.update(typedOld, typedNew)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Internal/AnyEpoxyModelProperty.swift
|
Swift
|
unknown
| 1,067
|
// Created by Cal Stephens on 10/15/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
// MARK: - ClassReference
/// A `Hashable` value wrapper around an `AnyClass` value
/// - Unlike `ObjectIdentifier(class)`, `ClassReference(class)`
/// preserves the `AnyClass` value and is more human-readable.
struct ClassReference {
init(_ class: AnyClass) {
self.class = `class`
}
let `class`: AnyClass
}
// MARK: Equatable
extension ClassReference: Equatable {
static func ==(_ lhs: Self, _ rhs: Self) -> Bool {
ObjectIdentifier(lhs.class) == ObjectIdentifier(rhs.class)
}
}
// MARK: Hashable
extension ClassReference: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(`class`))
}
}
// MARK: CustomStringConvertible
extension ClassReference: CustomStringConvertible {
var description: String {
String(describing: `class`)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Internal/ClassReference.swift
|
Swift
|
unknown
| 903
|
// Created by eric_horacek on 12/16/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
/// The capability of providing a flag indicating whether an operation should be animated.
///
/// Typically conformed to by the `CallbackContext` of a `CallbackContextEpoxyModeled`.
protocol AnimatedProviding {
/// Whether this operation should be animated.
var animated: Bool { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/AnimatedProviding.swift
|
Swift
|
unknown
| 387
|
// Created by eric_horacek on 12/1/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - DataIDProviding
/// The capability of providing a stable data identifier with an erased type.
///
/// While it has similar semantics, this type cannot inherit from `Identifiable` as this would give
/// it an associated type, which would cause the `keyPath` used in its `EpoxyModelProperty` to not
/// be stable across types if written as `\Self.dataID` since the `KeyPath` `Root` would be
/// different for each type.
///
/// - SeeAlso: `Identifiable`.
protocol DataIDProviding {
/// A stable identifier that uniquely identifies this instance, with its typed erased.
///
/// Defaults to `DefaultDataID.noneProvided` if no data ID is provided.
var dataID: AnyHashable { get }
}
// MARK: - EpoxyModeled
extension EpoxyModeled where Self: DataIDProviding {
// MARK: Internal
/// A stable identifier that uniquely identifies this model, with its typed erased.
var dataID: AnyHashable {
get { self[dataIDProperty] }
set { self[dataIDProperty] = newValue }
}
/// Returns a copy of this model with the ID replaced with the provided ID.
func dataID(_ value: AnyHashable) -> Self {
copy(updating: dataIDProperty, to: value)
}
// MARK: Private
private var dataIDProperty: EpoxyModelProperty<AnyHashable> {
EpoxyModelProperty(
keyPath: \DataIDProviding.dataID,
defaultValue: DefaultDataID.noneProvided,
updateStrategy: .replace)
}
}
// MARK: - DefaultDataID
/// The default data ID when none is provided.
enum DefaultDataID: Hashable, CustomDebugStringConvertible {
case noneProvided
var debugDescription: String {
"DefaultDataID.noneProvided"
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/DataIDProviding.swift
|
Swift
|
unknown
| 1,725
|
// Created by eric_horacek on 1/6/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
// MARK: - DidDisplayProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a `didDisplay`
/// closure property.
///
/// - SeeAlso: `WillDisplayProviding`
/// - SeeAlso: `DidEndDisplayingProviding`
protocol DidDisplayProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: DidDisplayProviding {
// MARK: Internal
/// A closure that's called after a view has been added to the view hierarchy following any
/// appearance animations.
typealias DidDisplay = (_ context: CallbackContext) -> Void
/// A closure that's called after the view has been added to the view hierarchy following any
/// appearance animations.
var didDisplay: DidDisplay? {
get { self[didDisplayProperty] }
set { self[didDisplayProperty] = newValue }
}
/// Returns a copy of this model with the given did display closure called after the current did
/// display closure of this model, if there is one.
func didDisplay(_ value: DidDisplay?) -> Self {
copy(updating: didDisplayProperty, to: value)
}
// MARK: Private
private var didDisplayProperty: EpoxyModelProperty<DidDisplay?> {
.init(keyPath: \Self.didDisplay, defaultValue: nil, updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/DidDisplayProviding.swift
|
Swift
|
unknown
| 1,363
|
// Created by eric_horacek on 12/15/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - DidEndDisplayingProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a
/// `didEndDisplaying` closure property.
protocol DidEndDisplayingProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: DidEndDisplayingProviding {
// MARK: Internal
/// A closure that's called when a view is no longer displayed following any disappearance
/// animations and when it has been removed from the view hierarchy.
typealias DidEndDisplaying = (_ context: CallbackContext) -> Void
/// A closure that's called when the view is no longer displayed following any disappearance
/// animations and when it has been removed from the view hierarchy.
var didEndDisplaying: DidEndDisplaying? {
get { self[didEndDisplayingProperty] }
set { self[didEndDisplayingProperty] = newValue }
}
/// Returns a copy of this model with the given did end displaying closure called after the
/// current did end displaying closure of this model, if there is one.
func didEndDisplaying(_ value: DidEndDisplaying?) -> Self {
copy(updating: didEndDisplayingProperty, to: value)
}
// MARK: Private
private var didEndDisplayingProperty: EpoxyModelProperty<DidEndDisplaying?> {
.init(
keyPath: \Self.didEndDisplaying,
defaultValue: nil,
updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/DidEndDisplayingProviding.swift
|
Swift
|
unknown
| 1,485
|
// Created by eric_horacek on 12/2/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - DidSelectProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a `didSelect`
/// closure property.
protocol DidSelectProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: DidSelectProviding {
// MARK: Internal
/// A closure that's called to handle this model's view being selected.
typealias DidSelect = (CallbackContext) -> Void
/// A closure that's called to handle this model's view being selected.
var didSelect: DidSelect? {
get { self[didSelectProperty] }
set { self[didSelectProperty] = newValue }
}
/// Returns a copy of this model with the given did select closure called after the current did
/// select closure of this model, if there is one.
func didSelect(_ value: DidSelect?) -> Self {
copy(updating: didSelectProperty, to: value)
}
// MARK: Private
private var didSelectProperty: EpoxyModelProperty<DidSelect?> {
.init(keyPath: \Self.didSelect, defaultValue: nil, updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/DidSelectProviding.swift
|
Swift
|
unknown
| 1,151
|
// Created by eric_horacek on 12/2/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - ErasedContentProviding
/// The capability of providing an type-erased `Equatable` content instance.
protocol ErasedContentProviding {
/// The type-erased content instance of this model, else `nil` if there is no content.
///
/// If there was an `AnyEquatable` type, we could store this property using it. Instead we need
/// need to store `isErasedContentEqual` to determine equality.
var erasedContent: Any? { get }
/// A closure that can be called to determine whether the given `model`'s `erasedContent` is equal
/// to this model's `erasedContent`, else `nil` if there is no content or the content is always
/// equal.
var isErasedContentEqual: ((Self) -> Bool)? { get }
}
// MARK: - EpoxyModeled
extension EpoxyModeled where Self: ErasedContentProviding {
// MARK: Internal
/// The type-erased content instance of this model, else `nil` if there is no content.
var erasedContent: Any? {
get { self[contentProperty] }
set { self[contentProperty] = newValue }
}
/// A closure that can be called to determine whether the given `model`'s `erasedContent` is equal
/// to this model's `erasedContent`, else `nil` if there is no content or the content is always
/// equal.
var isErasedContentEqual: ((Self) -> Bool)? {
get { self[isContentEqualProperty] }
set { self[isContentEqualProperty] = newValue }
}
// MARK: Private
private var contentProperty: EpoxyModelProperty<Any?> {
.init(keyPath: \Self.erasedContent, defaultValue: nil, updateStrategy: .replace)
}
private var isContentEqualProperty: EpoxyModelProperty<((Self) -> Bool)?> {
.init(keyPath: \Self.isErasedContentEqual, defaultValue: nil, updateStrategy: .replace)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/ErasedContentProviding.swift
|
Swift
|
unknown
| 1,813
|
// Created by eric_horacek on 12/1/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - MakeViewProviding
/// The capability of constructing a `UIView`.
protocol MakeViewProviding {
/// The view constructed when the `MakeView` closure is called.
associatedtype View: ViewType
/// A closure that's called to construct an instance of `View`.
typealias MakeView = () -> View
/// A closure that's called to construct an instance of `View`.
var makeView: MakeView { get }
}
// MARK: - ViewEpoxyModeled
extension ViewEpoxyModeled where Self: MakeViewProviding {
// MARK: Internal
/// A closure that's called to construct an instance of `View` represented by this model.
var makeView: MakeView {
get { self[makeViewProperty] }
set { self[makeViewProperty] = newValue }
}
/// Replaces the default closure to construct the view with the given closure.
func makeView(_ value: @escaping MakeView) -> Self {
copy(updating: makeViewProperty, to: value)
}
// MARK: Private
private var makeViewProperty: EpoxyModelProperty<MakeView> {
// If you're getting a `EXC_BAD_INSTRUCTION` crash with this property in your stack trace, you
// probably either:
// - Conformed a view to `EpoxyableView` / `StyledView` with a custom initializer that
// takes parameters, or:
// - Used the `EpoxyModeled.init(dataID:)` initializer on a view has required initializer
// parameters.
// If you have parameters to view initialization, they should either be passed to `init(style:)`
// or you should provide a `makeView` closure when constructing your view's corresponding model,
// e.g:
// ```
// MyView.itemModel(…)
// .makeView { MyView(customParameter: …) }
// .styleID(…)
// ```
// Note that with the above approach that you must supply an `styleID` with the same identity as
// your view parameters to ensure that views with different parameters are not reused in place
// of one another.
.init(
keyPath: \Self.makeView,
defaultValue: View.init,
updateStrategy: .replace)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/MakeViewProviding.swift
|
Swift
|
unknown
| 2,121
|
// Created by eric_horacek on 12/2/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - SetBehaviorsProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a `setBehaviors`
/// closure property.
protocol SetBehaviorsProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: SetBehaviorsProviding {
// MARK: Internal
/// A closure that's called to set the content on this model's view with behaviors (e.g. tap handler
/// closures) whenever this model is updated.
typealias SetBehaviors = (CallbackContext) -> Void
/// A closure that's called to set the content on this model's view with behaviors (e.g. tap handler
/// closures) whenever this model is updated.
var setBehaviors: SetBehaviors? {
get { self[setBehaviorsProperty] }
set { self[setBehaviorsProperty] = newValue }
}
/// Returns a copy of this model with the set behaviors closure called after the current set
/// behaviors closure of this model, if there is one.
func setBehaviors(_ value: SetBehaviors?) -> Self {
copy(updating: setBehaviorsProperty, to: value)
}
// MARK: Private
private var setBehaviorsProperty: EpoxyModelProperty<SetBehaviors?> {
.init(keyPath: \Self.setBehaviors, defaultValue: nil, updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/SetBehaviorsProviding.swift
|
Swift
|
unknown
| 1,350
|
// Created by eric_horacek on 12/1/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - SetContentProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a `setContent`
/// closure property.
protocol SetContentProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: SetContentProviding {
// MARK: Internal
/// A closure that's called to set the content on this model's view when it is first created and
/// subsequently when the content changes.
typealias SetContent = (CallbackContext) -> Void
/// A closure that's called to set the content on this model's view when it is first created and
/// subsequently when the content changes.
var setContent: SetContent? {
get { self[setContentProperty] }
set { self[setContentProperty] = newValue }
}
/// Returns a copy of this model with the given setContent view closure called after the current
/// setContent view closure of this model, if there is one.
func setContent(_ value: SetContent?) -> Self {
copy(updating: setContentProperty, to: value)
}
// MARK: Private
private var setContentProperty: EpoxyModelProperty<SetContent?> {
.init(keyPath: \Self.setContent, defaultValue: nil, updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/SetContentProviding.swift
|
Swift
|
unknown
| 1,316
|
// Created by eric_horacek on 12/1/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - StyleIDProviding
protocol StyleIDProviding {
/// An optional ID for a style type to use for reuse of a view.
///
/// Use this to differentiate between different styling configurations.
var styleID: AnyHashable? { get }
}
// MARK: - EpoxyModeled
extension EpoxyModeled where Self: StyleIDProviding {
// MARK: Internal
var styleID: AnyHashable? {
get { self[styleIDProperty] }
set { self[styleIDProperty] = newValue }
}
/// Returns a copy of this model with the `styleID` replaced with the provided `value`.
func styleID(_ value: AnyHashable?) -> Self {
copy(updating: styleIDProperty, to: value)
}
// MARK: Private
private var styleIDProperty: EpoxyModelProperty<AnyHashable?> {
.init(
keyPath: \StyleIDProviding.styleID,
defaultValue: nil,
updateStrategy: .replace)
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/StyleIDProviding.swift
|
Swift
|
unknown
| 943
|
// Created by eric_horacek on 12/16/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
#if !os(macOS)
import UIKit
/// The capability of providing a `UITraitCollection` instance.
///
/// Typically conformed to by the `CallbackContext` of a `CallbackContextEpoxyModeled`.
protocol TraitCollectionProviding {
/// The `UITraitCollection` instance provided by this type.
var traitCollection: UITraitCollection { get }
}
#endif
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/TraitCollectionProviding.swift
|
Swift
|
unknown
| 436
|
// Created by Bryan Keller on 12/17/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - ViewDifferentiatorProviding
/// The capability of providing a view differentiator that facilitates generating collection view
/// cell reuse identifiers.
protocol ViewDifferentiatorProviding {
/// The view differentiator for the item model.
var viewDifferentiator: ViewDifferentiator { get }
}
// MARK: - ViewDifferentiator
/// Facilitates differentiating between two models' views, based on their view type, optional style
/// identifier, and optional element kind for supplementary view models. If two models have the same
/// view differentiator, then they're compatible with one another for element reuse. If two models
/// have different view differentiators, then they're incompatible with one another for element
/// reuse.
struct ViewDifferentiator: Hashable {
// MARK: Lifecycle
init(viewType: AnyClass, styleID: AnyHashable?) {
viewTypeDescription = "\(type(of: viewType.self))"
self.styleID = styleID
}
// MARK: Public
var viewTypeDescription: String
var styleID: AnyHashable?
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/ViewDifferentiatorProviding.swift
|
Swift
|
unknown
| 1,128
|
// Created by eric_horacek on 12/16/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
/// The capability of providing an `View` instance
///
/// Typically conformed to by the `CallbackContext` of a `CallbackContextEpoxyModeled`.
protocol ViewProviding {
/// The `UIView` view of this type.
associatedtype View: ViewType
/// The `UIView` view instance provided by this type.
var view: View { get }
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/ViewProviding.swift
|
Swift
|
unknown
| 417
|
// Created by eric_horacek on 12/15/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
// MARK: - WillDisplayProviding
/// A sentinel protocol for enabling an `CallbackContextEpoxyModeled` to provide a `willDisplay`
/// closure property.
///
/// - SeeAlso: `DidDisplayProviding`
/// - SeeAlso: `DidEndDisplayingProviding`
protocol WillDisplayProviding { }
// MARK: - CallbackContextEpoxyModeled
extension CallbackContextEpoxyModeled where Self: WillDisplayProviding {
// MARK: Internal
/// A closure that's called when a view is about to be displayed, before it has been added to the
/// view hierarcy.
typealias WillDisplay = (_ context: CallbackContext) -> Void
/// A closure that's called when the view is about to be displayed, before it has been added to
/// the view hierarcy.
var willDisplay: WillDisplay? {
get { self[willDisplayProperty] }
set { self[willDisplayProperty] = newValue }
}
/// Returns a copy of this model with the given will display closure called after the current will
/// display closure of this model, if there is one.
func willDisplay(_ value: WillDisplay?) -> Self {
copy(updating: willDisplayProperty, to: value)
}
// MARK: Private
private var willDisplayProperty: EpoxyModelProperty<WillDisplay?> {
.init(keyPath: \Self.willDisplay, defaultValue: nil, updateStrategy: .chain())
}
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/Providers/WillDisplayProviding.swift
|
Swift
|
unknown
| 1,377
|
// Created by eric_horacek on 12/4/20.
// Copyright © 2020 Airbnb Inc. All rights reserved.
/// An Epoxy model with an associated `UIView` type.
protocol ViewEpoxyModeled: EpoxyModeled {
/// The view type associated with this model.
///
/// An instance of this view is typically configured by this model.
associatedtype View: ViewType
}
|
2201_75827989/zhi_shi_ku
|
uni_modules/uts-animation-view/utssdk/app-ios/lottie-ios/Private/EmbeddedLibraries/EpoxyCore/Model/ViewEpoxyModeled.swift
|
Swift
|
unknown
| 347
|