forked from MrLesk/Backlog.md
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.ts
More file actions
333 lines (282 loc) · 10.8 KB
/
Copy pathboard.ts
File metadata and controls
333 lines (282 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import type { Milestone, Task } from "./types/index.ts";
export interface BoardOptions {
statuses?: string[];
}
export type BoardLayout = "horizontal" | "vertical";
export type BoardFormat = "terminal" | "markdown";
export function buildKanbanStatusGroups(
tasks: Task[],
statuses: string[],
): { orderedStatuses: string[]; groupedTasks: Map<string, Task[]> } {
const canonicalByLower = new Map<string, string>();
const orderedConfiguredStatuses: string[] = [];
const configuredSeen = new Set<string>();
for (const status of statuses ?? []) {
if (typeof status !== "string") continue;
const trimmed = status.trim();
if (!trimmed) continue;
const lower = trimmed.toLowerCase();
if (!canonicalByLower.has(lower)) {
canonicalByLower.set(lower, trimmed);
}
if (!configuredSeen.has(trimmed)) {
orderedConfiguredStatuses.push(trimmed);
configuredSeen.add(trimmed);
}
}
const groupedTasks = new Map<string, Task[]>();
for (const status of orderedConfiguredStatuses) {
groupedTasks.set(status, []);
}
for (const task of tasks) {
const raw = (task.status ?? "").trim();
if (!raw) continue;
const canonical = canonicalByLower.get(raw.toLowerCase()) ?? raw;
if (!groupedTasks.has(canonical)) {
groupedTasks.set(canonical, []);
}
groupedTasks.get(canonical)?.push(task);
}
const orderedStatuses: string[] = [];
const seen = new Set<string>();
for (const status of orderedConfiguredStatuses) {
if (seen.has(status)) continue;
orderedStatuses.push(status);
seen.add(status);
}
for (const status of groupedTasks.keys()) {
if (seen.has(status)) continue;
orderedStatuses.push(status);
seen.add(status);
}
return { orderedStatuses, groupedTasks };
}
export function generateKanbanBoardWithMetadata(tasks: Task[], statuses: string[], projectName: string): string {
// Generate timestamp
const now = new Date();
const timestamp = now.toISOString().replace("T", " ").substring(0, 19);
const { orderedStatuses, groupedTasks } = buildKanbanStatusGroups(tasks, statuses);
// Create header
const header = `# Kanban Board Export (powered by Backlog.md)
Generated on: ${timestamp}
Project: ${projectName}
`;
// Return early if there are no configured statuses and no tasks
if (orderedStatuses.length === 0) {
return `${header}No tasks found.`;
}
// Create table header
const headerRow = `| ${orderedStatuses.map((status) => status || "No Status").join(" | ")} |`;
const separatorRow = `| ${orderedStatuses.map(() => "---").join(" | ")} |`;
// Map for quick lookup by id
const byId = new Map<string, Task>(tasks.map((t) => [t.id, t]));
// Group tasks by status and handle parent-child relationships
const columns: Task[][] = orderedStatuses.map((status) => {
const items = groupedTasks.get(status) || [];
const top: Task[] = [];
const children = new Map<string, Task[]>();
// Sort items: All columns by updatedDate descending (fallback to createdDate), then by ID as secondary
const sortedItems = items.sort((a, b) => {
// Primary sort: updatedDate (newest first), fallback to createdDate if updatedDate is missing
const dateA = a.updatedDate ? new Date(a.updatedDate).getTime() : new Date(a.createdDate).getTime();
const dateB = b.updatedDate ? new Date(b.updatedDate).getTime() : new Date(b.createdDate).getTime();
if (dateB !== dateA) {
return dateB - dateA; // Newest first
}
// Secondary sort: ID descending when dates are equal
const idA = Number.parseInt(a.id.replace("task-", ""), 10);
const idB = Number.parseInt(b.id.replace("task-", ""), 10);
return idB - idA; // Highest ID first (newest)
});
// Separate top-level tasks from subtasks
for (const t of sortedItems) {
const parent = t.parentTaskId ? byId.get(t.parentTaskId) : undefined;
if (parent && parent.status === t.status) {
// Subtask with same status as parent - group under parent
const list = children.get(parent.id) || [];
list.push(t);
children.set(parent.id, list);
} else {
// Top-level task or subtask with different status
top.push(t);
}
}
// Build final list with subtasks nested under parents
const result: Task[] = [];
for (const t of top) {
result.push(t);
const subs = children.get(t.id) || [];
subs.sort((a, b) => {
const idA = Number.parseInt(a.id.replace("task-", ""), 10);
const idB = Number.parseInt(b.id.replace("task-", ""), 10);
return idA - idB; // Subtasks in ascending order
});
result.push(...subs);
}
return result;
});
const maxTasks = Math.max(...columns.map((c) => c.length), 0);
const rows = [headerRow, separatorRow];
for (let taskIdx = 0; taskIdx < maxTasks; taskIdx++) {
const row = orderedStatuses.map((_, cIdx) => {
const task = columns[cIdx]?.[taskIdx];
if (!task || !task.id || !task.title) return "";
// Check if this is a subtask
const isSubtask = task.parentTaskId;
const taskIdPrefix = isSubtask ? "└─ " : "";
const taskIdUpper = task.id.toUpperCase();
// Format assignees in brackets or empty string if none
// Add @ prefix only if not already present
const assigneesText =
task.assignee && task.assignee.length > 0
? ` [${task.assignee.map((a) => (a.startsWith("@") ? a : `@${a}`)).join(", ")}]`
: "";
// Format labels with # prefix and italic or empty string if none
const labelsText =
task.labels && task.labels.length > 0 ? `<br>*${task.labels.map((label) => `#${label}`).join(" ")}*` : "";
return `${taskIdPrefix}**${taskIdUpper}** - ${task.title}${assigneesText}${labelsText}`;
});
rows.push(`| ${row.join(" | ")} |`);
}
const table = `${rows.join("\n")}`;
if (maxTasks === 0) {
return `${header}${table}\n\nNo tasks found.\n`;
}
return `${header}${table}\n`;
}
export function generateMilestoneGroupedBoard(
tasks: Task[],
statuses: string[],
milestoneEntities: Milestone[],
projectName: string,
): string {
const now = new Date();
const timestamp = now.toISOString().replace("T", " ").substring(0, 19);
// Collect canonical milestone identifiers from milestone files and tasks.
// Task values can be either IDs or titles, so normalize aliases to one key.
const milestoneSeen = new Set<string>();
const allMilestones: string[] = [];
const aliasToMilestone = new Map<string, string>();
const milestoneLabelsByKey = new Map<string, string>();
const titleCounts = new Map<string, number>();
for (const milestone of milestoneEntities) {
const titleKey = milestone.title.trim().toLowerCase();
if (!titleKey) continue;
titleCounts.set(titleKey, (titleCounts.get(titleKey) ?? 0) + 1);
}
for (const milestone of milestoneEntities) {
const normalizedId = milestone.id.trim();
const normalizedTitle = milestone.title.trim();
const idKey = normalizedId.toLowerCase();
if (normalizedId && !milestoneSeen.has(idKey)) {
milestoneSeen.add(idKey);
allMilestones.push(normalizedId);
}
if (normalizedId) {
aliasToMilestone.set(idKey, normalizedId);
const idAliasMatch = normalizedId.match(/^m-(\d+)$/i);
if (idAliasMatch?.[1]) {
const numericAlias = String(Number.parseInt(idAliasMatch[1], 10));
aliasToMilestone.set(`m-${numericAlias}`, normalizedId);
if (!aliasToMilestone.has(numericAlias)) {
aliasToMilestone.set(numericAlias, normalizedId);
}
}
}
if (normalizedTitle) {
const titleKey = normalizedTitle.toLowerCase();
if (titleCounts.get(titleKey) === 1 && !aliasToMilestone.has(titleKey)) {
aliasToMilestone.set(titleKey, normalizedId || normalizedTitle);
}
milestoneLabelsByKey.set(idKey, normalizedTitle);
if (titleCounts.get(titleKey) === 1 && !milestoneLabelsByKey.has(titleKey)) {
milestoneLabelsByKey.set(titleKey, normalizedTitle);
}
}
}
const canonicalizeMilestone = (value?: string | null): string => {
const normalized = value?.trim();
if (!normalized) return "";
const direct = aliasToMilestone.get(normalized.toLowerCase());
if (direct) {
return direct;
}
const idMatch = normalized.match(/^m-(\d+)$/i);
if (idMatch?.[1]) {
const numericAlias = String(Number.parseInt(idMatch[1], 10));
return aliasToMilestone.get(`m-${numericAlias}`) ?? aliasToMilestone.get(numericAlias) ?? normalized;
}
if (/^\d+$/.test(normalized)) {
const numericAlias = String(Number.parseInt(normalized, 10));
return aliasToMilestone.get(`m-${numericAlias}`) ?? aliasToMilestone.get(numericAlias) ?? normalized;
}
return normalized;
};
for (const task of tasks) {
const canonicalMilestone = canonicalizeMilestone(task.milestone);
if (canonicalMilestone && !milestoneSeen.has(canonicalMilestone.toLowerCase())) {
milestoneSeen.add(canonicalMilestone.toLowerCase());
allMilestones.push(canonicalMilestone);
}
}
const header = `# Kanban Board by Milestone (powered by Backlog.md)
Generated on: ${timestamp}
Project: ${projectName}
`;
const sections: string[] = [];
// No milestone section
const noMilestoneTasks = tasks.filter((t) => !t.milestone?.trim());
if (noMilestoneTasks.length > 0) {
sections.push(generateMilestoneSection("No Milestone", noMilestoneTasks, statuses));
}
// Each milestone section
for (const milestone of allMilestones) {
const milestoneTasks = tasks.filter(
(task) => canonicalizeMilestone(task.milestone).toLowerCase() === milestone.toLowerCase(),
);
if (milestoneTasks.length > 0) {
const milestoneLabel = milestoneLabelsByKey.get(milestone.toLowerCase()) ?? milestone;
sections.push(generateMilestoneSection(milestoneLabel, milestoneTasks, statuses));
}
}
if (sections.length === 0) {
return `${header}No tasks found.\n`;
}
return `${header}${sections.join("\n\n")}\n`;
}
function generateMilestoneSection(milestone: string, tasks: Task[], statuses: string[]): string {
const { orderedStatuses, groupedTasks } = buildKanbanStatusGroups(tasks, statuses);
const sectionHeader = `## ${milestone} (${tasks.length} tasks)\n`;
if (orderedStatuses.length === 0) {
return `${sectionHeader}\nNo tasks.\n`;
}
const statusLines = orderedStatuses.map((status) => {
const statusTasks = groupedTasks.get(status) || [];
const taskLines = statusTasks.map((t) => {
const id = t.id.toUpperCase();
const assignees = t.assignee?.length ? ` [@${t.assignee.join(", @")}]` : "";
return ` - **${id}** - ${t.title}${assignees}`;
});
return `### ${status} (${statusTasks.length})\n${taskLines.length > 0 ? taskLines.join("\n") : " (empty)"}`;
});
return `${sectionHeader}\n${statusLines.join("\n\n")}`;
}
export async function exportKanbanBoardToFile(
tasks: Task[],
statuses: string[],
filePath: string,
projectName: string,
_overwrite = false,
): Promise<void> {
const board = generateKanbanBoardWithMetadata(tasks, statuses, projectName);
// Ensure directory exists
try {
await mkdir(dirname(filePath), { recursive: true });
} catch {
// Directory might already exist
}
// Write the content (overwrite mode)
await Bun.write(filePath, board);
}