本文へ移動

連動ビューとデータ ​

これらの補助関数は、アプリケーションのビューどうしと、その裏のデータをつなぎます。ビューバインディングはアプリケーションのエンティティ(タスク、リソース、部品)を各ビューの表示要素に対応づけるので、バーを選ぶとそのノード、負荷の区間、ツリーグリッドの行がハイライトされます。useLinkedSelection はこれをリアクティブに行います。時間範囲の探索は、ある時間帯に行われた作業を示します。diffStructure は部品表の 2 つの版など、平坦またはツリー状のコレクションの 2 つの版を比較します。ウィンドウ化データとグラフの展開は画面に見えている部分だけを読み込み、時間バケットは期間の表(日・週・シフトごとの行)を作ります。

どれも純粋な関数でデータを返すだけです。コンポーネントには、結果の ID やハイライトをプロップとして渡します。

最小の例 ​

ts
import { diffStructure } from '@eightkk/vue-weave/core'

const before = [
  { id: 'bike', name: '自転車' },
  { id: 'frame', parentId: 'bike', name: 'フレーム', quantity: 1 },
  { id: 'bell', parentId: 'bike', name: 'ベル', quantity: 1 },
]
const after = [
  { id: 'bike', name: '自転車' },
  { id: 'frame', parentId: 'bike', name: 'フレーム', quantity: 2 },
]
const diff = diffStructure(before, after, { key: 'id', parentKey: 'parentId', fields: ['name', 'quantity'] })
diff.changed // [{ key: 'frame', fields: [{ name: 'quantity', before: 1, after: 2 }] }]
diff.removed // ['bell']

例: 連動ビュー、ツリーグリッド、部品表。ガイド: データ、保存、連動ビュー。型: diffStructure、ViewBinding、useLinkedSelection、useWindowedData。

英語の詳細

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

Linked views ​

Core helpers and a composable link entities (tasks, resources, anything the application defines) to what the graph, timeline and load views show. The application passes the results to the components: selectedIds for the view the user acts in and display-only highlights for the others (NetworkGraph highlightedNodeIds and highlightedEdgeIds, GanttChart highlightedBarIds and highlightedDependencyIds, or relatedIds, matchIds or its own handling). Both components report what the user points at or activates through target-enter, target-leave and target-activate (ViewTargetEvent; NetworkGraph narrows it to ViewTargetEvent<GraphViewTarget>), and revealNode and revealBar bring a linked item into view (RevealResult). Types: GraphViewTarget, ViewTargetSource, ViewTargetEvent, RevealStatus, RevealOptions and RevealResult.

ts
import { buildViewBindingIndex, resolveViewTargets, resolveEntityRefs } from '@eightkk/vue-weave/core'

