Skip to content

Create a Live Coding Music App · Part 18 of 18 in the series

Part 18: Save and Share

Keep the song across reloads with localStorage, and pack it into a link that needs no server. Code that arrives with a link is shown, but not run until you press Play. Then the series ends: what you built in 18 parts, and where to take it from here.

Quest objectives

  • Save the code half a second after the last key stroke
  • Pack the code with CompressionStream and carry it in the part of an address behind the #
  • Show code from a link without running it and without saving it over your own song
  • Add a button that copies a link and one that brings back the example
  • Look back at the series and pick what to build next

The app can do a lot by now, but it forgets. A reload brings back the example song, and what you wrote is gone. And the only way to hand a song to someone else is to copy its code into a message.

This last part adds both: the code is kept between visits, and a link carries a song to another browser, without a server that stores anything. After that, the series looks back at what you built.

Keeping the code

localStorage is a small store that the browser keeps for every site. A page can put texts into it under a name, and finds them again after a reload or a restart of the browser. Create src/share.ts. It has two sections that follow one another in the file. The first reads and writes the code:

src/share.ts
/** The name under which the browser keeps the code between visits. */
const KEY = 'loopcode:code';

/** The code of the last visit, if there is one. */
export function savedCode(): string | undefined {
  try {
    return localStorage.getItem(KEY) ?? undefined;
  } catch {
    // Storage can be switched off, in a private window for example.
    return undefined;
  }
}

export function saveCode(code: string) {
  try {
    localStorage.setItem(KEY, code);
  } catch {
    // Without storage the code is simply not kept.
  }
}

getItem() answers null if nothing was stored under the name. Both functions catch errors, because a browser can switch the store off for a page. The app then works as it did so far, without a memory.

Knowing when the code changes

To save the code, the page has to hear about every change. The editor gets a third function to call, next to the two for the keys. In src/editor.ts, replace the EditorKeys interface:

src/editor.ts
export interface EditorKeys {
  /** Ctrl+Enter (Cmd+Enter on a Mac). */
  run(): void;
  /** Ctrl+. */
  stop(): void;
  /** Called whenever the code changed. */
  change(code: string): void;
}

CodeMirror reports changes through an extension, EditorView.updateListener. Its function is called with every update of the editor, which includes a cursor that only moved. docChanged tells the changes to the text from the rest. Replace createEditor():

src/editor.ts
/** A code editor in `parent`, holding `code`. */
export function createEditor(parent: HTMLElement, code: string, keys: EditorKeys): EditorView {
  return new EditorView({
    parent,
    doc: code,
    extensions: [
      // Before the basic setup, and with the highest precedence: Ctrl+Enter means
      // something else there.
      Prec.highest(
        keymap.of([
          { key: 'Mod-Enter', run: () => (keys.run(), true) },
          { key: 'Mod-.', run: () => (keys.stop(), true) },
        ]),
      ),
      basicSetup,
      EditorView.updateListener.of((update) => {
        if (update.docChanged) keys.change(update.state.doc.toString());
      }),
      javascript(),
      help,
      playingMarks,
      look,
      oneDark,
    ],
  });
}

The page will also have to put code into the editor: the code of a link, and the example. Add at the end of the file:

src/editor.ts
/** Replaces all of the code. One step of the editor's history, so Ctrl+Z brings the old code back. */
export function setCode(view: EditorView, code: string) {
  view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: code } });
}

The whole text is replaced in one transaction. For the editor's history that is one step, so Ctrl+Z brings the old code back.

Saving after a pause

Writing to the store with every key stroke would be work for nothing: only the last version counts. So the page waits for a pause. Every change cancels the timer that is running and starts a new one of half a second. The code is saved when half a second has passed without a change.

In src/main.ts, add setCode to the import from ./editor.ts, and import saveCode and savedCode from ./share.ts. Then replace the statement that creates the editor:

src/main.ts
/** False while code is put into the editor that the reader didn't write: it is not theirs to keep. */
let keep = true;
let saving = 0;

// The editor starts with the code of the last visit, or with the example.
const editor = createEditor(document.querySelector<HTMLElement>('#editor')!, savedCode() ?? SONG, {
  // Ctrl+Enter starts the music, or runs the changed code while it plays.
  run: () => void (engine.clock.playing ? run() : start()),
  stop,
  // Half a second after the last key stroke, the code is saved.
  change(code) {
    if (!keep) return;
    window.clearTimeout(saving);
    saving = window.setTimeout(() => saveCode(code), 500);
  },
});

/** Puts code into the editor without saving it over the reader's own. */
function show(code: string) {
  keep = false;
  setCode(editor, code);
  keep = true;
}

The editor now starts with the code of the last visit, and with the example only if there is none.

show() is for code you did not write. Replacing the text is a change like any other, and the editor calls change() for it before setCode() returns. During that call keep is false, so change() returns at once. No save is planned for the code that is shown, and a save that was already planned for your own code still takes place. Your own song stays in the store. From the first change you make to code that was shown this way, it is saved like anything else you type, and takes the place of the song that was stored before.

A link can carry more than the address of a page. The part behind a # is called the fragment. It was made to point at a place inside a page, so the browser keeps it to itself: when it asks a server for the page, it sends the address without the fragment. A song in the fragment therefore goes from the sender to the receiver, by whatever way the link is sent, and the server that hosts the app never sees it. Nothing has to be stored anywhere.

Code is wordy, and a link should stay short. So the code is packed first. CompressionStream is built into the browser. 'deflate-raw' asks it for deflate, the method that zip and gzip files are packed with, without the header and the checksum those formats put around it. Deflate replaces stretches of text that came up before with a reference back to them, and code repeats itself a lot.

What comes out is bytes, numbers from 0 to 255, and an address can only hold certain characters. Base64 writes any three bytes as four characters out of a set of 64: the letters in upper and lower case, the digits, + and /. Those last two have meanings of their own in an address, so they are swapped for - and _. The = signs that base64 uses to fill up its last group are cut off. Add the second section to src/share.ts:

src/share.ts
/** Sends bytes through a stream that packs or unpacks them. */
async function through(bytes: Uint8Array<ArrayBuffer>, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
  const result = new Blob([bytes]).stream().pipeThrough(stream);
  return new Uint8Array(await new Response(result).arrayBuffer());
}

/**
 * A link that carries the code in the part after the #, which never leaves the browser. The
 * code is packed first, and then written with the 64 characters that are safe in an address.
 */
export async function linkFor(code: string): Promise<string> {
  const bytes = await through(new TextEncoder().encode(code), new CompressionStream('deflate-raw'));
  let binary = '';
  for (const byte of bytes) binary += String.fromCharCode(byte);
  const packed = btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
  return `${location.origin}${location.pathname}#code=${packed}`;
}

/** The code in the address of this page, if it was opened from such a link. */
export async function codeFromLink(): Promise<string | undefined> {
  const packed = /^#code=([\w-]+)$/.exec(location.hash)?.[1];
  if (!packed) return undefined;
  try {
    const binary = atob(packed.replaceAll('-', '+').replaceAll('_', '/'));
    const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
    return new TextDecoder().decode(await through(bytes, new DecompressionStream('deflate-raw')));
  } catch {
    // A link that was cut off or changed carries nothing we can read.
    return undefined;
  }
}

through() is the same for both directions. A Blob offers the bytes as a stream, pipeThrough() sends the stream through the packer or the unpacker, and a Response, the class for answers from the network, is used for one thing it can do: collect a stream into one block of bytes.

btoa() is the browser's function for base64. It takes a string in which every character stands for one byte, which is what the loop in linkFor() builds. codeFromLink() goes the way back. Its regular expression lets through only the 64 characters a link of ours can contain. A link that was cut off fails while it is decoded or unpacked, and the function answers as if there were no link at all. A link in which a character was changed can fail in the same way, or unpack to some other text: nothing in it checks that the code is what was sent.

Code from someone else

A link puts code into the app that someone else wrote, and running code is what the app does. Part 9 pointed out that the code in the editor is run as it is, and part 11 moved it into a worker, where it has no access to the page and can be stopped. That does not make the worker a sandbox. The code is still JavaScript that runs under the address of this site, and a worker can do a lot: send requests over the network, for example, or open the database with your samples. So the rule for a link is: its code is shown, and not run. It only runs when whoever opened the link has had the chance to read it and presses Play.

In src/main.ts, add codeFromLink to the import from ./share.ts, and add below show():

src/main.ts
// Opened from a link: show its code, but don't run it. Code from someone else only plays
// once the reader has seen it and pressed Play.
void codeFromLink().then((code) => {
  if (code === undefined) return;
  show(code);
  // Without the code in the address, a reload brings back the reader's own code.
  history.replaceState(null, '', location.pathname);
  status.textContent = 'This song came with a link. Have a look at the code, then press Play.';
});

show() puts the code into the editor without saving it. Then history.replaceState() takes the code out of the address, without loading the page again. A reload after that brings back the receiver's own song, not the one of the link. The line under the editor says what happened.

Two buttons

The header gets a button that makes a link, and one that brings back the example song. In index.html, replace the header:

index.html
<header>
  <strong class="name">loopcode</strong>
  <button id="play">▶ Play</button>
  <span id="position" class="position">1.1</span>
  <canvas id="scope" class="scope"></canvas>
  <span class="tempo"><span id="bpm">120</span> bpm</span>
  <button id="run" title="Ctrl+Enter">Run</button>
  <button id="share" title="Copy a link to this song">Share</button>
  <button id="example" title="Load the example song">Example</button>
</header>

In src/main.ts, add linkFor to the import from ./share.ts, and add below the code for the link:

src/main.ts
document.querySelector<HTMLButtonElement>('#share')!.addEventListener('click', async () => {
  const link = await linkFor(editor.state.doc.toString());
  try {
    await navigator.clipboard.writeText(link);
    status.textContent = `Copied a link to this song, ${link.length} characters long. Samples you added are not part of it.`;
  } catch {
    // The clipboard can be off limits. Then the link is shown, to copy by hand.
    status.textContent = link;
  }
  status.classList.remove('error');
});

