Files
dragology-pd/src/bridge/client.ts
T
david fe6f2bfe76 Browser patch editor for Pure Data (closes #1)
Open a .pd file, drag boxes and pull cords, save it back as a file Pd
will load. Dragging is Dragology: `d.vary` moves a box, and a cord drag
is `d.closest(...).whenFar(vary)` over every inlet in the patch, so the
plug snaps to an inlet and cancels on empty space.

The parser is a byte-exact round trip. Two Pd format details that matter:
`#X connect` indices count comments, and `;;` (an empty record) is not the
same as a blank line. Anything unmodelled — arrays, `#X declare`,
subpatches — is preserved verbatim.

Tests run real Pd: patches round trip, an edited patch loads in
`pd -nogui` without new complaints, and the bridge carries a message into
a running Pd and back.

The bridge writes to server/patches/ and runs `pd -nogui` itself, so
saving and hearing the patch is one button.
2026-11-04 19:19:53 -08:00

77 lines
2.1 KiB
TypeScript

import type { PatchState } from "../editor/ops.ts";
export type BridgeMessage =
| { type: "hello"; pdRunning: boolean; toPdPort: number; fromPdPort: number }
| { type: "from-pd"; receiver: string; args: string[] }
| { type: "log"; stream: "stdout" | "stderr"; line: string }
| { type: "pd-status"; running: boolean; file: string | null }
| { type: "error"; message: string };
export type BridgeStatus = "disconnected" | "connecting" | "open";
/**
* Thin WebSocket client for `server/bridge.mjs`.
*
* The bridge is optional: the editor works on files alone, and the socket
* only exists to run a patch in a real Pd and to poke named receivers.
*/
export class Bridge {
private ws: WebSocket | null = null;
private listeners = new Set<(m: BridgeMessage) => void>();
private statusListeners = new Set<(s: BridgeStatus) => void>();
constructor(private url: string) {}
onMessage(fn: (m: BridgeMessage) => void) {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
onStatus(fn: (s: BridgeStatus) => void) {
this.statusListeners.add(fn);
return () => this.statusListeners.delete(fn);
}
private emitStatus(status: BridgeStatus) {
for (const fn of this.statusListeners) fn(status);
}
connect() {
if (this.ws) return;
this.emitStatus("connecting");
const ws = new WebSocket(this.url);
this.ws = ws;
ws.onopen = () => this.emitStatus("open");
ws.onclose = () => {
this.ws = null;
this.emitStatus("disconnected");
};
ws.onerror = () => this.emitStatus("disconnected");
ws.onmessage = (event) => {
let message: BridgeMessage;
try {
message = JSON.parse(String(event.data));
} catch {
return;
}
for (const fn of this.listeners) fn(message);
};
}
disconnect() {
this.ws?.close();
this.ws = null;
this.emitStatus("disconnected");
}
send(message: unknown): boolean {
if (this.ws?.readyState !== WebSocket.OPEN) return false;
this.ws.send(JSON.stringify(message));
return true;
}
get isOpen() {
return this.ws?.readyState === WebSocket.OPEN;
}
}