const index = buildViewBindingIndex([
  { entity: { kind: 'task', id: 'A' }, target: { view: 'graph', kind: 'node', id: 'n1' } },
  { entity: { kind: 'task', id: 'A' }, target: { view: 'timeline', kind: 'bar', id: 'b1' } },
])
resolveViewTargets(index, [{ kind: 'task', id: 'A' }]) // { targets: [n1, b1], unknown: [] }
resolveEntityRefs(index, [{ view: 'timeline', kind: 'bar', id: 'b1' }]) // { entities: [task A], unknown: [] }
ExportContract
buildViewBindingIndex(bindings)Two-way index. Many-to-many links are allowed, identical bindings count once, inputs are not modified. Keys encode kind and ID as a JSON tuple, so a task A and a resource A never collide. Throws Error for an empty kind and for an ID or load resourceId that is not a non-empty string (Invalid entity ID: <value>, Invalid view target ID: <value>, Invalid resource ID: <value> (load target)), and RangeError for a load range that is not finite or ends before it starts.
resolveViewTargets(index, entities){ targets, unknown }: targets without repeats; entities with no binding are listed in unknown.
resolveEntityRefs(index, targets){ entities, unknown }. A load target matches bound load targets of the same resource whose half-open range overlaps it.
taskViewBindings({ tasks, assignments?, dependencies?, inactiveTaskIds?, taskKind?, dependencyKind? })The ViewBinding[] of a plan whose views show tasks and dependencies under their own IDs (for example scheduleToGraph nodes and edges and GanttChart bars, rows and dependencies). Each task becomes the entity { kind: taskKind ?? 'task', id }, bound to the graph node, the timeline bar and the timeline row with its ID; each assignment binds its task to a load target of its resource for every period in which it uses the resource, assignmentWorkPeriods(task.work, assignment), so the bindings agree with calculateResourceLoad for the same tasks and assignments (pauses, calendar breaks and the work outside a workOffset/workDuration part bind nothing; a milestone binds no load). Each dependency becomes { kind: dependencyKind ?? 'dependency', id }, bound to the graph edge and the timeline dependency with its ID. tasks takes a schedule's tasks ({ id, work? }; work is read only for assigned tasks) and assignments the ResourceAssignment[] passed to calculateResourceLoad; the assignments of inactiveTaskIds (for example a schedule's) are skipped, as there. Order: per task its node, bar, row and load targets (per assignment in assignment order, its periods in time order), then per dependency its edge and arrow. Add bindings of your own for other targets (spread both into one array). Throws Error for an invalid or duplicate task or dependency ID, an empty kind, an assignment of an unknown task or with an invalid resource ID, an inactive task that is also in tasks and an assigned task without a work array, and RangeError for work segments without safe integer endpoints and positive length or an invalid workOffset or workDuration. The input is not modified. Related type: TaskViewBindingsInput.
resolveLoadTargets(segments, targets){ segments, unknown }: current segments that overlap a load target. A load segment has no ID and its boundaries change when load is recalculated, so a target that overlaps no current segment is reported in unknown and never replaced by another segment.
traverseGraph({ nodes, edges }, startIds, { direction, maxHops })Iterative walk ('forward', 'backward' or 'both', default 'both'; maxHops default Infinity). Returns { nodeIds, edgeIds, unknownIds }; unknown start IDs are reported, not thrown. A duplicate or empty node or edge ID and an edge with an unknown end throw an Error. 'both' walks each direction independently, like graphNeighborhood. Safe on cycles and long chains. Opt-in options: see Traversal filters, limits and paths.
graphTracePath(result, nodeId, { direction }?)Rebuilds a path from a start to nodeId from a traverseGraph result made with paths: true. Returns GraphTracedPath ({ direction?, nodeIds, edgeIds }) or undefined. See Traversal filters, limits and paths.
resolveCollapsedTargets(collapse, { nodeIds, edgeIds }, edges)Resolves IDs of the full graph against a collapseGraphGroups result: hidden nodes to their proxy, edges merged into a re-attached edge to the merged edge, and edges dropped inside one collapsed group to that group's proxy node. edges are the edges given to collapseGraphGroups. Returns { nodeIds, edgeIds, unknownNodeIds, unknownEdgeIds }.
timelineBarsInRange(bars, range, { rowIds }?)The bars worked on in the half-open range [range.start, range.end), in input order, with their own type (B extends TimelineBarActivity: id, rowId, start, end, segments). See Time range exploration.
resolveTimeRangeTargets(index, barIds, { graph, traversal }?)TimeRangeTargets: { activeBarIds, activeEntities, activeTargets, relatedEntities, relatedTargets, unknownBarIds }. See Time range exploration.
useLinkedSelection({ bindings, onSelect, timeRange })See below.

useLinkedSelection returns select(view, targets), selectEntities(entities, { source }?), clearSelection(), hoverEnter(view, target), hoverLeave(view, target?), owner, selectedEntities, selectionSource, hoveredEntities and the per-view sets graph, timeline and load. The view the user acted in owns the selection: its selected* sets contain what it selected, and every view gets highlighted* sets for the other linked targets, so a linked view never receives targets it did not select. Selecting the same targets again is a no-op and does not call onSelect, so connecting a view's events back to select does not loop. A new selection replaces the previous one, whichever view made it. Hover only produces highlights, and hoverLeave clears them. The optional timeRange adds display-only highlights for a time range; see Time range exploration.

onSelect(entities, owner) is called after a select, selectEntities or clearSelection that changed the selection; owner is undefined after selectEntities and after clearing.

Views that are not graph, timeline or load (your own table or list) select through entity references:

MemberDescription
selectEntities(entities: Iterable<EntityRef>, options?: { source?: string }): { changed: boolean; unknown: EntityRef[] }Replaces the selection of any view with entities. The selection has no owner: owner stays undefined, no view gets selected* sets or load.selected, and every view gets highlighted* sets and load.highlighted for the targets bound to the entities, re-resolved when bindings change. selectedEntities returns the given entities without repeats, in input order, unbound ones included; unknown lists those no binding reaches now. An empty input clears the selection like clearSelection(). Selecting the same entities (in any order) with the same source again returns changed: false and does not call onSelect, so wiring a table's selection events back cannot loop; otherwise onSelect(entities, undefined) is called. A later select(view, …) replaces it and it replaces a view's selection. Throws Error for an entity whose kind or id is not a valid non-empty string, or a source that is not a string; a throwing call changes nothing.
selectionSourceComputedRef<string | undefined>: the source given to selectEntities for the current selection; undefined for a view's selection, no selection, or selectEntities without source.

