Skip to content

Documentation / @ripl/core

@ripl/core

Core rendering library for Ripl — a unified API for 2D graphics rendering across Canvas, SVG, and Terminal contexts.

Installation

bash
npm install @ripl/core

Features

  • Unified rendering API — One API surface for both Canvas and SVG contexts
  • Built-in elements — Arc, circle, rect, line, polyline, polygon, ellipse, path, text, and image
  • Scene management — Scenegraph with grouping, property inheritance, and element querying
  • Animation — High-performance async transitions with CSS-like keyframe support and custom interpolators
  • Event system — Event bubbling, delegation, and stop propagation (mimics the DOM)
  • Scales — Continuous, discrete, and time scales for data mapping
  • Color — Color parsing, interpolation, and conversion (RGB, HSL, Hex)
  • Math — Geometry utilities, vector operations, and easing functions
  • Zero dependencies — Fully self-contained
  • Tree-shakable — Only ship what you use

Usage

typescript
import {
    createCircle,
    createContext,
    createRenderer,
    createScene,
} from '@ripl/web';

const context = createContext('.mount-element');

const circle = createCircle({
    fill: 'rgb(30, 105, 120)',
    cx: context.width / 2,
    cy: context.height / 2,
    radius: 50,
});

const scene = createScene({
    children: [circle],
});

const renderer = createRenderer(scene, {
    autoStart: true,
    autoStop: true,
});

await renderer.transition(circle, {
    duration: 1000,
    state: {
        radius: 100,
        fill: '#FF0000',
    },
});

Switching to SVG

Replace the createContext import with @ripl/svg — everything else stays the same:

typescript
import {
    createContext,
} from '@ripl/svg';

Documentation

Full documentation and interactive demos are available at ripl.run.

License

MIT

Namespaces

NamespaceDescription
interpolateAnyFallback interpolator factory that snaps from the first value to the second at the halfway point.
interpolateBorderRadiusInterpolator factory that transitions between two border-radius values (single number or four-corner tuple).
interpolateColorInterpolator factory that smoothly transitions between two CSS color strings by interpolating their RGBA channels.
interpolateDateInterpolator factory that interpolates between two Date instances by lerping their timestamps.
interpolateGradientInterpolator factory that transitions between two CSS gradient strings by interpolating their stops, angles, and positions.
interpolateNumberInterpolator factory that linearly interpolates between two numbers.
interpolatePointsInterpolator factory that transitions between two point arrays. By default it extrapolates additional points where set lengths differ; pass resolveKeys to match points by identity instead (preserving curved renderers across add/remove).
interpolateRotationInterpolator factory that transitions between two rotation values (numbers in radians or strings like "90deg").
interpolateTransformOriginInterpolator factory that transitions between two transform-origin values (numbers or percentage strings).

Classes

