Skip to main content

ChartML

Struct ChartML 

Source
pub struct ChartML { /* private fields */ }
Expand description

Main ChartML instance. Orchestrates parsing, data fetching, and rendering. Maintains source and parameter registries that persist across render calls, matching the JS ChartML class behavior.

Implementations§

Source§

impl ChartML

Source

pub fn new() -> Self

Create a new empty ChartML instance with the built-in inline and http providers pre-registered. The datasource provider slot is intentionally empty — consumers using data: { datasource: ... } shapes must register their own provider via register_provider("datasource", ...).

Source

pub fn with_defaults() -> Self

Create with default built-in plugins. (No built-in renderers — those come from chartml-chart-* crates)

Source

pub fn register_renderer( &mut self, chart_type: &str, renderer: impl ChartRenderer + 'static, )

Source

pub fn register_data_source( &mut self, name: &str, source: impl DataSource + 'static, )

Source

pub fn register_transform( &mut self, middleware: impl TransformMiddleware + 'static, )

Source

pub fn set_datasource_resolver( &mut self, resolver: impl DatasourceResolver + 'static, )

Source

pub fn set_default_palette(&mut self, colors: Vec<String>)

Set the default color palette for charts that don’t specify style.colors. Matches the JS ChartML setDefaultPalette() API.

Source

pub fn set_theme(&mut self, theme: Theme)

Set the theme for chart chrome colors (axes, grid, text, background). Use Theme::default() for light mode, Theme::dark() for dark mode, or construct a custom Theme to match your application’s appearance.

Source

pub fn theme(&self) -> &Theme

Get a reference to the current theme. Consumers (e.g. chartml-leptos) use this to thread typography into HTML chrome rendered outside the SVG.

Source

pub fn register_component(&mut self, yaml: &str) -> Result<(), ChartError>

Register a non-chart component (source, style, config, params) from a YAML string. Sources are stored in the instance and available to all subsequent render calls. This matches the JS chartml.registerComponent(spec) API.

Source

pub fn register_source(&mut self, name: &str, data: DataTable)

Register a named source directly from a DataTable.

Source

pub fn register_provider( &mut self, kind: &str, provider: impl DataSourceProvider + 'static, )

Register a DataSourceProvider under a dispatch key.

Built-in kinds:

  • "inline" — handles data: { rows: [...] }. Pre-registered; overridable.
  • "http" — handles data: { url: "..." }. Pre-registered; overridable.
  • "datasource" — handles data: { datasource: "slug", query: "..." }. NOT pre-registered. Consumers whose YAML uses the datasource: shape MUST register their own provider under this key (or under an explicit provider: "..." slug the spec also names).

Re-registration replaces the provider for that kind; no merging.

Source

pub fn set_cache(&mut self, backend: impl CacheBackend + 'static)

Replace the tier-1 cache backend (default: MemoryBackend). The new backend starts empty — entries in the old backend are not migrated. Safe to call after resolver() handles have been handed out — the swap is atomic on the shared resolver.

Source

pub fn with_cache(self, backend: impl CacheBackend + 'static) -> Self

Builder-style variant of set_cache. Takes self by value so it can chain off ChartML::new() in a single expression.

Source

pub fn set_namespace(&mut self, slug: impl Into<String>)

Set the tenant / workspace namespace threaded into every resolver cache key. Multi-tenant deployments MUST set this so two tenants sharing a slug name cannot collide in the cache.

Source

pub fn with_namespace(self, slug: impl Into<String>) -> Self

Builder-style variant of set_namespace.

Source

pub fn resolver(&self) -> ResolverRef

Get a clone of the ResolverRef handle (Arc<Resolver> on native, Rc<Resolver> on WASM) so callers can drive the bulk invalidate* API (or inspect registered provider kinds).

Source

pub fn set_hooks(&self, hooks: impl ResolverHooks + 'static)

Register a resolver::ResolverHooks impl. Replaces any previously registered hooks. Pass NullHooks (or call clear_hooks on the resolver handle) to disable observability.

Hook callbacks are fire-and-forget on the current async runtime (tokio::spawn on native, wasm_bindgen_futures::spawn_local on WASM) so a slow telemetry sink can’t stall the resolver. See resolver::ResolverHooks for the safety contract (panic-free, no resolver re-entry, no shared locks).

Source

pub async fn shutdown(&self)

Await graceful shutdown on every registered provider AND cache backend. Called at SSR request end, browser tab close, or explicit host-app lifecycle boundaries. Safe to call multiple times — every provider’s default shutdown is a no-op.

Source

pub fn render_from_yaml(&self, yaml: &str) -> Result<ChartElement, ChartError>

Parse a YAML string and render the chart component(s). Returns the ChartElement tree. Uses default dimensions (800x400) unless the spec overrides them.

Source

pub fn render_from_yaml_with_size( &self, yaml: &str, container_width: Option<f64>, container_height: Option<f64>, ) -> Result<ChartElement, ChartError>

Parse a YAML string and render with an explicit container size. container_width overrides the default width (used when the spec doesn’t specify one). container_height overrides the default height.

Source

pub fn render_from_yaml_with_params( &self, yaml: &str, container_width: Option<f64>, container_height: Option<f64>, param_overrides: Option<&ParamValues>, ) -> Result<ChartElement, ChartError>

Render with explicit param value overrides. param_overrides are current interactive values that take priority over defaults.

Source

pub fn render_chart( &self, chart_spec: &ChartSpec, ) -> Result<ChartElement, ChartError>

Render a parsed ChartSpec into a ChartElement tree.

Source

pub fn render_chart_with_size( &self, chart_spec: &ChartSpec, container_width: Option<f64>, container_height: Option<f64>, ) -> Result<ChartElement, ChartError>

Render a parsed ChartSpec with explicit container dimensions. Spec-level width/height take priority; container size is the fallback.

Source

pub async fn fetch( &self, yaml: &str, opts: &RenderOptions, ) -> Result<FetchedChart, ChartError>

Stage 1 of the chartml 5.0 pipeline: parse YAML, resolve params, and produce a FetchedChart whose sources map contains every named source the chart needs.

Phase 3 dispatch order, per source:

  1. DataRef::Named(n) → look up in pre-registered self.sources. No provider call (this is the chartml-5 fast path: callers that already own the data and registered it via register_source skip the resolver entirely).
  2. DataRef::NamedMap entry whose key matches a pre-registered source → use the registered table. Resolver bypassed for that entry. Other entries route through the resolver in parallel via try_join_all.
  3. DataRef::Inline(flat) without transform → single resolver call, wrapped in a 1-entry map keyed "source".
  4. DataRef::Inline(flat) with transform → normalized to NamedMap { "source": flat } first, then taken through the NamedMap path so transforms see a uniform IndexMap shape.

FetchMetadata.cache_hits / cache_misses / per_source are populated from each resolver call’s ResolveOutcome.

Source

pub async fn transform( &self, fetched: FetchedChart, _opts: &RenderOptions, ) -> Result<PreparedChart, ChartError>

Stage 2: collapse the fetched sources into a single DataTable ready for the renderer. Runs the registered TransformMiddleware when a transform: block is present, falls back to the built-in aggregate-only transform when no middleware is registered, or passes the lone source through unchanged when no transform is declared.

Validation rules (error text begins with the React/JS-matching wording, then appends extra source-count context for debuggability):

  • 0 sources → internal invariant violation (fetch always produces ≥1 entry).
  • 1 source, no transform → passthrough.
  • 1 sources, no transform → error beginning with "Named data sources require a transform block when multiple sources are defined" followed by (got N sources: …) detail.

  • Otherwise → middleware (or built-in fallback for aggregate-only).
Source

pub fn render_prepared_to_svg( &self, prepared: &PreparedChart, opts: &RenderOptions, ) -> Result<String, ChartError>

Stage 3: render an already-prepared chart to an SVG string. Sync and pure — no I/O, no async — so consumers can resize-render from the same PreparedChart repeatedly without re-fetching or re-transforming.

Source

pub async fn render_to_svg_async( &self, yaml: &str, opts: &RenderOptions, ) -> Result<String, ChartError>

Convenience: run the full async pipeline (fetch + transform + render_prepared_to_svg) in one call. Equivalent to chaining the three stages explicitly; use the explicit form when you need to cache the intermediate FetchedChart / PreparedChart.

Source

pub async fn render_from_yaml_with_params_async( &self, yaml: &str, container_width: Option<f64>, container_height: Option<f64>, param_overrides: Option<&ParamValues>, ) -> Result<ChartElement, ChartError>

Async render with full parameter support — mirrors render_from_yaml_with_params but uses the registered TransformMiddleware for ALL transforms (sql, aggregate, forecast). Falls back to built-in sync transform only if no middleware is registered.

Back-compat shim over the chartml 5.0 three-stage pipeline. Returns ChartElement (not String) so existing internal callers (chartml-leptos, chartml-render, npm wrappers) keep compiling unchanged. Will be deprecated in phase 7 once every caller has migrated to render_to_svg_async.

Source

pub async fn render_from_yaml_with_data_async( &self, yaml: &str, data: DataTable, ) -> Result<ChartElement, ChartError>

Async render with external data — for integration tests and programmatic use. Data is used as fallback when spec has empty inline rows.

Source

pub fn registry(&self) -> &ChartMLRegistry

Get a reference to the internal registry.

Source

pub fn registry_mut(&mut self) -> &mut ChartMLRegistry

Get a mutable reference to the internal registry.

Trait Implementations§

Source§

impl Default for ChartML

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more