An external view renders its own selection from selectedEntities (which also reflects a selection made in another view) and its hover from hoveredEntities. Hover starts only from the linked views; there is no entity-based hover.

ViewPass to the component
graph (LinkedGraphSets)selectedNodeIds to NetworkGraph selectedIds; highlightedNodeIds and highlightedEdgeIds to the props of the same name; highlightedGroupIds to your own group rendering
timeline (LinkedTimelineSets)selectedBarIds to GanttChart selectedIds; highlightedBarIds and highlightedDependencyIds to the props of the same name; highlightedRowIds to your own row rendering
load (LinkedLoadSets)selected to GanttChart selectedLoadTargets and highlighted to highlightedLoadTargets

Each set object also has related* sets (relatedNodeIds, relatedEdgeIds, relatedGroupIds; relatedBarIds, relatedDependencyIds, relatedRowIds; load.related). They are empty unless timeRange has a traversal; see below.

revealLinkedTarget({ reveal, expand?, maxExpansions? }) (Vue entry) goes to a linked item that may be inside a collapsed group or row. It calls reveal() (for example () => graph.value?.revealNode(id, { focus: true })); when the result is hidden-by-collapse it asks expand(proxyId, result), which expands that proxy in the controlled collapsedGroupIds or collapsedIds and returns true, or returns false to decline. After an accepted expansion it waits for the render (two nextTicks) and reveals again, up to maxExpansions (default 16) nested collapses. It resolves a LinkedRevealResult: the last RevealResult plus expandedIds, and declined: true when expand declined or accepted without the item becoming visible. It never expands anything itself, and it resolves revealed only when the last reveal did, so a refused expansion is never reported as a completed move. Without expand it returns the first result.

Related exported types: ViewBinding, ViewBindingIndex, LoadSegmentLike, ResolvedEntityRefs, ResolvedViewTargets, ResolvedLoadTargets, GraphTraversalDirection, GraphTraversalOptions, GraphTraversalResult, GraphWalkDirection, GraphTraversalTruncation, GraphTraversalStep, GraphTraversalVia, GraphTracedPath, CollapsedTargetsResult, LinkedViewName, UseLinkedSelectionOptions, RevealLinkedTargetOptions.

Time range exploration ​

Select a time range, for example 14:00–16:00 on inspection machine X, and show what was worked on in it in the linked views, optionally with what the graph relates to it. Times are never inferred from the graph: activity comes only from the bars.

ts
import { buildViewBindingIndex, resolveTimeRangeTargets, timelineBarsInRange } from '@eightkk/vue-weave/core'

const active = timelineBarsInRange(bars, { start: t1400, end: t1600 }, { rowIds: ['machine-x'] })
const result = resolveTimeRangeTargets(buildViewBindingIndex(bindings), active.map(bar => bar.id), {
  graph: { nodes, edges }, traversal: { direction: 'forward' }, // all successors
})
result.activeTargets  // the active bars and every target bound to their entities
result.relatedTargets // what the walk reached, without the active targets

timelineBarsInRange(bars, range, options?) follows the half-open interval rules:

  • A bar without segments is active when bar.start < range.end && bar.end > range.start.
  • A bar with segments is active only when one of its work segments overlaps the range the same way. A pause between segments (a lunch break, for example) that covers the whole range does not count, although the bar's outer extent overlaps.
  • A milestone (start === end) at time t is active when range.start <= t < range.end: at the range start, not at its end.
  • An empty range (start === end) is the instant t: it matches work with start <= t < end and milestones at exactly t.
  • options.rowIds keeps only bars of those rows; unknown row IDs match nothing.

It throws RangeError for a range or bar time that is not finite or ends before it starts, and for empty, non-finite or zero-length segments or segments on a milestone. It returns the input bar objects in input order and does not modify them.

resolveTimeRangeTargets(index, barIds, options?) resolves the active bars through a buildViewBindingIndex index. activeEntities are the entities bound to the bars; activeTargets are the bars themselves plus every target bound to those entities, so an active task's node, load range and other bars are active too. Bar IDs that no binding reaches stay in activeTargets and are listed in unknownBarIds. With graph and traversal (GraphTraversalOptions), it walks the graph with traverseGraph from the graph nodes of the active entities: { direction: 'forward' } for all successors, 'backward' for all predecessors, 'both' for both, { direction: 'both', maxHops: 1 } for direct neighbours, and maxHops to limit the depth; edgeFilter and maxNodes limit it to some relations or a number of nodes as in traverseGraph (paths is accepted but its result is not used). The walk is iterative and terminates on cycles. relatedEntities are the reached entities that are not active, and relatedTargets the reached graph nodes and edges and the targets bound to related entities, without any active target. Invalid traversal options or graph edges throw as in traverseGraph.

