Skip to main content

Embedding the Strudel Editor in another project

The editor described in Live-coding music with Strudel is published from cnotv/strudel-node-editor as @webgamekit/strudel-editor, a Vue 3 component library. Any Vue 3 app can mount the whole editor, or only its code editor, without copying source.

What the host app must provide​

The editor is not self-contained: it reads three things from the app around it.

NeedWhy
Vue 3.4 or laterIt is a Vue component.
Vue Router 4The open tab, pattern and mode live in the address query (?tab=, ?pattern=, ?mode=), so a router must be installed, even on a single-route app.
Pinia 2The AI settings and instrument stores use it, so app.use(createPinia()) must run before the editor mounts.
A modern bundlerIt ships ES modules at the esnext target, with web workers for transcription and instrument rendering, and expects a bundler that handles new URL(..., import.meta.url) workers, such as Vite.

Vue, Vue Router and Pinia are peer dependencies; everything else, including the Strudel engine and CodeMirror, installs with the package.

Install​

pnpm add @webgamekit/strudel-editor vue vue-router pinia

Mount it​

Import the stylesheets once, then use the component as any route or child component.

import '@webgamekit/strudel-editor/tokens.css'
import '@webgamekit/strudel-editor/style.css'
import { StrudelEditor } from '@webgamekit/strudel-editor'

style.css holds the component styles. tokens.css holds default values for the design tokens they read (--color-*, --spacing-*, --font-size-*, --radius-*, --btn-*-height and --font-mono), with a dark variant under prefers-color-scheme, .dark or [data-theme='dark']. Its selectors have zero specificity, so a token the host already defines wins. Import it before the host's own styles. If the host defines every token itself, skip it.

The editor is heavy, so load it only when it is opened:

const StrudelEditor = defineAsyncComponent(() =>
import('@webgamekit/strudel-editor').then((module) => module.StrudelEditor)
)

Size​

The editor fills 100dvh, because it was built as a full-page view. Inside a smaller container, set --strudel-editor-height on the editor or any ancestor:

.music-panel {
--strudel-editor-height: 40rem;
}

Adding your own buttons​

StrudelEditor has one slot, actions, rendered in its toolbar. The Sound panel in generative-art uses it for "Use code in sound" and "Close".

<StrudelEditor>
<template #actions>
<button type="button" @click="saveAndClose">Save</button>
</template>
</StrudelEditor>

Listening to the editor​

StrudelEditor emits what a host needs to stay in sync, so nothing has to be polled:

EventPayloadWhen
update:codethe code on screenevery change: typing, a picked pattern, an import
savedthe saved songs, newest firstafter a save or a delete in the editor
<StrudelEditor v-model:code="code" @saved="onSavedSongs" />

v-model:code is the live code: the editor emits it once when it opens, then on every change, and shows a code the host sets. STRUDEL_SAVED_CODE_STORAGE_KEY is the same code persisted on every change, for a host that prefers to read storage after the editor closes. saved carries the whole saved list, so a host's list refreshes without reading storage at all.

Reading and writing the editor's state​

Every export is listed here. The package root holds what mounts or plays the editor; the light helpers come from @webgamekit/strudel-editor/helpers, so a host can list songs, read addresses and chart a song without loading the whole editor.

EntryExportUse
@webgamekit/strudel-editorStrudelEditorThe whole editor, with v-model:code, the actions slot and the saved event.
StrudelCodeEditorOnly the CodeMirror editor, with v-model:code and evaluate, stop and ready events.
StrudelBassTabThe Instrument tab alone, to show beside a game's controls, for a bass or a guitar (instrument prop). It is compact by default: the gate, Monitor and Synth, the fretboard, the calibration notes (always open), and start, tune and the input dropdown in one row. Its ui prop takes components to draw the buttons, select, sliders, checkbox and instrument picker with (type StrudelBassTabUi), so a host can use its own UI kit. Its advanced prop shows everything: the note log, calibration collapsible with export, import and delay, and the All frets and MIDI options. See Drawing the Instrument tab with your own UI for the props that turn Monitor, Synth and the picker off, set the synth's sound, start listening by itself, and set the fonts.
loadDefaultStrudelPlaybackA playback with no UI, for playing or rendering code in the host.
Types StrudelPlayback, StrudelEditorMode, StrudelExampleThe playback handle, the editor's code or flow mode, and a song as { id, label, code }.
style.css, tokens.cssThe component styles and the default design tokens.
@webgamekit/strudel-editor/helpersSTRUDEL_SONGSThe songs that ship with the editor, as StrudelExample[].
readStrudelSavedSongs, saveStrudelSavedSong, deleteStrudelSavedSongThe songs the player saved under a name.
STRUDEL_SAVED_CODE_STORAGE_KEYThe localStorage key holding the code on screen, written on every change, so a host can seed or read it.
readStrudelAddress, writeStrudelAddressRead or clear tab, pattern and mode on a route query, so a host can keep its own query intact.
readStrudelNoteBarsThe note bars of a pattern's code, for drawing a timeline.
readBassStringSetupThe string calibration the Instrument tab saved for an instrument (bass if left out), as { model, stringGuessMs }, for telling which string a note was played on.
useStrudelSoundsThe sound names Strudel has loaded.
playStrudelSong, renderStrudelCodeToNotes, type StrudelLiveSongPlay a song live, or render its notes to MIDI, with no editor mounted. See the next section.

