Skip to content

Scheduling & resources

Calendar-aware scheduling

Tasks scheduled on a work calendar with split shifts and a plant closure: dependencies with lags, constraints, critical path, float, a status date, diagnostics and resource demand against capacity.

Live demoView on GitHub ↗

Calendar-aware schedule

JST · split shifts · 10 November plant closure

09 Nov 12:00
Projected finish
09 Nov 16:00
Zero-float tasks
3 / 4
Resource overload
1 resource-hour
Drag a cutting order or use its arrow keys; dashed outlines preview the operations that move with it. Link labels show lag; −2 h is a lead. Bar labels show work hours. Grey lines show the original plan. Split bars show work around breaks; red outlines mark the critical path, thin lines show float and the flag marks the dispatch cut-off.
100%
Operation
Finish (JST)
Float
09 Nov 08:0009 Nov 14:0009 Nov 20:0010 Nov 02:0010 Nov 08:0010 Nov 14:0010 Nov 20:0011 Nov 02:0011 Nov 08:0011 Nov 14:00
Mon 9 Nov · operating day
Tue 10 Nov · plant closed
Wed 11 Nov · operating day
Shift
Shift
Shift
Shift
Cut order ACNC cell · editable
09 Nov 11:00
0 h
Cut order BCNC cell · editable
09 Nov 12:00
3 h
Inspect order AInspection station
09 Nov 14:00
0 h
Pack order APacking station
09 Nov 16:00
0 h
Arrow keys move. Shift resizes the end. Alt resizes the start. Escape cancels.

Move either cutting order to recalculate the plan. Amber tasks have zero float. Amber links show controlling dependencies.

Resource demand and capacity

Demand uses work segments. Breaks and closed dates consume zero work.

Demand / available units · Amber indicates overload
Equipment
Calendar
Units
09 Nov 08:0009 Nov 14:0009 Nov 20:0010 Nov 02:0010 Nov 08:0010 Nov 14:0010 Nov 20:0011 Nov 02:0011 Nov 08:0011 Nov 14:00
Mon 9 Nov · operating day
Tue 10 Nov · plant closed
Wed 11 Nov · operating day
CNC cell
Plant shifts
1
Inspection station
Plant shifts
1
Packing station
Plant shifts
1
Arrow keys move. Shift resizes the end. Alt resizes the start. Escape cancels.
Overload intervals
EquipmentFromToDemand / capacityOperations
CNC cell09 Nov 10:0009 Nov 11:002 / 1Cut order A, Cut order B

Planning diagnostics

    • Capacity is reported here, not enforced: no leveling reason was recorded.

Drag the lower-right corner of the demo to change its height.

Source code

vue
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue'
import {
  GanttChart, NetworkGraph, buildWorkPeriods, calculateResourceLoad, createWorkingTimeScale, formatDependencyLag, invertWorkPeriods, propagateEdit, rescheduleFromStatusDate,
  scheduleTasks, scheduleToGraph, scheduledBarFields, toPlanningDiagnostics, timelineConstraints, timelineCsvTable, toCsv, toICalendar, toMsProjectXml,
  type ResourceAssignment, type ScheduleConstraintName, type ScheduleInput, type ScheduleLink, type ScheduleManualConflict, type ScheduleResult,
  type ScheduleTask, type ScheduledTask, type TimelineBar, type TimelineColumn, type TimelineConstraintEdit, type TimelineEdit,
} from '../src'
import { download } from './download'
import PlanningDiagnostics from './components/PlanningDiagnostics.vue'
import SummaryLinksDemo from './SummaryLinksDemo.vue'
import ActualsDemo from './ActualsDemo.vue'
import DemoPanel from './components/DemoPanel.vue'
import StatusLine from './components/StatusLine.vue'
import { hour } from './data'
import { useDemoLocale } from './i18n'

const { t, labels: componentLabels, isJapanese } = useDemoLocale()

const local = (value: string) => Date.parse(value + '+09:00')
const range = { start: local('2026-11-09T08:00:00'), end: local('2026-11-11T17:00:00') }
const shifts = buildWorkPeriods(range, {
  utcOffsetMinutes: 540,
  weekly: [1, 2, 3, 4, 5].flatMap(weekday => [
    { weekday, startMinute: 8 * 60, endMinute: 12 * 60 },
    { weekday, startMinute: 13 * 60, endMinute: 17 * 60 },
  ]),
  exceptions: { '2026-11-10': [] },
})
const calendars = [{ id: 'plant', periods: shifts }]
// Breaks, nights and the closed date, shaded behind both charts.
const nonWorking = invertWorkPeriods(shifts, range)
// A display-only due date: packing must finish before the dispatch cut-off or the bar is marked late.
const deadlines = new Map([['pack', local('2026-11-09T17:00:00')]])
const shade = ref(true)
// "Compress non-working time" swaps the linear axis for a working-time scale: working hours get twice the width and
// breaks, nights and the closure keep a tenth of it. Times, snapping and edits are unchanged; only x positions differ.
const compress = ref(false)
const workingScale = computed(() => compress.value ? createWorkingTimeScale(range, shifts, 36 / hour, 0.1) : undefined)
// "Summary task links" adds a separate, opt-in example of links to and from a summary task (GanttChart summaryDependencies).
const summaryLinks = ref(false)
// "Recorded actuals" adds a separate, opt-in example of rescheduling from recorded actual intervals (rescheduleFromActuals).
const recordedActuals = ref(false)
const showCritical = ref(true)
const originalTasks: ScheduleTask[] = [
  { id: 'cut-a', duration: 3 * hour },
  { id: 'cut-b', duration: 2 * hour, startNoEarlierThan: range.start + 2 * hour },
  { id: 'inspect', duration: 2 * hour },
  { id: 'pack', duration: 2 * hour },
]
// The chart draws these links and the scheduler uses them unchanged, lag included: a ScheduleLink is a
// TimelineDependency with a lag. Packing may overlap the last two hours of cutting order B (a lead, drawn as "−2 h").
const dependencies: ScheduleLink[] = [
  { id: 'cut-inspect', from: 'cut-a', to: 'inspect', type: 'FS' },
  { id: 'inspect-pack', from: 'inspect', to: 'pack', type: 'FS' },
  { id: 'cut-b-pack', from: 'cut-b', to: 'pack', type: 'FS', lag: -2 * hour },
]
const resources = [
  { id: 'cnc', label: t({ en: 'CNC cell', ja: 'CNC セル' }), capacity: 1, periods: shifts },
  { id: 'quality', label: t({ en: 'Inspection station', ja: '検査ステーション' }), capacity: 1, periods: shifts },
  { id: 'dispatch', label: t({ en: 'Packing station', ja: '梱包ステーション' }), capacity: 1, periods: shifts },
]
const assignments: ResourceAssignment[] = [
  { resourceId: 'cnc', taskId: 'cut-a' }, { resourceId: 'cnc', taskId: 'cut-b' },
  { resourceId: 'quality', taskId: 'inspect' }, { resourceId: 'dispatch', taskId: 'pack' },
]
const baseRows = [
  { id: 'cut-a', label: t({ en: 'Cut order A', ja: '切断オーダー A' }), detail: t({ en: 'CNC cell · editable', ja: 'CNC セル · 編集可' }) },
  { id: 'cut-b', label: t({ en: 'Cut order B', ja: '切断オーダー B' }), detail: t({ en: 'CNC cell · editable', ja: 'CNC セル · 編集可' }) },
  { id: 'inspect', label: t({ en: 'Inspect order A', ja: '検査オーダー A' }), detail: t({ en: 'Inspection station', ja: '検査ステーション' }) },
  { id: 'pack', label: t({ en: 'Pack order A', ja: '梱包オーダー A' }), detail: t({ en: 'Packing station', ja: '梱包ステーション' }) },
]
// Manual and inactive tasks, both off by default. "Schedule inspection manually" pins inspection at its planned dates
// with `ScheduleTask.manual`: links into it no longer move it, a link its dates break is listed as a manual conflict, and
// its bar can be moved or resized. "Cancel order B (inactive)" sets `inactive` on cutting order B: the scheduler, the
// load view and the network diagram leave it and its links out, and its bar stays as a placeholder at the dates it had.
const manualInspection = ref(false)
const orderBCancelled = ref(false)
// Placeholder dates of inactive tasks, which the scheduler no longer reports.
const parked = shallowRef(new Map<string, ScheduledTask>())
const rows = computed(() => baseRows.map(row => row.id === 'inspect' && manualInspection.value ? { ...row, detail: t({ en: 'Inspection · manual', ja: '検査 · 手動' }) }
  : row.id === 'cut-b' && orderBCancelled.value ? { ...row, detail: t({ en: 'CNC cell · inactive', ja: 'CNC セル · 無効' }) } : row))
