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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 | 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 1x 1x 1x 1x 1x 8026x 8026x 8026x 8026x 7524x 7524x 502x 8026x 1x 1x 1x 1x 1x 1x 1x 90x 90x 90x 90x 90x 74x 74x 90x 90x 1x 1x 1x 1x 1x 1x 1x 309x 309x 309x 1x 1x 1x 1x 1x 1x 657x 657x 657x 657x 657x 1x 1x 1x 1x 1x 1x 119x 119x 119x 119x 1x 1x 1x 1x 1x 1x 1x 1x 187x 187x 327x 143x 143x 327x 44x 187x 1x 1x 1x 1x 1x 1x 1x 318x 318x 452x 318x 318x 452x 318x 1x 1x 1x 1x 1x 1x 1x 1x 1x 89x 89x 59x 89x 30x 30x 89x 89x 1x 1x 1x 1x 1x 1x 1x 63x 63x 218x 218x 63x 63x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 66x 66x 7x 7x 59x 66x 1x 1x 1x 1x 1x 1x 1x 1x 142x 142x 26x 26x 142x 2x 142x 140x 140x 142x 142x 1x 1x 1x 1x 1x 1x 1x 77x 77x 46x 46x 77x 77x 77x 77x 77x 77x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 125x 125x 125x 1x 1x 1x 1x 1x 1x 435x 435x 435x 1x 294x 294x 294x 1x 1x 1x 1x 1x 1x 1x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 23x 23x 16x 16x 16x 16x 16x 39x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 52x 52x 52x 52x 52x 18x 18x 18x 52x 52x 52x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 1x 1x 1x 1x 1x 1x 1x 55x 55x 55x 55x 55x 35x 35x 20x 55x 1x 1x 1x 1x 1x 1x 1x 48x 48x 126x 126x 126x 126x 126x 126x 9x 9x 117x 117x 117x 117x 117x 126x 4x 4x 117x 117x 126x 117x 117x 126x 117x 117x 126x 20x 20x 117x 117x 117x 126x 126x 117x 117x 117x 126x 126x 117x 117x 117x 126x 126x 117x 117x 117x 126x 10x 126x 7x 7x 117x 117x 126x 117x 117x 117x 126x 126x 117x 117x 117x 126x 126x 117x 117x 126x 117x 117x 126x 117x 117x 117x 126x 20x 126x 9x 9x 117x 117x 117x 126x 12x 12x 12x 12x 126x 7x 7x 117x 117x 126x 3x 3x 117x 117x 126x 1x 1x 117x 117x 117x 126x 126x 117x 117x 117x 126x 126x 117x 117x 126x 117x 117x 117x 126x 126x 117x 117x 126x 117x 117x 126x 25x 25x 23x 6x 23x 17x 17x 2x 1x 1x 2x 17x 6x 3x 3x 6x 17x 3x 1x 1x 3x 17x 6x 3x 3x 6x 17x 17x 17x 23x 25x 25x 117x 48x 48x 1x 1x 1x 1x 1x 1x 1x 89x 89x 6x 6x 89x 89x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 7x 7x 7x 7x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 163x 163x 163x 163x 163x 163x 163x 163x 42x 252x 36x 36x 36x 252x 42x 163x 129x 129x 163x 163x 1x 1x 1x 1x 1x 1x 1x 163x 163x 17x 17x 163x 163x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 84x 84x 36x 21x 21x 21x 23x 23x 23x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 1x 1x 6x 7x 7x 7x 7x 7x 6x 7x 7x 1x 1x 7x 6x 7x 1x 1x 1x 1x 1x 1x 1x 8x 8x 7x 7x 7x 25x 4x 4x 25x 2x 2x 25x 7x 7x 7x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 24x 24x 24x 6x 6x 18x 24x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 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 5x 5x 5x 1x 1x 1x 1x 4x 4x 5x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 9x 6x 6x 6x 6x 4x 6x 2x 1x 1x 1x 1x 2x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 7x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 38x 38x 38x 20x 38x 38x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 8x 8x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 11x 11x 11x 9x 9x 11x 11x 8x 19x 4x 4x 19x 19x 1x 1x 19x 19x 1x 1x 1x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 12x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 12x 89x 89x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 193x 193x 193x 193x 193x 193x 40x 40x 2x 2x 40x 38x 28x 28x 38x 40x 40x 40x 193x 193x 1x 1x 1x 22x 22x 22x 22x 1x 1x 1x 22x 21x 21x 21x 21x 22x 1x 1x 1x 1x 1x 1x 163x 163x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 3531x 3507x 3507x 1x 1x 1x 3507x 1x 1x 1x 1x 3507x 3507x 3531x 3531x 1x 1x 1x 1x 1x 496x 496x 1x 1x 1x 1x 1x 1x 1631x 1631x 14x 14x 1617x 1631x 1x 1x 1x 1x 1x 1x 856x 856x 8x 8x 848x 856x 1x 1x 1x 1x 1x 1x 681x 681x 2x 2x 679x 681x 1x 1x 1x 1x 1x 1x 25x 25x 25x 25x 1x 1x 1x 1x 1x 1x 1631x 1631x 1x 1x 1x 1x 1x 1x 856x 856x 1x 1x 1x 1x 1x 1x 681x 681x 1x 1x 1x 1x 1x 1x 25x 25x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 46x 46x 46x 1x 1x 1x 1x 1x 1x 1x 1x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 2x 16x 14x 14x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 2x 2x 16x 16x 16x 16x 16x 16x 16x 97x 97x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 1x 1x 1x 1x 1x 1x 163x 163x 4x 4x 4x 4x 4x 4x 4x 4x 4x 163x 163x 163x 163x 2x 2x 2x 163x 163x 163x 163x 1x 1x 1x 1x 1x 1x 302x 302x 302x 302x 302x 302x 302x 302x 302x 301x 302x 1x 1x 1x 1x 1x 1x 1x 126x 126x 1x 1x 1x 1x 1x 1x 1x 342x 342x 342x 342x 342x 342x 342x 1x 1x 1x 1x 1x 1x 1x 1x 65x 65x 65x 185x 185x 65x 65x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 345x 345x 1x 1x 1x 1x 1x 1x 38x 38x 38x 38x 38x 37x 37x 38x 38x 38x 38x 37x 37x 38x 38x 38x 38x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 38x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 38x 38x 1x 1x 1x 1x 1x 1x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 33x 33x 1x 1x 32x 32x 33x 2x 2x 30x 30x 30x 30x 33x 1x 1x 29x 29x 29x 33x 1x 1x 28x 28x 33x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 33x 33x 33x 33x 33x 27x 27x 27x 27x 27x 33x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 4x 4x 4x 5x 1x 1x 3x 3x 3x 5x 1x 1x 2x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 1x 1x 18x 18x 18x 19x 1x 1x 17x 17x 17x 19x 1x 1x 16x 16x 19x 1x 1x 15x 15x 15x 19x 2x 1x 1x 1x 1x 14x 14x 19x 14x 14x 14x 14x 14x 19x 19x 19x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 19x 4x 4x 4x 19x 10x 10x 14x 14x 14x 14x 19x 8x 8x 8x 10x 10x 8x 8x 8x 14x 19x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 1x 1x 6x 6x 6x 7x 1x 1x 5x 5x 5x 7x 1x 1x 4x 4x 4x 4x 7x 2x 2x 2x 2x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 60x 60x 1x 1x 59x 59x 59x 60x 1x 1x 58x 58x 58x 60x 1x 1x 57x 57x 60x 1x 1x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 60x 39x 39x 39x 39x 39x 39x 39x 56x 56x 56x 56x 56x 56x 56x 60x 27x 10x 10x 27x 27x 56x 56x 56x 56x 56x 56x 60x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 1x 1x 9x 9x 9x 9x 10x 2x 2x 7x 7x 7x 7x 7x 10x 6x 6x 7x 7x 10x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 1x 1x 24x 24x 24x 24x 24x 24x 24x 41x 24x 25x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 15x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 12x 12x 15x 4x 4x 4x 4x 15x 5x 5x 5x 5x 12x 12x 15x 11x 11x 11x 11x 11x 2x 2x 7x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 11x 11x 11x 11x 11x 11x 34x 34x 34x 34x 34x 11x 11x 11x 33x 33x 33x 33x 33x 11x 11x 11x 11x 11x 11x 11x 11x 34x 34x 34x 34x 34x 34x 34x 11x 11x 11x 11x 11x 34x 10x 4x 4x 4x 4x 4x 4x 10x 10x 10x 10x 34x 11x 11x 2x 2x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 11x 11x 11x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 11x 12x 15x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 3x 3x 5x 1x 1x 5x 1x 1x 1x 1x 1x 4x 4x 5x 1x 1x 3x 3x 3x 5x 9x 9x 6x 6x 9x 3x 3x 9x 3x 3x 3x 3x 3x 9x 3x 3x 5x 1x 1x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 24x 17x 17x 7x 7x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 7x 7x 6x 6x 24x 24x 12x 12x 12x 12x 12x 12x 5x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x 1x 1x 1x 5x 5x 3x 3x 3x 3x 3x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 1x 1x 14x 14x 14x 15x 1x 1x 13x 13x 15x 2x 1x 1x 2x 2x 2x 15x 11x 11x 11x 11x 13x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 3x 3x 3x 4x 2x 2x 3x 3x 3x 3x 3x 3x 4x 2x 4x 1x 1x 3x 3x 4x 1x 1x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 7x 7x 2x 2x 4x 4x 4x 4x 3x 3x 4x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 11x 11x 11x 11x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 1x 1x 1x 1x 1x 1x 4x 4x 9x 9x 3x 3x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 6x 6x 6x 12x 12x 12x 12x 12x 12x 6x 6x 6x 3x 3x 6x 9x 12x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 4x 4x 4x 5x 1x 1x 3x 3x 3x 5x 1x 1x 2x 2x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 3x 3x 3x 4x 1x 1x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 9x 9x 1x 1x 8x 8x 8x 9x 1x 1x 7x 7x 7x 9x 1x 1x 6x 6x 6x 6x 9x 1x 1x 5x 5x 9x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 9x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 1x 1x 10x 10x 10x 10x 10x 10x 10x 11x 1x 1x 9x 9x 11x 1x 1x 8x 8x 8x 11x 1x 1x 7x 7x 11x 1x 1x 6x 6x 6x 11x 1x 1x 5x 5x 5x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 5x 5x 5x 5x 5x 5x 5x 5x 5x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const fs = require("fs");
const path = require("path");
const glob = require("glob-promise");
const parseIndex = require("./parse-index");
const parseTask = require("./parse-task");
const utility = require("./utility");
const yaml = require("yamljs");
const humanizeDuration = require("humanize-duration");
const rimraf = require("rimraf");
const DEFAULT_FOLDER_NAME = ".kanbn";
const DEFAULT_INDEX_FILE_NAME = "index.md";
const DEFAULT_TASKS_FOLDER_NAME = "tasks";
const DEFAULT_ARCHIVE_FOLDER_NAME = "archive";
// Date normalisation intervals measured in milliseconds
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
// Default fallback values for index options
const DEFAULT_TASK_WORKLOAD = 2;
const DEFAULT_TASK_WORKLOAD_TAGS = {
Nothing: 0,
Tiny: 1,
Small: 2,
Medium: 3,
Large: 5,
Huge: 8,
};
const DEFAULT_DATE_FORMAT = "d mmm yy, H:MM";
// Metadata fields that hold a task's started and completed dates. Boards can override these with the
// startedField and completedField options, so that a task shared between several boards can carry
// separate started/completed state for each of them
const DEFAULT_STARTED_FIELD = "started";
const DEFAULT_COMPLETED_FIELD = "completed";
const DEFAULT_TASK_TEMPLATE = "^+^_${overdue ? '^R' : ''}${name}^: ${created ? ('\\n^-^/' + created) : ''}";
/**
* Default options for the initialise command
*/
const defaultInitialiseOptions = {
name: "Project Name",
description: "",
options: {
startedColumns: ["In Progress"],
completedColumns: ["Done"],
},
columns: ["Backlog", "Todo", "In Progress", "Done"],
};
/**
* Check if a file or folder exists
* @param {string} path
* @return {Promise<boolean>} True if the file or folder exists
*/
async function exists(path) {
try {
await fs.promises.access(path, fs.constants.R_OK | fs.constants.W_OK);
} catch (error) {
return false;
}
return true;
}
/**
* Get a list of all tracked task ids
* @param {object} index The index object
* @param {?string} [columnName=null] The optional column name to filter tasks by
* @return {Set} A set of task ids appearing in the index
*/
function getTrackedTaskIds(index, columnName = null) {
return new Set(
columnName
? index.columns[columnName]
: Object.keys(index.columns)
.map((columnName) => index.columns[columnName])
.flat()
);
}
/**
* Get a task path from the id
* @param {string} tasksPath The path to the tasks folder
* @param {string} taskId The task id
* @return {string} The task path
*/
function getTaskPath(tasksPath, taskId) {
return path.join(tasksPath, addFileExtension(taskId));
}
/**
* Add the file extension to an id if it doesn't already have one
* @param {string} taskId The task id
* @return {string} The task id with .md extension
*/
function addFileExtension(taskId) {
if (!/\.md$/.test(taskId)) {
return `${taskId}.md`;
}
return taskId;
}
/**
* Remove the file extension from an id if it has one
* @param {string} taskId The task id
* @return {string} The task id without .md extension
*/
function removeFileExtension(taskId) {
if (/\.md$/.test(taskId)) {
return taskId.slice(0, taskId.length - ".md".length);
}
return taskId;
}
/**
* Check if a task exists in the index
* @param {object} index The index object
* @param {string} taskId The task id to search for
* @return {boolean} True if the task exists in the index
*/
function taskInIndex(index, taskId) {
for (let columnName in index.columns) {
if (index.columns[columnName].indexOf(taskId) !== -1) {
return true;
}
}
return false;
}
/**
* Find a task in the index and returns the column that it's in
* @param {object} index The index data
* @param {string} taskId The task id to search for
* @return {?string} The column name for the specified task, or null if it wasn't found
*/
function findTaskColumn(index, taskId) {
for (let columnName in index.columns) {
if (index.columns[columnName].indexOf(taskId) !== -1) {
return columnName;
}
}
return null;
}
/**
* Add a task id to the specified column in the index
* @param {object} index The index object
* @param {string} taskId The task id to add
* @param {string} columnName The column to add the task to
* @param {?number} [position=null] The position in the column to move the task to, or last position if null
* @return {object} The modified index object
*/
function addTaskToIndex(index, taskId, columnName, position = null) {
if (position === null) {
index.columns[columnName].push(taskId);
} else {
index.columns[columnName].splice(position, 0, taskId);
}
return index;
}
/**
* Remove all instances of a task id from the index
* @param {object} index The index object
* @param {string} taskId The task id to remove
* @return {object} The modified index object
*/
function removeTaskFromIndex(index, taskId) {
for (let columnName in index.columns) {
index.columns[columnName] = index.columns[columnName].filter((t) => t !== taskId);
}
return index;
}
/**
* Rename all instances of a task id in the index
* @param {object} index The index object
* @param {string} taskId The task id to rename
* @param {string} newTaskId The new task id
* @return {object} The modified index object
*/
function renameTaskInIndex(index, taskId, newTaskId) {
for (let columnName in index.columns) {
index.columns[columnName] = index.columns[columnName].map((t) => (t === taskId ? newTaskId : t));
}
return index;
}
/**
* Get a metadata property from a task, or undefined if the metadata property doesn't exist or
* if the task has no metadata
* @param {object} taskData The task object
* @param {string} property The metadata property to check
* @return {any} The metadata property value
*/
function getTaskMetadata(taskData, property) {
if ("metadata" in taskData && property in taskData.metadata) {
return taskData.metadata[property];
}
return undefined;
}
/**
* Set a metadata value in a task. If the value is undefined, remove the metadata property instead
* @param {object} taskData The task object
* @param {string} property The metadata property to update
* @param {string} value The value to set
* @return {object} The modified task object
*/
function setTaskMetadata(taskData, property, value) {
if (!("metadata" in taskData)) {
taskData.metadata = {};
}
if (property in taskData.metadata && value === undefined) {
delete taskData.metadata[property];
} else {
taskData.metadata[property] = value;
}
return taskData;
}
/**
* Append a structured history event to a task
* @param {object} taskData The task object
* @param {object} historyEvent The history event payload
* @return {object} The modified task object
*/
function appendTaskHistory(taskData, historyEvent) {
if (!('history' in taskData) || taskData.history === null) {
taskData.history = [];
}
taskData.history.push({
date: new Date(),
...historyEvent
});
return taskData;
}
/**
* Check if a task is completed
* @param {object} index
* @param {object} task
* @return {boolean} True if the task is in a completed column or has a completed date
*/
/**
* Get the name of the metadata field that holds a task's started date for this board. Boards can
* point this at a custom date field so that several boards can track their own started/completed
* state against the same shared task file
* @param {object} index The index object
* @return {string} The metadata field name
*/
function getStartedField(index) {
return ("startedField" in index.options && index.options.startedField) || DEFAULT_STARTED_FIELD;
}
/**
* Get the name of the metadata field that holds a task's completed date for this board
* @param {object} index The index object
* @return {string} The metadata field name
*/
function getCompletedField(index) {
return ("completedField" in index.options && index.options.completedField) || DEFAULT_COMPLETED_FIELD;
}
function taskCompleted(index, task) {
return getCompletedField(index) in task.metadata;
}
/**
* Flatten a task's metadata and computed values into a single object that can be used for sorting
* @param {object} index The index object
* @param {object} task The task object
* @return {object} An object containing all sortable task fields
*/
function taskSortFields(index, task) {
return {
...task,
...task.metadata,
created: "created" in task.metadata ? task.metadata.created : "",
updated: "updated" in task.metadata ? task.metadata.updated : "",
started: "started" in task.metadata ? task.metadata.started : "",
completed: "completed" in task.metadata ? task.metadata.completed : "",
due: "due" in task.metadata ? task.metadata.due : "",
plannedStart: "plannedStart" in task.metadata ? task.metadata.plannedStart : "",
plannedFinish: "plannedFinish" in task.metadata ? task.metadata.plannedFinish : "",
assigned: "assigned" in task.metadata ? task.metadata.assigned : "",
countSubTasks: task.subTasks.length,
subTasks: task.subTasks.map((subTask) => `[${subTask.completed ? "x" : ""}] ${subTask.text}`).join("\n"),
countTags: "tags" in task.metadata ? task.metadata.tags.length : 0,
tags: "tags" in task.metadata ? task.metadata.tags.join("\n") : "",
countRelations: task.relations.length,
relations: task.relations.map((relation) => `${relation.type} ${relation.task}`).join("\n"),
countComments: task.comments.length,
comments: task.comments.map((comment) => `${comment.author} ${comment.text}`).join("\n"),
workload: taskWorkload(index, task),
progress: taskProgress(index, task),
};
}
/**
* Sort a list of tasks without modifying them, using each task's flattened sort fields
* @param {object} index The index object
* @param {object[]} tasks
* @param {object[]} sorters
* @return {object[]} The sorted tasks
*/
function sortTasksWithFields(index, tasks, sorters) {
if (!sorters.length) {
return tasks;
}
return sortTasks(
tasks.map((task) => ({ task, fields: taskSortFields(index, task) })),
sorters,
(entry, field) => entry.fields[field]
).map((entry) => entry.task);
}
/**
* Sort a column in the index
* @param {object} index The index object
* @param {object[]} tasks The tasks in the index
* @param {string} columnName The column to sort
* @param {object[]} sorters A list of sorter objects
* @return {object} The modified index object
*/
function sortColumnInIndex(index, tasks, columnName, sorters) {
// Sort the tasks in the target column using their flattened sort fields
tasks = sortTasksWithFields(index, tasks, sorters);
// Save the list of tasks back to the index
index.columns[columnName] = tasks.map((task) => task.id);
return index;
}
/**
* Sort a list of tasks
* @param {object[]} tasks
* @param {object[]} sorters
* @param {?function} [getField=null] An optional accessor used to read a sort field from a task
* @return {object[]} The sorted tasks
*/
function sortTasks(tasks, sorters, getField = null) {
const readField = getField || ((task, field) => task[field]);
tasks.sort((a, b) => {
let compareA, compareB;
for (let sorter of sorters) {
compareA = readField(a, sorter.field);
compareB = readField(b, sorter.field);
if (sorter.filter) {
compareA = sortFilter(compareA, sorter.filter);
compareB = sortFilter(compareB, sorter.filter);
}
if (compareA === compareB) {
continue;
}
return sorter.order === "descending" ? compareValues(compareB, compareA) : compareValues(compareA, compareB);
}
return 0;
});
return tasks;
}
/**
* Transform a value using a sort filter regular expression
* @param {string} value
* @param {string} filter
* @return {string} The transformed value
*/
function sortFilter(value, filter) {
// Filter regex is global and case-insensitive
const matches = [...value.matchAll(new RegExp(filter, "gi"))];
const result = matches.map((match) => {
// If the matched string has named capturing groups, concatenate their contents
if (match.groups) {
return Object.values(match.groups).join("");
}
// If the matched string has non-named capturing groups, use the contents of the first group
if (match[1]) {
return match[1];
}
// Otherwise use the matched string
return match[0];
});
return result.join("");
}
/**
* Compare two values (supports string, date and number values)
* @param {any} a
* @param {any} b
* @return {number} A positive value if a > b, negative if a < b, otherwise 0
*/
function compareValues(a, b) {
if (a === undefined && b === undefined) {
return 0;
}
a = utility.coerceUndefined(a, typeof b);
b = utility.coerceUndefined(b, typeof a);
if (typeof a === "string" && typeof b === "string") {
return a.localeCompare(b, undefined, { sensitivity: "accent" });
}
return a - b;
}
/**
* Filter a list of tasks using a filters object containing field names and filter values
* @param {object} index
* @param {object[]}} tasks
* @param {object} filters
*/
function filterTasks(index, tasks, filters) {
return tasks.filter((task) => {
// Get task id and column
const taskId = utility.getTaskId(task.name);
const column = findTaskColumn(index, taskId);
// If no filters are defined, return all tasks
if (Object.keys(filters).length === 0) {
return true;
}
// Apply filters
let result = true;
// Id
if ("id" in filters && !stringFilter(filters.id, task.id)) {
result = false;
}
// Name
if ("name" in filters && !stringFilter(filters.name, task.name)) {
result = false;
}
// Description
if ("description" in filters && !stringFilter(filters.description, task.description)) {
result = false;
}
// Column
if ("column" in filters && !stringFilter(filters.column, column)) {
result = false;
}
// Created date
if (
"created" in filters &&
(!("created" in task.metadata) || !dateFilter(filters.created, task.metadata.created))
) {
result = false;
}
// Updated date
if (
"updated" in filters &&
(!("updated" in task.metadata) || !dateFilter(filters.updated, task.metadata.updated))
) {
result = false;
}
// Started date
if (
"started" in filters &&
(!("started" in task.metadata) || !dateFilter(filters.started, task.metadata.started))
) {
result = false;
}
// Completed date
if (
"completed" in filters &&
(!("completed" in task.metadata) || !dateFilter(filters.completed, task.metadata.completed))
) {
result = false;
}
// Due
if ("due" in filters && (!("due" in task.metadata) || !dateFilter(filters.due, task.metadata.due))) {
result = false;
}
// Planned start date
if (
"plannedStart" in filters &&
(!("plannedStart" in task.metadata) || !dateFilter(filters.plannedStart, task.metadata.plannedStart))
) {
result = false;
}
// Planned finish date
if (
"plannedFinish" in filters &&
(!("plannedFinish" in task.metadata) || !dateFilter(filters.plannedFinish, task.metadata.plannedFinish))
) {
result = false;
}
// Workload
if ("workload" in filters && !numberFilter(filters.workload, taskWorkload(index, task))) {
result = false;
}
// Progress
if ("progress" in filters && !numberFilter(filters.progress, taskProgress(index, task))) {
result = false;
}
// Assigned
if (
"assigned" in filters &&
!stringFilter(filters.assigned, "assigned" in task.metadata ? task.metadata.assigned : "")
) {
result = false;
}
// Sub-tasks
if (
"sub-task" in filters &&
!stringFilter(
filters["sub-task"],
task.subTasks.map((subTask) => `[${subTask.completed ? "x" : " "}] ${subTask.text}`).join("\n")
)
) {
result = false;
}
// Count sub-tasks
if ("count-sub-tasks" in filters && !numberFilter(filters["count-sub-tasks"], task.subTasks.length)) {
result = false;
}
// Tag
if ("tag" in filters && !stringFilter(filters.tag, ("tags" in task.metadata ? task.metadata.tags : []).join("\n"))) {
result = false;
}
// Count tags
if (
"count-tags" in filters &&
!numberFilter(filters["count-tags"], ("tags" in task.metadata ? task.metadata.tags : []).length)
) {
result = false;
}
// Relation
if (
"relation" in filters &&
!stringFilter(
filters.relation,
task.relations.map((relation) => `${relation.type} ${relation.task}`).join("\n")
)
) {
result = false;
}
// Count relations
if ("count-relations" in filters && !numberFilter(filters["count-relations"], task.relations.length)) {
result = false;
}
// Comments
if (
"comment" in filters &&
!stringFilter(filters.comment, task.comments.map((comment) => `${comment.author} ${comment.text}`).join("\n"))
) {
result = false;
}
// Count comments
if ("count-comments" in filters && !numberFilter(filters["count-comments"], task.comments.length)) {
result = false;
}
// Custom metadata properties
if ("customFields" in index.options) {
for (let customField of index.options.customFields) {
if (customField.name in filters) {
if (!(customField.name in task.metadata)) {
result = false;
} else {
switch (customField.type) {
case "boolean":
if (task.metadata[customField.name] !== filters[customField.name]) {
result = false;
}
break;
case "number":
if (!numberFilter(filters[customField.name], task.metadata[customField.name])) {
result = false;
}
break;
case "string":
if (!stringFilter(filters[customField.name], task.metadata[customField.name])) {
result = false;
}
break;
case "date":
if (!dateFilter(filters[customField.name], task.metadata[customField.name])) {
result = false;
}
break;
default:
break;
}
}
}
}
}
return result;
});
}
/**
* Check if the input string matches the filter regex
* @param {string|string[]} filter A regular expression or array of regular expressions
* @param {string} input The string to match against
* @return {boolean} True if the input matches the string filter
*/
function stringFilter(filter, input) {
if (Array.isArray(filter)) {
filter = filter.join("|");
}
return new RegExp(filter, "i").test(input);
}
/**
* Check if the input date matches a date (ignore time part), or if multiple dates are passed in, check if the
* input date is between the earliest and latest dates
* @param {Date|Date[]} dates A date or list of dates to check against
* @param {Date} input The input date to match against
* @return {boolean} True if the input matches the date filter
*/
function dateFilter(dates, input) {
dates = utility.arrayArg(dates);
if (dates.length === 1) {
return utility.compareDates(input, dates[0]);
}
const earliest = Math.min(...dates);
const latest = Math.max(...dates);
return input >= earliest && input <= latest;
}
/**
* Check if the input matches a number, or if multiple numbers are passed in, check if the input is between the
* minimum and maximum numbers
* @param {number|number[]} filter A filter number or array of filter numbers
* @param {number} input The number to match against
* @return {boolean} True if the input matches the number filter
*/
function numberFilter(filter, input) {
filter = utility.arrayArg(filter);
return input >= Math.min(...filter) && input <= Math.max(...filter);
}
/**
* Calculate task workload
* @param {object} index The index object
* @param {object} task The task object
* @return {number} The task workload
*/
function taskWorkload(index, task) {
const defaultTaskWorkload =
"defaultTaskWorkload" in index.options ? index.options.defaultTaskWorkload : DEFAULT_TASK_WORKLOAD;
const taskWorkloadTags =
"taskWorkloadTags" in index.options ? index.options.taskWorkloadTags : DEFAULT_TASK_WORKLOAD_TAGS;
let workload = 0;
let hasWorkloadTags = false;
if ("tags" in task.metadata) {
for (let workloadTag of Object.keys(taskWorkloadTags)) {
if (task.metadata.tags.indexOf(workloadTag) !== -1) {
workload += taskWorkloadTags[workloadTag];
hasWorkloadTags = true;
}
}
}
if (!hasWorkloadTags) {
workload = defaultTaskWorkload;
}
return workload;
}
/**
* Get task progress amount
* @param {object} index
* @param {object} task
* @return {number} Task progress
*/
function taskProgress(index, task) {
if (taskCompleted(index, task)) {
return 1;
}
return "progress" in task.metadata ? task.metadata.progress : 0;
}
/**
* Calculate task workload statistics between a start and end date
* @param {object[]} tasks
* @param {string} metadataProperty
* @param {Date} start
* @param {Date} end
* @return {object} A statistics object
*/
function taskWorkloadInPeriod(tasks, metadataProperty, start, end) {
const filteredTasks = tasks.filter(
(task) =>
metadataProperty in task.metadata &&
task.metadata[metadataProperty] >= start &&
task.metadata[metadataProperty] <= end
);
return {
tasks: filteredTasks.map((task) => ({
id: task.id,
column: task.column,
workload: task.workload,
})),
workload: filteredTasks.reduce((a, task) => a + task.workload, 0),
};
}
/**
* Find the date at which a task most recently entered one of the specified columns, using its
* history. Returns null if the task has no history, or none of its events mention those columns
* @param {object} task
* @param {string[]} columnNames
* @return {?Date}
*/
function findColumnEntryDate(task, columnNames) {
if (!("history" in task) || !Array.isArray(task.history) || task.history.length === 0) {
return null;
}
let result = null;
for (const historyEvent of [...task.history].sort((a, b) => a.date.getTime() - b.date.getTime())) {
if (!historyEvent.date) {
continue;
}
const enteredColumn = historyEvent.type === "moved"
? historyEvent.toColumn
: (historyEvent.type === "created" || historyEvent.type === "restored")
? (historyEvent.column || historyEvent.toColumn)
: null;
if (enteredColumn && columnNames.indexOf(enteredColumn) !== -1) {
result = historyEvent.date;
}
}
return result;
}
/**
* Get task progress at a specific date from history when available
* @param {object} task
* @param {Date} date
* @return {number}
*/
function getTaskProgressAtDate(task, date) {
if ("history" in task && Array.isArray(task.history) && task.history.length > 0) {
let progress = 0;
const history = [...task.history].sort((a, b) => a.date.getTime() - b.date.getTime());
history.forEach((historyEvent) => {
if (!historyEvent.date || historyEvent.date > date) {
return;
}
if (historyEvent.type === 'progress' && historyEvent.toProgress !== undefined) {
progress = historyEvent.toProgress;
}
if (historyEvent.type === 'created' && historyEvent.toProgress !== undefined) {
progress = historyEvent.toProgress;
}
});
return Math.max(0, Math.min(progress, 1));
}
if (task.completed && task.completed <= date) {
return 1;
}
const progress = "progress" in task.metadata ? task.metadata.progress : 0;
return Math.max(0, Math.min(progress, 1));
}
/**
* Get timeline dates for a task in a period. For history-enabled tasks this uses all history event dates,
* otherwise it falls back to created/started/completed dates.
* @param {object} task
* @param {Date} from
* @param {Date} to
* @return {Date[]}
*/
function getTaskTimelineDates(task, from, to) {
if ("history" in task && Array.isArray(task.history) && task.history.length > 0) {
return task.history
.map((historyEvent) => historyEvent.date)
.filter((date) => date && date >= from && date <= to);
}
return [task.created, task.started, task.completed].filter((date) => date && date >= from && date <= to);
}
/**
* Normalise relation type text to kebab-case
* @param {string} relationType
* @return {string}
*/
function normaliseRelationType(relationType) {
return String(relationType || '')
.trim()
.toLowerCase()
.replace(/\s+/g, '-');
}
/**
* Get the earliest date in a list of dates
* @param {Date[]} dates
* @return {?Date}
*/
function minDate(dates) {
const filteredDates = dates.filter((date) => date instanceof Date);
if (filteredDates.length === 0) {
return null;
}
return new Date(Math.min(...filteredDates.map((date) => date.getTime())));
}
/**
* Get the latest date in a list of dates
* @param {Date[]} dates
* @return {?Date}
*/
function maxDate(dates) {
const filteredDates = dates.filter((date) => date instanceof Date);
if (filteredDates.length === 0) {
return null;
}
return new Date(Math.max(...filteredDates.map((date) => date.getTime())));
}
/**
* Set a date to the start of the day
* @param {Date} date
* @return {Date}
*/
function startOfDay(date) {
const result = new Date(date.getTime());
result.setHours(0, 0, 0, 0);
return result;
}
/**
* Set a date to the end of the day
* @param {Date} date
* @return {Date}
*/
function endOfDay(date) {
const result = new Date(date.getTime());
result.setHours(23, 59, 59, 999);
return result;
}
/**
* Get the task anchor date used for gantt ordering
* @param {object} task
* @return {Date}
*/
function getTaskGanttAnchor(task) {
return minDate([
task.metadata.plannedStart,
task.created,
task.started,
task.metadata.plannedFinish,
task.completed
]) || new Date(0);
}
/**
* Find one concrete dependency cycle in the graph, if present
* @param {Map<string, Set<string>>} dependencyMap
* @return {string[]}
*/
function findDependencyCycle(dependencyMap) {
const visiting = new Set();
const visited = new Set();
const stack = [];
let cycleTaskIds = [];
const visit = (taskId) => {
if (cycleTaskIds.length) {
return;
}
visiting.add(taskId);
stack.push(taskId);
for (let dependencyId of dependencyMap.get(taskId) || []) {
if (!visited.has(dependencyId) && !visiting.has(dependencyId)) {
visit(dependencyId);
if (cycleTaskIds.length) {
return;
}
} else if (visiting.has(dependencyId)) {
const cycleStartIndex = stack.indexOf(dependencyId);
cycleTaskIds = stack.slice(cycleStartIndex).concat(dependencyId);
return;
}
}
stack.pop();
visiting.delete(taskId);
visited.add(taskId);
};
for (let taskId of dependencyMap.keys()) {
if (!visited.has(taskId)) {
visit(taskId);
if (cycleTaskIds.length) {
break;
}
}
}
return cycleTaskIds;
}
/**
* Build gantt schedule data from tracked tasks
* @param {object} index
* @param {object[]} tasks
* @param {Date} now
* @return {object}
*/
function buildGanttSchedule(index, tasks, now, trackedTaskIds = new Set()) {
const taskById = new Map(tasks.map((task) => [task.id, task]));
const dependencyMap = new Map(tasks.map((task) => [task.id, new Set()]));
const dependentsMap = new Map();
const indegree = new Map(tasks.map((task) => [task.id, 0]));
const externalIncomingDependenciesMap = new Map(tasks.map((task) => [task.id, new Set()]));
const externalOutgoingDependentsMap = new Map(tasks.map((task) => [task.id, new Set()]));
const taskExistsInBoard = (taskId) => trackedTaskIds.has(taskId);
const addDependencyEdge = (dependencyId, dependentId) => {
if (!taskById.has(dependentId)) {
throw new Error(`Task "${dependentId}" depends on missing task "${dependencyId}"`);
}
if (!taskById.has(dependencyId)) {
if (taskExistsInBoard(dependencyId)) {
externalIncomingDependenciesMap.get(dependentId).add(dependencyId);
return;
}
throw new Error(`Task "${dependentId}" depends on missing task "${dependencyId}"`);
}
const dependencies = dependencyMap.get(dependentId);
if (dependencies.has(dependencyId)) {
return;
}
dependencies.add(dependencyId);
indegree.set(dependentId, indegree.get(dependentId) + 1);
if (!dependentsMap.has(dependencyId)) {
dependentsMap.set(dependencyId, []);
}
dependentsMap.get(dependencyId).push(dependentId);
};
tasks.forEach((task) => {
(Array.isArray(task.relations) ? task.relations : []).forEach((relation) => {
if (!relation || !relation.task) {
return;
}
const relationType = normaliseRelationType(relation.type);
if (relationType === 'depends-on') {
addDependencyEdge(relation.task, task.id);
} else if (relationType === 'blocks') {
if (taskById.has(relation.task)) {
addDependencyEdge(task.id, relation.task);
} else if (taskExistsInBoard(relation.task)) {
externalOutgoingDependentsMap.get(task.id).add(relation.task);
} else {
throw new Error(`Task "${task.id}" blocks missing task "${relation.task}"`);
}
}
});
});
const queue = tasks
.filter((task) => indegree.get(task.id) === 0)
.slice()
.sort((a, b) => compareValues(getTaskGanttAnchor(a), getTaskGanttAnchor(b)) || compareValues(a.id, b.id));
const orderedTasks = [];
while (queue.length > 0) {
const nextTask = queue.shift();
orderedTasks.push(nextTask);
for (let dependentId of dependentsMap.get(nextTask.id) || []) {
indegree.set(dependentId, indegree.get(dependentId) - 1);
if (indegree.get(dependentId) === 0) {
queue.push(taskById.get(dependentId));
queue.sort((a, b) => compareValues(getTaskGanttAnchor(a), getTaskGanttAnchor(b)) || compareValues(a.id, b.id));
}
}
}
let dependencyCycleDetected = false;
let cycleFallbackTaskIds = [];
let dependencyCycleTaskIds = [];
if (orderedTasks.length !== tasks.length) {
dependencyCycleDetected = true;
dependencyCycleTaskIds = findDependencyCycle(dependencyMap);
const orderedTaskIds = new Set(orderedTasks.map((task) => task.id));
const remainingTasks = tasks
.filter((task) => !orderedTaskIds.has(task.id))
.slice()
.sort((a, b) => compareValues(getTaskGanttAnchor(a), getTaskGanttAnchor(b)) || compareValues(a.id, b.id));
cycleFallbackTaskIds = remainingTasks.map((task) => task.id);
orderedTasks.push(...remainingTasks);
}
const scheduledTasks = [];
const scheduleById = new Map();
for (let task of orderedTasks) {
const dependencies = [...(dependencyMap.get(task.id) || [])];
const dependencyEnd = maxDate(
dependencies
.map((dependencyId) => scheduleById.get(dependencyId))
.filter((scheduledDependency) => scheduledDependency)
.map((scheduledDependency) => scheduledDependency.end)
);
const hasPlannedStart = task.metadata.plannedStart instanceof Date;
const hasPlannedFinish = task.metadata.plannedFinish instanceof Date;
const hasStarted = task.started instanceof Date;
const hasCompleted = task.completed instanceof Date;
const duration = hasPlannedStart && hasPlannedFinish
? Math.max(DAY, task.metadata.plannedFinish.getTime() - task.metadata.plannedStart.getTime())
: hasStarted && hasCompleted
? Math.max(DAY, task.completed.getTime() - task.started.getTime())
: Math.max(DAY, Math.ceil(Math.max(1, task.workload)) * DAY);
const preferredStart = hasPlannedStart
? task.metadata.plannedStart
: hasStarted
? task.started
: task.created;
const finishHint = hasPlannedFinish
? task.metadata.plannedFinish
: hasCompleted
? task.completed
: null;
const derivedStartFromFinish = finishHint instanceof Date
? new Date(finishHint.getTime() - duration)
: null;
const taskBaseDate = hasPlannedStart || hasStarted
? preferredStart
: (derivedStartFromFinish || preferredStart);
const scheduleAnchor = maxDate([
taskBaseDate,
dependencyEnd
]) || new Date(0);
let start = new Date(scheduleAnchor.getTime());
let end = hasPlannedFinish
? new Date(task.metadata.plannedFinish.getTime())
: hasCompleted
? new Date(task.completed.getTime())
: new Date(start.getTime() + duration);
if (end.getTime() < start.getTime()) {
end = new Date(start.getTime() + duration);
}
const scheduledTask = {
...task,
dependencies,
externalIncomingDependencies: [...(externalIncomingDependenciesMap.get(task.id) || [])],
externalOutgoingDependents: [...(externalOutgoingDependentsMap.get(task.id) || [])],
start,
end,
blocked: dependencyEnd !== null && preferredStart instanceof Date && dependencyEnd.getTime() > preferredStart.getTime()
};
scheduleById.set(task.id, scheduledTask);
scheduledTasks.push(scheduledTask);
}
const from = startOfDay(minDate(scheduledTasks.map((task) => task.start)) || now);
const to = endOfDay(maxDate(scheduledTasks.map((task) => task.end)) || now);
return {
from,
to,
dependencyCycleDetected,
dependencyCycleTaskIds,
cycleFallbackTaskIds,
tasks: scheduledTasks
};
}
/**
* Get a list of tasks that were started before and/or completed after a date
*
* A task is active from its started date until its completed date. This used to be derived by
* replaying the task's history to work out which column it was in at the time and comparing that
* column against the index options, which meant a task's activity depended on column names rather
* than on the dates recorded against it
* @param {object} index
* @param {object[]} tasks
* @param {Date} date
* @return {object[]} A filtered list of tasks
*/
function getActiveTasksAtDate(index, tasks, date) {
return tasks.filter((task) => (
(task.started !== false && task.started <= date) &&
(task.completed === false || task.completed > date)
));
}
/**
* Calculate the total workload at a specific date
* @param {object} index
* @param {object[]} tasks
* @param {Date} date
* @return {number} The total workload at the specified date
*/
function getWorkloadAtDate(index, tasks, date) {
return getActiveTasksAtDate(index, tasks, date).reduce((a, task) => {
const progress = getTaskProgressAtDate(task, date);
return a + task.workload * (1 - progress);
}, 0);
}
/**
* Get the number of tasks that were active at a specific date
* @param {object} index
* @param {object[]} tasks
* @param {Date} date
* @return {number} The total number of active tasks at the specified date
*/
function countActiveTasksAtDate(index, tasks, date) {
return getActiveTasksAtDate(index, tasks, date).length;
}
/**
* Get a list of tasks that were started or completed on a specific date
* @param {object} index
* @param {object[]} tasks
* @param {Date} date
* @return {object[]} A list of event objects, with event type and task id
*/
function getTaskEventsAtDate(index, tasks, date) {
return tasks
.map((task) => {
if ("history" in task && Array.isArray(task.history) && task.history.length > 0) {
return task.history
.filter((historyEvent) => historyEvent.date && historyEvent.date.getTime() === date.getTime())
.map((historyEvent) => ({
eventType: historyEvent.type,
task
}));
}
return [
(task.created ? task.created.getTime() : 0) === date.getTime() && {
eventType: "created",
task
},
(task.started ? task.started.getTime() : 0) === date.getTime() && {
eventType: "started",
task
},
(task.completed ? task.completed.getTime() : 0) === date.getTime() && {
eventType: "completed",
task
}
].filter((event) => !!event);
})
.flat();
}
/**
* Quantize a burndown chart date to 1-hour resolution
* @param {Date} date
* @param {string} resolution One of 'days', 'hours', 'minutes', 'seconds'
* @return {Date} The quantized dates
*/
function normaliseDate(date, resolution = 'minutes') {
const result = new Date(date.getTime());
switch (resolution) {
case 'days':
result.setHours(0);
case 'hours':
result.setMinutes(0);
case 'minutes':
result.setSeconds(0);
case 'seconds':
result.setMilliseconds(0);
default:
break;
}
return result;
}
/**
* If a task's column is linked in the index to a custom field with type date, update the custom field's value
* in the task data with the current date
* @param {object} index
* @param {object} taskData
* @param {string} columnName
* @param {Date} [date=new Date()] The date to stamp
* @return {object} The updated task data
*/
function updateColumnLinkedCustomFields(index, taskData, columnName, date = new Date()) {
// Update built-in column-linked metadata properties first (started and completed dates). The
// columns are always listed in startedColumns/completedColumns, but the field that gets written
// can be pointed elsewhere with startedField/completedField
taskData = updateColumnLinkedCustomField(
index, taskData, columnName, getCompletedField(index), "once", "completedColumns", date
);
taskData = updateColumnLinkedCustomField(
index, taskData, columnName, getStartedField(index), "once", "startedColumns", date
);
// Update column-linked custom fields
if ("customFields" in index.options) {
for (let customField of index.options.customFields) {
if (customField.type === "date") {
taskData = updateColumnLinkedCustomField(
index,
taskData,
columnName,
customField.name,
customField.updateDate || "none",
null,
date
);
}
}
}
return taskData;
}
/**
* If index options contains a list of columns linked to a custom field name and a task's column matches one
* of the columns in this list, set the task's custom field value to the current date depending on criteria:
* - if 'once', update the value only if it's not currently set
* - if 'always', update the value regardless
* - otherwise, don't update the value
* @param {object} index
* @param {object} taskData
* @param {string} columnName
* @param {string} fieldName
* @param {string} [updateCriteria='none']
* @param {?string} [columnListName=null] The option holding the linked column names, or null to use
* the `${fieldName}Columns` convention
* @param {Date} [date=new Date()] The date to stamp
*/
function updateColumnLinkedCustomField(
index, taskData, columnName, fieldName, updateCriteria = "none", columnListName = null,
date = new Date()
) {
const columnList = columnListName || `${fieldName}Columns`;
if (columnList in index.options && index.options[columnList].indexOf(columnName) !== -1) {
switch (updateCriteria) {
case "always":
taskData = setTaskMetadata(taskData, fieldName, date);
break;
case "once":
if (!(fieldName in taskData.metadata && taskData.metadata[fieldName])) {
taskData = setTaskMetadata(taskData, fieldName, date);
}
break;
default:
break;
}
}
return taskData;
}
class Kanbn {
ROOT = process.cwd();
CONFIG_YAML = path.join(this.ROOT, "kanbn.yml");
CONFIG_JSON = path.join(this.ROOT, "kanbn.json");
// Memoize config
configMemo = null;
constructor(root = null) {
if(root) {
this.ROOT = root
this.CONFIG_YAML = path.join(this.ROOT, "kanbn.yml");
this.CONFIG_JSON = path.join(this.ROOT, "kanbn.json");
}
}
/**
* Check if a separate config file exists
* @returns {Promise<boolean>} True if a config file exists
*/
async configExists() {
return await exists(this.CONFIG_YAML) || await exists(this.CONFIG_JSON);
}
/**
* Save configuration data to a separate config file
*/
async saveConfig(config) {
if (await exists(this.CONFIG_YAML)) {
await fs.promises.writeFile(this.CONFIG_YAML, yaml.stringify(config, 4, 2));
} else {
await fs.promises.writeFile(this.CONFIG_JSON, JSON.stringify(config, null, 4));
}
}
/**
* Get configuration settings from the config file if it exists, otherwise return null
* @return {Promise<Object|null>} Configuration settings or null if there is no separate config file
*/
async getConfig() {
if (this.configMemo === null) {
let config = null;
if (await exists(this.CONFIG_YAML)) {
try {
config = yaml.load(this.CONFIG_YAML);
} catch (error) {
throw new Error(`Couldn't load config file: ${error.message}`);
}
} else if (await exists(this.CONFIG_JSON)) {
try {
config = JSON.parse(await fs.promises.readFile(this.CONFIG_JSON, { encoding: "utf-8" }));
} catch (error) {
throw new Error(`Couldn't load config file: ${error.message}`);
}
}
this.configMemo = config;
}
return this.configMemo;
}
/**
* Clear cached config
*/
clearConfigCache() {
this.configMemo = null;
}
/**
* Get the name of the folder where the index and tasks are stored
* @return {Promise<string>} The kanbn folder name
*/
async getFolderName() {
const config = await this.getConfig();
if (config !== null && 'mainFolder' in config) {
return config.mainFolder;
}
return DEFAULT_FOLDER_NAME;
}
/**
* Get the index filename
* @return {Promise<string>} The index filename
*/
async getIndexFileName() {
const config = await this.getConfig();
if (config !== null && 'indexFile' in config) {
return config.indexFile;
}
return DEFAULT_INDEX_FILE_NAME;
}
/**
* Get the name of the folder where tasks are stored
* @return {Promise<string>} The task folder name
*/
async getTaskFolderName() {
const config = await this.getConfig();
if (config !== null && 'taskFolder' in config) {
return config.taskFolder;
}
return DEFAULT_TASKS_FOLDER_NAME;
}
/**
* Get the name of the archive folder
* @return {Promise<string>} The archive folder name
*/
async getArchiveFolderName() {
const config = await this.getConfig();
if (config !== null && 'archiveFolder' in config) {
return config.archiveFolder;
}
return DEFAULT_ARCHIVE_FOLDER_NAME;
}
/**
* Get the kanbn folder location for the current working directory
* @return {Promise<string>} The kanbn folder path
*/
async getMainFolder() {
return path.join(this.ROOT, await this.getFolderName());
}
/**
* Get the index path
* @return {Promise<string>} The kanbn index path
*/
async getIndexPath() {
return path.join(await this.getMainFolder(), await this.getIndexFileName());
}
/**
* Get the task folder path
* @return {Promise<string>} The kanbn task folder path
*/
async getTaskFolderPath() {
return path.join(await this.getMainFolder(), await this.getTaskFolderName());
}
/**
* Get the archive folder path
* @return {Promise<string>} The kanbn archive folder path
*/
async getArchiveFolderPath() {
return path.join(await this.getMainFolder(), await this.getArchiveFolderName());
}
/**
* Get the index as an object
* @return {Promise<index>} The index
*/
async getIndex() {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
return this.loadIndex();
}
/**
* Get a task as an object
* @param {string} taskId The task id to get
* @return {Promise<task>} The task
*/
async getTask(taskId) {
await this.taskExists(taskId);
return this.loadTask(taskId);
}
/**
* Add additional index-based information to a task
* @param {index} index The index object
* @param {task} task The task object
* @return {task} The hydrated task
*/
hydrateTask(index, task) {
const completed = taskCompleted(index, task);
task.column = findTaskColumn(index, task.id);
task.workload = taskWorkload(index, task);
// Add progress information
task.progress = taskProgress(index, task);
task.remainingWorkload = Math.ceil(task.workload * (1 - task.progress));
// Add due information
if ("due" in task.metadata) {
const dueData = {};
// A task is overdue if it's due date is in the past and the task is not in a completed column
// or doesn't have a completed dates
const completedField = getCompletedField(index);
const completedDate = completedField in task.metadata ? task.metadata[completedField] : null;
// Get task due delta - this is the difference between now and the due date, or if the task is completed
// this is the difference between the completed and due dates
let delta;
if (completedDate !== null) {
delta = completedDate - task.metadata.due;
} else {
delta = new Date() - task.metadata.due;
}
// Populate due information
dueData.completed = completed;
dueData.completedDate = completedDate;
dueData.dueDate = task.metadata.due;
dueData.overdue = !completed && delta > 0;
dueData.dueDelta = delta;
// Prepare a due message for the task
let dueMessage = "";
if (completed) {
dueMessage += "Completed ";
}
dueMessage += `${humanizeDuration(delta, {
largest: 3,
round: true,
})} ${delta > 0 ? "overdue" : "remaining"}`;
dueData.dueMessage = dueMessage;
task.dueData = dueData;
}
return task;
}
/**
* Return a filtered and sorted list of tasks
* @param {index} index The index object
* @param {task[]} tasks A list of task objects
* @param {object} filters A list of task filters
* @param {object[]} sorters A list of task sorters
* @return {object[]} A filtered and sorted list of tasks
*/
filterAndSortTasks(index, tasks, filters, sorters) {
return sortTasksWithFields(index, filterTasks(index, tasks, filters), sorters);
}
/**
* Overwrite the index file with the specified data
* @param {object} indexData Index data to save
*/
async saveIndex(indexData) {
// Apply column sorting if any sorters are defined in options
if ("columnSorting" in indexData.options && Object.keys(indexData.options.columnSorting).length) {
for (let columnName in indexData.options.columnSorting) {
indexData = sortColumnInIndex(
indexData,
await this.loadAllTrackedTasks(indexData, columnName),
columnName,
indexData.options.columnSorting[columnName]
);
}
}
// If there is a separate config file, save options to this file
let ignoreOptions = false;
if (await this.configExists()) {
await this.saveConfig(indexData.options);
ignoreOptions = true;
}
// Save index
await fs.promises.writeFile(await this.getIndexPath(), parseIndex.json2md(indexData, ignoreOptions));
}
/**
* Load the index file and parse it to an object
* @return {Promise<object>} The index object
*/
async loadIndex() {
let indexData = "";
try {
indexData = await fs.promises.readFile(await this.getIndexPath(), { encoding: "utf-8" });
} catch (error) {
throw new Error(`Couldn't access index file: ${error.message}`);
}
const index = parseIndex.md2json(indexData);
// If configuration settings exist in a separate config file, merge them with index options
const config = await this.getConfig();
if (config !== null) {
index.options = { ...index.options, ...config };
}
return index;
}
/**
* Overwrite a task file with the specified data
* @param {string} path The task path
* @param {object} taskData The task data
*/
async saveTask(path, taskData) {
await fs.promises.writeFile(path, parseTask.json2md(taskData));
}
/**
* Load a task file and parse it to an object
* @param {string} taskId The task id
* @return {Promise<object>} The task object
*/
async loadTask(taskId) {
const taskPath = path.join(await this.getTaskFolderPath(), addFileExtension(taskId));
let taskData = "";
try {
taskData = await fs.promises.readFile(taskPath, { encoding: "utf-8" });
} catch (error) {
throw new Error(`Couldn't access task file: ${error.message}`);
}
return parseTask.md2json(taskData);
}
/**
* Load all tracked tasks and return an array of task objects
* @param {object} index The index object
* @param {?string} [columnName=null] The optional column name to filter tasks by
* @return {Promise<object[]>} All tracked tasks
*/
async loadAllTrackedTasks(index, columnName = null) {
const result = [];
const trackedTasks = getTrackedTaskIds(index, columnName);
for (let taskId of trackedTasks) {
result.push(await this.loadTask(taskId));
}
return result;
}
/**
* Load a task file from the archive and parse it to an object
* @param {string} taskId The task id
* @return {Promise<object>} The task object
*/
async loadArchivedTask(taskId) {
const taskPath = path.join(await this.getArchiveFolderPath(), addFileExtension(taskId));
let taskData = "";
try {
taskData = await fs.promises.readFile(taskPath, { encoding: "utf-8" });
} catch (error) {
throw new Error(`Couldn't access archived task file: ${error.message}`);
}
return parseTask.md2json(taskData);
}
/**
* Get the date format defined in the index, or the default date format
* @param {object} index The index object
* @return {string} The date format
*/
getDateFormat(index) {
return "dateFormat" in index.options ? index.options.dateFormat : DEFAULT_DATE_FORMAT;
}
/**
* Get the task template for displaying tasks on the kanbn board from the index, or the default task template
* @param {object} index The index object
* @return {string} The task template
*/
getTaskTemplate(index) {
return "taskTemplate" in index.options ? index.options.taskTemplate : DEFAULT_TASK_TEMPLATE;
}
/**
* Check if the current working directory has been initialised
* @return {Promise<boolean>} True if the current working directory has been initialised, otherwise false
*/
async initialised() {
return await exists(await this.getIndexPath());
}
/**
* Initialise a kanbn board in the current working directory
* @param {object} [options={}] Initial columns and other config options
*/
async initialise(options = {}) {
// Check if a main folder is defined in an existing config file
const mainFolder = await this.getMainFolder();
// Create main folder if it doesn't already exist
if (!(await exists(mainFolder))) {
await fs.promises.mkdir(mainFolder, { recursive: true });
}
// Create tasks folder if it doesn't already exist
const taskFolder = await this.getTaskFolderPath();
if (!(await exists(taskFolder))) {
await fs.promises.mkdir(taskFolder, { recursive: true });
}
// Create index if one doesn't already exist
let index;
if (!(await exists(await this.getIndexPath()))) {
// If config already exists in a separate file, merge it into the options
const config = await this.getConfig();
// Create initial options
const opts = Object.assign({}, defaultInitialiseOptions, options);
index = {
name: opts.name,
description: opts.description,
options: Object.assign({}, opts.options, config || {}),
columns: Object.fromEntries(opts.columns.map((columnName) => [columnName, []])),
};
// Otherwise, if index already exists and we have specified new settings, re-write the index file
} else if (Object.keys(options).length > 0) {
index = await this.loadIndex();
"name" in options && (index.name = options.name);
"description" in options && (index.description = options.description);
"options" in options && (index.options = Object.assign(index.options, options.options));
"columns" in options &&
(index.columns = Object.assign(
index.columns,
Object.fromEntries(
options.columns.map((columnName) => [
columnName,
columnName in index.columns ? index.columns[columnName] : [],
])
)
));
}
await this.saveIndex(index);
}
/**
* Check if a task file exists and is in the index, otherwise throw an error
* @param {string} taskId The task id to check
*/
async taskExists(taskId) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Check if the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Check that the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`No task with id "${taskId}" found in the index`);
}
}
/**
* Get the column that a task is in or throw an error if the task doesn't exist or isn't indexed
* @param {string} taskId The task id to find
* @return {Promise<string>} The name of the column the task is in
*/
async findTaskColumn(taskId) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Check if the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Check that the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`No task with id "${taskId}" found in the index`);
}
// Find which column the task is in
return findTaskColumn(index, taskId);
}
/**
* Create a task file and add the task to the index
* @param {object} taskData The task object
* @param {string} columnName The name of the column to add the task to
* @return {Promise<string>} The id of the task that was created
*/
async createTask(taskData, columnName) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Make sure the task has a name
if (!taskData.name) {
throw new Error("Task name cannot be blank");
}
// Make sure a task doesn't already exist with the same name
const taskId = utility.getTaskId(taskData.name);
const taskPath = getTaskPath(await this.getTaskFolderPath(), taskId);
if (await exists(taskPath)) {
throw new Error(`A task with id "${taskId}" already exists`);
}
// Get index and make sure the column exists
let index = await this.loadIndex();
if (!(columnName in index.columns)) {
throw new Error(`Column "${columnName}" doesn't exist`);
}
// Check that a task with the same id isn't already indexed
if (taskInIndex(index, taskId)) {
throw new Error(`A task with id "${taskId}" is already in the index`);
}
// Set the created date
taskData = setTaskMetadata(taskData, "created", new Date());
// Add initial history event
taskData = appendTaskHistory(taskData, {
type: 'created',
column: columnName,
fromProgress: 0,
toProgress: getTaskMetadata(taskData, 'progress') || 0
});
// Update task metadata dates
taskData = updateColumnLinkedCustomFields(index, taskData, columnName);
await this.saveTask(taskPath, taskData);
// Add the task to the index
index = addTaskToIndex(index, taskId, columnName);
await this.saveIndex(index);
return taskId;
}
/**
* Add an untracked task to the specified column in the index
* @param {string} taskId The untracked task id
* @param {string} columnName The column to add the task to
* @return {Promise<string>} The id of the task that was added
*/
async addUntrackedTaskToIndex(taskId, columnName) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the column exists
let index = await this.loadIndex();
if (!(columnName in index.columns)) {
throw new Error(`Column "${columnName}" doesn't exist`);
}
// Check that the task isn't already indexed
if (taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is already in the index`);
}
// Load task data
let taskData = await this.loadTask(taskId);
const taskPath = getTaskPath(await this.getTaskFolderPath(), taskId);
// Update task metadata dates
taskData = updateColumnLinkedCustomFields(index, taskData, columnName);
await this.saveTask(taskPath, taskData);
// Add the task to the column and save the index
index = addTaskToIndex(index, taskId, columnName);
await this.saveIndex(index);
return taskId;
}
/**
* Get a list of tracked tasks (i.e. tasks that are listed in the index)
* @param {?string} [columnName=null] The optional column name to filter tasks by
* @return {Promise<Set>} A set of task ids
*/
async findTrackedTasks(columnName = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get all tasks currently in index
const index = await this.loadIndex();
return getTrackedTaskIds(index, columnName);
}
/**
* Get a list of untracked tasks (i.e. markdown files in the tasks folder that aren't listed in the index)
* @return {Promise<Set>} A set of untracked task ids
*/
async findUntrackedTasks() {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get all tasks currently in index
const index = await this.loadIndex();
const trackedTasks = getTrackedTaskIds(index);
// Get all tasks in the tasks folder
const files = await glob(`${await this.getTaskFolderPath()}/*.md`);
const untrackedTasks = new Set(files.map((task) => path.parse(task).name));
// Return the set difference
return new Set([...untrackedTasks].filter((x) => !trackedTasks.has(x)));
}
/**
* Update an existing task
* @param {string} taskId The id of the task to update
* @param {object} taskData The new task data
* @param {?string} [columnName=null] The column name to move this task to, or null if not moving this task
* @param {string[]} [unsetFields=[]] Metadata field names to remove from the task
* @return {Promise<string>} The id of the task that was updated
*/
async updateTask(taskId, taskData, columnName = null, unsetFields = []) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Make sure the updated task data has a name
if (!taskData.name) {
throw new Error("Task name cannot be blank");
}
// Rename the task if we're updating the name
const originalTaskData = await this.loadTask(taskId);
if (originalTaskData.name !== taskData.name) {
taskId = await this.renameTask(taskId, taskData.name);
// Re-load the index
index = await this.loadIndex();
}
// Get index and make sure the column exists
if (columnName && !(columnName in index.columns)) {
throw new Error(`Column "${columnName}" doesn't exist`);
}
// Set the updated date
taskData = setTaskMetadata(taskData, "updated", new Date());
// Add history for progress changes only
const originalProgress = getTaskMetadata(originalTaskData, 'progress') || 0;
const updatedProgress = getTaskMetadata(taskData, 'progress') || 0;
if (originalProgress !== updatedProgress) {
taskData = appendTaskHistory(taskData, {
type: 'progress',
fromProgress: originalProgress,
toProgress: updatedProgress
});
}
// Save task
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), taskId), taskData);
// Move the task if we're updating the column
if (columnName) {
await this.moveTask(taskId, columnName);
// Otherwise save the index
} else {
await this.saveIndex(index);
}
// Remove any explicitly unset metadata fields last. This has to happen after the move, because
// moving into a started or completed column stamps the linked date fields - an explicit unset
// from the user should win over that automatic stamp
if (unsetFields.length) {
const finalTaskData = await this.loadTask(taskId);
if ("metadata" in finalTaskData) {
for (const field of unsetFields) {
delete finalTaskData.metadata[field];
}
}
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), taskId), finalTaskData);
}
return taskId;
}
/**
* Change a task name, rename the task file and update the task id in the index
* @param {string} taskId The id of the task to rename
* @param {string} newTaskName The new task name
* @return {Promise<string>} The new id of the task that was renamed
*/
async renameTask(taskId, newTaskName) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Make sure there isn't already a task with the new task id
const newTaskId = utility.getTaskId(newTaskName);
const newTaskPath = getTaskPath(await this.getTaskFolderPath(), newTaskId);
if (await exists(newTaskPath)) {
throw new Error(`A task with id "${newTaskId}" already exists`);
}
// Check that a task with the new id isn't already indexed
if (taskInIndex(index, newTaskId)) {
throw new Error(`A task with id "${newTaskId}" is already in the index`);
}
// Update the task name and updated date
let taskData = await this.loadTask(taskId);
taskData.name = newTaskName;
taskData = setTaskMetadata(taskData, "updated", new Date());
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), taskId), taskData);
// Rename the task file
await fs.promises.rename(getTaskPath(await this.getTaskFolderPath(), taskId), newTaskPath);
// Update the task id in the index
index = renameTaskInIndex(index, taskId, newTaskId);
await this.saveIndex(index);
return newTaskId;
}
/**
* Move a task from one column to another column
* @param {string} taskId The task id to move
* @param {string} columnName The name of the column that the task will be moved to
* @param {?number} [position=null] The position to move the task to within the target column
* @param {boolean} [relative=false] Treat the position argument as relative instead of absolute
* @return {Promise<string>} The id of the task that was moved
*/
async moveTask(taskId, columnName, position = null, relative = false) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Make sure the target column exists
if (!(columnName in index.columns)) {
throw new Error(`Column "${columnName}" doesn't exist`);
}
// Find current column before mutating data
const currentColumnName = findTaskColumn(index, taskId);
// Stamp every date this move writes with the same timestamp, so that the history event and the
// dates it backfills from can't disagree by a millisecond
const moveDate = new Date();
// Update the task's updated date
let taskData = await this.loadTask(taskId);
taskData = setTaskMetadata(taskData, "updated", moveDate);
// Add history only when a task changes columns
if (currentColumnName !== columnName) {
taskData = appendTaskHistory(taskData, {
date: moveDate,
type: 'moved',
fromColumn: currentColumnName,
toColumn: columnName
});
}
// Update task metadata dates
taskData = updateColumnLinkedCustomFields(index, taskData, columnName, moveDate);
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), taskId), taskData);
// If we're moving the task to a new position, calculate the absolute position
const currentPosition = index.columns[currentColumnName].indexOf(taskId);
if (position) {
if (relative) {
position = currentPosition + position;
}
position = Math.max(Math.min(position, index.columns[currentColumnName].length), 0);
}
// Remove the task from its current column and add it to the new column
index = removeTaskFromIndex(index, taskId);
index = addTaskToIndex(index, taskId, columnName, position);
await this.saveIndex(index);
return taskId;
}
/**
* Remove a task from the index and optionally delete the task file as well
* @param {string} taskId The id of the task to remove
* @param {boolean} [removeFile=false] True if the task file should be removed
* @return {Promise<string>} The id of the task that was deleted
*/
async deleteTask(taskId, removeFile = false) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Remove the task from whichever column it's in
index = removeTaskFromIndex(index, taskId);
// Optionally remove the task file as well
if (removeFile && (await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
await fs.promises.unlink(getTaskPath(await this.getTaskFolderPath(), taskId));
}
await this.saveIndex(index);
return taskId;
}
/**
* Search for indexed tasks
* @param {object} [filters={}] The filters to apply
* @param {boolean} [quiet=false] Only return task ids if true, otherwise return full task details
* @return {Promise<object[]>} A list of tasks that match the filters
*/
async search(filters = {}, quiet = false) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Load all tracked tasks and filter the results
const index = await this.loadIndex();
let tasks = filterTasks(index, await this.loadAllTrackedTasks(index), filters);
// Return resulting task ids or the full tasks
return tasks.map((task) => {
return quiet ? utility.getTaskId(task.name) : this.hydrateTask(index, task);
});
}
/**
* Output project status information
* @param {boolean} [quiet=false] Output full or partial status information
* @param {boolean} [untracked=false] Show a list of untracked tasks
* @param {boolean} [due=false] Show information about overdue tasks and time remaining
* @param {?string|?number} [sprint=null] The sprint name or number to show stats for, or null for current sprint
* @param {?Date[]} [dates=null] The date(s) to show stats for, or null for no date filter
* @return {Promise<object|string[]>} Project status information as an object, or an array of untracked task filenames
*/
async status(quiet = false, untracked = false, due = false, sprint = null, dates = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get index and column names
const index = await this.loadIndex();
const columnNames = Object.keys(index.columns);
const startedField = getStartedField(index);
const completedField = getCompletedField(index);
// Prepare output
const result = {
name: index.name,
};
// Get un-tracked tasks if required
if (untracked) {
result.untrackedTasks = [...(await this.findUntrackedTasks())].map((taskId) => `${taskId}.md`);
// If output is quiet, output a list of untracked task filenames
if (quiet) {
return result.untrackedTasks;
}
}
// Get basic project status information
result.tasks = columnNames.reduce((a, v) => a + index.columns[v].length, 0);
result.columnTasks = Object.fromEntries(
columnNames.map((columnName) => [columnName, index.columns[columnName].length])
);
if ("startedColumns" in index.options && index.options.startedColumns.length > 0) {
result.startedTasks = Object.entries(index.columns)
.filter((c) => index.options.startedColumns.indexOf(c[0]) > -1)
.reduce((a, c) => a + c[1].length, 0);
}
if ("completedColumns" in index.options && index.options.completedColumns.length > 0) {
result.completedTasks = Object.entries(index.columns)
.filter((c) => index.options.completedColumns.indexOf(c[0]) > -1)
.reduce((a, c) => a + c[1].length, 0);
}
// If required, load more detailed task information
if (!quiet) {
// Load all tracked tasks and hydrate them
const tasks = [...(await this.loadAllTrackedTasks(index))].map((task) => this.hydrateTask(index, task));
// If showing due information, calculate time remaining or overdue time for each task
if (due) {
result.dueTasks = [];
tasks.forEach((task) => {
if ("dueData" in task) {
result.dueTasks.push({
task: task.id,
workload: task.workload,
progress: task.progress,
remainingWorkload: task.remainingWorkload,
...task.dueData,
});
}
});
}
// Calculate total and per-column workload
let totalWorkload = 0,
totalRemainingWorkload = 0;
const columnWorkloads = tasks.reduce(
(a, task) => {
totalWorkload += task.workload;
totalRemainingWorkload += task.remainingWorkload;
a[task.column].workload += task.workload;
a[task.column].remainingWorkload += task.remainingWorkload;
return a;
},
Object.fromEntries(
columnNames.map((columnName) => [
columnName,
{
workload: 0,
remainingWorkload: 0,
},
])
)
);
result.totalWorkload = totalWorkload;
result.totalRemainingWorkload = totalRemainingWorkload;
result.columnWorkloads = columnWorkloads;
result.taskWorkloads = Object.fromEntries(
tasks.map((task) => [
task.id,
{
workload: task.workload,
progress: task.progress,
remainingWorkload: task.remainingWorkload,
completed: taskCompleted(index, task),
},
])
);
// Calculate assigned task totals and workloads
const assignedTasks = tasks.reduce((a, task) => {
if ("assigned" in task.metadata) {
if (!(task.metadata.assigned in a)) {
a[task.metadata.assigned] = {
total: 0,
workload: 0,
remainingWorkload: 0,
};
}
a[task.metadata.assigned].total++;
a[task.metadata.assigned].workload += task.workload;
a[task.metadata.assigned].remainingWorkload += task.remainingWorkload;
}
return a;
}, {});
if (Object.keys(assignedTasks).length > 0) {
result.assigned = assignedTasks;
}
// If any sprints are defined in index options, calculate sprint statistics
if ("sprints" in index.options && index.options.sprints.length) {
const sprints = index.options.sprints;
// Default to current sprint
const currentSprint = index.options.sprints.length;
let sprintIndex = currentSprint - 1;
// Check if we're requesting stats for a specific sprint
if (sprint !== null) {
// Select sprint by number (1-based index)
if (typeof sprint === "number") {
if (sprint < 1 || sprint > sprints.length) {
throw new Error(`Sprint ${sprint} does not exist`);
} else {
sprintIndex = sprint - 1;
}
// Or select sprint by name
} else if (typeof sprint === "string") {
sprintIndex = sprints.findIndex((s) => s.name === sprint);
if (sprintIndex === -1) {
throw new Error(`No sprint found with name "${sprint}"`);
}
}
}
// Add sprint information
result.sprint = {
number: sprintIndex + 1,
name: sprints[sprintIndex].name,
start: sprints[sprintIndex].start,
};
if (currentSprint - 1 !== sprintIndex) {
if (sprintIndex === sprints.length - 1) {
result.sprint.end = sprints[sprintIndex + 1].start;
}
result.sprint.current = currentSprint;
}
if (sprints[sprintIndex].description) {
result.sprint.description = sprints[sprintIndex].description;
}
const sprintStartDate = sprints[sprintIndex].start;
const sprintEndDate = sprintIndex === sprints.length - 1 ? new Date() : sprints[sprintIndex + 1].start;
// Calculate sprint duration
const duration = sprintEndDate - sprintStartDate;
result.sprint.durationDelta = duration;
result.sprint.durationMessage = humanizeDuration(duration, {
largest: 3,
round: true,
});
// Add task workload information for the sprint
result.sprint.created = taskWorkloadInPeriod(tasks, "created", sprintStartDate, sprintEndDate);
result.sprint.started = taskWorkloadInPeriod(tasks, startedField, sprintStartDate, sprintEndDate);
result.sprint.completed = taskWorkloadInPeriod(tasks, completedField, sprintStartDate, sprintEndDate);
result.sprint.due = taskWorkloadInPeriod(tasks, "due", sprintStartDate, sprintEndDate);
// Add custom date property workload information for the sprint
if ("customFields" in index.options) {
for (let customField of index.options.customFields) {
if (customField.type === "date") {
result.sprint[customField.name] = taskWorkloadInPeriod(
tasks,
customField.name,
sprintStartDate,
sprintEndDate
);
}
}
}
}
// If any dates were specified, calculate task statistics for these dates
if (dates !== null && dates.length > 0) {
let periodStart, periodEnd;
result.period = {};
if (dates.length === 1) {
periodStart = new Date(+dates[0]);
periodStart.setHours(0, 0, 0, 0);
periodEnd = new Date(+dates[0]);
periodEnd.setHours(23, 59, 59, 999);
result.period.start = periodStart;
result.period.end = periodEnd;
} else {
result.period.start = periodStart = new Date(Math.min(...dates));
result.period.end = periodEnd = new Date(Math.max(...dates));
}
result.period.created = taskWorkloadInPeriod(tasks, "created", periodStart, periodEnd);
result.period.started = taskWorkloadInPeriod(tasks, startedField, periodStart, periodEnd);
result.period.completed = taskWorkloadInPeriod(tasks, completedField, periodStart, periodEnd);
result.period.due = taskWorkloadInPeriod(tasks, "due", periodStart, periodEnd);
// Add custom date property workload information for the selected date range
if ("customFields" in index.options) {
for (let customField of index.options.customFields) {
if (customField.type === "date") {
result.sprint[customField.name] = taskWorkloadInPeriod(tasks, customField.name, periodStart, periodEnd);
}
}
}
}
}
return result;
}
/**
* Validate the index and task files
* @param {boolean} [save=false] Re-save all files
* @return {Promise<boolean>} True if everything validated, otherwise an array of parsing errors
*/
async validate(save = false) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
const errors = [];
// Load & parse index
let index = null;
try {
index = await this.loadIndex();
// Re-save index if required
if (save) {
await this.saveIndex(index);
}
} catch (error) {
errors.push({
task: null,
errors: error.message,
});
}
// Exit early if any errors were found in the index
if (errors.length) {
return errors;
}
// Load & parse tasks
const trackedTasks = getTrackedTaskIds(index);
for (let taskId of trackedTasks) {
try {
const task = await this.loadTask(taskId);
// Re-save tasks if required
if (save) {
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), taskId), task);
}
} catch (error) {
errors.push({
task: taskId,
errors: error.message,
});
}
}
// Return a list of errors or true if there were no errors
if (errors.length) {
return errors;
}
return true;
}
/**
* Find tasks whose started/completed dates disagree with the column they're in
*
* Task state comes from metadata dates only, so a task moved between columns by hand (by editing
* the index file, or through a merge) won't have had its dates updated. This reports both
* directions: a task sitting in a started or completed column with no date, and a task carrying a
* completed date while sitting somewhere else
* @return {Promise<object[]>} A list of drift entries
*/
async findDateDrift() {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
const index = await this.loadIndex();
const tasks = [];
for (const taskId of getTrackedTaskIds(index)) {
try {
tasks.push(await this.loadTask(taskId));
} catch (error) {
// Unreadable tasks are reported by validate(), not here
}
}
return this.getDateDrift(index, tasks);
}
/**
* Find date drift in a list of tasks that have already been loaded
* @param {object} index The index object
* @param {object[]} tasks Loaded task objects
* @return {object[]} A list of drift entries
*/
getDateDrift(index, tasks) {
const startedField = getStartedField(index);
const completedField = getCompletedField(index);
const startedColumns = "startedColumns" in index.options ? index.options.startedColumns : [];
const completedColumns = "completedColumns" in index.options ? index.options.completedColumns : [];
const drift = [];
for (const task of tasks) {
const column = findTaskColumn(index, task.id);
// A task in a started or completed column with no date to say when that happened. The date is
// usually recoverable from history, so these can be backfilled
for (const [field, columns] of [[completedField, completedColumns], [startedField, startedColumns]]) {
if (columns.indexOf(column) === -1 || field in task.metadata) {
continue;
}
const historyDate = findColumnEntryDate(task, columns);
const date = historyDate
|| ("updated" in task.metadata ? task.metadata.updated : null)
|| ("created" in task.metadata ? task.metadata.created : null);
drift.push({
task: task.id,
column,
field,
issue: "missing",
message: `task is in column "${column}" but has no ${field} date`,
fixable: date !== null,
date,
source: date === null
? null
: historyDate
? "history"
: "updated" in task.metadata && task.metadata.updated === date
? "updated"
: "created"
});
}
// A task carrying a completed date while sitting outside the completed columns. This is left
// alone: the date records something that really happened, and removing it would lose it
if (
completedColumns.length > 0 &&
completedField in task.metadata &&
completedColumns.indexOf(column) === -1
) {
drift.push({
task: task.id,
column,
field: completedField,
issue: "unexpected",
message: `task has a ${completedField} date but is in column "${column}"`,
fixable: false,
date: null,
source: null
});
}
}
return drift;
}
/**
* Check whether hints and notices should be shown for this board
* @param {object} index The index object
* @return {boolean} True if hints should be shown
*/
isVerbose(index) {
return !("verbose" in index.options) || index.options.verbose !== false;
}
/**
* Backfill missing started/completed dates for tasks that are in a started or completed column
* @return {Promise<object[]>} The drift entries that were fixed
*/
async fixDateDrift() {
const fixed = [];
for (const item of (await this.findDateDrift()).filter((d) => d.fixable && d.issue === "missing")) {
const task = await this.loadTask(item.task);
setTaskMetadata(task, item.field, item.date);
await this.saveTask(getTaskPath(await this.getTaskFolderPath(), item.task), task);
fixed.push(item);
}
return fixed;
}
/**
* Sort a column in the index
* @param {string} columnName The column name to sort
* @param {object[]} sorters A list of objects containing the field to sort by, filters and sort order
* @param {boolean} [save=false] True if the settings should be saved in index
*/
async sort(columnName, sorters, save = false) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get index and make sure the column exists
let index = await this.loadIndex();
if (!(columnName in index.columns)) {
throw new Error(`Column "${columnName}" doesn't exist`);
}
// Save the sorter settings if required (the column will be sorted when saving the index)
if (save) {
if (!("columnSorting" in index.options)) {
index.options.columnSorting = {};
}
index.options.columnSorting[columnName] = sorters;
// Otherwise, remove sorting settings for the specified column and manually sort the column
} else {
if ("columnSorting" in index.options && columnName in index.options.columnSorting) {
delete index.options.columnSorting[columnName];
}
const tasks = await this.loadAllTrackedTasks(index, columnName);
index = sortColumnInIndex(index, tasks, columnName, sorters);
}
await this.saveIndex(index);
}
/**
* Start a sprint
* @param {string} name Sprint name
* @param {string} description Sprint description
* @param {Date} start Sprint start date
* @return {Promise<object>} The sprint object
*/
async sprint(name, description, start) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get index and make sure it has a list of sprints in the options
const index = await this.loadIndex();
if (!("sprints" in index.options)) {
index.options.sprints = [];
}
const sprintNumber = index.options.sprints.length + 1;
const sprint = {
start: start,
};
// If the name is blank, generate a default name
if (!name) {
sprint.name = `Sprint ${sprintNumber}`;
} else {
sprint.name = name;
}
// Add description if one exists
if (description) {
sprint.description = description;
}
// Add sprint and save the index
index.options.sprints.push(sprint);
await this.saveIndex(index);
return sprint;
}
/**
* Output burndown chart data
* @param {?string[]} [sprints=null] The sprint names or numbers to show a chart for, or null for
* the current sprint
* @param {?Date[]} [dates=null] The dates to show a chart for, or null for no date filter
* @param {?string} [assigned=null] The assigned user to filter for, or null for no assigned filter
* @param {?string[]} [columns=null] The columns to filter for, or null for no column filter
* @param {?string} [normalise=null] The date normalisation mode
* @return {Promise<object>} Burndown chart data as an object
*/
async burndown(sprints = null, dates = null, assigned = null, columns = null, normalise = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Get index and tasks
const index = await this.loadIndex();
const startedField = getStartedField(index);
const completedField = getCompletedField(index);
const tasks = [...(await this.loadAllTrackedTasks(index))]
.map((task) => {
const taskColumn = findTaskColumn(index, task.id);
const created = "created" in task.metadata ? task.metadata.created : new Date(0);
return {
...task,
created,
// A task's started and completed dates come from its metadata only. They used to fall back
// to the task's created date whenever it sat in a started or completed column, which
// invented timings that had nothing to do with when the work actually happened
started: startedField in task.metadata ? task.metadata[startedField] : false,
completed: completedField in task.metadata ? task.metadata[completedField] : false,
progress: taskProgress(index, task),
assigned: "assigned" in task.metadata ? task.metadata.assigned : null,
workload: taskWorkload(index, task),
column: taskColumn,
};
})
.filter(
(task) =>
(assigned === null || task.assigned === assigned) &&
(columns === null || columns.indexOf(task.column) !== -1)
);
// Get sprints and dates to plot from arguments
const series = [];
const indexSprints = "sprints" in index.options && index.options.sprints.length ? index.options.sprints : null;
if (sprints === null && dates === null) {
if (indexSprints !== null) {
// Show current sprint
const currentSprint = indexSprints.length - 1;
series.push({
sprint: indexSprints[currentSprint],
from: new Date(indexSprints[currentSprint].start),
to: new Date(),
});
} else {
// Show all time
series.push({
from: new Date(
Math.min(
...tasks
.map((t) =>
[
"created" in t.metadata && t.metadata.created,
startedField in t.metadata && t.metadata[startedField],
completedField in t.metadata && (t.metadata[completedField] || new Date(8640000000000000))
].filter((d) => d)
)
.flat()
)
),
to: new Date(),
});
}
} else {
// Show specified sprint
if (sprints !== null) {
if (indexSprints === null) {
throw new Error(`No sprints defined`);
} else {
for (let sprint of sprints) {
let sprintIndex = null;
// Select sprint by number (1-based index)
if (typeof sprint === "number") {
if (sprint < 1 || sprint > indexSprints.length) {
throw new Error(`Sprint ${sprint} does not exist`);
} else {
sprintIndex = sprint - 1;
}
// Or select sprint by name
} else if (typeof sprint === "string") {
sprintIndex = indexSprints.findIndex((s) => s.name === sprint);
if (sprintIndex === -1) {
throw new Error(`No sprint found with name "${sprint}"`);
}
}
if (sprintIndex === null) {
throw new Error(`Invalid sprint "${sprint}"`);
}
// Get sprint start and end
series.push({
sprint: indexSprints[sprintIndex],
from: new Date(indexSprints[sprintIndex].start),
to: sprintIndex < indexSprints.length - 1 ? new Date(indexSprints[sprintIndex + 1].start) : new Date(),
});
}
}
}
// Show specified date range
if (dates !== null) {
series.push({
from: new Date(Math.min(...dates)),
to: dates.length === 1 ? new Date() : new Date(Math.max(...dates)),
});
}
}
// If normalise mode is 'auto', find the most appropriate normalisation mode
if (normalise === 'auto') {
const delta = series[0].to - series[0].from;
if (delta >= DAY * 7) {
normalise = 'days';
} else if (delta >= DAY) {
normalise = 'hours';
} else if (delta >= HOUR ) {
normalise = 'minutes';
} else {
normalise = 'seconds';
}
}
if (normalise !== null) {
// Normalize series from and to dates
series.forEach((s) => {
s.from = normaliseDate(s.from, normalise);
s.to = normaliseDate(s.to, normalise);
});
// Normalise task dates
tasks.forEach((task) => {
if ("history" in task && Array.isArray(task.history) && task.history.length > 0) {
task.history = task.history.map((historyEvent) => ({
...historyEvent,
date: historyEvent.date ? normaliseDate(historyEvent.date, normalise) : historyEvent.date
}));
}
if (task.created) {
task.created = normaliseDate(task.created, normalise);
}
if (task.started) {
task.started = normaliseDate(task.started, normalise);
}
if (task.completed) {
task.completed = normaliseDate(task.completed, normalise);
}
});
}
// Get workload datapoints for each period
series.forEach((s) => {
s.dataPoints = [
{
x: s.from,
y: getWorkloadAtDate(index, tasks, s.from),
count: countActiveTasksAtDate(index, tasks, s.from),
tasks: getTaskEventsAtDate(index, tasks, s.from),
},
...tasks
.map((task) => getTaskTimelineDates(task, s.from, s.to))
.flat()
.filter((d) => d)
.map((x) => ({
x,
y: getWorkloadAtDate(index, tasks, x),
count: countActiveTasksAtDate(index, tasks, x),
tasks: getTaskEventsAtDate(index, tasks, x),
})),
{
x: s.to,
y: getWorkloadAtDate(index, tasks, s.to),
count: countActiveTasksAtDate(index, tasks, s.to),
tasks: getTaskEventsAtDate(index, tasks, s.to),
},
].sort((a, b) => a.x.getTime() - b.x.getTime());
});
return { series };
}
/**
* Get a chronological list of task events from metadata dates and structured task history
* @param {?string[]} [sprints=null] The sprint names or numbers to include, or null for no sprint filter
* @param {?Date[]} [dates=null] One or more dates to define a range filter, or null for no date filter
* @param {?string} [assigned=null] The assigned user to filter for, or null for no assigned filter
* @param {?string[]} [taskIds=null] One or more task ids to filter for, or null for no task id filter
* @return {Promise<object>} A list of chronological task history events
*/
async history(sprints = null, dates = null, assigned = null, taskIds = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
const index = await this.loadIndex();
const selectedTaskIds = taskIds === null
? null
: new Set(taskIds.map((taskId) => removeFileExtension(taskId)));
// Build date filter periods from sprints and/or dates
const periods = [];
const indexSprints = "sprints" in index.options && index.options.sprints.length ? index.options.sprints : null;
if (sprints !== null) {
if (indexSprints === null) {
throw new Error("No sprints defined");
}
for (let sprint of sprints) {
let sprintIndex = null;
// Select sprint by number (1-based index)
if (typeof sprint === "number") {
if (sprint < 1 || sprint > indexSprints.length) {
throw new Error(`Sprint ${sprint} does not exist`);
}
sprintIndex = sprint - 1;
// Or select sprint by name
} else if (typeof sprint === "string") {
sprintIndex = indexSprints.findIndex((s) => s.name === sprint);
if (sprintIndex === -1) {
throw new Error(`No sprint found with name "${sprint}"`);
}
}
if (sprintIndex === null) {
throw new Error(`Invalid sprint "${sprint}"`);
}
periods.push({
type: "sprint",
label: indexSprints[sprintIndex].name,
from: new Date(indexSprints[sprintIndex].start),
to: sprintIndex < indexSprints.length - 1
? new Date(indexSprints[sprintIndex + 1].start)
: new Date(),
});
}
}
if (dates !== null) {
periods.push({
type: "date",
from: new Date(Math.min(...dates)),
to: dates.length === 1 ? new Date() : new Date(Math.max(...dates)),
});
}
const includeEventDate = (date) => {
if (!(date instanceof Date) || isNaN(date.getTime())) {
return false;
}
if (periods.length === 0) {
return true;
}
return periods.some((period) => date >= period.from && date <= period.to);
};
const buildBaseTask = (task) => ({
id: task.id,
name: task.name,
assigned: getTaskMetadata(task, "assigned") || null,
column: findTaskColumn(index, task.id),
});
const tasks = await this.loadAllTrackedTasks(index);
let events = tasks
.filter((task) => {
const assignedUser = getTaskMetadata(task, "assigned") || null;
return (
(assigned === null || assignedUser === assigned) &&
(selectedTaskIds === null || selectedTaskIds.has(task.id))
);
})
.map((task) => {
const taskBase = buildBaseTask(task);
const metadataEvents = Object.entries(task.metadata)
.filter(([, value]) => value instanceof Date)
.map(([field, value]) => ({
date: value,
source: "metadata",
eventType: field,
task: taskBase,
event: {
field,
value,
},
}));
const historyEvents = ("history" in task && Array.isArray(task.history) ? task.history : [])
.filter((historyEvent) => historyEvent.date instanceof Date)
.map((historyEvent) => {
const event = { ...historyEvent };
delete event.date;
return {
date: historyEvent.date,
source: "history",
eventType: historyEvent.type,
task: taskBase,
event,
};
});
return [...metadataEvents, ...historyEvents];
})
.flat()
.filter((event) => includeEventDate(event.date));
events.sort((a, b) => compareValues(a.date, b.date) || compareValues(a.task.id, b.task.id));
return { periods, events };
}
/**
* Output gantt chart data
* @param {?string} [assigned=null] The assigned user to filter for, or null for no assigned filter
* @param {?string[]} [columns=null] The columns to filter for, or null for no column filter
* @param {?Date[]} [dates=null] The dates to filter for (tasks created within range), or null for no date filter
* @param {?Date} [now=null] Optional date to treat as the current time
* @return {Promise<object>} Gantt chart data as an object
*/
async gantt(assigned = null, columns = null, dates = null, now = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
const effectiveNow = now instanceof Date ? now : new Date();
// Get index and tasks
const index = await this.loadIndex();
const startedField = getStartedField(index);
const completedField = getCompletedField(index);
const tasks = [...(await this.loadAllTrackedTasks(index))]
.map((task) => {
const taskColumn = findTaskColumn(index, task.id);
const created = "created" in task.metadata ? task.metadata.created : new Date(0);
return {
...task,
created,
started: startedField in task.metadata ? task.metadata[startedField] : false,
completed: completedField in task.metadata ? task.metadata[completedField] : false,
plannedStart: "plannedStart" in task.metadata ? task.metadata.plannedStart : false,
plannedFinish: "plannedFinish" in task.metadata ? task.metadata.plannedFinish : false,
workload: taskWorkload(index, task),
progress: taskProgress(index, task),
column: taskColumn,
assignedUser: "assigned" in task.metadata ? task.metadata.assigned : null,
};
})
.filter(
(task) => {
// Filter by assigned user
if (assigned !== null && task.assignedUser !== assigned) {
return false;
}
// Filter by columns
if (columns !== null && !columns.includes(task.column)) {
return false;
}
// Filter by date range
if (dates !== null && dates.length > 0) {
const from = Math.min(...dates);
const to = dates.length === 1 ? effectiveNow.getTime() : Math.max(...dates);
if (task.created.getTime() < from || task.created.getTime() > to) {
return false;
}
}
return true;
}
);
const trackedTaskIds = getTrackedTaskIds(index);
return buildGanttSchedule(index, tasks, effectiveNow, trackedTaskIds);
}
/**
* Add a comment to a task
* @param {string} taskId The task id
* @param {string} text The comment text
* @param {string} author The comment author
* @return {Promise<string>} The task id
*/
async comment(taskId, text, author) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Make sure the comment text isn't empty
if (!text) {
throw new Error("Comment text cannot be empty");
}
// Add the comment
const taskData = await this.loadTask(taskId);
const taskPath = getTaskPath(await this.getTaskFolderPath(), taskId);
taskData.comments.push({
text,
author,
date: new Date(),
});
// Save the task
await this.saveTask(taskPath, taskData);
return taskId;
}
/**
* Return a list of archived tasks
* @return {Promise<string[]>} A list of archived task ids
*/
async listArchivedTasks() {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
// Make sure the archive folder exists
const archiveFolder = await this.getArchiveFolderPath();
if (!(await exists(archiveFolder))) {
throw new Error("Archive folder doesn't exist");
}
// Get a list of archived task files
const files = await glob(`${archiveFolder}/*.md`);
return [...new Set(files.map((task) => path.parse(task).name))];
}
/**
* Move a task to the archive
* @param {string} taskId The task id
* @return {Promise<string>} The task id
*/
async archiveTask(taskId) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
// Make sure the task file exists
if (!(await exists(getTaskPath(await this.getTaskFolderPath(), taskId)))) {
throw new Error(`No task file found with id "${taskId}"`);
}
// Get index and make sure the task is indexed
let index = await this.loadIndex();
if (!taskInIndex(index, taskId)) {
throw new Error(`Task "${taskId}" is not in the index`);
}
// Make sure there isn't already an archived task with the same id
const archiveFolder = await this.getArchiveFolderPath();
const archivedTaskPath = getTaskPath(archiveFolder, taskId);
if (await exists(archivedTaskPath)) {
throw new Error(`An archived task with id "${taskId}" already exists`);
}
// Create archive folder if it doesn't already exist
if (!(await exists(archiveFolder))) {
await fs.promises.mkdir(archiveFolder, { recursive: true });
}
// Save the column name in the task's metadata
let taskData = await this.loadTask(taskId);
const taskColumn = findTaskColumn(index, taskId);
taskData = setTaskMetadata(taskData, "column", taskColumn);
// Add history event
taskData = appendTaskHistory(taskData, {
type: 'archived',
fromColumn: taskColumn
});
// Save the task inside the archive folder
await this.saveTask(archivedTaskPath, taskData);
// Remove the original task
await this.deleteTask(taskId, true);
return taskId;
}
/**
* Restore a task from the archive
* @param {string} taskId The task id
* @param {?string} [columnName=null] The column to restore the task to
* @return {Promise<string>} The task id
*/
async restoreTask(taskId, columnName = null) {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
taskId = removeFileExtension(taskId);
const archiveFolder = await this.getArchiveFolderPath();
const archivedTaskPath = getTaskPath(archiveFolder, taskId);
const taskPath = getTaskPath(await this.getTaskFolderPath(), taskId);
// Make sure the archive folder exists
if (!(await exists(archiveFolder))) {
throw new Error("Archive folder doesn't exist");
}
// Make sure the task file exists in the archive
if (!(await exists(archivedTaskPath))) {
throw new Error(`No archived task found with id "${taskId}"`);
}
// Get index and make sure there isn't already an indexed task with the same id
let index = await this.loadIndex();
if (taskInIndex(index, taskId)) {
throw new Error(`There is already an indexed task with id "${taskId}"`);
}
// Check if there is already a task with the same id
if (await exists(taskPath)) {
throw new Error(`There is already an untracked task with id "${taskId}"`);
}
// Make sure the index has some columns
const columns = Object.keys(index.columns);
if (columns.length === 0) {
throw new Error('No columns defined in the index');
}
// Load the task from the archive
let taskData = await this.loadArchivedTask(taskId);
let actualColumnName = columnName || getTaskMetadata(taskData, "column") || columns[0];
taskData = setTaskMetadata(taskData, "column", undefined);
// Add history event
taskData = appendTaskHistory(taskData, {
type: 'restored',
toColumn: actualColumnName
});
// Update task metadata dates and save task
taskData = updateColumnLinkedCustomFields(index, taskData, actualColumnName);
await this.saveTask(taskPath, taskData);
// Add the task to the column and save the index
index = addTaskToIndex(index, taskId, actualColumnName);
await this.saveIndex(index);
// Delete the archived task file
await fs.promises.unlink(archivedTaskPath);
return taskId;
}
/**
* Nuke it from orbit, it's the only way to be sure
*/
async removeAll() {
// Check if this folder has been initialised
if (!(await this.initialised())) {
throw new Error("Not initialised in this folder");
}
rimraf.sync(await this.getMainFolder());
}
};
// Preserve backward compatibility for existing callers that expect
// require('./main') to expose the Kanbn API directly.
const kanbn = new Kanbn();
module.exports = kanbn;
module.exports.Kanbn = Kanbn;
|