Skip to content

feat(plot): Convert Mosaic Plot to TypeScript - #1398

Open
dangotbanned wants to merge 34 commits into
js-to-ts/vgplot-2-strictfrom
js-to-ts/plot-1
Open

dangotbanned wants to merge 34 commits into
js-to-ts/vgplot-2-strictfrom
js-to-ts/plot-1

Conversation

@dangotbanned

@dangotbanned dangotbanned commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1388

Description

This PR adds enough typing to vgplot/plot to get it to compile.

As mentioned in (#1388 (comment)) there was a lot to fix 🫠

Started with 400-500 errors from cd packages/vgplot/plot && pnpm tsc --build.

I have not aimed to fix every error, I'm not sure that's possible without it being a rewrite.
But this is a start and the issues which were already there are now more visible

@dangotbanned
dangotbanned added this pull request to stack #1375 November 11, 2026 22:29
@dangotbanned dangotbanned linked an issue Nov 11, 2026 that may be closed by this pull request
@dangotbanned dangotbanned added the javascript Pull requests that update Javascript code label Nov 11, 2026
@dangotbanned
dangotbanned marked this pull request as ready for review November 11, 2026 22:39
import type { SVG } from '../../types.js';

function wrap(brush) {
function wrap(brush: BrushBehavior<unknown>) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrap is a very misleading name for what's happening here

It would make sense if the returned object was like:

result =  {brush: BrushBehavior, ..extras}

But patching methods onto the same object? 🤔

@@ -2,14 +2,14 @@
* Return the bound datum value on a Plot-generated SVG element.
* Following D3, bound data is assigned to the `__data__` property.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If D3 exposes the type being described - that should be used instead of Element

// @ts-ignore
const node = this;
export function patchScreenCTM(): void {
const node: SVGGraphicsElement = this;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the singular hit for noImplicitThis

I fixed some of those in vgplot but this one looks different

@@ -0,0 +1,9 @@
import { toKebabCase } from './to-kebab-case.js';

export function sanitizeStyles(styles: Record<string, string | number>): Record<string, string | number> {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is called on things unrelated to styles

Comment on lines +15 to +36
export type EncodingName = ChannelName | 'tip' | ConstantOption | 'orderby'; // (uwdata/mosaic#266)
export type Encodings = { [name in EncodingName]?: any };
export type Reqs = { [name in EncodingName]?: mc.Stat[] };

export type Field = { stats?: { stats?: mc.Stat[], column?: mc.FieldRef; }; basis?: unknown; } | msql.ExprValue | msql.ColumnRefNode | msql.ColumnParamNode | msql.SQLNode;

/** `channels: Entry[]` is being used to describe every possible input that is not `data` or `type: MarkType`.
*
* For example, {@link markQuery} anticipates `channel: 'orderby'` - which is a property of a transform (`WindowOptions.orderby`).
*/
interface Entry {
channel: EncodingName;
value?: any;
field?: Field;
as?: string;
column?: mc.FieldInfo['column'];
type?: mc.FieldInfo['type'];
count?: mc.FieldInfo['count'];
min?: mc.FieldInfo['min'];
max?: mc.FieldInfo['max'];
sqlType?: mc.FieldInfo['sqlType'];
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just describing the current state of things - but I don't understand why they are.

  • What is a channel?
  • What is an encoding?
  • What is a field?
  • What is reqs?
  • Why are stats nested in stats?
  • Why is a column available in multiple levels?
  • Even though Entry only requires channel - why is that not required here?

@dangotbanned dangotbanned Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had more time to think and here are some problems I've found.

Note

TL;DR: I think Mark.channels is wearing too many hats.
If they need to all to go on 1 head, it should not be Record<string, unknown>[]

Mark.prepare

This includes Mark._fieldInfo and Mark.channels, but the body of the method is where things get weird:

Show Mark.prepare

async prepare(): Promise<void> {
if (this.hasOwnData()) return;
const { channels, reqs } = this;
const fields = new Map<any, Set<mc.Stat>>();
for (const { channel, field } of channels) {
if (!field) continue;
//@ts-expect-error Property 'stats' does not exist on type 'string'
const stats = field.stats?.stats || [];
//@ts-expect-error Property 'stats' does not exist on type 'string'
const key = field.stats?.column ?? field;
const entry = fields.get(key) ?? fields.set(key, new Set).get(key);
stats.forEach(s => entry.add(s));
reqs[channel]?.forEach(s => entry.add(s));
}
const table = this.sourceTable();
const info = await queryFieldInfo(
this.coordinator,
Array.from(fields, ([c, s]) => ({ table, column: c, stats: Array.from(s) }))
);
const lookup = Object.fromEntries(info.map(x => [x.column, x]));
for (const entry of this.channels) {
const { field } = entry;
if (field) {
//@ts-expect-error Property 'stats' does not exist on type 'string'
Object.assign(entry, lookup[field.stats?.column ?? field]);
}
}
this._fieldInfo = true;
}

_fieldInfo represents a state change that happens when a subset Mark.channels[*] (an Entry with a field) is assigned FieldInfo results:

Zoom in to that bit

const lookup = Object.fromEntries(info.map(x => [x.column, x]));
for (const entry of this.channels) {
const { field } = entry;
if (field) {
//@ts-expect-error Property 'stats' does not exist on type 'string'
Object.assign(entry, lookup[field.stats?.column ?? field]);
}
}
this._fieldInfo = true;

I'd been struggling to understand the motivation for that.
It isn't something you can represent in types and it isn't documented either.

Mark.constructor

However I now believe it is because Mark's constructor can set event listeners on an Entry.value.
So in this case, assigning to an existing object would prevent breaking the references that may have dependencies

Show Mark.ts#L147-L155

} else if (isParamLike(entry)) {
const c = { channel, value: entry.value };
channels.push(c);
//@ts-expect-error Argument of type '<T>(value: unknown) => Promise<void>' is not assignable to parameter of type 'EventCallback'.
entry.addEventListener('value', value => {
// update immediately, the value is simply passed to Plot
c.value = value;
return this.update();
});

The rest of the constructor is (mainly) about populating Mark.channels, where each Entry should actually be:

type EntryRevised = { channel: string, value: unknown; } | { channel: string, field: object; as: string; };

EntryRevised is not a very useful type, but we can't narrow it further since there aren't any errors raised to define what invalid input looks like.

Mark.channels

Now we have a rough how?, what? (v1), what? (v2) for channels.
The stuff with Param.value is a guess at why?

The answer to where is channels used? is, kind of, everywhere.
Direct references are mostly scoped to methods I've mentioned + the (including subclasses):

  • Mark.query: for field-related things (mosaic-core, mosaic-sql)
  • Mark.plotSpecs, Marks.markPlotSpec: for value and (resolved) field-related things (@observablehq/plot and DOM)

Beyond that though, a huge amount of usage comes from all of the utilities that arise from dealing with such a complex object.
We start with some seemingly harmless searching of an array:

Show 2 "search for something" functions

What's wrong here?

channel(channel: ChannelName): Entry | undefined {
return this.channels.find(c => c.channel === channel);
}

public channelField(channel: ChannelName, { exact = false } = {}): Entry | null {
const c = exact
? this.channel(channel)
: this.channels.find(c => c.channel.startsWith(channel));
return c?.field ? c : null;
}

Well, channels: Entry[] started it's life as options: Record<string, any>.
That was keyed on Entry.channel, meaning we could represent this as a Map and avoid all the linear time searching

Okay, so perhaps sub-optimal, but there are bigger fish to fry right?
Well, the vg.plot thickens when more utilities start stacking on top - and we gets loops in loops in ...

Show 4 more "search for something" functions

function extractField(field) {
if (isNode(field)) {
if (field.type === 'COLUMN_REF') {
// @ts-ignore
return field.column;
} else if (field.type === 'AGGREGATE') {
// @ts-ignore
return field.args[0] ?? field;
} else if (field.type === 'CUSTOM' && 'column' in field) {
// handle custom transforms (like bin) that expose a column
return field.column;
}
}
return field;
}

export function getField(mark, channel) {
return extractField(mark.channelField(channel)?.field);
}

export function getFields(mark, channels) {
const fields = [];
const as = [];
channels.forEach(c => {
const q = c === 'color' ? ['color', 'fill', 'stroke']
: c === 'x' ? ['x', 'x1', 'x2']
: c === 'y' ? ['y', 'y1', 'y2']
: [c];
for (let i = 0; i < q.length; ++i) {
const f = mark.channelField(q[i], { exact: true });
if (f) {
fields.push(extractField(f.field));
as.push(f.as);
return;
}
}
throw new Error(`Missing channel: ${c}`);
});
return { fields, as };
}

// search marks for a backing data field for the legend
function findField(marks: Mark[], channel: 'symbol' | 'color' | 'opacity'): Field | null {
const channels = channel === 'color' ? ['fill', 'stroke'] as const
: channel === 'opacity' ? ['opacity', 'fillOpacity', 'strokeOpacity'] as const
: null;
if (channels == null) return null;
for (let i = marks.length - 1; i > -1; --i) {
for (const c of channels) {
const field = marks[i].channelField(c, { exact: true });
if (field) return field.field;
}
}
return null;
}

And then by the time we're multiple steps removed from a Mark, things begin looking quadratic:

Show more ...

export function binExpr(mark: Mark, channel: 'x' | 'y', n, extent, pad = 1, expr?) {
// get base expression, the channel field unless otherwise given
const { field } = mark.channelField(channel);
expr = expr ?? field;
// extract scale information
const { type, apply, sqlApply } = channelScale(mark, channel);

export function channelScale<T>(mark: Mark, channel: TransformScaleName): msql.Scale<T> {
const { plot } = mark;
let scaleType: msql.ScaleType | undefined = plot.getAttribute(`${channel}Scale`);
if (!scaleType) {
const { type } = mark.channelField(channel);

// Plot defaults temporal scales to UTC; TIMESTAMPTZ values are
// instants, so render them in local time instead
function inferScaleTypes(spec: Spec, plot: Plot): void {
for (const key of ['x', 'y'] as const) {
const scale = spec[key] || {};
if (scale.type != null) continue;
const timestamptz = plot.marks.some(
mark => TIMESTAMPTZ_TYPES.has(mark.channelField(key)?.sqlType)
);
if (timestamptz) spec[key] = { ...scale, type: 'time' };
}
}
function inferLabels(spec: Spec, plot: Plot): void {
const { marks } = plot;
inferLabel('x', spec, marks);
inferLabel('y', spec, marks);
inferLabel('fx', spec, marks);
inferLabel('fy', spec, marks);
}
function inferLabel(key: 'x' | 'y' | 'fx' | 'fy', spec: Spec, marks: Mark[]): void {
const scale = spec[key] || {};
if (scale.axis === null || scale.label !== undefined) return; // nothing to do
const fields = marks.map(mark => mark.channelField(key)?.field);
if (fields.every(x => x == null)) return; // no columns found
// check for consistent label

channels.forEach(c => {
const q = c === 'color' ? ['color', 'fill', 'stroke'] as const
: c === 'x' ? ['x', 'x1', 'x2'] as const
: c === 'y' ? ['y', 'y1', 'y2'] as const
: [c];
for (let i = 0; i < q.length; ++i) {
const f = mark.channelField(q[i], { exact: true });
let field: Field | undefined;
if ((field = f?.field)) {
fields.push(typeof field === 'object' && 'basis' in field ? field.basis : field);
as.push(f.as);
return;

All of this is screaming Map to me

Comment on lines +88 to +89
const rx = Array.from(this.xscale.range).slice().sort(asc);
const ry = Array.from(this.yscale.range).slice().sort(asc);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and a few other places I needed to add Array.from due to upstream typing:

Internally, it wouldn't make sense for Observable to be storing an Iterable - as they can't guarantee multiple passes are valid.
My guess is they've reused the permissive typing that describes what the use can pass but these accesses are on some normalized data structure (probably Array)

Comment on lines 158 to 174
// generate a faux mark to pass to an interactor
/**
* @import { InteractorMark } from './marks/Mark.js'
* @returns {InteractorMark | undefined}
*/
function interactorMark(legend) {
function interactorMark(legend: Legend): InteractorMark | undefined {
const { channel, plot } = legend;
const field = legend.field ?? findField(plot.marks, channel) ?? 'value';
if (field) {
const f = { field };
const f = { field, channel };
return {
plot,
channelField: c => channel === c ? f : undefined,
isUnnested: () => false
channelField: (c) => channel === c ? f : undefined,
isUnnested: () => false,
channels: [],
query: () => null,
filterBy: undefined,
coordinator: undefined
};
}
}

@dangotbanned dangotbanned Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

InteractorMark causes a lot of yelling from the type checker.

On main, we have:

Show InteractorMark

/**
* The minimal mark surface consumed by interactors, allowing marks
* and lightweight stand-ins to be used interchangeably.
* @typedef {object} InteractorMark
* @property {import('../plot.js').Plot} plot
* The plot the mark belongs to.
* @property {(channel: string, options?: { exact?: boolean }) =>
* ({ field?: any, as?: any } | null | undefined)} channelField
* Look up the channel entry bound to a channel, if any.
* @property {(field: any) => boolean} isUnnested
* Whether the given field is unnested by the mark's source.
* @property {DataColumns} [data]
* Materialized column data, when available.
* @property {number} [index]
* The mark's index within the plot.
*/

but that definition didn't reflect usage, and even what I've updated it to isn't enough:

/**
* The minimal mark surface consumed by interactors, allowing marks
* and lightweight stand-ins to be used interchangeably.
*/
export interface InteractorMark {
plot: Plot;
data?: mc.DataColumns;
index?: number;
channels: Entry[];
channelField: (channel: ChannelName, options?: { exact?: boolean; }) => Entry | null;
isUnnested: (field: any) => boolean;
query(filter: msql.FilterExpr): msql.SelectQuery | null;
get filterBy(): mc.Selection | undefined;
get coordinator(): mc.Coordinator | null;
}

InteractorMark must be a MosaicClient for what is going on in Highlight:

Show Highlight

//NOTE: This function depends on `Mark` and reaches into the internals of mosaic sql
async function predicateFunction(mark: InteractorMark, selection: Selection): Promise<(i: any) => boolean> {
//@ts-expect-error Argument of type 'InteractorMark' is not assignable to parameter of type 'MosaicClient'.
const pred = selection?.predicate(mark);
if (!pred || Array.isArray(pred) && pred.length === 0) {
return () => true;
}
// set flag so we do not skip cross-filtered sources
//@ts-expect-error Argument of type 'InteractorMark' is not assignable to parameter of type 'MosaicClient'.
const filter = mark.filterBy?.predicate(mark, true);
const s = { __: and(pred) };
const q = mark.query(filter);
('queries' in q ? q.queries as SelectQuery[] : [q]).forEach(q => {
q._groupby.length ? q.select(s) : q.setSelect(s);
});
const data = await mark.coordinator.query(q);
const v = data.getChild?.('__');
return !(data.numRows) ? (() => false)
: v ? (i => v.at(i))
: (i => data[i].__);
}

I'm not sure why we are where we are - but Legend appears to be the source of all these errors:

ts-expect-error Argument of type 'InteractorMark' is not assignable to parameter of type 'MosaicClient'.

Comment on lines +1 to +9
import type * as mc from '@uwdata/mosaic-core';

export interface LegendOptions {
as?: mc.Selection;
field?: string;
label?: string;
tickSize?: number;
marginTop?: number;
marginRight?: number;

@dangotbanned dangotbanned Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was planning to fill this with all of the (Mark and Interactor) *Options interfaces.
I still think it would be a good thing to aim for, but:

  1. Defining all of them wasn't required to fix every (non-strict) error
  2. I have an idea for reusing the definitions in Mosaic Spec without creating circular dependencies

Either way, LegendOptions was the only one I've used in vgplot - so that's all that I've exposed in this mini namespace 🙂

@@ -1,6 +1,9 @@
import * as Plot from '@observablehq/plot';
import * as ObPlot from '@observablehq/plot';

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not precious about the name ObPlot - I just thought Plot should be reserved for the class defined in this package 😅

Comment on lines +13 to +17
/**Observable Plot spec. */
export type Spec = { [x: string]: any; marks?: ObPlot.Mark[]; };

/**Observable plot element */
export type SVG = (SVGSVGElement | HTMLElement) & ObPlot.Plot;

@dangotbanned dangotbanned Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two types are kinda limited by how plot-renderer is written.

Functions that mutate and return void can't be observed in a type system:

// populate top-level and scale properties
setAttributes(attributes, spec, symbols);

These set a lot of things:

Show more

// infer scale types and labels
inferScaleTypes(spec, plot);
inferLabels(spec, plot);
// render plot
const svg: SVG = ObPlot.plot(spec);
// annotate svg with mark indices
annotatePlot(svg, indices);
// set symbol-valued attributes, such as fixed domains
setSymbolAttributes(plot, svg, attributes, symbols);

So by the time we get here something presumably has changed - but you would need to read the body of every function to know what that was:

Show interactor init

// initialize interactors
for (const interactor of plot.interactors) {
await interactor.init(svg);
}
return svg;
}

However, if these functions could return an intersection - we might be able to model what changed in each signature?

Comment thread packages/vgplot/vgplot/tsconfig.json Resolved
dangotbanned added a commit that referenced this pull request Nov 13, 2026
The problems with `(Mark.)channels` are leaking everywhere

Related #1360, #1398 (comment)
dangotbanned added a commit that referenced this pull request Nov 13, 2026
dangotbanned added a commit that referenced this pull request Nov 13, 2026
The problems with `(Mark.)channels` are leaking everywhere

Related #1360, #1398 (comment)
dangotbanned added a commit that referenced this pull request Nov 16, 2026
dangotbanned added a commit that referenced this pull request Nov 16, 2026
The problems with `(Mark.)channels` are leaking everywhere

Related #1360, #1398 (comment)
dangotbanned added a commit that referenced this pull request Nov 16, 2026
dangotbanned added a commit that referenced this pull request Nov 16, 2026
The problems with `(Mark.)channels` are leaking everywhere

Related #1360, #1398 (comment)
@dangotbanned
dangotbanned force-pushed the js-to-ts/plot-1 branch 2 times, most recently from f490c24 to ed2a136 Compare November 20, 2026 15:44
Comment on lines +38 to +40
let field: Field | undefined;
if ((field = f?.field)) {
fields.push(typeof field === 'object' && 'basis' in field ? field.basis : field);

@dangotbanned dangotbanned Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I finally have an answer to what Field.basis is was

Per #91

Add basis expression property to aggregates/windows to identify an untransformed column for selection.

Which refers to two getters that no longer exist (1, 2).

Why do I care?

That is one of the causes for the following 5 errors:

Show errors

// @ts-expect-error Type '{ stats?: { stats?: Stat[]; column?: FieldRef; }; basis?: unknown; }' is not assignable to type 'ExprValue'.

//@ts-expect-error Type '{ stats?: { stats?: Stat[]; column?: FieldRef; }; basis?: unknown; }' is not assignable to type 'ExprValue'.

//@ts-expect-error Type '{ stats?: { stats?: Stat[]; column?: FieldRef; }; basis?: unknown; }' is not assignable to type 'ExprValue'.

// @ts-expect-error Type '{ stats?: { stats?: Stat[]; column?: FieldRef; }; basis?: unknown; }' is not assignable to type 'ExprValue'.

// @ts-expect-error Type '{ stats?: { stats?: Stat[]; column?: FieldRef; }; basis?: unknown; }' is not assignable to type 'ExprValue'.

Which is displaying the type I needed to create to represent Mark.channels[*].field:

export type Field = { stats?: { stats?: mc.Stat[], column?: mc.FieldRef; }; basis?: msql.ExprValue; } | msql.ExprValue | msql.ColumnRefNode | msql.ColumnParamNode | msql.SQLNode;

But this is just dead code 😓

(#1398 (comment)) is related - and would be helped by removing basis - but there are multiple other issues left

Comment on lines +282 to 283
queryResult(data: Table | Record<string, unknown>[]): this {
this.data = toDataColumns(data);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data is correct in terms of what it could support, but might be wider than we need since #1172

Comment on lines +247 to 248
//@ts-expect-error Property 'stats' does not exist on type 'string'
Object.assign(entry, lookup[field.stats?.column ?? field]);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In (#1398 (comment)) I focused on the assignment and state change as problems.

I thought lookup looked fishy too, but didn't understand why it was working until now.

What's going on?

The 1st pass in Mark.prepare builds a Map<unknown, Set<Stat>>.
That unknown is probably intended to be SQLNode or something narrower that describes one column.

(skipping some steps)

Those keys then end up over here (as column: string | ExprNode).
And then a FieldInfo.column is a string interpolation of that ...

const info: FieldInfo = {
table,
column: `${column}`,

Which is the source for lookup's "keys":

const lookup = Object.fromEntries(info.map(x => [x.column, x]));

Finally, the index-access implicitly performs that ExprNode.toString() again for every field

       Object.assign(entry, lookup[field.stats?.column ?? field]);

🤨 🤨 🤨

IIUC, that means for this method - every field channel for a Mark will run through DuckDBCodeGenerator twice?
I can't wrap my head around why codegen is required here. If it is unavoidable; would that not be considered an expensive thing to want to avoid doing twice?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update Javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Convert Mosaic Plot to TypeScript

1 participant