@molecule/app-canvas-logic

Feature · canvas · App (browser) · v1.1.0 · Apache-2.0

Framework-neutral viewport, hit-testing and editing logic for Molecule canvas features

npm install @molecule/app-canvas-logic

npm · Source on GitHub

How it works

@molecule/app-canvas-logic is a ready-made canvas feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { screenToCanvas, zoomViewport } from '@molecule/app-canvas-logic'

const camera = { x: 40, y: -20, zoom: 2 }
const fingertip = { x: 100, y: 100 }
const inkPosition = screenToCanvas(fingertip, camera)
const nextCamera = zoomViewport(camera, 1.1, fingertip)

Reference

Shared viewport, geometry and editing policy for canvas features.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { screenToCanvas, zoomViewport } from '@molecule/app-canvas-logic'

const camera = { x: 40, y: -20, zoom: 2 }
const fingertip = { x: 100, y: 100 }
const inkPosition = screenToCanvas(fingertip, camera)
const nextCamera = zoomViewport(camera, 1.1, fingertip)

Type

feature

Installation

npm install @molecule/app-canvas-logic

API

Interfaces

CanvasPath

One continuous painted path in local coordinates.

interface CanvasPath {
  /** The initial point. */
  readonly start: Point
  /** Drawing commands in paint order. */
  readonly segments: readonly CanvasPathSegment[]
}

CanvasAffineTransform

A local-to-world affine matrix with the coefficient order used by SVG.

interface CanvasAffineTransform {
  /** Horizontal scale. */
  readonly a: number
  /** Vertical shear. */
  readonly b: number
  /** Horizontal shear. */
  readonly c: number
  /** Vertical scale. */
  readonly d: number
  /** Horizontal translation. */
  readonly e: number
  /** Vertical translation. */
  readonly f: number
}

CanvasHitRegion

A painted item and the semantic result of hitting it.

interface CanvasHitRegion<T> {
  /** Stable key within the surface. */
  readonly key: string
  /** The hit's priority relative to its own node. */
  readonly kind: 'node' | 'resize' | 'port' | 'edge'
  /** The owning node key for a port or grip. */
  readonly ownerKey?: string
  /** What to return to the caller on a hit. */
  readonly value: T
  /** Shape describing the interaction area. */
  readonly shape: CanvasHitShape
  /** Optional local-to-world transform, including the transforms of enclosing groups. */
  readonly transform?: CanvasAffineTransform
  /** Paint order, from back to front. Defaults to the item's array index. */
  readonly paintOrder?: number
}

CanvasInteraction

The current canvas activity. Each gesture or field edit claims the activity until its owner releases it. A termination can consume the activity once.

interface CanvasInteraction<T> {
  /** The activity currently being edited. */
  readonly active: T | undefined
  /** Claims an idle interaction and returns whether it was acquired. */
  begin(value: T): boolean
  /** Releases and returns the current activity, if any. */
  take(): T | undefined
}

CanvasNodeDrag

One incremental node movement in canvas units.

interface CanvasNodeDrag {
  /** Resulting top-left position. */
  position: Point
  /** World displacement since the preceding move. */
  delta: Point
  /** True on the first nonzero move. */
  start: boolean
  /** True on termination. */
  end: boolean
}

CanvasNodeResize

One southeast resize in canvas units.

interface CanvasNodeResize {
  /** The node's top-left position. */
  position: Point
  /** Resulting node size. */
  size: Size
  /** True on termination. */
  end: boolean
}

CanvasNodeInteractionOptions

Geometry and callbacks for the node's current render.

interface CanvasNodeInteractionOptions {
  /** The authored top-left position. */
  position: Point
  /** Explicit node size. A resize handle is present only when it is specified. */
  size?: Size
  /** Zoom currently applied by the enclosing surface. */
  zoom: number
  /** Receives an unmodified contact release. */
  select?: (point: CanvasContact) => void
  /** Receives a stationary release when the surface resolved the child geometrically. */
  selectFromSurface?: (point: CanvasContact) => void
  /** Receives incremental and terminal drag events. */
  move?: (info: CanvasNodeDrag) => void
  /** Receives incremental and terminal resize events. */
  resize?: (info: CanvasNodeResize) => void
}

