@quartzio/gantt 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/API.md +533 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -2
  4. package/dist/index.d.ts +1341 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +6556 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/styles.css +1299 -0
  9. package/package.json +51 -3
  10. package/src/calendar/duration.ts +42 -0
  11. package/src/calendar/project.ts +29 -0
  12. package/src/calendar/workingCalendar.ts +218 -0
  13. package/src/data/draft.ts +78 -0
  14. package/src/data/graph.ts +215 -0
  15. package/src/data/normalize.ts +661 -0
  16. package/src/data/operations.ts +112 -0
  17. package/src/data/project.ts +194 -0
  18. package/src/data/serialize.ts +26 -0
  19. package/src/data/transaction.ts +460 -0
  20. package/src/data/tree.ts +156 -0
  21. package/src/data/types.ts +229 -0
  22. package/src/index.ts +139 -0
  23. package/src/scheduling/schedule.ts +310 -0
  24. package/src/styles.css +1299 -0
  25. package/src/timeaxis/align.ts +120 -0
  26. package/src/timeaxis/format.ts +72 -0
  27. package/src/timeaxis/presets.ts +219 -0
  28. package/src/timeaxis/timeAxis.ts +205 -0
  29. package/src/util/civil.ts +38 -0
  30. package/src/util/emitter.ts +53 -0
  31. package/src/util/equal.ts +23 -0
  32. package/src/util/errors.ts +4 -0
  33. package/src/util/parse.ts +70 -0
  34. package/src/util/time.ts +18 -0
  35. package/src/util/zone.ts +303 -0
  36. package/src/view/bars.ts +63 -0
  37. package/src/view/binding.ts +162 -0
  38. package/src/view/cellEditor.ts +239 -0
  39. package/src/view/cells.ts +89 -0
  40. package/src/view/columns.ts +197 -0
  41. package/src/view/createGantt.ts +1164 -0
  42. package/src/view/dates.ts +14 -0
  43. package/src/view/dependencies.ts +147 -0
  44. package/src/view/editing.ts +303 -0
  45. package/src/view/history.ts +72 -0
  46. package/src/view/interaction.ts +671 -0
  47. package/src/view/keyboard.ts +149 -0
  48. package/src/view/listWidth.ts +201 -0
  49. package/src/view/menu.ts +265 -0
  50. package/src/view/nonWorking.ts +113 -0
  51. package/src/view/range.ts +41 -0
  52. package/src/view/rows.ts +235 -0
  53. package/src/view/selection.ts +156 -0
  54. package/src/view/taskActions.ts +71 -0
  55. package/src/view/taskEditor.ts +553 -0
  56. package/src/view/timeline.ts +155 -0
  57. package/src/view/tooltip.ts +117 -0
  58. package/src/view/types.ts +328 -0
