JavaScript API Reference
The public surface of @jolars/eunoia. This page catalogs the exported functions and their options; the shipped TypeScript definitions remain the exhaustive, field-level source. New here? Start with the JavaScript quickstart.
All functions are pure (no shared state) and synchronous, except init() on the ./web entry, which must be awaited once before fitting.
euler(options)
Fits an area-proportional Euler diagram from set sizes and returns a Layout.
const = ;
Option | Type | Default | Meaning |
|---|---|---|---|
|
| (required) | Sizes keyed by combination expression ( |
|
|
| Whether values are exclusive pieces or full set unions. |
|
|
| Shape family to fit with. |
|
|
| What the |
|
| — | RNG seed for reproducible fits. |
|
| core default | Optimization algorithm (see below). |
|
| optimizer's | Region-error loss function. |
|
|
| Finite, nonnegative convergence tolerance; see below. |
|
|
| Random restarts of the two-phase fit; lowest loss is kept. |
|
|
| Vertices per polygon outline ( |
|
| — | Items outside every set; fits a bounding container. See Complement. |
Optimizer is one of "cmaEsBoundedLm", "cmaEsLm", "cmaEs", "levenbergMarquardt", "boundedLevenbergMarquardt", "lbfgs", or "nelderMead". The default for shapes with analytic gradients is "cmaEsBoundedLm", which uses an LM baseline, a bounded LM retry, and CMA-ES escape with bounded LM polishing when needed. "cmaEsTrf" and "trf" remain accepted as deprecated synonyms for "cmaEsBoundedLm" and "boundedLevenbergMarquardt", respectively.
LossType is one of "sumSquared", "sumAbsolute", "sumAbsoluteRegionError", "sumSquaredRegionError", "maxAbsolute", "maxSquared", "rootMeanSquared", "stress", "diagError". The defaults match the Rust core and are what you want unless you are deliberately exploring; see the Fitter Pipeline chapter.
Rotated rectangles use derivative-free Nelder–Mead and CMA-ES by default because their exact polygon overlap areas do not supply analytical gradients.
For final-layout unbounded LM stages, tolerance controls relative model reduction: both the actual and predicted cost reductions must be small before this test stops the solver. Zero disables that test. For L-BFGS, it controls the absolute gradient norm and cost change. Bounded LM, CMA-ES, and Nelder-Mead stages ignore this option. Invalid tolerances throw an error.
venn(options)
Lays out a canonical n-set Venn diagram (fixed template, not proportional—set sizes are ignored). Returns a Layout.
const = ; // 1 ≤ n ≤ 5
Option | Type | Default | Meaning |
|---|---|---|---|
|
| (required) | Number of sets. |
|
|
| Shape family. |
|
|
| What the |
|
|
| Vertices per outline. |
|
| — | Optional complement container. |
Only "ellipse" reaches n = 5; "circle" gives the classic 1–3-circle diagrams, and "square"/"rectangle" are axis-aligned and cap at n = 3. "rotatedRectangle" supports n = 1..4.
The Layout Object
Both euler and venn return a Layout, a union discriminated on mode, which follows the output option:
|
| Carries |
|---|---|---|
|
| The selected shape's geometric parameters, listed below. |
|
| the shapes plus |
|
|
|
Every Layout also carries:
shape: the shape family used ("circle","ellipse", …).metrics:{ loss, stress, diagError, iterations, targetAreas, fittedAreas, regionError, residuals }. See Goodness of Fit.container: present only whencomplementwas set:{ x, y, width, height }.
In "shapes" and "polygons" modes, shape selects the array of primitives:
| Array | Geometry fields |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Each primitive also has a label and a labelAnchor. For ellipses and rotated rectangles, rotation is in radians, counterclockwise from the positive x-axis; the axis lengths describe the shape before rotation.
Each shape and region carries a labelAnchor ({ x, y }) for interior labels; "regions" mode adds setAnchors and shapeOutlines. The latter is one closed ring per set — the set's own silhouette, which region decomposition clips away and so cannot be recovered from regions without a union pass. Use it for seam-free per-set strokes, or to feed placeSetLabels. Coordinates are abstract, centered units—compute a bounding box for your viewBox.
placeLabelsForRegions(options)
Places one label per region, choosing interior or exterior positions (with leader lines) based on whether each region can hold its measured label. Returns Record<string, LabelPlacement> keyed by combination.
const = ;
sizes are the measured label dimensions in diagram units, which usually means a render → measure → re-place loop. The strategy knobs (leader, precision, tether, leaderGap) and that loop are covered in Label Placement.
All three straight strategies refine exit directions to reduce traversal through other regions, including regions without labels. The refinement preserves label clearance and matched angular order; enclosed sources can require some traversal. Elbow leaders use their separate column placement.
placeSetLabels(options)
Places one label per set, just outside that set's own shape and with no leader line — the label is adjacent to the thing it names. Returns Record<string, LabelPlacement> keyed by set name, every entry with kind: "exteriorSet".
const = ;
Each label rotates around its shape to the angle with the most clearance to the other sets' outlines, the labels already placed, and any strategy.obstacles. For nested sets, the sweep favors keeping the inner label inside the enclosing outline, clear of its boundary. Shape clearance remains best-effort when space is tight or the collision guard moves a label. Label boxes never overlap each other; clearance from the shapes is best-effort. The knobs (margin, angularSteps, obstacles, precision) and the algorithm are covered in Label Placement.
placementsBbox(options)
Returns the bounding box ({ x, y, width, height }, or undefined) enclosing a set of placed label boxes; useful for extending the viewport so exterior labels aren't clipped.
placeGlyphsForRegions(options)
Packs equally-sized circular glyphs—one mark per data unit, eulerGlyphs-style—inside each region. Returns { radius, positions, unplaced? }: the single diagram-wide radius plus the glyph centers per combination.
const = ;
Omit options.radius to auto-size the glyphs (largest radius at which every region holds its count). Arrangements, the gap knob, and the fixed-radius overflow behavior are covered in Glyphs. Pass the result straight to the SVG serializer via ToSvgOptions.glyphs.
options.obstacles takes keep-out boxes ({ x, y, width, height }, center plus full extents) that glyph centers steer clear of—see Label keep-out.
Set options.obstaclePolicy to "strict" to require obstacle clearance and report overflow in unplaced, including with automatic sizing. The default "bestEffort" permits overlap when the glyphs do not fit. Both policies keep the automatic radius floor of half the radius chosen without obstacles.
placeGlyphBoxesForRegions(options)
Packs per-item text boxes—member names—inside each region. The rectangular-footprint sibling of placeGlyphsForRegions: hand it the { w, h } you measured for every item and it returns { scale, boxes, unplaced? }—one centered { x, y, width, height } per item, plus the single diagram-wide factor those boxes were packed at.
const = ;
const = ;
const = ;
// Render your text at `fontSize * placed.scale`.
Omit options.scale to auto-fit. Auto-scale only ever shrinks (the bracket is [minScale, 1], default floor 0.35), since you own the reference font size—deliberately asymmetric with the disc packer, which grows to fill.
Set options.targetAspectRatio to a positive width-to-height ratio to balance uniform rows. For example, 1 favors a roughly square occupied block, including its halo. The packer maximizes the placed prefix before choosing the closest candidate ratio, keeping boundary, hole, and obstacle clearance. This preference does not change automatic scale selection. Omitted, non-positive, or non-finite values keep the first complete packing; "random" ignores it. Raw WASM JSON uses the same targetAspectRatio name.
boxes[combo] is a prefix of sizes[combo], so boxes[combo][i] belongs to your labels[combo][i]. Pass the result plus the strings to the SVG serializer via ToSvgOptions.glyphBoxes. options.obstacles takes the same keep-out boxes as placeGlyphsForRegions, and options.obstaclePolicy accepts "bestEffort" (default) or "strict". Strict mode reports overflow while preserving minScale, the floor of half the obstacle-free scale, and input order. See Member labels.
labelObstacles(options)
Turns a placeLabelsForRegions result plus the sizes you measured into the keep-out boxes placeGlyphsForRegions expects, each padded by an optional padding on every side. Pure JS—no WebAssembly call.
const = ;
const = ;
SVG Serializer: @jolars/eunoia/svg
A wasm-free, DOM-free entry that turns a Layout into SVG. It never touches WebAssembly, so it works during server-side rendering and from a CDN as-is.
document.. = ;
toSvg(layout, opts?): a complete standalone<svg>document string.svgBody(layout, opts?): inner markup only, when you own the<svg>element.viewBox(layout, opts?): the{ x, y, w, h }viewBox for a layout.boundingBox(layout, opts?): geometry bounds, including exterior labels when placements + sizes are supplied.polygonPath,regionPath,leaderPath: SVGdpath builders.Color helpers:
PALETTES,paletteColors,defaultColorFor,colorForSet,mixColors, plusnestedSets/regionTitleLinesfor region labeling.
For rotated rectangles, request output: "polygons" or output: "regions" when using the serializer.
ToSvgOptions covers palettes and per-set color overrides, opacity, strokes, label and count rendering, a legend, padding, the placements/labelSizes from placeLabelsForRegions for exterior labels with leader lines, the setLabelPlacements/setLabelSizes from placeSetLabels (which move every set name outside its shape and suppress the interior copies), and the glyphs result from placeGlyphsForRegions (rendered above region fills, below labels; tinted from each region's own color with a finer, darker edge by default, tunable via tint, fill, stroke, and strokeWidth).
showCounts prints each region's own area. When the numbers you want are not the geometry — a Venn layout is topological, so its areas are not quantities at all — pass counts, keyed by canonical combination:
;
A supplied counts map is authoritative: a region with no entry draws no count, which is what lets you annotate only the regions you have numbers for.
glyphBoxes renders a placeGlyphBoxesForRegions result in the same slot. The placer deliberately carries no text, so pass the strings alongside it as labels, index-aligned with boxes:
;
fontSize is the reference size you measured at—the rendered size is fontSize * scale, emitted once on each region's <g>. color, fontWeight, fontFamily, and className override the defaults, and background (off by default) adds a rounded chip behind each label, tinted from the region color like the glyph discs. glyphs and glyphBoxes may both be set; discs draw first.
memberCallouts renders complete roster blocks composed by the caller. Each combination maps to a MemberCallout with a placement from the label placer, the measured size: { w, h } of the entire block, and lines containing { text, y, fontSize, fontWeight?, fontStyle? }. Each line's y is its vertical center relative to the block's anchor. Supply the region heading and count as lines when wanted: a callout replaces that region's ordinary label. Blocks expand the viewport and draw the placement's leader when it has a tether. A block whose region has no geometry can omit the tether and label the missing region explicitly. Text inherits the SVG's font family and uses labelColor. The serializer does not measure, pack, or choose which rosters become callouts.
Interactivity: tooltips and data hooks
The serializer can attach hover tooltips and identifying attributes to each region (and each set shape) so a host page can layer interactivity on top of the static markup. Three ToSvgOptions fields drive this, and each hook receives a RegionInfo ({ combination, sets, area }):
tooltip(info) => string | null— a non-empty return becomes a<title>child on the fill element, giving native (zero-JS) browser hover tooltips.interactive: boolean— emitsdata-combinationanddata-areaon every fill, a payload-free hook for event delegation.regionAttrs(info) => Record<string, string | number | null>— arbitrary extra attributes (typicallydata-*); nullish values are skipped, and keys override theinteractivedefaults.
const = ;
Member names. Eunoia only sees set and intersection sizes, never the underlying elements, so the combination -> members mapping is yours to build (set algebra over your own data). For small lists, format them in tooltip. For large lists (e.g. gene sets), don't bake them into the file — enable interactive and look the members up on hover from a JS-side map keyed on data-combination, keeping the SVG small.
Bundler-Less Entry: @jolars/eunoia/web
A single self-contained ESM file with the WebAssembly inlined. Re-exports everything from the default entry, plus:
init(): Promise<void>: instantiate the embedded wasm once; idempotent. Must be awaited beforeeuler/venn.
For exact field-level types, rely on the TypeScript definitions shipped with the package; your editor's "go to definition"/IntelliSense will surface them.
