Open Plant WSI
Reference

Public API Surface

All items below are exported from src/index.ts.

`WsiViewerCanvas` props

NameTypeDescription
sourceWsiImageSource | nullImage source metadata.
authTokenstringAuthorization header token when required.
viewStatePartial<WsiViewState>Controlled zoom/offset/rotation state (rotationDeg).
onViewStateChange(next) => voidCamera state callback.
imageColorSettingsWsiImageColorSettings | nullTile-only brightness/contrast/saturation input ([-100, 100]). Point/ROI/draw overlay colors are unaffected.
onStats(stats: WsiRenderStats) => voidPer-frame observability event. Includes tile/point counters plus queue/failure/cache-hit metrics and frame time.
onTileError(event) => voidTile load failure callback with tile info, error object, and retry attempt count.
onContextLost() => voidCalled when WebGL context is lost and render loop is paused.
onContextRestored() => voidCalled after renderer rebuilds GPU state on context restore.
debugOverlaybooleanEnables built-in runtime debug HUD overlay. Default: false.
debugOverlayStyleCSSPropertiesStyle override for the built-in debug HUD.
fitNoncenumberRe-triggers fit-to-image when changed.
rotationResetNoncenumberCalls rotation reset when changed.
ctrlDragRotatebooleanEnables Ctrl/Cmd + drag rotate interaction. Default: true.
minZoomnumberMinimum zoom override. If omitted, renderer uses fitZoom * 0.5. Applied to wheel, double-click, setViewState, and fitToImage.
maxZoomnumberMaximum zoom override. If omitted, renderer uses fitZoom * 8.
viewTransition{ duration?: number; easing?: (t) => number }Default camera transition for view updates. Duration is clamped to 0..2000ms.
zoomSnapsnumber[]Magnification snap stops (for example [1.25, 2.5, 5, 10, 20, 40]). Internally normalized with source.mpp.
zoomSnapFitAsMinbooleanIf true, snap-out treats fit zoom as the lower bound.
pointDataWsiPointData | nullPoint position + palette index buffers (optional ids supported for point hit-test).
pointPaletteUint8Array | nullRGBA palette texture data.
pointSizeByZoomRecord<number, number>Custom point size(px) stops by continuous zoom level. Values between stops are linearly interpolated.
pointStrokeScalenumberPoint ring stroke thickness scale.
pointInnerFillOpacitynumberPoint inner fill opacity in range 0..1.
roiRegionsWsiRegion[]Persisted ROI list with labels.
roiPolygonsDrawCoordinate[][]Simplified polygon-only ROI input.
clipPointsToRoisbooleanRender only points inside ROI polygons.
clipMode"sync" | "worker" | "hybrid-webgpu"ROI clip execution mode. Default is "worker".
onClipStats(event) => voidClip timing/result callback: mode, duration, input/output count, WebGPU usage, and draw-bridge flag (bridgedToDraw).
onRoiPointGroups(stats) => voidROI term count callback derived from current points + regions.
roiPaletteIndexToTermIdReadonlyMap<number,string> | string[]Optional palette-index to term-id map used by ROI term group callback.
interactionLockbooleanLocks pan/zoom interactions.
drawTool"cursor" | "freehand" | "rectangle" | "circular" | "brush" | StampDrawToolActive draw tool. stamp-rectangle-4096px emits patch intent. Brush emits intent: "brush" on completion.
stampOptions{ rectangleAreaMm2?: number; circleAreaMm2?: number; rectanglePixelSize?: number }Stamp size configuration from outside the library. Defaults are 2mm² for area stamps and 4096px for fixed-pixel rectangle stamp.
brushOptionsBrushOptionsBrush radius/detail/smoothing/cursor options. Radius is HTML/CSS px and stays zoom-invariant on screen.
drawFillColorstringPreview fill color for freehand/rectangle/circular while drawing. Default: transparent.
patchRegionsWsiRegion[]Patch-only persisted polygons rendered independently from ROI selection/hover state.
patchStrokeStylePartial<RegionStrokeStyle>Patch-only stroke style override (default: dashed cyan).
regionStrokeStylePartial<RegionStrokeStyle>Persisted region stroke override.
regionStrokeHoverStylePartial<RegionStrokeStyle>Stroke override while hovering a region.
regionStrokeActiveStylePartial<RegionStrokeStyle>Stroke override for active region (including shadow).
resolveRegionStrokeStyle(context) => Partial<RegionStrokeStyle>Per-region/per-state dynamic stroke resolver.
resolveRegionLabelStyle(context) => Partial<RegionLabelStyle>Per-region dynamic label style resolver (for zoom-aware offsetY etc).
overlayShapesDrawOverlayShape[]Custom overlay shapes rendered by DrawLayer (supports polygon stroke and inverted-fill mask).
customLayersWsiCustomLayer[]Custom React overlay layer slots with world/screen converters and redraw trigger.
regionLabelStylePartial<RegionLabelStyle>Persisted region label override.
regionLabelAnchor"top-center" | "centroid"Label anchor mode used for hit area and placement.
drawAreaTooltipDrawAreaTooltipOptionsRealtime mm² tooltip during freehand/rectangle/circular drawing.
autoLiftRegionLabelAtMaxZoombooleanWhen true, labels animate upward by 20px when view reaches maxZoom and animate back when leaving max zoom.
clampRegionLabelToViewportbooleanClamps region labels to viewport bounds.
onPointerWorldMove(event) => voidWorld-coordinate pointer stream callback for custom coordinate HUD.
onPointHover(event) => voidNearest point hover event in cursor mode. Emits index/id or null when no hit.
onPointClick(event) => voidNearest point click event in cursor mode (left/right button info included).
getCellByCoordinatesRefMutableRefObject<(coord) => PointHitEvent | null>Imperative world-coordinate point hit-test resolver.
onRegionHover(event) => voidRegion hover event in cursor mode.
onRegionClick(event) => voidRegion click event in cursor mode.
activeRegionIdstring | number | nullControlled active region id. If omitted, component runs in uncontrolled mode.
onActiveRegionChange(regionId) => voidActive region changed event. Default behavior toggles off when clicking the same region, and clears on empty-space click.
onDrawComplete(result) => voidDraw completion callback payload with intent: "roi" | "patch" | "brush".
onPatchComplete(result) => voidPatch-only callback, emitted for stamp-rectangle-4096px.
overviewMapConfigOverviewMapConfigOverview map toggles/options/styles.
classNamestringRoot container class name.
styleCSSPropertiesRoot container style.
Region hit-test in cursor mode is constrained to contour + label area. Region interior fill is intentionally excluded.
Tile color correction normalization: brightness / 200, contrast / 100, saturation / 100. It applies to tile shader only.