CanvasNodeInteraction

Separate node body and southeast grip bindings backed by one editing owner.

interface CanvasNodeInteraction {
  /** The node body acquires a selection or node drag. */
  body: CanvasContactHandler
  /** Uses the same node state when a surface resolves the body as its painted hit. */
  surfaceBody: CanvasContactHandler
  /** The grip acquires resize ahead of the node body. */
  grip: CanvasContactHandler
  /** Resizes by a canvas-unit increment for keyboard and assistive activation. */
  resizeBy(delta: Point): void
  /** Retires the active edit when its node is removed from the scene. */
  cancel(): void
}

CanvasContact

A sample from the kit contact owner, in the current host's untransformed screen frame.

interface CanvasContact extends Readonly<Point> {
  /** Screen displacement from contact-down. */
  readonly dx: number
  /** Screen displacement from contact-down. */
  readonly dy: number
  /** The host's bounds in the renderer's window coordinates. */
  readonly bounds: Readonly<Bounds>
  /** Whether Alt or Option was held. */
  readonly altKey: boolean
  /** Whether Control was held. */
  readonly ctrlKey: boolean
  /** Whether Meta or Command was held. */
  readonly metaKey: boolean
  /** Whether Shift was held. */
  readonly shiftKey: boolean
}

CanvasContactHandler

Phases delivered by the kit drag owner.

interface CanvasContactHandler {
  /** Direction used when negotiating scroll ownership. */
  axis?: 'horizontal' | 'vertical' | 'both'
  /** Enables long-press ownership inside a touch scroller. */
  touchStart?: 'immediate' | 'longPress'
  /** Receives the first acquired sample. */
  onStart(point: CanvasContact): void
  /** Receives motion from the active contact. */
  onMove?(point: CanvasContact): void
  /** Receives release from the active contact. */
  onEnd?(point: CanvasContact): void
  /** Receives interruption with the last reliable sample. */
  onCancel?(point: CanvasContact): void
}

CanvasSurfaceDragOptions

Current surface policy read at contact start.

interface CanvasSurfaceDragOptions {
  /** Routes a surface-owned contact to a painted child before a tool or pan. */
  pickDrag?: (contact: CanvasContact) => CanvasContactHandler | undefined
  /** A content tool that acquires ahead of the background pan. */
  contentDrag?: CanvasContactHandler
  /** Whether a background contact can pan. */
  panOnDrag?: boolean
  /** Reports a background contact in the portable form. */
  onBackgroundContact?: (contact: CanvasContact) => void
  /** Pans by an incremental screen delta. */
  panBy(dx: number, dy: number): void
}

Point

A 2D point in either screen-space or canvas-space.

interface Point {
  /** X coordinate. */
  x: number
  /** Y coordinate. */
  y: number
}

Size

A 2D size in either screen-space or canvas-space.

interface Size {
  /** Width in the relevant coordinate space. */
  width: number
  /** Height in the relevant coordinate space. */
  height: number
}

Bounds

An axis-aligned rectangle in canvas-space (top-left origin, +x right, +y down). Used for selection regions, content bounds, fitting, etc.

interface Bounds {
  /** Left edge in canvas units. */
  x: number
  /** Top edge in canvas units. */
  y: number
  /** Width in canvas units. */
  width: number
  /** Height in canvas units. */
  height: number
}

CanvasViewport

Viewport state — the camera over the canvas. (x, y) is the canvas-space coordinate that maps to the surface's top-left corner. zoom is the scale factor (1 = identity, 2 = 2x zoom-in, 0.5 = zoom-out).

interface CanvasViewport {
  /** Canvas-space x at the surface's top-left corner. */
  x: number
  /** Canvas-space y at the surface's top-left corner. */
  y: number
  /** Scale factor (1 = identity, > 1 = zoomed in). */
  zoom: number
}

ViewportLimits

Optional clamping limits for the viewport. All fields are optional; omitted limits are unbounded. bounds constrains where (x, y) may sit; minZoom / maxZoom clamp the zoom factor.

interface ViewportLimits {
  /** Allowed range for the viewport origin. Omit for unbounded. */
  bounds?: Bounds
  /** Minimum allowed zoom. Defaults to no minimum. */
  minZoom?: number
  /** Maximum allowed zoom. Defaults to no maximum. */
  maxZoom?: number
}

