This repository has been archived by the owner on Feb 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 103
/
EventsPanel.tsx
488 lines (469 loc) · 13.2 KB
/
EventsPanel.tsx
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import {
ChevronDownIcon,
ChevronRightIcon,
ChevronUpIcon,
} from '@chakra-ui/icons';
import {
Box,
Button,
ButtonGroup,
FormLabel,
IconButton,
Input,
Popover,
PopoverArrow,
PopoverBody,
PopoverContent,
PopoverFooter,
PopoverHeader,
PopoverTrigger,
Portal,
Switch,
Table,
Tbody,
Td,
Text,
Th,
Thead,
Tr,
} from '@chakra-ui/react';
import Editor from '@monaco-editor/react';
import { useActor, useMachine, useSelector } from '@xstate/react';
import { format } from 'date-fns';
import React, { useEffect, useState } from 'react';
import { assign, createMachine, SCXML, send, StateFrom } from 'xstate';
import { createModel } from 'xstate/lib/model';
import { toSCXMLEvent } from 'xstate/lib/utils';
import { JSONView } from './JSONView';
import { useSimulation } from './SimulationContext';
import { SimEvent, simulationMachine } from './simulationMachine';
import { isInternalEvent, isNullEvent } from './utils';
const EventConnection: React.FC<{ event: SimEvent }> = ({ event }) => {
const sim = useSimulation();
const originId = useSelector(
sim,
(state) =>
event.origin && state.context.serviceDataMap[event.origin]?.machine.id,
);
const targetId = useSelector(
sim,
(state) => state.context.serviceDataMap[event.sessionId]?.machine.id,
);
return (
<Box display="inline-flex" flexDirection="row" gap="1ch" fontSize="sm">
{originId && <Text whiteSpace="nowrap">{originId} → </Text>}
<Text whiteSpace="nowrap">{targetId}</Text>
</Box>
);
};
// To keep the table header sticky, the trick is to make all `th` elements sticky
const stickyProps = {
position: 'sticky',
top: 0,
backgroundColor: 'var(--chakra-colors-gray-800)',
zIndex: 1,
} as const;
const sortByCriteria = {
ASC: (events: SimEvent[]) =>
events.sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1)),
DESC: (events: SimEvent[]) =>
events.sort((a, b) => (a.timestamp > b.timestamp ? 1 : -1)),
};
type SortCriteria = keyof typeof sortByCriteria;
const eventsModel = createModel(
{
sortCriteria: null as SortCriteria | null,
filterKeyword: '',
showBuiltins: false,
rawEvents: [] as SimEvent[],
},
{
events: {
SORT_BY_TIMESTAMP: (sortCriteria: SortCriteria) => ({ sortCriteria }),
FILTER_BY_KEYWORD: (keyword: string) => ({ keyword }),
TOGGLE_BUILTIN_EVENTS: (showBuiltins: boolean) => ({ showBuiltins }),
EVENTS_UPDATED: (events: SimEvent[]) => ({ events }),
},
},
);
const eventsMachine = createMachine<typeof eventsModel>({
initial: 'raw',
context: eventsModel.initialContext,
states: {
raw: {},
modified: {},
},
on: {
SORT_BY_TIMESTAMP: {
target: 'modified',
actions: [
eventsModel.assign((_, e) => ({
sortCriteria: e.sortCriteria,
})),
],
},
FILTER_BY_KEYWORD: {
target: 'modified',
actions: [
eventsModel.assign((_, e) => ({
filterKeyword: e.keyword,
})),
],
},
EVENTS_UPDATED: {
actions: [
eventsModel.assign((_, e) => ({
rawEvents: e.events,
})),
],
},
TOGGLE_BUILTIN_EVENTS: {
target: 'modified',
actions: [
eventsModel.assign((_, e) => ({
showBuiltins: e.showBuiltins,
})),
],
},
},
});
const deriveFinalEvents = (ctx: typeof eventsModel.initialContext) => {
let finalEvents = ctx.rawEvents;
if (!ctx.showBuiltins) {
finalEvents = finalEvents.filter((event) => {
return !isInternalEvent(event.name) && !isNullEvent(event.name);
});
}
if (ctx.filterKeyword) {
finalEvents = finalEvents.filter((evt) =>
evt.name.toUpperCase().includes(ctx.filterKeyword.toUpperCase()),
);
}
if (ctx.sortCriteria) {
finalEvents = sortByCriteria[ctx.sortCriteria](finalEvents.slice());
}
return finalEvents;
};
const selectMachine = (state: StateFrom<typeof simulationMachine>) =>
state.context.currentSessionId
? state.context.serviceDataMap[state.context.currentSessionId]
: undefined; // TODO: select() method on model
export const EventsPanel: React.FC = () => {
const sim = useSimulation();
const [state, send] = useActor(sim);
const rawEvents = state.context!.events;
const nextEvents = useSelector(
sim,
(state) => selectMachine(state)?.state.nextEvents,
(a, b) => JSON.stringify(a) === JSON.stringify(b),
);
const [eventsState, sendToEventsMachine] = useMachine(() =>
eventsMachine.withContext({
...eventsModel.initialContext,
rawEvents: rawEvents,
}),
);
const finalEvents = deriveFinalEvents(eventsState.context);
useEffect(() => {
sendToEventsMachine({
type: 'EVENTS_UPDATED',
events: rawEvents,
});
}, [rawEvents, sendToEventsMachine]);
return (
<Box
display="grid"
gridTemplateRows="auto 1fr auto"
gridRowGap="2"
height="100%"
>
<Box display="flex" justifyContent="flex-end" alignItems="center">
<Input
placeholder="Filter events"
type="search"
onChange={(e) => {
sendToEventsMachine({
type: 'FILTER_BY_KEYWORD',
keyword: e.target.value,
});
}}
marginRight="auto"
width="40%"
/>
<Box display="flex" alignItems="center">
<FormLabel marginBottom="0" marginRight="1" htmlFor="builtin-toggle">
Show built-in events
</FormLabel>
<Switch
id="builtin-toggle"
onChange={(e) => {
sendToEventsMachine({
type: 'TOGGLE_BUILTIN_EVENTS',
showBuiltins: e.target.checked,
});
}}
/>
</Box>
</Box>
<Box overflowY="auto">
<Table width="100%">
<Thead>
<Tr>
<Th {...stickyProps} width="100%">
Event type
</Th>
<Th {...stickyProps}>To</Th>
<Th {...stickyProps} whiteSpace="nowrap">
Time
<Box
display="inline-flex"
flexDirection="column"
verticalAlign="middle"
marginLeft="1"
>
<IconButton
aria-label="sort by timestamp descending"
title="sort by timestamp descending"
icon={<ChevronUpIcon />}
variant="unstyled"
size="xs"
bg={
eventsState.context.sortCriteria === 'DESC'
? 'var(--chakra-colors-gray-700)'
: undefined
}
onClick={() => {
sendToEventsMachine({
type: 'SORT_BY_TIMESTAMP',
sortCriteria: 'DESC',
});
}}
/>
<IconButton
aria-label="sort by timestamp ascending"
title="sort by timestamp ascending"
icon={<ChevronDownIcon />}
variant="unstyled"
size="xs"
bg={
eventsState.context.sortCriteria === 'ASC'
? 'var(--chakra-colors-gray-700)'
: undefined
}
onClick={() => {
sendToEventsMachine({
type: 'SORT_BY_TIMESTAMP',
sortCriteria: 'ASC',
});
}}
/>
</Box>
</Th>
</Tr>
</Thead>
<Tbody>
{finalEvents.map((event, i) => {
return <EventRow event={event} key={i} />;
})}
</Tbody>
</Table>
</Box>
<NewEvent
onSend={(event) => send({ type: 'SERVICE.SEND', event })}
nextEvents={nextEvents}
/>
</Box>
);
};
const EventRow: React.FC<{ event: SimEvent }> = ({ event }) => {
const [show, setShow] = useState(false);
return (
<>
<Tr cursor="pointer" onClick={() => setShow(!show)}>
<Td>
{show ? <ChevronDownIcon /> : <ChevronRightIcon />}
{event.name}
</Td>
<Td color="gray.500" textAlign="right">
<EventConnection event={event} />
</Td>
<Td color="gray.500">{format(event.timestamp, 'H:mm:ss')}</Td>
</Tr>
{show ? (
<Tr>
<Td colSpan={3}>
<JSONView src={event.data} />
</Td>
</Tr>
) : null}
</>
);
};
const newEventModel = createModel(
{
eventType: '',
eventString: `{\n\t"type": ""\n}`,
},
{
events: {
'EVENT.TYPE': (value: string) => ({ value }),
'EVENT.PAYLOAD': (value: string) => ({ value }),
'EVENT.SEND': () => ({}),
'EVENT.RESET': () => ({}),
},
},
);
const newEventMachine = newEventModel.createMachine({
type: 'parallel',
states: {
validity: {
initial: 'invalid',
states: {
invalid: {},
valid: {
tags: 'valid',
},
},
on: {
'*': [
{
cond: (_, e) => {
try {
const eventObject = JSON.parse(
(e as ReturnType<
typeof newEventModel.events['EVENT.PAYLOAD']
>).value,
);
return typeof eventObject.type === 'string';
} catch (e) {
return false;
}
},
target: '.valid',
},
{ target: '.invalid' },
],
},
},
editing: {
on: {
'EVENT.PAYLOAD': {
actions: assign({ eventString: (_, e) => e.value }),
},
'EVENT.SEND': {
actions: ['sendEvent', send('EVENT.RESET')],
},
'EVENT.RESET': {
actions: newEventModel.reset(),
},
},
},
},
});
const NewEvent: React.FC<{
onSend: (scxmlEvent: SCXML.Event<any>) => void;
nextEvents?: string[];
}> = ({ onSend, nextEvents }) => {
const [state, send] = useMachine(newEventMachine, {
actions: {
sendEvent: (ctx) => {
try {
const scxmlEvent = toSCXMLEvent({
type: ctx.eventType,
...JSON.parse(ctx.eventString),
});
onSend(scxmlEvent);
} catch (e) {
console.error(e);
}
},
},
});
return (
<Box
display="flex"
flexDirection="row"
css={{
gap: '.5rem', // TODO: source from Chakra
}}
>
<Popover>
{({ onClose }) => (
<>
<PopoverTrigger>
<Button variant="outline">Send event</Button>
</PopoverTrigger>
<Portal>
<PopoverContent>
<PopoverArrow />
<PopoverHeader
display="flex"
flexWrap="wrap"
css={{
gap: '.5rem',
}}
>
{nextEvents &&
nextEvents.map((nextEvent) => (
<Button
key={nextEvent}
size="xs"
colorScheme="blue"
onClick={() =>
send(
newEventModel.events['EVENT.PAYLOAD'](
`{\n\t"type": "${nextEvent}"\n}`,
),
)
}
>
{nextEvent}
</Button>
))}
</PopoverHeader>
<PopoverBody bg="gray.800">
<Editor
language="json"
options={{
minimap: { enabled: false },
lineNumbers: 'off',
tabSize: 2,
}}
height="150px"
width="auto"
value={state.context.eventString}
onChange={(text) => {
text && send(newEventModel.events['EVENT.PAYLOAD'](text));
}}
/>
</PopoverBody>
<PopoverFooter display="flex" justifyContent="flex-end">
<ButtonGroup spacing={2}>
<Button
variant="ghost"
onClick={() => {
send(newEventModel.events['EVENT.RESET']());
onClose();
}}
>
Cancel
</Button>
<Button
disabled={!state.hasTag('valid')}
onClick={() => {
send(newEventModel.events['EVENT.SEND']());
onClose();
}}
>
Send
</Button>
</ButtonGroup>
</PopoverFooter>
</PopoverContent>
</Portal>
</>
)}
</Popover>
</Box>
);
};