const dates = new Intl.DateTimeFormat(isJapanese.value ? 'ja-JP' : 'en-GB', {
  timeZone: 'Asia/Tokyo', day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
})
const format = (time: number) => dates.format(time).replace(',', '')
const labels = new Map(baseRows.map(row => [row.id, row.label]))
const headerBands = [
  [
    { start: range.start, end: local('2026-11-10T00:00:00'), label: t({ en: 'Mon 9 Nov · operating day', ja: '11月9日(月)· 稼働日' }) },
    { start: local('2026-11-10T00:00:00'), end: local('2026-11-11T00:00:00'), label: t({ en: 'Tue 10 Nov · plant closed', ja: '11月10日(火)· 工場休業' }) },
    { start: local('2026-11-11T00:00:00'), end: range.end, label: t({ en: 'Wed 11 Nov · operating day', ja: '11月11日(水)· 稼働日' }) },
  ],
  shifts.map(period => ({ ...period, label: t({ en: 'Shift', ja: 'シフト' }) })),
]

function scheduleInput(tasks: readonly ScheduleTask[]): ScheduleInput {
  return { range, calendars, defaultCalendarId: 'plant', quantum: 60_000, tasks, dependencies }
}
function propose(tasks: readonly ScheduleTask[]): ScheduleResult {
  return scheduleTasks(scheduleInput(tasks))
}
const original = propose(originalTasks)
if (!original.ok) throw new Error('The demo schedule must be feasible')
const model = shallowRef({ tasks: originalTasks, plan: original })
const notice = ref(t({ en: 'Move either cutting order to recalculate the plan. Amber tasks have zero float. Amber links show controlling dependencies.', ja: 'どちらかの切断オーダーを動かすと計画を再計算します。琥珀色のタスクは余裕がゼロで、琥珀色のリンクは支配的な依存関係です。' }))
const selected = ref(new Set<string>())
const originalDates = new Map(original.tasks.map(task => [task.id, { start: task.start, end: task.end }]))
// A second saved baseline: the plan after a revision that held cutting order A back by one hour.
const revision = propose(originalTasks.map(task => task.id === 'cut-a' ? { ...task, startNoEarlierThan: range.start + hour } : task))
if (!revision.ok) throw new Error('The demo revision must be feasible')
const revisionDates = new Map(revision.tasks.map(task => [task.id, { start: task.start, end: task.end }]))
// Named baseline sets: off by default, so the chart shows the single original-plan baseline as before.
const compareBaselines = ref(false)
const baselineSets = [{ id: 'plan', label: t({ en: 'Original plan', ja: '当初計画' }) }, { id: 'rev1', label: t({ en: 'Revision 1', ja: '改訂 1' }) }]
const shownSets = ref(new Set(baselineSets.map(set => set.id)))
const baselineIds = computed(() => compareBaselines.value ? baselineSets.filter(set => shownSets.value.has(set.id)).map(set => set.id) : undefined)
const baselineLabel = (id: string) => baselineSets.find(set => set.id === id)?.label ?? id
const slotColours = ['var(--vw-baseline, #718497)', 'var(--vw-baseline-2, #9a4c95)', 'var(--vw-baseline-3, #23806f)']
function swatch(id: string) {
  const slot = baselineIds.value?.indexOf(id) ?? -1
  return slot < 0 ? 'transparent' : slotColours[slot]
}
function toggleSet(id: string, shown: boolean) {
  const next = new Set(shownSets.value)
  if (shown) next.add(id)
  else next.delete(id)
  shownSets.value = next
}
const byTask = computed(() => new Map(model.value.plan.tasks.map(task => [task.id, task])))
/** A task as drawn: its scheduled dates, or the placeholder dates of an inactive task. */
const shownTask = (id: string) => byTask.value.get(id) ?? parked.value.get(id)
const columns: TimelineColumn[] = [
  { id: 'finish', label: t({ en: 'Finish (JST)', ja: '終了(JST)' }), width: 106, value: row => format(shownTask(row.id)!.end) },
  // Manual tasks have no float (the scheduler reports 0 without making them critical), and inactive ones no dates.
  { id: 'float', label: t({ en: 'Float', ja: '余裕' }), width: 58, value: row => {
    const task = byTask.value.get(row.id)
    return !task ? t({ en: 'inactive', ja: '無効' }) : task.manual ? t({ en: 'manual', ja: '手動' }) : (task.totalFloat / hour) + t({ en: ' h', ja: ' 時間' })
  } },
]
const resourceColumns: TimelineColumn[] = [
  { id: 'calendar', label: t({ en: 'Calendar', ja: 'カレンダー' }), width: 106, value: () => t({ en: 'Plant shifts', ja: '工場のシフト' }) },
  { id: 'capacity', label: t({ en: 'Units', ja: '単位数' }), width: 58, value: row => resources.find(resource => resource.id === row.id)!.capacity },
]
const criticalLinks = computed(() => new Set(model.value.plan.criticalDependencyIds))
const workHours = new Map(originalTasks.map(task => [task.id, task.duration / hour]))
// scheduledBarFields supplies the dates, split work segments, critical flag and latest finish of each task.
// Reported progress at the status date: cutting order A is done, B is half done and inspection has started.
const reported = new Map([['cut-a', 1], ['cut-b', 0.5], ['inspect', 0.25]])
const statusDate = ref(local('2026-11-09T12:00:00'))
const showProgressLine = ref(true)
// Bars follow the task order. An inactive task keeps a pale outline bar at its placeholder dates, without critical,
// float or deadline overlays, and cannot be edited; a manual task is violet, has no float line and moves and resizes.
const taskBars = computed<TimelineBar[]>(() => originalTasks.flatMap(({ id }) => {
  const task = byTask.value.get(id)
  const placeholder = task ? undefined : parked.value.get(id)
  if (!task && !placeholder) return []
  const { critical, latestEnd, ...dates } = scheduledBarFields((task ?? placeholder)!)
  return [{
    id, rowId: id, label: labels.get(id)!, ...dates, progress: reported.get(id),
    ...(compareBaselines.value
      ? { baselines: [{ id: 'plan', ...originalDates.get(id)! }, { id: 'rev1', ...revisionDates.get(id)! }] }
      : { baseline: originalDates.get(id) }),
    editable: task !== undefined && (id.startsWith('cut-') || task.manual === true),
    tone: task?.critical ? 'amber' : task?.manual ? 'violet' : 'blue',
    ...(placeholder ? { appearance: 'outline' as const } : {}),
    // Screen readers hear the same cue as the colour and row detail.
    ...(placeholder ? { description: t({ en: 'Inactive: takes no part in the plan', ja: '無効: 計画に含まれません' }) }
      : task?.manual ? { description: t({ en: 'Manually scheduled: its links do not move it', ja: '手動スケジュール: リンクでは動きません' }) } : {}),
    ...(showCritical.value && task ? { critical, ...(task.manual ? {} : { latestEnd }), deadline: deadlines.get(id) } : {}),
    ...(showConstraints.value ? { constraints: timelineConstraints(taskById.value.get(id)) } : {}),
  }]
}))
// Scheduling constraints, off by default. Shown, packing must finish by the dispatch cut-off (a hard
// `finishNoLaterThan` that the scheduler applies, unlike the display-only deadline), and the requested starts of the
// cutting orders are `startNoEarlierThan` handles. Moving or deleting a handle reschedules the plan; a constraint that
// cannot be met is not applied, and the scheduler's diagnostic says why.
const showConstraints = ref(false)
const taskById = computed(() => new Map(model.value.tasks.map(task => [task.id, task])))
const constraintNames: Record<ScheduleConstraintName, string> = t({
  en: {
    range: 'the planning horizon', startNoEarlierThan: 'its start no earlier than', startNoLaterThan: 'its start no later than',
    finishNoEarlierThan: 'its finish no earlier than', finishNoLaterThan: 'its finish no later than', fixedStart: 'its fixed start',
    deadline: 'the project deadline', projectFinish: 'the project finish', calendar: 'its working time',
  },
  ja: {
    range: '計画期間', startNoEarlierThan: '指定日以降の開始', startNoLaterThan: '指定日以前の開始',
    finishNoEarlierThan: '指定日以降の終了', finishNoLaterThan: '指定日以前の終了', fixedStart: '固定の開始日',
    deadline: 'プロジェクトの期限', projectFinish: 'プロジェクトの完了', calendar: '稼働時間',
  },
})
const cycleText = t({ en: 'A dependency cycle prevents scheduling.', ja: '依存関係の循環があるため日程を計算できません。' })
function withConstraint(task: ScheduleTask, kind: TimelineConstraintEdit['kind'], time: number | undefined): ScheduleTask {
  const { [kind]: _previous, ...rest } = task
  return time === undefined ? rest : { ...rest, [kind]: time }
}
function infeasibility(plan: Exclude<ScheduleResult, { ok: true }>) {
  if (plan.code === 'cycle') return cycleText
  const links = plan.dependencyIds.map(id => dependencies.find(link => link.id === id)!)
    .map(link => labels.get(link.from) + ' → ' + labels.get(link.to))
  if (isJapanese.value) {
    return `実行不可能: ${labels.get(plan.taskId)} は${plan.constraints.map(name => constraintNames[name]).join('と')}を満たせません`
      + (links.length ? '(リンク ' + links.join('、') + ')' : '') + '。変更は適用していません。'
  }
  return `Infeasible: ${labels.get(plan.taskId)} cannot meet ${plan.constraints.map(name => constraintNames[name]).join(' and ')}`
    + (links.length ? ' with the link ' + links.join(', ') : '') + '. The change was not applied.'
}
function toggleConstraints(event: Event) {
  const input = event.target as HTMLInputElement
  const tasks = model.value.tasks.map(task => task.id === 'pack' ? withConstraint(task, 'finishNoLaterThan', input.checked ? deadlines.get('pack') : undefined) : task)
  const plan = propose(tasks)
  if (!plan.ok) {
    notice.value = infeasibility(plan)
    input.checked = showConstraints.value
    return
  }
  model.value = { tasks, plan }
  showConstraints.value = input.checked
}
function applyConstraint(change: TimelineConstraintEdit) {
  const tasks = model.value.tasks.map(task => task.id === change.id ? withConstraint(task, change.kind, change.after) : task)
  const plan = propose(tasks)
  if (!plan.ok) {
    notice.value = infeasibility(plan)
    return
  }
  model.value = { tasks, plan }
  notice.value = change.after === undefined
    ? t({ en: `Constraint removed from ${labels.get(change.id)}. Plan recalculated.`, ja: `${labels.get(change.id)} の制約を外しました。計画を再計算しました。` })
    : t({
      en: `${labels.get(change.id)}: ${constraintNames[change.kind].replace('its ', '')} ${format(change.after)}. Plan recalculated.`,
      ja: `${labels.get(change.id)}: ${constraintNames[change.kind]} ${format(change.after)}。計画を再計算しました。`,
    })
}
// The full assignment list is passed; the assignments of inactive tasks take no capacity.
const load = computed(() => calculateResourceLoad(range, model.value.plan.tasks, resources, assignments, { inactiveTaskIds: model.value.plan.inactiveTaskIds }))
const overloads = computed(() => load.value.filter(segment => segment.overload > 0))
// The same overloads as a structured diagnostic list; activating one shows its first operation in the chart above.
const diagnostics = computed(() => toPlanningDiagnostics(model.value.plan, load.value))
async function revealDiagnostic(diagnostic: { entities: readonly { kind: string; id: string }[] }) {
  const task = diagnostic.entities.find(entity => entity.kind === 'task')
  if (!task) return
  const result = await chart.value?.revealBar(task.id)
  const state = result && result.status !== 'revealed' ? ' (' + result.status + ')' : ''
  notice.value = t({ en: 'Showing ' + labels.get(task.id) + state + ' for the diagnostic.', ja: '診断に対応する ' + labels.get(task.id) + state + ' を表示しています。' })
}
const overloadHours = computed(() => overloads.value.reduce((hours, segment) => hours + (segment.end - segment.start) / hour, 0))
const loadBars = computed<TimelineBar[]>(() => load.value.filter(segment => segment.load > 0).map(segment => ({
  id: segment.resourceId + ':' + segment.start, rowId: segment.resourceId,
  start: segment.start, end: segment.end, label: segment.load + ' / ' + segment.capacity,
  tone: segment.overload ? 'amber' : 'teal',
})))
const criticalCount = computed(() => model.value.plan.tasks.filter(task => task.critical).length)