`DrawLayer` and shape utilities

ExportDescription
DrawLayerStandalone draw overlay canvas component.
closeRing(coords)Closes polygon by repeating first coordinate at the end.
createRectangle(start, end)Generates closed rectangle coordinates.
createCircle(start, end)Generates circle polygon coordinates.
DrawResult{ tool, intent, coordinates, bbox, areaPx } where intent is "roi", "patch", or "brush".
PatchDrawResultPatch-specialized draw payload for stamp-rectangle-4096px.
DrawRegion{ id?, coordinates, label? }
DrawIntentIntent union used by draw completion ("roi" | "patch" | "brush").
DrawOverlayShape{ id?, coordinates, closed?, fill?, stroke?, strokeStyle?, invertedFill?, visible? } where coordinates accepts DrawCoordinate[], DrawCoordinate[][], or DrawCoordinate[][][] (single ring, multi-ring, or multi-polygon).
DrawOverlayInvertedFillStyle{ fillColor: string } fill style for inverted mask outside polygons.
BrushOptionsBrush radius/detail/smoothing/cursor config. radius is HTML/CSS px (screen-fixed), while output geometry is converted to world coordinates per zoom.
RegionStyleContextState payload for resolveRegionStrokeStyle (default/hover/active).
RegionLabelStyleContextResolver context payload (region, regionId, regionIndex, zoom).
RegionLabelStyleResolverDynamic label resolver used by resolveRegionLabelStyle.
StampOptionsStamp options for mm² and fixed pixel rectangle size.
RegionStrokeStyleColor/width/dash/cap/join + shadow (color/blur/offset) fields.
RegionLabelStyleTypography/background/padding/offset/border fields for persisted labels.
DrawAreaTooltipOptionsRealtime area tooltip options (enabled, format, style, cursorOffset).
DrawAreaTooltipStyleTooltip typography/background/padding style fields used during drawing.

