@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.
- package/API.md +533 -0
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/index.d.ts +1341 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6556 -0
- package/dist/index.js.map +1 -0
- package/dist/styles.css +1299 -0
- package/package.json +51 -3
- package/src/calendar/duration.ts +42 -0
- package/src/calendar/project.ts +29 -0
- package/src/calendar/workingCalendar.ts +218 -0
- package/src/data/draft.ts +78 -0
- package/src/data/graph.ts +215 -0
- package/src/data/normalize.ts +661 -0
- package/src/data/operations.ts +112 -0
- package/src/data/project.ts +194 -0
- package/src/data/serialize.ts +26 -0
- package/src/data/transaction.ts +460 -0
- package/src/data/tree.ts +156 -0
- package/src/data/types.ts +229 -0
- package/src/index.ts +139 -0
- package/src/scheduling/schedule.ts +310 -0
- package/src/styles.css +1299 -0
- package/src/timeaxis/align.ts +120 -0
- package/src/timeaxis/format.ts +72 -0
- package/src/timeaxis/presets.ts +219 -0
- package/src/timeaxis/timeAxis.ts +205 -0
- package/src/util/civil.ts +38 -0
- package/src/util/emitter.ts +53 -0
- package/src/util/equal.ts +23 -0
- package/src/util/errors.ts +4 -0
- package/src/util/parse.ts +70 -0
- package/src/util/time.ts +18 -0
- package/src/util/zone.ts +303 -0
- package/src/view/bars.ts +63 -0
- package/src/view/binding.ts +162 -0
- package/src/view/cellEditor.ts +239 -0
- package/src/view/cells.ts +89 -0
- package/src/view/columns.ts +197 -0
- package/src/view/createGantt.ts +1164 -0
- package/src/view/dates.ts +14 -0
- package/src/view/dependencies.ts +147 -0
- package/src/view/editing.ts +303 -0
- package/src/view/history.ts +72 -0
- package/src/view/interaction.ts +671 -0
- package/src/view/keyboard.ts +149 -0
- package/src/view/listWidth.ts +201 -0
- package/src/view/menu.ts +265 -0
- package/src/view/nonWorking.ts +113 -0
- package/src/view/range.ts +41 -0
- package/src/view/rows.ts +235 -0
- package/src/view/selection.ts +156 -0
- package/src/view/taskActions.ts +71 -0
- package/src/view/taskEditor.ts +553 -0
- package/src/view/timeline.ts +155 -0
- package/src/view/tooltip.ts +117 -0
- package/src/view/types.ts +328 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["formatters","formatterFor","mod","EMPTY","cache","MIN_TIME","MAX_TIME","cache","unknown","MILESTONE_RADIUS","EMPTY","round","SUB_DAY","finite"],"sources":["../src/util/civil.ts","../src/calendar/duration.ts","../src/util/equal.ts","../src/util/errors.ts","../src/util/zone.ts","../src/util/parse.ts","../src/util/time.ts","../src/data/tree.ts","../src/data/graph.ts","../src/data/normalize.ts","../src/calendar/workingCalendar.ts","../src/calendar/project.ts","../src/util/emitter.ts","../src/data/draft.ts","../src/data/operations.ts","../src/data/serialize.ts","../src/data/transaction.ts","../src/data/project.ts","../src/timeaxis/presets.ts","../src/timeaxis/align.ts","../src/timeaxis/format.ts","../src/timeaxis/timeAxis.ts","../src/scheduling/schedule.ts","../src/view/dates.ts","../src/view/cells.ts","../src/view/columns.ts","../src/view/binding.ts","../src/view/history.ts","../src/view/selection.ts","../src/view/keyboard.ts","../src/view/bars.ts","../src/view/rows.ts","../src/view/dependencies.ts","../src/view/interaction.ts","../src/view/range.ts","../src/view/timeline.ts","../src/view/nonWorking.ts","../src/view/tooltip.ts","../src/view/editing.ts","../src/view/cellEditor.ts","../src/view/menu.ts","../src/view/taskActions.ts","../src/view/taskEditor.ts","../src/view/listWidth.ts","../src/view/createGantt.ts"],"sourcesContent":["// Calendar-date (\"civil\") arithmetic, independent of any time zone. A civil day number counts days\n// since 1970-01-01; it names a date on the wall calendar, not an instant.\n\nexport const MS_PER_SECOND = 1000;\nexport const MS_PER_MINUTE: number = 60 * MS_PER_SECOND;\nexport const MS_PER_HOUR: number = 60 * MS_PER_MINUTE;\nexport const MS_PER_DAY: number = 24 * MS_PER_HOUR;\n\nexport interface CivilDate {\n year: number;\n /** 1–12 */\n month: number;\n /** 1–31 */\n day: number;\n}\n\n/** Day number for a date. Out-of-range months and days roll over (month 13 → January next year). */\nexport function daysFromCivil(year: number, month: number, day: number): number {\n const date = new Date(0);\n // setUTCFullYear, not Date.UTC: Date.UTC maps years 0–99 to 1900–1999.\n date.setUTCFullYear(year, month - 1, day);\n return Math.round(date.getTime() / MS_PER_DAY);\n}\n\nexport function civilFromDays(days: number): CivilDate {\n const date = new Date(days * MS_PER_DAY);\n return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };\n}\n\n/** 0 = Sunday … 6 = Saturday. */\nexport function weekdayFromDays(days: number): number {\n // 1970-01-01 was a Thursday.\n return (((days + 4) % 7) + 7) % 7;\n}\n\nexport function daysInMonth(year: number, month: number): number {\n return daysFromCivil(year, month + 1, 1) - daysFromCivil(year, month, 1);\n}\n","import type { ProjectSettings } from '../data/types';\nimport { MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from '../util/civil';\nimport type { TimeUnit } from '../util/time';\n\nexport type DurationSettings = Pick<ProjectSettings, 'hoursPerDay' | 'daysPerWeek' | 'daysPerMonth'>;\n\n/**\n * Working milliseconds in one unit. Durations are working time (like MS Project): with 8 hours per day,\n * \"1 day\" is 8 working hours, and \"1 week\" is `daysPerWeek` such days — not 7 calendar days.\n */\nexport function workingMsPerUnit(unit: TimeUnit, settings: DurationSettings): number {\n const day = settings.hoursPerDay * MS_PER_HOUR;\n const month = settings.daysPerMonth * day;\n switch (unit) {\n case 'millisecond':\n return 1;\n case 'second':\n return MS_PER_SECOND;\n case 'minute':\n return MS_PER_MINUTE;\n case 'hour':\n return MS_PER_HOUR;\n case 'day':\n return day;\n case 'week':\n return settings.daysPerWeek * day;\n case 'month':\n return month;\n case 'quarter':\n return 3 * month;\n case 'year':\n return 12 * month;\n }\n}\n\nexport function durationToWorkingMs(value: number, unit: TimeUnit, settings: DurationSettings): number {\n return value * workingMsPerUnit(unit, settings);\n}\n\nexport function workingMsToDuration(ms: number, unit: TimeUnit, settings: DurationSettings): number {\n return ms / workingMsPerUnit(unit, settings);\n}\n","/** Structural equality for JSON-like values (primitives, arrays, plain objects). */\nexport function isEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every(\n (key) =>\n Object.hasOwn(b, key) &&\n isEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\n/** Freezes an object and everything reachable from it. */\nexport function deepFreeze<T>(value: T): T {\n if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n }\n return value;\n}\n","/** Thrown for invalid input or operations, e.g. unknown ids or a task moved into its own subtree. */\nexport class QuartzioError extends Error {\n override name = 'QuartzioError';\n}\n","// Time-zone aware wall-clock arithmetic. This is the only place (with civil.ts) that may depend on\n// the host time zone; everything else works on epoch milliseconds and goes through these helpers.\nimport {\n civilFromDays,\n daysFromCivil,\n daysInMonth,\n MS_PER_DAY,\n MS_PER_HOUR,\n MS_PER_MINUTE,\n MS_PER_SECOND,\n weekdayFromDays,\n} from './civil';\nimport { QuartzioError } from './errors';\nimport type { TimeUnit } from './time';\n\n/** `'local'` (the host's zone), `'UTC'`, or an IANA name such as `'Europe/Oslo'`. */\nexport type TimeZone = string;\n\nexport const LOCAL_TIME_ZONE: TimeZone = 'local';\n\nexport interface WallTime {\n year: number;\n /** 1–12 */\n month: number;\n /** 1–31 */\n day: number;\n hour: number;\n minute: number;\n second: number;\n millisecond: number;\n}\n\nexport interface ZonedWallTime extends WallTime {\n /** 0 = Sunday … 6 = Saturday. */\n weekday: number;\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatterFor(zone: string): Intl.DateTimeFormat {\n let formatter = formatters.get(zone);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: zone,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n formatters.set(zone, formatter);\n }\n return formatter;\n}\n\nexport function isValidTimeZone(zone: unknown): zone is TimeZone {\n if (zone === LOCAL_TIME_ZONE || zone === 'UTC') return true;\n if (typeof zone !== 'string' || zone === '') return false;\n try {\n formatterFor(zone);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function assertTimeZone(zone: unknown): asserts zone is TimeZone {\n if (!isValidTimeZone(zone)) {\n throw new QuartzioError(\n `\"${String(zone)}\" is not a valid time zone. Use \"local\", \"UTC\" or an IANA name.`,\n );\n }\n}\n\nfunction intlOffset(time: number, zone: string): number {\n const values: Partial<Record<Intl.DateTimeFormatPartTypes, number>> = {};\n for (const part of formatterFor(zone).formatToParts(time)) {\n if (part.type !== 'literal') values[part.type] = Number(part.value);\n }\n const wallAsUtc =\n daysFromCivil(values.year ?? 1970, values.month ?? 1, values.day ?? 1) * MS_PER_DAY +\n (values.hour ?? 0) * MS_PER_HOUR +\n (values.minute ?? 0) * MS_PER_MINUTE +\n (values.second ?? 0) * MS_PER_SECOND;\n return wallAsUtc - (time - mod(time, MS_PER_SECOND));\n}\n\n// Offsets are cached in two levels. A whole day is cached as one entry when the offset is the same at both\n// ends (real zones never change twice in a day). Days with a transition are cached per 15 minutes; most\n// transitions fall on quarter hours, but not all (e.g. St. John's before 2011), so a quarter hour is only\n// cached when its ends agree, and otherwise computed exactly.\nconst QUARTER_HOUR = 15 * MS_PER_MINUTE;\nconst MAX_CACHED_OFFSETS = 50_000;\n/** Per zone: day bucket → offset, or `null` for days with a transition. */\nconst dayCache = new Map<string, Map<number, number | null>>();\nconst quarterCache = new Map<string, Map<number, number>>();\n\nfunction cacheFor<V>(caches: Map<string, Map<number, V>>, zone: string): Map<number, V> {\n let cache = caches.get(zone);\n if (!cache) caches.set(zone, (cache = new Map<number, V>()));\n if (cache.size >= MAX_CACHED_OFFSETS) cache.clear();\n return cache;\n}\n\n/** Offset from UTC in milliseconds at `time` (e.g. +3 600 000 for CET). */\nexport function zoneOffset(time: number, zone: TimeZone): number {\n if (zone === 'UTC') return 0;\n if (zone === LOCAL_TIME_ZONE) return -new Date(time).getTimezoneOffset() * MS_PER_MINUTE;\n\n const days = cacheFor(dayCache, zone);\n const day = Math.floor(time / MS_PER_DAY);\n let dayOffset = days.get(day);\n if (dayOffset === undefined) {\n assertTimeZone(zone);\n const start = intlOffset(day * MS_PER_DAY, zone);\n dayOffset = start === intlOffset((day + 1) * MS_PER_DAY - MS_PER_SECOND, zone) ? start : null;\n days.set(day, dayOffset);\n }\n if (dayOffset !== null) return dayOffset;\n\n const quarters = cacheFor(quarterCache, zone);\n const quarter = Math.floor(time / QUARTER_HOUR);\n const cached = quarters.get(quarter);\n if (cached !== undefined) return cached;\n const start = intlOffset(quarter * QUARTER_HOUR, zone);\n const end = intlOffset((quarter + 1) * QUARTER_HOUR - MS_PER_SECOND, zone);\n if (start !== end) return intlOffset(time, zone); // the transition is inside this quarter hour\n quarters.set(quarter, start);\n return start;\n}\n\nfunction mod(value: number, divisor: number): number {\n return ((value % divisor) + divisor) % divisor;\n}\n\n/** Civil day number (days since 1970-01-01) of the wall date at `time` in `zone`. */\nexport function wallDay(time: number, zone: TimeZone): number {\n return Math.floor((time + zoneOffset(time, zone)) / MS_PER_DAY);\n}\n\nexport function toWallTime(time: number, zone: TimeZone): ZonedWallTime {\n const local = time + zoneOffset(time, zone);\n const days = Math.floor(local / MS_PER_DAY);\n const msOfDay = local - days * MS_PER_DAY;\n return {\n ...civilFromDays(days),\n hour: Math.floor(msOfDay / MS_PER_HOUR),\n minute: Math.floor((msOfDay % MS_PER_HOUR) / MS_PER_MINUTE),\n second: Math.floor((msOfDay % MS_PER_MINUTE) / MS_PER_SECOND),\n millisecond: msOfDay % MS_PER_SECOND,\n weekday: weekdayFromDays(days),\n };\n}\n\nconst wallAsUtcOf = (wall: Partial<WallTime> & Pick<WallTime, 'year'>): number =>\n daysFromCivil(wall.year, wall.month ?? 1, wall.day ?? 1) * MS_PER_DAY +\n (wall.hour ?? 0) * MS_PER_HOUR +\n (wall.minute ?? 0) * MS_PER_MINUTE +\n (wall.second ?? 0) * MS_PER_SECOND +\n (wall.millisecond ?? 0);\n\n/**\n * The instant a wall-clock time happens in `zone`. Out-of-range fields roll over.\n * A time skipped by a DST change (e.g. 02:30 on spring-forward day) resolves to the same distance after\n * the change (03:30); a time that happens twice (fall-back) resolves to the first occurrence.\n */\nexport function fromWallTime(wall: Partial<WallTime> & Pick<WallTime, 'year'>, zone: TimeZone): number {\n return wallAsUtcToInstant(wallAsUtcOf(wall), zone, {});\n}\n\n/**\n * Midnight at the start of civil day `days`, plus `minutes` of wall-clock time. Times inside a DST gap\n * resolve to the transition instant, so boundaries of consecutive intervals stay ordered and never overlap\n * (a working interval 02:15–02:45 on spring-forward day collapses to nothing).\n */\nexport function wallDayTime(days: number, minutes: number, zone: TimeZone): number {\n return wallAsUtcToInstant(days * MS_PER_DAY + minutes * MS_PER_MINUTE, zone, { gap: 'transition' });\n}\n\ninterface Resolution {\n /** `'shift'` (default): move forward by the gap's length. `'transition'`: the instant the gap starts. */\n gap?: 'shift' | 'transition';\n /** For repeated wall times: prefer the occurrence with this offset instead of the first one. */\n preferOffset?: number;\n}\n\nfunction wallAsUtcToInstant(wallAsUtc: number, zone: TimeZone, resolution: Resolution): number {\n if (zone === 'UTC') return wallAsUtc;\n // Real zones have at most one transition within a day, so the offsets a day before and after cover\n // every candidate.\n const before = zoneOffset(wallAsUtc - MS_PER_DAY, zone);\n const after = zoneOffset(wallAsUtc + MS_PER_DAY, zone);\n const candidates = (before === after ? [before] : [before, after])\n .filter((offset) => zoneOffset(wallAsUtc - offset, zone) === offset)\n .map((offset) => ({ offset, time: wallAsUtc - offset }))\n .sort((a, b) => a.time - b.time);\n\n const chosen = candidates.find(({ offset }) => offset === resolution.preferOffset) ?? candidates[0];\n if (chosen) return chosen.time;\n\n // No candidate: the wall time falls in a DST gap.\n if (resolution.gap === 'transition') return findTransition(wallAsUtc - after, wallAsUtc - before, zone);\n return wallAsUtc - before; // the offset from before the gap moves it forward\n}\n\n/** Binary search for the instant the offset changes, given `low` (old offset) < `high` (new offset). */\nfunction findTransition(low: number, high: number, zone: TimeZone): number {\n const offsetAtLow = zoneOffset(low, zone);\n while (high - low > 1) {\n const middle = Math.floor((low + high) / 2);\n if (zoneOffset(middle, zone) === offsetAtLow) low = middle;\n else high = middle;\n }\n return high;\n}\n\nexport function startOfDay(time: number, zone: TimeZone): number {\n return wallDayTime(wallDay(time, zone), 0, zone);\n}\n\n/**\n * Start of the unit containing `time`, e.g. midnight for `'day'`, the first day of the month for `'month'`.\n * `weekStartsOn`: 0 = Sunday … 6 = Saturday.\n */\nexport function startOfUnit(time: number, unit: TimeUnit, zone: TimeZone, weekStartsOn = 1): number {\n switch (unit) {\n case 'millisecond':\n return time;\n case 'second':\n case 'minute':\n case 'hour': {\n // Work on the instant, not by rebuilding the wall time: in a repeated hour (fall-back) the wall time\n // is ambiguous and would resolve to the first occurrence.\n const size = unit === 'hour' ? MS_PER_HOUR : unit === 'minute' ? MS_PER_MINUTE : MS_PER_SECOND;\n return time - mod(time + zoneOffset(time, zone), size);\n }\n case 'day':\n return startOfDay(time, zone);\n case 'week': {\n const days = wallDay(time, zone);\n return wallDayTime(days - mod(weekdayFromDays(days) - weekStartsOn, 7), 0, zone);\n }\n case 'month':\n case 'quarter':\n case 'year': {\n const { year, month } = toWallTime(time, zone);\n const firstMonth = unit === 'month' ? month : unit === 'quarter' ? month - ((month - 1) % 3) : 1;\n return fromWallTime({ year, month: firstMonth, day: 1 }, zone);\n }\n }\n}\n\n/**\n * Adds calendar time. Units up to hours are exact durations; days and longer follow the wall clock, so\n * adding a day across a DST change keeps the time of day. Month arithmetic clamps to the month's last day\n * (31 January + 1 month = 28/29 February). Days and longer need whole numbers.\n */\nexport function addUnits(time: number, amount: number, unit: TimeUnit, zone: TimeZone): number {\n switch (unit) {\n case 'millisecond':\n return time + amount;\n case 'second':\n return time + amount * MS_PER_SECOND;\n case 'minute':\n return time + amount * MS_PER_MINUTE;\n case 'hour':\n return time + amount * MS_PER_HOUR;\n case 'day':\n case 'week':\n case 'month':\n case 'quarter':\n case 'year': {\n if (!Number.isInteger(amount)) {\n throw new QuartzioError(`addUnits: \"${unit}\" needs a whole number, got ${String(amount)}.`);\n }\n const wall = toWallTime(time, zone);\n let { year, month, day } = wall;\n if (unit === 'day' || unit === 'week') {\n day += amount * (unit === 'week' ? 7 : 1);\n } else {\n const months = amount * (unit === 'year' ? 12 : unit === 'quarter' ? 3 : 1);\n const monthIndex = year * 12 + (month - 1) + months;\n year = Math.floor(monthIndex / 12);\n month = mod(monthIndex, 12) + 1;\n day = Math.min(day, daysInMonth(year, month));\n }\n // Keep the same occurrence of a repeated hour (e.g. adding 0 days to the second 02:30 on fall-back day).\n return wallAsUtcToInstant(wallAsUtcOf({ ...wall, year, month, day }), zone, {\n preferOffset: zoneOffset(time, zone),\n });\n }\n }\n}\n\n/** ISO 8601 week number: weeks start on Monday, and week 1 contains the year's first Thursday. */\nexport function isoWeek(time: number, zone: TimeZone): { year: number; week: number } {\n const days = wallDay(time, zone);\n const thursday = days - mod(weekdayFromDays(days) - 1, 7) + 3;\n const { year } = civilFromDays(thursday);\n return { year, week: Math.floor((thursday - daysFromCivil(year, 1, 1)) / 7) + 1 };\n}\n","import { daysFromCivil, daysInMonth, MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from './civil';\nimport { fromWallTime, type TimeZone } from './zone';\n\n// YYYY-MM-DD, optionally followed by a time, optionally followed by an explicit offset.\nconst ISO_DATE =\n /^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:[.,](\\d+))?)?(Z|[+-]\\d{2}:?\\d{2})?)?$/;\n\n/**\n * Parses an ISO 8601 date string. Without an offset (\"2026-10-05\", \"2026-10-05T08:00\") the string is a\n * wall-clock time in `zone`; with one (\"…Z\", \"…+02:00\") it is an absolute instant.\n * Returns `null` for anything else, including impossible dates like 2026-02-30.\n */\nexport function parseDateString(value: string, zone: TimeZone): number | null {\n const match = ISO_DATE.exec(value.trim());\n if (!match) return null;\n const [, y, mo, d, h = '0', mi = '0', s = '0', ms = '0', offset] = match;\n const year = Number(y);\n const month = Number(mo);\n const day = Number(d);\n const hour = Number(h);\n const minute = Number(mi);\n const second = Number(s);\n // More than three decimals (as written by .NET and PostgreSQL) are truncated to milliseconds.\n const millisecond = Number(ms.slice(0, 3).padEnd(3, '0'));\n\n if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return null;\n if (hour > 23 || minute > 59 || second > 59) return null;\n\n if (offset === undefined)\n return fromWallTime({ year, month, day, hour, minute, second, millisecond }, zone);\n\n const wallAsUtc =\n daysFromCivil(year, month, day) * MS_PER_DAY +\n hour * MS_PER_HOUR +\n minute * MS_PER_MINUTE +\n second * MS_PER_SECOND +\n millisecond;\n if (offset === 'Z') return wallAsUtc;\n const sign = offset.startsWith('-') ? -1 : 1;\n const digits = offset.slice(1).replace(':', '');\n const offsetHours = Number(digits.slice(0, 2));\n const extraMinutes = Number(digits.slice(2));\n if (offsetHours > 14 || extraMinutes > 59) return null;\n const offsetMinutes = offsetHours * 60 + extraMinutes;\n return wallAsUtc - sign * offsetMinutes * MS_PER_MINUTE;\n}\n\nconst ISO_DAY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** Parses \"YYYY-MM-DD\" to a civil day number, or `null` if invalid. */\nexport function parseCivilDate(value: string): number | null {\n const match = ISO_DAY.exec(value);\n if (!match) return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return null;\n return daysFromCivil(year, month, day);\n}\n\nconst TIME_OF_DAY = /^(\\d{2}):(\\d{2})$/;\n\n/** Parses \"HH:mm\" (00:00–24:00) to minutes since midnight, or `null` if invalid. */\nexport function parseTimeOfDay(value: string): number | null {\n const match = TIME_OF_DAY.exec(value);\n if (!match) return null;\n const minutes = Number(match[1]) * 60 + Number(match[2]);\n if (Number(match[2]) > 59 || minutes > 24 * 60) return null;\n return minutes;\n}\n","export type TimeUnit =\n 'millisecond' | 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year';\n\nexport const TIME_UNITS: readonly TimeUnit[] = [\n 'millisecond',\n 'second',\n 'minute',\n 'hour',\n 'day',\n 'week',\n 'month',\n 'quarter',\n 'year',\n];\n\nexport function isTimeUnit(value: unknown): value is TimeUnit {\n return typeof value === 'string' && (TIME_UNITS as readonly string[]).includes(value);\n}\n","import type { Id, Table, Task } from './types';\n\nconst EMPTY: readonly Id[] = [];\n\n/** Derived hierarchy for a task table. Built in O(n); cached per table so repeated lookups are cheap. */\nexport interface TreeIndex {\n /** Child ids in sibling order. `null` returns the root tasks. */\n children: (parentId: Id | null) => readonly Id[];\n /** Position of each task in the table's `order`. */\n position: (id: Id) => number;\n /** Ancestors from the direct parent up to the root. */\n ancestors: (id: Id) => Id[];\n /** All descendants, depth-first in sibling order. */\n descendants: (id: Id) => Id[];\n depth: (id: Id) => number;\n isLeaf: (id: Id) => boolean;\n /** Tasks depth-first in sibling order: the order rows appear in when everything is expanded. */\n flatten: () => readonly Id[];\n}\n\n/**\n * The hierarchy of a table that is still changing (a transaction draft). Added and removed tasks are updated in\n * place, so adding or removing many tasks doesn't rebuild it each time. No positions: they shift with every\n * change (use `order`).\n */\nexport interface DraftTreeIndex extends Omit<TreeIndex, 'position' | 'flatten'> {\n /** Like `children`, without copying: only valid until the next insert. */\n childrenView: (parentId: Id | null) => readonly Id[];\n insert: (id: Id, parentId: Id | null, siblingIndex: number) => void;\n /** Removes a task with all its descendants (given, so they aren't walked twice). */\n removeSubtree: (id: Id, descendants: readonly Id[]) => void;\n}\n\nconst cache = new WeakMap<Table<Task>, TreeIndex>();\n// Tables with the same structure (order and parents) as an earlier table, whose index they share once one is\n// built. Points at the first table of such a run, never along a chain, so it keeps at most one old table alive.\nconst sameStructure = new WeakMap<Table<Task>, Table<Task>>();\n\nexport function getTreeIndex(tasks: Table<Task>): TreeIndex {\n const cached = cache.get(tasks);\n if (cached) return cached;\n const earlier = sameStructure.get(tasks);\n const index = (earlier && cache.get(earlier)) ?? buildTreeIndex(tasks);\n if (earlier) cache.set(earlier, index);\n cache.set(tasks, index);\n sameStructure.delete(tasks);\n return index;\n}\n\n/**\n * Records that `next` has the same order and parents as `previous` (only other fields changed), so it can use\n * the same index instead of building one: field edits are far more common than structural ones.\n */\nexport function shareTreeIndex(previous: Table<Task>, next: Table<Task>): void {\n if (previous === next) return;\n const index = cache.get(previous);\n if (index) cache.set(next, index);\n else sameStructure.set(next, sameStructure.get(previous) ?? previous);\n}\n\n/** Uncached build of a finished table's index. */\nexport function buildTreeIndex(tasks: Table<Task>): TreeIndex {\n const structure = readStructure(tasks);\n const positions = new Map<Id, number>();\n tasks.order.forEach((id, position) => positions.set(id, position));\n const walk = walker(structure);\n let flattened: Id[] | undefined;\n return {\n ...walk,\n position: (id) => positions.get(id) ?? -1,\n flatten: () => {\n flattened ??= walk.children(null).flatMap((rootId) => [rootId, ...walk.descendants(rootId)]);\n return flattened;\n },\n };\n}\n\nexport function buildDraftTreeIndex(tasks: Table<Task>): DraftTreeIndex {\n const structure = readStructure(tasks);\n const walk = walker(structure);\n return {\n ...walk,\n // A copy: the lists change with later inserts.\n children: (parentId) => [...walk.children(parentId)],\n childrenView: walk.children,\n insert: (id, parentId, siblingIndex) => {\n structure.parents.set(id, parentId);\n const siblings = structure.childrenByParent.get(parentId);\n if (siblings) siblings.splice(siblingIndex, 0, id);\n else structure.childrenByParent.set(parentId, [id]);\n },\n removeSubtree: (id, descendants) => {\n // Only the root leaves a sibling list; the descendants' lists go with them.\n const siblings = structure.childrenByParent.get(structure.parents.get(id) ?? null);\n const at = siblings?.indexOf(id) ?? -1;\n if (at !== -1) siblings?.splice(at, 1);\n for (const removed of [id, ...descendants]) {\n structure.parents.delete(removed);\n structure.childrenByParent.delete(removed);\n }\n },\n };\n}\n\ninterface Structure {\n childrenByParent: Map<Id | null, Id[]>;\n // Kept in the index rather than read from the table, so a shared index doesn't hold on to old tables.\n parents: Map<Id, Id | null>;\n}\n\nfunction readStructure(tasks: Table<Task>): Structure {\n const childrenByParent = new Map<Id | null, Id[]>();\n const parents = new Map<Id, Id | null>();\n for (const id of tasks.order) {\n const parentId = tasks.byId.get(id)?.parentId ?? null;\n parents.set(id, parentId);\n const siblings = childrenByParent.get(parentId);\n if (siblings) siblings.push(id);\n else childrenByParent.set(parentId, [id]);\n }\n return { childrenByParent, parents };\n}\n\nfunction walker({ childrenByParent, parents }: Structure): Omit<TreeIndex, 'position' | 'flatten'> {\n const children = (parentId: Id | null): readonly Id[] => childrenByParent.get(parentId) ?? EMPTY;\n\n const descendants = (id: Id): Id[] => {\n const result: Id[] = [];\n const stack = [...children(id)].reverse();\n while (stack.length > 0) {\n const current = stack.pop() as Id;\n result.push(current);\n const kids = children(current);\n for (let i = kids.length - 1; i >= 0; i--) stack.push(kids[i] as Id);\n }\n return result;\n };\n\n const ancestors = (id: Id): Id[] => {\n const result: Id[] = [];\n let parentId = parents.get(id) ?? null;\n while (parentId !== null) {\n result.push(parentId);\n parentId = parents.get(parentId) ?? null;\n }\n return result;\n };\n\n return {\n children,\n ancestors,\n descendants,\n depth: (id) => ancestors(id).length,\n isLeaf: (id) => children(id).length === 0,\n };\n}\n","import { QuartzioError } from '../util/errors';\nimport { getTreeIndex, type TreeIndex } from './tree';\nimport type { Dependency, Id, ProjectState, Table } from './types';\n\nconst NONE: readonly Dependency[] = [];\n\nexport interface DependencyIndex {\n /** Dependencies where the task is the successor (`to`). */\n incoming: (taskId: Id) => readonly Dependency[];\n /** Dependencies where the task is the predecessor (`from`). */\n outgoing: (taskId: Id) => readonly Dependency[];\n}\n\nconst dependencyCache = new WeakMap<Table<Dependency>, DependencyIndex>();\n\n/** Dependencies per task, in table order. Built in O(n); cached per table. */\nexport function getDependencyIndex(dependencies: Table<Dependency>): DependencyIndex {\n let index = dependencyCache.get(dependencies);\n if (!index) {\n const incoming = new Map<Id, Dependency[]>();\n const outgoing = new Map<Id, Dependency[]>();\n const add = (map: Map<Id, Dependency[]>, key: Id, dependency: Dependency) => {\n const list = map.get(key);\n if (list) list.push(dependency);\n else map.set(key, [dependency]);\n };\n for (const id of dependencies.order) {\n const dependency = dependencies.byId.get(id) as Dependency;\n add(incoming, dependency.to, dependency);\n add(outgoing, dependency.from, dependency);\n }\n index = {\n incoming: (taskId) => incoming.get(taskId) ?? NONE,\n outgoing: (taskId) => outgoing.get(taskId) ?? NONE,\n };\n dependencyCache.set(dependencies, index);\n }\n return index;\n}\n\n/**\n * The order to schedule in. Every task has two nodes: `in` (its requirements) and `out` (its dates). Node\n * `2i` is the `in` node and `2i + 1` the `out` node of task `ids[i]`. Edges:\n * - `out(predecessor) → in(successor)` for each dependency;\n * - `in(parent) → in(child)`: requirements on a parent apply to its children;\n * - `out(child) → out(parent)`: a parent spans its children;\n * - `in(task) → out(task)`.\n * Splitting parents in two is what lets a parent both pass requirements down and roll dates up.\n */\nexport interface ScheduleGraph {\n readonly ids: readonly Id[];\n /** Node numbers in topological order. */\n readonly order: Int32Array;\n}\n\nconst graphCache = new WeakMap<TreeIndex, WeakMap<Table<Dependency>, ScheduleGraph>>();\n// Dependency tables with the same ends (`from`/`to`, in the same order) as an earlier table, so the graph is\n// shared when only other fields (lag, type) change. Points at the first table of such a run, never along a\n// chain, so it keeps at most one old table alive.\nconst sameEnds = new WeakMap<Table<Dependency>, Table<Dependency>>();\n\n/** Records that `next` has the same dependency ends as `previous`, so they can share a schedule graph. */\nexport function shareDependencyEnds(previous: Table<Dependency>, next: Table<Dependency>): void {\n if (previous !== next) sameEnds.set(next, sameEnds.get(previous) ?? previous);\n}\n\n/** Whether two dependency tables have the same records in the same order with the same ends. */\nexport function sameDependencyEnds(table: Table<Dependency>, previous: Table<Dependency>): boolean {\n if (previous.order.length !== table.order.length) return false;\n for (let i = 0; i < table.order.length; i++) {\n const id = table.order[i] as Id;\n const a = table.byId.get(id);\n const b = previous.byId.get(id);\n if (previous.order[i] !== id || a?.from !== b?.from || a?.to !== b?.to) return false;\n }\n return true;\n}\n\n/**\n * Builds the scheduling order in O(n), cached per task structure and dependency table (so field edits reuse it).\n * Throws QuartzioError when dependencies form a cycle, directly or through the hierarchy (e.g. a task that\n * depends on its own parent).\n */\nexport function getScheduleGraph(state: ProjectState): ScheduleGraph {\n const tree = getTreeIndex(state.tasks);\n const dependencyKey = sameEnds.get(state.dependencies) ?? state.dependencies;\n let byDependencies = graphCache.get(tree);\n const cached = byDependencies?.get(dependencyKey);\n if (cached) return cached;\n const graph = buildScheduleGraph(state);\n if (!byDependencies) {\n byDependencies = new WeakMap();\n graphCache.set(tree, byDependencies);\n }\n byDependencies.set(dependencyKey, graph);\n return graph;\n}\n\n/** Builds the graph (uncached), optionally with one more dependency, e.g. to try it for cycles. */\nfunction buildScheduleGraph(state: ProjectState, extra?: { from: Id; to: Id }): ScheduleGraph {\n const ids = state.tasks.order;\n const indexOf = new Map<Id, number>();\n ids.forEach((id, i) => indexOf.set(id, i));\n\n // Edges as linked lists in flat arrays: fast to build for 10 000s of tasks.\n const nodeCount = ids.length * 2;\n const head = new Int32Array(nodeCount).fill(-1);\n const next: number[] = [];\n const target: number[] = [];\n const inDegree = new Int32Array(nodeCount);\n const edge = (from: number, to: number) => {\n target.push(to);\n next.push(head[from] as number);\n head[from] = target.length - 1;\n inDegree[to] = (inDegree[to] as number) + 1;\n };\n\n ids.forEach((id, i) => {\n edge(2 * i, 2 * i + 1);\n const parentId = state.tasks.byId.get(id)?.parentId ?? null;\n const p = parentId === null ? undefined : indexOf.get(parentId);\n if (p !== undefined) {\n edge(2 * p, 2 * i);\n edge(2 * i + 1, 2 * p + 1);\n }\n });\n const ends: Iterable<{ from: Id; to: Id }> = extra\n ? [...state.dependencies.byId.values(), extra]\n : state.dependencies.byId.values();\n for (const dependency of ends) {\n const from = indexOf.get(dependency.from);\n const to = indexOf.get(dependency.to);\n if (from !== undefined && to !== undefined) edge(2 * from + 1, 2 * to);\n }\n\n // Kahn's algorithm, iterative.\n const order = new Int32Array(nodeCount);\n let size = 0;\n for (let node = 0; node < nodeCount; node++) if (inDegree[node] === 0) order[size++] = node;\n for (let read = 0; read < size; read++) {\n for (let e = head[order[read] as number] as number; e !== -1; e = next[e] as number) {\n const to = target[e] as number;\n inDegree[to] = (inDegree[to] as number) - 1;\n if (inDegree[to] === 0) order[size++] = to;\n }\n }\n if (size < nodeCount) throw cycleError(ids, head, next, target, inDegree);\n\n return { ids, order };\n}\n\n/**\n * Names the tasks of one cycle. Nodes left over by Kahn's algorithm (in-degree > 0) all have a leftover\n * predecessor, so walking predecessors from any of them must come back around.\n */\nfunction cycleError(\n ids: readonly Id[],\n head: Int32Array,\n next: readonly number[],\n target: readonly number[],\n inDegree: Int32Array,\n): QuartzioError {\n const predecessor = new Map<number, number>();\n for (let from = 0; from < head.length; from++) {\n if (inDegree[from] === 0) continue;\n for (let e = head[from] as number; e !== -1; e = next[e] as number) {\n const to = target[e] as number;\n if ((inDegree[to] as number) > 0 && !predecessor.has(to)) predecessor.set(to, from);\n }\n }\n let node = predecessor.keys().next().value as number;\n const seen = new Map<number, number>();\n const path: number[] = [];\n while (!seen.has(node)) {\n seen.set(node, path.length);\n path.push(node);\n node = predecessor.get(node) as number;\n }\n const cycle = path.slice(seen.get(node)).reverse();\n // Two nodes per task: name each task once, in order around the cycle.\n const names: string[] = [];\n for (const n of cycle) {\n const name = `\"${String(ids[n >> 1])}\"`;\n if (names[names.length - 1] !== name) names.push(name);\n }\n if (names.length > 1 && names[0] === names[names.length - 1]) names.pop();\n names.push(names[0] as string);\n return new QuartzioError(\n `Dependencies form a cycle: ${names.join(' → ')}. (A task can't depend on its own parent or child, ` +\n `and a task inherits the dependencies of its parents.)`,\n );\n}\n\nconst cycleCache = new WeakMap<ProjectState, Map<string, boolean>>();\n\n/**\n * Whether a dependency from `from` to `to` would form a cycle (also through the hierarchy). Tries it: builds the\n * graph with it added, in O(n). Cached per state and pair, since a drag asks again on every pointer move.\n */\nexport function wouldCreateCycle(state: ProjectState, from: Id, to: Id): boolean {\n let byPair = cycleCache.get(state);\n if (!byPair) cycleCache.set(state, (byPair = new Map<string, boolean>()));\n const key = `${typeof from}:${String(from)}→${typeof to}:${String(to)}`;\n const known = byPair.get(key);\n if (known !== undefined) return known;\n let cycle = false;\n try {\n buildScheduleGraph(state, { from, to });\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n cycle = true;\n }\n byPair.set(key, cycle);\n return cycle;\n}\n","import { deepFreeze, isEqual } from '../util/equal';\nimport { QuartzioError } from '../util/errors';\nimport { parseCivilDate, parseDateString, parseTimeOfDay } from '../util/parse';\nimport { isTimeUnit, type TimeUnit } from '../util/time';\nimport { assertTimeZone, type TimeZone } from '../util/zone';\nimport { getScheduleGraph, sameDependencyEnds, shareDependencyEnds } from './graph';\nimport { shareTreeIndex } from './tree';\nimport type {\n Calendar,\n CalendarException,\n ConstraintType,\n CalendarExceptionInput,\n CalendarInput,\n DateInput,\n Dependency,\n DependencyInput,\n DependencyType,\n Id,\n ProjectInput,\n ProjectSettings,\n ProjectSettingsInput,\n ProjectState,\n Table,\n Task,\n TaskInput,\n Weekday,\n WorkingInterval,\n} from './types';\n\nconst DEPENDENCY_TYPES: readonly DependencyType[] = ['FS', 'SS', 'FF', 'SF'];\n\n/** Index = weekday number (0 = Sunday), matching `Date` and `weekStartsOn`. */\nexport const WEEKDAYS: readonly Weekday[] = [\n 'sunday',\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n];\n\nexport const DEFAULT_DURATION_UNIT: TimeUnit = 'day';\nexport const DEFAULT_LAG_UNIT: TimeUnit = 'day';\n\nexport const DEFAULT_SETTINGS: ProjectSettings = deepFreeze({\n timeZone: 'local',\n calendarId: null,\n hoursPerDay: 8,\n daysPerWeek: 5,\n daysPerMonth: 20,\n weekStartsOn: 1,\n startDate: null,\n});\n\nconst OFFICE_HOURS: readonly WorkingInterval[] = [{ start: '08:00', end: '16:00' }];\n\n/** Used when `settings.calendarId` is `null`: Monday–Friday 08:00–16:00, no exceptions. */\nexport const STANDARD_CALENDAR: Calendar = deepFreeze({\n id: 'standard',\n name: 'Standard',\n week: {\n sunday: [],\n monday: OFFICE_HOURS,\n tuesday: OFFICE_HOURS,\n wednesday: OFFICE_HOURS,\n thursday: OFFICE_HOURS,\n friday: OFFICE_HOURS,\n saturday: [],\n },\n exceptions: [],\n});\n\nconst label = (kind: string, id: Id): string => `${kind} \"${String(id)}\"`;\n\nexport function isId(value: unknown): value is Id {\n return (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value));\n}\n\n// --- Fields ---\n\n/** Dates must fall in the years 1000–9999; anything outside is almost certainly a typo. */\nconst MIN_TIME = Date.UTC(1000, 0, 1);\nconst MAX_TIME = Date.UTC(10_000, 0, 1) - 1;\n\nexport function toTime(\n value: DateInput | null | undefined,\n field: string,\n owner: string,\n zone: TimeZone,\n): number | null {\n if (value === null || value === undefined) return null;\n const time =\n typeof value === 'string'\n ? parseDateString(value, zone)\n : value instanceof Date\n ? value.getTime()\n : value;\n if (typeof time !== 'number' || !Number.isFinite(time)) {\n throw new QuartzioError(\n `${owner}: \"${field}\" must be a valid Date, epoch milliseconds or an ISO 8601 string like \"2026-10-05\".`,\n );\n }\n if (time < MIN_TIME || time > MAX_TIME) {\n throw new QuartzioError(`${owner}: \"${field}\" must be between the years 1000 and 9999.`);\n }\n // Fractions of a millisecond would make working-time arithmetic (and so scheduling) inexact.\n if (!Number.isInteger(time)) throw new QuartzioError(`${owner}: \"${field}\" must be whole milliseconds.`);\n return time;\n}\n\nfunction toName(value: unknown, owner: string): string {\n if (value === undefined) return '';\n if (typeof value !== 'string') throw new QuartzioError(`${owner}: \"name\" must be a string.`);\n return value;\n}\n\nfunction toDuration(value: number | null | undefined, owner: string): number | null {\n if (value === null || value === undefined) return null;\n if (!Number.isFinite(value) || value < 0) {\n throw new QuartzioError(`${owner}: \"duration\" must be a finite number >= 0.`);\n }\n return value;\n}\n\nfunction toPercent(value: number | undefined, owner: string): number {\n if (value === undefined) return 0;\n if (!Number.isFinite(value) || value < 0 || value > 100) {\n throw new QuartzioError(`${owner}: \"percentDone\" must be between 0 and 100.`);\n }\n return value;\n}\n\nfunction toBoolean(value: unknown, field: string, owner: string): boolean {\n if (value === undefined) return false;\n if (typeof value !== 'boolean') throw new QuartzioError(`${owner}: \"${field}\" must be true or false.`);\n return value;\n}\n\nconst CONSTRAINT_TYPES: readonly ConstraintType[] = ['startnoearlierthan'];\n// Recognized, so the error can say they're coming rather than unknown.\nconst FUTURE_CONSTRAINT_TYPES = [\n 'startnolaterthan',\n 'finishnoearlierthan',\n 'finishnolaterthan',\n 'muststarton',\n 'mustfinishon',\n];\n\nfunction toConstraintType(value: unknown, owner: string): ConstraintType | null {\n if (value === undefined || value === null) return null;\n if (CONSTRAINT_TYPES.includes(value as ConstraintType)) return value as ConstraintType;\n if (typeof value === 'string' && FUTURE_CONSTRAINT_TYPES.includes(value)) {\n throw new QuartzioError(`${owner}: constraint \"${value}\" is not supported yet.`);\n }\n throw new QuartzioError(\n `${owner}: \"constraintType\" must be one of ${CONSTRAINT_TYPES.join(', ')}, or null.`,\n );\n}\n\nfunction toUnit(value: TimeUnit | undefined, fallback: TimeUnit, field: string, owner: string): TimeUnit {\n if (value === undefined) return fallback;\n if (!isTimeUnit(value)) throw new QuartzioError(`${owner}: \"${field}\" is not a valid time unit.`);\n return value;\n}\n\n// --- Tasks ---\n\nexport type TaskFieldsInput = Omit<TaskInput, 'id' | 'parentId' | 'children'>;\nexport type TaskFields = Omit<Task, 'id' | 'parentId'>;\n\nexport function normalizeTaskFields(input: TaskFieldsInput, owner: string, zone: TimeZone): TaskFields {\n return {\n name: toName(input.name, owner),\n startDate: toTime(input.startDate, 'startDate', owner, zone),\n endDate: toTime(input.endDate, 'endDate', owner, zone),\n duration: toDuration(input.duration, owner),\n durationUnit: toUnit(input.durationUnit, DEFAULT_DURATION_UNIT, 'durationUnit', owner),\n percentDone: toPercent(input.percentDone, owner),\n manuallyScheduled: toBoolean(input.manuallyScheduled, 'manuallyScheduled', owner),\n constraintType: toConstraintType(input.constraintType, owner),\n constraintDate: toTime(input.constraintDate, 'constraintDate', owner, zone),\n };\n}\n\n/** Normalizes only the fields present in `input` (for updates). */\nexport function normalizeTaskChanges(\n input: TaskFieldsInput,\n owner: string,\n zone: TimeZone,\n): Partial<TaskFields> {\n const changes: { -readonly [K in keyof TaskFields]?: TaskFields[K] } = {};\n if (input.name !== undefined) changes.name = toName(input.name, owner);\n if (input.startDate !== undefined) changes.startDate = toTime(input.startDate, 'startDate', owner, zone);\n if (input.endDate !== undefined) changes.endDate = toTime(input.endDate, 'endDate', owner, zone);\n if (input.duration !== undefined) changes.duration = toDuration(input.duration, owner);\n if (input.durationUnit !== undefined) {\n changes.durationUnit = toUnit(input.durationUnit, DEFAULT_DURATION_UNIT, 'durationUnit', owner);\n }\n if (input.percentDone !== undefined) changes.percentDone = toPercent(input.percentDone, owner);\n if (input.manuallyScheduled !== undefined) {\n changes.manuallyScheduled = toBoolean(input.manuallyScheduled, 'manuallyScheduled', owner);\n }\n if (input.constraintType !== undefined)\n changes.constraintType = toConstraintType(input.constraintType, owner);\n if (input.constraintDate !== undefined) {\n changes.constraintDate = toTime(input.constraintDate, 'constraintDate', owner, zone);\n }\n return changes;\n}\n\n/** Structure is changed with `position`/`move`, not with fields; catch data passed in by mistake. */\nexport function assertNoStructureFields(input: object, owner: string): void {\n if ('children' in input) {\n throw new QuartzioError(\n `${owner}: \"children\" is not supported here. Add child tasks with a parentId position.`,\n );\n }\n if ('parentId' in input) {\n throw new QuartzioError(\n `${owner}: \"parentId\" is not supported here. Use a position ({ parentId }) or move().`,\n );\n }\n}\n\n/** A constraint has a type and a date, or neither. */\nexport function assertTaskConstraint(task: Task): void {\n if ((task.constraintType === null) !== (task.constraintDate === null)) {\n throw new QuartzioError(\n `${label('Task', task.id)}: \"constraintType\" and \"constraintDate\" are set together (both or neither).`,\n );\n }\n}\n\nexport function assertTaskDates(task: Task): void {\n if (task.startDate !== null && task.endDate !== null && task.endDate < task.startDate) {\n throw new QuartzioError(`${label('Task', task.id)}: \"endDate\" is before \"startDate\".`);\n }\n}\n\n// --- Dependencies ---\n\nexport type DependencyFieldsInput = Omit<DependencyInput, 'id' | 'from' | 'to'>;\nexport type DependencyFields = Omit<Dependency, 'id' | 'from' | 'to'>;\n\nfunction toDependencyType(value: DependencyType | undefined, owner: string): DependencyType {\n if (value === undefined) return 'FS';\n if (!DEPENDENCY_TYPES.includes(value)) {\n throw new QuartzioError(`${owner}: \"type\" must be one of ${DEPENDENCY_TYPES.join(', ')}.`);\n }\n return value;\n}\n\nfunction toLag(value: number | undefined, owner: string): number {\n if (value === undefined) return 0;\n if (!Number.isFinite(value)) throw new QuartzioError(`${owner}: \"lag\" must be a finite number.`);\n return value;\n}\n\nexport function normalizeDependencyFields(input: DependencyFieldsInput, owner: string): DependencyFields {\n return {\n type: toDependencyType(input.type, owner),\n lag: toLag(input.lag, owner),\n lagUnit: toUnit(input.lagUnit, DEFAULT_LAG_UNIT, 'lagUnit', owner),\n };\n}\n\nexport function normalizeDependencyChanges(\n input: DependencyFieldsInput,\n owner: string,\n): Partial<DependencyFields> {\n const changes: { -readonly [K in keyof DependencyFields]?: DependencyFields[K] } = {};\n if (input.type !== undefined) changes.type = toDependencyType(input.type, owner);\n if (input.lag !== undefined) changes.lag = toLag(input.lag, owner);\n if (input.lagUnit !== undefined)\n changes.lagUnit = toUnit(input.lagUnit, DEFAULT_LAG_UNIT, 'lagUnit', owner);\n return changes;\n}\n\nexport function assertDependencyEnds(tasks: Table<Task>['byId'], from: Id, to: Id, owner: string): void {\n if (!tasks.has(from)) throw new QuartzioError(`${owner}: \"from\" task \"${String(from)}\" does not exist.`);\n if (!tasks.has(to)) throw new QuartzioError(`${owner}: \"to\" task \"${String(to)}\" does not exist.`);\n if (from === to) throw new QuartzioError(`${owner}: a task cannot depend on itself.`);\n}\n\n// --- Settings ---\n\nfunction toPositive(value: unknown, field: string, max: number): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > max) {\n throw new QuartzioError(\n `Project settings: \"${field}\" must be a number above 0 and at most ${String(max)}.`,\n );\n }\n return value;\n}\n\n/**\n * Normalizes only the settings present in `input`. Date strings are read in `input.timeZone`, or `zone` (the\n * project's current time zone) when the input doesn't change it.\n */\nexport function normalizeSettingsChanges(\n input: ProjectSettingsInput,\n zone: TimeZone = DEFAULT_SETTINGS.timeZone,\n): Partial<ProjectSettings> {\n const changes: { -readonly [K in keyof ProjectSettings]?: ProjectSettings[K] } = {};\n if (input.timeZone !== undefined) {\n assertTimeZone(input.timeZone);\n changes.timeZone = input.timeZone;\n }\n if (input.calendarId !== undefined) {\n if (input.calendarId !== null && !isId(input.calendarId)) {\n throw new QuartzioError('Project settings: \"calendarId\" must be a calendar id or null.');\n }\n changes.calendarId = input.calendarId;\n }\n if (input.hoursPerDay !== undefined) changes.hoursPerDay = toPositive(input.hoursPerDay, 'hoursPerDay', 24);\n if (input.daysPerWeek !== undefined) changes.daysPerWeek = toPositive(input.daysPerWeek, 'daysPerWeek', 7);\n if (input.daysPerMonth !== undefined)\n changes.daysPerMonth = toPositive(input.daysPerMonth, 'daysPerMonth', 31);\n if (input.weekStartsOn !== undefined) {\n if (!Number.isInteger(input.weekStartsOn) || input.weekStartsOn < 0 || input.weekStartsOn > 6) {\n throw new QuartzioError(\n 'Project settings: \"weekStartsOn\" must be an integer from 0 (Sunday) to 6 (Saturday).',\n );\n }\n changes.weekStartsOn = input.weekStartsOn;\n }\n if (input.startDate !== undefined) {\n changes.startDate = toTime(input.startDate, 'startDate', 'Project settings', changes.timeZone ?? zone);\n }\n return changes;\n}\n\nexport function normalizeSettings(input: ProjectSettingsInput = {}): ProjectSettings {\n return { ...DEFAULT_SETTINGS, ...normalizeSettingsChanges(input) };\n}\n\n// --- Calendars ---\n\nfunction normalizeIntervals(input: unknown, owner: string): readonly WorkingInterval[] {\n if (!Array.isArray(input)) throw new QuartzioError(`${owner}: working intervals must be an array.`);\n const parsed = (input as unknown[]).map((interval) => {\n const { start, end } = (interval ?? {}) as Partial<WorkingInterval>;\n const from = typeof start === 'string' ? parseTimeOfDay(start) : null;\n const to = typeof end === 'string' ? parseTimeOfDay(end) : null;\n if (from === null || to === null || from >= to) {\n throw new QuartzioError(\n `${owner}: working intervals need \"start\" before \"end\", as \"HH:mm\" (e.g. { start: \"08:00\", end: \"16:00\" }).`,\n );\n }\n return { start: start as string, end: end as string, from, to };\n });\n parsed.sort((a, b) => a.from - b.from);\n for (let i = 1; i < parsed.length; i++) {\n if ((parsed[i] as { from: number }).from < (parsed[i - 1] as { to: number }).to) {\n throw new QuartzioError(`${owner}: working intervals overlap.`);\n }\n }\n return parsed.map(({ start, end }) => ({ start, end }));\n}\n\nfunction normalizeWeek(input: CalendarInput['week'], owner: string): Calendar['week'] {\n if (input === undefined) return STANDARD_CALENDAR.week;\n const week = {} as Record<Weekday, readonly WorkingInterval[]>;\n for (const day of WEEKDAYS) week[day] = normalizeIntervals(input[day] ?? [], `${owner} (${day})`);\n for (const key of Object.keys(input)) {\n if (!(WEEKDAYS as readonly string[]).includes(key)) {\n throw new QuartzioError(`${owner}: \"${key}\" is not a weekday. Use ${WEEKDAYS.join(', ')}.`);\n }\n }\n return week;\n}\n\nfunction normalizeException(input: CalendarExceptionInput, owner: string): CalendarException {\n const endDate = input.endDate ?? input.startDate;\n const start = typeof input.startDate === 'string' ? parseCivilDate(input.startDate) : null;\n const end = typeof endDate === 'string' ? parseCivilDate(endDate) : null;\n if (start === null || end === null) {\n throw new QuartzioError(`${owner}: exception dates must be \"YYYY-MM-DD\".`);\n }\n if (end < start) throw new QuartzioError(`${owner}: exception \"endDate\" is before \"startDate\".`);\n return {\n startDate: input.startDate,\n endDate,\n name: toName(input.name, owner),\n intervals: normalizeIntervals(input.intervals ?? [], owner),\n };\n}\n\nexport type CalendarFieldsInput = Omit<CalendarInput, 'id'>;\nexport type CalendarFields = Omit<Calendar, 'id'>;\n\nexport function normalizeCalendarFields(input: CalendarFieldsInput, owner: string): CalendarFields {\n return {\n name: toName(input.name, owner),\n week: normalizeWeek(input.week, owner),\n exceptions: (input.exceptions ?? []).map((exception) => normalizeException(exception, owner)),\n };\n}\n\nexport function normalizeCalendarChanges(input: CalendarFieldsInput, owner: string): Partial<CalendarFields> {\n const changes: { -readonly [K in keyof CalendarFields]?: CalendarFields[K] } = {};\n if (input.name !== undefined) changes.name = toName(input.name, owner);\n if (input.week !== undefined) changes.week = normalizeWeek(input.week, owner);\n if (input.exceptions !== undefined) {\n changes.exceptions = input.exceptions.map((exception) => normalizeException(exception, owner));\n }\n return changes;\n}\n\nfunction assertCalendarExists(calendars: ReadonlyMap<Id, Calendar>, calendarId: Id | null): void {\n if (calendarId !== null && !calendars.has(calendarId)) {\n throw new QuartzioError(`Project settings: calendar \"${String(calendarId)}\" does not exist.`);\n }\n}\n\n// --- Structure ---\n\n/** Throws if placing task `id` under `parentId` would make the task its own ancestor. */\nexport function assertNoParentCycle(byId: ReadonlyMap<Id, Task>, id: Id, parentId: Id | null): void {\n let current = parentId;\n const seen = new Set<Id>();\n while (current !== null) {\n if (current === id) {\n throw new QuartzioError(`${label('Task', id)} cannot be placed inside its own subtree.`);\n }\n if (seen.has(current)) break; // pre-existing cycle elsewhere; reported by load validation\n seen.add(current);\n current = byId.get(current)?.parentId ?? null;\n }\n}\n\n/** Throws unless every parent exists and no parent chain loops. O(n). */\nfunction assertTaskHierarchy(tasks: ReadonlyMap<Id, Task>): void {\n const verified = new Set<Id>();\n for (const task of tasks.values()) {\n const chain = new Set<Id>();\n let current: Task = task;\n while (current.parentId !== null && !verified.has(current.id)) {\n chain.add(current.id);\n const parent = tasks.get(current.parentId);\n if (!parent) {\n throw new QuartzioError(\n `${label('Task', current.id)} has parentId \"${String(current.parentId)}\", which does not exist.`,\n );\n }\n if (chain.has(parent.id)) {\n throw new QuartzioError(`${label('Task', parent.id)} is part of a parent cycle.`);\n }\n current = parent;\n }\n for (const id of chain) verified.add(id);\n }\n}\n\n// --- Whole project ---\n\n/** The first candidate structurally equal to `record`, or `record` itself. */\nfunction reuse<R>(record: R, ...candidates: unknown[]): R {\n for (const candidate of candidates) {\n if (candidate !== undefined && isEqual(candidate, record)) return candidate as R;\n }\n return record;\n}\n\n/**\n * Whether two task tables have the same order and parents, so the new one can share the tree index. Checked\n * after reuseTable, for controlled data coming back with field changes only (the common case).\n */\nfunction sameTaskStructure(table: Table<Task>, previous: Table<Task>): boolean {\n if (previous.order.length !== table.order.length) return false;\n for (let i = 0; i < table.order.length; i++) {\n const id = table.order[i] as Id;\n if (previous.order[i] !== id || previous.byId.get(id)?.parentId !== table.byId.get(id)?.parentId) {\n return false;\n }\n }\n return true;\n}\n\n/** The previous table when order and every record are unchanged, so downstream caches keep hitting. */\nfunction reuseTable<R extends { readonly id: Id }>(\n table: Table<R>,\n previous: Table<R> | undefined,\n): Table<R> {\n if (previous?.order.length !== table.order.length) return table;\n for (let i = 0; i < table.order.length; i++) {\n const id = table.order[i] as Id;\n if (previous.order[i] !== id || previous.byId.get(id) !== table.byId.get(id)) return table;\n }\n return previous;\n}\n\n/**\n * Normalizes and validates user input into an immutable ProjectState. Throws QuartzioError on invalid data.\n *\n * Unchanged records keep their identity: a record equal to the one in `previous` (or to the input object\n * itself, when that is already canonical) is reused, and so is a whole table when nothing in it changed.\n * That lets memoized views skip work after `load()`/`applyPatch()`. Treat data you pass in as immutable.\n */\nexport function createProjectState(input: ProjectInput = {}, previous?: ProjectState): ProjectState {\n const settings = reuse(normalizeSettings(input.settings), previous?.settings, input.settings);\n\n const calendars = new Map<Id, Calendar>();\n const calendarOrder: Id[] = [];\n for (const calendar of input.calendars ?? []) {\n if (!isId(calendar.id))\n throw new QuartzioError('Calendar id must be a non-empty string or a finite number.');\n const owner = label('Calendar', calendar.id);\n if (calendars.has(calendar.id)) throw new QuartzioError(`${owner} is defined more than once.`);\n const record: Calendar = { id: calendar.id, ...normalizeCalendarFields(calendar, owner) };\n calendars.set(calendar.id, reuse(record, previous?.calendars.byId.get(calendar.id), calendar));\n calendarOrder.push(calendar.id);\n }\n assertCalendarExists(calendars, settings.calendarId);\n\n const tasks = new Map<Id, Task>();\n const taskOrder: Id[] = [];\n // Depth-first with an explicit stack (not recursion), so deeply nested input can't overflow the stack.\n const stack: [TaskInput, Id | undefined][] = [...(input.tasks ?? [])]\n .reverse()\n .map((task): [TaskInput, Id | undefined] => [task, undefined]);\n while (stack.length > 0) {\n const [task, nestedParent] = stack.pop() as [TaskInput, Id | undefined];\n if (!isId(task.id)) throw new QuartzioError('Task id must be a non-empty string or a finite number.');\n const owner = label('Task', task.id);\n if (tasks.has(task.id)) throw new QuartzioError(`${owner} is defined more than once.`);\n if (nestedParent !== undefined && task.parentId != null && task.parentId !== nestedParent) {\n throw new QuartzioError(\n `${owner} is nested under \"${String(nestedParent)}\" but has parentId \"${String(task.parentId)}\".`,\n );\n }\n const record: Task = {\n id: task.id,\n parentId: nestedParent ?? task.parentId ?? null,\n ...normalizeTaskFields(task, owner, settings.timeZone),\n };\n assertTaskDates(record);\n assertTaskConstraint(record);\n tasks.set(task.id, reuse(record, previous?.tasks.byId.get(task.id), task));\n taskOrder.push(task.id);\n const children: unknown = task.children ?? [];\n if (!Array.isArray(children)) throw new QuartzioError(`${owner}: \"children\" must be an array.`);\n for (let i = children.length - 1; i >= 0; i--) stack.push([children[i] as TaskInput, task.id]);\n }\n assertTaskHierarchy(tasks);\n\n const dependencies = new Map<Id, Dependency>();\n const dependencyOrder: Id[] = [];\n for (const dependency of input.dependencies ?? []) {\n if (!isId(dependency.id)) {\n throw new QuartzioError('Dependency id must be a non-empty string or a finite number.');\n }\n const owner = label('Dependency', dependency.id);\n if (dependencies.has(dependency.id)) throw new QuartzioError(`${owner} is defined more than once.`);\n assertDependencyEnds(tasks, dependency.from, dependency.to, owner);\n const record: Dependency = {\n id: dependency.id,\n from: dependency.from,\n to: dependency.to,\n ...normalizeDependencyFields(dependency, owner),\n };\n dependencies.set(\n dependency.id,\n reuse(record, previous?.dependencies.byId.get(dependency.id), dependency),\n );\n dependencyOrder.push(dependency.id);\n }\n\n const taskTable = reuseTable({ byId: tasks, order: taskOrder }, previous?.tasks);\n if (previous && sameTaskStructure(taskTable, previous.tasks)) shareTreeIndex(previous.tasks, taskTable);\n\n const dependencyTable = reuseTable({ byId: dependencies, order: dependencyOrder }, previous?.dependencies);\n if (previous && sameDependencyEnds(dependencyTable, previous.dependencies)) {\n shareDependencyEnds(previous.dependencies, dependencyTable);\n }\n const state: ProjectState = {\n settings,\n calendars: reuseTable({ byId: calendars, order: calendarOrder }, previous?.calendars),\n tasks: taskTable,\n dependencies: dependencyTable,\n };\n getScheduleGraph(state); // rejects dependency cycles\n return state;\n}\n\n/** Records touched by operations from outside; only these get full field validation. */\nexport interface TouchedRecords {\n settings: boolean;\n calendars: ReadonlySet<Id>;\n tasks: ReadonlySet<Id>;\n dependencies: ReadonlySet<Id>;\n}\n\nfunction assertNormalized(record: object, expected: object, owner: string): void {\n if (!isEqual(record, expected)) {\n throw new QuartzioError(\n `${owner} is not a valid, normalized record (from an operation that was applied).`,\n );\n }\n}\n\nfunction assertValidSettings(settings: ProjectSettings): void {\n for (const [key, value] of Object.entries(settings)) {\n if (!Object.hasOwn(DEFAULT_SETTINGS, key))\n throw new QuartzioError(`Project settings: unknown setting \"${key}\".`);\n if (value === undefined) throw new QuartzioError(`Project settings: \"${key}\" is undefined.`);\n }\n assertNormalized(settings, normalizeSettings(settings), 'Project settings');\n}\n\n/**\n * Checks the invariants of a state produced by applying operations from outside (undo stacks, servers).\n * Transactions keep these invariants by construction. Structure is checked in O(n); record fields only\n * for `touched` records (all records when omitted).\n */\nexport function assertValidState(\n state: ProjectState,\n touched?: TouchedRecords,\n { taskDates = true }: { taskDates?: boolean } = {},\n): void {\n const check = <R>(store: keyof Omit<TouchedRecords, 'settings'>, table: Table<R & { readonly id: Id }>) =>\n touched ? [...touched[store]].flatMap((id) => table.byId.get(id) ?? []) : [...table.byId.values()];\n\n if (!touched || touched.settings) assertValidSettings(state.settings);\n assertCalendarExists(state.calendars.byId, state.settings.calendarId);\n\n for (const calendar of check('calendars', state.calendars)) {\n const owner = label('Calendar', calendar.id);\n if (!isId(calendar.id)) throw new QuartzioError(`${owner}: invalid id.`);\n assertNormalized(calendar, { id: calendar.id, ...normalizeCalendarFields(calendar, owner) }, owner);\n }\n\n for (const task of check('tasks', state.tasks)) {\n const owner = label('Task', task.id);\n if (!isId(task.id) || (task.parentId !== null && !isId(task.parentId))) {\n throw new QuartzioError(`${owner}: invalid id or parentId.`);\n }\n // Stored dates are numbers, so the zone passed here doesn't matter; strings would fail the comparison.\n assertNormalized(\n task,\n { id: task.id, parentId: task.parentId, ...normalizeTaskFields(task, owner, 'UTC') },\n owner,\n );\n if (taskDates) assertTaskDates(task);\n assertTaskConstraint(task);\n }\n assertTaskHierarchy(state.tasks.byId);\n\n const touchedDependencies = new Set(check('dependencies', state.dependencies));\n for (const dependency of state.dependencies.byId.values()) {\n const owner = label('Dependency', dependency.id);\n assertDependencyEnds(state.tasks.byId, dependency.from, dependency.to, owner);\n if (touchedDependencies.has(dependency)) {\n const { id, from, to } = dependency;\n assertNormalized(dependency, { id, from, to, ...normalizeDependencyFields(dependency, owner) }, owner);\n }\n }\n // Cycles, including ones through the hierarchy. Cached per structure, so field edits don't repeat it.\n getScheduleGraph(state);\n}\n","import { WEEKDAYS } from '../data/normalize';\nimport type { Calendar, Id } from '../data/types';\nimport { weekdayFromDays } from '../util/civil';\nimport { QuartzioError } from '../util/errors';\nimport { parseCivilDate, parseTimeOfDay } from '../util/parse';\nimport { wallDay, wallDayTime, type TimeZone } from '../util/zone';\n\n/** A working period as instants: `[start, end)`. */\nexport type Interval = readonly [start: number, end: number];\n\n/**\n * A calendar bound to a time zone, answering working-time questions in epoch milliseconds.\n * Durations here are working milliseconds (see `durationToWorkingMs`).\n */\nexport interface WorkingCalendar {\n readonly calendarId: Id;\n readonly timeZone: TimeZone;\n isWorking: (time: number) => boolean;\n /** The earliest working instant at or after `time`. */\n nextWorkingTime: (time: number) => number;\n /** The latest instant at or before `time` that ends working time (working time lies just before it). */\n previousWorkingTime: (time: number) => number;\n /**\n * Walks forward from `start` until `workingMs` of working time has passed and returns that instant.\n * When the duration ends exactly at the end of a working period, that end is returned (end dates\n * are exclusive). Zero returns `start` unchanged. Negative walks backwards.\n */\n addWorkingTime: (start: number, workingMs: number) => number;\n /** Walks backwards from `end`; the mirror of `addWorkingTime`. */\n subtractWorkingTime: (end: number, workingMs: number) => number;\n /** Working milliseconds in `[from, to)`. Negative when `to` is before `from`. */\n workingTimeBetween: (from: number, to: number) => number;\n /** Working intervals overlapping `[from, to)`, clipped to it. For drawing working/non-working time. */\n workingIntervals: (from: number, to: number) => Interval[];\n}\n\n/** How far to search for working time before deciding the calendar has none (~10 years). */\nconst MAX_EMPTY_DAYS = 3660;\n/**\n * The longest span (~25 years) any calculation walks through day by day. Longer spans are almost always\n * typos (a year like 2126 instead of 2026), and walking them would freeze the page, so they throw instead.\n */\nexport const MAX_SPAN_DAYS = 9150;\nconst MAX_CACHED_DAYS = 20_000;\n\ntype MinuteInterval = readonly [from: number, to: number];\n\nconst toMinutes = (intervals: Calendar['week']['monday']): MinuteInterval[] =>\n intervals.map(({ start, end }) => [parseTimeOfDay(start) ?? 0, parseTimeOfDay(end) ?? 0] as const);\n\nexport function createWorkingCalendar(calendar: Calendar, zone: TimeZone): WorkingCalendar {\n const week = WEEKDAYS.map((day) => toMinutes(calendar.week[day]));\n const hasWeeklyWork = week.some((intervals) => intervals.length > 0);\n\n // Kept as ranges (not expanded per day), so a long exception costs nothing extra. Later ones win.\n const exceptions = calendar.exceptions.map((exception) => {\n const first = parseCivilDate(exception.startDate) ?? 0;\n return {\n first,\n last: parseCivilDate(exception.endDate) ?? first,\n intervals: toMinutes(exception.intervals),\n };\n });\n const exceptionOn = (day: number): MinuteInterval[] | undefined => {\n for (let i = exceptions.length - 1; i >= 0; i--) {\n const exception = exceptions[i];\n if (exception && exception.first <= day && day <= exception.last) return exception.intervals;\n }\n return undefined;\n };\n\n const cache = new Map<number, readonly Interval[]>();\n\n const intervalsOnDay = (day: number): readonly Interval[] => {\n let intervals = cache.get(day);\n if (!intervals) {\n const minutes = exceptionOn(day) ?? week[weekdayFromDays(day)] ?? [];\n intervals = minutes\n .map(([from, to]): Interval => [wallDayTime(day, from, zone), wallDayTime(day, to, zone)])\n // A DST change can squeeze an interval to nothing (e.g. 02:00–03:00 on spring-forward day).\n .filter(([start, end]) => end > start);\n if (cache.size >= MAX_CACHED_DAYS) cache.clear();\n cache.set(day, intervals);\n }\n return intervals;\n };\n\n const noWorkingTime = (): QuartzioError =>\n new QuartzioError(\n `Calendar \"${String(calendar.id)}\" has no working time within ${String(MAX_EMPTY_DAYS)} days. ` +\n 'Check its weekly schedule and exceptions.',\n );\n\n /** Calls `visit` for each working interval from `time` onward (or backward) until it returns true. */\n const scan = (time: number, direction: 1 | -1, visit: (interval: Interval) => boolean): void => {\n let day = wallDay(time, zone);\n let emptyDays = 0;\n for (let scanned = 0; ; scanned++) {\n if (scanned > MAX_SPAN_DAYS) throw tooLong();\n const intervals = intervalsOnDay(day);\n if (intervals.length === 0) {\n // Only exceptions can produce long runs of empty days when the week has working time.\n if (++emptyDays > MAX_EMPTY_DAYS || (!hasWeeklyWork && exceptions.length === 0))\n throw noWorkingTime();\n } else {\n emptyDays = 0;\n const ordered = direction === 1 ? intervals : [...intervals].reverse();\n for (const interval of ordered) if (visit(interval)) return;\n }\n day += direction;\n }\n };\n\n const tooLong = (): QuartzioError =>\n new QuartzioError(\n `Working-time calculation spans more than ${String(MAX_SPAN_DAYS)} days (~25 years). Check the dates and durations.`,\n );\n\n const assertFinite = (...values: number[]): void => {\n if (!values.every(Number.isFinite)) {\n throw new QuartzioError('Working-time calculations need finite numbers (not NaN or Infinity).');\n }\n };\n\n const addWorkingTime = (start: number, workingMs: number): number => {\n assertFinite(start, workingMs);\n if (workingMs === 0) return start;\n if (workingMs < 0) return subtractWorkingTime(start, -workingMs);\n let remaining = workingMs;\n let result = start;\n scan(start, 1, ([intervalStart, intervalEnd]) => {\n if (intervalEnd <= start) return false;\n const from = Math.max(intervalStart, start);\n if (intervalEnd - from >= remaining) {\n result = from + remaining;\n return true;\n }\n remaining -= intervalEnd - from;\n return false;\n });\n return result;\n };\n\n const subtractWorkingTime = (end: number, workingMs: number): number => {\n assertFinite(end, workingMs);\n if (workingMs === 0) return end;\n if (workingMs < 0) return addWorkingTime(end, -workingMs);\n let remaining = workingMs;\n let result = end;\n scan(end, -1, ([intervalStart, intervalEnd]) => {\n if (intervalStart >= end) return false;\n const to = Math.min(intervalEnd, end);\n if (to - intervalStart >= remaining) {\n result = to - remaining;\n return true;\n }\n remaining -= to - intervalStart;\n return false;\n });\n return result;\n };\n\n const workingIntervals = (from: number, to: number): Interval[] => {\n assertFinite(from, to);\n if (wallDay(to, zone) - wallDay(from, zone) > MAX_SPAN_DAYS) throw tooLong();\n const result: Interval[] = [];\n for (let day = wallDay(from, zone), last = wallDay(to, zone); day <= last; day++) {\n for (const [start, end] of intervalsOnDay(day)) {\n const clippedStart = Math.max(start, from);\n const clippedEnd = Math.min(end, to);\n if (clippedEnd > clippedStart) result.push([clippedStart, clippedEnd]);\n }\n }\n return result;\n };\n\n const workingTimeBetween = (from: number, to: number): number => {\n if (to < from) return -workingTimeBetween(to, from);\n return workingIntervals(from, to).reduce((total, [start, end]) => total + end - start, 0);\n };\n\n return {\n calendarId: calendar.id,\n timeZone: zone,\n\n isWorking: (time) =>\n Number.isFinite(time) &&\n intervalsOnDay(wallDay(time, zone)).some(([start, end]) => start <= time && time < end),\n\n nextWorkingTime(time) {\n assertFinite(time);\n let result = time;\n scan(time, 1, ([start, end]) => {\n if (end <= time) return false;\n result = Math.max(start, time);\n return true;\n });\n return result;\n },\n\n previousWorkingTime(time) {\n assertFinite(time);\n let result = time;\n scan(time, -1, ([start, end]) => {\n if (start >= time) return false;\n result = Math.min(end, time);\n return true;\n });\n return result;\n },\n\n addWorkingTime,\n subtractWorkingTime,\n\n workingTimeBetween,\n workingIntervals,\n };\n}\n","import { STANDARD_CALENDAR } from '../data/normalize';\nimport type { Calendar, Id, ProjectState } from '../data/types';\nimport { QuartzioError } from '../util/errors';\nimport type { TimeZone } from '../util/zone';\nimport { createWorkingCalendar, type WorkingCalendar } from './workingCalendar';\n\n// Keyed by the calendar record, so edits (which create new records) naturally get a fresh instance.\nconst cache = new WeakMap<Calendar, Map<TimeZone, WorkingCalendar>>();\n\n/**\n * The working calendar for a project: the calendar with `calendarId`, or the project calendar\n * (`settings.calendarId`, falling back to the standard Mon–Fri 08:00–16:00 calendar), in the project's\n * time zone. Instances are cached and cache their day computations. With `timeZone: 'local'`, the cached\n * results assume the host's zone doesn't change while the app runs.\n */\nexport function getWorkingCalendar(\n state: ProjectState,\n calendarId: Id | null = state.settings.calendarId,\n): WorkingCalendar {\n const calendar = calendarId === null ? STANDARD_CALENDAR : state.calendars.byId.get(calendarId);\n if (!calendar) throw new QuartzioError(`Calendar \"${String(calendarId)}\" does not exist.`);\n\n const zone = state.settings.timeZone;\n let byZone = cache.get(calendar);\n if (!byZone) cache.set(calendar, (byZone = new Map<TimeZone, WorkingCalendar>()));\n let working = byZone.get(zone);\n if (!working) byZone.set(zone, (working = createWorkingCalendar(calendar, zone)));\n return working;\n}\n","export type Listener<T> = (value: T) => void;\n\nexport interface Emitter<T> {\n subscribe: (listener: Listener<T>) => () => void;\n emit: (value: T) => void;\n clear: () => void;\n}\n\nexport function createEmitter<T>(): Emitter<T> {\n // Each subscription gets its own entry, so subscribing the same function twice needs two unsubscribes.\n const listeners = new Set<{ listener: Listener<T> }>();\n const queue: T[] = [];\n let emitting = false;\n\n return {\n subscribe(listener) {\n const entry = { listener };\n listeners.add(entry);\n return () => {\n listeners.delete(entry);\n };\n },\n emit(value) {\n queue.push(value);\n // An event emitted from inside a listener waits until everyone has seen the current one, so every\n // listener sees events in the same order (and the last one it sees is the latest).\n if (emitting) return;\n emitting = true;\n let failure: { error: unknown } | undefined;\n try {\n // An array iterator also visits items appended while iterating: events queued by listeners.\n for (const next of queue) {\n // Snapshot so listeners that unsubscribe during emit don't skip their neighbours.\n for (const entry of [...listeners]) {\n // One failing listener must not keep the others from being notified; rethrow afterwards.\n try {\n entry.listener(next);\n } catch (error) {\n failure ??= { error };\n }\n }\n }\n } finally {\n emitting = false;\n queue.length = 0;\n }\n if (failure) throw failure.error;\n },\n clear() {\n listeners.clear();\n },\n };\n}\n","import { shareDependencyEnds } from './graph';\nimport { shareTreeIndex } from './tree';\nimport type { Id, ProjectSettings, ProjectState, StoreName, StoreRecords, Table } from './types';\n\nexport interface DraftTable<R extends { readonly id: Id }> {\n byId: Map<Id, R>;\n order: Id[];\n}\n\n/**\n * Mutable, copy-on-write view of a ProjectState. Tables are cloned on first write only, so\n * untouched tables keep their identity in the finished state (cheap change detection downstream).\n */\nexport class Draft {\n private readonly base: ProjectState;\n private readonly writable = new Map<StoreName, DraftTable<{ readonly id: Id }>>();\n private readonly version = new Map<StoreName, number>();\n private readonly structureVersion = new Map<StoreName, number>();\n private settings: ProjectSettings | undefined;\n\n constructor(base: ProjectState) {\n this.base = base;\n }\n\n read<S extends StoreName>(store: S): Table<StoreRecords[S]> {\n const table: Table<{ readonly id: Id }> = this.writable.get(store) ?? this.base[store];\n return table as Table<StoreRecords[S]>;\n }\n\n write<S extends StoreName>(store: S): DraftTable<StoreRecords[S]> {\n this.version.set(store, (this.version.get(store) ?? 0) + 1);\n let table = this.writable.get(store);\n if (!table) {\n const source: Table<{ readonly id: Id }> = this.base[store];\n table = { byId: new Map(source.byId), order: [...source.order] };\n this.writable.set(store, table);\n }\n return table as DraftTable<StoreRecords[S]>;\n }\n\n readSettings(): ProjectSettings {\n return this.settings ?? this.base.settings;\n }\n\n writeSettings(settings: ProjectSettings): void {\n this.settings = settings;\n }\n\n /** Increments on every write to the store; lets callers cache derived data per version. */\n versionOf(store: StoreName): number {\n return this.version.get(store) ?? 0;\n }\n\n /** Records a change to the store's structure: records added, removed or moved, or a task's parent. */\n markStructure(store: StoreName): void {\n this.structureVersion.set(store, (this.structureVersion.get(store) ?? 0) + 1);\n }\n\n /** Increments on every structural change (see markStructure), e.g. to cache the task tree. */\n structureVersionOf(store: StoreName): number {\n return this.structureVersion.get(store) ?? 0;\n }\n\n finish(): ProjectState {\n if (this.writable.size === 0 && this.settings === undefined) return this.base;\n const tasks = this.read('tasks');\n if (this.structureVersionOf('tasks') === 0) shareTreeIndex(this.base.tasks, tasks);\n const dependencies = this.read('dependencies');\n if (this.structureVersionOf('dependencies') === 0)\n shareDependencyEnds(this.base.dependencies, dependencies);\n return {\n settings: this.readSettings(),\n calendars: this.read('calendars'),\n tasks,\n dependencies,\n };\n }\n}\n","import { QuartzioError } from '../util/errors';\nimport { Draft, type DraftTable } from './draft';\nimport { isId, type TouchedRecords } from './normalize';\nimport type { Id, Operation, ProjectState, StoreName } from './types';\n\nconst STORES: readonly string[] = ['calendars', 'tasks', 'dependencies'] satisfies StoreName[];\n\ntype AnyRecord = { readonly id: Id } & Record<string, unknown>;\n\nconst clamp = (value: number, max: number): number => Math.max(0, Math.min(value, max));\n\n/**\n * Applies one operation to the draft and returns its inverse.\n * Only checks what is needed to keep the tables consistent (ids exist / are unique);\n * semantic validation (parents exist, no cycles, ...) is the transaction's job.\n */\nexport function applyOperation(draft: Draft, op: Operation): Operation {\n if (op.type === 'settings') {\n if (typeof op.changes !== 'object' || (op.changes as unknown) === null) {\n throw new QuartzioError('Settings operation: \"changes\" must be an object.');\n }\n const settings = draft.readSettings();\n const previous: Record<string, unknown> = {};\n for (const key of Object.keys(op.changes) as (keyof typeof settings)[]) previous[key] = settings[key];\n draft.writeSettings({ ...settings, ...op.changes });\n return { type: 'settings', changes: previous };\n }\n // Operations may come from outside (JSON, servers), so don't trust their shape.\n if (!STORES.includes(op.store)) throw new QuartzioError(`Unknown store \"${op.store}\" in operation.`);\n const table = draft.write(op.store) as unknown as DraftTable<AnyRecord>;\n const store: StoreName = op.store;\n if (op.type === 'update' && (typeof op.changes !== 'object' || (op.changes as unknown) === null)) {\n throw new QuartzioError(`Cannot update ${store} \"${String(op.id)}\": \"changes\" must be an object.`);\n }\n // Structure: records added, removed or moved, a task's parent, or a dependency's ends.\n if (op.type !== 'update' || 'parentId' in op.changes || 'from' in op.changes || 'to' in op.changes) {\n draft.markStructure(store);\n }\n\n switch (op.type) {\n case 'add': {\n const record = op.record as unknown as AnyRecord;\n if (!isId(record.id)) throw new QuartzioError(`Cannot add ${store}: the record has no valid id.`);\n if (table.byId.has(record.id)) {\n throw new QuartzioError(`Cannot add ${store} \"${String(record.id)}\": the id already exists.`);\n }\n table.order.splice(clamp(op.index, table.order.length), 0, record.id);\n table.byId.set(record.id, record);\n return { type: 'remove', store, id: record.id };\n }\n case 'remove': {\n const record = table.byId.get(op.id);\n if (!record) throw unknownId(store, op.id, 'remove');\n const index = table.order.indexOf(op.id);\n table.order.splice(index, 1);\n table.byId.delete(op.id);\n return { type: 'add', store, record, index } as unknown as Operation;\n }\n case 'update': {\n const record = table.byId.get(op.id);\n if (!record) throw unknownId(store, op.id, 'update');\n if ('id' in op.changes)\n throw new QuartzioError(`Cannot update ${store} \"${String(op.id)}\": ids are immutable.`);\n const previous: Record<string, unknown> = {};\n for (const key of Object.keys(op.changes)) previous[key] = record[key];\n table.byId.set(op.id, { ...record, ...op.changes });\n return { type: 'update', store, id: op.id, changes: previous };\n }\n case 'move': {\n if (!table.byId.has(op.id)) throw unknownId(store, op.id, 'move');\n const from = table.order.indexOf(op.id);\n table.order.splice(from, 1);\n table.order.splice(clamp(op.index, table.order.length), 0, op.id);\n return { type: 'move', store, id: op.id, index: from };\n }\n default: {\n const unknown: never = op;\n throw new QuartzioError(`Unknown operation type \"${String((unknown as { type: unknown }).type)}\".`);\n }\n }\n}\n\n/**\n * Applies operations in order and returns the new state, the inverse operations and which records were\n * added or changed (for validation).\n */\nexport function applyOperations(\n state: ProjectState,\n operations: readonly Operation[],\n): { state: ProjectState; inverse: Operation[]; touched: TouchedRecords } {\n const draft = new Draft(state);\n const touched = {\n settings: false,\n calendars: new Set<Id>(),\n tasks: new Set<Id>(),\n dependencies: new Set<Id>(),\n };\n const inverse = operations\n .map((op) => {\n const result = applyOperation(draft, op);\n if (op.type === 'settings') touched.settings = true;\n else if (op.type === 'add') touched[op.store].add(op.record.id);\n else if (op.type === 'update') touched[op.store].add(op.id);\n return result;\n })\n .reverse();\n return { state: draft.finish(), inverse, touched };\n}\n\nfunction unknownId(store: StoreName, id: Id, action: string): QuartzioError {\n return new QuartzioError(`Cannot ${action} ${store} \"${String(id)}\": no record with that id.`);\n}\n","import { assertValidState, createProjectState } from './normalize';\nimport { applyOperations } from './operations';\nimport type { Id, Patch, ProjectData, ProjectState, Table } from './types';\n\nconst records = <R extends { readonly id: Id }>(table: Table<R>): R[] =>\n table.order.map((id) => table.byId.get(id) as R);\n\n/** Converts a state snapshot to the canonical, JSON-serializable data format. */\nexport function toProjectData(state: ProjectState): ProjectData {\n return {\n settings: state.settings,\n calendars: records(state.calendars),\n tasks: records(state.tasks),\n dependencies: records(state.dependencies),\n };\n}\n\n/**\n * Returns new project data with the patch applied; the input is not modified.\n * Meant for controlled usage: `onChange={({ patch }) => setData((data) => applyPatch(data, patch))}`.\n */\nexport function applyPatch(data: ProjectData, patch: Patch): ProjectData {\n const { state, touched } = applyOperations(createProjectState(data), patch.operations);\n assertValidState(state, touched);\n return toProjectData(state);\n}\n","import { isEqual } from '../util/equal';\nimport { QuartzioError } from '../util/errors';\nimport type { Draft } from './draft';\nimport {\n assertDependencyEnds,\n assertNoParentCycle,\n assertNoStructureFields,\n assertTaskConstraint,\n assertTaskDates,\n isId,\n normalizeCalendarChanges,\n normalizeCalendarFields,\n normalizeDependencyChanges,\n normalizeDependencyFields,\n normalizeSettingsChanges,\n normalizeTaskChanges,\n normalizeTaskFields,\n type CalendarFieldsInput,\n type DependencyFieldsInput,\n type TaskFieldsInput,\n} from './normalize';\nimport { applyOperation } from './operations';\nimport { getScheduleGraph } from './graph';\nimport { buildDraftTreeIndex, type DraftTreeIndex } from './tree';\nimport type {\n Calendar,\n Dependency,\n Id,\n Operation,\n ProjectState,\n ProjectSettings,\n ProjectSettingsInput,\n StoreName,\n Table,\n Task,\n} from './types';\n\n/** Where to put a task. `parentId` defaults to root (for add) or the current parent (for move); `index` to last. */\nexport interface TaskPosition {\n parentId?: Id | null;\n /** Position among the new siblings. */\n index?: number;\n}\n\nexport interface TaskAddInput extends TaskFieldsInput {\n /** Generated when omitted. */\n id?: Id;\n}\n\nexport type TaskUpdateInput = TaskFieldsInput;\n\nexport interface DependencyAddInput extends DependencyFieldsInput {\n /** Generated when omitted. */\n id?: Id;\n from: Id;\n to: Id;\n}\n\nexport interface DependencyUpdateInput extends DependencyFieldsInput {\n from?: Id;\n to?: Id;\n}\n\n// Property signatures (not methods) so the functions can be destructured and passed around.\nexport interface TaskTransaction {\n /** Reads reflect earlier writes in the same transaction. */\n get: (id: Id) => Task | undefined;\n children: (parentId: Id | null) => readonly Id[];\n add: (input: TaskAddInput, position?: TaskPosition) => Task;\n /** Fields that equal the current value are skipped, so no-op updates produce no operations. */\n update: (id: Id, changes: TaskUpdateInput) => void;\n move: (id: Id, position: TaskPosition) => void;\n /** Also removes all descendants and every dependency connected to them. */\n remove: (id: Id) => void;\n}\n\nexport interface DependencyTransaction {\n get: (id: Id) => Dependency | undefined;\n add: (input: DependencyAddInput) => Dependency;\n update: (id: Id, changes: DependencyUpdateInput) => void;\n remove: (id: Id) => void;\n}\n\nexport interface CalendarAddInput extends CalendarFieldsInput {\n /** Generated when omitted. */\n id?: Id;\n}\n\nexport type CalendarUpdateInput = CalendarFieldsInput;\n\nexport interface CalendarTransaction {\n get: (id: Id) => Calendar | undefined;\n add: (input: CalendarAddInput) => Calendar;\n update: (id: Id, changes: CalendarUpdateInput) => void;\n /** Fails while the calendar is the project calendar. */\n remove: (id: Id) => void;\n}\n\nexport interface SettingsTransaction {\n get: () => ProjectSettings;\n /**\n * Changing `timeZone` does not move existing dates (they are instants), but it changes how wall-clock\n * logic and date strings in later input are interpreted.\n */\n update: (changes: ProjectSettingsInput) => void;\n}\n\nexport interface Transaction {\n readonly settings: SettingsTransaction;\n readonly calendars: CalendarTransaction;\n readonly tasks: TaskTransaction;\n readonly dependencies: DependencyTransaction;\n}\n\nexport type IdGenerator = (store: StoreName, exists: (id: Id) => boolean) => Id;\n\nexport interface TransactionRecorder {\n transaction: Transaction;\n draft: Draft;\n operations: Operation[];\n inverse: Operation[];\n /** Checks structural invariants once the transaction function is done (e.g. no dependency cycles). */\n validate: () => void;\n /**\n * Checks invariants that may be broken until the change is complete, on the final state (after propagation,\n * which can repair them, e.g. a new start after the old end on a scheduled task).\n */\n validateResult: (state: ProjectState) => void;\n /** Makes every further use of the transaction throw. Called when the transaction function returns. */\n close: () => void;\n}\n\nconst clampIndex = (index: number | undefined, length: number): number => {\n if (index === undefined) return length;\n // NaN can't be clamped to anything meaningful (and would put a task in different places in the tree and in\n // `order`); out-of-range numbers, including ±Infinity, are clamped.\n if (typeof index !== 'number' || Number.isNaN(index)) {\n throw new QuartzioError(`Position index must be a number, got ${String(index)}.`);\n }\n return Math.max(0, Math.min(Math.trunc(index), length));\n};\n\n// Subtree size from which placementFor looks up positions through a map instead of scanning `order`.\nconst MAP_ABOVE = 8;\n\n/** Creates a transaction that applies every change to `draft` immediately and records the operations. */\nexport function createTransaction(draft: Draft, generateId: IdGenerator): TransactionRecorder {\n const operations: Operation[] = [];\n const inverse: Operation[] = [];\n const touchedTasks = new Set<Id>();\n let closed = false;\n\n // The draft's tables become the committed state, so a transaction used after it finished\n // (e.g. after an `await`) would silently mutate \"immutable\" state.\n const assertOpen = (): void => {\n if (closed) {\n throw new QuartzioError(\n 'This transaction has already finished. Transactions must be synchronous; do not keep or await them.',\n );\n }\n };\n\n const apply = (op: Operation): void => {\n assertOpen();\n inverse.push(applyOperation(draft, op));\n operations.push(op);\n };\n\n const tasks = (): Table<Task> => {\n assertOpen();\n return draft.read('tasks');\n };\n const dependencies = (): Table<Dependency> => {\n assertOpen();\n return draft.read('dependencies');\n };\n const calendars = (): Table<Calendar> => {\n assertOpen();\n return draft.read('calendars');\n };\n const settings = (): ProjectSettings => {\n assertOpen();\n return draft.readSettings();\n };\n\n const newId = (store: StoreName, requested: Id | undefined, exists: (id: Id) => boolean): Id => {\n const id = requested ?? generateId(store, exists);\n if (!isId(id)) {\n throw new QuartzioError(\n `${store === 'tasks' ? 'Task' : 'Dependency'} id must be a non-empty string or a finite number.`,\n );\n }\n return id;\n };\n\n // Rebuilt only after structural changes other than adds, which are inserted in place (see add).\n let tree: { version: number; index: DraftTreeIndex } | undefined;\n const treeIndex = (): DraftTreeIndex => {\n const version = draft.structureVersionOf('tasks');\n if (tree?.version !== version) tree = { version, index: buildDraftTreeIndex(tasks()) };\n return tree.index;\n };\n\n // Dependency ids per task (both ends), kept in step with adds and removals here and rebuilt after other\n // structural changes, so removing many tasks doesn't scan every dependency each time.\n let links: { version: number; byTask: Map<Id, Set<Id>> } | undefined;\n const linksOf = (): Map<Id, Set<Id>> => {\n const version = draft.structureVersionOf('dependencies');\n if (links?.version !== version) {\n const byTask = new Map<Id, Set<Id>>();\n for (const dependency of dependencies().byId.values()) link(byTask, dependency, true);\n links = { version, byTask };\n }\n return links.byTask;\n };\n const link = (byTask: Map<Id, Set<Id>>, dependency: Dependency, add: boolean): void => {\n for (const taskId of [dependency.from, dependency.to]) {\n let set = byTask.get(taskId);\n if (!set) byTask.set(taskId, (set = new Set()));\n if (add) set.add(dependency.id);\n else set.delete(dependency.id);\n }\n };\n // Applies a dependency add or remove and updates the links in place instead of invalidating them.\n const applyLinked = (op: Operation, dependency: Dependency, add: boolean): void => {\n const byTask = linksOf();\n apply(op);\n link(byTask, dependency, add);\n if (links) links.version = draft.structureVersionOf('dependencies');\n };\n\n const requireTask = (id: Id): Task => {\n const task = tasks().byId.get(id);\n if (!task) throw new QuartzioError(`Task \"${String(id)}\" does not exist.`);\n return task;\n };\n\n const requireDependency = (id: Id): Dependency => {\n const dependency = dependencies().byId.get(id);\n if (!dependency) throw new QuartzioError(`Dependency \"${String(id)}\" does not exist.`);\n return dependency;\n };\n\n const requireParent = (parentId: Id | null): void => {\n if (parentId !== null) requireTask(parentId);\n };\n\n /**\n * Where a task goes to be at `index` among the children of `parentId`: its index in `order`, and among its\n * siblings. With `moving`, positions are counted as if that task were already taken out (move semantics).\n */\n const placementFor = (\n parentId: Id | null,\n index: number | undefined,\n moving?: Id,\n ): { orderIndex: number; siblingIndex: number } => {\n const tree = treeIndex();\n // Positions come straight from `order`: it changes with every add, so a position map would need\n // rebuilding each time. Large subtrees get a map for their one lookup below.\n const order = tasks().order;\n const movingPosition = moving === undefined ? -1 : order.indexOf(moving);\n const adjust = (p: number): number => (movingPosition !== -1 && p > movingPosition ? p - 1 : p);\n\n const all = tree.childrenView(parentId);\n const siblings = moving === undefined ? all : all.filter((id) => id !== moving);\n const siblingIndex = clampIndex(index, siblings.length);\n const before = siblings[siblingIndex];\n if (before !== undefined) return { orderIndex: adjust(order.indexOf(before)), siblingIndex };\n\n const last = siblings[siblings.length - 1];\n if (last !== undefined) {\n const subtree = tree.descendants(last);\n // One scan per descendant is cheaper than a map for small subtrees, the common case when adding.\n const positions = subtree.length > MAP_ABOVE ? new Map(order.map((id, i) => [id, i])) : undefined;\n // A loop, not Math.max(...spread): large subtrees would overflow the call stack.\n let end = order.lastIndexOf(last); // appends usually go after the last task: search from the end\n for (const id of subtree) end = Math.max(end, positions?.get(id) ?? order.indexOf(id));\n return { orderIndex: adjust(end) + 1, siblingIndex };\n }\n if (parentId !== null) return { orderIndex: adjust(order.indexOf(parentId)) + 1, siblingIndex };\n return { orderIndex: order.length - (movingPosition === -1 ? 0 : 1), siblingIndex };\n };\n\n const changedFields = <R extends object>(record: R, changes: Partial<R>): Partial<R> => {\n const result: Partial<R> = {};\n for (const key of Object.keys(changes) as (keyof R)[]) {\n // Structural, so re-sending equal arrays/objects (e.g. a calendar's week) is not a change.\n if (!isEqual(record[key], changes[key])) result[key] = changes[key];\n }\n return result;\n };\n\n const taskTransaction: TaskTransaction = {\n get: (id) => tasks().byId.get(id),\n children: (parentId) => treeIndex().children(parentId),\n\n add(input, position = {}) {\n const { id: requestedId, ...fields } = input;\n const id = newId('tasks', requestedId, (candidate) => tasks().byId.has(candidate));\n const owner = `Task \"${String(id)}\"`;\n assertNoStructureFields(fields, owner);\n const parentId = position.parentId ?? null;\n requireParent(parentId);\n const record: Task = { id, parentId, ...normalizeTaskFields(fields, owner, settings().timeZone) };\n assertTaskConstraint(record);\n const { orderIndex, siblingIndex } = placementFor(parentId, position.index);\n apply({ type: 'add', store: 'tasks', record, index: orderIndex });\n // placementFor brought the tree up to date; insert instead of rebuilding it for the next add.\n if (tree) {\n tree.index.insert(id, parentId, siblingIndex);\n tree.version = draft.structureVersionOf('tasks');\n }\n touchedTasks.add(id);\n return record;\n },\n\n update(id, input) {\n const task = requireTask(id);\n const owner = `Task \"${String(id)}\"`;\n assertNoStructureFields(input, owner);\n const changes = changedFields(task, normalizeTaskChanges(input, owner, settings().timeZone));\n // A new end before the start is an error. (A new start after the old end isn't: scheduling moves the\n // end, keeping the duration; see validateResult.)\n if ('endDate' in changes) assertTaskDates({ ...task, ...changes });\n assertTaskConstraint({ ...task, ...changes });\n if (Object.keys(changes).length > 0) apply({ type: 'update', store: 'tasks', id, changes });\n touchedTasks.add(id);\n },\n\n move(id, position) {\n const task = requireTask(id);\n const parentId = position.parentId === undefined ? task.parentId : position.parentId;\n requireParent(parentId);\n assertNoParentCycle(tasks().byId, id, parentId);\n\n if (parentId !== task.parentId) apply({ type: 'update', store: 'tasks', id, changes: { parentId } });\n const { orderIndex } = placementFor(parentId, position.index, id);\n if (orderIndex !== tasks().order.indexOf(id))\n apply({ type: 'move', store: 'tasks', id, index: orderIndex });\n },\n\n remove(id) {\n requireTask(id);\n const index = treeIndex();\n const descendants = index.descendants(id);\n const subtree = [id, ...descendants];\n // Dependencies first, then tasks leaf-first, so the inverse re-adds parents before children\n // and tasks before the dependencies that reference them.\n const byTask = linksOf();\n const touching = new Set(subtree.flatMap((taskId) => [...(byTask.get(taskId) ?? [])]));\n for (const dependencyId of touching) {\n const dependency = requireDependency(dependencyId);\n applyLinked({ type: 'remove', store: 'dependencies', id: dependencyId }, dependency, false);\n }\n for (const taskId of [...subtree].reverse()) apply({ type: 'remove', store: 'tasks', id: taskId });\n index.removeSubtree(id, descendants);\n if (tree) tree.version = draft.structureVersionOf('tasks');\n },\n };\n\n const dependencyTransaction: DependencyTransaction = {\n get: (id) => dependencies().byId.get(id),\n\n add(input) {\n const { id: requestedId, from, to, ...fields } = input;\n const id = newId('dependencies', requestedId, (candidate) => dependencies().byId.has(candidate));\n const owner = `Dependency \"${String(id)}\"`;\n assertDependencyEnds(tasks().byId, from, to, owner);\n const record: Dependency = { id, from, to, ...normalizeDependencyFields(fields, owner) };\n applyLinked(\n { type: 'add', store: 'dependencies', record, index: dependencies().order.length },\n record,\n true,\n );\n return record;\n },\n\n update(id, input) {\n const dependency = requireDependency(id);\n const owner = `Dependency \"${String(id)}\"`;\n const { from = dependency.from, to = dependency.to, ...fields } = input;\n assertDependencyEnds(tasks().byId, from, to, owner);\n const changes = changedFields(dependency, { from, to, ...normalizeDependencyChanges(fields, owner) });\n if (Object.keys(changes).length > 0) apply({ type: 'update', store: 'dependencies', id, changes });\n },\n\n remove(id) {\n applyLinked({ type: 'remove', store: 'dependencies', id }, requireDependency(id), false);\n },\n };\n\n const calendarTransaction: CalendarTransaction = {\n get: (id) => calendars().byId.get(id),\n\n add(input) {\n const { id: requestedId, ...fields } = input;\n const id = newId('calendars', requestedId, (candidate) => calendars().byId.has(candidate));\n const record: Calendar = { id, ...normalizeCalendarFields(fields, `Calendar \"${String(id)}\"`) };\n apply({ type: 'add', store: 'calendars', record, index: calendars().order.length });\n return record;\n },\n\n update(id, input) {\n const calendar = calendars().byId.get(id);\n if (!calendar) throw new QuartzioError(`Calendar \"${String(id)}\" does not exist.`);\n const changes = changedFields(calendar, normalizeCalendarChanges(input, `Calendar \"${String(id)}\"`));\n if (Object.keys(changes).length > 0) apply({ type: 'update', store: 'calendars', id, changes });\n },\n\n remove(id) {\n if (!calendars().byId.has(id)) throw new QuartzioError(`Calendar \"${String(id)}\" does not exist.`);\n if (settings().calendarId === id) {\n throw new QuartzioError(\n `Calendar \"${String(id)}\" is the project calendar. Change settings.calendarId first.`,\n );\n }\n apply({ type: 'remove', store: 'calendars', id });\n },\n };\n\n const settingsTransaction: SettingsTransaction = {\n get: settings,\n update(input) {\n const changes = changedFields(settings(), normalizeSettingsChanges(input, settings().timeZone));\n if (changes.calendarId != null && !calendars().byId.has(changes.calendarId)) {\n throw new QuartzioError(`Project settings: calendar \"${String(changes.calendarId)}\" does not exist.`);\n }\n if (Object.keys(changes).length > 0) apply({ type: 'settings', changes });\n },\n };\n\n return {\n transaction: {\n settings: settingsTransaction,\n calendars: calendarTransaction,\n tasks: taskTransaction,\n dependencies: dependencyTransaction,\n },\n draft,\n operations,\n // Inverse operations must run in reverse order; pushed in order and reversed on read.\n get inverse() {\n return [...inverse].reverse();\n },\n validate: () => {\n // Dependency cycles, also through the hierarchy (a move can create one). Cached when nothing structural\n // changed.\n getScheduleGraph(draft.finish());\n },\n validateResult: (state) => {\n for (const id of touchedTasks) {\n const task = state.tasks.byId.get(id);\n if (task) assertTaskDates(task);\n }\n },\n close: () => {\n closed = true;\n },\n };\n}\n","import { createEmitter } from '../util/emitter';\nimport { QuartzioError } from '../util/errors';\nimport { Draft } from './draft';\nimport { assertTaskDates, assertValidState, createProjectState } from './normalize';\nimport { applyOperations } from './operations';\nimport { toProjectData } from './serialize';\nimport { createTransaction, type IdGenerator, type Transaction } from './transaction';\nimport type { Operation, Patch, ProjectData, ProjectInput, ProjectState, StoreName } from './types';\n\nexport interface ProjectChange {\n readonly state: ProjectState;\n /** `null` when the whole project was replaced via `load()`. */\n readonly patch: Patch | null;\n}\n\nexport interface PlannedChange {\n readonly state: ProjectState;\n readonly patch: Patch;\n}\n\nexport interface ProjectOptions {\n /** Creates ids for records added without one. Defaults to `task-1`, `dependency-1`, ... */\n generateId?: IdGenerator;\n /**\n * Completes every change (transactions, `apply`, `load` and the initial data) with more operations, applied\n * in the same change and included in its patch: this is how the scheduler writes computed dates back.\n * Gets the operations that were applied, or `null` for loaded data. Must be pure, and return nothing for a\n * state it already completed; if it throws, the change is rejected.\n */\n propagate?: (state: ProjectState, operations: readonly Operation[] | null) => readonly Operation[];\n}\n\n// Property signatures (not methods) so the functions can be passed around unbound.\nexport interface Project {\n getState: () => ProjectState;\n subscribe: (listener: (change: ProjectChange) => void) => () => void;\n /**\n * Replaces the whole project. Returns the operations `propagate` added to the loaded data (e.g. computed\n * dates), or `null` when it added none.\n */\n load: (input: ProjectInput) => Patch | null;\n /**\n * Runs `fn` against a draft and commits all its changes at once, emitting a single change.\n * If `fn` throws, nothing is changed. Returns `null` when nothing changed.\n */\n transact: (fn: (tx: Transaction) => void) => Patch | null;\n /**\n * Like `transact`, but only computes the result without committing it.\n * `base` plans on top of another state than the current one (e.g. an earlier planned change).\n */\n plan: (fn: (tx: Transaction) => void, base?: ProjectState) => PlannedChange | null;\n /**\n * Applies operations, e.g. a patch's `inverse` for undo or operations received from a server.\n * The result is validated (parents and dependency ends must exist, no cycles); on failure nothing changes.\n */\n apply: (operations: readonly Operation[]) => Patch | null;\n /** Like `apply`, but only computes the result without committing it (`base` as for `plan`). */\n planApply: (operations: readonly Operation[], base?: ProjectState) => PlannedChange | null;\n toData: () => ProjectData;\n}\n\nconst PREFIX: Record<StoreName, string> = {\n calendars: 'calendar',\n tasks: 'task',\n dependencies: 'dependency',\n};\n\nfunction createDefaultIdGenerator(): IdGenerator {\n const counters: Record<StoreName, number> = { calendars: 0, tasks: 0, dependencies: 0 };\n return (store, exists) => {\n let id: string;\n do id = `${PREFIX[store]}-${String(++counters[store])}`;\n while (exists(id));\n return id;\n };\n}\n\nfunction isThenable(value: unknown): boolean {\n return (\n typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function'\n );\n}\n\nexport function createProject(input: ProjectInput = {}, options: ProjectOptions = {}): Project {\n const changes = createEmitter<ProjectChange>();\n const generateId = options.generateId ?? createDefaultIdGenerator();\n const { propagate } = options;\n\n /** Applies what `propagate` adds to `base`, returning the state and a patch relative to `base`. */\n const complete = (\n base: ProjectState,\n applied: readonly Operation[] | null,\n ): { state: ProjectState; patch: Patch | null } => {\n const extra = propagate?.(base, applied) ?? [];\n if (extra.length === 0) return { state: base, patch: null };\n const result = applyOperations(base, extra);\n assertValidState(result.state, result.touched);\n return { state: result.state, patch: { operations: [...extra], inverse: result.inverse } };\n };\n /** Joins a change and what propagate added to it into one patch. */\n const join = (first: Patch, second: Patch | null): Patch =>\n second\n ? {\n operations: [...first.operations, ...second.operations],\n inverse: [...second.inverse, ...first.inverse],\n }\n : first;\n\n /** Applies operations and what propagate adds, validated, without committing. */\n const applyCompleted = (base: ProjectState, operations: readonly Operation[]): PlannedChange => {\n const result = applyOperations(base, operations);\n // End before start is checked after propagation, which can repair it (like transact does).\n assertValidState(result.state, result.touched, { taskDates: false });\n const completed = complete(result.state, operations);\n for (const id of result.touched.tasks) {\n const task = completed.state.tasks.byId.get(id);\n if (task) assertTaskDates(task);\n }\n return {\n state: completed.state,\n patch: join({ operations: [...operations], inverse: result.inverse }, completed.patch),\n };\n };\n\n let state = complete(createProjectState(input), null).state;\n let running = false;\n\n const commit = (next: ProjectState, patch: Patch | null): void => {\n state = next;\n changes.emit({ state, patch });\n };\n\n const assertNotRunning = (): void => {\n if (running) throw new QuartzioError('Cannot change the project while a transaction is running.');\n };\n\n // `fn` is typed as returning `unknown` here: callers pass `=> void`, but an async function still\n // type-checks as that, so the return value is checked at runtime.\n const plan = (fn: (tx: Transaction) => unknown, base: ProjectState = state): PlannedChange | null => {\n assertNotRunning();\n running = true;\n const recorder = createTransaction(new Draft(base), generateId);\n try {\n const result = fn(recorder.transaction);\n if (isThenable(result)) {\n throw new QuartzioError(\n 'Transaction functions must be synchronous. Do the async work before transact().',\n );\n }\n recorder.validate();\n } finally {\n recorder.close();\n running = false;\n }\n if (recorder.operations.length === 0) return null;\n const completed = complete(recorder.draft.finish(), recorder.operations);\n recorder.validateResult(completed.state);\n return {\n state: completed.state,\n patch: join({ operations: recorder.operations, inverse: recorder.inverse }, completed.patch),\n };\n };\n\n return {\n getState: () => state,\n subscribe: (listener) => changes.subscribe(listener),\n load(nextInput) {\n assertNotRunning();\n const completed = complete(createProjectState(nextInput, state), null);\n commit(completed.state, null);\n return completed.patch;\n },\n plan,\n transact(fn) {\n const planned = plan(fn);\n if (!planned) return null;\n commit(planned.state, planned.patch);\n return planned.patch;\n },\n planApply(operations, base = state) {\n assertNotRunning();\n if (operations.length === 0) return null;\n return applyCompleted(base, operations);\n },\n apply(operations) {\n assertNotRunning();\n if (operations.length === 0) return null;\n const { state: next, patch } = applyCompleted(state, operations);\n commit(next, patch);\n return patch;\n },\n toData: () => toProjectData(state),\n };\n}\n","import { deepFreeze } from '../util/equal';\nimport { QuartzioError } from '../util/errors';\nimport { isTimeUnit, type TimeUnit } from '../util/time';\nimport type { TimeZone } from '../util/zone';\n\nexport interface HeaderCellContext {\n start: number;\n end: number;\n unit: TimeUnit;\n increment: number;\n timeZone: TimeZone;\n /** BCP 47 locale, e.g. \"nb-NO\"; `undefined` uses the runtime default. */\n locale: string | undefined;\n}\n\n/** Built-in label formats. Month and weekday names follow the locale. */\nexport type HeaderFormatName =\n | 'year'\n | 'quarter'\n | 'quarterYear'\n | 'month'\n | 'monthShort'\n | 'monthYear'\n | 'monthShortYear'\n /** ISO 8601 week number, e.g. \"W41\". */\n | 'week'\n | 'day'\n | 'weekdayShort'\n | 'weekdayNarrow'\n | 'weekdayDay'\n | 'dayMonth'\n | 'weekdayDayMonth'\n | 'hour'\n | 'hourMinute';\n\n/** A built-in format, or a function. Functions should be pure and must not throw (errors leave the label empty). */\nexport type HeaderFormat = HeaderFormatName | ((cell: HeaderCellContext) => string);\n\nexport const HEADER_FORMATS: readonly HeaderFormatName[] = [\n 'year',\n 'quarter',\n 'quarterYear',\n 'month',\n 'monthShort',\n 'monthYear',\n 'monthShortYear',\n 'week',\n 'day',\n 'weekdayShort',\n 'weekdayNarrow',\n 'weekdayDay',\n 'dayMonth',\n 'weekdayDayMonth',\n 'hour',\n 'hourMinute',\n];\n\nexport interface HeaderRow {\n unit: TimeUnit;\n /** Units per cell. Defaults to 1. */\n increment?: number;\n format: HeaderFormat;\n}\n\nexport interface ViewPreset {\n id: string;\n /** The smallest column. Every tick gets the same width, however long it is in time. */\n tickUnit: TimeUnit;\n tickIncrement: number;\n /** Pixels per tick. */\n tickWidth: number;\n /** Header rows from top to bottom. */\n headers: readonly HeaderRow[];\n /** Resolution for snapping when dragging and resizing. */\n timeResolution: { unit: TimeUnit; increment: number };\n}\n\n/** Built-in presets, from most zoomed in to most zoomed out. */\nexport const VIEW_PRESETS: readonly ViewPreset[] = deepFreeze([\n {\n id: 'hourAndDay',\n tickUnit: 'hour',\n tickIncrement: 1,\n tickWidth: 44,\n headers: [\n { unit: 'day', format: 'weekdayDayMonth' },\n { unit: 'hour', format: 'hour' },\n ],\n timeResolution: { unit: 'minute', increment: 15 },\n },\n {\n id: 'dayAndWeek',\n tickUnit: 'day',\n tickIncrement: 1,\n tickWidth: 64,\n headers: [\n { unit: 'week', format: 'week' },\n { unit: 'day', format: 'weekdayDay' },\n ],\n timeResolution: { unit: 'hour', increment: 1 },\n },\n {\n id: 'weekAndDay',\n tickUnit: 'day',\n tickIncrement: 1,\n tickWidth: 32,\n headers: [\n { unit: 'month', format: 'monthYear' },\n { unit: 'week', format: 'week' },\n { unit: 'day', format: 'weekdayNarrow' },\n ],\n timeResolution: { unit: 'day', increment: 1 },\n },\n {\n id: 'weekAndMonth',\n tickUnit: 'week',\n tickIncrement: 1,\n tickWidth: 56,\n headers: [\n { unit: 'month', format: 'monthShortYear' },\n { unit: 'week', format: 'week' },\n ],\n timeResolution: { unit: 'day', increment: 1 },\n },\n {\n id: 'monthAndYear',\n tickUnit: 'month',\n tickIncrement: 1,\n tickWidth: 72,\n headers: [\n { unit: 'year', format: 'year' },\n { unit: 'month', format: 'monthShort' },\n ],\n timeResolution: { unit: 'day', increment: 1 },\n },\n {\n id: 'quarterAndYear',\n tickUnit: 'quarter',\n tickIncrement: 1,\n tickWidth: 96,\n headers: [\n { unit: 'year', format: 'year' },\n { unit: 'quarter', format: 'quarter' },\n ],\n timeResolution: { unit: 'week', increment: 1 },\n },\n {\n id: 'manyYears',\n tickUnit: 'year',\n tickIncrement: 1,\n tickWidth: 72,\n headers: [\n { unit: 'year', increment: 5, format: 'year' },\n { unit: 'year', format: 'year' },\n ],\n timeResolution: { unit: 'month', increment: 1 },\n },\n]);\n\nexport const DEFAULT_PRESET_ID = 'weekAndDay';\n\n/**\n * Increments must divide the next larger unit evenly (6 hours, not 5), so cells and ticks line up with\n * natural boundaries wherever you start counting. Days, weeks and years can use any whole number.\n */\nconst ALLOWED_INCREMENTS: Partial<Record<TimeUnit, readonly number[]>> = {\n millisecond: [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500],\n second: [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30],\n minute: [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30],\n hour: [1, 2, 3, 4, 6, 8, 12],\n month: [1, 2, 3, 4, 6],\n quarter: [1, 2],\n};\n\nfunction assertUnitAndIncrement(unit: unknown, increment: unknown, owner: string): void {\n if (!isTimeUnit(unit)) throw new QuartzioError(`${owner}: \"${String(unit)}\" is not a time unit.`);\n if (typeof increment !== 'number' || !Number.isInteger(increment) || increment < 1) {\n throw new QuartzioError(`${owner}: increment must be a whole number >= 1.`);\n }\n const allowed = ALLOWED_INCREMENTS[unit];\n if (allowed && !allowed.includes(increment)) {\n throw new QuartzioError(`${owner}: a \"${unit}\" increment must be one of ${allowed.join(', ')}.`);\n }\n}\n\n/** Looks up a built-in preset by id, or validates a custom one. */\nexport function resolvePreset(preset: string | ViewPreset = DEFAULT_PRESET_ID): ViewPreset {\n if (typeof preset === 'string') {\n const found = VIEW_PRESETS.find((candidate) => candidate.id === preset);\n if (!found) {\n throw new QuartzioError(\n `Unknown view preset \"${preset}\". Built-in presets: ${VIEW_PRESETS.map((p) => p.id).join(', ')}.`,\n );\n }\n return found;\n }\n\n const owner = `View preset \"${String((preset as Partial<ViewPreset> | null)?.id)}\"`;\n if (typeof preset !== 'object' || typeof preset.id !== 'string' || preset.id === '') {\n throw new QuartzioError('A view preset needs a non-empty string id.');\n }\n if (typeof preset.tickWidth !== 'number' || !Number.isFinite(preset.tickWidth) || preset.tickWidth <= 0) {\n throw new QuartzioError(`${owner}: tickWidth must be a number above 0.`);\n }\n assertUnitAndIncrement(preset.tickUnit, preset.tickIncrement, `${owner} (ticks)`);\n const resolution = preset.timeResolution as ViewPreset['timeResolution'] | undefined;\n assertUnitAndIncrement(resolution?.unit, resolution?.increment, `${owner} (timeResolution)`);\n if (!Array.isArray(preset.headers) || preset.headers.length === 0) {\n throw new QuartzioError(`${owner}: headers must be a non-empty array.`);\n }\n preset.headers.forEach((row: HeaderRow, index) => {\n const rowOwner = `${owner} (header row ${String(index)})`;\n assertUnitAndIncrement(row.unit, row.increment ?? 1, rowOwner);\n if (typeof row.format !== 'function' && !HEADER_FORMATS.includes(row.format)) {\n throw new QuartzioError(`${rowOwner}: unknown format \"${row.format}\".`);\n }\n });\n return preset;\n}\n","import { MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from '../util/civil';\nimport type { TimeUnit } from '../util/time';\nimport {\n addUnits,\n fromWallTime,\n startOfUnit,\n toWallTime,\n wallDay,\n zoneOffset,\n type TimeZone,\n} from '../util/zone';\n\nconst mod = (value: number, divisor: number): number => ((value % divisor) + divisor) % divisor;\n\n/**\n * Start of the `increment`-sized unit containing `time`, aligned to natural boundaries: 6 hours → 00, 06,\n * 12, 18; 3 months → January, April, …; 5 years → 2025, 2030, …\n */\nexport function alignToUnit(\n time: number,\n unit: TimeUnit,\n increment: number,\n zone: TimeZone,\n weekStartsOn: number,\n): number {\n const base = startOfUnit(time, unit, zone, weekStartsOn);\n if (increment === 1) return base;\n\n const wall = toWallTime(base, zone);\n let position: number;\n switch (unit) {\n case 'millisecond':\n position = wall.millisecond;\n break;\n case 'second':\n position = wall.second;\n break;\n case 'minute':\n position = wall.minute;\n break;\n case 'hour':\n position = wall.hour;\n break;\n case 'day':\n position = wallDay(base, zone);\n break;\n case 'week':\n // Every week start is the same weekday, so this counts weeks consistently.\n position = Math.floor(wallDay(base, zone) / 7);\n break;\n case 'month':\n position = wall.month - 1;\n break;\n case 'quarter':\n position = Math.floor((wall.month - 1) / 3);\n break;\n case 'year':\n position = wall.year;\n break;\n }\n const remainder = mod(position, increment);\n if (remainder === 0) return base;\n switch (unit) {\n // Sub-day units: go back on the wall clock, not by a fixed duration, which would overshoot across a\n // DST gap (03:00 on spring-forward day minus 3 hours is 23:00 the day before, not 00:00).\n case 'millisecond':\n return fromWallTime({ ...wall, millisecond: wall.millisecond - remainder }, zone);\n case 'second':\n return fromWallTime({ ...wall, second: wall.second - remainder }, zone);\n case 'minute':\n return fromWallTime({ ...wall, minute: wall.minute - remainder }, zone);\n case 'hour':\n return fromWallTime({ ...wall, hour: wall.hour - remainder }, zone);\n default:\n return addUnits(base, -remainder, unit, zone);\n }\n}\n\nconst SUB_DAY_SIZE: Partial<Record<TimeUnit, number>> = {\n millisecond: 1,\n second: MS_PER_SECOND,\n minute: MS_PER_MINUTE,\n hour: MS_PER_HOUR,\n};\n\n/**\n * The natural boundary after an aligned boundary. Always re-aligns instead of adding a fixed step, so the\n * result doesn't depend on where counting started.\n */\nexport function nextBoundary(\n boundary: number,\n unit: TimeUnit,\n increment: number,\n zone: TimeZone,\n weekStartsOn: number,\n): number {\n // Fast path: if `boundary` sits exactly on a wall-clock boundary (not shifted by a DST gap) and the UTC\n // offset is the same one step later, the wall clock moved exactly one step, so a fixed step lands on the\n // next natural boundary. This is the common case (no DST change in between) and avoids wall-clock math.\n const subDay = SUB_DAY_SIZE[unit];\n const step = subDay ?? (unit === 'day' ? MS_PER_DAY : unit === 'week' ? 7 * MS_PER_DAY : undefined);\n if (step !== undefined) {\n const offset = zoneOffset(boundary, zone);\n const candidate = boundary + step * increment;\n if (mod(boundary + offset, subDay ?? MS_PER_DAY) === 0 && zoneOffset(candidate, zone) === offset) {\n return candidate;\n }\n }\n\n const size = SUB_DAY_SIZE[unit];\n if (size !== undefined) {\n // Step half a step past the next boundary, then align down. A plain 6-hour step would drift from\n // 00/06/12/18 to 07/13/19 after a DST change.\n const next = alignToUnit(boundary + size * increment * 1.5, unit, increment, zone, weekStartsOn);\n return next > boundary ? next : boundary + size * increment;\n }\n // Days and longer: step on the wall calendar and re-align, so a DST change that skips midnight\n // (e.g. Cairo) doesn't leave every later boundary at 01:00.\n return alignToUnit(addUnits(boundary, increment, unit, zone), unit, increment, zone, weekStartsOn);\n}\n","import { QuartzioError } from '../util/errors';\nimport { isoWeek, toWallTime } from '../util/zone';\nimport type { HeaderCellContext, HeaderFormat, HeaderFormatName } from './presets';\n\nconst INTL_OPTIONS: Partial<Record<HeaderFormatName, Intl.DateTimeFormatOptions>> = {\n year: { year: 'numeric' },\n month: { month: 'long' },\n monthShort: { month: 'short' },\n monthYear: { month: 'long', year: 'numeric' },\n monthShortYear: { month: 'short', year: 'numeric' },\n day: { day: 'numeric' },\n weekdayShort: { weekday: 'short' },\n weekdayNarrow: { weekday: 'narrow' },\n weekdayDay: { weekday: 'short', day: 'numeric' },\n dayMonth: { day: 'numeric', month: 'short' },\n weekdayDayMonth: { weekday: 'short', day: 'numeric', month: 'short' },\n hour: { hour: 'numeric' },\n hourMinute: { hour: '2-digit', minute: '2-digit' },\n};\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatterFor(name: HeaderFormatName, cell: HeaderCellContext): Intl.DateTimeFormat {\n const key = `${name}|${cell.locale ?? ''}|${cell.timeZone}`;\n let formatter = formatters.get(key);\n if (!formatter) {\n const options = INTL_OPTIONS[name] ?? {};\n formatter = new Intl.DateTimeFormat(\n cell.locale,\n cell.timeZone === 'local' ? options : { ...options, timeZone: cell.timeZone },\n );\n formatters.set(key, formatter);\n }\n return formatter;\n}\n\n/** Throws QuartzioError for malformed locale tags (unsupported but well-formed tags fall back silently). */\nexport function assertLocale(locale: unknown): void {\n try {\n if (typeof locale !== 'string') throw new TypeError();\n Intl.DateTimeFormat.supportedLocalesOf(locale);\n } catch {\n throw new QuartzioError(\n `\"${String(locale)}\" is not a valid locale. Use a BCP 47 tag such as \"en-US\" or \"nb-NO\".`,\n );\n }\n}\n\nexport function formatHeaderCell(format: HeaderFormat, cell: HeaderCellContext): string {\n if (typeof format === 'function') {\n // A bug in a custom label must not break rendering (or leave the controller in a broken state).\n try {\n const label: unknown = format(cell);\n return typeof label === 'string' ? label : String(label);\n } catch {\n return '';\n }\n }\n switch (format) {\n case 'quarter':\n case 'quarterYear': {\n const { year, month } = toWallTime(cell.start, cell.timeZone);\n const quarter = `Q${String(Math.floor((month - 1) / 3) + 1)}`;\n return format === 'quarter' ? quarter : `${quarter} ${String(year)}`;\n }\n case 'week':\n // The middle of the cell, so weeks starting on Sunday still get the ISO number of their Mon–Sat.\n return `W${String(isoWeek(cell.start + (cell.end - cell.start) / 2, cell.timeZone).week)}`;\n default:\n return formatterFor(format, cell).format(cell.start);\n }\n}\n","import { QuartzioError } from '../util/errors';\nimport type { TimeZone } from '../util/zone';\nimport { alignToUnit, nextBoundary } from './align';\nimport { formatHeaderCell } from './format';\nimport type { ViewPreset } from './presets';\n\nexport interface TimeAxisOptions {\n /** The axis is widened to whole ticks around `[start, end)`. */\n start: number;\n end: number;\n preset: ViewPreset;\n timeZone: TimeZone;\n /** 0 = Sunday … 6 = Saturday. */\n weekStartsOn: number;\n locale?: string | undefined;\n /** Adds ticks after `end` until the axis is at least this many pixels wide (e.g. to fill a viewport). */\n minWidth?: number | undefined;\n /**\n * When the range needs more than `MAX_TICKS` ticks: stop there (the axis ends early) instead of\n * throwing. Used by the controller, which must never fail while rendering.\n */\n truncate?: boolean | undefined;\n}\n\nexport interface Tick {\n index: number;\n start: number;\n end: number;\n x: number;\n width: number;\n}\n\nexport interface HeaderCell {\n /** Stable key for rendering lists. */\n key: string;\n /** The cell's full time span; it may extend beyond the axis at the edges. */\n start: number;\n end: number;\n /** Position and width, clipped to the axis. */\n x: number;\n width: number;\n label: string;\n}\n\n/**\n * Maps time to pixels and back. Every tick has the same width; within a tick, position is linear in\n * time. So a 23-hour DST day is as wide as any other day, and every month is as wide as every other.\n */\nexport interface TimeAxis {\n readonly preset: ViewPreset;\n readonly timeZone: TimeZone;\n readonly locale: string | undefined;\n readonly weekStartsOn: number;\n /** First tick start and last tick end. */\n readonly start: number;\n readonly end: number;\n readonly tickCount: number;\n readonly tickWidth: number;\n readonly totalWidth: number;\n tick: (index: number) => Tick;\n /** Pixel position of a time. Times outside the axis are extrapolated from the edge ticks. */\n dateToX: (time: number) => number;\n /** Time at a pixel position; the inverse of `dateToX`, rounded to whole milliseconds. */\n xToDate: (x: number) => number;\n /** Ticks overlapping `[fromX, toX)`. */\n ticksInRange: (fromX: number, toX: number) => Tick[];\n /**\n * Cells of header row `row` (0 = top) overlapping `[fromX, toX)`, clipped to the axis. Always aligned to\n * natural boundaries, so the same cells come back whatever window is asked for. At most 10 000 cells.\n */\n headerCells: (row: number, fromX: number, toX: number) => HeaderCell[];\n /** Rounds to the nearest `timeResolution` boundary of the preset. */\n snap: (time: number) => number;\n}\n\n/** Guards against presets that would create absurd numbers of ticks (e.g. hours over centuries). */\nexport const MAX_TICKS = 200_000;\nconst MAX_HEADER_CELLS = 10_000;\n\nexport function createTimeAxis(options: TimeAxisOptions): TimeAxis {\n const { preset, timeZone, weekStartsOn, locale } = options;\n const { tickUnit, tickIncrement, tickWidth } = preset;\n if (!Number.isFinite(options.start) || !Number.isFinite(options.end)) {\n throw new QuartzioError('Time axis: start and end must be finite times.');\n }\n\n const minTicks = Math.ceil((options.minWidth ?? 0) / tickWidth);\n const boundaries: number[] = [alignToUnit(options.start, tickUnit, tickIncrement, timeZone, weekStartsOn)];\n do {\n if (boundaries.length - 1 >= MAX_TICKS) {\n if (options.truncate) break;\n throw new QuartzioError(\n `Time axis: more than ${String(MAX_TICKS)} ticks. Use a more zoomed-out preset or a shorter range.`,\n );\n }\n const last = boundaries[boundaries.length - 1] as number;\n boundaries.push(nextBoundary(last, tickUnit, tickIncrement, timeZone, weekStartsOn));\n } while ((boundaries[boundaries.length - 1] as number) < options.end || boundaries.length - 1 < minTicks);\n\n const tickCount = boundaries.length - 1;\n const totalWidth = tickCount * tickWidth;\n const boundary = (i: number): number => boundaries[i] as number;\n const start = boundary(0);\n const end = boundary(tickCount);\n\n /** Index of the tick containing `time` (which must be inside the axis). */\n const tickIndexAt = (time: number): number => {\n let low = 0;\n let high = tickCount - 1;\n while (low < high) {\n const middle = (low + high + 1) >> 1;\n if (boundary(middle) <= time) low = middle;\n else high = middle - 1;\n }\n return low;\n };\n\n const tick = (index: number): Tick => ({\n index,\n start: boundary(index),\n end: boundary(index + 1),\n x: index * tickWidth,\n width: tickWidth,\n });\n\n const dateToX = (time: number): number => {\n if (time < start) return ((time - start) / (boundary(1) - start)) * tickWidth;\n if (time >= end) return totalWidth + ((time - end) / (end - boundary(tickCount - 1))) * tickWidth;\n const i = tickIndexAt(time);\n return i * tickWidth + ((time - boundary(i)) / (boundary(i + 1) - boundary(i))) * tickWidth;\n };\n\n const xToDate = (x: number): number => {\n const i = Math.floor(x / tickWidth);\n if (i < 0) return Math.round(start + (x / tickWidth) * (boundary(1) - start));\n if (i >= tickCount) {\n return Math.round(end + ((x - totalWidth) / tickWidth) * (end - boundary(tickCount - 1)));\n }\n return Math.round(boundary(i) + ((x - i * tickWidth) / tickWidth) * (boundary(i + 1) - boundary(i)));\n };\n\n const clampIndex = (i: number): number => Math.max(0, Math.min(tickCount, i));\n\n return {\n preset,\n timeZone,\n locale,\n weekStartsOn,\n start,\n end,\n tickCount,\n tickWidth,\n totalWidth,\n tick,\n dateToX,\n xToDate,\n\n ticksInRange(fromX, toX) {\n const first = clampIndex(Math.floor(fromX / tickWidth));\n const last = clampIndex(Math.ceil(toX / tickWidth));\n const result: Tick[] = [];\n for (let i = first; i < last; i++) result.push(tick(i));\n return result;\n },\n\n headerCells(row, fromX, toX) {\n const header = preset.headers[row];\n if (!header)\n throw new QuartzioError(`Time axis: preset \"${preset.id}\" has no header row ${String(row)}.`);\n const increment = header.increment ?? 1;\n const from = Math.max(start, xToDate(fromX));\n const to = Math.min(end, xToDate(toX));\n const cells: HeaderCell[] = [];\n let cellStart = alignToUnit(from, header.unit, increment, timeZone, weekStartsOn);\n while (cellStart < to && cells.length < MAX_HEADER_CELLS) {\n const cellEnd = nextBoundary(cellStart, header.unit, increment, timeZone, weekStartsOn);\n const x = dateToX(Math.max(cellStart, start));\n cells.push({\n key: `${String(row)}:${String(cellStart)}`,\n start: cellStart,\n end: cellEnd,\n x,\n width: dateToX(Math.min(cellEnd, end)) - x,\n label: formatHeaderCell(header.format, {\n start: cellStart,\n end: cellEnd,\n unit: header.unit,\n increment,\n timeZone,\n locale,\n }),\n });\n cellStart = cellEnd;\n }\n return cells;\n },\n\n snap(time) {\n const { unit, increment } = preset.timeResolution;\n const floor = alignToUnit(time, unit, increment, timeZone, weekStartsOn);\n const ceil = nextBoundary(floor, unit, increment, timeZone, weekStartsOn);\n return time - floor < ceil - time ? floor : ceil;\n },\n };\n}\n","import { workingMsPerUnit } from '../calendar/duration';\nimport { getWorkingCalendar } from '../calendar/project';\nimport type { WorkingCalendar } from '../calendar/workingCalendar';\nimport { getDependencyIndex, getScheduleGraph } from '../data/graph';\nimport { getTreeIndex } from '../data/tree';\nimport type { Dependency, Id, Operation, ProjectState, Task } from '../data/types';\nimport { QuartzioError } from '../util/errors';\n\nconst NO_BOUND = Number.NEGATIVE_INFINITY;\n\n/**\n * Schedules the project and returns the operations that write the results back: for automatically scheduled\n * tasks, dates as soon as possible after the project start and their predecessors' requirements; for parents,\n * the span of their children; start, end and duration kept consistent everywhere.\n *\n * `operations` are the ones just applied (to tell a new end from a new duration), or `null` for loaded data.\n * Pure, idempotent (nothing to add to a state it scheduled), and doesn't throw for calendar trouble: a task\n * whose dates can't be computed (e.g. no working time at all) keeps its dates.\n */\nexport function scheduleProject(state: ProjectState, operations: readonly Operation[] | null): Operation[] {\n const { settings } = state;\n if (settings.startDate !== null) return run(state, operations, settings.startDate).operations;\n\n // No project start yet: the earliest task start. Without any, only manual tasks can get a start (e.g. from\n // an end and a duration), so schedule once to find the earliest, then again from there. Written back, so it\n // doesn't move when the earliest task does.\n let projectStart: number | null = null;\n for (const t of state.tasks.byId.values()) {\n if (t.startDate !== null && (projectStart === null || t.startDate < projectStart))\n projectStart = t.startDate;\n }\n let result = run(state, operations, projectStart);\n if (projectStart === null && result.earliest !== null) {\n projectStart = result.earliest;\n result = run(state, operations, projectStart);\n }\n return projectStart === null\n ? result.operations\n : [{ type: 'settings', changes: { startDate: projectStart } }, ...result.operations];\n}\n\nfunction run(\n state: ProjectState,\n operations: readonly Operation[] | null,\n projectStart: number | null,\n): { operations: Operation[]; earliest: number | null } {\n const result: Operation[] = [];\n const { settings } = state;\n const calendar = getWorkingCalendar(state);\n const graph = getScheduleGraph(state);\n const tree = getTreeIndex(state.tasks);\n const dependencies = getDependencyIndex(state.dependencies);\n const ids = graph.ids;\n const count = ids.length;\n const indexOf = new Map<Id, number>();\n ids.forEach((id, i) => indexOf.set(id, i));\n\n // Which task fields each operation changed: a new end (without a new duration) keeps the end.\n const changed = new Map<Id, Set<string>>();\n for (const op of operations ?? []) {\n if (op.type === 'update' && op.store === 'tasks') {\n let fields = changed.get(op.id);\n if (!fields) changed.set(op.id, (fields = new Set()));\n for (const key of Object.keys(op.changes)) fields.add(key);\n }\n }\n\n // Rounded one way only, so a derived duration converts back to exactly the same working time.\n const toMs = (value: number, unit: Task['durationUnit']) =>\n Math.round(value * workingMsPerUnit(unit, settings));\n const fromMs = (ms: number, unit: Task['durationUnit']) => ms / workingMsPerUnit(unit, settings);\n const context: Context = { calendar, toMs, fromMs };\n const shift = (time: number, lag: number, unit: Task['durationUnit']) => {\n const ms = toMs(lag, unit);\n return ms === 0 ? time : calendar.addWorkingTime(time, ms); // negative: subtracts\n };\n\n // Per task: its requirements (from the `in` node) and its dates (from the `out` node). NaN = unscheduled.\n const boundStart = new Float64Array(count).fill(NO_BOUND);\n const boundEnd = new Float64Array(count).fill(NO_BOUND);\n const starts = new Float64Array(count).fill(Number.NaN);\n const ends = new Float64Array(count).fill(Number.NaN);\n const durations = new Float64Array(count); // working ms, for weighting parents' progress\n const percents = new Float64Array(count);\n\n const requirements = (i: number, task: Task): void => {\n let start = NO_BOUND;\n let end = NO_BOUND;\n const parent = task.parentId === null ? undefined : indexOf.get(task.parentId);\n if (parent !== undefined) {\n start = boundStart[parent] as number;\n end = boundEnd[parent] as number;\n }\n // A manually scheduled task isn't pushed itself, but passes its parents' requirements on to its children.\n if (!task.manuallyScheduled) {\n // \"Start no earlier than\": like a requirement from a predecessor (and passed on to children the same way).\n if (task.constraintType === 'startnoearlierthan' && task.constraintDate !== null) {\n start = Math.max(start, task.constraintDate);\n }\n for (const dependency of dependencies.incoming(task.id)) {\n const from = indexOf.get(dependency.from);\n if (from === undefined || Number.isNaN(starts[from])) continue;\n let required: number;\n try {\n required = requirement(dependency, starts[from] as number, ends[from] as number, shift);\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n continue; // e.g. a lag beyond what the calendar will calculate: skip this requirement\n }\n if (dependency.type === 'FS' || dependency.type === 'SS') start = Math.max(start, required);\n else end = Math.max(end, required);\n }\n }\n boundStart[i] = start;\n boundEnd[i] = end;\n };\n let earliest: number | null = null;\n\n for (const node of graph.order) {\n const i = node >> 1;\n const id = ids[i] as Id;\n const task = state.tasks.byId.get(id) as Task;\n if ((node & 1) === 0) {\n requirements(i, task);\n continue;\n }\n\n let dates: Computed | null;\n try {\n dates = task.manuallyScheduled\n ? ownDates(task, context, changed.get(id))\n : (rollUp(tree.children(id), indexOf, { starts, ends, durations, percents }, task, context) ??\n asSoonAsPossible(\n task,\n projectStart,\n boundStart[i] as number,\n boundEnd[i] as number,\n context,\n changed.get(id),\n ));\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n dates = null; // e.g. no working time in the calendar: keep what the task has\n }\n\n const start = dates?.start ?? task.startDate;\n const end = dates?.end ?? task.endDate;\n if (start !== null && end !== null) {\n if (earliest === null || start < earliest) earliest = start;\n starts[i] = start;\n ends[i] = end;\n durations[i] =\n dates?.workingMs ?? (task.duration === null ? 0 : toMs(task.duration, task.durationUnit));\n }\n percents[i] = dates?.percentDone ?? task.percentDone;\n if (dates) {\n const changes = differences(task, dates);\n if (changes) result.push({ type: 'update', store: 'tasks', id, changes });\n }\n }\n return { operations: result, earliest };\n}\n\ninterface Context {\n calendar: WorkingCalendar;\n toMs: (value: number, unit: Task['durationUnit']) => number;\n fromMs: (ms: number, unit: Task['durationUnit']) => number;\n}\n\ninterface Computed {\n start: number;\n end: number;\n /** Only when it has to change (derived); otherwise the task's own duration stands. */\n duration?: number;\n workingMs: number;\n percentDone?: number;\n}\n\nfunction requirement(\n dependency: Dependency,\n start: number,\n end: number,\n shift: (time: number, lag: number, unit: Dependency['lagUnit']) => number,\n): number {\n const from = dependency.type === 'FS' || dependency.type === 'FF' ? end : start;\n return shift(from, dependency.lag, dependency.lagUnit);\n}\n\n/** The duration to schedule with, in working ms, and whether it's derived (and has to be written). */\nfunction workingDuration(\n task: Task,\n { calendar, toMs }: Context,\n changed: Set<string> | undefined,\n): { ms: number; derived: boolean } {\n const { startDate, endDate, duration } = task;\n const newEnd = changed?.has('endDate') === true && !changed.has('duration') && !changed.has('durationUnit');\n // (An end before the start comes from a new start on its own: the duration stands, and the end moves.)\n if (startDate !== null && endDate !== null && endDate >= startDate && (newEnd || duration === null)) {\n const ms = calendar.workingTimeBetween(startDate, endDate);\n // A replayed patch (redo, undo, controlled data coming back) repeats the scheduler's own new ends: when the\n // duration already amounts to that, it stands instead of being derived again (which could drift).\n if (duration !== null && toMs(duration, task.durationUnit) === ms) return { ms, derived: false };\n return { ms, derived: true };\n }\n if (duration !== null) return { ms: toMs(duration, task.durationUnit), derived: false };\n return { ms: 0, derived: true };\n}\n\n/** No dates and no duration: left out of scheduling (no bar), like Bryntum's unscheduled tasks. */\nconst isUnscheduled = (task: Task) =>\n task.startDate === null && task.endDate === null && task.duration === null;\n\nfunction asSoonAsPossible(\n task: Task,\n projectStart: number | null,\n startBound: number,\n endBound: number,\n context: Context,\n changed: Set<string> | undefined,\n): Computed | null {\n if (isUnscheduled(task)) return null;\n const { calendar } = context;\n const { ms, derived } = workingDuration(task, context, changed);\n let earliest = Math.max(projectStart ?? NO_BOUND, startBound);\n if (endBound !== NO_BOUND) earliest = Math.max(earliest, calendar.addWorkingTime(endBound, -ms));\n if (earliest === NO_BOUND) return null; // no project start and no requirements: unscheduled\n // Zero-length tasks (milestones) stay where they are required; others start at working time.\n const start = ms > 0 ? calendar.nextWorkingTime(earliest) : earliest;\n return computed(task, start, calendar.addWorkingTime(start, ms), ms, derived, context);\n}\n\nfunction ownDates(task: Task, context: Context, changed: Set<string> | undefined): Computed | null {\n const { calendar } = context;\n const { ms, derived } = workingDuration(task, context, changed);\n if (task.startDate !== null) {\n return computed(task, task.startDate, calendar.addWorkingTime(task.startDate, ms), ms, derived, context);\n }\n if (task.endDate !== null) {\n return computed(task, calendar.addWorkingTime(task.endDate, -ms), task.endDate, ms, derived, context);\n }\n return null;\n}\n\n/** A parent spans its scheduled children; `null` when none are scheduled (it's then scheduled like a task). */\nfunction rollUp(\n children: readonly Id[],\n indexOf: ReadonlyMap<Id, number>,\n { starts, ends, durations, percents }: Record<'starts' | 'ends' | 'durations' | 'percents', Float64Array>,\n task: Task,\n { calendar, fromMs }: Context,\n): Computed | null {\n let start = Number.POSITIVE_INFINITY;\n let end = Number.NEGATIVE_INFINITY;\n let weight = 0;\n let weighted = 0;\n let sum = 0;\n for (const child of children) {\n const c = indexOf.get(child) as number;\n sum += percents[c] as number;\n if (Number.isNaN(starts[c])) continue;\n start = Math.min(start, starts[c] as number);\n end = Math.max(end, ends[c] as number);\n weight += durations[c] as number;\n weighted += (durations[c] as number) * (percents[c] as number);\n }\n if (start === Number.POSITIVE_INFINITY) return null;\n const ms = calendar.workingTimeBetween(start, end);\n return {\n start,\n end,\n duration: fromMs(ms, task.durationUnit),\n workingMs: ms,\n percentDone: weight > 0 ? weighted / weight : sum / children.length,\n };\n}\n\nfunction computed(\n task: Task,\n start: number,\n computedEnd: number,\n ms: number,\n derived: boolean,\n context: Context,\n): Computed {\n // Keep the task's own end when it amounts to the same working time (e.g. midnight instead of 16:00 the day\n // before): the dates as given stay, and scheduling again changes nothing.\n const own = task.endDate;\n const keepOwn =\n own !== null &&\n own !== computedEnd &&\n task.startDate === start &&\n own >= start &&\n context.calendar.workingTimeBetween(start, own) === ms;\n const end = keepOwn ? own : computedEnd;\n return derived\n ? { start, end, workingMs: ms, duration: context.fromMs(ms, task.durationUnit) }\n : { start, end, workingMs: ms };\n}\n\n/** The fields that differ from the task, or `null`. */\nfunction differences(task: Task, dates: Computed): Partial<Task> | null {\n const changes: { -readonly [K in keyof Task]?: Task[K] } = {};\n if (task.startDate !== dates.start) changes.startDate = dates.start;\n if (task.endDate !== dates.end) changes.endDate = dates.end;\n if (dates.duration !== undefined && task.duration !== dates.duration) changes.duration = dates.duration;\n if (dates.percentDone !== undefined && task.percentDone !== dates.percentDone) {\n changes.percentDone = dates.percentDone;\n }\n return Object.keys(changes).length > 0 ? changes : null;\n}\n","import type { Task } from '../data/types';\n\n/** A task's dates as shown (scheduling keeps them in the task itself). */\nexport interface TaskDates {\n readonly start: number;\n readonly end: number;\n}\n\n/** Start and end; zero-length when only one is set (unscheduled data); `null` when neither is. */\nexport function taskDates(task: Task): TaskDates | null {\n const start = task.startDate ?? task.endDate;\n const end = task.endDate ?? task.startDate;\n return start === null || end === null ? null : { start, end: Math.max(start, end) };\n}\n","import type { TimeUnit } from '../util/time';\nimport { startOfUnit, type TimeZone } from '../util/zone';\n\nconst cache = new Map<string, Intl.DateTimeFormat | Intl.NumberFormat>();\n\nfunction cached<F extends Intl.DateTimeFormat | Intl.NumberFormat>(key: string, create: () => F): F {\n let formatter = cache.get(key) as F | undefined;\n if (!formatter) cache.set(key, (formatter = create()));\n return formatter;\n}\n\nexport function formatDate(time: number, zone: TimeZone, locale: string | undefined): string {\n return cached(\n `date|${locale ?? ''}|${zone}`,\n () =>\n new Intl.DateTimeFormat(\n locale,\n zone === 'local' ? { dateStyle: 'medium' } : { dateStyle: 'medium', timeZone: zone },\n ),\n ).format(time);\n}\n\nexport function formatDateTime(time: number, zone: TimeZone, locale: string | undefined): string {\n return cached(\n `datetime|${locale ?? ''}|${zone}`,\n () =>\n new Intl.DateTimeFormat(\n locale,\n zone === 'local'\n ? { dateStyle: 'medium', timeStyle: 'short' }\n : { dateStyle: 'medium', timeStyle: 'short', timeZone: zone },\n ),\n ).format(time);\n}\n\n/**\n * End dates are exclusive: a task on 5–8 October ends at midnight on the 9th. Shown as a date, that reads\n * as one day too many, so an end exactly at midnight is shown as the day before (like MS Project).\n */\nexport function formatEndDate(\n start: number,\n end: number,\n zone: TimeZone,\n locale: string | undefined,\n): string {\n const atMidnight = end > start && startOfUnit(end, 'day', zone) === end;\n return formatDate(atMidnight ? end - 1 : end, zone, locale);\n}\n\n// Units Intl.NumberFormat can spell out in every locale.\nconst INTL_UNITS: Partial<Record<TimeUnit, string>> = {\n millisecond: 'millisecond',\n second: 'second',\n minute: 'minute',\n hour: 'hour',\n day: 'day',\n week: 'week',\n month: 'month',\n year: 'year',\n};\n\nexport function formatDuration(value: number, unit: TimeUnit, locale: string | undefined): string {\n const intlUnit = INTL_UNITS[unit];\n if (intlUnit === undefined) {\n // Quarters have no localized unit name.\n const number = cached(\n `number|${locale ?? ''}`,\n () => new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }),\n );\n return `${number.format(value)} q`;\n }\n return cached(\n `duration|${locale ?? ''}|${intlUnit}`,\n () =>\n new Intl.NumberFormat(locale, {\n style: 'unit',\n unit: intlUnit,\n unitDisplay: 'long',\n maximumFractionDigits: 2,\n }),\n ).format(value);\n}\n\nexport function formatPercent(value: number, locale: string | undefined): string {\n return cached(\n `percent|${locale ?? ''}`,\n () => new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: 0 }),\n ).format(value / 100);\n}\n","import { workingMsPerUnit } from '../calendar/duration';\nimport type { WorkingCalendar } from '../calendar/workingCalendar';\nimport type { ProjectSettings, Task } from '../data/types';\nimport type { TaskDates } from './dates';\nimport { QuartzioError } from '../util/errors';\nimport { formatDate, formatDuration, formatEndDate, formatPercent } from './cells';\n\nexport type BuiltInColumnId = 'name' | 'startDate' | 'endDate' | 'duration' | 'percentDone';\n\n/** What a cell's value function gets. */\nexport interface CellContext {\n readonly task: Task;\n /** Whether the task has children (its dates then span its descendants). */\n readonly isParent: boolean;\n /** Computed display dates, or `null` for unscheduled tasks. */\n readonly dates: TaskDates | null;\n readonly settings: ProjectSettings;\n readonly locale: string | undefined;\n /** The project calendar, e.g. to measure working time. Absent if it can't be used. */\n readonly calendar: WorkingCalendar | undefined;\n}\n\nexport interface ColumnDefinition {\n id: string;\n title?: string;\n /** Pixels. */\n width?: number;\n /** A built-in column to base this one on (its title, width and value). */\n field?: BuiltInColumnId;\n align?: 'start' | 'end';\n /** Cell text. Must not throw (errors leave the cell empty). */\n value?: (cell: CellContext) => string;\n /**\n * Whether cells can be edited (double-click, Enter/F2). Default `true` for columns with a `field` (the edit\n * writes that field), and always `false` without one.\n */\n editable?: boolean;\n}\n\nexport type ColumnInput = BuiltInColumnId | ColumnDefinition;\n\nexport interface Column {\n readonly id: string;\n readonly title: string;\n readonly width: number;\n /** Left edge within the task list. */\n readonly x: number;\n readonly align: 'start' | 'end';\n /** The column that shows the tree (indentation and expand/collapse). */\n readonly tree: boolean;\n /** Its cells can be edited (some cells still can't, e.g. a parent's dates). */\n readonly editable: boolean;\n}\n\nexport interface ColumnsState {\n readonly items: readonly Column[];\n /** Width of the task list. */\n readonly totalWidth: number;\n}\n\nexport interface ResolvedColumns {\n readonly state: ColumnsState;\n readonly values: readonly ((cell: CellContext) => string)[];\n /** The field each column edits, or `null` when it can't be edited. */\n readonly fields: readonly (BuiltInColumnId | null)[];\n}\n\ninterface BuiltIn {\n title: string;\n width: number;\n align: 'start' | 'end';\n value: (cell: CellContext) => string;\n}\n\nconst zoneOf = (cell: CellContext) => cell.settings.timeZone;\n\nconst BUILT_IN: Record<BuiltInColumnId, BuiltIn> = {\n name: { title: 'Name', width: 240, align: 'start', value: ({ task }) => task.name },\n startDate: {\n title: 'Start',\n width: 120,\n align: 'start',\n value: (cell) => (cell.dates ? formatDate(cell.dates.start, zoneOf(cell), cell.locale) : ''),\n },\n endDate: {\n title: 'End',\n width: 120,\n align: 'start',\n value: (cell) =>\n cell.dates ? formatEndDate(cell.dates.start, cell.dates.end, zoneOf(cell), cell.locale) : '',\n },\n duration: {\n title: 'Duration',\n width: 100,\n align: 'end',\n value: ({ task, isParent, dates, settings, locale, calendar }) => {\n // A parent's dates span its children, so its own duration would contradict the dates shown.\n if (task.duration !== null && !isParent)\n return formatDuration(task.duration, task.durationUnit, locale);\n // Otherwise: the working time its dates span, in days.\n if (!dates || !calendar) return '';\n const days = calendar.workingTimeBetween(dates.start, dates.end) / workingMsPerUnit('day', settings);\n return formatDuration(days, 'day', locale);\n },\n },\n percentDone: {\n title: '% Done',\n width: 80,\n align: 'end',\n value: ({ task, locale }) => formatPercent(task.percentDone, locale),\n },\n};\n\n/** A built-in column's text for a cell (also used by the task tooltip). */\nexport const builtInText = (field: BuiltInColumnId, cell: CellContext): string => BUILT_IN[field].value(cell);\n\nexport const DEFAULT_COLUMNS: readonly BuiltInColumnId[] = ['name', 'startDate', 'endDate', 'duration'];\n\nconst isBuiltIn = (value: unknown): value is BuiltInColumnId =>\n typeof value === 'string' && Object.hasOwn(BUILT_IN, value);\n\n/** Validates columns; throws QuartzioError for invalid definitions. */\nexport function resolveColumns(input: readonly ColumnInput[] = DEFAULT_COLUMNS): ResolvedColumns {\n // Input may come from plain JavaScript, so check it as unknown.\n const entries: unknown = input;\n if (!Array.isArray(entries)) throw new QuartzioError('Gantt options: \"columns\" must be an array.');\n const ids = new Set<string>();\n const items: Column[] = [];\n const values: ((cell: CellContext) => string)[] = [];\n const fields: (BuiltInColumnId | null)[] = [];\n let x = 0;\n\n for (const entry of entries as readonly ColumnInput[]) {\n if (typeof entry !== 'string' && (typeof entry !== 'object' || (entry as unknown) === null)) {\n throw new QuartzioError('Every column must be a built-in column id or a column definition object.');\n }\n const definition: ColumnDefinition = typeof entry === 'string' ? { id: entry, field: entry } : entry;\n if (typeof entry === 'string' && !isBuiltIn(entry)) {\n throw new QuartzioError(\n `Unknown column \"${String(entry)}\". Built-in columns: ${Object.keys(BUILT_IN).join(', ')}.`,\n );\n }\n const { id, field } = definition;\n if (typeof id !== 'string' || id === '')\n throw new QuartzioError('Every column needs a non-empty string id.');\n if (ids.has(id)) throw new QuartzioError(`Column \"${id}\" is defined more than once.`);\n if (field !== undefined && !isBuiltIn(field))\n throw new QuartzioError(`Column \"${id}\": unknown field \"${String(field)}\".`);\n const builtIn = field ? BUILT_IN[field] : undefined;\n if (definition.value !== undefined && typeof definition.value !== 'function') {\n throw new QuartzioError(`Column \"${id}\": \"value\" must be a function.`);\n }\n if (definition.title !== undefined && typeof definition.title !== 'string') {\n throw new QuartzioError(`Column \"${id}\": \"title\" must be a string.`);\n }\n const editableInput: unknown = definition.editable;\n if (editableInput !== undefined && typeof editableInput !== 'boolean') {\n throw new QuartzioError(`Column \"${id}\": \"editable\" must be true or false.`);\n }\n const editable = field !== undefined && editableInput !== false;\n const align: unknown = definition.align;\n if (align !== undefined && align !== 'start' && align !== 'end') {\n throw new QuartzioError(`Column \"${id}\": \"align\" must be \"start\" or \"end\".`);\n }\n const value = definition.value ?? builtIn?.value;\n if (!value) throw new QuartzioError(`Column \"${id}\" needs a \"field\" or a \"value\" function.`);\n const width = definition.width ?? builtIn?.width ?? 120;\n if (typeof width !== 'number' || !Number.isFinite(width) || width <= 0 || width > 4000) {\n throw new QuartzioError(`Column \"${id}\": width must be a number above 0 and at most 4000.`);\n }\n\n ids.add(id);\n items.push({\n id,\n title: definition.title ?? builtIn?.title ?? id,\n width,\n x,\n align: definition.align ?? builtIn?.align ?? 'start',\n tree: field === 'name',\n editable,\n });\n fields.push(editable ? field : null);\n // A bug in a custom value function must not break rendering.\n values.push((cell) => {\n try {\n const text: unknown = value(cell);\n if (typeof text === 'string') return text;\n // Numbers and booleans read fine as text; anything else (null, objects) becomes an empty cell.\n return typeof text === 'number' || typeof text === 'boolean' ? String(text) : '';\n } catch {\n return '';\n }\n });\n x += width;\n }\n return { state: { items, totalWidth: x }, values, fields };\n}\n","import type { PlannedChange, Project } from '../data/project';\nimport { toProjectData } from '../data/serialize';\nimport type { Transaction } from '../data/transaction';\nimport type { Operation, Patch, ProjectData, ProjectInput, ProjectState } from '../data/types';\nimport type { History, HistoryAction } from './history';\nimport type { GanttDataChange } from './types';\n\nexport interface DataBinding {\n /** Controlled mode: new data from the app. */\n setData: (data: ProjectInput | undefined) => void;\n transact: (fn: (tx: Transaction) => void) => Patch | null;\n /** Applies operations as one change (undo and redo), recorded in the history as `action`. */\n apply: (operations: readonly Operation[], action: (patch: Patch) => HistoryAction) => Patch | null;\n /**\n * Controlled mode: whether an edit reported in this synchronous run is still waiting for the app. The history\n * doesn't show it yet, so undo and redo would pick the wrong step.\n */\n awaiting: () => boolean;\n setOnChange: (onChange: ((change: GanttDataChange) => void) | undefined) => void;\n /**\n * Reports what scheduling changed in the initial data, after a microtask. Called when the controller gets\n * its first subscriber: a renderer took it into use (React may create controllers it then throws away).\n */\n start: () => void;\n /** Stops reporting (a pending report of the initial scheduling is dropped). */\n destroy: () => void;\n}\n\n/**\n * Connects the project to the app's data: uncontrolled (the engine keeps edits) or controlled (edits are\n * only reported, and shown once the app passes new data back in).\n *\n * Loaded data is shown completed (scheduled). What that changed is reported through onChange too, so the app\n * can keep the scheduled data: right away for data passed in later; for the initial data (`initialPatch`) once\n * `start` is called, after a microtask, since the controller is usually created during rendering.\n */\nexport function createDataBinding(\n project: Project,\n controlled: boolean,\n initialData: ProjectInput | undefined,\n initialOnChange: ((change: GanttDataChange) => void) | undefined,\n initialPatch: Patch | null,\n history: Pick<History, 'confirm' | 'clear'>,\n): DataBinding {\n let onChange = initialOnChange;\n let currentData = initialData;\n // Set once anything newer than the initial data was reported or loaded: its report is then out of date.\n let superseded = false;\n let destroyed = false;\n const report = (change: GanttDataChange): void => {\n superseded = true;\n if (!destroyed) onChange?.(change);\n };\n // Controlled mode: the last change reported through onChange, relative to the committed state.\n // If exactly its data comes back, the operations are replayed instead of re-normalizing everything.\n // Its history actions take effect when the data comes back (the app accepted the change).\n let pending:\n { state: ProjectState; data: ProjectData; operations: Operation[]; actions: HistoryAction[] } | undefined;\n // Edits in the same synchronous run (e.g. two transact() calls in one event handler) build on each\n // other. Later edits build on the last data passed in, so a change the app rejected (by not passing\n // it back) is dropped instead of sneaking into the next one — like a controlled <input>.\n let chaining = false;\n\n /** Reports what completing loaded data changed; controlled, that data coming back is recognized. */\n const reportLoaded = (patch: Patch): void => {\n const data = toProjectData(project.getState());\n if (controlled) pending = { state: project.getState(), data, operations: [], actions: [] };\n report({ patch, data, source: 'load' });\n };\n\n let started = false;\n\n /** One change: controlled, planned and reported; uncontrolled, applied and reported. */\n const change = (\n plan: (base: ProjectState | undefined) => PlannedChange | null,\n apply: () => Patch | null,\n action: (patch: Patch) => HistoryAction,\n ): Patch | null => {\n if (controlled) {\n const previous = chaining ? pending : undefined;\n const planned = plan(previous?.state);\n if (!planned) return null;\n const done = action(planned.patch);\n pending = {\n state: planned.state,\n data: toProjectData(planned.state),\n operations: [...(previous?.operations ?? []), ...planned.patch.operations],\n actions: [...(previous?.actions ?? []), done],\n };\n if (!chaining) {\n chaining = true;\n void Promise.resolve().then(() => {\n chaining = false;\n });\n }\n report({ patch: planned.patch, data: pending.data, source: done.type });\n return planned.patch;\n }\n const patch = apply();\n if (patch) {\n const done = action(patch);\n history.confirm([done]);\n report({ patch, data: project.toData(), source: done.type });\n }\n return patch;\n };\n\n return {\n setData(data) {\n if (data === currentData) return;\n let patch: Patch | null = null;\n const accepted = pending !== undefined && pending.data === data ? pending : undefined;\n if (accepted) project.apply(accepted.operations);\n else patch = project.load(data ?? {});\n // Only after loading succeeded, so passing the same (fixed) data again is not skipped, and rejected data\n // doesn't cancel the initial report.\n superseded = true;\n currentData = data;\n pending = undefined;\n // The reported changes happened; other data makes the history meaningless.\n if (accepted) history.confirm(accepted.actions);\n else history.clear();\n if (patch) reportLoaded(patch);\n },\n\n transact(fn) {\n return change(\n (base) => project.plan(fn, base),\n () => project.transact(fn),\n (patch) => ({ type: 'edit', patch }),\n );\n },\n\n apply(operations, action) {\n return change(\n (base) => project.planApply(operations, base),\n () => project.apply(operations),\n action,\n );\n },\n\n awaiting() {\n return chaining && pending !== undefined && pending.actions.length > 0;\n },\n\n setOnChange(next) {\n onChange = next;\n },\n\n start() {\n if (started || !initialPatch) return;\n started = true;\n void Promise.resolve().then(() => {\n if (!superseded) reportLoaded(initialPatch);\n });\n },\n\n destroy() {\n destroyed = true;\n },\n };\n}\n","import type { Patch } from '../data/types';\n\n/** A change as it goes into the history: an edit, or an undo or redo of an earlier one (its patch). */\nexport interface HistoryAction {\n readonly type: 'edit' | 'undo' | 'redo';\n readonly patch: Patch;\n}\n\nexport interface HistoryState {\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n}\n\nexport interface History {\n readonly state: () => HistoryState;\n /** The change an undo would revert, and a redo would redo. */\n readonly undoable: () => Patch | undefined;\n readonly redoable: () => Patch | undefined;\n /** Records changes that took effect (in controlled mode: once the app passed the data back). */\n readonly confirm: (actions: readonly HistoryAction[]) => void;\n readonly clear: () => void;\n}\n\nconst LIMIT = 100;\n\n/** Undo and redo stacks of patches. The state object is the same while nothing changes. */\nexport function createHistory(): History {\n let undo: Patch[] = [];\n let redo: Patch[] = [];\n let state: HistoryState = { canUndo: false, canRedo: false };\n const update = () => {\n const next = { canUndo: undo.length > 0, canRedo: redo.length > 0 };\n if (next.canUndo !== state.canUndo || next.canRedo !== state.canRedo) state = next;\n };\n return {\n state: () => state,\n undoable: () => undo.at(-1),\n redoable: () => redo.at(-1),\n confirm(actions) {\n for (const { type, patch } of actions) {\n if (type === 'edit') {\n undo.push(patch);\n if (undo.length > LIMIT) undo.shift();\n redo = [];\n } else if (type === 'undo') {\n // Only the step on top can be undone. Anything else means the history no longer matches the data.\n if (undo.at(-1) !== patch) {\n undo = [];\n redo = [];\n continue;\n }\n undo.pop();\n redo.push(patch);\n } else {\n if (redo.at(-1) !== patch) {\n undo = [];\n redo = [];\n continue;\n }\n redo.pop();\n undo.push(patch);\n }\n }\n update();\n },\n clear() {\n undo = [];\n redo = [];\n update();\n },\n };\n}\n","import type { TreeIndex } from '../data/tree';\nimport type { Id, Task } from '../data/types';\n\n/** Which keys were held, for clicks and key presses. Ctrl and Cmd (meta) mean the same. */\nexport interface KeyModifiers {\n readonly shift?: boolean | undefined;\n readonly ctrl?: boolean | undefined;\n readonly meta?: boolean | undefined;\n readonly alt?: boolean | undefined;\n}\n\n/** Selected tasks, the keyboard cursor, and where Shift ranges start from. */\nexport interface Selection {\n /** In the order they were selected; a range in row order. */\n readonly ids: readonly Id[];\n readonly set: ReadonlySet<Id>;\n readonly active: Id | null;\n readonly anchor: Id | null;\n}\n\nexport const NO_SELECTION: Selection = { ids: [], set: new Set(), active: null, anchor: null };\n\n/** The visible rows, to find ranges and neighbours in. */\nexport interface VisibleRows {\n readonly rowIds: readonly Id[];\n readonly rowIndex: ReadonlyMap<Id, number>;\n readonly tree: TreeIndex;\n}\n\nconst sameIds = (a: readonly Id[], b: readonly Id[]) =>\n a.length === b.length && a.every((id, i) => id === b[i]);\n\n/** A selection, or `previous` when nothing changed (so its arrays keep their identity). */\nexport function selectionOf(\n previous: Selection,\n ids: readonly Id[],\n active: Id | null,\n anchor: Id | null,\n): Selection {\n const same = sameIds(previous.ids, ids);\n if (same && previous.active === active && previous.anchor === anchor) return previous;\n return same\n ? { ...previous, active, anchor }\n : {\n ids: previous.ids.length === 0 && ids.length === 0 ? previous.ids : ids,\n set: new Set(ids),\n active,\n anchor,\n };\n}\n\n/** The row showing a task: its own, or its nearest visible ancestor's when collapsed away. */\nexport function visibleRowOf(id: Id | null, rows: VisibleRows): number | undefined {\n if (id === null) return undefined;\n const own = rows.rowIndex.get(id);\n if (own !== undefined) return own;\n for (const ancestor of rows.tree.ancestors(id)) {\n const index = rows.rowIndex.get(ancestor);\n if (index !== undefined) return index;\n }\n return undefined;\n}\n\n/** The rows from the anchor (or its visible ancestor) to `target`, in row order. */\nfunction rangeTo(selection: Selection, target: number, rows: VisibleRows): Id[] {\n const from = visibleRowOf(selection.anchor, rows) ?? target;\n return rows.rowIds.slice(Math.min(from, target), Math.max(from, target) + 1);\n}\n\nconst union = (a: readonly Id[], b: readonly Id[]) => {\n const seen = new Set(a);\n return [...a, ...b.filter((id) => !seen.has(id))];\n};\n\n/**\n * Moves the cursor to a row: selects just it; with `extend` (Shift), the rows from the anchor to it (added to\n * the selection with `add`); with `add` alone (Ctrl/Cmd), leaves the selection as it is.\n */\nexport function moveTo(\n selection: Selection,\n target: number,\n rows: VisibleRows,\n { extend, add }: { extend: boolean; add: boolean },\n multiSelect: boolean,\n): Selection {\n const id = rows.rowIds[target] as Id;\n if (multiSelect && extend) {\n const range = rangeTo(selection, target, rows);\n return selectionOf(selection, add ? union(selection.ids, range) : range, id, selection.anchor ?? id);\n }\n if (multiSelect && add) return selectionOf(selection, selection.ids, id, selection.anchor);\n return selectionOf(selection, [id], id, id);\n}\n\n/** Selects or deselects a row (Ctrl/Cmd-click, Space). */\nexport function toggleRow(\n selection: Selection,\n target: number,\n rows: VisibleRows,\n multiSelect: boolean,\n): Selection {\n const id = rows.rowIds[target] as Id;\n const has = selection.set.has(id);\n if (!multiSelect) return selectionOf(selection, has && selection.ids.length === 1 ? [] : [id], id, id);\n return selectionOf(\n selection,\n has ? selection.ids.filter((other) => other !== id) : [...selection.ids, id],\n id,\n id,\n );\n}\n\n/** A click on a visible row, as in a file list: select it, toggle with Ctrl/Cmd, a range with Shift. */\nexport function clickRow(\n selection: Selection,\n id: Id,\n modifiers: KeyModifiers,\n rows: VisibleRows,\n multiSelect: boolean,\n): Selection {\n const target = rows.rowIndex.get(id);\n if (target === undefined) return selection;\n const add = modifiers.ctrl === true || modifiers.meta === true;\n const extend = modifiers.shift === true && selection.anchor !== null;\n if (add && !extend) return toggleRow(selection, target, rows, multiSelect);\n return moveTo(selection, target, rows, { extend, add }, multiSelect);\n}\n\n/** Selects existing tasks by id (duplicates and unknown ids skipped); the last one becomes the cursor. */\nexport function selectIds(\n selection: Selection,\n ids: readonly unknown[],\n tasks: ReadonlyMap<Id, Task>,\n multiSelect: boolean,\n): Selection {\n const known = [...new Set(ids)].filter((id): id is Id => tasks.has(id as Id));\n const kept = multiSelect ? known : known.slice(-1);\n const last = kept.at(-1);\n return last === undefined\n ? selectionOf(selection, [], selection.active, selection.anchor)\n : selectionOf(selection, kept, last, last);\n}\n\n/** Drops tasks that no longer exist (the same selection when none were removed). */\nexport function pruneSelection(selection: Selection, tasks: ReadonlyMap<Id, Task>): Selection {\n const exists = (id: Id | null) => (id !== null && tasks.has(id) ? id : null);\n if (selection.ids.every((id) => tasks.has(id)) && exists(selection.active) === selection.active) {\n if (exists(selection.anchor) === selection.anchor) return selection;\n }\n return selectionOf(\n selection,\n selection.ids.filter((id) => tasks.has(id)),\n exists(selection.active),\n exists(selection.anchor),\n );\n}\n","import type { Id } from '../data/types';\nimport {\n moveTo,\n selectionOf,\n toggleRow,\n visibleRowOf,\n type KeyModifiers,\n type Selection,\n type VisibleRows,\n} from './selection';\n\n/** A key press, as `KeyboardEvent.key` plus the modifiers held. */\nexport interface KeyInput extends KeyModifiers {\n readonly key: string;\n /** `KeyboardEvent.code`: finds shortcuts (Ctrl+Z, Ctrl+A) on layouts without latin letters. */\n readonly code?: string | undefined;\n}\n\nexport interface KeyContext extends VisibleRows {\n readonly selection: Selection;\n readonly collapsed: ReadonlySet<Id>;\n /** Rows that fit in the viewport, for PageUp and PageDown. */\n readonly pageRows: number;\n readonly multiSelect: boolean;\n readonly deleteKey: boolean;\n readonly undoRedo: boolean;\n readonly cellEdit: boolean;\n}\n\n/** What a key press does; carried out by the controller. */\nexport type KeyCommand =\n | { readonly type: 'select'; readonly selection: Selection }\n | { readonly type: 'expand'; readonly id: Id; readonly expanded: boolean }\n | { readonly type: 'delete'; readonly ids: readonly Id[]; readonly selection: Selection }\n | { readonly type: 'edit'; readonly id: Id }\n | { readonly type: 'menu'; readonly id: Id }\n | { readonly type: 'undo' }\n | { readonly type: 'redo' };\n\n/** The keyboard of the task grid. `null` for keys it leaves alone. */\nexport function keyCommand(input: KeyInput, context: KeyContext): KeyCommand | null {\n const { key } = input;\n if (typeof key !== 'string' || input.alt === true) return null;\n const mod = input.ctrl === true || input.meta === true;\n const shift = input.shift === true;\n const { selection, rowIds } = context;\n const count = rowIds.length;\n const lower = shortcutLetter(key, input.code);\n\n if (mod && (lower === 'z' || lower === 'y')) {\n if (!context.undoRedo) return null;\n return lower === 'y' || shift ? { type: 'redo' } : { type: 'undo' };\n }\n if (key === 'Delete' || key === 'Backspace') {\n return context.deleteKey && selection.ids.length > 0 ? deletion(context) : null;\n }\n if (key === 'Escape') {\n return selection.ids.length > 0\n ? { type: 'select', selection: selectionOf(selection, [], selection.active, selection.anchor) }\n : null;\n }\n if (count === 0) return null;\n if (mod && lower === 'a') {\n if (!context.multiSelect) return null;\n // A copy: the selection is handed to the app, and rowIds is the engine's own.\n return {\n type: 'select',\n selection: selectionOf(selection, [...rowIds], selection.active, selection.anchor),\n };\n }\n\n const current = visibleRowOf(selection.active, context);\n const move = (target: number): KeyCommand => ({\n type: 'select',\n selection: moveTo(\n selection,\n Math.max(0, Math.min(count - 1, target)),\n context,\n { extend: shift, add: mod },\n context.multiSelect,\n ),\n });\n const page = Math.max(1, context.pageRows);\n switch (key) {\n case 'ArrowDown':\n return move(current === undefined ? 0 : current + 1);\n case 'ArrowUp':\n return move(current === undefined ? 0 : current - 1);\n case 'PageDown':\n return move(current === undefined ? 0 : current + page);\n case 'PageUp':\n return move(current === undefined ? 0 : current - page);\n case 'Home':\n return move(0);\n case 'End':\n return move(count - 1);\n }\n if (current === undefined) return null;\n const id = rowIds[current] as Id;\n const isParent = !context.tree.isLeaf(id);\n switch (key) {\n case 'ArrowRight':\n if (!isParent) return null;\n if (context.collapsed.has(id)) return { type: 'expand', id, expanded: true };\n return move(current + 1); // its first child\n case 'ArrowLeft': {\n if (isParent && !context.collapsed.has(id)) return { type: 'expand', id, expanded: false };\n const parent = context.tree.ancestors(id)[0];\n const index = parent === undefined ? undefined : context.rowIndex.get(parent);\n return index === undefined ? null : move(index);\n }\n case ' ':\n return { type: 'select', selection: toggleRow(selection, current, context, context.multiSelect) };\n case 'ContextMenu':\n return { type: 'menu', id };\n case 'F10':\n return shift && !mod ? { type: 'menu', id } : null;\n case 'Enter':\n case 'F2':\n return context.cellEdit && !mod && !shift ? { type: 'edit', id } : null;\n }\n return null;\n}\n\n/** The letter of a key for shortcuts; from the physical key when the layout's key isn't a latin letter. */\nfunction shortcutLetter(key: string, code: string | undefined): string {\n const letter = key.length === 1 ? key.toLowerCase() : key;\n if (/^[a-z]$/.test(letter) || typeof code !== 'string' || !/^Key[A-Z]$/.test(code)) return letter;\n return code.slice(3).toLowerCase();\n}\n\n/**\n * Deletes the selected rows (a task inside another selected one goes with it). Selected tasks hidden in a\n * collapsed parent are left alone: a key press never deletes what can't be seen. The cursor moves to the row\n * that takes the place of the active one, or the one before when nothing comes after.\n */\nfunction deletion(context: KeyContext): KeyCommand | null {\n const { selection, tree, rowIds, rowIndex } = context;\n const ids = selection.ids.filter(\n (id) => rowIndex.has(id) && !tree.ancestors(id).some((ancestor) => selection.set.has(ancestor)),\n );\n if (ids.length === 0) return null;\n const gone = new Set(ids);\n const stays = (id: Id) => !gone.has(id) && !tree.ancestors(id).some((ancestor) => gone.has(ancestor));\n const from = visibleRowOf(selection.active, context) ?? context.rowIndex.get(ids[0] as Id) ?? 0;\n const after = rowIds.slice(from).find(stays);\n const next = after ?? rowIds.slice(0, from).reverse().find(stays) ?? null;\n return { type: 'delete', ids, selection: selectionOf(selection, [], next, next) };\n}\n","import type { Task } from '../data/types';\nimport type { TaskDates } from './dates';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\n\nexport type BarKind = 'task' | 'summary' | 'milestone';\n\n/** A task's bar on the timeline, in timeline coordinates (x = 0 is the start of the axis). */\nexport interface Bar {\n readonly kind: BarKind;\n /**\n * Left edge; for milestones, the center of the diamond. May be outside the axis for tasks that extend beyond\n * it, but is kept within one axis width on either side (`start` and `end` keep the real dates).\n */\n readonly x: number;\n /** 0 for milestones. */\n readonly width: number;\n readonly start: number;\n readonly end: number;\n /** 0–1. */\n readonly progress: number;\n readonly label: string;\n}\n\n/** Keeps very short tasks visible and clickable at coarse zoom levels. */\nexport const MIN_BAR_WIDTH = 2;\n\nexport function computeBar(\n task: Task,\n dates: TaskDates | null,\n isParent: boolean,\n axis: TimeAxis,\n): Bar | null {\n if (!dates) return null;\n // Browsers stop drawing tens of millions of pixels out, so keep positions near the axis.\n const clamp = (value: number) => Math.max(-axis.totalWidth, Math.min(2 * axis.totalWidth, value));\n const start = clamp(axis.dateToX(dates.start));\n const common = {\n start: dates.start,\n end: dates.end,\n progress: Math.max(0, Math.min(1, task.percentDone / 100)),\n label: task.name,\n };\n if (dates.end === dates.start && !isParent) return { kind: 'milestone', x: start, width: 0, ...common };\n const width = Math.max(MIN_BAR_WIDTH, clamp(axis.dateToX(dates.end)) - start);\n return {\n kind: isParent ? 'summary' : 'task',\n x: Math.min(start, 2 * axis.totalWidth - width),\n width,\n ...common,\n };\n}\n\nexport const sameBar = (a: Bar | null, b: Bar | null): boolean =>\n a === b ||\n (a !== null &&\n b !== null &&\n a.kind === b.kind &&\n a.x === b.x &&\n a.width === b.width &&\n a.start === b.start &&\n a.end === b.end &&\n a.progress === b.progress &&\n a.label === b.label);\n","import { getWorkingCalendar } from '../calendar/project';\nimport type { WorkingCalendar } from '../calendar/workingCalendar';\nimport { getTreeIndex } from '../data/tree';\nimport type { Id, ProjectState, Task } from '../data/types';\nimport { taskDates, type TaskDates } from './dates';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { computeBar, sameBar, type Bar } from './bars';\nimport type { ResolvedColumns } from './columns';\nimport type { Selection } from './selection';\nimport type { Viewport } from './types';\n\n/** A string key per task for rendering lists: tasks 1 and \"1\" are different. */\nexport const rowKey = (id: Id): string => `${typeof id === 'number' ? 'n' : 's'}:${String(id)}`;\n\nexport interface Row {\n readonly id: Id;\n /** Unique string key for rendering lists (ids 1 and \"1\" are different tasks). */\n readonly key: string;\n /** Position among the visible rows. */\n readonly index: number;\n readonly y: number;\n readonly height: number;\n /** 0 for root tasks. */\n readonly depth: number;\n readonly task: Task;\n readonly hasChildren: boolean;\n readonly expanded: boolean;\n /** Computed display dates, or `null` for unscheduled tasks. */\n readonly dates: TaskDates | null;\n /** Cell texts, one per column. */\n readonly cells: readonly string[];\n /** The task's bar on the timeline, or `null` for unscheduled tasks. */\n readonly bar: Bar | null;\n readonly selected: boolean;\n /** The keyboard cursor is on this row. */\n readonly active: boolean;\n}\n\nexport interface RowsState {\n readonly rowHeight: number;\n /** Visible rows in total (not counting collapsed descendants). */\n readonly count: number;\n readonly totalHeight: number;\n /**\n * Rows around the visible part only (virtualized). Unchanged rows keep their identity, so they can be\n * memoized, and the array itself is reused while scrolling within the rendered window.\n */\n readonly items: readonly Row[];\n}\n\nexport interface RowsInput {\n readonly project: ProjectState;\n readonly collapsed: ReadonlySet<Id>;\n /** Changes whenever `collapsed` changes. */\n readonly collapsedVersion: number;\n readonly viewport: Viewport;\n readonly rowHeight: number;\n readonly columns: ResolvedColumns;\n readonly locale: string | undefined;\n readonly timeAxis: TimeAxis;\n readonly selection: Selection;\n}\n\n/** Assumed viewport height before it has been measured (and when rendering on the server). */\nexport const UNMEASURED_HEIGHT = 800;\n\ninterface VisibleRows {\n readonly ids: readonly Id[];\n readonly depths: readonly number[];\n /** Row index per visible task. */\n readonly index: ReadonlyMap<Id, number>;\n}\n\n/** Tree order, skipping the descendants of collapsed tasks. Iterative, so deep trees can't overflow. */\nfunction visibleRows(project: ProjectState, collapsed: ReadonlySet<Id>): VisibleRows {\n const tree = getTreeIndex(project.tasks);\n const ids: Id[] = [];\n const depths: number[] = [];\n const index = new Map<Id, number>();\n const stack: [Id, number][] = [...tree.children(null)].reverse().map((id): [Id, number] => [id, 0]);\n while (stack.length > 0) {\n const [id, depth] = stack.pop() as [Id, number];\n index.set(id, ids.length);\n ids.push(id);\n depths.push(depth);\n if (!collapsed.has(id)) {\n const children = tree.children(id);\n for (let i = children.length - 1; i >= 0; i--) stack.push([children[i] as Id, depth + 1]);\n }\n }\n return { ids, depths, index };\n}\n\nconst sameCells = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && a.every((text, i) => text === b[i]);\n\nconst sameDates = (a: TaskDates | null, b: TaskDates | null) =>\n a === b || (a !== null && b !== null && a.start === b.start && a.end === b.end);\n\nexport function createRowsView(): {\n /** The rows, the row index of every visible task and the task of every row (the same while visibility is unchanged). */\n rowsFor: (input: RowsInput) => {\n rows: RowsState;\n rowIndex: ReadonlyMap<Id, number>;\n rowIds: readonly Id[];\n };\n} {\n let visibleCache: { key: unknown[]; rows: VisibleRows } | undefined;\n let calendarCache: { project: ProjectState; calendar: WorkingCalendar | undefined } | undefined;\n let windowCache: { key: unknown[]; first: number; last: number; state: RowsState } | undefined;\n let previousRows = new Map<Id, Row>();\n\n const calendarFor = (project: ProjectState): WorkingCalendar | undefined => {\n if (calendarCache?.project !== project) {\n let calendar: WorkingCalendar | undefined;\n try {\n calendar = getWorkingCalendar(project);\n } catch {\n calendar = undefined;\n }\n calendarCache = { project, calendar };\n }\n return calendarCache.calendar;\n };\n\n const rowsFor = (input: RowsInput): RowsState => {\n const {\n project,\n collapsed,\n collapsedVersion,\n viewport,\n rowHeight,\n columns,\n locale,\n timeAxis,\n selection,\n } = input;\n\n const visibleKey = [project.tasks, collapsedVersion];\n if (!visibleCache || visibleKey.some((part, i) => part !== visibleCache?.key[i])) {\n visibleCache = { key: visibleKey, rows: visibleRows(project, collapsed) };\n }\n const visible = visibleCache.rows;\n const count = visible.ids.length;\n\n const height = viewport.height > 0 ? viewport.height : UNMEASURED_HEIGHT;\n const clamp = (index: number) => Math.max(0, Math.min(count, index));\n const visibleFirst = clamp(Math.floor(viewport.scrollTop / rowHeight));\n const visibleLast = clamp(Math.ceil((viewport.scrollTop + height) / rowHeight));\n\n const key = [visible, project, rowHeight, columns, locale, timeAxis, selection];\n if (\n windowCache &&\n key.every((part, i) => part === windowCache?.key[i]) &&\n windowCache.first <= visibleFirst &&\n visibleLast <= windowCache.last\n ) {\n return windowCache.state;\n }\n\n // Render one extra viewport above and below, so most scrolling reuses the same rows.\n const first = clamp(Math.floor((viewport.scrollTop - height) / rowHeight));\n const last = clamp(Math.ceil((viewport.scrollTop + 2 * height) / rowHeight));\n const tree = getTreeIndex(project.tasks);\n const calendar = calendarFor(project);\n const rows = new Map<Id, Row>();\n const items: Row[] = [];\n\n for (let index = first; index < last; index++) {\n const id = visible.ids[index] as Id;\n const task = project.tasks.byId.get(id) as Task;\n const hasChildren = !tree.isLeaf(id);\n const rowDates = taskDates(task);\n const context = {\n task,\n isParent: hasChildren,\n dates: rowDates,\n settings: project.settings,\n locale,\n calendar,\n };\n const row: Row = {\n id,\n key: rowKey(id),\n index,\n y: index * rowHeight,\n height: rowHeight,\n depth: visible.depths[index] as number,\n task,\n hasChildren,\n expanded: hasChildren && !collapsed.has(id),\n dates: rowDates,\n cells: columns.values.map((value) => value(context)),\n bar: computeBar(task, rowDates, hasChildren, timeAxis),\n selected: selection.set.has(id),\n active: selection.active === id,\n };\n const previous = previousRows.get(id);\n const same =\n previous?.task === row.task &&\n previous.index === row.index &&\n previous.height === row.height &&\n previous.depth === row.depth &&\n previous.expanded === row.expanded &&\n previous.hasChildren === row.hasChildren &&\n previous.selected === row.selected &&\n previous.active === row.active &&\n sameDates(previous.dates, row.dates) &&\n sameCells(previous.cells, row.cells) &&\n sameBar(previous.bar, row.bar);\n const kept = same ? previous : row;\n rows.set(id, kept);\n items.push(kept);\n }\n\n previousRows = rows;\n const state: RowsState = { rowHeight, count, totalHeight: count * rowHeight, items };\n // At the list's edges the window can't grow, so treat it as open-ended there.\n windowCache = {\n key,\n first: first === 0 ? -1 : first,\n last: last === count ? Number.POSITIVE_INFINITY : last,\n state,\n };\n return state;\n };\n\n return {\n rowsFor: (input) => {\n const rows = rowsFor(input);\n const visible = (visibleCache as { rows: VisibleRows }).rows;\n return { rows, rowIndex: visible.index, rowIds: visible.ids };\n },\n };\n}\n","import { getTreeIndex } from '../data/tree';\nimport type { Dependency, DependencyType, Id, ProjectState, Task } from '../data/types';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { computeBar, type Bar } from './bars';\nimport { taskDates } from './dates';\nimport { rowKey, type RowsState } from './rows';\n\n/** A dependency drawn as an arrow between two bars, in timeline coordinates. */\nexport interface DependencyLine {\n /** Unique string key for rendering lists (ids 1 and \"1\" are different dependencies). */\n readonly key: string;\n readonly id: Id;\n readonly from: Id;\n readonly to: Id;\n readonly type: DependencyType;\n /** SVG path data, orthogonal, ending at the successor (put the arrowhead there with `marker-end`). */\n readonly path: string;\n}\n\n/** Horizontal distance a line runs straight out of a bar, and straight into one. */\nconst STUB = 8;\n/** Half the width of a milestone diamond, so lines end at its tips (matches the default `--qz-milestone-size`). */\nconst MILESTONE_RADIUS = 7;\n\nconst EMPTY: readonly DependencyLine[] = [];\n\nexport interface DependencyLinesInput {\n readonly project: ProjectState;\n readonly timeAxis: TimeAxis;\n readonly rows: RowsState;\n /** Row index of every visible task (collapsed-away tasks are missing). */\n readonly rowIndex: ReadonlyMap<Id, number>;\n}\n\n/**\n * Lines for the dependencies near the rendered rows: those with an end in them, or passing through them.\n * Dependencies to unscheduled or collapsed-away tasks aren't drawn. The array is reused while nothing it\n * depends on changes (e.g. while scrolling within the rendered rows).\n */\nexport function createDependencyView(): {\n linesFor: (input: DependencyLinesInput) => readonly DependencyLine[];\n} {\n let cache: { key: unknown[]; lines: readonly DependencyLine[] } | undefined;\n // Lines by key from the last call: unchanged ones keep their identity, so renderers can skip them.\n let previous = new Map<string, DependencyLine>();\n\n const linesFor = ({\n project,\n timeAxis,\n rows,\n rowIndex,\n }: DependencyLinesInput): readonly DependencyLine[] => {\n const key = [project.dependencies, project.tasks, timeAxis, rows.items, rowIndex];\n if (cache && key.every((part, i) => part === cache?.key[i])) return cache.lines;\n\n const first = rows.items[0]?.index;\n const last = rows.items.at(-1)?.index;\n let lines: readonly DependencyLine[] = EMPTY;\n if (first !== undefined && last !== undefined && project.dependencies.order.length > 0) {\n const tree = getTreeIndex(project.tasks);\n // Bars of rendered rows, and of other tasks computed once per call (a task can have many dependencies).\n const bars = new Map<Id, Bar | null>(rows.items.map((row) => [row.id, row.bar]));\n const barOf = (id: Id): Bar | null => {\n let bar = bars.get(id);\n if (bar === undefined) {\n const task = project.tasks.byId.get(id) as Task;\n bar = computeBar(task, taskDates(task), !tree.isLeaf(id), timeAxis);\n bars.set(id, bar);\n }\n return bar;\n };\n const result: DependencyLine[] = [];\n const kept = new Map<string, DependencyLine>();\n for (const id of project.dependencies.order) {\n const dependency = project.dependencies.byId.get(id) as Dependency;\n const fromRow = rowIndex.get(dependency.from);\n const toRow = rowIndex.get(dependency.to);\n if (fromRow === undefined || toRow === undefined) continue;\n if (Math.max(fromRow, toRow) < first || Math.min(fromRow, toRow) > last) continue;\n const fromBar = barOf(dependency.from);\n const toBar = barOf(dependency.to);\n if (!fromBar || !toBar) continue;\n const lineKey = rowKey(id);\n const path = route(dependency.type, fromBar, fromRow, toBar, toRow, rows.rowHeight);\n const old = previous.get(lineKey);\n const line =\n old?.path === path &&\n old.from === dependency.from &&\n old.to === dependency.to &&\n old.type === dependency.type\n ? old\n : { key: lineKey, id, from: dependency.from, to: dependency.to, type: dependency.type, path };\n kept.set(lineKey, line);\n result.push(line);\n }\n lines = result;\n previous = kept;\n }\n cache = { key, lines };\n return lines;\n };\n\n return { linesFor };\n}\n\nfunction edge(bar: Bar, side: 'start' | 'end'): number {\n if (bar.kind === 'milestone') return bar.x + (side === 'start' ? -MILESTONE_RADIUS : MILESTONE_RADIUS);\n return side === 'start' ? bar.x : bar.x + bar.width;\n}\n\nconst round = (value: number) => Math.round(value * 10) / 10;\n\n/**\n * An orthogonal path, like Bryntum's: straight out of the predecessor's side (its end for FS/FF, its start for\n * SS/SF), one vertical run, and straight into the successor's side (its start for FS/SS, its end for FF/SF).\n * When no single vertical run leaves room for both straight parts, the line goes around along the boundary of\n * the successor's row.\n */\nfunction route(\n type: DependencyType,\n from: Bar,\n fromRow: number,\n to: Bar,\n toRow: number,\n rowHeight: number,\n): string {\n const fromEnd = type === 'FS' || type === 'FF';\n const toStart = type === 'FS' || type === 'SS';\n const x1 = edge(from, fromEnd ? 'end' : 'start');\n const x2 = edge(to, toStart ? 'start' : 'end');\n const y1 = fromRow * rowHeight + rowHeight / 2;\n const y2 = toRow * rowHeight + rowHeight / 2;\n const out = fromEnd ? 1 : -1; // direction out of the predecessor\n const into = toStart ? 1 : -1; // direction into the successor\n\n // Where the vertical run can be: at least STUB out of the predecessor and STUB before the successor.\n const lower = Math.max(out === 1 ? x1 + STUB : -Infinity, into === 1 ? -Infinity : x2 + STUB);\n const upper = Math.min(out === 1 ? Infinity : x1 - STUB, into === 1 ? x2 - STUB : Infinity);\n const f = (...values: number[]) => values.map((value) => String(round(value)));\n if (lower <= upper) {\n const [a, b, c, d, e] = f(x1, y1, out === 1 ? lower : upper, y2, x2);\n return `M${a} ${b} H${c} V${d} H${e}`;\n }\n const boundary = toRow > fromRow ? y2 - rowHeight / 2 : y2 + rowHeight / 2;\n const [a, b, c, d, e, g, h] = f(x1, y1, x1 + out * STUB, boundary, x2 - into * STUB, y2, x2);\n return `M${a} ${b} H${c} V${d} H${e} V${g} H${h}`;\n}\n","import { workingMsPerUnit } from '../calendar/duration';\nimport { getWorkingCalendar } from '../calendar/project';\nimport { getDependencyIndex, wouldCreateCycle } from '../data/graph';\nimport type { Transaction } from '../data/transaction';\nimport { getTreeIndex } from '../data/tree';\nimport type { DependencyType, Id, ProjectState, Task } from '../data/types';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { QuartzioError } from '../util/errors';\nimport { addUnits } from '../util/zone';\nimport { computeBar, type Bar } from './bars';\nimport { formatDate, formatDateTime, formatEndDate } from './cells';\nimport { taskDates } from './dates';\nimport { rowKey, type RowsState } from './rows';\nimport type { Viewport } from './types';\n\n/** A point on the timeline body: x from the start of the axis, y from the top of the first row. */\nexport interface TimelinePoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * What a press would grab: a bar to move, its end to resize, its progress handle, an empty row of an\n * unscheduled task to draw a bar in, or a link handle at either end of a bar to draw a dependency from.\n */\nexport type HitArea = 'bar' | 'resize-end' | 'progress' | 'create' | 'link-start' | 'link-end';\n\n/** What's under a point (only what's enabled). */\nexport interface TimelineHit {\n readonly taskId: Id;\n readonly area: HitArea;\n}\n\n/** A change an interaction proposes, for `validateChange`. */\nexport type ProposedChange =\n | {\n readonly kind: 'move' | 'resize' | 'create';\n readonly task: Task;\n readonly start: number;\n readonly end: number;\n }\n | { readonly kind: 'progress'; readonly task: Task; readonly percentDone: number }\n | { readonly kind: 'link'; readonly from: Task; readonly to: Task; readonly type: DependencyType };\n\ninterface InteractionBase {\n /** Whether the drop would be applied: `validateChange` (and, for links, the rules) allow it. */\n readonly valid: boolean;\n /** Why it isn't valid, if there's a reason to show. */\n readonly message: string | null;\n /** Text for a tooltip: the new dates, the percentage, or the link. */\n readonly label: string;\n /**\n * Pixels per frame to scroll by, while the pointer is near or past an edge of the visible timeline. The\n * renderer scrolls and then sends the pointer position again.\n */\n readonly autoScroll: { readonly x: number; readonly y: number };\n}\n\n/** A bar being moved, resized, drawn (created) or having its progress dragged: where it would land. */\nexport interface BarInteraction extends InteractionBase {\n readonly kind: 'move' | 'resize' | 'create' | 'progress';\n readonly taskId: Id;\n /** Key of the task's row, to set the original bar apart. */\n readonly rowKey: string;\n /** The bar at its new place (snapped), in timeline coordinates, in the task's row. */\n readonly bar: Bar;\n readonly start: number;\n readonly end: number;\n /** 0–100; for progress. */\n readonly percent: number;\n}\n\n/** A dependency being drawn from a bar's end (or start) to the pointer. */\nexport interface LinkInteraction extends InteractionBase {\n readonly kind: 'link';\n readonly from: Id;\n /** The bar under the pointer, if any. */\n readonly to: Id | null;\n /** The type the drop would create (from the sides), when over a bar. */\n readonly type: DependencyType | null;\n /** SVG path data of the line, in timeline coordinates. */\n readonly path: string;\n /** Where the line ends (the pointer), e.g. to put a tooltip there. */\n readonly end: TimelinePoint;\n}\n\nexport type TaskInteraction = BarInteraction | LinkInteraction;\n\n/** Movement (px) below which a press and release is a click, not a drag. */\nexport const CLICK_TOLERANCE = 3;\n/** Hit targets are at least this wide, so short bars can still be grabbed. */\nconst MIN_HIT_WIDTH = 6;\n/** The resize handle at a bar's end; less on short bars, so their middle can still be moved. */\nconst RESIZE_HANDLE = 6;\n/** Link handles sit just outside a bar's ends. */\nconst LINK_HANDLE = 10;\n/** The progress handle: this far either side of the progress edge, low in the bar (fractions of the row). */\nconst PROGRESS_HANDLE = 5;\nconst PROGRESS_TOP = 0.6;\nconst PROGRESS_BOTTOM = 0.9;\n/** Half a milestone diamond (matches the default --qz-milestone-size; a changed size doesn't move the target). */\nconst MILESTONE_RADIUS = 7;\n/** Auto-scroll: within this distance of an edge, up to this many px per frame (more past the edge). */\nconst EDGE = 30;\nconst MAX_SPEED = 20;\n/** Dates must stay within what the data accepts (years 1000–9999). */\nconst MIN_TIME = Date.UTC(1000, 0, 1);\nconst MAX_TIME = Date.UTC(10_000, 0, 1) - 1;\nconst SUB_DAY = new Set(['millisecond', 'second', 'minute', 'hour']);\nconst NO_SCROLL = { x: 0, y: 0 };\n\n/** What the interaction needs from the view. */\nexport interface InteractionView {\n readonly project: ProjectState;\n readonly timeAxis: TimeAxis;\n readonly rows: RowsState;\n readonly viewport: Viewport;\n /** Row index of every visible task. */\n readonly rowIndex: ReadonlyMap<Id, number>;\n /** Task ids of the visible rows, by row index. */\n readonly rowIds: readonly Id[];\n readonly locale: string | undefined;\n readonly enabled: {\n readonly drag: boolean;\n readonly resize: boolean;\n readonly create: boolean;\n readonly progress: boolean;\n readonly link: boolean;\n };\n readonly validate: ((change: ProposedChange) => boolean | string) | undefined;\n}\n\nexport interface InteractionContext {\n readonly view: () => InteractionView;\n readonly show: (interaction: TaskInteraction | null) => void;\n readonly commit: (fn: (tx: Transaction) => void) => void;\n}\n\nexport interface Interaction {\n hitTest: (point: TimelinePoint) => TimelineHit | null;\n pointerDown: (point: TimelinePoint) => boolean;\n pointerMove: (point: TimelinePoint) => void;\n pointerUp: (point: TimelinePoint) => void;\n /** Drops the drag; returns whether there was one. */\n cancel: () => boolean;\n /**\n * For a new view, before it's shown: whether the drag still applies. A drag on a stale basis (another time\n * axis, a changed or hidden task, turned-off options) is dropped silently, so no outdated preview is shown.\n */\n keep: (next: InteractionView) => boolean;\n /**\n * After the chart scrolled: the pointer is now over another part of it, so the drag follows (with the fresh\n * viewport). Lets auto-scrolling work without the renderer sending the pointer again.\n */\n follow: () => void;\n}\n\n/** A drop to apply, decided by the latest preview. */\ntype Drop = (tx: Transaction) => void;\n\ninterface Pending {\n readonly hit: TimelineHit;\n readonly origin: TimelinePoint;\n readonly task: Task;\n /** The task's bar; `null` when drawing a new one. */\n readonly bar: Bar | null;\n readonly axis: TimeAxis;\n readonly row: number;\n started: boolean;\n preview: TaskInteraction | null;\n drop: Drop | null;\n /** The last pointer position, and the scroll position at that moment (to follow scrolling). */\n last: TimelinePoint | null;\n scroll: { left: number; top: number };\n}\n\nconst finite = (point: TimelinePoint) => Number.isFinite(point.x) && Number.isFinite(point.y);\nconst inRange = (time: number) => Number.isFinite(time) && time >= MIN_TIME && time <= MAX_TIME;\nconst round = (value: number) => Math.round(value * 10) / 10;\n\n/** Link type from the sides: out of the predecessor's end or start, into the successor's start or end. */\nfunction linkType(fromSide: 'start' | 'end', toSide: 'start' | 'end'): DependencyType {\n if (fromSide === 'end') return toSide === 'start' ? 'FS' : 'FF';\n return toSide === 'start' ? 'SS' : 'SF';\n}\n\n/** Speed towards an edge: 0 far from it, growing inside EDGE px, and more past it. */\nfunction speed(position: number, low: number, high: number): number {\n if (high - low <= 2 * EDGE) return 0; // too small to tell an edge from the middle\n const ease = (distance: number) =>\n Math.min(MAX_SPEED * 2, Math.ceil(((EDGE - distance) / EDGE) * MAX_SPEED));\n if (position > high - EDGE) return ease(high - position);\n if (position < low + EDGE) return -ease(position - low);\n return 0;\n}\n\nfunction barOf(view: Pick<InteractionView, 'project' | 'timeAxis' | 'rows'>, id: Id): Bar | null {\n const rendered = view.rows.items.find((row) => row.id === id);\n if (rendered) return rendered.bar;\n const task = view.project.tasks.byId.get(id);\n if (!task) return null;\n return computeBar(task, taskDates(task), !getTreeIndex(view.project.tasks).isLeaf(id), view.timeAxis);\n}\n\n/** The bar extent a point is tested against: milestones are their diamond; short bars get a minimum width. */\nconst extent = (bar: Bar) => {\n const left = bar.kind === 'milestone' ? bar.x - MILESTONE_RADIUS : bar.x;\n const width = bar.kind === 'milestone' ? 2 * MILESTONE_RADIUS : bar.width;\n const extra = Math.max(0, MIN_HIT_WIDTH - width) / 2;\n return { left, width, from: left - extra, to: left + width + extra };\n};\n\nconst rowAt = (view: Pick<InteractionView, 'rows' | 'rowIds'>, point: TimelinePoint) => {\n if (!finite(point) || point.y < 0) return null;\n const index = Math.floor(point.y / view.rows.rowHeight);\n const taskId = view.rowIds[index];\n return taskId === undefined ? null : { taskId, index };\n};\n\n/** The bar under a point (its whole extent, whatever is enabled), for the task tooltip. */\nexport function barUnder(\n view: Pick<InteractionView, 'project' | 'timeAxis' | 'rows' | 'rowIds'>,\n point: TimelinePoint,\n): { taskId: Id; index: number; bar: Bar } | null {\n const row = rowAt(view, point);\n if (!row) return null;\n const bar = barOf(view, row.taskId);\n if (!bar) return null;\n const { from, to } = extent(bar);\n return point.x >= from && point.x <= to ? { ...row, bar } : null;\n}\n\n/**\n * Dragging on the timeline, as a small state machine fed with pointer events in timeline coordinates: moving,\n * resizing, drawing bars, dragging progress and drawing dependencies. Snaps to the preset's time resolution; a\n * drop becomes one transaction.\n */\nexport function createInteraction(context: InteractionContext): Interaction {\n let pending: Pending | null = null;\n\n const hitTest = (point: TimelinePoint): TimelineHit | null => {\n const view = context.view();\n const { enabled } = view;\n const row = rowAt(view, point);\n if (!row) return null;\n const { taskId } = row;\n const bar = barOf(view, taskId);\n // Drawing gives a task its own dates, so not a parent (it spans its children).\n if (!bar) {\n return enabled.create && getTreeIndex(view.project.tasks).isLeaf(taskId)\n ? { taskId, area: 'create' }\n : null;\n }\n\n const { left, width, from, to } = extent(bar);\n const inRow = (point.y - row.index * view.rows.rowHeight) / view.rows.rowHeight;\n if (point.x >= from && point.x <= to) {\n const progressX = bar.x + bar.progress * bar.width;\n if (\n enabled.progress &&\n bar.kind === 'task' &&\n Math.abs(point.x - progressX) <= PROGRESS_HANDLE &&\n inRow >= PROGRESS_TOP &&\n inRow <= PROGRESS_BOTTOM\n ) {\n return { taskId, area: 'progress' };\n }\n const handle = Math.min(RESIZE_HANDLE, width / 3);\n if (enabled.resize && bar.kind === 'task' && point.x >= left + width - handle)\n return { taskId, area: 'resize-end' };\n return enabled.drag ? { taskId, area: 'bar' } : null;\n }\n if (enabled.link && point.x >= from - LINK_HANDLE && point.x < from)\n return { taskId, area: 'link-start' };\n if (enabled.link && point.x > to && point.x <= to + LINK_HANDLE) return { taskId, area: 'link-end' };\n return null;\n };\n\n /** Where a move to `start` lands: the end the drop will give, from the duration in working time. */\n const moved = (\n view: InteractionView,\n task: Task,\n bar: Bar,\n start: number,\n ): { start: number; end: number } => {\n if (bar.kind === 'milestone') return { start, end: start };\n try {\n const calendar = getWorkingCalendar(view.project);\n const ms =\n task.duration !== null && bar.kind === 'task'\n ? Math.round(task.duration * workingMsPerUnit(task.durationUnit, view.project.settings))\n : calendar.workingTimeBetween(bar.start, bar.end);\n // Automatic tasks start at working time (scheduling moves them there; predecessors may push further).\n const begin = task.manuallyScheduled || ms === 0 ? start : calendar.nextWorkingTime(start);\n return { start: begin, end: calendar.addWorkingTime(begin, ms) };\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n return { start, end: start + (bar.end - bar.start) }; // e.g. no working time: keep the span\n }\n };\n\n /** One step of the time resolution after `time`, snapped: the least a bar may span. */\n const stepAfter = (axis: TimeAxis, time: number, zone: ProjectState['settings']['timeZone']): number => {\n const snapped = axis.snap(time);\n if (snapped > time) return snapped;\n const { unit, increment } = axis.preset.timeResolution;\n return addUnits(snapped, increment, unit, zone);\n };\n\n /** Where an automatic task drawn over `first`–`last` lands: at working time, lasting the span's working time. */\n const landing = (view: InteractionView, first: number, last: number) => {\n try {\n const calendar = getWorkingCalendar(view.project);\n const ms = calendar.workingTimeBetween(first, last);\n if (ms === 0) return { start: first, end: last, empty: true };\n const start = calendar.nextWorkingTime(first);\n return { start, end: calendar.addWorkingTime(start, ms), empty: false };\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n return { start: first, end: last, empty: true };\n }\n };\n\n const dateLabel = (view: InteractionView, start: number, end: number, milestone: boolean): string => {\n const zone = view.project.settings.timeZone;\n const subDay = SUB_DAY.has(view.timeAxis.preset.timeResolution.unit);\n const format = (time: number) =>\n subDay ? formatDateTime(time, zone, view.locale) : formatDate(time, zone, view.locale);\n if (milestone) return format(start);\n return `${format(start)} – ${subDay ? format(end) : formatEndDate(start, end, zone, view.locale)}`;\n };\n\n const verdict = (\n view: InteractionView,\n change: ProposedChange,\n ): { valid: boolean; message: string | null } => {\n let result: boolean | string;\n try {\n result = view.validate?.(change) ?? true;\n } catch (error) {\n // A validator that throws refuses: pointer handlers (and what renders) must not throw.\n return { valid: false, message: error instanceof Error && error.message !== '' ? error.message : null };\n }\n if (result === true) return { valid: true, message: null };\n return { valid: false, message: typeof result === 'string' && result !== '' ? result : null };\n };\n\n // Bar gestures stay in their row, so only links (to other rows) scroll vertically.\n const autoScroll = (view: InteractionView, point: TimelinePoint, vertical: boolean) => {\n const { scrollLeft, scrollTop, width, height } = view.viewport;\n if (width <= 0 || height <= 0) return NO_SCROLL;\n // Only as far as there is to scroll: nothing towards an edge already reached.\n const limit = (value: number, position: number, max: number) =>\n (value < 0 && position <= 0) || (value > 0 && position >= max) ? 0 : value;\n const x = limit(\n speed(point.x, scrollLeft, scrollLeft + width),\n scrollLeft,\n view.timeAxis.totalWidth - width,\n );\n const y = vertical\n ? limit(speed(point.y, scrollTop, scrollTop + height), scrollTop, view.rows.totalHeight - height)\n : 0;\n return x === 0 && y === 0 ? NO_SCROLL : { x, y };\n };\n\n /** Preview and drop for moving, resizing, creating and progress. */\n const barPreview = (\n view: InteractionView,\n current: Pending,\n point: TimelinePoint,\n ): { interaction: BarInteraction; drop: Drop | null } | null => {\n const { timeAxis, project } = view;\n const { task, bar, hit } = current;\n const zone = project.settings.timeZone;\n const dx = point.x - current.origin.x;\n const scroll = autoScroll(view, point, false);\n const base = { taskId: task.id, rowKey: rowKey(task.id), autoScroll: scroll };\n\n if (hit.area === 'progress' && bar) {\n const percent = Math.round(Math.max(0, Math.min(1, (point.x - bar.x) / bar.width)) * 100);\n const change: ProposedChange = { kind: 'progress', task, percentDone: percent };\n const { valid, message } = verdict(view, change);\n const interaction: BarInteraction = {\n ...base,\n kind: 'progress',\n bar: { ...bar, progress: percent / 100 },\n start: bar.start,\n end: bar.end,\n percent,\n label: `${String(percent)}%`,\n valid,\n message,\n };\n const drop: Drop | null =\n valid && percent !== task.percentDone\n ? (tx) => {\n tx.tasks.update(task.id, { percentDone: percent });\n }\n : null;\n return { interaction, drop };\n }\n\n // From the dates, not the bar: a bar far outside the axis is clipped to near it.\n let kind: BarInteraction['kind'];\n let start: number;\n let end: number;\n let drop: Drop | null = null;\n if (hit.area === 'create') {\n const a = timeAxis.snap(timeAxis.xToDate(current.origin.x));\n const b = timeAxis.snap(timeAxis.xToDate(point.x));\n if (!inRange(a) || !inRange(b)) return null;\n kind = 'create';\n const first = Math.min(a, b);\n const last = Math.max(Math.max(a, b), stepAfter(timeAxis, first, zone));\n // An automatic task lands at working time, with the working time in the span as its duration.\n const landed = task.manuallyScheduled\n ? { start: first, end: last, empty: false }\n : landing(view, first, last);\n start = landed.start;\n end = landed.end;\n if (landed.empty) {\n const drawn = computeBar(task, { start: first, end: last }, false, timeAxis);\n if (!drawn) return null;\n const interaction: BarInteraction = {\n ...base,\n kind,\n bar: drawn,\n start: first,\n end: last,\n percent: task.percentDone,\n label: dateLabel(view, first, last, false),\n valid: false,\n message: 'No working time in the drawn span',\n };\n return { interaction, drop: null };\n }\n drop = (tx) => {\n if (task.manuallyScheduled) tx.tasks.update(task.id, { startDate: first, endDate: last });\n else {\n // Automatic: held at the drawn start (\"start no earlier than\"); the duration comes from the drawn span.\n tx.tasks.update(task.id, {\n startDate: first,\n endDate: last,\n constraintType: 'startnoearlierthan',\n constraintDate: first,\n });\n }\n };\n } else if (hit.area === 'bar' && bar) {\n const snapped = timeAxis.snap(timeAxis.xToDate(timeAxis.dateToX(bar.start) + dx));\n if (!inRange(snapped)) return null;\n kind = 'move';\n ({ start, end } = moved(view, task, bar, snapped));\n // Compared with where the bar snaps to without moving: an automatic task starting at 08:00 snaps to\n // midnight, which isn't a move.\n if (snapped !== timeAxis.snap(bar.start)) {\n drop = (tx) => {\n if (task.manuallyScheduled) tx.tasks.update(task.id, { startDate: snapped });\n else tx.tasks.update(task.id, { constraintType: 'startnoearlierthan', constraintDate: snapped });\n };\n }\n } else if (bar) {\n const snapped = timeAxis.snap(timeAxis.xToDate(timeAxis.dateToX(bar.end) + dx));\n if (!inRange(snapped)) return null;\n kind = 'resize';\n start = bar.start;\n end = Math.max(stepAfter(timeAxis, start, zone), snapped);\n if (end !== timeAxis.snap(bar.end)) {\n const newEnd = end;\n drop = (tx) => {\n tx.tasks.update(task.id, { endDate: newEnd });\n };\n }\n } else {\n return null;\n }\n if (!inRange(start) || !inRange(end)) return null;\n\n const isParent = bar?.kind === 'summary' || !getTreeIndex(project.tasks).isLeaf(task.id);\n const next = computeBar(task, { start, end }, isParent, timeAxis);\n if (!next) return null;\n const { valid, message } = verdict(view, { kind, task, start, end });\n const interaction: BarInteraction = {\n ...base,\n kind,\n bar: next,\n start,\n end,\n percent: task.percentDone,\n label: dateLabel(view, start, end, next.kind === 'milestone'),\n valid,\n message,\n };\n return { interaction, drop: valid ? drop : null };\n };\n\n /** Preview and drop for drawing a dependency. */\n const linkPreview = (\n view: InteractionView,\n current: Pending,\n point: TimelinePoint,\n ): { interaction: LinkInteraction; drop: Drop | null } | null => {\n const { task, bar, hit, row } = current;\n if (!bar) return null;\n const fromSide = hit.area === 'link-start' ? 'start' : 'end';\n const { from, to } = extent(bar);\n const x1 = fromSide === 'start' ? from : to;\n const y1 = row * view.rows.rowHeight + view.rows.rowHeight / 2;\n const base = {\n kind: 'link' as const,\n from: task.id,\n path: `M${String(round(x1))} ${String(round(y1))} L${String(round(point.x))} ${String(round(point.y))}`,\n end: { x: point.x, y: point.y },\n autoScroll: autoScroll(view, point, true),\n };\n const nothing = { ...base, to: null, type: null, label: '', valid: false, message: null };\n\n const target = rowAt(view, point);\n const targetBar = target && barOf(view, target.taskId);\n const targetTask = target && view.project.tasks.byId.get(target.taskId);\n if (!target || !targetBar || !targetTask) return { interaction: nothing, drop: null };\n const edges = extent(targetBar);\n if (point.x < edges.from - LINK_HANDLE || point.x > edges.to + LINK_HANDLE)\n return { interaction: nothing, drop: null };\n // Onto the end handle (or the last third of the bar): into its end; otherwise into its start.\n const toSide = point.x > edges.left + (edges.width * 2) / 3 ? 'end' : 'start';\n const type = linkType(fromSide, toSide);\n const label = `${task.name || String(task.id)} → ${targetTask.name || String(targetTask.id)} (${type})`;\n\n let rule: string | null = null;\n const tree = getTreeIndex(view.project.tasks);\n if (targetTask.id === task.id) rule = 'Can’t link a task to itself';\n else if (\n tree.ancestors(task.id).includes(targetTask.id) ||\n tree.ancestors(targetTask.id).includes(task.id)\n ) {\n rule = 'Can’t link a task to its parent or child';\n } else if (\n getDependencyIndex(view.project.dependencies)\n .outgoing(task.id)\n .some((d) => d.to === targetTask.id)\n ) {\n rule = 'Already linked';\n } else if (wouldCreateCycle(view.project, task.id, targetTask.id)) rule = 'Would create a cycle';\n const checked = rule === null ? verdict(view, { kind: 'link', from: task, to: targetTask, type }) : null;\n const valid = checked?.valid ?? false;\n const interaction: LinkInteraction = {\n ...base,\n to: targetTask.id,\n type,\n label,\n valid,\n message: rule ?? checked?.message ?? null,\n };\n const drop: Drop | null = valid\n ? (tx) => {\n tx.dependencies.add({ from: task.id, to: targetTask.id, type });\n }\n : null;\n return { interaction, drop };\n };\n\n const cancel = (): boolean => {\n if (!pending) return false;\n const shown = pending.preview !== null;\n pending = null;\n if (shown) context.show(null);\n return true;\n };\n\n const pointerMove = (point: TimelinePoint) => {\n if (!pending || !finite(point)) return;\n if (!pending.started) {\n if (Math.hypot(point.x - pending.origin.x, point.y - pending.origin.y) < CLICK_TOLERANCE) return;\n pending.started = true;\n }\n const view = context.view();\n pending.last = point;\n pending.scroll = { left: view.viewport.scrollLeft, top: view.viewport.scrollTop };\n const isLink = pending.hit.area === 'link-start' || pending.hit.area === 'link-end';\n const next = isLink ? linkPreview(view, pending, point) : barPreview(view, pending, point);\n if (!next) return;\n pending.drop = next.drop;\n if (!sameInteraction(pending.preview, next.interaction)) {\n pending.preview = next.interaction;\n context.show(next.interaction);\n }\n };\n\n return {\n hitTest,\n pointerMove,\n cancel,\n\n pointerDown(point) {\n cancel();\n const hit = hitTest(point);\n if (!hit) return false;\n const view = context.view();\n const task = view.project.tasks.byId.get(hit.taskId);\n const row = view.rowIndex.get(hit.taskId);\n if (!task || row === undefined) return false;\n const bar = barOf(view, hit.taskId);\n if (!bar && hit.area !== 'create') return false;\n pending = {\n hit,\n origin: point,\n task,\n bar,\n axis: view.timeAxis,\n row,\n started: false,\n preview: null,\n drop: null,\n last: null,\n scroll: { left: view.viewport.scrollLeft, top: view.viewport.scrollTop },\n };\n return true;\n },\n\n pointerUp(point) {\n const current = pending;\n if (!current) return;\n try {\n if (current.started) pointerMove(point);\n } finally {\n cancel(); // the drag ends with the release, whatever happens\n }\n if (current.started && current.drop) context.commit(current.drop);\n },\n\n follow() {\n if (!pending?.started || !pending.last) return;\n const { viewport } = context.view();\n const dx = viewport.scrollLeft - pending.scroll.left;\n const dy = viewport.scrollTop - pending.scroll.top;\n if (dx !== 0 || dy !== 0) pointerMove({ x: pending.last.x + dx, y: pending.last.y + dy });\n },\n\n keep(next) {\n if (!pending) return true;\n const { hit, task, axis, row } = pending;\n const { enabled } = next;\n const allowed = {\n bar: enabled.drag,\n 'resize-end': enabled.resize,\n progress: enabled.progress,\n create: enabled.create,\n 'link-start': enabled.link,\n 'link-end': enabled.link,\n }[hit.area];\n const stillValid =\n allowed &&\n next.timeAxis === axis &&\n next.project.tasks.byId.get(hit.taskId) === task &&\n next.rowIndex.get(hit.taskId) === row;\n if (!stillValid) pending = null;\n return stillValid;\n },\n };\n}\n\n/** Whether a new preview shows the same as the last (so nothing needs rendering). */\nfunction sameInteraction(a: TaskInteraction | null, b: TaskInteraction): boolean {\n if (a?.kind !== b.kind || a.valid !== b.valid || a.message !== b.message) return false;\n if (a.autoScroll.x !== b.autoScroll.x || a.autoScroll.y !== b.autoScroll.y) return false;\n if (a.kind === 'link' && b.kind === 'link') return a.path === b.path && a.to === b.to && a.type === b.type;\n if (a.kind !== 'link' && b.kind !== 'link')\n return a.start === b.start && a.end === b.end && a.percent === b.percent;\n return false;\n}\n","import type { ProjectState } from '../data/types';\nimport type { ViewPreset } from '../timeaxis/presets';\nimport { addUnits, startOfUnit } from '../util/zone';\n\n/** Ticks of empty space added on each side of the tasks. */\nconst PADDING_TICKS = 2;\n/** Shown when there are no dated tasks. */\nconst EMPTY_WEEKS = 4;\n\n/**\n * The time range to show when none is given: from the earliest to the latest task date, padded by a few\n * ticks. Without dated tasks, a few weeks from the start of the current week.\n */\nexport function defaultTimelineRange(\n state: ProjectState,\n preset: ViewPreset,\n now: number,\n): { start: number; end: number } {\n let min = Number.POSITIVE_INFINITY;\n let max = Number.NEGATIVE_INFINITY;\n for (const task of state.tasks.byId.values()) {\n for (const time of [task.startDate, task.endDate]) {\n if (time !== null) {\n if (time < min) min = time;\n if (time > max) max = time;\n }\n }\n }\n\n const { timeZone, weekStartsOn } = state.settings;\n if (min === Number.POSITIVE_INFINITY) {\n const start = startOfUnit(now, 'week', timeZone, weekStartsOn);\n return { start, end: addUnits(start, EMPTY_WEEKS, 'week', timeZone) };\n }\n const padding = PADDING_TICKS * preset.tickIncrement;\n return {\n start: addUnits(min, -padding, preset.tickUnit, timeZone),\n // A zero-length range (one milestone) still gets room after it.\n end: addUnits(max, padding, preset.tickUnit, timeZone),\n };\n}\n","import { toTime } from '../data/normalize';\nimport type { DateInput, ProjectState } from '../data/types';\nimport { assertLocale } from '../timeaxis/format';\nimport { resolvePreset, type ViewPreset } from '../timeaxis/presets';\nimport { createTimeAxis, type TimeAxis } from '../timeaxis/timeAxis';\nimport { isEqual } from '../util/equal';\nimport { QuartzioError } from '../util/errors';\nimport { defaultTimelineRange } from './range';\nimport type { HeaderState, Viewport } from './types';\n\n/** Assumed viewport width before it has been measured (and when rendering on the server). */\nexport const UNMEASURED_WIDTH = 1200;\n\nexport interface TimelineOptions {\n preset: ViewPreset;\n startDate: DateInput | undefined;\n endDate: DateInput | undefined;\n locale: string | undefined;\n}\n\ninterface TimelineOptionsInput {\n preset?: string | ViewPreset | undefined;\n startDate?: DateInput | null | undefined;\n endDate?: DateInput | null | undefined;\n locale?: string | undefined;\n}\n\n/** Validates the timeline options; throws QuartzioError before anything is changed. */\nexport function resolveTimeline(options: TimelineOptionsInput): TimelineOptions {\n const preset = resolvePreset(options.preset);\n if (options.locale !== undefined) assertLocale(options.locale);\n // `null` from plain JavaScript means \"not set\", like `undefined`.\n const startDate = options.startDate ?? undefined;\n const endDate = options.endDate ?? undefined;\n // The format doesn't depend on the zone, so check it now; the real value is read in the project's zone.\n const start = toTime(startDate, 'startDate', 'Gantt options', 'UTC');\n const end = toTime(endDate, 'endDate', 'Gantt options', 'UTC');\n if (start !== null && end !== null && end <= start) {\n throw new QuartzioError('Gantt options: \"endDate\" must be after \"startDate\".');\n }\n return { preset, startDate, endDate, locale: options.locale };\n}\n\nconst dateValue = (value: DateInput | undefined): unknown =>\n value instanceof Date ? value.getTime() : value;\n\n/** Equal by value, so re-rendering with a new but equal Date (or an equal custom preset) is no change. */\nexport const sameTimeline = (a: TimelineOptions, b: TimelineOptions): boolean =>\n (a.preset === b.preset || isEqual(a.preset, b.preset)) &&\n Object.is(dateValue(a.startDate), dateValue(b.startDate)) &&\n Object.is(dateValue(a.endDate), dateValue(b.endDate)) &&\n a.locale === b.locale;\n\n/** Parses an already validated date option, falling back when it isn't set. Never throws. */\nfunction parseOr(value: DateInput | undefined, zone: string, fallback: number): number {\n try {\n return toTime(value, 'date', 'Gantt options', zone) ?? fallback;\n } catch {\n return fallback;\n }\n}\n\nexport interface TimelineView {\n axisFor: (project: ProjectState, viewportWidth: number, timeline: TimelineOptions) => TimeAxis;\n headerFor: (axis: TimeAxis, viewport: Viewport, rowHeight: number) => HeaderState;\n}\n\n/**\n * Derives the time axis and the visible header cells. Each piece is reused while its inputs are unchanged,\n * and nothing here throws: options are validated up front, and oversized ranges are cut short.\n */\nexport function createTimelineView(): TimelineView {\n let rangeCache: { key: unknown[]; range: { start: number; end: number } } | undefined;\n const timelineRange = (\n project: ProjectState,\n timeline: TimelineOptions,\n ): { start: number; end: number } => {\n const key = [project.tasks, project.settings, timeline];\n if (!rangeCache || key.some((part, i) => part !== rangeCache?.key[i])) {\n const zone = project.settings.timeZone;\n const fallback = defaultTimelineRange(project, timeline.preset, Date.now());\n const start = parseOr(timeline.startDate, zone, fallback.start);\n const end = parseOr(timeline.endDate, zone, fallback.end);\n rangeCache = { key, range: { start, end: Math.max(start, end) } };\n }\n return rangeCache.range;\n };\n\n let axisCache: { key: unknown[]; axis: TimeAxis } | undefined;\n const axisFor = (project: ProjectState, viewportWidth: number, timeline: TimelineOptions): TimeAxis => {\n const { start, end } = timelineRange(project, timeline);\n const { timeZone, weekStartsOn } = project.settings;\n const { preset, locale } = timeline;\n const minWidth = viewportWidth > 0 ? viewportWidth : UNMEASURED_WIDTH;\n // Keyed on the tick count needed to fill the viewport, so resizing by a few pixels reuses the axis.\n const key = [start, end, preset, locale, timeZone, weekStartsOn, Math.ceil(minWidth / preset.tickWidth)];\n if (axisCache && key.every((part, i) => part === axisCache?.key[i])) return axisCache.axis;\n\n const axis = createTimeAxis({\n start,\n end,\n preset,\n timeZone,\n weekStartsOn,\n locale,\n minWidth,\n truncate: true,\n });\n // Different inputs can still produce the same axis (e.g. the last task moved by an hour). Keeping the\n // old object lets everything memoized on it stay valid.\n const previous = axisCache?.axis;\n const same =\n previous?.start === axis.start &&\n previous.end === axis.end &&\n previous.tickCount === axis.tickCount &&\n previous.preset === axis.preset &&\n previous.locale === axis.locale &&\n previous.timeZone === axis.timeZone &&\n previous.weekStartsOn === axis.weekStartsOn;\n axisCache = { key, axis: same ? previous : axis };\n return axisCache.axis;\n };\n\n let headerCache:\n { axis: TimeAxis; rowHeight: number; from: number; to: number; header: HeaderState } | undefined;\n const headerFor = (axis: TimeAxis, viewport: Viewport, rowHeight: number): HeaderState => {\n const width = viewport.width > 0 ? viewport.width : UNMEASURED_WIDTH;\n const visibleFrom = viewport.scrollLeft;\n const visibleTo = viewport.scrollLeft + width;\n if (\n headerCache?.axis === axis &&\n headerCache.rowHeight === rowHeight &&\n headerCache.from <= visibleFrom &&\n visibleTo <= headerCache.to\n ) {\n return headerCache.header;\n }\n // Render one extra viewport on each side, so most scrolling reuses the same cells.\n const from = Math.max(0, visibleFrom - width);\n const to = Math.min(axis.totalWidth, visibleTo + width);\n const rows = axis.preset.headers.map((_, row) => axis.headerCells(row, from, to));\n const header: HeaderState = { rows, rowHeight, height: rows.length * rowHeight };\n // At the timeline's edges the window can't grow, so treat it as open-ended there.\n headerCache = {\n axis,\n rowHeight,\n from: from === 0 ? Number.NEGATIVE_INFINITY : from,\n to: to === axis.totalWidth ? Number.POSITIVE_INFINITY : to,\n header,\n };\n return header;\n };\n\n return { axisFor, headerFor };\n}\n","import { getWorkingCalendar } from '../calendar/project';\nimport type { WorkingCalendar } from '../calendar/workingCalendar';\nimport type { ProjectState } from '../data/types';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { QuartzioError } from '../util/errors';\nimport { addUnits, startOfUnit } from '../util/zone';\nimport { UNMEASURED_WIDTH } from './timeline';\nimport type { Viewport } from './types';\n\n/** A time range drawn on the timeline, in timeline coordinates. */\nexport interface TimeSpan {\n /** Stable key for rendering lists. */\n readonly key: string;\n readonly start: number;\n readonly end: number;\n readonly x: number;\n readonly width: number;\n}\n\nconst EMPTY: readonly TimeSpan[] = [];\nconst SUB_DAY_TICKS = new Set(['millisecond', 'second', 'minute', 'hour']);\n\n/**\n * Non-working time to shade, around the visible part of the timeline. What is shown depends on the tick size,\n * so the shading stays readable: with ticks under a day, every non-working interval (nights, weekends); with\n * day ticks, only whole days without working time (weekends, holidays) — shading nights would cover most of\n * every day; with longer ticks, nothing.\n */\nexport function createNonWorkingView(): {\n spansFor: (\n project: ProjectState,\n axis: TimeAxis,\n viewport: Viewport,\n enabled: boolean,\n ) => readonly TimeSpan[];\n} {\n let cache: { key: unknown[]; from: number; to: number; spans: readonly TimeSpan[] } | undefined;\n\n const compute = (calendar: WorkingCalendar, axis: TimeAxis, from: number, to: number): TimeSpan[] => {\n const zone = axis.timeZone;\n const ranges: [number, number][] = [];\n const push = (start: number, end: number) => {\n const last = ranges[ranges.length - 1];\n if (last && last[1] >= start) last[1] = Math.max(last[1], end);\n else if (end > start) ranges.push([start, end]);\n };\n\n if (SUB_DAY_TICKS.has(axis.preset.tickUnit)) {\n let cursor = from;\n for (const [start, end] of calendar.workingIntervals(from, to)) {\n push(cursor, start);\n cursor = end;\n }\n push(cursor, to);\n } else {\n for (let day = startOfUnit(from, 'day', zone); day < to;) {\n // Re-align: after a day that starts late (a DST gap at midnight), adding a day keeps the late start.\n const next = startOfUnit(addUnits(day, 1, 'day', zone), 'day', zone);\n if (calendar.workingIntervals(day, next).length === 0) push(day, next);\n day = next;\n }\n }\n\n return ranges.map(([start, end]) => {\n const x = axis.dateToX(start);\n return { key: String(start), start, end, x, width: axis.dateToX(end) - x };\n });\n };\n\n const spansFor = (project: ProjectState, axis: TimeAxis, viewport: Viewport, enabled: boolean) => {\n const tickUnit = axis.preset.tickUnit;\n if (!enabled || (tickUnit !== 'day' && !SUB_DAY_TICKS.has(tickUnit))) return EMPTY;\n\n const width = viewport.width > 0 ? viewport.width : UNMEASURED_WIDTH;\n const visibleFrom = viewport.scrollLeft;\n const visibleTo = viewport.scrollLeft + width;\n const key = [axis, project.calendars, project.settings];\n if (\n cache &&\n key.every((part, i) => part === cache?.key[i]) &&\n cache.from <= visibleFrom &&\n visibleTo <= cache.to\n ) {\n return cache.spans;\n }\n\n // One extra viewport on each side, like the header.\n const fromX = Math.max(0, visibleFrom - width);\n const toX = Math.min(axis.totalWidth, visibleTo + width);\n let spans: readonly TimeSpan[];\n try {\n const calendar = getWorkingCalendar(project);\n spans = compute(\n calendar,\n axis,\n Math.max(axis.start, axis.xToDate(fromX)),\n Math.min(axis.end, axis.xToDate(toX)),\n );\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n spans = EMPTY; // e.g. a range beyond what the calendar will calculate; shading is decoration\n }\n cache = {\n key,\n from: fromX === 0 ? Number.NEGATIVE_INFINITY : fromX,\n to: toX === axis.totalWidth ? Number.POSITIVE_INFINITY : toX,\n spans,\n };\n return spans;\n };\n\n return { spansFor };\n}\n","import { getWorkingCalendar } from '../calendar/project';\nimport type { WorkingCalendar } from '../calendar/workingCalendar';\nimport { getTreeIndex } from '../data/tree';\nimport type { Id, ProjectState, Task } from '../data/types';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { builtInText, type CellContext } from './columns';\nimport { taskDates } from './dates';\nimport { barUnder, type TimelinePoint } from './interaction';\nimport { rowKey, type RowsState } from './rows';\nimport type { Viewport } from './types';\n\n/** The tooltip for the task under the pointer: what to show, and where. */\nexport interface TaskTooltip {\n readonly taskId: Id;\n /** Key of the task's row. */\n readonly rowKey: string;\n readonly task: Task;\n readonly title: string;\n /** Formatted values, in order. */\n readonly fields: readonly { readonly label: string; readonly value: string }[];\n /**\n * Where it points to, in timeline coordinates: the start of the visible part of the bar (`align: 'start'`) or\n * its end (`'end'`, the tooltip's right edge there).\n */\n readonly x: number;\n readonly align: 'start' | 'end';\n /** The room (px) from `x` to the edge of the visible timeline it runs towards; `null` before measuring. */\n readonly room: number | null;\n /**\n * The top of the row (the tooltip above it), or its bottom when `below`: when there's no room above it in the\n * visible rows (the header would cover it) and more below.\n */\n readonly y: number;\n readonly below: boolean;\n}\n\nexport interface TooltipView {\n readonly project: ProjectState;\n readonly timeAxis: TimeAxis;\n readonly rows: RowsState;\n readonly rowIds: readonly Id[];\n readonly viewport: Viewport;\n readonly locale: string | undefined;\n}\n\n/**\n * About how tall the default tooltip can get (a title and four lines, wrapped when there's little room), to\n * decide whether it fits above a row. Below a row, there's room for it.\n */\nconst TOOLTIP_HEIGHT = 160;\n\n/** The tooltip for a point, or `null`. Returns `previous` when it would show the same. Never throws. */\nexport function tooltipFor(\n view: TooltipView,\n point: TimelinePoint,\n previous: TaskTooltip | null,\n): TaskTooltip | null {\n const hit = barUnder(view, point);\n if (!hit) return null;\n const { bar, index, taskId } = hit;\n const task = view.project.tasks.byId.get(taskId);\n const dates = task ? taskDates(task) : null;\n if (!task || !dates) return null;\n\n const { scrollLeft, width } = view.viewport;\n const right = bar.x + bar.width; // a milestone's width is 0: its center\n const visibleStart = Math.max(bar.x, scrollLeft);\n const visibleEnd = width > 0 ? Math.min(right, scrollLeft + width) : right;\n // Towards the side with more room, so it runs past the edge as little as possible (and is kept within it).\n const roomAfter = scrollLeft + width - visibleStart;\n const roomBefore = visibleEnd - scrollLeft;\n const align = width > 0 && roomBefore > roomAfter ? 'end' : 'start';\n const room = width > 0 ? Math.max(0, Math.round(align === 'end' ? roomBefore : roomAfter)) : null;\n const rowHeight = view.rows.rowHeight;\n const roomAbove = index * rowHeight - view.viewport.scrollTop;\n const roomBelow =\n view.viewport.height > 0\n ? view.viewport.scrollTop + view.viewport.height - (index + 1) * rowHeight\n : Number.POSITIVE_INFINITY;\n const below = roomAbove < TOOLTIP_HEIGHT && roomBelow > roomAbove;\n const x = align === 'end' ? visibleEnd : visibleStart;\n const y = below ? (index + 1) * rowHeight : index * rowHeight;\n const same =\n previous?.task === task &&\n previous.x === x &&\n previous.y === y &&\n previous.align === align &&\n previous.room === room;\n if (same) return previous;\n\n const cell: CellContext = {\n task,\n isParent: !getTreeIndex(view.project.tasks).isLeaf(taskId),\n dates,\n settings: view.project.settings,\n locale: view.locale,\n calendar: calendarOf(view.project),\n };\n const fields: TaskTooltip['fields'] =\n bar.kind === 'milestone'\n ? [{ label: 'Date', value: builtInText('startDate', cell) }]\n : [\n { label: 'Start', value: builtInText('startDate', cell) },\n { label: 'End', value: builtInText('endDate', cell) },\n { label: 'Duration', value: builtInText('duration', cell) },\n { label: 'Done', value: builtInText('percentDone', cell) },\n ];\n return { taskId, rowKey: rowKey(taskId), task, title: task.name, fields, x, align, room, y, below };\n}\n\nfunction calendarOf(project: ProjectState): WorkingCalendar | undefined {\n try {\n return getWorkingCalendar(project);\n } catch {\n return undefined;\n }\n}\n","import { workingMsPerUnit } from '../calendar/duration';\nimport type { Transaction } from '../data/transaction';\nimport type { Id, ProjectSettings, Task } from '../data/types';\nimport type { TimeUnit } from '../util/time';\nimport { daysInMonth } from '../util/civil';\nimport { fromWallTime, startOfUnit, toWallTime, type TimeZone } from '../util/zone';\nimport type { BuiltInColumnId } from './columns';\nimport type { TaskDates } from './dates';\nimport type { ProposedChange } from './interaction';\n\n/** The kind of field a cell is edited in. */\nexport type EditKind = 'text' | 'duration' | 'percent' | 'date' | 'datetime';\n\n/** The cell being edited. */\nexport interface CellEdit {\n readonly taskId: Id;\n /** Key of the task's row. */\n readonly rowKey: string;\n readonly columnId: string;\n readonly kind: EditKind;\n /** What's in the field now. */\n readonly text: string;\n /** Why the last attempt to save was refused, until the text changes. */\n readonly error: string | null;\n}\n\n/** Dates must stay within what the data accepts. */\nconst MIN_YEAR = 1000;\nconst MAX_YEAR = 9999;\nconst SUB_DAY = new Set<TimeUnit>(['millisecond', 'second', 'minute', 'hour']);\n/**\n * Longer durations and spans are refused: most likely a typo (a year off by decades), and the scheduler can't\n * place tasks that long (it would keep the old dates).\n */\nexport const MAX_WORKING_DAYS = 5000;\nconst MAX_SPAN_YEARS = 20;\nconst MAX_SPAN = MAX_SPAN_YEARS * 365.25 * 24 * 60 * 60 * 1000;\n\n/** Dates are edited with a time when the time axis resolves to less than a day. */\nexport const dateKind = (resolution: TimeUnit): 'date' | 'datetime' =>\n SUB_DAY.has(resolution) ? 'datetime' : 'date';\n\n/** The field a cell is edited in, or `null` when it can't be edited. */\nexport function editKind(\n field: BuiltInColumnId | null,\n task: Task,\n isParent: boolean,\n dates: TaskDates | null,\n dateField: 'date' | 'datetime',\n): EditKind | null {\n if (field === null) return null;\n if (field === 'name') return 'text';\n // A parent's dates, duration and progress roll up from its children.\n if (isParent) return null;\n switch (field) {\n case 'startDate':\n return dateField;\n case 'endDate':\n // A milestone has one date; an unscheduled task has no start to end after.\n return dates && dates.end > dates.start ? dateField : null;\n case 'duration':\n return 'duration';\n case 'percentDone':\n return 'percent';\n }\n}\n\nconst pad = (value: number, length = 2) => String(value).padStart(length, '0');\n\n/** A time as an `<input type=\"date\">` or `datetime-local` value, in the project's time zone. */\nexport function inputValue(time: number, kind: 'date' | 'datetime', zone: TimeZone): string {\n const wall = toWallTime(time, zone);\n const date = `${pad(wall.year, 4)}-${pad(wall.month)}-${pad(wall.day)}`;\n return kind === 'date' ? date : `${date}T${pad(wall.hour)}:${pad(wall.minute)}`;\n}\n\n// Units as MS Project writes them; `m` is minutes, `mo` months.\nconst UNIT_ABBREVIATIONS: Record<TimeUnit, string> = {\n millisecond: 'ms',\n second: 's',\n minute: 'm',\n hour: 'h',\n day: 'd',\n week: 'w',\n month: 'mo',\n quarter: 'q',\n year: 'y',\n};\nconst UNIT_NAMES: Record<string, TimeUnit> = {\n ms: 'millisecond',\n millisecond: 'millisecond',\n milliseconds: 'millisecond',\n s: 'second',\n sec: 'second',\n secs: 'second',\n second: 'second',\n seconds: 'second',\n m: 'minute',\n min: 'minute',\n mins: 'minute',\n minute: 'minute',\n minutes: 'minute',\n h: 'hour',\n hr: 'hour',\n hrs: 'hour',\n hour: 'hour',\n hours: 'hour',\n d: 'day',\n day: 'day',\n days: 'day',\n w: 'week',\n wk: 'week',\n wks: 'week',\n week: 'week',\n weeks: 'week',\n mo: 'month',\n mon: 'month',\n month: 'month',\n months: 'month',\n q: 'quarter',\n quarter: 'quarter',\n quarters: 'quarter',\n y: 'year',\n yr: 'year',\n yrs: 'year',\n year: 'year',\n years: 'year',\n};\n\n/** What the field shows when editing starts. */\nexport function initialText(\n field: BuiltInColumnId,\n kind: EditKind,\n task: Task,\n dates: TaskDates | null,\n zone: TimeZone,\n): string {\n switch (field) {\n case 'name':\n return task.name;\n case 'startDate':\n return dates && kind !== 'text'\n ? inputValue(dates.start, kind === 'date' ? 'date' : 'datetime', zone)\n : '';\n case 'endDate': {\n if (!dates) return '';\n if (kind === 'datetime') return inputValue(dates.end, 'datetime', zone);\n // As in the column: an end at midnight is the end of the day before.\n return inputValue(atMidnight(dates, zone) ? dates.end - 1 : dates.end, 'date', zone);\n }\n case 'duration':\n return task.duration === null ? '' : durationText(task.duration, task.durationUnit);\n case 'percentDone':\n return String(task.percentDone);\n }\n}\n\n/** A duration as the field shows it, e.g. `4d` or `-1.5h`. */\nexport const durationText = (value: number, unit: TimeUnit): string =>\n `${String(Math.round(value * 100) / 100)}${UNIT_ABBREVIATIONS[unit]}`;\n\nconst atMidnight = (dates: TaskDates, zone: TimeZone) =>\n dates.end > dates.start && startOfUnit(dates.end, 'day', zone) === dates.end;\n\n/** What an edit changes, and the change to propose to `validateChange` once it's planned. */\nexport interface ParsedEdit {\n readonly change: (tx: Transaction) => void;\n /**\n * The change for `validateChange`: the task as it is (as a drag gives it), with where the plan puts it\n * (`dates`, after the change). `null` for nothing to validate.\n */\n readonly propose: (task: Task, dates: TaskDates | null) => ProposedChange | null;\n}\n\n/** Reads the field's text into a change, or says why it can't. Never throws. */\nexport function parseEdit(\n field: BuiltInColumnId,\n kind: EditKind,\n text: string,\n task: Task,\n dates: TaskDates | null,\n settings: ProjectSettings,\n): ParsedEdit | { readonly error: string } {\n const id = task.id;\n const zone = settings.timeZone;\n switch (field) {\n case 'name':\n return {\n change: (tx) => {\n tx.tasks.update(id, { name: text });\n },\n propose: () => null,\n };\n case 'startDate': {\n const wall = parseInputDate(text, kind);\n if (typeof wall === 'string') return { error: wall };\n // A date alone keeps a manual task's time of day (an automatic one starts on the day's first working time).\n const old = dates && kind === 'date' && task.manuallyScheduled ? toWallTime(dates.start, zone) : null;\n const start = fromWallTime(old ? { ...wall, hour: old.hour, minute: old.minute } : wall, zone);\n // Without a duration, a start alone would make it a milestone.\n const duration = task.duration === null ? { duration: 1 } : {};\n return {\n change: (tx) => {\n if (task.manuallyScheduled) tx.tasks.update(id, { startDate: start, ...duration });\n else\n tx.tasks.update(id, { constraintType: 'startnoearlierthan', constraintDate: start, ...duration });\n },\n propose: (before, next) =>\n next ? { kind: 'move', task: before, start: next.start, end: next.end } : null,\n };\n }\n case 'endDate': {\n if (!dates) return { error: 'Set a start date first.' };\n const wall = parseInputDate(text, kind);\n if (typeof wall === 'string') return { error: wall };\n let end: number;\n if (kind === 'datetime') {\n end = fromWallTime(wall, zone);\n } else if (atMidnight(dates, zone)) {\n // The whole day: up to the next midnight.\n end = fromWallTime({ ...wall, day: wall.day + 1 }, zone);\n } else {\n const old = toWallTime(dates.end, zone);\n end = fromWallTime({ ...wall, hour: old.hour, minute: old.minute }, zone);\n }\n if (end <= dates.start) return { error: 'The end must be after the start.' };\n if (end - dates.start > MAX_SPAN) {\n return { error: `A task can span at most ${String(MAX_SPAN_YEARS)} years.` };\n }\n return {\n change: (tx) => {\n tx.tasks.update(id, { endDate: end });\n },\n propose: (before, next) =>\n next ? { kind: 'resize', task: before, start: next.start, end: next.end } : null,\n };\n }\n case 'duration': {\n const parsed = parseDuration(text, task.durationUnit);\n if (typeof parsed === 'string') return { error: parsed };\n const days =\n (parsed.value * workingMsPerUnit(parsed.unit, settings)) / workingMsPerUnit('day', settings);\n if (!(days <= MAX_WORKING_DAYS)) {\n return { error: `Enter a duration of at most ${String(MAX_WORKING_DAYS)} working days.` };\n }\n return {\n change: (tx) => {\n tx.tasks.update(id, { duration: parsed.value, durationUnit: parsed.unit });\n },\n propose: (before, next) =>\n next ? { kind: 'resize', task: before, start: next.start, end: next.end } : null,\n };\n }\n case 'percentDone': {\n const match = /^\\s*(\\d+(?:[.,]\\d+)?)\\s*%?\\s*$/.exec(text);\n const value = match ? Number((match[1] as string).replace(',', '.')) : Number.NaN;\n if (!(value >= 0 && value <= 100)) return { error: 'Enter a percentage from 0 to 100.' };\n return {\n change: (tx) => {\n tx.tasks.update(id, { percentDone: value });\n },\n propose: (before) => ({ kind: 'progress', task: before, percentDone: value }),\n };\n }\n }\n}\n\n/** A duration like `4d`, `2 weeks` or `1,5` (in the task's unit). */\nexport function parseDuration(text: string, fallback: TimeUnit): { value: number; unit: TimeUnit } | string {\n const match = /^\\s*(\\d+(?:[.,]\\d+)?)\\s*([a-z]*)\\s*$/i.exec(text);\n const message = 'Enter a duration, like 4d, 2w or 3h.';\n if (!match) return message;\n const value = Number((match[1] as string).replace(',', '.'));\n const name = (match[2] as string).toLowerCase();\n const unit = name === '' ? fallback : UNIT_NAMES[name];\n if (unit === undefined || !Number.isFinite(value)) return message;\n return { value, unit };\n}\n\n/** The wall-clock date (and time) of an `<input type=\"date\">` or `datetime-local` value. */\nexport function parseInputDate(\n text: string,\n kind: EditKind,\n): { year: number; month: number; day: number; hour: number; minute: number } | string {\n const match =\n kind === 'datetime'\n ? /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::\\d{2}(?:\\.\\d+)?)?$/.exec(text.trim())\n : /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text.trim());\n if (!match) return kind === 'datetime' ? 'Enter a date and time.' : 'Enter a date.';\n const [year, month, day, hour = 0, minute = 0] = match.slice(1).map(Number) as [\n number,\n number,\n number,\n number?,\n number?,\n ];\n if (year < MIN_YEAR || year > MAX_YEAR)\n return `Enter a year from ${String(MIN_YEAR)} to ${String(MAX_YEAR)}.`;\n if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month) || hour > 23 || minute > 59) {\n return 'That date does not exist.';\n }\n return { year, month, day, hour, minute };\n}\n","import type { PlannedChange } from '../data/project';\nimport type { Transaction } from '../data/transaction';\nimport type { TreeIndex } from '../data/tree';\nimport type { Id, ProjectState } from '../data/types';\nimport { QuartzioError } from '../util/errors';\nimport type { ResolvedColumns } from './columns';\nimport { taskDates } from './dates';\nimport { editKind, initialText, parseEdit, type CellEdit, type EditKind } from './editing';\nimport type { ProposedChange } from './interaction';\nimport type { KeyInput } from './keyboard';\nimport { rowKey } from './rows';\n\n/** What the editor needs from the view. */\nexport interface EditorView {\n readonly project: ProjectState;\n readonly tree: TreeIndex;\n readonly rowIds: readonly Id[];\n readonly rowIndex: ReadonlyMap<Id, number>;\n readonly columns: ResolvedColumns;\n readonly dateField: 'date' | 'datetime';\n}\n\nexport interface EditorContext {\n readonly view: () => EditorView;\n readonly enabled: () => boolean;\n /** Plans a change without applying it (to validate what it would do); throws QuartzioError if refused. */\n readonly plan: (fn: (tx: Transaction) => void) => PlannedChange | null;\n /** Applies (or, controlled, reports) the change; throws QuartzioError if refused. */\n readonly commit: (fn: (tx: Transaction) => void) => void;\n readonly validate: (change: ProposedChange) => boolean | string;\n /** The edit changed: show it. */\n readonly show: () => void;\n /** Editing starts on a row: move the cursor there. */\n readonly focusRow: (id: Id) => void;\n}\n\nexport interface CellEditor {\n /** The open edit as the view shows it; drops an edit on a stale basis. The same object while unchanged. */\n readonly current: (view: EditorView) => CellEdit | null;\n readonly start: (id: Id, columnId?: string) => boolean;\n readonly input: (text: string) => void;\n readonly keyDown: (key: KeyInput) => boolean;\n readonly commit: () => boolean;\n readonly cancel: () => void;\n}\n\ninterface Open {\n readonly taskId: Id;\n readonly columnId: string;\n readonly kind: EditKind;\n readonly text: string;\n /** The value's text: while `text` is still this, nothing was typed (and the field follows the value). */\n readonly initial: string;\n readonly error: string | null;\n}\n\n/** A cell of the task list, if it can be edited: the field it edits and how. */\nfunction cellOf(view: EditorView, id: Id, columnIndex: number) {\n const task = view.project.tasks.byId.get(id);\n const column = view.columns.state.items[columnIndex];\n const field = view.columns.fields[columnIndex] ?? null;\n if (!task || !column || field === null || !view.rowIndex.has(id)) return null;\n const dates = taskDates(task);\n const kind = editKind(field, task, !view.tree.isLeaf(id), dates, view.dateField);\n return kind ? { task, column, field, dates, kind } : null;\n}\n\nconst columnIndexOf = (view: EditorView, columnId: string) =>\n view.columns.state.items.findIndex((column) => column.id === columnId);\n\n/** Editing cells in the task list. */\nexport function createCellEditor(context: EditorContext): CellEditor {\n let open: Open | null = null;\n let shown: CellEdit | null = null;\n\n const current = (view: EditorView): CellEdit | null => {\n const cell =\n open && context.enabled() ? cellOf(view, open.taskId, columnIndexOf(view, open.columnId)) : null;\n // Stale: the cell can't be edited now, or needs another kind of field (its text would not fit it).\n if (!open || cell?.kind !== open.kind) {\n open = null;\n shown = null;\n return null;\n }\n if (open.text === open.initial) {\n // Nothing typed: show the value as it is now (changed elsewhere, or the app accepted an earlier edit).\n const value = initialText(cell.field, cell.kind, cell.task, cell.dates, view.project.settings.timeZone);\n if (value !== open.initial) open = { ...open, text: value, initial: value };\n }\n const { taskId, columnId, kind, text, error } = open;\n if (\n shown?.taskId !== taskId ||\n shown.columnId !== columnId ||\n shown.kind !== kind ||\n shown.text !== text ||\n shown.error !== error\n ) {\n shown = { taskId, rowKey: rowKey(taskId), columnId, kind, text, error };\n }\n return shown;\n };\n\n const start = (id: Id, columnId?: string): boolean => {\n const wasOpen = open !== null;\n open = null;\n const view = context.view();\n let cell = null;\n if (context.enabled()) {\n if (columnId === undefined) {\n for (let index = 0; index < view.columns.state.items.length && !cell; index++)\n cell = cellOf(view, id, index);\n } else if (typeof columnId === 'string') {\n cell = cellOf(view, id, columnIndexOf(view, columnId));\n }\n }\n if (!cell) {\n if (wasOpen) context.show();\n return false;\n }\n const text = initialText(cell.field, cell.kind, cell.task, cell.dates, view.project.settings.timeZone);\n open = { taskId: id, columnId: cell.column.id, kind: cell.kind, text, initial: text, error: null };\n context.focusRow(id);\n context.show();\n return true;\n };\n\n const refuse = (error: string): false => {\n if (open) open = { ...open, error };\n context.show();\n return false;\n };\n\n const commit = (): boolean => {\n if (!open) return false;\n const view = context.view();\n const cell = cellOf(view, open.taskId, columnIndexOf(view, open.columnId));\n if (!cell) {\n open = null;\n context.show();\n return false;\n }\n const { text } = open;\n const close = (): true => {\n open = null;\n context.show();\n return true;\n };\n if (text === open.initial) return close();\n const parsed = parseEdit(cell.field, cell.kind, text, cell.task, cell.dates, view.project.settings);\n if ('error' in parsed) return refuse(parsed.error);\n try {\n const planned = context.plan(parsed.change);\n if (!planned) return close();\n const after = planned.state.tasks.byId.get(cell.task.id);\n const proposed = after ? parsed.propose(cell.task, taskDates(after)) : null;\n if (proposed) {\n let verdict: boolean | string;\n try {\n verdict = context.validate(proposed);\n } catch (error) {\n // A validator that throws is a no, with its message.\n verdict = error instanceof Error ? error.message : 'Not allowed.';\n }\n if (verdict !== true) return refuse(typeof verdict === 'string' ? verdict : 'Not allowed.');\n }\n const edited = open;\n open = null;\n try {\n context.commit(parsed.change);\n } catch (error) {\n open = edited;\n throw error;\n }\n context.show();\n return true;\n } catch (error) {\n // The data refusing the change (e.g. an unreasonable duration): shown in the field.\n if (error instanceof QuartzioError) return refuse(error.message);\n throw error;\n }\n };\n\n /** The next (or previous) editable cell after the open one, across rows. */\n const neighbour = (from: Open, step: 1 | -1): { id: Id; columnId: string } | null => {\n const view = context.view();\n const columns = view.columns.state.items.length;\n let row = view.rowIndex.get(from.taskId);\n let column = columnIndexOf(view, from.columnId);\n if (row === undefined || column < 0) return null;\n for (;;) {\n column += step;\n if (column < 0 || column >= columns) {\n row += step;\n column = step === 1 ? 0 : columns - 1;\n }\n const id = view.rowIds[row];\n if (id === undefined) return null;\n const cell = cellOf(view, id, column);\n if (cell) return { id, columnId: cell.column.id };\n }\n };\n\n return {\n current,\n start,\n commit,\n input(text) {\n if (!open || typeof text !== 'string') return;\n open = { ...open, text, error: null };\n context.show();\n },\n keyDown(key) {\n if (!open || typeof key !== 'object' || (key as unknown) === null) return false;\n switch (key.key) {\n case 'Escape':\n open = null;\n context.show();\n return true;\n case 'Enter':\n commit();\n return true;\n case 'Tab': {\n const from = open;\n if (commit()) {\n const next = neighbour(from, key.shift === true ? -1 : 1);\n if (next) start(next.id, next.columnId);\n }\n return true; // focus stays in the chart\n }\n }\n return false;\n },\n cancel() {\n if (!open) return;\n open = null;\n context.show();\n },\n };\n}\n","import type { TreeIndex } from '../data/tree';\nimport type { Id, Task } from '../data/types';\nimport { VIEW_PRESETS, type ViewPreset } from '../timeaxis/presets';\nimport type { TimeUnit } from '../util/time';\nimport { isEqual } from '../util/equal';\nimport type { KeyInput } from './keyboard';\n\n/** What a menu is for: a task (its row or bar), or the time axis (its header). */\nexport type MenuTarget = { readonly kind: 'task'; readonly id: Id } | { readonly kind: 'timeAxis' };\n\n/** What an item's `action` (and the item customizers) get. */\nexport interface MenuContext {\n readonly target: MenuTarget;\n /** The task the menu is for, or `null` for the time axis. */\n readonly task: Task | null;\n readonly selection: readonly Id[];\n readonly preset: ViewPreset;\n}\n\nexport interface MenuItem {\n readonly id: string;\n readonly label: string;\n readonly disabled?: boolean | undefined;\n /** Shown checked (e.g. the current preset). */\n readonly checked?: boolean | undefined;\n /** A line before it. */\n readonly separator?: boolean | undefined;\n /** A submenu (one level). */\n readonly items?: readonly MenuItem[] | undefined;\n /** For your own items: what choosing it does. Built-in items are carried out by the engine. */\n readonly action?: ((context: MenuContext) => void) | undefined;\n}\n\n/** The open menu. */\nexport interface MenuState {\n readonly kind: 'task' | 'timeAxis';\n readonly taskId: Id | null;\n /** Where it opens, in the chart's coordinates (from the root element's corner). */\n readonly x: number;\n readonly y: number;\n readonly items: readonly MenuItem[];\n /** The highlighted item (in the open submenu, if there is one). */\n readonly active: string | null;\n /** The item whose submenu is open. */\n readonly submenu: string | null;\n}\n\nexport type MenuCustomizer = (items: readonly MenuItem[], context: MenuContext) => readonly MenuItem[];\n\n/** A task menu's built-in item ids, carried out by the engine. */\nexport type TaskMenuItemId =\n | 'edit'\n | 'addTaskAbove'\n | 'addTaskBelow'\n | 'addSubtask'\n | 'addMilestone'\n | 'addSuccessor'\n | 'addPredecessor'\n | 'indent'\n | 'outdent'\n | 'convertToMilestone'\n | 'delete';\n\n/** The tasks an action on `id` applies to: the selection when it includes `id`, without tasks inside others. */\nexport function targetsOf(id: Id, selection: readonly Id[], tree: TreeIndex): Id[] {\n const ids = selection.includes(id) ? selection : [id];\n const set = new Set(ids);\n const roots = ids.filter((each) => !tree.ancestors(each).some((ancestor) => set.has(ancestor)));\n // In tree order, so moving several keeps their order.\n const order = tree.flatten();\n const position = new Map(order.map((each, index) => [each, index]));\n return roots.sort((a, b) => (position.get(a) ?? 0) - (position.get(b) ?? 0));\n}\n\nconst hasSiblingBefore = (tree: TreeIndex, id: Id, parentOf: (id: Id) => Id | null) =>\n tree.children(parentOf(id)).indexOf(id) > 0;\n\n/** The built-in task menu. */\nexport function taskMenuItems(\n task: Task,\n targets: readonly Id[],\n tree: TreeIndex,\n parentOf: (id: Id) => Id | null,\n { edit }: { edit: boolean },\n): MenuItem[] {\n const isParent = !tree.isLeaf(task.id);\n const items: MenuItem[] = [];\n if (edit) items.push({ id: 'edit', label: 'Edit' });\n items.push(\n {\n id: 'add',\n label: 'Add',\n items: [\n { id: 'addTaskAbove', label: 'Task above' },\n { id: 'addTaskBelow', label: 'Task below' },\n { id: 'addSubtask', label: 'Subtask' },\n { id: 'addMilestone', label: 'Milestone' },\n { id: 'addSuccessor', label: 'Successor' },\n { id: 'addPredecessor', label: 'Predecessor' },\n ],\n },\n {\n id: 'indent',\n label: 'Indent',\n separator: true,\n disabled: !targets.some((id) => hasSiblingBefore(tree, id, parentOf)),\n },\n { id: 'outdent', label: 'Outdent', disabled: !targets.some((id) => parentOf(id) !== null) },\n { id: 'convertToMilestone', label: 'Convert to milestone', disabled: isParent || task.duration === 0 },\n { id: 'delete', label: 'Delete', separator: true },\n );\n return items;\n}\n\nconst PRESET_LABELS: Record<string, string> = {\n hourAndDay: 'Hours',\n dayAndWeek: 'Days',\n weekAndDay: 'Weeks and days',\n weekAndMonth: 'Weeks',\n monthAndYear: 'Months',\n quarterAndYear: 'Quarters',\n manyYears: 'Years',\n};\n\n/** The built-in time axis menu: zooming, and the presets. */\nexport function timeAxisMenuItems(preset: ViewPreset): MenuItem[] {\n return [\n { id: 'zoomIn', label: 'Zoom in', disabled: zoomStep(preset, 'in') === undefined },\n { id: 'zoomOut', label: 'Zoom out', disabled: zoomStep(preset, 'out') === undefined },\n ...VIEW_PRESETS.map((each, index) => ({\n id: `preset:${each.id}`,\n label: PRESET_LABELS[each.id] ?? each.id,\n checked: each === preset || isEqual(each, preset),\n separator: index === 0,\n })),\n ];\n}\n\n// Rough lengths, only to compare how zoomed in presets are.\nconst UNIT_MS: Record<TimeUnit, number> = {\n millisecond: 1,\n second: 1000,\n minute: 60_000,\n hour: 3_600_000,\n day: 86_400_000,\n week: 604_800_000,\n month: 2_629_800_000,\n quarter: 7_889_400_000,\n year: 31_557_600_000,\n};\n\n/** Pixels per millisecond: how zoomed in a preset is. */\nconst zoomLevel = (preset: ViewPreset) =>\n preset.tickWidth / (UNIT_MS[preset.tickUnit] * preset.tickIncrement);\n\n/** The built-in preset one step in (more pixels per time) or out, from any preset (custom ones too). */\nexport function zoomStep(preset: ViewPreset, direction: 'in' | 'out'): ViewPreset | undefined {\n const level = zoomLevel(preset);\n let best: ViewPreset | undefined;\n for (const candidate of VIEW_PRESETS) {\n const other = zoomLevel(candidate);\n if (direction === 'in' ? other <= level * 1.0001 : other >= level * 0.9999) continue;\n if (!best || (direction === 'in' ? other < zoomLevel(best) : other > zoomLevel(best))) best = candidate;\n }\n return best;\n}\n\n/** Items that can be picked in the list shown (the open submenu, or the menu). */\nconst shownItems = (menu: MenuState): readonly MenuItem[] =>\n menu.submenu === null ? menu.items : (menu.items.find((item) => item.id === menu.submenu)?.items ?? []);\n\nconst enabled = (items: readonly MenuItem[]) => items.filter((item) => item.disabled !== true);\n\n/** An item by id, in the menu or its submenus. */\nexport function findItem(items: readonly MenuItem[], id: string): MenuItem | undefined {\n for (const item of items) {\n if (item.id === id) return item;\n const inner = item.items ? findItem(item.items, id) : undefined;\n if (inner) return inner;\n }\n return undefined;\n}\n\n/** What a key does in a menu: the new state (`null` closes it) and an item to carry out, or `undefined` when unused. */\nexport function menuKey(\n menu: MenuState,\n input: KeyInput,\n): { menu: MenuState | null; pick?: string } | undefined {\n const items = enabled(shownItems(menu));\n const index = items.findIndex((item) => item.id === menu.active);\n const at = (i: number) => items[(i + items.length) % items.length]?.id ?? null;\n const openSubmenu = (item: MenuItem | undefined) => {\n const children = enabled(item?.items ?? []);\n return item && children.length > 0\n ? { ...menu, submenu: item.id, active: children[0]?.id ?? null }\n : null;\n };\n switch (input.key) {\n case 'ArrowDown':\n return { menu: { ...menu, active: index < 0 ? at(0) : at(index + 1) } };\n case 'ArrowUp':\n return { menu: { ...menu, active: index < 0 ? at(-1) : at(index - 1) } };\n case 'Home':\n return { menu: { ...menu, active: at(0) } };\n case 'End':\n return { menu: { ...menu, active: at(-1) } };\n case 'ArrowRight': {\n const opened = menu.submenu === null ? openSubmenu(items[index]) : null;\n return opened ? { menu: opened } : { menu };\n }\n case 'ArrowLeft':\n return { menu: menu.submenu === null ? menu : { ...menu, active: menu.submenu, submenu: null } };\n case 'Enter':\n case ' ': {\n const item = items[index];\n if (!item) return { menu };\n if (item.items) return { menu: openSubmenu(item) ?? menu };\n return { menu: null, pick: item.id };\n }\n case 'Escape':\n return { menu: menu.submenu === null ? null : { ...menu, active: menu.submenu, submenu: null } };\n case 'Tab':\n return { menu: null };\n }\n return undefined;\n}\n\n/** The pointer over an item: it's highlighted, and a submenu opens (another one closes). */\nexport function menuHover(menu: MenuState, id: string): MenuState {\n const top = menu.items.find((item) => item.id === id);\n if (top) {\n if (top.disabled === true) return menu.submenu === null ? menu : { ...menu, submenu: null, active: null };\n return { ...menu, active: id, submenu: top.items ? id : null };\n }\n const inSubmenu = shownItems(menu).find((item) => item.id === id);\n return inSubmenu && inSubmenu.disabled !== true && menu.submenu !== null ? { ...menu, active: id } : menu;\n}\n\n/** Items from a customizer, checked (it's app code): anything unusable falls back to the built-in items. */\nexport function customized(\n builtIn: readonly MenuItem[],\n customize: MenuCustomizer | undefined,\n context: MenuContext,\n): readonly MenuItem[] {\n if (!customize) return builtIn;\n try {\n const items: unknown = customize(builtIn, context);\n const ids = new Set<string>();\n // An item with an id not seen yet, a label, an action if any, and (at the top) one level of submenu.\n const valid = (entry: unknown, top: boolean): boolean => {\n if (typeof entry !== 'object' || entry === null) return false;\n const { id, label, action, items: children } = entry as Record<string, unknown>;\n if (typeof id !== 'string' || ids.has(id) || typeof label !== 'string') return false;\n if (action !== undefined && typeof action !== 'function') return false;\n ids.add(id);\n if (children === undefined) return true;\n return top && Array.isArray(children) && children.every((child) => valid(child, false));\n };\n return Array.isArray(items) && items.every((entry) => valid(entry, true))\n ? (items as MenuItem[])\n : builtIn;\n } catch {\n return builtIn;\n }\n}\n","import type { Transaction } from '../data/transaction';\nimport type { TreeIndex } from '../data/tree';\nimport type { Dependency, Id, Task } from '../data/types';\n\nexport type AddWhere = 'above' | 'below' | 'subtask' | 'milestone' | 'successor' | 'predecessor';\n\nconst NEW_TASK_NAME = 'New task';\n\n/**\n * Adds a task next to (or in) `target`: 1 day, or 0 for a milestone; a successor or predecessor is linked with\n * FS. Returns the new task's id. `id` is used when given (it must be new), otherwise the data makes one up.\n */\nexport function addTask(tx: Transaction, target: Task, where: AddWhere, id: Id | undefined): Id {\n const parentId = target.parentId;\n const index = tx.tasks.children(parentId).indexOf(target.id);\n const before = where === 'above' || where === 'predecessor';\n const fields = {\n ...(id === undefined ? {} : { id }),\n name: NEW_TASK_NAME,\n duration: where === 'milestone' ? 0 : 1,\n };\n const added =\n where === 'subtask'\n ? tx.tasks.add(fields, { parentId: target.id })\n : tx.tasks.add(fields, { parentId, index: before ? index : index + 1 });\n if (where === 'successor') tx.dependencies.add({ from: target.id, to: added.id, type: 'FS' });\n if (where === 'predecessor') tx.dependencies.add({ from: added.id, to: target.id, type: 'FS' });\n return added.id;\n}\n\n/**\n * Makes each task the last child of the sibling before it (in tree order; those without one stay). Links between\n * the task (or its subtasks) and its new parent go: a parent and its children can't be linked.\n */\nexport function indent(\n tx: Transaction,\n ids: readonly Id[],\n tree: TreeIndex,\n dependencies: Iterable<Dependency>,\n): Id[] {\n const parents: Id[] = [];\n const links = [...dependencies];\n for (const id of ids) {\n const task = tx.tasks.get(id);\n if (!task) continue;\n const siblings = tx.tasks.children(task.parentId);\n const before = siblings[siblings.indexOf(id) - 1];\n if (before === undefined) continue;\n const subtree = new Set([id, ...tree.descendants(id)]);\n for (const link of links) {\n const between =\n (subtree.has(link.from) && link.to === before) || (link.from === before && subtree.has(link.to));\n if (between && tx.dependencies.get(link.id)) tx.dependencies.remove(link.id);\n }\n tx.tasks.move(id, { parentId: before });\n parents.push(before);\n }\n return parents;\n}\n\n/** Moves each task out of its parent, right after it (root tasks stay). */\nexport function outdent(tx: Transaction, ids: readonly Id[]): void {\n // Last first, so several siblings end up after their parent in their own order.\n for (const id of [...ids].reverse()) {\n const task = tx.tasks.get(id);\n const parent = task?.parentId === null || task === undefined ? undefined : tx.tasks.get(task.parentId);\n if (!parent) continue;\n const index = tx.tasks.children(parent.parentId).indexOf(parent.id);\n tx.tasks.move(id, { parentId: parent.parentId, index: index + 1 });\n }\n}\n","import { workingMsPerUnit } from '../calendar/duration';\nimport type { PlannedChange } from '../data/project';\nimport type { Transaction } from '../data/transaction';\nimport type { TreeIndex } from '../data/tree';\nimport type { DependencyType, Id, ProjectState, Task } from '../data/types';\nimport type { TimeUnit } from '../util/time';\nimport { QuartzioError } from '../util/errors';\nimport { fromWallTime } from '../util/zone';\nimport { taskDates } from './dates';\nimport {\n durationText,\n editKind,\n initialText,\n inputValue,\n MAX_WORKING_DAYS,\n parseDuration,\n parseEdit,\n parseInputDate,\n type EditKind,\n} from './editing';\n\nexport type TaskEditorTab = 'general' | 'predecessors' | 'successors' | 'advanced';\nexport type TaskEditorField =\n 'name' | 'startDate' | 'endDate' | 'duration' | 'percentDone' | 'constraintDate';\nexport type TaskEditorSide = 'predecessors' | 'successors';\nexport type TaskEditorConstraint = 'none' | 'startnoearlierthan';\n\nexport interface TaskEditorFieldState {\n readonly text: string;\n readonly kind: EditKind;\n readonly error: string | null;\n /** Can't be edited (e.g. a parent's dates, which roll up). */\n readonly disabled: boolean;\n}\n\n/** A predecessor or successor in the editor. */\nexport interface TaskEditorDependency {\n /** Stable key for rendering and actions. */\n readonly key: string;\n /** The dependency it edits, or `null` for a new one. */\n readonly dependencyId: Id | null;\n /** The other task, or `null` until one is chosen. */\n readonly taskId: Id | null;\n readonly type: DependencyType;\n /** Lag as text, e.g. `2d` or `-1d`. */\n readonly lag: string;\n readonly error: string | null;\n}\n\n/** The open task editor. */\nexport interface TaskEditorState {\n readonly taskId: Id;\n /** The task as it is now. */\n readonly task: Task;\n readonly tab: TaskEditorTab;\n readonly fields: Readonly<Record<TaskEditorField, TaskEditorFieldState>>;\n readonly manuallyScheduled: boolean;\n readonly constraintType: TaskEditorConstraint;\n readonly predecessors: readonly TaskEditorDependency[];\n readonly successors: readonly TaskEditorDependency[];\n /** Tasks a dependency can link to, in tree order. */\n readonly candidates: readonly { readonly id: Id; readonly name: string; readonly depth: number }[];\n /** Why saving failed as a whole (e.g. a dependency cycle). */\n readonly error: string | null;\n}\n\nexport type TaskEditorAction =\n | { readonly type: 'input'; readonly field: TaskEditorField; readonly value: string }\n | { readonly type: 'input'; readonly field: 'manuallyScheduled'; readonly value: boolean }\n | { readonly type: 'input'; readonly field: 'constraintType'; readonly value: TaskEditorConstraint }\n | { readonly type: 'tab'; readonly tab: TaskEditorTab }\n | { readonly type: 'addDependency'; readonly side: TaskEditorSide }\n | {\n readonly type: 'updateDependency';\n readonly side: TaskEditorSide;\n readonly key: string;\n readonly changes: {\n readonly taskId?: Id | null | undefined;\n readonly type?: DependencyType | undefined;\n readonly lag?: string | undefined;\n };\n }\n | { readonly type: 'removeDependency'; readonly side: TaskEditorSide; readonly key: string }\n | { readonly type: 'save' }\n | { readonly type: 'close' };\n\nexport interface TaskEditorView {\n readonly project: ProjectState;\n readonly tree: TreeIndex;\n readonly dateField: 'date' | 'datetime';\n}\n\nexport interface TaskEditorContext {\n readonly view: () => TaskEditorView;\n readonly enabled: () => boolean;\n readonly plan: (fn: (tx: Transaction) => void) => PlannedChange | null;\n readonly commit: (fn: (tx: Transaction) => void) => void;\n readonly show: () => void;\n}\n\nexport interface TaskEditor {\n readonly current: (view: TaskEditorView) => TaskEditorState | null;\n readonly open: (id: Id) => boolean;\n readonly act: (action: TaskEditorAction) => boolean;\n}\n\ninterface DraftDependency {\n readonly key: string;\n readonly dependencyId: Id | null;\n readonly taskId: Id | null;\n readonly type: DependencyType;\n readonly lag: string;\n /** As loaded, to tell whether it changed. */\n readonly initial: {\n readonly taskId: Id | null;\n readonly type: DependencyType;\n readonly lag: string;\n /** The exact lag, kept while its text isn't changed (the text is rounded). */\n readonly value: number;\n readonly unit: TimeUnit;\n } | null;\n readonly error: string | null;\n}\n\ninterface Draft {\n readonly taskId: Id;\n readonly tab: TaskEditorTab;\n readonly texts: Readonly<Record<TaskEditorField, string>>;\n /** The values' texts: a field whose text is still this wasn't typed in (and follows the value). */\n readonly initial: Readonly<Record<TaskEditorField, string>>;\n readonly errors: Readonly<Partial<Record<TaskEditorField, string>>>;\n readonly manual: boolean;\n readonly constraint: TaskEditorConstraint;\n readonly predecessors: readonly DraftDependency[];\n readonly successors: readonly DraftDependency[];\n readonly removed: readonly Id[];\n readonly error: string | null;\n}\n\nconst FIELDS: readonly TaskEditorField[] = [\n 'name',\n 'startDate',\n 'endDate',\n 'duration',\n 'percentDone',\n 'constraintDate',\n];\nconst TABS = new Set<TaskEditorTab>(['general', 'predecessors', 'successors', 'advanced']);\nconst TYPES = new Set<DependencyType>(['FS', 'SS', 'FF', 'SF']);\n// The fields a save reads first; the end comes last, read against where the rest puts the task.\nconst SAVE_ORDER = ['name', 'percentDone', 'startDate', 'duration'] as const;\n\n/** The value of each field as text. */\nfunction texts(task: Task, view: TaskEditorView): Record<TaskEditorField, string> {\n const zone = view.project.settings.timeZone;\n const dates = taskDates(task);\n const text = (field: Exclude<TaskEditorField, 'constraintDate'>) =>\n initialText(field, field === 'name' ? 'text' : kindOf(field, view), task, dates, zone);\n return {\n name: text('name'),\n startDate: text('startDate'),\n endDate: text('endDate'),\n duration: text('duration'),\n percentDone: text('percentDone'),\n constraintDate: task.constraintDate === null ? '' : inputValue(task.constraintDate, view.dateField, zone),\n };\n}\n\nfunction kindOf(field: TaskEditorField, view: TaskEditorView): EditKind {\n if (field === 'name') return 'text';\n if (field === 'duration') return 'duration';\n if (field === 'percentDone') return 'percent';\n return view.dateField;\n}\n\n/** A lag like `2d` or `-1.5h`, in working time. */\nfunction parseLag(text: string, view: TaskEditorView): { value: number; unit: TimeUnit } | string {\n const match = /^\\s*([+-]?)\\s*(.*)$/.exec(text) as RegExpExecArray;\n const parsed = parseDuration(match[2] as string, 'day');\n if (typeof parsed === 'string') return 'Enter a lag, like 2d or -1d.';\n const settings = view.project.settings;\n const days = (parsed.value * workingMsPerUnit(parsed.unit, settings)) / workingMsPerUnit('day', settings);\n if (days > MAX_WORKING_DAYS) return `Enter a lag of at most ${String(MAX_WORKING_DAYS)} working days.`;\n return { value: match[1] === '-' ? -parsed.value : parsed.value, unit: parsed.unit };\n}\n\n/** Editing a task in a dialog: a draft, saved as one change. */\nexport function createTaskEditor(context: TaskEditorContext): TaskEditor {\n let draft: Draft | null = null;\n let nextKey = 0;\n let shown: { draft: Draft; task: Task; project: ProjectState; state: TaskEditorState } | null = null;\n let candidatesCache: { tasks: unknown; taskId: Id; list: TaskEditorState['candidates'] } | null = null;\n\n const candidatesFor = (view: TaskEditorView, id: Id): TaskEditorState['candidates'] => {\n if (candidatesCache?.tasks === view.project.tasks && candidatesCache.taskId === id)\n return candidatesCache.list;\n // Not itself, its ancestors or its descendants: links between a parent and its children are refused.\n const excluded = new Set<Id>([id, ...view.tree.ancestors(id), ...view.tree.descendants(id)]);\n const list = view.tree\n .flatten()\n .filter((each) => !excluded.has(each))\n .map((each) => ({\n id: each,\n name: view.project.tasks.byId.get(each)?.name ?? '',\n depth: view.tree.depth(each),\n }));\n candidatesCache = { tasks: view.project.tasks, taskId: id, list };\n return list;\n };\n\n const dependencyRows = (view: TaskEditorView, id: Id, side: TaskEditorSide): DraftDependency[] => {\n const rows: DraftDependency[] = [];\n for (const dependency of view.project.dependencies.byId.values()) {\n const mine = side === 'predecessors' ? dependency.to === id : dependency.from === id;\n if (!mine) continue;\n const taskId = side === 'predecessors' ? dependency.from : dependency.to;\n const lag = durationText(dependency.lag, dependency.lagUnit);\n rows.push({\n key: `d${String(nextKey++)}`,\n dependencyId: dependency.id,\n taskId,\n type: dependency.type,\n lag,\n initial: { taskId, type: dependency.type, lag, value: dependency.lag, unit: dependency.lagUnit },\n error: null,\n });\n }\n return rows;\n };\n\n const current = (view: TaskEditorView): TaskEditorState | null => {\n const task = draft && context.enabled() ? view.project.tasks.byId.get(draft.taskId) : undefined;\n if (!draft || !task) {\n draft = null;\n shown = null;\n return null;\n }\n // Fields nobody typed in follow the value (changed elsewhere, or an earlier save the app accepted).\n const now = texts(task, view);\n const { texts: typed, initial: loaded } = draft;\n const followed = FIELDS.filter((field) => typed[field] === loaded[field] && now[field] !== loaded[field]);\n if (followed.length > 0) {\n const next = { ...draft.texts };\n const initial = { ...draft.initial };\n for (const field of followed) next[field] = initial[field] = now[field];\n draft = { ...draft, texts: next, initial };\n }\n if (shown?.draft === draft && shown.task === task && shown.project === view.project) return shown.state;\n\n const isParent = !view.tree.isLeaf(task.id);\n const dates = taskDates(task);\n const field = (name: TaskEditorField): TaskEditorFieldState => {\n let disabled = false;\n if (name === 'constraintDate') disabled = draft?.constraint === 'none';\n else if (name !== 'name') {\n const builtIn = name === 'percentDone' ? 'percentDone' : name;\n disabled = editKind(builtIn, task, isParent, dates, view.dateField) === null;\n }\n return {\n text: draft?.texts[name] ?? '',\n kind: kindOf(name, view),\n error: draft?.errors[name] ?? null,\n disabled,\n };\n };\n const row = ({ key, dependencyId, taskId, type, lag, error }: DraftDependency): TaskEditorDependency => ({\n key,\n dependencyId,\n taskId,\n type,\n lag,\n error,\n });\n const state: TaskEditorState = {\n taskId: task.id,\n task,\n tab: draft.tab,\n fields: {\n name: field('name'),\n startDate: field('startDate'),\n endDate: field('endDate'),\n duration: field('duration'),\n percentDone: field('percentDone'),\n constraintDate: field('constraintDate'),\n },\n manuallyScheduled: draft.manual,\n constraintType: draft.constraint,\n predecessors: draft.predecessors.map(row),\n successors: draft.successors.map(row),\n candidates: candidatesFor(view, task.id),\n error: draft.error,\n };\n shown = { draft, task, project: view.project, state };\n return state;\n };\n\n const open = (id: Id): boolean => {\n draft = null;\n const view = context.view();\n const task = context.enabled() ? view.project.tasks.byId.get(id) : undefined;\n if (!task) {\n context.show();\n return false;\n }\n const initial = texts(task, view);\n draft = {\n taskId: id,\n tab: 'general',\n texts: initial,\n initial,\n errors: {},\n manual: task.manuallyScheduled,\n constraint: task.constraintType === 'startnoearlierthan' ? 'startnoearlierthan' : 'none',\n predecessors: dependencyRows(view, id, 'predecessors'),\n successors: dependencyRows(view, id, 'successors'),\n removed: [],\n error: null,\n };\n context.show();\n return true;\n };\n\n const set = (next: Draft): true => {\n draft = next;\n context.show();\n return true;\n };\n\n const save = (): boolean => {\n if (!draft) return false;\n const view = context.view();\n const task = view.project.tasks.byId.get(draft.taskId);\n const state = task ? current(view) : null;\n if (!task || !state) return false;\n const settings = view.project.settings;\n const zone = settings.timeZone;\n const errors: Partial<Record<TaskEditorField, string>> = {};\n const changes: ((tx: Transaction) => void)[] = [];\n const id = task.id;\n\n if (draft.manual !== task.manuallyScheduled) {\n const manual = draft.manual;\n changes.push((tx) => {\n tx.tasks.update(id, { manuallyScheduled: manual });\n });\n }\n // Read against the task as it will be scheduled (a start on a task switched to manual is its start date).\n const asScheduled = { ...task, manuallyScheduled: draft.manual };\n const dates = taskDates(task);\n const typed = (name: TaskEditorField) =>\n !state.fields[name].disabled && (draft as Draft).texts[name] !== (draft as Draft).initial[name];\n // Each decides the end: which one to keep would be a guess.\n if (typed('duration') && typed('endDate')) errors.endDate = 'Change the duration or the end, not both.';\n for (const name of SAVE_ORDER) {\n if (!typed(name)) continue;\n const parsed = parseEdit(\n name,\n state.fields[name].kind,\n draft.texts[name],\n asScheduled,\n dates,\n settings,\n );\n if ('error' in parsed) errors[name] = parsed.error;\n else changes.push(parsed.change);\n }\n\n const constraintChanged =\n draft.constraint !== (task.constraintType === 'startnoearlierthan' ? 'startnoearlierthan' : 'none');\n if (constraintChanged || draft.texts.constraintDate !== draft.initial.constraintDate) {\n if (typed('startDate') && !draft.manual) {\n // An automatic task's start is its constraint: both changed contradict each other.\n errors.constraintDate = 'Change the start or the constraint, not both.';\n } else if (draft.constraint === 'none') {\n changes.push((tx) => {\n tx.tasks.update(id, { constraintType: null, constraintDate: null });\n });\n } else {\n const wall = parseInputDate(draft.texts.constraintDate, view.dateField);\n if (typeof wall === 'string') errors.constraintDate = wall;\n else {\n const date = fromWallTime(wall, zone);\n changes.push((tx) => {\n tx.tasks.update(id, { constraintType: 'startnoearlierthan', constraintDate: date });\n });\n }\n }\n }\n\n let failed = Object.keys(errors).length > 0;\n const checkSide = (side: TaskEditorSide): DraftDependency[] => {\n const seen = new Set<Id>();\n return (draft as Draft)[side].map((row) => {\n let error: string | null = null;\n const initial = row.initial;\n const lag =\n row.lag === initial?.lag ? { value: initial.value, unit: initial.unit } : parseLag(row.lag, view);\n if (row.taskId === null || !view.project.tasks.byId.has(row.taskId)) error = 'Choose a task.';\n else if (seen.has(row.taskId)) error = 'This task is linked twice.';\n else if (typeof lag === 'string') error = lag;\n if (row.taskId !== null) seen.add(row.taskId);\n if (error) failed = true;\n else if (\n row.initial?.taskId !== row.taskId ||\n row.initial.type !== row.type ||\n row.initial.lag !== row.lag\n ) {\n const other = row.taskId as Id;\n const { value, unit } = lag as { value: number; unit: TimeUnit };\n const ends = side === 'predecessors' ? { from: other, to: id } : { from: id, to: other };\n const fields = { ...ends, type: row.type, lag: value, lagUnit: unit };\n const dependencyId = row.dependencyId;\n changes.push((tx) => {\n if (dependencyId === null) tx.dependencies.add(fields);\n else tx.dependencies.update(dependencyId, fields);\n });\n }\n return row.error === error ? row : { ...row, error };\n });\n };\n const predecessors = checkSide('predecessors');\n const successors = checkSide('successors');\n for (const dependencyId of draft.removed) {\n changes.unshift((tx) => {\n if (tx.dependencies.get(dependencyId)) tx.dependencies.remove(dependencyId);\n });\n }\n if (failed) return !set({ ...draft, errors, predecessors, successors, error: null });\n const refuse = (message: { field: TaskEditorField; text: string } | string) =>\n !set({\n ...(draft as Draft),\n errors: typeof message === 'string' ? errors : { ...errors, [message.field]: message.text },\n predecessors,\n successors,\n error: typeof message === 'string' ? message : null,\n });\n\n const fn = (tx: Transaction) => {\n for (const change of changes) change(tx);\n };\n try {\n if (typed('endDate')) {\n // The end is read against where the other changes put the task (a new start moves it).\n const moved = changes.length > 0 ? context.plan(fn)?.state.tasks.byId.get(id) : undefined;\n const base = { ...(moved ?? task), manuallyScheduled: draft.manual };\n const kind = state.fields.endDate.kind;\n const end = parseEdit('endDate', kind, draft.texts.endDate, base, taskDates(base), settings);\n if ('error' in end) return refuse({ field: 'endDate', text: end.error });\n // The duration comes from the start to the end: the new start (an automatic task's is only its constraint\n // until it's scheduled).\n const start = taskDates(base)?.start;\n if (moved && start !== undefined) {\n changes.push((tx) => {\n tx.tasks.update(id, { startDate: start });\n });\n }\n changes.push(end.change);\n }\n if (changes.length > 0 && context.plan(fn)) context.commit(fn);\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n return refuse(error.message);\n }\n draft = null;\n context.show();\n return true;\n };\n\n const updateSide = (\n side: TaskEditorSide,\n update: (rows: readonly DraftDependency[]) => DraftDependency[] | null,\n ) => {\n if (!draft) return false;\n const rows = update(draft[side]);\n return rows ? set({ ...draft, [side]: rows, error: null }) : false;\n };\n\n const act = (action: TaskEditorAction): boolean => {\n if (!draft || typeof action !== 'object' || (action as unknown) === null) return false;\n if ('side' in action && action.side !== 'predecessors' && (action.side as unknown) !== 'successors')\n return false;\n switch (action.type) {\n case 'input': {\n const { field, value } = action;\n if (field === 'manuallyScheduled')\n return typeof value === 'boolean' ? set({ ...draft, manual: value, error: null }) : false;\n if (field === 'constraintType') {\n const constraint: unknown = value;\n if (constraint !== 'none' && constraint !== 'startnoearlierthan') return false;\n const { constraintDate: _cleared, ...rest } = draft.errors;\n return set({ ...draft, constraint: value, errors: rest, error: null });\n }\n if (!FIELDS.includes(field) || typeof value !== 'string') return false;\n const { [field]: _cleared, ...errors } = draft.errors;\n return set({ ...draft, texts: { ...draft.texts, [field]: value }, errors, error: null });\n }\n case 'tab':\n return TABS.has(action.tab) ? set({ ...draft, tab: action.tab }) : false;\n case 'addDependency':\n return updateSide(action.side, (rows) => [\n ...rows,\n {\n key: `n${String(nextKey++)}`,\n dependencyId: null,\n taskId: null,\n type: 'FS',\n lag: '0d',\n initial: null,\n error: null,\n },\n ]);\n case 'updateDependency': {\n const changes: unknown = action.changes;\n if (typeof changes !== 'object' || changes === null) return false;\n const { taskId, type, lag } = changes as Record<string, unknown>;\n return updateSide(action.side, (rows) => {\n if (!rows.some((row) => row.key === action.key)) return null;\n if (type !== undefined && !TYPES.has(type as DependencyType)) return null;\n if (lag !== undefined && typeof lag !== 'string') return null;\n return rows.map((row) =>\n row.key !== action.key\n ? row\n : {\n ...row,\n ...(taskId === undefined ? {} : { taskId: taskId as Id | null }),\n ...(type === undefined ? {} : { type: type as DependencyType }),\n ...(lag === undefined ? {} : { lag: lag }),\n error: null,\n },\n );\n });\n }\n case 'removeDependency': {\n const removed = draft[action.side].find((row) => row.key === action.key);\n if (!removed) return false;\n const dependencyId = removed.dependencyId;\n const withRemoved =\n dependencyId === null ? draft : { ...draft, removed: [...draft.removed, dependencyId] };\n draft = withRemoved;\n return updateSide(action.side, (rows) => rows.filter((row) => row.key !== action.key));\n }\n case 'save':\n return save();\n case 'close':\n draft = null;\n context.show();\n return true;\n }\n return false;\n };\n\n return { current, open, act };\n}\n","import { QuartzioError } from '../util/errors';\n\n/** The task list is never narrower than this, so the divider can always be found and dragged back. */\nexport const MIN_LIST_WIDTH = 80;\n/** Room the timeline keeps when the list is widened. */\nexport const MIN_TIMELINE_WIDTH = 120;\nconst KEY_STEP = 10;\nconst BIG_KEY_STEP = 50;\n\n/**\n * The width of the task list (its pane, border included), as the divider between it and the timeline sets it.\n * `width: null` means automatic: as wide as the columns, up to `--qz-list-max-width`.\n */\nexport interface ListPaneState {\n readonly width: number | null;\n /** The divider is being dragged. */\n readonly resizing: boolean;\n /** Bounds for the divider: at most as wide as the columns (the chart may show it narrower). */\n readonly min: number;\n readonly max: number;\n}\n\n/**\n * What the divider does, sent from the renderer with measured sizes: `width` is the list pane as shown now,\n * `chartWidth` the whole chart's. `x` is any horizontal coordinate that moves with the pointer.\n */\nexport type ListResizeAction =\n | { readonly type: 'start'; readonly x: number; readonly width: number; readonly chartWidth: number }\n | { readonly type: 'move'; readonly x: number }\n | { readonly type: 'end' }\n | { readonly type: 'cancel' }\n | {\n readonly type: 'key';\n readonly key: string;\n readonly shift?: boolean | undefined;\n readonly width: number;\n readonly chartWidth: number;\n }\n /** Back to automatic (double-click on the divider). */\n | { readonly type: 'reset' };\n\n/** The `listWidth` option: a positive number of pixels, or `null`/`undefined` for automatic. */\nexport function toListWidth(value: unknown): number | null {\n if (value === undefined || value === null) return null;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 100_000) {\n throw new QuartzioError('Gantt options: \"listWidth\" must be a positive number of pixels, or null.');\n }\n return value;\n}\n\nconst finite = (...values: readonly unknown[]): boolean =>\n values.every((value) => typeof value === 'number' && Number.isFinite(value));\n\nexport interface ListWidth {\n readonly state: () => ListPaneState;\n /** A new `listWidth` option. The same value again keeps a dragged width; another one ends a drag. */\n readonly setOption: (value: number | null) => void;\n /** The columns' total width changed (it bounds the list). */\n readonly setColumnsWidth: (width: number) => void;\n /**\n * Applies an action: `used` says whether it was one the divider acts on, `changed` the new width to report\n * (`undefined` when there's nothing to report).\n */\n readonly act: (action: ListResizeAction) => { used: boolean; changed?: number | null };\n}\n\n/**\n * The divider between the task list and the timeline. Like zooming and the `preset` option: dragging overrides\n * the `listWidth` option until the option changes (compared by value), and the new width is reported.\n */\nexport function createListWidth(option: number | null, columnsWidth: number): ListWidth {\n // undefined: nothing dragged since the option was set.\n let override: number | null | undefined;\n let columns = columnsWidth;\n let drag: {\n x: number;\n width: number;\n chartWidth: number;\n // What to go back to on cancel, and what the drop is compared with.\n override: number | null | undefined;\n effective: number | null;\n } | null = null;\n\n function maxOf(columnsTotal: number): number {\n return Math.max(MIN_LIST_WIDTH, Math.round(columnsTotal) + 1);\n }\n // An option below the minimum (a width stored from another layout, say) is shown at the minimum.\n const effective = (): number | null => {\n const width = override === undefined ? option : override;\n return width === null ? null : Math.max(MIN_LIST_WIDTH, width);\n };\n const clamp = (width: number, chartWidth: number) =>\n Math.round(\n Math.min(\n Math.max(width, MIN_LIST_WIDTH),\n Math.max(MIN_LIST_WIDTH, Math.min(maxOf(columns), chartWidth - MIN_TIMELINE_WIDTH)),\n ),\n );\n let current: ListPaneState = {\n width: effective(),\n resizing: false,\n min: MIN_LIST_WIDTH,\n max: maxOf(columns),\n };\n const update = (): void => {\n const next = { width: effective(), resizing: drag !== null, min: MIN_LIST_WIDTH, max: maxOf(columns) };\n if (next.width !== current.width || next.resizing !== current.resizing || next.max !== current.max) {\n current = next;\n }\n };\n\n return {\n state: () => current,\n\n setOption(value) {\n if (value === option) return;\n option = value;\n override = undefined;\n drag = null;\n update();\n },\n\n setColumnsWidth(width) {\n columns = width;\n update();\n },\n\n act(action) {\n // Plain JavaScript may pass anything.\n if (typeof action !== 'object' || (action as unknown) === null) return { used: false };\n switch (action.type) {\n case 'start': {\n // One drag at a time: a second finger doesn't restart it.\n if (drag || !finite(action.x, action.width, action.chartWidth) || action.chartWidth <= 0)\n return { used: false };\n drag = {\n x: action.x,\n width: action.width,\n chartWidth: action.chartWidth,\n override,\n effective: effective(),\n };\n update();\n return { used: true };\n }\n case 'move': {\n if (!drag || !finite(action.x)) return { used: false };\n const width = clamp(drag.width + action.x - drag.x, drag.chartWidth);\n // A press that hasn't moved the width yet (a click) leaves an automatic width automatic.\n if (override !== drag.override || width !== Math.round(drag.width)) override = width;\n update();\n return { used: true };\n }\n case 'end': {\n if (!drag) return { used: false };\n const moved = effective() !== drag.effective;\n drag = null;\n update();\n return moved ? { used: true, changed: effective() } : { used: true };\n }\n case 'cancel': {\n if (!drag) return { used: false };\n override = drag.override;\n drag = null;\n update();\n return { used: true };\n }\n case 'key': {\n if (drag || !finite(action.width, action.chartWidth) || action.chartWidth <= 0)\n return { used: false };\n const step = action.shift ? BIG_KEY_STEP : KEY_STEP;\n const target =\n action.key === 'ArrowLeft'\n ? action.width - step\n : action.key === 'ArrowRight'\n ? action.width + step\n : action.key === 'Home'\n ? MIN_LIST_WIDTH\n : action.key === 'End'\n ? Number.POSITIVE_INFINITY\n : null;\n if (target === null) return { used: false };\n // A key at a bound is used, but moves nothing (an automatic width stays automatic).\n const width = clamp(target, action.chartWidth);\n if (width === Math.round(action.width)) return { used: true };\n override = width;\n update();\n return { used: true, changed: width };\n }\n case 'reset': {\n if (drag || effective() === null) return { used: false };\n override = null;\n update();\n return { used: true, changed: null };\n }\n default:\n return { used: false };\n }\n },\n };\n}\n","import { createProject } from '../data/project';\nimport { scheduleProject } from '../scheduling/schedule';\nimport { getTreeIndex } from '../data/tree';\nimport type { Id, Operation, ProjectState } from '../data/types';\nimport { createEmitter } from '../util/emitter';\nimport { isEqual } from '../util/equal';\nimport { QuartzioError } from '../util/errors';\nimport { createDataBinding } from './binding';\nimport { createHistory, type HistoryAction } from './history';\nimport { keyCommand } from './keyboard';\nimport {\n clickRow,\n NO_SELECTION,\n pruneSelection,\n selectIds,\n selectionOf,\n visibleRowOf,\n type KeyModifiers,\n type Selection,\n type VisibleRows,\n} from './selection';\nimport { resolveColumns, type ColumnInput, type ResolvedColumns } from './columns';\nimport type { TimeAxis } from '../timeaxis/timeAxis';\nimport { createDependencyView } from './dependencies';\nimport {\n CLICK_TOLERANCE,\n createInteraction,\n type Interaction,\n type InteractionView,\n type TaskInteraction,\n type TimelinePoint,\n} from './interaction';\nimport { createNonWorkingView } from './nonWorking';\nimport { createRowsView, UNMEASURED_HEIGHT } from './rows';\nimport { tooltipFor, type TaskTooltip } from './tooltip';\nimport { createCellEditor, type EditorView } from './cellEditor';\nimport { barUnder } from './interaction';\nimport {\n customized,\n findItem,\n menuHover,\n menuKey,\n taskMenuItems,\n targetsOf,\n timeAxisMenuItems,\n zoomStep,\n type MenuContext,\n type MenuItem,\n type MenuState,\n type MenuTarget,\n type TaskMenuItemId,\n} from './menu';\nimport { addTask, indent, outdent, type AddWhere } from './taskActions';\nimport { createTaskEditor } from './taskEditor';\nimport { createListWidth, toListWidth } from './listWidth';\nimport { VIEW_PRESETS } from '../timeaxis/presets';\nimport type { Transaction } from '../data/transaction';\n\nimport { dateKind } from './editing';\nimport { createTimelineView, resolveTimeline, sameTimeline, type TimelineOptions } from './timeline';\nimport type {\n GanttController,\n GanttOptions,\n Interactions,\n ScrollRequest,\n TodayLine,\n ViewState,\n Viewport,\n} from './types';\n\nexport type {\n GanttController,\n GanttDataChange,\n GanttOptions,\n HeaderState,\n Interactions,\n ViewState,\n Viewport,\n} from './types';\n\nconst INITIAL_VIEWPORT: Viewport = { width: 0, height: 0, scrollLeft: 0, scrollTop: 0 };\nconst DEFAULT_ROW_HEIGHT = 44;\nconst DEFAULT_HEADER_ROW_HEIGHT = 28;\n/** Where a menu opened with the keyboard goes, from the left edge of the chart. */\nconst KEYBOARD_MENU_X = 24;\n\n/** The `scrollTop` that shows row `index`, or `null` when it shows (or nothing is measured). */\nfunction revealTopOf(index: number, viewport: Viewport, rowHeight: number): number | null {\n if (viewport.height <= 0) return null;\n const top = index * rowHeight;\n if (top < viewport.scrollTop) return top;\n if (top + rowHeight > viewport.scrollTop + viewport.height) return top + rowHeight - viewport.height;\n return null;\n}\n\n/** Options that shape the view (as opposed to data and callbacks), validated as a whole. */\ninterface ViewOptions {\n timeline: TimelineOptions;\n columnInput: readonly ColumnInput[] | undefined;\n columns: ResolvedColumns;\n rowHeight: number;\n headerRowHeight: number;\n showToday: boolean;\n showNonWorkingTime: boolean;\n taskDrag: boolean;\n taskResize: boolean;\n taskDragCreate: boolean;\n progressDrag: boolean;\n dependencyCreate: boolean;\n /** The five switches above as one object, kept while they're unchanged. */\n interactions: Interactions;\n}\n\nconst VIEW_KEYS = [\n 'preset',\n 'startDate',\n 'endDate',\n 'locale',\n 'columns',\n 'rowHeight',\n 'headerRowHeight',\n 'showToday',\n 'showNonWorkingTime',\n 'taskDrag',\n 'taskResize',\n 'taskDragCreate',\n 'progressDrag',\n 'dependencyCreate',\n] as const;\n\n/** Modifiers straight from events (or plain JavaScript): anything that isn't an object means none. */\nconst modifiersOf = (value: unknown): KeyModifiers =>\n typeof value === 'object' && value !== null ? value : {};\n\nfunction toSwitch(value: unknown, fallback: boolean, name: string): boolean {\n if (value === undefined || value === null) return fallback;\n if (typeof value !== 'boolean') throw new QuartzioError(`Gantt options: \"${name}\" must be true or false.`);\n return value;\n}\n\nfunction toHeight(value: unknown, fallback: number, name: string): number {\n if (value === undefined || value === null) return fallback;\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 8 || value > 500) {\n throw new QuartzioError(`Gantt options: \"${name}\" must be a number from 8 to 500.`);\n }\n return value;\n}\n\n/** Validates the view options, reusing unchanged parts of `previous`. Throws before anything changes. */\nfunction resolveViewOptions(options: GanttOptions, previous?: ViewOptions): ViewOptions {\n const resolved = resolveSwitches(options, previous);\n const interactions: Interactions = {\n drag: resolved.taskDrag,\n resize: resolved.taskResize,\n create: resolved.taskDragCreate,\n progress: resolved.progressDrag,\n link: resolved.dependencyCreate,\n };\n return {\n ...resolved,\n interactions:\n previous && isEqual(previous.interactions, interactions) ? previous.interactions : interactions,\n };\n}\n\nfunction resolveSwitches(options: GanttOptions, previous?: ViewOptions): Omit<ViewOptions, 'interactions'> {\n const has = (key: keyof GanttOptions) => previous === undefined || key in options;\n const timeline = resolveTimeline({\n preset: has('preset') ? options.preset : previous?.timeline.preset,\n startDate: has('startDate') ? options.startDate : previous?.timeline.startDate,\n endDate: has('endDate') ? options.endDate : previous?.timeline.endDate,\n locale: has('locale') ? options.locale : previous?.timeline.locale,\n });\n const columnInput = has('columns') ? options.columns : previous?.columnInput;\n // Equal by value, so an inline array with the same columns (new on every React render) is no change.\n // Value functions compare by identity: define columns with custom functions outside render.\n const columns =\n previous && (columnInput === previous.columnInput || isEqual(columnInput, previous.columnInput))\n ? previous.columns\n : resolveColumns(columnInput ?? undefined);\n return {\n timeline: previous && sameTimeline(timeline, previous.timeline) ? previous.timeline : timeline,\n columnInput,\n columns,\n rowHeight: has('rowHeight')\n ? toHeight(options.rowHeight, DEFAULT_ROW_HEIGHT, 'rowHeight')\n : (previous?.rowHeight ?? DEFAULT_ROW_HEIGHT),\n headerRowHeight: has('headerRowHeight')\n ? toHeight(options.headerRowHeight, DEFAULT_HEADER_ROW_HEIGHT, 'headerRowHeight')\n : (previous?.headerRowHeight ?? DEFAULT_HEADER_ROW_HEIGHT),\n showToday: has('showToday')\n ? toSwitch(options.showToday, true, 'showToday')\n : (previous?.showToday ?? true),\n showNonWorkingTime: has('showNonWorkingTime')\n ? toSwitch(options.showNonWorkingTime, true, 'showNonWorkingTime')\n : (previous?.showNonWorkingTime ?? true),\n taskDrag: has('taskDrag') ? toSwitch(options.taskDrag, true, 'taskDrag') : (previous?.taskDrag ?? true),\n taskResize: has('taskResize')\n ? toSwitch(options.taskResize, true, 'taskResize')\n : (previous?.taskResize ?? true),\n taskDragCreate: has('taskDragCreate')\n ? toSwitch(options.taskDragCreate, true, 'taskDragCreate')\n : (previous?.taskDragCreate ?? true),\n progressDrag: has('progressDrag')\n ? toSwitch(options.progressDrag, true, 'progressDrag')\n : (previous?.progressDrag ?? true),\n dependencyCreate: has('dependencyCreate')\n ? toSwitch(options.dependencyCreate, true, 'dependencyCreate')\n : (previous?.dependencyCreate ?? true),\n };\n}\n\ntype CallbackOption =\n | 'validateChange'\n | 'onSelectionChange'\n | 'taskMenuItems'\n | 'timeAxisMenuItems'\n | 'createTaskId'\n | 'onPresetChange'\n | 'onListWidthChange';\n\nfunction toCallback<K extends CallbackOption>(value: unknown, name: K): GanttOptions[K] {\n if (value === undefined || value === null) return undefined;\n if (typeof value !== 'function') throw new QuartzioError(`Gantt options: \"${name}\" must be a function.`);\n return value as GanttOptions[K];\n}\n\n/** Behaviour switches that don't change how anything looks. */\ninterface Behaviour {\n taskTooltip: boolean;\n cellEdit: boolean;\n undoRedo: boolean;\n multiSelect: boolean;\n deleteKey: boolean;\n taskMenu: boolean;\n timeAxisMenu: boolean;\n taskEdit: boolean;\n validateChange: GanttOptions['validateChange'];\n onSelectionChange: GanttOptions['onSelectionChange'];\n taskMenuItems: GanttOptions['taskMenuItems'];\n timeAxisMenuItems: GanttOptions['timeAxisMenuItems'];\n createTaskId: GanttOptions['createTaskId'];\n onPresetChange: GanttOptions['onPresetChange'];\n onListWidthChange: GanttOptions['onListWidthChange'];\n}\n\nfunction resolveBehaviour(options: GanttOptions, previous?: Behaviour): Behaviour {\n const has = (key: keyof GanttOptions) => previous === undefined || key in options;\n return {\n taskTooltip: has('taskTooltip')\n ? toSwitch(options.taskTooltip, true, 'taskTooltip')\n : (previous?.taskTooltip ?? true),\n cellEdit: has('cellEdit') ? toSwitch(options.cellEdit, true, 'cellEdit') : (previous?.cellEdit ?? true),\n undoRedo: has('undoRedo') ? toSwitch(options.undoRedo, true, 'undoRedo') : (previous?.undoRedo ?? true),\n multiSelect: has('multiSelect')\n ? toSwitch(options.multiSelect, true, 'multiSelect')\n : (previous?.multiSelect ?? true),\n deleteKey: has('deleteKey')\n ? toSwitch(options.deleteKey, true, 'deleteKey')\n : (previous?.deleteKey ?? true),\n validateChange: has('validateChange')\n ? toCallback(options.validateChange, 'validateChange')\n : previous?.validateChange,\n onSelectionChange: has('onSelectionChange')\n ? toCallback(options.onSelectionChange, 'onSelectionChange')\n : previous?.onSelectionChange,\n taskMenu: has('taskMenu') ? toSwitch(options.taskMenu, true, 'taskMenu') : (previous?.taskMenu ?? true),\n timeAxisMenu: has('timeAxisMenu')\n ? toSwitch(options.timeAxisMenu, true, 'timeAxisMenu')\n : (previous?.timeAxisMenu ?? true),\n taskEdit: has('taskEdit') ? toSwitch(options.taskEdit, true, 'taskEdit') : (previous?.taskEdit ?? true),\n taskMenuItems: has('taskMenuItems')\n ? toCallback(options.taskMenuItems, 'taskMenuItems')\n : previous?.taskMenuItems,\n timeAxisMenuItems: has('timeAxisMenuItems')\n ? toCallback(options.timeAxisMenuItems, 'timeAxisMenuItems')\n : previous?.timeAxisMenuItems,\n createTaskId: has('createTaskId')\n ? toCallback(options.createTaskId, 'createTaskId')\n : previous?.createTaskId,\n onPresetChange: has('onPresetChange')\n ? toCallback(options.onPresetChange, 'onPresetChange')\n : previous?.onPresetChange,\n onListWidthChange: has('onListWidthChange')\n ? toCallback(options.onListWidthChange, 'onListWidthChange')\n : previous?.onListWidthChange,\n };\n}\n\nconst sameView = (a: ViewOptions, b: ViewOptions) =>\n a.taskDrag === b.taskDrag &&\n a.taskResize === b.taskResize &&\n a.taskDragCreate === b.taskDragCreate &&\n a.progressDrag === b.progressDrag &&\n a.dependencyCreate === b.dependencyCreate &&\n a.showToday === b.showToday &&\n a.showNonWorkingTime === b.showNonWorkingTime &&\n a.timeline === b.timeline &&\n a.columns === b.columns &&\n a.rowHeight === b.rowHeight &&\n a.headerRowHeight === b.headerRowHeight;\n\nexport function createGantt(options: GanttOptions = {}): GanttController {\n let view = resolveViewOptions(options);\n let behaviour = resolveBehaviour(options);\n const controlled = 'data' in options;\n // Scheduling writes computed dates back into the data.\n const project = createProject({}, { propagate: scheduleProject });\n const initialPatch = project.load((controlled ? options.data : options.defaultData) ?? {});\n const history = createHistory();\n // Changes are recorded after they're committed, so the history in the state is brought up to date then.\n const syncHistory = (): void => {\n if (!batching && !destroyed && state.history !== history.state())\n setState({ ...state, history: history.state() });\n };\n const binding = createDataBinding(project, controlled, options.data, options.onChange, initialPatch, {\n confirm(actions) {\n if (!behaviour.undoRedo) return;\n history.confirm(actions);\n syncHistory();\n },\n clear() {\n history.clear();\n syncHistory();\n },\n });\n const timelineView = createTimelineView();\n const rowsView = createRowsView();\n const dependencyView = createDependencyView();\n const nonWorkingView = createNonWorkingView();\n const changes = createEmitter<ViewState>();\n let collapsed: ReadonlySet<Id> = new Set();\n let selection: Selection = NO_SELECTION;\n let menu: MenuState | null = null;\n // Where the renderer should scroll to (after zooming, or to show a new task); new object each time.\n let scrollTo: ScrollRequest | null = null;\n // A zoom overrides the preset option until the option changes (compared by value).\n let zoomed = false;\n let presetOption: unknown = options.preset;\n const listWidth = createListWidth(toListWidth(options.listWidth), view.columns.state.totalWidth);\n // A task just added from the menu: selected, shown and opened for editing once it's in the data.\n let added: Id | null = null;\n let reveal: Id | null = null;\n // Its name is opened once the rows show it (after the state is derived).\n let editAdded: Id | null = null;\n const openAdded = (): void => {\n const id = editAdded;\n editAdded = null;\n if (id !== null) editor.start(id, 'name');\n };\n // The selection last reported through onSelectionChange.\n let announced = selection.ids;\n // A press in the timeline that is a click as long as the pointer stays within the tolerance.\n let press: { origin: TimelinePoint; id: Id | null; modifiers: KeyModifiers } | null = null;\n let visible: VisibleRows | undefined;\n let collapsedVersion = 0;\n let destroyed = false;\n // True while setOptions applies several changes, so they produce one state update instead of several.\n let batching = false;\n\n // The pointer over the timeline (for the tooltip), and the tooltip it shows.\n let hoverPoint: TimelinePoint | null = null;\n let tooltip: TaskTooltip | null = null;\n let editorView: EditorView | undefined;\n\n // The bar being dragged (a preview), and the task of every visible row (for hit testing).\n let shownInteraction: TaskInteraction | null = null;\n let interactionView: InteractionView | undefined;\n // Created after the first state (it reads the view), so derive can't use it yet on that first call.\n const interactionRef: { current?: Interaction } = {};\n\n let todayCache: { axis: TimeAxis; line: TodayLine } | undefined;\n const todayOn = (axis: TimeAxis): TodayLine | null => {\n const now = Date.now();\n if (!view.showToday || now < axis.start || now >= axis.end) return null;\n // Whole pixels, and the same object while on the same pixel, so the line doesn't re-render on every update.\n const x = Math.round(axis.dateToX(now));\n if (todayCache?.axis !== axis || todayCache.line.x !== x) todayCache = { axis, line: { time: now, x } };\n return todayCache.line;\n };\n\n // Deriving never throws: options are validated up front, and oversized ranges are cut short.\n const derive = (viewport: Viewport, projectState: ProjectState): ViewState => {\n const timeAxis = timelineView.axisFor(projectState, viewport.width, view.timeline);\n const { rows, rowIndex, rowIds } = rowsView.rowsFor({\n project: projectState,\n collapsed,\n collapsedVersion,\n viewport,\n rowHeight: view.rowHeight,\n columns: view.columns,\n locale: view.timeline.locale,\n timeAxis,\n selection,\n });\n visible = { rowIds, rowIndex, tree: getTreeIndex(projectState.tasks) };\n if (reveal !== null) {\n const index = rowIndex.get(reveal);\n const top = index === undefined ? null : revealTopOf(index, viewport, rows.rowHeight);\n if (top !== null) scrollTo = { top };\n reveal = null;\n }\n if (menu?.kind === 'task' && !projectState.tasks.byId.has(menu.taskId as Id)) menu = null;\n editorView = {\n ...visible,\n project: projectState,\n columns: view.columns,\n dateField: dateKind(timeAxis.preset.timeResolution.unit),\n };\n const tooltipView = {\n project: projectState,\n timeAxis,\n rows,\n rowIds,\n viewport,\n locale: view.timeline.locale,\n };\n tooltip =\n hoverPoint && behaviour.taskTooltip && !shownInteraction\n ? tooltipFor(tooltipView, hoverPoint, tooltip)\n : null;\n const next: ViewState = {\n viewport,\n project: projectState,\n timeAxis,\n header: timelineView.headerFor(timeAxis, viewport, view.headerRowHeight),\n columns: view.columns.state,\n rows,\n dependencies: dependencyView.linesFor({\n project: projectState,\n timeAxis,\n rows,\n rowIndex,\n }),\n today: todayOn(timeAxis),\n nonWorkingTime: nonWorkingView.spansFor(projectState, timeAxis, viewport, view.showNonWorkingTime),\n interaction: shownInteraction,\n interactions: view.interactions,\n history: history.state(),\n selection: selection.ids,\n activeId: selection.active,\n tooltip,\n editing: editor.current(editorView),\n menu,\n taskEditor: taskEditor.current(editorView),\n scrollTo,\n list: listWidth.state(),\n };\n interactionView = {\n project: projectState,\n timeAxis,\n rows,\n rowIndex,\n rowIds,\n viewport,\n locale: view.timeline.locale,\n enabled: {\n drag: view.taskDrag,\n resize: view.taskResize,\n create: view.taskDragCreate,\n progress: view.progressDrag,\n link: view.dependencyCreate,\n },\n // Read when asked, so a validator set later (or one closing over newer app state) is the one used.\n validate: (change) => (behaviour.validateChange ? behaviour.validateChange(change) : true),\n };\n // A drag on a stale basis (another axis, a changed or hidden task, options turned off) is dropped before\n // anything shows it.\n if (interactionRef.current && !interactionRef.current.keep(interactionView)) {\n shownInteraction = null;\n return { ...next, interaction: null };\n }\n if (shownInteraction) tooltip = null;\n return next;\n };\n\n const editor = createCellEditor({\n view: () => editorView as EditorView,\n enabled: () => behaviour.cellEdit,\n plan: (fn) => project.plan(fn),\n commit(fn) {\n changing(() => binding.transact(fn));\n },\n validate: (change) => (behaviour.validateChange ? behaviour.validateChange(change) : true),\n show: () => {\n if (!batching && !destroyed) refresh();\n },\n focusRow(id) {\n selection = selection.set.has(id)\n ? selectionOf(selection, selection.ids, id, selection.anchor)\n : selectionOf(selection, [id], id, id);\n },\n });\n\n const taskEditor = createTaskEditor({\n view: () => editorView as EditorView,\n enabled: () => behaviour.taskEdit,\n plan: (fn) => project.plan(fn),\n commit(fn) {\n changing(() => binding.transact(fn));\n },\n show: () => {\n if (!batching && !destroyed) refresh();\n },\n });\n\n let state = derive(INITIAL_VIEWPORT, project.getState());\n\n const drags = createInteraction({\n view: () => interactionView as InteractionView,\n show(next) {\n shownInteraction = next;\n setState({ ...state, interaction: next, tooltip: next ? null : state.tooltip });\n },\n commit(fn) {\n try {\n changing(() => binding.transact(fn));\n } catch (error) {\n // Expected: the data rejecting the change (a dependency cycle can't come from a drop, but a date the\n // data doesn't accept could). Nothing changes and the bar goes back; a pointer handler must not throw.\n if (!(error instanceof QuartzioError)) throw error;\n }\n },\n });\n interactionRef.current = drags;\n\n const setState = (next: ViewState): void => {\n state = next;\n changes.emit(state);\n };\n const refresh = (): void => {\n setState(derive(state.viewport, project.getState()));\n };\n\n const unsubscribeProject = project.subscribe(({ state: projectState }) => {\n pruneCollapsed(projectState);\n selection = pruneSelection(selection, projectState.tasks.byId);\n const arrived = added !== null && projectState.tasks.byId.has(added) ? added : null;\n added = null; // in this change, or not coming (the app didn't take it)\n if (arrived !== null) {\n selection = selectionOf(selection, [arrived], arrived, arrived);\n reveal = arrived;\n }\n // Reported once the change is complete (see announce), not in the middle of committing it.\n if (arrived !== null) editAdded = arrived;\n if (!batching) {\n setState(derive(state.viewport, projectState));\n openAdded();\n }\n });\n\n /**\n * Reports a changed selection. Called once an action is done (the data change reported and recorded), so an\n * app callback that throws or changes things again can't leave a change half done.\n */\n const announce = (): void => {\n if (selection.ids === announced || destroyed) return;\n const same =\n selection.ids.length === announced.length && selection.ids.every((id, i) => id === announced[i]);\n announced = selection.ids;\n if (!same) behaviour.onSelectionChange?.(announced);\n };\n\n /** Runs a data change, then reports what it did to the selection (deleted tasks drop out). */\n const changing = <T>(fn: () => T): T => {\n const result = fn();\n announce();\n return result;\n };\n\n const setSelection = (next: Selection): void => {\n if (next === selection) return;\n selection = next;\n refresh();\n announce();\n };\n\n const visibleRows = (): VisibleRows => visible as VisibleRows;\n\n /**\n * Saves an open edit whose field is no longer there to take the keys and presses (its row scrolled out of the\n * rendered window, say); a value that can't be saved is dropped, as on blur.\n */\n const closeEdit = (): void => {\n if (!state.editing) return;\n if (!editor.commit()) editor.cancel();\n };\n\n const parentOf = (id: Id): Id | null => state.project.tasks.byId.get(id)?.parentId ?? null;\n\n const menuContext = (target: MenuTarget): MenuContext => ({\n target,\n task: target.kind === 'task' ? (state.project.tasks.byId.get(target.id) ?? null) : null,\n selection: selection.ids,\n preset: view.timeline.preset,\n });\n\n /** A change from the task menu; the data refusing it changes nothing. */\n const changeFromMenu = (fn: (tx: Transaction) => void): void => {\n try {\n changing(() => binding.transact(fn));\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n added = null;\n }\n };\n\n const expand = (ids: readonly Id[]): void => {\n if (ids.some((id) => collapsed.has(id)))\n setCollapsed(new Set([...collapsed].filter((id) => !ids.includes(id))));\n };\n\n const runTaskAction = (id: TaskMenuItemId, taskId: Id): void => {\n const task = state.project.tasks.byId.get(taskId);\n if (!task) return;\n const targets = targetsOf(taskId, selection.ids, getTreeIndex(state.project.tasks));\n const add = (where: AddWhere) => {\n // A subtask of a collapsed parent would be hidden.\n if (where === 'subtask') expand([taskId]);\n changeFromMenu((tx) => {\n added = addTask(tx, task, where, behaviour.createTaskId?.());\n });\n };\n switch (id) {\n case 'edit':\n controller.openTaskEditor(taskId);\n return;\n case 'addTaskAbove': {\n add('above');\n return;\n }\n case 'addTaskBelow': {\n add('below');\n return;\n }\n case 'addSubtask': {\n add('subtask');\n return;\n }\n case 'addMilestone': {\n add('milestone');\n return;\n }\n case 'addSuccessor': {\n add('successor');\n return;\n }\n case 'addPredecessor': {\n add('predecessor');\n return;\n }\n case 'indent': {\n let parents: Id[] = [];\n const { tasks, dependencies } = state.project;\n changeFromMenu((tx) => {\n parents = indent(tx, targets, getTreeIndex(tasks), dependencies.byId.values());\n });\n expand(parents); // so the indented tasks stay in view\n return;\n }\n case 'outdent': {\n changeFromMenu((tx) => {\n outdent(tx, targets);\n });\n return;\n }\n case 'convertToMilestone': {\n changeFromMenu((tx) => {\n tx.tasks.update(taskId, { duration: 0 });\n });\n return;\n }\n case 'delete':\n removeTasks(targets);\n }\n };\n\n /** Undo or redo. If the data refuses it, the history no longer matches the data and is dropped. */\n const replay = (operations: readonly Operation[], action: HistoryAction): boolean => {\n try {\n binding.apply(operations, () => action);\n return true;\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n history.clear();\n syncHistory();\n return false;\n }\n };\n\n const removeTasks = (ids: readonly Id[]): void => {\n try {\n changing(() =>\n binding.transact((tx) => {\n for (const id of ids) tx.tasks.remove(id);\n }),\n );\n } catch (error) {\n if (!(error instanceof QuartzioError)) throw error;\n }\n };\n\n const sameSet = (a: ReadonlySet<Id>, b: ReadonlySet<Id>) =>\n a.size === b.size && [...a].every((id) => b.has(id));\n\n const setCollapsed = (next: ReadonlySet<Id>): void => {\n if (sameSet(next, collapsed)) return;\n collapsed = next;\n collapsedVersion++;\n refresh();\n // A cursor hidden by collapsing moves to the parent that hides it, so it stays in view.\n const shown = visibleRowOf(selection.active, visibleRows());\n const shownId = shown === undefined ? undefined : visibleRows().rowIds[shown];\n if (shownId !== undefined && shownId !== selection.active) {\n setSelection(selectionOf(selection, selection.ids, shownId, shownId));\n }\n };\n\n /** Forgets collapsed tasks that were removed or lost their children, so they start expanded if reused. */\n const pruneCollapsed = (projectState: ProjectState): void => {\n if (collapsed.size === 0) return;\n const tree = getTreeIndex(projectState.tasks);\n const kept = new Set([...collapsed].filter((id) => !tree.isLeaf(id)));\n if (kept.size !== collapsed.size) {\n collapsed = kept;\n collapsedVersion++;\n }\n };\n\n const controller: GanttController = {\n getState: () => state,\n subscribe: (listener) => {\n binding.start(); // a renderer took this controller into use: report the initial scheduling\n return changes.subscribe(listener);\n },\n\n setOptions(next) {\n if (destroyed) return;\n // Validate everything first, so an invalid option changes nothing.\n // The same preset as before on a zoomed chart (e.g. the same prop on the next render) keeps the zoom.\n const keepZoom = zoomed && 'preset' in next && isEqual(next.preset, presetOption);\n const { preset: _preset, ...withoutPreset } = next;\n const effective = keepZoom ? withoutPreset : next;\n const nextView = VIEW_KEYS.some((key) => key in effective) ? resolveViewOptions(effective, view) : view;\n const nextBehaviour = resolveBehaviour(next, behaviour);\n const nextListWidth = 'listWidth' in next ? toListWidth(next.listWidth) : undefined;\n const before = project.getState();\n\n const previousView = view;\n view = nextView;\n batching = true;\n try {\n if (controlled && 'data' in next) {\n binding.setData(next.data);\n // A task added from the menu comes with the next data, or not at all (the app didn't take it).\n added = null;\n }\n } catch (error) {\n view = previousView;\n throw error;\n } finally {\n batching = false;\n }\n if ('onChange' in next) binding.setOnChange(next.onChange);\n behaviour = nextBehaviour;\n if ('preset' in next && !keepZoom) {\n zoomed = false;\n presetOption = next.preset;\n }\n if (menu && !(menu.kind === 'task' ? behaviour.taskMenu : behaviour.timeAxisMenu)) menu = null;\n if (!behaviour.undoRedo) history.clear();\n if (nextListWidth !== undefined) listWidth.setOption(nextListWidth);\n if (nextView.columns !== previousView.columns)\n listWidth.setColumnsWidth(nextView.columns.state.totalWidth);\n // Recomputed from scratch: the texts depend on the options (locale, columns).\n if (!sameView(nextView, previousView)) tooltip = null;\n if (!behaviour.multiSelect && selection.ids.length > 1) {\n const last = selection.ids.at(-1) as Id;\n selection = selectionOf(selection, [last], selection.active, last);\n }\n if (\n !sameView(nextView, previousView) ||\n project.getState() !== before ||\n state.history !== history.state() ||\n state.selection !== selection.ids ||\n (state.tooltip !== null && !behaviour.taskTooltip) ||\n (state.editing !== null && !behaviour.cellEdit) ||\n state.menu !== menu ||\n state.list !== listWidth.state() ||\n (state.taskEditor !== null && !behaviour.taskEdit)\n ) {\n refresh();\n }\n openAdded();\n announce();\n },\n\n setViewport(patch) {\n if (destroyed) return;\n const viewport = { ...state.viewport, ...patch };\n const current = state.viewport;\n if (\n viewport.width === current.width &&\n viewport.height === current.height &&\n viewport.scrollLeft === current.scrollLeft &&\n viewport.scrollTop === current.scrollTop\n ) {\n return;\n }\n // What's under a still pointer changes while scrolling; the tooltip goes until it moves again.\n if (viewport.scrollLeft !== current.scrollLeft || viewport.scrollTop !== current.scrollTop) menu = null;\n if (viewport.scrollLeft !== current.scrollLeft || viewport.scrollTop !== current.scrollTop)\n hoverPoint = null;\n setState(derive(viewport, state.project));\n // A drag follows the pointer to what's under it now (this is how auto-scrolling moves it).\n drags.follow();\n },\n\n transact(fn) {\n if (destroyed) return null;\n return changing(() => binding.transact(fn));\n },\n\n undo() {\n const patch = destroyed || !behaviour.undoRedo || binding.awaiting() ? undefined : history.undoable();\n if (!patch) return false;\n return changing(() => replay(patch.inverse, { type: 'undo', patch }));\n },\n\n redo() {\n const patch = destroyed || !behaviour.undoRedo || binding.awaiting() ? undefined : history.redoable();\n if (!patch) return false;\n return changing(() => replay(patch.operations, { type: 'redo', patch }));\n },\n\n hitTest: (point) => (destroyed ? null : drags.hitTest(point)),\n pointerDown(point, modifiers) {\n if (destroyed || !Number.isFinite(point.x) || !Number.isFinite(point.y)) return false;\n const index = Math.floor(point.y / state.rows.rowHeight);\n closeEdit();\n if (menu) {\n menu = null;\n refresh();\n }\n press = { origin: point, id: visibleRows().rowIds[index] ?? null, modifiers: modifiersOf(modifiers) };\n if (hoverPoint) {\n hoverPoint = null;\n refresh();\n }\n drags.pointerDown(point);\n return true;\n },\n pointerMove(point) {\n if (destroyed) return;\n if (press && Math.hypot(point.x - press.origin.x, point.y - press.origin.y) >= CLICK_TOLERANCE)\n press = null;\n drags.pointerMove(point);\n },\n pointerUp(point) {\n if (destroyed) return;\n const click = press;\n press = null;\n drags.pointerUp(point);\n if (!click) return;\n // Below the rows: a plain click clears the selection, as in a file list.\n if (click.id === null) {\n if (!click.modifiers.ctrl && !click.modifiers.meta && !click.modifiers.shift) {\n setSelection(selectionOf(selection, [], selection.active, selection.anchor));\n }\n return;\n }\n setSelection(clickRow(selection, click.id, click.modifiers, visibleRows(), behaviour.multiSelect));\n },\n cancelInteraction() {\n press = null;\n return !destroyed && drags.cancel();\n },\n\n rowClick(id, modifiers) {\n if (destroyed) return;\n setSelection(clickRow(selection, id, modifiersOf(modifiers), visibleRows(), behaviour.multiSelect));\n },\n\n select(ids) {\n if (destroyed || !Array.isArray(ids)) return;\n setSelection(selectIds(selection, ids, state.project.tasks.byId, behaviour.multiSelect));\n },\n\n clearSelection() {\n if (destroyed) return;\n setSelection(selectionOf(selection, [], selection.active, selection.anchor));\n },\n\n keyDown(input) {\n // Checked, as it comes straight from DOM events (or plain JavaScript).\n if (destroyed || typeof (input as unknown) !== 'object' || (input as unknown) === null) return false;\n closeEdit();\n const height = state.viewport.height > 0 ? state.viewport.height : UNMEASURED_HEIGHT;\n const command = keyCommand(input, {\n ...visibleRows(),\n selection,\n collapsed,\n pageRows: Math.floor(height / state.rows.rowHeight),\n multiSelect: behaviour.multiSelect,\n deleteKey: behaviour.deleteKey,\n undoRedo: behaviour.undoRedo,\n cellEdit: behaviour.cellEdit,\n });\n if (!command) return false;\n switch (command.type) {\n case 'select':\n setSelection(command.selection);\n return true;\n case 'expand':\n controller.setExpanded(command.id, command.expanded);\n return true;\n case 'delete':\n removeTasks(command.ids);\n setSelection(command.selection);\n return true;\n case 'undo':\n return controller.undo();\n case 'redo':\n return controller.redo();\n case 'menu':\n return controller.openMenu({ kind: 'task', id: command.id });\n case 'edit': {\n const started = editor.start(command.id);\n announce(); // the cursor may have moved\n return started;\n }\n }\n },\n\n hover(point) {\n if (destroyed) return;\n const next = point && Number.isFinite(point.x) && Number.isFinite(point.y) ? point : null;\n if (next === null && hoverPoint === null) return;\n hoverPoint = next;\n const shown =\n next && behaviour.taskTooltip && !shownInteraction && interactionView\n ? tooltipFor(interactionView, next, tooltip)\n : null;\n tooltip = shown;\n if (shown !== state.tooltip) setState({ ...state, tooltip: shown });\n },\n\n startEdit(id, columnId) {\n if (destroyed) return false;\n const started = editor.start(id, columnId);\n announce(); // the cursor may have moved\n return started;\n },\n editInput(text) {\n if (!destroyed) editor.input(text);\n },\n editKeyDown(key) {\n if (destroyed) return false;\n const used = editor.keyDown(key);\n announce(); // Tab may move the cursor\n return used;\n },\n commitEdit: () => !destroyed && editor.commit(),\n cancelEdit() {\n if (!destroyed) editor.cancel();\n },\n\n openMenu(target, point) {\n if (destroyed || typeof target !== 'object' || (target as unknown) === null) return false;\n // Opened during a press (Ctrl-click on macOS): that press is not a click or a drag.\n press = null;\n drags.cancel();\n const at = point && Number.isFinite(point.x) && Number.isFinite(point.y) ? point : null;\n let items: readonly MenuItem[];\n let y: number;\n if (target.kind === 'task') {\n const task = state.project.tasks.byId.get(target.id);\n if (!behaviour.taskMenu || !task) return false;\n // As in a file list: a row that isn't selected is selected alone; a selection that has it is kept.\n const id = task.id;\n selection = selection.set.has(id)\n ? selectionOf(selection, selection.ids, id, selection.anchor)\n : selectionOf(selection, [id], id, id);\n const tree = getTreeIndex(state.project.tasks);\n const targets = targetsOf(id, selection.ids, tree);\n const builtIn = taskMenuItems(task, targets, tree, parentOf, { edit: behaviour.taskEdit });\n items = customized(builtIn, behaviour.taskMenuItems, menuContext(target));\n const row = visibleRows().rowIndex.get(id) ?? 0;\n const { header, rows, viewport } = state;\n // Below the row, kept within the visible rows (the row may be scrolled out of view).\n const below = header.height + (row + 1) * rows.rowHeight - viewport.scrollTop;\n y = Math.max(header.height, Math.min(below, header.height + Math.max(viewport.height, 0)));\n } else if ((target.kind as unknown) === 'timeAxis') {\n if (!behaviour.timeAxisMenu) return false;\n const builtIn = timeAxisMenuItems(view.timeline.preset);\n items = customized(builtIn, behaviour.timeAxisMenuItems, menuContext(target));\n y = state.header.height;\n } else {\n return false;\n }\n if (items.length === 0) return false;\n menu = {\n kind: target.kind,\n taskId: target.kind === 'task' ? target.id : null,\n x: at?.x ?? KEYBOARD_MENU_X,\n y: at?.y ?? y,\n items,\n // Opened with the keyboard: the first item is ready to be picked.\n active: at ? null : (items.find((item) => item.disabled !== true)?.id ?? null),\n submenu: null,\n };\n refresh();\n announce();\n return true;\n },\n\n menuKeyDown(key) {\n if (destroyed || !menu || typeof key !== 'object' || (key as unknown) === null) return false;\n const result = menuKey(menu, key);\n if (!result) return false;\n if (result.pick !== undefined) {\n controller.menuAction(result.pick);\n return true;\n }\n menu = result.menu;\n refresh();\n return true;\n },\n\n menuHover(id) {\n if (destroyed || !menu) return;\n const next = menuHover(menu, id);\n if (next === menu) return;\n menu = next;\n refresh();\n },\n\n menuAction(id) {\n const open = menu;\n const item = open && !destroyed ? findItem(open.items, id) : undefined;\n if (!open || !item || item.disabled === true || item.items) return;\n menu = null;\n refresh();\n const target: MenuTarget =\n open.kind === 'task' ? { kind: 'task', id: open.taskId as Id } : { kind: 'timeAxis' };\n if (item.action) {\n item.action(menuContext(target));\n return;\n }\n if (target.kind === 'timeAxis') {\n if (id === 'zoomIn' || id === 'zoomOut') controller.zoom(id === 'zoomIn' ? 'in' : 'out');\n else if (id.startsWith('preset:')) controller.zoom(id.slice('preset:'.length));\n return;\n }\n runTaskAction(id as TaskMenuItemId, target.id);\n },\n\n closeMenu() {\n if (destroyed || !menu) return;\n menu = null;\n refresh();\n },\n\n zoom(target) {\n if (destroyed || typeof target !== 'string') return false;\n const current = view.timeline.preset;\n const next =\n target === 'in' || target === 'out'\n ? zoomStep(current, target)\n : VIEW_PRESETS.find((preset) => preset.id === target);\n if (!next || next === current || isEqual(next, current)) return false;\n const { width, scrollLeft } = state.viewport;\n const middle = width > 0 ? state.timeAxis.xToDate(scrollLeft + width / 2) : null;\n view = resolveViewOptions({ preset: next }, view);\n zoomed = true;\n tooltip = null;\n refresh();\n if (middle !== null) {\n // Keep what was in the middle of the view there.\n scrollTo = { left: Math.max(0, Math.round(state.timeAxis.dateToX(middle) - width / 2)) };\n setState({ ...state, scrollTo });\n }\n behaviour.onPresetChange?.(next.id);\n return true;\n },\n\n resizeList(action) {\n if (destroyed) return false;\n const result = listWidth.act(action);\n if (!result.used) return false;\n if (listWidth.state().resizing) {\n // Nothing else shows while the divider moves.\n menu = null;\n hoverPoint = null;\n tooltip = null;\n }\n if (state.list !== listWidth.state() || state.menu !== menu || state.tooltip !== tooltip)\n setState({ ...state, list: listWidth.state(), menu, tooltip });\n if (result.changed !== undefined) behaviour.onListWidthChange?.(result.changed);\n return true;\n },\n\n openTaskEditor(id) {\n if (destroyed) return false;\n closeEdit();\n menu = null;\n return taskEditor.open(id);\n },\n\n taskEditorAction(action) {\n if (destroyed) return false;\n const used = taskEditor.act(action);\n announce();\n return used;\n },\n\n doubleClick(point) {\n if (destroyed || !interactionView || !Number.isFinite(point.x) || !Number.isFinite(point.y))\n return false;\n const hit = barUnder(interactionView, point);\n return hit ? controller.openTaskEditor(hit.taskId) : false;\n },\n\n revealTop(id) {\n const index = destroyed ? undefined : visibleRows().rowIndex.get(id);\n return index === undefined ? null : revealTopOf(index, state.viewport, state.rows.rowHeight);\n },\n\n toggle(id) {\n if (destroyed || getTreeIndex(state.project.tasks).isLeaf(id)) return;\n const next = new Set(collapsed);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n setCollapsed(next);\n },\n\n setExpanded(id, expanded) {\n if (destroyed || getTreeIndex(state.project.tasks).isLeaf(id) || collapsed.has(id) !== expanded) return;\n const next = new Set(collapsed);\n if (expanded) next.delete(id);\n else next.add(id);\n setCollapsed(next);\n },\n\n expandAll() {\n if (destroyed) return;\n setCollapsed(new Set());\n },\n\n collapseAll() {\n if (destroyed) return;\n const tree = getTreeIndex(state.project.tasks);\n setCollapsed(new Set(state.project.tasks.order.filter((id) => !tree.isLeaf(id))));\n },\n\n destroy() {\n destroyed = true;\n binding.destroy();\n unsubscribeProject();\n changes.clear();\n },\n };\n return controller;\n}\n"],"mappings":";AAGA,MAAa,gBAAgB;AAC7B,MAAa,gBAAwB,KAAK;AAC1C,MAAa,cAAsB,KAAK;AACxC,MAAa,aAAqB,KAAK;;AAWvC,SAAgB,cAAc,MAAc,OAAe,KAAqB;CAC9E,MAAM,uBAAO,IAAI,KAAK,CAAC;CAEvB,KAAK,eAAe,MAAM,QAAQ,GAAG,GAAG;CACxC,OAAO,KAAK,MAAM,KAAK,QAAQ,IAAI,UAAU;AAC/C;AAEA,SAAgB,cAAc,MAAyB;CACrD,MAAM,uBAAO,IAAI,KAAK,OAAO,UAAU;CACvC,OAAO;EAAE,MAAM,KAAK,eAAe;EAAG,OAAO,KAAK,YAAY,IAAI;EAAG,KAAK,KAAK,WAAW;CAAE;AAC9F;;AAGA,SAAgB,gBAAgB,MAAsB;CAEpD,SAAU,OAAO,KAAK,IAAK,KAAK;AAClC;AAEA,SAAgB,YAAY,MAAc,OAAuB;CAC/D,OAAO,cAAc,MAAM,QAAQ,GAAG,CAAC,IAAI,cAAc,MAAM,OAAO,CAAC;AACzE;;;;;;;AC3BA,SAAgB,iBAAiB,MAAgB,UAAoC;CACnF,MAAM,MAAM,SAAS,cAAc;CACnC,MAAM,QAAQ,SAAS,eAAe;CACtC,QAAQ,MAAR;EACE,KAAK,eACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,QACH,OAAO;EACT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