function validateEdit(change: TimelineEdit) {
  // A manual task's dates are whatever the planner sets, so its bar can also be resized.
  if (taskById.value.get(change.id)?.manual) return
  if (change.mode !== 'move') return t({ en: 'Move the bar to change the requested start. Working duration is fixed in this example.', ja: 'バーを動かして希望開始日を変えてください。この例では作業時間は固定です。' })
}
/** A requested start inside a break or a closed day begins at the next working time, as the scheduler places it. */
function nextWorkingTime(time: number) {
  const period = shifts.find(item => item.end > time)
  return period ? Math.max(time, period.start) : time
}
// Auto-scheduling preview. While a cutting order is dragged (or moved with the arrow keys), propagateEdit pins it at
// the new start and reports every operation whose dates change; the chart draws those as dashed outlines and proposes
// them with the move as one batch. The order is first pinned where it is now, so the changes are measured against the
// plan on screen. An infeasible move previews nothing and is reported when the edit is applied.
// A manual task needs no pin: propagateEdit moves its manual dates to the proposed interval as they are, in breaks too,
// and a resize sets their end. Its successors follow; its predecessors stay, and a link it now breaks is a conflict.
function cascade(change: TimelineEdit): TimelineEdit[] {
  const current = byTask.value.get(change.id)
  if (!current || (change.mode !== 'move' && !current.manual)) return []
  const tasks = current.manual ? model.value.tasks
    : model.value.tasks.map(task => task.id === change.id ? { ...task, startNoEarlierThan: undefined, fixedStart: current.start } : task)
  const result = propagateEdit(scheduleInput(tasks), current.manual
    ? { id: change.id, start: change.after.start, end: change.after.end }
    : { id: change.id, start: nextWorkingTime(change.after.start) })
  if (!result.ok) return []
  return result.changes.filter(item => item.id !== change.id)
    .map(item => ({ id: item.id, before: item.before, after: item.after, mode: 'move', source: change.source }))
}
// The batch lists the moved order first. Recalculating from its new requested start (or manual dates) reproduces the
// cascaded dates.
function applyEdits(changes: TimelineEdit[]) {
  applyEdit(changes[0]!)
}
function applyEdit(change: TimelineEdit) {
  const tasks = model.value.tasks.map(task => task.id !== change.id ? task
    : task.manual ? { ...task, manual: { start: change.after.start, end: change.after.end } } : { ...task, startNoEarlierThan: change.after.start })
  const plan = propose(tasks)
  if (!plan.ok) {
    notice.value = plan.code === 'cycle' ? cycleText : t({ en: 'The edit would exceed the available shifts for ' + labels.get(plan.taskId) + '.', ja: 'この編集では ' + labels.get(plan.taskId) + ' が使えるシフトを超えます。' })
    return
  }
  const previous = byTask.value
  const affected = plan.tasks.filter(task => task.id !== change.id
    && (task.start !== previous.get(task.id)!.start || task.end !== previous.get(task.id)!.end)).length
  model.value = { tasks, plan }
  notice.value = t({ en: 'Plan recalculated. ' + affected + ' other operation' + (affected === 1 ? '' : 's') + ' changed.', ja: '計画を再計算しました。ほかの工程が ' + affected + ' 件変わりました。' }) + conflictCount(plan)
}
const chart = ref<InstanceType<typeof GanttChart>>()
function exportSchedule() {
  const svg = chart.value?.exportSvg({ title: t({ en: 'Calendar-aware schedule', ja: 'カレンダーを考慮した日程' }), rowHeading: t({ en: 'Operation', ja: '工程' }) })
  if (!svg) return
  download(svg, 'schedule.svg')
  notice.value = t({ en: 'Exported schedule SVG (' + svg.length + ' characters).', ja: '日程を SVG に出力しました(' + svg.length + ' 文字)。' })
}
function reset() {
  // With constraints shown, packing keeps its cut-off; the original plan meets it, so the plan is the same.
  const tasks = showConstraints.value
    ? originalTasks.map(task => task.id === 'pack' ? withConstraint(task, 'finishNoLaterThan', deadlines.get('pack')) : task) : originalTasks
  const plan = showConstraints.value ? propose(tasks) : original
  if (!plan.ok) throw new Error('The demo schedule must be feasible')
  model.value = { tasks, plan }
  // The original tasks are neither manual nor inactive, so both options are turned off.
  manualInspection.value = false
  orderBCancelled.value = false
  parked.value = new Map()
  selected.value = new Set()
  notice.value = t({ en: 'Original plan restored.', ja: '当初計画に戻しました。' })
}
/** Schedules changed tasks for one of the options; an infeasible result is reported and changes nothing. */
function replan(tasks: ScheduleTask[]) {
  const plan = propose(tasks)
  if (!plan.ok) {
    notice.value = infeasibility(plan)
    return undefined
  }
  model.value = { tasks, plan }
  return plan
}
// Like the constraint option, both options recalculate the plan from the requested starts, so a status-date
// rescheduling is replaced by the plan it started from.
function toggleManualInspection(event: Event) {
  const input = event.target as HTMLInputElement
  const current = byTask.value.get('inspect')!
  const plan = replan(model.value.tasks.map(task => {
    if (task.id !== 'inspect') return task
    if (input.checked) return { ...task, manual: { start: current.start, end: current.end } }
    const { manual: _manual, ...rest } = task
    return rest
  }))
  if (!plan) {
    input.checked = manualInspection.value
    return
  }
  manualInspection.value = input.checked
  notice.value = (input.checked
    ? t({
      en: `Inspect order A is scheduled manually at ${format(current.start)}–${format(current.end)}. Its links no longer move it; move or resize its bar.`,
      ja: `検査オーダー A を ${format(current.start)}–${format(current.end)} に手動で固定しました。リンクでは動かなくなります。バーを動かすか伸縮してください。`,
    })
    : t({ en: 'Inspect order A is scheduled automatically again. Plan recalculated.', ja: '検査オーダー A を自動スケジュールに戻しました。計画を再計算しました。' })) + conflictCount(plan)
}
function toggleOrderB(event: Event) {
  const input = event.target as HTMLInputElement
  const current = byTask.value.get('cut-b')
  const plan = replan(model.value.tasks.map(task => {
    if (task.id !== 'cut-b') return task
    if (input.checked) return { ...task, inactive: true }
    const { inactive: _inactive, ...rest } = task
    return rest
  }))
  if (!plan) {
    input.checked = orderBCancelled.value
    return
  }
  parked.value = input.checked && current ? new Map([['cut-b', current]]) : new Map()
  orderBCancelled.value = input.checked
  notice.value = (input.checked
    ? t({ en: 'Cut order B is inactive: it no longer drives packing or loads the CNC cell. Plan recalculated.', ja: '切断オーダー B を無効にしました。梱包を左右せず、CNC セルの負荷にもなりません。計画を再計算しました。' })
    : t({ en: 'Cut order B is active again. Plan recalculated.', ja: '切断オーダー B を有効に戻しました。計画を再計算しました。' })) + conflictCount(plan)
}
// Links into a manual task bind nothing; the scheduler lists each one that the manual dates break.
const manualConflicts = computed(() => model.value.plan.manualConflicts ?? [])
function conflictCount(plan: ScheduleResult) {
  const count = plan.ok ? plan.manualConflicts?.length ?? 0 : 0
  return count ? t({ en: ` ${count} manual date conflict${count === 1 ? '' : 's'}.`, ja: `手動の日程の競合が ${count} 件あります。` }) : ''
}
function dependencyLabel(id: string) {
  const link = dependencies.find(item => item.id === id)
  return link ? `${labels.get(link.from)} → ${labels.get(link.to)}` : id
}
const endpoints = { FS: ['starts', 'finishes'], SS: ['starts', 'starts'], FF: ['finishes', 'finishes'], SF: ['finishes', 'starts'] } as const
function describeConflict(conflict: ScheduleManualConflict) {
  const link = dependencies.find(item => item.id === conflict.dependencyId)!
  const [own, other] = endpoints[link.type ?? 'FS']
  if (isJapanese.value) {
    const word = (verb: string) => verb === 'starts' ? '開始' : '終了'
    const lag = link.lag ? `(ラグ ${formatDependencyLag(link.lag)})` : ''
    return `${labels.get(conflict.taskId)} の${word(own)}が ${labels.get(link.from)} の${word(other)}${lag}より前です(リンク ${labels.get(link.from)} → ${labels.get(link.to)})`
  }
  const lag = link.lag ? ` with a lag of ${formatDependencyLag(link.lag)}` : ''
  return `${labels.get(conflict.taskId)} ${own} before ${labels.get(link.from)} ${other}${lag} (link ${labels.get(link.from)} → ${labels.get(link.to)})`
}
// The chart leaves out the links of inactive tasks, as the scheduler and the network diagram do. Without inactive
// tasks it gets the same array as before.
const chartDependencies = computed(() => orderBCancelled.value ? dependencies.filter(link => link.from !== 'cut-b' && link.to !== 'cut-b') : dependencies)
const barHours = (id: string) => {
  const task = byTask.value.get(id)
  // Manual dates set the elapsed span, so the work in them can differ from the planned duration.
  return task?.manual ? task.work.reduce((sum, part) => sum + part.end - part.start, 0) / hour : workHours.get(id)
}
// Done work stays where it is, partly done work is split at the status date and unstarted work moves after it. The
// next edit recalculates the plan from the requested starts again.
function rescheduleFromStatus() {
  let plan: ScheduleResult
  try {
    plan = rescheduleFromStatusDate(scheduleInput(model.value.tasks), statusDate.value, reported)
  } catch (error) {
    // Reported progress that cannot fit before the status date (for example at the start of the range) throws a
    // RangeError; the current plan stays as it is.
    if (!(error instanceof RangeError)) throw error
    notice.value = t({ en: `The reported progress does not fit before status date ${format(statusDate.value)}. Choose a later status date.`, ja: `報告された進捗が状況日付 ${format(statusDate.value)} より前に収まりません。もっと後の状況日付を選んでください。` })
    return
  }
  if (!plan.ok) {
    notice.value = plan.code === 'cycle' ? cycleText : t({ en: 'The status date leaves no room for ' + labels.get(plan.taskId) + '.', ja: 'この状況日付では ' + labels.get(plan.taskId) + ' の入る余地がありません。' })
    return
  }
  const previous = byTask.value
  const moved = plan.tasks.filter(task => task.start !== previous.get(task.id)!.start || task.end !== previous.get(task.id)!.end).length
  model.value = { tasks: model.value.tasks, plan }
  notice.value = t({ en: `Rescheduled from status date ${format(statusDate.value)}. ${moved} operation${moved === 1 ? '' : 's'} moved.`, ja: `状況日付 ${format(statusDate.value)} から再計算しました。${moved} 件の工程が動きました。` })
}
// Interchange exports of the current plan. The times are written in JST for Microsoft Project and in UTC for iCalendar.
// Microsoft Project has fields for both options, so an inactive task is written at its placeholder dates with `Active`
// 0, and links are kept (Microsoft Project ignores those of inactive tasks too). Every task is already written as
// manually scheduled so that Microsoft Project keeps the dates without the plant calendar; `manual: true` only states it.
function exportMsProject() {
  const tasks = originalTasks.flatMap(({ id }) => {
    const task = shownTask(id)
    return task ? [{ task, inactive: !byTask.value.has(id) }] : []
  })
  const xml = toMsProjectXml({
    name: t({ en: 'Calendar-aware schedule', ja: 'カレンダーを考慮した日程' }),
    tasks: tasks.map(({ task, inactive }) => ({
      id: task.id, name: labels.get(task.id)!, start: task.start, end: task.end, percentComplete: (reported.get(task.id) ?? 0) * 100,
      // Microsoft Project numbers baselines: the original plan is Baseline (0) and the revision Baseline1.
      baselines: [{ number: 0, ...originalDates.get(task.id)! }, { number: 1, ...revisionDates.get(task.id)! }],
      // A task with exactly one constraint gets its ConstraintType and ConstraintDate.
      ...(showConstraints.value ? { constraints: timelineConstraints(taskById.value.get(task.id)) } : {}),
      ...(inactive ? { inactive: true } : {}),
      ...(task.manual ? { manual: true } : {}),
    })),
    dependencies: dependencies.map(link => ({ from: link.from, to: link.to, type: link.type, lag: link.lag })),
  }, { utcOffsetMinutes: 540 })
  download(new Blob([xml], { type: 'application/xml' }), 'schedule.xml')
  notice.value = t({ en: 'Exported Microsoft Project XML with ' + tasks.length + ' tasks.', ja: 'タスク ' + tasks.length + ' 件を Microsoft Project XML に出力しました。' })
}
// iCalendar lists what will happen, so an inactive task, which the plan leaves out, has no event; a manual task is an
// event like any other, and its description says it is manual.
function exportICalendar() {
  const text = toICalendar(model.value.plan.tasks.map(task => ({
    id: task.id + '@vue-weave.example', summary: labels.get(task.id)!, start: task.start, end: task.end,
    description: rows.value.find(row => row.id === task.id)!.detail,
  })), { calendarName: t({ en: 'Calendar-aware schedule', ja: 'カレンダーを考慮した日程' }) })
  download(new Blob([text], { type: 'text/calendar' }), 'schedule.ics')
  notice.value = t({ en: 'Exported iCalendar with ' + model.value.plan.tasks.length + ' events.', ja: '予定 ' + model.value.plan.tasks.length + ' 件を iCalendar に出力しました。' })
}
// The CSV lists the chart as drawn, inactive placeholders included. With either option on, a Scheduling column says
// whether each task is automatic, manual or inactive; without them the file is unchanged.
function exportCsv() {
  const table = timelineCsvTable(rows.value, taskBars.value, { formatTime: format, headers: { row: t({ en: 'Operation', ja: '工程' }), bar: t({ en: 'Task', ja: 'タスク' }) } })
  const mode = (label: unknown) => {
    const id = baseRows.find(row => row.label === label)!.id
    const task = byTask.value.get(id)
    return !task ? t({ en: 'Inactive', ja: '無効' }) : task.manual ? t({ en: 'Manual', ja: '手動' }) : t({ en: 'Auto', ja: '自動' })
  }
  const text = toCsv(manualInspection.value || orderBCancelled.value
    ? table.map((record, index) => [...record, index ? mode(record[0]) : t({ en: 'Scheduling', ja: 'スケジュール方式' })]) : table)
  download(new Blob([text], { type: 'text/csv' }), 'schedule.csv')
  notice.value = t({ en: 'Exported CSV with ' + taskBars.value.length + ' tasks.', ja: 'タスク ' + taskBars.value.length + ' 件を CSV に出力しました。' })
}
// The network diagram shows the same plan as a PERT chart; critical tasks and the links between them are highlighted.
// scheduleToGraph leaves out inactive tasks and their links, so it gets the full dependency list.
const showNetwork = ref(false)
// Japanese node details for scheduleToGraph; English pages keep its defaults (ES, EF, Float and hours).
const pertText = isJapanese.value
  ? { labels: { earlyStart: '最早開始', earlyFinish: '最早終了', float: '余裕' }, formatDuration: (value: number) => value / hour + ' 時間' }
  : {}
