encode

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BandTicks

func BandTicks(scale *BandScale) []scene.Tick

BandTicks places one tick per category at the band's center. Used by axis tick placement so labels sit under (or beside) the band middle rather than its left edge.

func BuildAxis

func BuildAxis(scale Scale, channel scene.Channel, position scene.AxisPosition, plot scene.Rect, title string) scene.Axis

BuildAxis converts a resolved Scale into a populated scene.Axis, including ticks, the axis domain line, and grid lines anchored to the plot region. Uses DefaultAxisOpts; callers needing overrides invoke BuildAxisWithOpts instead.

func BuildAxisWithOpts

func BuildAxisWithOpts(scale Scale, channel scene.Channel, position scene.AxisPosition, plot scene.Rect, opts AxisOpts) scene.Axis

BuildAxisWithOpts is the full-control axis builder.

func BuildGradientLegend

func BuildGradientLegend(in LegendInputs, plot scene.Rect) *scene.Legend

BuildGradientLegend returns one Legend with a single gradient swatch referencing the supplied Gradient via scene.Defs.

func BuildSelections

func BuildSelections(specSel map[string]spec.Selection) []scene.Selection

BuildSelections turns a spec.Selection map into post-resolve scene.Selection entries (D004 wiring; full hit-testing lands on the browser side per D077/D078). Returns nil when specSel is empty so SceneDoc round-trips without an empty `selections: []` artifact.

Iteration order is sorted-by-selection-id for stable JSON output (cross-impl parity per D076 + IR contract per D011).

Default Reactive mode is "client" (per D004 / D078): the JS port applies prism-selected / prism-deselected CSS classes without a server round-trip. Server-reactive mode is opt-in once the spec schema gains a `reactive` knob (deferred to P14 alongside the hardened /prism/scene endpoint per D081).

Default On event:

  • point → click (default), hover (when p.On == "hover"), dblclick (when p.On == "dblclick").
  • interval → brush.

Channels for interval selections derive from i.Encodings via channelFor — the validator (PRISM_SPEC_020) ensures interval encodings only list position channels.

func BuildSymbolLegend

func BuildSymbolLegend(in LegendInputs, plot scene.Rect) *scene.Legend

BuildSymbolLegend returns one Legend with N solid swatches, one per category. Returns nil when the channel is trivial (<=1 category).

func CategoryToColor

func CategoryToColor(category string, categories []string, palette []*scene.Color) *scene.Color

CategoryToColor returns the palette entry for a category, with stable ordering — the i-th unique category in `categories` maps to palette[i % len(palette)]. Falls back to palette[0] for out-of-domain inputs.

func DefaultPalette

func DefaultPalette() []*scene.Color

DefaultPalette returns an 8-entry color palette derived from D3's category10. Used as the fallback color mapping for color-channel encodings until P06 lands the full theme + scheme registry. The returned slice is freshly allocated; callers may mutate.

func Encode

func Encode(s *spec.Spec, tables map[plan.NodeID]*table.Table, tipID plan.NodeID, opts EncodeOpts) (*scene.SceneDoc, error)

Encode turns a validated *spec.Spec plus the executor's output tables into a SceneDoc ready for any Renderer. The tipID is the node id whose Table feeds the encoder (returned by plan/build.Build alongside the DAG).

Pipeline (per design/02-architecture.md § Stage 5):

  1. Pull the tip table.
  2. Compute layout.
  3. Resolve x / y scales from the upstream column values.
  4. Build axes from the resolved scales.
  5. Dispatch the encoded mark to encode/marks for geometry.
  6. Wrap one SceneLayer → Scene → 1×1 SceneGrid → SceneDoc (full nesting always; no flat-chart special case).

All warnings collected along the way attach to SceneDoc.Warnings.

func EncodeComposite

func EncodeComposite(s *spec.Spec, composite *plan.CompositeDAG, childTables []map[plan.NodeID]*table.Table, opts EncodeOpts) (*scene.SceneDoc, error)

EncodeComposite turns a *plan.CompositeDAG + the executor's per-child tip tables into a SceneDoc. Layer kinds collapse into a single Scene whose Layers slice carries one entry per child; concat / hconcat / vconcat kinds emit one Scene per cell into the grid.

childTables is one map per child (positional: childTables[i] holds the executor result for composite.Children[i]). Per-child maps avoid the NodeID-collision foot-gun where two sibling sub-DAGs independently allocate the same auto-counter id; the encoder reads `childTables[i][child.Tip]` rather than a merged map.

Per D049 each child's tip table comes from `childTables[i][child.Tip]`; missing tips emit PRISM_WARN_LAYER_SKIPPED and that child is dropped from the output (the other children still render).

Per D050 nested composites are rejected at BuildComposite time; EncodeComposite does not recurse into a child composite — children here are always flat (built via Build).

