forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
action_list.tsx
77 lines (64 loc) · 2.36 KB
/
action_list.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React, { FC, useEffect, useState } from 'react';
import { EuiSelectable, EuiSelectableOption } from '@elastic/eui';
import addons from '@storybook/addons';
import uuid from 'uuid/v4';
import { EVENTS } from '../constants';
import { RecordedAction, RecordedPayload } from '../types';
export const ActionList: FC<{
onSelect: (action: RecordedAction | null) => void;
}> = ({ onSelect }) => {
const [recordedActions, setRecordedActions] = useState<Record<string, RecordedAction>>({});
const [selectedAction, setSelectedAction] = useState<RecordedAction | null>(null);
useEffect(() => {
onSelect(selectedAction);
}, [onSelect, selectedAction]);
useEffect(() => {
const actionListener = (newAction: RecordedPayload) => {
const id = uuid();
setRecordedActions({ ...recordedActions, [id]: { ...newAction, id } });
};
const resetListener = () => {
setSelectedAction(null);
setRecordedActions({});
};
const channel = addons.getChannel();
channel.addListener(EVENTS.ACTION, actionListener);
channel.addListener(EVENTS.RESET, resetListener);
return () => {
channel.removeListener(EVENTS.ACTION, actionListener);
channel.removeListener(EVENTS.RESET, resetListener);
};
});
useEffect(() => {
const values = Object.values(recordedActions);
if (values.length > 0) {
setSelectedAction(values[values.length - 1]);
}
}, [recordedActions]);
const options: EuiSelectableOption[] = Object.values(recordedActions).map((recordedAction) => ({
key: recordedAction.id,
label: recordedAction.action.type,
checked: recordedAction.id === selectedAction?.id ? 'on' : undefined,
}));
const onChange: (selectedOptions: EuiSelectableOption[]) => void = (selectedOptions) => {
selectedOptions.forEach((option) => {
if (option && option.checked && option.key) {
const selected = recordedActions[option.key];
if (selected) {
setSelectedAction(selected);
}
}
});
};
return (
<EuiSelectable singleSelection={true} {...{ onChange, options }}>
{(list) => list}
</EuiSelectable>
);
};