Web Component Implementation in Vanilla-Gantt
<vn-gantt> (VanillaGanttElement, vanilla-gantt-element.js) owns the
attributes, the stylesheets, the DataManager and the load. It builds the two
panes, and constructs a VanillaGantt (vanilla-gantt.js), which draws the
timeline.
1. Markup
Light DOM, like <vn-grid>. connectedCallback() (through _ensureMarkup())
adds the class vn-gantt and appends, after any <vn-grid-column> children
(§ 4.1), which stay where they are:
vn-gantt.vn-gantt
div.vn-gantt-layout flex row, contain: layout
div.vn-gantt-grid-pane#vn-gantt-task-list-N width: the task list's width; min-width: minTaskListWidth
vn-grid.vn-gantt-task-grid the task list
div.vn-gantt-splitter[role=separator] the 1px line between the panes (§ 8)
div.vn-gantt-timeline min-width: minTimelineWidth
div.vn-gantt-scroller horizontal scroller, native scrollbar hidden
div.vn-gantt-canvas as wide as the timeline
div.vn-gantt-header two tiers of ticks
div.vn-gantt-body tick lines and the lane block
div.vn-gantt-message[role=status] loading and error text
div.vn-gantt-hscrollbar-track the custom horizontal scrollbar
The <vn-grid> is created only once vn-grid is defined; until then the
pane stays empty and initializeGantt() throws 'grid-missing'.
The two panes share one frame: the task grid's container drops its right
border and right corners, the timeline its left ones, and the splitter draws
the one line between them (Themes § 2).
contain: layout on .vn-gantt-layout makes it the containing block of every
fixed-positioned descendant, which places the task grid's vertical scrollbar
at the timeline's right edge
(Timeline § 6.2).
2. Attributes and properties
| Attribute | Property | Effect |
|---|---|---|
theme |
theme |
Default 'default'. The timeline's theme, and the embedded grid's (06-themes) |
theme-css-path |
themeCssPath |
Overrides theme for the timeline only |
zoom |
zoom |
Read by initializeGantt() when options.zoom is absent; afterwards a change calls setZoom(), and the attribute reflects the level in effect (a clamp can differ from the request) |
read-only |
readOnly |
No bar can be moved, by pointer, touch or keyboard (Task Moving); turning it on cancels a drag. options.readOnly sets it |
tree-column |
The key of the column holding the tree toggles, read at each initializeGantt(), not observed; options.treeColumn wins over it (§ 4.1) |
setTheme() and setZoom() are the method forms. zoomIn() and zoomOut()
move one level and reflect the attribute.
3. Lifecycle
connectedCallback()injects the base stylesheet and the theme link, then builds the markup.disconnectedCallback()waits one microtask and, if the element was only moved, keeps everything. On a real removal it stops a running touch fling and releases its theme link. The embedded grid tears itself down and rebuilds and reloads on re-insertion with the kept internal manager, so the Gantt needs no teardown of its own: its listeners are kept by the grid element.ready()resolves once the grid's scripts (VanillaGridReady, or the grid bundle'svn-griddefinition), the Gantt's (VanillaGanttReady), the Gantt's two stylesheets and the task grid's two (<vn-grid>'sstylesheetsReady()) have loaded. On a connected Gantt it first creates the task grid if the grid's script wasn't ready at connect, so its links exist. Until the grid's sheets apply it lays out unstyled: in Firefox its viewport is one row tall, and the skeleton a load shows, sized from that viewport, would be the minimum ten rows over an empty pane. With no grid on the page it rejects with anErrorwhosecodeis'grid-missing'.initializeGantt(options)builds the Gantt; calling it again rebuilds it. It returns theVanillaGanttinstance.destroy()aborts a load in flight, detaches the manager and destroys theVanillaGantt(its listeners, observer and fling). The grid element stays in the DOM.
4. The embedded grid
initializeGantt() configures the grid before calling its initializeGrid():
| Setting | Value | Why |
|---|---|---|
row-key-field |
id |
Rows are keyed by task id; the grid compares keys as strings |
storage-mode |
none |
No persistence |
theme |
the Gantt's theme, or default |
06-themes |
| columns | options.columns, else the <vn-grid-column> children, else name (the tree column), start, end, duration, id; a column bound by ganttValue starts from that built-in (§ 4.1) |
The start and end columns are type: 'date' with timeZone: 'UTC', so a date-only value shows its calendar day in every time zone, and highlightSearchMatches: false, as the search never looks at them. Duration reads VanillaGantt#durationOf() through valueGetter and renders messages.durationDays; it has no field on the task, so its filterValueGetter is durationOf() too, and its filter compares days. Id shows the task's id as type: 'string' (so it sorts as text: t10 before t2); the search looks at it, so it marks its matches |
| DataManager | an internal StaticDataManager with searchFields: options.searchFields, default ['name', 'id'] |
Fed by the Gantt's load (§ 5). By default the search matches the task names and ids: a task's other fields are its parent's id and the stored dates. searchFields lists task fields, dotted paths allowed, not column keys, so a custom column is searched when its field is listed; [] searches every scalar field. The manager is created once, at the first call; a later call whose fields differ from getSearchFields() passes them to setSearchFields(). A bound toolbar's search names each field by the column with that key, else the field itself ("Searching: Task and Id") |
selection |
{ mode: 'single', showCheckboxes: false } |
One selected task, always on with no option, and what the keys act on: a row click (anywhere along the row, up to the splitter: Themes § 2), a bar press, Space or Shift+Space (the first fully visible task), the row keys (arrows, Page keys, Home, End) over or in either pane, or ArrowRight / ArrowLeft in the grid pane (to a child or parent) select it; Space or Shift+Space with a task selected clears it (Task Moving § 4). Every selection change but a bar press scrolls the timeline sideways to the selected bar. It shows in both panes at once: the grid row's tint and selection marker, the lane's tint and the ring around the task's bar. The selected-row style shows it, so no checkbox column takes the task list's width. getTaskGrid()'s getSelectedKeys(), setSelectedKeys(), clearSelection() and vn-grid-selection-changed work with task ids as keys (Selection), and so do the toolbar's selection predicates (hasSingleSelection) |
tree |
{ parentKeyGetter, toggleTabStop: false, column } |
The parent the Gantt resolved, so both panes show the Gantt's tree (Data Manager § 4). column is options.treeColumn, else the tree-column attribute, else the key of the first column bound to name, else 'name' when a column has that key, else unset; the grid then takes the first visible data column, and a key naming no visible data column falls back to it too (Tree Rows § 1). The toggles leave the tab order (Tree Rows § 1), so Tab crosses the task grid in one press; ArrowRight / ArrowLeft expand and collapse the selected task instead |
layout.headerHeight |
48 | Two 24px tiers; the timeline header is then sized to end exactly where the grid's rows begin (Timeline § 4) |
formatting.locale |
the Gantt's locale | One locale for both panes |
gridId |
'vn-gantt-' + (id or 'tasks') |
Keeps the grid from warning about a shared default storage scope |
logger |
options.logger, when given |
One logger for both panes |
highlightSearchMatches |
options.highlightSearchMatches === true |
Off by default, as in the grid: a search marks its match in the task names and ids. The grid reads it at initializeGrid() only, so it is an option here rather than an attribute set on the task grid afterwards |
getTaskGrid() returns the grid element once initialized. A toolbar links
it through <vn-gantt-toolbar gantt="<gantt id>">,
which names the Gantt in markup and links the grid once getTaskGrid()
returns it, as the sample does for its expand-all, collapse-all and scroll to
task. The grid
has no id of its own, so a plain <vn-grid-toolbar grid="..."> can't name it.
Options. zoom, columns and treeColumn (§ 4.1), searchFields (the DataManager row above), taskListWidth (px, default the width in effect: 360 on a first call; § 8), the splitter's minTaskListWidth, minTimelineWidth, splitterStep and splitterLargeStep (§ 8), readOnly, highlightSearchMatches (default false), locale
(default navigator.language, then VanillaGantt.defaultLocale), messages
(among them timelineLabel, the timeline's accessible name, 'Timeline')
and logger. The locale registry is the grid's: VanillaGantt.registerLocale(),
getLocaleMessages() and defaultLocale, looked up by the exact tag, then its
language prefix, then defaultLocale, then the built-in en bundle; a
registered bundle falls back to en key by key. The built-in column labels
are English; a host localizes one through its binding,
{ ganttValue: 'name', label: 'Aufgabe' }.
4.1 The task list's columns
initializeGantt() resolves the list once per call, in O(columns), and passes
it to the grid's setColumns(), whose strict validator checks it as for any
grid:
- The list.
options.columnswhen it is an array; else the<vn-grid-column>direct children of<vn-gantt>(:scope > vn-grid-column); else the five built-ins in their default order. When both are given the option wins. - Built-ins by
ganttValue. An entry whoseganttValueis exactlyname,start,end,durationoridbecomes a new object: the built-in definition with the entry's own properties copied over it (key, kind and type included), withoutganttValue. The host's objects are never mutated. A built-in keeps its key unless the entry sets one, so two columns bound to the same value need distinct keys. - Other entries go to the grid as given: a grid column over the task's
fields, by its key's dot path. The tasks the host's DataManager returns
are the grid's rows (§ 5), so a field on a task needs no DataManager
change, and a move or a roll-up writes only
startandend(Task Moving). A column keyeddurationwith noganttValueshows the task's owndurationfield; the built-in is{ ganttValue: 'duration' }. An unknown value ('Name') is not a built-in, and the grid reports the column's missing key, kind or type.
The list decides which columns show and in what order; [] shows none.
Markup. The children are read in place at each initializeGantt(), so a
change takes effect at the next call and React, Vue and Angular keep owning
the nodes. They are parsed by the grid's own mapping,
VanillaGridElement.parseColumnElements()
(§ 6 there), which copies the attribute it doesn't map, gantt-value, under
its own name; the Gantt reads the binding off it. parseColumnElements()
leaves out <vn-grid>'s fallbacks, so a bare
<vn-grid-column gantt-value="name"> keeps the header Task; header sets a
built-in's label. Any other markup column gets <vn-grid>'s fallbacks (key
'', header the key, label the header). The embedded <vn-grid> holds no
<vn-grid-column>, so its own parse at initializeGrid() finds none and the
Gantt's setColumns() stands.
5. The load
Nothing half-built is shown. Before initializeGantt() the layout is
visibility: hidden (inline, so it holds before the stylesheet loads): the
task grid has no columns and no header yet, and the timeline nothing to show.
initializeGantt() shows both panes and measures the timeline header against
the grid's at once (Timeline § 4).
From then on both panes say the same thing while a load runs.
loadTasksAsync():
- Aborts the previous load and stamps a new generation, as the grid's
loadRowsAsync()does. Firesvn-gantt-loading, showsmessages.loadingover the timeline, and puts the task grid in its loading state (setLoading(true): its skeleton, andisLoadingfor a toolbar bound to it, whose status then shows no stale count). - Calls
fetchTasks({ signal })andfetchDependencies({ signal })together. - Builds the task model (
VanillaGanttTasks.buildTaskModel()), writes each summary's rolled-up dates onto its task object (writeSummaryDates()), and resolves the links (VanillaGanttDependencies.resolveLinksAsync()), each in chunks that yield to the page every 20,000 items and stop on the abort signal (Data Manager § 3). Then installs them (VanillaGantt#setModel(): range, zoom clamp, lanes). - Hands the model's tasks, duplicates left out, to the internal grid manager
(
setRows()) and awaits the grid'sloadRowsAsync(). - Waits until the grid is done with the rows and shows them: its load
resolves before a large tree is built (above the grid's 5,000-row shimmer
threshold the rows are ordered and the tree built behind its skeleton), so
while the grid is still busy (
isBusy()) the Gantt waits for itsvn-grid-busy-changedwithbusy: false, announced in the same task as the pass that renders the rows. The grid's viewport phase can't tell: a render in that window (arefresh()after a theme stylesheet loads) reports'rows'with the skeleton still up. - Hides the message and fires
vn-gantt-loadedwith{ taskCount, dependencyCount },dependencyCountcounting the links that resolved. The grid'svn-grid-tree-rebuiltfor the new rows builds the link index, and the links are drawn once it is done, just after.
A load superseded at any await (a newer call, or a rebuild) resolves with
[] and leaves both panes to the newer one. A load aborted with no successor
(setDataManager() while loading, destroy()) also resolves with [], hides
the message and takes the grid out of its loading state: its earlier rows
come back, or its empty row. A rejected fetch shows messages.error in the
timeline and in the grid (showError()), fires vn-gantt-error with
{ error } and rejects; an AbortError is never reported. Without a
manager, or before initializeGantt(), the call rejects.
reloadDataManager() calls the manager's reset(), then loadTasksAsync().
setDataManager() sets the manager's onConfigChanged; with
setAutoReloadOnConfigChange(true), setters called in one task coalesce into
one reload (a microtask).
6. Events
All bubble and are composed, dispatched on <vn-gantt>, named in
VanillaGanttEvents (vanilla-gantt-events.js).
| Event | Detail | When |
|---|---|---|
vn-gantt-loading |
{} |
A load starts |
vn-gantt-loaded |
{ taskCount, dependencyCount } |
Both panes show the new tasks: the grid shows its rows (a large tree included), the timeline their bars |
vn-gantt-error |
{ error } |
A fetch rejected |
vn-gantt-task-move |
{ task, changes, source } |
Cancelable, before a move is applied (Task Moving § 3) |
vn-gantt-task-moved |
{ task, tasks, previous, source } |
The manager's updateTasks() resolved |
vn-gantt-task-move-failed |
{ task, code, error? } |
A move reached a dependency cycle ('dependency-cycle'), or updateTasks() rejected and every change was reverted ('manager-rejected') |
vn-gantt-zoom-changed |
{ zoom, previousZoom } |
The level in effect changed |
vn-gantt-task-list-resized |
{ width, source } |
The task list's width changed with the splitter or a fit: once when a drag that changed it ends, once per key press that changed it, once per fitTaskListWidth() call or splitter double-click that changed it (source 'pointer', 'keyboard' or 'fit'). Not for setTaskListWidth(), initializeGantt() or a narrower Gantt squeezing the pane (§ 8) |
vn-gantt-task-dblclick |
{ task, pane } |
A double-click on a task's grid row (pane: 'grid') or on its bar (pane: 'timeline'), once the task is selected. Fired before the grid's own vn-grid-row-dblclick reaches <vn-gantt>. Not cancelable (Task Moving § 2) |
7. Stylesheet links
The grid's link machinery is module-private in vanilla-grid-element.js, so
it is copied, as the toolbar copied it: one vanilla-gantt.css link per page
(vn-gantt-base-css), injected before the theme link because both declare
custom-property defaults at the same specificity; and one theme link per
resolved URL, its id derived from the URL, with a refcount so Gantts with
different themes don't fight over one link and a released link is removed.
A theme link's URL is written once, when it is created, so a Gantt that joins a link another holds doesn't reload it. Waiters are per instance because a shared link fires load only once. Once
both sheets have loaded the Gantt re-measures the pane geometry. URLs resolve
against the folder the element's script was loaded from and carry the ?v=
cache-bust token (Cache Bust).
8. The splitter and the task list's width
div.vn-gantt-splitter (built by _ensureMarkup(), driven by
features/splitter.feature.js) is the 1px line between the panes and a
WAI-ARIA window splitter: role="separator", aria-orientation="vertical",
tabindex="0", aria-controls naming the task list pane, aria-label from
messages.splitterLabel ('Resize task list'), and aria-valuenow /
aria-valuemin / aria-valuemax in px. Its hit area reaches 4px past each
side (8px under pointer: coarse), above the panes' own layers.
The width. The element owns it. getTaskListWidth() returns the width as
last set (taskListWidth, setTaskListWidth(), the splitter or a fit);
setTaskListWidth(px) clamps to minTaskListWidth, writes the pane's inline
width and fires nothing (a non-finite value warns and changes nothing);
before initializeGantt() it sets the width the panes are built with.
initializeGantt() takes taskListWidth when given, else keeps the width in
effect, and clamps it to the minimum.
| Option | Default | Effect |
|---|---|---|
minTaskListWidth |
120 | The task list is never narrower, by the splitter, setTaskListWidth() or a narrower Gantt |
minTimelineWidth |
160 | The splitter never makes the timeline narrower (its border included) |
splitterStep |
10 | px per Left / Right on the focused splitter |
splitterLargeStep |
50 | px per Shift+Left / Shift+Right |
A minimum must be a finite number >= 0, a step a finite number > 0; any
other value takes the default. Each initializeGantt() reads the four afresh.
The defaults are VanillaGantt.DEFAULT_MIN_TASK_LIST_WIDTH_PX,
DEFAULT_MIN_TIMELINE_WIDTH_PX, DEFAULT_SPLITTER_STEP_PX and
DEFAULT_SPLITTER_LARGE_STEP_PX.
A narrower Gantt. Flex squeezes without script: the pane is
flex: 0 1 auto with the minimum as its inline min-width, the timeline
flex: 1 1 0 with its own. With a basis of 0 the timeline never shrinks below
its minimum while the pane can, so the task list narrows down to its minimum,
and the width as set comes back when the Gantt widens. Below both minimums
plus the line the timeline is cut at the Gantt's right edge.
Pointer. As <vn-resize-box>'s handle: a press (the main button of a
mouse; any touch or pen) captures the pointer and reads the pane's width
once; a second pointer is ignored while a drag runs. Each move clamps the
target to [minTaskListWidth, layout width - line - minTimelineWidth] and
writes at most once per frame through VanillaGridScheduler.write(). A
release, pointercancel or lostpointercapture writes the last width,
removes vn-gantt-splitter-dragging from the element, and fires the event
when the width changed; a disconnect mid-drag ends it with no event. A mouse
drag doesn't move focus. The grid's observer and the geometry sync follow each
write as on a window resize; the grid's heavy pass waits for a 180ms pause,
and its near-top scroll reset no longer runs on a width-only change
(Grid 02 § 1.12),
so a drag keeps the task list's scroll position.
Keyboard. On the focused splitter: Left / Right by splitterStep,
Shift+Left / Shift+Right by splitterLargeStep, Home to the minimum, End to
the maximum. A press that changes the width fires the event and updates
aria-valuenow at once; the geometry sync keeps the values right afterwards
(a squeezed pane, a new maximum). The row keys over the panes skip a key
whose target is the splitter, so Home and End there resize only. The
splitter is the second of the Gantt's three tab stops, between the task
grid's viewport and the timeline
(Task Moving § 4).
Fit. fitTaskListWidth() sets the width so the task grid's last visible
column ends at the splitter; the columns keep their widths. The width is the
sum of the header <col> inline widths (the grid's own table width, so
hidden columns don't count; no layout read) plus the pane's chrome, the
pane's width minus the grid viewport's clientWidth (the grid container's
left border: 1px in default and default-dark; read, not assumed). It is
clamped to [minTaskListWidth, layout width - line - minTimelineWidth], the
splitter's own range, and applied as a key press applies it (aria-valuenow
at once). Columns wider than that maximum stay cut off and scroll sideways;
the stored width is the capped one, so a Gantt widened later gives the extra
width to the timeline, not the task list. A fit that changed the width
fires the event with source: 'fit', whoever called it; an unchanged one
writes nothing and fires nothing. Before initializeGantt() it returns
false, else true. A double-click on the splitter calls it (as a
double-click on a column's resize handle auto-fits that column); the two
presses before it are drags with no travel, which fire nothing. A touch
double-tap fits only where the browser fires dblclick for it (Chromium's
touch emulation does, Firefox's doesn't). The fit doesn't follow later
changes: a column resized, hidden or shown, or a deeper tree level expanded
(the tree column's indent is part of its fitted width), leaves the width as
it is until the next fit. <vn-gantt-toolbar>'s autoFitTaskList command
auto-fits the columns first, then calls it
(Gantt Toolbar).
Read-only. The splitter works: it moves no task.
Persistence. None: the task grid runs with storage-mode="none". A host
keeps the width by saving detail.width from the event and passing it back as
taskListWidth.