The flat-chart Encode path is unchanged; existing P05 / P06 / P07 goldens stay byte-identical because the 1×1 single-layer case is preserved.

func LogTicks

func LogTicks(s *LogScale) []scene.Tick

LogTicks returns the canonical tick set for a LogScale: integer powers of base between log_b(min) and log_b(max) as major ticks, with the mantissa values (2..base-1) at each major as minor ticks.

Major tick labels render in compact form (e.g. "1k" for 1e3 when base=10 and value >= 1000). Minor ticks carry empty labels so the renderer skips text emission.

func NiceTicks

func NiceTicks(min, max float64, count int) []float64

NiceTicks returns the canonical "nice" tick values for the domain [min, max] with approximately count ticks. Ported from D3's d3-array#ticks (commit 4f24b06, MIT licence). The shape:

  1. If min == max, return [min].
  2. Compute step ≈ (max - min) / count.
  3. Round step to the nearest "nice" value in {1, 2, 5} × 10ⁿ.
  4. Snap min to step * floor(min/step), max to step * ceil(max/step).
  5. Walk from snapped-min to snapped-max by step, collecting values.

Returns ticks in ascending order. Negative ranges work (min < max with negative values). When min > max, the result is reversed.

func PowTicks

func PowTicks(s *PowScale, count int) []scene.Tick

PowTicks returns ticks for a PowScale by generating linear ticks in the transformed (post-pow) domain, then inverting them back to the original space. This gives evenly-spaced ticks in pixel space while keeping label values readable in the original units.

func SqrtTicks

func SqrtTicks(s *SqrtScale, count int) []scene.Tick

SqrtTicks delegates to PowTicks via the inner PowScale.

func TicksWithLabels

func TicksWithLabels(values []float64, scale Scale, format string) ([]scene.Tick, error)

TicksWithLabels formats raw tick values into scene.Tick entries. Each tick's Pixel is computed by applying scale.Apply to the value; the Label is formatted via the supplied format spec (use "" for the default %g rendering). Errors from scale.Apply are surfaced as a wrapped error tagged with the failing value.

func TimeTicks

func TimeTicks(s *TimeScale, count int) []scene.Tick

TimeTicks produces calendar-aligned ticks for a time scale. The domain is interpreted as epoch milliseconds; ticks align to a natural calendar boundary chosen by the span:

span > 2 years   → year ticks ("2006")
span > 2 months  → month ticks ("2006-01")
span > 2 days    → day ticks ("2006-01-02")
span > 2 hours   → hour ticks ("15:04")
span > 2 minutes → minute ticks ("15:04")
span > 2 seconds → second ticks ("15:04:05")
else             → millisecond ticks ("15:04:05.000")

Pure stdlib; no external date library. Returned ticks carry the epoch-ms float64 as Value (so callers can re-apply the scale) and a pre-formatted Label.

Types

type AxisOpts

type AxisOpts struct {
	Title        string
	Grid         bool
	LabelAngle   float64
	LabelOverlap string // "parity" (default) | "auto" | "none"
	MinorTicks   bool   // default true for linear
	Format       string // d3-format spec for tick labels
}

AxisOpts carries per-axis overrides resolved from the spec's channel.axis block. Defaults match the P05 behaviour (grid on, 0-degree labels, parity-skip overlap mode).

func DefaultAxisOpts

func DefaultAxisOpts(title string) AxisOpts

DefaultAxisOpts returns the P06 defaults.

type BandScale

type BandScale = scale.BandScale

BandScale is re-exported from encode/scale for back-compat.

type EncodeOpts

type EncodeOpts struct {
	Width          float64
	Height         float64
	Theme          *scene.Theme
	ThemeName      string
	OverrideXScale Scale
	OverrideYScale Scale
}

EncodeOpts controls the encoder's per-call layout knobs. Width and Height default to 800×600 when zero. ThemeName selects a registered theme (light/dark/print + user-loaded); Theme is the resolved scene-IR theme override (wins over ThemeName).

OverrideXScale / OverrideYScale (P09) let a composite caller hand the flat Encode path pre-computed shared scales. When non-nil, Encode skips its per-channel resolver for that axis and uses the override verbatim. Drives the shared-axis facet path (D057) and any future composite that wants to share a scale across cells without restating the spec.

type GradientLegend

type GradientLegend struct {
	ID          string
	DomainMin   float64
	DomainMax   float64
	Stops       []scene.GradientStop
	LabelFormat string
}

GradientLegend describes a continuous-color legend.

type Layout

type Layout struct {
	Frame   scene.Rect
	Plot    scene.Rect
	Padding Padding
}

Layout is the resolved frame + plot region for a single Scene. Frame = the outer SVG bounds; Plot = the inner rect marks render into.

func Compute

func Compute(width, height float64, hasTitle bool) Layout

