forked from webxdc/webxdc-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
93 lines (74 loc) · 2.3 KB
/
store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { createResource, createSignal } from "solid-js";
import { createStore, produce } from "solid-js/store";
import type { Message, UpdateMessage } from "../types/message";
import type { Instance as InstanceData } from "../types/instance";
import type { Info } from "../types/info";
export type Search = {
instanceId?: string;
type?: string;
info?: boolean;
};
const [appInfo] = createResource<Info>(async () => {
return await (await fetch("/app-info")).json();
});
export { appInfo };
const [instances, { refetch: refetchInstances, mutate: mutateInstances }] =
createResource<InstanceData[]>(async () => {
return (await fetch(`/instances`)).json();
});
export { instances, refetchInstances, mutateInstances };
const [state, setState] = createStore<Message[]>([]);
const [summary, setSummary] = createSignal<string | undefined>(undefined);
export { summary };
export function addMessage(message: Message): void {
if (isUpdateMessage(message) && message.type === "received") {
const summary = message.update.summary;
if (hasText(summary)) {
setSummary(summary);
}
}
setState(
produce((s) => {
s.push(message);
})
);
}
export function clearMessages(): void {
setState([]);
}
export function sent(instanceId: string): number {
let result = 0;
for (const message of state) {
if (message.type === "sent" && message.instanceId === instanceId) {
result++;
}
}
return result;
}
export function received(instanceId: string): number {
let result = 0;
for (const message of state) {
if (message.type === "received" && message.instanceId === instanceId) {
result++;
}
}
return result;
}
export function getMessages(search: Search): Message[] {
const { instanceId, type, info } = search;
if (instanceId == null && type == null && info == null) {
return state;
}
return state.filter(
(message) =>
(instanceId == null || message.instanceId === instanceId) &&
(type == null || message.type === type) &&
(!info || (isUpdateMessage(message) && hasText(message.update.info)))
);
}
function hasText(s: string | undefined): s is string {
return s != null && s.length > 0;
}
export function isUpdateMessage(message: Message): message is UpdateMessage {
return message.type === "sent" || message.type === "received";
}