ClassDescription
ArcAn arc or annular sector shape supporting inner radius and pad angle.
BoxAn axis-aligned bounding box defined by its four edges.
CircleA circle shape rendered at a center point with a given radius.
ColorParseErrorError thrown when a color string cannot be parsed in the expected format.
ContextAbstract rendering context providing a unified API for Canvas and SVG, with state management and coordinate scaling.
ContextPathA virtual path element used to record drawing commands; subclassed by Canvas and SVG implementations.
ContextTextA virtual text element capturing position, content, and optional path-based text layout.
DisposerAbstract base class that manages disposable resources, supporting keyed retention and bulk disposal.
ElementThe base renderable element with state management, event handling, interpolation, transform support, and context rendering.
EllipseAn ellipse shape rendered at a center point with separate x/y radii, rotation, and angle range.
EventAn event object carrying type, data, target reference, and propagation control.
EventBusA typed pub/sub event system with parent-chain bubbling, disposable subscriptions, and self-filtering.
GroupA container element that manages child elements, providing scenegraph traversal, CSS-like querying, and composite bounding boxes.
ImageElementAn image element that draws a CanvasImageSource at a given position and optional size.
LineA straight line segment between two points.
NavigatorAn interactive 2D pan/zoom/brush controller — the flat-scene analogue of the 3D Camera. This base class is deliberately context-agnostic: it owns the view model (a { k, x, y } transform plus an optional brush selection) and the imperative commands that mutate it, but it attaches no input listeners of its own. That mirrors the Context/DOMContext split — the DOM-bound DOMNavigator in @ripl/dom extends this class to translate real wheel/pointer/touch gestures into these commands, while non-DOM environments can drive the same view model programmatically (or subclass it with their own input source).
PathA general-purpose shape rendered by a user-supplied path renderer callback.
PolygonA regular polygon shape with a configurable number of sides.
PolylineA multi-point line shape supporting various curve interpolation algorithms.
RectA rectangle shape with optional rounded corners via border radius.
RendererDrives the animation loop via requestAnimationFrame, managing per-element transitions and rendering the scene each frame.
SceneThe top-level group bound to a rendering context, maintaining a hoisted flat instruction stream for O(n) rendering.
ShapeAbstract base class for renderable shapes, extending Element with a type-constrained constructor.
Shape2DA concrete 2D shape with path management, automatic fill/stroke rendering, clipping support, and path-based hit testing.
TaskA cancellable promise with AbortController integration, supporting abort callbacks and chaining.
TaskAbortErrorError thrown when a task is aborted, carrying the abort reason.
TextA text element that renders string or numeric content, with optional path-based text layout.
TransitionA Task-based animation that drives a callback over time with easing, looping, and abort support.

Interfaces

