manzt / anywidget

reusable widgets made easy
https://anywidget.dev
MIT License
488 stars 38 forks source link

Is it possible to sync the frontend model changes with the model in the Deno kernel? #582

Open gergelyszerovay opened 5 months ago

gergelyszerovay commented 5 months ago

Hi,

I tried the following, and expected that the model in Deno will be updated and the change:value event handler will be called:

image

I ran the first code cell, then clicked on the button a few times, then ran the second code cell.

If I execute model.set('value', 13); from a code cell, the event handler is triggered:

image

Is there a way to subscribe to the frontend model changes from the code in the Deno kernel? Thanks.


Full source code:

import { widget } from "jsr:@anywidget/deno";

let model = await widget({
    state: { value: 0 },
    imports: `
import React from "https://esm.sh/react@18";
import ReactDOM from "https://esm.sh/react-dom@18";

import { createRender, useModelState } from "https://esm.sh/@anywidget/react";
`,
    render: ({ model, el }) => {
        function Counter() {
            let [value, setValue] = useModelState("value");
            return <button onClick={() => setValue(value + 1)}>count is {value}</button>;
        }

        return createRender(Counter)({model, el})
    }
});

let v;
model.on("change:value", (x) => {
    console.log(x)
    v = x.detail;
})

model

// ---

console.log(model);
console.log(v);
manzt commented 5 months ago

Thanks for opening the issue! I believe that Deno's jupyter integration only supports broadcasting messages to the frontend (via Deno.jupyter.broadcast) at the moment, but unfortunately not receiving messages. If this API were to be added we could support the bidirectional communication in jsr:@anywidget/deno.

cc: @rgbkrk

rgbkrk commented 5 months ago

Once https://github.com/denoland/deno/pull/23826 is in, it will be pretty smooth to work on the comms receiver.

manzt commented 5 months ago

slick!!! thanks for all your work on runtimelib