Skip to content

feat(vgplot): Convert Mosaic vgplot to TypeScript - #1394

Open
dangotbanned wants to merge 32 commits into
js-to-ts/inputs-1from
js-to-ts/vgplot-1
Open

dangotbanned wants to merge 32 commits into
js-to-ts/inputs-1from
js-to-ts/vgplot-1

Conversation

@dangotbanned

@dangotbanned dangotbanned commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1389

Description

This PR goes a few steps beyond renaming *.js files.
The majority of src and all of test has pretty rich parameter types and everything has a useful return type.

Highlights

Here's a bunch of screenshots

Directive !== Component

We now warn when directives are used in place of components (or the reverse).
This even includes *Legend functions which can return either kind - depending on for: ...:

Legend error

Selection !== Param

From (#1264)

(Clarification): ParamRef is used where the docs imply that only a reference to a Selection may be valid.
If the two are not interchangable, perhaps there's a way to express this...

I was working on interactors back when I noticed that.
Now that I'm typing the implementation - it looks like the only interactor that anticipates a regular Param is Nearest.
So we now report an error on as: Param for everything but nearest*:

Interactor selection error

Attributes

attributes.js defined 200+ single-parameter functions which had no typing whatsoever.
In attributes.ts, they all have a return type of PlotDirective and I've made a start on typing each parameter too.

By redefining attrf as a generic function with a permissive default - we can now gradually constrain what is allowed at the definition site.

attrf hint

So far I've only done this for a handful of cases, since I'm manually translating from spec/PlotAttribute.ts.
But it works! and the rest can be tightened up in a follow-up

Attribute completion error

Checked ESM examples

Most of the above have been screenshots from specs/esm/*.js. For more details see (#1394 (comment)).

@dangotbanned dangotbanned added the javascript Pull requests that update Javascript code label Nov 7, 2026
@dangotbanned
dangotbanned added this pull request to stack #1375 November 7, 2026 17:06
@dangotbanned

This comment was marked as resolved.

Comment thread specs/esm/package.json
Comment on lines +1 to +12
{
"name": "mosaic-esm-examples",
"version": "0.35.0",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --build"
},
"dependencies": {
"@uwdata/vgplot": "workspace:^"
}
} No newline at end of file

@dangotbanned dangotbanned Nov 7, 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.

This is the vgplot equivalent of what I did for Mosaic Spec:

I feel quite strongly that these files need to be type-checked. I'd made so many mistakes in this PR 1 and they were not caught without the typing coverage provided by them.

I think it would be simpler to just write them to vgplot's test suite though?

  • We'd avoid the need for this packaging boilerplate
  • Could also measure runtime coverage
  • The location of specs/esm/ seems not that important, since everything is duplicated to docs/public/specs/esm/ anyway 🤔

Footnotes

  1. beyond what's visible from the commits ↩

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 VSCode, the References CodeLens now has the information required to link between vgplot and usage in specs/esm

Image

Comment thread packages/vgplot/inputs/src/Menu.ts Resolved
Comment thread packages/vgplot/inputs/src/Menu.ts Resolved
Comment thread packages/vgplot/inputs/src/Search.ts Resolved
Comment thread packages/vgplot/inputs/src/Search.ts Resolved
Comment thread packages/vgplot/inputs/src/Slider.ts Resolved
Comment thread packages/vgplot/inputs/src/Slider.ts Resolved
dangotbanned added a commit that referenced this pull request Nov 7, 2026
Comment on lines +48 to 51
//@ts-expect-error A spread argument must either have a tuple type or be passed to a rest parameter.
export const area = (...args) => mark('area', ...args);
//@ts-expect-error
export const areaX = (...args) => mark('areaX', ...args);

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 think resolving these issues in a meaningful way, is out of scope for the PR - but is something we need to do.
The wrong solution would be changing the signature of mark, {explicit,implicit}Type to accept ...args: any[] - which silences the errors without improving the UX.

Problem

Simply put, this signature provides no information to the caller - while being a core part of the vgplot API:

export const line = (...args) => mark('line', ...args);

If I'm incredibly persistent, I could leave my editor and:

  1. Visit the Marks API Reference
  2. Scroll all the way down to vgplot/marks#Line
  3. Find out we don't provide this information at all, then follow through to the Observable Plot line docs
  4. Scroll all the way to the bottom again to plot/marks/line#line-options
  5. Find out that this still doesn't tell me the signature, get redirected again to standard mark options
  6. Accept these single line descriptions that don't have types 😔

Does it have to be this way?

Observable Plot looks very different.
The JS definition of line already tells me much more:

export function line(data, {x, y, ...options} = {}) {
  [x, y] = maybeTuple(x, y);
  return new Line(data, {...options, x, y});
}

But only that's only untyped because there's a marks/line.d.ts too.

This is what I actually want.
I don't care about fixing the @ts-expect-errors. I do care that they highlight a design choice that makes the UX worse than I know it can be 🙏

Image

Comment on lines +34 to +36
if (!(typeof maybePlot === 'string')) {
throw new TypeError(`Unrecognized 'for' type: ${typeof maybePlot}`)
}

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.

On main, there are 3 branches here for the type of for.

Show vgplot/vgplot/src/plot/legends.js#L8-L15

const type = typeof maybePlot;
const add = plot => plot.addLegend(legend, false);
if (type === 'string') {
requestNamedPlot(this, maybePlot, add);
} else if (maybePlot.value) {
add(maybePlot.value);
}
return legend.element;

We don't have coverage for anything besides string.
It is the only documented option in the API ref and this matches the spec definition too:

Show vgplot/spec/src/spec/PlotLegend.ts#L64-L69

export interface Legend extends PlotLegend {
/**
* The name of the plot this legend applies to.
* A plot must include a `name` attribute to be referenced.
*/
for: string;

Throwing here was only meant to explain the change.
Of all the places that could validate types - I don't think it's needed when we aren't dealing with a union

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.

@domoritz RE: (#1425) this was the legend thread

Open decision: the stack also dropped colorLegend({for: plotElement}) and data-format inference for query objects. Either restore them here or list them as breaking changes.

Comment on lines +27 to +30
// TODO @dangotbanned: `options` might be expressible as a conditional type
function legend(channel: 'color' | 'opacity' | 'symbol', options: LegendForOptions): HTMLDivElement
function legend(channel: 'color' | 'opacity' | 'symbol', options: LegendOptions): PlotDirective
function legend(channel: 'color' | 'opacity' | 'symbol', options: Options = {}): HTMLDivElement | PlotDirective {

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.

It might save a few lines from the duplicated overloads - but I'm not sure the result would be as readable

@dangotbanned
dangotbanned marked this pull request as ready for review November 9, 2026 15:42
dangotbanned added a commit that referenced this pull request Nov 9, 2026
All of the others would have this too,
but they also have other errors (#1394 (comment))
Comment on lines +3 to +6
interface Options {
filterBy?: mc.Selection;
optimize?: boolean;
}

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.

AFAICT, it isn't really documented anywhere - but we have quite a lot of code in vgplot/plot/src/marks/Marks.ts that supports an unnest option too.

There's an example of it here:

I suppose you could call this documenting it 😉

/**
* The source field names to unnest, as declared by the `unnest` option.
* @returns {string[]}
*/
get unnestFields() {
const { unnest } = this.source?.options ?? {};
return unnest == null ? [] : [unnest].flat();
}

@dangotbanned dangotbanned Nov 14, 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.

There's probably something I'm missing, but this seems an odd form of special-casing:

Show Mark.query

query(filter = []) {
if (this.hasOwnData()) return null;
const { unnestFields } = this;
// wrap unnested column fields in UNNEST() so arrays expand into rows
const channels = unnestFields.length === 0
? this.channels
: this.channels.map(c => {
const name = unnestableColumn(c.field);
return name != null && unnestFields.includes(name)
? { ...c, field: unnest(c.field) }
: c;
});
return markQuery(channels, this.sourceTable()).where(filter);

I can see 2 more general features:

  1. Add an unnest method to Query or SelectQuery in mosaic-sql
    i. See polars.LazyFrame.unnest 1.
    I think that has a better user-facing API than if you were to write it using EXCLUDE 2
  2. Accept 3 query operators as a source for marks in vgplot

These two look pretty much the same, but the second one could allow queries that uses things besides where and unnest 😄

function current($filter: vg.Selection) {
  return vg.plot(
    vg.barX(vg.from('events', { filterBy: $filter, unnest: 'tags' }), {
      x: vg.count(),
      y: 'tags'
    }),
    vg.toggleY({ as: $filter })
  );
}


function proposed($filter: vg.Selection) {
  return vg.plot(
    vg.barX(Query.from('events').where($filter).unnest('tags'), {
      x: vg.count(),
      y: 'tags'
    }),
    vg.toggleY({ as: $filter })
  );
}

Footnotes

  1. Polars uses unnest for Struct and explode for List - whereas DuckDB uses unnest for both ops ↩

  2. The gaia example uses EXCLUDE inside a string, but we haven't got an expression form yet ↩

  3. possibly a limited selection of ↩

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.

  1. Accept query operators as a source for marks in vgplot

Another use-case for that would be aligning 2 ways you can specify "inline" data.

We have one example that uses vg.loadObjects, which is wrapping a CreateQuery

Show mark-types.js

await vg.coordinator().exec([
vg.loadObjects("md", [
{"i":0,"u":"A","v":2},
{"i":1,"u":"B","v":8},
{"i":2,"u":"C","v":3},
{"i":3,"u":"D","v":7},
{"i":4,"u":"E","v":5},
{"i":5,"u":"F","v":4},
{"i":6,"u":"G","v":6},
{"i":7,"u":"H","v":1}
],)
]);

But marks can also take data "directly", at the cost of interactivity.
I haven't seen an example that uses that feature

mosaic/docs/vgplot/index.md

Lines 104 to 105 in 3cc45be

::: warning
Interactive filtering is not supported if you bypass the database and pass data directly to a mark.

If marks accepted query nodes - the output of vg.loadObjects would work - and the only magic is piping that into a coordinator.
I'm assuming that would avoid the interactivity issue?

The other aspect is that Mark is complicated by needing to handle vg.from and arbitrary data 😅

@dangotbanned
dangotbanned force-pushed the js-to-ts/vgplot-1 branch 9 times, most recently from 42f6c84 to 449c6e1 Compare November 21, 2026 13:21
Similar to #1361, but `vgplot` instead of `spec`
Changes the signature of and stops exporting `concat`
Now that *concat` is typed, the `Callback` alternative failed

Related (f351d60)
This "allowed" `spec/ast` to pass in the wrong shape
but the source is fixed now and unpacks correctly
Can finish the rest another time, but they all have a reasonable upper bound now
It is quite confusing that "options" aren't optional
All optional/required are now correct

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 vgplot to TypeScript

1 participant