Embed Garphield in your application
A plain embed needs only HTML. Interactive host control uses the JavaScript driver.
Plain iframe
Section titled “Plain iframe”The simplest integration is a plain iframe.
Set the file parameter to a public .gph project:
<iframe src="/embed?file=https%3A%2F%2Fexample.com%2Fnetwork.gph" title="Interactive Garphield network" style="width: 100%; min-height: 32rem; border: 0"></iframe>The file server must allow cross-origin browser requests. A same-site project can use a relative URL.
Readers pan by dragging the background and zoom with the wheel or a pinch. With a mouse or trackpad they can also drag a node to move the node. On a touch screen a drag pans, even when it starts on a node; to move a node, rest a finger on it until a ring shows, then drag. A move lasts until the page reloads and is never saved.
A saved drawing keeps its layout in the embed. When its pictures would cover one another in a frame smaller than the one it was saved from, the embed nudges them apart for that view; the file is not changed.
JavaScript control
Section titled “JavaScript control”Use the browser driver when the host page needs to load projects, change the view, or respond to network events.
pnpm add garphield<iframe id="network" title="Interactive Garphield network"></iframe>import { createGarphield } from "garphield";
const frame = document.querySelector<HTMLIFrameElement>("#network");if (!frame) throw new Error("Missing graph iframe");
const graph = createGarphield(frame);await graph.ready();await graph.setTheme({ colorScheme: "dark" });await graph.setDocument(project);
const stop = graph.on("nodeClick", ({ nodeId }) => { detailPanel.show(nodeId);});
// Before removing the iframe:stop();graph.destroy();Pass project as a parsed .gph document; a JSON string is rejected.
setDocument resolves with the parts of the document the embed skipped and
loads the rest. A binding whose source does not fit its channel, such as a
link colour that reads a node field, is skipped, so nothing draws wrong:
const { warnings } = await graph.setDocument(project);for (const { code, path, message } of warnings) { console.warn(`${code} at ${path}: ${message}`);}warnings is empty when the whole document loaded. Each code and path is
the one document validation reports for the same
problem, for example TARGET_MISMATCH at config.bindings.0.source.target.
Choose UI components
Section titled “Choose UI components”The default embed includes the interaction toolbar, the minimap, and the
Garphield wordmark that opens the graph in the full app. Set chrome to list
the components to show:
/embed?chrome=minimap/embed?chrome=toolbar/embed?chrome=minimap,toolbarAdd search for a node finder in the top-right corner. Typing matches node
labels; choosing a suggestion selects the node, centres the camera on it, and
sends the same nodeClick event as clicking it:
/embed?chrome=minimap,toolbar,searchThe wordmark includes a small arrow, and hovering or focusing it shows
Open in Garphield. It opens the full app in a new tab with the same project
and view. A project too large to send that way, such as one with many
pictures inside, opens from the embed’s file URL with the same view; if the
embed has no file to fall back on, it says so and offers the .gph to
download instead.
The wordmark is always drawn. -wordmark takes the link to the full app off
it and draws it as a static watermark instead:
/embed?chrome=-wordmark/embed?chrome=search,-wordmarkwatermark does the same and reads better in a screenshot or a rendered
image: the mark is larger, with no arrow and no link. PNG export from the MCP
tools uses it:
/embed?chrome=watermarkLegend
Section titled “Legend”Add legend to show what the node colours and shapes mean. It is built from
the document’s colour and shape bindings, one row per colour and per shape in
use, and shows nothing when neither is bound. Each row shows the value’s
label from the binding’s
scale, or else the value itself. A shape section whose values are only shape names
(“diamond”, “square”) is left out. Readers can open and close it, and click a colour to fade the
rest of the graph:
/embed?chrome=toolbar,legend/embed?chrome=toolbar,legend:open/embed?chrome=toolbar,legend:closedA bare legend starts open when the embed is wider than 640px and at least
400px tall, and closed otherwise. An embed 640px wide or less always starts
with the legend closed, legend:open included; opened there, it is a compact
card at most two fifths of the embed’s height, and its rows scroll.
Node popover
Section titled “Node popover”Add tooltip to show a card for a node. By default the card appears once the
pointer rests on a node for about a third of a second. Passing over nodes on
the way somewhere shows nothing. While a card is open, resting on another node
switches the card to it; while the view pans or zooms, the hover card hides
until the pointer rests again. Clicking a node selects it and clears the card
away; clicking the selected node again pins its card, links and all, and so
does double-clicking a node. Restrict
it with tooltip:hover (no pinned cards from the pointer) or tooltip:select
(no hover cards, and a click pins the card at once). On a touch screen, the
first tap selects a node and a second tap on it opens the card, however
quickly it follows. Where another node sits within a fingertip of
the one tapped, the first tap also zooms in on it, so the next tap lands where
it was meant. On an embed 640px wide or less, a selected node’s card sits
along the bottom of the frame, and the view moves the node up if the card
would cover it:
/embed?chrome=toolbar,tooltip/embed?chrome=toolbar,tooltip:selectThe card’s content comes from a template in the document; see Popover template. Links in the card always open in a new tab.
A document can give links a card too, with a link template (see
Link cards). Resting on a link then shows
its card and highlights the link, with the same timing as a node’s hover card;
a node under the pointer takes precedence. Link cards show on hover only, so
tooltip:select shows none, and neither does a touch screen.
Time bar
Section titled “Time bar”Add time for a timeline under the graph that drives the document’s first
enabled time filter: scrub the histogram, or press play. The calendar button
opens exact dates, speed, loop and undated-node options. The bar shows nothing
when the document has no time filter:
/embed?chrome=toolbar,time/embed?chrome=toolbar,time:closedA bare time starts open on roomy embeds and collapsed on narrow ones, like
the legend.
Unknown component names are ignored, and a suffix the embed doesn’t recognise is read as the bare name.
Match your page’s theme
Section titled “Match your page’s theme”Without a theme parameter the embed follows the reader’s light or dark
system setting, and changes when that setting does. A .gph loaded from
file does not change the theme.
Set theme in the URL to choose the theme the embed starts in. It holds even
if a document sent with setDocument() saved a different one:
/embed?theme=light/embed?theme=dark/embed?theme=seafoamTo follow your page’s own theme switcher, start the embed in the page’s
current theme with theme, so it never paints in the wrong one, then call
setTheme() whenever the page changes. setTheme() replaces the URL theme
and is in the default command grant:
const theme = () => document.documentElement.dataset.theme === "dark" ? "dark" : "light";
frame.src = `/embed?file=/network.gph&theme=${theme()}`;const graph = createGarphield(frame);await graph.ready();new MutationObserver(() => graph.setTheme({ colorScheme: theme() })).observe( document.documentElement, { attributes: true, attributeFilter: ["data-theme"] },);A document sent with setDocument() brings its saved theme unless the URL set
one; the latest of setTheme() and setDocument() wins. These docs do the
same for every embed on the page: switch the theme in the header and the
graphs follow.
Match your accent colour
Section titled “Match your accent colour”Set accent to a hex colour to draw the selection glow and ring, the fisheye
lens, and the minimap viewport in your own brand colour. Encode # as %23:
/embed?accent=%23e0115f/embed?theme=dark&accent=%23f80Add accentDark for a different colour while the embed is in the dark theme,
for example when it follows the reader’s setting or the host switches it with
setTheme. Without it the dark
theme uses accent too:
/embed?accent=%23a73752&accentDark=%23e8a4b5Only #rgb and #rrggbb are accepted. Any other value is ignored and the
theme’s accent is used. The legend and time bar use the accent
too; other buttons and focus rings keep the theme’s colours.
Set the background
Section titled “Set the background”Set background to a hex colour to replace the canvas background, so the
embed sits on your page’s own colour. Add backgroundDark for the dark theme;
without it the dark theme uses background too:
/embed?background=%23faf7f2/embed?background=%23faf7f2&backgroundDark=%231e1e1eChoose colours that keep labels readable: node labels are drawn in the theme’s label colour.
Shape the live view
Section titled “Shape the live view”await graph.setBindingEnabled("nodeLabel", false);await graph.setEdgeFilter({ field: "weight", min: 2 });await graph.goToStep(0);Listen for stepChange to keep host navigation in sync with a saved Story.
Once the page sends a Story command, the embed stops drawing its own Story
player and shows only the step’s caption, in a strip above the graph, so the
page’s controls are the only ones and nothing covers the drawing.
Step through dates
Section titled “Step through dates”A document’s time filter (see Time filters) can be moved from the page, for example from buttons that step through years, with no Story and no second document:
// Show the papers published up to the end of 1998.await graph.setTimeFilter({ to: "1998-12-31" });// Only those from 1995 to 2004.await graph.setTimeFilter({ from: "1995-01-01", to: "2004-12-31" });// Remove the start again.await graph.setTimeFilter({ from: null });// The next date in the data, as the time bar's next button does; -1 steps back.await graph.setTimeFilter({ step: 1 });setTimeFilter sets the document’s first enabled time filter, the one the
time bar drives, and stops its playback. Dates are YYYY-MM-DD (UTC
midnight), RFC3339 timestamps with a timezone, or epoch milliseconds; both
ends are inclusive. Name a date field with field to filter by it: the time
filter moves to that field, or, in a document without one, a time filter is
added on it, ending at the field’s latest date. A colour bound to a number
keeps its colours as the window moves: its domain spans every node in the
document, hidden ones included.
Drive the view from your page
Section titled “Drive the view from your page”The host page can change the drawing of one document without sending another one: its layout, its grouping, the fields the colours and sizes read, and the camera. Every method below is in the default command grant.
// Group the nodes by a field: each value becomes a ring around its nodes.await graph.setGroups({ by: ["role"], links: "all" });// Turn grouping off. Rings never move the nodes, so the previous drawing returns.await graph.setGroups(null);
// One node per role, with the links between two roles combined.await graph.setMerge({ by: ["role"], label: "{role} {tasks by side}" });// Stop merging; the network was never changed, so its drawing returns.await graph.setMerge(null);
await graph.setLayout("levels");// Levels from one package down, or one band per value of a numeric field.await graph.setLevels({ roots: ["express"] });await graph.setLevels({ levelAttribute: "year" });// An organisation chart: a tidy tree, growing down or right.await graph.setLevels({ style: "tree", direction: "right" });// Back to automatic levels.await graph.setLevels({});await graph.setBackbone(true);await graph.setLinkStyle("arrow");// Bundle links along the network's shortest paths, or draw them straight.await graph.setLinkRouting({ mode: "bundled", strength: 85 });await graph.setLinkRouting({ mode: "direct" });// Draw each node as its name in a box, as a concept map does.await graph.setLabelPlacement("text");await graph.bind("color", { field: "department" });await graph.bind("size", { algorithm: "degree" });await graph.unbind("size");
await graph.select(["ada"]);await graph.frame({ nodeIds: ["ada", "grace"], durationMs: 300 });await graph.fit();setGroups takes up to four fields, outer to inner. An empty list groups by
detected communities. links says which links draw besides those at the
hovered or selected node: none (the default), inside (links within the
innermost group), between (one curve per pair of groups, as thick as the
links between them), or all, faded. Call it again while grouping is on to
switch to other fields or another links setting; leaving out links keeps
the current one.
setMerge draws one node per value of up to four fields, with the links
between two merged nodes combined into one per direction. Numbers add up, the
field the size channel reads adds areas, categories keep their most common
value, and long text, such as notes, is listed; combine gives a field
another rule (sum, mean, min, max, area, first, mode or list).
label is a template over the merged fields, with {members} for how many
nodes merged and {field by other} for a field’s values per value of another
(see Merged node labels). A merge turns grouping and the Backbone off.
setLinkStyle draws links as plain lines (line), tapered toward their
target (tapered), with arrowheads (arrow), or as animated flow (flow),
the same choices as the style picker in the Links settings. The direction
styles show on directed networks.
setLinkRouting draws links straight between their ends (direct) or
bundled (bundled): each link follows the shortest path through the network
between its ends, so links that travel the same way merge into one trunk, as
the Bundling switch does in the workbench. strength, 0 to 100, is how far a
bundled link follows its route; 0 is the straight drawing. Leaving it out
keeps the current strength.
setLabelPlacement puts node labels beside their nodes (beside), centres
them on the nodes (center), or draws each node as its label in a box sized
to the text (text), the way a concept map names its ideas. Links end at the
box’s edge. setLabelSize sizes labels all alike (fixed), by their node
(node), or shrinks each until it fits (fit).
Each call resolves once the embed has applied it and rejects when the embed
refuses it, for example a node id that is not in the document. A rejection
from the embed is a GarphieldProtocolError with a code such as
VALIDATION and a fixed message. Calls resolve with no value, and errors do
not say what was wrong: the default grant returns nothing about the document.
For two views of one network, such as a pair of buttons, send the document once and switch between the views with these methods.
Driver methods
Section titled “Driver methods”| Method | Purpose |
|---|---|
ready() |
Wait for the renderer. |
setDocument(project) |
Replace the network and view; resolves with what was skipped. |
setTheme({ colorScheme }) |
Set Light, Graphite, or Seafoam. |
setEdgeFilter({ field, min }) |
Hide links below a value. |
setBindingEnabled(channel, enabled) |
Toggle a visual binding. |
setTimeFilter({ field, to, from, step }) |
Set the time filter’s window, or step through its dates. |
setLayout(mode) |
Switch to Force, Levels, or Geo. |
setLevels({ roots, levelAttribute, style, direction }) |
Draw Levels from chosen nodes or by a numeric field, or as a tree growing down or right. |
setGroups({ by, links }), setGroups(null) |
Group nodes by fields, or stop. |
setMerge({ by, label, combine }), setMerge(null) |
Draw one node per value of fields, or stop. |
setBackbone(on), setDetail({ mode }) |
Draw only the Backbone’s links, or every link. |
setLinkStyle(style) |
Draw links as lines, tapered, arrows, or flow. |
setLinkRouting({ mode, strength }) |
Draw links straight, or bundled along shortest paths. |
setLabelPlacement(placement), setLabelSize(mode) |
Place node labels beside, centred, or as the node; size them. |
bind(channel, source), unbind(channel) |
Bind a visual channel to a field or algorithm, or remove it. |
setScale(channel, scale) |
Set a bound channel’s explicit marks and legend labels, or pass null to return to the default marks. |
fit(), frame(options), focus(nodeId) |
Move the camera. |
select(nodeIds), clearSelection() |
Change the selection. |
goToStep(), nextStep(), prevStep() |
Control a saved Story. |
run(command, params) |
Run a granted workbench command. |
on(event, handler) |
Listen for node clicks, Story changes, and errors. |
destroy() |
Remove listeners and reject pending calls. |
Calls and the initial ready wait use a 10-second timeout by default.
Use another deployment
Section titled “Use another deployment”embedUrl is the renderer loaded into the iframe. appUrl is the full
Garphield workbench opened by Open full app. Set both when Garphield runs on
your own domain, behind an internal gateway, or in a private deployment.
const graph = createGarphield(frame, { embedUrl: "https://graphs.example.com/embed", appUrl: "https://graphs.example.com/", timeoutMs: 20_000,});The deployment must allow the host to frame the embed route and grant the commands it uses. See Security and self-hosting.