All files / kanbn/src/controller gantt.js

90.93% Statements 381/419
79.27% Branches 88/111
95.23% Functions 20/21
90.93% Lines 381/419

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 4201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 6x 6x     6x     6x 6x 1x 762x 762x 762x 762x 762x 762x 762x 762x 1x 5x 5x 5x 1x 8x 8x 8x 1x 2x 2x     2x 2x 2x 2x 2x 2x 2x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 6x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 1x 6x 6x 1x 1x 5x 5x 5x 5x 1x 807x 807x 373x 373x 434x 807x 807x 1x 6x 6x 762x 762x 3x 3x 759x 762x 762x 4x 4x 755x 762x 1x 1x 754x 762x 2x 2x 752x 752x 6x 6x 1x 5x 5x 635x 45x 45x 635x     590x 5x 5x 1x 5x 5x 10x 10x 10x 10x 55x 55x 55x 55x 55x 55x 55x 10x 10x 55x 5x 5x 55x 55x 55x 5x 5x 5x 50x 50x 50x 50x 10x 10x 5x 5x 10x     5x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 45x 45x 450x 450x 45x 5x 5x 5x 1x 5x 5x 3x 3x 2x 2x 2x 5x 1x                   1x 6x 6x 6x 6x   6x 1x 1x 10x 10x 10x 1x 1x 1x 9x 9x 9x 9x 10x 1x 1x 9x 9x 9x 10x 1x 1x 9x 9x 9x 10x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 8x 8x 8x 10x 3x 3x 1x 1x 1x 3x 7x 7x 7x 7x 7x 7x 2x 2x 2x 7x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x 5x 7x 7x   7x 1x  
const kanbn = require('../main');
const utility = require('../utility');
const formatDate = require('dateformat');
const chrono = require('chrono-node');
 
const NOW_MARKER = '┆';
const ANSI_RESET = '\x1b[0m';
const ANSI_FG_LINE = '\x1b[97m';
const ANSI_FG_NOW = '\x1b[90m';
const ANSI_BG_NOT_STARTED = '\x1b[100m';
const ANSI_BG_STARTED = '\x1b[44m';
const ANSI_BG_COMPLETED = '\x1b[42m';
 
const DIR_UP = 1;
const DIR_DOWN = 2;
const DIR_LEFT = 4;
const DIR_RIGHT = 8;
 
const LINE_CHARS = {
  [DIR_UP]: '│',
  [DIR_DOWN]: '│',
  [DIR_LEFT]: '─',
  [DIR_RIGHT]: '─',
  [DIR_UP | DIR_DOWN]: '│',
  [DIR_LEFT | DIR_RIGHT]: '─',
  [DIR_DOWN | DIR_RIGHT]: '┌',
  [DIR_DOWN | DIR_LEFT]: '┐',
  [DIR_UP | DIR_RIGHT]: '└',
  [DIR_UP | DIR_LEFT]: '┘',
  [DIR_UP | DIR_DOWN | DIR_RIGHT]: '├',
  [DIR_UP | DIR_DOWN | DIR_LEFT]: '┤',
  [DIR_UP | DIR_LEFT | DIR_RIGHT]: '┴',
  [DIR_DOWN | DIR_LEFT | DIR_RIGHT]: '┬',
  [DIR_UP | DIR_DOWN | DIR_LEFT | DIR_RIGHT]: '┼'
};
 
function getBarGeometry(task, from, to, width) {
  if (width <= 1 || from.getTime() === to.getTime()) {
    return { start: 0, end: 0 };
  }
 
  // Calculate the position in the chart
  const totalSpan = to.getTime() - from.getTime();
  const taskStartPos = Math.max(0, Math.round((task.start.getTime() - from.getTime()) / totalSpan * (width - 1)));
  const taskEndPos = Math.min(width - 1, Math.round((task.end.getTime() - from.getTime()) / totalSpan * (width - 1)));
 
  return {
    start: taskStartPos,
    end: taskEndPos
  };
}
 
