Skip to content

JavaScript API Reference ​

Complete API reference for the Graph class.

Overview ​

The Graph class is the core orchestrator for programmatic graph manipulation. Access it via the .graph property on the Web Component:

typescript
const element = document.querySelector("graphty-element");
const graph = element.graph;

TIP

For usage patterns and examples, see the JavaScript API Guide.

Core Methods ​

Data Management ​

MethodParametersReturnsDescription
addNodes(nodes)NodeData[]Promise<void>Add nodes to the graph
addEdges(edges, options?)EdgeData[], {source?, target?, repeated?}Promise<void>Add edges to the graph
setEdges(edges, options?)EdgeData[], {source?, target?, repeated?}Promise<void>Replace every edge with these
removeNodes(ids)string[]Promise<void>Remove nodes and their incident edges
updateNodes(updates)NodeUpdate[]Promise<void>Update node properties
getNode(id)stringNode | undefinedGet node by ID
getNodes()-Node[]Get all nodes
clear()-Promise<void>Remove all data

Every node and edge record at once is session.data.nodes() and session.data.edges(); one window of them, with the total and a revision, is session.data.nodePage({ offset, limit, sort, scope }) and session.data.edgePage({ ..., touching }) (see the JavaScript API guide, "Reading records a page at a time"). Edge records are read through the session, by edge id -- session.data.edge(id) -- because an edge's identity is the element's own counter rather than a pair of endpoints. Every edge running between two nodes is graph.getDataManager().getEdgesBetween(a, b), which answers a list because a graph may hold more than one.

addEdges' options are the endpoint expressions to read this batch with and the repeat policy for this call. Assigning the edge-data property, or calling setEdges, REPLACES the edge set; addEdges appends.

Selection ​

MethodParametersReturnsDescription
selectNode(id)stringvoidSelect a node
deselectNode()-voidClear selection
getSelectedNode()-Node | nullGet selected node

elementAt({ x, y }) returns the node a click at a point on the element would select, as { kind: "node", id }, or null. See What Is Under a Point.

Layout ​

MethodParametersReturnsDescription
setLayout(type, options?)string, objectvoidSet layout algorithm
waitForSettled()-Promise<void>Wait for queued operations to finish
waitForStableFrame(opts?){ timeoutMs? }Promise<void>Wait for the picture to stop changing
isFrameStable-booleanWhether the drawn frame is the final one
isSettled()-booleanCheck if layout is stable

Algorithms ​

MethodParametersReturnsDescription
runAlgorithm(namespace, type)string, stringPromise<AlgorithmResult>Run an algorithm
applySuggestedStyles(id)stringvoidApply algorithm visualization

Camera Control ​

MethodParametersReturnsDescription
zoomToFit()-voidFit all nodes in view
zoomToNodes(ids, options?)string | number | (string | number)[], CameraAnimationOptionsPromise<void>Fit these nodes in view
zoomStep(direction, options?)"in" | "out", CameraAnimationOptionsPromise<void>One zoom step in or out
getCameraState()-CameraStateGet camera state
setCameraState(state, options?)CameraState, CameraAnimationOptionsPromise<void>Set camera state
setCameraPosition(pos){x, y, z}voidSet camera position
setCameraTarget(target){x, y, z}voidSet camera target

Styling ​

Styling is the session's, not the graph's. Every verb is on graph.getSession().styles, and every one of them addresses a layer by the id the element minted for it:

MethodReturnsDescription
list()readonly Layer[]Every layer, bottom first
get(id)Layer | undefinedOne layer
validate(spec)ValidationResultCheck a spec, committing nothing
add(spec, at?)Run<Layer>Add a layer and repaint
update(id, patch)Run<Layer>Change one and repaint
remove(id)Run<void>Take one out and repaint
move(id, before)Run<void>Restack it; null means the top
removeBySource(predicate)Run<readonly LayerId[]>Sweep every layer from one source
encode(spec)Run<Layer>Paint a channel from a finished run
mark(spec)Run<readonly Layer[]>Paint the elements a run chose
highlight(spec)Run<readonly Layer[]>The same, as the one exclusive highlight
legend()readonly LegendBlock[]What a reader needs to read the picture
explain(target)StyleExplanationWhich layer decided each channel

A write verb returns a Run rather than resolving to a value, so a layer edit on a large graph can report progress and be cancelled. The stack moves only once the repaint has succeeded.

Notes ​

Notes are the session's too, on graph.getSession().notes (element.session.notes). Reads are synchronous; every write is one undoable step:

MethodReturnsDescription
list(options?)readonly Note[]Notes, newest first, filtered by target, kind, cite, author
get(id)Note | undefinedOne note
status(id)NoteStatusWhat each target and cite points at now
authors()readonly string[]The distinct authors
counts(){ notes, nodes, edges }How many notes, and how many nodes and edges have one
add(input)NoteIdWrite a note
update(id, patch)voidChange one
remove(id)voidDelete one
toDocument(options?)NotesDocumentThe notes as a graphty-notes document, ready to save
mergeDocument(doc, options?)NotesReportAdd a saved document's notes; never deletes one

See the notes guide and the generated NotesApi reference.

Events ​

MethodParametersReturnsDescription
on(event, handler)string, FunctionvoidSubscribe to events
off(event, handler)string, FunctionvoidUnsubscribe from events

Batch Operations ​

MethodParametersReturnsDescription
batchOperations(fn)async (tx) => voidPromise<void>Make the changes fn makes through tx one undoable step

Manager Classes ​

The Graph class exposes manager instances for advanced control:

DataManager ​

typescript
await graph.dataManager.loadFromUrl(url);
await graph.dataManager.addNodes(nodes);
await graph.dataManager.clear();

LayoutManager ​

typescript
graph.layoutManager.setLayout("ngraph", options);

Waiting belongs to the graph rather than to the layout manager: graph.waitForSettled() waits for the operation queue, and graph.waitForStableFrame() waits for the picture -- the layout converged, the camera framed, and a frame drawn in that state.

typescript
await graph.waitForStableFrame();
const shot = await graph.captureScreenshot();

AlgorithmManager ​

typescript
await graph.algorithmManager.run("graphty", "degree");
graph.algorithmManager.applySuggestedStyles("graphty:degree");

Data Types ​

NodeData ​

typescript
interface NodeData {
    id: string;
    label?: string;
    [key: string]: unknown;
}

EdgeData ​

typescript
interface EdgeData {
    source: string;
    target: string;
    weight?: number;
    [key: string]: unknown;
}

CameraState ​

typescript
interface CameraState {
    position: { x: number; y: number; z: number };
    target: { x: number; y: number; z: number };
    up: { x: number; y: number; z: number };
}

LayerSpec ​

typescript
interface LayerSpec {
    name: string;
    target?: "node" | "edge";
    kind?: "base" | "encoding" | "highlight" | "custom";
    selector: Selector;
    set?: StaticStyle; // literal channel values
    encode?: Encoding; // channel values bound to the data
    enabled?: boolean;
}

The channels a layer can write, the selector language and the scales an encoding reads through are all in the styling guide.

Generated Reference ​

For complete type definitions and detailed API documentation:

Extension Classes ​

For creating custom extensions: