@molecule/app-feature-graph-view-angular
v1.1.2
Published
Force-directed graph view (Obsidian-style) for visualizing note / page linkages
Maintainers
Readme
@molecule/app-feature-graph-view-angular
Angular force-directed graph view (Obsidian-style) — the counterpart of
@molecule/app-feature-graph-view-react: the same exports, the same props
(React names), and the same DOM for the same input.
Exports:
<GraphView>(div[mol-graph-view]) — top-level node-and-edge visualization with built-inforce,circular, andgridlayouts, click + selection support, and pluggable node / edge templates.GraphNode,GraphEdge,GraphLayout,GraphPoint,PositionedNode,GraphNodeRenderer,GraphEdgeRenderer,GraphViewPropstypes.- Pure layout helpers (
forceLayout,circularLayout,gridLayout,layoutNodes,boundingBox,createRng).
Used by note-taking and other apps to visualize page / note linkages the same way Obsidian does — a force-directed map of which notes link to which.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { Component } from '@angular/core'
import { GraphView, type GraphEdge, type GraphNode } from '@molecule/app-feature-graph-view-angular'
const noteNodes: GraphNode[] = [
{ id: 'a', label: 'Alpha' },
{ id: 'b', label: 'Beta', group: 'project', weight: 2 },
]
const linkEdges: GraphEdge[] = [{ id: 'e1', source: 'a', target: 'b' }]
@Component({
selector: 'app-note-graph',
standalone: true,
imports: [GraphView],
template: `<div mol-graph-view [nodes]="nodes" [edges]="edges" [onNodeClick]="open"></div>`,
})
export class NoteGraph {
nodes = noteNodes
edges = linkEdges
open(node: GraphNode): void {
console.log(`open ${node.id}`)
}
}Type
feature
Installation
npm install @molecule/app-feature-graph-view-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angularAPI
Interfaces
ForceLayoutOptions
Force-layout tunables.
interface ForceLayoutOptions {
/** Hard cap on iterations. Defaults to {@link DEFAULT_FORCE_ITERATIONS}. */
iterations?: number
/** Repulsive constant between every pair of nodes. */
repulsion?: number
/** Spring (Hooke) constant for edges. */
spring?: number
/** Ideal edge length (rest distance). */
restLength?: number
/** Velocity damping per step (0–1). */
damping?: number
/** Optional deterministic seed (for tests). Defaults to a fixed value. */
seed?: number
}GraphPoint
A 2-D point in graph (world) coordinates.
interface GraphPoint {
/** X coordinate. */
x: number
/** Y coordinate. */
y: number
}GraphNode
Single node in the graph.
group is an opaque grouping discriminator (e.g. tag, folder) the
caller can use for colouring; weight scales the rendered radius.
interface GraphNode {
/** Unique node id. */
id: string
/** Human-readable label rendered next to the node. */
label: string
/** Optional grouping discriminator (e.g. tag id). */
group?: string
/** Optional weight; default 1. Scales the rendered radius. */
weight?: number
}GraphEdge
Edge connecting two nodes by id.
interface GraphEdge {
/** Unique edge id. */
id: string
/** Source node id. */
source: string
/** Target node id. */
target: string
/** Optional weight; default 1. Stronger edges pull harder under force layout. */
weight?: number
}PositionedNode
Internal positioned node used by the renderer; the x/y coordinates
are in world (graph) space, with (0, 0) at the canvas centre.
interface PositionedNode extends GraphNode {
/** World-space X coordinate. */
x: number
/** World-space Y coordinate. */
y: number
}GraphViewProps
Props accepted by {@link GraphView} — the same props
@molecule/app-feature-graph-view-react accepts. The renderer props are
Angular templates (a node cannot carry a function), so they are written in
the host template, not bound as values.
interface GraphViewProps {
/** Nodes to render. */
nodes: GraphNode[]
/** Edges to render. */
edges: GraphEdge[]
/** Fired when the user clicks (or activates) a node. */
onNodeClick?: (node: GraphNode) => void
/** Currently-selected node id (highlighted in the view). */
selectedNodeId?: string
/** Layout strategy. Defaults to `'force'`. */
layout?: GraphLayout
/** Custom node renderer (overrides the default circle + label). */
nodeRenderer?: GraphNodeRenderer
/** Custom edge renderer (overrides the default `<line>`). */
edgeRenderer?: GraphEdgeRenderer
/** Force-layout tunables; ignored for non-force layouts. */
forceOptions?: ForceLayoutOptions
/** Extra classes merged onto the outer wrapper. */
className?: string
}Types
GraphLayout
Available layout strategies.
type GraphLayout = 'force' | 'circular' | 'grid'GraphNodeRenderer
Renderer for an individual node: an Angular template rendered through
ngTemplateOutlet, with the positioned node as a0 ($implicit is not
used, so the template reads let-node="a0").
type GraphNodeRenderer = TemplateRef<{ a0: PositionedNode }>GraphEdgeRenderer
Renderer for an individual edge: a template rendered with the edge as a0,
the source node as a1 and the target node as a2.
type GraphEdgeRenderer = TemplateRef<{
a0: GraphEdge
a1: PositionedNode
a2: PositionedNode
}>Classes
GraphView
Force-directed graph view (Obsidian-style).
Renders nodes + edges into an SVG, computing positions via a built-in
minimal velocity-Verlet simulation. Three layouts are supported —
force (default), circular and grid — and either nodes or edges
can be overridden via custom templates.
The host IS the outer <div> (div[mol-graph-view]), matching React's root
exactly. Style is driven by getClassMap(). Inline styles are reserved for
SVG geometry — transform, viewBox computation, stroke widths — which
classes can't express.
@Component({
selector: 'div[mol-graph-view]',
standalone: true,
imports: [NgTemplateOutlet],
inputs: [
'nodes',
'edges',
'onNodeClick',
'selectedNodeId',
'layout',
'nodeRenderer',
'edgeRenderer',
'forceOptions',
'className',
],
host: {
role: 'application',
'[attr.aria-label]': 'ariaLabel()',
'data-mol-id': 'graph-view',
'[class]': 'classes()',
'[style.width]': '"100%"',
'[style.height]': '"100%"',
'[style.overflow]': '"hidden"',
},
template: `@if (positionedNodes().length === 0) {
<div
data-mol-id="graph-view-empty"
role="status"
[class]="emptyClasses()"
[style.inset]="'0px'"
[style.display]="'grid'"
[style.place-items]="'center'"
>
{{ emptyLabel() }}
</div>
} @else {
<svg
data-mol-id="graph-view-svg"
width="100%"
height="100%"
[attr.viewBox]="viewBox()"
preserveAspectRatio="xMidYMid meet"
[style.display]="'block'"
>
<g data-mol-id="graph-view-edges">
@for (item of renderableEdges(); track item.edge.id) {
@if (edgeRenderer) {
<g [attr.data-mol-id]="'graph-view-edge-' + item.edge.id">
<ng-container
[ngTemplateOutlet]="edgeRenderer"
[ngTemplateOutletContext]="{ a0: item.edge, a1: item.src, a2: item.tgt }"
/>
</g>
} @else {
<line
[attr.data-mol-id]="'graph-view-edge-' + item.edge.id"
[attr.x1]="item.src.x"
[attr.y1]="item.src.y"
[attr.x2]="item.tgt.x"
[attr.y2]="item.tgt.y"
stroke="currentColor"
stroke-width="1"
opacity="0.4"
/>
}
}
</g>
<g data-mol-id="graph-view-nodes">
@for (node of positionedNodes(); track node.id) {
<g
[attr.data-mol-id]="'graph-view-node-hit-' + node.id"
role="button"
[attr.aria-label]="nodeAria(node)"
tabindex="0"
(click)="activate(node)"
(keydown)="keydown($event, node)"
[style.cursor]="onNodeClick ? 'pointer' : 'default'"
[style.outline]="'none'"
>
@if (nodeRenderer) {
<ng-container
[ngTemplateOutlet]="nodeRenderer"
[ngTemplateOutletContext]="{ a0: node }"
/>
} @else {
<g
[attr.data-mol-id]="'graph-view-node-' + node.id"
[attr.data-selected]="isSelected(node) ? 'true' : 'false'"
[attr.transform]="'translate(' + node.x + ', ' + node.y + ')'"
>
<circle
[attr.r]="radius(node)"
fill="currentColor"
[attr.opacity]="isSelected(node) ? 1 : 0.85"
stroke="currentColor"
[attr.stroke-width]="isSelected(node) ? 2 : 0"
/>
<text
[attr.x]="radius(node) + 4"
y="4"
font-size="11"
fill="currentColor"
[attr.opacity]="isSelected(node) ? 1 : 0.75"
[style.pointer-events]="'none'"
[style.user-select]="'none'"
[textContent]="node.label"
></text>
</g>
}
</g>
}
</g>
</svg>
}`,
})
export class GraphView {
/** Nodes to render. */
nodes?: GraphNode[]
/** Edges to render. */
edges?: GraphEdge[]
/** Fired when the user clicks (or activates) a node. */
onNodeClick?: (node: GraphNode) => void
/** Currently-selected node id (highlighted in the view). */
selectedNodeId?: string
/** Layout strategy (defaults to `'force'` at read time). */
layout?: GraphLayout
/** Custom node renderer template. */
nodeRenderer?: GraphNodeRenderer
/** Custom edge renderer template. */
edgeRenderer?: GraphEdgeRenderer
/** Force-layout tunables; ignored for non-force layouts. */
forceOptions?: ForceLayoutOptions
/** Extra classes merged onto the outer wrapper. */
className?: string
/** The bonded translation function. */
private readonly i18n = useTranslation()
/**
* The current class map.
* @returns The UIClassMap.
*/
cm(): UIClassMap {
return getClassMap()
}
/**
* Computes the wrapper class list.
* @returns The class string.
*/
classes(): string {
return this.cm().cn(this.cm().position('relative'), this.cm().surfaceSecondary, this.className)
}
/**
* Computes the empty-state class list.
* @returns The class string.
*/
emptyClasses(): string {
return this.cm().cn(this.cm().position('absolute'), this.cm().sp('p', 6))
}
/**
* The canvas' accessible name.
* @returns The translated label.
*/
ariaLabel(): string {
return this.i18n.t('graphView.aria.canvas', {}, { defaultValue: 'Graph view' })
}
/**
* The empty-state message.
* @returns The translated message.
*/
emptyLabel(): string {
return this.i18n.t('graphView.empty', {}, { defaultValue: 'No nodes to display' })
}
/**
* One node hit group's accessible name.
* @param node - The node.
* @returns The translated label.
*/
nodeAria(node: GraphNode): string {
return this.i18n.t(
'graphView.aria.node',
{ label: node.label },
{ defaultValue: 'Node {{label}}' },
)
}
/**
* World-space positions for every node, from the chosen layout. The force
* simulation is deterministic given a fixed seed, so repeated reads (change
* detection runs several) produce identical coordinates.
* @returns The positioned nodes.
*/
positionedNodes(): PositionedNode[] {
return layoutNodes(
this.nodes ?? [],
this.edges ?? [],
this.layout ?? 'force',
this.forceOptions,
)
}
/**
* The edges whose endpoints both exist, with both endpoints resolved.
* @returns The renderable edges, in input order.
*/
renderableEdges(): RenderableEdge[] {
const byId = new Map<string, PositionedNode>()
for (const node of this.positionedNodes()) byId.set(node.id, node)
const out: RenderableEdge[] = []
for (const edge of this.edges ?? []) {
const src = byId.get(edge.source)
const tgt = byId.get(edge.target)
if (src && tgt) out.push({ edge, src, tgt })
}
return out
}
/**
* The SVG viewBox that fits the layout bounds.
* @returns The viewBox string.
*/
viewBox(): string {
const box = boundingBox(this.positionedNodes(), 40)
return box
? `${box.minX} ${box.minY} ${Math.max(1, box.maxX - box.minX)} ${Math.max(1, box.maxY - box.minY)}`
: '-100 -100 200 200'
}
/**
* Whether a node is the selected one.
* @param node - The node.
* @returns True when it matches `selectedNodeId`.
*/
isSelected(node: GraphNode): boolean {
return node.id === this.selectedNodeId
}
/**
* The rendered radius of a node, scaled by its weight.
* @param node - The node.
* @returns The radius in world units.
*/
radius(node: GraphNode): number {
return NODE_RADIUS * Math.sqrt(Math.max(0.25, node.weight ?? 1))
}
/**
* Calls `onNodeClick` for a node.
* @param node - The node.
*/
activate(node: GraphNode): void {
this.onNodeClick?.(node)
}
/**
* Activates a node on Enter or Space, as React's keydown handler does.
* @param event - The keyboard event.
* @param node - The node.
*/
keydown(event: KeyboardEvent, node: GraphNode): void {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
this.onNodeClick?.(node)
}
}
}Functions
createRng(seed)
Tiny deterministic PRNG (mulberry32). Allows reproducible initial
positions in tests without depending on Math.random().
function createRng(seed: number): () => numberseed— 32-bit unsigned seed.
Returns: A function returning floats in [0, 1).
circularLayout(nodes, radius)
Place nodes evenly around the unit circle (scaled by radius).
function circularLayout(nodes: GraphNode[], radius: number): PositionedNode[]nodes— Nodes to position.radius— Circle radius in world units.
Returns: Positioned nodes, in input order.
gridLayout(nodes, spacing)
Place nodes on a square-ish grid, centred on the origin.
function gridLayout(nodes: GraphNode[], spacing: number): PositionedNode[]nodes— Nodes to position.spacing— Pixel spacing between adjacent grid cells.
Returns: Positioned nodes, in input order.
forceLayout(nodes, edges, options)
Run a minimal velocity-Verlet force-directed simulation.
Implements:
- Pairwise repulsion (Coulomb-like, O(n²)) between every node pair.
- Spring (Hooke) attraction along each edge toward
restLength. - Per-step velocity damping for stability.
Stops early once the maximum per-node displacement-squared drops below
{@link CONVERGENCE_EPSILON}, or after iterations steps — whichever
comes first.
function forceLayout(
nodes: GraphNode[],
edges: GraphEdge[],
options?: ForceLayoutOptions,
): PositionedNode[]nodes— Nodes to lay out.edges— Edges (used only for attractive springs).options— Force-layout tunables.
Returns: Positioned nodes, in input order.
layoutNodes(nodes, edges, layout, options)
Compute world-space positions for every node using the chosen layout.
function layoutNodes(
nodes: GraphNode[],
edges: GraphEdge[],
layout: GraphLayout,
options?: ForceLayoutOptions,
): PositionedNode[]nodes— Nodes to position.edges— Edges (consumed only byforce).layout— Layout strategy.options— Optional force-layout tunables (ignored for non-force).
Returns: Positioned nodes.
boundingBox(nodes, padding)
Compute the world-space bounding box of a set of positioned nodes, with a small padding for visual breathing room.
function boundingBox(
nodes: PositionedNode[],
padding?: number,
): { minX: number; minY: number; maxX: number; maxY: number } | nullnodes— Positioned nodes.padding— Padding (world units) added to every side. Default 40.
Returns: Bounding box { minX, minY, maxX, maxY } — or null if empty.
Constants
DEFAULT_FORCE_ITERATIONS
Default cap on force-layout iterations.
const DEFAULT_FORCE_ITERATIONS: 200DEFAULT_REPULSION
Default repulsion strength used by forceLayout.
const DEFAULT_REPULSION: 800DEFAULT_SPRING
Default spring stiffness used by forceLayout.
const DEFAULT_SPRING: 0.05DEFAULT_REST_LENGTH
Default ideal edge length used by forceLayout.
const DEFAULT_REST_LENGTH: 80DEFAULT_DAMPING
Default velocity damping used by forceLayout.
const DEFAULT_DAMPING: 0.85CONVERGENCE_EPSILON
Convergence threshold (max per-node displacement squared).
const CONVERGENCE_EPSILON: 0.01Injection Notes
Requirements
Peer dependencies:
@angular/common^22.0.0@angular/core^22.0.0@angular/platform-browser^22.0.0@molecule/app-angular^3.5.0 || ^4.0.0@molecule/app-ui^1.0.1@molecule/app-ui-angular^1.1.0
Runtime Dependencies
@angular/common@angular/core@angular/platform-browser@molecule/app-angular@molecule/app-ui@molecule/app-ui-angular
The root element fills 100% of its parent — the PARENT must have an explicit height (e.g. a fixed-height panel or a flex/grid track) or the graph renders zero-tall and appears blank.
Interaction surface is click / keyboard-activate + selectedNodeId
highlighting only. Nodes are NOT draggable and there is no built-in
pan / zoom — the SVG viewBox auto-fits the layout bounds.
The renderer props are Angular templates, rendered with ngTemplateOutlet:
nodeRenderer receives the positioned node as a0; edgeRenderer receives
the edge as a0, the source node as a1 and the target node as a2.
Layout is deterministic (seeded RNG), computed once per
(nodes, edges, layout, forceOptions) change. forceOptions is
ignored by the circular and grid layouts.
Translations
Translation strings are provided by @molecule/app-locales-feature-graph-view.
