no more $smType in webapp

This commit is contained in:
ari committed 2022-05-09 22:14:51 -04:00
1 parent 47bf511bbf
commit 021fa2b651
20 files changed
+327 -502

No files matched your search

@@ -84,18 +84,14 @@ Simple.args = {
] ]
}, },
{ {
$smType: "action", alias: "Start Music In Kitchen",
action: "service", service: 'media_player.play_media',
action_data: { target: {
alias: "Start Music In Kitchen", entity_id: "media_player.kitchen_dot"
service: 'media_player.play_media', },
target: { data: {
entity_id: "media_player.kitchen_dot" media_content_id: "Good Morning",
}, media_content_type: "SPOTIFY",
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
} }
} }
] ]
+86 -126
View File
@@ -73,18 +73,14 @@ Simple.args = {
] ]
}, },
{ {
$smType: "action", alias: "Start Music In Kitchen",
action: "service", service: 'media_player.play_media',
action_data: { target: {
alias: "Start Music In Kitchen", entity_id: "media_player.kitchen_dot"
service: 'media_player.play_media', },
target: { data: {
entity_id: "media_player.kitchen_dot" media_content_id: "Good Morning",
}, media_content_type: "SPOTIFY",
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
} }
} }
] ]
@@ -120,128 +116,92 @@ Complex.args = {
] ]
}, },
{ {
"$smType": "action", "alias": "Start Music In Kitchen",
"action": "service", "service": "media_player.play_media",
"action_data": { "target": {
"alias": "Start Music In Kitchen", "entity_id": "media_player.kitchen_dot"
"service": "media_player.play_media", },
"target": { "data": {
"entity_id": "media_player.kitchen_dot" "media_content_id": "Good Morning",
}, "media_content_type": "SPOTIFY"
"data": {
"media_content_id": "Good Morning",
"media_content_type": "SPOTIFY"
}
} }
}, },
{ {
"$smType": "action", "choose": [
"action": "choose", {
"action_data": { "conditions": [
"choose": [ {
{ "condition": "state",
"conditions": [ "entity_id": "lights.bathroom",
{ "state": "off",
"condition": "state", }
"entity_id": "lights.bathroom", ],
"state": "off", "sequence": [
} {
], "service": "light.turn_on",
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_on",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn off bedroom",
"service": "light.turn_off",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
}
]
},
{
"conditions": [
{
"condition": "state",
"entity_id": "lights.bedroom",
"state": "off",
}
],
"sequence": [
{
"$smType": "action",
"action": "service",
"action_data": {
"alias": "Turn on bedroom",
"service": "light.turn_on",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
}
},
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [
{
"conditions": [],
"sequence": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "choose",
"action_data": {
"choose": [],
"default": [],
}
}
],
}
}
]
}
],
"default": [
{
"$smType": "action",
"action": "service",
"action_data": {
"service": "light.turn_off",
"target": { "target": {
"entity_id": "lights.bathroom" "entity_id": "lights.bathroom"
}, },
"data": {} "data": {}
},
{
"alias": "Turn off bedroom",
"service": "light.turn_off",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
} }
} ]
] },
} {
"conditions": [
{
"condition": "state",
"entity_id": "lights.bedroom",
"state": "off",
}
],
"sequence": [
{
"alias": "Turn on bedroom",
"service": "light.turn_on",
"target": {
"entity_id": "lights.bedroom"
},
"data": {}
},
{
"choose": [
{
"conditions": [],
"sequence": [
{
"choose": [],
"default": [],
}
]
}
],
"default": [
{
"choose": [],
"default": [],
}
],
}
]
}
],
"default": [
{
"service": "light.turn_off",
"target": {
"entity_id": "lights.bathroom"
},
"data": {}
}
]
}, },
{ {
"condition": "and", "condition": "and",
@@ -35,8 +35,8 @@ export const sequenceToFlow = (
}; };
} }
// draw node // draw node
if ('$smType' in node && node.$smType === 'action') { if (getNodeType(node) === 'action') {
if (node.action === 'choose') { if ('choose' in node) {
position = addChooseNode(flowData, node, position, nodeId, dims, updater, i) position = addChooseNode(flowData, node, position, nodeId, dims, updater, i)
} else { } else {
addSingleNode(flowData, node, position, nodeId, dims, { addSingleNode(flowData, node, position, nodeId, dims, {
@@ -127,7 +127,7 @@ const addChooseNode = (
}); });
let lastPos: XYPosition = position; let lastPos: XYPosition = position;
// conditions // conditions
node.action_data.choose.forEach(({ sequence, conditions }, j) => { node.choose.forEach(({ sequence, conditions }, j) => {
const sequenceId = `${nodeId}.${j}`; const sequenceId = `${nodeId}.${j}`;
// edit/delete circle // edit/delete circle
const circle = makeFlowCircle(`${sequenceId}>cond`, { const circle = makeFlowCircle(`${sequenceId}>cond`, {
@@ -158,7 +158,7 @@ const addChooseNode = (
lastPos = xyApply(lastPos, { x: lastPos.x, y: lastPos.y + dims.nodeHeight * dims.distanceFactor }, Math.max) lastPos = xyApply(lastPos, { x: lastPos.x, y: lastPos.y + dims.nodeHeight * dims.distanceFactor }, Math.max)
} }
}) })
const totalChildren = node.action_data.choose.length; const totalChildren = node.choose.length;
// add button // add button
const addCirlce = makeFlowCircle( const addCirlce = makeFlowCircle(
@@ -170,16 +170,13 @@ const addChooseNode = (
size: dims.circleSize * dims.distanceFactor, size: dims.circleSize * dims.distanceFactor,
onAdd: () => updater.updateNode(i, { onAdd: () => updater.updateNode(i, {
...node, ...node,
action_data: { choose: [
...node.action_data, ...node.choose,
choose: [ {
...node.action_data.choose, sequence: [],
{ conditions: [],
sequence: [], }
conditions: [], ]
}
]
}
}), }),
disableSource: true, disableSource: true,
} }
@@ -194,7 +191,7 @@ const addChooseNode = (
}, { size: dims.circleSize * dims.distanceFactor }) }, { size: dims.circleSize * dims.distanceFactor })
flowData.nodes.push(elseCircle) flowData.nodes.push(elseCircle)
addEdge(flowData, nodeId, elseCircle.id, true) addEdge(flowData, nodeId, elseCircle.id, true)
const lastPoint = sequenceToFlow(flowData, node.action_data.default, elseCircle.id, { const lastPoint = sequenceToFlow(flowData, node.default, elseCircle.id, {
...dims, ...dims,
padding: { padding: {
x: position.x - dims.nodeWidth, x: position.x - dims.nodeWidth,
+19 -27
View File
@@ -27,44 +27,36 @@ const mockSequenceUpdater = (defaultState: AutomationSequenceNode[] = []) => {
test("sequence updater updates nodes", () => { test("sequence updater updates nodes", () => {
const mock = mockSequenceUpdater([ const mock = mockSequenceUpdater([
{ {
"$smType": "action", "choose": [
"action": "choose", {
"action_data": { "conditions": [],
"choose": [ "sequence": [],
{ }
"conditions": [], ],
"sequence": [], "default": [],
}
],
"default": [],
}
} }
]); ]);
expect(mock.state.length).toBe(1) expect(mock.state.length).toBe(1)
expect((mock.state[0] as ChooseAction).action_data.alias).toBe(undefined) expect((mock.state[0] as ChooseAction).alias).toBe(undefined)
mock.updater.updateNode(0, { mock.updater.updateNode(0, {
...mock.state[0], ...mock.state[0],
action_data: { action_data: {
...(mock.state[0] as ChooseAction).action_data, ...(mock.state[0] as ChooseAction),
alias: "Hello" alias: "Hello"
} }
} as any) } as any)
expect((mock.state[0] as ChooseAction).action_data.alias).toBe("Hello") expect((mock.state[0] as ChooseAction).alias).toBe("Hello")
}) })
test('update conditions for node', () => { test('update conditions for node', () => {
const mock = mockSequenceUpdater([ const mock = mockSequenceUpdater([
{ {
"$smType": "action", "choose": [
"action": "choose", {
"action_data": { "conditions": [],
"choose": [ "sequence": [],
{ }
"conditions": [], ],
"sequence": [], "default": [],
}
],
"default": [],
}
} }
]); ]);
mock.updater.makeOnEditConditionsForChooseNode(0, 0)(); mock.updater.makeOnEditConditionsForChooseNode(0, 0)();
@@ -77,6 +69,6 @@ test('update conditions for node', () => {
"conditions": [], "conditions": [],
} }
] as any) ] as any)
expect((mock.state[0] as ChooseAction).action_data.choose[0].conditions.length).toBe(1) expect((mock.state[0] as ChooseAction).choose[0].conditions.length).toBe(1)
expect((mock.state[0] as ChooseAction).action_data.choose[0].conditions[0].condition).toBe("and") expect((mock.state[0] as ChooseAction).choose[0].conditions[0].condition).toBe("and")
}) })
+29 -45
View File
@@ -23,12 +23,8 @@ export const makeSequenceUpdater = (
single: true, single: true,
saveBtnCreateText: true, saveBtnCreateText: true,
node: { node: {
$smType: 'action', choose: [],
action: 'choose', default: [],
action_data: {
choose: [],
default: [],
}
}, },
update: n => onChange([ update: n => onChange([
...sequence, ...sequence,
@@ -44,44 +40,38 @@ export const makeSequenceUpdater = (
...sequence.slice(i + 1), ...sequence.slice(i + 1),
]) ])
}, },
updateChooseActionData(i: number, data: ChooseAction['action_data']) { updateChooseActionData(i: number, data: ChooseAction) {
const node = sequence[i] as ChooseAction; const node = sequence[i] as ChooseAction;
return this.updateNode(i, { return this.updateNode(i, {
...node, ...node,
action_data: data, ...data,
}) })
}, },
makeChildUpdaterForChooseAction(i: number, j: number | null) { makeChildUpdaterForChooseAction(i: number, j: number | null) {
const node = sequence[i]; const node = sequence[i];
if (('$smType' in node) && (node.$smType === 'action') && (node.action === 'choose')) { if ('choose' in node) {
if (j !== null) { if (j !== null) {
return makeSequenceUpdater( return makeSequenceUpdater(
node.action_data.choose[j].sequence, node.choose[j].sequence,
seq => this.updateNode(i, { seq => this.updateNode(i, {
...node, ...node,
action_data: { choose: [
...node.action_data, ...node.choose.slice(0, j),
choose: [ {
...node.action_data.choose.slice(0, j), ...node.choose[j],
{ sequence: seq,
...node.action_data.choose[j], },
sequence: seq, ...node.choose.slice(j + 1),
}, ]
...node.action_data.choose.slice(j + 1),
]
}
}), }),
openModal, openModal,
) )
} else { } else {
return makeSequenceUpdater( return makeSequenceUpdater(
node.action_data.default, node.default,
seq => this.updateNode(i, { seq => this.updateNode(i, {
...node, ...node,
action_data: { default: seq
...node.action_data,
default: seq
}
}), }),
openModal, openModal,
) )
@@ -108,21 +98,18 @@ export const makeSequenceUpdater = (
const node = sequence[i] as ChooseAction; const node = sequence[i] as ChooseAction;
return openModal({ return openModal({
single: false, single: false,
node: node.action_data.choose[j].conditions, node: node.choose[j].conditions,
allowedTypes: ['condition'], allowedTypes: ['condition'],
update: conditions => this.updateNode(i, { update: conditions => this.updateNode(i, {
...node, ...node,
action_data: { choose: [
...node.action_data, ...node.choose.slice(0, j),
choose: [ {
...node.action_data.choose.slice(0, j), sequence: node.choose[j].sequence,
{ conditions: conditions as AutomationCondition[],
sequence: node.action_data.choose[j].sequence, },
conditions: conditions as AutomationCondition[], ...node.choose.slice(j + 1),
}, ]
...node.action_data.choose.slice(j + 1),
]
}
}), }),
}) })
} }
@@ -136,11 +123,8 @@ export const createOnRemoveForChooseNode = (
j: number j: number
) => () => update({ ) => () => update({
...action, ...action,
action_data: { choose: [
...action.action_data, ...action.choose.slice(0, j),
choose: [ ...action.choose.slice(j + 1),
...action.action_data.choose.slice(0, j), ]
...action.action_data.choose.slice(j + 1),
]
}
}) })
@@ -9,13 +9,9 @@ const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => {
switch (nodeType) { switch (nodeType) {
case 'action': case 'action':
return { return {
$smType: 'action', 'data': {},
action: "service", 'service': '',
action_data: { 'target': {},
'data': {},
'service': '',
'target': {},
}
} }
case 'condition': case 'condition':
return { return {
@@ -5,15 +5,11 @@ import { OptionManager, updateActionData } from './OptionManager';
export const ActionChooseState: OptionManager<ChooseAction> = { export const ActionChooseState: OptionManager<ChooseAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: 'action', alias: "",
action: 'choose', default: [],
action_data: { choose: [],
alias: "Choose",
default: [],
choose: [],
}
}), }),
isReady: ({ action_data: { alias } }) => { isReady: ({ alias }) => {
return alias !== '' return alias !== ''
}, },
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
@@ -21,7 +17,7 @@ export const ActionChooseState: OptionManager<ChooseAction> = {
return <> return <>
<InputText <InputText
label="Description" label="Description"
value={state.action_data.alias ?? ""} value={state.alias ?? ""}
onChange={alias => update({ alias })} onChange={alias => update({ alias })}
/> />
</> </>
@@ -5,24 +5,18 @@ import { OptionManager, updateActionData } from './OptionManager';
export const ActionDeviceState: OptionManager<DeviceAction> = { export const ActionDeviceState: OptionManager<DeviceAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: 'action', alias: "",
action: 'device', type: "",
action_data: { entity_id: "",
alias: "Device", device_id: "",
type: "", domain: "",
entity_id: "",
device_id: "",
domain: "",
}
}), }),
isReady: ({ isReady: ({
action_data: { alias,
alias, type,
type, entity_id,
entity_id, device_id,
device_id, domain,
domain,
}
}) => ( }) => (
alias !== '' && alias !== '' &&
type !== "" && type !== "" &&
@@ -35,25 +29,25 @@ export const ActionDeviceState: OptionManager<DeviceAction> = {
return <> return <>
<InputText <InputText
label="Description" label="Description"
value={state.action_data.alias ?? ""} value={state.alias ?? ""}
onChange={alias => update({ alias })} onChange={alias => update({ alias })}
/> />
<InputText <InputText
textBoxFor="device_id" textBoxFor="device_id"
label="Device" label="Device"
value={state.action_data.device_id} value={state.device_id}
onChange={device_id => update({ device_id })} onChange={device_id => update({ device_id })}
/> />
<InputText <InputText
textBoxFor="type" textBoxFor="type"
label="Action" label="Action"
value={state.action_data.type} value={state.type}
onChange={type => update({ type })} onChange={type => update({ type })}
/> />
<InputText <InputText
textBoxFor="entity_id" textBoxFor="entity_id"
label="Entity ID" label="Entity ID"
value={state.action_data.entity_id ?? ""} value={state.entity_id ?? ""}
onChange={entity_id => update({ entity_id, domain: entity_id.split('.')[0] })} onChange={entity_id => update({ entity_id, domain: entity_id.split('.')[0] })}
/> />
</> </>
@@ -6,15 +6,11 @@ import { OptionManager, updateActionData } from "./OptionManager";
export const ActionEventState: OptionManager<FireEventAction> = { export const ActionEventState: OptionManager<FireEventAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: "action", alias: "Fire Event",
action: 'event', event: "",
action_data: { event_data: {},
alias: "Fire Event",
event: "",
event_data: {},
}
}), }),
isReady: ({ action_data: { alias, event } }) => ( isReady: ({ alias, event }) => (
alias !== '' && alias !== '' &&
event !== "" event !== ""
), ),
@@ -23,18 +19,18 @@ export const ActionEventState: OptionManager<FireEventAction> = {
return <> return <>
<InputText <InputText
label="Description" label="Description"
value={state.action_data.alias ?? ""} value={state.alias ?? ""}
onChange={alias => update({ alias })} onChange={alias => update({ alias })}
/> />
<InputText <InputText
textBoxFor="event" textBoxFor="event"
label="Event" label="Event"
value={state.action_data.event} value={state.event}
onChange={event => update({ event })} onChange={event => update({ event })}
/> />
<InputYaml <InputYaml
label="Event Data" label="Event Data"
value={state.action_data.event_data} value={state.event_data}
onChange={event_data => update({ event_data })} onChange={event_data => update({ event_data })}
/> />
</> </>
@@ -7,20 +7,16 @@ import { OptionManager, updateActionData } from './OptionManager';
export const ActionRepeatState: OptionManager<RepeatAction> = { export const ActionRepeatState: OptionManager<RepeatAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: 'action', alias: "Repeat",
action: 'repeat', repeat: {
action_data: { count: 1,
alias: "Repeat", sequence: [],
repeat: {
count: 1,
sequence: [],
}
} }
}), }),
isReady: ({ action_data: { isReady: ({
alias, alias,
repeat, repeat,
} }) => ( }) => (
alias !== '' && alias !== '' &&
repeat?.sequence.length > 0 repeat?.sequence.length > 0
), ),
@@ -29,18 +25,18 @@ export const ActionRepeatState: OptionManager<RepeatAction> = {
return <> return <>
<InputText <InputText
label="Description" label="Description"
value={state.action_data.alias ?? ""} value={state.alias ?? ""}
onChange={alias => update({ alias })} onChange={alias => update({ alias })}
/> />
<InputNumber <InputNumber
label="How many times?" label="How many times?"
value={state.action_data.repeat.count} value={state.repeat.count}
onChange={(count = 1) => update({ repeat: { ...state.action_data.repeat, count } })} onChange={(count = 1) => update({ repeat: { ...state.repeat, count } })}
/> />
<InputYaml <InputYaml
label="Sequence" label="Sequence"
value={state.action_data.repeat.sequence ?? []} value={state.repeat.sequence ?? []}
onChange={sequence => update({ repeat: { ...state.action_data.repeat, sequence } })} onChange={sequence => update({ repeat: { ...state.repeat, sequence } })}
/> />
</> </>
} }
@@ -6,23 +6,19 @@ import { OptionManager, updateActionData } from './OptionManager';
export const ActionCallServiceState: OptionManager<ServiceAction> = { export const ActionCallServiceState: OptionManager<ServiceAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: 'action', service: "",
action: 'service', target: "",
action_data: { data: {},
service: "",
target: "",
data: {},
}
}), }),
isReady: ({ isReady: ({
action_data: { service, alias, target } service, alias, target
}) => ( }) => (
service !== '' && service !== '' &&
alias !== '' && alias !== '' &&
target !== '' target !== ''
), ),
renderOptionList: (state, setState) => { renderOptionList: (state, setState) => {
const { service, alias = "", target } = state.action_data; const { service, alias = "", target } = state;
const update = updateActionData(state, setState); const update = updateActionData(state, setState);
return <> return <>
<InputText <InputText
@@ -6,17 +6,13 @@ import { OptionManager, updateActionData } from './OptionManager';
export const ActionWaitState: OptionManager<WaitAction> = { export const ActionWaitState: OptionManager<WaitAction> = {
defaultState: () => ({ defaultState: () => ({
$smType: 'action', alias: "Wait",
action: 'wait', wait_template: "",
action_data: { // timeout: 0,
alias: "Wait", continue_on_timeout: false,
wait_template: "",
// timeout: 0,
continue_on_timeout: false,
}
}), }),
isReady: ({ isReady: ({
action_data: { alias, wait_template } alias, wait_template
}) => ( }) => (
alias !== '' && alias !== '' &&
wait_template !== "" wait_template !== ""
@@ -26,23 +22,23 @@ export const ActionWaitState: OptionManager<WaitAction> = {
return <> return <>
<InputText <InputText
label="Description" label="Description"
value={state.action_data.alias ?? ""} value={state.alias ?? ""}
onChange={alias => update({ alias })} onChange={alias => update({ alias })}
/> />
<InputText <InputText
textBoxFor="template" textBoxFor="template"
label="Template" label="Template"
value={state.action_data.wait_template} value={state.wait_template}
onChange={wait_template => update({ wait_template })} onChange={wait_template => update({ wait_template })}
/> />
{/* <InputNumber {/* <InputNumber
label="Timeout" label="Timeout"
value={state.action_data.timeout ?? 0} value={state.timeout ?? 0}
onChange={(timeout = 0) => update({ timeout })} onChange={(timeout = 0) => update({ timeout })}
/> */} /> */}
<InputBoolean <InputBoolean
label="Continue on Timeout" label="Continue on Timeout"
value={state.action_data.continue_on_timeout ?? false} value={state.continue_on_timeout ?? false}
onChange={continue_on_timeout => update({ continue_on_timeout })} onChange={continue_on_timeout => update({ continue_on_timeout })}
/> />
</> </>
@@ -21,11 +21,8 @@ export const updateActionData = <T extends AutomationAction>(
state: T, state: T,
setState: (s: T) => void setState: (s: T) => void
) => ( ) => (
data: Partial<T['action_data']>, data: Partial<T>,
) => setState({ ) => setState({
...state, ...state,
action_data: { ...data,
...state.action_data,
...data,
},
}) })
@@ -3,9 +3,7 @@ import { AutomationNode, AutomationNodeTypes } from 'types/automations';
import { AutomationNodeSubtype } from 'types/automations'; import { AutomationNodeSubtype } from 'types/automations';
import { getOptionManager } from './getOptionManager'; import { getOptionManager } from './getOptionManager';
import { getNodeType, getSubTypeList } from 'utils/automations'; import { getNodeType, getSubTypeList } from 'utils/automations';
import { AutomationCondition } from 'types/automations/conditions'; import { getNodeSubType } from '../constants';
import { AutomationAction } from 'types/automations/actions';
import { AutomationTrigger } from 'types/automations/triggers';
export const useEditorNodeState = (node: AutomationNode) => { export const useEditorNodeState = (node: AutomationNode) => {
@@ -18,11 +16,9 @@ export const useEditorNodeState = (node: AutomationNode) => {
}, [node]) }, [node])
const setState = (node: AutomationNode) => setAllState(({ node, isModified: true })); const setState = (node: AutomationNode) => setAllState(({ node, isModified: true }));
const originalNodeType = getNodeType(node); const originalNodeType = getNodeType(node);
const originalNodeSubType = getNodeSubType(node);
const nodeType = getNodeType(state); const nodeType = getNodeType(state);
const subType: AutomationNodeSubtype = const subType = getNodeSubType(state);
nodeType === 'action' ? (state as AutomationAction).action :
nodeType === 'condition' ? (state as AutomationCondition).condition :
(state as AutomationTrigger).platform;
const subTypes = getSubTypeList(nodeType) const subTypes = getSubTypeList(nodeType)
const optionManager = getOptionManager(nodeType, subType as any); const optionManager = getOptionManager(nodeType, subType as any);
return { return {
@@ -43,50 +39,16 @@ export const useEditorNodeState = (node: AutomationNode) => {
}, },
setNodeType(newType: AutomationNodeTypes) { setNodeType(newType: AutomationNodeTypes) {
if (newType === originalNodeType) { if (newType === originalNodeType) {
if (originalNodeType === 'action') { setState(node)
setState({
...state,
$smType: 'action',
action: (node as any).action,
} as any)
} else if (originalNodeType === 'condition') {
setState({
...state,
condition: (node as any).condition
} as any)
} else {
setState({
...state,
platform: (node as any).platform
} as any)
}
} else { } else {
setState({ setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState())
...state,
$smType: newType === 'trigger' ? undefined : newType,
...getOptionManager(newType, getSubTypeList(newType)[0]).defaultState()
} as any)
} }
}, },
setSubType(newSubType: AutomationNodeSubtype<typeof nodeType>) { setSubType(newSubType: AutomationNodeSubtype<typeof nodeType>) {
if (nodeType === 'action') { if (newSubType === originalNodeSubType) {
setState({ setState(node)
...state,
action: newSubType,
...getOptionManager(nodeType, newSubType as any).defaultState()
} as any)
} else if (nodeType === 'condition') {
setState({
...state,
condition: newSubType,
...getOptionManager(nodeType, newSubType as any).defaultState()
} as any)
} else { } else {
setState({ setState(getOptionManager(nodeType, newSubType as any).defaultState())
...state,
platform: newSubType,
...getOptionManager(nodeType, newSubType as any).defaultState()
} as any)
} }
} }
} }
+14 -3
View File
@@ -1,4 +1,5 @@
import { AutomationNodeSubtype, AutomationNodeTypes } from "types/automations"; import { AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
import { ActionType } from "types/automations/actions";
import { AutomationNode } from '../../types/automations/index'; import { AutomationNode } from '../../types/automations/index';
@@ -54,12 +55,22 @@ export const getSubTypeList = <T extends AutomationNodeTypes>(
export const getNodeSubType = <T extends AutomationNodeTypes>( export const getNodeSubType = <T extends AutomationNodeTypes>(
node: AutomationNode<T> node: AutomationNode<T>
): AutomationNodeSubtype<T> => { ): AutomationNodeSubtype<T> => {
if ('$smType' in node && node.$smType === 'action') { if ('condition' in node) {
return node.action as any;
} else if ('condition' in node) {
return node.condition as any; return node.condition as any;
} else if ('platform' in node) { } else if ('platform' in node) {
return node.platform as any; return node.platform as any;
} else if ('service' in node) {
return 'service' as any
} else if ('repeat' in node) {
return 'repeat' as any
} else if ('wait_template' in node) {
return 'wait' as any
} else if ('event' in node) {
return 'event' as any
} else if ('device_id' in node) {
return 'device' as any
} else if ('choose' in node) {
return 'choose' as any
} else { } else {
throw new Error("Invalid node type!") throw new Error("Invalid node type!")
} }
@@ -14,13 +14,9 @@ export default {
parameters: { actions: { argTypesRegex: '^on.*' } }, parameters: { actions: { argTypesRegex: '^on.*' } },
args: { args: {
node: { node: {
$smType: 'action', 'data': {},
action: 'service', 'service': '',
action_data: { 'target': '',
'data': {},
'service': '',
'target': '',
}
} }
} }
} as ComponentMeta<typeof NodeEditor> } as ComponentMeta<typeof NodeEditor>
+25 -22
View File
@@ -2,54 +2,57 @@ import { AutomationSequenceNode } from ".";
import { AutomationTime } from "./common"; import { AutomationTime } from "./common";
import { AutomationCondition } from "./conditions"; import { AutomationCondition } from "./conditions";
interface AutomationActionNodeBase<Name extends String,Data extends Object> { type AutomationActionNodeBase<Data extends Object> = Data & {
$smType: 'action'; alias?: string;
action: Name; variables?: Record<string, any>;
action_data: Data & {
alias?: string;
variables?: Record<string, any>;
};
} }
export interface ServiceAction extends AutomationActionNodeBase<"service", { export type ServiceAction = AutomationActionNodeBase<{
service: string; service: string;
target: any; target: any;
data: any; data: any;
}>{} }>
export interface RepeatAction extends AutomationActionNodeBase<"repeat", { export type RepeatAction = AutomationActionNodeBase<{
repeat: { repeat: {
count: number; count: number;
sequence: AutomationAction[]; sequence: AutomationAction[];
} }
}>{} }>
export interface WaitAction extends AutomationActionNodeBase<"wait", { export type WaitAction = AutomationActionNodeBase<{
wait_template: string; wait_template: string;
timeout?: AutomationTime; timeout?: AutomationTime;
continue_on_timeout?: boolean; continue_on_timeout?: boolean;
}>{} }>
export interface FireEventAction extends AutomationActionNodeBase<"event", { export type FireEventAction = AutomationActionNodeBase<{
event: string; event: string;
event_data: any; event_data: any;
}>{} }>
export interface DeviceAction extends AutomationActionNodeBase<"device", { export type DeviceAction = AutomationActionNodeBase<{
type: string; type: string;
device_id: string; device_id: string;
entity_id?: string; entity_id?: string;
domain: string; domain: string;
}>{} }>
export interface ChooseAction extends AutomationActionNodeBase<"choose", { export type ChooseAction = AutomationActionNodeBase<{
choose: Array<{ choose: Array<{
conditions: AutomationCondition[]; conditions: AutomationCondition[];
sequence: AutomationSequenceNode[]; sequence: AutomationSequenceNode[];
}>; }>;
default: AutomationSequenceNode[]; default: AutomationSequenceNode[];
}>{} }>
export type AutomationAction = export type AutomationAction =
| ServiceAction | ServiceAction
| RepeatAction | RepeatAction
| WaitAction | WaitAction
| FireEventAction | FireEventAction
| DeviceAction | DeviceAction
| ChooseAction | ChooseAction
; ;
export type ActionType = AutomationAction['action']; export type ActionType =
| 'service'
| 'repeat'
| 'wait'
| 'event'
| 'device'
| 'choose'
;
+29 -63
View File
@@ -10,18 +10,14 @@ test('converting time to a string', () => {
test('using alias as description', () => { test('using alias as description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: "action", alias: "Start Music In Kitchen",
action: "service", service: 'media_player.play_media',
action_data: { target: {
alias: "Start Music In Kitchen", entity_id: "media_player.kitchen_dot"
service: 'media_player.play_media', },
target: { data: {
entity_id: "media_player.kitchen_dot" media_content_id: "Good Morning",
}, media_content_type: "SPOTIFY",
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
} }
})).toEqual("Start Music In Kitchen") })).toEqual("Start Music In Kitchen")
}) })
@@ -29,30 +25,22 @@ test('using alias as description', () => {
test('get service action description', () => { test('get service action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: "action", service: 'media_player.play_media',
action: "service", target: {
action_data: { entity_id: "media_player.kitchen_dot"
service: 'media_player.play_media', },
target: { data: {
entity_id: "media_player.kitchen_dot" media_content_id: "Good Morning",
}, media_content_type: "SPOTIFY",
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
} }
})).toEqual("media_player.play_media") })).toEqual("media_player.play_media")
}) })
test('get repeat action description', () => { test('get repeat action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: "action", repeat: {
action: "repeat", count: 10,
action_data: { sequence: []
repeat: {
count: 10,
sequence: []
}
} }
})).toEqual("Repeat 10") })).toEqual("Repeat 10")
}) })
@@ -60,57 +48,35 @@ test('get repeat action description', () => {
test('get wait action description', () => { test('get wait action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: "action", wait_template: "states(switch.kitchen_light) == 'on'"
action: "wait",
action_data: {
wait_template: "states(switch.kitchen_light) == 'on'"
}
})).toEqual("Wait on states(switch.kitchen_light) == 'on'") })).toEqual("Wait on states(switch.kitchen_light) == 'on'")
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: "action", wait_template: "states(switch.kitchen_light) == 'on'",
action: "wait", timeout: {
action_data: { 'minutes': 1,
wait_template: "states(switch.kitchen_light) == 'on'",
// timeout: '00:01:00',
timeout: {
'minutes': 1,
}
} }
})).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00") })).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00")
}) })
test('get fire event action description', () => { test('get fire event action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: 'action', event: 'test_event',
action: 'event', event_data: {},
action_data: {
event: 'test_event',
event_data: {},
}
})).toEqual("Trigger test_event") })).toEqual("Trigger test_event")
}) })
test('get device action description', () => { test('get device action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: 'action', device_id: "12310das01231",
action: 'device', domain: "zwave_js",
action_data: { type: "set_value"
device_id: "12310das01231",
domain: "zwave_js",
type: "set_value"
}
})).toEqual("set_value on 12310das01231") })).toEqual("set_value on 12310das01231")
}) })
test('get choose action description', () => { test('get choose action description', () => {
expect(getDescriptionFromAutomationNode({ expect(getDescriptionFromAutomationNode({
$smType: 'action', choose: [],
action: 'choose', default: [],
action_data: {
choose: [],
default: [],
}
})).toEqual("Choose") })).toEqual("Choose")
}) })
+30 -35
View File
@@ -10,36 +10,13 @@ export const convertTimeToString = ({
}: AutomationTime) => [hours, minutes, seconds, milliseconds].map(n => String(n).padStart(2, '0')).join(':') }: AutomationTime) => [hours, minutes, seconds, milliseconds].map(n => String(n).padStart(2, '0')).join(':')
export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(node: AutomationNode<N>): string => { export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(node: AutomationNode<N>): string => {
if ('$smType' in node) { if (node.alias) {
switch (node['$smType']) { return node.alias;
case "action": }
if (node.action_data.alias) { if ('platform' in node) {
return node.action_data.alias; return node.platform
} }
switch (node.action) { if ('condition' in node) {
case 'service':
return node.action_data.service
case 'repeat':
return 'Repeat ' + node.action_data.repeat.count;
case 'wait':
let out = 'Wait on ' + node.action_data.wait_template;
if (node.action_data.timeout) {
out += (' for ' + convertTimeToString(node.action_data.timeout))
}
return out;
case 'event':
return `Trigger ${node.action_data.event}`
case 'device':
return `${node.action_data.type} on ${node.action_data.device_id}`
case 'choose':
return "Choose"
}
}
return 'n/a'
} else if ('condition' in node) {
if (node.alias) {
return node.alias;
}
if ( if (
(node.condition === 'and') || (node.condition === 'and') ||
(node.condition === 'or') || (node.condition === 'or') ||
@@ -71,12 +48,30 @@ export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(
return 'n/a' return 'n/a'
} }
} }
} else {
if (node.alias) {
return node.alias;
}
return node.platform
} }
if ('service' in node) {
return node.service
}
if ('repeat' in node) {
return 'Repeat ' + node.repeat.count
}
if ('wait_template' in node) {
let out = 'Wait on ' + node.wait_template;
if (node.timeout) {
out += (' for ' + convertTimeToString(node.timeout))
}
return out;
}
if ('event' in node) {
return `Trigger ${node.event}`
}
if ('device_id' in node) {
return `${node.type} on ${node.device_id}`
}
if ('choose' in node) {
return "Choose"
}
return 'n/a'
} }
export const prettyEntityId = (entityId: string | string[]) => { export const prettyEntityId = (entityId: string | string[]) => {
+8 -12
View File
@@ -38,18 +38,14 @@ export const createMockAuto = (tags: Record<string, string> = {}): AutomationDat
] ]
}, },
{ {
$smType: "action", alias: "Start Music In Kitchen",
action: "service", service: 'media_player.play_media',
action_data: { target: {
alias: "Start Music In Kitchen", entity_id: "media_player.kitchen_dot"
service: 'media_player.play_media', },
target: { data: {
entity_id: "media_player.kitchen_dot" media_content_id: "Good Morning",
}, media_content_type: "SPOTIFY",
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
} }
} }
] ]