@@ -0,0 +1,53 @@
1
+ export type Listener<T> = (value: T) => void;
2
+
3
+ export interface Emitter<T> {
4
+ subscribe: (listener: Listener<T>) => () => void;
5
+ emit: (value: T) => void;
6
+ clear: () => void;
7
+ }
8
+
9
+ export function createEmitter<T>(): Emitter<T> {
10
+ // Each subscription gets its own entry, so subscribing the same function twice needs two unsubscribes.
11
+ const listeners = new Set<{ listener: Listener<T> }>();
12
+ const queue: T[] = [];
13
+ let emitting = false;
14
+
15
+ return {
16
+ subscribe(listener) {
17
+ const entry = { listener };
18
+ listeners.add(entry);
19
+ return () => {
20
+ listeners.delete(entry);
21
+ };
22
+ },
23
+ emit(value) {
24
+ queue.push(value);
25
+ // An event emitted from inside a listener waits until everyone has seen the current one, so every
26
+ // listener sees events in the same order (and the last one it sees is the latest).
27
+ if (emitting) return;
28
+ emitting = true;
29
+ let failure: { error: unknown } | undefined;
30
+ try {
31
+ // An array iterator also visits items appended while iterating: events queued by listeners.
32
+ for (const next of queue) {
33
+ // Snapshot so listeners that unsubscribe during emit don't skip their neighbours.
34
+ for (const entry of [...listeners]) {
35
+ // One failing listener must not keep the others from being notified; rethrow afterwards.
36
+ try {
37
+ entry.listener(next);
38
+ } catch (error) {
39
+ failure ??= { error };
40
+ }
41
+ }
42
+ }
43
+ } finally {
44
+ emitting = false;
45
+ queue.length = 0;
46
+ }
47
+ if (failure) throw failure.error;
48
+ },
49
+ clear() {
50
+ listeners.clear();
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,23 @@
1
+ /** Structural equality for JSON-like values (primitives, arrays, plain objects). */
2
+ export function isEqual(a: unknown, b: unknown): boolean {
3
+ if (Object.is(a, b)) return true;
4
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
5
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
6
+ const keysA = Object.keys(a);
7
+ const keysB = Object.keys(b);
8
+ if (keysA.length !== keysB.length) return false;
9
+ return keysA.every(
10
+ (key) =>
11
+ Object.hasOwn(b, key) &&
12
+ isEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),
13
+ );
14
+ }
15
+
16
+ /** Freezes an object and everything reachable from it. */
17
+ export function deepFreeze<T>(value: T): T {
18
+ if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
19
+ Object.freeze(value);
20
+ for (const child of Object.values(value)) deepFreeze(child);
21
+ }
22
+ return value;
23
+ }
@@ -0,0 +1,4 @@
1
+ /** Thrown for invalid input or operations, e.g. unknown ids or a task moved into its own subtree. */
2
+ export class QuartzioError extends Error {
3
+ override name = 'QuartzioError';
4
+ }
@@ -0,0 +1,70 @@
1
+ import { daysFromCivil, daysInMonth, MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from './civil';
2
+ import { fromWallTime, type TimeZone } from './zone';
3
+
4
+ // YYYY-MM-DD, optionally followed by a time, optionally followed by an explicit offset.
5
+ const ISO_DATE =
6
+ /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
7
+
8
+ /**
9
+ * Parses an ISO 8601 date string. Without an offset ("2026-10-05", "2026-10-05T08:00") the string is a
10
+ * wall-clock time in `zone`; with one ("…Z", "…+02:00") it is an absolute instant.
11
+ * Returns `null` for anything else, including impossible dates like 2026-02-30.
12
+ */
13
+ export function parseDateString(value: string, zone: TimeZone): number | null {
14
+ const match = ISO_DATE.exec(value.trim());
15
+ if (!match) return null;
16
+ const [, y, mo, d, h = '0', mi = '0', s = '0', ms = '0', offset] = match;
17
+ const year = Number(y);
18
+ const month = Number(mo);
19
+ const day = Number(d);
20
+ const hour = Number(h);
21
+ const minute = Number(mi);
22
+ const second = Number(s);
23
+ // More than three decimals (as written by .NET and PostgreSQL) are truncated to milliseconds.
24
+ const millisecond = Number(ms.slice(0, 3).padEnd(3, '0'));
25
+
26
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return null;
27
+ if (hour > 23 || minute > 59 || second > 59) return null;
28
+
29
+ if (offset === undefined)
30
+ return fromWallTime({ year, month, day, hour, minute, second, millisecond }, zone);
31
+
32
+ const wallAsUtc =
33
+ daysFromCivil(year, month, day) * MS_PER_DAY +
34
+ hour * MS_PER_HOUR +
35
+ minute * MS_PER_MINUTE +
36
+ second * MS_PER_SECOND +
37
+ millisecond;
38
+ if (offset === 'Z') return wallAsUtc;
39
+ const sign = offset.startsWith('-') ? -1 : 1;
40
+ const digits = offset.slice(1).replace(':', '');
41
+ const offsetHours = Number(digits.slice(0, 2));
42
+ const extraMinutes = Number(digits.slice(2));
43
+ if (offsetHours > 14 || extraMinutes > 59) return null;
44
+ const offsetMinutes = offsetHours * 60 + extraMinutes;
45
+ return wallAsUtc - sign * offsetMinutes * MS_PER_MINUTE;
46
+ }
47
+
48
+ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
49
+
50
+ /** Parses "YYYY-MM-DD" to a civil day number, or `null` if invalid. */
51
+ export function parseCivilDate(value: string): number | null {
52
+ const match = ISO_DAY.exec(value);
53
+ if (!match) return null;
54
+ const year = Number(match[1]);
55
+ const month = Number(match[2]);
56
+ const day = Number(match[3]);
57
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return null;
58
+ return daysFromCivil(year, month, day);
59
+ }
60
+
61
+ const TIME_OF_DAY = /^(\d{2}):(\d{2})$/;
62
+
63
+ /** Parses "HH:mm" (00:00–24:00) to minutes since midnight, or `null` if invalid. */
64
+ export function parseTimeOfDay(value: string): number | null {
65
+ const match = TIME_OF_DAY.exec(value);
66
+ if (!match) return null;
67
+ const minutes = Number(match[1]) * 60 + Number(match[2]);
68
+ if (Number(match[2]) > 59 || minutes > 24 * 60) return null;
69
+ return minutes;
70
+ }
@@ -0,0 +1,18 @@
1
+ export type TimeUnit =
2
+ 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';
3
+
4
+ export const TIME_UNITS: readonly TimeUnit[] = [
5
+ 'millisecond',
6
+ 'second',
7
+ 'minute',
8
+ 'hour',
9
+ 'day',
10
+ 'week',
11
+ 'month',
12
+ 'quarter',
13
+ 'year',
14
+ ];
15
+
16
+ export function isTimeUnit(value: unknown): value is TimeUnit {
17
+ return typeof value === 'string' && (TIME_UNITS as readonly string[]).includes(value);
18
+ }
@@ -0,0 +1,303 @@
1
+ // Time-zone aware wall-clock arithmetic. This is the only place (with civil.ts) that may depend on
2
+ // the host time zone; everything else works on epoch milliseconds and goes through these helpers.
3
+ import {
4
+ civilFromDays,
5
+ daysFromCivil,
6
+ daysInMonth,
7
+ MS_PER_DAY,
8
+ MS_PER_HOUR,
9
+ MS_PER_MINUTE,
10
+ MS_PER_SECOND,
11
+ weekdayFromDays,
12
+ } from './civil';
13
+ import { QuartzioError } from './errors';
14
+ import type { TimeUnit } from './time';
15
+
16
+ /** `'local'` (the host's zone), `'UTC'`, or an IANA name such as `'Europe/Oslo'`. */
17
+ export type TimeZone = string;
18
+
19
+ export const LOCAL_TIME_ZONE: TimeZone = 'local';
20
+
21
+ export interface WallTime {
22
+ year: number;
23
+ /** 1–12 */
24
+ month: number;
25
+ /** 1–31 */
26
+ day: number;
27
+ hour: number;
28
+ minute: number;
29
+ second: number;
30
+ millisecond: number;
31
+ }
32
+
33
+ export interface ZonedWallTime extends WallTime {
34
+ /** 0 = Sunday … 6 = Saturday. */
35
+ weekday: number;
36
+ }
37
+
38
+ const formatters = new Map<string, Intl.DateTimeFormat>();
39
+
40
+ function formatterFor(zone: string): Intl.DateTimeFormat {
41
+ let formatter = formatters.get(zone);
42
+ if (!formatter) {
43
+ formatter = new Intl.DateTimeFormat('en-US', {
44
+ timeZone: zone,
45
+ hourCycle: 'h23',
46
+ year: 'numeric',
47
+ month: 'numeric',
48
+ day: 'numeric',
49
+ hour: 'numeric',
50
+ minute: 'numeric',
51
+ second: 'numeric',
52
+ });
53
+ formatters.set(zone, formatter);
54
+ }
55
+ return formatter;
56
+ }
57
+
58
+ export function isValidTimeZone(zone: unknown): zone is TimeZone {
59
+ if (zone === LOCAL_TIME_ZONE || zone === 'UTC') return true;
60
+ if (typeof zone !== 'string' || zone === '') return false;
61
+ try {
62
+ formatterFor(zone);
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ export function assertTimeZone(zone: unknown): asserts zone is TimeZone {
70
+ if (!isValidTimeZone(zone)) {
71
+ throw new QuartzioError(
72
+ `"${String(zone)}" is not a valid time zone. Use "local", "UTC" or an IANA name.`,
73
+ );
74
+ }
75
+ }
76
+
77
+ function intlOffset(time: number, zone: string): number {
78
+ const values: Partial<Record<Intl.DateTimeFormatPartTypes, number>> = {};
79
+ for (const part of formatterFor(zone).formatToParts(time)) {
80
+ if (part.type !== 'literal') values[part.type] = Number(part.value);
81
+ }
82
+ const wallAsUtc =
83
+ daysFromCivil(values.year ?? 1970, values.month ?? 1, values.day ?? 1) * MS_PER_DAY +
84
+ (values.hour ?? 0) * MS_PER_HOUR +
85
+ (values.minute ?? 0) * MS_PER_MINUTE +
86
+ (values.second ?? 0) * MS_PER_SECOND;
87
+ return wallAsUtc - (time - mod(time, MS_PER_SECOND));
88
+ }
89
+
90
+ // Offsets are cached in two levels. A whole day is cached as one entry when the offset is the same at both
91
+ // ends (real zones never change twice in a day). Days with a transition are cached per 15 minutes; most
92
+ // transitions fall on quarter hours, but not all (e.g. St. John's before 2011), so a quarter hour is only
93
+ // cached when its ends agree, and otherwise computed exactly.
94
+ const QUARTER_HOUR = 15 * MS_PER_MINUTE;
95
+ const MAX_CACHED_OFFSETS = 50_000;
96
+ /** Per zone: day bucket → offset, or `null` for days with a transition. */
97
+ const dayCache = new Map<string, Map<number, number | null>>();
98
+ const quarterCache = new Map<string, Map<number, number>>();
99
+
100
+ function cacheFor<V>(caches: Map<string, Map<number, V>>, zone: string): Map<number, V> {
101
+ let cache = caches.get(zone);
102
+ if (!cache) caches.set(zone, (cache = new Map<number, V>()));
103
+ if (cache.size >= MAX_CACHED_OFFSETS) cache.clear();
104
+ return cache;
105
+ }
106
+
107
+ /** Offset from UTC in milliseconds at `time` (e.g. +3 600 000 for CET). */
108
+ export function zoneOffset(time: number, zone: TimeZone): number {
109
+ if (zone === 'UTC') return 0;
110
+ if (zone === LOCAL_TIME_ZONE) return -new Date(time).getTimezoneOffset() * MS_PER_MINUTE;
111
+
112
+ const days = cacheFor(dayCache, zone);
113
+ const day = Math.floor(time / MS_PER_DAY);
114
+ let dayOffset = days.get(day);
115
+ if (dayOffset === undefined) {
116
+ assertTimeZone(zone);
117
+ const start = intlOffset(day * MS_PER_DAY, zone);
118
+ dayOffset = start === intlOffset((day + 1) * MS_PER_DAY - MS_PER_SECOND, zone) ? start : null;
119
+ days.set(day, dayOffset);
120
+ }
121
+ if (dayOffset !== null) return dayOffset;
122
+
123
+ const quarters = cacheFor(quarterCache, zone);
124
+ const quarter = Math.floor(time / QUARTER_HOUR);
125
+ const cached = quarters.get(quarter);
126
+ if (cached !== undefined) return cached;
127
+ const start = intlOffset(quarter * QUARTER_HOUR, zone);
128
+ const end = intlOffset((quarter + 1) * QUARTER_HOUR - MS_PER_SECOND, zone);
129
+ if (start !== end) return intlOffset(time, zone); // the transition is inside this quarter hour
130
+ quarters.set(quarter, start);
131
+ return start;
132
+ }
133
+
134
+ function mod(value: number, divisor: number): number {
135
+ return ((value % divisor) + divisor) % divisor;
136
+ }
137
+
138
+ /** Civil day number (days since 1970-01-01) of the wall date at `time` in `zone`. */
139
+ export function wallDay(time: number, zone: TimeZone): number {
140
+ return Math.floor((time + zoneOffset(time, zone)) / MS_PER_DAY);
141
+ }
142
+
143
+ export function toWallTime(time: number, zone: TimeZone): ZonedWallTime {
144
+ const local = time + zoneOffset(time, zone);
145
+ const days = Math.floor(local / MS_PER_DAY);
146
+ const msOfDay = local - days * MS_PER_DAY;
147
+ return {
148
+ ...civilFromDays(days),
149
+ hour: Math.floor(msOfDay / MS_PER_HOUR),
150
+ minute: Math.floor((msOfDay % MS_PER_HOUR) / MS_PER_MINUTE),
151
+ second: Math.floor((msOfDay % MS_PER_MINUTE) / MS_PER_SECOND),
152
+ millisecond: msOfDay % MS_PER_SECOND,
153
+ weekday: weekdayFromDays(days),
154
+ };
155
+ }
156
+
157
+ const wallAsUtcOf = (wall: Partial<WallTime> & Pick<WallTime, 'year'>): number =>
158
+ daysFromCivil(wall.year, wall.month ?? 1, wall.day ?? 1) * MS_PER_DAY +
159
+ (wall.hour ?? 0) * MS_PER_HOUR +
160
+ (wall.minute ?? 0) * MS_PER_MINUTE +
161
+ (wall.second ?? 0) * MS_PER_SECOND +
162
+ (wall.millisecond ?? 0);
163
+
164
+ /**
165
+ * The instant a wall-clock time happens in `zone`. Out-of-range fields roll over.
166
+ * A time skipped by a DST change (e.g. 02:30 on spring-forward day) resolves to the same distance after
167
+ * the change (03:30); a time that happens twice (fall-back) resolves to the first occurrence.
168
+ */
169
+ export function fromWallTime(wall: Partial<WallTime> & Pick<WallTime, 'year'>, zone: TimeZone): number {
170
+ return wallAsUtcToInstant(wallAsUtcOf(wall), zone, {});
171
+ }
172
+
173
+ /**
174
+ * Midnight at the start of civil day `days`, plus `minutes` of wall-clock time. Times inside a DST gap
175
+ * resolve to the transition instant, so boundaries of consecutive intervals stay ordered and never overlap
176
+ * (a working interval 02:15–02:45 on spring-forward day collapses to nothing).
177
+ */
178
+ export function wallDayTime(days: number, minutes: number, zone: TimeZone): number {
179
+ return wallAsUtcToInstant(days * MS_PER_DAY + minutes * MS_PER_MINUTE, zone, { gap: 'transition' });
180
+ }
181
+
182
+ interface Resolution {
183
+ /** `'shift'` (default): move forward by the gap's length. `'transition'`: the instant the gap starts. */
184
+ gap?: 'shift' | 'transition';
185
+ /** For repeated wall times: prefer the occurrence with this offset instead of the first one. */
186
+ preferOffset?: number;
187
+ }
188
+
189
+ function wallAsUtcToInstant(wallAsUtc: number, zone: TimeZone, resolution: Resolution): number {
190
+ if (zone === 'UTC') return wallAsUtc;
191
+ // Real zones have at most one transition within a day, so the offsets a day before and after cover
192
+ // every candidate.
193
+ const before = zoneOffset(wallAsUtc - MS_PER_DAY, zone);
194
+ const after = zoneOffset(wallAsUtc + MS_PER_DAY, zone);
195
+ const candidates = (before === after ? [before] : [before, after])
196
+ .filter((offset) => zoneOffset(wallAsUtc - offset, zone) === offset)
197
+ .map((offset) => ({ offset, time: wallAsUtc - offset }))
198
+ .sort((a, b) => a.time - b.time);
199
+
200
+ const chosen = candidates.find(({ offset }) => offset === resolution.preferOffset) ?? candidates[0];
201
+ if (chosen) return chosen.time;
202
+
203
+ // No candidate: the wall time falls in a DST gap.
204
+ if (resolution.gap === 'transition') return findTransition(wallAsUtc - after, wallAsUtc - before, zone);
205
+ return wallAsUtc - before; // the offset from before the gap moves it forward
206
+ }
207
+
208
+ /** Binary search for the instant the offset changes, given `low` (old offset) < `high` (new offset). */
209
+ function findTransition(low: number, high: number, zone: TimeZone): number {
210
+ const offsetAtLow = zoneOffset(low, zone);
211
+ while (high - low > 1) {
212
+ const middle = Math.floor((low + high) / 2);
213
+ if (zoneOffset(middle, zone) === offsetAtLow) low = middle;
214
+ else high = middle;
215
+ }
216
+ return high;
217
+ }
218
+
219
+ export function startOfDay(time: number, zone: TimeZone): number {
220
+ return wallDayTime(wallDay(time, zone), 0, zone);
221
+ }
222
+
223
+ /**
224
+ * Start of the unit containing `time`, e.g. midnight for `'day'`, the first day of the month for `'month'`.
225
+ * `weekStartsOn`: 0 = Sunday … 6 = Saturday.
226
+ */
227
+ export function startOfUnit(time: number, unit: TimeUnit, zone: TimeZone, weekStartsOn = 1): number {
228
+ switch (unit) {
229
+ case 'millisecond':
230
+ return time;
231
+ case 'second':
232
+ case 'minute':
233
+ case 'hour': {
234
+ // Work on the instant, not by rebuilding the wall time: in a repeated hour (fall-back) the wall time
235
+ // is ambiguous and would resolve to the first occurrence.
236
+ const size = unit === 'hour' ? MS_PER_HOUR : unit === 'minute' ? MS_PER_MINUTE : MS_PER_SECOND;
237
+ return time - mod(time + zoneOffset(time, zone), size);
238
+ }
239
+ case 'day':
240
+ return startOfDay(time, zone);
241
+ case 'week': {
242
+ const days = wallDay(time, zone);
243
+ return wallDayTime(days - mod(weekdayFromDays(days) - weekStartsOn, 7), 0, zone);
244
+ }
245
+ case 'month':
246
+ case 'quarter':
247
+ case 'year': {
248
+ const { year, month } = toWallTime(time, zone);
249
+ const firstMonth = unit === 'month' ? month : unit === 'quarter' ? month - ((month - 1) % 3) : 1;
250
+ return fromWallTime({ year, month: firstMonth, day: 1 }, zone);
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Adds calendar time. Units up to hours are exact durations; days and longer follow the wall clock, so
257
+ * adding a day across a DST change keeps the time of day. Month arithmetic clamps to the month's last day
258
+ * (31 January + 1 month = 28/29 February). Days and longer need whole numbers.
259
+ */
260
+ export function addUnits(time: number, amount: number, unit: TimeUnit, zone: TimeZone): number {
261
+ switch (unit) {
262
+ case 'millisecond':
263
+ return time + amount;
264
+ case 'second':
265
+ return time + amount * MS_PER_SECOND;
266
+ case 'minute':
267
+ return time + amount * MS_PER_MINUTE;
268
+ case 'hour':
269
+ return time + amount * MS_PER_HOUR;
270
+ case 'day':
271
+ case 'week':
272
+ case 'month':
273
+ case 'quarter':
274
+ case 'year': {
275
+ if (!Number.isInteger(amount)) {
276
+ throw new QuartzioError(`addUnits: "${unit}" needs a whole number, got ${String(amount)}.`);
277
+ }
278
+ const wall = toWallTime(time, zone);
279
+ let { year, month, day } = wall;
280
+ if (unit === 'day' || unit === 'week') {
281
+ day += amount * (unit === 'week' ? 7 : 1);
282
+ } else {
283
+ const months = amount * (unit === 'year' ? 12 : unit === 'quarter' ? 3 : 1);
284
+ const monthIndex = year * 12 + (month - 1) + months;
285
+ year = Math.floor(monthIndex / 12);
286
+ month = mod(monthIndex, 12) + 1;
287
+ day = Math.min(day, daysInMonth(year, month));
288
+ }
289
+ // Keep the same occurrence of a repeated hour (e.g. adding 0 days to the second 02:30 on fall-back day).
290
+ return wallAsUtcToInstant(wallAsUtcOf({ ...wall, year, month, day }), zone, {
291
+ preferOffset: zoneOffset(time, zone),
292
+ });
293
+ }
294
+ }
295
+ }
296
+
297
+ /** ISO 8601 week number: weeks start on Monday, and week 1 contains the year's first Thursday. */
298
+ export function isoWeek(time: number, zone: TimeZone): { year: number; week: number } {
299
+ const days = wallDay(time, zone);
300
+ const thursday = days - mod(weekdayFromDays(days) - 1, 7) + 3;
301
+ const { year } = civilFromDays(thursday);
302
+ return { year, week: Math.floor((thursday - daysFromCivil(year, 1, 1)) / 7) + 1 };
303
+ }
@@ -0,0 +1,63 @@
1
+ import type { Task } from '../data/types';
2
+ import type { TaskDates } from './dates';
3
+ import type { TimeAxis } from '../timeaxis/timeAxis';
4
+
5
+ export type BarKind = 'task' | 'summary' | 'milestone';
6
+
7
+ /** A task's bar on the timeline, in timeline coordinates (x = 0 is the start of the axis). */
8
+ export interface Bar {
9
+ readonly kind: BarKind;
10
+ /**
11
+ * Left edge; for milestones, the center of the diamond. May be outside the axis for tasks that extend beyond
12
+ * it, but is kept within one axis width on either side (`start` and `end` keep the real dates).
13
+ */
14
+ readonly x: number;
15
+ /** 0 for milestones. */
16
+ readonly width: number;
17
+ readonly start: number;
18
+ readonly end: number;
19
+ /** 0–1. */
20
+ readonly progress: number;
21
+ readonly label: string;
22
+ }
23
+
24
+ /** Keeps very short tasks visible and clickable at coarse zoom levels. */
25
+ export const MIN_BAR_WIDTH = 2;
26
+
27
+ export function computeBar(
28
+ task: Task,
29
+ dates: TaskDates | null,
30
+ isParent: boolean,
31
+ axis: TimeAxis,
32
+ ): Bar | null {
33
+ if (!dates) return null;
34
+ // Browsers stop drawing tens of millions of pixels out, so keep positions near the axis.
35
+ const clamp = (value: number) => Math.max(-axis.totalWidth, Math.min(2 * axis.totalWidth, value));
36
+ const start = clamp(axis.dateToX(dates.start));
37
+ const common = {
38
+ start: dates.start,
39
+ end: dates.end,
40
+ progress: Math.max(0, Math.min(1, task.percentDone / 100)),
41
+ label: task.name,
42
+ };
43
+ if (dates.end === dates.start && !isParent) return { kind: 'milestone', x: start, width: 0, ...common };
44
+ const width = Math.max(MIN_BAR_WIDTH, clamp(axis.dateToX(dates.end)) - start);
45
+ return {
46
+ kind: isParent ? 'summary' : 'task',
47
+ x: Math.min(start, 2 * axis.totalWidth - width),
48
+ width,
49
+ ...common,
50
+ };
51
+ }
52
+
53
+ export const sameBar = (a: Bar | null, b: Bar | null): boolean =>
54
+ a === b ||
55
+ (a !== null &&
56
+ b !== null &&
57
+ a.kind === b.kind &&
58
+ a.x === b.x &&
59
+ a.width === b.width &&
60
+ a.start === b.start &&
61
+ a.end === b.end &&
62
+ a.progress === b.progress &&
63
+ a.label === b.label);