function getBarBackground(task) {
  if (task.completed instanceof Date) {
    return ANSI_BG_COMPLETED;
  }
  if (task.started instanceof Date) {
    return ANSI_BG_STARTED;
  }
  return ANSI_BG_NOT_STARTED;
}
 
function createChartCell() {
  return {
    bg: null,
    lineMask: 0,
    arrowChar: null,
    markerChar: null
  };
}
 
function createChartGrid(height, width) {
  return Array.from({ length: height }, () => Array.from({ length: width }, createChartCell));
}
 
function addMask(cell, mask) {
  cell.lineMask |= mask;
}
 
function addHorizontalConnection(grid, row, fromCol, toCol) {
  if (fromCol === toCol) {
    return;
  }
 
  const step = fromCol < toCol ? 1 : -1;
  for (let col = fromCol; col !== toCol; col += step) {
    addMask(grid[row][col], step > 0 ? DIR_RIGHT : DIR_LEFT);
    addMask(grid[row][col + step], step > 0 ? DIR_LEFT : DIR_RIGHT);
  }
}
 
function addVerticalConnection(grid, col, fromRow, toRow) {
  if (fromRow === toRow) {
    return;
  }
 
  const step = fromRow < toRow ? 1 : -1;
  for (let row = fromRow; row !== toRow; row += step) {
    addMask(grid[row][col], step > 0 ? DIR_DOWN : DIR_UP);
    addMask(grid[row + step][col], step > 0 ? DIR_UP : DIR_DOWN);
  }
}
 
function routeDependency(grid, sourceRow, sourceCol, targetRow, targetCol) {
  if (sourceRow === null || targetRow === null) {
    return;
  }
 
  if (sourceRow === targetRow) {
    addHorizontalConnection(grid, sourceRow, sourceCol, targetCol);
    grid[targetRow][targetCol].arrowChar = targetCol >= sourceCol ? '→' : '←';
    return;
  }
 
  const moveRight = targetCol >= sourceCol;
  let routeCol = moveRight ? Math.max(sourceCol + 1, targetCol - 1) : Math.min(sourceCol - 1, targetCol + 1);
  routeCol = Math.max(0, Math.min(grid[0].length - 1, routeCol));
 
  addHorizontalConnection(grid, sourceRow, sourceCol, routeCol);
  addVerticalConnection(grid, routeCol, sourceRow, targetRow);
  addHorizontalConnection(grid, targetRow, routeCol, targetCol);
  grid[targetRow][targetCol].arrowChar = targetCol >= routeCol ? '→' : '←';
}
 
function setMarker(cell, markerChar) {
  if (!cell.arrowChar && !cell.markerChar) {
    cell.markerChar = markerChar;
  }
}
 
function routeIncomingExternalDependency(grid, row, targetCol) {
  const arrowCol = Math.max(0, targetCol);
  grid[row][arrowCol].arrowChar = '→';
 
  if (arrowCol > 0) {
    addMask(grid[row][arrowCol], DIR_LEFT);
    addMask(grid[row][arrowCol - 1], DIR_RIGHT);
  }
  if (arrowCol > 1) {
    setMarker(grid[row][arrowCol - 2], '…');
  }
}
 
function routeOutgoingExternalDependency(grid, row, sourceCol, width) {
  const arrowCol = Math.min(width - 1, sourceCol);
  grid[row][arrowCol].arrowChar = '→';
 
  if (arrowCol < width - 1) {
    addMask(grid[row][arrowCol], DIR_RIGHT);
    addMask(grid[row][arrowCol + 1], DIR_LEFT);
  }
  if (arrowCol < width - 2) {
    setMarker(grid[row][arrowCol + 2], '…');
  }
}
 
