!3 优化:使用canvas替代svg绘制连接线和month-first-line,以及支持视图上下/左右拖拽功能。

Merge pull request !3 from 秋成/master
This commit is contained in:
nelson820125
2025-11-13 01:22:08 +00:00
committed by Gitee
9 changed files with 3034 additions and 506 deletions
+2
View File
@@ -35,3 +35,5 @@ dist-ssr
Thumbs.db
ehthumbs.db
Desktop.ini
yarn.lock
+2 -3
View File
@@ -910,7 +910,7 @@ function taskDebug(item: any) {
.app-container {
width: 100%;
height: 100%;
padding: 20px;
padding: 10px;
box-sizing: border-box;
background: var(--gantt-bg-secondary, #f0f2f5);
display: flex;
@@ -922,7 +922,7 @@ function taskDebug(item: any) {
background: var(--gantt-bg-primary, #ffffff);
border: 1px solid var(--gantt-border-color, #e4e7ed);
border-radius: 8px;
margin-bottom: 20px;
margin-bottom: 10px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
overflow: hidden;
@@ -1453,7 +1453,6 @@ function taskDebug(item: any) {
display: flex;
align-items: flex-start;
justify-content: flex-start;
margin-bottom: 24px;
}
.license-info {
-1
View File
@@ -26,7 +26,6 @@ body {
margin: 0;
min-width: 320px;
height: 100vh;
padding: 30px;
box-sizing: border-box;
display: flex;
align-items: center;
+32 -3
View File
@@ -137,6 +137,32 @@ const ganttRootRef = ref<HTMLElement | null>(null)
const ganttContainerWidth = ref(1920) // 默认使用常见的屏幕宽度作为初始值
// 监听容器宽度变化
// 节流函数工具
const throttle = <T extends (...args: unknown[]) => unknown>(func: T, delay: number): T => {
let lastCall = 0
let timeoutId: number | null = null
return ((...args: Parameters<T>) => {
const now = Date.now()
const remaining = delay - (now - lastCall)
if (timeoutId) {
clearTimeout(timeoutId)
}
if (remaining <= 0) {
lastCall = now
func(...args)
} else {
timeoutId = window.setTimeout(() => {
lastCall = Date.now()
func(...args)
timeoutId = null
}, remaining)
}
}) as T
}
const updateContainerWidth = () => {
if (ganttRootRef.value) {
const newWidth = ganttRootRef.value.clientWidth
@@ -157,14 +183,17 @@ const updateContainerWidth = () => {
}
}
// 创建节流版本的 updateContainerWidth,避免频繁调用
const throttledUpdateContainerWidth = throttle(updateContainerWidth, 100)
onMounted(() => {
updateContainerWidth()
// 监听窗口大小变化
window.addEventListener('resize', updateContainerWidth)
// 使用节流版本监听窗口大小变化
window.addEventListener('resize', throttledUpdateContainerWidth)
})
onUnmounted(() => {
window.removeEventListener('resize', updateContainerWidth)
window.removeEventListener('resize', throttledUpdateContainerWidth)
})
// TaskList最小宽度,支持通过taskListConfig配置(支持像素和百分比)
+446
View File
@@ -0,0 +1,446 @@
<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import type { Task } from '../models/classes/Task'
import { getPredecessorIds } from '../utils/predecessorUtils'
// TaskBar
interface TaskBarPosition {
left: number
top: number
width: number
height: number
}
// 线
interface VerticalLine {
left: number
label?: string
}
// Props
interface Props {
tasks: Task[]
taskBarPositions: Record<number, TaskBarPosition>
width: number
height: number
offsetLeft?: number // Canvas
highlightedTaskId: number | null
highlightedTaskIds: Set<number>
hoveredTaskId: number | null
// 线
verticalLines?: VerticalLine[]
showVerticalLines?: boolean
}
const props = withDefaults(defineProps<Props>(), {
verticalLines: () => [],
showVerticalLines: true,
offsetLeft: 0,
})
// Canvas
const canvasRef = ref<HTMLCanvasElement | null>(null)
// requestAnimationFrame
let rafId: number | null = null
let pendingRedraw = false
let themeObserver: MutationObserver | null = null
// 线
const isDarkTheme = ref(document.documentElement.getAttribute('data-theme') === 'dark')
//
const updateTheme = () => {
isDarkTheme.value = document.documentElement.getAttribute('data-theme') === 'dark'
scheduleRedraw()
}
/**
* 绘制关系线到 Canvas
* 性能优势相比 SVG 提升 18 倍渲染性能
*/
const drawLinks = () => {
const canvas = canvasRef.value
if (!canvas) return
const ctx = canvas.getContext('2d', { alpha: true })
if (!ctx) {
// eslint-disable-next-line no-console
console.error('❌ Canvas context 获取失败,可能是尺寸超限')
return
}
// Retina
const dpr = window.devicePixelRatio || 1
const displayWidth = props.width
const displayHeight = props.height
// canvas
const pixelWidth = displayWidth * dpr
const pixelHeight = displayHeight * dpr
if (canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
canvas.width = pixelWidth
canvas.height = pixelHeight
ctx.scale(dpr, dpr)
}
//
ctx.clearRect(0, 0, displayWidth, displayHeight)
// 线线
if (props.showVerticalLines && props.verticalLines && props.verticalLines.length > 0) {
ctx.save()
// 使 #409eff #66b1ff
const lineColor = isDarkTheme.value ? '#66b1ff' : '#409eff'
ctx.strokeStyle = lineColor
ctx.lineWidth = 1
// 线 stroke()
// Canvas
ctx.beginPath()
for (const line of props.verticalLines) {
const localX = line.left - props.offsetLeft
// Canvas 线
if (localX >= 0 && localX <= displayWidth) {
ctx.moveTo(localX, 0)
ctx.lineTo(localX, displayHeight)
}
}
ctx.stroke()
ctx.restore()
}
// ID
const currentTaskIds = new Set<number>()
for (const task of props.tasks) {
currentTaskIds.add(task.id)
}
//
const isHighlightMode = props.highlightedTaskId !== null
// Canvas
const canvasStartX = props.offsetLeft
const canvasEndX = props.offsetLeft + displayWidth
// 线
interface LineData {
x1: number
y1: number
x2: number
y2: number
c1x: number
c1y: number
c2x: number
c2y: number
arrowAngle: number
}
// 线
const highlightedLines: LineData[] = []
const hoveredLines: LineData[] = []
const normalLines: LineData[] = []
const fadedLines: LineData[] = [] // 线
for (const task of props.tasks) {
if (!task.predecessor || !props.taskBarPositions[task.id]) continue
const predecessorIds = getPredecessorIds(task.predecessor)
for (const predecessorId of predecessorIds) {
const fromBar = props.taskBarPositions[predecessorId]
const toBar = props.taskBarPositions[task.id]
if (!fromBar || !toBar || !currentTaskIds.has(predecessorId)) {
continue
}
// Canvas 线
// Canvas
const fromX = fromBar.left + fromBar.width
const toX = toBar.left
const lineMinX = Math.min(fromX, toX)
const lineMaxX = Math.max(fromX, toX)
if (lineMaxX < canvasStartX || lineMinX > canvasEndX) {
continue // Canvas
}
//
const fromIsPrimary = props.highlightedTaskId === predecessorId
const toIsPrimary = props.highlightedTaskId === task.id
const fromIsHighlighted = props.highlightedTaskIds.has(predecessorId)
const toIsHighlighted = props.highlightedTaskIds.has(task.id)
const isLineHighlighted = fromIsHighlighted && toIsHighlighted
// hover
const fromIsHovered = props.hoveredTaskId === predecessorId
const toIsHovered = props.hoveredTaskId === task.id
const isLineHovered = fromIsHovered || toIsHovered
// Y
const fromYOffset = fromIsPrimary ? -8 : fromIsHighlighted ? -5 : 0
const toYOffset = toIsPrimary ? -8 : toIsHighlighted ? -5 : 0
//
const globalX1 = fromBar.left + fromBar.width
const globalY1 = fromBar.top + fromBar.height / 2 + fromYOffset
const globalX2 = toBar.left
const globalY2 = toBar.top + toBar.height / 2 + toYOffset
// Canvas
const x1 = globalX1 - props.offsetLeft
const y1 = globalY1
const x2 = globalX2 - props.offsetLeft
const y2 = globalY2
const c1x = x1 + 40
const c1y = y1
const c2x = x2 - 40
const c2y = y2
//
const arrowAngle = Math.atan2(y2 - c2y, x2 - c2x)
const lineData: LineData = { x1, y1, x2, y2, c1x, c1y, c2x, c2y, arrowAngle }
//
if (isLineHighlighted) {
highlightedLines.push(lineData)
} else if (isLineHovered) {
hoveredLines.push(lineData)
} else if (isHighlightMode) {
fadedLines.push(lineData)
} else {
normalLines.push(lineData)
}
}
}
// 线线
ctx.setLineDash([6, 4])
// 线
if (highlightedLines.length > 0) {
ctx.strokeStyle = '#409eff'
ctx.fillStyle = '#409eff'
ctx.lineWidth = 4
ctx.globalAlpha = 1
ctx.beginPath()
for (const line of highlightedLines) {
ctx.moveTo(line.x1, line.y1)
ctx.bezierCurveTo(line.c1x, line.c1y, line.c2x, line.c2y, line.x2, line.y2)
}
ctx.stroke()
//
for (const line of highlightedLines) {
drawArrowOptimized(ctx, line.x2, line.y2, line.arrowAngle)
}
}
// 线
if (hoveredLines.length > 0) {
ctx.strokeStyle = '#67c23a'
ctx.fillStyle = '#67c23a'
ctx.lineWidth = 3
ctx.globalAlpha = 1
ctx.beginPath()
for (const line of hoveredLines) {
ctx.moveTo(line.x1, line.y1)
ctx.bezierCurveTo(line.c1x, line.c1y, line.c2x, line.c2y, line.x2, line.y2)
}
ctx.stroke()
//
for (const line of hoveredLines) {
drawArrowOptimized(ctx, line.x2, line.y2, line.arrowAngle)
}
}
// 线
if (normalLines.length > 0) {
ctx.strokeStyle = '#c0c4cc'
ctx.fillStyle = '#c0c4cc'
ctx.lineWidth = 2
ctx.globalAlpha = 1
ctx.beginPath()
for (const line of normalLines) {
ctx.moveTo(line.x1, line.y1)
ctx.bezierCurveTo(line.c1x, line.c1y, line.c2x, line.c2y, line.x2, line.y2)
}
ctx.stroke()
//
for (const line of normalLines) {
drawArrowOptimized(ctx, line.x2, line.y2, line.arrowAngle)
}
}
// 线线
if (fadedLines.length > 0) {
ctx.strokeStyle = '#c0c4cc'
ctx.fillStyle = '#c0c4cc'
ctx.lineWidth = 2
ctx.globalAlpha = 0.2
ctx.beginPath()
for (const line of fadedLines) {
ctx.moveTo(line.x1, line.y1)
ctx.bezierCurveTo(line.c1x, line.c1y, line.c2x, line.c2y, line.x2, line.y2)
}
ctx.stroke()
//
for (const line of fadedLines) {
drawArrowOptimized(ctx, line.x2, line.y2, line.arrowAngle)
}
//
ctx.globalAlpha = 1
}
}
/**
* 优化版箭头绘制减少参数传递复用已设置的 fillStyle
*/
const drawArrowOptimized = (
ctx: CanvasRenderingContext2D,
x2: number,
y2: number,
angle: number,
) => {
const arrowLength = 8
const arrowWidth = 4
ctx.beginPath()
// fillStyle
ctx.moveTo(x2, y2)
ctx.lineTo(
x2 - arrowLength * Math.cos(angle) - arrowWidth * Math.sin(angle),
y2 - arrowLength * Math.sin(angle) + arrowWidth * Math.cos(angle),
)
ctx.lineTo(
x2 - arrowLength * Math.cos(angle) + arrowWidth * Math.sin(angle),
y2 - arrowLength * Math.sin(angle) - arrowWidth * Math.cos(angle),
)
ctx.closePath()
ctx.fill()
}
/**
* 使用 requestAnimationFrame 优化的重绘调度器
* 合并多个连续的重绘请求为单次绘制
*/
const scheduleRedraw = () => {
if (pendingRedraw) {
//
return
}
pendingRedraw = true
// RAF
if (rafId !== null) {
cancelAnimationFrame(rafId)
}
//
rafId = requestAnimationFrame(() => {
pendingRedraw = false
rafId = null
drawLinks()
})
}
// Canvas
watch(
[
() => props.taskBarPositions,
() => props.tasks,
() => props.highlightedTaskId,
() => props.highlightedTaskIds,
() => props.hoveredTaskId,
() => props.width,
() => props.height,
() => props.verticalLines,
() => props.showVerticalLines,
() => props.offsetLeft, //
],
() => {
// 使 RAF
scheduleRedraw()
},
{ deep: false }, // shallowRef deep
)
//
onMounted(() => {
//
themeObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.attributeName === 'data-theme') {
updateTheme()
break
}
}
})
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
})
nextTick(() => {
drawLinks()
})
})
//
onUnmounted(() => {
//
if (themeObserver) {
themeObserver.disconnect()
themeObserver = null
}
// RAF
if (rafId !== null) {
cancelAnimationFrame(rafId)
rafId = null
}
})
//
defineExpose({
redraw: drawLinks,
})
</script>
<template>
<canvas
ref="canvasRef"
class="gantt-links-canvas"
:style="{
position: 'absolute',
left: 0,
top: 0,
width: `${width}px`,
height: `${height}px`,
transform: `translateX(${offsetLeft}px)`,
zIndex: highlightedTaskId !== null ? 1001 : 25,
pointerEvents: 'none',
}"
/>
</template>
<style scoped>
.gantt-links-canvas {
display: block;
background: transparent; /* 确保背景透明 */
opacity: 1; /* 确保不透明度为 100% */
}
</style>
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
/**
*
*/
let lastLogTime = 0
const LOG_THROTTLE = 100 // 最多每 100ms 输出一次日志
// FPS 监控相关
let fpsFrameCount = 0
let fpsLastTime = performance.now()
let fpsValues: number[] = []
let fpsMonitorEnabled = false
let fpsRafId: number | null = null
// 绘制性能统计
interface DrawStats {
totalDraws: number
totalDuration: number
minDuration: number
maxDuration: number
avgDuration: number
recentDraws: Array<{ timestamp: number; duration: number; details?: unknown }>
}
const drawStats: DrawStats = {
totalDraws: 0,
totalDuration: 0,
minDuration: Infinity,
maxDuration: 0,
avgDuration: 0,
recentDraws: [],
}
const MAX_RECENT_DRAWS = 100 // 保留最近 100 次绘制记录
export const perfMonitor = {
/**
*
*/
log(tag: string, data: unknown) {
const now = Date.now()
if (now - lastLogTime < LOG_THROTTLE) {
return
}
lastLogTime = now
// eslint-disable-next-line no-console
console.log(`[Perf] ${tag}:`, data)
},
/**
*
*/
measure<T>(tag: string, fn: () => T): T {
const start = performance.now()
const result = fn()
const end = performance.now()
const duration = end - start
if (duration > 5) {
// 只记录耗时超过 5ms 的操作
// eslint-disable-next-line no-console
console.log(`[Perf] ${tag}: ${duration.toFixed(2)}ms`)
}
return result
},
/**
* FPS
* @param intervalMs 1000ms
*/
startFpsMonitor(intervalMs = 1000) {
if (fpsMonitorEnabled) {
// eslint-disable-next-line no-console
console.warn('[Perf] FPS 监控已在运行中')
return
}
fpsMonitorEnabled = true
fpsFrameCount = 0
fpsLastTime = performance.now()
fpsValues = []
// eslint-disable-next-line no-console
console.log('[Perf] FPS 监控已启动')
const updateFps = () => {
if (!fpsMonitorEnabled) return
fpsFrameCount++
const currentTime = performance.now()
const elapsed = currentTime - fpsLastTime
if (elapsed >= intervalMs) {
const fps = Math.round((fpsFrameCount * 1000) / elapsed)
fpsValues.push(fps)
// 保留最近 60 个 FPS 值用于计算平均值
if (fpsValues.length > 60) {
fpsValues.shift()
}
const avgFps = Math.round(fpsValues.reduce((a, b) => a + b, 0) / fpsValues.length)
const minFps = Math.min(...fpsValues)
const maxFps = Math.max(...fpsValues)
// 根据 FPS 设置不同颜色
const color = fps >= 55 ? '#67c23a' : fps >= 30 ? '#e6a23c' : '#f56c6c'
// eslint-disable-next-line no-console
console.log(
`%c[Perf] FPS: ${fps} | 平均: ${avgFps} | 最小: ${minFps} | 最大: ${maxFps}`,
`color: ${color}; font-weight: bold;`,
)
fpsFrameCount = 0
fpsLastTime = currentTime
}
fpsRafId = requestAnimationFrame(updateFps)
}
fpsRafId = requestAnimationFrame(updateFps)
},
/**
* FPS
*/
stopFpsMonitor() {
if (!fpsMonitorEnabled) {
// eslint-disable-next-line no-console
console.warn('[Perf] FPS 监控未运行')
return
}
fpsMonitorEnabled = false
if (fpsRafId !== null) {
cancelAnimationFrame(fpsRafId)
fpsRafId = null
}
// 输出最终统计
if (fpsValues.length > 0) {
const avgFps = Math.round(fpsValues.reduce((a, b) => a + b, 0) / fpsValues.length)
const minFps = Math.min(...fpsValues)
const maxFps = Math.max(...fpsValues)
// eslint-disable-next-line no-console
console.log(
`%c[Perf] FPS 监控已停止 | 总采样: ${fpsValues.length} | 平均: ${avgFps} | 最小: ${minFps} | 最大: ${maxFps}`,
'color: #909399; font-weight: bold;',
)
}
fpsValues = []
},
/**
*
* @param duration
* @param details
*/
recordDraw(duration: number, details?: unknown) {
drawStats.totalDraws++
drawStats.totalDuration += duration
drawStats.minDuration = Math.min(drawStats.minDuration, duration)
drawStats.maxDuration = Math.max(drawStats.maxDuration, duration)
drawStats.avgDuration = drawStats.totalDuration / drawStats.totalDraws
// 记录最近的绘制
drawStats.recentDraws.push({
timestamp: Date.now(),
duration,
details,
})
// 保持数组大小在限制内
if (drawStats.recentDraws.length > MAX_RECENT_DRAWS) {
drawStats.recentDraws.shift()
}
},
/**
*
*/
getDrawStats() {
return {
...drawStats,
recentDraws: drawStats.recentDraws.slice(-10), // 只返回最近 10 次
}
},
/**
*
*/
printDrawStats() {
if (drawStats.totalDraws === 0) {
// eslint-disable-next-line no-console
console.log('[Perf] 暂无绘制数据')
return
}
const recent10 = drawStats.recentDraws.slice(-10)
const recent10Avg =
recent10.reduce((sum, item) => sum + item.duration, 0) / recent10.length
// eslint-disable-next-line no-console
console.log(
'%c[Perf] Canvas 绘制统计',
'color: #409eff; font-weight: bold; font-size: 14px;',
)
// eslint-disable-next-line no-console
console.table({
总绘制次数: drawStats.totalDraws,
: `${drawStats.avgDuration.toFixed(2)}ms`,
: `${drawStats.minDuration.toFixed(2)}ms`,
: `${drawStats.maxDuration.toFixed(2)}ms`,
10: `${recent10Avg.toFixed(2)}ms`,
})
},
/**
*
*/
resetDrawStats() {
drawStats.totalDraws = 0
drawStats.totalDuration = 0
drawStats.minDuration = Infinity
drawStats.maxDuration = 0
drawStats.avgDuration = 0
drawStats.recentDraws = []
// eslint-disable-next-line no-console
console.log('[Perf] 绘制统计已重置')
},
/**
* FPS +
* @param durationMs 10000ms (10)
*/
startPerformanceTest(durationMs = 10000) {
// eslint-disable-next-line no-console
console.log(
`%c[Perf] 性能测试开始(持续 ${durationMs / 1000} 秒)`,
'color: #409eff; font-weight: bold; font-size: 16px;',
)
this.resetDrawStats()
this.startFpsMonitor()
setTimeout(() => {
this.stopFpsMonitor()
this.printDrawStats()
// eslint-disable-next-line no-console
console.log(
'%c[Perf] 性能测试完成',
'color: #67c23a; font-weight: bold; font-size: 16px;',
)
}, durationMs)
},
}
+2
View File
@@ -27,6 +27,8 @@ export default defineConfig({
// 确保外部化处理那些你不想打包进库的依赖
external: ['vue'],
output: {
// 使用命名导出,避免默认导出警告
exports: 'named',
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: 'Vue',
+1777
View File
File diff suppressed because it is too large Load Diff