Because the editor writes its tab and pattern into the route query, a host that does not want them should clear them when it closes the editor, as the Sound panel does with writeStrudelAddress.

Listing songs and saved songs​

The Pattern library inside the editor lists the songs that ship with it and the songs the player saved under a name. A host can list both, and save and delete like the editor does, from the helpers entry:

import {
STRUDEL_SONGS,
deleteStrudelSavedSong,
readStrudelSavedSongs,
saveStrudelSavedSong,
writeStrudelAddress
} from '@webgamekit/strudel-editor/helpers'

STRUDEL_SONGS and readStrudelSavedSongs() both return { id, label, code }[], so one picker lists them together. Every id is an address: navigating the editor's route to ?pattern=<id> opens that song, as the editor itself does when a listed song is clicked.

const openSong = (songId: string): void => {
void router.push({ query: writeStrudelAddress(route.query, { patternId: songId }) })
}

saveStrudelSavedSong(name, code) stores code under a name, replacing a save with the same name, and deleteStrudelSavedSong(id) removes one. Both write the same localStorage the editor reads, so a save made in either place shows up in the other once the editor opens; an editor that is already mounted keeps the list it read when it opened.

Playing a song and reading its notes​

A game that keeps time with a song needs it playing, and needs to know where its notes fall. Both come from the helpers entry and work without mounting the editor.

import { playStrudelSong, renderStrudelCodeToNotes } from '@webgamekit/strudel-editor/helpers'

const { midi, cyclesPerSecond } = await renderStrudelCodeToNotes(songCode)
const song = await playStrudelSong(songCode)
const { cycle } = song.readPosition()
song.pause()
await song.resume()
await song.stop()
FunctionReturnsNotes
renderStrudelCodeToNotes(code){ midi: ArrayBuffer, cyclesPerSecond: number }Renders notes only, never audio, so it takes a fraction of a second. Throws when the code does not evaluate.
playStrudelSong(code)StrudelLiveSong: readPosition(), pause(), resume() and stop()readPosition() gives { cycle, cyclesPerSecond }. pause() holds the song at its cycle and resume() carries on from there, where stop() rewinds. Throws when the code does not evaluate.

preloadStrudelSong(code, onProgress) fetches every recording a song plays before it starts, and reports (loadedCount, totalCount). Superdough drops a note whose file is still downloading, so on a slow connection a song started cold stays silent for a long while. Await it after a tap and hold the start button until it resolves.

Both queue behind each other, because Strudel renders swap the single audio context the engine plays on. A song that sets no tempo starts from 0.5 cycles per second.

The MIDI file​

midi is a standard MIDI file of one full play of the song, from cycle 0 to the cycle the whole song repeats at, or 64 cycles when it never does.

  • One cycle is one bar of four beats, so the tempo is cyclesPerSecond * 60 * 4 beats per minute.
  • Each sound gets its own track, named after it. Events with a note or freq become notes; known drum samples (bd, sd, hh and the rest) go to a drums track on channel 10 with their General MIDI keys; anything else is skipped.
  • Velocity is the event's velocity (0.8 when absent) times its gain, between 0 and 1.

How Strudel notes are mapped to MIDI holds the full key table and the timing rules.

What it fetches and stores​

  • Samples. Sample banks load from strudel.b-cdn.net and raw.githubusercontent.com, among others, so the host's content security policy must allow them.
  • AI composer. It calls openrouter.ai only when the player uses the composer with their own key from the settings tab; the key stays in localStorage.
  • Storage. Saved patterns, the current code and the AI settings use localStorage keys prefixed strudel-.

Content security policy and workers​

The editor fetches from these hosts, so the embedding page must allow them in connect-src:

HostWhat it servesWhen
strudel.b-cdn.netSample bank manifests and audio, and the drum-machine aliaseswhenever sounds load
raw.githubusercontent.comThe dirt-samples bankwhenever sounds load
felixroos.github.ioThe GM soundfontswhen a gm_ preset renders
openrouter.aiThe AI composer's chat and model listsonly when the composer is used with a key

Transcription, tab reading and instrument rendering run in same-origin web workers, so worker-src 'self' must be allowed too, plus blob: if the host's bundler inlines workers.

Licence​

The Strudel engine the editor wraps is AGPL-3.0-or-later, and so is this package. An app that distributes it, or serves it to users over a network, carries the same obligation.

Releasing a new version​

A push to main in strudel-node-editor publishes every package whose version is not on npm yet, so bump the version in the package's own pull request. strudel-editor depends on @webgamekit/strudel-flow, so a change to flow needs its version bumped too.