Skip to content

Instantly share code, notes, and snippets.

@manzt
Last active July 21, 2023 20:55
Show Gist options
  • Save manzt/af46972d7a0a8e870f5228da66c52891 to your computer and use it in GitHub Desktop.
Save manzt/af46972d7a0a8e870f5228da66c52891 to your computer and use it in GitHub Desktop.
anywidget svelte demo

anywidget-svelte

This is a toy example demonstrating how to start prototyping with Svelte in anywidget.

Since Svelte requires a compiler, we need to configure a bundler to prototype our widget. This example extends from the Vite recipe in the documentation, and importantly adds the svelte compiler in the vite.config.js.

Make sure you have a Python environment with anywidget installed and the Node.js dependencies:

pip install jupyterlab anywidget
pnpm install

To get started you will need to run both a notebook server:

jupyterlab SvelteDemo.ipynb # open notebook

and run the vite dev server:

pnpm vite # run vite development server

You can now start developing the widget. Any changes to the JavaScript/Svelte source are automatically reflected in the notebook frontend.

Note: this example is incomplete and only demonstrates live prototyping with the development server. Follow the rest of the Vite recipe to learn the recommended bundling strategy for production.

<script>
import { onDestroy, onMount } from "svelte";
export let model;
export let name = "value";
let count = model.get(name);
let event = `change:${name}`
let callback = () => count = model.get(name);
onMount(() => {
model.on(event, callback);
});
onDestroy(() => {
model.off(event, callback);
})
</script>
<button on:click={() => {
model.set(name, model.get(name) + 1);
model.save_changes();
}}>
Count is {count}
</button>
<style>
button {
padding: 10px;
font-size: 2em;
}
</style>
import Counter from "./Counter.svelte";
export function render({ model, el }) {
let counter = new Counter({ target: el, props: { model } });
return () => counter.$destroy();
}
{
"name": "anywidget-svelte",
"type": "module",
"devDependencies": {
"@anywidget/vite": "^0.1.1",
"@sveltejs/vite-plugin-svelte": "^2.4.2",
"vite": "^4.4.1"
},
"dependencies": {
"svelte": "^4.0.5"
}
}
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
import { defineConfig } from "vite";
import anywidget from "@anywidget/vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
export default defineConfig({
plugins: [
svelte({ hot: false }),
anywidget(),
],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment