本文へ移動

タイムラインと時間軸 ​

タイムラインの補助関数は GanttChart の計算の土台です。逆変換できる時間軸(createTimeScale、非稼働時間を圧縮する createWorkingTimeScale)、安定した目盛り、スナップ付きの区間編集(editTimeRange)、サマリーを集計する行ツリー、列とセルエディターのための型付きフィールド定義、元のデータを変えずに行を検索・並べ替え・絞り込みするタイムラインビュー(projectTimelineView、useTimelineView)があります。

区間は半開区間 [start, end) で、単位は自由に選べます(標準はミリ秒)。どの時間軸も逆変換でき、toTime(toX(t)) は t に戻るので、ピクセル位置と時刻を双方向に変換できます。

最小の例 ​

ts
import { createTimeScale, editTimeRange } from '@eightkk/vue-weave/core'

const hour = 3_600_000
const range = { start: 0, end: 24 * hour }
const scale = createTimeScale(range, 80 / hour) // 1 時間 80 ピクセル
scale.toX(2 * hour) // 160
scale.toTime(160) // 7_200_000

// バーを 50 分動かし、15 分単位にスナップし、範囲内に収める
const moved = editTimeRange({ start: hour, end: 3 * hour }, 'move', 50 * 60_000, 15 * 60_000, range)

例: スケジューリング、建設工程。ガイド: 別の時間軸。型: TimeScale、createTimeScale、editTimeRange、useTimelineView。

英語の詳細

ここから下の詳細なリファレンスは英語です。

Timeline editing helpers ​

ExportPurpose
removeTimelineBars(bars, dependencies, ids)New { bars, dependencies } arrays without the given bars and without every dependency whose from or to is one of them. Accepts any iterable of IDs and keeps the remaining items and their order. An unknown ID throws an Error
assignLanes(bars, options?)AssignLanesResult: { bars, laneCount, rowLaneCounts } with new bar objects in input order, each with lane set so that the bars of one row never overlap within a lane. See below
dependencyTypeForEnds(fromEnd, toEnd)Dependency type for a source and target TimelineBarEnd (start or finish)
dependencyEndsForType(type = FS)The bar ends a dependency type joins
moveTimeRanges(ranges, delta, snap, bounds)Move intervals by one snapped displacement, clamped so every interval stays in bounds. A fractional snap is applied in exact decimal arithmetic, like editTimeRange
calendarBands(range, unit, options)One header band level of hours, days, weeks, months or years in epoch milliseconds, aligned to a fixed UTC offset or to local time in an IANA time zone and clipped to the range. locale and labelFormat give locale-aware labels; see Calendar zoom presets and locale-aware labels
calendarZoomPresets(range, options?)Ready-made hour, day, week, month, quarter and year zoomPresets with header bands, ticks, snap and a matching formatTime; see Calendar zoom presets and locale-aware labels
intlTimeFormatter(options?)A cached, deterministic Intl.DateTimeFormat-based formatTime for a locale and time zone; see the same section
resourceLoadHistogram(segments, resourceIds?)Validate load segments, group them by resource, sort them and report each resource's peak. Segments that overlap within a resource throw a RangeError (an Error in 1.2.0 and earlier), as do invalid times, load and capacity; an unknown resource throws an Error
timelineWbsCodes(rows)Map from row ID to its outline (WBS) code in tree preorder: roots "1", "2", children "1.1", "1.2.1". Sibling order is array order. Invalid rows throw like createTimelineRowTree
timelineRowPosition(rows, id)The row's TimelineRowPosition: its parentId (absent for a root) and index among its siblings. An unknown ID throws an Error
moveTimelineRow(rows, id, target)New rows array in tree preorder with the row and its subtree moved under target.parentId (a root without it) at sibling target.index, counted without the moved row. The moved row is a new object; the others keep their identity. Unknown rows or parents and moves into the own subtree throw an Error; an index that is not an integer from 0 to the sibling count throws a RangeError
indentTimelineRow(rows, id) / outdentTimelineRow(rows, id)moveTimelineRow to the last child of the previous sibling, or to the next sibling after the parent. A first sibling cannot be indented and a root row cannot be outdented (Error)
timelineCsvTable(rows, bars, options?)A header and one record per bar for toCsv; see Interchange exports
timelineLabelColumnId'$label', the TimelineColumnResize.id of the row label column; see Column resizing
applyTimelineConstraintEdit(bars, change)New bars array in which the bar change.id is a copy with constraints[change.kind] set to change.after, or without it when after is undefined; the constraints field is left out once no constraint remains. Other bars keep their identity and the input is not modified. An unknown bar or kind throws an Error and an after that is not a finite number a RangeError. before is not compared with the bar. See Scheduling constraints
timelineConstraints(source)The constraint fields of any object, for example a ScheduleTask, as a new TimelineConstraints with only the kinds that are set, or undefined when none is; a set value that is not finite throws a RangeError. Builds TimelineBar.constraints from scheduler tasks
timelineConstraintViolated(range, kind, time)Whether the interval breaks the constraint, as GanttChart draws it. An unknown kind throws an Error
timelineConstraintKindsThe five TimelineConstraintKind names in the order the chart describes them, frozen