Compute returns the Layout for a width × height frame. Pure arithmetic. P05 ships only one variant; P06 introduces a richer LayoutOpts shape.

func ComputeSparkline

func ComputeSparkline(width, height float64) Layout

ComputeSparkline returns a Layout for a sparkline plot: 4-px padding all sides, no axis/legend/title reservation. See D067.

type LegendInputs

type LegendInputs struct {
	Channel    scene.Channel
	Title      string
	Categories []string       // for symbol legends
	Palette    []*scene.Color // for symbol legends
	Position   scene.LegendPosition
	// Continuous gradient legend (optional, overrides Categories):
	Gradient *GradientLegend
}

LegendInputs carries the inputs the encoder collects to build one legend per non-trivial mark channel.

type LinearScale

type LinearScale = scale.LinearScale

LinearScale is re-exported from encode/scale for back-compat.

type LogScale

type LogScale = scale.LogScale

LogScale is re-exported from encode/scale.

type OrdinalScale

type OrdinalScale = scale.OrdinalScale

OrdinalScale is re-exported from encode/scale for back-compat.

type Padding

type Padding struct {
	Top    float64
	Right  float64
	Bottom float64
	Left   float64
}

Padding carries the per-side pixel padding around the plot region. P05 defaults: top 20, right 20, bottom 40 (x-axis room), left 40 (y-axis room). Title (if present) adds 30 to top.

func DefaultPadding

func DefaultPadding(hasTitle bool) Padding

DefaultPadding returns the per-side padding constants P05 uses. hasTitle reserves extra top space (30 px) for a title text element. P06 will compute padding from theme + axis-label metrics rather than hard-coding.

type PointScale

type PointScale = scale.PointScale

PointScale is re-exported from encode/scale.

type PowScale

type PowScale = scale.PowScale

PowScale is re-exported from encode/scale.

type Scale

type Scale = scale.Scale

Scale is the interface satisfied by every per-type scale impl. Re- exported from encode/scale so existing call sites compile unchanged.

func ResolveScale

func ResolveScale(channelType string, kind table.Kind, values []any, rangeMin, rangeMax float64) (Scale, *scene.Warning, error)

ResolveScale picks the right Scale impl for a channel + column kind, computes its domain from the values, and returns the resulting Scale + an optional warning. The rangeMin / rangeMax span the plot region for the channel's orientation; for y-axes the renderer is responsible for the "invert-y" flip via passing (rangeMax, rangeMin).

func ResolveScaleTyped

func ResolveScaleTyped(scaleType scene.ScaleType, values []any, rangeMin, rangeMax float64, opts ScaleOpts) (Scale, *scene.Warning, error)

ResolveScaleTyped accepts an explicit scene.ScaleType (from the spec's `scale.type` field) and resolves the appropriate impl. Used by the encoder once the spec carries a scale.type override.

type ScaleOpts

type ScaleOpts struct {
	Base float64 // log base (default 10 if zero)
	Exp  float64 // pow exponent (default 1 if zero)
}

ScaleOpts carries per-scale knobs (log base, pow exponent, etc.).

type SqrtScale

type SqrtScale = scale.SqrtScale

SqrtScale is re-exported from encode/scale.

type TimeScale

type TimeScale = scale.TimeScale

TimeScale is re-exported from encode/scale for back-compat.

Directories

Path Synopsis
Package format implements a small subset of the d3-format mini-DSL plus a strftime-style mini-mapping for time formats.
Package format implements a small subset of the d3-format mini-DSL plus a strftime-style mini-mapping for time formats.
Package marks holds the per-mark encoders that turn rows of a materialised table into scene.Mark entries with pixel-resolved geometry.
Package marks holds the per-mark encoders that turn rows of a materialised table into scene.Mark entries with pixel-resolved geometry.
layout
Package layout holds the shared graph + tree layout helpers used by the encode/marks tree, dendrogram, and network encoders.
Package layout holds the shared graph + tree layout helpers used by the encode/marks tree, dendrogram, and network encoders.
Package projection maps geographic coordinates (longitude / latitude in degrees) to plot-space pixels for the geoshape mark family.
Package projection maps geographic coordinates (longitude / latitude in degrees) to plot-space pixels for the geoshape mark family.
Package resolve carries cross-layer scale + axis resolution.
Package resolve carries cross-layer scale + axis resolution.
Package scale holds the per-type scale implementations consumed by the encode stage.
Package scale holds the per-type scale implementations consumed by the encode stage.
Package scene holds the Prism Scene IR — the renderer-agnostic intermediate representation produced by the encode stage and consumed by every Renderer (SVG ships in P05; PNG / PDF / canvas land in later phases).
Package scene holds the Prism Scene IR — the renderer-agnostic intermediate representation produced by the encode stage and consumed by every Renderer (SVG ships in P05; PNG / PDF / canvas land in later phases).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL