Skip to content

Commit 2ed552d

Browse files
committed
✨ dispatch: add middleware-extensible host events
1 parent 371f18d commit 2ed552d

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

‎packages/ui/src/dispatch.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { describe, expect, test } from 'vitest';
2+
import { DispatchApi, useDispatch } from './dispatch.ts';
3+
import { createHost } from './host.ts';
4+
5+
const { dispatch } = DispatchApi.methods;
6+
7+
describe('dispatch', () => {
8+
test('catches errors thrown by middleware installed on the host', () => {
9+
const host = createHost();
10+
const reason = new Error('dispatch failed');
11+
useDispatch(host);
12+
DispatchApi.around(host.root, {
13+
dispatch() {
14+
throw reason;
15+
},
16+
});
17+
18+
expect(dispatch(host.root, {})).toEqual({ ok: false, reason });
19+
});
20+
});

‎packages/ui/src/dispatch.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { createApi } from './core.ts';
2+
import type { Host } from './host.ts';
3+
4+
export const DispatchApi = createApi('dispatch', {
5+
dispatch(_node, _event: unknown): Result {
6+
return Ok;
7+
},
8+
});
9+
10+
export function useDispatch(host: Host): void {
11+
DispatchApi.around(host.root, {
12+
dispatch(args, next) {
13+
try {
14+
return next(...args);
15+
} catch (reason) {
16+
return { ok: false, reason };
17+
}
18+
},
19+
});
20+
}
21+
22+
export type Result =
23+
| typeof Ok
24+
| {
25+
ok: false;
26+
reason: unknown;
27+
};
28+
29+
const Ok = { ok: true } as const;

‎packages/ui/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export { rgba } from '@bomb.sh/tty';
2+
export { DispatchApi } from './dispatch.ts';
23
export { box, type BoxProps } from './components/box.ts';
34
export { text, type TextProps } from './components/text.ts';
45
export { layout, LayoutApi } from './layout.ts';

0 commit comments

Comments
 (0)