assignLanes(bars, options: AssignLanesOptions = {}) treats bars as half-open intervals, so touching bars share a lane; a milestone at t conflicts with every bar of its row that contains t (start <= t < end) and with milestones at t. By default lanes are assigned first-fit in start order, ties in input order, which uses the fewest lanes possible; input lanes are ignored. With keepLanes: true the bars are placed in input order: each keeps its lane (default 0) when no bar placed before it conflicts with it in that lane, and only a conflicting bar moves to the lowest free lane. This keeps lanes stable while an application adds or moves bars. laneCount is the largest number of lanes of any row and at least 1, and rowLaneCounts is a Map from each row ID that has bars to its highest lane plus one. Non-finite or inverted intervals and lanes that are not nonnegative integers throw a RangeError; the input is not modified.

calendarBands options are utcOffsetMinutes (integer from -1080 to 1080, the same limit as buildWorkPeriods and toMsProjectXml; default 0; daylight-saving transitions are not applied), timeZone (an IANA zone such as Europe/Berlin, described below; cannot be combined with utcOffsetMinutes), step (units per band, default 1; a divisor of 24 for hours; multi-unit days, weeks and months follow a fixed grid counted from 1970-01-01 in the offset or zone, and years from year 0, so overlapping ranges share boundaries), weekStartsOn (0 Sunday to 6 Saturday, default 1), locale and labelFormat (locale-aware labels, see Calendar zoom presets and locale-aware labels) and label(start, end, local), which receives the unclipped band and the CalendarBandLocalTime of its start: year, month (1 to 12), day, hour, minute, weekday (0 Sunday to 6 Saturday), utcOffsetMinutes in effect at the start, and timeZone (undefined for a fixed offset). Default labels are HH:mm, YYYY-MM-DD (days and week starts), YYYY-MM and YYYY in local time. Results are capped at 10,000 bands.

With timeZone, bands follow local time with the zone's daylight-saving rules from Intl.DateTimeFormat, as in Time-zone calendars, so GanttChart headerBands built this way stay on local midnights across transitions instead of drifting by an hour:

  • Day, week, month and year bands start at the first instant of their local date: local midnight, or the end of a gap that skips midnight (in America/Santiago on 2022-09-11 the day starts at 01:00). A day band lasts 23 or 25 hours on a transition day. A local date that the zone skips entirely, such as 2011-12-30 in Pacific/Apia, has no band.
  • Hour bands start where local time reaches a multiple of step hours, counted from local midnight on every date. A 23-hour day has 23 one-hour bands and a 25-hour day has 25, with the repeated hour labelled twice (the label callback can tell them apart by utcOffsetMinutes). A grid hour inside a gap starts its band at the end of the gap: with a 30-minute shift (Australia/Lord_Howe) the 02:00 band starts at 02:30 and lasts 30 minutes. With step greater than 1, every occurrence of a grid hour starts a band, and the bands that contain a transition are shorter or longer, for example 00:00–06:00 lasts 5 hours on a spring-forward night.
  • Labels are taken from the local time of the band start, so a band that starts after a gap is labelled with that time (01:00, 02:30).
  • An unknown or empty zone name throws a RangeError with the name, and so does combining it with utcOffsetMinutes. Results depend on the time-zone data of the runtime.
ts
import { calendarBands } from '@eightkk/vue-weave/core'

const range = { start: Date.parse('2025-10-24T22:00:00Z'), end: Date.parse('2025-10-28T23:00:00Z') }
const headerBands = [
  calendarBands(range, 'day', { timeZone: 'Europe/Berlin' }), // 2025-10-26 lasts 25 hours
  calendarBands(range, 'hour', { timeZone: 'Europe/Berlin', step: 6 }),
]

Row trees and summaries ​

createTimelineRowTree(rows) validates unique nonempty IDs, parent references and cycles. Each preorder entry contains row, depth, hasChildren and afterSubtree, the exclusive index after that row and its descendants. Root and sibling order follows input order.

summarizeTimelineRows(tree, bars) expects the tree returned by createTimelineRowTree and valid bars for those rows. It aggregates leaf-row bars into their ancestors and returns a Map keyed by row ID, including leaves with bars. Each summary reports the earliest start, latest end and interval count. Progress is weighted by duration across bars with known progress. Bars without progress and zero-duration milestones do not contribute to the progress denominator. Explicit parent bars are excluded from descendant aggregation.

Typed fields and timeline views ​