ScreenTranslation

A viewport stored as a screen-space translation followed by a scale.

interface ScreenTranslation extends Point {
  /** Scale factor. */
  zoom: number
}

Types

CanvasPathSegment

A command in a canvas path, using the same points for painting and hit-testing.

type CanvasPathSegment =
  | { readonly kind: 'line'; readonly to: Point }
  | {
      readonly kind: 'cubic'
      readonly control1: Point
      readonly control2: Point
      readonly to: Point
    }

CanvasHitShape

The shape used to resolve a hit, in the item's local coordinates.

type CanvasHitShape =
  | ({ readonly kind: 'rect' } & Readonly<Bounds>)
  | {
      readonly kind: 'ellipse'
      readonly cx: number
      readonly cy: number
      readonly rx: number
      readonly ry: number
    }
  | {
      readonly kind: 'path'
      readonly path: CanvasPath
      /** Interaction stroke width before applying the item's transform. */
      readonly width: number
    }

CanvasEdgeKind

Kinds of edge geometry <CanvasEdge> knows how to draw.

type CanvasEdgeKind = 'line' | 'bezier' | 'orthogonal'

CanvasZoomSample

Focal input in the untransformed surface.

type CanvasZoomSample =
  | { readonly kind: 'wheel'; readonly at: Point; readonly deltaY: number }
  | { readonly kind: 'pinch'; readonly from: Point; readonly at: Point; readonly factor: number }

Functions

horizontalBezierPath(start, to, minimumHandle)

Create an edge with horizontal Bézier handles.

function horizontalBezierPath(start: Point, to: Point, minimumHandle: number): CanvasPath
  • start — Source endpoint.
  • to — Target endpoint.
  • minimumHandle — Minimum length of either control handle.

Returns: The same cubic geometry for rendering and pointer hits.

canvasPathData(path)

Serialize a canvas path as SVG path data.

function canvasPathData(path: CanvasPath): string
  • path — The path to paint.

Returns: SVG path data.

buildEdgePath(from, to, kind)

Build the SVG path for a line, horizontal Bézier, or horizontal-then-vertical edge.

function buildEdgePath(from: Point, to: Point, kind: CanvasEdgeKind): string
  • from — Source endpoint.
  • to — Target endpoint.
  • kind — Shape of the edge.

Returns: SVG path data.

hitTestCanvas(point, items)

Resolve a world-space hit in paint order. When a node wins the hit, a matching grip or port on that same node takes priority.

function hitTestCanvas<T>(point: Point, items: readonly CanvasHitRegion<T>[]): T | undefined
  • point — Pointer position in world space.
  • items — Painted hit regions.

Returns: The frontmost hit's semantic result, if any.

createCanvasInteraction()

Create an owner for a single editing interaction.

function createCanvasInteraction<T>(): CanvasInteraction<T>

Returns: A per-surface or per-editor activity owner.

createCanvasNodeInteraction(read)

Owns tap, incremental world drag and resize policy independently of the renderer. The kit offers the deepest control first, while this state prevents the same node from acquiring body drag after its grip has acquired resize.

function createCanvasNodeInteraction(
  read: () => CanvasNodeInteractionOptions,
): CanvasNodeInteraction
  • read — Reads current options when a sample arrives.

Returns: The handlers for a node and its resize grip.

createCanvasSurfaceDrag(read)

Keeps the contact's edit or pan owner through release or cancellation even if tool props change. The kit owns capture, scroll and pinch takeover and supplies all contact samples.

function createCanvasSurfaceDrag(read: () => CanvasSurfaceDragOptions): CanvasContactHandler
  • read — Current tool, background behavior and pan callback.

Returns: The handlers to install on the surface's kit gesture.

canvasZoomSample(sample, step)

Applies the surface's configured wheel step, or passes a moving two-contact focal point through.

function canvasZoomSample(
  sample: CanvasZoomSample,
  step: number,
): { factor: number; from: Point; at: Point }
  • sample — The kit's focal zoom or pinch sample.
  • step — The canvas surface wheel step.

Returns: The zoom multiplier and the focal position before and after the sample.

