graphein 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -3873,6 +3873,14 @@ interface RenderOptions {
3873
3873
  * flat so the chrome isn't doubled. Optional; defaults to false.
3874
3874
  */
3875
3875
  frame?: boolean;
3876
+ /**
3877
+ * Publish the chart's effective config (spec minus `data`) to a
3878
+ * `data-graphein-spec` DOM attribute on the root and re-render when an external
3879
+ * tool edits it (merging the edit with the chart's in-memory data). Lets browser
3880
+ * tools identify and live-edit the chart from the DOM. Optional; defaults to true.
3881
+ * Set `false` to opt out (no attribute, no observer).
3882
+ */
3883
+ inspect?: boolean;
3876
3884
  }
3877
3885
  interface ChartInstance {
3878
3886
  /** Re-render with a new spec (data or config changes). */
@@ -3912,6 +3920,62 @@ declare global {
3912
3920
  }
3913
3921
  declare function render(target: HTMLElement | string, spec: ChartSpec, options?: RenderOptions): ChartInstance;
3914
3922
 
3923
+ /**
3924
+ * DOM spec publishing — makes a rendered chart identifiable and editable by
3925
+ * external tools (agents, devtools extensions, page scripts) straight from the
3926
+ * DOM, with no JS handle required.
3927
+ *
3928
+ * Each chart/dashboard root carries:
3929
+ * - `data-graphein-spec`: the effective spec **minus its `data` array** (config
3930
+ * only), JSON-serialized. Compact, and no row-level data leaks into the DOM.
3931
+ * - `data-graphein-type`: the chart/dashboard `type`, so a tool can find and
3932
+ * filter Graphein visuals cheaply (`querySelectorAll('[data-graphein-spec]')`)
3933
+ * without parsing JSON.
3934
+ *
3935
+ * Editing `data-graphein-spec` is **two-way**: a {@link MutationObserver} reports
3936
+ * the change and the runtime re-renders, merging the edited config with the
3937
+ * chart's existing in-memory data (see the runtime's `onExternalEdit`). Malformed
3938
+ * edits are ignored so a tool can't break a live chart mid-keystroke.
3939
+ */
3940
+ /** Attribute holding the JSON-serialized config (spec without `data`). */
3941
+ declare const SPEC_ATTR = "data-graphein-spec";
3942
+ /** Attribute holding the chart/dashboard type, for cheap querying. */
3943
+ declare const TYPE_ATTR = "data-graphein-type";
3944
+ interface SpecLike {
3945
+ type?: unknown;
3946
+ data?: unknown;
3947
+ }
3948
+ /** A shallow copy of a spec without its top-level `data` array (config only). */
3949
+ declare function stripData<T extends SpecLike>(spec: T): Omit<T, 'data'>;
3950
+ /** Serialize a spec's config (its `data` excluded) to a JSON string. */
3951
+ declare function serializeSpec(spec: SpecLike): string;
3952
+ interface Inspector {
3953
+ /**
3954
+ * Publish `spec`'s config to the root. Writes `data-graphein-spec` only when the
3955
+ * serialized config actually changed (so resize/animation frames don't churn the
3956
+ * DOM), and refreshes `data-graphein-type`.
3957
+ */
3958
+ write(spec: SpecLike): void;
3959
+ /** Stop observing. Leaves the published attributes in place. */
3960
+ destroy(): void;
3961
+ }
3962
+ interface InspectorOptions {
3963
+ /**
3964
+ * Invoked when an external agent edits `data-graphein-spec` to a value the
3965
+ * inspector didn't write, with the parsed config object. JSON parse failures and
3966
+ * non-object payloads are swallowed (the last good render is kept).
3967
+ */
3968
+ onExternalEdit(config: Record<string, unknown>): void;
3969
+ }
3970
+ /**
3971
+ * Wire spec-publishing + two-way editing onto a chart/dashboard root element.
3972
+ *
3973
+ * The {@link MutationObserver} is created only when the API exists, so this is a
3974
+ * no-op observer in SSR/Node/headless environments (attributes are still set,
3975
+ * which is harmless).
3976
+ */
3977
+ declare function createInspector(root: HTMLElement, options: InspectorOptions): Inspector;
3978
+
3915
3979
  /**
3916
3980
  * Dashboard auto-wiring — pure spec rewriting that turns a set of views into
3917
3981
  * cross-interacting ones by injecting `params` (sources), `highlight`, and
@@ -3955,6 +4019,13 @@ declare function wireViews(views: DashboardView[], interactions: 'auto' | 'none'
3955
4019
  interface RenderDashboardOptions {
3956
4020
  /** Share a bus with charts/dashboards outside this one. */
3957
4021
  store?: SelectionStore;
4022
+ /**
4023
+ * Publish each view's config (and the dashboard's) to `data-graphein-spec` DOM
4024
+ * attributes and re-render on external edits, so browser tools can identify and
4025
+ * live-edit the page from the DOM. Optional; defaults to true. Set `false` to opt
4026
+ * out for the whole dashboard (propagates to every view).
4027
+ */
4028
+ inspect?: boolean;
3958
4029
  }
