observablehq / framework

A static site generator for data apps, dashboards, reports, and more. Observable Framework combines JavaScript on the front-end for interactive graphics with any language on the back-end for data analysis.
https://observablehq.com/framework/
ISC License
2.59k stars 126 forks source link

Server-side JavaScript #234

Open mbostock opened 1 year ago

mbostock commented 1 year ago

I’d like a way to opt-in to server-side JavaScript, akin to "use client"; with React Server Components (or more precisely "use server"; with Server Actions, I guess?). I’m imagining something like this:

```js server
console.log("<b>I’m server-side rendered!</b>");


Or perhaps `context=server` and the default would be `context=client` for JavaScript fenced code blocks.

The idea is closely-related to @cinxmo’s “data loader from a cell” #145 idea, with the caveat being that server-side rendered JavaScript _must_ emit HTML. And this “loader” doesn’t generate a file — the generated HTML fragment is inserted into the page, inline, wherever the fenced code block lives. In theory we could allow other languages besides JavaScript, too, as long as they too emit HTML.

Implied above is that there’s no magic hydration that happens on the client. There’s still an explicit boundary between server-side and client-side code, so if you want interaction, you have to do the hydration yourself (by selecting the elements and adding event listeners etc.).

Also unclear is whether you can have reactive references to other JavaScript cells from server-side JavaScript? For example, maybe you can define a top-level variable and reference it from multiple server-side cells. And maybe we could treat current JavaScript cells as isomorphic, and run them on the server if needed too? I expect that would work in most cases (the main hurdle being support for `FileAttachment`).

Anyway, let’s think about this more… Running a bit more code on the server (during build) often means a better user experience.
Fil commented 1 year ago

Related https://github.com/observablehq/cli/issues/141 (& https://github.com/observablehq/cli/pull/150 https://github.com/observablehq/cli/pull/153)

mbostock commented 3 months ago

This is now closely related to the new page loader feature #1523. We could consider server-side code blocks as “page fragment loaders” — programs that generate fragments of Markdown (or perhaps HTML) that is interpolated into the page during build. In effect, they are “just” page loaders, but without explicit names, and that get incorporated into the rest of the page. This approach would also support fenced code blocks in any language (at least any interpreted language that we already support for data loaders, but that list is also extensible by the user).