`TileViewerCanvas` props

NameTypeDescription
imageWidthnumberSource image width in pixels.
imageHeightnumberSource image height in pixels.
tilesTileDefinition[]M1 tile definition list.
viewStatePartial<ViewState>Optional controlled camera state.

Core types

interface WsiImageSource {
  id: string;
  name: string;
  width: number;
  height: number;
  mpp?: number;
  tileSize: number;
  maxTierZoom: number;
  tilePath: string;
  tileBaseUrl: string;
  terms: WsiTerm[];
  tileUrlBuilder?: (tier: number, x: number, y: number) => string;
}

interface WsiPointData {
  count: number;
  positions: Float32Array;
  paletteIndices: Uint16Array;
  fillModes?: Uint8Array; // optional fill mode per point (0: ring, 1: solid)
  ids?: Uint32Array; // optional point ids for hit-test/cell actions
  drawIndices?: Uint32Array; // optional draw bridge (subset indices)
}

interface WsiViewState {
  zoom: number;
  offsetX: number;
  offsetY: number;
  rotationDeg: number;
}

interface WsiRenderStats {
  tier: number;
  visible: number;
  rendered: number;
  fallback: number;
  points: number;
  cache: number;
  inflight: number;
  queued?: number;
  retries?: number;
  failed?: number;
  aborted?: number;
  cacheHits?: number;
  cacheMisses?: number;
  drawCalls?: number;
  frameMs?: number;
}

API Stability Policy (WS-10)

SemVer: patch = bug fixes, minor = backward-compatible additions, major = breaking changes.
Deprecation lifecycle: add replacement first, mark deprecated in docs, keep compatibility for at least two minor releases, remove only in the next major.
Migration contract: every breaking change must ship with before/after examples and a checklist.
Known limitations: browser-interaction E2E (real pan/zoom/draw automation) is not yet fully covered in CI.
For upgrade steps and before/after snippets, see Migration Guide.

Utility exports

FunctionDescription
normalizeImageInfo(raw, tileBaseUrl)Converts backend payload + tile base URL to WsiImageSource.
toTileUrl(source, tier, x, y)Builds IMS tile URL.
buildTermPalette(terms)Builds termId to palette mapping and RGBA texture.
filterPointDataByPolygons(data, polygons)Filters points inside ROI polygons only.
filterPointDataByPolygonsInWorker(data, polygons)Runs ROI clipping in a dedicated worker thread.
terminateRoiClipWorker()Terminates the shared ROI clip worker instance (useful on teardown/tests).
filterPointIndicesByPolygons(data, polygons)Returns original point indices inside polygons for patch JSON export pipelines.
filterPointIndicesByPolygonsInWorker(data, polygons)Worker variant returning point indices + timing metadata.
filterPointDataByPolygonsHybrid(data, polygons, options?)Experimental hybrid clipping (WebGPU bbox prefilter + exact polygon test). Use { bridgeToDraw: true } to return full buffers + drawIndices bridge payload.
computeRoiPointGroups(pointData, regions, options)Computes per-ROI term counts (roiPointGroups-style) from typed point buffers.
getWebGpuCapabilities()Returns WebGPU support/adapter/features for runtime decisions.
prefilterPointsByBoundsWebGpu(positions, count, bounds)Experimental compute pass to classify points by ROI bounding boxes.
calcScaleResolution(imageMpp, imageZoom, currentZoom)Returns microns-per-screen-pixel for the current zoom.
calcScaleLength(imageMpp, imageZoom, currentZoom)Formats a 100px scale-bar label in μm/mm.
toBearerToken(token)Normalizes token to Bearer ... format.
What is mpp? mpp means microns per pixel at native pyramid level (maxTierZoom). Stamp physical size depends on this value. If mpp is missing, the renderer falls back to 1μm/px assumption, so physical size is only approximate.