useLinkedSelection({ bindings, timeRange }) does both reactively. timeRange is a LinkedTimeRange ({ range, bars, rowIds?, graph?, traversal? }), a ref or getter, or undefined. Active targets join the highlighted* sets and load.highlighted, and related targets fill the related* sets, both without targets the owning view selected and without repeats; the returned timeRange computed holds the TimeRangeTargets. The range is display only: it never changes owner, selectedEntities, the selected* sets or calls onSelect, so Delete in a view never removes range-highlighted items. An invalid range throws RangeError when the sets are read; validate user input first. Without timeRange, no range targets are added and the related* sets are empty.

Pass graph.relatedNodeIds to NetworkGraph relatedIds to draw related nodes, and the edges between them, apart from active ones (vw-is-related instead of vw-is-highlighted). GanttChart has no related-bar prop; merge relatedBarIds into highlightedBarIds or style them yourself, for example through appearance or tone on derived bars.

Related exported types: TimelineBarsInRangeOptions, TimeRangeTargetsOptions.

Structure comparison ​

diffStructure(before, after, options) (core) compares two versions of a flat or tree-shaped keyed collection, for example two revisions of a bill of materials, a WBS or a product hierarchy. Unlike the PlanCollectionDiff parts of comparePlans, which name changed fields only, it returns the values of both versions. It is pure, uses loops only (a 12,000-item chain is fine), never changes its arguments and runs in linear time apart from the field comparisons. Resolve effective dates, variants and the like before the call: it compares two already resolved snapshots.

OptionMeaning
keyRequired. A property name or a function (item) => string that returns the key matching the two versions: a non-empty string, unique within each version.
fieldsOptional. A list of property names, compared in list order; or a function (item) => Record<string, unknown> that returns the compared values of an item (computed or normalized fields), compared in order of first appearance, the before item's fields first. Default: the own enumerable properties of both items in order of first appearance, without the properties that key and parentKey name when they are property names. A property that is undefined on one side and absent on the other is equal.
parentKeyOptional. A property name or a function that returns the parent key of a tree-shaped collection; undefined or null for a root. A parent must be a key of the same version, and the hierarchy must have no cycle. Omit it for a flat collection.
equalsOptional (before, after, field) => boolean, called for every compared field of every item that is in both versions. Default: Object.is, so objects and arrays are equal only when they are the same reference, NaN equals NaN, and 0 and -0 differ.

StructureDiff:

FieldMeaning
addedKeys only in after, in after order
removedKeys only in before, in before order
changedStructureChange { key, fields } for every key in both versions with a differing field, in before order; fields holds StructureFieldChange { name, before, after } in field order. The values are the inputs' own, not copies
movedWith parentKey: StructureMove { key, beforeParent?, afterParent? } for every key in both versions whose parent differs, in before order; a missing parent is a root. Always empty without parentKey. A new position among the same siblings is not a move

A parent field that the default field set leaves out (because parentKey names it) appears only in moved; with a parentKey function or a fields function that returns the parent, a parent change is reported in both lists. Each version is checked on its own, and the message of a failed check ends with (before) or (after): an Error for an invalid or duplicate key (Invalid item ID: "" (after), Duplicate item ID: a (before)), an invalid parent key (Invalid parent ID: …), an unknown parent (Unknown parent for item: <key>) or a cycle (The item hierarchy contains a cycle: <key>); a TypeError for a version that is not an array, an item that is not an object when properties are read, a key or parentKey that is neither a property name nor a function, fields that is neither a list of strings nor a function (or a function that returns no object) and an equals that is not a function; an Error for a field name listed twice. Errors thrown by your accessors pass through.

ts
import { diffStructure } from '@eightkk/vue-weave/core'

const diff = diffStructure(bomRevisionA, bomRevisionB, { key: 'partId', parentKey: 'parentPartId', fields: ['quantity', 'material'] })
diff.changed // [{ key: 'spoke', fields: [{ name: 'quantity', before: 32, after: 28 }] }]
diff.moved   // [{ key: 'spoke', beforeParent: 'wheel', afterParent: 'hub' }]

The exported types are StructureDiffOptions, StructureKeyAccessor, StructureDiff, StructureChange, StructureFieldChange and StructureMove.

Partial data loading ​

The components virtualise rendering, but validate and index every row, bar, node and edge they are given. To load only what is shown, GanttChart reports the window it renders, and the helpers below keep the request state; the application fetches. See Loading only what is visible for a walkthrough.

GanttChart:

Event / propMeaning
visible-window-change(window)TimelineVisibleWindow: start and end, the half-open time window [start, end) that the chart renders (the visible time area plus 80 px on each side, clipped to range; end >= start), in the chart's time units; rowIds, the rendered rows top to bottom (the displayed rows after collapsing, in the scrolled row window plus two overscan rows on each side); expandedIds, every displayed row that has child rows and is not collapsed. Emitted only in the browser after mounting (never during server rendering), when scrolling, resizing, zooming, collapsing or new rows change the window, after it has settled for visibleWindowDelay ms (during a long scroll still about every four delays), and only when it differs from the last reported window. The payload holds new arrays. Adding the listener changes no markup.
visibleWindowDelaynumber / 100. Settling delay of the event in milliseconds; 0 reports on the next task.

Core (@eightkk/vue-weave/core), all pure (no Vue, DOM or timers) and iterative:

  • createWindowedDataState<T, L>(options: WindowedDataOptions<T, L>, condition = ''): WindowedDataState<T, L>. Options: chunkSize (required, positive) and origin (default 0) cut the time axis into half-open chunks [origin + k·chunkSize, origin + (k+1)·chunkSize); padding (time units, default 0) widens a view before it is aligned to chunks, so small scrolls do not refetch; maxChunksPerRequest (default Infinity); maxCells (default 100000; a larger view throws RangeError); accessors itemId (default item.id), itemRow (default item.rowId), itemRange (default item.start/item.end) and linkId (default link.id). A cell is one chunk of one row (or one chunk, for views without rowIds).
  • setWindowedView(state, view: WindowedView | undefined, condition?): WindowedDataTransition ({ state, start: WindowedDataRequest[], abort: string[] }). Plans requests for the cells of the view that are not loaded, loading or failed (adjacent chunks with the same missing rows share one request) and aborts requests in flight whose cells are all outside the view; their cells become unloaded. A request that still covers a needed cell keeps running. A different condition (a caller-supplied filter or version token) aborts every request and drops all cells, items and links. A view with an empty rowIds (a row filter that matches nothing) needs no cell: it requests nothing, walks no chunk and aborts every request in flight. Otherwise the work is bounded by maxCells. Throws RangeError for a non-finite view, end < start, more than maxCells cells, or a view so far from origin for chunkSize that its chunk indices are not safe integers (Number.isSafeInteger) or its chunk boundaries origin + k·chunkSize are not distinct finite numbers, Error (Invalid view row ID: <value>, the shared ID rule) for a row ID in rowIds that is not a non-empty string, and TypeError for a view that is not an object or rowIds that is not an array. A repeated row ID is not an error: it is dropped and the first occurrence keeps its place (the same rules apply to the window of retryWindowedData and windowedCoverage). A throw changes nothing, so the given state keeps its condition, requests and data. To switch the condition even when the new view may be invalid, apply setWindowedView(state, undefined, condition) first (it never throws for a string condition) and set the view afterwards, as useWindowedData does.
  • WindowedDataRequest: requestId (new for every request, also when the same data is requested again), key (condition, span and rows as text), condition, start and end (chunk-aligned; return the items that overlap [start, end): item.start < end && item.end > start, a milestone when start <= item.start < end) and rowIds (absent for views without rows).
  • resolveWindowedRequest(state, requestId, response: T[] | WindowedDataPage<T, L>): WindowedDataSettlement ({ state, applied }). Merges items and links by ID (a bar that two overlapping requests return is kept once; the later response replaces it) and marks each cell of the request loaded (an item of that row overlaps the chunk) or loaded-empty. A response is matched by request ID and by condition: the response of an unknown, aborted or superseded request, or of a request whose condition is not the state's, is ignored (applied: false, state unchanged). Throws Error for an item or link without a non-empty string ID or with an ID twice in one response, TypeError for a malformed response, and whatever an accessor throws; all checks run before anything is merged, so after a throw the state is unchanged and nothing of the response is merged.
  • rejectWindowedRequest(state, requestId, error): marks the cells of the request failed; loaded items stay. Ignored for requests that are not in flight or not of the state's condition.
  • retryWindowedData(state, window?): failed cells (all, or those in window) become unloaded and the cells the view needs are requested again. Failed cells are never refetched otherwise.
  • invalidateWindowedData(state): aborts everything, makes every cell unloaded and requests the view again, keeping loaded items on display until they are replaced by ID. cancelWindowedRequests(state) aborts every request (cells become unloaded); resetWindowedData(state) also drops cells, items and links.
  • windowedCellStatus(state, time, rowId?) and windowedCoverage(state, window = state.view): WindowedCoverage: status, complete, total, unloaded, loading, empty, loaded and failed cell counts of a window, without padding. status is failed if any cell failed, else loading, else unloaded, else loaded if any cell has items, else loaded-empty. complete is true only when every cell of the window has loaded. windowedCoverage is not limited by maxCells, so it can check the whole extent of a plan: total is computed from the chunk and row counts and unloaded from the cells recorded in the state, so the work is bounded by the smaller of the window's cell count and the number of recorded cells, not by the width of the window. It throws like setWindowedView for an invalid window, and RangeError when the window's chunk indices are not safe integers or its cell count exceeds Number.MAX_SAFE_INTEGER. retryWindowedData throws the same errors for its window.
  • WindowedCellStatus: 'unloaded' | 'loading' | 'loaded-empty' | 'loaded' | 'failed'.
  • splitDanglingLinks(links, present, options?: { from?, to? }): { resolved, dangling } splits links into those whose both ends are in present (a Set, a Map by ID, anything with has, or an iterable of IDs), in input order, and DanglingLinks ({ link, missingIds }). GanttChart and NetworkGraph throw for links to unknown items, so pass only resolved; call it again when more items load and the dangling links whose ends arrived move to resolved. Without from/to accessors, links need from and to fields.
  • Graph neighbourhood expansion: createGraphExpansion(seed?: GraphExpansionPage), beginGraphExpansion(state, ids, { key }?), cancelGraphExpansion(state, ids, { key }?), mergeGraphExpansionPage(state, page: { nodes?, edges? }, expandedIds?, { key }?) and graphExpansionView(state, { key }?): { nodes, edges, dangling, frontierIds }. Pages are merged by node and edge ID (cycles and shared neighbours never duplicate), expandedIds are marked expanded, pendingIds tracks expansions in flight, edges holds only edges whose both ends are loaded and frontierIds the loaded nodes that are neither expanded nor pending. Throws Error for an invalid or duplicate ID within one page (Invalid graph page node ID: <value>, Duplicate graph page edge ID: <id> (in one page)). The helpers do not place anything: NetworkGraph lays the larger graph out again, unless each page is placed with layoutGraphIncrementally around the shown boxes (see Incremental placement).
  • Keyed expansion (GraphExpansionKeyOptions, { key?: string }) records what was expanded per node, for example 'forward' and 'backward' or a relation name. A keyed beginGraphExpansion adds the nodes to pendingIdsByKey (skipping nodes expanded entirely or for that key), a keyed cancelGraphExpansion removes them from it, and a keyed mergeGraphExpansionPage adds expandedIds to expandedIdsByKey and removes them from pendingIdsByKey. Both state fields are optional ReadonlyMap<string, ReadonlySet<string>> from key to node IDs; they appear after the first keyed call, a key whose set becomes empty is removed, and a state without them (created before, or by hand) stays valid. graphExpansionView(state, { key }) gives the frontier of that key: loaded nodes not in expandedIds or pendingIds and not expanded or pending for the key. How keyed and unkeyed calls interact: an unkeyed merge marks a node expanded for every key (it leaves every keyed frontier); an unkeyed expansion in flight takes a node out of every keyed frontier; a node expanded or pending for a key only stays in the unkeyed frontier; unkeyed and keyed cancels each remove only their own pending entry. Calls without a key behave as before and leave the keyed fields as they are. A key must be a non-empty string (Invalid graph expansion key: <value>, Error); options that are not an object throw TypeError., TimelineVisibleWindow, WindowedDataOptions, WindowedDataNormalizedOptions, WindowedDataRequest, WindowedDataPage, WindowedCell, WindowedInFlightRequest, WindowedDataState, WindowedDataTransition, WindowedDataSettlement, WindowedCoverage, WindowedCellStatus, DanglingLink, SplitDanglingLinks, SplitDanglingLinksOptions, GraphExpansionState, GraphExpansionPage, GraphExpansionView, GraphExpansionKeyOptions.

Vue (@eightkk/vue-weave):

  • useWindowedData<T, L = never>(options: UseWindowedDataOptions<T, L>): WindowedData<T, L> with the core options plus view (a ref or getter of a WindowedView, such as the visible-window-change payload), condition (ref or getter of a string, default ''), load(request, { signal }) (returns items, { items, links } or a promise of either; signal aborts when the request is superseded) and linkEnds. It returns state, items and links (all loaded, deduplicated), resolvedLinks and danglingLinks, coverage, status and complete of the current view, pending, error (WindowedDataError, a computed: the current failure with its request, or a view or link-ends failure without one), coverageOf(window), retry(window?), invalidate(), cancel() and dispose(). Requests start when the owning component mounts (immediately outside a component), so nothing is requested during server rendering; late, aborted and out-of-order responses are ignored, matched by request ID and condition, and a rejection after an abort is not an error. items keeps its contents while requests load or fail. A new condition is processed before the new view is checked: every request of the old condition is aborted and its data dropped first. An invalid view (more than maxCells cells, non-finite, end < start, chunk indices or boundaries that are not representable) or condition (not a string), and a view or condition getter that throws, are reported through error without request, never thrown, not even by the useWindowedData call itself when the first read of condition fails (also during server rendering): requests in flight are aborted, no view is current (complete false), the data of the current condition stays (an invalid condition drops it), and the error clears once a valid condition and view are read again, on the next change of either or when requests start; the view is then requested again. Invalid core options (such as chunkSize) still throw from the call. retry and invalidate first catch up with a condition or view change the watcher has not processed yet; they do nothing before mounting and request nothing while the view is invalid. A load that throws synchronously fails its request like a rejection. A linkEnds accessor that throws is reported through error as { error } without request, not thrown from resolvedLinks or danglingLinks: both are then empty arrays (never a partial split, so no link whose ends are unknown reaches a chart as resolved) while items, links, status and complete are unaffected. error shows, in this order, a failed request, an invalid view or condition, and then the link-ends failure; a lower one is shown once the higher ones clear, so a request failure is never hidden by it. The link-ends failure is derived, not stored: it clears by itself when the split succeeds again (other links, or anything the accessor reads has changed). The split stays lazy and cached: linkEnds runs only when resolvedLinks, danglingLinks or error (when no request or view failure is shown) is read, once per change of the loaded data. An end that is not a present ID (undefined, a number, '') is not an error: like splitDanglingLinks, the link is dangling and missingIds holds the value as returned. splitDanglingLinks itself throws whatever its accessors throw.
  • Types: UseWindowedDataOptions, WindowedData, WindowedDataLoader, WindowedDataError.