TimelineColumn.field is an optional TimelineFieldSpec (id, kind, raw getter get, optional parse, format, required, choices, multiple, min, max, integer, allowNegative, timeZone, utcOffsetMinutes, durationBasis, unitSize, unitLabel). Columns without it are edited as text through cell-edit. kind is 'text', 'number', 'time', 'duration', 'select' or 'checkbox'; FieldValue is a string, number, boolean, null or an array of those (multiple selection). TimelineFieldEdit<R> describes a typed change (rowId, columnId, fieldId, before, after, source). GanttChart emits it through field-edit; see Timeline columns and rollups.

Core helpers in @eightkk/vue-weave/core:

  • parseFieldValue(spec, text) returns { ok: true, value } or { ok: false, code, error }. Blank text is null (or a required error); 0 and negative numbers are values. Error codes are required, invalid, negative, range, integer, choice, time-zone and custom.
  • parseSheetText(text) reads tab-separated clipboard text into records of cells: CRLF, LF or CR end a record, one trailing line break is ignored, and a cell that starts with a double quote is read as quoted only when a tab, a line break or the end follows its closing quote (otherwise the quote is text). formatSheetText(records) writes records with tabs and CRLF, quoting cells with a tab, a line break or a quote, and ends the text with a line break when several records end with a single empty cell, so the two round-trip.
  • applyTimelineSheetEdit(rows, change, { field?, cell? }) applies the fieldEdits and cellEdits of a sheet-edit batch (or of single field-edit and cell-edit proposals) through the given callbacks, which return new rows. It returns a new array in the same order, keeps the identity of rows without edits and applies the edits of one row in order, field edits first. It throws an Error, before applying anything, for an invalid or duplicate row ID, an edit of an unknown row (Unknown row in sheet edit: <id>) or edits without their callback, and when a callback changes the row ID.
  • validateFieldValue(spec, value) checks a value with the same rules and returns { ok: true } or an error. null and [] are empty.
  • formatFieldValue(spec, value) returns editor text; fieldValuesEqual(a, b) compares values. The built-in formats and parsers round-trip: parsing the formatted text of a valid value gives the same value back, with two normalizations in select fields: with multiple, a single value (1, which validateFieldValue accepts) reads back as a one-element array ([1]), and an empty selection (null or []) reads back as null. Store the parsed value, not the value you formatted, when the type matters.
  • Built-in select text: a choice is shown by its label (or its value when it has none) and read back from either. A label that exactly one choice shows wins over a value with the same text. Text that matches several choices (a label shared by several choices, with no single value of that text) is a choice error naming the text, never resolved to one of them; for such choices formatFieldValue shows the values instead of the labels, so the text stays readable back. With multiple, the text is a comma-separated list read into an array in typed order (one entry gives a one-element array), and the formatter joins the entries with , . Quoting follows CSV: an entry in double quotes runs to the closing quote, with "" for a quote inside, and is read exactly, commas and leading or trailing whitespace included; an unquoted comma always separates entries, whitespace around an entry is ignored, and a quote inside an unquoted entry is an ordinary character. Each entry is then read by the single-choice rule above. The formatter writes each choice by its label when that label names it, else by its value, and quotes the entry when it is empty, contains a comma or a double quote, or starts or ends with whitespace; so the labels Cut, weld and Cut, weld give Cut, weld for two choices and "Cut, weld" for one, and every valid selection parses back to the same array. An empty unquoted entry (a,,b, a trailing comma), an unclosed quote, or text after a closing quote is invalid. In a single select, empty text reads as no value (null), so a choice with an empty label is written by its value; an empty selection (null or []) is shown as empty text and reads back as null. Every choice must have a text that names it, its label or its value: when both read as other choices (for example a label shared with another choice, and a value that is the label of a third), or two choices have values with the same text (1 and '1'), formatFieldValue and parseFieldValue throw an Error (Choice "A" of select field <id> has no text that names it: …) instead of writing text that reads back as another value. Give such a choice a label of its own. Formatting and parsing take time linear in the text and the number of choices.
  • Built-in time parsing reads YYYY-MM-DD[ T]HH:mm[:ss[.SSS]] with the spec's IANA timeZone (daylight saving applied) or fixed utcOffsetMinutes, or a Z/±HH:MM written in the text. It never uses the runtime's time zone or Date.parse. With timeZone, typed text for a wall time that does not exist (clocks going forward) resolves to the transition, and text without an offset for a wall time that occurs twice (clocks going back) resolves to the earlier occurrence. formatFieldValue writes the offset after a wall time that occurs twice, for example 2026-11-01 01:30 -04:00 and 2026-11-01 01:30 -05:00 in America/New_York, so either instant parses back exactly; other times are written without an offset. Without timeZone or utcOffsetMinutes, supply parse and format; otherwise parsing returns time-zone. duration values are in model units; unitSize converts the typed number and durationBasis ('elapsed' or 'working') states what is edited. Negative durations need allowNegative.

