From f3252008e522db7fae723cdc7b28a2f7b26caa98 Mon Sep 17 00:00:00 2001 From: monkey-w1n5t0n Date: Tue, 7 Apr 2026 16:29:09 +0200 Subject: [PATCH] feat(solidjs): implement reactive signal bus with wildcard matching Add signal bus (src/bus/signal-bus.ts) with: - Named topics using createSignal with equals:false for event semantics - emit() triggers all subscribers even with identical data - subscribe() returns unsubscribe function - match() with wildcard patterns: * (single segment) and ** (multi-segment) - Callable topic interface (topic() reads current value) Wire bus into App.tsx, expose as window.__nispsBus for tests. 10 e2e tests covering all bus behaviors (VAL-PROJ-004). Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- src/App.tsx | 9 ++ src/bus/signal-bus.ts | 187 +++++++++++++++++++++++ tests/solidjs/signal-bus.spec.ts | 255 +++++++++++++++++++++++++++++++ 3 files changed, 451 insertions(+) create mode 100644 src/bus/signal-bus.ts create mode 100644 tests/solidjs/signal-bus.spec.ts diff --git a/src/App.tsx b/src/App.tsx index 95e6424..e34b507 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,10 +1,19 @@ import { onMount, onCleanup, createSignal } from 'solid-js'; import { WasmIML } from './core/iml'; +import { createSignalBus, type SignalBus } from './bus/signal-bus'; const N_INPUTS = 2; const HIDDEN_LAYERS = [32, 48, 64]; const N_OUTPUTS = 126; +// Singleton signal bus — shared across the entire app +const bus: SignalBus = createSignalBus(); + +// Expose bus globally for e2e tests and debug access +(window as any).__nispsBus = bus; + +export { bus }; + /** * Root application component for the NISPS immersive app. * Initializes WASM IML, runs initial inference, and exposes debug probe. diff --git a/src/bus/signal-bus.ts b/src/bus/signal-bus.ts new file mode 100644 index 0000000..6a75e22 --- /dev/null +++ b/src/bus/signal-bus.ts @@ -0,0 +1,187 @@ +/** + * Reactive Signal Bus — unified event system for the NISPS SolidJS app. + * + * Replaces EventBus + CustomEvents from the old playground app. + * Uses SolidJS `createSignal` with `equals: false` so every emit() + * triggers subscribers even when the data is identical. + * + * Wildcard matching via `match()` supports: + * `*` — matches exactly one segment (e.g. "ml.*" matches "ml.loss" but not "ml.a.b") + * `**` — matches zero or more segments (e.g. "a.**" matches "a", "a.b", "a.b.c") + */ +import { createSignal } from 'solid-js'; + +// ─── Types ──────────────────────────────────────────────────────────── + +export type Unsubscribe = () => void; + +export type Subscriber = (value: T, topicName: string) => void; + +/** A callable topic: read current value by calling it, or use emit/subscribe. */ +export interface Topic { + /** Read the current value (signal getter) */ + (): T | undefined; + /** Emit a new value — always triggers subscribers (equals: false) */ + emit(value: T): void; + /** Subscribe to emissions. Returns an unsubscribe function. */ + subscribe(fn: Subscriber): Unsubscribe; + /** The topic name */ + readonly name: string; +} + +export interface SignalBus { + /** Create (or get existing) named topic */ + createTopic(name: string): Topic; + /** Retrieve an existing topic by name, or undefined */ + getTopic(name: string): Topic | undefined; + /** + * Subscribe to all topics matching a wildcard pattern. + * - `*` matches one segment + * - `**` matches zero or more segments + * Also fires for topics created after the match() call. + * Returns an unsubscribe function. + */ + match(pattern: string, fn: Subscriber): Unsubscribe; +} + +// ─── Implementation ─────────────────────────────────────────────────── + +/** + * Check if a topic name matches a wildcard pattern. + * + * - `*` matches exactly one dot-separated segment + * - `**` matches zero or more segments + */ +function matchesWildcard(pattern: string, name: string): boolean { + // Exact match + if (pattern === name) return true; + + const patternParts = pattern.split('.'); + const nameParts = name.split('.'); + + return matchParts(patternParts, 0, nameParts, 0); +} + +function matchParts( + pp: string[], pi: number, + np: string[], ni: number, +): boolean { + // Both exhausted → match + if (pi === pp.length && ni === np.length) return true; + // Pattern exhausted but name remains → no match + if (pi === pp.length) return false; + + // Double wildcard ** + if (pp[pi] === '**') { + // Try matching ** with zero segments (skip ** in pattern) + if (matchParts(pp, pi + 1, np, ni)) return true; + // Try matching ** with one or more segments (consume one name segment, keep **) + if (ni < np.length && matchParts(pp, pi, np, ni + 1)) return true; + return false; + } + + // Name exhausted but pattern remains (and it's not **) → no match + if (ni === np.length) return false; + + // Single wildcard * or exact segment match + if (pp[pi] === '*' || pp[pi] === np[ni]) { + return matchParts(pp, pi + 1, np, ni + 1); + } + + return false; +} + +/** + * Create a Topic by wrapping a function with signal-backed emit/subscribe. + * + * We use a factory function + Object.assign instead of an object literal with + * a call signature, because Vite's OXC parser doesn't support function-call + * shorthand inside object literals. + */ +function makeTopic( + name: string, + matchSubscribers: Array<{ + pattern: string; + fn: Subscriber; + matcher: (name: string) => boolean; + }>, +): Topic { + // equals: false ensures every emit() triggers subscribers, + // even if the value is identical to the previous one. + const [getValue, setValue] = createSignal(undefined, { equals: false }); + + const subs: Array> = []; + + // Start with a simple function (callable — reads the signal value) + const topic = function topicReader(): T | undefined { + return getValue(); + } as Topic; + + // Attach properties + Object.defineProperty(topic, 'name', { + get: () => name, + enumerable: true, + }); + + topic.emit = function emit(value: T): void { + setValue(() => value); + + // Notify direct subscribers + for (const sub of subs) { + sub(value, name); + } + + // Notify wildcard match subscribers + for (const ms of matchSubscribers) { + if (ms.matcher(name)) { + ms.fn(value, name); + } + } + }; + + topic.subscribe = function subscribe(fn: Subscriber): Unsubscribe { + subs.push(fn); + return () => { + const idx = subs.indexOf(fn); + if (idx !== -1) subs.splice(idx, 1); + }; + }; + + return topic; +} + +export function createSignalBus(): SignalBus { + const topics = new Map>(); + const matchSubscribers = new Array<{ + pattern: string; + fn: Subscriber; + matcher: (name: string) => boolean; + }>(); + + function createTopic(name: string): Topic { + const existing = topics.get(name); + if (existing) return existing as Topic; + + const topic = makeTopic(name, matchSubscribers); + topics.set(name, topic); + return topic; + } + + function getTopic(name: string): Topic | undefined { + return topics.get(name) as Topic | undefined; + } + + function match(pattern: string, fn: Subscriber): Unsubscribe { + const matcher = (name: string) => matchesWildcard(pattern, name); + + const entry = { pattern, fn, matcher }; + matchSubscribers.push(entry); + + return () => { + const idx = matchSubscribers.indexOf(entry); + if (idx !== -1) matchSubscribers.splice(idx, 1); + }; + } + + return { createTopic, getTopic, match }; +} diff --git a/tests/solidjs/signal-bus.spec.ts b/tests/solidjs/signal-bus.spec.ts new file mode 100644 index 0000000..1cef198 --- /dev/null +++ b/tests/solidjs/signal-bus.spec.ts @@ -0,0 +1,255 @@ +/** + * e2e tests for f02-signal-bus. + * Validates: + * VAL-PROJ-004: Signal bus creates topics, emit/receive, match() wildcards, + * equals:false semantics (every emit triggers subscribers) + */ +import { test, expect, Page } from '@playwright/test'; +import { loadSolidApp } from './helpers'; + +test.describe('Signal Bus', () => { + + test('VAL-PROJ-004a: createTopic creates a named topic and emit triggers subscriber', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: number[] = []; + + const topic = bus.createTopic('test-emit'); + const unsub = topic.subscribe((val: number) => received.push(val)); + + topic.emit(42); + topic.emit(99); + + unsub(); + + return { received }; + }); + + expect(result.received).toEqual([42, 99]); + }); + + test('VAL-PROJ-004b: emit with identical data triggers subscriber every time (equals:false)', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + let callCount = 0; + const received: string[] = []; + + const topic = bus.createTopic('test-equals'); + const unsub = topic.subscribe((val: string) => { + callCount++; + received.push(val); + }); + + // Emit the same value 3 times + topic.emit('hello'); + topic.emit('hello'); + topic.emit('hello'); + + unsub(); + + return { callCount, received }; + }); + + expect(result.callCount).toBe(3); + expect(result.received).toEqual(['hello', 'hello', 'hello']); + }); + + test('VAL-PROJ-004c: match() with wildcards merges multiple topics', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: { topic: string; value: number }[] = []; + + // Create three topics + bus.createTopic('ml.loss'); + bus.createTopic('ml.outputs'); + bus.createTopic('ui.state'); + + // Subscribe to all 'ml.*' topics via wildcard match + const unsub = bus.match('ml.*', (value: number, topicName: string) => { + received.push({ topic: topicName, value }); + }); + + // Emit on different topics + bus.getTopic('ml.loss')!.emit(0.5); + bus.getTopic('ml.outputs')!.emit(0.8); + bus.getTopic('ui.state')!.emit(0.3); + + unsub(); + + return { received }; + }); + + // Should have received from ml.loss and ml.outputs but NOT ui.state + expect(result.received).toHaveLength(2); + expect(result.received[0]).toEqual({ topic: 'ml.loss', value: 0.5 }); + expect(result.received[1]).toEqual({ topic: 'ml.outputs', value: 0.8 }); + }); + + test('match() with nested wildcards matches deeply', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: string[] = []; + + bus.createTopic('a.b.c'); + bus.createTopic('a.b.d'); + bus.createTopic('a.x.y'); + bus.createTopic('z.b.c'); + + const unsub = bus.match('a.b.*', (val: number, name: string) => { + received.push(name); + }); + + bus.getTopic('a.b.c')!.emit(1); + bus.getTopic('a.b.d')!.emit(2); + bus.getTopic('a.x.y')!.emit(3); + bus.getTopic('z.b.c')!.emit(4); + + unsub(); + + return { received }; + }); + + expect(result.received).toEqual(['a.b.c', 'a.b.d']); + }); + + test('match() with double wildcard ** matches all levels', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: string[] = []; + + bus.createTopic('a.b.c'); + bus.createTopic('a.b'); + bus.createTopic('a'); + + const unsub = bus.match('a.**', (val: number, name: string) => { + received.push(name); + }); + + bus.getTopic('a')!.emit(1); + bus.getTopic('a.b')!.emit(2); + bus.getTopic('a.b.c')!.emit(3); + + unsub(); + + return { received }; + }); + + // ** should match 'a' itself and all descendants + expect(result.received).toEqual(['a', 'a.b', 'a.b.c']); + }); + + test('unsubscribe stops further emissions', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: number[] = []; + + const topic = bus.createTopic('test-unsub'); + const unsub = topic.subscribe((val: number) => received.push(val)); + + topic.emit(1); + topic.emit(2); + + unsub(); + + topic.emit(3); + topic.emit(4); + + return { received }; + }); + + expect(result.received).toEqual([1, 2]); + }); + + test('multiple subscribers on same topic all fire', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received1: number[] = []; + const received2: number[] = []; + + const topic = bus.createTopic('test-multi'); + + const unsub1 = topic.subscribe((val: number) => received1.push(val)); + const unsub2 = topic.subscribe((val: number) => received2.push(val * 10)); + + topic.emit(5); + + unsub1(); + unsub2(); + + return { received1, received2 }; + }); + + expect(result.received1).toEqual([5]); + expect(result.received2).toEqual([50]); + }); + + test('topic() reads current value', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + + const topic = bus.createTopic('test-read'); + topic.emit(42); + + const val = topic(); + + return { val }; + }); + + expect(result.val).toBe(42); + }); + + test('getTopic returns undefined for non-existent topic', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + return { exists: bus.getTopic('non-existent') !== undefined }; + }); + + expect(result.exists).toBe(false); + }); + + test('match() fires for topics created after match call', async ({ page }) => { + await loadSolidApp(page); + + const result = await page.evaluate(() => { + const bus = (window as any).__nispsBus; + const received: string[] = []; + + // Set up match before the topic exists + const unsub = bus.match('dynamic.*', (val: number, name: string) => { + received.push(name); + }); + + // Now create the topic and emit + bus.createTopic('dynamic.one'); + bus.getTopic('dynamic.one')!.emit(1); + + // Create another matching topic + bus.createTopic('dynamic.two'); + bus.getTopic('dynamic.two')!.emit(2); + + unsub(); + + return { received }; + }); + + expect(result.received).toEqual(['dynamic.one', 'dynamic.two']); + }); +});