Skip to content

Core entry point ​

@eightkk/vue-weave/core is pure TypeScript: graph layout and routing, graph algorithms, time scales, scheduling and resource load, earned value, linked-view bindings, windowed data, interchange formats and SVG export. It does not import Vue, the DOM or browser globals, so it runs in Node.js 22.18+, Web Workers and serverless functions as well as in the browser. Every function returns new values and never changes its arguments. The Vue entry re-exports all of it.

Use it to calculate on a server (schedule a plan before sending it), in a Worker (lay out a large graph off the main thread), or in tests, and pass the results to the components as plain props.

Minimal example ​

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

const layout = layoutLayeredGraph(
  [{ id: 'a', label: 'Cut' }, { id: 'b', label: 'Weld' }],
  [{ id: 'ab', from: 'a', to: 'b' }],
  { direction: 'LR' },
)
console.log(layout.boxes.get('b')) // { x, y, width, height }

The exports are grouped by area on the following pages: Graph layout and routing, Graph algorithms and traversal, Timeline and scales, Scheduling and resources, Linked views and data and Interchange and export. The generated type reference of the core lists every export with its signature.

Core entry point ​

Import pure functions and types from @eightkk/vue-weave/core. The Vue entry also re-exports them. Core has no Vue or DOM runtime dependency and does not mutate input data.

