Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

fix: #119

Nikolai Giman511337fd5402
diff --git a/web/src/components/features/graph/ProjectGraph.vue b/web/src/components/features/graph/ProjectGraph.vue
index 0013f5d..803b0c4 100644
--- a/web/src/components/features/graph/ProjectGraph.vue
+++ b/web/src/components/features/graph/ProjectGraph.vue
@@ -88,15 +88,18 @@ import {
PanOnScrollMode,
useVueFlow,
VueFlow,
+ type XYPosition,
} from '@vue-flow/core'
import { nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
+import { storeToRefs } from 'pinia'
import { useGraphStore } from '@/stores/graph.store'
import type { TaskItem } from '@/types/tasks.types'
+import type { GraphDirection } from '@/types/graph.types'
import { useGoalPermissions } from '@/composables/useGoalPermissions'
import { useAppRouteInfo } from '@/composables/useAppRouteInfo'
import AddNewTaskToGraph from './AddNewTaskToGraph.vue'
-import { useLayout } from './composables/useLayout'
+import { layoutCenter, useLayout } from './composables/useLayout'
import TaskNode from './TaskNode.vue'
const listIds = defineModel<number[]>('listIds', { default: () => [] })
@@ -129,7 +132,8 @@ watch(assigneeIds, applyFilters, { deep: true })
watch(sprintId, applyFilters)
const {
- fitView,
+ setCenter,
+ onPaneReady,
onConnect,
addEdges,
onEdgesChange,
@@ -142,10 +146,13 @@ const {
const { projectId } = useAppRouteInfo()
const { layout } = useLayout()
const store = useGraphStore()
+const { direction: layoutDirection } = storeToRefs(store)
const { t } = useI18n()
const { canManageGraph, canViewGraph } = useGoalPermissions()
const layoutReady = ref(false)
+// A center asked for before the pane was ready, applied once it is
+const pendingCenter = ref<XYPosition | null>(null)
const addNewTaskToGraph = ref(false)
const currentSession = ref<number | null>(null)
@@ -167,7 +174,6 @@ const defaultEdgeOptions: DefaultEdgeOptions = {
}
const selectedEdge = ref<Edge | null>(null)
-const layoutDirection = ref<'LR' | 'TB'>('TB')
watch(
projectId,
@@ -290,11 +296,25 @@ const deleteSelectedEdge = async (id: number) => {
removeEdges([id.toString()])
}
-const layoutGraph = async (direction: 'LR' | 'TB') => {
+// The graph opens at 1:1 around its middle, not fitted as a whole: fitting would
+// render every node and defeat only-render-visible-elements. The fit button in
+// Controls is still there to see the whole graph
+const showLayoutCenter = async () => {
+ const center = layoutCenter(store.nodes)
+ pendingCenter.value = (await setCenter(center.x, center.y, { zoom: 1 })) ? null : center
+}
+
+onPaneReady(() => {
+ if (!pendingCenter.value) return
+ setCenter(pendingCenter.value.x, pendingCenter.value.y, { zoom: 1 })
+ pendingCenter.value = null
+})
+
+const layoutGraph = async (direction: GraphDirection) => {
layoutDirection.value = direction
store.nodes = layout(store.nodes, store.edges, direction)
- nextTick(() => {
- fitView()
+ nextTick(async () => {
+ await showLayoutCenter()
layoutReady.value = true
})
}
diff --git a/web/src/components/features/graph/composables/useLayout.ts b/web/src/components/features/graph/composables/useLayout.ts
index ab908f7..2e617b2 100644
--- a/web/src/components/features/graph/composables/useLayout.ts
+++ b/web/src/components/features/graph/composables/useLayout.ts
@@ -1,5 +1,6 @@
import dagre from '@dagrejs/dagre'
-import { type Edge, type Node, Position } from '@vue-flow/core'
+import { type Edge, type GraphNode, type Node, Position, type XYPosition } from '@vue-flow/core'
+import type { GraphPlaceNodeNearArgs } from '@/types/graph.types'
const NODE_WIDTH = 288 // w-72 wrapper in TaskNode
const NODE_MIN_HEIGHT = 74 // checkbox + priority column with paddings
@@ -19,6 +20,9 @@ const BADGE_CHROME_WIDTH = 34 // badge paddings + icon
const BADGE_CHAR_WIDTH = 6.5
const BADGE_GAP = 8
+export const NODE_SEP = 50 // minimum space between nodes of one rank
+export const RANK_SEP = 100 // minimum space between ranks
+
const ISOLATED_GAP_X = 40
const ISOLATED_GAP_Y = 32
const ISOLATED_BLOCK_OFFSET = 120
@@ -27,7 +31,7 @@ const ISOLATED_MIN_ROW_WIDTH = 1200
// Estimates the rendered TaskNode size from task data alone, so the layout can
// run before (and without) rendering every node — a prerequisite for
// only-render-visible-elements, where offscreen nodes are never measured.
-function estimateNodeSize(node: Node): { width: number; height: number } {
+export function estimateNodeSize(node: Pick<Node, 'data'>): { width: number; height: number } {
const task = node.data?.task
if (!task) return { width: NODE_WIDTH, height: NODE_MIN_HEIGHT }
@@ -64,6 +68,75 @@ function estimateNodeSize(node: Node): { width: number; height: number } {
return { width: NODE_WIDTH, height: Math.max(NODE_MIN_HEIGHT, height) + NODE_SAFETY }
}
+// The rendered size once vue-flow has measured the node, the estimate before that
+export function nodeSize(node: Node): { width: number; height: number } {
+ const { dimensions } = node as Partial<GraphNode>
+ if (dimensions?.width && dimensions.height) return { width: dimensions.width, height: dimensions.height }
+ return estimateNodeSize(node)
+}
+
+// Center of the node closest to the middle of the laid-out graph. The middle itself can
+// be empty (say, between the linked graph and the grid of isolated tasks below it), the
+// node never is. Read from positions and estimates only, so it does not depend on what
+// vue-flow has measured so far
+export function layoutCenter(nodes: Node[]): XYPosition {
+ if (!nodes.length) return { x: 0, y: 0 }
+ const rects = nodes.map((node) => ({ ...node.position, ...estimateNodeSize(node) }))
+ const centers = rects.map((rect) => ({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }))
+ const left = Math.min(...rects.map((rect) => rect.x))
+ const top = Math.min(...rects.map((rect) => rect.y))
+ const right = Math.max(...rects.map((rect) => rect.x + rect.width))
+ const bottom = Math.max(...rects.map((rect) => rect.y + rect.height))
+ const middle = { x: (left + right) / 2, y: (top + bottom) / 2 }
+ const distance = (point: XYPosition) => Math.hypot(point.x - middle.x, point.y - middle.y)
+ return centers.reduce((closest, point) => (distance(point) < distance(closest) ? point : closest))
+}
+
+// The spot one rank before or after the anchor, centered on it; when that spot is taken
+// it slides along the rank to the nearest free one. Successors go right in LR and up in TB
+// (the TB layout is inverted: roots sit at the bottom, matching TaskNode's handles)
+export function placeNodeNear({ anchor, node, side, direction, obstacles }: GraphPlaceNodeNearArgs): XYPosition {
+ const anchorSize = nodeSize(anchor)
+ const size = estimateNodeSize(node)
+ const isHorizontal = direction === 'LR'
+ const towardsEnd = isHorizontal ? side === 'after' : side === 'before'
+
+ const origin = isHorizontal
+ ? {
+ x: towardsEnd ? anchor.position.x + anchorSize.width + RANK_SEP : anchor.position.x - RANK_SEP - size.width,
+ y: anchor.position.y + (anchorSize.height - size.height) / 2,
+ }
+ : {
+ x: anchor.position.x + (anchorSize.width - size.width) / 2,
+ y: towardsEnd ? anchor.position.y + anchorSize.height + RANK_SEP : anchor.position.y - RANK_SEP - size.height,
+ }
+
+ const rects = obstacles.map((item) => ({ ...item.position, ...nodeSize(item) }))
+ const isFree = (position: XYPosition) =>
+ rects.every(
+ (rect) =>
+ position.x + size.width + NODE_SEP <= rect.x ||
+ rect.x + rect.width + NODE_SEP <= position.x ||
+ position.y + size.height + NODE_SEP <= rect.y ||
+ rect.y + rect.height + NODE_SEP <= position.y,
+ )
+
+ // The nearest free spot is either the centered one or flush against a side of some node
+ const axis = isHorizontal ? 'y' : 'x'
+ const extent = isHorizontal ? 'height' : 'width'
+ const candidates = [origin[axis]]
+ for (const rect of rects) {
+ candidates.push(rect[axis] - NODE_SEP - size[extent], rect[axis] + rect[extent] + NODE_SEP)
+ }
+ candidates.sort((a, b) => Math.abs(a - origin[axis]) - Math.abs(b - origin[axis]))
+
+ for (const value of candidates) {
+ const position = { ...origin, [axis]: value }
+ if (isFree(position)) return position
+ }
+ return origin
+}
+
/**
* Composable to run the layout algorithm on the graph.
* Connected nodes are laid out with `dagre`; isolated nodes (no edges) are
@@ -84,8 +157,8 @@ export function useLayout() {
dagreGraph.setDefaultEdgeLabel(() => ({}))
dagreGraph.setGraph({
rankdir: direction,
- nodesep: 50, // Minimum space between nodes
- ranksep: 100, // Minimum space between ranks
+ nodesep: NODE_SEP,
+ ranksep: RANK_SEP,
marginx: 20,
marginy: 20,
})
@@ -165,7 +238,13 @@ export function useLayout() {
}
})
- return [...layoutedConnected, ...layoutedIsolated]
+ // vue-flow merges these into its nodes and refreshes computedPosition only for
+ // rendered ones, yet culls by computedPosition under only-render-visible-elements:
+ // a stale one would keep a node that moved into view from ever rendering
+ return [...layoutedConnected, ...layoutedIsolated].map((node) => ({
+ ...node,
+ computedPosition: { z: (node as Partial<GraphNode>).computedPosition?.z ?? 0, ...node.position },
+ }))
}
return { layout }
diff --git a/web/src/components/features/tasks/parts/TaskDependencies.types.ts b/web/src/components/features/tasks/parts/TaskDependencies.types.ts
index de46f0a..a3bac31 100644
--- a/web/src/components/features/tasks/parts/TaskDependencies.types.ts
+++ b/web/src/components/features/tasks/parts/TaskDependencies.types.ts
@@ -1,3 +1,6 @@
+import type { Task } from 'taskview-api'
+import type { GraphPlacementSide } from '@/types/graph.types'
+
export type DependencyTask = {
id: number
description: string
@@ -14,3 +17,8 @@ export type DependencyEdgeAddArgs = {
target: number
task: DependencyTask
}
+
+export type DependencyPlaceOnGraphArgs = {
+ task: Task
+ side: GraphPlacementSide
+}
diff --git a/web/src/components/features/tasks/parts/TaskDependencies.vue b/web/src/components/features/tasks/parts/TaskDependencies.vue
index 53054fe..fa146ac 100644
--- a/web/src/components/features/tasks/parts/TaskDependencies.vue
+++ b/web/src/components/features/tasks/parts/TaskDependencies.vue
@@ -17,6 +17,7 @@
:can-manage="canManageGraph"
@open="openTask"
@add="(task) => addEdge({ source: task.id, target: taskId, task })"
+ @created="(task) => placeOnGraph({ task, side: 'before' })"
@remove="removeEdge"
/>
@@ -37,6 +38,7 @@
:can-manage="canManageGraph"
@open="openTask"
@add="(task) => addEdge({ source: taskId, target: task.id, task })"
+ @created="(task) => placeOnGraph({ task, side: 'after' })"
@remove="removeEdge"
/>
</div>
@@ -51,8 +53,9 @@ import { $tvApi } from '@/plugins/axios'
import { logError } from '@/helpers/Helper'
import { useGoalPermissions } from '@/composables/useGoalPermissions'
import { useTaskDetailPanel } from '@/composables/useTaskDetailPanel'
+import { useGraphStore } from '@/stores/graph.store'
import TaskDependencyGroup from './TaskDependencyGroup.vue'
-import type { DependencyEdgeAddArgs, DependencyEntry, DependencyTask } from './TaskDependencies.types'
+import type { DependencyEdgeAddArgs, DependencyEntry, DependencyPlaceOnGraphArgs, DependencyTask } from './TaskDependencies.types'
const props = defineProps<{
taskId: number
@@ -63,6 +66,7 @@ const { t } = useI18n()
const toast = useToast()
const { canViewGraph, canManageGraph } = useGoalPermissions()
const { openTask } = useTaskDetailPanel()
+const graphStore = useGraphStore()
const edges = ref<GraphResponseAddEdge[]>([])
const taskNames = ref(new Map<number, DependencyTask>())
@@ -120,11 +124,21 @@ async function addEdge({ source, target, task }: DependencyEdgeAddArgs) {
}
taskNames.value.set(task.id, task)
edges.value.push(edge)
+ graphStore.insertEdge(edge)
+}
+
+// A task created from the picker goes onto the open graph right next to this task,
+// before its edge is added, so the edge has both ends on screen
+function placeOnGraph({ task, side }: DependencyPlaceOnGraphArgs) {
+ const position = graphStore.positionNear({ taskId: props.taskId, task, side })
+ graphStore.insertTask({ task, position })
+ if (position) void graphStore.updateTaskPosition({ id: task.id, nodeGraphPosition: position })
}
async function removeEdge(edgeId: number) {
const result = await $tvApi.graph.deleteEdge(edgeId).catch((err: unknown) => logError(err))
if (!result) return
edges.value = edges.value.filter((e) => e.id !== edgeId)
+ graphStore.removeEdge(edgeId)
}
</script>
diff --git a/web/src/components/features/tasks/parts/TaskDependencyGroup.vue b/web/src/components/features/tasks/parts/TaskDependencyGroup.vue
index c738ec8..baec551 100644
--- a/web/src/components/features/tasks/parts/TaskDependencyGroup.vue
+++ b/web/src/components/features/tasks/parts/TaskDependencyGroup.vue
@@ -57,6 +57,7 @@
:goal-id="goalId"
:excluded-ids="excludedIds"
@select="(task) => $emit('add', task)"
+ @created="(task) => $emit('created', task)"
/>
</div>
</div>
@@ -64,6 +65,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
+import type { Task } from 'taskview-api'
import TaskDependencyPicker from './TaskDependencyPicker.vue'
import type { DependencyEntry, DependencyTask } from './TaskDependencies.types'
@@ -80,6 +82,7 @@ defineProps<{
defineEmits<{
open: [taskId: number]
add: [task: DependencyTask]
+ created: [task: Task]
remove: [edgeId: number]
}>()
diff --git a/web/src/components/features/tasks/parts/TaskDependencyPicker.vue b/web/src/components/features/tasks/parts/TaskDependencyPicker.vue
index c323ed3..68e5323 100644
--- a/web/src/components/features/tasks/parts/TaskDependencyPicker.vue
+++ b/web/src/components/features/tasks/parts/TaskDependencyPicker.vue
@@ -76,7 +76,7 @@
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDebounceFn } from '@vueuse/core'
-import { ALL_TASKS_LIST_ID } from 'taskview-api'
+import { ALL_TASKS_LIST_ID, type Task } from 'taskview-api'
import { $tvApi } from '@/plugins/axios'
import { logError } from '@/helpers/Helper'
import { useGoalPermissions } from '@/composables/useGoalPermissions'
@@ -89,6 +89,7 @@ const props = defineProps<{
const emit = defineEmits<{
select: [task: DependencyTask]
+ created: [task: Task]
}>()
const { t } = useI18n()
@@ -152,6 +153,7 @@ async function create() {
toast.add({ title: t('tasks.dependencies.createFailed'), color: 'error' })
return
}
+ emit('created', task)
pick({ id: task.id, description: task.description, complete: task.complete })
}
</script>
diff --git a/web/src/composables/useCentrifugo/handlers/tasks.ts b/web/src/composables/useCentrifugo/handlers/tasks.ts
index 5e97341..123399a 100644
--- a/web/src/composables/useCentrifugo/handlers/tasks.ts
+++ b/web/src/composables/useCentrifugo/handlers/tasks.ts
@@ -54,7 +54,7 @@ function isShown(request: RealtimeTaskRefresh): boolean {
) {
return true
}
- return request.created && (Number(tasksStore.fetchRules.goalId) === request.goalId || kanbanStore.goalId === request.goalId)
+ return request.created && [Number(tasksStore.fetchRules.goalId), kanbanStore.goalId, useGraphStore().goalId].includes(request.goalId)
}
async function refreshTask(request: RealtimeTaskRefresh) {
@@ -74,7 +74,9 @@ async function refreshTask(request: RealtimeTaskRefresh) {
const kanbanStore = useKanbanStore()
kanbanStore.syncTask(task)
if (created) kanbanStore.insertTask(task)
- useGraphStore().syncTask(task)
+ const graphStore = useGraphStore()
+ graphStore.syncTask(task)
+ if (created) graphStore.insertTask({ task })
useBaseScreenStore().syncTask(task)
}
diff --git a/web/src/stores/graph.store.ts b/web/src/stores/graph.store.ts
index 4e63610..312a4e6 100644
--- a/web/src/stores/graph.store.ts
+++ b/web/src/stores/graph.store.ts
@@ -1,11 +1,13 @@
import { defineStore } from 'pinia'
-import type { GoalItem, GraphArgAddEdge, TaskArgUpdate } from 'taskview-api'
+import type { GoalItem, GraphArgAddEdge, GraphResponseAddEdge, TaskArgUpdate } from 'taskview-api'
+import { Position, type XYPosition } from '@vue-flow/core'
import { $tvApi } from '@/plugins/axios'
-import type { GraphStore } from '@/types/graph.types'
+import type { GraphDirection, GraphInsertTaskArgs, GraphPositionNearArgs, GraphStore } from '@/types/graph.types'
import type { TaskItem } from '@/types/tasks.types'
import { useGoalListsStore } from './goal-lists.store'
import { useTasksStore } from './tasks.store'
import { logError } from '@/helpers/Helper'
+import { placeNodeNear } from '@/components/features/graph/composables/useLayout'
export const useGraphStore = defineStore('use-graph-store', {
state: (): GraphStore => {
@@ -14,6 +16,8 @@ export const useGraphStore = defineStore('use-graph-store', {
edges: [],
allNodes: [],
allEdges: [],
+ goalId: null,
+ direction: 'TB',
}
},
actions: {
@@ -26,6 +30,7 @@ export const useGraphStore = defineStore('use-graph-store', {
async fetchAllTasksAndLists(goalId: GoalItem['id']): Promise<void> {
const { tasksStore, goalListsStore } = this.getStores()
+ this.goalId = goalId
await Promise.all([
goalListsStore.fetchLists(goalId),
@@ -45,33 +50,72 @@ export const useGraphStore = defineStore('use-graph-store', {
},
async addNode(task: TaskItem) {
+ if (this.hasTask(task.id)) return task.id.toString()
const node = {
id: task.id.toString(),
data: { task, label: `${task.description} == ${task.id}` },
position: task.nodeGraphPosition ?? { x: 0, y: 0 },
type: 'task',
style: { resize: 'none' as const },
+ ...this.handlePositions(this.direction),
}
this.allNodes.push({ ...node })
this.nodes.push(node)
return task.id.toString()
},
+ // A task created elsewhere (the task panel, another device) joins the graph of its project
+ insertTask({ task, position }: GraphInsertTaskArgs) {
+ if (task.goalId !== this.goalId) return
+ const nodeId = task.id.toString()
+ if (position) {
+ for (const node of [...this.allNodes, ...this.nodes]) {
+ if (node.id === nodeId) node.position = position
+ }
+ }
+ void this.addNode(position ? { ...task, nodeGraphPosition: position } : task)
+ },
+
+ // Where a new task goes next to one already shown, or null when that task is not on screen.
+ // Rendered nodes carry the laid-out positions; allNodes keeps the ones loaded from the server
+ positionNear({ taskId, task, side }: GraphPositionNearArgs): XYPosition | null {
+ const anchor = this.nodes.find((item) => item.id === taskId.toString())
+ if (!anchor) return null
+ return placeNodeNear({
+ anchor,
+ node: { data: { task } },
+ side,
+ direction: this.direction,
+ obstacles: this.nodes,
+ })
+ },
+
+ handlePositions(direction: GraphDirection) {
+ const isHorizontal = direction === 'LR'
+ return {
+ targetPosition: isHorizontal ? Position.Left : Position.Top,
+ sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
+ }
+ },
+
async addEdge(data: GraphArgAddEdge) {
const result = await $tvApi.graph.addEdge(data).catch((err: unknown) => logError(err))
if (!result) return
+ return this.insertEdge(result)
+ },
- const edge = result
-
+ // An edge saved elsewhere shows up only when both of its tasks are on the loaded graph
+ insertEdge(edge: GraphResponseAddEdge) {
const newEdge = {
id: edge.id.toString(),
source: edge.fromTaskId.toString(),
target: edge.toTaskId.toString(),
}
+ if (!this.hasTask(edge.fromTaskId) || !this.hasTask(edge.toTaskId)) return newEdge
+ if (this.allEdges.some((item) => item.id === newEdge.id)) return newEdge
this.allEdges.push({ ...newEdge })
this.edges.push(newEdge)
-
return newEdge
},
@@ -103,6 +147,10 @@ export const useGraphStore = defineStore('use-graph-store', {
async deleteEdge(id: number) {
const result = await $tvApi.graph.deleteEdge(id).catch((err: unknown) => logError(err))
if (!result) return
+ this.removeEdge(id)
+ },
+
+ removeEdge(id: number) {
const idStr = id.toString()
this.allEdges = this.allEdges.filter((e) => e.id !== idStr)
this.edges = this.edges.filter((e) => e.id !== idStr)
diff --git a/web/src/types/graph.types.ts b/web/src/types/graph.types.ts
index c73cd9c..a6ab10f 100644
--- a/web/src/types/graph.types.ts
+++ b/web/src/types/graph.types.ts
@@ -1,8 +1,35 @@
-import type { Edge, Node } from '@vue-flow/core'
+import type { Edge, Node, XYPosition } from '@vue-flow/core'
+import type { TaskItem } from './tasks.types'
+
+export type GraphDirection = 'LR' | 'TB';
+
+// Which side of an existing task a new one goes: before it (a predecessor) or after it (a successor)
+export type GraphPlacementSide = 'before' | 'after';
export type GraphStore = {
nodes: Node[];
edges: Edge[];
allNodes: Node[];
allEdges: Edge[];
+ goalId: number | null;
+ direction: GraphDirection;
+};
+
+export type GraphInsertTaskArgs = {
+ task: TaskItem;
+ position?: XYPosition | null;
+};
+
+export type GraphPositionNearArgs = {
+ taskId: number;
+ task: TaskItem;
+ side: GraphPlacementSide;
+};
+
+export type GraphPlaceNodeNearArgs = {
+ anchor: Node;
+ node: Pick<Node, 'data'>;
+ side: GraphPlacementSide;
+ direction: GraphDirection;
+ obstacles: Node[];
};