3959
4030
  interface DashboardInstance {
3960
4031
  /** Re-render with a new dashboard spec (keeps the shared store/selection). */
@@ -4017,4 +4088,4 @@ declare function renderDashboard(target: HTMLElement | string, spec: DashboardSp
4017
4088
  */
4018
4089
  declare const VERSION = "0.1.0";
4019
4090
 
4020
- export { type AggOp, type AggregateOp, type AggregateTransform, type AnimateOptions, type AnimationConfig, type AnimationHandle, type Annotation, type AnySpec, type ArcOptions, type AreaOptions, type AreaPoint, type AreaSpec, type AxesConfig, type AxisConfig, type AxisInput, type BackingSize, type BandScale, type BandScaleOptions, type BarSpec, type BaseSlicerSpec, type BaseSpec, type BinLayout, type BinTransform, type BoxSpec, type BuildOptions, type BulletSpec, CARTESIAN_TYPES, CHART_TYPES, type CalculateTransform, type CalendarHeatmapSpec, CanvasLayer, type CanvasPillStyle, type CanvasTextCmd, type CartesianChartSpec, type CartesianInteractionBuilder, type CartesianModel, type CartesianRenderer, type CategoryInsights, type ChartInsights, type ChartInstance, type ChartSpec, type ChartSummary, type ChartType, type ChoroplethSpec, type ColorScale, type ColumnProfile, type ComboAxisModel, type ComboLayer, type ComboLayerModel, type ComboMark, type ComboModel, type ComboSide, type ComboSpec, type Comparable, type ConditionalFormat, type ContinuousScale, type ControllerSelect, type Curve, type CurveType, type CustomRenderer, DEFAULT_ENTRANCE_DURATION, DEFAULT_ROUGH_STYLE, DEFAULT_UPDATE_DURATION, DIM_ALPHA, type DashboardCell, type DashboardInstance, type DashboardLayout, type DashboardResponsiveSpan, type DashboardSection, type DashboardSpec, type DashboardView, type DateRangeSlicerSpec, type Datum, type DecimateOptions, type Dimensions, type DropdownSlicerSpec, type DumbbellSpec, type EasingFunction, type Emphasis, type Encoding, type EntranceContext, ExpressionError, type Extent, FACETABLE_TYPES, FUNCTION_NAMES, type FacetConfig, type FacetLayout, type FacetPanel, type FieldDef, type FieldType, type FieldValue, type FillStyle, type FilterClause, type FilterPredicate, type FilterTransform, type FoldTransform, type Frame, type FrameInput, type FunnelSpec, type GaugeSpec, type GeoFeature, type GeoFeatureCollection, type GeoGeometry, type GeoMultiPolygon, type GeoPolygon, type GeoPosition, type GroupedMap, type HachureSegment, type HeadlessTarget, type HeatmapSpec, type HighlightConfig, type HistogramBin, type HistogramBinDatum, type HistogramModel, type HistogramSpec, type Hover, type IconRule, type Insets, type InsightFamily, type InsightOptions, InteractionController, type InteractionLink, type InteractionModel, type Interpolator, type JsonPatchOp, type KpiComparison, type KpiSpec, type LegendConfig, type LegendHitRegion, type LegendItem, type LegendPosition, type LegendSymbol, type LineOptions, type LineSpec, type LinearScaleOptions, type LintFinding, type ListSlicerSpec, type LiteralPredicate, type LogScaleOptions, type MapProjection, type MarkOptions, type MatrixSpec, type MatrixValueDef, NO_PADDING, type NumberFormatSpec, type OKLCH, type OKLab, type OverlayTextOpts, type PathSink, type PieLabels, type PieSpec, type PivotCell, type PivotFlatRow, type PivotHeaderNode, type PivotOptions, type PivotResult, type PivotValueDef, type Point, type PointRef, type PointScale, type PointScaleOptions, type PointSelection, type PositionedLegendItem, type RGBA, type RangeSelection, type RangeSlicerSpec, type RecommendOptions, type RecommendedChart, type Rect, type RegressionFit, type RenderContext, type RenderDashboardOptions, type RenderDiagnostic, type RenderOptions, type RenderReport, type RepairResult, type ReportInput, type ReportSeverity, type ResolvedEntrance, type ResolvedSeries, type ResolvedSketch, type Rng, type RoughContext, RoughPen, type RoughStyle, SKETCH_FONT_FAMILY, SKETCH_FONT_NAME, SLICER_TYPES, SR_ONLY_STYLE, type SankeySpec, type ScaleConfig, type ScaleType, type ScatterInsights, type ScatterSpec, type SearchSlicerSpec, type SelectConfig, type SelectionChangeListener, type SelectionDef, type SelectionListener, type SelectionParam, type SelectionStore, type SelectionValue, type SeriesInsights, type SetSelection, type SharedScales, type Size, type SketchConfig, type SlicerSpec, type SlicerType, type SlopeSpec, Surface, TICK_SIZE, TIME_UNITS, TRANSFORM_KINDS, type TableColumn, type TableSpec, type TextMetricsLite, type TextSelection, type ThemeColors, type ThemeFont, type ThemeInput, type ThemeTokens, type Tick, type TimeScaleOptions, type TimeUnit, type TimeUnitTransform, type TitleConfig, type TitleInput, Tooltip, type TooltipConfig, type TooltipContent, type TooltipRow, type Transform, type TreemapSpec, type TrendlineConfig, type UpdateContext, VERSION, type ValidationError, type ValidationResult, type ValueInsights, type ValueRef, type ValueRule, type WaterfallSpec, type WiredView, type XKind, type XModel, type YModel, aggregateValues, analyzeChart, animate, applyA11y, applyAggregate, applyBin, applyCalculate, applyFilter, applyFold, applyPatch, applyPick, applyTimeUnit, applyTransform, applyTransforms, arc, area, assertValidSpec, autoInsightAnnotations, backOut, bandScale, bounceOut, buildCartesianInteraction, buildCartesianModel, buildComboModel, buildDataTableFallback, buildFacetModels, buildHistogramModel, buildRenderReport, cartesianInteractionBuilders, cartesianRenderers, categorical, categoricalSchemes, chartTitleText, chartTypeLabel, checkExpression, clamp01, clamp255, compileExpression, compilePredicate, computeBackingSize, computeBins, computeFrame, computeSeriesInsights, contrastRatio, createDiv, createRoughPen, createSelectionStore, cubicIn, cubicInOut, cubicOut, curveCatmullRom, curveLinear, curveMonotoneX, curveStep, curveStepAfter, curveStepBefore, customRenderers, darkTheme, decimate, defaultSpan, dependentParams, diverging, divergingColorScale, divergingSchemes, drawAnnotationLabels, drawAnnotations, drawAxesUnderlay, drawFacet, drawLegend, drawOverlay, drawTitle, drawTrendlineLabels, drawTrendlines, easings, elasticOut, ellipsize, ensureSketchFont, expoInOut, expoOut, facetReport, fillParentStyle, filterRows, fontString, formatDate, formatNumber, formatValue, getDevicePixelRatio, groupBy, hashString, inferFieldType, inferFieldTypes, inferValueType, inheritInto, interpolateArray, interpolateNumber, interpolateNumberArray, interpolateObject, interpolateOklab, interpolateRgb, isBrowser, isEmptyValue, isFaceted, isParamClause, isSlicerType, keyFields, legendSwatchWidth, lightTheme, line, linear, linearRegression, linearScale, linearToSrgb, lintSpec, literalToValue, logScale, lttbRun, makeMatcher, matchesValue, measureText, monotoneXTangents, mulberry32, niceDomain, oklabToOklch, oklabToRgb, oklchToOklab, ordinalColorScale, overlayTextToCanvasCmd, paintCanvasText, paintLegendSwatch, parseColor, parseNumberFormat, pivot, placeViews, pointScale, polygonHachureLines, prefersReducedMotion, prettyDate, profileColumns, quadIn, quadInOut, quadOut, rampFromStops, readableTextColor, recommendChart, relativeLuminance, render, renderDashboard, renderToContext, repairReport, repairSpec, resolveCurve, resolveDashboardLayout, resolveDashboardSections, resolveEmphasis, resolveEntrance, resolveFilterValues, resolveInsightOptions, resolveSketch, resolveTheme, resolveUpdate, resolveValueRef, rgbToOklab, rgbaToCss, rotatePoint, roundedRect, sampleArc, sequential, sequentialColorScale, sequentialSchemes, setMeasureContext, setStyle, sinInOut, slicerParamName, smartDate, specFields, srgbToLinear, summarize, summarizeChart, themes, tickIncrement, tickStep, ticks, timeScale, timeTickFormat, timeTicks, toHex, toPointer, tooltipEnabled, truncateTo, validateDashboard, validateSpec, wireViews, withAlpha, withSketchFont };
4091
+ export { type AggOp, type AggregateOp, type AggregateTransform, type AnimateOptions, type AnimationConfig, type AnimationHandle, type Annotation, type AnySpec, type ArcOptions, type AreaOptions, type AreaPoint, type AreaSpec, type AxesConfig, type AxisConfig, type AxisInput, type BackingSize, type BandScale, type BandScaleOptions, type BarSpec, type BaseSlicerSpec, type BaseSpec, type BinLayout, type BinTransform, type BoxSpec, type BuildOptions, type BulletSpec, CARTESIAN_TYPES, CHART_TYPES, type CalculateTransform, type CalendarHeatmapSpec, CanvasLayer, type CanvasPillStyle, type CanvasTextCmd, type CartesianChartSpec, type CartesianInteractionBuilder, type CartesianModel, type CartesianRenderer, type CategoryInsights, type ChartInsights, type ChartInstance, type ChartSpec, type ChartSummary, type ChartType, type ChoroplethSpec, type ColorScale, type ColumnProfile, type ComboAxisModel, type ComboLayer, type ComboLayerModel, type ComboMark, type ComboModel, type ComboSide, type ComboSpec, type Comparable, type ConditionalFormat, type ContinuousScale, type ControllerSelect, type Curve, type CurveType, type CustomRenderer, DEFAULT_ENTRANCE_DURATION, DEFAULT_ROUGH_STYLE, DEFAULT_UPDATE_DURATION, DIM_ALPHA, type DashboardCell, type DashboardInstance, type DashboardLayout, type DashboardResponsiveSpan, type DashboardSection, type DashboardSpec, type DashboardView, type DateRangeSlicerSpec, type Datum, type DecimateOptions, type Dimensions, type DropdownSlicerSpec, type DumbbellSpec, type EasingFunction, type Emphasis, type Encoding, type EntranceContext, ExpressionError, type Extent, FACETABLE_TYPES, FUNCTION_NAMES, type FacetConfig, type FacetLayout, type FacetPanel, type FieldDef, type FieldType, type FieldValue, type FillStyle, type FilterClause, type FilterPredicate, type FilterTransform, type FoldTransform, type Frame, type FrameInput, type FunnelSpec, type GaugeSpec, type GeoFeature, type GeoFeatureCollection, type GeoGeometry, type GeoMultiPolygon, type GeoPolygon, type GeoPosition, type GroupedMap, type HachureSegment, type HeadlessTarget, type HeatmapSpec, type HighlightConfig, type HistogramBin, type HistogramBinDatum, type HistogramModel, type HistogramSpec, type Hover, type IconRule, type Insets, type InsightFamily, type InsightOptions, type Inspector, type InspectorOptions, InteractionController, type InteractionLink, type InteractionModel, type Interpolator, type JsonPatchOp, type KpiComparison, type KpiSpec, type LegendConfig, type LegendHitRegion, type LegendItem, type LegendPosition, type LegendSymbol, type LineOptions, type LineSpec, type LinearScaleOptions, type LintFinding, type ListSlicerSpec, type LiteralPredicate, type LogScaleOptions, type MapProjection, type MarkOptions, type MatrixSpec, type MatrixValueDef, NO_PADDING, type NumberFormatSpec, type OKLCH, type OKLab, type OverlayTextOpts, type PathSink, type PieLabels, type PieSpec, type PivotCell, type PivotFlatRow, type PivotHeaderNode, type PivotOptions, type PivotResult, type PivotValueDef, type Point, type PointRef, type PointScale, type PointScaleOptions, type PointSelection, type PositionedLegendItem, type RGBA, type RangeSelection, type RangeSlicerSpec, type RecommendOptions, type RecommendedChart, type Rect, type RegressionFit, type RenderContext, type RenderDashboardOptions, type RenderDiagnostic, type RenderOptions, type RenderReport, type RepairResult, type ReportInput, type ReportSeverity, type ResolvedEntrance, type ResolvedSeries, type ResolvedSketch, type Rng, type RoughContext, RoughPen, type RoughStyle, SKETCH_FONT_FAMILY, SKETCH_FONT_NAME, SLICER_TYPES, SPEC_ATTR, SR_ONLY_STYLE, type SankeySpec, type ScaleConfig, type ScaleType, type ScatterInsights, type ScatterSpec, type SearchSlicerSpec, type SelectConfig, type SelectionChangeListener, type SelectionDef, type SelectionListener, type SelectionParam, type SelectionStore, type SelectionValue, type SeriesInsights, type SetSelection, type SharedScales, type Size, type SketchConfig, type SlicerSpec, type SlicerType, type SlopeSpec, Surface, TICK_SIZE, TIME_UNITS, TRANSFORM_KINDS, TYPE_ATTR, type TableColumn, type TableSpec, type TextMetricsLite, type TextSelection, type ThemeColors, type ThemeFont, type ThemeInput, type ThemeTokens, type Tick, type TimeScaleOptions, type TimeUnit, type TimeUnitTransform, type TitleConfig, type TitleInput, Tooltip, type TooltipConfig, type TooltipContent, type TooltipRow, type Transform, type TreemapSpec, type TrendlineConfig, type UpdateContext, VERSION, type ValidationError, type ValidationResult, type ValueInsights, type ValueRef, type ValueRule, type WaterfallSpec, type WiredView, type XKind, type XModel, type YModel, aggregateValues, analyzeChart, animate, applyA11y, applyAggregate, applyBin, applyCalculate, applyFilter, applyFold, applyPatch, applyPick, applyTimeUnit, applyTransform, applyTransforms, arc, area, assertValidSpec, autoInsightAnnotations, backOut, bandScale, bounceOut, buildCartesianInteraction, buildCartesianModel, buildComboModel, buildDataTableFallback, buildFacetModels, buildHistogramModel, buildRenderReport, cartesianInteractionBuilders, cartesianRenderers, categorical, categoricalSchemes, chartTitleText, chartTypeLabel, checkExpression, clamp01, clamp255, compileExpression, compilePredicate, computeBackingSize, computeBins, computeFrame, computeSeriesInsights, contrastRatio, createDiv, createInspector, createRoughPen, createSelectionStore, cubicIn, cubicInOut, cubicOut, curveCatmullRom, curveLinear, curveMonotoneX, curveStep, curveStepAfter, curveStepBefore, customRenderers, darkTheme, decimate, defaultSpan, dependentParams, diverging, divergingColorScale, divergingSchemes, drawAnnotationLabels, drawAnnotations, drawAxesUnderlay, drawFacet, drawLegend, drawOverlay, drawTitle, drawTrendlineLabels, drawTrendlines, easings, elasticOut, ellipsize, ensureSketchFont, expoInOut, expoOut, facetReport, fillParentStyle, filterRows, fontString, formatDate, formatNumber, formatValue, getDevicePixelRatio, groupBy, hashString, inferFieldType, inferFieldTypes, inferValueType, inheritInto, interpolateArray, interpolateNumber, interpolateNumberArray, interpolateObject, interpolateOklab, interpolateRgb, isBrowser, isEmptyValue, isFaceted, isParamClause, isSlicerType, keyFields, legendSwatchWidth, lightTheme, line, linear, linearRegression, linearScale, linearToSrgb, lintSpec, literalToValue, logScale, lttbRun, makeMatcher, matchesValue, measureText, monotoneXTangents, mulberry32, niceDomain, oklabToOklch, oklabToRgb, oklchToOklab, ordinalColorScale, overlayTextToCanvasCmd, paintCanvasText, paintLegendSwatch, parseColor, parseNumberFormat, pivot, placeViews, pointScale, polygonHachureLines, prefersReducedMotion, prettyDate, profileColumns, quadIn, quadInOut, quadOut, rampFromStops, readableTextColor, recommendChart, relativeLuminance, render, renderDashboard, renderToContext, repairReport, repairSpec, resolveCurve, resolveDashboardLayout, resolveDashboardSections, resolveEmphasis, resolveEntrance, resolveFilterValues, resolveInsightOptions, resolveSketch, resolveTheme, resolveUpdate, resolveValueRef, rgbToOklab, rgbaToCss, rotatePoint, roundedRect, sampleArc, sequential, sequentialColorScale, sequentialSchemes, serializeSpec, setMeasureContext, setStyle, sinInOut, slicerParamName, smartDate, specFields, srgbToLinear, stripData, summarize, summarizeChart, themes, tickIncrement, tickStep, ticks, timeScale, timeTickFormat, timeTicks, toHex, toPointer, tooltipEnabled, truncateTo, validateDashboard, validateSpec, wireViews, withAlpha, withSketchFont };
package/dist/index.js CHANGED
@@ -17450,6 +17450,54 @@ function onFontsReady(cb) {
17450
17450
  });
17451
17451
  }
