# SimplexViz v1.0.0 — Full Developer & Strategy Reference Overlap-free 60-degree simplex triangulation engine for vector embeddings, pairwise similarities, and tagged collections in TypeScript, SVG, Canvas 2D, React, and Web Components. --- # [Guide] Quickstart & Three-Layer Architecture Install SimplexViz in under two minutes, understand its strict three-layer / five-package separation, and inspect every default setting. Key Takeaways: - Zero-config defaults solve 60-degree equilateral simplex layouts with guaranteed 0.0 px convex overlap. - Works identically for tagged records, single- or multi-modal vector embeddings, and pairwise similarity kernels. - Strictly decoupled across @simplex-viz/core (+ /worker & /dom), @simplex-viz/svg, @simplex-viz/canvas (2,000–10,000+ items at 60 FPS), @simplex-viz/react, and @simplex-viz/wc. SimplexViz maps high-dimensional collections onto an **adaptive 60° equilateral triangle mesh**, blends node colors in perceptual **OKLab** space, separates every convex hull to **`0.0 px` overlap**, and supports conformal **`1:4` hierarchical drill-down** plus path-independent **chronological timeline playback**. ## Choose Your Package Layer Each higher-level package re-exports core/SVG runtime primitives from lower layers—install only the single package matching your runtime, and import specialized subpaths (`@simplex-viz/core/worker`, `@simplex-viz/core/dom`, `@simplex-viz/svg/ssr`, `@simplex-viz/wc/define`) directly: | Package | Runtime & Dependencies | Primary Entry Points | | --- | --- | --- | | `@simplex-viz/react` | React 18 / 19 | ``, `useSimplexGraphController()`, `useSimplexTimeline()` | | `@simplex-viz/wc` | Plain HTML, Astro, Vue, Svelte, Angular (zero React) | ``, `defineSimplexTopicGraphElement()`, `@simplex-viz/wc/define` | | `@simplex-viz/svg` | Vanilla TS, Vue, Svelte, Angular, Node.js SSR (`@simplex-viz/svg/ssr` exclusive) | `createSimplexSvg()`, `SimplexSvgController`, `SvgRendererAdapter`, `@simplex-viz/svg/ssr` (`renderSimplexSvgString()`) | | `@simplex-viz/canvas` | High-capacity HTML5 Canvas 2D (2,000–10,000+ items, zero per-node DOM, independent of `@simplex-viz/svg`) | `createSimplexCanvas()`, `SimplexCanvasController`, `CanvasRendererAdapter`, `renderSimplexSnapshotToCanvas()` | | `@simplex-viz/core` | Browser, Node.js, Bun, Deno, Web Workers (`0` deps, DOM-free root & exclusive `@simplex-viz/core/worker` / `@simplex-viz/core/dom`) | `solveSimplexSnapshot()`, `SimplexGraphEngine`, `createSimplexTimeline()`, `@simplex-viz/core/worker`, `@simplex-viz/core/dom` | ## React Quickstart ```bash npm install @simplex-viz/react ``` ```tsx const items = [ { id: '1', label: 'Simplex Mesh', tags: ['geometry', 'triangulation', 'math'] }, { id: '2', label: 'OKLab Mixing', tags: ['color', 'geometry', 'perception'] }, { id: '3', label: 'SAT Solver', tags: ['collision', 'geometry'] }, ]; const zoom = createBarycentricZoomStrategy(); export function KnowledgeAtlas() { return (
); } ``` ## Vanilla TypeScript / Framework-Agnostic SVG ```bash npm install @simplex-viz/svg ``` ```ts const controller = createSimplexSvg('#atlas', items); ``` ## Web Component Quickstart (`@simplex-viz/wc`) ```bash npm install @simplex-viz/wc ``` ```html ``` ## High-Capacity Canvas 2D Quickstart (`@simplex-viz/canvas`) When rendering **2,000–10,000+ items** where thousands of SVG DOM elements become a bottleneck, switch to `@simplex-viz/canvas` for single-`` HiDPI rendering, world-space frustum culling, automatic `lodThresholdPx` simplification, and native `exportPng()`: ```bash npm install @simplex-viz/canvas ``` ```ts createSimplexCanvas, createSubspaceZoomStrategy, createCollisionDrivenLayoutStrategy, } from '@simplex-viz/canvas'; const controller = createSimplexCanvas('#atlas', { items: largeCorpus, preset: 'badges', theme: 'dark', layoutStrategy: createCollisionDrivenLayoutStrategy(), zoomStrategy: createSubspaceZoomStrategy(), lodThresholdPx: 3.5, tooltip: true, }); // Native zero-serialization PNG export: const pngBlob = await controller.exportPng({ scale: 2 }); ``` ## Off-Main-Thread Web Worker Quickstart (`@simplex-viz/core/worker`) Keep UI frames locked at 60 FPS during heavy QAP annealing and PBD/SAT layout solves by moving computation into a Web Worker (or Node.js `worker_threads`) via `@simplex-viz/core/worker`, then painting the solved snapshot onto Canvas 2D or SVG: ```ts // worker.ts attachSimplexWorkerHandler(); // main.ts const worker = createSimplexWorkerClient( () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }), ); const { snapshot } = await worker.solve(largeCorpus, { width: 1200, height: 760, layoutStrategy: { kind: 'collision-driven' }, }); renderSimplexSnapshotToCanvas(canvasEl, snapshot, { theme: 'dark' }); ``` ## Untagged Vector Embeddings Quickstart When passing an embedding or pairwise similarity `clusteringStrategy`, `getTags` becomes optional at both the TypeScript type level and runtime: ```tsx SimplexTopicGraph, createSoftSimplexEmbeddingClusteringStrategy, } from '@simplex-viz/react'; interface AudioSample { readonly id: string; readonly label: string; readonly timbreVec: readonly number[]; readonly prosodyVec: readonly number[]; } const audioClustering = createSoftSimplexEmbeddingClusteringStrategy({ getEmbedding: [ { name: 'Timbre', getVector: (s) => s.timbreVec, weight: 0.7 }, { name: 'Prosody', getVector: (s) => s.prosodyVec, weight: 0.3 }, ], metric: 'cosine', triangleSpread: 0.45, }); ; ``` ## Complete Default Settings Table Every pipeline stage ships with a named deterministic default strategy out of the box: | Stage / Option | Canonical Strategy | Factory & Out-of-the-Box Behavior | | --- | --- | --- | | `meshStrategy` | **Adaptive Hex Lattice** | `createAdaptiveHexMeshStrategy()` — Aspect-aligned full-canvas 60° equilateral lattice (`minSideLength: 130 px`, `maxClusters: 14`, adaptive `innerPadding: 32–48 px`). | | `clusteringStrategy` | **Jaccard Annealing Clustering** | `createJaccardAnnealingClusteringStrategy()` — Jaccard partitioning + QAP Simulated Annealing + `'planar-hitting-set'` + `'explaining-away'`. | | `colorStrategy` | **OKLab Edge Contrast** | `createOklabContrastColorStrategy()` — Greedy + swap OKLab edge contrast (`ΔE_OK`) + barycentric OKLab mixing. | | `layoutStrategy` | **Uniform PBD Layout** | `createPbdUniformLayoutStrategy()` — Mesh-inward fan seeder + space-filling PBD dispersion + global uniform scale search (`0.0 px` overlap). | | `zoomStrategy` | **Continuous Free Camera** | `createFreeCameraZoomStrategy()` — Continuous cursor wheel zoom, drag-to-pan, and 2-finger touch pinch. | | `timeline` | **Disabled (`false`)** | Opt-in `true \| TimelinePlayerOptions` — Built-in Play/Pause/Step/Scrubber HUD with `autoFinalSeed`, `autoFinalSeedLayout` (`false \| 'pinned' \| 'adaptive'`), and `emptyClusterBehavior`. | | `emptyClusterBehavior` | **Normal (`'normal'`)** | `'normal' \| 'dim' \| 'hide'` — Controls how `0`-item clusters render (e.g., future clusters during chronological playback). | | `itemFilter` / `itemFilterMode` | **`null` / `'dim'`** | Zero-relayout item filtering (`(item) => boolean`, `'dim' \| 'hide'`) dimming or hiding non-matching items while preserving exact SAT coordinates. | | `deferInitialLayout` | **Auto-Recover (`false`)** | Automatically recovers from `0×0` mounts on the first non-zero `ResizeObserver` entry (zero spring jump); set `true` or `{ fallbackTimeoutMs }` to skip provisional `960×620` solving until visible. | | `touchScrollLockPx` / `clickTolerancePx` | **`8 px` / `12 px`** | Mobile touch direction-locking (`touch-action: pan-y`; set `0` for `touch-action: none`) and peak-displacement drag-vs-click click suppression across `free-camera` and `drill-down` modes. | | `ariaLabel` / `keyboardNavigation` | **Accessible (`true`)** | WCAG 2.1 AA single-tabstop keyboard navigation (`Arrow` keys, `Home`/`End`, `Enter`/`Space`, `Shift+Enter`/`Shift+Space`, `Escape`), high-contrast double-halo SVG focus ring, semantic ARIA labels, and polite `aria-live` announcements. | | `reducedMotion` | **Auto (`'auto'`)** | `'auto' \| boolean` — Subscribes live to OS `(prefers-reduced-motion: reduce)` and snaps springs, camera flights, zoom transitions, and morphs immediately when active. | | `selectedIds` / `marqueeSelection` | **`[]` / `true`** | Independent multi-selection state supporting `Shift+Click`, `Shift+Drag` marquee overlay, keyboard selection, and high-contrast violet selection rings. | | `preset` / `theme` | **Geometric Preset (Dark)** | `'geometric'` / `'dark'` — Morphing geometric SVG content shapes (customizable via `getShape` & `shapeOptions`) + cluster anchors/badges on dark canvas. | --- # [Guide] Custom Views, Tooltips, Timeline & Headless Snapshots Customize content nodes, cluster anchors, triangle faces, mesh edges, chronological timeline playback, and headless Node.js/Worker snapshots. Key Takeaways: - Measure arbitrary React JSX cards or custom SVG glyphs automatically via offscreen getBBox() convex hull extraction. - Swap SvgTriangleView and SvgEdgeView plugins independently—internal 1:4 drillable previews automatically inherit your SvgEdgeView. - Enable chronological timeline playback with pinned full-corpus clusters, optional final-seeded item positions (pinned or adaptive), and configurable empty-cluster dimming. - Render zero-DOM SSR SVG strings via @simplex-viz/svg/ssr (ready for @resvg/resvg-js without Puppeteer), offload solving to Web Workers via @simplex-viz/core/worker, and paint 2,000–10,000+ item corpora at 60 FPS with @simplex-viz/canvas. SimplexViz separates **mathematical solving** (`@simplex-viz/core` + `@simplex-viz/core/worker`) and **shared structural DOM/interaction utilities** (`@simplex-viz/core/dom`) from **scene rendering & framework adapters** (`@simplex-viz/svg`, `@simplex-viz/canvas`, `@simplex-viz/react`, and `@simplex-viz/wc`). Every visual layer can be customized without rewriting layout or collision code. ## 1. Declarative React JSX Node Renderers In `@simplex-viz/react`, pass `renderContentNode` or `renderClusterNode` returning standard `` JSX elements centered around `(0, 0)`. The adapter measures each rendered `` offscreen via `getBBox()`, builds a `ConvexGeometry` polygon, and feeds it directly into the SAT collision solver: ```tsx ( {article.label.slice(0, 15)} )} />; ``` ## 2. Portable `SvgTriangleView` & `SvgEdgeView` Plugins Both `@simplex-viz/svg` and `@simplex-viz/react` accept reusable view classes for background triangles and lattice edges: - **Built-in Triangle Views**: `OklabTintTriangleSvgView` *(default)*, `GradientTriangleSvgView`, `BarycentricSectorTriangleSvgView`, `BlueprintInsetTriangleSvgView`, `DensityHeatmapTriangleSvgView` - **Built-in Edge Views**: `DashedMeshEdgeSvgView` *(default)*, `ClusterTintedEdgeSvgView`, `PrecisionRailEdgeSvgView`, `MinimalHighlightEdgeSvgView` Whenever `triangle.isDrillable` is `true`, `SvgRendererAdapter` automatically renders the 3 internal `1:4` midpoint edges through your active `edgeView`, keeping outer and inner triangulation visually unified. ## 3. Headless SSR SVG Rendering (`@simplex-viz/svg/ssr`) & `solveSimplexSnapshot` Need static SVG generation at build time (Astro, Next.js, Eleventy), OG/social cards, or headless PNG rasterization with `@resvg/resvg-js` without Puppeteer? Import `renderSimplexSvgString` from the dedicated zero-DOM subpath `@simplex-viz/svg/ssr`—it solves overlap-free layouts deterministically (including `'badges'` via built-in proportional/monospace font metrics or a custom `measureText` callback) or renders a pre-solved `SimplexLayoutSnapshot`: ```ts const svg = renderSimplexSvgString(records, { width: 1200, height: 720, getId: (r) => r.slug, getTags: (r) => r.topics, getLabel: (r) => r.title, preset: 'badges', theme: 'dark', padding: 24, title: 'Research Topics Atlas', }); ``` For custom HTML5 `` / WebGL renderers or raw coordinate solving inside a Web Worker, call `solveSimplexSnapshot` from `@simplex-viz/core`: ```ts const snapshot = solveSimplexSnapshot(records, { width: 1280, height: 800, getId: (r) => r.slug, getTags: (r) => r.topics, measureContentHull: (r) => rectToConvexPolygon(r.title.length * 6.5 + 16, 24, 6), }); // Zero overlaps guaranteed: console.assert(snapshot.metrics.overlapCount === 0); ``` To keep the main thread at 60 fps on large corpora (`500+` items or high-dimensional embeddings), offload QAP annealing and PBD/SAT solving via the dedicated **`@simplex-viz/core/worker`** subpath (`attachSimplexWorkerHandler` + `createSimplexWorkerClient` / `solveSimplexSnapshotAsync`). It cancels stale generations automatically during rapid resize or filter bursts, rehydrates non-cloneable domain `TItem` references on the main thread, and falls back asynchronously in SSR environments without a `Worker` global: ```ts // worker.ts attachSimplexWorkerHandler(); // main.ts const workerClient = createSimplexWorkerClient( () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }), ); const { snapshot } = await workerClient.solve(records, { width: 1280, height: 800, getId: (r) => r.slug, getTags: (r) => r.topics, layoutStrategy: { kind: 'collision-driven' }, }); ``` ### Pairing `@simplex-viz/core/worker` with High-Capacity Canvas 2D (`@simplex-viz/canvas`) For large datasets (**2,000–10,000+ items**) where SVG DOM nodes limit pan/zoom frame rate, paint the solved snapshot directly with `renderSimplexSnapshotToCanvas()` or mount a full interactive `SimplexCanvasController` (`createSimplexCanvas`) with world-space frustum culling (`cullMarginPx`), automatic sub-pixel LOD simplification (`lodThresholdPx`), custom `CanvasNodeRenderer` / `CanvasTriangleRenderer` / `CanvasEdgeRenderer` hooks, and native `exportPng()`: ```ts createSimplexCanvas, renderSimplexSnapshotToCanvas, } from '@simplex-viz/canvas'; // Option A — Stateless one-shot render of a Worker snapshot: renderSimplexSnapshotToCanvas(canvasEl, snapshot, { theme: 'dark', preset: 'badges', lodThresholdPx: 3.5, }); // Option B — Full interactive 60 FPS Canvas controller (1:4 drill-down, timeline, marquee, WCAG keys): const controller = createSimplexCanvas('#atlas', { items: records, preset: 'badges', theme: 'dark', lodThresholdPx: 3.5, cullMarginPx: 48, tooltip: true, }); ``` ## 4. Composable Interactions, Tooltips, Mobile Touch-Scroll & Zero-Size Mount Recovery Every interaction handler across `@simplex-viz/core`, `@simplex-viz/svg`, `@simplex-viz/canvas`, `@simplex-viz/react`, and `@simplex-viz/wc` (`onContentClick`, `onClusterClick`, `onTriangleClick`, `onBackgroundClick`, `onLeftClick`, `onRightClick`, `onContentHover`, `onClusterHover`, `onTriangleHover`, and custom `onWheel`) follows one uniform contract powered by `@simplex-viz/core/dom`: - Return `void` or `false` to **compose** with built-in behavior (drill-down navigation, focus toggles, hover tooltips, or cursor zoom). - Return `true` to **consume** the event and suppress the built-in default for that interaction. Across browser packages (`@simplex-viz/svg`, `@simplex-viz/canvas`, `@simplex-viz/react`, and `@simplex-viz/wc`), shared `@simplex-viz/core/dom` primitives handle four common browser behaviors uniformly: - **Viewport Edge-Flipped Tooltips (`computeSimplexTooltipCoords`, `buildSimplexTooltipContentModel`)**: Built-in DOM and React JSX tooltips share the same target model, tag/weight formatting, drill-down hints, and dynamic viewport edge-flipping so tooltips never clip past container edges. - **Mobile Touch-Scroll Direction-Locking (`touchScrollLockPx`, default `8`)**: Sets `touch-action: pan-y` on the graph surface so vertical single-finger swipes yield smoothly to native page scrolling while horizontal swipes and two-finger pinches lock onto the canvas. Pass `touchScrollLockPx={0}` to restore `touch-action: none` for full 2D touch panning. - **Drag-vs-Click Peak-Displacement Tolerance (`clickTolerancePx`, default `12`)**: Tracks peak pointer displacement from `pointerdown` across the entire gesture and suppresses trailing clicks whenever movement exceeds `clickTolerancePx`—in both `free-camera` and `drill-down` modes. - **Zero-Size (`0×0`) Container Mounts & Webfont Auto-Relayout (`deferInitialLayout`, `relayoutOnFontLoad`)**: If a graph mounts inside a hidden tab, modal, or before async CSS applies, controllers automatically invalidate cached hulls and perform a clean `'initial'` viewport re-initialization (with zero spring jump) on the first non-zero `ResizeObserver` entry via `observeSimplexContainerResize()`. Pass `deferInitialLayout` (`true` or `{ fallbackTimeoutMs }`) to skip the provisional `960×620` solve entirely until the container becomes visible. Once webfonts finish loading (`document.fonts.ready` / `loadingdone`), `relayoutOnFontLoad: true` automatically re-measures hulls and re-solves layout. ## 5. Tag Display Labels, Cluster Badge Options & Geometric Shape Styling (`getShape`, `shapeOptions`) You can tailor built-in presets to match your host design system without writing a custom `VisualResolver` or `SvgNodeView`: - **Decoupled Tag Display Labels (`formatTagLabel`)**: Pass `formatTagLabel: (tag) => displayName` to keep canonical slugs (e.g. `'autonomous-driving'`) strictly for clustering/matching while rendering human-readable labels (`'Autonomous Driving'`) in cluster badges, breadcrumbs, semantic zoom subclusters, and tooltips. - **Cluster Badge Formatting (`badgeOptions`)**: Hide internal `T1`/`T2` prefix codes (`showCode: false`), apply word-aware truncation (`maxTitleChars: 18`), or transform titles (`formatTitle: (title, { variant, cluster }) => ...`)—or pass the same options directly to `new BadgeClusterSvgView(options)`. - **Category-Driven & N-gon Shapes (`getShape`)**: Bind items to fixed or data-driven shapes (`'circle'`, `'triangle'`, `'square'`, `'diamond'`, `'pentagon'`, `'hexagon'`, `'heptagon'`, `'octagon'`, `'star'`, an arbitrary side count `>= 3`, or `{ sides, rotationRad }`) so shapes stay invariant across hierarchical `1:4` drill-down levels with exact convex SAT hulls. - **Lightweight Hover, Dimming & Stroke Hooks (`shapeOptions`)**: Customize `GeometricShapeSvgView` with `{ hoverScale, hoverRingColor, dimmedOpacity, strokeColor, strokeWidth }` (or call `controller.setShapeOptions(...)` at runtime). `hoverScale` scales the outer `` on hover without altering collision hulls, `dimmedOpacity` replaces the default `0.34` dimming factor once with zero double-dimming, and `strokeWidth` is automatically factored into `measureConvexHull()` so wider strokes remain strictly overlap-free. ```tsx TOPIC_LABELS[slug] ?? slug} badgeOptions={{ showCode: false, maxTitleChars: 18 }} getShape={(pub) => (pub.kind === 'paper' ? 'hexagon' : pub.kind === 'talk' ? 'triangle' : 'pentagon')} shapeOptions={{ hoverScale: 1.38, hoverRingColor: '#38bdf8', dimmedOpacity: 0.18, strokeColor: '#0f172a', strokeWidth: 1.8, }} deferInitialLayout tooltip /> ``` ## 6. Chronological Timeline Playback, Final-Seeded Layout & Empty-Cluster Dimming Turn any timestamped or bucketed dataset into an interactive chronological replay (`0 → N`) using the built-in `timeline` option in `@simplex-viz/svg` and `@simplex-viz/react`—or drive custom UI headlessly via `createSimplexTimeline()` (`@simplex-viz/core`) and `useSimplexTimeline()` (`@simplex-viz/react`): ```tsx SimplexTopicGraph, useSimplexGraphController, useSimplexTimeline, } from '@simplex-viz/react'; export function PublicationTimeline({ publications }: { publications: readonly Publication[] }) { const { controllerRef } = useSimplexGraphController(); const timeline = useSimplexTimeline(controllerRef); return ( p.year, // numeric year, Date, ISO string, or custom getFrameKey stepIntervalMs: 850, // playback interval per step (ms) showControls: true, // built-in theme-adaptive Play/Pause/Step/Scrubber HUD position: 'bottom', // 'bottom' | 'top' loop: false, // optionally loop back to frame 0 after end includeEmptyStart: false, // optionally prepend an empty frame 0 autoFinalSeed: true, // wraps clustering in createFinalSeededClusteringStrategy autoFinalSeedLayout: 'adaptive', // false | 'pinned' | 'adaptive' (createFinalSeededLayoutStrategy) emptyClusterBehavior: 'dim', // 'normal' | 'dim' | 'hide' for 0-item future clusters }} onTimelineStateChange={(state) => { console.log(state.activeLabel, state.activeItemCount, timeline.isReady); }} /> ); } ``` ### Independent Control Over All Three Timeline Axes 1. **Cluster Stability (`autoFinalSeed` / `createFinalSeededClusteringStrategy`)**: Enabled by default (`autoFinalSeed: true`), wrapping your active clustering strategy so canonical full-corpus clusters, mesh vertices, UIDs, and OKLab hues stay pinned across frames `0..N`. Set `autoFinalSeed: false` to let clusters re-form dynamically at each chronological step, or wrap manually via `createFinalSeededClusteringStrategy(base, { seedItems })`. 2. **Item Position & Scale Stability (`autoFinalSeedLayout` / `createFinalSeededLayoutStrategy`)**: - `false` *(default)* — Re-solves layout dynamically on every frame using your active `layoutStrategy` (for example, `createWarmStartPbdLayoutStrategy()` or `createCollisionDrivenLayoutStrategy()`). - `'pinned'` — Wraps your active layout strategy in `createFinalSeededLayoutStrategy(base, { scaleMode: 'pinned' })` so items stay locked to their canonical full-corpus `(x, y)` coordinates and final scales with zero drift. - `'adaptive'` — Keeps canonical `(x, y)` coordinates pinned while symmetrically expanding sparse early-frame items up to `1.0x` with exact SAT `0.0 px` overlap verification. 3. **Empty / Future Cluster Visibility (`emptyClusterBehavior`)**: Available both inside `timeline` and directly as a top-level prop/method (`emptyClusterBehavior` / `setEmptyClusterBehavior()`): - `'normal'` *(default)* — All pinned clusters render at full opacity even before their first member item enters. - `'dim'` — Clusters with `0` active members stay visible as dimmed landmarks until their first item arrives. - `'hide'` — Clusters with `0` active members are hidden until activated by an incoming item. Because `estimateClusterCount(ctx)` and `ClusteringStrategyContext` receive explicit `reason` (`'initial' | 'items' | 'viewport' | 'mesh' | 'strategy'`) and viewport dimensions, resizing the canvas cleanly re-seeds both final-seeded clustering and final-seeded layout against the canonical full corpus. ### Cookbook: Binding an External Host Timeline Bar (`showControls: false`) When your application already provides a site-wide scrubber or Play/Pause bar, pass `showControls: false` and `formatStepLabel` to disable the built-in HUD while letting `SimplexSvgController` (or ``) manage canonical cluster seeding, item slicing, and `rAF` playback for you: ```ts const controller = createSimplexSvg('#atlas', { items: publications, timeline: { showControls: false, getTimestamp: (p) => p.year, formatStepLabel: (frame) => `${frame.timestamp} (${frame.cumulativeItems.length} items)`, autoFinalSeed: true, emptyClusterBehavior: 'dim', }, }); // 1. Sync your existing HTML / Preact / React scrubber directly from controller state: const unsubscribe = controller.subscribeTimeline((state) => { if (!state) return; scrubber.max = String(state.totalSteps); scrubber.value = String(state.step); labelEl.textContent = state.activeLabel; playBtn.textContent = state.playing ? 'Pause' : 'Play'; }); // 2. Drive playback without writing a manual setItems() slicing adapter: playBtn.onclick = () => (controller.timeline?.getState().playing ? controller.timeline.pause() : controller.timeline?.play()); prevBtn.onclick = () => controller.timeline?.stepBy(-1); nextBtn.onclick = () => controller.timeline?.stepBy(1); resetBtn.onclick = () => controller.timeline?.resetToEnd(); scrubber.oninput = () => controller.timeline?.seek(Number(scrubber.value)); ``` The exact same binding works on `` (`el.subscribeTimeline(...)` + `el.getTimeline()`) and in React via `useSimplexTimeline(controllerRef)` or `handle.subscribeTimeline(...)`. ## 7. Zero-Relayout Item Filtering, Batched Updates & WCAG 2.1 AA Accessibility Three production ergonomics features keep interactive dashboards responsive, deterministic, and accessible out of the box: - **Zero-Relayout Item Filtering (`itemFilter`, `itemFilterMode`, `setItemFilter()`)**: Filter content items visually in `'dim'` (default) or `'hide'` mode without re-clustering or re-solving the SAT layout. Every node preserves its exact `(x, y)` coordinate so toggling search queries or facet filters produces zero spring jumps. In `'hide'` mode, filtered-out items are non-interactive (`pointer-events: none`) and automatically excluded from both pointer hit-testing and keyboard navigation. - **Re-entrant `batch()` & Atomic `setOptions()`**: Wrap multiple imperative updates inside `engine.batch(fn)` or `controller.batch(fn)`, or pass a partial update object to `controller.setOptions(opts)` (`SimplexSvgUpdateOptions`), to coalesce changes (such as `theme`, `preset`, `meshOptions`, `layoutOptions`, `itemFilter`, and strategies) into a single minimal pipeline recomputation. In `@simplex-viz/react`, `` automatically batches all dynamic prop changes per render commit inside one `controller.batch(...)` pass. - **WCAG 2.1 AA Keyboard Navigation & Screen-Reader Support (`ariaLabel`, `keyboardNavigation`)**: Enabled by default (`keyboardNavigation: true`), the root `` exposes a single tabstop (`role="application"`, `tabindex="0"`, `aria-activedescendant`) with full keyboard traversal (`ArrowRight`/`ArrowDown` next, `ArrowLeft`/`ArrowUp` previous, `Home`/`End` first/last, `Enter`/`Space` activate/drill/focus, `Escape` clear focus or drill up), a zoom- and theme-adaptive high-contrast double-halo SVG focus ring (`g.sv-a11y-focus-ring`), collision-free instance-scoped ARIA IDs and roles on clusters/items/triangles/breadcrumbs, and polite screen-reader announcements (`div.sv-sr-announcer[role="status"][aria-live="polite"]`). ```tsx p.year >= minYear} itemFilterMode="dim" ariaLabel="Interactive research publications topic map" keyboardNavigation tooltip /> ``` ## 8. Linked-View Search, Programmatic Focus/Zoom & Client-Side SVG/PNG Export Synchronize external search boxes, tables, or detail panels with the graph without mutating dataset layout, and export publication-grade SVG or HiDPI PNG snapshots directly from the live canvas: - **Programmatic Search & Linked-View API (`setHighlightedIds`, `focusItem`, `zoomToItem`)**: Pass any `Iterable | null` to `setHighlightedIds()` (or the React `highlightedIds` prop) to emphasize matching items. Call `focusItem(itemId, { highlight?, hover?, announce? })` to focus a node with synchronized hover tooltip, SVG focus ring, and polite screen-reader announcement. Call `zoomToItem(itemId, { zoom?, maxDrillSteps?, focus? })` to smoothly frame an item in `free-camera` mode or automatically drill down across covering triangles in `drill-down` mode. - **Client-Side Snapshot Export (`exportSvg`, `exportPng`)**: `exportSvg(options?)` clones the live SVG, inlines resolved CSS custom properties and visual styles (`inlineStyles: true`), injects a theme-matched or custom background `` (`includeBackground: true`), expands `viewBox` by `padding`, strips transient focus rings by default (`includeFocusRing: false`), and returns a standalone `` string. `exportPng(options?)` rasterizes that SVG on an offscreen HiDPI `` (`scale: 2` default) and resolves to a `Blob` (`format: 'blob'`, default) or base64 `data:` URL (`format: 'dataUrl'`). ```ts // From a search bar, table row click, or export button: handle.setHighlightedIds(searchResultIds); handle.zoomToItem(selectedId, { zoom: 2.2, maxDrillSteps: 4 }); const svgString = handle.exportSvg({ padding: 24, title: 'Publications Atlas' }); const pngBlob = await handle.exportPng({ scale: 2, padding: 24 }); ``` ## 9. Multi-Selection (`Shift+Click` / `Shift+Drag`), Reduced Motion & Deep-Link View State Build analytical workflows and shareable URLs without custom interaction plumbing: - **Interactive Multi-Selection (`selectedIds`, `marqueeSelection`, `onSelectionChange`)**: Independent from `highlightedIds` and `pinnedIds`. Users can `Shift+Click` items to toggle selection, `Shift+Drag` to select rectangular regions with a marquee overlay (automatically excluded from `exportSvg()`), toggle selection via keyboard (`Shift+Enter`/`Shift+Space`), or press `Escape` to clear. Built-in node views and `@simplex-viz/svg/ssr` render high-contrast violet selection rings. - **Automatic `prefers-reduced-motion` (`reducedMotion: 'auto' | boolean`)**: Subscribes live to `(prefers-reduced-motion: reduce)`, sets `data-reduced-motion="true"`, and snaps node springs, camera flights, zoom transitions, and visual morphs immediately when active. - **Serializable View State (`getViewState`, `restoreViewState`)**: Captures a JSON-safe `SimplexViewState` (`version: 1`, `camera`, `zoomPath`, cluster/triangle/item focus, `highlightedIds`, `selectedIds`, `pinnedIds`, and optional `timelineStep`). `restoreViewState()` snaps immediately by default (`{ animate?: boolean }`), replays drill-down steps cleanly from root, and gracefully ignores stale IDs or unreachable steps without throwing. ```ts // Deep-link serialization into URL hash / query params or localStorage: const viewState = handle.getViewState(); const encoded = encodeURIComponent(JSON.stringify(viewState)); // Restore on page load (snaps immediately, ignores stale IDs safely): handle.restoreViewState(JSON.parse(decodeURIComponent(encoded))); ``` --- # [Guide] 01. Mesh Triangulation Strategies How SimplexViz constructs toothed 60-degree equilateral triangle lattices, selects orientation and parity, and pins fixed grids. Key Takeaways: - Every triangle in SimplexViz is a true 60-degree equilateral simplex (height h = s * sqrt(3) / 2), ensuring isotropic barycentric distances. - createAdaptiveHexMeshStrategy chooses horizontal vs. vertical orientation and row parity automatically from viewport aspect ratio. - createFixedLatticeMeshStrategy locks an exact (cols × rows) vertex count K across resizes. Stage 1 (`SimplexMeshStrategy`) establishes the **planar 2-complex** of vertices, edges, and equilateral triangles before any items or clusters are placed. Because every face is an exact **60° equilateral triangle**, barycentric weights `(w_A, w_B, w_C)` translate linearly into Euclidean proximity without aspect-ratio distortion. ## Strategy Decision Matrix ## Geometric Mechanics of the Adaptive Hex Lattice Given viewport dimensions `(W, H)` and `MeshOptions` (`innerPadding`, `minSideLength`, `maxSideLength`, `maxClusters`), `buildSimplexMesh`: 1. Computes the target cluster budget `K ∈ [3, maxClusters]` (`maxClusters = 14` by default) from corpus richness or explicit `clusterCount`, and resolves an adaptive outer margin (`32 px` on compact mobile screens up to `48 px` on desktop) when `innerPadding` is omitted. 2. Enumerates candidate staggered hexagonal grids `(rows, cols, orientation, wideFirst)` where alternating rows offset by `s / 2` along the primary axis and step by `h = s · √3 / 2` along the perpendicular axis. 3. Scores viable candidates (`s ≥ minSideLength`, `130 px` by default) by **viewport area efficiency**, **aspect-ratio alignment** (automatically rotating into landscape on wide monitors and portrait on mobile screens), and **cluster richness**, applying `maxSideLength` purely as an optional upper cap when specified. ## Explicit Triangle Side Length Override Both built-in mesh strategies honor `sideLength` when you want deterministic world-space spacing regardless of monitor size: ```ts createAdaptiveHexMeshStrategy, createFixedLatticeMeshStrategy, } from '@simplex-viz/core'; // Adaptive topology with exact 210 px equilateral edges: const adaptive = createAdaptiveHexMeshStrategy({ innerPadding: 48, sideLength: 210, maxClusters: 10, }); // Fixed 4×3 lattice (K = 12 vertices) with 195 px edges: const fixed = createFixedLatticeMeshStrategy({ cols: 4, rows: 3, orientation: 'horizontal', wideFirst: true, sideLength: 195, }); ``` --- # [Guide] 02. Clustering & Planar Simplex Projection Deep dive into Soft-Simplex interior spreading, Jaccard QAP annealing, multi-modal embeddings, NNLS barycentric projection, and PAM k-Medoids. Key Takeaways: - SimplexClusteringStrategy decouples data representation cleanly: tag strategies set requiresTags: true, while embedding and similarity strategies set requiresTags: false. - Quadratic Assignment Problem (QAP) simulated annealing places related clusters on adjacent mesh vertices so shared items land on planar edges and triangles. - Soft-Simplex strategies distribute multi-cluster items smoothly across triangle interiors while leaving single-cluster items free in a 360-degree halo. Stage 2 (`SimplexClusteringStrategy`) solves three coupled mathematical problems: 1. **Partitioning**: Grouping domain items into `K` coherent topic clusters or medoids/centroids. 2. **Planar Mesh Embedding (QAP)**: Assigning those `K` clusters to the `K` vertices of the 60° simplex mesh so pairwise cluster affinity aligns with 1-hop mesh adjacency (preserving identities across updates via the **Hungarian algorithm**). 3. **Barycentric Simplex Anchoring**: Mapping every item onto its covering vertex (`1`-simplex), shared edge (`2`-simplex), or triangle face (`3`-simplex) with normalized weights `∑ w_i = 1`. ## Strategy Decision Matrix ## Parameter Effect: `triangleSpread` (`0.00` vs. `0.45` vs. `0.90`) Raising `triangleSpread` smoothly distributes multi-cluster items across the covering 2-simplex triangle interior while keeping single-cluster items unconstrained in an outer `360°` vertex halo: ## Tag Rules: Planar Hitting-Set & Explaining-Away In tagged collections, two subtle edge cases arise when projecting hypergraph tag overlaps onto a 2D planar triangulation: - **`sharedTagRule: 'planar-hitting-set'` *(Default)***: If a bridge tag co-occurs across clusters that cannot all touch on a planar graph, a weighted hitting-set pass promotes minimal bridge coverage onto shared mesh edges so cross-cutting items remain geometrically faithfully tethered. - **`anchorRule: 'explaining-away'` *(Default)***: Ranks incident clusters by specificity and prunes redundant secondary matches once an item's tags are explained, preventing generic tags from dragging every node toward the canvas center. ## Closed-Form Planar NNLS Projection for Embeddings For untagged vector embeddings `x ∈ ℝ^d`, `createEmbeddingClusteringStrategy` evaluates every candidate vertex, mesh edge, and mesh triangle `τ = (c₁, c₂, c₃)` and solves the exact constrained least-squares projection onto the 2-simplex `Δ²`: ```text minimize || x − (w₁·μ₁ + w₂·μ₂ + w₃·μ₃) ||₂² subject to w₁, w₂, w₃ ≥ 0 and w₁ + w₂ + w₃ = 1 ``` Selecting the planar simplex `τ*` with minimal reconstruction residual guarantees that every embedded item lands inside a true planar mesh triangle rather than across non-adjacent clusters. ## Base-Rate-Aware Discriminative Cluster Labeling (`features` & `peerClusters`) When clustering untagged embeddings or pairwise similarity kernels, naively naming each cluster after its most frequent category often produces duplicate badges whenever a single class dominates the corpus (for example, `77%` of classic feature films carrying `"Drama"` as a primary genre, or two penguin clusters sharing the same species). SimplexViz solves this directly inside Stage 2 and exposes the underlying primitives for custom `deriveClusterMeta` callbacks: 1. **Built-In `features` Option on Embedding & Similarity Strategies**: Passing `features: SubspaceZoomFeature[]` to `createSoftSimplexEmbeddingClusteringStrategy`, `createEmbeddingClusteringStrategy`, or `createSimilarityClusteringStrategy` invokes `assignDiscriminativeClusterLabels` across all `K` sibling clusters—scoring numeric features by standardized z-score separation (`|z_k|`), boolean/categorical facets by specificity lift above corpus base rates, and shared taxonomic groups by intra-group secondary contrast (such as *Adélie · Male* vs. *Adélie · Female*). 2. **Sibling Context in `deriveClusterMeta`**: Every `ClusterDerivationContext` receives `allItems` and `peerClusters: readonly PeerClusterContext[]`, enabling custom domain meta builders to call `resolveDiscriminativeClusterLabel(ctx, { features })` or `disambiguatePeerClusterTitle(ctx, getBaseTitle, getQualifier)` with guaranteed pairwise uniqueness across the mesh. ## Path-Independent Chronological Pinning (`createFinalSeededClusteringStrategy`) When stepping chronologically (`0 → N`) through a growing corpus or applying interactive filters, running a clustering strategy from scratch on early sparse frames can cause clusters to jump vertices or rename themselves from frame to frame. Wrap any Stage 2 strategy—tag, embedding, similarity, or custom—with `createFinalSeededClusteringStrategy`: ```ts createFinalSeededClusteringStrategy, createSoftSimplexEmbeddingClusteringStrategy, } from '@simplex-viz/core'; const pinnedClustering = createFinalSeededClusteringStrategy( createSoftSimplexEmbeddingClusteringStrategy({ getEmbedding: (d) => d.vec }), { seedItems: fullCorpus }, ); ``` - Computes and pins the canonical full-corpus clusters, vertex assignments, UIDs, and OKLab colors once on initialization (or re-seeds cleanly whenever the viewport/mesh changes cluster count `K`). - Projects every chronological or filtered subset onto those pinned anchors with **zero cluster hopping** and path-independent parity at the final frame. - Enabled automatically whenever `timeline` is active with `autoFinalSeed: true` (the default). To disable automatic pinning and let clusters re-form dynamically at every timeline step, pass `timeline={{ ..., autoFinalSeed: false }}`. --- # [Guide] 03. Perceptual OKLab Color Strategies Why SimplexViz assigns cluster hues via perceptual OKLab graph-coloring optimization and mixes multi-cluster items without muddy sRGB midpoints. Key Takeaways: - Adjacent mesh vertices maximize minimum perceptual distance ΔE_OK via greedy seeding plus pairwise swap refinement. - Barycentric item colors interpolate in Björn Ottosson's OKLab space with chroma preservation so bridge items stay vivid and legible. - Hungarian cluster matching preserves assigned vertex colors across live item additions, removals, and resizes. Stage 3 (`SimplexColorStrategy`) assigns a canonical hex color to each vertex cluster and computes `mixedColorHex` for every content item from its barycentric simplex weights `(w₁, …, w_m)`. ## Why sRGB Fails on Triangulated Meshes Linearly averaging sRGB hex values along a mesh edge—for instance between Cyan (`#06B6D4`) and Amber (`#F59E0B`)—collapses perceptual lightness and chroma near `w = (0.5, 0.5)`, turning bridge items into dull grey-brown dots that look visually *inactive* rather than *interdisciplinary*. SimplexViz converts cluster colors into **OKLab** `(L, a, b)`, computes the weighted barycentric sum, gently restores perceptual chroma `C = √(a² + b²)` toward the weighted mean chroma of the contributing clusters, and clamps cleanly into the sRGB gamut. ## Strategy Decision Matrix ## Custom Brand Palette Example ```ts const corporatePalette = createPaletteColorStrategy( ['#0891b2', '#d97706', '#c026d3', '#059669', '#2563eb', '#e11d48'], { mode: 'edge-contrast', preserveMatchedColors: true, }, ); ``` --- # [Guide] 04. Composable Collision Layout (Seeder × Relaxer × ScaleController) How SimplexViz guarantees 0.0 px overlap across arbitrary convex shapes and JSX cards by composing Seeders, Position Relaxers, and Scale Controllers. Key Takeaways: - Every built-in layout strategy strictly enforces two hard invariants: covering-triangle containment and 0.0 px convex SAT overlap. - Layout pipelines decompose orthogonally into LayoutSeeder × PositionRelaxer × ScaleController. - Collision-Driven Local Scaling keeps sparse neighborhoods at full 1.0x size and shrinks only locally colliding pockets. Stage 4 (`SimplexLayoutStrategy`) transforms abstract barycentric weights into exact 2D world coordinates `(x, y)` and per-node scale factors (`clusterScale`, `itemScales`) for arbitrary `ConvexGeometry` hulls (circles, regular polygons, star hulls, or measured React/SVG bounding boxes). ## Built-In Layout Strategies ## Orthogonal Building Blocks (`createComposedLayoutStrategy`) Instead of monolithic layout algorithms, SimplexViz factors layout solving into three composable interfaces: ### 1. `LayoutSeeder` (Initial Placement) - `createPhyllotaxisSeeder()` — Places co-located items on a golden-angle Vogel spiral (`θ_n = n · 137.508°`) around their barycentric target. - `createMeshInwardFanSeeder()` — Fans vertex-anchored items smoothly toward incident mesh sectors to maximize initial clearance before relaxation. - `withWarmStartSeeder(seeder)` — Reuses settled coordinates from the previous frame for existing item IDs so live mutations settle with minimal visual displacement. ### 2. `PositionRelaxer` (Iterative PBD + SAT/MTV Separation) - `createBarycentricPbdRelaxer()` — Couples a gentle spring toward each item's exact barycentric target with Separating Axis Theorem (SAT) Minimum Translation Vector (MTV) impulses accelerated by `UniformSpatialHashGrid`. - `createSpaceFillingPbdRelaxer()` — Adds short-range electrostatic-style dispersion inside covering triangles so nodes utilize open triangle interiors evenly. ### 3. `ScaleController` (Adaptive Node Sizing) - `createUniformScaleController()` — Binary-searches a single global `α ∈ [minContentScale, 1]`; ideal when node radius encodes a quantitative metric (e.g. citations or duration) whose global ratio must stay exact. - `createCollisionLocalScaleController()` — Starts every item at `1.0x` and iteratively multiplies only actively colliding pairs by `shrinkFactor` (`0.85` default, bounded by `minLocalScale`). Pairs naturally with hierarchical `1:4` drill-down! - `createDensityPriorScaleController()` — Runs a `1.0x` space-filling dispersion pass first, evaluates smooth radial crowd density within `crowdRadiusPx` (`76 px`) on the dispersed positions, and resolves any residual collisions locally with halo blending. - `createFixedScaleController({ scale: 1.0 })` — Locks node scale at a constant factor without auto-shrinking. ## Preset & Custom Composition Example ```ts createComposedLayoutStrategy, createMeshInwardFanSeeder, createSpaceFillingPbdRelaxer, createCollisionLocalScaleController, } from '@simplex-viz/core'; const customLayout = createComposedLayoutStrategy({ seeder: createMeshInwardFanSeeder(), relaxer: createSpaceFillingPbdRelaxer({ springFactor: 0.7, dispersionGapPx: 18, }), scaleController: createCollisionLocalScaleController({ minLocalScale: 0.32, shrinkFactor: 0.85, }), warmStart: true, }); ``` ## Chronological Layout Stability (`createFinalSeededLayoutStrategy`) Just as `createFinalSeededClusteringStrategy` pins cluster vertices across chronological timeline frames (`0 → N`), `createFinalSeededLayoutStrategy` wraps any Stage 4 layout strategy to solve canonical full-corpus `(x, y)` coordinates once (when `canonicalSeedItems` are provided) and reuse them path-independently across subsets: ```ts createFinalSeededLayoutStrategy, createCollisionDrivenLayoutStrategy, } from '@simplex-viz/core'; const chronologicalLayout = createFinalSeededLayoutStrategy( createCollisionDrivenLayoutStrategy(), { scaleMode: 'adaptive', // 'pinned' | 'adaptive' unseenItemPolicy: 'fallback', // 'fallback' | 'reseed' }, ); ``` - **`scaleMode: 'pinned'` *(Default)***: Freezes both the canonical `(x, y)` positions and the final full-corpus item scales. Earlier items never slide, shrink, or jump as later items enter—making frame `N` strictly identical whether reached by stepping forward, scrubbing backward, or jumping directly to the end. - **`scaleMode: 'adaptive'`**: Keeps every item anchored at its exact canonical `(x, y)` position, while expanding sparse early-frame items symmetrically up to `1.0x` via exact SAT convex clearance checks (`0.0 px` overlap guaranteed) so early frames stay readable without sacrificing spatial landmarks. - **`unseenItemPolicy`**: Controls what happens if a live mutation introduces an item ID absent from the canonical seed (`'fallback'` delegates to the wrapped base strategy for that frame; `'reseed'` updates the canonical seed automatically). - **One-line Timeline Integration**: In `@simplex-viz/svg` and `@simplex-viz/react`, setting `timeline={{ ..., autoFinalSeedLayout: 'adaptive' }}` (or `'pinned'`) automatically wraps your active `layoutStrategy` and feeds the full timeline corpus via `canonicalSeedItems`. --- # [Guide] 05. Conformal 1:4 Zoom & Hierarchical Drill-Down Mathematical and UX design of SimplexViz's conformal 1:4 triangle subdivision, Adaptive Contrast Stretch, 3→6 semantic tag splitting, and 1-ring cluster stars. Key Takeaways: - Conformal 1:4 subdivision splits any equilateral triangle along its 3 edge midpoints into 3 corner triangles matching parent orientation plus 1 inverted center triangle. - Drillable triangles render their internal 1:4 subdivision edges directly in the active mesh edge style and pass clicks through content nodes until leaf scale (1.0x) is reached. - Non-subdividable leaf triangles in multi-triangle meshes remain focusable via their free triangle face ('triangle-focus'), scaling that single un-subdivided triangle to fill the viewport while keeping content nodes directly clickable. Stage 5 (`SimplexZoomStrategy`) governs how users navigate dense regions of the simplex atlas—either via a **continuous 2D camera** (`mode: 'free-camera'`) or via **discrete, structure-preserving hierarchical drill-down** (`mode: 'drill-down'`). ## Strategy Decision Matrix ## Side-by-Side Comparison: How Each 1:4 Drill-Down Strategy Refines a Triangle Clicking the same crowded `(Physics, Math, CS)` parent triangle behaves distinctly depending on whether you want pure geometric magnification, secondary tag promotion, or variance-driven subspace re-clustering: ## Key UX & Geometric Mechanics in `drill-down` Mode 1. **Local Subspace Variance Projection**: When using `createSubspaceZoomStrategy`, attributes that defined the parent cluster (such as `milk = true` inside *Mammals*) have zero intra-subset variance and vanish automatically, letting secondary domain attributes, continuous embeddings, or similarity landmarks separate the zoomed subset cleanly across the `6` sub-vertices. 2. **3-Tier Spatial Orientation & Collision-Free Sub-Vertex Badges**: Every zoomed `1:4` frame preserves spatial orientation via three coordinated cues: (a) **two-line corner plaques** (`parentContextLabel` above `subclusterLabel`) whenever an outer corner is locally refined—while unchanged outer corners remain clean single-line primary capsules without `PARENT / Parent` stutter; (b) **explicit `A ↔ B` midpoint bridge plaques** (chamfered hexagonal geometry distinguishing `role: 'intermediate'` from primary capsules) with canonical uniqueness across all `6` sub-vertices; and (c) **color-pip breadcrumb trails** (`ZoomBreadcrumbSegment[]`) displaying the active parent triangle's three corner hues. 3. **Direct Internal `1:4` Subdivision Preview**: Any triangle with `isDrillable === true` renders its 3 internal midpoint-to-midpoint edges using your active `SvgEdgeView` (`DashedMeshEdgeSvgView`, `SolidMeshEdgeSvgView`, or custom), signaling subdivision affordance at a glance. 4. **Content Pass-Through vs. Single-Triangle Leaf Focus**: When `stopWhenFullScale: true` (default), triangles stop `1:4` subdividing as soon as all covered items reach `fullScaleThreshold` (`0.75`, exported as `DEFAULT_FULL_SCALE_THRESHOLD`). While a triangle is still `1:4` drillable, content nodes inside it set `isPassThrough: true` so clicking anywhere inside triggers `1:4` subdivision. Once leaf scale is reached (`leafTriangleFocus: true`, default), content nodes inside the leaf triangle become directly clickable, while clicking the **free triangle face** focuses that single un-subdivided triangle (`kind: 'triangle-focus'`) across the viewport—and clicking its free face again toggles back out (`drillUp`). 5. **Uniform 1-Ring Cluster & Subcluster Focus with Simplex-Distance Dimming**: In `'incident-star'` mode (default), every cluster and subcluster badge—at any zoom depth, including `1.0×` leaf triangles and sparse corners—behaves identically: clicking it focuses its lattice-conformal 1-ring star of incident triangles and dims active items by barycentric simplex distance `d = 1 − w̃₀ ∈ [0, 1]` (`opacity = 0.32 + 0.68 · w̃₀`). Clicking a rim neighbor cluster inside an active star (or any of the 3 corners of a `'triangle-focus'` frame) switches laterally at the same breadcrumb depth to its full 1-ring star, while clicking the focused center cluster again toggles cleanly back up one level (`drillUp`). 6. **Dimmed Neighborhood Context & Lateral Switching**: Surrounding triangles and clusters are projected around the focused sub-mesh via `ZoomAffineTransform` at reduced opacity without node hover distraction. Clicking any adjacent dimmed neighbor triangle switches laterally at the same zoom depth—subdividing `1:4` when dense or focusing as a single un-subdivided `'triangle-focus'` when already at leaf scale. --- # [Strategy] Adaptive Hex Lattice (Stage 01: Mesh Triangulation) Factory: `createAdaptiveHexMeshStrategy(overrideOptions?: MeshOptions): SimplexMeshStrategy` Chooses orientation and staggered 60° row parity automatically to maximize triangle side length. When to Use: - Default choice for responsive browser atlases and varying collection sizes. - Automatically adapts lattice orientation (horizontal vs. vertical) and row parity to viewport aspect ratio. - Pairs with any tag, embedding, or similarity clustering strategy. ## How Adaptive Hex Lattice Works **Adaptive Hex Lattice** evaluates candidate staggered hexagonal grids `(rows, cols, orientation, wideFirst)` for the active cluster budget `K` (informed by `clusteringStrategy.estimateClusterCount` or tag diversity, clamped to `[3, maxClusters]`). Every face in the generated mesh is an exact **60° equilateral triangle** with height `h = s · √3 / 2`. Evaluating both horizontal and vertical primary axes—and whether even or odd rows carry the extra vertex (`wideFirst`)—maximizes usable canvas area and aspect-ratio alignment across widescreen, square, and portrait mobile viewports without distorting barycentric angles. ## Usage Example ```tsx SimplexTopicGraph, createAdaptiveHexMeshStrategy, } from '@simplex-viz/react'; const meshStrategy = createAdaptiveHexMeshStrategy({ innerPadding: 56, minSideLength: 160, maxClusters: 10, }); ; ``` --- # [Strategy] Fixed Grid Lattice (Stage 01: Mesh Triangulation) Factory: `createFixedLatticeMeshStrategy(config: FixedLatticeConfig): SimplexMeshStrategy` Pins an exact (cols × rows) equilateral vertex grid across viewport resizes. When to Use: - Use when your visualization requires a constant, predictable vertex count K = cols × rows across all screen sizes. - Ideal for static SSR exports, side-by-side cohort comparisons, and fixed taxonomy boards. ## Deterministic Fixed Topology Whereas **Adaptive Hex Lattice** adjusts vertex count dynamically, **Fixed Grid Lattice** locks the exact planar graph `(cols × rows)` across every resize. By default (`orientation: 'auto'`), the grid aligns its longer axis with the canvas aspect ratio (landscape vs. mobile portrait) while scaling the equilateral side length `s` to fill the container—or keeping `s` constant when `sideLength` is explicitly specified. ## Usage Example ```tsx SimplexTopicGraph, createFixedLatticeMeshStrategy, } from '@simplex-viz/react'; // Exact 3 × 3 = 9 topic vertices in horizontal 60° rows: const fixedNine = createFixedLatticeMeshStrategy({ cols: 3, rows: 3, orientation: 'horizontal', wideFirst: true, }); ; ``` --- # [Strategy] Soft-Simplex Tag Clustering (Stage 02: Clustering & Projection) Factory: `createSoftSimplexTagClusteringStrategy(options?: SoftSimplexTagOptions): SimplexClusteringStrategy` Spreads multi-tag items smoothly across triangle interiors while keeping 1-tag items in a free 360° halo. When to Use: - Recommended primary strategy for multi-tag articles, repositories, papers, and catalog items. - Spreads multi-topic items smoothly across covering triangle interiors instead of stacking them on exact midpoints. - Leaves single-topic items unconstrained in a 360° outer halo around their vertex. ## Continuous Interior Spreading + Unconstrained Halos Discrete tag assignment snaps 2-cluster items onto exact edge midpoints and 3-cluster items onto exact triangle centroids. **Soft-Simplex Tag Clustering** blends tag specificity across the best covering planar triangle `τ = (c₁, c₂, c₃)` controlled by `triangleSpread`, utilizing the 2D triangle area naturally while keeping 1-cluster items (`unitVertexIndices.length === 1`) completely free to fan around their anchor in 360°. ## Usage Example ```tsx SimplexTopicGraph, createSoftSimplexTagClusteringStrategy, } from '@simplex-viz/react'; const tagClustering = createSoftSimplexTagClusteringStrategy
({ getTags: (article) => article.hashtags, triangleSpread: 0.45, sharedTagRule: 'planar-hitting-set', anchorRule: 'explaining-away', }); ; ``` --- # [Strategy] Jaccard Annealing Clustering (Stage 02: Clustering & Projection) Factory: `createJaccardAnnealingClusteringStrategy(options?: JaccardClusteringOptions): SimplexClusteringStrategy` Regularized Jaccard tag partitioning with QAP Simulated Annealing and planar hitting-set edges. When to Use: - Built-in default clustering strategy when items carry discrete tags. - Best when you want crisp structural separation between 1-cluster halos, 2-cluster edge bridges, and 3-cluster centroids. ## Jaccard Tag Partitioning & QAP Simulated Annealing **Jaccard Annealing Clustering** builds a regularized tag co-occurrence graph, partitions tags into `K` balanced clusters, and solves a **Quadratic Assignment Problem (QAP)** via deterministic Simulated Annealing so strongly co-occurring clusters sit on 1-hop adjacent mesh vertices. Across updates, the **Hungarian algorithm** matches new clusters to prior vertices to preserve cluster UIDs and OKLab colors. ## Usage Example ```tsx SimplexTopicGraph, createJaccardAnnealingClusteringStrategy, } from '@simplex-viz/react'; const jaccard = createJaccardAnnealingClusteringStrategy({ sharedTagRule: 'planar-hitting-set', anchorRule: 'explaining-away', }); ; ``` --- # [Strategy] Incremental Tag Anchoring (Stage 02: Clustering & Projection) Factory: `createIncrementalAnchorClusteringStrategy(options?: IncrementalClusteringOptions): SimplexClusteringStrategy` Preserves existing cluster vertices and UIDs during live updates while attaching new tags incrementally. When to Use: - Ideal for live collaborative feeds, streaming search results, and incremental document ingestion. - Prevents existing topic vertices from swapping positions when new items and tags arrive. ## Zero-Reshuffle Streaming Updates On `initialize()`, **Incremental Tag Anchoring** establishes the initial `K`-vertex topic layout via QAP annealing. On subsequent `update()` calls (when items are added or removed without changing mesh dimensions), it freezes existing vertex assignments and routes newly discovered tags to the vertex with highest co-occurrence affinity—guaranteeing maximum spatial mental-map stability. ## Usage Example ```tsx SimplexTopicGraph, createIncrementalAnchorClusteringStrategy, createWarmStartPbdLayoutStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Soft-Simplex Embedding Projection (Stage 02: Clustering & Projection) Factory: `createSoftSimplexEmbeddingClusteringStrategy(options: SoftSimplexEmbeddingClusteringOptions): SimplexClusteringStrategy` Load-balanced QAP and continuous interior simplex projection for single- or multi-modal embeddings. When to Use: - Recommended primary strategy for untagged dense embeddings (text, audio, vision, or latent vectors). - Supports weighted multi-modal vector fusion and automatic base-rate-aware discriminative cluster naming via optional features. - Sets requiresTags: false so getTags is completely optional. ## Multi-Modal Vector Fusion & Contrastive Cluster Naming **Soft-Simplex Embedding Projection** L2-normalizes and weights one or more embedding modalities into a unified feature vector, runs load-balanced Spherical/Euclidean k-Means++, embeds the learned centroid affinity matrix onto the 60° mesh via QAP annealing, and projects items continuously onto their optimal planar triangle `τ = (c₁, c₂, c₃)`. When `features` are supplied, SimplexViz scores each cluster against corpus-wide base rates—suppressing ubiquitous majority categories (such as a 77% `"Drama"` baseline in cinema catalogs) while automatically disambiguating sibling clusters that split a shared taxonomic group via intra-group secondary traits (for example *Adélie · Male* vs. *Adélie · Female*). ## Usage Example ```tsx SimplexTopicGraph, createSoftSimplexEmbeddingClusteringStrategy, } from '@simplex-viz/react'; const mediaClustering = createSoftSimplexEmbeddingClusteringStrategy({ getEmbedding: [ { name: 'Scene', getVector: (m) => m.sceneVec, weight: 0.65 }, { name: 'Style', getVector: (m) => m.styleVec, weight: 0.35 }, ], features: [ { label: 'Budget', getValue: (m) => Math.log10(m.budgetMusd), highLabel: 'Big-Budget Epics', lowLabel: 'Low-Budget Cult' }, { label: 'Runtime', getValue: (m) => m.runtimeMin, highLabel: 'Epic Runtime', lowLabel: 'Compact Classics' }, ], clusterCount: 7, metric: 'cosine', triangleSpread: 0.45, }); ; ``` --- # [Strategy] Planar NNLS Embedding Projection (Stage 02: Clustering & Projection) Factory: `createEmbeddingClusteringStrategy(options: EmbeddingClusteringOptions): SimplexClusteringStrategy` Spherical/L2 k-Means++ with closed-form non-negative least-squares projection onto planar triangles. When to Use: - Use when you want exact geometric least-squares reconstruction weights onto planar mesh simplices. - Supports sparse vertex/edge/triangle anchoring ('simplex-projection', 'explaining-away', or 'top-1') and optional contrastive feature naming. ## Closed-Form Planar NNLS Projection For each item vector `x`, **Planar NNLS Embedding Projection** evaluates every candidate planar simplex `τ` (vertices, 1-hop mesh edges, and 60° mesh triangles) and solves the exact constrained quadratic program minimizing `|| x − ∑ w_i · μ_i ||₂²` subject to `w_i ≥ 0` and `∑ w_i = 1`. Selecting the planar simplex with lowest reconstruction residual guarantees faithful geometric interpolation without cross-mesh tangling, while optional `features` automatically synthesize contrastive, collision-free labels across all `K` vertices. ## Usage Example ```tsx SimplexTopicGraph, createEmbeddingClusteringStrategy, } from '@simplex-viz/react'; const nnlsProjection = createEmbeddingClusteringStrategy({ getEmbedding: (doc) => doc.embedding, clusterCount: 8, metric: 'cosine', anchorRule: 'simplex-projection', }); ; ``` --- # [Strategy] Pairwise k-Medoids Projection (Stage 02: Clustering & Projection) Factory: `createSimilarityClusteringStrategy(options: SimilarityClusteringOptions): SimplexClusteringStrategy` Partitions arbitrary S(a, b) ∈ [0, 1] similarity kernels via PAM k-Medoids and QAP mesh embedding. When to Use: - Use when items have neither tags nor fixed-length vectors—only a pairwise similarity function S(a, b) ∈ [0, 1]. - Ideal for string edit distances, Gower trait kernels, AST/graph kernels, SQL join overlap, or biological sequence alignment. ## Partitioning Around Medoids (PAM) on 60° Meshes **Pairwise k-Medoids Projection** builds the symmetric `N × N` similarity matrix, selects `K` real domain items as cluster medoids via deterministic farthest-first initialization plus PAM swap refinement, embeds inter-medoid similarity onto the 60° mesh via QAP annealing, and projects every item onto its closest planar medoid triangle. Supplying `features` (or `deriveLabel`) turns medoid neighborhoods into concise, pairwise-distinct taxonomic or domain badges rather than raw exemplar IDs. ## Usage Example ```tsx SimplexTopicGraph, createSimilarityClusteringStrategy, } from '@simplex-viz/react'; const kernelClustering = createSimilarityClusteringStrategy({ getSimilarity: (a, b) => computeBlastAlignmentScore(a, b), clusterCount: 6, }); ; ``` --- # [Strategy] OKLab Edge Contrast (Stage 03: OKLab Color Science) Factory: `createOklabContrastColorStrategy(options?: OklabColorOptions): SimplexColorStrategy` Maximizes perceptual ΔE_OK across mesh edges and preserves chroma on barycentric bridge items. When to Use: - Built-in default perceptual color strategy for dark canvases and headless snapshots. - Maximizes perceptual ΔE_OK separation across every 1-hop mesh edge so neighboring clusters never share confusable hues. ## Graph-Coloring Contrast & Chroma-Preserving Mixing **OKLab Edge Contrast** generates a uniform ring of perceptual hues in Björn Ottosson's OKLab space, seeds vertices greedily, and runs pairwise swap refinement to maximize the minimum perceptual distance `ΔE_OK` across all mesh edges. Multi-cluster bridge items interpolate linearly in `(L, a, b)` with chroma restoration so 50/50 edge midpoints remain vivid rather than collapsing to muddy sRGB grey. ## Usage Example ```tsx SimplexTopicGraph, createOklabContrastColorStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Theme-Adaptive OKLab (Stage 03: OKLab Color Science) Factory: `createThemeAdaptiveOklabColorStrategy(options?: ThemeAdaptiveColorOptions): SimplexColorStrategy` Adjusts perceptual lightness and chroma automatically between light and dark themes. When to Use: - Recommended for dual-theme ('light' and 'dark') web applications. - Automatically deepens perceptual lightness on light backgrounds for crisp WCAG contrast while keeping luminous hues in dark mode. ## Seamless Light & Dark Theme Parity Colors optimized for dark backgrounds (`L ≈ 0.74`) wash out against white surfaces, while colors darkened for white surfaces look murky on `#07090E`. **Theme-Adaptive OKLab** inspects the active `theme` (`'light' | 'dark'`) passed to `` or `SimplexSvgController`, shifting OKLab lightness `L` while preserving hue angle `h = atan2(b, a)` so every cluster keeps its recognizable identity across theme switches. ## Usage Example ```tsx SimplexTopicGraph, createThemeAdaptiveOklabColorStrategy, } from '@simplex-viz/react'; const adaptiveColors = createThemeAdaptiveOklabColorStrategy(); ; ``` --- # [Strategy] Custom Brand Palette (Stage 03: OKLab Color Science) Factory: `createPaletteColorStrategy(paletteHex: readonly string[], options?: PaletteColorOptions): SimplexColorStrategy` Maps custom design-system hex colors onto the mesh with edge-contrast optimization. When to Use: - Use when clusters must match an organization's exact design-system hex tokens or categorical chart palette. - Still optimizes vertex assignment for edge contrast and blends bridge items in perceptual OKLab space. ## Brand Tokens Meet Perceptual OKLab Blending **Custom Brand Palette** converts your supplied sRGB hex colors into OKLab tuples, assigns them onto the 60° mesh to maximize perceptual contrast across adjacent triangle edges (`mode: 'edge-contrast'`), and computes `mixedColorHex` for multi-cluster items in OKLab space so even custom corporate palettes produce clean, legible intermediate blends. ## Usage Example ```tsx SimplexTopicGraph, createPaletteColorStrategy, } from '@simplex-viz/react'; const brandColors = createPaletteColorStrategy( ['#0891b2', '#d97706', '#c026d3', '#059669', '#2563eb', '#e11d48'], { mode: 'edge-contrast' }, ); ; ``` --- # [Strategy] Collision-Local Pocket Layout (Stage 04: Composable Layout) Factory: `createCollisionDrivenLayoutStrategy(options?: CollisionDrivenLayoutOptions): SimplexLayoutStrategy` Keeps sparse regions at full 1.0x scale and shrinks only locally colliding pockets to 0.0 px overlap. When to Use: - Recommended layout strategy whenever conformal 1:4 drill-down zoom is enabled. - Keeps sparse outer clusters at full 1.0x leaf scale and shrinks only locally colliding dense pockets. - Guarantees covering-triangle containment and 0.0 px convex SAT overlap. ## Local Pocket Shrinking + 1:4 Drill-Down Synergy In real-world corpora, one interdisciplinary triangle may hold 25 items while neighboring triangles hold 3. Instead of shrinking the entire atlas to fit the busiest triangle, **Collision-Local Pocket Layout** composes `createMeshInwardFanSeeder()`, `createSpaceFillingPbdRelaxer()`, and `createCollisionLocalScaleController()`: sparse regions stay at crisp `1.0x` scale, while dense pockets pack cleanly and automatically mark their parent triangle as `isDrillable: true` for `1:4` conformal zoom! ## Usage Example ```tsx SimplexTopicGraph, createCollisionDrivenLayoutStrategy, createBarycentricZoomStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Uniform PBD Layout (Stage 04: Composable Layout) Factory: `createPbdUniformLayoutStrategy(): SimplexLayoutStrategy` Space-filling mesh-inward fan seeding with global uniform scale search and exact convex SAT separation. When to Use: - Built-in default layout strategy when node area encodes a quantitative metric that must remain globally comparable. - Applies a single global scale factor α ∈ [minContentScale, 1] across every item in the atlas. ## Global Relative Size Preservation When circle or glyph radius encodes an exact quantitative variable—such as citation count, market cap, or clip duration—shrinking one dense region locally would alter visual size comparisons across the canvas. **Uniform PBD Layout** fans co-located items into their open covering mesh triangles (`createMeshInwardFanSeeder()` + `createSpaceFillingPbdRelaxer()`), binary-searches the largest global `α` where the entire scene settles cleanly, and polishes coordinates via Separating Axis Theorem (SAT) Minimum Translation Vectors (`0.0 px` overlap). *(Note: General solver bounds such as `minContentScale`, `nodePadding`, and `maxIterations` can also be passed via `layoutOptions` on ``.)* ## Usage Example ```tsx SimplexTopicGraph, createPbdUniformLayoutStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Warm-Start PBD Layout (Stage 04: Composable Layout) Factory: `createWarmStartPbdLayoutStrategy(): SimplexLayoutStrategy` Reuses settled coordinates across live mutations with space-filling PBD relaxation and uniform scale ratios. When to Use: - Ideal for streaming dashboards and interactive editors where items are inserted or deleted frequently. - Preserves global uniform scale ratios while anchoring existing item IDs to their previously settled coordinates. ## Minimal Node Displacement Across Live Mutations Re-seeding every item from scratch when a single new record arrives can cause unnecessary local swaps among neighboring nodes. **Warm-Start PBD Layout** wraps `createMeshInwardFanSeeder()` with `withWarmStartSeeder(...)` and pairs it with `createSpaceFillingPbdRelaxer()`: existing item IDs start relaxation from their exact previous-frame `(x, y)` coordinates, so only nodes directly displaced by the newcomer shift smoothly out of the way. ## Usage Example ```tsx SimplexTopicGraph, createIncrementalAnchorClusteringStrategy, createWarmStartPbdLayoutStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Density-Adaptive Layout (Stage 04: Composable Layout) Factory: `createLocalAdaptiveLayoutStrategy(options?: DensityAdaptiveLayoutOptions): SimplexLayoutStrategy` Disperses nodes into open triangle interiors, evaluates smooth radial crowd density, and polishes locally without global shrink. When to Use: - Use when you want smooth, continuous radial scale gradients from dense hubs out toward sparse fringes without shrinking isolated regions. - Spreads pockets across open covering triangles first, then evaluates crowd pressure inside crowdRadiusPx and polishes locally. ## Post-Dispersion Smooth Crowd-Density Scaling Whereas **Collision-Local Pocket Layout** shrinks strictly those pairs that touch during relaxation, **Density-Adaptive Layout** pairs `createMeshInwardFanSeeder()` and `createSpaceFillingPbdRelaxer()` with `createDensityPriorScaleController()`. Co-located anchors first fan out across the open interior of their covering mesh triangles at `1.0x`; a smooth radial spatial kernel (`crowdRadiusPx`) then measures true post-dispersion crowding so moderate pockets that fit comfortably stay at `1.0x`, while genuinely congested hubs exhibit gradual core-to-fringe size transitions polished locally (`0.0 px` convex SAT clearance, zero global collateral shrink). ## Usage Example ```tsx SimplexTopicGraph, createLocalAdaptiveLayoutStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Subspace Re-Clustering Drill-Down (Stage 05: Conformal 1:4 Zoom) Factory: `createSubspaceZoomStrategy(options?: SubspaceZoomStrategyOptions): SimplexZoomStrategy` Projects out constant parent traits and re-clusters zoomed subsets locally over high-variance features, vectors, or similarities. When to Use: - Recommended conformal 1:4 drill-down strategy for embeddings, similarity kernels, mixed-attribute records, and multi-modal catalogs. - Automatically zeroes out parent traits with no intra-cluster variance (σ_local = 0) so secondary domain facets, continuous axes, or residual embeddings separate items cleanly. - Works zero-config via automatic tag and object-field introspection, or with explicit domain SubspaceZoomFeature extractors for human-readable sub-cluster badges. ## Local Variance Projection & Exact `6!` Sub-Mesh QAP Purely geometric `1:4` subdivision preserves parent barycentric ratios, which works well as a baseline—but inside a specialized region (for example a *Mammals* triangle in **UCI Zoo** or a *Blockbuster* triangle in **Vega Cinema**), the features that formed the root overview are already locally constant (`milk = true`, `backbone = true` → `σ_local = 0`). `createSubspaceZoomStrategy` solves a genuine **local subspace re-clustering problem** at every drill-down step while preserving conformal `1:4` equilateral geometry: 1. **Zero-Variance Projection**: Evaluates candidate boolean, categorical, numeric, vector, or similarity axes exclusively over the subset `S` of items inside the focused triangle or cluster. Any attribute that is constant across `S` (`σ_local ≤ 10⁻⁶`) drops out automatically, promoting intra-group variations (such as *Predator*, *Aquatic*, *Body Size*, *Budget*, or *Release Era*). 2. **Local `k`-Means++ & Distinct Facet Labeling**: Partitions `S` into up to `6` local prototypes (or `3` prototypes for a cluster spotlight) and assigns collision-free, human-readable `subclusterLabel`s ranked by standardized z-score separation. 3. **Exact `6! = 720` Permutation Alignment**: Evaluates all `720` bijections mapping the `6` local prototypes onto `[V₀, V₁, V₂, M₀₁, M₁₂, M₂₀]` to jointly maximize parent-corner spatial continuity, `9`-edge QAP cosine similarity, and degree-4 midpoint load balance. 4. **Parent-Context Orientation Plaques**: The `3` outer corners (`V₀, V₁, V₂`) retain their parent corner's `parentContextLabel` as a compact header line above the newly discovered local `subclusterLabel` (for example `EPIC RUNTIME / New Hollywood`), while the `3` edge midpoints (`M₀₁, M₁₂, M₂₀`) render as single-line chamfered sub-cluster plaques alongside color-coded `ZoomBreadcrumbSegment` breadcrumbs. 5. **Uniform Cluster/Subcluster Stars & Single-Triangle Leaf Focus**: Clicking any cluster or subcluster badge opens its lattice-conformal 1-ring `'incident-star'` with continuous simplex-distance item dimming (`opacity = 0.32 + 0.68 · w̃₀`), and clicking the free background face of a `1.0×` leaf triangle focuses that single un-subdivided triangle (`'triangle-focus'`) while keeping its items directly clickable. ## Usage Example ```tsx SimplexTopicGraph, createCollisionDrivenLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/react'; const zoomStrategy = createSubspaceZoomStrategy({ features: [ { label: 'Budget', getValue: (f) => Math.log10(f.budgetMusd), highLabel: 'High Budget', lowLabel: 'Low Budget', }, { label: 'Release Era', getValue: (f) => f.releaseYear, highLabel: 'New Hollywood', lowLabel: 'Golden Age', }, { label: 'Genre', getValue: (f) => f.genre, }, ], clusterZoomMode: 'incident-star', }); ; ``` --- # [Strategy] Barycentric 1:4 Drill-Down (Stage 05: Conformal 1:4 Zoom) Factory: `createBarycentricZoomStrategy(options?: BarycentricZoomStrategyOptions): SimplexZoomStrategy` Purely geometric orientation-preserving 1:4 subdivision with Adaptive Contrast Stretch and explicit A ↔ B midpoint bridges. When to Use: - Use when you want purely geometric 1:4 coordinate magnification that preserves exact parent barycentric ratios without re-clustering. - Preserves exact equilateral ▲/▼/▶/◀ orientation with explicit A ↔ B midpoint bridge plaques and color-coded 3-segment breadcrumbs. ## Universal Conformal 1:4 Equilateral Subdivision Clicking any drillable triangle splits its edges at midpoints `(M_ab, M_bc, M_ca)` into `4` congruent equilateral sub-triangles (`3` corner triangles matching parent orientation + `1` inverted center triangle). To preserve spatial orientation at every zoom depth without cluttering the sub-mesh: 1. **Unchanged Outer Corners (`V₀, V₁, V₂`)**: Retain their primary cluster capsule and exact parent title, or switch to a two-line plaque with `parentContextLabel` when **Adaptive Contrast Stretch** shifts an outer corner's weight profile. 2. **Explicit Midpoint Bridge Plaques (`M₀₁, M₁₂, M₂₀`)**: Render as compact chamfered hexagonal sub-cluster plaques (`role: 'intermediate'`) labeled with their immediate edge bridge relation (`A ↔ B`), blended in perceptual OKLab space. 3. **Uniform 1-Ring Cluster & Subcluster Stars with Simplex-Distance Dimming**: In `'incident-star'` mode (default), every cluster and subcluster badge—at any depth, including `1.0×` leaf frames and sparse corners—focuses strictly its incident lattice triangles (never spawning off-grid spotlight triangles) and dims active items continuously by barycentric simplex distance `d = 1 − w̃₀ ∈ [0, 1]` (`opacity = 0.32 + 0.68 · w̃₀`). Clicking a rim cluster switches laterally at the same depth, while clicking the focused center cluster toggles back up (`drillUp`). 4. **Single-Triangle Leaf Focus (`'triangle-focus'`)**: Once a triangle reaches leaf scale (`leafTriangleFocus: true`), its content items become directly clickable without pointer pass-through, while clicking the free triangle background focuses that single un-subdivided triangle across the viewport (clicking its free face again toggles back out). 5. **Color-Coded Breadcrumb Segments**: Every drill step emits `ZoomBreadcrumbSegment[]` carrying the parent corner names and hex swatches so users always know where they are in the global atlas. ## Usage Example ```tsx SimplexTopicGraph, createCollisionDrivenLayoutStrategy, createBarycentricZoomStrategy, } from '@simplex-viz/react'; ; ``` --- # [Strategy] Semantic 3→6 Tag Drill-Down (Stage 05: Conformal 1:4 Zoom) Factory: `createSemanticZoomStrategy(options?: SemanticZoomStrategyOptions): SimplexZoomStrategy` Promotes vertex-exclusive secondary tags across 6 collision-free sub-vertices with parent-corner context and A ↔ B bridge fallbacks. When to Use: - Recommended 1:4 drill-down strategy for multi-tag corpora (requiresTags: true) such as software repositories, research papers, or knowledge bases. - Discovers emergent sub-topics inside a zoomed triangle, promotes vertex-exclusive tags first, and guarantees 6 pairwise-distinct sub-vertex labels. ## Emergent 3→6 Sub-Topic Discovery & Collision-Free Labeling While **Barycentric 1:4 Drill-Down** subdivides purely from parent barycentric coordinates, **Semantic 3→6 Tag Drill-Down** inspects all secondary and tertiary tags carried by items inside the focused triangle—keeping parent corners anchored when already balanced, or re-partitioning the triangle's discriminative tags across all `6` sub-vertices (`[V₀, V₁, V₂, M₀₁, M₁₂, M₂₀]`) via deterministic farthest-signature seeding and hill-climbing balance optimization. To keep every zoomed `1:4` frame immediately legible even in overlapping multi-tag ecosystems: 1. **Sibling-Vertex Exclusivity First**: Assigned tags on each sub-vertex are ranked by *exclusivity across the 6 sibling vertices* (`vertexTagFreq === 1` first) and intra-triangle specificity, while filtering out tags that merely repeat an outer corner's `parentContextLabel`. Exclusive sub-topics (such as `#graph` or `#threejs`) are never buried behind shared carrier tags (`#javascript`, `#visualization`). 2. **Honest Midpoint Bridges on Sparse Subsets**: When a triangle contains fewer discriminative tags than sub-vertices, tags are never duplicated onto empty midpoints; post-optimization duplicate buckets are cleared so pure transition midpoints display explicit `A ↔ B` bridge relations. 3. **Canonical 6-Vertex Uniqueness & Zero Corner Stutter**: Outer corners whose sub-tags do not refine their parent topic remain clean single-line primary capsules (preventing `JAVASCRIPT / JavaScript` redundancy), while a joint canonical pass guarantees all `6` sub-vertices carry pairwise-distinct labels—even up to symmetric order swaps (`A · B` vs. `B · A` and `A ↔ B` vs. `B ↔ A`). 4. **Uniform Cluster/Subcluster Stars & Single-Triangle Leaf Focus**: Every primary cluster and `1:4` subcluster badge opens a lattice-conformal 1-ring `'incident-star'` with simplex-distance item dimming (`opacity = 0.32 + 0.68 · w̃₀`), while leaf triangles (`leafTriangleFocus: true`) keep their items directly clickable and remain focusable as single un-subdivided `'triangle-focus'` frames via their free triangle background. ## Usage Example ```tsx SimplexTopicGraph, createSoftSimplexTagClusteringStrategy, createCollisionDrivenLayoutStrategy, createSemanticZoomStrategy, } from '@simplex-viz/react'; tagTaxonomy[tag]} clusteringStrategy={createSoftSimplexTagClusteringStrategy()} layoutStrategy={createCollisionDrivenLayoutStrategy()} zoomStrategy={createSemanticZoomStrategy({ clusterZoomMode: 'incident-star', })} showZoomBreadcrumbs />; ``` --- # [Strategy] Continuous Free Camera (Stage 05: Conformal 1:4 Zoom) Factory: `createFreeCameraZoomStrategy(options?: FreeCameraZoomOptions): SimplexZoomStrategy` Continuous cursor-centered wheel zoom, drag-to-pan, and two-finger touch pinch. When to Use: - Built-in default navigation mode for continuous pan-and-zoom map exploration. - Use when you want smooth cursor-centered wheel zoom and drag-to-pan without discrete sub-mesh re-solving. ## Continuous Affine Camera Navigation **Continuous Free Camera** sets `mode: 'free-camera'`, enabling smooth cursor-centered mouse-wheel zoom (`onWheel: 'zoom-to-cursor'`), click-and-drag panning, two-finger touch pinch-zoom, and single-click cluster/triangle spotlight highlighting without subdividing triangles into child frames. ## Usage Example ```tsx SimplexTopicGraph, createFreeCameraZoomStrategy, } from '@simplex-viz/react'; ; ``` --- # [API] @simplex-viz/core (v1.0.0) Pure ES2022 TypeScript engine with zero runtime dependencies and zero DOM globals for browsers, Node.js, Bun, Deno, and Web Workers. Install: `npm install @simplex-viz/core` Entry Points: - `@simplex-viz/core` (Universal ES2022 (Browser, Node.js, Deno, Bun, Web Worker, Edge); DOM-free; sideEffects: false; root): Headless geometry, clustering, OKLab mixing, SAT collision layout, 1:4 zoom/drill-down, timeline engine, and shared DOM-free utilities. - `@simplex-viz/core/worker` (Web Worker, Node.js worker_threads, or SSR async fallback; DOM-free; sideEffects: false; exclusive subpath): Exclusive subpath (not re-exported from root) providing off-thread RPC protocol, solver client/handler, and async SSR fallback. - `@simplex-viz/core/dom` (Browser / DOM Hosts (structural TS interfaces); DOM / Host; sideEffects: false; exclusive subpath): Exclusive subpath (not re-exported from root) sharing container, ResizeObserver, tooltip, ARIA/live-region, cursor, click, and viewport zoom helpers across renderers. Exports: - `solveSimplexSnapshot` [@simplex-viz/core] (Function): `solveSimplexSnapshot( items: readonly TItem[], options?: SimplexSolverOptions, ): SimplexSnapshotResult` — Synchronous one-shot solver returning clusters, mesh triangles, OKLab colors, and 0.0 px non-overlapping item coordinates. - `SimplexGraphEngine` [@simplex-viz/core] (Class): `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` [@simplex-viz/core] (Function): `createAdaptiveHexMeshStrategy( defaults?: Partial, ): SimplexMeshStrategy` — Selects aspect-aligned 60-degree lattice orientation, row parity, and full-canvas scaling automatically (supports explicit sideLength). - `createSoftSimplexEmbeddingClusteringStrategy` [@simplex-viz/core] (Function): `createSoftSimplexEmbeddingClusteringStrategy( options: SoftSimplexEmbeddingClusteringOptions, ): SimplexClusteringStrategy` — Clusters single- or multi-modal vector embeddings via load-balanced QAP, continuous interior simplex projection, and optional contrastive feature naming. - `createSoftSimplexTagClusteringStrategy` [@simplex-viz/core] (Function): `createSoftSimplexTagClusteringStrategy( config?: SoftSimplexTagClusteringConfig, ): SimplexClusteringStrategy` — Partitions discrete tags with smooth triangleSpread interior anchoring and unconstrained 360-degree vertex halos. - `createComposedLayoutStrategy` [@simplex-viz/core] (Function): `createComposedLayoutStrategy( options: ComposedLayoutStrategyOptions, ): SimplexLayoutStrategy` — Composes any LayoutSeeder × PositionRelaxer × ScaleController with guaranteed 0.0 px convex SAT separation. - `createPbdUniformLayoutStrategy` [@simplex-viz/core] (Function): `createPbdUniformLayoutStrategy(): SimplexLayoutStrategy` — Default space-filling uniform layout strategy dispersing items across open covering triangles while preserving one exact global scale factor α. - `createLocalAdaptiveLayoutStrategy` [@simplex-viz/core] (Function): `createLocalAdaptiveLayoutStrategy( options?: { crowdRadiusPx?: number; minLocalScale?: number; warmStart?: boolean }, ): SimplexLayoutStrategy` — Post-dispersion smooth radial crowd-kernel layout with local halo collision polish and zero global shrink collateral. - `createCollisionDrivenLayoutStrategy` [@simplex-viz/core] (Function): `createCollisionDrivenLayoutStrategy( options?: CollisionDrivenLayoutOptions, ): SimplexLayoutStrategy` — Space-filling local pocket layout keeping all non-colliding items at 1.0x leaf scale and shrinking only colliding pairs. - `createSubspaceZoomStrategy` [@simplex-viz/core] (Function): `createSubspaceZoomStrategy( options?: SubspaceZoomStrategyOptions, ): SimplexZoomStrategy` — Local variance-projected 1:4 sub-clustering with exact 6! QAP alignment, uniform 1-ring cluster stars, and single-triangle leaf focus. - `createBarycentricZoomStrategy` [@simplex-viz/core] (Function): `createBarycentricZoomStrategy( options?: BarycentricZoomStrategyOptions, ): SimplexZoomStrategy` — Conformal 1:4 equilateral subdivision with Adaptive Contrast Stretch, 1-ring cluster stars, and single-triangle leaf focus. - `createSemanticZoomStrategy` [@simplex-viz/core] (Function): `createSemanticZoomStrategy( options?: SemanticZoomStrategyOptions, ): SimplexZoomStrategy` — Exclusive-first 3→6 sub-vertex tag re-partitioning with collision-free labels, 1-ring cluster stars, and single-triangle leaf focus. - `assignDiscriminativeClusterLabels` [@simplex-viz/core] (Function): `assignDiscriminativeClusterLabels( clusters: readonly DiscriminativeClusterInput[], allItems: readonly TItem[], options: DiscriminativeClusterLabelOptions, ): readonly string[]` — Scores numeric, boolean, and categorical features against corpus base rates to assign pairwise-distinct labels across sibling clusters. - `resolveDiscriminativeClusterLabel` [@simplex-viz/core] (Function): `resolveDiscriminativeClusterLabel( ctx: ClusterDerivationContext, options: DiscriminativeClusterLabelOptions, ): string` — Convenience helper for deriveClusterMeta that resolves a cluster's base-rate-aware, collision-free label using ctx.peerClusters and ctx.allItems. - `createFinalSeededClusteringStrategy` [@simplex-viz/core] (Function): `createFinalSeededClusteringStrategy( baseStrategy?: SimplexClusteringStrategy, options?: FinalSeededClusteringOptions, ): SimplexClusteringStrategy` — Pins canonical full-corpus clusters, vertex positions, UIDs, and OKLab hues across chronological timeline frames or filtered subsets. - `createFinalSeededLayoutStrategy` [@simplex-viz/core] (Function): `createFinalSeededLayoutStrategy( baseStrategy?: SimplexLayoutStrategy, options?: FinalSeededLayoutOptions, ): SimplexLayoutStrategy` — Freezes canonical full-corpus (x, y) item coordinates across timeline frames with scaleMode: 'pinned' | 'adaptive' and exact SAT overlap verification. - `createSimplexTimeline` [@simplex-viz/core] (Function): `createSimplexTimeline( options?: SimplexTimelineOptions, ): SimplexTimelineController` — Zero-DOM headless chronological frame grouper and playback controller with play/pause/step/seek/speed APIs. - `createSimplexWorkerClient` [@simplex-viz/core/worker] (Function): `createSimplexWorkerClient( workerOrFactory?: SimplexWorkerPort | (() => SimplexWorkerPort) | null, options?: SimplexWorkerClientOptions, ): SimplexWorkerClient` — Generation-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` [@simplex-viz/core/worker] (Function): `attachSimplexWorkerHandler( options?: AttachSimplexWorkerHandlerOptions, ): () => void` — Attaches the protocol handler inside a Web Worker or Node worker_threads script with a pluggable solver hook (WASM-ready). - `solveSimplexSnapshotAsync` [@simplex-viz/core/worker] (Function): `solveSimplexSnapshotAsync( items: readonly TItem[], options?: SolveSimplexSnapshotAsyncOptions, ): Promise>` — Async counterpart to solveSimplexSnapshot() delegating to an optional SimplexWorkerClient or a yielded macrotask turn. - `observeSimplexContainerResize` [@simplex-viz/core/dom] (Function): `observeSimplexContainerResize( options: ObserveSimplexContainerResizeOptions, ): SimplexResizeObserverHandle` — Coordinates ResizeObserver viewport updates, 0x0 auto-recovery, and optional deferInitialLayout fallback timers across SVG and Canvas controllers. - `computeSimplexTooltipCoords` [@simplex-viz/core/dom] (Function): `computeSimplexTooltipCoords( input: ComputeSimplexTooltipCoordsInput, ): SimplexTooltipCoords` — Computes viewport edge-flipped, margin-clamped tooltip (left, top) coordinates shared by SVG, Canvas, and React tooltips. - `buildSimplexTooltipContentModel` [@simplex-viz/core/dom] (Function): `buildSimplexTooltipContentModel( target: SimplexTooltipTargetInput<...>, options?: BuildSimplexTooltipModelOptions, ): SimplexTooltipContentModel` — Builds normalized tooltip titles, formatted tags, OKLab accents, cluster counts, and drill-down/neighbor hints. - `dispatchSimplexDefaultLeftClick` [@simplex-viz/core/dom] (Function): `dispatchSimplexDefaultLeftClick( target: HitTarget<...>, rawEvent: NormalizedPointerEvent, context: ..., ): boolean` — Unifies composable user click callbacks, 1:4 drill-down navigation, and free-camera focus/selection clearing. - `zoomSimplexViewportByFactor` [@simplex-viz/core/dom] (Function): `zoomSimplexViewportByFactor( element: Pick, camera: Pick, factor: number, fallbackWidth?: number, fallbackHeight?: number, ): void` — Zooms any renderer viewport around its current center using structural element dimensions. - `getSimplexTooltipThemeTokens` [@simplex-viz/core/dom] (Function): `getSimplexTooltipThemeTokens(theme: SimplexColorTheme): SimplexTooltipThemeTokens` — Returns canonical dark/light floating tooltip surface, border, text, and shadow tokens shared by SVG, Canvas, and React overlays. - `createSimplexTooltipOverlay` [@simplex-viz/core/dom] (Function): `createSimplexTooltipOverlay( options: CreateSimplexTooltipOverlayOptions<...>, ): SimplexTooltipOverlay<...>` — Manages lazy floating tooltip mounting, theme synchronization, custom DOM renderers, target deduplication, and edge-flipped positioning across SVG and Canvas. - `bindSimplexInteractiveViewport` [@simplex-viz/core/dom] (Function): `bindSimplexInteractiveViewport( options: BindSimplexInteractiveViewportOptions<...>, ): SimplexInteractiveViewportHandle` — Binds shared pointer panning, multi-touch pinch, touch scroll-locking, Shift-drag marquee, wheel zoom, cursor resolution, click suppression, and keyboard handling. - `createSimplexZoomBreadcrumbsOverlay` [@simplex-viz/core/dom] (Function): `createSimplexZoomBreadcrumbsOverlay( options: CreateSimplexZoomBreadcrumbsOverlayOptions, ): SimplexZoomBreadcrumbsOverlay` — Mounts and updates the theme-adaptive drill-down breadcrumb navigation bar shared by SVG and Canvas controllers. - `createSimplexTimelineBarOverlay` [@simplex-viz/core/dom] (Function): `createSimplexTimelineBarOverlay( options: CreateSimplexTimelineBarOverlayOptions, ): SimplexTimelineBarOverlay` — Mounts and updates the compact Play/Pause/Step/Scrubber timeline HUD bar shared by SVG and Canvas controllers. - `createSimplexKeyboardNavigator` [@simplex-viz/core/dom] (Function): `createSimplexKeyboardNavigator( options: SimplexKeyboardNavigatorOptions<...>, ): SimplexKeyboardNavigator` — Provides the shared WCAG 2.1 AA single-tabstop keyboard traversal, selection/activation, Escape cascade, and screen-reader announcement state machine. - `createSimplexTimelineHostSession` [@simplex-viz/core] (Function): `createSimplexTimelineHostSession( initialConfig?: { readonly rawClusteringStrategy?: SimplexClusteringStrategy; readonly rawLayoutStrategy?: SimplexLayoutStrategy; readonly baseEmptyClusterBehavior?: EmptyClusterBehavior }, ): SimplexTimelineHostSession` — Coordinates chronological timeline playback, autoFinalSeed/autoFinalSeedLayout wrapping, and emptyClusterBehavior transitions for renderer controllers. - `resolveEffectiveGeometricPolygon` [@simplex-viz/core] (Function): `resolveEffectiveGeometricPolygon( base: { readonly shape: GeometricShapeKind; readonly sides?: number; readonly rotationRad?: number }, overrides?: { readonly shape?: GeometricShapeKind; readonly sides?: number; readonly rotationRad?: number }, ): ResolvedGeometricPolygon` — Resolves base shape visuals plus view-level overrides into canonical polygon kind, side count, rotation, and area-equalized scale. - `getGeometricShapeVertices` [@simplex-viz/core] (Function): `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` [@simplex-viz/core] (Function): `measureGeometricShapeHull( resolved: ResolvedGeometricPolygon, radius: number, options?: { readonly useRadiusScale?: boolean; readonly starOuterScale?: number }, ): ConvexGeometry` — Builds the exact analytical convex collision hull matching a resolved geometric shape. - `resolveSimplexThemeBackgroundColor` [@simplex-viz/core] (Function): `resolveSimplexThemeBackgroundColor(theme: SimplexColorTheme, surface?: 'svg' | 'canvas'): string` — Returns the canonical dark/light backdrop fill color for SVG and Canvas surfaces. - `decodeSimplexDataUrlToBytes` [@simplex-viz/core] (Function): `decodeSimplexDataUrlToBytes( dataUrl: string, fallbackMime?: string, ): { readonly bytes: Uint8Array; readonly mimeType: string }` — Pure ES2022 decoder converting base64 or UTF-8 data: URLs into raw byte buffers without atob, Blob, or DOM globals. ## 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`) ```ts 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: ```ts // worker.ts attachSimplexWorkerHandler(); // main.ts 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` --- # [API] @simplex-viz/svg (v1.0.0) Portable SVG renderer, offscreen getBBox() hull measurement, root pointer hit-testing, client-side SVG/PNG export, zero-DOM SSR string rendering (@simplex-viz/svg/ssr), 1:4 subdivision previews, and breadcrumbs. Install: `npm install @simplex-viz/svg` Entry Points: - `@simplex-viz/svg` (Browser DOM (Vanilla TS, Vue, Angular, Svelte, Solid); DOM / Host; sideEffects: false; root): Interactive SVG controller, offscreen getBBox() hull measurement, pluggable Svg*View system, client-side SVG/PNG export, and core strategy re-exports. - `@simplex-viz/svg/ssr` (Node.js, Edge, Astro / Next.js SSR builds; DOM-free; sideEffects: false; exclusive subpath): Exclusive zero-DOM subpath (not re-exported from root) providing SVG string rendering & deterministic font-metric measurers for server bundles. Exports: - `createSimplexSvg` [@simplex-viz/svg] (Function): `createSimplexSvg( container: HTMLElement | string, itemsOrOptions: readonly TItem[] | SimplexSvgOptions<...>, maybeOptions?: Partial>, ): SimplexSvgController<...>` — Zero-boilerplate factory mounting a complete interactive SVG simplex atlas into an HTMLElement or CSS selector. - `SimplexSvgController` [@simplex-viz/svg] (Class): `new SimplexSvgController< TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta >(options: SimplexSvgOptions<...>)` — Manages ResizeObserver (with 0x0 auto-recovery & deferInitialLayout), rAF loop, live prefers-reduced-motion subscription (reducedMotion), Shift+Click & Shift+Drag marquee multi-selection (selectedIds, shiftClickSelects, marqueeSelection, onSelectionChange), structured getLegendModel()/onLegendChange synced with zoom/filter/focus/timeline, custom DOM/HTML tooltip renderers (SimplexDomTooltipRenderer) with viewport edge-flipping, deep-link getViewState()/restoreViewState(), zero-relayout itemFilter, linked-view setHighlightedIds()/focusItem()/zoomToItem(), client-side exportSvg()/exportPng(), re-entrant batch()/setOptions(), WCAG 2.1 AA keyboard navigation & aria-live announcements, mobile touchScrollLockPx/clickTolerancePx, timeline HUD, and breadcrumbs—powered by shared @simplex-viz/core/dom primitives. - `SvgRendererAdapter` [@simplex-viz/svg] (Class): `new SvgRendererAdapter(options: SvgRendererAdapterOptions)` — Low-level SimplexRendererAdapter reconciling SVG layers, view-level hoverScale/dimmedOpacity hooks, semantic ARIA metadata (ariaIdPrefix), zoom-adaptive double-halo focus rings, dual-layer crossfades, and internal 1:4 drillable edges. - `GeometricShapeSvgView` [@simplex-viz/svg] (View Plugin): `new GeometricShapeSvgView(options?: GeometricShapeSvgViewOptions)` — Renders and morphs circles, diamonds, stars, and arbitrary regular N-gons (sides >= 3) with exact convex SAT hulls plus lightweight shapeOptions (hoverScale, hoverRingColor, dimmedOpacity, strokeColor, strokeWidth). - `MultiSectorGlyphSvgView` [@simplex-viz/svg] (View Plugin): `new MultiSectorGlyphSvgView()` — Renders multi-arc donut glyphs proportional to an item's barycentric cluster weights. - `OklabTintTriangleSvgView` [@simplex-viz/svg] (View Plugin): `new OklabTintTriangleSvgView(options?: OklabTintTriangleOptions)` — Default triangle face view with subtle OKLab fills, hover/focus perimeter strokes, and dimmed neighbor context. - `BadgeClusterSvgView` [@simplex-viz/svg] (View Plugin): `new BadgeClusterSvgView(options?: BadgeClusterSvgViewOptions)` — WCAG-AA saturated OKLab cluster view rendering full-round capsules (configurable via showCode, maxTitleChars, formatTitle) and chamfered hexagonal plaques for intermediate sub-clusters. - `DashedMeshEdgeSvgView` [@simplex-viz/svg] (View Plugin): `new DashedMeshEdgeSvgView(options?: DashedMeshEdgeOptions)` — Default dashed 60-degree mesh edge view, automatically reused for internal 1:4 drillable triangle subdivision lines. - `renderSimplexSvgString` [@simplex-viz/svg/ssr] (Function): `renderSimplexSvgString( itemsOrSnapshot: readonly TItem[] | SimplexLayoutSnapshot, options?: RenderSimplexSvgStringOptions, ): string` — Zero-DOM SSR SVG string renderer supporting deterministic font metrics (estimateSsrTextWidth, createSsrPresetHullMeasurers, pluggable measureText), all presets, themes, filters, highlights, and custom SVG string hooks. ## Mounting in Vanilla TypeScript, Vue, Svelte, or Angular `createSimplexSvg` accepts either a CSS selector (`'#atlas'`) or an `HTMLElement` reference and returns a `SimplexSvgController` whose `.destroy()` method cleans up all DOM listeners and `ResizeObserver` instances: ```ts createSimplexSvg, createSubspaceZoomStrategy, GradientTriangleSvgView, ClusterTintedEdgeSvgView, } from '@simplex-viz/svg'; const controller = createSimplexSvg('#atlas', { items, preset: 'glyphs', theme: 'dark', triangleView: new GradientTriangleSvgView({ baseOpacity: 0.16 }), edgeView: new ClusterTintedEdgeSvgView({ strokeWidth: 1.35 }), zoomStrategy: createSubspaceZoomStrategy(), showZoomBreadcrumbs: true, itemFilter: (item) => item.tags.includes('geometry'), itemFilterMode: 'dim', ariaLabel: 'Interactive knowledge simplex atlas', keyboardNavigation: true, tooltip: { render(target, container) { if (target.kind !== 'content') return false; const title = document.createElement('strong'); title.textContent = target.item.label; container.replaceChildren(title); }, }, onLegendChange: (legend) => { console.log('Legend entries:', legend.entries.length, 'visible:', legend.visibleItems); }, }); // Coalesce multi-property runtime updates into a single recomputation: controller.setOptions({ theme: 'light', itemFilterMode: 'hide', highlightedIds: ['item-1', 'item-4'], }); // Programmatic linked-view navigation, legend snapshot, multi-selection, deep-linking & export: const legend = controller.getLegendModel(); controller.zoomToItem('item-1', { zoom: 2.2, maxDrillSteps: 4 }); controller.setSelectedIds(['item-1', 'item-4']); const snapshot = controller.getViewState(); controller.restoreViewState(snapshot); const svgMarkup = controller.exportSvg({ padding: 24, title: 'Knowledge Atlas' }); const pngBlob = await controller.exportPng({ scale: 2, padding: 24 }); // Clean up on unmount: // controller.destroy(); ``` ## Headless Zero-DOM SSR (`@simplex-viz/svg/ssr`) Import `renderSimplexSvgString` from `@simplex-viz/svg/ssr` in Node.js, Edge runtimes, Astro/Next.js builds, or headless PNG pipelines (such as `@resvg/resvg-js`) without bundling browser controller code or running Puppeteer: ```ts const svg = renderSimplexSvgString(items, { width: 1200, height: 720, preset: 'badges', theme: 'dark', padding: 24, }); ``` ## Custom `SvgNodeView` Contract Implement `SvgNodeView` when building high-throughput custom SVG glyphs that update imperatively at 60 fps without virtual-DOM overhead: ```ts export const pillNodeView: SvgNodeView< { label: string; colorHex: string }, ContentNodeRenderState<{ label: string; colorHex: string }, MyItem> > = { createElement(doc) { const g = doc.createElementNS('http://www.w3.org/2000/svg', 'g'); const rect = doc.createElementNS('http://www.w3.org/2000/svg', 'rect'); const text = doc.createElementNS('http://www.w3.org/2000/svg', 'text'); g.append(rect, text); return g; }, updateElement(g, visual, state) { const [rect, text] = g.children as unknown as [SVGRectElement, SVGTextElement]; rect.setAttribute('x', '-42'); rect.setAttribute('y', '-12'); rect.setAttribute('width', '84'); rect.setAttribute('height', '24'); rect.setAttribute('rx', '6'); rect.setAttribute('fill', visual.colorHex); rect.setAttribute('opacity', state.interaction.isDimmed ? '0.28' : '1'); text.textContent = visual.label; }, }; ``` --- # [API] @simplex-viz/react (v1.0.0) Declarative component, JSX custom node measurement, and imperative useSimplexGraphController() hook re-exporting all SVG and Core utilities. Install: `npm install @simplex-viz/react` Entry Points: - `@simplex-viz/react` (React 18 & 19 (Browser DOM); DOM / Host; sideEffects: false; root): Declarative component, JSX custom node measurement, controller & timeline hooks, and all SVG/Core re-exports. Exports: - `SimplexTopicGraph` [@simplex-viz/react] (Component): ` {...props} />` — Primary responsive React component supporting presets, shapeOptions, getShape, badgeOptions, viewport edge-flipped built-in JSX tooltips (@simplex-viz/core/dom), reducedMotion, Shift+Click & Shift+Drag multi-selection (selectedIds, shiftClickSelects, marqueeSelection, onSelectionChange), structured legend subscriptions (onLegendChange), zero-relayout itemFilter/itemFilterMode, batched prop sync, WCAG 2.1 AA ariaLabel/keyboardNavigation, timeline playback, deferInitialLayout, mobile touchScrollLockPx/clickTolerancePx, JSX node renderers, and drill-down. - `useSimplexGraphController` [@simplex-viz/react] (Hook): `useSimplexGraphController< TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta >(): { controllerRef: RefObject | null>; handle: SimplexGraphControllerHandle; }` — Provides stable imperative access to live item mutations, multi-selection (setSelectedIds/toggleSelectedId/clearSelection/selectItemsInScreenRect), structured legend snapshots (getLegendModel), deep-linking (getViewState/restoreViewState), reducedMotion controls, setItemFilter(), linked-view setHighlightedIds()/focusItem()/zoomToItem(), exportSvg()/exportPng() snapshots, batch()/setOptions(), keyboard focus helpers, camera resets, relayout(), timeline access, and drillDown / drillUp actions. - `useSimplexTimeline` [@simplex-viz/react] (Hook): `useSimplexTimeline( target: RefObject | null> | SimplexTimelineController | null, ): UseSimplexTimelineResult` — Reactive React hook subscribing to chronological timeline state with play, pause, toggle, stepBy, seek, and speed controls. - `SimplexTopicGraphProps` [@simplex-viz/react] (Interface): `interface SimplexTopicGraphProps< TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta >` — Conditional hybrid prop types enforcing getId / getTags only when TItem lacks id / tags and tags are required. ## `` Props Overview `` syncs declarative React prop updates into the underlying `SimplexSvgController` without remounting the SVG scene or interrupting active spring animations (using shared option-equality helpers from `@simplex-viz/core` plus viewport edge-flipped tooltips via `@simplex-viz/core/dom`): ```tsx SimplexTopicGraph, createSubspaceZoomStrategy, createCollisionDrivenLayoutStrategy, createSoftSimplexTagClusteringStrategy, useSimplexGraphController, } from '@simplex-viz/react'; export function InteractiveAtlas({ articles }: { readonly articles: readonly Article[] }) { const { controllerRef, handle } = useSimplexGraphController
(); return (
a.slug} getTags={(a) => a.tags} getLabel={(a) => a.title} preset="glyphs" theme="dark" clusteringStrategy={createSoftSimplexTagClusteringStrategy({ triangleSpread: 0.45 })} layoutStrategy={createCollisionDrivenLayoutStrategy()} zoomStrategy={createSubspaceZoomStrategy()} showZoomBreadcrumbs itemFilter={(a) => a.tags.length > 0} itemFilterMode="dim" ariaLabel="Interactive research articles atlas" keyboardNavigation tooltip onZoomStateChange={(state) => { console.log('Current drill depth:', state.depth); }} />
); } ``` ## Imperative Handle Methods (`handle`) Returned by `useSimplexGraphController()`: - **Live Corpus Mutations & Filtering**: `handle.addItems(items)`, `handle.removeItems(ids)`, `handle.setItems(items)`, `handle.setItemFilter(predicate, options?)`, `handle.getItemFilter()` - **Multi-Selection & Deep-Linking**: `handle.setSelectedIds(ids)`, `handle.toggleSelectedId(id)`, `handle.clearSelection()`, `handle.getSelectedIds()`, `handle.selectItemsInScreenRect(rect, options?)`, `handle.getViewState()`, `handle.restoreViewState(state, options?)` - **Linked-View Search & Navigation**: `handle.setHighlightedIds(ids)`, `handle.getHighlightedIds()`, `handle.focusItem(itemId | null, options?)`, `handle.getFocusedItemId()`, `handle.zoomToItem(itemId, options?)` - **Client-Side Snapshot Export**: `handle.exportSvg(options?)`, `handle.exportPng(options?)` (`format: 'blob' | 'dataUrl'`, HiDPI `scale`) - **Atomic Batching & Options**: `handle.batch(fn)`, `handle.setOptions(options)` - **Hierarchical Drill-Down**: `handle.drillDownTriangle(index)`, `handle.drillDownCluster(uid)`, `handle.drillToNeighbor(neighborId)`, `handle.drillUp()`, `handle.drillToDepth(depth)`, `handle.drillToRoot()`, `handle.getZoomState()` - **Focus, Motion, Accessibility, Camera & Telemetry**: `handle.setFocusedTriangleIndex(index | null)`, `handle.setReducedMotion(pref)`, `handle.getReducedMotion()`, `handle.isReducedMotionActive()`, `handle.getKeyboardFocusTarget()`, `handle.clearKeyboardFocus()`, `handle.zoomBy(factor)`, `handle.resetCamera()`, `handle.relayout()`, `handle.getMetrics()`, `handle.getClusters()`, `handle.getLegendModel(options?)`, `handle.getTimeline()`, `handle.subscribeTimeline(listener)` --- # [API] @simplex-viz/wc (v1.0.0) Dedicated Custom Element package with zero React dependency, SSR-safe registration (@simplex-viz/wc/define), 24 reactive HTML attributes, inline JSON support, custom DOM tooltip renderers, structured legend snapshots, standard CustomEvents, and full imperative delegation. Install: `npm install @simplex-viz/wc` Entry Points: - `@simplex-viz/wc` (Browser Custom Elements & SSR-safe module imports (zero React); DOM / Host; sideEffects: false; root): Exports SimplexTopicGraphElement and SSR-safe defineSimplexTopicGraphElement() cleanly with zero side effects on import. - `@simplex-viz/wc/define` (Browser (side-effect auto-registration); DOM / Host; sideEffects: true; exclusive subpath): Exclusive side-effect subpath that automatically registers on CustomElementRegistry and exports DEFAULT_SIMPLEX_TAG_NAME. Exports: - `SimplexTopicGraphElement` [@simplex-viz/wc] (Class): `class SimplexTopicGraphElement< TItem = DefaultTaggedItem > extends HTMLElement` — Light-DOM Custom Element () mounting SimplexSvgController inside .sv-wc-stage (preserving getBBox(), webfonts, CSS inheritance, and SVG/PNG export) with pre-upgrade property preservation, 24 reactive HTML attributes, inline ``` ## Inline JSON Data (HTML-Only) For static pages, blogs, or Markdown/Astro embeds without writing imperative JavaScript, place a ` ``` ## Reactive Attributes & Standard `CustomEvent`s - **Observed Attributes (24)**: `preset`, `theme`, `renderer` (`'svg'`), `tooltip`, `aria-label`, `keyboard-navigation`, `reduced-motion`, `marquee-selection`, `shift-click-selects`, `show-zoom-breadcrumbs`, `show-hulls`, `empty-cluster-behavior`, `defer-initial-layout`, `item-filter-mode`, `touch-scroll-lock-px`, `click-tolerance-px`, `focus-on-cluster-click`, `focus-on-triangle-click`, `relayout-on-font-load`, `timeline`, `items`, `selected-ids`, `highlighted-ids`, `pinned-ids`. - **Bubbling & Composed Events**: `simplex-click` *(cancelable via `preventDefault()`)*, `simplex-hover` *(cancelable)*, `simplex-selection-change` (`{ selectedIds, ids }`), `simplex-zoom`, `simplex-timeline-change`, `simplex-metrics`, `simplex-clusters-change`, and `simplex-legend-change` (`SimplexLegendModel`). - **Imperative Methods**: `getLegendModel()`, `getTimeline()`, `subscribeTimeline()`, `getViewState()`, `restoreViewState()`, `exportSvg()`, `exportPng()`, `setSelectedIds()`, `toggleSelectedId()`, `clearSelection()`, `selectItemsInScreenRect()`, `setHighlightedIds()`, `focusItem()`, `zoomToItem()`, `setItemFilter()`, `drillDownTriangle()`, `drillDownCluster()`, `drillUp()`, `drillToRoot()`, `resetCamera()`, `zoomBy()`, `setReducedMotion()`, `batch()`, `setOptions()`, and `relayout()`. --- # [API] @simplex-viz/canvas (v1.0.0) Framework-agnostic Canvas 2D renderer with viewport frustum culling, automatic LOD simplification, HiDPI scaling, 1:4 zoom/drill-down, timeline playback, and native PNG export. Install: `npm install @simplex-viz/canvas` Entry Points: - `@simplex-viz/canvas` (Browser HTML5 Canvas 2D (Framework-agnostic, zero @simplex-viz/svg dependency); DOM / Host; sideEffects: false; root): High-capacity Canvas 2D controller & adapter, stateless snapshot painter, frustum culling, automatic LOD simplification, and native PNG export. Exports: - `createSimplexCanvas` [@simplex-viz/canvas] (Function): `createSimplexCanvas( container: HTMLElement | string, itemsOrOptions: readonly TItem[] | SimplexCanvasControllerOptions<...>, ): SimplexCanvasController<...>` — Zero-boilerplate factory mounting an interactive high-capacity Canvas 2D simplex atlas into an HTMLElement or CSS selector. - `SimplexCanvasController` [@simplex-viz/canvas] (Class): `new SimplexCanvasController< TItem, TContentVisual, TClusterVisual, TTagMeta, TClusterMeta >(container: HTMLElement | string, options: SimplexCanvasControllerOptions<...>)` — Manages ResizeObserver (with 0x0 auto-recovery & deferInitialLayout), relayoutOnFontLoad, rAF spring loop with onFpsUpdate, frustum-culled Canvas 2D rendering, hierarchical 1:4 zoom with built-in breadcrumb HUD, timeline playback bar & subscribeTimeline(), Shift+Click/Shift+Drag marquee multi-selection, WCAG 2.1 AA keyboard navigation & focus target APIs, custom DOM/HTML tooltips (SimplexDomTooltipRenderer), getLegendModel()/setOnLegendChange(), getViewState()/restoreViewState(), full atomic setOptions()/batch(), highlightedIds, onClustersChange, and native exportPng(). - `CanvasRendererAdapter` [@simplex-viz/canvas] (Class): `new CanvasRendererAdapter(options: CanvasRendererAdapterOptions)` — Low-level SimplexRendererAdapter implementing HiDPI DPR scaling, world-space viewport culling, automatic LOD simplification (lodThresholdPx), dual-layer crossfades, and pluggable CanvasNodeRenderer / CanvasTriangleRenderer / CanvasEdgeRenderer hooks. - `renderSimplexSnapshotToCanvas` [@simplex-viz/canvas] (Function): `renderSimplexSnapshotToCanvas( canvas: HTMLCanvasElement, snapshot: SimplexLayoutSnapshot, options?: RenderSimplexSnapshotToCanvasOptions, ): CanvasRenderStats` — Stateless one-shot renderer painting a pre-solved SimplexLayoutSnapshot (from solveSimplexSnapshot() or @simplex-viz/core/worker) directly onto a element. - `createCanvasPresetVisualResolver` [@simplex-viz/canvas] (Function): `createCanvasPresetVisualResolver( preset: CanvasVisualPreset, options?: CanvasPresetResolverOptions, ): VisualResolver<...>` — Creates built-in 'geometric', 'glyphs', or 'badges' visual resolvers with analytical Canvas 2D convex hull measurement. ## Overview `@simplex-viz/canvas` renders the entire simplex atlas onto a single HiDPI `` with zero per-node DOM overhead, world-space viewport frustum culling, and automatic Level-of-Detail (LOD) shape simplification for corpora of **2,000–10,000+ items** at 60 FPS. It depends exclusively on `@simplex-viz/core` (including pure preset/OKLab/timeline helpers and `@simplex-viz/core/dom` container, tooltip, breadcrumb & timeline HUD overlays, accessibility, and gesture primitives) with zero dependency on `@simplex-viz/svg`, while mirroring `SimplexSvgController`'s full interactive API (`timeline: true` shorthand, `setTimelineOptions`, `subscribeTimeline`, `showZoomBreadcrumbs`, `setZoomUiOptions`, `setOptions`, `batch`, `deferInitialLayout`, `relayoutOnFontLoad`, `onClustersChange`, `onFpsUpdate`, `SimplexDomTooltipRenderer` tooltips, `getKeyboardFocusTarget`, `getInteractiveTargets`, `restoreViewState`) and curated `@simplex-viz/core` root re-exports. ## Interactive Canvas Controller ```ts createSimplexCanvas, createCollisionDrivenLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/canvas'; const controller = createSimplexCanvas('#atlas', { items: largeCorpus, preset: 'badges', theme: 'dark', lodThresholdPx: 3.5, layoutStrategy: createCollisionDrivenLayoutStrategy(), zoomStrategy: createSubspaceZoomStrategy(), tooltip: true, }); // Inspect render culling & LOD stats for profiling: console.log(controller.getRenderStats()); // Native zero-serialization PNG export: const pngBlob = await controller.exportPng({ scale: 2 }); ``` ## Pairing with `@simplex-viz/core/worker` ```ts const worker = createSimplexWorkerClient( () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }), ); const { snapshot } = await worker.solve(largeCorpus, { width: 1200, height: 760, layoutStrategy: { kind: 'collision-driven' }, }); renderSimplexSnapshotToCanvas(canvasEl, snapshot, { theme: 'dark' }); ``` See this exact pipeline running live on 1,000–3,500 stars in the [Hertzsprung-Russell Stellar Spectral Atlas example](/examples/stellar-spectral-canvas). --- # [Example] arXiv Computer Science & Geometry Papers Domain: Academic Literature | Representation: Multi-Category Tag Hypergraph | requiresTags: true Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Soft-Simplex Tag Clustering (`createSoftSimplexTagClusteringStrategy`) Color Strategy: Theme-Adaptive OKLab (`createThemeAdaptiveOklabColorStrategy`) Layout Strategy: Collision-Local Pocket Layout (`createCollisionDrivenLayoutStrategy`) Zoom Strategy: Semantic 3→6 Tag Drill-Down (`createSemanticZoomStrategy`) ## Dataset Structure & Multi-Category Topology This example loads real publication metadata harvested from the **Cornell University arXiv.org Open-Access API** (`CC0 1.0` public-domain metadata) spanning cross-disciplinary Computer Science and Mathematics papers (`cs.CG`, `cs.GR`, `cs.HC`, `cs.LG`, `cs.CV`, `cs.RO`, `cs.AI`, and `math.MG`). Academic preprints frequently bridge two or three primary research communities—for example *Neural Radiance Fields* combining Computer Graphics (`#gr`), Computer Vision (`#cv`), and Machine Learning (`#lg`). Force-directed co-authorship or tag graphs quickly tangle into unreadable hairballs when every interdisciplinary paper connects to three or four hubs. ## Why This 5-Stage Pipeline Is Optimal Here 1. **Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`)**: Maximizes equilateral side length `s` for the current viewport aspect ratio so multi-category triangles have generous interior area. 2. **Soft-Simplex Tag Clustering (`createSoftSimplexTagClusteringStrategy`)**: Partitions subject categories into vertex topics via load-balanced QAP annealing and spreads 2- and 3-topic preprints smoothly across covering triangle interiors (`triangleSpread: 0.45`), while keeping single-category papers unconstrained in a `360°` vertex halo. 3. **Theme-Adaptive OKLab (`createThemeAdaptiveOklabColorStrategy`)**: Maintains WCAG-compliant contrast across both crisp light paper mode and dark obsidian mode while mixing interdisciplinary bridge colors in perceptual OKLab space. 4. **Collision-Local Pocket Layout (`createCollisionDrivenLayoutStrategy`)**: Leaves sparse outer categories at full `1.0x` leaf scale and shrinks only dense interdisciplinary pockets so drillable regions stand out immediately. 5. **Semantic 3→6 Tag Drill-Down (`createSemanticZoomStrategy`)**: Clicking any subdivided interdisciplinary triangle promotes vertex-exclusive secondary arXiv categories (`stat.ML`, `math.MG`, `cs.IR`, `cs.DC`) ahead of shared parent categories, pairing refined outer corners with two-line `parentContextLabel` headers while guaranteeing `6` pairwise-distinct sub-vertex badges. Reproduction Snippet: ```tsx import { SimplexTopicGraph, createAdaptiveHexMeshStrategy, createSoftSimplexTagClusteringStrategy, createThemeAdaptiveOklabColorStrategy, createCollisionDrivenLayoutStrategy, createSemanticZoomStrategy, } from '@simplex-viz/react'; paper.slug} getTags={(paper) => paper.hashtags} resolveTagMeta={(tag) => arxivTaxonomy[tag]} meshStrategy={createAdaptiveHexMeshStrategy()} clusteringStrategy={createSoftSimplexTagClusteringStrategy({ triangleSpread: 0.45, sharedTagRule: 'planar-hitting-set', anchorRule: 'explaining-away', })} colorStrategy={createThemeAdaptiveOklabColorStrategy()} layoutStrategy={createCollisionDrivenLayoutStrategy()} zoomStrategy={createSemanticZoomStrategy({ clusterZoomMode: 'incident-star', })} showZoomBreadcrumbs tooltip />; ``` --- # [Example] GitHub Visualization & WebGL Ecosystems Domain: Open-Source Software | Representation: Discrete Repository Topics | requiresTags: true Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Jaccard Annealing Clustering (`createJaccardAnnealingClusteringStrategy`) Color Strategy: OKLab Edge Contrast (`createOklabContrastColorStrategy`) Layout Strategy: Collision-Local Pocket Layout (`createCollisionDrivenLayoutStrategy`) Zoom Strategy: Semantic 3→6 Tag Drill-Down (`createSemanticZoomStrategy`) ## Ecosystem Topology & Discrete Stack Boundaries This dataset contains real public repository records queried from the **GitHub REST Search API** across the data-visualization, WebGL, GPU rendering, and network-analysis ecosystem (including projects such as `three.js`, `d3`, `apache/echarts`, `visx`, `cytoscape.js`, `deck.gl`, and `pixijs`). Each repository carries normalized technology and domain topics (`#webgl`, `#threejs`, `#svg`, `#canvas`, `#charts`, `#graph`, `#rust`, `#wasm`, `#typescript`). ## Why Jaccard QAP Annealing Excels on Curated Tech Stacks Unlike broad prose tags, software ecosystem topics exhibit sharp structural boundaries: a repository either targets `#webgl` + `#shaders`, bridges `#svg` + `#charts`, or combines `#graph` + `#canvas`. - **Jaccard Annealing Clustering (`createJaccardAnnealingClusteringStrategy`)**: Partitions repository topics via regularized Jaccard affinity, embeds co-occurring ecosystems on adjacent 60° mesh vertices via Simulated Annealing, snaps shared dual-stack libraries onto exact 1-hop edges and triangle centroids, and disambiguates sibling hubs sharing a broad umbrella topic via `disambiguatePeerClusterTitle`. - **OKLab Edge Contrast (`createOklabContrastColorStrategy`)**: Maximizes perceptual `ΔE_OK` across neighboring technology hubs so adjacent stacks remain unmistakable at a glance. - **Exclusive-First Semantic 3→6 Tag Drill-Down (`createSemanticZoomStrategy`)**: Zooming into an overlapping ecosystem triangle—such as *Visualization – Data Vis – JavaScript*—ranks assigned sub-tags by **exclusivity across the 6 sibling sub-vertices** (`#graph`, `#threejs`, `#typescript`, `#webgl`) ahead of ubiquitous carrier tags (`#javascript`, `#visualization`). Refined corners render two-line context plaques (`VISUALIZATION / Graphs · JavaScript`, `DATA VIS / TypeScript`), unchanged corners remain clean single-line capsules (`JavaScript` without redundant header stutter), and sparse neighbor midpoints fall back to explicit `A ↔ B` bridge relations. Reproduction Snippet: ```tsx import { SimplexTopicGraph, createAdaptiveHexMeshStrategy, createJaccardAnnealingClusteringStrategy, createOklabContrastColorStrategy, createCollisionDrivenLayoutStrategy, createSemanticZoomStrategy, disambiguatePeerClusterTitle, } from '@simplex-viz/react'; repo.id} getTags={(repo) => repo.topics} resolveTagMeta={(tag) => repoTagTaxonomy[tag]} deriveClusterMeta={(ctx) => ({ title: ctx.role === 'intermediate' ? (ctx.subclusterLabel ?? ctx.defaultLabel) : disambiguatePeerClusterTitle( ctx, (peer) => peer.coreTags[0]?.meta?.displayTitle ?? peer.defaultLabel, (peer) => peer.coreTags[1]?.meta?.displayTitle, ), })} meshStrategy={createAdaptiveHexMeshStrategy()} clusteringStrategy={createJaccardAnnealingClusteringStrategy({ sharedTagRule: 'planar-hitting-set', anchorRule: 'explaining-away', })} colorStrategy={createOklabContrastColorStrategy()} layoutStrategy={createCollisionDrivenLayoutStrategy()} zoomStrategy={createSemanticZoomStrategy({ clusterZoomMode: 'incident-star', })} showZoomBreadcrumbs />; ``` --- # [Example] Vega Cinema Reception & Box-Office Vectors Domain: Cinema & Media Analytics | Representation: Dual Weighted Embeddings | requiresTags: false Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Soft-Simplex Embedding Projection (`createSoftSimplexEmbeddingClusteringStrategy`) Color Strategy: Theme-Adaptive OKLab (`createThemeAdaptiveOklabColorStrategy`) Layout Strategy: Collision-Local Pocket Layout (`createCollisionDrivenLayoutStrategy`) Zoom Strategy: Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`) ## Dual Continuous Feature Modalities This example uses real feature-film records from **`vega-datasets` (`movies.json`, BSD-3-Clause)** maintained by the University of Washington Interactive Data Lab, paired with self-hosted **Public-Domain original theatrical posters from Wikimedia Commons**. Every film carries theatrical production budgets, worldwide box-office gross, runtime, IMDb ratings, vote counts, and Rotten Tomatoes critic scores—and is projected **purely from two continuous feature vectors (`requiresTags: false`)**: 1. **Audience & Critical Reception (`4D`, weight `0.65`)**: Normalized IMDb score, Rotten Tomatoes score, log-scaled audience vote volume, and critic-vs-audience consensus delta. 2. **Production & Commercial Scale (`4D`, weight `0.35`)**: Log-scaled production budget, log-scaled worldwide gross, theatrical runtime, and return-on-investment ratio. ## Contrastive Cluster Naming & Local Subspace Re-Clustering In historical film canons, discrete genre labels are heavily skewed—nearly four-fifths of acclaimed classics carry `"Drama"` as their primary genre, so naive majority-category naming would label five out of seven clusters *"Drama"*. Passing `features: cinemaFeatures` into `createSoftSimplexEmbeddingClusteringStrategy` evaluates **base-rate-aware z-scores and specificity lift** across continuous commercial and critical axes, producing seven pairwise-distinct archetypes (*Low-Budget Cult*, *Acclaimed Canon*, *Sleeper Hits*, *Roadshow Prestige*, *Critic Classics*, *Genre Curiosities*, and *Epic Runtime*). Clicking any triangle or cluster badge activates **Subspace Re-Clustering Drill-Down** (`createSubspaceZoomStrategy`): SimplexViz projects out parent traits with low local variance and re-clusters covered films across **production budget**, **release era** (*Golden Age* vs. *New Hollywood*), **theatrical runtime**, **box-office ROI**, **Rotten Tomatoes consensus**, and **genre**—preserving spatial orientation via two-line `parentContextLabel` headers on the `3` outer corners. ## Chronological Cinema Timeline (1928–1976) Use the floating timeline bar at the bottom of the canvas to **Play**, **Pause**, **Step**, or **Scrub** through `29` release-year frames spanning nearly five decades of film history—from early silent/pre-Code classics (`1928`) through post-war noir (`1944–1955`) and `1960s` roadshow epics to `1970s` New Hollywood. Because this example configures `timeline` with `autoFinalSeed: true`, `autoFinalSeedLayout: 'adaptive'`, and `emptyClusterBehavior: 'dim'`, SimplexViz automatically pins all seven cinema archetype vertices, labels, and OKLab hues via `createFinalSeededClusteringStrategy`, anchors every film to its canonical full-corpus `(x, y)` coordinate via `createFinalSeededLayoutStrategy` (with symmetric SAT-verified adaptive scaling on sparse early decades), and renders future archetype clusters dimmed until their first film enters the timeline. Reproduction Snippet: ```tsx import { SimplexTopicGraph, createAdaptiveHexMeshStrategy, createSoftSimplexEmbeddingClusteringStrategy, createThemeAdaptiveOklabColorStrategy, createCollisionDrivenLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/react'; const cinemaFeatures = [ { label: 'Gross', getValue: (f: FilmRecord) => Math.log10(f.worldwideGrossMusd), highLabel: 'Box-Office Hits', lowLabel: 'Modest Gross' }, { label: 'Budget', getValue: (f: FilmRecord) => Math.log10(f.budgetMusd), highLabel: 'Big-Budget Epics', lowLabel: 'Low-Budget Cult' }, { label: 'Runtime', getValue: (f: FilmRecord) => f.runtimeMin, highLabel: 'Epic Runtime', lowLabel: 'Compact Classics' }, { label: 'Era', getValue: (f: FilmRecord) => f.releaseYear, highLabel: 'New Hollywood', lowLabel: 'Golden Age' }, { label: 'Critics', getValue: (f: FilmRecord) => f.rottenTomatoes, highLabel: 'Critic Classics', lowLabel: 'Crowd-Pleasers' }, ]; const cinemaClustering = createSoftSimplexEmbeddingClusteringStrategy({ getEmbedding: [ { name: 'reception', getVector: (f) => f.receptionVector, weight: 0.65 }, { name: 'production', getVector: (f) => f.productionVector, weight: 0.35 }, ], features: cinemaFeatures, clusterCount: 7, metric: 'cosine', triangleSpread: 0.45, }); const cinemaZoom = createSubspaceZoomStrategy({ features: cinemaFeatures, }); film.releaseYear, stepIntervalMs: 550, autoFinalSeed: true, autoFinalSeedLayout: 'adaptive', emptyClusterBehavior: 'dim', }} showZoomBreadcrumbs />; ``` --- # [Example] UCI Deterding Spoken Vowel Formants Domain: Speech & Acoustic Phonetics | Representation: 10D LPC Log-Area Vector | requiresTags: false Mesh Strategy: Fixed Grid Lattice (`createFixedLatticeMeshStrategy`) Clustering Strategy: Planar NNLS Embedding Projection (`createEmbeddingClusteringStrategy`) Color Strategy: Theme-Adaptive OKLab (`createThemeAdaptiveOklabColorStrategy`) Layout Strategy: Uniform PBD Layout (`createPbdUniformLayoutStrategy`) Zoom Strategy: Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`) ## Vocal-Tract Acoustic Vectors This example loads real acoustic feature vectors from **David Deterding's Spoken Vowel Recognition dataset** (`Connectionist Bench`, **UCI Machine Learning Repository**, `CC BY 4.0`). Speakers uttered steady-state British English monophthongs (`i:`, `ɪ`, `ɛ`, `æ`, `ɑ:`, `ɒ`, `ɔ:`, `ʊ`, `u:`, `ʌ`, `ɜ:`), digitized with LPC reflection coefficients transformed into **10 log-area vocal-tract cross-section parameters** and rendered as SVG LPC envelope capsules (`SvgNodeView`). ## Why Fixed Lattice + Planar NNLS + Uniform PBD Fit Acoustic Calibration 1. **Fixed Grid Lattice (`createFixedLatticeMeshStrategy({ cols: 3, rows: 2 })`)**: Locks an invariant `6`-vertex vowel-formant reference chart across screen sizes so phonetic quadrants stay spatially anchored. 2. **Planar NNLS Embedding Projection & Register Disambiguation (`createEmbeddingClusteringStrategy`)**: Evaluates every planar mesh triangle `τ = (μ₁, μ₂, μ₃)` and solves exact Non-Negative Least Squares (`wᵢ ≥ 0`, `∑ wᵢ = 1`) so intermediate vowel articulations land at their minimum-residual acoustic convex combination, while `features` qualifies overlapping formant hubs by speaker vocal-tract register (*Female* vs. *Male*). 3. **Uniform PBD Layout (`createPbdUniformLayoutStrategy`)**: Disperses co-located phoneme capsules into the open interior of their covering vowel triangles while applying a single global scale factor `α` so capsule widths remain strictly proportional across the entire vowel chart with `0.0 px` overlap. 4. **Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`)**: Drilling into a broad vowel quadrant separates individual monophthong phonemes (`i:`, `ɪ`, `ɛ`, `æ`, …), speaker vocal-tract register, fundamental pitch (`F0`), and local 10D LPC residual axes while keeping parent vowel anchors visible on the `3` outer corners. Reproduction Snippet: ```tsx import { SimplexTopicGraph, createFixedLatticeMeshStrategy, createEmbeddingClusteringStrategy, createThemeAdaptiveOklabColorStrategy, createPbdUniformLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/react'; const acousticFeatures = [ { label: 'Vowel', getValue: (rec: VowelRecording) => `Vowel ${rec.ipaSymbol}` }, { label: 'Speaker Sex', getValue: (rec: VowelRecording) => `${rec.speakerSex} Voice` }, { label: 'Pitch', getValue: (rec: VowelRecording) => rec.pitchHz, highLabel: 'High Pitch', lowLabel: 'Low Pitch' }, ]; rec.lpcVector, features: acousticFeatures, clusterCount: 6, })} colorStrategy={createThemeAdaptiveOklabColorStrategy()} layoutStrategy={createPbdUniformLayoutStrategy()} zoomStrategy={createSubspaceZoomStrategy({ features: acousticFeatures, getVector: (rec) => rec.lpcVector, })} showZoomBreadcrumbs />; ``` --- # [Example] UCI Zoo Animal Morphology Kernel Domain: Comparative Biology | Representation: Pairwise Similarity Kernel S(a, b) | requiresTags: false Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Pairwise k-Medoids Projection (`createSimilarityClusteringStrategy`) Color Strategy: OKLab Edge Contrast (`createOklabContrastColorStrategy`) Layout Strategy: Collision-Local Pocket Layout (`createCollisionDrivenLayoutStrategy`) Zoom Strategy: Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`) ## Coordinate-Free Similarity Kernels Many scientific and enterprise domains lack clean Euclidean vectors or curated hashtag vocabularies, offering instead a **domain-specific pairwise similarity function `S(a, b) ∈ [0, 1]`** (such as edit distance over biological sequences, Gower similarity across mixed boolean/categorical records, or graph-edit kernels). This example loads all **101 named animal species** from **Richard S. Forsyth's UCI Zoo dataset** (`CC BY 4.0`)—rendered with self-hosted **Wikimedia Commons species photographs**—spanning mammals, birds, reptiles, fish, amphibians, insects, and marine invertebrates across 16 anatomical and ecological attributes (`hair`, `feathers`, `eggs`, `milk`, `airborne`, `aquatic`, `predator`, `toothed`, `backbone`, `breathes`, `venomous`, `fins`, `legs`, `tail`, `domestic`, `catsize`). ## How PAM k-Medoids Anchors Real Species Exemplars - **Pairwise k-Medoids Projection & Ecological Disambiguation (`createSimilarityClusteringStrategy`)**: Rather than averaging boolean traits into synthetic centroids, **Partitioning Around Medoids (PAM)** selects *actual species* (such as *Dolphin*, *Eagle*, or *Frog*) as cluster medoids `m₁★ … m_K★` and embeds them onto adjacent 60° mesh vertices via QAP annealing. Peer-aware trait disambiguation distinguishes multiple mammalian or invertebrate medoids automatically (*Carnivores*, *Marine Mammals*, *Mammals · Small*, *Birds*, *Fish*, *Insects*, *Marine Fauna*). - **Subspace Re-Clustering Over the 16 UCI Traits (`createSubspaceZoomStrategy`)**: Once you zoom into a *Mammals* or *Birds* triangle, traits that are locally constant (`σ_local = 0`, such as `milk = true` and `backbone = true` across all mammals) vanish automatically, allowing intra-class UCI attributes (`predator`, `catsize`, `aquatic`, `legs`, `domestic`, `airborne`) to re-partition the `1:4` sub-mesh while outer corners preserve their parent clade header (`CARNIVORES / Cat-Sized`). Reproduction Snippet: ```tsx import { SimplexTopicGraph, createAdaptiveHexMeshStrategy, createSimilarityClusteringStrategy, createOklabContrastColorStrategy, createCollisionDrivenLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/react'; computeGowerTraitSimilarity(a.traits, b.traits), features: uciZoo16TraitFeatures, })} colorStrategy={createOklabContrastColorStrategy()} layoutStrategy={createCollisionDrivenLayoutStrategy()} zoomStrategy={createSubspaceZoomStrategy({ features: uciZoo16TraitFeatures, getSimilarity: (a, b) => computeGowerTraitSimilarity(a.traits, b.traits), clusterZoomMode: 'incident-star', })} showZoomBreadcrumbs />; ``` --- # [Example] Palmer Station Antarctic Penguin Morphometrics Domain: Ecological Morphometrics | Representation: 6D Standardized Biometric Vector | requiresTags: false Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Soft-Simplex Embedding Projection (`createSoftSimplexEmbeddingClusteringStrategy`) Color Strategy: Custom Brand Palette (`createPaletteColorStrategy`) Layout Strategy: Density-Adaptive Layout (`createLocalAdaptiveLayoutStrategy`) Zoom Strategy: Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`) ## Morphological Gradients Without Species Labels This example uses real field measurements collected by **Dr. Kristen Gorman and the Palmer Station Antarctica LTER** (`penguins.json`, released under **`CC0 1.0`**). Each specimen records exact culmen (bill) length and depth in millimeters, flipper length, body mass in grams, and island habitat (*Biscoe*, *Dream*, *Torgersen*) across *Adelie*, *Chinstrap*, and *Gentoo* populations—without passing species labels to the clustering solver (`requiresTags: false`). ## Highlighting Custom Brand Palette & Density-Adaptive Scaling 1. **Soft-Simplex Embedding Projection & Intra-Species Disambiguation (`createSoftSimplexEmbeddingClusteringStrategy`)**: Uncovers morphological archetypes purely from standardized 6D biometric measurements. Because *Adélie* and *Chinstrap* populations exhibit pronounced sexual dimorphism across culmen depth and body mass, each splits naturally into two clusters—which `features` automatically disambiguates via intra-species secondary contrast (*Adélie · Male* vs. *Adélie · Female*, *Chinstrap · Male* vs. *Chinstrap · Female*) alongside *Gentoo*. 2. **Custom Brand Palette (`createPaletteColorStrategy`)**: Demonstrates mapping a curated 6-swatch scientific publication palette (`#0891b2`, `#d97706`, `#c026d3`, `#059669`, `#2563eb`, `#e11d48`) onto mesh vertices using `'edge-contrast'` optimization while still interpolating hybrid specimens in perceptual OKLab space. 3. **Density-Adaptive Layout (`createLocalAdaptiveLayoutStrategy`)**: Fans congested specimen pockets into open covering triangles first, evaluates smooth radial crowd density within `76 px` on the dispersed coordinates, and polishes collisions locally so sparse specimens stay at full `1.0x` scale while dense species hubs taper smoothly. 4. **Subspace Re-Clustering Drill-Down (`createSubspaceZoomStrategy`)**: Zooming into a species-dominated triangle projects out the shared species baseline (`σ_local = 0`) and splits specimens locally by **island habitat** (*Biscoe*, *Dream*, *Torgersen*), **sexual dimorphism**, **body mass**, and **culmen geometry** while retaining two-line `parentContextLabel` corner plaques. Reproduction Snippet: ```tsx import { SimplexTopicGraph, createAdaptiveHexMeshStrategy, createSoftSimplexEmbeddingClusteringStrategy, createPaletteColorStrategy, createLocalAdaptiveLayoutStrategy, createSubspaceZoomStrategy, } from '@simplex-viz/react'; const scientificPalette = [ '#0891b2', '#d97706', '#c026d3', '#059669', '#2563eb', '#e11d48', ]; const penguinFeatures = [ { label: 'Species', getValue: (p: PenguinSpecimen) => p.species, weight: 1.5 }, { label: 'Sex', getValue: (p: PenguinSpecimen) => p.sex, weight: 1.2 }, { label: 'Island', getValue: (p: PenguinSpecimen) => `${p.island} Isl.` }, { label: 'Body Mass', getValue: (p: PenguinSpecimen) => p.bodyMassG, highLabel: 'Heavy Mass', lowLabel: 'Light Mass' }, { label: 'Bill Length', getValue: (p: PenguinSpecimen) => p.billLengthMm, highLabel: 'Long Bill', lowLabel: 'Short Bill' }, ]; p.morphVector, features: penguinFeatures, clusterCount: 5, triangleSpread: 0.45, })} colorStrategy={createPaletteColorStrategy(scientificPalette, { mode: 'edge-contrast', })} layoutStrategy={createLocalAdaptiveLayoutStrategy()} zoomStrategy={createSubspaceZoomStrategy({ features: penguinFeatures, getVector: (p) => p.morphVector, })} showZoomBreadcrumbs />; ``` --- # [Example] Hertzsprung-Russell Stellar Spectral Atlas (Canvas + Worker) Domain: High-Capacity Astrophysics | Representation: 8D Float32Array · Canvas 2D + Worker | requiresTags: false Mesh Strategy: Adaptive Hex Lattice (`createAdaptiveHexMeshStrategy`) Clustering Strategy: Soft-Simplex Embedding Projection (`createSoftSimplexEmbeddingClusteringStrategy`) Color Strategy: Theme-Adaptive OKLab (`createThemeAdaptiveOklabColorStrategy`) Layout Strategy: Uniform PBD Layout (`createPbdUniformLayoutStrategy`) Zoom Strategy: Continuous Free Camera (`createFreeCameraZoomStrategy`) ## Off-Main-Thread Solving + 60 FPS Canvas 2D Rendering When a dataset grows beyond a few hundred interactive SVG nodes into **thousands of records**, two bottlenecks emerge in browser apps: running iterative QAP annealing and PBD collision relaxation synchronously on the UI thread, and mutating thousands of DOM/SVG elements during pan and zoom. This example pairs **`@simplex-viz/core/worker`** with **`@simplex-viz/canvas`** to keep the main thread completely fluid across **1,000**, **2,000**, and **3,500** stars modeled on the **Morgan–Keenan / Hertzsprung–Russell (H–R)** spectral sequence and evolutionary branches (*O–M Main Sequence*, *Red Giants*, *Yellow & Red Supergiants*, *Hot White Dwarfs*, and *Halo Subdwarfs*). ## Architecture Highlights 1. **Zero-Copy Worker Handoff (`createSimplexWorkerClient` + `attachSimplexWorkerHandler`)**: Each star carries an 8D astrophysical `Float32Array` embedding (`log Teff`, `log L`, `log R`, `log M`, `B−V`, `[Fe/H]`, `log Age`, `log g`). With `transferEmbeddings: true`, `SimplexWorkerClient` transfers standalone `ArrayBuffer`s across the Worker boundary without JSON cloning, solves the full 12-cluster Soft-Simplex triangulation off-thread, and rehydrates your original main-thread `StellarRecord` objects on return. 2. **Automatic Stale-Generation Cancellation**: Toggle rapidly between **`1,000`**, **`2,000`**, and **`3,500`** stars in the bottom bar—`cancelPreviousByDefault: true` supersedes earlier in-flight generations automatically while keeping the previous Canvas snapshot interactive at 60 FPS until the newest snapshot settles. 3. **Frustum Culling & Automatic Level-of-Detail (`CanvasRendererAdapter`)**: At overview magnification, `lodThresholdPx: 3.5` collapses sub-threshold stars into single-pass flat fills; as you zoom smoothly (wheel, pinch, double-click, or `−`/`+` stepper) or click a cluster badge or simplex triangle to frame it, visible stars upgrade to full geometric shapes (circles for core stars, diamonds for 2-population bridges, and stars for 3-cluster hybrids) while off-screen stars are culled before touching the Canvas 2D context. 4. **Zero-Relayout Cluster & Star Inspection**: Clicking a cluster badge frames that stellar population and opens its Cluster Inspector (core vs. hybrid breakdown and representative stars); clicking any star inspects its astrophysical parameters and barycentric simplex weights inside the container-query side drawer without altering the Canvas stage dimensions or triggering a worker re-solve. Reproduction Snippet: ```tsx // 1. simplex.worker.ts (dedicated Vite ES module Web Worker) import { attachSimplexWorkerHandler } from '@simplex-viz/core/worker'; attachSimplexWorkerHandler(); // 2. Main thread: off-thread solve + high-capacity Canvas 2D rendering import { createSimplexWorkerClient, isSimplexWorkerCancelledError, } from '@simplex-viz/core/worker'; import { CanvasRendererAdapter, renderSimplexSnapshotToCanvas, } from '@simplex-viz/canvas'; const workerClient = createSimplexWorkerClient( () => new Worker(new URL('./simplex.worker.ts', import.meta.url), { type: 'module' }), { cancelPreviousByDefault: true, fallbackToInThread: true }, ); // Solve 2,000+ stars off the main thread with zero-copy Float32Array handoff const { snapshot } = await workerClient.solve(stellarCatalog, { getId: (star) => star.id, getEmbedding: (star) => new Float32Array(star.embedding), transferEmbeddings: true, width: canvas.clientWidth, height: canvas.clientHeight, itemRadius: 2.4, clusterRadius: 20, theme: 'dark', meshStrategy: { kind: 'adaptive-hex' }, clusteringStrategy: { kind: 'soft-simplex-embedding', metric: 'cosine', clusterCount: 12, triangleSpread: 0.82, balanceLoad: true, }, colorStrategy: { kind: 'theme-adaptive-oklab' }, layoutStrategy: { kind: 'pbd-uniform' }, layoutOptions: { itemGapPx: 0.85, relaxationIterations: 12 }, }); // Paint snapshot onto HiDPI Canvas 2D with automatic LOD & frustum culling renderSimplexSnapshotToCanvas(canvas, snapshot, { theme: 'dark', lodThresholdPx: 3.5, devicePixelRatio: Math.min(window.devicePixelRatio || 1, 2), }); ``` --- # [Note] SimplexViz 1.0: Five Synchronized Packages & Strict Subpath Boundaries (2026-11-22) Releasing v1.0.0 across @simplex-viz/core, @simplex-viz/svg, @simplex-viz/canvas, @simplex-viz/react, and @simplex-viz/wc—introducing @simplex-viz/core/dom, canonical subpaths, and CI contract enforcement. Key Takeaways: - All five packages (@simplex-viz/core, @simplex-viz/svg, @simplex-viz/canvas, @simplex-viz/react, @simplex-viz/wc) ship in lockstep at v1.0.0 with zero internal circular dependencies. - A new zero-dependency @simplex-viz/core/dom subpath unifies container resizing, ARIA announcers, tooltips, gestures, and zoom math across SVG, Canvas, React, and Web Components while preserving an ES2022 DOM-free root. - Specialized entrypoints (@simplex-viz/core/worker, @simplex-viz/core/dom, @simplex-viz/svg/ssr, @simplex-viz/wc/define) are strictly canonical and verified by automated TypeScript declaration tests in CI. SimplexViz **1.0.0** is live across all five packages of the monorepo: `@simplex-viz/core`, `@simplex-viz/svg`, `@simplex-viz/canvas`, `@simplex-viz/react`, and `@simplex-viz/wc`. Rather than rushing into `1.0.0` immediately after adding Canvas 2D and Web Components, we spent the final milestone consolidating the architecture so every layer is clean, predictable, and safe to depend on long term. ## 1. Five Synchronized Packages Under One Mental Model Whether you build with plain HTML, Astro, Vue, Svelte, React 19, Canvas 2D, or Node.js servers, the entire SimplexViz stack now shares one unified vocabulary and synchronized `1.0.0` version: - **`@simplex-viz/core`**: The zero-dependency, DOM-free `ES2022` engine (hex triangulation, clustering, OKLab color science, convex SAT collision physics, `1:4` drill-down, timelines)—plus opt-in `@simplex-viz/core/worker` and `@simplex-viz/core/dom`. - **`@simplex-viz/svg`**: Framework-agnostic interactive SVG scene graph, pluggable node/triangle/edge views, client SVG/PNG snapshot export, and zero-DOM `@simplex-viz/svg/ssr`. - **`@simplex-viz/canvas`**: High-capacity HTML5 Canvas 2D renderer for 2,000–10,000+ items at 60 FPS with frustum culling, automatic LOD, and zero dependency on `@simplex-viz/svg`. - **`@simplex-viz/react`**: Type-safe React 18/19 ``, headless JSX renderers, edge-flipping JSX tooltips, `useSimplexGraphController()`, and `useSimplexTimeline()`. - **`@simplex-viz/wc`**: A dedicated framework-agnostic `` Web Component with zero React dependency, Light-DOM CSS/webfont compatibility, inline `