const network = computed(() => scheduleToGraph(model.value.plan, dependencies, { label: id => labels.get(id)!, formatTime: format, ...pertText }))
</script>

<template>
  <DemoPanel class="schedule-panel" title-id="schedule-title" :title="t({ en: 'Calendar-aware schedule', ja: 'カレンダーを考慮した日程' })" :subtitle="t({ en: 'JST · split shifts · 10 November plant closure', ja: 'JST · 分割シフト · 11月10日は工場休業' })">
    <template #options>
      <label><input v-model="shade" type="checkbox"> {{ t({ en: 'Shade non-working time', ja: '非稼働時間に網掛け' }) }}</label>
      <label><input v-model="compress" type="checkbox"> {{ t({ en: 'Compress non-working time', ja: '非稼働時間を圧縮' }) }}</label>
      <label><input v-model="showCritical" type="checkbox"> {{ t({ en: 'Show critical path and float', ja: 'クリティカルパスと余裕を表示' }) }}</label>
      <label><input v-model="showNetwork" type="checkbox"> {{ t({ en: 'Network diagram', ja: 'ネットワーク図' }) }}</label>
      <label><input v-model="compareBaselines" type="checkbox"> {{ t({ en: 'Compare baseline sets', ja: 'ベースラインを比較' }) }}</label>
      <label><input type="checkbox" :checked="showConstraints" @change="toggleConstraints"> {{ t({ en: 'Show scheduling constraints', ja: 'スケジュールの制約を表示' }) }}</label>
      <label><input type="checkbox" :checked="manualInspection" @change="toggleManualInspection"> {{ t({ en: 'Schedule inspection manually', ja: '検査を手動でスケジュール' }) }}</label>
      <label><input type="checkbox" :checked="orderBCancelled" @change="toggleOrderB"> {{ t({ en: 'Cancel order B (inactive)', ja: 'オーダー B を取り消す(無効)' }) }}</label>
      <label><input v-model="summaryLinks" type="checkbox"> {{ t({ en: 'Summary task links', ja: '集計タスクのリンク' }) }}</label>
      <label><input v-model="recordedActuals" type="checkbox"> {{ t({ en: 'Recorded actuals', ja: '記録された実績' }) }}</label>
      <button type="button" @click="exportSchedule">{{ t({ en: 'Export schedule SVG', ja: '日程を SVG で出力' }) }}</button>
      <button type="button" @click="reset">{{ t({ en: 'Reset schedule', ja: '日程をリセット' }) }}</button>
    </template>
    <div class="options status-options" role="group" :aria-label="t({ en: 'Status date and exports', ja: '状況日付と出力' })">
      <label>{{ t({ en: 'Status date', ja: '状況日付' }) }} <input v-model.number="statusDate" type="range" :min="range.start" :max="range.end" :step="hour"
        :aria-valuetext="format(statusDate)"></label>
      <output :aria-label="t({ en: 'Status date value', ja: '状況日付の値' })">{{ format(statusDate) }}</output>
      <label><input v-model="showProgressLine" type="checkbox"> {{ t({ en: 'Show progress line', ja: 'イナズマ線を表示' }) }}</label>
      <button type="button" @click="rescheduleFromStatus">{{ t({ en: 'Reschedule from status date', ja: '状況日付から再計算' }) }}</button>
      <button type="button" @click="exportMsProject">{{ t({ en: 'Export MS Project XML', ja: 'MS Project XML で出力' }) }}</button>
      <button type="button" @click="exportICalendar">{{ t({ en: 'Export iCalendar', ja: 'iCalendar で出力' }) }}</button>
      <button type="button" @click="exportCsv">{{ t({ en: 'Export CSV', ja: 'CSV で出力' }) }}</button>
    </div>
    <div v-if="compareBaselines" class="options status-options" role="group" :aria-label="t({ en: 'Baseline sets', ja: 'ベースライン' })">
      <label v-for="set in baselineSets" :key="set.id" class="baseline-key" :style="{ '--baseline-key': swatch(set.id) }">
        <input type="checkbox" :checked="shownSets.has(set.id)" @change="toggleSet(set.id, ($event.target as HTMLInputElement).checked)">
        {{ set.label }}</label>
      <span class="hint">{{ t({ en: `Strips under each bar, in this order. Hover a strip, or read a bar's description, for its variance.`, ja: '各バーの下にこの順で帯を表示します。差異は帯にポインターを合わせるか、バーの説明で確認できます。' }) }}</span>
    </div>
    <p v-if="showConstraints" class="hint constraint-hint">{{ t({
      en: `Packing must finish by the 17:00 cut-off. Drag a cutting order's start constraint, or focus it and use the arrow keys or Delete; the plan is rescheduled, and a constraint that cannot be met is reported.`,
      ja: '梱包は 17:00 の締め切りまでに終える必要があります。切断オーダーの開始制約をドラッグするか、フォーカスして矢印キーか Delete を使うと計画を再計算し、満たせない制約は報告します。',
    }) }}</p>
    <dl class="schedule-metrics">
      <div><dt>{{ t({ en: 'Projected finish', ja: '完了予測' }) }}</dt><dd data-testid="schedule-finish">{{ format(model.plan.finish) }}</dd></div>
      <div><dt>{{ t({ en: 'Zero-float tasks', ja: '余裕ゼロのタスク' }) }}</dt><dd>{{ criticalCount }} / {{ model.plan.tasks.length }}</dd></div>
      <div><dt>{{ t({ en: 'Resource overload', ja: 'リソースの過負荷' }) }}</dt><dd data-testid="schedule-overload">{{ t({ en: `${overloadHours} resource-hour${overloadHours === 1 ? '' : 's'}`, ja: `${overloadHours} リソース時間` }) }}</dd></div>
    </dl>
    <GanttChart @background-click="selected = new Set()" ref="chart" :rows="rows" :bars="taskBars" :range="range" :dependencies="chartDependencies" :highlighted-dependency-ids="criticalLinks"
      :columns="columns" :header-bands="headerBands" :row-height="58" :height="325" :pixels-per-unit="18 / hour" :scale="workingScale"
      :tick-steps="[4 * hour, 6 * hour, 12 * hour]" :snap="hour" :format-time="format" :selected-ids="selected"
      :non-working-periods="shade ? nonWorking : undefined" :validate-edit="validateEdit" :cascade="cascade" @select="selected = new Set([$event])"
      :status-date="statusDate" :show-progress-line="showProgressLine" :baseline-ids="baselineIds" :baseline-label="baselineLabel"
      :constraints-editable="showConstraints" @constraint-edit="applyConstraint" :labels="componentLabels.gantt"
      @edit="applyEdit" @edits="applyEdits" @edit-rejected="(_change, reason) => notice = reason" @edits-rejected="(_changes, reason) => notice = reason">
      <template #row-heading>{{ t({ en: 'Operation', ja: '工程' }) }}</template>
      <template #bar="{ bar }"><span class="vw-bar-text">{{ barHours(bar.id) }}{{ t({ en: ' h', ja: ' 時間' }) }}</span></template>
      <template #legend><span class="hint">{{ t({ en: 'Drag a cutting order or use its arrow keys; dashed outlines preview the operations that move with it. Link labels show lag; −2 h is a lead. Bar labels show work hours. Grey lines show the original plan. Split bars show work around breaks; red outlines mark the critical path, thin lines show float and the flag marks the dispatch cut-off.', ja: '切断オーダーをドラッグするか矢印キーで動かすと、一緒に動く工程を破線でプレビューします。リンクのラベルはラグで、−2 h はリードです。バーのラベルは作業時間、灰色の線は当初計画です。分割されたバーは休憩をまたぐ作業、赤い枠はクリティカルパス、細い線は余裕、旗は出荷の締め切りを示します。' }) }}<template
        v-if="manualInspection">{{ t({ en: ' The violet bar keeps its manual dates: move or resize it, and links into it are checked instead of moving it.', ja: '紫のバーは手動の日程を保ちます。動かしたり伸縮したりでき、入ってくるリンクはバーを動かさずに検査します。' }) }}</template><template
        v-if="orderBCancelled">{{ t({ en: ' The pale bar is inactive and takes no part in the plan.', ja: '淡いバーは無効で、計画に含まれません。' }) }}</template></span></template>
    </GanttChart>
    <StatusLine>{{ notice }}</StatusLine>
    <section v-if="manualInspection" class="manual-conflicts" aria-labelledby="manual-conflicts-title">
      <h3 id="manual-conflicts-title">{{ t({ en: 'Manual date conflicts', ja: '手動の日程の競合' }) }}</h3>
      <ul v-if="manualConflicts.length">
        <li v-for="conflict in manualConflicts" :key="conflict.dependencyId">{{ describeConflict(conflict) }}</li>
      </ul>
      <p v-else>{{ t({ en: 'None: the manual dates meet every link into them.', ja: 'なし: 手動の日程は入ってくるすべてのリンクを満たしています。' }) }}</p>
    </section>
    <NetworkGraph v-if="showNetwork" :nodes="network.nodes" :edges="network.edges" :related-ids="network.criticalNodeIds"
      :options="{ nodeWidth: 300, nodeHeight: 58 }" :height="300" :labels="{ ...componentLabels.graph, region: t({ en: 'Schedule network diagram', ja: '日程のネットワーク図' }) }" />
  </DemoPanel>
  <DemoPanel title-id="load-title" :title="t({ en: 'Resource demand and capacity', ja: 'リソースの需要と能力' })" :subtitle="t({ en: 'Demand uses work segments. Breaks and closed dates consume zero work.', ja: '需要は作業区間から計算します。休憩と休業日は作業を消費しません。' })">
    <GanttChart :rows="resources" :bars="loadBars" :range="range" :columns="resourceColumns" :header-bands="[headerBands[0]!]"
      :row-height="48" :height="213" :pixels-per-unit="18 / hour" :tick-steps="[4 * hour, 6 * hour, 12 * hour]" :scale="workingScale"
      :format-time="format" :non-working-periods="shade ? nonWorking : undefined" readonly :show-controls="false" :labels="componentLabels.gantt">
      <template #row-heading>{{ t({ en: 'Equipment', ja: '設備' }) }}</template>
      <template #legend><span class="hint">{{ t({ en: 'Demand / available units · Amber indicates overload', ja: '需要 / 利用可能な単位数 · 琥珀色は過負荷' }) }}</span></template>
    </GanttChart>
    <table v-if="overloads.length" class="load-table">
      <caption>{{ t({ en: 'Overload intervals', ja: '過負荷の区間' }) }}</caption>
      <thead><tr><th scope="col">{{ t({ en: 'Equipment', ja: '設備' }) }}</th><th scope="col">{{ t({ en: 'From', ja: '開始' }) }}</th><th scope="col">{{ t({ en: 'To', ja: '終了' }) }}</th><th scope="col">{{ t({ en: 'Demand / capacity', ja: '需要 / 能力' }) }}</th><th scope="col">{{ t({ en: 'Operations', ja: '工程' }) }}</th></tr></thead>
      <tbody><tr v-for="segment in overloads" :key="segment.resourceId + ':' + segment.start">
        <td>{{ resources.find(resource => resource.id === segment.resourceId)?.label }}</td>
        <td>{{ format(segment.start) }}</td><td>{{ format(segment.end) }}</td>
        <td>{{ segment.load }} / {{ segment.capacity }}</td>
        <td>{{ segment.taskIds.map(id => labels.get(id)).join(', ') }}</td>
      </tr></tbody>
    </table>
    <p v-else class="status">{{ t({ en: 'No capacity conflicts in the current plan.', ja: '現在の計画に能力の競合はありません。' }) }}</p>
    <PlanningDiagnostics v-if="diagnostics.length" :diagnostics="diagnostics" :task-label="id => labels.get(id) ?? id"
      :resource-label="id => resources.find(resource => resource.id === id)?.label ?? id" :dependency-label="dependencyLabel" :format-time="format" @activate="revealDiagnostic" />
  </DemoPanel>
  <SummaryLinksDemo v-if="summaryLinks" />
  <ActualsDemo v-if="recordedActuals" />
