@graphty/graphty-element / index / Graph
Class: Graph ​
Defined in: graphty-element/src/Graph.ts:296
Main orchestrator class for graph visualization and interaction. Integrates Babylon.js scene management, coordinates nodes, edges, layouts, and styling.
Implements ​
Constructors ​
Constructor ​
new Graph(
element,useMockInput?):Graph
Defined in: graphty-element/src/Graph.ts:465
Creates a new Graph instance and initializes the rendering engine and managers.
Parameters ​
element ​
string | Element
DOM element or element ID to attach the graph canvas to
useMockInput? ​
boolean = false
Whether to use mock input for testing (defaults to false)
Returns ​
Graph
Properties ​
acceleration ​
readonlyacceleration:AccelerationController
Defined in: graphty-element/src/Graph.ts:374
The one acceleration controller this graph, its session and its element share.
Built here because it is the earliest owner both the element's acceleration attribute and the session can reach: the element builds its Graph in its own constructor, before Lit has parsed an attribute, and the Graph builds the session in its. It is disposed by shutdown, so it lives and dies with the graph.
Since ​
2.0.0
camera ​
camera:
CameraManager
Defined in: graphty-element/src/Graph.ts:313
canvas ​
canvas:
HTMLCanvasElement
Defined in: graphty-element/src/Graph.ts:310
element ​
element:
Element
Defined in: graphty-element/src/Graph.ts:309
enableDetailedProfiling? ​
optionalenableDetailedProfiling?:boolean
Defined in: graphty-element/src/Graph.ts:345
engine ​
engine:
Engine|WebGPUEngine
Defined in: graphty-element/src/Graph.ts:311
eventManager ​
readonlyeventManager:EventManager
Defined in: graphty-element/src/Graph.ts:402
Event manager for adding/removing event listeners
fetchEdges? ​
optionalfetchEdges?:FetchEdgesFn
Defined in: graphty-element/src/Graph.ts:337
fetchNodes? ​
optionalfetchNodes?:FetchNodesFn
Defined in: graphty-element/src/Graph.ts:336
initialized ​
initialized:
boolean=false
Defined in: graphty-element/src/Graph.ts:338
needRays ​
needRays:
boolean=false
Defined in: graphty-element/src/Graph.ts:332
Has no effect: the element never reads it.
Deprecated ​
Each edge aims its own ray when it needs one. Will be removed in graphty-element 4.0.
onNodeLabelCounts ​
readonlyonNodeLabelCounts:Observable<NodeLabelCounts>
Defined in: graphty-element/src/Graph.ts:404
Told the node label counts once the view is still and they changed.
Implementation of ​
GraphContext.onNodeLabelCounts
pinOnDrag? ​
optionalpinOnDrag?:boolean
Defined in: graphty-element/src/Graph.ts:334
scene ​
scene:
Scene
Defined in: graphty-element/src/Graph.ts:312
skybox? ​
optionalskybox?:string
Defined in: graphty-element/src/Graph.ts:325
xrHelper ​
xrHelper:
WebXRDefaultExperience|null=null
Defined in: graphty-element/src/Graph.ts:326
Accessors ​
input ​
Get Signature ​
get input():
InputManager
Defined in: graphty-element/src/Graph.ts:4017
Get the input manager
Returns ​
The input manager instance
isFrameStable ​
Get Signature ​
get isFrameStable():
boolean
Defined in: graphty-element/src/Graph.ts:4228
Whether the picture on screen is the finished one.
Remarks ​
True only when the layout has converged, the camera has finished framing the graph, no style work is queued, AND a frame has been drawn in that state. False again the moment any of that stops being true -- new data, a new layout, a re-frame.
It is deliberately silent about the reader: someone dragging the camera or a node changes the picture, and the element does not call that unstable.
Since ​
2.0.0
Example ​
if (graph.isFrameStable) {
const screenshot = await graph.captureScreenshot();
}Returns ​
boolean
True when the last frame drawn is the last frame that will change.
nodeLabelCounts ​
Get Signature ​
get nodeLabelCounts():
NodeLabelCounts
Defined in: graphty-element/src/Graph.ts:1699
How many node labels this graph is drawing, and why the rest are not, as of the last frame that decided it. All zeros before a label is drawn. Reading it never forces a frame.
Returns ​
The counts.
rendererRequest ​
Get Signature ​
get rendererRequest():
RendererRequest
Defined in: graphty-element/src/Graph.ts:1252
The renderer asked for through Graph.setRenderer.
Returns ​
The request; "webgl" unless something else was set.
rendererStatus ​
Get Signature ​
get rendererStatus():
RendererStatus|null
Defined in: graphty-element/src/Graph.ts:1260
Which renderer is drawing, and why when it is not the one asked for.
Returns ​
RendererStatus | null
The status once Graph.init has chosen; null before.
runAlgorithmsOnLoad ​
Get Signature ​
get runAlgorithmsOnLoad():
boolean
Defined in: graphty-element/src/Graph.ts:1561
Whether the algorithms in the configuration's data.algorithms run once data has loaded. A project setting: setting it is one step, which undo takes back.
Returns ​
boolean
The setting.
Set Signature ​
set runAlgorithmsOnLoad(
value):void
Defined in: graphty-element/src/Graph.ts:1569
Set whether the on-load algorithms run.
Parameters ​
value ​
boolean
The setting.
Returns ​
void
styles ​
Get Signature ​
get styles():
Styles
Defined in: graphty-element/src/Graph.ts:302
The element's configuration document, read-only: its config is the frozen merged view. Change a setting through getSession().config.set, which is an undoable step.
Returns ​
Styles
The configuration document.
Methods ​
addDataFromSource() ​
addDataFromSource(
type,opts?,options?):Promise<{loadId:number; }>
Defined in: graphty-element/src/Graph.ts:1831
Adds graph data from a registered data source, as one undoable step.
The load takes its turn on the operation queue behind the loads and layouts asked for before it, and is added to what the graph holds unless it replaces it. It paints what it loaded before the promise settles: the pass that follows its last chunk repaints the graph from the style stack, so a graph loaded this way is painted exactly as one built from records is. A load that fails part way records nothing and takes back the rows that did arrive, so a replacing load that fails leaves the graph it would have replaced.
EVERY LOAD HAS AN ID. The promise resolves to it, and every event about this load -- data-loading-progress, data-loading-complete, data-loading-error, data-loaded and the error beside a failure -- carries it as loadId, so a consumer that started two loads can tell whose report is whose.
Parameters ​
type ​
string
Type/name of the registered data source
opts? ​
object = {}
Options to pass to the data source
options? ​
How to load
replace? ​
boolean
Replace the graph with what the source holds, but only once all of it has parsed: a malformed or empty source rejects and leaves the graph as it was
Returns ​
Promise<{ loadId: number; }>
Promise that resolves to the load's id when data is loaded
addEdge() ​
addEdge(
edge,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2096
Add a single edge to the graph.
Parameters ​
edge ​
Edge data object to add
options? ​
AddEdgesOptions & QueueableOptions
The endpoint expressions, the repeat policy, and queue ordering
Returns ​
Promise<void>
addEdges() ​
addEdges(
edges,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2137
Add edges to the graph incrementally.
Parameters ​
edges ​
Record<string | number, unknown>[]
Array of edge data objects to add
options? ​
AddEdgesOptions & QueueableOptions
The endpoint expressions, the repeat policy, and queue ordering. With no source and target named, the element reads source/target, then src/dst, then from/to, deciding once for the whole batch and throwing E_EDGE_ENDPOINTS_UNRESOLVED when none of them answers
Returns ​
Promise<void>
Promise that resolves when edges are added
Remarks ​
This method ADDS edges to the existing graph without removing existing edges. Source and target nodes should exist before adding edges, otherwise the edges will reference non-existent nodes.
Edges connect nodes and can optionally store additional data accessible via edge.data.
Since ​
1.0.0
See ​
- addNodes for adding nodes first
- Data Loading Examples
Example ​
// Add edges with default source/target fields
await graph.addEdges([
{ source: 'node-1', target: 'node-2', weight: 1.5 },
{ source: 'node-2', target: 'node-3', weight: 2.0 }
]);
// Add edges naming the endpoint fields explicitly
await graph.addEdges(
[{ start: 'a', end: 'b', label: 'connects' }],
{ source: 'start', target: 'end' }
);
// Add nodes and edges together
await graph.addNodes([{id: 'a'}, {id: 'b'}]);
await graph.addEdges([{source: 'a', target: 'b'}]);addListener() ​
addListener<
K>(type,cb):symbol
Defined in: graphty-element/src/Graph.ts:3042
Add an event listener for graph events.
Type Parameters ​
K ​
K extends EventType
Parameters ​
type ​
K
Event type to listen for
cb ​
(evt) => void
Callback function to execute when event fires
Returns ​
symbol
The listener's id, which removeListener takes. It used to be dropped here, so nothing a consumer could reach was able to undo an addListener.
addNode() ​
addNode(
node,idPath?,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2041
Add a single node to the graph.
Parameters ​
node ​
Node data object to add
idPath? ​
string
Key to use for node ID (default: "id")
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
addNodes() ​
addNodes(
nodes,idPath?,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2080
Add nodes to the graph incrementally.
Parameters ​
nodes ​
Record<string | number, unknown>[]
Array of node data objects to add
idPath? ​
string
Key to use for node IDs (default: "id")
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Promise that resolves when nodes are added
Remarks ​
This method ADDS nodes to the existing graph without removing existing nodes. For complete replacement, use the nodeData property on the web component instead.
Nodes are added to the current layout and will animate into position if a force-directed layout is active.
Since ​
1.0.0
See ​
- addEdges for adding edges
- Data Loading Examples
Example ​
// Add nodes with default ID field
await graph.addNodes([
{ id: 'node-1', label: 'First Node', category: 'A' },
{ id: 'node-2', label: 'Second Node', category: 'B' }
]);
// Add nodes with custom ID field
await graph.addNodes(
[{ nodeId: 'n1', name: 'Node One' }],
'nodeId'
);
// Wait for layout to settle after adding
await graph.addNodes(newNodes);
await graph.waitForSettled();
graph.zoomToFit();aiCommand() ​
aiCommand(
input):Promise<ExecutionResult>
Defined in: graphty-element/src/Graph.ts:6130
Send a natural language command to the AI controller.
Parameters ​
input ​
string
Natural language command (e.g., "switch to circular layout")
Returns ​
Promise<ExecutionResult>
Promise resolving to command result
Example ​
// Query graph info
const result = await graph.aiCommand('How many nodes are there?');
console.log(result.message);
// Change layout
await graph.aiCommand('Use circular layout');
// Switch dimension
await graph.aiCommand('Show in 2D');applyCameraView() ​
applyCameraView(
id,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5833
Put the viewer where a named camera view says they should stand.
This is the route that can frame a SUBSET. The element measures the box over whatever the scope covers and hands the smaller box to the view, so every view -- the element's own and a third party's alike -- frames a selection with no code of its own.
Parameters ​
id ​
string
The view's name.
options? ​
object & CameraAnimationOptions
The scope to frame, the view's own options, and how to get there. Animation follows the same rules as setCameraState.
Returns ​
Promise<void>
A promise that resolves once the camera has arrived.
Throws ​
A GraphtyError with E_UNKNOWN_CAMERA, E_UNSUPPORTED, E_UNKNOWN_OPTION or E_OPTION_RANGE, exactly as resolveCameraPreset does.
applySuggestedStyles() ​
applySuggestedStyles(
algorithmKey):boolean
Defined in: graphty-element/src/Graph.ts:2598
Paint what an algorithm's finished runs suggest be drawn from them.
DERIVED, NOT WRITTEN OUT. A run already declares its result shape and its fields, and that is everything a first picture needs: a node metric suggests a sequential colour over the nodes it measured, a community suggests a categorical one, a route or a chosen set suggests a highlight, and a table of pairs suggests nothing at all. There is one derivation for every algorithm rather than a block per algorithm, so there is no per-algorithm branch that can paint the elements its own run measured nothing about.
CALLING THIS IS USUALLY UNNECESSARY, and never harmful. A run paints itself on its FIRST completion through the session's auto-apply policy, and applying a suggestion again replaces the layer already bound to that run and channel rather than stacking a second one on it. So this is the verb for a run that was started with { style: false }, or for putting a picture back after a reader cleared it.
THE LAST ALGORITHM NAMED IS THE ONE A READER SEES. Two algorithms of the same shape suggest the same channel -- a node metric and a community both paint node.color -- so which of them makes the picture is decided by which layer sits higher in the stack, and nothing else. This call puts the layers it applied on top in the order they were named, which is the order the argument reads in. Without that, a suggestion that replaced an already-applied layer kept that layer's place, and the place it had was the order the RUNS FINISHED in -- so applySuggestedStyles(["pagerank", "louvain"]) painted a PageRank picture whenever PageRank happened to finish last, and a Louvain one whenever it did not.
It starts the style edits and returns at once. To wait for the picture, await Graph.waitForStableFrame after the call: it settles only once every suggested layer is added, stacked in the order named and painted.
Parameters ​
algorithmKey ​
string | string[]
A catalogue key such as "degree", a 1.10 address such as "graphty:degree", or an array of either.
Returns ​
boolean
True when at least one suggestion was applied, false when no finished run of that algorithm has anything per element to paint.
batchOperations() ​
batchOperations(
fn,label?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2930
Make several changes one undoable step.
A transaction of this graph's session: what fn does through tx -- tx.data.addNodes, tx.layout.set, tx.run, tx.styles.add -- is recorded as one step once fn settles, and a throw rolls all of it back. A call on this graph itself while fn runs is a step of its own, and logs a warning naming the tx verb to use instead.
Parameters ​
fn ​
(tx) => void | Promise<void>
The changes, made through tx.
label? ​
string = "Batch of changes"
The step's label.
Returns ​
Promise<void>
Once the step is recorded and drawn.
Since ​
3.0.0
Example ​
await graph.batchOperations(async (tx) => {
await tx.data.addNodes([{ id: "a" }, { id: "b" }]);
await tx.data.addEdges([{ src: "a", dst: "b" }]);
await tx.layout.set("circular");
});canCaptureScreenshot() ​
canCaptureScreenshot(
options?):Promise<CapabilityCheck>
Defined in: graphty-element/src/Graph.ts:4407
Check if screenshot can be captured with given options.
Parameters ​
options? ​
Screenshot options to validate
Returns ​
Promise<CapabilityCheck>
Promise<CapabilityCheck> - Result indicating whether screenshot is supported
Example ​
// Check if 4x multiplier is supported
const check = await graph.canCaptureScreenshot({ multiplier: 4 });
if (!check.supported) {
console.error('Cannot capture:', check.reason);
} else if (check.warnings) {
console.warn('Warnings:', check.warnings);
}
// Check 8K resolution
const check8k = await graph.canCaptureScreenshot({
width: 7680,
height: 4320
});
console.log(`Memory: ${check8k.estimatedMemoryMB.toFixed(0)}MB`);cancelAiCommand() ​
cancelAiCommand():
void
Defined in: graphty-element/src/Graph.ts:6193
Cancel any in-progress AI command.
Returns ​
void
Example ​
// Start a long-running command
const promise = graph.aiCommand('complex query');
// Cancel it
graph.cancelAiCommand();cancelAnimationCapture() ​
cancelAnimationCapture():
boolean
Defined in: graphty-element/src/Graph.ts:4598
Cancel ongoing animation capture
Returns ​
boolean
true if a capture was cancelled, false if no capture was in progress
Example ​
// Start a capture
const capturePromise = graph.captureAnimation({
duration: 10000,
fps: 30,
cameraMode: 'stationary'
});
// Cancel it after 2 seconds
setTimeout(() => {
const wasCancelled = graph.cancelAnimationCapture();
console.log('Cancelled:', wasCancelled);
}, 2000);
// The promise will reject with AnimationCancelledError
try {
await capturePromise;
} catch (error) {
if (error.name === 'AnimationCancelledError') {
console.log('Capture was cancelled');
}
}captureAnimation() ​
captureAnimation(
options):Promise<AnimationResult>
Defined in: graphty-element/src/Graph.ts:4451
Capture an animation as a video (stationary or animated camera)
Parameters ​
options ​
Animation capture options
Returns ​
Promise<AnimationResult>
Promise resolving to AnimationResult with blob and metadata
Example ​
// Basic 5-second video at 30fps
const result = await graph.captureAnimation({
duration: 5000,
fps: 30,
cameraMode: 'stationary'
});
// High-quality 60fps video with download
const result = await graph.captureAnimation({
duration: 10000,
fps: 60,
cameraMode: 'stationary',
download: true,
downloadFilename: 'graph-video.webm'
});
// Animated camera path (camera tour)
const result = await graph.captureAnimation({
duration: 5000,
fps: 30,
cameraMode: 'animated',
cameraPath: [
{ position: { x: 10, y: 10, z: 10 }, target: { x: 0, y: 0, z: 0 } },
{ position: { x: 0, y: 20, z: 0 }, target: { x: 0, y: 0, z: 0 }, duration: 2500 },
{ position: { x: -10, y: 10, z: 10 }, target: { x: 0, y: 0, z: 0 }, duration: 2500 }
],
easing: 'easeInOut',
download: true
});captureScreenshot() ​
captureScreenshot(
options?):Promise<ScreenshotResult>
Defined in: graphty-element/src/Graph.ts:4380
Capture a screenshot of the current graph visualization.
Parameters ​
options? ​
Screenshot options (format, resolution, destinations, etc.)
Returns ​
Promise<ScreenshotResult>
Promise resolving to ScreenshotResult with blob and metadata
Example ​
// Basic PNG screenshot
const result = await graph.captureScreenshot();
// High-res JPEG with download
const result = await graph.captureScreenshot({
format: 'jpeg',
multiplier: 2,
destination: { download: true }
});
// Copy to clipboard
const result = await graph.captureScreenshot({
destination: { clipboard: true }
});clearData() ​
clearData():
void
Defined in: graphty-element/src/Graph.ts:3071
Remove every node and edge, leaving the graph empty and ready for the next dataset, as one undoable step.
The verb the data guide has always taught -- as graph.clear(), which has never existed. <graphty-element> has had clearData() throughout; a consumer holding a Graph had to reach through graph.getDataManager().clear(), which is the element's own internals.
Returns ​
void
Since ​
2.0.0
Example ​
graph.clearData();createApiKeyManager() ​
staticcreateApiKeyManager():Promise<ApiKeyManager>
Defined in: graphty-element/src/Graph.ts:6290
Create a standalone ApiKeyManager for key management without enabling AI. Useful for settings UIs that configure keys before AI activation.
ASYNCHRONOUS, AND THE REASON IS THE BUNDLE. The key store encrypts what it persists, so it imports encrypt-storage. This method used to construct one directly, which made that a STATIC import of Graph -- and Graph is what the root entry point pulls in. The result was that an encryption library shipped to every consumer who drew a graph and never touched the AI layer, which is exactly what the separate ./ai entry point exists to prevent. The entry point's own comment claimed no such cost; for the three LLM SDKs that was true, and for this one it was not.
A consumer who wants it synchronously imports ApiKeyManager from @graphty/graphty-element/ai and constructs it themselves -- which is the honest shape, because they are then choosing to load the encryption library.
Returns ​
Promise<ApiKeyManager>
A new ApiKeyManager instance
Example ​
// In a settings UI component
const keyManager = await Graph.createApiKeyManager();
keyManager.enablePersistence({
encryptionKey: userSecret,
storage: 'localStorage',
});
keyManager.setKey('openai', apiKey);deselectNode() ​
deselectNode():
void
Defined in: graphty-element/src/Graph.ts:3355
Deselect the currently selected node.
Superseded by session.selection.clear(), which empties both sets. This clears the node half through the same model and keeps working.
Returns ​
void
Remarks ​
Clears the current selection and triggers a selection-changed event. If no node is selected, this is a no-op.
Since ​
1.0.0
See ​
- selectNode to select a node
- getSelectedNode to check current selection
Example ​
// Clear selection programmatically
graph.selectNode("node-123");
graph.deselectNode();
console.log(graph.getSelectedNode()); // null
// Clear selection on escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
graph.deselectNode();
}
});disableAiControl() ​
disableAiControl():
void
Defined in: graphty-element/src/Graph.ts:6106
Disable AI control and clean up resources.
Returns ​
void
Example ​
graph.disableAiControl();
// AI commands will no longer workdispose() ​
dispose():
void
Defined in: graphty-element/src/Graph.ts:6549
Dispose all graph resources including voice, AI, XR, and Babylon.js components.
Returns ​
void
enableAiControl() ​
enableAiControl(
config):Promise<void>
Defined in: graphty-element/src/Graph.ts:6088
Enable AI-powered natural language control of the graph.
Parameters ​
config ​
AI configuration including provider and optional API key
Returns ​
Promise<void>
Promise resolving when AI is ready
Example ​
// Enable with mock provider (for testing)
await graph.enableAiControl({ provider: 'mock' });
// Enable with OpenAI
await graph.enableAiControl({
provider: 'openai',
apiKey: 'sk-...'
});
// Now you can send commands
const result = await graph.aiCommand('Show me the graph summary');enterXR() ​
enterXR(
mode):Promise<void>
Defined in: graphty-element/src/Graph.ts:6475
Enter XR mode (VR or AR)
Parameters ​
mode ​
"immersive-vr" | "immersive-ar"
The XR mode to enter ('immersive-vr' or 'immersive-ar')
Returns ​
Promise<void>
estimateAnimationCapture() ​
estimateAnimationCapture(
options):Promise<CaptureEstimate>
Defined in: graphty-element/src/Graph.ts:4639
Estimate performance and potential issues for animation capture
Parameters ​
options ​
Pick<AnimationOptions, "duration" | "fps" | "width" | "height">
Animation options to estimate
Returns ​
Promise<CaptureEstimate>
Promise resolving to CaptureEstimate
Example ​
const estimate = await graph.estimateAnimationCapture({
duration: 5000,
fps: 60,
width: 3840,
height: 2160
});
if (estimate.likelyToDropFrames) {
console.warn(`May drop frames. Recommended: ${estimate.recommendedFps}fps`);
}exitXR() ​
exitXR():
Promise<void>
Defined in: graphty-element/src/Graph.ts:6519
Exit XR mode and return to previous camera
Returns ​
Promise<void>
exportCameraPresets() ​
exportCameraPresets():
Record<string,CameraState>
Defined in: graphty-element/src/Graph.ts:5925
Export user-defined presets as JSON
Returns ​
Record<string, CameraState>
Object mapping preset names to camera states
exportGraph() ​
exportGraph(
format,options?):Promise<ExportResult>
Defined in: graphty-element/src/Graph.ts:5959
Write the graph in a file format.
The export carries whatever the format can represent: every node and edge with its attributes, the current positions, every published algorithm result (as attributes named by the result's path, results.<runId>.<field>) and the colour, size and edge width each element is drawn with. What the format has no place for is listed in lossNotes, one note per kind of omission; nothing is dropped silently. The element's internal ids and columns are never written.
Notes are left out unless { notes: true } asks for them; then each node and edge a note names gets the graphty.notes.count and graphty.notes.text columns. Either way an export of a session holding notes reports W_GRAPHTY_NOTES.
Every built-in format can be written, and so can any format a writer was registered for with registerFormatWriter. A Neo4j admin-import file is exportGraph("csv", { variant: "neo4j" }).
Parameters ​
format ​
The format id, as session.catalog.formats() lists it.
options? ​
The writer's options, plus graph-io's sanitizeIds and onMixedDirection and the element's notes.
Returns ​
Promise<ExportResult>
The loss notes, and the document as text or as UTF-8 chunks.
Throws ​
A GraphtyError (as a rejection): E_UNKNOWN_FORMAT when nothing writes the format, E_UNKNOWN_OPTION or E_OPTION_RANGE for an option the format's writerOptions does not accept, E_UNSUPPORTED when the writer's up-front check refuses this graph under these options. A refusal found only while writing rejects text() or bytes instead.
getAcceleration() ​
getAcceleration():
AccelerationController
Defined in: graphty-element/src/Graph.ts:3269
Get the acceleration controller this graph owns, for a manager reached through GraphContext.
Returns ​
AccelerationController
The acceleration controller
Since ​
2.0.0
Implementation of ​
getAiManager() ​
getAiManager():
AiManager|null
Defined in: graphty-element/src/Graph.ts:6210
Get the AI manager for advanced configuration. Returns null if AI is not enabled.
Returns ​
AiManager | null
The AI manager or null
Example ​
const manager = graph.getAiManager();
if (manager) {
// Register custom command
manager.registerCommand(myCustomCommand);
}getAiStatus() ​
getAiStatus():
AiStatus|null
Defined in: graphty-element/src/Graph.ts:6152
Get the current AI status synchronously.
Returns ​
AiStatus | null
Current AI status or null if AI is not enabled
Example ​
const status = graph.getAiStatus();
if (status?.state === 'executing') {
console.log('AI is processing a command...');
}getApiKeyManager() ​
getApiKeyManager():
ApiKeyManager|null
Defined in: graphty-element/src/Graph.ts:6259
Get the API key manager for configuring keys before enabling AI. Returns null if AI has never been enabled.
Returns ​
ApiKeyManager | null
The API key manager or null
Example ​
const keyManager = graph.getApiKeyManager();
if (keyManager) {
const providers = keyManager.getConfiguredProviders();
console.log('Configured providers:', providers);
}getAutoFrame() ​
getAutoFrame():
boolean
Defined in: graphty-element/src/Graph.ts:3532
Whether the camera frames the graph on its own after a data load or a layout change.
Returns ​
boolean
True (the default) when it does
getCameraController() ​
getCameraController():
CameraController|null
Defined in: graphty-element/src/Graph.ts:4148
Get the active camera controller.
Returns ​
CameraController | null
The active camera controller or null if none active
getCameraPresets() ​
getCameraPresets():
Record<string,CameraState| {builtin:true; }>
Defined in: graphty-element/src/Graph.ts:5906
Every name loadCameraPreset will answer to: the camera views, then this graph's snapshots.
{ builtin: true } marks a name that is a VIEW -- a rule recomputed against whatever is on screen -- as against a snapshot, which is a fixed state and is returned as one. A view a third party registered is listed on the same terms as one the element ships, because a picker built from this list would otherwise offer the element's own views and silently omit everybody else's. What each view is called in plain words, and which drawing modes it works in, is in session.catalog.cameras().
Returns ​
Record<string, CameraState | { builtin: true; }>
Every name, mapped to the snapshot it holds or to the computed-view marker.
getCameraState() ​
getCameraState():
CameraState
Defined in: graphty-element/src/Graph.ts:4650
Get the current camera state
Returns ​
Camera state including position, target, and rotation
getConfig() ​
getConfig():
GraphContextConfig
Defined in: graphty-element/src/Graph.ts:3906
Get the current graph context configuration.
Returns ​
The graph context configuration
Implementation of ​
getDataManager() ​
getDataManager():
DataManager
Defined in: graphty-element/src/Graph.ts:3204
Get the DataManager instance.
Returns ​
The DataManager instance
Implementation of ​
getEdgeCount() ​
getEdgeCount():
number
Defined in: graphty-element/src/Graph.ts:3002
Get the total number of edges in the graph.
As with the node count, this is the count in the graph data rather than the count of edges that have a mesh yet.
Returns ​
number
The number of edges
getEventManager() ​
getEventManager():
EventManager
Defined in: graphty-element/src/Graph.ts:3260
Get the EventManager instance for event handling.
Returns ​
The EventManager instance
Implementation of ​
getLayoutBehavior() ​
getLayoutBehavior(): {
fetchEdges?:Function;fetchNodes?:Function;labels?: {declutter?:boolean; };layout?: {iterationsPerStep?:number;maxInFlight?:number;minDelta?:number;preSteps?:number;stepMultiplier?:number;type?:string;zoomStepInterval?:number; };node?: {pinOnDrag?:boolean; }; } |undefined
Defined in: graphty-element/src/Graph.ts:1711
The layout behaviour: the view preferences somebody set on this graph, and the pacing settings saved with the project (preSteps, stepMultiplier, minDelta) as they are in effect. Those three always read their value, so assigning one its default reads back even though it records no step.
Returns ​
{ fetchEdges?: Function; fetchNodes?: Function; labels?: { declutter?: boolean; }; layout?: { iterationsPerStep?: number; maxInFlight?: number; minDelta?: number; preSteps?: number; stepMultiplier?: number; type?: string; zoomStepInterval?: number; }; node?: { pinOnDrag?: boolean; }; } | undefined
The behaviour settings.
getLayoutManager() ​
getLayoutManager():
LayoutManager
Defined in: graphty-element/src/Graph.ts:3212
Get the LayoutManager instance.
Returns ​
The LayoutManager instance
Implementation of ​
getLayoutScope() ​
getLayoutScope():
Scope|undefined
Defined in: graphty-element/src/Graph.ts:2309
What layouts run over: the scope the running layout was given, carried to the next one.
Returns ​
Scope | undefined
The canonical scope, or undefined when layouts run over the whole graph.
Since ​
2.5.0
getMeshCache() ​
getMeshCache():
MeshCache
Defined in: graphty-element/src/Graph.ts:3228
Get the MeshCache instance used for mesh instancing.
Returns ​
MeshCache
The MeshCache instance
Implementation of ​
getNode() ​
getNode(
nodeId):Node|undefined
Defined in: graphty-element/src/Graph.ts:6043
Get a specific node
Parameters ​
nodeId ​
string | number
ID of the node to retrieve
Returns ​
Node | undefined
The node instance or undefined if not found
getNodeCount() ​
getNodeCount():
number
Defined in: graphty-element/src/Graph.ts:2991
Get the total number of nodes in the graph.
This is the count in the graph data, which mid-load can be AHEAD of the nodes that have been drawn: an edge whose endpoints have not arrived materialises them in the store while its render objects wait. The data is the authority, so the data is what is counted.
Returns ​
number
The number of nodes
getNodeMesh() ​
getNodeMesh(
nodeId):AbstractMesh|null
Defined in: graphty-element/src/Graph.ts:4157
Get the Babylon.js mesh for a node by its ID.
Parameters ​
nodeId ​
string
ID of the node
Returns ​
AbstractMesh | null
The node's mesh or null if not found
getNodes() ​
getNodes():
Node[]
Defined in: graphty-element/src/Graph.ts:6051
Get all nodes
Returns ​
Node[]
Array of all node instances
getScene() ​
getScene():
Scene
Defined in: graphty-element/src/Graph.ts:3236
Get the Babylon.js Scene instance.
Returns ​
Scene
The Scene instance
Implementation of ​
getSelectedNode() ​
getSelectedNode():
Node|null
Defined in: graphty-element/src/Graph.ts:3286
Get the currently selected node.
Superseded by session.selection.nodes, which is the whole selection rather than the first node of it: this answers with one render object, and a selection now holds any number of nodes and edges. It keeps working, and returns the first selected node.
Returns ​
Node | null
The first selected node, or null if nothing is selected.
See ​
Graph.select to change the selection.
getSelectionManager() ​
getSelectionManager():
SelectionManager
Defined in: graphty-element/src/Graph.ts:3252
Get the SelectionManager instance for handling node selection.
Returns ​
The SelectionManager instance
Implementation of ​
GraphContext.getSelectionManager
getSession() ​
getSession():
GraphSession
Defined in: graphty-element/src/Graph.ts:2979
The headless model behind this renderer: the graph data, the coordinates, the statistics, the catalogue, the configuration and what this machine can do.
Everything about the graph that needs no screen is answered from here, so a consumer asking "how dense is this?" or "what attributes does it carry?" asks the session rather than walking the render objects.
Returns ​
The session
Implementation of ​
getStatsManager() ​
getStatsManager():
StatsManager
Defined in: graphty-element/src/Graph.ts:3244
Get the StatsManager instance for performance metrics.
Returns ​
The StatsManager instance
Implementation of ​
getStylePainter() ​
getStylePainter():
StylePainter
Defined in: graphty-element/src/Graph.ts:3131
Get the painter that answers what the session's style stack resolved for one element.
Part of this class's GraphContext half: Node and Edge reach it through here, and it is what tells them which of the two style systems owns their paint.
Returns ​
StylePainter
The painter.
Implementation of ​
getStyles() ​
getStyles():
Styles
Defined in: graphty-element/src/Graph.ts:3120
Get the Styles instance for the graph.
Returns ​
Styles
The Styles instance
Implementation of ​
getSuggestedStyles() ​
getSuggestedStyles(
algorithmKey): readonlyStyleSuggestion[]
Defined in: graphty-element/src/Graph.ts:2694
What an algorithm's finished runs suggest be drawn from them, without painting any of it.
Parameters ​
algorithmKey ​
string
A catalogue key such as "degree", or a 1.10 address such as "graphty:degree".
Returns ​
readonly StyleSuggestion[]
One suggestion per channel a run of that algorithm would paint, empty when it has finished no run or its result is read rather than painted.
getUpdateManager() ​
getUpdateManager():
UpdateManager
Defined in: graphty-element/src/Graph.ts:3220
Get the UpdateManager instance.
Returns ​
The UpdateManager instance
getViewMode() ​
getViewMode():
"2d"|"3d"|"ar"|"vr"
Defined in: graphty-element/src/Graph.ts:3448
Get the current view mode. Returns the viewMode from config (always set due to default value).
Returns ​
"2d" | "3d" | "ar" | "vr"
The current view mode ("2d", "3d", "ar", or "vr")
getVoiceAdapter() ​
getVoiceAdapter():
VoiceInputAdapter
Defined in: graphty-element/src/Graph.ts:6315
Get the voice input adapter. Creates the adapter on first use.
Returns ​
The voice input adapter
Example ​
const adapter = graph.getVoiceAdapter();
if (adapter.isSupported) {
adapter.start({ continuous: true });
}getXRConfig() ​
getXRConfig():
XRConfig|undefined
Defined in: graphty-element/src/Graph.ts:3949
Get the current XR configuration.
Returns ​
XRConfig | undefined
The XR configuration if set
Implementation of ​
getXRSessionManager() ​
getXRSessionManager():
XRSessionManager|undefined
Defined in: graphty-element/src/Graph.ts:3968
Get the XR session manager instance.
Returns ​
XRSessionManager | undefined
The XR session manager if XR is initialized
Implementation of ​
GraphContext.getXRSessionManager
importCameraPresets() ​
importCameraPresets(
presets):void
Defined in: graphty-element/src/Graph.ts:5982
Import user-defined presets from JSON, as one undoable step.
Parameters ​
presets ​
Record<string, CameraState>
Object mapping preset names to camera states
Returns ​
void
init() ​
init():
Promise<void>
Defined in: graphty-element/src/Graph.ts:1399
Initializes the graph instance, setting up managers, styles, and rendering pipeline.
Returns ​
Promise<void>
is2D() ​
is2D():
boolean
Defined in: graphty-element/src/Graph.ts:3438
Check if the graph is in 2D mode (deprecated - use getViewMode instead).
Returns ​
boolean
True if in 2D mode, false otherwise
Deprecated ​
Use getViewMode() === "2d" instead
Implementation of ​
isAiEnabled() ​
isAiEnabled():
boolean
Defined in: graphty-element/src/Graph.ts:6218
Check if AI control is currently enabled.
Returns ​
boolean
True if AI is enabled
isAnimationCapturing() ​
isAnimationCapturing():
boolean
Defined in: graphty-element/src/Graph.ts:4617
Check if an animation capture is currently in progress
Returns ​
boolean
True if currently capturing an animation
isARSupported() ​
isARSupported():
Promise<boolean>
Defined in: graphty-element/src/Graph.ts:4004
Check if AR mode is supported on this device/browser. Returns true if WebXR is available and AR sessions are supported.
Returns ​
Promise<boolean>
Promise resolving to true if AR is supported
Example ​
const arSupported = await graph.isARSupported();
if (!arSupported) {
console.log("AR not available on this device");
}isNodeSelected() ​
isNodeSelected(
nodeId):boolean
Defined in: graphty-element/src/Graph.ts:3368
Check if a specific node is currently selected.
Answered from the selection masks, so it is one array read and it is true for EVERY selected node rather than only the first one. Superseded by session.selection.has, which answers the same question for an edge too.
Parameters ​
nodeId ​
string | number
The ID of the node to check.
Returns ​
boolean
True if the node is selected, false otherwise.
isRunning() ​
isRunning():
boolean
Defined in: graphty-element/src/Graph.ts:3928
Check if the layout engine is currently running.
Returns ​
boolean
True if layout is running
Implementation of ​
isVoiceActive() ​
isVoiceActive():
boolean
Defined in: graphty-element/src/Graph.ts:6412
Check if voice input is currently active.
Returns ​
boolean
True if voice input is active
isVRSupported() ​
isVRSupported():
Promise<boolean>
Defined in: graphty-element/src/Graph.ts:3984
Check if VR mode is supported on this device/browser. Returns true if WebXR is available and VR sessions are supported.
Returns ​
Promise<boolean>
Promise resolving to true if VR is supported
Example ​
const vrSupported = await graph.isVRSupported();
if (!vrSupported) {
console.log("VR not available on this device");
}listenerCount() ​
listenerCount():
number
Defined in: graphty-element/src/Graph.ts:3082
Get the total number of registered event listeners. Useful for debugging and testing to ensure listeners are properly cleaned up.
Returns ​
number
The number of registered listeners
loadCameraPreset() ​
loadCameraPreset(
name,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5888
Load a camera preset (built-in or user-defined)
Parameters ​
name ​
string
Name of the preset to load
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when camera state is applied
loadFromFile() ​
loadFromFile(
file,options?):Promise<{loadId:number; }>
Defined in: graphty-element/src/Graph.ts:1886
Load graph data from a File object with auto-format detection
Parameters ​
file ​
File
File object from file input
options? ​
Loading options
edgeSource? ​
string
Where the node an edge starts at is named in the record. Left unset, the element reads source, then src, then from
edgeTarget? ​
string
Where the node an edge ends at is named in the record
format? ​
string
Explicit format override (e.g., "graphml", "json")
graphIndex? ​
number
Which graph to read, by position, from a file that holds several (listGraphs from ./catalog lists them); the first when neither choice is given
graphName? ​
string
Which graph to read, by name, from a file that holds several
nodeIdPath? ​
string
JMESPath for node ID extraction
replace? ​
boolean
Replace the graph, once the file has parsed; see addDataFromSource
Returns ​
Promise<{ loadId: number; }>
Promise that resolves to the load's id when data is loaded
loadFromUrl() ​
loadFromUrl(
url,options?):Promise<{loadId:number; }>
Defined in: graphty-element/src/Graph.ts:1965
Load graph data from a URL with auto-format detection
Parameters ​
url ​
string
URL to fetch graph data from
options? ​
Loading options
edgeSource? ​
string
Where the node an edge starts at is named in the record. Left unset, the element reads source, then src, then from
edgeTarget? ​
string
Where the node an edge ends at is named in the record
format? ​
string
Explicit format override (e.g., "graphml", "json")
graphIndex? ​
number
Which graph to read, by position, from a file that holds several
graphName? ​
string
Which graph to read, by name, from a file that holds several
nodeIdPath? ​
string
JMESPath for node ID extraction
replace? ​
boolean
Replace the graph, once the data has parsed; see addDataFromSource
Returns ​
Promise<{ loadId: number; }>
Promise that resolves to the load's id when data is loaded
Remarks ​
This method attempts to detect the format from the URL extension first. If the extension is not recognized (e.g., .txt), it fetches the content and uses content-based detection. The content is then passed directly to the data source to avoid a double-fetch.
Example ​
// Auto-detect format from extension
await graph.loadFromUrl("https://example.com/data.graphml");
// Auto-detect from content when extension doesn't match
await graph.loadFromUrl("https://example.com/data.txt");
// Explicitly specify format
await graph.loadFromUrl("https://example.com/data.txt", { format: "graphml" });needsRayUpdate() ​
needsRayUpdate():
boolean
Defined in: graphty-element/src/Graph.ts:3920
Always false.
Returns ​
boolean
false
Deprecated ​
Each edge aims its own ray when it needs one. Will be removed in graphty-element 4.0.
Implementation of ​
nodeScreenPosition() ​
nodeScreenPosition(
nodeId):NodeScreenPosition|undefined
Defined in: graphty-element/src/Graph.ts:4082
Where a node is drawn on screen, in the same pixels worldToScreen returns.
Parameters ​
nodeId ​
string | number
The node's id.
Returns ​
NodeScreenPosition | undefined
The centre, whether it is drawn on screen, and its radius in pixels; undefined for an id the graph does not hold.
on() ​
on<
K>(type,cb): () =>void
Defined in: graphty-element/src/Graph.ts:3027
Listen for a graph event, and get back the way to stop listening.
THE RETURN VALUE IS THE POINT. on used to hand back nothing, and the events guide taught graph.off(type, handler) to undo it -- a method that has never existed in any version of this package. So a consumer who subscribed could not unsubscribe at all: the element's own unsubscribe takes the id that addListener now returns, and on threw that id away. A component that mounted, subscribed and unmounted leaked a listener per mount.
The shape is the session's: session.on(...) returns a function that undoes it, and this is the same promise for the renderer's events.
Type Parameters ​
K ​
K extends EventType
Parameters ​
type ​
K
Event type to listen for
cb ​
(evt) => void
Callback function to execute when event fires
Returns ​
A function that removes this listener. Calling it twice is harmless.
() => void
Since ​
2.0.0
Example ​
const stop = graph.on("graph-settled", () => console.log("settled"));
stop();onAiStatusChange() ​
onAiStatusChange(
callback): () =>void
Defined in: graphty-element/src/Graph.ts:6173
Subscribe to AI status changes.
Parameters ​
callback ​
Function called when status changes
Returns ​
Unsubscribe function
() => void
Example ​
const unsubscribe = graph.onAiStatusChange((status) => {
console.log('AI state:', status.state);
if (status.streamedText) {
console.log('Response:', status.streamedText);
}
});
// Later: stop listening
unsubscribe();removeCameraPreset() ​
removeCameraPreset(
name):Promise<void>
Defined in: graphty-element/src/Graph.ts:5878
Forget a camera state saved with saveCameraPreset or importCameraPresets. One undoable step.
Parameters ​
name ​
string
The name it was saved under.
Returns ​
Promise<void>
Settles once the step is recorded.
Throws ​
A GraphtyError (as a rejection) with E_BAD_COMMAND when nothing is saved under the name.
removeEdges() ​
removeEdges(
edgeIds,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2745
Remove edges from the graph by their ids, as one undoable step. Undo puts them back at the rows they held, with their weights and ids.
Parameters ​
edgeIds ​
string[]
The element-assigned edge ids
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Settles once the change is drawn
removeListener() ​
removeListener(
id):boolean
Defined in: graphty-element/src/Graph.ts:3054
Stop listening, given the id addListener handed back.
Parameters ​
id ​
symbol
The id to remove.
Returns ​
boolean
True when a listener was removed, false when that id is not registered.
Since ​
2.0.0
removeNodes() ​
removeNodes(
nodeIds,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2734
Remove nodes from the graph by their IDs, and with them every edge attached to one, as one undoable step. Undo puts them back at the rows they held.
One elements-removed event is emitted per call, naming the nodes and every edge that went with them. A removal used to be silent, so a consumer watching the element saw its counts change with nothing to say why; cascading the incident edges made that gap bigger, which is why the notification lands with the cascade rather than after it.
Parameters ​
nodeIds ​
(string | number)[]
Array of node IDs to remove
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Settles once the change is drawn
render() ​
render():
void
Defined in: graphty-element/src/Graph.ts:6058
Render method (public for testing)
Returns ​
void
resetCamera() ​
resetCamera(
options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5615
Reset camera to default state
Parameters ​
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when camera is reset
resolveCameraPreset() ​
resolveCameraPreset(
preset,options?):CameraState
Defined in: graphty-element/src/Graph.ts:5794
Work out where a named camera view would put the viewer, without moving anything.
The name is resolved against the views the element ships and then the views a third party registered, so a plugin's view is named exactly the way "isometric" is. A name that is neither, and is not a snapshot this graph saved, is refused with E_UNKNOWN_CAMERA.
Parameters ​
preset ​
string
The view's name, or the name of a snapshot saved with saveCameraPreset.
options? ​
What to frame and how to configure the view.
nodes? ​
Iterable<string | number, any, any>
The nodes to measure the box over. Absent frames the whole graph.
params? ​
Readonly<Record<string, unknown>>
The view's own options, filled in from its declared defaults.
Returns ​
The camera state the view computed.
Throws ​
A GraphtyError with E_UNKNOWN_CAMERA when nothing answers to the name, E_UNSUPPORTED when the view does not work in the drawing mode the element is in, or E_UNKNOWN_OPTION / E_OPTION_RANGE when params is not what the view declared.
retryLastAiCommand() ​
retryLastAiCommand():
Promise<ExecutionResult>
Defined in: graphty-element/src/Graph.ts:6238
Retry the last AI command. Useful for retrying after transient errors.
Returns ​
Promise<ExecutionResult>
Promise resolving to command result
Throws ​
Error if AI not enabled or no previous command
Example ​
// After a failed command
try {
const result = await graph.retryLastAiCommand();
console.log('Retry succeeded:', result);
} catch (error) {
console.error('Retry failed:', error);
}run() ​
run(
algorithm,params?,options?):Run
Defined in: graphty-element/src/Graph.ts:2509
Start an algorithm and get back something a caller can watch, stop and read.
This is the verb Graph.runAlgorithm should have been. It returns a Run: an object with an identity, a label, live progress, a cancel() and a promise that resolves to the result. Awaiting it gives the result; not awaiting it is safe, because a run is a PromiseLike rather than a Promise subclass and a failure nobody awaited cannot reach the window as an unhandled rejection.
Parameters ​
algorithm ​
Which algorithm to run, by its catalogue key such as "betweenness".
params? ​
Record<string, unknown>
Its parameters, as the catalogue declares them.
options? ​
The scope, the seed, the id, the signal and the progress handler.
Returns ​
The run.
Since ​
2.0.0
Example ​
const run = graph.run("betweenness");
run.cancel(); // a Cancel button, wired
const result = await graph.run("degree");
console.log(result.summary().top); // the ten highest, already rankedrunAlgorithm() ​
runAlgorithm(
namespace,type,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2406
Run a graph algorithm, addressed the 1.10 way.
Parameters ​
namespace ​
string
Algorithm namespace (e.g., "graphty")
type ​
string
Algorithm type (e.g., "degree", "pagerank")
options? ​
Algorithm options and queue settings
Returns ​
Promise<void>
Promise that resolves when algorithm completes
Remarks ​
Algorithms are identified by namespace and type (e.g., graphty:degree). What the run produces is published on the run itself and addressed at results.<runId>.<field>, which is what a style selector reads; nothing is written onto a node.
Available algorithms by category:
- Centrality: degree, betweenness, closeness, pagerank, eigenvector
- Community: louvain, label-propagation, leiden
- Components: connected-components, strongly-connected
- Traversal: bfs, dfs
- Shortest Path: dijkstra, bellman-ford
- Spanning Tree: prim, kruskal
- Flow: max-flow, min-cut
Deprecated ​
Since 2.0. Use Graph.run, which returns a Run: the result is on the object the call hands back, the work reports progress and can be cancelled, and the result is addressed at results.<runId>.<field>. This method still works and is expressed in terms of run, so it produces the same run and the same result; what it cannot give back is the run object those three things hang off.
Since ​
1.0.0
See ​
- Graph.run for the verb that replaces this one
- applySuggestedStyles to visualize results
- Centrality Examples
- Community Detection
Example ​
// This entry point starts the work and hands nothing back. Everything below reads the
// result through the session, which is where a run publishes what it measured.
await graph.runAlgorithm('graphty', 'degree');
const session = graph.getSession();
const [run] = session.runs.list();
// What it measured, per node and as a whole
console.log(run.result?.node('node-1'));
console.log(run.result?.summary().max);
// Paint from it. The selector is written by the element, scoped to the elements the run
// measured, so a node the run never reached is not painted.
await session.styles.encode({ run: run.id, channel: 'node.color' });runAlgorithmsFromTemplate() ​
runAlgorithmsFromTemplate():
Promise<void>
Defined in: graphty-element/src/Graph.ts:1141
Executes all algorithms specified in the style template configuration.
Returns ​
Promise<void>
saveCameraPreset() ​
saveCameraPreset(
name,camera?):void
Defined in: graphty-element/src/Graph.ts:5863
Save where the camera is now under a name of the consumer's choosing. One undoable step.
A snapshot records a POSITION, not a rule: it cannot re-derive itself for a different graph the way a camera view does. Which is why a name a view already holds -- the element's own or a registered one -- is refused rather than shadowed.
Parameters ​
name ​
string
The name to save it under.
camera? ​
The camera state to save instead of where the camera is now.
Returns ​
void
Throws ​
A GraphtyError with E_PROTECTED when a camera view already answers to the name.
screenToWorld() ​
screenToWorld(
screenPos): {x:number;y:number;z:number; } |null
Defined in: graphty-element/src/Graph.ts:4130
Convert 2D screen coordinates to 3D world coordinates via raycasting.
Parameters ​
screenPos ​
Screen position to convert
x ​
number
X coordinate in screen space
y ​
number
Y coordinate in screen space
Returns ​
{ x: number; y: number; z: number; } | null
World coordinates {x, y, z} or null if no intersection
select() ​
select(
target,op?):Promise<SelectionDelta>
Defined in: graphty-element/src/Graph.ts:3384
Change what is selected.
The one selection verb: five set operations over every way of naming elements -- a list of ids, a pasted column, a neighbourhood, a scope, the top twenty of a finished run. Selecting a second node, selecting an edge and inverting a selection are all this call, which is why it supersedes Graph.selectNode and Graph.deselectNode.
Parameters ​
target ​
What to select.
op? ​
What to do with it; replaces the selection when absent, which is what a click does.
Returns ​
Promise<SelectionDelta>
What changed: what joined, what left, and what the selection holds now.
selectNode() ​
selectNode(
nodeId):boolean
Defined in: graphty-element/src/Graph.ts:3325
Select a node by its ID, replacing whatever was selected before.
Superseded by Graph.select, which takes the same five set operations over every way of naming elements. This is select({ nodes: [nodeId] }, "replace") with a render-object lookup in front of it, and it keeps working because it is what a click has always done.
Parameters ​
nodeId ​
string | number
The ID of the node to select
Returns ​
boolean
True if the node was found and selected, false if not found
Remarks ​
Selection triggers a selection-changed event. Only one node is selected by this call; it replaces any previous selection.
Selection is often used to:
- Show a details panel with node information
- Highlight the node and its connections
- Enable context-specific actions
Since ​
1.0.0
See ​
- deselectNode to clear selection
- getSelectedNode to get current selection
- Selection Examples
Example ​
// Select a node and show its details
if (graph.selectNode('node-123')) {
const node = graph.getSelectedNode();
console.log('Selected:', node.data);
showDetailsPanel(node);
}
// Handle click events for selection
graph.on('node-click', ({ node }) => {
graph.selectNode(node.id);
});setAutoFrame() ​
setAutoFrame(
on):void
Defined in: graphty-element/src/Graph.ts:3543
Switch the camera's own framing after a data load or a layout change on or off. Off, the camera stays where it is, and a re-frame already following a moving layout stops. An explicit zoomToFit() frames the graph either way. A preference of the view, not saved in a project file.
Parameters ​
on ​
boolean
True to frame after each load or layout change, false to leave the camera alone.
Returns ​
void
setBackground() ​
setBackground(
background):void
Defined in: graphty-element/src/Graph.ts:1584
Set what the graph is drawn against: a flat colour, or a photo-dome skybox.
A project setting: one step, which undo takes back. The colour reaches the scene's clear colour and a skybox builds a PhotoDome around the graph, announcing skybox-loaded once its texture has arrived; the scene never holds more than one dome. A later read of styles.config.graph.background sees the value, parsed.
Parameters ​
background ​
{ backgroundType: "color"; color: string | undefined; } | { backgroundType: "skybox"; data: string; }
A colour ({backgroundType: "color", color}) or a skybox ({backgroundType: "skybox", data}), where data is an image URL or a base64 PNG.
Returns ​
void
Throws ​
A Zod error when the value is not a background; nothing is changed then.
setCameraMode() ​
setCameraMode(
mode,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2846
Activate the camera that belongs to the current view mode: "2d" in 2D, "orbit" in 3D.
A camera belongs to one view mode, and switching between them is setViewMode's job: it also rebuilds the meshes and the layout for the new mode. A camera from the other mode is refused rather than activated, because activating it would leave the scene drawing through one mode's camera while recording the other, and setViewMode would then take the scene for already being where it was asked to go.
Parameters ​
mode ​
CameraKey
Camera key to activate
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Throws ​
A GraphtyError with E_BAD_COMMAND when the camera does not belong to the view mode the graph is in (or is going to, once queued view-mode changes run).
setCameraPan() ​
setCameraPan(
pan,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5603
Set camera pan (2D)
Parameters ​
pan ​
Pan offset coordinates
x ​
number
X offset
y ​
number
Y offset
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when pan is set
setCameraPosition() ​
setCameraPosition(
position,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5556
Set camera position (3D)
Parameters ​
position ​
Camera position coordinates
x ​
number
X coordinate
y ​
number
Y coordinate
z ​
number
Z coordinate
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when camera position is set
setCameraState() ​
setCameraState(
state,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:4765
Set the camera state (Phase 4: with animation support)
Parameters ​
state ​
CameraState | { preset: string; }
Camera state or preset name to apply
options? ​
Optional animation configuration
Returns ​
Promise<void>
setCameraTarget() ​
setCameraTarget(
target,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5575
Set camera target (3D)
Parameters ​
target ​
Camera target coordinates
x ​
number
X coordinate
y ​
number
Y coordinate
z ​
number
Z coordinate
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when camera target is set
setCameraZoom() ​
setCameraZoom(
zoom,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5591
Set camera zoom (2D)
Parameters ​
zoom ​
number
Zoom level (1.0 = default, >1 = zoomed in, <1 = zoomed out)
options? ​
Optional animation configuration
Returns ​
Promise<void>
Promise that resolves when zoom is set
setData() ​
setData(
data):void
Defined in: graphty-element/src/Graph.ts:6008
Set graph data (delegates to data manager)
Parameters ​
data ​
Graph data object
edges ​
Record<string, unknown>[]
Array of edge data objects. They load as one batch, so the endpoint spelling (source/target, src/dst or from/to) is decided once for all of them.
nodes ​
Record<string, unknown>[]
Array of node data objects
Returns ​
void
setEdges() ​
setEdges(
edges,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2168
Replace every edge in the graph with a new set.
This is what the edge-data property does, and it has to REPLACE rather than append. Under the repeat policy's keep default, an additive setter would double every edge already present each time a host re-assigned the property -- and a host that re-renders on state change re-assigns it constantly. The old drop guard was silently doing this job; deleting the guard without this would have turned "assign the same edges twice" into "hold them twice".
A set past the render ceiling is refused with E_TOO_LARGE before an edge is removed, so the graph keeps the edges it had.
Parameters ​
edges ​
Record<string | number, unknown>[]
the edges the graph should hold afterwards
options? ​
AddEdgesOptions & QueueableOptions
The endpoint expressions, the repeat policy, and queue ordering
Returns ​
Promise<void>
Promise that resolves once the graph holds exactly these edges
setInputEnabled() ​
setInputEnabled(
enabled):void
Defined in: graphty-element/src/Graph.ts:4025
Enable or disable input
Parameters ​
enabled ​
boolean
True to enable input, false to disable
Returns ​
void
setLayout() ​
setLayout(
type,opts?,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2287
Set the layout algorithm and configuration.
Parameters ​
type ​
string
Layout algorithm name
opts? ​
object = {}
Layout-specific configuration options
options? ​
SetLayoutOptions = {}
Options for operation queue behavior, and scope: what the layout runs over (see SetLayoutOptions.scope)
Returns ​
Promise<void>
Promise that resolves when layout is initialized
Remarks ​
Available layouts:
ngraph: Force-directed (3D optimized, recommended for general use)d3-force: Force-directed (2D, web standard)circular: Nodes arranged in a circlegrid: Nodes arranged in a gridhierarchical: Tree/DAG layoutrandom: Random positions (useful for testing)fixed: Use pre-defined positions from node data
Layout changes are queued and execute in order. The layout will animate nodes from their current positions to new positions.
Throws ​
A GraphtyError with E_UNSUPPORTED for a scope on a layout that is not scoped.
Since ​
1.0.0
See ​
- waitForSettled to wait for layout completion
- 3D Layout Examples
- 2D Layout Examples
Example ​
// Use force-directed layout with custom settings
await graph.setLayout('ngraph', {
springLength: 100,
springCoefficient: 0.0008,
gravity: -1.2,
dimensions: 3
});
// Wait for layout to settle then zoom to fit
await graph.waitForSettled();
graph.zoomToFit();
// Switch to circular layout
await graph.setLayout('circular', { radius: 5 });setLayoutBehavior() ​
setLayoutBehavior(
behavior):void
Defined in: graphty-element/src/Graph.ts:1633
Set how the element drives the layout.
MERGED, NOT REPLACED, and one level deep on purpose: a caller naming layout.preSteps means that field and not "reset every other pacing setting to its default", which is what parsing a partial document against a schema of defaults would do.
layout.preSteps, layout.stepMultiplier and layout.minDelta are project settings: setting any of them is one step, which undo takes back. The rest -- label declutter, pin on drag, the throughput settings, the fetchers -- are preferences of this view, and undo does not touch them.
The settings take effect on the next layout the element runs. preSteps is read when a layout starts, so setting it after a graph has already settled changes nothing that is already on screen. labels.declutter is the exception: it takes effect on the next frame.
Parameters ​
behavior ​
The fields to change. Anything omitted keeps its current value.
fetchEdges? ​
Function = ...
fetchNodes? ​
Function = ...
labels? ​
{ declutter?: boolean; } = LabelBehaviorOpts
labels.declutter? ​
boolean = ...
layout? ​
{ iterationsPerStep?: number; maxInFlight?: number; minDelta?: number; preSteps?: number; stepMultiplier?: number; type?: string; zoomStepInterval?: number; } = ...
layout.iterationsPerStep? ​
number = ...
layout.maxInFlight? ​
number = ...
layout.minDelta? ​
number = ...
layout.preSteps? ​
number = ...
layout.stepMultiplier? ​
number = ...
layout.type? ​
string = ...
layout.zoomStepInterval? ​
number = ...
node? ​
{ pinOnDrag?: boolean; } = NodeBehaviorOpts
node.pinOnDrag? ​
boolean = ...
Returns ​
void
Throws ​
A Zod error when a value is outside what the schema allows; nothing is changed then.
setLayoutScope() ​
setLayoutScope(
scope):Promise<void>
Defined in: graphty-element/src/Graph.ts:2325
Change what layouts run over, and restart the running layout over it.
The scope is carried at once, so a layout set after this call runs over it too. It never refuses a scope that cannot be laid out -- one naming a removed set, or a running layout that is not scoped -- because it is not an explicit setLayout: such a scope is inactive, and the layout runs over the whole graph.
Parameters ​
scope ​
ScopeInput | undefined
The scope; undefined or "graph" for the whole graph.
Returns ​
Promise<void>
A promise that resolves once the running layout has restarted.
Throws ​
A GraphtyError with E_BAD_COMMAND when the value is not a scope.
Since ​
2.5.0
setNodes() ​
setNodes(
nodes,idPath?,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2213
Replace every node in the graph with a new set, as one undoable step.
What the node-data property does, and the node half of setEdges. A node whose id is not in the new set is removed the way removeNodes removes one, so the edges attached to it go too. A node whose id IS in the new set keeps its object and its position; its data is not rewritten. A set past the render ceiling is refused with E_TOO_LARGE before a node is removed, so the graph keeps the nodes it had.
Parameters ​
nodes ​
Record<string | number, unknown>[]
the nodes the graph should hold afterwards
idPath? ​
string
Key to use for node IDs (default: the configured node id path)
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Promise that resolves once the graph holds exactly these nodes
Since ​
2.3.0
setRenderer() ​
setRenderer(
request):void
Defined in: graphty-element/src/Graph.ts:1233
Chooses the renderer Graph.init opens. Read once, by init: a graph already drawing keeps its renderer, and a change after that is refused.
Parameters ​
request ​
"webgl" (the default), "webgpu", or "auto" for WebGPU where the browser has it. Where it does not, WebGL draws and Graph.rendererStatus says why.
Returns ​
void
setRenderSettings() ​
setRenderSettings(
_settings,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2887
Update rendering settings for the graph visualization.
Parameters ​
_settings ​
Record<string, unknown>
Object containing rendering configuration options (reserved for future use)
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
setRunning() ​
setRunning(
running):void
Defined in: graphty-element/src/Graph.ts:3941
Set whether the layout engine should run.
Resuming a simulation layout that had settled restarts it, so "play" moves nodes again; pausing stops the per-frame stepping and nothing else. A pause holds until setRunning(true): loading data, setting a layout, an accelerator attaching or a drag never resume it.
Parameters ​
running ​
boolean
True to start the layout, false to stop it
Returns ​
void
Implementation of ​
setSelectionStyle() ​
setSelectionStyle(
selection):void
Defined in: graphty-element/src/Graph.ts:1606
Set what a selected node looks like: its halo's colour, how far it stands out past the node, and how solid it is.
MERGED, NOT REPLACED: naming the colour leaves the scale and the opacity where they were. A project setting: one step, which undo takes back. It takes effect on a selection that is already on screen as well as on the next one.
THE HALO IS NOT A STYLE LAYER, deliberately. A selection is what a person is pointing at rather than a property of the data, so it is drawn by the renderer from the selection mask and its appearance is configuration. See GraphStyle's own note for why a layer would be the wrong shape.
Parameters ​
selection ​
The fields to change. Anything omitted keeps its current value.
color? ​
string = ...
The halo's colour. Any colour the element understands; normalised to hex on parse.
opacity? ​
number = ...
How solid the halo is, in [0, 1]. Low enough to read as a highlight rather than a node.
scale? ​
number = ...
How much of the node's own size the halo is drawn at.
Greater than 1 puts a ring around the node, which is what a highlight reads as. Below 1 the halo disappears inside the node it is meant to mark, so the schema takes any positive number and the default stands a little clear of the node.
Returns ​
void
Throws ​
A Zod error when a value is outside what the schema allows -- a scale that is not positive, an opacity outside [0, 1], a colour the element cannot read.
setStartingCameraDistance() ​
setStartingCameraDistance(
distance):void
Defined in: graphty-element/src/Graph.ts:3560
Set how far the camera stands from the graph, and stop the element framing the graph on its own. Undefined hands framing back to zoom-to-fit.
The 3D orbit camera is moved to the distance (floored at its minimum zoom distance). The 2D camera's half-width becomes the half-extent the 3D camera's field of view covers at that distance, so switching view mode keeps a comparable framing.
Parameters ​
distance ​
number | undefined
The distance, in scene units, or undefined for automatic framing.
Returns ​
void
Throws ​
A GraphtyError with E_OPTION_RANGE when the distance is not a finite number.
setViewMode() ​
setViewMode(
mode,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:3621
Set the view mode. This controls the camera type, input handling, and rendering approach.
Switching between 2D and 3D is one undoable step (view.dimension). Entering VR or AR is not a step -- it is a device session -- but VR and AR draw in 3D, so asking for one from 2D switches to 3D first, and the switch and the entry are one step. When entry fails, because the browser has no WebXR or the session is refused, nothing is recorded, the graph stays in the dimension it was in, and the failure is logged rather than thrown.
Parameters ​
mode ​
"2d" | "3d" | "ar" | "vr"
The view mode to set: "2d", "3d", "ar", or "vr"
options? ​
Optional queueing options; skipQueue switches at once.
Returns ​
Promise<void>
Promise that resolves when view mode is set
Example ​
// Switch to 2D orthographic view
await graph.setViewMode("2d");
// Switch to VR mode
await graph.setViewMode("vr");setXRConfig() ​
setXRConfig(
config):void
Defined in: graphty-element/src/Graph.ts:3958
Set XR configuration. Merges with defaults and updates the graph context.
Parameters ​
config ​
{ ar?: { enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; }; enabled?: boolean; input?: { controllers?: boolean; enableZAmplificationInDesktop?: boolean; handTracking?: boolean; nearInteraction?: boolean; physics?: boolean; zAxisAmplification?: number; }; teleportation?: { easeTime?: number; enabled?: boolean; }; ui?: { enabled?: boolean; position?: "top-right" | "top-left" | "bottom-left" | "bottom-right"; showAvailabilityWarning?: boolean; unavailableMessageDuration?: number; }; vr?: { enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; }; } | undefined
Partial XR configuration to apply
Type Literal ​
{ ar?: { enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; }; enabled?: boolean; input?: { controllers?: boolean; enableZAmplificationInDesktop?: boolean; handTracking?: boolean; nearInteraction?: boolean; physics?: boolean; zAxisAmplification?: number; }; teleportation?: { easeTime?: number; enabled?: boolean; }; ui?: { enabled?: boolean; position?: "top-right" | "top-left" | "bottom-left" | "bottom-right"; showAvailabilityWarning?: boolean; unavailableMessageDuration?: number; }; vr?: { enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; }; }
Partial XR configuration to apply
ar? ​
{ enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; } = ...
AR mode configuration
ar.enabled? ​
boolean = ...
Enable AR mode
Default
truear.optionalFeatures? ​
string[] = ...
Optional WebXR features to request
Default
["hit-test"]ar.referenceSpaceType? ​
"unbounded" | "local" | "local-floor" | "bounded-floor" = ...
WebXR reference space type for AR
Default
"local-floor"enabled? ​
boolean = ...
Enable/disable XR functionality globally
Default
trueinput? ​
{ controllers?: boolean; enableZAmplificationInDesktop?: boolean; handTracking?: boolean; nearInteraction?: boolean; physics?: boolean; zAxisAmplification?: number; } = ...
XR input and interaction configuration
input.controllers? ​
boolean = ...
Enable motion controllers
Default
trueinput.enableZAmplificationInDesktop? ​
boolean = ...
Enable Z-axis amplification in desktop mode Normally amplification only applies in XR mode, but this can enable it for desktop too
Default
falseinput.handTracking? ​
boolean = ...
Enable hand tracking
Default
trueinput.nearInteraction? ​
boolean = ...
Enable near interaction (touch/grab)
Default
trueinput.physics? ​
boolean = ...
Enable physics-based interactions
Default
falseinput.zAxisAmplification? ​
number = ...
Z-axis movement amplification factor Multiplies Z-axis delta during drag to make depth manipulation practical in VR
Example: With zAxisAmplification = 10, moving controller 0.1 units in Z will move the node 1.0 units in Z
Default
10.0teleportation? ​
{ easeTime?: number; enabled?: boolean; } = ...
Teleportation configuration
teleportation.easeTime? ​
number = ...
Teleportation animation duration (ms)
Default
200teleportation.enabled? ​
boolean = ...
Enable teleportation system
Default
falseui? ​
{ enabled?: boolean; position?: "top-right" | "top-left" | "bottom-left" | "bottom-right"; showAvailabilityWarning?: boolean; unavailableMessageDuration?: number; } = ...
XR UI button configuration
ui.enabled? ​
boolean = ...
Show VR/AR entry buttons
Default
trueui.position? ​
"top-right" | "top-left" | "bottom-left" | "bottom-right" = ...
Button position on screen
Default
"bottom-right"ui.showAvailabilityWarning? ​
boolean = ...
Show "VR / AR NOT AVAILABLE" warning when XR is not available When false, no message is displayed if AR/VR aren't available
Default
falseui.unavailableMessageDuration? ​
number = ...
Duration to show "not available" message (ms)
Default
5000vr? ​
{ enabled?: boolean; optionalFeatures?: string[]; referenceSpaceType?: "unbounded" | "local" | "local-floor" | "bounded-floor"; } = ...
VR mode configuration
vr.enabled? ​
boolean = ...
Enable VR mode
Default
truevr.optionalFeatures? ​
string[] = ...
Optional WebXR features to request
Default
[]vr.referenceSpaceType? ​
"unbounded" | "local" | "local-floor" | "bounded-floor" = ...
WebXR reference space type for VR
- "local": Seated/standing experience, no room bounds
- "local-floor": Floor-level origin, no room bounds
- "bounded-floor": Room-scale with bounds
- "unbounded": Unlimited tracking space
Default
"local-floor"undefined
Returns ​
void
shutdown() ​
shutdown():
void
Defined in: graphty-element/src/Graph.ts:1032
Shuts down the graph, stopping animations and disposing all resources.
Returns ​
void
startInputRecording() ​
startInputRecording():
void
Defined in: graphty-element/src/Graph.ts:4032
Start recording input for testing/automation
Returns ​
void
startVoiceInput() ​
startVoiceInput(
options?):boolean
Defined in: graphty-element/src/Graph.ts:6361
Start voice input and execute commands.
Parameters ​
options? ​
Voice input options
continuous? ​
boolean
Whether to continuously listen for input
interimResults? ​
boolean
Whether to return interim transcription results
language? ​
string
BCP 47 language tag (e.g., "en-US", "fr-FR")
onStart? ​
(started, error?) => void
Callback when voice input starts
onTranscript? ​
(text, isFinal) => void
Callback for transcription events
Returns ​
boolean
True if voice input started successfully
Example ​
graph.startVoiceInput({
continuous: true,
interimResults: true,
onTranscript: (text, isFinal) => {
console.log('Transcript:', text, isFinal ? '(final)' : '(interim)');
if (isFinal) {
graph.aiCommand(text);
}
},
});stopInputRecording() ​
stopInputRecording():
RecordedInputEvent[]
Defined in: graphty-element/src/Graph.ts:4040
Stop recording and get recorded events
Returns ​
RecordedInputEvent[]
Array of recorded input events
stopVoiceInput() ​
stopVoiceInput():
void
Defined in: graphty-element/src/Graph.ts:6404
Stop voice input.
Returns ​
void
Example ​
graph.stopVoiceInput();update() ​
update(
frameMs?):void
Defined in: graphty-element/src/Graph.ts:1486
Update method - kept for backward compatibility All update logic is now handled by UpdateManager
Parameters ​
frameMs? ​
number = 0
How long the previous frame took, which sets how many layout steps this frame owes; see UpdateManager.update. Omitted, the frame takes one step.
Returns ​
void
updateEdges() ​
updateEdges(
updates,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2772
Update edge data for existing edges in the graph, as one undoable step. Keys not named are kept; an id the graph does not hold is skipped.
Parameters ​
updates ​
object[]
The edge id and the new values of each edge
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Settles once the change is drawn
updateNodes() ​
updateNodes(
updates,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:2755
Update node data for existing nodes in the graph, as one undoable step.
Parameters ​
updates ​
object[]
Array of update objects containing node ID and properties to update
options? ​
Queue options for operation ordering
Returns ​
Promise<void>
Settles once the change is drawn
waitForSettled() ​
waitForSettled():
Promise<void>
Defined in: graphty-element/src/Graph.ts:4200
Wait for every queued graph operation to finish.
Returns ​
Promise<void>
Promise that resolves when all operations are complete
Remarks ​
This waits for the operation QUEUE -- data loading, layout changes, algorithm runs -- and for nothing else. When it resolves, everything asked for has been carried out; the layout may still be running and the camera may still be moving, because neither of those is a queued operation.
For a picture that will not change again -- a screenshot, a video frame, a visual regression snapshot -- wait for Graph.waitForStableFrame instead, which waits for this queue AND for the layout to converge AND for the camera to finish framing AND for a frame to be drawn in that state.
Since ​
1.0.0
See ​
- zoomToFit to zoom after settling
- captureScreenshot for capturing stable views
Example ​
// Wait for layout to settle before zooming
await graph.addNodes(nodes);
await graph.addEdges(edges);
await graph.waitForSettled();
graph.zoomToFit();
// Wait before taking a screenshot
await graph.setLayout('circular');
await graph.waitForSettled();
const screenshot = await graph.captureScreenshot();
// Chain operations with settle
await graph.runAlgorithm('graphty', 'pagerank');
await graph.waitForSettled();
console.log('Algorithm complete, results available');waitForStableFrame() ​
waitForStableFrame(
options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:4261
Wait until the picture is final.
Parameters ​
options? ​
How the wait is bounded.
timeoutMs? ​
number
How long to wait before giving up; 30 seconds by default.
Returns ​
Promise<void>
Promise that resolves once a frame of the finished picture has been drawn.
Remarks ​
Resolves when all four of these are true, in this order: every queued operation has run, the layout has converged, the camera has finished framing what the layout arrived at, and a frame has been drawn showing it.
The graph-settled event is NOT that moment. It fires the instant the layout engine reports convergence, in the same update pass that merely ASKS for the final framing, so a consumer who photographs on that event photographs a camera that is still moving -- by tens of thousands of projected pixels on a force layout. This is the method that means what that event is usually mistaken for.
It rejects rather than resolving when the picture has not come to rest in time, and the error names what was still moving. A wait for a final frame that quietly gives up and returns a moving one is worse than no wait at all: the caller cannot tell the two apart.
Throws ​
Error when the picture is still changing when the timeout expires.
Since ​
2.0.0
Example ​
await graph.addNodes(nodes);
await graph.addEdges(edges);
await graph.waitForStableFrame();
const screenshot = await graph.captureScreenshot();worldToScreen() ​
worldToScreen(
worldPos):object
Defined in: graphty-element/src/Graph.ts:4052
Convert 3D world coordinates to 2D screen coordinates.
Parameters ​
worldPos ​
World position to convert
x ​
number
X coordinate in world space
y ​
number
Y coordinate in world space
z ​
number
Z coordinate in world space
Returns ​
object
Screen coordinates
x ​
x:
number
y ​
y:
number
zoomStep() ​
zoomStep(
direction,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5636
Move the camera one step nearer or further, the way a Zoom in or Zoom out button does.
One step is a factor of 1.25: the 3D orbit camera's distance from its pivot is divided or multiplied by it, and the 2D camera's zoom multiplied or divided. The camera is view state, so this is not an undoable step.
Parameters ​
direction ​
"out" | "in"
"in" to approach, "out" to withdraw.
options? ​
Optional animation configuration.
Returns ​
Promise<void>
Promise that resolves when the camera has moved.
Since ​
3.0.0
Example ​
await graph.zoomStep("in");zoomToFit() ​
zoomToFit():
void
Defined in: graphty-element/src/Graph.ts:3110
Zoom the camera to fit all nodes in view.
Returns ​
void
Remarks ​
This operation executes immediately and does not go through the operation queue. It may race with queued camera updates.
For better coordination, consider using batchOperations.
Since ​
1.0.0
See ​
- waitForSettled to wait for layout before zooming
- setCameraState for manual camera control
Example ​
// Zoom to fit after data loads
await graph.addNodes(nodes);
await graph.waitForSettled();
graph.zoomToFit();
// Zoom to fit within batch operations
await graph.batchOperations(async () => {
await graph.setViewMode("2d");
graph.zoomToFit(); // Will execute after the mode switch
});zoomToNodes() ​
zoomToNodes(
nodeIds,options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5701
Frame the given nodes: the camera moves so the box around them fills the view.
Works the same in 2D and 3D -- it is the fitToGraph view measured over these nodes only. Ids that name no node are skipped; when none of them names a node the camera does not move. The camera is view state, so this is not an undoable step.
Parameters ​
nodeIds ​
string | number | readonly (string | number)[]
One node id, or several.
options? ​
Optional animation configuration.
Returns ​
Promise<void>
Promise that resolves when the camera has moved.
Since ​
3.3.0
Example ​
await graph.zoomToNodes(["n1", "n2"]);zoomToSelection() ​
zoomToSelection(
options?):Promise<void>
Defined in: graphty-element/src/Graph.ts:5667
Center the camera on the selection, keeping where it stands.
The camera turns to look at the center of the box around the selected nodes and the ends of the selected edges; with nothing selected it does not move. The camera is view state, so this is not an undoable step.
Parameters ​
options? ​
Optional animation configuration.
Returns ​
Promise<void>
Promise that resolves when the camera has moved.
Since ​
3.0.0
Example ​
await graph.select({ nodes: ["n1"] });
await graph.zoomToSelection();