Partial data cannot answer questions about the whole: complete describes the loaded part of the current view, not the plan. Run scheduling, leveling, resource load, critical paths, deadlines and plan comparisons on complete inputs (on the server or over the full data set) and show their results as data, or label any figure computed over the loaded part as partial. A total or aggregate must not change when the visible subset changes.

Time bucket tables ​

Pure helpers (@eightkk/vue-weave/core) for period tables: rows (items or metrics) by columns (days, weeks, shifts) with sparse cells { rowId, columnId, value, status }. They do not depend on any component. See Period tables from time buckets.

Buckets are caller-defined half-open periods [start, end) in the caller's time units, sorted by time without overlaps. Gaps between them (nights, weekends, breaks between shifts) are allowed. The library does not define calendar periods here: generate days, weeks, months or hours in an IANA timeZone or fixed offset with calendarBands (a local day can last 23 or 25 hours; its bands carry labels), working periods with buildWorkPeriods, or pass your own. calendarBands clips the first and last band to its range, so pass a range on period boundaries to get whole periods.

  • createTimeBucketColumns<P extends TimeBucketPeriod>(periods: readonly P[], options?: TimeBucketColumnOptions<P>): TimeBucketColumn[] gives { id, label, width, start, end } per period, in order. id is options.id(period, index), else period.id, else idPrefix + start (idPrefix default 'bucket:'), so a column keeps its ID when the shown periods move. label is options.label(period, index), else period.label, else String(start). width (pixels, a number or a function of the period, default 80) must be positive and finite. Throws TypeError for a non-array or a period that is not an object, RangeError for a non-finite period, end <= start, a period that starts before the previous one ends (out of order or overlapping) and an invalid width, and Error for an invalid or duplicate ID (Invalid time bucket ID: <value>, Duplicate time bucket ID: <id>).
  • timeBucketIndex(buckets, time): number: the index of the bucket with start <= time < end, or -1 when time is before, after or between the buckets. timeBucketIndexRange(buckets, range): { start, end }: the half-open index range of the buckets that overlap [range.start, range.end); buckets.slice(start, end) are the columns to show for a GanttChart TimelineVisibleWindow, so a period table can follow the chart's visible range. An empty range or one between buckets gives start === end. Both are binary searches and do not validate the buckets again; both throw RangeError for a non-finite time or range and end < start.
  • aggregateTimeBuckets<T = TimeBucketItem>(items: readonly T[], buckets: readonly TimeBucket[], options?: TimeBucketAggregateOptions<T>): TimeBucketCell[] aggregates quantities into one cell per row and bucket (rows in order, then buckets in time order). buckets need IDs (TimeBucketColumn has them) and are validated like createTimeBucketColumns. Runs in O((items + cells) · log buckets) plus the buckets each interval item overlaps; the inputs are not modified.