17452
17452
 
17453
+ // src/runtime/inspect.ts
17454
+ var SPEC_ATTR = "data-graphein-spec";
17455
+ var TYPE_ATTR = "data-graphein-type";
17456
+ function stripData(spec) {
17457
+ const { data: _data, ...config } = spec;
17458
+ return config;
17459
+ }
17460
+ function serializeSpec(spec) {
17461
+ return JSON.stringify(stripData(spec));
17462
+ }
17463
+ function createInspector(root, options) {
17464
+ let lastWritten = null;
17465
+ let disposed = false;
17466
+ const write = (spec) => {
17467
+ const type = typeof spec.type === "string" ? spec.type : "";
17468
+ if (type) root.setAttribute(TYPE_ATTR, type);
17469
+ const json = serializeSpec(spec);
17470
+ if (json === lastWritten) return;
17471
+ lastWritten = json;
17472
+ root.setAttribute(SPEC_ATTR, json);
17473
+ };
17474
+ let observer;
17475
+ if (typeof MutationObserver !== "undefined") {
17476
+ observer = new MutationObserver(() => {
17477
+ if (disposed) return;
17478
+ const current = root.getAttribute(SPEC_ATTR);
17479
+ if (current == null || current === lastWritten) return;
17480
+ let parsed;
17481
+ try {
17482
+ parsed = JSON.parse(current);
17483
+ } catch {
17484
+ return;
17485
+ }
17486
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
17487
+ lastWritten = current;
17488
+ options.onExternalEdit(parsed);
17489
+ });
17490
+ observer.observe(root, { attributes: true, attributeFilter: [SPEC_ATTR] });
17491
+ }
17492
+ return {
17493
+ write,
17494
+ destroy() {
17495
+ disposed = true;
17496
+ observer?.disconnect();
17497
+ }
17498
+ };
17499
+ }
17500
+
17453
17501
  // src/runtime/render.ts