function buildDependencyOverlay(tasks, barGeometries, width) {
  const grid = createChartGrid(tasks.length, width);
  const taskRowMap = new Map(tasks.map((task, index) => [task.id, index]));
 
  tasks.forEach((task, targetRow) => {
    (task.dependencies || []).forEach((dependencyId) => {
      const sourceRow = taskRowMap.get(dependencyId);
      if (sourceRow === undefined) {
        return;
      }
 
      routeDependency(
        grid,
        sourceRow,
        barGeometries[sourceRow].end,
        targetRow,
        barGeometries[targetRow].start
      );
    });
 
    if (Array.isArray(task.externalIncomingDependencies) && task.externalIncomingDependencies.length > 0) {
      routeIncomingExternalDependency(grid, targetRow, barGeometries[targetRow].start);
    }
 
    if (Array.isArray(task.externalOutgoingDependents) && task.externalOutgoingDependents.length > 0) {
      routeOutgoingExternalDependency(grid, targetRow, barGeometries[targetRow].end, width);
    }
  });
 
  return grid;
}
 
function styleCell(char, fg = null, bg = null) {
  if (!fg && !bg) {
    return char;
  }
 
  return `${fg || ''}${bg || ''}${char}${ANSI_RESET}`;
}
 
function renderChartRow(gridRow, barGeometry, barBackground, nowPosition) {
  return gridRow.map((cell, column) => {
    const bg = column >= barGeometry.start && column <= barGeometry.end ? barBackground : null;
    if (cell.arrowChar) {
      return styleCell(cell.arrowChar, ANSI_FG_LINE, bg);
    }
 
    const lineChar = LINE_CHARS[cell.lineMask] || null;
    if (lineChar) {
      return styleCell(lineChar, ANSI_FG_LINE, bg);
    }
 
    if (cell.markerChar) {
      return styleCell(cell.markerChar, ANSI_FG_LINE, bg);
    }
 
    if (nowPosition === column) {
      return styleCell(NOW_MARKER, ANSI_FG_NOW, bg);
    }
 
    return styleCell(' ', null, bg);
  }).join('');
}
 
function renderTickRow(ticks, nowPosition) {
  return ticks.split('').map((char, column) => {
    if (char !== ' ') {
      return styleCell(char, ANSI_FG_LINE, null);
    }
    if (nowPosition === column) {
      return styleCell(NOW_MARKER, ANSI_FG_NOW, null);
    }
    return char;
  }).join('');
}
 
function getLabelPlacements(from, to, width, dateFormat, maxLabels) {
  for (let count = maxLabels; count >= 1; count--) {
    const placements = [];
    let previousEnd = -1;
 
    for (let i = 0; i < count; i++) {
      const ratio = count === 1 ? 0 : i / (count - 1);
      const position = Math.round(ratio * (width - 1));
      const value = new Date(from.getTime() + Math.round((to.getTime() - from.getTime()) * ratio));
      const label = formatDate(value, dateFormat);
 
      let start = position - Math.floor(label.length / 2);
      if (start < 0) {
        start = 0;
      }
      if (start + label.length > width) {
        start = Math.max(0, width - label.length);
      }
 
      const end = start + label.length - 1;
      if (i > 0 && start <= previousEnd + 1) {
        placements.length = 0;
        break;
      }
 
      placements.push({ position, start, label, end });
      previousEnd = end;
    }
 
    if (placements.length) {
      return placements;
    }
  }

  return [];
}
 
function renderXAxisLabels(from, to, width, dateFormat) {
  const sampleLabel = formatDate(from, dateFormat);
  const maxLabels = Math.max(1, Math.floor((width + 2) / (sampleLabel.length + 2)));
  const placements = getLabelPlacements(from, to, width, dateFormat, maxLabels);
 
  const ticks = Array(width).fill(' ');
  const labels = Array(width).fill(' ');
 
  for (const placement of placements) {
    ticks[placement.position] = '│';
    for (let i = 0; i < placement.label.length; i++) {
      labels[placement.start + i] = placement.label[i];
    }
  }
 
  return [ticks.join(''), labels.join('')];
}
 
function getNowPosition(from, to, width, now = new Date()) {
  if (now < from || now > to) {
    return null;
  }
 
  const totalSpan = to.getTime() - from.getTime();
  return Math.round((now.getTime() - from.getTime()) / totalSpan * (width - 1));
}
 
