@simplex-viz/core API Reference
Pure ES2022 TypeScript engine with zero runtime dependencies and zero DOM globals for browsers, Node.js, Bun, Deno, and Web Workers.
- @simplex-viz/core v1.0.0
- Headless Geometry, Clustering, OKLab & SAT Engine
Entry Points
Environment: Universal ES2022 (Browser, Node.js, Deno, Bun, Web Worker, Edge)
Headless geometry, clustering, OKLab mixing, SAT collision layout, 1:4 zoom/drill-down, timeline engine, and shared DOM-free utilities.
Environment: Web Worker, Node.js worker_threads, or SSR async fallback
Exclusive subpath (not re-exported from root) providing off-thread RPC protocol, solver client/handler, and async SSR fallback.
Environment: Browser / DOM Hosts (structural TS interfaces)
Exclusive subpath (not re-exported from root) sharing container, ResizeObserver, tooltip, ARIA/live-region, cursor, click, and viewport zoom helpers across renderers.
Primary Exports
import { … } from '@simplex-viz/core'
Root entrypointsolveSimplexSnapshot<TItem, TTagMeta, TClusterMeta>(
items: readonly TItem[],
options?: SimplexSolverOptions<TItem, TTagMeta, TClusterMeta>,
): SimplexSnapshotResult<TItem, TTagMeta, TClusterMeta>Synchronous one-shot solver returning clusters, mesh triangles, OKLab colors, and 0.0 px non-overlapping item coordinates.
new SimplexGraphEngine<
TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta
>(config: SimplexEngineConfig<...>)Stateful 60 fps engine with live mutations, reduced-motion snapping (reducedMotion), independent multi-selection (selectedIds, shiftClickSelects, selectItemsInScreenRect), structured legend snapshots & diff-gated updates (getLegendModel, onLegendChange), serializable deep-link view state (getViewState, restoreViewState), zero-relayout item filtering (setItemFilter), programmatic search & linked-view navigation (setHighlightedIds, focusItem, zoomToItem), re-entrant batch() coalescing, spring transitions, deferred 0x0 viewport re-initialization, keyboard target traversal, convex/triangle hit-testing, and conformal 1:4 drill-down.
createAdaptiveHexMeshStrategy<TItem>(
defaults?: Partial<MeshOptions>,
): SimplexMeshStrategy<TItem>Selects aspect-aligned 60-degree lattice orientation, row parity, and full-canvas scaling automatically (supports explicit sideLength).
createSoftSimplexEmbeddingClusteringStrategy<TItem, TTagMeta>(
options: SoftSimplexEmbeddingClusteringOptions<TItem>,
): SimplexClusteringStrategy<TItem, TTagMeta>Clusters single- or multi-modal vector embeddings via load-balanced QAP, continuous interior simplex projection, and optional contrastive feature naming.
createSoftSimplexTagClusteringStrategy<TItem, TTagMeta>(
config?: SoftSimplexTagClusteringConfig<TTagMeta>,
): SimplexClusteringStrategy<TItem, TTagMeta>Partitions discrete tags with smooth triangleSpread interior anchoring and unconstrained 360-degree vertex halos.
createComposedLayoutStrategy<TItem>(
options: ComposedLayoutStrategyOptions<TItem>,
): SimplexLayoutStrategy<TItem>Composes any LayoutSeeder × PositionRelaxer × ScaleController with guaranteed 0.0 px convex SAT separation.
createPbdUniformLayoutStrategy(): SimplexLayoutStrategyDefault space-filling uniform layout strategy dispersing items across open covering triangles while preserving one exact global scale factor α.
createLocalAdaptiveLayoutStrategy(
options?: { crowdRadiusPx?: number; minLocalScale?: number; warmStart?: boolean },
): SimplexLayoutStrategyPost-dispersion smooth radial crowd-kernel layout with local halo collision polish and zero global shrink collateral.
createCollisionDrivenLayoutStrategy(
options?: CollisionDrivenLayoutOptions,
): SimplexLayoutStrategySpace-filling local pocket layout keeping all non-colliding items at 1.0x leaf scale and shrinking only colliding pairs.
createSubspaceZoomStrategy<TItem, TTagMeta, TClusterMeta>(
options?: SubspaceZoomStrategyOptions<TItem>,
): SimplexZoomStrategy<TItem, TTagMeta, TClusterMeta>Local variance-projected 1:4 sub-clustering with exact 6! QAP alignment, uniform 1-ring cluster stars, and single-triangle leaf focus.
createBarycentricZoomStrategy<TItem, TTagMeta, TClusterMeta>(
options?: BarycentricZoomStrategyOptions,
): SimplexZoomStrategy<TItem, TTagMeta, TClusterMeta>Conformal 1:4 equilateral subdivision with Adaptive Contrast Stretch, 1-ring cluster stars, and single-triangle leaf focus.
createSemanticZoomStrategy<TItem, TTagMeta, TClusterMeta>(
options?: SemanticZoomStrategyOptions,
): SimplexZoomStrategy<TItem, TTagMeta, TClusterMeta>Exclusive-first 3→6 sub-vertex tag re-partitioning with collision-free labels, 1-ring cluster stars, and single-triangle leaf focus.
assignDiscriminativeClusterLabels<TItem>(
clusters: readonly DiscriminativeClusterInput<TItem>[],
allItems: readonly TItem[],
options: DiscriminativeClusterLabelOptions<TItem>,
): readonly string[]Scores numeric, boolean, and categorical features against corpus base rates to assign pairwise-distinct labels across sibling clusters.
resolveDiscriminativeClusterLabel<TItem, TTagMeta>(
ctx: ClusterDerivationContext<TItem, TTagMeta>,
options: DiscriminativeClusterLabelOptions<TItem>,
): stringConvenience helper for deriveClusterMeta that resolves a cluster's base-rate-aware, collision-free label using ctx.peerClusters and ctx.allItems.
createFinalSeededClusteringStrategy<TItem, TTagMeta>(
baseStrategy?: SimplexClusteringStrategy<TItem, TTagMeta>,
options?: FinalSeededClusteringOptions<TItem>,
): SimplexClusteringStrategy<TItem, TTagMeta>Pins canonical full-corpus clusters, vertex positions, UIDs, and OKLab hues across chronological timeline frames or filtered subsets.
createFinalSeededLayoutStrategy(
baseStrategy?: SimplexLayoutStrategy,
options?: FinalSeededLayoutOptions,
): SimplexLayoutStrategyFreezes canonical full-corpus (x, y) item coordinates across timeline frames with scaleMode: 'pinned' | 'adaptive' and exact SAT overlap verification.
createSimplexTimeline<TItem>(
options?: SimplexTimelineOptions<TItem>,
): SimplexTimelineController<TItem>Zero-DOM headless chronological frame grouper and playback controller with play/pause/step/seek/speed APIs.
createSimplexTimelineHostSession<TItem, TTagMeta>(
initialConfig?: { readonly rawClusteringStrategy?: SimplexClusteringStrategy<TItem, TTagMeta>; readonly rawLayoutStrategy?: SimplexLayoutStrategy; readonly baseEmptyClusterBehavior?: EmptyClusterBehavior },
): SimplexTimelineHostSession<TItem, TTagMeta>Coordinates chronological timeline playback, autoFinalSeed/autoFinalSeedLayout wrapping, and emptyClusterBehavior transitions for renderer controllers.
resolveEffectiveGeometricPolygon(
base: { readonly shape: GeometricShapeKind; readonly sides?: number; readonly rotationRad?: number },
overrides?: { readonly shape?: GeometricShapeKind; readonly sides?: number; readonly rotationRad?: number },
): ResolvedGeometricPolygonResolves base shape visuals plus view-level overrides into canonical polygon kind, side count, rotation, and area-equalized scale.
getGeometricShapeVertices(
resolved: ResolvedGeometricPolygon,
radius: number,
options?: { readonly circleSamples?: number; readonly minRadius?: number; readonly starOuterScale?: number; readonly starInnerScale?: number; readonly useRadiusScale?: boolean },
): readonly Point2D[]Generates local-coordinate perimeter vertices for geometric preset shapes across SVG and Canvas renderers.
measureGeometricShapeHull(
resolved: ResolvedGeometricPolygon,
radius: number,
options?: { readonly useRadiusScale?: boolean; readonly starOuterScale?: number },
): ConvexGeometryBuilds the exact analytical convex collision hull matching a resolved geometric shape.
resolveSimplexThemeBackgroundColor(theme: SimplexColorTheme, surface?: 'svg' | 'canvas'): stringReturns the canonical dark/light backdrop fill color for SVG and Canvas surfaces.
decodeSimplexDataUrlToBytes(
dataUrl: string,
fallbackMime?: string,
): { readonly bytes: Uint8Array<ArrayBuffer>; readonly mimeType: string }Pure ES2022 decoder converting base64 or UTF-8 data: URLs into raw byte buffers without atob, Blob, or DOM globals.
import { … } from '@simplex-viz/core/worker'
Exclusive subpathcreateSimplexWorkerClient(
workerOrFactory?: SimplexWorkerPort | (() => SimplexWorkerPort) | null,
options?: SimplexWorkerClientOptions,
): SimplexWorkerClientGeneration-aware Web Worker / worker_threads client with stale-request cancellation, AbortSignal, zero-copy embedding buffer transfer, main-thread TItem rehydration, and SSR async fallback.
attachSimplexWorkerHandler(
options?: AttachSimplexWorkerHandlerOptions,
): () => voidAttaches the protocol handler inside a Web Worker or Node worker_threads script with a pluggable solver hook (WASM-ready).
solveSimplexSnapshotAsync<TItem>(
items: readonly TItem[],
options?: SolveSimplexSnapshotAsyncOptions<TItem>,
): Promise<SimplexLayoutSnapshot<TItem>>Async counterpart to solveSimplexSnapshot() delegating to an optional SimplexWorkerClient or a yielded macrotask turn.
import { … } from '@simplex-viz/core/dom'
Exclusive subpathobserveSimplexContainerResize(
options: ObserveSimplexContainerResizeOptions,
): SimplexResizeObserverHandleCoordinates ResizeObserver viewport updates, 0x0 auto-recovery, and optional deferInitialLayout fallback timers across SVG and Canvas controllers.
computeSimplexTooltipCoords(
input: ComputeSimplexTooltipCoordsInput,
): SimplexTooltipCoordsComputes viewport edge-flipped, margin-clamped tooltip (left, top) coordinates shared by SVG, Canvas, and React tooltips.
buildSimplexTooltipContentModel<TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta>(
target: SimplexTooltipTargetInput<...>,
options?: BuildSimplexTooltipModelOptions<TItem>,
): SimplexTooltipContentModelBuilds normalized tooltip titles, formatted tags, OKLab accents, cluster counts, and drill-down/neighbor hints.
dispatchSimplexDefaultLeftClick<TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta>(
target: HitTarget<...>,
rawEvent: NormalizedPointerEvent,
context: ...,
): booleanUnifies composable user click callbacks, 1:4 drill-down navigation, and free-camera focus/selection clearing.
zoomSimplexViewportByFactor(
element: Pick<SimplexDomElementLike, 'getBoundingClientRect' | 'clientWidth' | 'clientHeight'>,
camera: Pick<CameraController, 'zoomToCursor'>,
factor: number,
fallbackWidth?: number,
fallbackHeight?: number,
): voidZooms any renderer viewport around its current center using structural element dimensions.
getSimplexTooltipThemeTokens(theme: SimplexColorTheme): SimplexTooltipThemeTokensReturns canonical dark/light floating tooltip surface, border, text, and shadow tokens shared by SVG, Canvas, and React overlays.
createSimplexTooltipOverlay<TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta, TElement extends SimplexDomDivLike = SimplexDomDivLike>(
options: CreateSimplexTooltipOverlayOptions<...>,
): SimplexTooltipOverlay<...>Manages lazy floating tooltip mounting, theme synchronization, custom DOM renderers, target deduplication, and edge-flipped positioning across SVG and Canvas.
bindSimplexInteractiveViewport<TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta>(
options: BindSimplexInteractiveViewportOptions<...>,
): SimplexInteractiveViewportHandleBinds shared pointer panning, multi-touch pinch, touch scroll-locking, Shift-drag marquee, wheel zoom, cursor resolution, click suppression, and keyboard handling.
createSimplexZoomBreadcrumbsOverlay(
options: CreateSimplexZoomBreadcrumbsOverlayOptions,
): SimplexZoomBreadcrumbsOverlayMounts and updates the theme-adaptive drill-down breadcrumb navigation bar shared by SVG and Canvas controllers.
createSimplexTimelineBarOverlay<TItem>(
options: CreateSimplexTimelineBarOverlayOptions,
): SimplexTimelineBarOverlay<TItem>Mounts and updates the compact Play/Pause/Step/Scrubber timeline HUD bar shared by SVG and Canvas controllers.
createSimplexKeyboardNavigator<TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta>(
options: SimplexKeyboardNavigatorOptions<...>,
): SimplexKeyboardNavigatorProvides the shared WCAG 2.1 AA single-tabstop keyboard traversal, selection/activation, Escape cascade, and screen-reader announcement state machine.
Overview & Runtime Guarantees
@simplex-viz/core root and @simplex-viz/core/worker compile strictly against lib: ["ES2022"] with "dependencies": {}. ESLint enforces module boundaries banning window, document, SVG, or React imports inside packages/core. Shared browser/host helpers live on @simplex-viz/core/dom behind purely structural TypeScript interfaces (SimplexDomElementLike, SimplexDomDocumentLike, SimplexDomWindowLike) so skipLibCheck: false consumers without DOM lib entries continue to compile cleanly.
Imperative Engine Lifecycle (SimplexGraphEngine)
import {
SimplexGraphEngine,
createSubspaceZoomStrategy,
createCollisionDrivenLayoutStrategy,
} from '@simplex-viz/core';
const engine = new SimplexGraphEngine({
items,
viewportWidth: 1200,
viewportHeight: 780,
visualResolver,
renderer,
layoutStrategy: createCollisionDrivenLayoutStrategy(),
zoomStrategy: createSubspaceZoomStrategy({ clusterZoomMode: 'incident-star' }),
});
// Mutate items without remounting:
engine.addItems(newItems);
engine.updateItems(modifiedItems);
engine.removeItems(['id-1']);
// Coalesce multiple updates into a single minimal recomputation:
engine.batch(() => {
engine.setMeshOptions({ sideLength: 210 });
engine.setZoomStrategy(createSubspaceZoomStrategy({ clusterZoomMode: 'spotlight' }));
});
// Zero-relayout visual filtering ('dim' | 'hide') without moving SAT coordinates:
engine.setItemFilter((item) => item.tags.includes('geometry'), { mode: 'dim' });
// Linked-view search highlighting, programmatic focus, and camera/drill-down navigation:
engine.setHighlightedIds(['item-1', 'item-4']);
engine.focusItem('item-1', { highlight: true, hover: true });
engine.zoomToItem('item-1', { zoom: 2.2, maxDrillSteps: 4 });
// Interactive multi-selection, reduced-motion preference, legend model & deep-linking view state:
engine.setSelectedIds(['item-1', 'item-2']);
engine.setShiftClickSelects(true);
engine.setReducedMotion('auto');
const legend = engine.getLegendModel();
engine.setOnLegendChange((nextLegend) => {
console.log('Visible legend entries:', nextLegend.entries.length);
});
const viewState = engine.getViewState();
engine.restoreViewState(viewState);
// Navigate hierarchical drill-down or deterministic interactive targets programmatically:
engine.drillDownTriangle(0);
engine.drillDownCluster(clusterUid);
engine.drillUp();
engine.drillToRoot();
const targets = engine.getInteractiveTargets();
Web Worker Offloading (@simplex-viz/core/worker)
Offload QAP annealing and SAT/PBD layout solving off the UI thread with automatic stale-generation cancellation (SUPERSEDED / AbortSignal), main-thread TItem reference rehydration, optional Float32Array ArrayBuffer transfers, and a pluggable solver hook ready for future Rust/WASM backends:
// worker.ts
import { attachSimplexWorkerHandler } from '@simplex-viz/core/worker';
attachSimplexWorkerHandler();
// main.ts
import {
createSimplexWorkerClient,
isSimplexWorkerCancelledError,
} from '@simplex-viz/core/worker';
const client = createSimplexWorkerClient(
() => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }),
);
try {
const { snapshot } = await client.solve(items, {
width: 1200,
height: 780,
clusteringStrategy: { kind: 'soft-simplex-tag' },
layoutStrategy: { kind: 'collision-driven' },
});
} catch (err) {
if (!isSimplexWorkerCancelledError(err)) throw err;
}
Shared Host & DOM Helpers (@simplex-viz/core/dom)
Custom browser renderers and host wrappers can reuse the exact same container, tooltip, accessibility, and pointer-interaction primitives that power @simplex-viz/svg, @simplex-viz/canvas, @simplex-viz/react, and @simplex-viz/wc:
- Container & ResizeObserver:
resolveSimplexContainer,measureSimplexContainer,ensureSimplexContainerPositioned,observeSimplexContainerResize - Reduced Motion & Webfonts:
resolveSimplexReducedMotion,subscribeSimplexReducedMotionMedia,subscribeSimplexFontLoadRelayout - Screen-Reader Live Regions & ARIA:
createSimplexSrAnnouncer,computeSimplexZoomAnnouncementSignature,formatSimplexClusterAriaMetadata,formatSimplexItemAriaMetadata,formatSimplexTriangleAriaMetadata,formatSimplexInteractiveTargetAriaLabel,formatSimplexZoomLevelAnnouncement - Tooltips & HUD Overlays:
getSimplexTooltipThemeTokens,applySimplexTooltipTheme,computeSimplexTooltipCoords,positionSimplexTooltipElement,buildSimplexTooltipContentModel,formatSimplexTooltipText,createSimplexTooltipOverlay,createSimplexZoomBreadcrumbsOverlay,createSimplexTimelineBarOverlay - Gestures, Clicks, Cursors, Keyboard & Zoom:
bindSimplexInteractiveViewport,createSimplexKeyboardNavigator,dispatchSimplexDefaultLeftClick,resolveSimplexCursorForPoint,resolveSimplexPinchDrillTarget,applySimplexPinchDrillTarget,stepSimplexDrillDownWheelPinch,normalizeSimplexMarqueeRect,isSameSimplexKeyboardTarget,toSimplexKeyboardFocusTargetRef,resolveNextSimplexKeyboardFocusIndex,isSimplexHoverEventConsumed,zoomSimplexViewportByFactor,toSimplexNormalizedPointerEvent
Low-Level Pure Math Primitives
All internal solvers are exported as pure standalone functions:
- Mesh & Affine Transforms:
buildSimplexMesh,buildSimplexLattice,buildSubdividedTriangleMesh,buildIncidentStarMesh,applyZoomAffine,invertZoomAffine,composeZoomAffine - Clustering, QAP & Discriminative Labeling:
computeSimplexClustering,embedSimilarityMatrixOnMesh,partitionTagsJaccard,embedClustersQapAnnealing,completePlanarSharedTags,matchClustersHungarian,assignDiscriminativeClusterLabels,resolveDiscriminativeClusterLabel,disambiguatePeerClusterTitle - Convex Geometry & SAT:
computeConvexHull,rectToConvexPolygon,regularPolygon,starConvexHull,isPointInTriangle,computeConvexMtv,hitTestConvexGeometry,UniformSpatialHashGrid - OKLab Perceptual Color:
hexToOklab,oklabToHex,mixOklabColors,lerpOklabHex,generatePerceptualClusterPalette,assignMeshClusterColors - Shared Preset, Timeline & Option Helpers:
SIMPLEX_PRESET_DEFAULTS,extractSimplexItemLabel,truncateSimplexBadgeTitle,resolveClusterBadgeTitle,resolveGeometricShapeSpec,resolveRankGeometricShape,getRegularPolygonRadiusScale,resolveEffectiveGeometricPolygon,getGeometricShapeVertices,measureGeometricShapeHull,NAMED_POLYGON_SIDES,getHexRelativeLuminance,resolveClusterSurfaceColors,resolveSimplexThemeBackgroundColor,hexWithAlpha,decodeSimplexDataUrlToBytes,estimateSimplexTextWidth,createSimplexTimelineNotifier,resolveTimelinePlayerConfig,createSimplexTimelineHostSession,areSimplexMeshOptionsEqual,areSimplexLayoutOptionsEqual,areSimplexTimelineOptionsEqual,normalizeTimelineLayoutScaleMode,wrapClusteringStrategyForTimeline,wrapLayoutStrategyForTimeline