feat: 导出甘特图
This commit is contained in:
parent
d21f09d3a6
commit
31fefeadb4
@ -4,6 +4,7 @@ import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import useUserStore from '@/store/modules/user'
|
||||
import { api, errorText, isAccessFailure } from '../api'
|
||||
import { plannedDate, planBoundary } from '../shared/utils/time'
|
||||
import { typeNames } from '../shared/constants/labels'
|
||||
import { reconcileRows, retainSnapshot } from '../shared/utils/snapshot'
|
||||
import type { Project, Member, WorkItem, ItemType, Lifecycle, FlowView, Iteration, ItemQuery } from '../types'
|
||||
import { iterationReadOnly, iterationCanExecute } from '../features/iterations/utils/scope'
|
||||
@ -169,6 +170,17 @@ export function useProjectCollaboration() {
|
||||
return { view, page: page.value, pageSize, keyword: keyword.value, type: typeFilter.value, blockedOnly: blockedOnly.value, stageId: stageFilter.value, ...(view === 'gantt' ? { from: ganttFrom.value, to: ganttTo.value, memberIds: [...ganttMemberIds.value] } : {}) }
|
||||
}
|
||||
|
||||
/** 导出沿用甘特的完整服务端筛选,但独立从第一页读取,翻页不改变导出范围。 */
|
||||
const ganttExportQuery = computed(() => ({ ...query('gantt'), page: 1, pageSize: 200 }))
|
||||
/** 文件中记录本次筛选含义,成员多选仍按负责人或协作人命中任一成员计算。 */
|
||||
const ganttExportFilters = computed(() => [
|
||||
keyword.value.trim() ? `标题:${keyword.value.trim()}` : '',
|
||||
typeFilter.value ? `类型:${typeNames[typeFilter.value]}` : '全部类型',
|
||||
blockedOnly.value ? '仅看依赖阻塞' : '',
|
||||
stageFilter.value == null ? '全部阶段' : stageFilter.value === 0 ? '未分配阶段' : `阶段:${flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.stagePath || flowView.value?.stages.find(stage => stage.id === stageFilter.value)?.name || stageFilter.value}`,
|
||||
ganttMemberIds.value.length ? `成员:${ganttMemberIds.value.map(id => members.value.find(member => member.userId === id)?.name || `用户 #${id}`).join('、')}` : '全部成员',
|
||||
].filter(Boolean).join(';'))
|
||||
|
||||
/** 用户主动刷新或业务操作完成时显示加载状态;独立包装避免分页事件的页码被当作后台标志。 */
|
||||
async function refresh() {
|
||||
await refreshData(false)
|
||||
@ -613,7 +625,7 @@ export function useProjectCollaboration() {
|
||||
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
|
||||
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection,
|
||||
editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts,
|
||||
ganttFrom, ganttTo, ganttMemberIds, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
|
||||
ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
|
||||
notifications, statCards, userStore,
|
||||
refreshWorkspace, refresh, loadBoardMore, moveGanttWindow,
|
||||
changeIteration, iterationsChanged, archiveFilterChanged, openNotice,
|
||||
|
||||
@ -1,8 +1,16 @@
|
||||
<template>
|
||||
<div class="gantt-wrap">
|
||||
<div class="gantt-note">阶段与工作项共用时间轴;拖动时间条或端点调整计划,失败恢复原排期。虚线为失效参考计划,仅供查看。</div>
|
||||
<div class="gantt-toolbar">
|
||||
<div class="gantt-note">阶段与工作项共用时间轴;拖动时间条或端点调整计划,失败恢复原排期。虚线为失效参考计划,仅供查看。</div>
|
||||
<div class="export-actions">
|
||||
<el-select v-model="exportFormat" size="small" aria-label="甘特导出格式" :disabled="exporting" class="export-format">
|
||||
<el-option label="PNG 图片" value="png" /><el-option label="SVG 矢量图" value="svg" />
|
||||
</el-select>
|
||||
<el-button size="small" :loading="exporting" :disabled="loading || !!gesture || pending.size > 0 || !projectId || !iterationId" title="导出当前筛选及时间范围的全部记录,包含其他分页" @click="exportImage">导出甘特图</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="unscheduled.length" class="unscheduled">排期未完成:<el-link v-for="item in unscheduled" :key="item.id" @click="emit('open', item.id)">{{ item.title }}{{ item.scheduleReviewRequired ? item.scheduleReviewClosed ? '(本轮未确认)' : '(待复核)' : '' }} </el-link></div>
|
||||
<div class="gantt-scroll">
|
||||
<div ref="scrollElement" class="gantt-scroll" :style="{ maxHeight: scrollHeight + 'px' }" role="region" aria-label="甘特排期,可横向及纵向滚动" tabindex="0">
|
||||
<div class="gantt-table" :style="{ width: (labelWidth + days * unit) + 'px' }">
|
||||
<div class="gantt-head"><div class="item-label">阶段 / 工作项</div><div v-for="day in days" :key="day" class="day" :style="{ width: unit + 'px' }">{{ dayLabel(day - 1) }}</div></div>
|
||||
<div v-for="row in rows" :key="row.key" class="gantt-row" :class="{ 'stage-row': !!row.stage }">
|
||||
@ -23,55 +31,64 @@
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, reactive, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onDeactivated, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import type { WorkItem, ScheduleChange, Stage, StageScheduleChange } from '../../types'
|
||||
import type { WorkItem, ScheduleChange, Stage, StageScheduleChange, ItemQuery } from '../../types'
|
||||
import { itemStatusLabel, stageStatusLabel } from '../../shared/constants/labels'
|
||||
import { shiftDays, visualMillis, localTime, plannedRange, planBoundary, plannedDate } from '../../shared/utils/time'
|
||||
import { api, errorText } from '../../api'
|
||||
import { moveSchedule } from '../../shared/utils/optimistic'
|
||||
import StageSchedulePanel from '../../features/schedules/components/StageSchedulePanel.vue'
|
||||
import { buildTimelineRows, type TimelineRow } from './utils/timeline'
|
||||
import { useGanttViewport } from './composables/useGanttViewport'
|
||||
import { collectGanttData } from './utils/exportData'
|
||||
import { createGanttImage, ganttImageBlob, downloadGanttImage, type GanttExportFormat } from './utils/exportImage'
|
||||
|
||||
interface TimelineRow { key: string; label: string; depth?: number; item?: WorkItem; stage?: Stage; start: string | null; end: string | null; reference: boolean }
|
||||
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; zone: string; canWrite: boolean; canManage?: boolean; projectId?: number; iterationId?: number; from?: string; to?: string; memberFiltered?: boolean; stageFilter?: number | null }>(), { stages: () => [], memberFiltered: false })
|
||||
const props = withDefaults(defineProps<{ items: WorkItem[]; stages?: Stage[]; zone: string; canWrite: boolean; canManage?: boolean; projectId?: number; iterationId?: number; from?: string; to?: string; memberFiltered?: boolean; stageFilter?: number | null; loading?: boolean; projectName?: string; iterationName?: string; exportQuery?: ItemQuery; exportFilters?: string }>(), { stages: () => [], memberFiltered: false })
|
||||
const emit = defineEmits<{ open: [id: number]; changed: [] }>()
|
||||
const unit = 34, labelWidth = 220, dayMs = 86400000
|
||||
const pending = reactive(new Set<string>()), selectedStageId = ref<number | null>(null)
|
||||
const scrollElement = ref<HTMLElement | null>(null), scrollHeight = useGanttViewport(scrollElement)
|
||||
const exporting = ref(false), exportFormat = ref<GanttExportFormat>('png')
|
||||
let exportSequence = 0
|
||||
// 筛选切走再切回也要作废旧导出;普通轮询替换同值摘要不改变本次导出范围。
|
||||
watch(() => JSON.stringify([props.projectId, props.iterationId, props.from, props.to, props.stageFilter, props.memberFiltered, props.exportQuery]), () => { exportSequence++ }, { flush: 'sync' })
|
||||
// 系统菜单由 KeepAlive 缓存,离页不会卸载;停用同样要取消旧导出,返回也不能继续下载。
|
||||
onDeactivated(() => { exportSequence++ })
|
||||
const selectedStage = computed(() => props.stages.find(stage => stage.id === selectedStageId.value))
|
||||
const unscheduled = computed(() => props.items.filter(item => !item.plannedStartAt || !item.plannedEndAt))
|
||||
/** 父组、子阶段及工作项逐层展示;成员筛选保留完整父路径,各工作项只进入所属工作阶段一次。 */
|
||||
const rows = computed(() => {
|
||||
const result: TimelineRow[] = [], known = new Set(props.stages.map(stage => stage.id))
|
||||
const visible = new Set(props.items.map(item => item.stageId).filter((id): id is number => !!id))
|
||||
if (props.stageFilter && !props.memberFiltered) {
|
||||
visible.add(props.stageFilter)
|
||||
for (const child of props.stages.filter(stage => stage.parentStageId === props.stageFilter)) visible.add(child.id)
|
||||
}
|
||||
for (const stage of props.stages) if (visible.has(stage.id) && stage.parentStageId) visible.add(stage.parentStageId)
|
||||
for (const root of props.stages.filter(stage => !stage.parentStageId)) append(root, 0)
|
||||
for (const item of props.items.filter(item => !item.stageId || !known.has(item.stageId))) if (hasRange(item)) result.push(timelineRow('i:' + item.id, item.title, item, false))
|
||||
return result
|
||||
/** 父级先展示,引用实际阶段计划而非子计划包络;层级只是显示,不改变原子改期入口。 */
|
||||
function append(stage: Stage, depth: number) {
|
||||
if ((props.memberFiltered || props.stageFilter != null) && !visible.has(stage.id)) return
|
||||
result.push({ ...timelineRow('s:' + stage.id, stage.name, stage, true), depth })
|
||||
for (const child of props.stages.filter(candidate => candidate.parentStageId === stage.id)) append(child, depth + 1)
|
||||
for (const item of props.items.filter(item => item.stageId === stage.id)) if (hasRange(item)) result.push({ ...timelineRow('i:' + item.id, item.title, item, false), depth: depth + 1 + (item.parentTaskId ? 1 : 0) })
|
||||
}
|
||||
})
|
||||
/** 有效时间优先;只有完整参考区间才画参考条,不拼接两种语义的端点。 */
|
||||
function timelineRow(key: string, label: string, source: Stage | WorkItem, stage: boolean): TimelineRow {
|
||||
const normal = !!source.plannedStartAt && !!source.plannedEndAt
|
||||
return { key, label, stage: stage ? source as Stage : undefined, item: stage ? undefined : source as WorkItem, start: normal ? source.plannedStartAt : source.referencePlannedStartAt || null, end: normal ? source.plannedEndAt : source.referencePlannedEndAt || null, reference: !normal }
|
||||
}
|
||||
/** 不完整任务仍保留顶部入口,避免生成没有业务意义的时间条。 */
|
||||
function hasRange(item: WorkItem) { return item.plannedStartAt && item.plannedEndAt || item.referencePlannedStartAt && item.referencePlannedEndAt }
|
||||
const rows = computed(() => buildTimelineRows(props.items, props.stages, props.memberFiltered, props.stageFilter))
|
||||
// 网格从北京时间零点开始,避免当前时分秒使日期刻度与整日计划错位。
|
||||
const minimum = computed(() => visualMillis(planBoundary(plannedDate(props.from || new Date(Math.min(...rows.value.filter(row => row.start).map(row => visualMillis(row.start!)), Date.now()) - dayMs).toISOString(), props.zone), 'start', props.zone)!))
|
||||
const maximum = computed(() => props.to ? visualMillis(props.to) : Math.max(...rows.value.filter(row => row.end).map(row => visualMillis(row.end!)), minimum.value + 14 * dayMs) + dayMs)
|
||||
const days = computed(() => Math.min(730, Math.max(1, Math.ceil((maximum.value - minimum.value) / dayMs))))
|
||||
const gesture = ref<{ row: TimelineRow; x: number; kind: 'move' | 'start' | 'end'; delta: number } | null>(null)
|
||||
let disposed = false
|
||||
/**
|
||||
* 固定点击时的筛选、标题和日期轴,读取全部匹配页后生成文件;期间暂停静默同步和改期手势。
|
||||
* 页面或筛选变化立即使旧结果失效,失败不下载部分数据,也不影响当前甘特的滚动与排期。
|
||||
*/
|
||||
async function exportImage() {
|
||||
if (exporting.value || props.loading || gesture.value || pending.size || !props.projectId || !props.iterationId) return
|
||||
const sequence = exportSequence, format = exportFormat.value
|
||||
const query = { ...props.exportQuery, from: props.from, to: props.to, stageId: props.stageFilter, memberIds: [...(props.exportQuery?.memberIds || [])] }
|
||||
const input = { minimum: minimum.value, days: days.value, zone: props.zone, projectName: props.projectName || '项目协作', iterationName: props.iterationName || '当前迭代', filters: props.exportFilters || '全部' }
|
||||
const current = () => !disposed && sequence === exportSequence
|
||||
exporting.value = true
|
||||
try {
|
||||
const data = await collectGanttData(props.projectId, props.iterationId, query, current)
|
||||
if (!current()) return
|
||||
const exportRows = buildTimelineRows(data.items, data.stages, props.memberFiltered, props.stageFilter, true)
|
||||
if (!exportRows.length) { ElMessage.info('当前筛选范围没有可导出的排期'); return }
|
||||
const image = createGanttImage({ ...input, rows: exportRows })
|
||||
const blob = await ganttImageBlob(image, format)
|
||||
if (!current()) return
|
||||
downloadGanttImage(blob, `${input.projectName}_${input.iterationName}_甘特排期_${plannedDate(new Date().toISOString(), props.zone)}`, format)
|
||||
ElMessage.success('甘特图已导出')
|
||||
} catch (error) { if (current()) ElMessage({ type: 'error', message: errorText(error), duration: 8000 }) }
|
||||
finally { exporting.value = false }
|
||||
}
|
||||
/** 完成后的正常计划只读;缺失计划在专门的补录面板处理。 */
|
||||
function frozen(stageId?: number | null) { return ['COMPLETED', 'LEGACY_PASSED'].includes(props.stages.find(stage => stage.id === stageId)?.executionStatus || '') }
|
||||
/** 参考条、只读阶段及缺少版本的条目不开放手势,最终权限仍由后端重新验证。 */
|
||||
@ -88,7 +105,7 @@ function barStyle(row: TimelineRow) {
|
||||
function dayLabel(day: number) { return localTime(new Date(minimum.value + day * dayMs).toISOString(), props.zone).slice(5, 10) }
|
||||
/** 手势只累计位移,松开前不修改原对象或发送请求。 */
|
||||
function begin(row: TimelineRow, event: PointerEvent, kind: 'move' | 'start' | 'end') {
|
||||
if (!editable(row)) return
|
||||
if (exporting.value || !editable(row)) return
|
||||
event.preventDefault(); cleanup(); gesture.value = { row, x: event.clientX, kind, delta: 0 }
|
||||
window.addEventListener('pointermove', track); window.addEventListener('pointerup', end, { once: true })
|
||||
}
|
||||
@ -125,8 +142,24 @@ async function end() {
|
||||
/** 退出时释放监听,打开的原因对话框也不能继续向已离开的迭代写入。 */
|
||||
function cleanup() { window.removeEventListener('pointermove', track); window.removeEventListener('pointerup', end); gesture.value = null }
|
||||
onBeforeUnmount(() => { disposed = true; cleanup() })
|
||||
defineExpose({ isEditing: computed(() => !!gesture.value || pending.size > 0 || selectedStageId.value !== null) })
|
||||
defineExpose({ isEditing: computed(() => exporting.value || !!gesture.value || pending.size > 0 || selectedStageId.value !== null) })
|
||||
</script>
|
||||
<style scoped>
|
||||
.gantt-note{font-size:12px;color:var(--el-text-color-secondary);margin:0 0 10px}.unscheduled{padding:8px;background:var(--el-color-warning-light-9);margin-bottom:10px;border-radius:6px;font-size:12px}.gantt-scroll{overflow:auto;max-height:calc(100vh - 320px);border:1px solid var(--el-border-color-light);border-radius:6px}.gantt-head,.gantt-row{display:flex;height:38px;align-items:center;border-bottom:1px solid var(--el-border-color-lighter)}.gantt-head{background:var(--el-fill-color-light);position:sticky;top:0;z-index:3}.item-label{width:220px;flex-shrink:0;position:sticky;left:0;background:var(--el-bg-color-overlay);z-index:2;padding:8px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.stage-row .item-label{font-weight:600;background:var(--el-fill-color-light)}.day{flex-shrink:0;text-align:center;color:var(--el-text-color-secondary);font-size:10px}.timeline{overflow:hidden;position:relative;height:100%;background:repeating-linear-gradient(to right,transparent 0,transparent 33px,var(--el-border-color-lighter) 33px,var(--el-border-color-lighter) 34px)}.bar{position:absolute;top:7px;height:24px;border-radius:4px;background:var(--el-color-primary-light-8);color:var(--el-text-color-primary);font-size:11px;min-width:20px;text-align:center;line-height:24px;cursor:grab;user-select:none;touch-action:none}.bar.stage-bar{background:var(--el-color-primary-light-5);font-weight:600}.bar.blocked{background:var(--el-color-warning-light-8)}.bar.busy{opacity:.55}.bar.reference{border:1px dashed var(--el-color-warning);background:var(--el-color-warning-light-9);color:var(--el-color-warning);cursor:pointer;line-height:22px}.handle{position:absolute;width:7px;top:0;height:100%;cursor:ew-resize;background:var(--el-color-primary-light-5)}.handle.left{left:0}.handle.right{right:0}.blocked-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--el-color-warning);margin-right:5px}.no-plan{font-size:12px;color:var(--el-text-color-secondary);padding:10px;display:inline-block;cursor:pointer}
|
||||
.gantt-note{font-size:12px;color:var(--el-text-color-secondary);margin:0 0 10px}.unscheduled{padding:8px;background:var(--el-color-warning-light-9);margin-bottom:10px;border-radius:6px;font-size:12px}.gantt-scroll{overflow:auto;border:1px solid var(--el-border-color-light);border-radius:6px}.gantt-head,.gantt-row{display:flex;height:38px;align-items:center;border-bottom:1px solid var(--el-border-color-lighter)}.gantt-head{background:var(--el-fill-color-light);position:sticky;top:0;z-index:3}.item-label{width:220px;flex-shrink:0;position:sticky;left:0;background:var(--el-bg-color-overlay);z-index:2;padding:8px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}.stage-row .item-label{font-weight:600;background:var(--el-fill-color-light)}.day{flex-shrink:0;text-align:center;color:var(--el-text-color-secondary);font-size:10px}.timeline{overflow:hidden;position:relative;height:100%;background:repeating-linear-gradient(to right,transparent 0,transparent 33px,var(--el-border-color-lighter) 33px,var(--el-border-color-lighter) 34px)}.bar{position:absolute;top:7px;height:24px;border-radius:4px;background:var(--el-color-primary-light-8);color:var(--el-text-color-primary);font-size:11px;min-width:20px;text-align:center;line-height:24px;cursor:grab;user-select:none;touch-action:none}.bar.stage-bar{background:var(--el-color-primary-light-5);font-weight:600}.bar.blocked{background:var(--el-color-warning-light-8)}.bar.busy{opacity:.55}.bar.reference{border:1px dashed var(--el-color-warning);background:var(--el-color-warning-light-9);color:var(--el-color-warning);cursor:pointer;line-height:22px}.handle{position:absolute;width:7px;top:0;height:100%;cursor:ew-resize;background:var(--el-color-primary-light-5)}.handle.left{left:0}.handle.right{right:0}.blocked-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--el-color-warning);margin-right:5px}.no-plan{font-size:12px;color:var(--el-text-color-secondary);padding:10px;display:inline-block;cursor:pointer}
|
||||
/* 高度按实际可用区域计算;长时间轴不能撑开父容器,否则横向滚动条会跑到页面之外。 */
|
||||
.gantt-wrap{min-width:0;width:100%;max-width:100%}
|
||||
.gantt-toolbar{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:8px}
|
||||
.gantt-toolbar .gantt-note{flex:1 1 280px;margin:0;line-height:18px}
|
||||
.export-actions{display:flex;align-items:center;gap:8px;flex:none;margin-left:auto}
|
||||
.export-format{width:132px}
|
||||
.unscheduled{max-height:76px;overflow:auto;line-height:22px;overflow-wrap:anywhere}
|
||||
.gantt-scroll{width:100%;max-width:100%;min-height:80px;box-sizing:border-box;scrollbar-gutter:stable;scrollbar-width:auto;scrollbar-color:var(--el-text-color-placeholder) var(--el-fill-color-light)}
|
||||
.gantt-scroll:focus-visible{outline:2px solid var(--el-color-primary);outline-offset:2px}
|
||||
.gantt-scroll::-webkit-scrollbar{width:10px;height:10px}
|
||||
.gantt-scroll::-webkit-scrollbar-track{background:var(--el-fill-color-light)}
|
||||
.gantt-scroll::-webkit-scrollbar-thumb{background:var(--el-text-color-placeholder);border-radius:5px;border:2px solid var(--el-fill-color-light)}
|
||||
.gantt-scroll::-webkit-scrollbar-corner{background:var(--el-fill-color-light)}
|
||||
.gantt-table{min-width:100%}
|
||||
.item-label{box-sizing:border-box}
|
||||
.timeline{flex-shrink:0}
|
||||
</style>
|
||||
|
||||
@ -0,0 +1,85 @@
|
||||
import { nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, type Ref } from 'vue'
|
||||
|
||||
/**
|
||||
* 根据滚动区真实位置分配高度,避免顶部换行、页面缩放和系统页签高度变化遮住横向滚动条。
|
||||
* @param element 甘特唯一的双向滚动容器
|
||||
* @returns 最大可用高度;内容较少时仍自然收缩,不改变滚动位置
|
||||
* 只监听当前工作区,尺寸回调通过一帧合并;卸载时释放全部监听及观察器。
|
||||
*/
|
||||
export function useGanttViewport(element: Ref<HTMLElement | null>) {
|
||||
const maxHeight = ref(320)
|
||||
let observer: ResizeObserver | undefined, mutations: MutationObserver | undefined, frame = 0, disposed = false, active = true
|
||||
let host: HTMLElement | null = null
|
||||
|
||||
/** 统一使用可视坐标,CSS 缩放时转换回布局像素;分页、容器边距与系统页脚均留在滚动区外。 */
|
||||
function measure() {
|
||||
frame = 0
|
||||
const scroll = element.value
|
||||
if (!scroll || disposed || !active) return
|
||||
const rect = scroll.getBoundingClientRect()
|
||||
if (!rect.width || !scroll.offsetWidth) return
|
||||
const scale = rect.width / scroll.offsetWidth
|
||||
const viewport = window.visualViewport
|
||||
let bottom = viewport ? viewport.offsetTop + viewport.height : window.innerHeight
|
||||
if (host) {
|
||||
const bounds = host.getBoundingClientRect(), style = getComputedStyle(host)
|
||||
bottom = Math.min(bottom, bounds.top + host.clientHeight * scale - (parseFloat(style.paddingBottom) || 0) * scale)
|
||||
}
|
||||
const surface = scroll.closest('.work-surface')
|
||||
const pagination = surface?.querySelector<HTMLElement>('.work-pagination')
|
||||
const footer = pagination ? pagination.getBoundingClientRect().height / scale + (parseFloat(getComputedStyle(pagination).marginTop) || 0) : 0
|
||||
const height = Math.max(80, Math.floor((bottom - Math.max(0, rect.top)) / scale - footer - 20))
|
||||
if (height !== maxHeight.value) maxHeight.value = height
|
||||
}
|
||||
|
||||
/** 尺寸及外层滚动事件可能同帧触发多次,只安排一次测量,避免 ResizeObserver 内同步写布局。 */
|
||||
function scheduleMeasure() {
|
||||
if (active && !disposed && !frame) frame = window.requestAnimationFrame(measure)
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面有 min-height 时,筛选换行可能只挤占留白,整页尺寸不变;因此也观察前置兄弟和甘特提示区。
|
||||
* 直接子节点增删后重建目标集合,避免错误提示或分页新出现时继续沿用旧位置。
|
||||
*/
|
||||
function observeLayout() {
|
||||
const scroll = element.value, workspace = scroll?.closest('.pm-app')
|
||||
if (!observer || !scroll) return
|
||||
observer.disconnect()
|
||||
for (const target of new Set([host, workspace, scroll.parentElement, ...(workspace?.children || [])])) {
|
||||
if (target) observer.observe(target)
|
||||
}
|
||||
scheduleMeasure()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
host = element.value?.closest<HTMLElement>('.app-main') || null
|
||||
void nextTick(scheduleMeasure)
|
||||
window.addEventListener('resize', scheduleMeasure)
|
||||
host?.addEventListener('scroll', scheduleMeasure, { passive: true })
|
||||
window.visualViewport?.addEventListener('resize', scheduleMeasure)
|
||||
window.visualViewport?.addEventListener('scroll', scheduleMeasure)
|
||||
if (typeof ResizeObserver !== 'undefined' && element.value) {
|
||||
observer = new ResizeObserver(scheduleMeasure)
|
||||
observeLayout()
|
||||
const workspace = element.value.closest('.pm-app')
|
||||
if (workspace && typeof MutationObserver !== 'undefined') {
|
||||
mutations = new MutationObserver(observeLayout)
|
||||
mutations.observe(workspace, { childList: true })
|
||||
}
|
||||
}
|
||||
})
|
||||
// KeepAlive 停用期间不计算脱离页面的尺寸;返回后即使外层尺寸未变化也重新测量。
|
||||
onActivated(() => { active = true; void nextTick(scheduleMeasure) })
|
||||
onDeactivated(() => { active = false; window.cancelAnimationFrame(frame); frame = 0 })
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
observer?.disconnect()
|
||||
mutations?.disconnect()
|
||||
window.cancelAnimationFrame(frame)
|
||||
window.removeEventListener('resize', scheduleMeasure)
|
||||
host?.removeEventListener('scroll', scheduleMeasure)
|
||||
window.visualViewport?.removeEventListener('resize', scheduleMeasure)
|
||||
window.visualViewport?.removeEventListener('scroll', scheduleMeasure)
|
||||
})
|
||||
return maxHeight
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
import { api } from '../../../api'
|
||||
import type { ItemQuery, WorkItem } from '../../../types'
|
||||
|
||||
/**
|
||||
* 读取当前筛选的全部分页,不把页面当前页误当作完整甘特图。
|
||||
* @param projectId 已选协作项目,所有请求继续经过原鉴权接口
|
||||
* @param iterationId 已选迭代,不跨迭代汇总
|
||||
* @param query 本次点击时的筛选快照,页码由导出独立管理
|
||||
* @param isCurrent 页面、迭代或筛选变化后返回 false,停止续页及文件生成
|
||||
* @returns 图版本一致的阶段与工作项;读取失败或版本变化时整次失败,不交付部分结果
|
||||
*/
|
||||
export async function collectGanttData(projectId: number, iterationId: number, query: ItemQuery, isCurrent: () => boolean) {
|
||||
const filter = { ...query, memberIds: [...(query.memberIds || [])], view: 'gantt' as const }
|
||||
checkScope()
|
||||
const graph = await api.flowView(projectId, iterationId)
|
||||
checkScope()
|
||||
const items: WorkItem[] = [], ids = new Set<number>()
|
||||
let total = 0
|
||||
for (let page = 1; ; page++) {
|
||||
checkScope()
|
||||
const result = await api.items(projectId, iterationId, { ...filter, page, pageSize: 200 })
|
||||
checkScope()
|
||||
if (result.graphVersion !== graph.graphVersion || page > 1 && result.total !== total) throw new Error('导出期间排期数据发生变化,请重新导出')
|
||||
total = result.total
|
||||
if (total > 10000) throw new Error('匹配工作项超过 10000 项,请缩小时间或筛选范围后导出')
|
||||
for (const item of result.rows) {
|
||||
if (ids.has(item.id)) throw new Error('导出期间分页数据发生变化,请重新导出')
|
||||
ids.add(item.id); items.push(item)
|
||||
}
|
||||
if (items.length === total) break
|
||||
if (!result.rows.length || items.length > total) throw new Error('导出数据不完整,请刷新后重试')
|
||||
}
|
||||
// 最后一页完成后再走一次鉴权与图版本检查;不把两次修改前后的分页拼成一张图。
|
||||
const latest = await api.items(projectId, iterationId, { ...filter, page: 1, pageSize: 1 })
|
||||
checkScope()
|
||||
if (latest.graphVersion !== graph.graphVersion || latest.total !== total) throw new Error('导出期间排期数据发生变化,请重新导出')
|
||||
return { items, stages: graph.stages }
|
||||
|
||||
/** 即使切走后又返回相同迭代,调用方的代次检查也会使旧导出失效。 */
|
||||
function checkScope() { if (!isCurrent()) throw new Error('导出范围已切换') }
|
||||
}
|
||||
@ -0,0 +1,135 @@
|
||||
import { itemStatusLabel, stageStatusLabel, typeNames } from '../../../shared/constants/labels'
|
||||
import { plannedDate, visualMillis } from '../../../shared/utils/time'
|
||||
import type { TimelineRow } from './timeline'
|
||||
|
||||
export type GanttExportFormat = 'png' | 'svg'
|
||||
export interface GanttImage { svg: string; width: number; height: number }
|
||||
interface ImageInput {
|
||||
rows: TimelineRow[]
|
||||
minimum: number
|
||||
days: number
|
||||
zone: string
|
||||
projectName: string
|
||||
iterationName: string
|
||||
filters: string
|
||||
}
|
||||
|
||||
/** 用户名称仅作为 SVG 文本,移除 XML 禁止字符并转义标记,不能产生脚本、链接或外部资源引用。 */
|
||||
function xml(value: string): string {
|
||||
return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]!)
|
||||
}
|
||||
|
||||
/** 按中英文近似字宽拆行,不省略长名称;行高随拆行增长,导出不依赖屏幕上的省略号或裁切。 */
|
||||
function wrap(value: string, units: number): string[] {
|
||||
const lines: string[] = []
|
||||
let line = '', length = 0
|
||||
for (const char of value.replace(/\s+/g, ' ')) {
|
||||
const size = char.charCodeAt(0) > 255 ? 2 : 1
|
||||
if (length + size > units && line) { lines.push(line); line = ''; length = 0 }
|
||||
line += char; length += size
|
||||
}
|
||||
lines.push(line)
|
||||
return lines
|
||||
}
|
||||
|
||||
/** SVG 基础文本保持固定字体和浅色底,导出不受用户暗黑主题影响;所有可变内容先转义。 */
|
||||
function text(x: number, y: number, value: string, size = 12, color = '#334155', weight = 400): string {
|
||||
return `<text x="${x}" y="${y}" font-size="${size}" fill="${color}" font-weight="${weight}">${xml(value)}</text>`
|
||||
}
|
||||
|
||||
/**
|
||||
* 从完整业务行生成独立矢量甘特,不截取 DOM,因此屏幕滚动、分页与设备像素比不会截断文件。
|
||||
* @param input 导出瞬间固定的标题、筛选、日期轴和完整行,预计日期仍按业务时区显示
|
||||
* @returns 不依赖外部字体、样式和图片的 SVG 及逻辑尺寸;参考计划仅作虚线标识
|
||||
*/
|
||||
export function createGanttImage(input: ImageInput): GanttImage {
|
||||
const { rows, minimum, days, zone } = input
|
||||
const unit = 34, dayMs = 86400000, padding = 16, labelWidth = 370, statusWidth = 130
|
||||
const timelineX = padding + labelWidth + statusWidth, timelineWidth = days * unit, width = timelineX + timelineWidth + padding
|
||||
const titleLines = wrap(`${input.projectName} / ${input.iterationName} · 甘特排期`, Math.floor((width - 32) / 11))
|
||||
const filters = wrap(`筛选:${input.filters || '全部'};工作项 ${rows.filter(row => row.item).length} 项`, Math.floor((width - 32) / 7))
|
||||
const layout = rows.map(row => {
|
||||
const prefix = row.stage ? `${row.stage.stageKind === 'GROUP' ? '阶段组' : '阶段'} · ` : `${row.item?.parentTaskId ? '子任务' : typeNames[row.item!.type]} #${row.item!.id} · `
|
||||
const name = prefix + row.label + (row.stage ? ` · v${row.stage.revisionNo || 1}` : '')
|
||||
const indent = Math.min(row.depth || 0, 8) * 16
|
||||
const lines = wrap(name, Math.floor((labelWidth - indent - 20) / 7))
|
||||
return { row, name, indent, lines, height: Math.max(74, lines.length * 18 + 50) }
|
||||
})
|
||||
const headerTop = 78 + titleLines.length * 26 + filters.length * 18
|
||||
const bodyTop = headerTop + 34, height = bodyTop + layout.reduce((sum, row) => sum + row.height, 0) + 24
|
||||
const output = [`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img"><title>${xml(`${input.projectName} / ${input.iterationName} 甘特排期`)}</title><defs><pattern id="day-grid" x="${timelineX}" width="${unit}" height="1" patternUnits="userSpaceOnUse"><path d="M0 0V1" stroke="#e2e8f0" stroke-width="1"/></pattern></defs><rect width="100%" height="100%" fill="#fff"/><g font-family="Microsoft YaHei, PingFang SC, Arial, sans-serif">`]
|
||||
titleLines.forEach((line, i) => output.push(text(padding, 30 + i * 26, line, 20, '#0f172a', 600)))
|
||||
let y = 38 + titleLines.length * 26
|
||||
output.push(text(padding, y, `日期:${plannedDate(new Date(minimum).toISOString(), zone)} — ${plannedDate(new Date(minimum + days * dayMs - 1).toISOString(), zone)}`))
|
||||
filters.forEach((line, i) => output.push(text(padding, y + 22 + i * 18, line)))
|
||||
output.push(text(padding, headerTop - 12, '蓝色:有效计划 橙色:前置阻塞 虚线:参考计划(未生效)', 11, '#64748b'))
|
||||
output.push(`<rect x="${padding}" y="${headerTop}" width="${width - padding * 2}" height="34" fill="#f1f5f9"/>`, text(padding + 8, headerTop + 22, '阶段 / 工作项 · 日期 · 负责人', 12, '#334155', 600), text(padding + labelWidth + 8, headerTop + 22, '状态', 12, '#334155', 600))
|
||||
for (let day = 0; day < days; day++) output.push(text(timelineX + day * unit + 2, headerTop + 22, plannedDate(new Date(minimum + day * dayMs).toISOString(), zone).slice(5), 10))
|
||||
y = bodyTop
|
||||
for (const entry of layout) {
|
||||
const { row, height: rowHeight, indent, lines, name } = entry
|
||||
const source = (row.stage || row.item)!, reference = row.reference && !!row.start && !!row.end
|
||||
const date = reference ? `参考:${plannedDate(row.start, zone)} → ${plannedDate(row.end, zone)}` : `${plannedDate(source.plannedStartAt, zone)} → ${plannedDate(source.plannedEndAt, zone)}`
|
||||
output.push(`<g><title>${xml(name)}</title><rect x="${padding}" y="${y}" width="${width - padding * 2}" height="${rowHeight}" fill="${row.stage ? '#f8fafc' : '#fff'}"/>`)
|
||||
lines.forEach((line, index) => output.push(text(padding + 8 + indent, y + 19 + index * 18, line, 12, '#0f172a', row.stage ? 600 : 400)))
|
||||
output.push(text(padding + 8 + indent, y + lines.length * 18 + 19, date, 11, reference ? '#b45309' : '#64748b'))
|
||||
output.push(text(padding + 8 + indent, y + lines.length * 18 + 35, `负责人:${row.stage?.ownerName || row.item?.assigneeName || '未分配'}`, 11, '#64748b'))
|
||||
const status = row.stage ? stageStatusLabel(row.stage) : itemStatusLabel(row.item!)
|
||||
wrap(status, 16).forEach((line, index) => output.push(text(padding + labelWidth + 8, y + 23 + index * 18, line)))
|
||||
if (reference) output.push(text(padding + labelWidth + 8, y + 46, source.scheduleReviewClosed ? '本轮未确认' : '排期待复核', 11, '#b45309'))
|
||||
else if (!row.start || !row.end) output.push(text(padding + labelWidth + 8, y + 46, '排期未完成', 11, '#b45309'))
|
||||
output.push(`<rect x="${timelineX}" y="${y}" width="${timelineWidth}" height="${rowHeight}" fill="url(#day-grid)"/>`)
|
||||
if (row.start && row.end) {
|
||||
// 只裁切时间条到当前日期窗口;左侧日期保持完整,不能改写或截断源排期。
|
||||
const startAt = visualMillis(row.start), endAt = visualMillis(row.end)
|
||||
if (endAt >= minimum && startAt < minimum + days * dayMs && endAt >= startAt) {
|
||||
const start = Math.min(timelineWidth - 1, Math.max(0, (startAt - minimum) / dayMs * unit))
|
||||
const end = Math.min(timelineWidth, (endAt - minimum) / dayMs * unit)
|
||||
// 既有计划允许起止相等或相差不足毫秒;这些窗口内区间仍有标记,不能被当作窗口外计划丢弃。
|
||||
output.push(`<rect x="${timelineX + start}" y="${y + 16}" width="${Math.min(timelineWidth - start, Math.max(1, end - start))}" height="24" rx="4" fill="${reference ? '#fffbeb' : row.item?.dependencyBlocked ? '#fed7aa' : row.stage ? '#93c5fd' : '#bfdbfe'}"${reference ? ' stroke="#d97706" stroke-dasharray="5 3"' : ''}/>`)
|
||||
}
|
||||
}
|
||||
output.push(`<path d="M${padding} ${y + rowHeight}H${width - padding}" stroke="#e2e8f0"/></g>`)
|
||||
y += rowHeight
|
||||
}
|
||||
output.push('</g></svg>')
|
||||
return { svg: output.join(''), width, height }
|
||||
}
|
||||
|
||||
/** PNG 尽量使用双倍像素;超过保守画布边长或总像素限制时明确拒绝,避免下载空白图或浏览器耗尽内存。 */
|
||||
export function pngScale(width: number, height: number): number {
|
||||
const scale = Math.min(2, 8192 / width, 16384 / height, Math.sqrt(24_000_000 / (width * height)))
|
||||
if (!Number.isFinite(scale) || scale < 1) throw new Error('当前甘特图过大,请选择 SVG 矢量图,或缩小时间和筛选范围后导出 PNG')
|
||||
return scale
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG 直接下载;PNG 将同一份无外链 SVG 绘制到画布,确保两种格式具有相同内容。
|
||||
* @param image 已完成排版的独立图像
|
||||
* @param format 用户选择的图片格式
|
||||
* @returns 可下载文件;浏览器解码或编码失败时抛错,临时 URL 和画布像素始终释放
|
||||
*/
|
||||
export async function ganttImageBlob(image: GanttImage, format: GanttExportFormat): Promise<Blob> {
|
||||
const svg = new Blob([image.svg], { type: 'image/svg+xml;charset=utf-8' })
|
||||
if (format === 'svg') return svg
|
||||
const scale = pngScale(image.width, image.height), url = URL.createObjectURL(svg), canvas = document.createElement('canvas')
|
||||
try {
|
||||
const bitmap = new Image()
|
||||
await new Promise<void>((resolve, reject) => { bitmap.onload = () => resolve(); bitmap.onerror = () => reject(new Error('图片生成失败,请尝试 SVG 格式')); bitmap.src = url })
|
||||
canvas.width = Math.ceil(image.width * scale); canvas.height = Math.ceil(image.height * scale)
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) throw new Error('浏览器无法生成 PNG,请选择 SVG 格式')
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
|
||||
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('PNG 编码失败,请选择 SVG 格式')), 'image/png'))
|
||||
} finally { URL.revokeObjectURL(url); canvas.width = 0; canvas.height = 0 }
|
||||
}
|
||||
|
||||
/** 文件名不携带路径或控制字符;点击后延迟释放 URL,给浏览器下载进程保留读取时间。 */
|
||||
export function downloadGanttImage(blob: Blob, name: string, format: GanttExportFormat): void {
|
||||
const url = URL.createObjectURL(blob), anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = `${name.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').slice(0, 140) || '甘特排期'}.${format}`
|
||||
document.body.append(anchor)
|
||||
try { anchor.click() }
|
||||
finally { anchor.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 10000) }
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
import type { Stage, WorkItem } from '../../../types'
|
||||
|
||||
export interface TimelineRow {
|
||||
key: string
|
||||
label: string
|
||||
depth?: number
|
||||
item?: WorkItem
|
||||
stage?: Stage
|
||||
start: string | null
|
||||
end: string | null
|
||||
reference: boolean
|
||||
}
|
||||
|
||||
/** 有效时间优先,参考时间必须作为整对使用;不把有效端点与参考端点拼成看似有效的计划。 */
|
||||
function timelineRow(key: string, label: string, source: Stage | WorkItem, stage: boolean): TimelineRow {
|
||||
const normal = !!source.plannedStartAt && !!source.plannedEndAt
|
||||
return { key, label, stage: stage ? source as Stage : undefined, item: stage ? undefined : source as WorkItem, start: normal ? source.plannedStartAt : source.referencePlannedStartAt || null, end: normal ? source.plannedEndAt : source.referencePlannedEndAt || null, reference: !normal }
|
||||
}
|
||||
|
||||
/** 不完整任务在界面顶部保留入口;只有完整有效或参考区间才绘制时间条。 */
|
||||
function hasRange(item: WorkItem) {
|
||||
return !!(item.plannedStartAt && item.plannedEndAt || item.referencePlannedStartAt && item.referencePlannedEndAt)
|
||||
}
|
||||
|
||||
/**
|
||||
* 屏幕与导出共用阶段层级和工作项顺序,成员筛选保留所属阶段的父路径。
|
||||
* @param items 已由服务端按当前筛选和权限过滤的工作项,不在此扩大查询范围
|
||||
* @param stages 当前迭代阶段摘要,组计划采用自身计划,不用子阶段包络代替
|
||||
* @param memberFiltered 是否只展示匹配成员所在的阶段
|
||||
* @param stageFilter 指定阶段或阶段组,0 表示未分配阶段
|
||||
* @param includeUnscheduled 导出时将未排期项纳入对应阶段,界面仍使用顶部未排期入口
|
||||
* @returns 不修改源数据的有序行,每个工作项最多出现一次
|
||||
*/
|
||||
export function buildTimelineRows(items: WorkItem[], stages: Stage[], memberFiltered = false, stageFilter?: number | null, includeUnscheduled = false): TimelineRow[] {
|
||||
const result: TimelineRow[] = [], known = new Set(stages.map(stage => stage.id))
|
||||
const visible = new Set(items.map(item => item.stageId).filter((id): id is number => !!id))
|
||||
if (stageFilter && !memberFiltered) {
|
||||
visible.add(stageFilter)
|
||||
for (const child of stages.filter(stage => stage.parentStageId === stageFilter)) visible.add(child.id)
|
||||
}
|
||||
for (const stage of stages) if (visible.has(stage.id) && stage.parentStageId) visible.add(stage.parentStageId)
|
||||
for (const root of stages.filter(stage => !stage.parentStageId)) append(root, 0)
|
||||
for (const item of items.filter(item => !item.stageId || !known.has(item.stageId))) {
|
||||
if (includeUnscheduled || hasRange(item)) result.push(timelineRow('i:' + item.id, item.title, item, false))
|
||||
}
|
||||
return result
|
||||
|
||||
/** 父级先于子级展示,层级仅用于显示,不改变后端阶段门禁或改期入口。 */
|
||||
function append(stage: Stage, depth: number) {
|
||||
if ((memberFiltered || stageFilter != null) && !visible.has(stage.id)) return
|
||||
result.push({ ...timelineRow('s:' + stage.id, stage.name, stage, true), depth })
|
||||
for (const child of stages.filter(candidate => candidate.parentStageId === stage.id)) append(child, depth + 1)
|
||||
for (const item of items.filter(item => item.stageId === stage.id)) {
|
||||
if (includeUnscheduled || hasRange(item)) result.push({ ...timelineRow('i:' + item.id, item.title, item, false), depth: depth + 1 + (item.parentTaskId ? 1 : 0) })
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -178,6 +178,11 @@
|
||||
:to="ganttTo"
|
||||
:member-filtered="ganttMemberIds.length > 0"
|
||||
:stage-filter="stageFilter"
|
||||
:export-query="ganttExportQuery"
|
||||
:export-filters="ganttExportFilters"
|
||||
:project-name="current.name"
|
||||
:iteration-name="selectedIteration.name"
|
||||
:loading="loading"
|
||||
:can-write="canWrite"
|
||||
:can-manage="canWrite && current.canManage"
|
||||
:project-id="current.id"
|
||||
@ -299,7 +304,7 @@ const {
|
||||
items, members, flowView, current, selectedIteration, zone, canWrite, canCreate, canExecute,
|
||||
loading, failure, tab, keyword, typeFilter, blockedOnly, stageFilter, detailId, refreshKey, selection,
|
||||
editing, editorOpen, creatingParent, defaultStageId, page, pageSize, total, boardCounts,
|
||||
ganttFrom, ganttTo, ganttMemberIds, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
|
||||
ganttFrom, ganttTo, ganttMemberIds, ganttExportQuery, ganttExportFilters, membersOpen, inviteUser, inviteRole, userCandidates, batchOpen,
|
||||
notifications, statCards, userStore,
|
||||
refreshWorkspace, refresh, loadBoardMore, moveGanttWindow,
|
||||
changeIteration, iterationsChanged, archiveFilterChanged, openNotice,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user