function renderNowOverlay(line, nowPosition) {
  if (nowPosition === null || nowPosition < 0 || nowPosition >= line.length) {
    return line;
  }

  const result = line.split('');
  result[nowPosition] = NOW_MARKER;
  return result.join('');
}
 
function truncateName(name, maxWidth) {
  if (name.length <= maxWidth) {
    return name;
  }
  return name.substring(0, maxWidth - 1) + '…';
}
 
module.exports = async args => {
 
  // Make sure kanbn has been initialised
  if (!await kanbn.initialised()) {
    utility.error('Kanbn has not been initialised in this folder\nTry running: {b}kanbn init{b}');
    return;
  }
  const index = await kanbn.getIndex();
 
  // Get assigned
  let assigned = null;
  if (args.assigned) {
    assigned = utility.strArg(args.assigned);
  }
 
  // Get columns
  let columns = null;
  if (args.column) {
    columns = utility.arrayArg(args.column);
  }
 
  // Get dates
  let dates = null;
  if (args.date) {
    dates = utility.arrayArg(args.date);
    if (dates.length) {
      for (let i = 0; i < dates.length; i++) {
        const dateValue = chrono.parseDate(dates[i]);
        if (dateValue === null) {
          utility.error('Unable to parse date');
          return;
        }
        dates[i] = dateValue;
      }
    }
  }
 
  // Get mocked now date
  let now = null;
  if (args.now) {
    now = chrono.parseDate(utility.strArg(args.now));
    if (now === null) {
      utility.error('Unable to parse now date');
      return;
    }
  }
 
  // Show gantt chart data
  kanbn
  .gantt(assigned, columns, dates, now)
  .then(data => {
    if (args.json) {
 
      // Output raw data
      console.log(JSON.stringify(data, null, 2));
    } else {
 
      // Render chart
      const dateFormat = kanbn.getDateFormat(index);
      const maxNameWidth = 16;
      const nowDate = now || new Date();
 
      // Keep each rendered task line within terminal width where possible.
      // Line shape: "<prefix> <name> │<bar>│" => maxNameWidth + barWidth + 5 columns.
      const terminalWidth = Number.isFinite(process.stdout.columns) && process.stdout.columns > 0
        ? process.stdout.columns
        : 120;
      const barWidth = Math.max(1, terminalWidth - maxNameWidth - 5);
      const nowPosition = getNowPosition(data.from, data.to, barWidth, nowDate);
      const barGeometries = data.tasks.map((task) => getBarGeometry(task, data.from, data.to, barWidth));
      const dependencyOverlay = buildDependencyOverlay(data.tasks, barGeometries, barWidth);
 
      // Render header
      console.log(`Gantt chart: ${formatDate(data.from, dateFormat)} to ${formatDate(data.to, dateFormat)}`);
      if (data.dependencyCycleDetected) {
        const cycleDescription = Array.isArray(data.dependencyCycleTaskIds) && data.dependencyCycleTaskIds.length
          ? ` Cycle: ${data.dependencyCycleTaskIds.join(' -> ')}.`
          : '';
        console.error(`Warning: dependency cycle detected; using fallback ordering for ${data.cycleFallbackTaskIds.length} task(s).${cycleDescription}`);
      }
      console.log('');
 
      // Render tasks with bars
      data.tasks.forEach((task, taskIndex) => {
        const prefix = task.blocked ? '⧗' : ' ';
        const truncatedName = truncateName(task.name, maxNameWidth);
        const bar = renderChartRow(
          dependencyOverlay[taskIndex],
          barGeometries[taskIndex],
          getBarBackground(task),
          nowPosition
        );
 
        console.log(`${prefix} ${truncatedName.padEnd(maxNameWidth)} │${bar}│`);
      });
 
      // Render x-axis
      const [ticks, labels] = renderXAxisLabels(data.from, data.to, barWidth, dateFormat);
      console.log(`  ${''.padEnd(maxNameWidth)}  ${renderTickRow(ticks, nowPosition)}`);
      console.log(`  ${''.padEnd(maxNameWidth)}  ${labels}`);
    }
  })
  .catch(error => {
    utility.error(error);
  });
};