refactor(client/ts): use discriminated unions for triggering events

This commit is contained in:
Elian Doran
2024-12-21 23:54:47 +02:00
parent 4e3417482e
commit 3bfb163a39

View File

@@ -100,7 +100,26 @@ type CommandMappings = {
closeProtectedSessionPasswordDialog: NoData; closeProtectedSessionPasswordDialog: NoData;
} }
type EventMappings = {
initialRenderComplete: {};
frocaReloaded: {};
protectedSessionStarted: {};
notesReloaded: {
noteIds: string[];
};
refreshIncludedNote: {
noteId: string;
};
apiLogMessages: {
noteId: string;
messages: string[];
};
}
type CommandAndEventMappings = (CommandMappings & EventMappings);
export type CommandNames = keyof CommandMappings; export type CommandNames = keyof CommandMappings;
type EventNames = keyof EventMappings;
class AppContext extends Component { class AppContext extends Component {
@@ -195,8 +214,9 @@ class AppContext extends Component {
this.triggerEvent('initialRenderComplete'); this.triggerEvent('initialRenderComplete');
} }
// TODO: Update signature once all client code is updated, to use a map similar to triggerCommand. // TODO: Remove ignore once all commands are mapped out.
triggerEvent(name: string, data: unknown = {}) { //@ts-ignore
triggerEvent<K extends EventNames | CommandNames>(name: K, data: CommandAndEventMappings[K] = {}) {
return this.handleEvent(name, data); return this.handleEvent(name, data);
} }
@@ -215,7 +235,7 @@ class AppContext extends Component {
// in the component tree to communicate with each other // in the component tree to communicate with each other
console.debug(`Unhandled command ${name}, converting to event.`); console.debug(`Unhandled command ${name}, converting to event.`);
return this.triggerEvent(name, data); return this.triggerEvent(name, data as CommandAndEventMappings[K]);
} }
getComponentByEl(el: HTMLElement) { getComponentByEl(el: HTMLElement) {