ExportPurpose
indexGraph(nodes, edges)Validate IDs, references and ports; create incoming/outgoing adjacency Maps
graphNeighborhood(index, id, maxHops = Infinity)Union of independent ancestor/descendant traversals
layoutLayeredGraph(nodes, edges, options)Deterministic graph layout. All nodes of a cycle (strongly connected component) share one rank, so a large cycle becomes one long column; see architecture
graphPortAnchor(box, port)World-coordinate point on a node box for a port
graphEdgeEndpoint(layout, nodes, edge, end, direction)Endpoint point and side for a named port, the drawn path end, or a direction-based default
routeGraphPorts(layout, nodes, edges, direction)Reroute edges with named ports after layout and saved positions
applyGraphPositions(layout, edges, positions, direction = LR)Apply saved coordinates and reroute incident edges
layoutGraphIncrementally(nodes, edges, positions, options?)Place new nodes around positioned ones without moving them; see Incremental placement
graphLayoutChangeMetrics(before, after, options?)Displacement, overlap and edge-through-box counts of a layout change, as a diagnostic
createTimeScale(range, pixelsPerUnit)Invertible linear scale
createWorkingTimeScale(range, periods, pixelsPerUnit, nonWorkingRatio = 0.1)Piecewise-linear invertible TimeScale for the scale prop: working periods (half-open, as buildWorkPeriods returns them) get pixelsPerUnit per unit, other time pixelsPerUnit × nonWorkingRatio. Periods are clipped, sorted and united, so they may be unsorted or overlapping; those outside the range are ignored; no working period gives a uniform pixelsPerUnit × nonWorkingRatio scale. nonWorkingRatio must be in (0, 1] (1 is linear); 0 is rejected because a zero-width interval cannot be inverted. Outside the range the scale extrapolates with the slope of the edge segment. toX and toTime binary-search precomputed breakpoints (O(log n)) and are exact at segment boundaries. Throws RangeError for a non-finite or inverted range, a non-positive or non-finite pixelsPerUnit, a ratio outside (0, 1], invalid periods or a width that overflows. defaultNonWorkingRatio is 0.1
timeTicks(window, step, anchor = 0)Stable tick sequence anchor + k × step inside the closed window; capped at 10,000 entries. A window so far from the anchor that the tick index is not finite throws RangeError. With a fractional step, ticks are exact decimals (0.1, 0.2, 0.3, not 0.30000000000000004) when the step and anchor have at most 15 decimal places; integer steps use plain arithmetic
visibleRows(scrollTop, bodyHeight, rowHeight, count, overscan = 2)First index and exclusive end index
intersectsWindow(interval, window)Half-open overlap; a point milestone counts when it lies in the closed window, including at either edge
editTimeRange(interval, mode, delta, snap, bounds, minDuration = snap)Immutable snapped proposal. With a fractional snap, the result is computed in exact decimal arithmetic when the snap, interval, bounds and minDuration have at most 15 decimal places (moving 0 by 3 × 0.1 gives 0.3); otherwise, and for integer snaps, plain floating-point arithmetic is used. Throws RangeError delta must be finite, snap must be finite and positive or minDuration must be finite and positive (checked in that order), the texts of the GanttChart snap and minDuration props
dependencyTimes(source, target, type = FS)Endpoint times for dependency routing
dependencyPath(x1, y1, x2, y2, style?)SVG path of a dependency connector. style (DependencyPathStyle) is orthogonal (default, unchanged output), rounded or curve; any other value throws RangeError
timelineBaselineId, timelineBaselineLimit'$baseline', the baseline set ID of TimelineBar.baseline, and 3, the most baseline sets drawn at once; see Baseline sets
timelineBaseline(bar, id)A bar's interval in baseline set id: bar.baseline for timelineBaselineId, otherwise its baselines entry, or undefined
timelineBaselineIds(bars)Every baseline set ID in the bars: timelineBaselineId first when any bar has a baseline, then the baselines IDs in order of first appearance
baselineVariance(bar, baseline)TimelineBaselineVariance { start, end, duration }: the bar's start and end minus the baseline's and its length minus the baseline's, so positive values are later or longer. Never -0. Throws RangeError for non-finite times
formatDependencyLag(lag)Default text of a dependency lag: signed hours of milliseconds rounded to two decimals, such as +2 h or −1.5 h (U+2212). Throws RangeError for a non-finite lag
validateTimelineData(rows, bars, dependencies = [], laneCount = 1, options = {})Validate references, lanes, durations, progress, baselines and named baseline sets (see Baseline sets) and dependency lags (a lag that is not a finite number throws RangeError). With TimelineDataOptions.summaryDependencies, a dependency end may also be a summary row ID (see Dependencies on summary rows), but not with a bar or summary row below that row (Error, as in scheduleTasks). IDs must be unique within each collection; a row and a bar may share an ID. A dependency from a bar to itself throws an Error that names the dependency and the bar, so GanttChart reports it through validation-error and renders its empty state, and renderTimelineSvg throws it. scheduleTasks takes its own links and reports a self-link as a cycle failure instead
createTimelineRowTree(rows)Validate row parents and cycles; produce stable preorder entries whose row keeps the type of the input rows
summarizeTimelineRows(tree, bars)Roll up leaf-row intervals and progress into a summary Map
normalizeWorkPeriods(periods, range)Clip, sort and merge overlapping or touching work periods
invertWorkPeriods(periods, range)Sorted half-open gaps between the clipped, sorted and merged work periods inside the range, for nonWorkingPeriods. Endpoints only need to be finite, so fractional units work; each period and the range must have positive length, otherwise RangeError
buildWorkPeriods(range, week)Expand weekly shifts and date overrides into epoch-millisecond work periods. utcOffsetMinutes is an integer from -1080 to 1080
scheduleTasks(input)Calculate calendar-aware earliest/latest dates, float and critical links
scheduledBarFields(task)ScheduledBarFields for a TimelineBar from a scheduled task: start, end, critical, latestEnd and, only for work in more than one segment, segments. Returns new objects
propagateEdit(input, edit)Reschedule with one task pinned at a new start (and optionally a new end) and list every task whose dates change, including summary tasks whose rolled-up dates follow: a PropagateEditResult. Editing a summary task throws an Error; see Propagate an edit
rescheduleFromStatusDate(input, statusDate, progress)Reschedule a plan at a status date from reported progress: done tasks keep their dates, partly done tasks keep their done work and continue at or after the status date, and unstarted tasks start no earlier than it. FS and SS links into started tasks and every link into done tasks no longer apply; FF and SF links into partly done tasks still bound their finish and can delay the remaining work. Returns a ScheduleResult; see Reschedule from a status date
rescheduleFromActuals(input, statusDate, actuals)Reschedule a plan from recorded actual intervals (ReadonlyMap<string, TaskActuals>): the actuals are kept exactly as recorded and only the remaining work is scheduled from the status date. Returns a RescheduleFromActualsResult with the forecast schedule, the original plan, per-task ActualsTask entries and diagnostics; see Recorded actuals and Reschedule from recorded actuals
actualsTimelineBars(result, options?)GanttChart bars for a rescheduleFromActuals result: a solid actual bar and an outline forecast bar per task, with the plan as a baseline; see Recorded actuals
scheduleToGraph(result, dependencies, options?)A PERT network diagram for NetworkGraph from a successful schedule; see Network diagram from a schedule
toMsProjectXml(project, options?), toICalendar(events, options?), toCsv(table, options?)Interchange documents as strings; see Interchange exports
parseCsv(text, options?), timelineFromCsvTable(table, options)CSV import: records of strings, then { rows, bars }; see Interchange exports
fromMsProjectXml(xml, options?), timelineFromMsProject(project, options?)Microsoft Project XML import: an MsProjectImport with tasks, links, calendars, resources, assignments and warnings, then GanttChart rows, bars and links; see Microsoft Project import
workCalendarsFromMsProject(project, range), resourceLoadFromMsProject(project, options?)Imported calendars as WorkCalendar[], and imported resources and assignments as the shapes of calculateResourceLoad, levelResources and projectResourceTimeline; see Microsoft Project import
fromICalendar(text, options?), timelineFromICalendar(events)iCalendar import: an ICalendarImport with events and warnings, then GanttChart rows and bars; see iCalendar import
toMermaid(graph, options?), toGraphMl(graph, options?), toDrawio(graph, options?)NetworkGraph nodes, edges, nested groups, positions and sizes as a Mermaid flowchart, GraphML or an uncompressed draw.io file; see Graph interchange
fromMermaid(text, options?), fromGraphMl(xml, options?), fromDrawio(xml, options?), fromDrawioAsync(xml, options?)Diagram import: a GraphInterchangeImport with the NetworkGraph props and warnings; fromDrawioAsync also reads compressed draw.io pages; see Graph interchange
calculateResourceLoad(range, tasks, resources, assignments, options?)Compare scheduled work with capacity over half-open intervals. Segments with the same tasks may share one taskIds array. options.inactiveTaskIds ignores the assignments of inactive tasks
assignmentWorkPeriods(work, assignment)The elapsed periods of a task's work that an assignment covers: all of it, or the part given by workOffset and workDuration, clipped to the work
levelResources(input)Delay tasks with a deterministic priority heuristic so that assigned load stays within capacity
graphDeletion(nodes, edges, nodeIds, edgeIds = [])Normalized GraphDeletion: validates the graph, throws Error for unknown IDs, adds every edge incident to a deleted node and returns both lists deduplicated in input order
removeGraphElements(nodes, edges, deletion)New node and edge arrays without the deleted elements and the edges incident to deleted nodes; unknown IDs throw Error and inputs are not modified
cloneGraphElements(nodes, edges, nodeIds, options)GraphCloneResult with shallow copies of the listed nodes and of every edge between two of them, in input order, with IDs from options.createId(id, kind) (kind is node or edge) and edges pointing at the copied nodes; ports, data and other fields are kept. options.positions entries of the source nodes are moved by options.offset (default 0, 0) and returned under the new IDs in positions, and the waypoints (points) of copied edges are moved by the same offset; idMap.nodes and idMap.edges map source IDs to new IDs. Duplicate requested IDs are ignored. Throws Error for an invalid graph, an unknown node ID (Unknown node in graph clone: <id>) or a new ID that is not a non-empty string (Invalid graph node ID: <value> (createId for <source ID>)) or is repeated or already used in the input (Duplicate graph node ID: <id> (createId for <source ID>); graph edge for edges), and RangeError for a non-finite offset, position or waypoint. Keep the returned positions nonnegative before saving them
createGraphConnectionChecker(nodes, edges, rules)GraphConnectionChecker with check(connection, replacingEdgeId?) and targets(origin, replacingEdgeId?), built once: validates the graph like indexGraph, validates the rules and counts the edge ends per endpoint, so each answer takes constant time per endpoint. Throws Error for rules that name an unknown node or port, a type that is not a nonempty string or list of them or an unknown direction, and RangeError for a negative, fractional or non-finite maxConnections; see Port rules and valid-target hints
checkGraphConnection(nodes, edges, rules, connection, replacingEdgeId?)GraphConnectionCheck: { ok: true } or a GraphConnectionRejection with code (GraphConnectionRejectionCode: unknown-node, unknown-port, direction, type-mismatch or limit-reached, checked in that order), a readable reason naming node labels and port labels ("Average · Input A already has its maximum of 1 connection."), and the end, node and port that broke the rule. replacingEdgeId leaves that edge out of the counts; an unknown one throws Error. Synchronous, so it can run inside validateConnection
graphConnectionTargets(nodes, edges, rules, origin, replacingEdgeId?)GraphConnectionTargets { nodeIds, ports } for a connection in progress from origin (GraphConnectionOrigin: node, optional port, and end, the end the candidates take, to by default): every port (ports.get(nodeId)) and every node without ports (nodeIds) that checkGraphConnection would accept; nodeIds also lists nodes with a valid port. One loop over the nodes after one pass over the edges. An unknown origin has no targets
graphConnectionViolations(nodes, edges, rules)GraphConnectionViolation[] (edgeId, code, reason, end, node, port) auditing existing edges in input order with the same rules: direction and type per edge, and for a limit every edge end past it (the first maxConnections ends are kept). An edge can appear more than once
graphConnectionValidator(nodes, edges, rules, validate?)A validateConnection function: returns the rule's reason for a broken rule without calling validate, otherwise the result of validate (or true)
graphAlignmentGuides(moving, others, threshold)GraphAlignment { dx, dy, guides } that aligns a GraphRect with the nearest left, centre or right (x) and top, middle or bottom (y) anchor of others within threshold chart units (inclusive), 0 on an axis without a match. Ties go to the earlier rectangle in others, then to the start, centre and end anchors of moving, then to those of the other rectangle. guides (GraphAlignmentGuide: axis, position, from, to) are the aligned lines of the shifted rectangle, x guides first, each sorted by position and spanning every rectangle aligned there. Throws RangeError for a negative or non-finite threshold and invalid rectangles. Iterative and deterministic
collapseGraphGroups(nodes, edges, groups, collapsedIds, options)GraphCollapseResult for the collapsed groups: visible nodes with one proxy per outermost collapsed group (ID and label of the group, detail from options.detail, default "N nodes", rounded shape, data of type GraphCollapsedNodeData), edges re-attached to proxies (ports on proxy ends and waypoints dropped, internal edges removed, parallel edges merged per source, source port, target and target port under the first ID; a merged edge keeps label, edgeStyle, markerStart, markerEnd, animated and dashed only when every merged edge has the same value for it, and drops data and points), the remaining groups (a collapsed child becomes a member of its parent), proxies (GraphCollapsedGroup with every hidden node ID), owners (hidden node to proxy), mergedEdges (re-attached edge ID to original IDs) and hiddenEdgeIds. Throws Error for invalid groups like NetworkGraph (including an unknown parent anywhere up a parent chain and a parent cycle), an unknown collapsed ID or a group ID that is also a visible node ID. Inputs are not modified; untouched nodes and edges are returned as is. GraphCollapsedNode is the type of a proxy node, NetworkNode<GraphCollapsedNodeData>
routeGraphEdges(layout, edges, nodes, options)Reroutes a finished layout in GraphEdgeRouteOptions.style (curve, orthogonal or straight, default curve; an edge's own edgeStyle overrides it) for a direction (default LR) with an orthogonal cornerRadius (default 0), and draws edges with points through their waypoints; see Group collapse, edge styles and waypoints. The opt-in avoidNodes (true or a GraphObstacleAvoidance) routes orthogonal edges without waypoints around every box of the layout with findOrthogonalRoute and keeps the plain orthogonal route for an edge without such a route (see the avoidNodes prop). The opt-in parallelSpacing spreads parallel edges and nests self-loops, and straight edges end on the outline of diamond, ellipse and hexagon nodes in nodes; see Node shapes, edge markers, animated and parallel edges. Returns the input layout for curve without waypoints, edge styles of their own or spread parallel edges. Throws Error for an unknown endpoint or a named port whose side is not left, right, top or bottom, and RangeError for an unknown style (of the options or an edge) or direction, a bad radius, a parallel spacing that is not positive and finite, a bad avoidNodes value or a non-finite waypoint. Orthogonal detours stay at or above 0 in a layout at nonnegative coordinates and keep their full 16-unit stub when an end lies at a negative coordinate. The opt-in cache (a GraphRouteCache from createGraphRouteCache) reuses the route of every edge whose inputs are unchanged since the previous call with that cache and returns the same layout as a call without it; a cache that does not come from createGraphRouteCache throws Error
createGraphRouteCache()GraphRouteCache. An empty memo for the cache option of routeGraphEdges. A call with it routes again only the edges whose own inputs changed: the edge, its end nodes' shape and named port, its end boxes, its path and label in the layout, its parallel slot or the options. With avoidNodes, an edge is also routed again when a box that moved, was resized, added or removed reaches into the area its obstacle search covered, or when a changed box edge lies within that area's horizontal or vertical extent (the search draws its lines between box edges), and when the bounds of all boxes change where the search reached them. In a graph only a few rows high every route spans the same rows, so a vertical move routes every edge again; in larger two-dimensional graphs a move routes again the edges near the moved node's rows and columns. Use one cache per sequence of related layouts, such as one view's layout after each edit. The cache holds the last call's routes, is not structured-cloneable and is not shared between workers. NetworkGraph keeps one for its saved layouts when cullOffscreen is on
findOrthogonalRoute(from, to, obstacles, options = {})GraphPoint[] | undefined. An axis-aligned route from from to to (each a GraphRouteEnd: a point and the side of its node it leaves or enters through) that keeps GraphObstacleAvoidance.clearance (default 8) away from every GraphRect in obstacles and leaves and enters perpendicular to the sides (with a clearance of 0 it may instead run along the border of an end's own node, which is only discouraged by an extra cost); include the two end nodes' boxes, otherwise the route may run through them. It minimises length plus bendPenalty (default 24) per bend, and the same input in any obstacle order gives the same route. Returns undefined when an end is boxed in or the bounded search gives up. When every input lies at nonnegative coordinates, so does the route. It searches a sparse grid, not a pixel grid: lines halfway between neighbouring obstacle edges (the middle of each free channel) and through both ends, plus the edges of the search region along an axis without obstacle edges. Obstacles go into a bucket grid in O(n); the search starts in a region around the ends and grows it fourfold up to the whole area, each round taking O(k log k) for the k obstacle edges in the region plus A* over at most 4·lx·ly states for lx by ly lines, capped at 200,000 expanded states. routeGraphEdges with avoidNodes builds the bucket grid once per call; routing every edge of a 3,000-node layered graph takes a few hundred milliseconds in Node. Throws RangeError for a non-finite end, an unknown side, an obstacle with non-finite coordinates or a negative size, and a negative or non-finite clearance or bend penalty
placeGraphEdgeLabels(layout, edges, options = {})A new layout (the same type as layout, other fields kept) whose edgeLabels place each label of edges where it covers no node box, other label, other edge or extra obstacles when there is space; the input is not changed. GraphEdgeLabelPlacementOptions: fontSize (default 11) and glyphWidth (default 0.6 of the font size) estimate a label's size from its text as characters × glyphWidth × fontSize by 1.25 × fontSize, unless labelSize(edge, text) returns a GraphEdgeLabelSize (nothing or null keeps the estimate); labelText(edge) (default edge.label) gives the text, and edges without text keep their anchor and are not avoided; gap (default 3) is the distance of a label beside its route, measured from the label box itself, so a gap smaller than margin still keeps the label beside its own route; margin (default 2) the free space kept around a label against nodes, obstacles, other labels and other edges; edgeWidth(edge) gives the drawn width of a wide edge such as a flow band (nothing, null or 0 for a thin line): its label keeps gap from the band's outer side and other labels avoid its full width; samples (an integer from 1 to 32, default 9) the positions tried along each route, besides the middles of its four longest segments; edgeIds places only those labels and keeps the others as obstacles; obstacles are more GraphRect areas to keep clear, such as group headers. Anchors keep their meaning: the horizontal centre and baseline of the text, the label box centred on anchor.y - 0.35 × fontSize. At each position a label is tried above (or right of) its route, below (or left of) it and on it; a candidate costs its distance from the middle of the route and its side plus its overlap with boxes, obstacles and other labels, the share of its padded box outside the layout (weighed in label area) and the number of other edges it crosses, and the cheapest wins. Routes without length (an empty path or one point) keep their anchors. Labels are placed greedily, those of shorter routes and then wider labels first, ties in edge ID order, so the result does not depend on the input order. Node boxes, labels and route segments go into bucket grids, so 2,000 labelled edges take tens to a few hundred milliseconds in Node. Throws Error for an invalid or duplicate edge ID (Duplicate edge ID: <id>, as the other graph functions), an edge without a path in the layout or an unknown ID in edgeIds (an ID of an edge without text is allowed and changes nothing), and RangeError for a font size, glyph width, gap, margin or sample count out of range (for example samples must be an integer from 1 to 32 (got 40)), an invalid label size (Invalid edge label size: <id>), an invalid edge width (Invalid edge width: <id>) or an obstacle that is not a rectangle with finite coordinates and a nonnegative size (Invalid edge label obstacle at index <i>). The NetworkGraph edgeLabelPlacement prop runs it
graphPolylinePath(points, cornerRadius = 0) / graphSmoothPath(points)SVG path data of a polyline with optionally rounded corners, and of a smooth Catmull-Rom curve through the points, for custom edge renderers. Throws RangeError for a point with a non-finite coordinate
applyGraphSizes(layout, edges, sizes, direction = LR)Overlay GraphNodeSize widths and heights on the layout boxes (top-left corners kept), grow the bounds and reroute incident edges like applyGraphPositions. RangeError for sizes that are not finite and positive, also under unknown IDs, which are otherwise ignored; Error naming the edge and node when an incident edge references a node without a box; returns the input layout when nothing changes
snapGraphPoint(point, grid)The point with both coordinates rounded to the nearest multiple of a positive finite grid (RangeError otherwise, and for non-finite coordinates); never returns -0

All exported interfaces and component props are included in the declaration files. Validation functions reject invalid references and numeric geometry with descriptive errors. Scheduling failures such as cycles and infeasible plans are returned as results; malformed scheduling inputs throw. Routing helpers assume validated graph data as described below.

Released under the MIT License.