InterfaceDescription
ArcStateState interface for an arc element, defining center, angles, radii, pad angle, and border radius.
BandScaleA band scale that divides a continuous range into uniform bands for categorical data, exposing bandwidth and step.
BaseStateThe full set of visual state properties inherited by every renderable element.
CircleStateState interface for a circle element, defining center coordinates and radius.
ColorParserA color parser that can test, parse, and serialise a specific color format.
ColorScaleA callable colour scale mapping a numeric value to a CSS colour, with domain and tick access.
ConicGradientA parsed conic gradient with angle, position, color stops, and optional repeating flag.
ContextElementMinimal interface for context-level elements (paths, text) identified by a unique id.
ContextEventMapEvent map for a rendering context, including resize and pointer events.
ContextExportSnapshot exporter returned by Context.export. Each method serializes the snapshot that was captured at the moment export() was called, so later mutations to the context do not affect the exported result. Contexts implement the formats relevant to them (see each context's export() for specifics); unsupported formats throw a descriptive error.
ContextOptionsOptions for constructing a rendering context.
DivergingScaleOptionsOptions for a diverging scale, adding a midpoint to the base linear scale options.
ElementEventMapEvent map for elements, extending the base event map with lifecycle and interaction events.
ElementValidationResultThe result of validating an element, with a severity type and descriptive message.
EllipseStateState interface for an ellipse element, defining center, radii, rotation, and angle range.
FactoryOptionsPlatform-specific function implementations injected at runtime.
GradientColorStopA single color stop within a gradient, consisting of a CSS color and an optional offset position.
GroupOptionsOptions for constructing a group, extending element options with an optional initial set of children.
ImageStateState interface for an image element, defining position, optional size, and image source.
InterpolatePointsFactoryThe interpolatePoints factory: a point-array interpolator factory that also accepts InterpolatePointsOptions.
InterpolatePointsOptionsOptions controlling how interpolatePoints reconciles two point sets.
LinearGradientA parsed linear gradient with angle, color stops, and optional repeating flag.
LinearScaleOptionsOptions shared by linear-based scales (continuous, logarithmic, power, etc.).
LineStateState interface for a line element, defining start and end coordinates.
LogarithmicScaleOptionsOptions for a logarithmic scale, adding a configurable base to the base linear scale options.
NavigatorBrushA rectangular brush selection in the navigator's pixel space.
NavigatorEventMapEvents emitted by a Navigator.
NavigatorFitOptionsOptions for Navigator.fitBounds.
NavigatorInteractionsConfigures which navigator interactions (zoom, pan, brush) are enabled.
NavigatorOptionsOptions for constructing a Navigator.
NavigatorTransformA 2D affine view transform: uniform scale k plus translation [x, y] (screen pixels).
NavigatorViewportThe pixel dimensions of the surface the navigator drives (used to centre/fit content).
OrdinalScaleA callable ordinal scale mapping discrete domain values to a cycling range of output values.
PathStateState interface for a path element, defining bounding position and dimensions.
PointScaleA point scale that positions discrete domain values at evenly spaced points, exposing the step.
PointScaleOptionsOptions for a point scale, controlling outer padding and alignment within the range.
PolygonStateState interface for a regular polygon element, defining center, radius, and number of sides.
PolylineStateState interface for a polyline element, defining points and an optional curve renderer.
PowerScaleOptionsOptions for a power scale, adding a configurable exponent to the base linear scale options.
QueryableThe structural contract the CSS-like query engine operates on, implemented by every Element. Container elements (Group) additionally provide children and a flattened descendant graph so combinators can traverse the scene tree. Typing the engine against this interface (rather than the concrete classes) lets Element, Group, and the engine live in separate modules without import cycles.
RadialGradientA parsed radial gradient with shape, position, color stops, and optional repeating flag.
RectStateState interface for a rectangle element, defining position, dimensions, and optional border radius.
RenderElementMinimal interface for any element that can be rendered and hit-tested by a context.
RenderElementIntersectionOptionsOptions for render element intersection testing.
RendererDebugOptionsOptions for enabling debug overlays on the renderer.
RendererEventMapEvent map for the renderer, with start, stop, and per-frame tick events.
RendererOptionsConfiguration for the renderer, controlling auto-start/stop behaviour and debug overlays.
RendererTransitionInternal representation of an active transition managed by the renderer.
RendererTransitionOptionsOptions for scheduling a transition on one or more elements via the renderer.
RenderInstructionA single entry in a Scene's flat render instruction stream. push/pop bracket a group so its transform and any group-scoped clip apply to the leaves drawn between them; draw renders a leaf element. Groups are contiguous (stacking-context ordering), so each group contributes exactly one push/pop pair.
ScaleA callable scale with domain, range, inverse mapping, tick generation, and inclusion testing.
ScaleBindingOptionsLow-level options for constructing a scale, providing conversion, inversion, inclusion, and tick generation callbacks.
SceneOptionsOptions for constructing a scene, extending group options with an optional auto-render-on-resize flag.
StringInterpolatorTagA tagged template result capturing the static fragments and dynamic numeric arguments.
TextStateState interface for a text element, defining position, content, and optional path-based text layout.
TransformTargetThe subset of Context transform operations required to apply an element's transform. Implemented by every Context, and by the internal matrix accumulator used to reconstruct an element's world transform for hit testing.
TransitionOptionsConfiguration for a transition animation.

Type Aliases

Type AliasDescription
BandScaleOptionsOptions for a band scale, controlling padding between and around bands, alignment, and rounding.
BaseElementStateBase state interface for all elements. All visual properties are optional at the element level.
BorderRadiusFour-corner border radius represented as [topLeft, topRight, bottomRight, bottomLeft].
ColorHSLAn HSL color represented as a three-element tuple.
ColorHSLAAn HSLA color represented as a four-element tuple.
ColorHSVAn HSV color represented as a three-element tuple.
ColorHSVAAn HSVA color represented as a four-element tuple.
ColorInterpolatorA function mapping a normalised position (0–1) to a CSS colour string.
ColorInterpolatorInputEither a ready-made colour interpolator or an array of colour stops to interpolate between.
ColorRGBAAn RGBA color represented as a four-element tuple of channel values.
ColorSpaceSupported color space identifiers.
DirectionText direction for the rendering context.
EaseAn easing function that maps a linear progress value (0–1) to an eased output value.
ElementInterpolationKeyFrameA single keyframe in a multi-step interpolation, with an optional offset (0–1) and a target value.
ElementInterpolationStatePartial state where each property can be a target value, keyframe array, or interpolator function.
ElementInterpolationStateValueAn interpolation target: a direct value, an array of keyframes, or a custom interpolator function.
ElementInterpolatorsA map of interpolator factories keyed by state property, used to override default interpolation behaviour.
ElementIntersectionOptionsOptions for element intersection (hit) testing.
ElementOptionsOptions for constructing an element, combining an optional id, CSS classes, data, pointer events, and initial state.
ElementPointerEventsControls which pointer events an element responds to during hit testing.
ElementValidationTypeSeverity level of an element validation result.
EventHandlerA callable event handler function with optional subscription options.
EventMapBase event map interface; all custom event maps should extend this.
EventOptionsOptions for emitting an event, controlling bubbling and attached data.
EventSubscriptionOptionsOptions for subscribing to an event, such as filtering to self-targeted events only.
FillRuleFill rule algorithm used to determine if a point is inside a path.
FontKerningFont kerning mode for the rendering context.
GradientUnion of all supported gradient types.
GradientTypeThe discriminant string identifying a gradient's kind ('linear', 'radial', or 'conic').
InterpolatorA function that interpolates between two values based on a normalised position (0–1).
InterpolatorFactoryA factory that creates an interpolator between two values of the same type, with a test predicate for type matching.
LineCapLine cap style for stroke endpoints.
LineJoinLine join style for stroke corners.
MatrixA 2D affine transformation matrix stored as the six significant values of the augmented 3×3 matrix, in the same [a, b, c, d, e, f] order used by the Canvas 2D API (setTransform) and CSS matrix():
MeasureTextOptionsOptions for measuring text dimensions.
NavigatorInteractionOptionEnable/disable a single interaction, optionally with a sensitivity multiplier.
PathPointA sampled point on an SVG path with position and tangent angle.
PathRendererA callback that draws custom geometry onto a ContextPath using the element's state.
PointA 2D point represented as an [x, y] tuple.
PolylineRendererBuilt-in polyline curve interpolation algorithm names.
PolylineRenderFuncA function that renders a polyline curve onto a path from an array of points.
PredicatedFunctionA callable with a test method used to determine whether the factory can handle a given value.
RenderElementPointerEventsControls which pointer events a render element responds to during hit testing.
RendererTransitionDirectionAlias for the transition playback direction within the renderer.
RendererTransitionOptionsArgTransition options can be a static object or a per-element factory function.
RenderInstructionTypeThe kind of a RenderInstruction: enter a group boundary, draw a leaf, or exit a group boundary.
RotationRotation value — a numeric radian value or a string with deg/rad suffix.
ScaleMethodA function that maps a value from one space to another.
SceneEventMapEvent map for the scene. Resize is deliberately not re-emitted here — listen for it on the scene's context instead (scene.context.on('resize', …)), the single source of truth.
Shape2DOptionsOptions for a 2D shape, adding automatic fill/stroke and clipping controls.
StringInterpolationFormatterOptional formatter applied to each interpolated numeric value before insertion into the output string.
StringInterpolationSetA pair of tagged template results representing the start and end states for string interpolation.
TaskAbortCallbackCallback invoked when a task is aborted, receiving the abort reason.
TaskExecutorExecutor function for a task, providing resolve, reject, abort registration, and the underlying AbortController.
TaskRejectCallback to reject a task with an optional reason.
TaskResolveCallback to resolve a task with a value or promise.
TextAlignmentHorizontal text alignment relative to the drawing position.
TextBaselineVertical text baseline used when rendering text.
TextOptionsOptions for creating a text element within the context.
TransformOriginTransform origin value — a numeric pixel offset or a percentage string.
TransitionCallbackCallback invoked on each animation frame with the current eased time value (0–1).
TransitionDirectionThe playback direction of a transition.
TransitionLoopModeControls whether a transition loops: true restarts from the beginning, 'alternate' ping-pongs direction each iteration.

Variables

VariableDescription
COLOR_SCHEME_BRBGDiverging — brown → white → teal (ColorBrewer BrBG).
COLOR_SCHEME_CIVIDISSequential — dark blue → slate → tan → yellow. Colour-vision-deficiency friendly.
COLOR_SCHEME_INFERNOSequential — black → purple → red → orange → pale yellow.
COLOR_SCHEME_MAGMASequential — black → purple → magenta → orange → cream.
COLOR_SCHEME_PLASMASequential — dark blue → purple → magenta → orange → yellow.
COLOR_SCHEME_RDBUDiverging — red → white → blue (ColorBrewer RdBu).
COLOR_SCHEME_TURBOSequential rainbow — purple → blue → cyan → green → yellow → orange → red. High contrast.
COLOR_SCHEME_VIRIDISSequential — dark purple → blue → teal → green → yellow. The default perceptual scheme.
CONTEXT_OPERATIONSMaps element state properties to their corresponding context setter functions.
easeInCubicCubic ease-in — accelerates from zero velocity.
easeInOutCubicCubic ease-in-out — accelerates then decelerates.
easeInOutQuadQuadratic ease-in-out — accelerates then decelerates.
easeInOutQuartQuartic ease-in-out — accelerates then decelerates.
easeInOutQuintQuintic ease-in-out — accelerates then decelerates.
easeInQuadQuadratic ease-in — accelerates from zero velocity.
easeInQuartQuartic ease-in — accelerates from zero velocity.
easeInQuintQuintic ease-in — accelerates from zero velocity.
easeLinearLinear easing — no acceleration or deceleration.
easeOutBackBack ease-out — overshoots slightly past the target and settles back (a subtle spring).
easeOutCubicCubic ease-out — decelerates to zero velocity.
easeOutElasticElastic ease-out — springs past the target and oscillates with decaying amplitude before settling.
easeOutQuadQuadratic ease-out — decelerates to zero velocity.
easeOutQuartQuartic ease-out — decelerates to zero velocity.
easeOutQuintQuintic ease-out — decelerates to zero velocity.
factoryGlobal platform factory instance. Call factory.set(...) to provide environment-specific implementations.
interpolateAnyFallback interpolator factory that snaps from the first value to the second at the halfway point.
interpolateBorderRadiusInterpolator factory that transitions between two border-radius values (single number or four-corner tuple).
interpolateColorInterpolator factory that smoothly transitions between two CSS color strings by interpolating their RGBA channels.
interpolateDateInterpolator factory that interpolates between two Date instances by lerping their timestamps.
interpolateGradientInterpolator factory that transitions between two CSS gradient strings by interpolating their stops, angles, and positions.
interpolateImageInterpolator factory that cross-fades between two image sources using an offscreen canvas.
interpolateNumberInterpolator factory that linearly interpolates between two numbers.
interpolatePointsInterpolator factory that transitions between two point arrays. By default it extrapolates additional points where set lengths differ; pass resolveKeys to match points by identity instead (preserving curved renderers across add/remove).
interpolateRotationInterpolator factory that transitions between two rotation values (numbers in radians or strings like "90deg").
interpolateTransformOriginInterpolator factory that transitions between two transform-origin values (numbers or percentage strings).
scaleRGBA continuous scale mapping normalised values (0–1) to the RGB channel range (0–255) with clamping.
TAUFull circle in radians (2π).
TRACKED_EVENTSDOM event types that are tracked and forwarded to elements for hit testing and interaction.
TRANSFORM_DEFAULTSDefault numeric values for transform properties (translate, scale, rotation, transform-origin).
TRANSFORM_INTERPOLATORSInterpolator factories for transform-related properties that require special interpolation (rotation, transform-origin).

Functions

FunctionDescription
applyElementTransformApplies an element's transform (translate, rotate, scale about its transform-origin) to the given target. Used both to drive a Context's transform during rendering and, via a matrix accumulator, to reconstruct an element's world transform for hit testing.
arePointsEqualTests whether two points have identical coordinates.
clampConstrains a value to the inclusive range between lower and upper bounds.
closestReturns the closest ancestor (including the element itself) matching a CSS-like selector, or undefined.
computeTransitionTimeComputes the eased time value for a transition given elapsed time, duration, easing function, and direction.
createArcFactory function that creates a new Arc instance.
createCircleFactory function that creates a new Circle instance.
createElementFactory function that creates a new Element instance.
createEllipseFactory function that creates a new Ellipse instance.
createFrameBufferCreates a debounced requestAnimationFrame wrapper that cancels any pending frame before scheduling a new one.
createGroupFactory function that creates a new Group instance.
createImageFactory function that creates a new ImageElement instance.
createLineFactory function that creates a new Line instance.
createNumericIncludesMethodCreates an includes predicate that tests whether a value falls within the numeric domain.
createPathFactory function that creates a new Path instance.
createPolygonFactory function that creates a new Polygon instance.
createPolylineFactory function that creates a new Polyline instance.
createRectFactory function that creates a new Rect instance.
createRendererFactory function that creates a new Renderer bound to the given scene.
createScaleAssembles a Scale object from explicit conversion, inversion, and tick functions.
createSceneFactory function that creates a new Scene instance from a context, selector, or element.
createShapeFactory function that creates a new Shape2D instance.
createTextFactory function that creates a new Text instance.
degreesToRadiansConverts degrees to radians.
elementIsArcType guard that checks whether a value is an Arc instance.
elementIsCircleType guard that checks whether a value is a Circle instance.
elementIsEllipseType guard that checks whether a value is an Ellipse instance.
elementIsImageType guard that checks whether a value is an ImageElement instance.
elementIsLineType guard that checks whether a value is a Line instance.
elementIsPathType guard that checks whether a value is a Path instance.
elementIsPolygonType guard that checks whether a value is a Polygon instance.
elementIsPolylineType guard that checks whether a value is a Polyline instance.
elementIsRectType guard that checks whether a value is a Rect instance.
elementIsShapeType guard that checks whether a value is a Shape instance.
elementIsTextType guard that checks whether a value is a Text instance.
fractionalReturns the fractional part of a number (e.g. fractional(3.7)0.7).
getColorParserFinds the first color parser whose pattern matches the given color string.
getContainingBoxComputes the smallest axis-aligned bounding box that contains all boxes extracted from the array.
getEuclideanDistanceComputes the Euclidean distance from two points.
getExtentComputes the [min, max] extent of an array using the given numeric accessor.
getLinearScaleMethodCreates a linear mapping function from a numeric domain to a numeric range, with optional clamping and tick-padding.
getLinearTicksGenerates an array of evenly spaced, "nice" tick values across the domain.
getMidpointReturns the midpoint between two points.
getPathLengthComputes the total length of an SVG path from its d attribute string.
getPolygonPointsGenerates the vertex points of a regular polygon centred at (cx, cy) with the given radius and number of sides.
getThetaPointReturns the point at a given angle and distance from an optional centre.
getTimeTicksGenerates calendar-aligned tick dates spanning [min, max] at roughly count ticks.
getTotalSums all numeric values extracted from an array via the accessor.
getWaypointReturns a point along the line segment between two points at the given normalised position (0–1).
getWorldTransformReconstructs an element's world transform — the composition of its own transform and every ancestor group's transform, from the root down — for use in hit testing against backends (such as canvas) that do not natively account for element transforms.
hslToRGBAConverts HSLA values to an RGBA tuple.
hsvToRGBAConverts HSVA values to an RGBA tuple.
interpolateCirclePointCreates an interpolator that traces a point around a circle of the given centre and radius.
interpolateColorsBuilds a colour interpolator from an array of colour stops. Position 0 returns the first stop, 1 the last, and intermediate positions interpolate (RGBA, channel-wise) between adjacent stops.
interpolatePathCreates an interpolator that progressively reveals a path from start to end as position advances from 0 to 1.
interpolatePolygonPointCreates an interpolator that traces a point around the vertices of a regular polygon.
interpolateStringCreates a string interpolator by interpolating between numeric values embedded in tagged template literals.
interpolateWaypointCreates an interpolator that returns the point along a polyline at the given normalised position.
isGradientStringTests whether a string looks like a CSS gradient (starts with a recognised gradient function name).
isGroupType guard that checks whether a value is a Group instance.
isPointInBoxTests whether a point lies within the given bounding box (inclusive).
matchesTests whether an element matches a CSS-like selector.
matrixApplyToPointApplies matrix to the point [x, y], returning the transformed point.
matrixIdentityReturns the identity matrix (a no-op transform).
matrixInvertReturns the inverse of matrix, or null when it is singular (zero determinant) and therefore not invertible.
matrixIsIdentityTests whether matrix is the identity transform (within an exact comparison).
matrixMultiplyPost-multiplies a by b, returning the composite a · b. Applying the result to a point is equivalent to applying b first and then a, matching how successive translate/rotate/scale calls accumulate onto a canvas transform matrix.
matrixRotateReturns a rotation matrix for the given angle, in radians.
matrixScaleReturns a scaling matrix with the given horizontal and vertical factors.
matrixTranslateReturns a translation matrix that moves points by (x, y).
maxReturns the maximum of the provided numbers.
maxOfReturns the maximum numeric value extracted from an array via the accessor.
measureTextMeasures the dimensions of a text string using an optional font and context override.
minReturns the minimum of the provided numbers.
minOfReturns the minimum numeric value extracted from an array via the accessor.
niceDomainReturns the domain expanded to round, tick-aligned [min, max] boundaries.
normaliseBorderRadiusNormalises a border radius value into a four-corner tuple, expanding a single number to all corners.
padDomainExpands a numeric domain to "nice" tick-aligned boundaries and returns [min, max, step].
parseColorParses any supported color string into an RGBA tuple, or returns undefined if no parser matches.
parseGradientParses a CSS gradient string (linear, radial, or conic) into a structured Gradient object, or returns undefined if the string is not a recognised gradient.
parseHEXParses a hexadecimal color string (e.g. #ff0000 or #ff000080) into an RGBA tuple.
parseHSLParses an hsl() color string into an RGBA tuple.
parseHSLAParses an hsla() color string into an RGBA tuple.
parseHSVParses an hsv() color string into an RGBA tuple.
parseHSVAParses an hsva() color string into an RGBA tuple.
parseRGBParses an rgb() color string into an RGBA tuple with alpha set to 1.
parseRGBAParses an rgba() color string into an RGBA tuple.
polylineBasisRendererCreates a cubic B-spline polyline renderer.
polylineBumpXRendererCreates a bump-X polyline renderer using horizontal midpoint bezier curves.
polylineBumpYRendererCreates a bump-Y polyline renderer using vertical midpoint bezier curves.
polylineCardinalRendererCreates a cardinal spline polyline renderer with configurable tension.
polylineCatmullRomRendererCreates a Catmull-Rom spline polyline renderer with configurable alpha.
polylineLinearRendererCreates a linear (straight segment) polyline renderer.
polylineMonotoneXRendererCreates a monotone-X polyline renderer preserving monotonicity along the x-axis.
polylineMonotoneYRendererCreates a monotone-Y polyline renderer preserving monotonicity along the y-axis.
polylineNaturalRendererCreates a natural cubic spline polyline renderer with second-derivative continuity.
polylineSplineRendererCreates a spline polyline renderer with configurable tension.
polylineStepAfterRendererCreates a step-after polyline renderer where the vertical transition occurs at the end of each segment.
polylineStepBeforeRendererCreates a step-before polyline renderer where the vertical transition occurs at the start of each segment.
polylineStepRendererCreates a step polyline renderer with midpoint horizontal transitions.
queryReturns the first element matching a CSS-like selector, or undefined if none match.
queryAllQueries all elements matching a CSS-like selector across the given element(s) and their descendants.
radiansToDegreesConverts radians to degrees.
rescaleDomainRescales a scale's domain to the window currently visible under a navigator transform. The scale maps data → the given pixel range; inverting the transformed range endpoints back through the scale yields the zoomed/panned data domain. This is how a cartesian chart turns navigator gestures into axis rescaling (scale.inverse) without transforming the rendered geometry.
resolveNiceCountResolves a nice option to a target tick count (defaults to 10 when true).
resolvePolylineRendererResolves a named curve algorithm (or a custom render function) to its render function. Defaults to linear.
resolveRotationResolves a rotation value (number, degrees string, or radians string) to radians.
resolveTransformOriginResolves a transform-origin value (number or percentage string) to a pixel offset relative to the given dimension.
rgbaToHSLConverts RGBA channel values to an HSLA tuple.
rgbaToHSVConverts RGBA channel values to an HSVA tuple.
rgbChannelToHEXConverts a single RGB channel value (0–255) to a two-character hexadecimal string.
samplePathPointSamples a point and tangent angle at the given distance along an SVG path.
scaleBandCreates a band scale that maps discrete domain values to evenly spaced bands within the range.
scaleContinuousCreates a continuous linear scale that maps a numeric domain to a numeric range.
scaleDiscreteCreates a discrete (ordinal) scale that maps domain values to corresponding range values by index.
scaleDivergingCreates a diverging scale that maps values below and above a midpoint to separate sub-ranges.
scaleLogShortcut for a base-10 logarithmic scale.
scaleLogarithmicCreates a logarithmic scale that maps a numeric domain to a range using a log transformation.
scaleOrdinalCreates an ordinal scale mapping each distinct domain value to a value from range, cycling when there are more domain values than range values. Unknown values encountered later are assigned the next range slot (so a chart can colour series without pre-declaring every category). Unlike the numeric scales this maps value → value of any type — its most common use is categorical colour.
scalePointCreates a point scale that maps discrete domain values to evenly spaced positions across the range (the categorical analogue of a continuous axis — points, not bands). With zero padding the first and last values sit exactly on the range endpoints. inverse returns the nearest domain value.
scalePowerCreates a power scale that maps a numeric domain to a range using an exponential transformation.
scaleQuantileCreates a quantile scale that divides a sorted numeric domain into quantiles mapped to discrete range values.
scaleQuantizeCreates a quantize scale that divides a continuous numeric domain into uniform segments mapped to discrete range values.
scaleSequentialCreates a colour scale mapping a numeric domain through a colour interpolator (or array of stops, e.g. one of the built-in COLOR_SCHEME_* palettes). Values are clamped to the domain.
scaleSqrtShortcut for a power scale with exponent 0.5 (square root).
scaleThresholdCreates a threshold scale that maps numeric values to range values based on a set of threshold breakpoints.
scaleTimeCreates a time scale that maps a Date domain to a numeric range using linear interpolation of timestamps.
serialiseGradientSerialises a structured Gradient object back into a CSS gradient string.
serialiseHEXSerialises RGBA channel values into a hexadecimal color string (e.g. #ff0000).
serialiseHSLSerialises RGBA channel values into an hsl() color string.
serialiseHSLASerialises RGBA channel values into an hsla() color string.
serialiseHSVSerialises RGBA channel values into an hsv() color string.
serialiseHSVASerialises RGBA channel values into an hsva() color string.
serialiseRGBSerialises RGBA channel values into an rgb() color string.
serialiseRGBASerialises RGBA channel values into an rgba() color string.
setColorAlphaReturns a new color string with the alpha channel replaced by the given value.
transformBoxTransforms a box by an affine matrix and returns the axis-aligned bounding box of the result. Returns the box unchanged when matrix is null (the identity case). Because it re-fits an AABB around the transformed corners, a rotated box yields a conservative (enlarged) bounding box.
transitionCreates and starts a frame-driven transition that invokes the callback with the eased time on each animation frame.
typeIsContextType guard that checks whether a value is a Context instance.
typeIsElementType guard that checks whether a value is an Element instance.
typeIsPointType guard that checks whether a value is a Point (a two-element array).