</template>

<style scoped>
/* Ten toggles do not fit beside the title: the toggles move below it and wrap instead of squeezing each label. */
.schedule-panel :deep(.section-head) { flex-wrap: wrap; }
.schedule-panel :deep(.section-head > .options) { flex-wrap: wrap; gap: 8px 16px; }
.status-options { flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }
.status-options input[type="range"] { vertical-align: middle; width: 180px; }
/* Legend swatches in the colour of the slot each shown set is drawn in. */
.constraint-hint { margin: 0 0 8px; }
.baseline-key::after { content: ''; display: inline-block; width: 18px; height: 3px; border-radius: 1.5px; background: var(--baseline-key); }
.manual-conflicts { margin: 8px 0 0; padding: 4px 0 4px 10px; border-inline-start: 4px solid #b07400; font-size: 12px; }
.manual-conflicts h3 { margin: 0 0 4px; font-size: 13px; }
.manual-conflicts ul { margin: 0; padding-inline-start: 18px; }
.manual-conflicts p { margin: 0; color: var(--vw-muted, #4f6574); }
</style>
vue
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue'
import {
  GanttChart, scheduleTasks, scheduledBarFields, type ScheduleLink, type ScheduleResult, type ScheduleTask, type TimelineBar,
  type TimelineConnection, type TimelineEdit, type TimelineReconnect, type TimelineRow,
} from '../src'
import { formatTime, hour, origin } from './data'
import { download } from './download'
import DemoPanel from './components/DemoPanel.vue'
import StatusLine from './components/StatusLine.vue'
import { unusedNumber } from './ids'
import { useDemoLocale } from './i18n'

const { t, labels: componentLabels } = useDemoLocale()

// Opt-in example of GanttChart `summaryDependencies`: links into and out of a summary task are drawn to the edges of its
// rollup bar. The plan uses `ScheduleTask.parentId`, so the scheduler and the chart read the same links unchanged.
const range = { start: origin, end: origin + 12 * hour }
const rows: TimelineRow[] = [
  { id: 'design', label: t({ en: 'Design review', ja: '設計レビュー' }) },
  { id: 'build', label: t({ en: 'Build phase', ja: '製作フェーズ' }) },
  { id: 'frame', label: t({ en: 'Frame', ja: 'フレーム' }), parentId: 'build' },
  { id: 'wiring', label: t({ en: 'Wiring', ja: '配線' }), parentId: 'build' },
  { id: 'inspect', label: t({ en: 'Final inspection', ja: '最終検査' }) },
]
const labels = new Map(rows.map(row => [row.id, row.label]))
const summaryIds = new Set(rows.flatMap(row => row.parentId === undefined ? [] : [row.parentId]))
const initialTasks: ScheduleTask[] = [
  { id: 'design', duration: 2 * hour },
  { id: 'build', duration: 0 },
  { id: 'frame', duration: 3 * hour, parentId: 'build' },
  { id: 'wiring', duration: hour, parentId: 'build' },
  { id: 'inspect', duration: hour },
]
const initialLinks: ScheduleLink[] = [
  { id: 'design-build', from: 'design', to: 'build', type: 'FS' },
  { id: 'build-inspect', from: 'build', to: 'inspect', type: 'FS' },
]

/** Schedule a proposal; an Error (such as an FF link into a summary) or a failed result is returned as a reason. */
function plan(tasks: readonly ScheduleTask[], links: readonly ScheduleLink[]): ScheduleResult | string {
  try {
    const result = scheduleTasks({ range, quantum: 15 * 60_000, tasks, dependencies: links })
    return result.ok ? result : result.code === 'cycle' ? t({ en: 'This link would create a cycle.', ja: 'このリンクは循環を生みます。' }) : t({ en: 'The plan no longer fits the horizon.', ja: '計画が計画期間に収まらなくなります。' })
  } catch (error) {
    return error instanceof Error ? error.message : String(error)
  }
}
type Model = { tasks: readonly ScheduleTask[]; links: readonly ScheduleLink[]; plan: ScheduleResult & { ok: true } }
const model = shallowRef<Model>({ tasks: initialTasks, links: initialLinks, plan: plan(initialTasks, initialLinks) as Model['plan'] })
const selectedDependency = ref<string>()
const chart = ref<InstanceType<typeof GanttChart>>()
const notice = ref(t({ en: 'Links end at the Build phase rollup bar. Drag a link handle onto the rollup bar to add one; Frame and Wiring move it.', ja: 'リンクは製作フェーズの集計バーで終わります。リンクのハンドルを集計バーへドラッグすると追加でき、フレームと配線が集計バーを動かします。' }))

const bars = computed<TimelineBar[]>(() => model.value.plan.tasks.filter(task => !task.summary).map(task => ({
  id: task.id, rowId: task.id, label: labels.get(task.id)!, editable: true, ...scheduledBarFields(task),
})))
const critical = computed(() => new Set(model.value.plan.criticalDependencyIds))
const name = (id: string) => labels.get(id) ?? id

function accept(tasks: readonly ScheduleTask[], links: readonly ScheduleLink[], message: string) {
  const result = plan(tasks, links)
  if (typeof result === 'string' || !result.ok) return
  model.value = { tasks, links, plan: result }
  notice.value = message
}
// FF and SF links cannot end at a summary task: the scheduler throws for them, so they are rejected before they are proposed.
function validateConnection(connection: TimelineConnection, replacing?: string) {
  if (summaryIds.has(connection.to) && (connection.type === 'FF' || connection.type === 'SF')) {
    return t({
      en: `A ${connection.type} link cannot end at the summary ${name(connection.to)}. Link to the subtask that should finish instead.`,
      ja: `${connection.type} リンクは集計タスク ${name(connection.to)} で終われません。代わりに、終わるべきサブタスクにつないでください。`,
    })
  }
  if (model.value.links.some(link => link.id !== replacing && link.from === connection.from && link.to === connection.to)) return t({ en: 'These tasks are already linked.', ja: 'これらのタスクはすでにつながっています。' })
  const links = replacing ? model.value.links.map(link => link.id === replacing ? { ...link, ...connection } : link) : [...model.value.links, { id: 'new', ...connection }]
  const result = plan(model.value.tasks, links)
  return typeof result === 'string' ? result : undefined
}
function connect(connection: TimelineConnection) {
  const number = unusedNumber(model.value.links, 'link-', model.value.links.length + 1)
  accept(model.value.tasks, [...model.value.links, { id: 'link-' + number, ...connection }],
    t({ en: `Added ${connection.type} link from ${name(connection.from)} to ${name(connection.to)}.`, ja: `${name(connection.from)} から ${name(connection.to)} への ${connection.type} リンクを追加しました。` }))
}
function reconnect(change: TimelineReconnect) {
  accept(model.value.tasks, model.value.links.map(link => link.id === change.id ? { ...link, ...change.after } : link),
    t({ en: `Reconnected ${name(change.after.from)} → ${name(change.after.to)} ${change.after.type}.`, ja: `${name(change.after.from)} → ${name(change.after.to)} ${change.after.type} につなぎ替えました。` }))
}
function removeLink(id: string) {
  selectedDependency.value = undefined
  accept(model.value.tasks, model.value.links.filter(link => link.id !== id), t({ en: 'Deleted link ' + id + '.', ja: 'リンク ' + id + ' を削除しました。' }))
}
// Moving a subtask requests a new start; the plan is recalculated and the rollup bar and its links follow.
function moved(change: TimelineEdit) {
  return model.value.tasks.map(task => task.id === change.id ? { ...task, startNoEarlierThan: change.after.start } : task)
}
function validateEdit(change: TimelineEdit) {
  if (change.mode !== 'move') return t({ en: 'Move a task to change its requested start.', ja: 'タスクを動かして希望開始日を変えてください。' })
  const result = plan(moved(change), model.value.links)
  return typeof result === 'string' ? result : undefined
}
function edit(change: TimelineEdit) {
  accept(moved(change), model.value.links, t({ en: `${name(change.id)} requested from ${formatTime(change.after.start)}.`, ja: `${name(change.id)} の開始を ${formatTime(change.after.start)} 以降に指定しました。` }))
  const build = model.value.plan.tasks.find(task => task.id === 'build')
  if (build) notice.value += t({ en: ` Build phase ${formatTime(build.start)}–${formatTime(build.end)}.`, ja: `製作フェーズ ${formatTime(build.start)}–${formatTime(build.end)}。` })
}
function reset() {
  model.value = { tasks: initialTasks, links: initialLinks, plan: plan(initialTasks, initialLinks) as Model['plan'] }
  selectedDependency.value = undefined
  notice.value = t({ en: 'Summary link example reset.', ja: '集計リンクの例を初期状態に戻しました。' })
}
function exportLinks() {
  const svg = chart.value?.exportSvg({ title: t({ en: 'Summary task links', ja: '集計タスクのリンク' }), rowHeading: t({ en: 'Task', ja: 'タスク' }) })
  if (!svg) return
  download(svg, 'summary-links.svg')
  const lines = svg.match(/<path d="[^"]+" fill="none" stroke="[^"]+" stroke-width="[^"]+" marker-end=/g)?.length ?? 0
  notice.value = t({ en: `Exported summary links SVG with ${lines} dependency lines.`, ja: `依存関係の線 ${lines} 本を含む SVG を出力しました。` })
}
</script>

<template>
  <DemoPanel title-id="summary-links-title" :title="t({ en: 'Summary task links', ja: '集計タスクのリンク' })" :subtitle="t({ en: 'summaryDependencies · links drawn to the rollup bar of a summary task · UTC', ja: 'summaryDependencies · 集計タスクの集計バーへ描くリンク · UTC' })">
    <template #options>
      <button type="button" @click="exportLinks">{{ t({ en: 'Export summary links SVG', ja: '集計リンクを SVG で出力' }) }}</button>
      <button type="button" @click="reset">{{ t({ en: 'Reset summary links', ja: '集計リンクをリセット' }) }}</button>
    </template>
    <GanttChart ref="chart" :rows="rows" :bars="bars" :range="range" :dependencies="model.links" :format-time="formatTime"
      :pixels-per-unit="70 / hour" :tick-steps="[hour, 2 * hour]" :row-height="52" :height="330" :snap="15 * 60_000"
      show-summaries summary-dependencies connectable reconnectable :highlighted-dependency-ids="critical"
      v-model:selected-dependency-id="selectedDependency" :labels="{ ...componentLabels.gantt, region: t({ en: 'Summary task links timeline', ja: '集計タスクのリンクのタイムライン' }) }"
      :validate-connection="validateConnection" :validate-edit="validateEdit"
      @connect="connect" @reconnect="reconnect" @dependency-delete="removeLink" @edit="edit"
      @connect-rejected="(_connection, reason) => notice = reason" @edit-rejected="(_change, reason) => notice = reason"
      @dependency-select="id => notice = t({ en: 'Selected link ' + id + '. Press Delete to remove it.', ja: 'リンク ' + id + ' を選択しました。Delete で削除します。' })">
      <template #row-heading>{{ t({ en: 'Task', ja: 'タスク' }) }}</template>
      <template #legend><span class="hint">{{ t({ en: 'Amber links are critical. FF and SF links into the summary are rejected, as the scheduler rejects them.', ja: '琥珀色のリンクはクリティカルです。集計タスクに入る FF と SF のリンクは、スケジューラーと同じく却下します。' }) }}</span></template>
    </GanttChart>
    <StatusLine>{{ notice }}</StatusLine>
  </DemoPanel>
</template>
vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  GanttChart, actualsTimelineBars, rescheduleFromActuals, type ActualsDiagnostic, type PlanningDiagnostic, type ScheduleInput,
  type ScheduleLink, type ScheduleTask, type TaskActuals, type TimelineRow,
} from '../src'
import { formatTime, hour, minute, origin } from './data'
import DemoPanel from './components/DemoPanel.vue'
import { useDemoLocale } from './i18n'

const { t, labels: componentLabels } = useDemoLocale()

// Opt-in example of `rescheduleFromActuals`: recorded actual intervals are kept exactly as reported and only the
// remaining work is scheduled on the shift calendar from the status date. Each row shows the original plan (grey strip),
// the actuals (solid bars) and the remaining forecast (outline bars), from `actualsTimelineBars`.
const at = (hours: number, minutes = 0) => origin + hours * hour + minutes * minute
const range = { start: origin, end: at(33) }
// Two shifts a day with a lunch break: 08:00–12:00 and 13:00–17:00 UTC.
const periods = [0, 24].flatMap(day => [{ start: at(day), end: at(day + 4) }, { start: at(day + 5), end: at(day + 9) }])
const nonWorking = [{ start: at(4), end: at(5) }, { start: at(9), end: at(24) }, { start: at(28), end: at(29) }]
const rows: TimelineRow[] = [
  { id: 'saw', label: t({ en: 'Cut stock', ja: '素材切断' }), detail: t({ en: 'Finished, overran', ja: '完了、超過' }) },
  { id: 'mill', label: t({ en: 'Mill housing', ja: 'ハウジング加工' }), detail: t({ en: 'Late start, interrupted', ja: '開始遅れ、中断あり' }) },
  { id: 'weld', label: t({ en: 'Weld frame', ja: 'フレーム溶接' }), detail: t({ en: 'Remaining work revised', ja: '残作業を見直し' }) },
  { id: 'paint', label: t({ en: 'Paint frame', ja: 'フレーム塗装' }), detail: t({ en: 'Not started', ja: '未着手' }) },
  { id: 'pack', label: t({ en: 'Pack', ja: '梱包' }), detail: t({ en: 'Not started', ja: '未着手' }) },
]
const labels = new Map(rows.map(row => [row.id, row.label]))
const tasks: ScheduleTask[] = [
  { id: 'saw', duration: 3 * hour },
  { id: 'mill', duration: 4 * hour },
  { id: 'weld', duration: 2 * hour },
  { id: 'paint', duration: 2 * hour },
  { id: 'pack', duration: hour },
]
const dependencies: ScheduleLink[] = [
  { id: 'saw-mill', from: 'saw', to: 'mill' },
  { id: 'mill-paint', from: 'mill', to: 'paint' },
  { id: 'weld-paint', from: 'weld', to: 'paint' },
  { id: 'paint-pack', from: 'paint', to: 'pack' },
]
const input: ScheduleInput = {
  range, quantum: 10 * minute, calendars: [{ id: 'shifts', periods }], defaultCalendarId: 'shifts', tasks, dependencies,
}
const statusDate = at(6)
// What the shop floor reported at 14:00. Cutting overran and is finished; milling started late, ran into the lunch break,
// stopped and resumed; welding did its planned 2 h and the welder now reports 3 h still to do.
const reviseWeld = ref(true)
const actuals = computed(() => new Map<string, TaskActuals>([
  ['saw', { intervals: [{ start: at(0), end: at(3, 30) }], finished: true }],
  ['mill', { intervals: [{ start: at(3, 40), end: at(4, 20) }, { start: at(5, 20), end: at(6) }] }],
  ['weld', { intervals: [{ start: at(0), end: at(2) }], ...(reviseWeld.value ? { remainingWork: 3 * hour } : {}) }],
]))
const result = computed(() => rescheduleFromActuals(input, statusDate, actuals.value))
const bars = computed(() => actualsTimelineBars(result.value, { label: id => labels.get(id) ?? id, baselineId: 'plan' }))
const finish = computed(() => result.value.ok ? formatTime(result.value.schedule.finish) : t({ en: 'not feasible', ja: '実行不可能' }))
const planFinish = result.value.plan.ok ? formatTime(result.value.plan.finish) : ''
const problems: Record<ActualsDiagnostic['code'], string> = t({
  en: {
    'actual-overlap': 'Actual intervals overlap',
    'actual-after-status-date': 'Actual work recorded after the status date',
    'actual-outside-calendar': 'Actual work outside the shift calendar (kept as recorded)',
    'actual-contradiction': 'Finished, but remaining work was reported',
  },
  ja: {
    'actual-overlap': '実績の区間が重なっています',
    'actual-after-status-date': '状況日付より後に実績が記録されています',
    'actual-outside-calendar': 'シフトのカレンダー外の実績です(記録どおりに保持)',
    'actual-contradiction': '完了していますが、残作業が報告されています',
  },
})
function describe(item: ActualsDiagnostic | PlanningDiagnostic) {
  const task = item.entities.find(entity => entity.kind === 'task')
  const title = (problems as Record<string, string>)[item.code] ?? item.code
  return `${task ? labels.get(task.id) + ': ' : ''}${title}${item.range ? ' ' + formatTime(item.range.start) + '–' + formatTime(item.range.end) : ''}`
}
const remainingHours = (id: string) => (result.value.tasks.find(task => task.id === id)?.remainingWork ?? 0) / hour
</script>

<template>
  <DemoPanel title-id="actuals-title" :title="t({ en: 'Recorded actuals', ja: '記録された実績' })" :subtitle="t({ en: 'rescheduleFromActuals · status 14:00 UTC · actuals stay as recorded', ja: 'rescheduleFromActuals · 状況日付 14:00 UTC · 実績は記録どおり' })">
    <template #options>
      <label><input v-model="reviseWeld" type="checkbox"> {{ t({ en: 'Welding needs 3 h more', ja: '溶接にあと 3 時間必要' }) }}</label>
    </template>
    <dl class="schedule-metrics">
      <div><dt>{{ t({ en: 'Planned finish', ja: '計画の完了' }) }}</dt><dd>{{ planFinish }}</dd></div>
      <div><dt>{{ t({ en: 'Forecast finish', ja: '予測の完了' }) }}</dt><dd data-testid="actuals-finish">{{ finish }}</dd></div>
      <div><dt>{{ t({ en: 'Welding remaining', ja: '溶接の残り' }) }}</dt><dd>{{ remainingHours('weld') }}{{ t({ en: ' h', ja: ' 時間' }) }}</dd></div>
    </dl>
    <GanttChart :rows="rows" :bars="bars" :range="range" :format-time="formatTime" :status-date="statusDate" readonly
      :pixels-per-unit="22 / hour" :tick-steps="[2 * hour, 4 * hour, 8 * hour]" :row-height="52" :height="320"
      :non-working-periods="nonWorking" :baseline-ids="['plan']" :baseline-label="() => t({ en: 'Original plan', ja: '当初計画' })"
      :labels="{ ...componentLabels.gantt, region: t({ en: 'Recorded actuals timeline', ja: '記録された実績のタイムライン' }) }">
      <template #row-heading>{{ t({ en: 'Operation', ja: '工程' }) }}</template>
      <template #legend>
        <ul class="actuals-key" :aria-label="t({ en: 'Recorded actuals legend', ja: '記録された実績の凡例' })">
          <li><span class="key key-actual" aria-hidden="true"></span>{{ t({ en: 'Actual: recorded work (solid)', ja: '実績: 記録された作業(塗りつぶし)' }) }}</li>
          <li><span class="key key-forecast" aria-hidden="true"></span>{{ t({ en: 'Forecast: remaining work (outline)', ja: '予測: 残りの作業(枠線)' }) }}</li>
          <li><span class="key key-plan" aria-hidden="true"></span>{{ t({ en: 'Original plan (strip below)', ja: '当初計画(下の帯)' }) }}</li>
        </ul>
      </template>
    </GanttChart>
    <ul class="actuals-diagnostics" :aria-label="t({ en: 'Recorded actuals diagnostics', ja: '記録された実績の診断' })">
      <li v-for="item in result.diagnostics" :key="item.id">{{ describe(item) }}</li>
    </ul>
  </DemoPanel>
</template>

<style scoped>
.actuals-key { display: flex; flex-wrap: wrap; gap: 12px; margin: 0; padding: 0; list-style: none; font-size: 12px; }
.actuals-key li { display: inline-flex; align-items: center; gap: 4px; }
.key { display: inline-block; width: 18px; height: 10px; border-radius: 2px; box-sizing: border-box; }
.key-actual { background: var(--vw-teal-solid, #2b756b); border: 1px solid var(--vw-teal-solid, #2b756b); }
.key-forecast { background: var(--vw-blue-pale, #e6effa); border: 1px solid var(--vw-blue-line, #6b96c5); }
.key-plan { height: 3px; background: var(--vw-baseline, #718497); }
.actuals-diagnostics { margin: 8px 0 0; padding-inline-start: 18px; font-size: 12px; }
@media (forced-colors: active) {
  .key-actual { background: CanvasText; border-color: CanvasText; }
  .key-forecast { background: Canvas; border-color: CanvasText; }
  .key-plan { background: CanvasText; }
}
</style>

Released under the MIT License.