日本語
データ、保存、連動ビュー
コンポーネントのまわりのデータの扱いを順に説明します。受け入れた編集の保持とサーバー経由の保存、別の時間軸、計算の再利用、グラフ・ガントチャート・負荷行の連動、検索と並べ替え、表示状態の保存と復元、エクスポート、大きな計画の見えている部分だけの読み込み、日程表でのスプレッドシート編集、部品表のためのツリーグリッドです。
英語の詳細
ここから下のガイドは英語です。
Persistence
The edit event carries the previous interval so your parent can detect a stale proposal. A synchronous local commit is shown in the README.
For an API-backed application, retain a record version alongside the interval, compare change.before to current state, submit the proposal with that version, and replace bars after the server accepts it. Serialize saves per document, not per bar: tasks, dependencies, assignments and calendars share one document version, so concurrent saves of different bars can conflict or leave related records inconsistent. Reject another edit (useEditTransaction returns busy) while a save is pending. The server must apply each save as a conditional update on baseVersion, deduplicate by operationId, and commit all affected records atomically; a client-generated ID alone cannot prevent a double update on retry, and without these server guarantees retries are not safe. Surface rejection in your application and retain the accepted state. The event is a proposal; ignoring it preserves the previous interval.
Saving through a server
useEditTransaction keeps the accepted state and the state being saved apart, saves one transaction per document at a time and commits only what the server accepted. Give it a document ID, the state and version you loaded and an adapter:
ts
import { useEditTransaction, type TransactionAdapter } from '@eightkk/vue-weave'
const adapter: TransactionAdapter<Plan, PlanChange> = {
validate: (plan, changes) => checkChanges(plan, changes), // synchronous: true, false or a reason
apply: (plan, changes) => applyChanges(plan, changes), // returns a new plan; never mutate
save: async (request, candidate) => {
const response = await fetch(`/api/plans/${request.documentId}`, {
method: 'PUT',
headers: { 'content-type': 'application/json', 'if-match': request.baseVersion },
body: JSON.stringify({ operationId: request.operationId, request, candidate }),
}).catch(() => undefined)
if (!response) return { status: 'uncertain', operationId: request.operationId } // the request may have arrived
if (response.status === 409) return { status: 'conflict', operationId: request.operationId, currentVersion: response.headers.get('etag') ?? '' }
if (!response.ok) return { status: 'rejected', operationId: request.operationId, code: String(response.status) }
const body = await response.json()
return { status: 'accepted', operationId: request.operationId, version: body.version, state: body.plan }
},
}
const plan = useEditTransaction({ documentId: 'plan-1', initialState: loaded.plan, initialVersion: loaded.version, adapter })
async function onEdit(change: TimelineEdit) {
const outcome = await plan.submit([toPlanChange(change)], { source: change.source })
if (outcome.status === 'busy') announce('A save is still in progress')
}Bind the chart to plan.candidateState.value ?? plan.acceptedState.value to show the change while it is saved, or to acceptedState to show only saved data. undo() and redo() send the previous or next history snapshot as a restore transaction and move the history only when the server accepts it. refresh(state, version) takes a state fetched from the server (after a conflict, or when another user changed the document), resets the history, sets historyReset and makes late responses discarded. After uncertain, fetch the operation's outcome by its ID and pass it to reconcile(result); never resend the changes under a new operation ID.
The server side of this contract:
- Apply a save only when
baseVersionis the current version (a conditional update, for exampleIf-Match), otherwise answerconflictwith the current version. - Store the
operationIdwith the change and answer a repeated request with the original result instead of applying it twice. - Commit every record a transaction touches (tasks, dependencies, assignments, calendars) atomically, for
changesandrestorealike, and return the whole normalised document with its new version. The client replaces its accepted state with what you return, so server-assigned IDs and recalculated dates must be consistent within it.
Without these guarantees a retry after a lost response can apply a change twice. The demo's examples/adapters/transactionStore.ts simulates such a server, including rejection, conflicts and lost responses.
Batches, row moves and other proposals
Treat a Gantt edits batch as one transaction: apply every change or none, and commit it as one history entry. Row moves arrive as change.row.after. Dependency connect, reconnect and dependency-delete events are proposals as well; assign dependency IDs in the application or on the server, and check for cycles there if your scheduling rules forbid them. A reconnect of a dependency with a lag carries the lag in before and after, so { ...dependency, ...change.after } keeps it; change a lag through your own UI and commit it like any other edit.
progress-edit and bars-delete follow the same pattern. Accept a progress proposal by setting the bar's progress to change.after. Accept a deletion with removeTimelineBars, which also drops the dependencies that touch the removed bars, and commit both arrays as one history entry so that undo restores the bars and their links together:
ts
function deleteBars(ids: string[]) {
const next = removeTimelineBars(history.state.value.bars, history.state.value.dependencies, ids)
history.commit(next)
}Accept a create proposal by adding a bar with an ID and label of your choice at proposal.start–proposal.end in proposal.rowId (and proposal.lane when you use lanes), again as one history entry. When new bars may overlap others, pass the bars through assignLanes(bars, { keepLanes: true }) and give the chart its laneCount with a rowHeight of at least 8 + laneCount × 14. With cascade, an accepted move arrives as an edits batch that lists the bars the user moved first and the cascaded bars after them; apply it like any batch, or recompute the plan from the moved bars when the cascaded dates come from your scheduler.
Accept a row-move proposal with moveTimelineRow(rows, change.id, change.after) and commit the new rows with the bars and dependencies as one history entry, so that undo restores the previous hierarchy. timelineWbsCodes(rows) numbers the rows for a WBS column.
Accept a column-resize proposal by setting the column's width, or labelWidth when change.id is timelineLabelColumnId. Widths are view settings: keep them in the same history as the data when Undo should restore them, as the timeline editing demo does, or store them per user.
To import a plan from CSV, read the file in the browser (await file.text()) or on a server, then call timelineFromCsvTable(parseCsv(text), { parseTime }) and commit the returned rows and bars as one history entry. The importer assigns its own row and bar IDs, so map them to your records or keep a lookup by label when you merge an import into existing data. Catch its errors and show the message, which names the CSV line.
A Microsoft Project XML file (MSPDI, "Save as XML") imports the same way: fromMsProjectXml(text, { utcOffsetMinutes }) returns the tasks, links and warnings about what could not be imported, and timelineFromMsProject(project) turns them into rows, bars and dependencies to commit as one history entry. Row and bar IDs are the file's task UIDs, summary tasks become parent rows without bars, and links to summary tasks are listed in hiddenDependencyIds, or, with timelineFromMsProject(project, { summaryDependencies: true }), kept in dependencies for a chart with show-summaries and summary-dependencies. Show the warnings next to the result; malformed XML throws an Error that names the line and column. The result also carries the file's calendars, resources and assignments when it has them: workCalendarsFromMsProject and resourceLoadFromMsProject turn them into the inputs of scheduleTasks, levelResources, calculateResourceLoad and projectResourceTimeline, and timelineFromMsProject exposes the resources and assignments for a resource timeline directly. Calendar exceptions become one-off dates: date ranges and the recurrences that can be expanded exactly (every N days, weekly on given days, monthly or yearly on a day or a weekday position) become exactly their dates, and the others are left out with an unsupported-calendar warning that names the calendar and the exception (see the table in Microsoft Project import). Cost resources (IsCostResource 1) are imported as type: 'cost' and have no work capacity. toMsProjectXml writes a cost resource as Type 0 with IsCostResource 1 and the import also accepts Type 2, but Microsoft's schema pages disagree on this encoding and neither form has been opened in Microsoft Project itself. The exported calendars, resources and assignments follow the MSPDI schema order but have not been opened in Microsoft Project either.
An iCalendar file imports with fromICalendar(text, { utcOffsetMinutes }) and timelineFromICalendar(events). Time zones that Intl knows are applied as RFC 5545 says (a local time skipped by a daylight-saving gap takes the offset before the gap, a repeated one its first occurrence; a DURATION of days, such as P1D, ends at the same local time on the next day even across a daylight saving change, while PT24H is 24 hours), recurring events are imported once with a warning unless you pass recurrence: 'series' or recurrence: { range } (see Recurring events), and the warnings list what was skipped; show them next to the result.
The context-menu event only reports what was targeted, the time and row under the pointer and the client coordinates. Render your own menu there (for example role="menu" with role="menuitem" entries), move focus into it, close it on Escape and return focus to the element that had it. Menu actions can reuse the same accept functions as the keyboard proposals.
Alternative time scales
A TimeScale exposes width, toX(time) and toTime(x). It must map range.start to 0 and range.end to width, be finite and strictly increasing, and provide mutually inverse mappings over the range. It should also extrapolate beyond the range when tick or interval calculations require it. The Gantt component applies zoom to that mapping and uses its inverse for pointer displacement.
A piecewise scale can give working hours more visual space while retaining a small positive width for other hours. createWorkingTimeScale builds one from the chart range, working periods and a base width:
vue
<script setup lang="ts">
import { computed } from 'vue'
import { GanttChart, buildWorkPeriods, createWorkingTimeScale } from '@eightkk/vue-weave'
const hour = 3_600_000
const range = { start: Date.UTC(2026, 10, 9), end: Date.UTC(2026, 10, 16) }
const periods = buildWorkPeriods(range, {
timeZone: 'Europe/Berlin',
weekly: [1, 2, 3, 4, 5].map(weekday => ({ weekday, startMinute: 9 * 60, endMinute: 17 * 60 })),
})
// 40 px per working hour; nights and weekends keep 10 % of that (4 px per hour).
const scale = computed(() => createWorkingTimeScale(range, periods, 40 / hour, 0.1))
</script>
<template><GanttChart :rows="rows" :bars="bars" :range="range" :scale="scale" :snap="hour" /></template>The helper follows the contract above: toX(range.start) is 0, toX(range.end) is width, both mappings are strictly increasing and continuous, they are exact inverses at segment boundaries (within rounding elsewhere), and outside the range they continue with the slope of the nearest edge segment, so a drag past either edge still inverts. Each call is a binary search over the breakpoints, so thousands of periods are fine.
nonWorkingRatio(default 0.1) must be in(0, 1]. Zero is rejected with aRangeError: a collapsed interval maps all its times to one pixel, sotoTimecould not invert pointer positions and an edit inside it would have no defined time. If you need a hidden gap, keep a small positive ratio. A ratio of 1 gives the linear scale.- Periods are clipped to the range, and unsorted, overlapping or touching periods are united; they are not rejected. Periods outside the range are ignored. With no working period in range the whole axis is compressed uniformly.
- Changing the ratio or
pixelsPerUnitmoves bars on screen but never changes their times, and snapping,minDurationand edit proposals work on time, so they stay on the same grid. A gesture is one pointer position in pixels, so a drag over non-working time covers more time per pixel than one over working time. - The scale does not know the text direction. GanttChart positions bars and ticks from the inline start edge, so the same scale works with
dir="rtl"; usemirrorTimeScaleonly for your own renderers.
A fully collapsed interval is not invertible and needs a separately defined editing policy. For calendar generation and work-duration scheduling, call buildWorkPeriods and scheduleTasks from @eightkk/vue-weave/core, then pass accepted intervals to the chart. buildWorkPeriods uses a fixed UTC offset or, with timeZone, an IANA zone including its daylight-saving transitions. The chart does not invoke the scheduler automatically. See Scheduling and resource load.
Reusing calculations
Use the core entry in a worker or server to compute layouts, transform times or validate input (see Running core calculations in a Worker). NetworkGraph's layout callback is synchronous. For an asynchronously computed layout, use useAsyncGraphLayout (see Asynchronous layouts and preserved routes), or store the result in application state yourself and supply a synchronous callback that returns it. Either way, update data and matching geometry together.
Geometry types use Maps. Convert them to entries arrays when serializing them across JSON boundaries, then reconstruct Maps at the consuming side.
Linking views
To show one plan as a graph, a Gantt chart and load rows that follow each other, bind your entities to what each view draws and let useLinkedSelection work out what every view shows. The view the user acts in keeps the selection; the others only highlight, so a linked bar is never deleted, moved or used to cancel a drag in another view.
vue
<script setup lang="ts">
import { computed, useTemplateRef } from 'vue'
import {
GanttChart, NetworkGraph, revealLinkedTarget, taskViewBindings, useLinkedSelection, type ViewTargetEvent,
} from '@eightkk/vue-weave'
// Each task is bound to its node, bar, row and the load ranges in which it uses each resource, each dependency to its
// edge and arrow, under the same IDs. Pass the same tasks and assignments as to calculateResourceLoad.
const bindings = computed(() => taskViewBindings({ tasks: schedule.value.tasks, assignments, dependencies }))
const linked = useLinkedSelection({ bindings })
const graph = useTemplateRef('graph')
// Only `target-activate` selects; the components' own `select` events are left unconnected, so one click is handled once.
const activate = (event: ViewTargetEvent) => linked.select(event.target.view, [event.target])
const enter = (event: ViewTargetEvent) => linked.hoverEnter(event.target.view, event.target)
const leave = (event: ViewTargetEvent) => linked.hoverLeave(event.target.view, event.target)
const clear = () => linked.clearSelection()
async function showInGraph(nodeId: string) {
const result = await revealLinkedTarget({
reveal: () => graph.value?.revealNode(nodeId, { focus: true }),
expand: groupId => {
collapsed.value = new Set([...collapsed.value].filter(id => id !== groupId))
return true // return false to keep the group collapsed; the result is then not 'revealed'
},
})
if (result.status !== 'revealed') explain(result) // unknown, or still hidden in a collapsed group
}
</script>
<template>
<NetworkGraph ref="graph" :nodes="nodes" :edges="edges" :groups="groups" :collapsed-group-ids="collapsed"
:selected-ids="linked.graph.value.selectedNodeIds" :highlighted-node-ids="linked.graph.value.highlightedNodeIds"
:highlighted-edge-ids="linked.graph.value.highlightedEdgeIds"
@target-activate="activate" @target-enter="enter" @target-leave="leave" @background-click="clear" @idle-escape="clear" />
<GanttChart :rows="rows" :bars="bars" :range="range" :load-rows="loadRows" :load-segments="loadSegments" load-selectable
multi-select :selected-ids="linked.timeline.value.selectedBarIds" :highlighted-bar-ids="linked.timeline.value.highlightedBarIds"
:selected-load-targets="linked.load.value.selected" :highlighted-load-targets="linked.load.value.highlighted"
@target-activate="activate" @target-enter="enter" @target-leave="leave" @background-click="clear" @idle-escape="clear" />
</template>- IDs are paired with their kind and view, so a task
Aand a resourceAnever mix. One entity may have several targets (a task shown as two nodes or two resource bars) and one target several entities.taskViewBindingscovers the common case of views that use the task and dependency IDs as they are; for anything else, writeViewBindingobjects yourself and spread both into one array. - The components keep no selection of their own, so clearing it is yours:
background-clickreports a click on empty space andidle-escapean Escape that cancelled nothing of the component's own. Escape anywhere in the component, its toolbar buttons included, first cancels a drag, an armed connection or an open editor (reported throughgesture-endoredit-cancel); only an Escape that finds nothing to cancel, outside text fields, arrives asidle-escape. - Load segments have no ID and change when load is recalculated. Bind load as resource time ranges:
taskViewBindingsbinds each assignment to the periods of the task'sworkin which it uses its resource (assignmentWorkPeriods), so pauses, calendar breaks and the parts outside a partial assignment'sworkOffsetandworkDurationselect nothing, just ascalculateResourceLoadcounts nothing there; the chart marks the segments that overlap them, andresolveLoadTargetstells you which current segments a stored range still touches (a range that touches none is reported as unknown, never moved to another segment). - Hover never scrolls. Move to an item only on an explicit action, with
revealNode,revealBarorrevealLinkedTarget. A hidden item is reported ashidden-by-collapsewith its visible proxy; expanding is the application's decision and requires the controlledcollapsedGroupIdsorcollapsedIds. Filters are your own: when your filter hides an item, say so in your UI and offer to clear it. - For impact analysis,
traverseGraph(graph, startIds, { direction, maxHops })returns the node and edge IDs reached. Opt-inedgeFilterfollows only some relations (it is told the walk direction, so upstream and downstream can follow different ones),maxNodescaps the result nearest first andtruncatedlists where a limit stopped the walk (the places to offer "show more"), andpaths: trueletsgraphTracePath(result, id)rebuild the edges from a start to a node (why it is affected) and lists inmultiplyReachedIdsthe nodes reached by more than one path; see Traversal filters, limits and paths.resolveCollapsedTargetsmaps IDs of the full graph to the proxies and merged edges shown while groups are collapsed (callcollapseGraphGroupswith the same input as the graph). - To explore a time range (what ran on machine X between 14:00 and 16:00), pass
timeRange: { range, bars, rowIds, graph, traversal }touseLinkedSelection. Bars are tested by their worksegmentswhen they have them, so a pause covering the range does not count. Active tasks join the highlight sets and related tasks therelated*sets, for example:related-ids="linked.graph.value.relatedNodeIds"on NetworkGraph. Nothing is selected, so Delete never removes them.timelineBarsInRangeandresolveTimeRangeTargetsdo the same in core; see Time range exploration. - TreeGrid links the same way; see Tree grids, matrices and bills of materials.
- A view of your own (a task table, a list, a diagnostics panel) links through entities instead of a view name: call
linked.selectEntities([{ kind: 'task', id }], { source: 'task-table' })when the user selects in it, and render its own selected rows fromlinked.selectedEntities, which also follows selections made in the graph or the timeline. No view owns such a selection, so the graph and the Gantt chart only highlight the bound items and never receive them asselectedIds. Reporting the same entities with the samesourceagain changes nothing and does not callonSelect, so a table that echoes its selection back cannot loop; an empty list clears the selection.linked.selectionSourcetells which of your views made the current selection. - Planning diagnostics carry
EntityReftargets, so a diagnostic list can select or reveal its tasks and resources through the same bindings. The reference list, inspector, diagnostics panel and context toolbar of the demo are inexamples/components/; they are examples to copy and adapt, not part of the package.
A multi-view app: linked selection, saving and undo
The production demo (examples/production/, served at /demo/) is a complete app on these parts: a planning tab with a process graph, a Gantt chart and a load chart, a lot flow tab with a second graph and a table, an approval workflow and a schedule sheet. Its wiring is in workspace.ts; the steps below follow it.
1. One document, one transaction. Keep everything the user edits in one document and save it through one useEditTransaction, so saving, conflicts and undo cover every view. A change replaces the part of the document its view owns:
ts
type AppChange =
| { area: 'plan'; plan: Plan }
| { area: 'approval'; flow: Flow }
| { area: 'sheet'; tasks: readonly Task[] }
const transaction = useEditTransaction<AppDocument, AppChange>({
documentId: 'production', initialState: loaded.document, initialVersion: loaded.version,
adapter: {
validate(_document, changes) {
for (const change of changes) if (change.area === 'sheet' && !scheduleSheet(change.tasks).ok) return 'The sheet cannot be scheduled.'
},
apply(document, changes) {
let next = document
for (const change of changes) {
if (change.area === 'plan') next = { ...next, plan: change.plan }
else if (change.area === 'approval') next = { ...next, approval: change.flow }
else next = { ...next, sheet: change.tasks }
}
return next
},
save: (request, candidate) => server.save(request, candidate),
},
})
// Every view renders this: the candidate while it is saved, else the accepted document.
const document = computed(() => transaction.candidateState.value ?? transaction.acceptedState.value)Each view derives what it draws from document and proposes changes with transaction.submit([change]). Check a change with the view's own, localized messages before submitting (the schedule sheet schedules the candidate tasks and shows the cycle it would create); the adapter's validate is the last line of defence. Only one save runs at a time: a submit while saving resolves to busy, so tell the user, or disable the actions that submit until status is no longer saving.
2. One save bar. Show status, result and acceptedVersion in one place, with app-wide Undo and Redo (transaction.undo() and redo(), disabled while saving). A rejected save leaves the accepted document as it was, so the views show it again. On conflict, fetch the latest document and pass it to transaction.refresh(state, version); that resets the history. On uncertain, ask the server for the operation's result and pass it to transaction.reconcile(result). Until then, block saves, undo and redo yourself: useEditTransaction refuses a new save only while one is in flight, and one started while the result is unknown replaces the unknown operation, which then can no longer be checked. The demo disables Adopt, Undo and Redo while saving or uncertain and refuses edits from the other tabs with a reason in the save bar; proposals can still be opened and edited. Do not offer to just dismiss an unknown result (clearResult): the save may have been applied, and the app would go on showing an older version than the server's. Offer checking (reconcile) and loading the latest version (refresh). The demo's save bar is examples/components/SaveStatus.vue with the mock server examples/adapters/transactionStore.ts, which can answer with each of these.
Local state that depends on the document, such as an open proposal or a selected step, must follow undo, redo and refresh: the demo closes the plan proposal in its undo, redo and reload functions, and the approval tab moves its selection when an undo removes the selected step. Tie such state to the save it belongs to, not to whatever is on screen when an answer arrives: the demo remembers which proposal a plan save adopts, closes that one when the save is accepted (and only if it is still open, so a proposal opened during the save survives), and keeps the operation ID of a save whose answer was lost, so that a later reconcile that reports it accepted closes its proposal too and it cannot be adopted twice.
Only submit runs your adapter's validate. A document that refresh loads, and the state of an accepted (or reconciled) result, come from the server as they are, so a view derived from them must handle documents your own edits would never produce: the demo's schedule sheet checks ok of its ScheduleResult and, for a stored sheet that no longer schedules, keeps the grid editable and says why, instead of reading the tasks of a failed result. The mock server checks the other planner's change with the same scheduleSheet before it stores it, as a real server would validate every write.
3. One linked selection. Create one useLinkedSelection next to the transaction and give every view of the same entities its bindings. The planning operations are the steps of the lot in the lot flow, so the demo binds each operation to its planning node, bar, row and load (taskViewBindings) and to its lot flow node:
ts
const linked = useLinkedSelection({ bindings: () => [
...taskViewBindings({ tasks: [...schedule.value.byId.values()], taskKind: 'operation', assignments }),
...taskIds.map((id): ViewBinding => ({ entity: { kind: 'operation', id }, target: { view: 'graph', kind: 'node', id: lotStepOf[id] } })),
] })Both graphs report as the graph view; this works because a node ID of one graph names the same entity, or nothing, in the other. Each graph passes the IDs of linked.graph.value.selectedNodeIds that are its own as its selection, and the lot table selects with selectEntities because it is not a component view. Detail panels read linked.selectedEntities, so the operation selected in planning is the step shown in the lot flow after a tab switch, and the other way round. Link only what is the same entity: the approval workflow and the schedule sheet show other data and keep their own selection.
4. Clearing. Wire background-click and idle-escape of each component to linked.clearSelection(). Escape then cancels a drag first and clears the selection on the next press.
The browser scenarios in test/browser/production-demo.spec.ts walk through it: a selection that follows a tab switch, a save that the server rejects, a conflict with another writer, a lost answer, and an undo from one tab that reverts an edit made in another.
Search, sort and saved views
Keep the source rows, bars and dependencies as they are and render the output of projectTimelineView or useTimelineView(...).projection. A search keeps each matching row with its ancestors, because a row array without a row's parent is invalid. Dependencies to hidden bars are removed from the displayed array; show removedDependencyCount and use hiddenTargets to offer a way to reveal the hidden bar. Sorting reorders siblings only. It does not change the business order or the WBS codes, which come from the original rows. Column filters (TimelineViewState.filters) keep the ancestors of matching rows like the search. GanttChart can offer both in its header: pass sortable-columns and filterable-columns, bind sort and filters to the view state and apply update:sort and update:filters with setSort and setFilters (see Header sorting and filtering); the chart never sorts or filters by itself. Turn a sort into a permanent order with a separate row move. Run scheduling, load and diagnostics on the full input. An application that shows the rows in its own tree table, without a chart, can call projectTimelineRows with the same view state: it applies the same search, filters, sort and collapsed-ID checks to the rows alone.
To save a view, store snapshot() (or any TimelineViewState) as JSON, for example in the application's snapshot. Register sort rules and zoom presets in code and save only their IDs. When restoring, call parseTimelineViewState, then read diagnostics for dropped columns or rules and for columns added since the save. Pass projection.collapsedIds and projection.window to the chart yourself; the view state does not change the chart.
For typed editing, give a column a field spec. A time field needs an explicit timeZone, utcOffsetMinutes or caller-supplied parse and format, and a duration field states whether it is elapsed or working time and its unitSize. Pass the text from an editor to parseFieldValue and propose the resulting value to the parent. Do not store an empty or invalid input as text. In GanttChart, a column with field emits field-edit instead of cell-edit: listen to field-edit, check it in validateFieldEdit and apply change.after to your row. Provide your own editor through the cell-editor slot (call commit(value) or commitText(text) and cancel()), or leave the slot out to use the built-in text input, which parses with the field. A cell slot still owns the whole cell. An editor that commits on Enter should skip keys with event.isComposing (or keyCode 229), so that confirming an input method conversion does not commit; the built-in inputs already do.
Export to SVG and PNG
Call exportSvg or exportPng on a NetworkGraph, GanttChart, TaskBoard, EventCalendar or TreeGrid ref to save the whole chart, board, calendar view or grid, independent of scrolling, zoom, culling or row virtualization. The SVG is a standalone document string; the PNG is rasterized in the browser at the scale you pass.
ts
const svg = timeline.value!.exportSvg({ title: 'Production plan' })
const png = await timeline.value!.exportPng({ scale: window.devicePixelRatio })
const url = URL.createObjectURL(png)
Object.assign(document.createElement('a'), { href: url, download: 'plan.png' }).click()
URL.revokeObjectURL(url)The export reads the --vw-* colours and the font in effect on the component, so a theme applies automatically; pass theme to override individual colours, for example a light theme for printing from a dark UI. The default rendering is exported: slot content is not, so pass barLabel, rowLabel, rowHeading, nodeLabel, nodeDetail, edgeLabel, cardLabel, cardDetail or eventLabel when your slots change text. TaskBoard also reads --vw-board-wip-warning and --vw-board-wip-under, and TreeGrid --vw-tree-grid-indent, --vw-tree-grid-selected and --vw-tree-grid-highlight; a failed cell mark uses the critical theme colour. Fonts are not embedded; a viewer without the font uses a fallback.
To render on a server or in a worker, call renderGraphSvg, renderTimelineSvg, renderTaskBoardSvg, renderEventCalendarSvg or renderTreeGridSvg from @eightkk/vue-weave/core with the same data (a layout or TimeScale for the first two) and an explicit theme. EventCalendar exports every view, agenda included (pass agendaDays as on the component). Before mounting, as on a server, the component exportSvg methods use the default theme and font, and exportPng rejects. Large charts produce large SVG strings. For PNG, width × scale and height × scale must stay within 16,384 pixels per side and 268,435,456 pixels in total; export a timeRange, rowRange or columnRange slice, or lower scale, for bigger charts and grids.
Saving and restoring a view
Use a snapshot to persist a chart's data and saved view as JSON (see "Versioned JSON snapshots" in api.md).
ts
import { parseWeaveSnapshot, restoreWeaveSnapshot, serializeWeaveSnapshot } from '@eightkk/vue-weave/core'
// Save. Pass savedAt yourself; the same input and metadata give the same text.
const text = serializeWeaveSnapshot({
kind: 'graph',
metadata: { title: 'Order flow', savedAt: new Date().toISOString() },
data: { nodes, edges, groups, positions, sizes }, // positions and sizes are Maps
view: { graph: { camera: { center, scale }, collapsedGroupIds } },
}, { codecs: [dateCodec], space: 2 })
// Restore. Nothing is applied until the whole snapshot is valid.
const parsed = parseWeaveSnapshot(text)
if (!parsed.ok) return showErrors(parsed.diagnostics)
const restored = restoreWeaveSnapshot(parsed.snapshot, { codecs: [dateCodec], layouts })
if (!restored.ok) return showErrors(restored.diagnostics) // the screen is unchangedThe restore procedure for a graph is: accept the restored nodes, edges, groups, positions, sizes and view.collapsedGroupIds into your state (positions and sizes are Map props, collapsedGroupIds is a Set), wait for the update with nextTick, then restore the camera. Replacing every node makes the chart fit itself to the new content, so a camera set earlier would be overwritten. In short: update nodes, await nextTick(), restore camera.
The camera is stored as the graph point at the viewport center plus the scale, so the same snapshot looks the same in a container of any size. Read it with getViewportCenter() and getViewport().scale, and restore it with setViewportCenter(view.camera.center, view.camera.scale) after the nextTick above:
ts
const snapshot = restored.snapshot // kind 'graph'
nodes.value = snapshot.nodes
edges.value = snapshot.edges
positions.value = snapshot.positions
collapsed.value = snapshot.view?.collapsedGroupIds ?? new Set()
await nextTick()
const camera = snapshot.view?.camera
if (camera) graph.value?.setViewportCenter(camera.center, camera.scale)Functions are never stored. Columns, layouts, sort comparators, editors and renderers are saved by name and resolved on restore from the registry you pass to restoreWeaveSnapshot: { codecs, layouts, columns, editors, renderers, comparators, onMissing }. columns maps a column ID (or the saved registryId) to its label, value and other functions, layouts maps a layout ID to a factory that receives the saved options. A name that is not registered fails the restore, unless onMissing: 'fallback' turns it into a warning and the default display; a missing codec always fails. Keep registries in code and version them with your application, and record a codec version when its encoding changes.
For a timeline or planning snapshot, pass restored.rows and restored.bars (or restored.input and restored.schedule) to your state first, then apply view.window, view.collapsedRowIds and the resolved view.columns. Reading a file never saves to a server by itself. To apply it to server data, fetch the server's current version and save the restored data as one change; metadata.sourceVersion is not that version.
Loading only what is visible
GanttChart renders only the rows and the time window on screen, and NetworkGraph can cull what is off screen, but both still validate and index every item they are given. For plans or graphs too large to fetch at once, load only what is shown. The library stays controlled: GanttChart reports what it renders, useWindowedData keeps the request state, and your load function fetches. Nothing is requested during server rendering.
vue
<script setup lang="ts">
import { ref } from 'vue'
import { GanttChart, useWindowedData, type TimelineBar, type TimelineDependency, type TimelineVisibleWindow } from '@eightkk/vue-weave'
const day = 86_400_000
// `rows` (the whole row skeleton), `range` (the whole plan) and `planVersion` come from your application.
const view = ref<TimelineVisibleWindow>()
const filter = ref('all')
const plan = useWindowedData<TimelineBar, TimelineDependency>({
view,
condition: () => `${filter.value}@${planVersion.value}`, // results for another filter or version are never attached
chunkSize: 7 * day, // requests are aligned to weeks...
origin: range.start,
padding: day, // ...and a day of padding means small scrolls do not refetch
load: async (request, { signal }) => {
const query = new URLSearchParams({ from: String(request.start), to: String(request.end), rows: request.rowIds!.join(','), filter: filter.value })
const response = await fetch(`/api/plan/bars?${query}`, { signal })
if (!response.ok) throw new Error(`Loading failed (${response.status})`)
return response.json() // { items: TimelineBar[], links: TimelineDependency[] }
},
})
</script>
<template>
<p role="status">{{ plan.status.value }}</p>
<button v-if="plan.coverage.value.failed" type="button" @click="plan.retry()">Retry</button>
<GanttChart :rows="rows" :bars="plan.items.value" :dependencies="plan.resolvedLinks.value" :range="range" readonly
@visible-window-change="view = $event" />
</template>- What is requested. The window (
[start, end), half-open like every interval in the library) is padded, aligned to chunks, and split into cells of one chunk of one row. Only cells that are not loaded, loading or failed are requested; adjacent chunks with the same missing rows share one request. A request asks for the items that overlap[start, end); because chunks are half-open, a bar that ends at midnight is not fetched for the next day, and a milestone at midnight belongs to the next day. - Rows. The row skeleton (
rows) is passed whole; it is what scrolling and collapsing work on.rowIdsin the event are the rendered rows after collapsing, with overscan. To fetch child rows on expansion, watchexpandedIds(orupdate:collapsedIds) and load the children of newly expanded rows yourself; collapsing a row while its children's bars load aborts the requests that no longer cover a visible row. - Superseded and stale responses. Scrolling away aborts requests whose cells are all out of view (
signalaborts; pass it tofetch), and a late answer to an aborted or superseded request is ignored even when it arrives. A fast scroll from A to B and back to A issues a new request for A, and only that one's answer is applied. Answers are matched by request ID and by condition, so an answer that arrives although yourloadignored the abort, or a rejection after an abort, changes nothing and is not reported aserror. - Condition changes come first. When the condition and the view change together, the condition is processed first: every request of the old condition is aborted and all its items, links and cell states are dropped before the new view is checked. So even if the new view is invalid, nothing of the old plant, filter or plan version stays on display or arrives later.
- Invalid views. A view with more cells than
maxCells(default 100000), a non-finite view, one withend < start, or one so far fromoriginforchunkSizethat its chunk indices leave the safe integer range, is not thrown from the watcher: it is reported througherrorwithout arequest, every request in flight is aborted, no view is current (statusisunloaded,completeis false) and the data of the current condition stays. The error clears as soon as a valid view is set;retry()andinvalidate()request nothing while the view is invalid. A row ID inrowIdsthat is not a non-empty string is invalid in the same way (Invalid view row ID: <value>); a repeated one is dropped. The coresetWindowedViewthrowsRangeErrorfor the same views (anErrorfor a bad row ID) and then changes nothing; to switch the condition anyway, callsetWindowedView(state, undefined, condition)first. Aconditionthat is not a string, or avieworconditiongetter that throws, is reported the same way, including on the first read (theuseWindowedDatacall does not throw for it, also during server rendering); an invalid condition also drops the data, and once the getter returns a valid value again the view is requested again. A view whoserowIdsis empty (a filter that matches no row) is valid and requests nothing. - Duplicates. A bar spanning two chunks is returned by both requests; items and links are merged by ID, so it is kept once (the later answer replaces it).
- Status.
status(andcoverageOf(window)for any window, for example one row) distinguishesunloaded,loading,loaded-empty(fetched, nothing there),loadedandfailed. A failed request keeps everything already loaded on display; its cells stayfaileduntilretry().invalidate()refetches the view while the current items stay on display; a newconditiondrops everything, because data for another filter or version must not be mixed in. - Dangling links. A dependency loaded with one bar may point to a bar that is not loaded. The components throw for links to unknown items, so bind
resolvedLinks;danglingLinksholds the rest with theirmissingIds, and they move toresolvedLinksas soon as the missing bar arrives. Outside the composable,splitDanglingLinks(links, presentIds)does the same split. If yourlinkEndsaccessor throws, the failure is reported througherror(after a failed request or an invalid view, which come first),resolvedLinksanddanglingLinksare both empty rather than partly filled, and the loaded items and links stay; it clears when the split works again. A link whose end isundefinedor not a string is dangling, not an error. - Memory. Loaded items are kept until the condition changes or
resetWindowedData; to bound memory, change the condition or keep your own cache inload.
Partial data cannot determine deadlines, critical paths, total load or plan comparisons. complete is true only when every cell of the current view has loaded, which says nothing about the rest of the plan. Run scheduleTasks, levelResources, calculateResourceLoad and comparisons on complete inputs (on the server, or in the client over the full data set) and display their results as data, or label any figure computed over the loaded part as partial. Totals must not change when the user scrolls; the demo's counters show fetched versus total items and say so.
Expanding a graph one hop at a time
For a graph, load the neighbourhood of the selected nodes and grow it on request. The graph expansion helpers merge pages, deduplicate nodes and edges (cycles and shared neighbours come back from several pages), remember which nodes have been expanded and keep edges to nodes that are not loaded out of the component input:
ts
import { shallowRef, computed } from 'vue'
import { beginGraphExpansion, cancelGraphExpansion, createGraphExpansion, graphExpansionView, mergeGraphExpansionPage } from '@eightkk/vue-weave'
const graph = shallowRef(createGraphExpansion({ nodes: [selectedNode] }))
const shown = computed(() => graphExpansionView(graph.value)) // bind shown.nodes and shown.edges to NetworkGraph
async function expand(id: string) {
graph.value = beginGraphExpansion(graph.value, [id])
try {
const page = await api.neighbours(id) // { nodes, edges } one hop around id
graph.value = mergeGraphExpansionPage(graph.value, page, [id])
} catch (error) {
graph.value = cancelGraphExpansion(graph.value, [id])
}
}shown.dangling lists edges waiting for a node, and shown.frontierIds the loaded nodes not expanded yet. By default each expansion gives NetworkGraph a larger graph, which it lays out again, so existing nodes can move. To keep them where they are, place each page around the boxes on display with layoutGraphIncrementally and pass the result through a layout function of stable identity:
ts
import { graphLayoutChangeMetrics, layoutGraphIncrementally, layoutLayeredGraph, type GraphLayoutFunction } from '@eightkk/vue-weave'
const first = layoutLayeredGraph(shown.value.nodes, shown.value.edges)
const kept = shallowRef(layoutGraphIncrementally(shown.value.nodes, shown.value.edges, first.boxes, { previousLayout: first }))
// Bind `:layout="keepLayout"` and keep this function: a new function would re-fit the camera.
const keepLayout: GraphLayoutFunction = (nodes, edges) =>
layoutGraphIncrementally(nodes, edges, kept.value.boxes, { previousLayout: kept.value })
watch(shown, ({ nodes, edges }) => {
const next = layoutGraphIncrementally(nodes, edges, kept.value.boxes, { previousLayout: kept.value })
// A diagnostic: the nodes that were on display did not move.
console.assert(graphLayoutChangeMetrics(kept.value.boxes, next).maxDisplacement === 0)
kept.value = next
})Every node that was on display keeps its box exactly; each new node goes next to its loaded neighbours on the flow side (after a predecessor, before a successor) in free space, and pages without a loaded neighbour go below the graph (for LR). A predecessor of a node at the left edge is placed beside it instead, because new boxes stay at nonnegative coordinates unless allowNegative is set. The camera re-fits to a larger graph while it is fitted automatically; to keep the visible nodes in place on screen too, pin it before merging a page, for example graph.value.setViewport(graph.value.getViewport()). The Large plan demo has this as the "Keep positions when expanding" option and shows the largest move of a shown part (0).
To expand one direction or relation at a time ("show callers" and "show callees" as separate actions), pass a key to the same functions. Each key has its own frontier, so a node expanded downstream still offers its upstream expansion:
ts
async function expandDirection(id: string, key: 'forward' | 'backward') {
graph.value = beginGraphExpansion(graph.value, [id], { key })
try {
const page = await api.neighbours(id, key) // only the successors or only the predecessors of id
graph.value = mergeGraphExpansionPage(graph.value, page, [id], { key })
} catch (error) {
graph.value = cancelGraphExpansion(graph.value, [id], { key })
}
}
const canExpandBackward = (id: string) => graphExpansionView(graph.value, { key: 'backward' }).frontierIds.includes(id)A page merged without a key still marks its nodes expanded for every key, and a node expanded for some keys only stays in the unkeyed frontierIds. See Partial data loading for every rule.
Period tables from time buckets
A period table shows rows (items or metrics) by time columns (days, weeks, shifts). createTimeBucketColumns turns half-open periods into column descriptors with stable IDs, and aggregateTimeBuckets turns time-stamped quantities into one sparse cell { rowId, columnId, value, status } per row and column. The periods are yours: calendarBands gives local days or weeks in an IANA zone (23- and 25-hour days included), and gaps such as nights or weekends are allowed.
ts
import { aggregateTimeBuckets, calendarBands, createTimeBucketColumns, timeBucketIndexRange, windowedCoverage } from '@eightkk/vue-weave/core'
const columns = createTimeBucketColumns(calendarBands(range, 'day', { timeZone: 'Europe/Berlin' }), { width: 72 })
const cells = aggregateTimeBuckets(records, columns, {
rowIds: ['output', 'yield', 'stock'],
rules: { output: 'sum', yield: 'ratio', stock: 'last' }, // yield: value = good units, denominator = all units
carryForward: rowId => rowId === 'stock', // a stock level stays until the next reading
loaded: (rowId, bucket) => windowedCoverage(state, { start: bucket.start, end: bucket.end, rowIds: [rowId] }).status,
})
// Follow the chart: show only the columns of its visible window.
const { start, end } = timeBucketIndexRange(columns, visibleWindow)
const shownColumns = columns.slice(start, end)- Not loaded is not zero. A column outside
loadedhas statusunloaded(orloading,failed) and value null. A loaded column without items isloaded-empty: 0 forsumandcount, null for the other rules. Show the three differently. - Ratios from their parts. Aggregate a rate from numerator and denominator with the
ratiorule; never average the percentages of the columns. Totals and parent rows sum the cells'numeratoranddenominator. - Precomputed values. When the server already aggregates per period, use
precomputed: one value per row and column, passed through unchanged. - In a TreeGrid. Map each cell to a
TreeGridCell: a loaded value to{ value }, a loaded null to{ status: 'none' }andunloaded,loadingorfailedto thatstatus. TreeGrid does not accept theloadedstatuses or a null value. The "Period table" demo does this, with the columns following a GanttChart's visible window.
See Time bucket tables for every rule and error.
Spreadsheet editing in a schedule
Turn on spreadsheet on a Gantt chart with editable columns, and the cells work like a spreadsheet: select a rectangle with Shift+click, a mouse drag or Shift+arrows, copy, cut and paste tab-separated text with other spreadsheet applications, clear with Delete, fill down with Ctrl/Cmd+D or the corner handle, and type to edit a cell. Each operation arrives as one sheet-edit proposal (see Spreadsheet editing for every key and rule).
vue
<script setup lang="ts">
import { GanttChart, applyTimelineSheetEdit, useEditHistory, type TimelineFieldEdit, type TimelineSheetChanges } from '@eightkk/vue-weave'
const history = useEditHistory(initialRows)
// One helper applies a single field edit and a whole paste, fill or clear, so each is one undo step.
function apply(change: TimelineSheetChanges<Row>) {
history.commit(applyTimelineSheetEdit(history.state.value, change, {
field: (row, edit) => ({ ...row, [edit.fieldId]: edit.after }),
cell: (row, edit) => ({ ...row, [edit.columnId]: edit.after }),
}))
}
// Checks the batch as a whole, for example a total or a dependency cycle across several cells.
const checkSheet = (change: TimelineSheetChanges<Row>) => totalHours(change) <= 40 || 'More than 40 hours in total'
</script>
<template>
<GanttChart spreadsheet :rows="history.state.value" :columns="columns" :bars="bars" :range="range"
:validate-sheet-edit="checkSheet"
@field-edit="(edit: TimelineFieldEdit<Row>) => apply({ fieldEdits: [edit] })"
@cell-edit="edit => apply({ cellEdits: [edit] })"
@sheet-edit="apply"
@sheet-edit-rejected="reason => message = reason" />
<p role="status">{{ message }}</p>
</template>The parent derives the bars from its rows, so the chart follows every applied change. A rejected operation changes nothing; the chart announces the reason to screen readers, and the page should show it too, as above. In the schedule sheet demo, the grid holds start constraints, durations, predecessors, resources and progress; the bars, arrows and critical path come from scheduleTasks, and validateSheetEdit rejects a paste that would create a dependency cycle.
Tree grids, matrices and bills of materials
TreeGrid shows a row tree against columns. Keep three things apart in your data:
- Rows are positions. A row ID names one place in the tree, such as "the second use of bolt M6 in frame F1". The parent decides IDs, and a row move or delete changes positions only.
- Entities are what rows and cells stand for. Put them in
entities; the same part may be used in many rows.matchTreeGridEntities({ rows, columns, cells }, entities)returns every row and cell that lists one, so a highlight shows all usages. - Cells say what they know. A listed 0 is a value;
status: 'none'says the value is known to be absent,unknownthat it is not known,not-applicablethat the row has no such attribute, andunloaded,loadingandfailedthat it is not loaded.missingCell(on the grid or a column) states what an unlisted cell means.
Linking. TreeGrid is not a LinkedViewName, so it links through entities, and ViewTarget stays as it is. Report its activations with selectEntities, and draw the linked state from selectedEntities:
ts
const linked = useLinkedSelection({ bindings })
const matches = computed(() => matchTreeGridEntities({ rows: rows.value, columns, cells: cells.value }, linked.selectedEntities.value))
function activate(activation: TreeGridActivation) {
linked.selectEntities(activation.entities, { source: 'tree-grid' })
}
// <TreeGrid :rows="rows" :columns="columns" :cells="cells" :highlighted-row-ids="matches.rowIds"
// :highlighted-cells="matches.cells" @row-activate="activate" @cell-activate="activate" />A graph or Gantt chart bound to the same entities then highlights its items, and a selection made there highlights the grid's rows and cells. To show a row that a collapsed ancestor hides, call revealRow(rowId): it reports hidden-by-collapse with the displayed ancestor, and expanding is your decision (add the ancestors to expandedIds).
Loading children on demand. Give a row childStatus: 'unloaded'. Expanding it emits expand-request; set childStatus to loading, fetch, then add the child rows with childStatus: 'loaded' (or failed, which a status line shows; Enter on it asks again). Keep loaded rows out of the undo history, or replace the current history entry, since loading is not an edit.
Editing. Every change is a proposal, and validators are synchronous. Accept a cell-edit or a sheet-edit with applyTreeGridEdits, a row-create with insertTreeGridRow (you choose the new ID), a row-delete with deleteTreeGridRows and a row-move with moveTimelineRow, and commit each result as one history entry (useEditHistory) or one save (useEditTransaction). A paste, fill, clear or cut is one batch, so it undoes in one step. Changes to rows, columns or cells cancel an open editor, a fill drag or a row drag (edit-cancel with source-changed), so a server update never lands in a stale edit. For a server-backed grid, send the batch with the version it was made against, as for the other components (see Saving through a server).