17454
17502
  var CANVAS_MARK_TYPES = /* @__PURE__ */ new Set([
17455
17503
  "line",
@@ -17727,6 +17775,7 @@ function render(target, spec, options) {
17727
17775
  interaction.setSelect(null);
17728
17776
  }
17729
17777
  applyA11y(surface, currentSpec);
17778
+ inspector?.write(currentSpec);
17730
17779
  lastReport = facetRpt ?? buildRenderReport({
17731
17780
  type,
17732
17781
  spec: currentSpec,
@@ -17776,6 +17825,46 @@ function render(target, spec, options) {
17776
17825
  });
17777
17826
  observer.observe(container);
17778
17827
  }
17828
+ const update = (next) => {
17829
+ updateTransition?.cancel();
17830
+ updateTransition = void 0;
17831
+ for (const param of next.params ?? []) {
17832
+ if (param.value !== void 0 && store.get(param.name) == null) {
17833
+ store.set(param.name, param.value ?? null);
17834
+ }
17835
+ }
17836
+ const prevType = currentSpec.type;
17837
+ const prevW = surface.width;
17838
+ const prevH = surface.height;
17839
+ const anim = resolveUpdate(next.animation, {
17840
+ reducedMotion: prefersReducedMotion(),
17841
+ disabled: globalThis.__GRAPHEIN_DISABLE_ANIM === true
17842
+ });
17843
+ const wantFade = anim.enabled && CANVAS_MARK_TYPES.has(prevType) && CANVAS_MARK_TYPES.has(next.type);
17844
+ const before = wantFade ? snapshotLayer(surface.marks) : void 0;
17845
+ const prevValue = lastValue;
17846
+ const prevCompare = lastCompare;
17847
+ const prevSparkline = lastSparkline;
17848
+ const wantValueTween = prevType === next.type && (COUNT_UP_TYPES.has(next.type) || SWEEP_TYPES.has(next.type)) && prevValue != null;
17849
+ const wantSparklineTween = prevType === next.type && next.type === "kpi" && prevSparkline != null && prevSparkline.length > 0;
17850
+ currentSpec = next;
17851
+ draw(
17852
+ false,
17853
+ wantValueTween ? prevValue ?? void 0 : void 0,
17854
+ wantValueTween ? prevCompare ?? void 0 : void 0,
17855
+ wantValueTween || wantSparklineTween ? prevSparkline ?? void 0 : void 0
17856
+ );
17857
+ if (before && surface.width === prevW && surface.height === prevH && surface.marks.canvas.width === before.width && surface.marks.canvas.height === before.height) {
17858
+ updateTransition = runUpdateCrossfade(surface, before, anim);
17859
+ }
17860
+ };
17861
+ const onExternalEdit = (config) => {
17862
+ if (destroyed) return;
17863
+ const merged = { ...config, data: currentSpec.data };
17864
+ if (validateSpec(merged).errors.length > 0) return;
17865
+ update(merged);
17866
+ };
17867
+ const inspector = options?.inspect === false ? void 0 : createInspector(surface.root, { onExternalEdit });
17779
17868
  const unsubscribe = store.subscribe((name, value) => {
17780
17869
  for (const listener of [...hostListeners]) listener(name, value);
17781
17870
  if (destroyed) return;
@@ -17818,37 +17907,7 @@ function render(target, spec, options) {
17818
17907
  hostListeners.delete(listener);
17819
17908
  },
17820
17909
  update(next) {
17821
- updateTransition?.cancel();
17822
- updateTransition = void 0;
17823
- for (const param of next.params ?? []) {
17824
- if (param.value !== void 0 && store.get(param.name) == null) {
17825
- store.set(param.name, param.value ?? null);
17826
- }
17827
- }
17828
- const prevType = currentSpec.type;
17829
- const prevW = surface.width;
17830
- const prevH = surface.height;
17831
- const anim = resolveUpdate(next.animation, {
17832
- reducedMotion: prefersReducedMotion(),
17833
- disabled: globalThis.__GRAPHEIN_DISABLE_ANIM === true
17834
- });
17835
- const wantFade = anim.enabled && CANVAS_MARK_TYPES.has(prevType) && CANVAS_MARK_TYPES.has(next.type);
17836
- const before = wantFade ? snapshotLayer(surface.marks) : void 0;
17837
- const prevValue = lastValue;
17838
- const prevCompare = lastCompare;
17839
- const prevSparkline = lastSparkline;
17840
- const wantValueTween = prevType === next.type && (COUNT_UP_TYPES.has(next.type) || SWEEP_TYPES.has(next.type)) && prevValue != null;
17841
- const wantSparklineTween = prevType === next.type && next.type === "kpi" && prevSparkline != null && prevSparkline.length > 0;
17842
- currentSpec = next;
17843
- draw(
17844
- false,
17845
- wantValueTween ? prevValue ?? void 0 : void 0,
17846
- wantValueTween ? prevCompare ?? void 0 : void 0,
17847
- wantValueTween || wantSparklineTween ? prevSparkline ?? void 0 : void 0
17848
- );
17849
- if (before && surface.width === prevW && surface.height === prevH && surface.marks.canvas.width === before.width && surface.marks.canvas.height === before.height) {
17850
- updateTransition = runUpdateCrossfade(surface, before, anim);
17851
- }
17910
+ update(next);
17852
17911
  },
17853
17912
  resize() {
17854
17913
  draw(false);
@@ -17860,6 +17919,7 @@ function render(target, spec, options) {
17860
17919
  entrance?.cancel();
17861
17920
  updateTransition?.cancel();
17862
17921
  observer?.disconnect();
17922
+ inspector?.destroy();
17863
17923
  interaction?.destroy();
17864
17924
  surface.destroy();
17865
17925
  }
@@ -18343,6 +18403,7 @@ function renderDashboard(target, spec, options) {
18343
18403
  const hostListeners = /* @__PURE__ */ new Set();
18344
18404
  let root;
18345
18405
  let resizeObs;
18406
+ let dashboardInspector;
18346
18407
  let destroyed = false;
18347
18408
  let sourceCells = /* @__PURE__ */ new Map();
18348
18409
  const syncSourceCell = (name, value) => {
@@ -18434,7 +18495,7 @@ function renderDashboard(target, spec, options) {
18434
18495
  const mount = (host, view) => {
18435
18496
  const finalSpec = inheritInto(view.spec, currentSpec, tokens, !!(view.title || view.subtitle));
18436
18497
  try {
18437
- instances.push(render(host, finalSpec, { store, frame: view.frame ?? true }));
18498
+ instances.push(render(host, finalSpec, { store, frame: view.frame ?? true, inspect: options?.inspect }));
18438
18499
  } catch (err) {
18439
18500
  host.textContent = String(err);
18440
18501
  }
@@ -18717,12 +18778,28 @@ function renderDashboard(target, spec, options) {
18717
18778
  });
18718
18779
  resizeObs.observe(root);
18719
18780
  }
18781
+ if (options?.inspect !== false && root) {
18782
+ dashboardInspector = createInspector(root, { onExternalEdit: applyExternalEdit });
18783
+ dashboardInspector.write(currentSpec);
18784
+ }
18785
+ };
18786
+ const applyExternalEdit = (config) => {
18787
+ if (destroyed) return;
18788
+ const merged = { ...config, data: currentSpec.data };
18789
+ if (validateSpec(merged).errors.length > 0) return;
18790
+ teardown();
18791
+ currentSpec = merged;
18792
+ build();
18720
18793
  };
18721
18794
  const teardown = () => {
18722
18795
  if (resizeObs) {
18723
18796
  resizeObs.disconnect();
18724
18797
  resizeObs = void 0;
18725
18798
  }
18799
+ if (dashboardInspector) {
18800
+ dashboardInspector.destroy();
18801
+ dashboardInspector = void 0;
18802
+ }
18726
18803
  for (const inst of instances) inst.destroy();
18727
18804
  instances.length = 0;
18728
18805
  if (root && root.parentNode) root.parentNode.removeChild(root);
@@ -18948,6 +19025,6 @@ function renderToContext(target, spec) {
18948
19025
  // src/index.ts
18949
19026
  var VERSION = "0.1.0";
18950
19027
 
18951
- export { CARTESIAN_TYPES, CHART_TYPES, CanvasLayer, DEFAULT_ENTRANCE_DURATION, DEFAULT_ROUGH_STYLE, DEFAULT_UPDATE_DURATION, DIM_ALPHA, ExpressionError, FACETABLE_TYPES2 as FACETABLE_TYPES, FUNCTION_NAMES, InteractionController, NO_PADDING, RoughPen, SKETCH_FONT_FAMILY, SKETCH_FONT_NAME, SLICER_TYPES, SR_ONLY_STYLE, Surface, TICK_SIZE, TIME_UNITS, TRANSFORM_KINDS, Tooltip, VERSION, aggregateValues, analyzeChart, animate, applyA11y, applyAggregate, applyBin, applyCalculate, applyFilter, applyFold, applyPatch, applyPick, applyTimeUnit, applyTransform, applyTransforms, arc, area, assertValidSpec, autoInsightAnnotations, backOut, bandScale, bounceOut, buildCartesianInteraction, buildCartesianModel, buildComboModel, buildDataTableFallback, buildFacetModels, buildHistogramModel, buildRenderReport, cartesianInteractionBuilders, cartesianRenderers, categorical, categoricalSchemes, chartTitleText, chartTypeLabel, checkExpression, clamp012 as clamp01, clamp255, compileExpression, compilePredicate, computeBackingSize, computeBins, computeFrame, computeSeriesInsights, contrastRatio, createDiv, createRoughPen, createSelectionStore, cubicIn, cubicInOut, cubicOut, curveCatmullRom, curveLinear, curveMonotoneX, curveStep, curveStepAfter, curveStepBefore, customRenderers, darkTheme, decimate, defaultSpan, dependentParams, diverging, divergingColorScale, divergingSchemes, drawAnnotationLabels, drawAnnotations, drawAxesUnderlay, drawFacet, drawLegend, drawOverlay, drawTitle, drawTrendlineLabels, drawTrendlines, easings, elasticOut, ellipsize, ensureSketchFont, expoInOut, expoOut, facetReport, fillParentStyle, filterRows, fontString, formatDate, formatNumber2 as formatNumber, formatValue, getDevicePixelRatio, groupBy, hashString, inferFieldType, inferFieldTypes, inferValueType, inheritInto, interpolateArray, interpolateNumber, interpolateNumberArray, interpolateObject, interpolateOklab, interpolateRgb, isBrowser, isEmptyValue, isFaceted, isParamClause, isSlicerType, keyFields, legendSwatchWidth, lightTheme, line, linear, linearRegression, linearScale, linearToSrgb, lintSpec, literalToValue, logScale, lttbRun, makeMatcher, matchesValue, measureText, monotoneXTangents, mulberry32, niceDomain, oklabToOklch, oklabToRgb, oklchToOklab, ordinalColorScale, overlayTextToCanvasCmd, paintCanvasText, paintLegendSwatch, parseColor, parseNumberFormat, pivot, placeViews, pointScale, polygonHachureLines, prefersReducedMotion, prettyDate, profileColumns, quadIn, quadInOut, quadOut, rampFromStops, readableTextColor, recommendChart, relativeLuminance, render, renderDashboard, renderToContext, repairReport, repairSpec, resolveCurve, resolveDashboardLayout, resolveDashboardSections, resolveEmphasis, resolveEntrance, resolveFilterValues, resolveInsightOptions, resolveSketch, resolveTheme, resolveUpdate, resolveValueRef, rgbToOklab, rgbaToCss, rotatePoint, roundedRect, sampleArc, sequential, sequentialColorScale, sequentialSchemes, setMeasureContext, setStyle, sinInOut, slicerParamName, smartDate, specFields, srgbToLinear, summarize, summarizeChart, themes, tickIncrement, tickStep, ticks, timeScale, timeTickFormat, timeTicks, toHex, toPointer, tooltipEnabled, truncateTo, validateDashboard, validateSpec, wireViews, withAlpha, withSketchFont };
19028
+ export { CARTESIAN_TYPES, CHART_TYPES, CanvasLayer, DEFAULT_ENTRANCE_DURATION, DEFAULT_ROUGH_STYLE, DEFAULT_UPDATE_DURATION, DIM_ALPHA, ExpressionError, FACETABLE_TYPES2 as FACETABLE_TYPES, FUNCTION_NAMES, InteractionController, NO_PADDING, RoughPen, SKETCH_FONT_FAMILY, SKETCH_FONT_NAME, SLICER_TYPES, SPEC_ATTR, SR_ONLY_STYLE, Surface, TICK_SIZE, TIME_UNITS, TRANSFORM_KINDS, TYPE_ATTR, Tooltip, VERSION, aggregateValues, analyzeChart, animate, applyA11y, applyAggregate, applyBin, applyCalculate, applyFilter, applyFold, applyPatch, applyPick, applyTimeUnit, applyTransform, applyTransforms, arc, area, assertValidSpec, autoInsightAnnotations, backOut, bandScale, bounceOut, buildCartesianInteraction, buildCartesianModel, buildComboModel, buildDataTableFallback, buildFacetModels, buildHistogramModel, buildRenderReport, cartesianInteractionBuilders, cartesianRenderers, categorical, categoricalSchemes, chartTitleText, chartTypeLabel, checkExpression, clamp012 as clamp01, clamp255, compileExpression, compilePredicate, computeBackingSize, computeBins, computeFrame, computeSeriesInsights, contrastRatio, createDiv, createInspector, createRoughPen, createSelectionStore, cubicIn, cubicInOut, cubicOut, curveCatmullRom, curveLinear, curveMonotoneX, curveStep, curveStepAfter, curveStepBefore, customRenderers, darkTheme, decimate, defaultSpan, dependentParams, diverging, divergingColorScale, divergingSchemes, drawAnnotationLabels, drawAnnotations, drawAxesUnderlay, drawFacet, drawLegend, drawOverlay, drawTitle, drawTrendlineLabels, drawTrendlines, easings, elasticOut, ellipsize, ensureSketchFont, expoInOut, expoOut, facetReport, fillParentStyle, filterRows, fontString, formatDate, formatNumber2 as formatNumber, formatValue, getDevicePixelRatio, groupBy, hashString, inferFieldType, inferFieldTypes, inferValueType, inheritInto, interpolateArray, interpolateNumber, interpolateNumberArray, interpolateObject, interpolateOklab, interpolateRgb, isBrowser, isEmptyValue, isFaceted, isParamClause, isSlicerType, keyFields, legendSwatchWidth, lightTheme, line, linear, linearRegression, linearScale, linearToSrgb, lintSpec, literalToValue, logScale, lttbRun, makeMatcher, matchesValue, measureText, monotoneXTangents, mulberry32, niceDomain, oklabToOklch, oklabToRgb, oklchToOklab, ordinalColorScale, overlayTextToCanvasCmd, paintCanvasText, paintLegendSwatch, parseColor, parseNumberFormat, pivot, placeViews, pointScale, polygonHachureLines, prefersReducedMotion, prettyDate, profileColumns, quadIn, quadInOut, quadOut, rampFromStops, readableTextColor, recommendChart, relativeLuminance, render, renderDashboard, renderToContext, repairReport, repairSpec, resolveCurve, resolveDashboardLayout, resolveDashboardSections, resolveEmphasis, resolveEntrance, resolveFilterValues, resolveInsightOptions, resolveSketch, resolveTheme, resolveUpdate, resolveValueRef, rgbToOklab, rgbaToCss, rotatePoint, roundedRect, sampleArc, sequential, sequentialColorScale, sequentialSchemes, serializeSpec, setMeasureContext, setStyle, sinInOut, slicerParamName, smartDate, specFields, srgbToLinear, stripData, summarize, summarizeChart, themes, tickIncrement, tickStep, ticks, timeScale, timeTickFormat, timeTicks, toHex, toPointer, tooltipEnabled, truncateTo, validateDashboard, validateSpec, wireViews, withAlpha, withSketchFont };
18952
19029
  //# sourceMappingURL=index.js.map
18953
19030
  //# sourceMappingURL=index.js.map