document.querySelector<HTMLButtonElement>('#example')!.addEventListener('click', () => show(SONG));

Share packs the code that is in the editor, copies the link to the clipboard and says how long it is. A browser can refuse access to the clipboard. Then the link itself is shown in the line under the editor, to be copied by hand. Example uses show(), so the example does not replace your saved song. Click into the editor and press Ctrl+Z to get back what was in it.

With two more buttons the header can get too wide for a narrow window. It is allowed to wrap, and the scope to shrink. In src/style.css, replace the rule for header:

src/style.css
header {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 12px;
  padding: 8px 12px;
  background: var(--night);
  border-bottom: 2px solid var(--edge);
}

And replace the rule for .scope:

src/style.css
.scope {
  flex: 0 1 200px;
  min-width: 60px;
  height: 32px;
  margin-left: auto;
  border: 1px solid var(--edge);
  border-radius: 4px;
  background: var(--void);
}

Building the app

So far the app ran on Vite's development server. For any other place it is built:

~/loopcode
$ npm run build> loopcode@0.0.0 build> tsc && vite buildvite v8.3.8 building client environment for production...transforming...✓ 46 modules transformed.rendering chunks...computing gzip size...dist/index.html                   1.15 kB │ gzip:   0.56 kBdist/assets/worker-Dpeao0ae.js   15.25 kBdist/assets/index-BxyxURz8.css    2.11 kB │ gzip:   0.82 kBdist/assets/index-C5I59F7t.js   543.16 kB │ gzip: 182.24 kB✓ built in 193ms

The folder dist now holds the whole app: a page, a style sheet and two scripts, of which the worker is one. Any web server that hands out files can host it, because nothing runs on the server. linkFor() builds its links from the address the page was opened at, so they lead to wherever you put it. The built page expects to sit at the root of its site. For a subfolder, set Vite's base option to that folder before you build.

What you built

The series began with a single oscillator and a click on a button. This is what stands at its end:

  • A clock that schedules notes ahead on the audio clock and counts in cycles instead of seconds (part 2)

  • A drum machine whose sounds are made from oscillators and noise (part 3)

  • Patterns as functions of time, and a mini-notation for them with its own tokenizer, parser and compiler (parts 4 to 7)

  • A mono synth with accent and slide, a poly synth for chords, and a sampler for your own recordings (parts 8, 12 and 15)

  • An editor whose code describes a patch, and an engine that turns the patch into sound (part 9)

  • Changes that are taken over while the music plays, in time and without a restart (part 10)

  • Error messages with a line number, and a worker that stops code that never ends (part 11)

  • Filter, delay, reverb and distortion, a limiter in front of the speakers, and LFOs, slow waves that move a setting in step with the bars (parts 13 and 14)

  • Steps that light up while they sound, a scope with a spectrum, suggestions and explanations in the editor (parts 16 and 17)

  • Songs that survive a reload and travel in a link (this part)

All of it uses the Web Audio API directly, without an audio library, and CodeMirror is the only larger package in the project.

Where to go from here

The app is built so that it can grow. Some ideas:

  • More instruments. A new unit takes a class, an entry in the schema and a line in the engine's factories, as in part 12. A synth built on frequency modulation, the method behind the bell of part 15, would be a start.

  • Swing. An option swing for pattern() that plays every second eighth note a little late. The place for it is events() in the player, where the times of the haps become times of the audio clock.

  • MIDI. With the Web MIDI API, in browsers that offer it, a unit could send the notes of a pattern to a hardware synth instead of playing them itself.

  • Recording. A MediaRecorder records a stream as data that can be saved as a file, and createMediaStreamDestination() of the AudioContext gives a node that turns sound into such a stream. Connect the limiter to it, the way part 16 connected the analyser.

And if you want to see these ideas in a bigger app: loopcode is a small relative of wicktone. There a code mode like this one sits next to a canvas of nodes, with more instruments to connect.

Try it

Replace the code with a short song and press Play:

javascript
bpm(110)

const kit = drums()
pattern('bd ~ sd ~, hh*8').to(kit)
kit.to(out)

Wait a moment, then load the page again. The song is still in the editor. Press Share: the line under the editor says that a link was copied and how long it is. For this song the packed code is about 100 characters, and the address of the page comes on top. If the link could not be copied, the line shows the link itself.

Open the link in a new tab. The code appears in the editor, the line under it says "This song came with a link. Have a look at the code, then press Play.", and the address no longer contains the code. Nothing sounds until you press Play. Then delete a few characters from the end of the link and open that in another tab: the broken link is ignored, and the app starts with your own code. Example brings back the example song. Click into the editor and press Ctrl+Z, and what was in it before is back.

The finished app. Write a song, press Play, then Share, and open the copied link in a new tab. Example brings back the example song. Ctrl+Enter runs changed code, Ctrl+. stops.
Open in a new tab

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.