Timeline view state (TimelineViewState, version 1) is JSON-safe: column order, visibility and width, a search (text, optional columnIds), sort entries (ruleId, direction), optional column filters, collapsedIds, window and a zoom preset ID. It holds no functions, DOM state or drafts. A TimelineViewFilter has a columnId (a column ID or timelineLabelColumnId for the row label), an optional text that the column's displayed value must contain, ignoring case, and optional values compared with the raw field.get value (else the displayed value; a multiple selection matches when one entry does; an empty list matches no row). States saved before filters existed have no filters and still parse.

  • createTimelineViewState(columns?, patch?), parseTimelineViewState(json) (throws on a malformed value), reconcileTimelineViewColumns(state, columns) and resolveTimelineColumns(state, columns). Unknown column IDs are dropped with an unknown-column diagnostic. Columns the state has not seen are appended after the known ones, visible, in declared order (new-column).
  • projectTimelineView(input, state) takes { rows, bars, dependencies?, columns?, sortRules?, laneCount? } and returns display copies plus matchedRowIds, removedDependencyIds, removedDependencyCount, hiddenTargets (hidden bars that a shown bar still depends on or feeds), wbs, collapsedIds, window, zoom and diagnostics. Matching rows keep their ancestors; siblings are sorted stably, with ties in the original order; dependencies to hidden bars are removed. The output passes validateTimelineData. The input is not changed. A sort ruleId is a registered compare rule (an own key of sortRules; inherited members such as constructor are not rules) or a column ID.
  • projectTimelineView computes wbs with timelineWbsCodes from the original, unfiltered rows.
  • projectTimelineRows(input, state) is the row part of projectTimelineView, for applications that show the rows in their own tree table. It takes TimelineRowsInput { rows, columns?, sortRules?, bars? } and the search, sort, filters and collapsed IDs of a view state (TimelineRowViewState; a whole TimelineViewState fits) and returns TimelineRowsProjection { rows, matchedRowIds, wbs, collapsedIds, diagnostics }, with the same search, filter and sort rules. rows are the input's row objects. With bars, the unrestricted search also matches bar labels and columns receive row summaries, exactly as in projectTimelineView; without them, columns receive no summary. The diagnostics are unknown-row (a collapsed ID that names no row, dropped from collapsedIds), unknown-column (a filter or search column) and unknown-sort-rule; the column diagnostics of reconcileTimelineViewColumns are left out. projectTimelineView uses it, so its rows, matchedRowIds, wbs and collapsedIds are the same, and its diagnostics are the column diagnostics followed by these. It throws like createTimelineRowTree for invalid or duplicate row IDs, unknown parents and cycles, and an Error for a bar whose row is unknown (Unknown row for bar: <id>). Inputs are not changed. Use createTimelineRowTree(result.rows) for depths.
  • Filters combine with each other and with the search: a row matches when it passes all of them, and matchedRowIds lists those rows. An unknown filter column is ignored with an unknown-column diagnostic. A sort or filter on timelineLabelColumnId reads the row label unless a column or sort rule has that ID.
  • filterTimelineRows(rows, predicate) returns the rows that match, each with its ancestors, in the original order (a loop, so deep hierarchies are fine). It throws like createTimelineRowTree for duplicate IDs, unknown parents and cycles, and does not change rows.
  • nextTimelineSort(sort, columnId) returns the sort after a header sort button. Only the column's own rule changes and the other rules keep their order and direction: a column without a rule is added as the first rule, ascending; an ascending rule turns descending in place; a descending rule is removed. It returns new objects and never changes sort.

useTimelineView(source, initial?) (Vue entry) wraps this reactively. It returns state (a writable ShallowRef<TimelineViewState>), projection (pass its rows, bars and dependencies to GanttChart), columns (the visible TimelineColumn<R> array in saved order with saved widths, ready for the columns prop), diagnostics (saved-view problems, column problems included), setSearch, setSort, setFilters (an empty list removes filters), setColumnVisible, setColumnWidth, moveColumn, toggleCollapsed, setWindow, restore(json), reset() and snapshot(). Compute schedules, loads and diagnostics from the full input, not from the projection.

Related exported types: TimelineFieldKind, FieldPrimitive, FieldChoice, FieldDurationBasis, FieldErrorCode, FieldParseResult, TimelineViewInput, TimelineViewColumn, TimelineViewSort, TimelineViewSearch, TimelineViewFilter, TimelineRowCompare, TimelineHiddenTarget, TimelineViewProjection, TimelineViewDiagnostic, TimelineViewDiagnosticCode, TimelineRowsInput, TimelineRowViewState, TimelineRowsProjection.

MIT ライセンスで公開しています。