Newer
Older
gnexus-tasks / frontend / src / components / TaskTree.vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import type { Task } from '../api'
import { statusOptions } from '../taskui'
import TaskBadges from './TaskBadges.vue'

// Наглядное дерево задач (ТЗ 3.6): линии связей, сворачивание узлов,
// прогресс поддерева. tasks — плоский список; корень выбирается rootId
// (0 — верхний уровень, N — поддерево задачи N). Действия эмитятся родителю.

const props = withDefaults(
  defineProps<{
    tasks: Task[]
    /** 0 — корни верхнего уровня; N — дети задачи N */
    rootId?: number
  }>(),
  { rootId: 0 },
)

const emit = defineEmits<{
  'status-change': [task: Task, status: string]
  'add-subtask': [task: Task]
  delete: [task: Task]
}>()

const { t } = useI18n()

interface FlatNode {
  task: Task
  depth: number
  hasChildren: boolean
  done: number
  total: number
}

const expanded = ref<Record<number, boolean>>({})

const byId = computed(() => {
  const map = new Map<number, Task[]>()
  props.tasks.forEach((t) => {
    const key = t.parent_task_id ?? 0
    const list = map.get(key) ?? []
    list.push(t)
    map.set(key, list)
  })
  return map
})

// Прогресс поддерева: выполнено / всего потомков (в пределах переданного набора)
function subtreeProgress(id: number): { done: number; total: number } {
  let done = 0
  let total = 0
  for (const child of byId.value.get(id) ?? []) {
    total += 1
    if (child.status === 'done') done += 1
    const sub = subtreeProgress(child.id)
    done += sub.done
    total += sub.total
  }
  return { done, total }
}

// Плоское представление дерева с отступами (проще, чем рекурсивный компонент)
const rows = computed<FlatNode[]>(() => {
  const out: FlatNode[] = []
  const visit = (parentId: number, depth: number) => {
    const children = byId.value.get(parentId) ?? []
    children.forEach((t) => {
      const kids = byId.value.get(t.id) ?? []
      const progress = subtreeProgress(t.id)
      out.push({ task: t, depth, hasChildren: kids.length > 0, ...progress })
      if (kids.length > 0 && (expanded.value[t.id] ?? true)) visit(t.id, depth + 1)
    })
  }
  visit(props.rootId, 0)
  return out
})

function toggle(task: Task) {
  expanded.value[task.id] = !(expanded.value[task.id] ?? true)
}

// Меню «⋯»: смена статуса (отмечен текущий), подзадача, удаление
function taskMenu(task: Task) {
  return [
    ...statusOptions().map((o) => ({
      label: o.label,
      icon: o.value === task.status ? 'ph-check' : undefined,
      onSelect: () => emit('status-change', task, o.value),
    })),
    { label: t('tree.addSubtask'), icon: 'ph-plus', onSelect: () => emit('add-subtask', task) },
    { label: t('common.delete'), icon: 'ph-trash', danger: true, onSelect: () => emit('delete', task) },
  ]
}
</script>

<template>
  <div class="tree">
    <div
      v-for="row in rows"
      :key="row.task.id"
      class="node"
      :class="{ 'is-child': row.depth > 0 }"
      :style="{ marginLeft: row.depth * 20 + 'px' }"
    >
      <div class="node-main">
        <GnIconButton
          v-if="row.hasChildren"
          class="caret"
          :icon="expanded[row.task.id] ?? true ? 'ph-caret-down' : 'ph-caret-right'"
          :label="expanded[row.task.id] ?? true ? t('tree.collapse') : t('tree.expand')"
          size="sm"
          @click="toggle(row.task)"
        />
        <span v-else class="leaf-space" />
        <RouterLink class="title" :class="{ done: row.task.status === 'done' }" :to="`/tasks/${row.task.id}`">
          {{ row.task.title }}
        </RouterLink>
        <GnBadge v-if="row.total > 0" variant="neutral" icon="ph-tree-structure">
          {{ row.done }}/{{ row.total }}
        </GnBadge>
        <GnDropdown class="node-menu" :items="taskMenu(row.task)">
          <template #trigger="{ toggle }">
            <GnIconButton icon="ph-dots-three-outline" :label="t('common.edit')" @click="toggle" />
          </template>
        </GnDropdown>
      </div>
      <div class="node-meta">
        <TaskBadges :task="row.task" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.tree {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
/* Линия связи: горизонтальный усик к каждому дочернему узлу */
.node {
  position: relative;
  border: 1px solid var(--border, #2a2f47);
  border-radius: 8px;
  padding: 0.4rem 0.6rem;
  background: var(--surface, transparent);
}
.node.is-child::before {
  content: '';
  position: absolute;
  left: -20px;
  top: 1.4rem;
  width: 16px;
  height: 2px;
  background: var(--border, #2a2f47);
}
.node-main {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}
.caret {
  flex: none;
}
.leaf-space {
  width: 28px;
  flex: none;
}
.title {
  flex: 1;
  min-width: 0;
  font-weight: 600;
  color: inherit;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.title:hover {
  color: var(--accent, #7aa2f7);
}
.title.done {
  text-decoration: line-through;
  color: var(--text-muted, #888);
}
.node-menu {
  flex: none;
}
.node-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 0.3rem;
  align-items: center;
  margin-top: 0.4rem;
  padding-left: 2.4rem;
}
@media (max-width: 480px) {
  .node {
    margin-left: 0 !important;
  }
  /* на узком экране отступов нет — усик торчал бы за край */
  .node.is-child::before {
    display: none;
  }
  .node-meta {
    padding-left: 0;
  }
}
</style>