screenToCanvas(point, viewport)

Convert a screen-space point (relative to the surface's top-left) into canvas-space. Inverse of canvasToScreen.

function screenToCanvas(point: Point, viewport: CanvasViewport): Point
  • point — Screen-space point in pixels.
  • viewport — Current viewport state.

Returns: The same point expressed in canvas-space.

canvasToScreen(point, viewport)

Convert a canvas-space point into screen-space (relative to the surface's top-left). Inverse of screenToCanvas.

function canvasToScreen(point: Point, viewport: CanvasViewport): Point
  • point — Canvas-space point.
  • viewport — Current viewport state.

Returns: The same point expressed in screen-space pixels.

clampViewport(viewport, limits)

Clamp a viewport to optional limits. bounds (if provided) constrains where the viewport origin may sit; minZoom / maxZoom clamp zoom. Returns a new viewport — does not mutate the input.

If bounds is provided AND has positive width/height, the origin is clamped so the surface still overlaps the bounds when fully zoomed out. (Wrappers can layer richer rules on top via onViewportChange.)

function clampViewport(viewport: CanvasViewport, limits?: ViewportLimits): CanvasViewport
  • viewport — The desired viewport.
  • limits — Optional clamping limits.

Returns: A clamped viewport.

fitToBounds(bounds, surface, padding)

Compute the viewport that fits a canvas-space bounds rectangle into a surface of the given screen-space size, with optional padding (in screen-space pixels) around the content.

The returned viewport centers the content, but if either dimension is zero the center is well-defined (the bounds origin) and zoom is clamped to 1.

function fitToBounds(bounds: Bounds, surface: Size, padding?: number): CanvasViewport
  • bounds — Canvas-space content rectangle to fit.
  • surface — Screen-space size of the surface.
  • padding — Screen-space padding around the content (default 0).

Returns: A viewport that frames bounds inside the surface.

panViewport(viewport, delta, limits)

Pan by the screen-space displacement of an owned contact.

function panViewport(
  viewport: CanvasViewport,
  delta: Point,
  limits?: ViewportLimits,
): CanvasViewport
  • viewport — Current viewport.
  • delta — Contact displacement in surface pixels.
  • limits — Limits applied to the resulting viewport.

Returns: The new viewport.

zoomViewport(viewport, factor, from, at, limits)

Zoom or pinch around a focal point. The world point at the old centroid moves to the new centroid even when the requested scale reaches its limit.

function zoomViewport(
  viewport: CanvasViewport,
  factor: number,
  from: Point,
  at?: Point,
  limits?: ViewportLimits,
): CanvasViewport
  • viewport — Current viewport.
  • factor — Requested scale relative to the current viewport.
  • from — Previous focal point in the untransformed surface.
  • at — New focal point. Wheel zoom uses the same point for both.
  • limits — Optional bounds and zoom limits.

Returns: The anchored viewport within the given limits.

screenTranslationToViewport(translation)

Convert Flow's screen translation into the world origin used by canvas logic.

function screenTranslationToViewport(translation: ScreenTranslation): CanvasViewport
  • translation — Screen-space translation and scale.

Returns: The equivalent viewport with a world-space origin.

viewportToScreenTranslation(viewport)

Convert a world-space viewport to Flow's screen translation.

function viewportToScreenTranslation(viewport: CanvasViewport): ScreenTranslation
  • viewport — World-space origin and scale.

Returns: The equivalent screen translation and scale.

zoomFlowViewport(translation, sample)

Apply Flow's exponential wheel curve or a pinch to its screen-translation viewport.

function zoomFlowViewport(
  translation: ScreenTranslation,
  sample: CanvasZoomSample,
): ScreenTranslation
  • translation — Current Flow viewport.
  • sample — A wheel or pinch sample in the surface.

Returns: The new screen translation and scale, anchored within the 0.2–4 scale range.

takeDragDelta(previous, cumulative, zoom)

Convert the change between two cumulative drag samples into a world delta.

function takeDragDelta(previous: Point, cumulative: Point, zoom: number): Point
  • previous — Previous cumulative screen displacement.
  • cumulative — Current cumulative screen displacement.
  • zoom — Scale used for the gesture.

Returns: The world delta since the previous sample.