TimeBucketItem: { rowId, time?, start?, end?, value, denominator? }. An item with time is an instant, placed in the bucket that contains it. An item with start and end is a half-open interval, placed by placement: 'start' (default) in the bucket containing its start; 'overlap' with its whole value in every bucket it overlaps (counts of active orders, peaks); 'prorate' split over the buckets it overlaps in proportion to the overlapped time (additive quantities: hours, output), where the parts in gaps or outside every bucket are dropped. A zero-length interval is an instant. Items outside every bucket are ignored. Accessors itemRow, itemTime (a number or a TimeRange), itemValue and itemDenominator read other item shapes.

Options:

OptionMeaning
ruleTimeBucketRule<T>, default 'sum': the rule of rows without an entry in rules.
rulesRules by row ID, a Map or a plain object, for tables that mix metrics.
rowIdsThe rows to emit, in order; items of other rows are ignored. Default: the rows of the items in first-appearance order.
loadedTimeBucketLoaded: what is loaded, as half-open ranges whose union is loaded for every row, or a function (rowId, bucket) => boolean | WindowedCellStatus. Default: everything.
placement'start' | 'overlap' | 'prorate', default 'start': placement of interval items.
carryForwardboolean | (rowId) => boolean, default false: carry the value of last rows into later loaded buckets without items.
maxCellsMost cells (rows × buckets) per call, default 1000000; more throws RangeError.

Rules, with the value of a loaded bucket that has items and of one that has none:

RuleWith itemsWithout items
sumtotal of the values0
countnumber of items0
min, maxthe smallest or largest valuenull
first, lastthe value of the earliest or latest item (by time, intervals by start; ties in input order)null, or the carried value
ratiosum of values ÷ sum of denominators (null when that sum is 0), with numerator and denominator on the cellnull, with numerator and denominator 0
precomputedthe value of the one item, as-is (server-side aggregates); a second item of the row in the bucket throws Errornull
(values, { rowId, bucket, items }) => number | nullthe result; values and items in time order (ties in input order)the result for []

TimeBucketCell: { rowId, columnId, value: number | null, status: WindowedCellStatus, count, numerator?, denominator?, carried? }. status is loaded when items were placed in a loaded bucket and loaded-empty when none were, so a known zero (sum, count) and a known absence (null for the other rules) are both distinguished from missing data. A bucket that loaded does not cover has status unloaded (or the loading or failed state the function returns) and value null, never 0, even when some items fall in it; count still reports them. With ranges, a bucket counts as loaded only when their union covers all of it, since a partly loaded sum would be wrong. The function form can return windowedCoverage(state, { start: bucket.start, end: bucket.end, rowIds: [rowId] }).status to follow a windowed data state; true, 'loaded' and 'loaded-empty' mean loaded, false means unloaded.

Ratios (yield, utilisation, on-time rate) must be aggregated from their parts: pass the numerator as value and the denominator as denominator (or by accessors) and use ratio. Averaging the percentages of the buckets weights a day of 10 units like a day of 1000. To roll a ratio up further (a total column, a parent row), sum the cells' numerator and denominator, or call aggregateTimeBuckets again with one bucket that spans the total. The same goes for any total: aggregate the items, not the displayed cells, except for sum and count.

carryForward (only for last rows) is for running balances such as stock levels or backlog: a loaded bucket without items shows the last value before it, with carried: true and status loaded-empty. The carry is seeded by the last item before the bucket, including one before the first bucket or in a gap, so pass the reading before the first shown period to get an opening balance. A bucket that is not loaded has no value and breaks the carry until the next item.

Throws TypeError for inputs of the wrong type, RangeError for invalid buckets, a non-finite time, value or denominator (a denominator is read only for ratio rows), an interval or loaded range with end < start, an unknown rule (Unknown time bucket rule: <rule>, Unknown time bucket rule of row <id>: <rule>), placement or loaded state, a custom result that is neither a finite number nor null, and more cells than maxCells, and Error for an invalid or duplicate bucket or row ID (Invalid time bucket row ID: <value>, Duplicate time bucket row ID: <id>) and a repeated precomputed value. Whatever an accessor, reducer or loaded function throws passes through.

Windowed data chunks are fixed lengths in time units from their origin, so day-sized chunks drift from local day buckets across a daylight-saving change; compute loaded per bucket (the function form) or use chunks no longer than the shortest bucket.

TimeBucketCell.status uses the loading states of partial data loading, not TreeGrid statuses, so convert cells with treeGridCellsFromTimeBuckets (or treeGridCellContentFromTimeBucket inside a column accessor) before passing them to TreeGrid.

Types: TimeBucketPeriod, TimeBucket, TimeBucketColumn, TimeBucketColumnOptions, TimeBucketRuleName, TimeBucketRule, TimeBucketReducer, TimeBucketReducerContext, TimeBucketPlacement, TimeBucketLoaded, TimeBucketItem, TimeBucketAggregateOptions, TimeBucketCell.

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