Pikchr Studio developer API

This is the opt-in introspection API in this app’s vendored renderer. It is not an upstream Pikchr API or a general SVG-to-Pikchr converter. Ordinary pikchr() remains available independently.

Contract and version

The native result currently contains version: 2. This is an experimental contract: pin the renderer and wrapper together, check the version before consuming geometry, and run compatibility tests when updating either. There is no schemaVersion field, schema negotiation, or stable cross-version object identity.

The source of truth is vendor/pikchr.y, with the exported C declaration in vendor/studio.h. vendor/check.cjs checks geometry, spans and sub-spans, comment exclusion, complete dependencies, class/flag passthrough, invalid UTF-8 repair, unsupported-object guards, allocation/free use, and legacy rendering equivalence against the locally available upstream fixtures. The studio patch is compiled in with -DPIKCHR_STUDIO; without that define the vendored source builds as plain upstream Pikchr. The native CLI accepts --studio to print the same JSON.

C and WebAssembly ownership

char *pikchr_studio(const char *source, const char *cls, unsigned flags);

cls and flags behave exactly as for pikchr(): cls adds class="…" to the <svg> element or may be NULL; flags is a bitmask of PIKCHR_PLAINTEXT_ERRORS (1) and PIKCHR_DARK_MODE (2). Without the plaintext flag, error contains Pikchr's HTML diagnostic. Pass a NUL-terminated UTF-8 string. The returned pointer owns a NUL-terminated UTF-8 JSON allocation. Copy or parse its contents, then release it with free(), including renderer-error results. Check for a null pointer before reading it. Do not pass embedded NUL characters: they terminate the C input.

const module = await initPikchrModule();
const render = module.cwrap('pikchr_studio', 'number', ['string', 'string', 'number']);
const pointer = render(source, null, 1);
if (!pointer) throw new Error('Renderer allocation failed');
let result;
try {
  result = JSON.parse(module.UTF8ToString(pointer));
} finally {
  module._free(pointer);
}

The worker performs this copy-and-free cycle for callers. The returned JavaScript object no longer depends on WASM memory.

Native JSON result

FieldCurrent meaning
versionInteger 2. Version 2 added spans, complete dependencies, and the cls/flags parameters.
svgRendered SVG string on success; empty string on parser/render failure.
errornull on success, otherwise a diagnostic string: plain text when flag 1 is set (the worker default), Pikchr's HTML otherwise. Display plain-text diagnostics as text, not HTML.
objectsFlat array of object records. Nested lists are recursively included after their containing object. Empty on render failure; valid empty source also has no objects.
transformObject containing numeric a, b, c, d, e, f for world-to-SVG coordinates. Do not use error-result geometry or invert a singular transform.

Object records

FieldCurrent meaning
idRender-local string such as o1. SVG groups carry the corresponding data-pikchr-id. IDs are not persistent document IDs.
name, kindPikchr object name, or empty string for unnamed objects; native primitive type name. Names need not be globally unique.
span{start, end}, half-open UTF-8 byte offsets into this exact source; identical to spans.statement and kept for compatibility. Unavailable provenance can be {start:-1,end:-1}. Ranges exclude the terminating statement separator, trailing whitespace, and trailing #, // or /* */ comments, so replacing a whole span never deletes a comment. Nested ranges can overlap enclosing ranges.
spans{statement, label, placement}, each {start,end} or null. statement equals span. label is the first string literal of the statement including its quotes, or null. placement is the last top-level at … or with … at … clause, from its keyword to the end of the position expression, or null when the object has no explicit placement. Macro-expanded objects have null sub-spans. Path movement (from, to, then, even with) is not a placement.
center{x,y}, the native placement point.
bbox{x,y,width,height}, native bounds with lower-left origin in world coordinates.
anchorsNamed points c,n,s,e,w,ne,nw,se,sw, each {x,y}, computed by the renderer.
pathOrdered native path points, each {x,y}. Usually empty for shapes. It is not an SVG command stream, outline tessellation, or complete curve representation.
editableCoarse renderer eligibility for movement: named top-level supported native shapes with usable provenance, outside macro expansion. It does not guarantee that an arbitrary source expression can be edited safely.
reasonEmpty when renderer-eligible; otherwise a human-readable explanation. This is not a stable machine-readable error code.
dependenciesCompleteAlways true since version 2.
dependenciesDeduplicated render-local IDs of every object this statement resolved by name or ordinal while parsing: at, with … at, from, to, then, even with, same as, behind, last box, 2nd circle, vertex and property references such as A.width. The object itself is excluded. Variables and macros are not tracked, and the list is direct, not transitive: compute dependents by inverting it across objects.

There are no exported depth, parent, or macro fields. Do not invent them when interpreting native results. Macro and nested provenance restrictions are represented by eligibility/reason and, where available, source ranges. Additional conservative checks belong in the edit layer.

Coordinates and pointer mapping

World geometry uses inches, with positive y pointing upward. SVG coordinates use the supplied affine transform:

svgX = a * worldX + c * worldY + e
svgY = b * worldX + d * worldY + f

The current renderer emits b=0, c=0, a=scale, d=-scale, with translation derived from the rendered bounds. Do not hard-code a scale or treat world inches as CSS pixels. Convert browser pointer coordinates through the inverse SVG screen matrix, then the inverse world transform. Handle missing matrices and singular transforms.

const t = result.transform;
const worldToSvg = new DOMMatrix([t.a, t.b, t.c, t.d, t.e, t.f]);
const screen = svgElement.getScreenCTM();
if (!screen) throw new Error('SVG is not displayed');
const worldPoint = new DOMPoint(event.clientX, event.clientY)
  .matrixTransform(screen.inverse())
  .matrixTransform(worldToSvg.inverse());

Source spans, suggestions, and stale results

JavaScript string indices use UTF-16 code units; source spans use UTF-8 bytes. Never pass native spans directly to slice() or setSelectionRange(). Use byteOffsetToIndex() from edits.js, which rejects out-of-range offsets and offsets splitting a UTF-8 character.

import {byteOffsetToIndex, applyPatch} from './edits.js';
const start = byteOffsetToIndex(source, object.span.start);
const end = byteOffsetToIndex(source, object.span.end);
const statement = source.slice(start, end);

Edit candidates carry {label, source, patch}; creation/conversion candidates also carry selectName. Patches contain {base,start,end,expected,text}. applyPatch() requires the exact base document and expected old text, and translates byte offsets. An accepted patch is still subject to rendering validation. Re-render every candidate through Pikchr before offering acceptance; never use SVG movement alone as proof of valid source.

Keep a source revision and request ID for each render. Ignore results for older source, invalidate old selections and suggestions after manual edits, and block manipulation of a stale diagram. If retaining a last-valid diagram after a failure, label it clearly. Match names only when unique; never reuse an old oN ID as a persistent selection.

Worker protocol and limits

const worker = new Worker('./worker.js');
worker.postMessage({id: 1, source: 'A: box "Hello" at (0,0)'});
worker.onmessage = ({data}) => {
  // data = {id, result}; verify this id is still current first.
  if (data.result.error) {
    showErrorAsText(data.result.error);
    return;
  }
  if (data.result.version !== 2) throw new Error('Unsupported API version');
  // Consume data.result.svg and data.result.objects.
};

Request id must be a nonnegative safe integer. Invalid requests without usable IDs and duplicate live IDs are silently ignored; they do not receive error responses. Use a fresh ID for each outstanding request. Source must be a string without NUL characters. Optional cls (short class string or null) and flags (0–3, default 1) pass through to the native call; invalid values receive an error response.

The worker accepts at most 100000 UTF-8 bytes, not 100000 JavaScript characters, and permits at most 32 pending requests while initialization/render requests await completion. An over-capacity request with a valid ID receives a busy error. These are wrapper policies, not C API limits. Initialization failures, input rejection, allocation failure, JSON parsing failure, and other wrapper errors can produce only {id,result:{error:message}}; svg, objects, transform, and version are not guaranteed on that path. Allocated results are freed on success and failure.

The renderer also has its native token limit, currently defined as PIKCHR_TOKEN_LIMIT 100000. Byte and token limits are different. The worker does not currently provide request cancellation, a time budget, or a complete hostile-input sandbox. Hosts should bound requests, handle worker errors/timeouts, and terminate/recreate a worker if their application requires cancellation or recovery.

Supported editing is narrower than rendering

The edit modules deliberately refuse unsupported syntax rather than rewriting the document. Macro-expanded and nested objects remain inspect-only. Shape conversion requires a supported named native primitive with one explicit numeric center placement and conservative attributes. Creation uses native box, circle, ellipse, oval, cylinder, or diamond syntax; triangle/trapezoid construction is not supplied by this API.

Connector edits recognize explicit named endpoint references and the app’s generated routes. Literal bend editing changes a supported numeric vertex tuple while preserving surrounding route source. Route presets and lane controls can replace the entire path. These operations do not understand arbitrary expressions, every possible Pikchr path, or obstacle avoidance. A renderer-level editable:false on an arrow does not itself prohibit the separately validated connector operations. Ask the appropriate edit API whether it can safely handle the specific source.

Because dependency metadata is incomplete, preview the entire re-rendered diagram and compare geometry to explain affected objects. Do not claim that an empty dependency list means an object is independent.

Host responsibilities

Serve worker.js, pikchr.js, and pikchr.wasm together over HTTP with an appropriate WebAssembly MIME type and worker policy. Keep untrusted source and error strings out of HTML insertion paths; only use the renderer’s SVG output for the diagram, with isolation or sanitization appropriate to your threat model. Keep the worker off the UI thread, provide loading/error states, and preserve keyboard alternatives to dragging. User source remains the canonical document; persistence, undo history, export, and approval of suggested edits belong to the host.

See the embedding example for a small consumer, or user help for editor behavior.