cleaned up styling for editor
This commit is contained in:
1 parent
bfc95db6f6
commit
4cfc429980
25 files changed
+532
-230
No files matched your search
@@ -18,7 +18,6 @@ export const useAutomatioEditorState = (
|
||||
const [state, update] = useState<EditorState>({
|
||||
status: "loading",
|
||||
});
|
||||
|
||||
const makeUpdate = <K extends keyof EditorData, D extends EditorData[K]>(name: K) => (
|
||||
data: D
|
||||
) => state.status !== 'loading' && update({
|
||||
|
||||
@@ -10,16 +10,7 @@ export default {
|
||||
component: AutomationList,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {
|
||||
dims: {
|
||||
nodeHeight: dgconst.NODE_HEIGHT,
|
||||
nodeWidth: dgconst.NODE_WIDTH,
|
||||
distanceFactor: dgconst.DISTANCE_FACTOR,
|
||||
circleSize: dgconst.CIRCLE_SIZE,
|
||||
padding: {
|
||||
x: dgconst.PADDING,
|
||||
y: dgconst.PADDING,
|
||||
},
|
||||
}
|
||||
dims: dgconst.DEFAULT_DIMS
|
||||
}
|
||||
} as ComponentMeta<typeof AutomationList>;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createMockAuto } from 'utils/mocks';
|
||||
test('group automations', () => {
|
||||
const automations: AutomationData[] = [
|
||||
{
|
||||
condition: [],
|
||||
metadata: {
|
||||
id: '1',
|
||||
alias: '',
|
||||
@@ -19,6 +20,7 @@ test('group automations', () => {
|
||||
trigger: [],
|
||||
},
|
||||
{
|
||||
condition: [],
|
||||
metadata: {
|
||||
id: '2',
|
||||
alias: '',
|
||||
@@ -33,6 +35,7 @@ test('group automations', () => {
|
||||
trigger: [],
|
||||
},
|
||||
{
|
||||
condition: [],
|
||||
metadata: {
|
||||
id: '3',
|
||||
alias: '',
|
||||
|
||||
@@ -2,23 +2,14 @@ import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { ConnectedAutomationList } from ".";
|
||||
import { createMockAuto } from "utils/mocks";
|
||||
import { useMockApiService } from "apiService";
|
||||
import * as dgconst from 'components/DAGSvgs/constants';
|
||||
import { DEFAULT_DIMS } from 'components/DAGSvgs/constants';
|
||||
|
||||
export default {
|
||||
title: 'App/AutomationList/Connected',
|
||||
component: ConnectedAutomationList,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {
|
||||
dims: {
|
||||
nodeHeight: dgconst.NODE_HEIGHT,
|
||||
nodeWidth: dgconst.NODE_WIDTH,
|
||||
distanceFactor: dgconst.DISTANCE_FACTOR,
|
||||
circleSize: dgconst.CIRCLE_SIZE,
|
||||
padding: {
|
||||
x: dgconst.PADDING,
|
||||
y: dgconst.PADDING,
|
||||
},
|
||||
},
|
||||
dims: DEFAULT_DIMS,
|
||||
initialAutomations: [],
|
||||
}
|
||||
} as ComponentMeta<typeof ConnectedAutomationList>;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
.input-boolean {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
max-width: fit-content;
|
||||
border: 1px solid var(--secondary-accent);
|
||||
border-radius: 5px;
|
||||
padding: 0.5em;
|
||||
background-color: var(--secondary);
|
||||
}
|
||||
|
||||
.input-boolean:hover, .input-boolean:hover * {
|
||||
cursor: pointer;
|
||||
background-color: var(--secondary-opaque);
|
||||
}
|
||||
|
||||
.input-boolean * {
|
||||
user-select: none;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { useState } from "react";
|
||||
|
||||
import InputBoolean from "./InputBoolean";
|
||||
|
||||
export default {
|
||||
title: 'Inputs/InputBoolean',
|
||||
component: InputBoolean,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
} as ComponentMeta<typeof InputBoolean>;
|
||||
|
||||
|
||||
const Template: ComponentStory<typeof InputBoolean> = args => {
|
||||
const [state, onChange] = useState(args.value)
|
||||
return <div className="page">
|
||||
<InputBoolean {...args} value={state} onChange={v => {
|
||||
args.onChange(v)
|
||||
onChange(v)
|
||||
}} />
|
||||
</div>
|
||||
}
|
||||
|
||||
export const SimpleText = Template.bind({})
|
||||
SimpleText.args = {
|
||||
label: "Template",
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import "./InputBoolean.css";
|
||||
import InputWrapper from "./InputWrapper";
|
||||
|
||||
export interface Props {
|
||||
@@ -10,12 +11,8 @@ export default function InputBoolean({
|
||||
value = false,
|
||||
onChange,
|
||||
}: Props) {
|
||||
return <InputWrapper label={label}>
|
||||
<span className="checkbox" onClick={e => {
|
||||
e.preventDefault()
|
||||
onChange(!value)
|
||||
}}>
|
||||
{value ? '✔️' : ' '}
|
||||
</span>
|
||||
</InputWrapper>
|
||||
return <div className="input-boolean" onClick={() => onChange(!value)}>
|
||||
<input type="checkbox" checked={value} onChange={() => { }} />
|
||||
<label>{label}</label>
|
||||
</div>
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ComponentMeta, ComponentStory } from "@storybook/react";
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
import { InputList } from "./InputList";
|
||||
|
||||
@@ -12,7 +12,12 @@ export default {
|
||||
|
||||
const Template: ComponentStory<typeof InputList> = args => {
|
||||
|
||||
const [value, setValue] = useState('')
|
||||
const [value, setValue] = useState(args.current);
|
||||
useEffect(() => {
|
||||
if (value !== args.current) {
|
||||
setValue(args.current)
|
||||
}
|
||||
}, [args.current])
|
||||
return <div className="page">
|
||||
<InputList {...args} current={value} onChange={setValue} />
|
||||
</div>
|
||||
@@ -27,3 +32,15 @@ SimpleText.args = {
|
||||
"Toots"
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
export const InvalidSelection = Template.bind({})
|
||||
InvalidSelection.args = {
|
||||
current: "Derek",
|
||||
label: "Entity ID",
|
||||
options: [
|
||||
'Bob',
|
||||
'Martin',
|
||||
"Toots"
|
||||
]
|
||||
}
|
||||
@@ -15,17 +15,33 @@ export const InputList: FC<Props<any>> = ({
|
||||
current, options, onChange, label,
|
||||
...selattr
|
||||
}) => {
|
||||
const { classes } = useInputListStyles({});
|
||||
return <InputWrapper label={label} labelSize={'small'} noMargin>
|
||||
const invalidCurrent = !options.includes(current);
|
||||
const { classes } = useInputListStyles({
|
||||
invalidCurrent
|
||||
});
|
||||
return <InputWrapper label={label} labelSize={'small'} noMargin error={invalidCurrent && "Invalid Selection"}>
|
||||
<select
|
||||
title={invalidCurrent ? "Invalid Selection" : ""}
|
||||
className={classes.input}
|
||||
{...selattr} value={current}
|
||||
onChange={e => {
|
||||
e.preventDefault();
|
||||
onChange(e.currentTarget.value as any);
|
||||
console.log(e.currentTarget.id)
|
||||
console.log(e.currentTarget.value)
|
||||
console.log(e.currentTarget.innerHTML)
|
||||
if (e.currentTarget.id === 'invalid') {
|
||||
onChange(options[0])
|
||||
} else {
|
||||
onChange(e.currentTarget.value as any);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{options.map((t, i) => <option id={String(i)} key={i}>{t}</option>)}
|
||||
{options.map((t, i) => <option id={String(i)} key={i} value={t}>{t}</option>)}
|
||||
{invalidCurrent ? <option
|
||||
id={'invalid'}
|
||||
value={current}
|
||||
style={{ display: 'none' }}
|
||||
>!{current}!</option> : <></>}
|
||||
</select>
|
||||
</InputWrapper>
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface Props {
|
||||
value: string;
|
||||
onChange: (v: string) => void;
|
||||
additionalTooltipFilters?: Record<string, string>;
|
||||
error?: string;
|
||||
resizable?: boolean;
|
||||
}
|
||||
export default function InputTextArea({
|
||||
@@ -16,13 +17,14 @@ export default function InputTextArea({
|
||||
textBoxFor,
|
||||
value = "",
|
||||
onChange,
|
||||
error,
|
||||
additionalTooltipFilters = {},
|
||||
resizable = false,
|
||||
}: Props) {
|
||||
const { classes } = useInputTextAreaStyles({ resizable });
|
||||
const tooltip = useToolTip();
|
||||
const [isFocused, setIsFocused] = useState(false)
|
||||
return <InputWrapper label={label} labelSize={(value === '') && !isFocused ? 'normal' : 'small'}>
|
||||
return <InputWrapper error={error} label={label} labelSize={(value === '') && !isFocused ? 'normal' : 'small'}>
|
||||
<textarea
|
||||
className={classes.input}
|
||||
value={value}
|
||||
|
||||
@@ -7,12 +7,14 @@ export interface Props {
|
||||
labelSize?: 'normal' | 'small';
|
||||
noMargin?: boolean;
|
||||
className?: string;
|
||||
error?: string;
|
||||
}
|
||||
const InputWrapper: FC<Props> = ({ label, children, labelSize = 'normal', noMargin = false, className = "" }) => {
|
||||
const { classes } = useInputWrapperStyles({ labelSize, noMargin })
|
||||
const InputWrapper: FC<Props> = ({ error, label, children, labelSize = 'normal', noMargin = false, className = "" }) => {
|
||||
const { classes } = useInputWrapperStyles({ labelSize, noMargin, hasError: !!error })
|
||||
return <div className={[classes.wrapper, className].join(" ")}>
|
||||
<label className={classes.label}>{label}</label>
|
||||
{children}
|
||||
<span className={classes.error}>{error}</span>
|
||||
</div>
|
||||
}
|
||||
export default InputWrapper;
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as yaml from "js-yaml";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import InputTextArea from "./InputTextArea";
|
||||
import { useDelayedFunction, useDelayEffect } from 'utils/useDelay';
|
||||
|
||||
export interface Props<T extends {}> {
|
||||
label: string;
|
||||
@@ -14,25 +15,37 @@ export default function InputYaml<T>({
|
||||
onChange,
|
||||
resizable,
|
||||
}: Props<T>) {
|
||||
const [text, setText] = useState("");
|
||||
useEffect(() => {
|
||||
setText(yaml.dump(value));
|
||||
}, [value]);
|
||||
const delayId = useRef<null | number>(null);
|
||||
const delayedUpdate = (update: string) => {
|
||||
setText(update)
|
||||
if (delayId.current) {
|
||||
window.clearTimeout(delayId.current);
|
||||
delayId.current = null;
|
||||
const [{ text, error }, setState] = useState<{
|
||||
text: string,
|
||||
error: undefined | string,
|
||||
}>({
|
||||
text: yaml.dump(value),
|
||||
error: undefined
|
||||
});
|
||||
const setText = (t: string) => {
|
||||
try {
|
||||
console.log(yaml.dump(yaml.load(t)));
|
||||
setState({ text: t, error: undefined })
|
||||
} catch (_) {
|
||||
setState({ text: t, error: "! Invalid Yaml !" })
|
||||
}
|
||||
delayId.current = window.setTimeout(() => {
|
||||
onChange(yaml.load(update) as any)
|
||||
}, 1000);
|
||||
}
|
||||
useDelayEffect(() => {
|
||||
if (!error && (yaml.dump(value) !== text)) {
|
||||
if (text) {
|
||||
onChange(yaml.load(text) as any)
|
||||
} else if (Array.isArray(value)) {
|
||||
onChange([] as any)
|
||||
} else {
|
||||
onChange({} as any)
|
||||
}
|
||||
}
|
||||
}, [text], 1000)
|
||||
return <InputTextArea
|
||||
error={error}
|
||||
label={label}
|
||||
value={text}
|
||||
onChange={delayedUpdate}
|
||||
onChange={setText}
|
||||
resizable={resizable}
|
||||
/>
|
||||
}
|
||||
@@ -35,6 +35,7 @@ export const useButtonStyles = createAppUseStyles<{}>(theme => ({
|
||||
export const useInputWrapperStyles = createAppUseStyles<{
|
||||
labelSize: 'normal' | 'small',
|
||||
noMargin: boolean,
|
||||
hasError: boolean,
|
||||
}>(theme => {
|
||||
return {
|
||||
wrapper: ({ noMargin }) => ({
|
||||
@@ -51,7 +52,16 @@ export const useInputWrapperStyles = createAppUseStyles<{
|
||||
top: labelSize === 'normal' ? '0.5em' : '0.25em',
|
||||
fontWeight: 'bold',
|
||||
color: theme.primaryAccent,
|
||||
})
|
||||
}),
|
||||
error: ({ hasError }) => (hasError ? {
|
||||
textAlign: 'center',
|
||||
color: theme.red,
|
||||
padding: '0.25em',
|
||||
border: `1px solid ${theme.red}`,
|
||||
borderTop: 'none',
|
||||
borderBottomRightRadius: 5,
|
||||
borderBottomLeftRadius: 5,
|
||||
} : {})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -111,13 +121,17 @@ export const useInputNumberStyles = createAppUseStyles<{}>(theme => {
|
||||
}
|
||||
});
|
||||
|
||||
export const useInputListStyles = createAppUseStyles<{}>(theme => {
|
||||
export const useInputListStyles = createAppUseStyles<{
|
||||
invalidCurrent: boolean;
|
||||
}>(theme => {
|
||||
const styles = commonInputStyle(theme);
|
||||
return {
|
||||
input: {
|
||||
input: ({ invalidCurrent }) => ({
|
||||
...styles.input,
|
||||
cursor: 'pointer'
|
||||
}
|
||||
cursor: 'pointer',
|
||||
borderColor: invalidCurrent ? theme.redAccent : styles.input.borderColor,
|
||||
color: invalidCurrent ? theme.redLight : styles.input.color,
|
||||
}),
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -12,4 +12,8 @@
|
||||
|
||||
.multinode-editor.modded>.multinode-editor--navbar * {
|
||||
border-color: var(--green-light);
|
||||
}
|
||||
|
||||
.multinode-editor.modded .multinode-editor--total {
|
||||
color: var(--green-light)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export default {
|
||||
component: MultiNodeEditor,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {
|
||||
allowedTypes: ['action', 'condition', 'trigger'],
|
||||
sequence: [
|
||||
{
|
||||
"condition": "numeric_state",
|
||||
@@ -28,10 +29,14 @@ export default {
|
||||
} as ComponentMeta<typeof MultiNodeEditor>
|
||||
|
||||
export const Simple: ComponentStory<typeof MultiNodeEditor> = args => {
|
||||
const [state, setState] = useState(args.sequence);
|
||||
|
||||
return <div className="page">
|
||||
<div className="center column" style={{ paddingTop: "1em" }}>
|
||||
<MultiNodeEditor {...args} />
|
||||
<MultiNodeEditor {...args} sequence={state} onSave={s => {
|
||||
args.onSave && args.onSave(s)
|
||||
setState(s)
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -39,6 +44,7 @@ export const InAModal: ComponentStory<typeof MultiNodeEditor> = props => {
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [state, setState] = useState(props.sequence);
|
||||
console.log({ state })
|
||||
return <div className="page">
|
||||
<Button onClick={() => setOpen(!open)}>Open Editor</Button>
|
||||
<Modal open={open}>
|
||||
@@ -46,8 +52,19 @@ export const InAModal: ComponentStory<typeof MultiNodeEditor> = props => {
|
||||
{...props}
|
||||
sequence={state}
|
||||
onClose={() => setOpen(!open)}
|
||||
onSave={setState}
|
||||
onSave={s => {
|
||||
props.onSave && props.onSave(s)
|
||||
setState(s)
|
||||
}}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
};
|
||||
|
||||
|
||||
export const EmptyConditionEditor = Simple.bind({})
|
||||
EmptyConditionEditor.args = {
|
||||
...EmptyConditionEditor.args,
|
||||
allowedTypes: ['condition'],
|
||||
sequence: [],
|
||||
}
|
||||
@@ -1,100 +1,24 @@
|
||||
import "./index.css";
|
||||
import { FC, useState } from 'react';
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { AutomationNode, AutomationNodeMapping } from 'types/automations';
|
||||
import { NodeEditor } from 'components/NodeEditor';
|
||||
import { Button } from 'components/Inputs/Button';
|
||||
import { AutomationTriggerDevice } from 'types/automations/triggers';
|
||||
import { useMultiNodeEditorState } from "./state";
|
||||
import { MultiNodeEditorProps } from "./types";
|
||||
|
||||
|
||||
const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => {
|
||||
switch (nodeType) {
|
||||
case 'action':
|
||||
return {
|
||||
'data': {},
|
||||
'service': '',
|
||||
'target': {},
|
||||
}
|
||||
case 'condition':
|
||||
return {
|
||||
condition: 'and',
|
||||
conditions: []
|
||||
}
|
||||
default:
|
||||
return {
|
||||
platform: 'device',
|
||||
device_id: '',
|
||||
domain: '',
|
||||
type: '',
|
||||
subtype: '',
|
||||
} as AutomationTriggerDevice
|
||||
}
|
||||
}
|
||||
|
||||
export interface MultiNodeEditorProps {
|
||||
sequence: AutomationNode[];
|
||||
allowedTypes?: Array<keyof AutomationNodeMapping>;
|
||||
onClose?: () => void;
|
||||
onSave?: (n: AutomationNode[]) => void;
|
||||
}
|
||||
|
||||
export const MultiNodeEditor: FC<MultiNodeEditorProps> = ({
|
||||
sequence: initialState,
|
||||
allowedTypes = ['action', 'condition'],
|
||||
onClose: _onClose = () => { },
|
||||
onSave = () => { },
|
||||
}) => {
|
||||
export const MultiNodeEditor: FC<MultiNodeEditorProps> = props => {
|
||||
// state
|
||||
const [{ slide, state, isModified, isReady }, setState] = useState({
|
||||
slide: 0,
|
||||
state: initialState,
|
||||
isModified: false,
|
||||
isReady: true,
|
||||
})
|
||||
// alias
|
||||
const areYouSureItsNotReady = () => !isReady ?
|
||||
window.confirm("The node is not ready, are you sure you want to move?") :
|
||||
true
|
||||
const areYouSureItsModified = () => !isModified ?
|
||||
window.confirm("If you close this without saving, you will lose all progress!") :
|
||||
true
|
||||
const onClose = () => areYouSureItsModified() ?
|
||||
_onClose() :
|
||||
null
|
||||
const onAdd = () => setState({
|
||||
slide: state.length,
|
||||
state: [...state, makeDefault(allowedTypes[0])],
|
||||
isReady,
|
||||
isModified: true,
|
||||
});
|
||||
const onRemove = () => setState({
|
||||
slide: slide > 0 ? slide - 1 : 0,
|
||||
state: [...state.slice(0, slide), ...state.slice(slide + 1)],
|
||||
isReady,
|
||||
isModified: true,
|
||||
});
|
||||
const onAllSave = (n: AutomationNode) => onSave([
|
||||
...state.slice(0, slide), n, ...state.slice(slide + 1)
|
||||
]);
|
||||
const onNextOrAdd = () => {
|
||||
if (!areYouSureItsNotReady()) {
|
||||
return
|
||||
}
|
||||
if (slide >= state.length - 1) {
|
||||
onAdd()
|
||||
} else {
|
||||
setState({ slide: slide + 1, state, isReady, isModified, })
|
||||
}
|
||||
}
|
||||
const onBack = () => areYouSureItsNotReady() &&
|
||||
setState({ slide: slide - 1, state, isReady, isModified })
|
||||
const state = useMultiNodeEditorState(props)
|
||||
// components
|
||||
const nextOrAddBtn = <Button
|
||||
onClick={onNextOrAdd}
|
||||
onClick={state.moveForward}
|
||||
>
|
||||
{(slide < state.length - 1) ? ">>" : "+"}
|
||||
{!state.isLast ? ">>" : "+"}
|
||||
</Button>;
|
||||
// branch
|
||||
if (state.length === 0) {
|
||||
if (state.isEmpty) {
|
||||
return <div className='column center' style={{
|
||||
minWidth: '20vw',
|
||||
}}>
|
||||
@@ -107,30 +31,26 @@ export const MultiNodeEditor: FC<MultiNodeEditorProps> = ({
|
||||
{nextOrAddBtn}
|
||||
</div>
|
||||
<div className='column center' style={{ marginTop: '1em' }}>
|
||||
<Button onClick={onClose}>Close</Button>
|
||||
<Button onClick={() => onSave(state)}>Save</Button>
|
||||
<Button onClick={state.onClose}>Close</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
return <div className={["multinode-editor", isModified ? "modded" : ''].join(' ')}>
|
||||
return <div className={["multinode-editor", state.isModified ? "modded" : ''].join(' ')}>
|
||||
<div className="multinode-editor--navbar">
|
||||
<Button onClick={onBack} disabled={slide === 0}>{"<<"}</Button>
|
||||
<Button onClick={onRemove}> Delete</Button>
|
||||
<Button onClick={state.moveBack} disabled={state.currentSlideNumber === 0}>{"<<"}</Button>
|
||||
<Button onClick={state.onRemove}> Delete</Button>
|
||||
{nextOrAddBtn}
|
||||
</div>
|
||||
<NodeEditor
|
||||
key={slide}
|
||||
node={state[slide]}
|
||||
allowedTypes={allowedTypes}
|
||||
onClose={onClose}
|
||||
onSave={onAllSave}
|
||||
onFlags={
|
||||
(ir) => (ir !== isReady) &&
|
||||
setState({ slide, state, isReady: ir, isModified })
|
||||
}
|
||||
key={state.currentSlideNumber}
|
||||
node={state.currentSlide}
|
||||
allowedTypes={props.allowedTypes}
|
||||
onClose={state.onClose}
|
||||
onSave={state.onSave}
|
||||
onFlags={state.updateInternalNode}
|
||||
/>
|
||||
<div className='column center'>
|
||||
<span>{slide + 1}/{state.length}</span>
|
||||
<span>{state.currentSlideNumber + 1}/<u className="multinode-editor--total">{state.totalSlides}</u></span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { MultiNodeEditorProps } from "./types";
|
||||
import { useState, useRef } from 'react';
|
||||
import { AutomationNode } from '../../types/automations/index';
|
||||
import { makeDefault } from "utils/automations";
|
||||
|
||||
|
||||
export type MultiNodeEditorInternalState = {
|
||||
slides: AutomationNode[];
|
||||
slide: number;
|
||||
multiNode: {
|
||||
isModified: boolean,
|
||||
isSaved: boolean,
|
||||
},
|
||||
internalNodeModified: boolean,
|
||||
};
|
||||
|
||||
export const useMultiNodeEditorState = (props: MultiNodeEditorProps) => {
|
||||
const [state, _setState] = useState(makeInitialState({
|
||||
slides: props.sequence
|
||||
}))
|
||||
const justSaved = useRef(false);
|
||||
|
||||
const {
|
||||
slide,
|
||||
slides,
|
||||
multiNode,
|
||||
internalNodeModified,
|
||||
} = state;
|
||||
const setState = (a: MultiNodeEditorInternalState) => {
|
||||
console.log('setting state', a)
|
||||
_setState(a)
|
||||
}
|
||||
return {
|
||||
get totalSlides() {
|
||||
return slides.length
|
||||
},
|
||||
get currentSlideNumber() {
|
||||
return slide
|
||||
},
|
||||
get currentSlide() {
|
||||
return slides[slide]
|
||||
},
|
||||
get isLast() {
|
||||
return slide >= slides.length - 1
|
||||
},
|
||||
get isEmpty() {
|
||||
return slides.length === 0
|
||||
},
|
||||
get isModified() {
|
||||
return (internalNodeModified || multiNode.isModified) && !multiNode.isSaved
|
||||
},
|
||||
moveBack() {
|
||||
if (slide <= 0) {
|
||||
return
|
||||
}
|
||||
if (internalNodeModified && !multiNode.isSaved) {
|
||||
if (!window.confirm("Moving back without saving will cause you to lose the work, are you sure you want to do that?")) {
|
||||
return
|
||||
}
|
||||
}
|
||||
setState({ ...state, slide: slide - 1, internalNodeModified: false, })
|
||||
},
|
||||
moveForward() {
|
||||
const createNew = slide >= slides.length - 1;
|
||||
if (internalNodeModified && !multiNode.isSaved) {
|
||||
const action = createNew ? 'Creating a new new node' : 'Moving forward'
|
||||
if (!window.confirm(`${action} without saving will cause you to lose the work, are you sure you want to do that?`)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (createNew) {
|
||||
setState({
|
||||
...state,
|
||||
slide: slides.length,
|
||||
slides: slides.concat([makeDefault(props.allowedTypes[0])]),
|
||||
internalNodeModified: false,
|
||||
multiNode: {
|
||||
isModified: true,
|
||||
isSaved: false,
|
||||
}
|
||||
})
|
||||
} else {
|
||||
setState({ ...state, slide: slide + 1, internalNodeModified: false, })
|
||||
}
|
||||
},
|
||||
updateInternalNode(isReady: boolean, isModified: boolean) {
|
||||
if (!isReady || isModified) {
|
||||
if (!state.multiNode.isModified || state.multiNode.isSaved) {
|
||||
if (justSaved.current) {
|
||||
justSaved.current = false
|
||||
} else {
|
||||
setState({
|
||||
...state,
|
||||
multiNode: { isModified: true, isSaved: false, },
|
||||
internalNodeModified: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onRemove() {
|
||||
setState({
|
||||
...state,
|
||||
slide: Math.max(slide - 1, 0),
|
||||
slides: slides
|
||||
.slice(0, slide)
|
||||
.concat(
|
||||
slides.slice(slide + 1)
|
||||
),
|
||||
multiNode: {
|
||||
isModified: multiNode.isModified,
|
||||
isSaved: false,
|
||||
}
|
||||
})
|
||||
},
|
||||
onSave(node: AutomationNode) {
|
||||
justSaved.current = true
|
||||
setState({
|
||||
...state,
|
||||
slides: slides
|
||||
.slice(0, slide)
|
||||
.concat([node])
|
||||
.concat(
|
||||
slides.slice(slide + 1)
|
||||
),
|
||||
multiNode: {
|
||||
isModified: multiNode.isModified,
|
||||
isSaved: true,
|
||||
},
|
||||
internalNodeModified: false,
|
||||
})
|
||||
},
|
||||
onClose() {
|
||||
if (!multiNode.isSaved) {
|
||||
if (!window.confirm("You haven't saved your work, are you ok with losing it?")) {
|
||||
return
|
||||
}
|
||||
}
|
||||
props.onSave && props.onSave(slides)
|
||||
props.onClose && props.onClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const makeInitialState = (props: Partial<MultiNodeEditorInternalState>): MultiNodeEditorInternalState => ({
|
||||
slides: [],
|
||||
slide: 0,
|
||||
multiNode: {
|
||||
isModified: false,
|
||||
isSaved: false,
|
||||
},
|
||||
internalNodeModified: false,
|
||||
...props,
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { AutomationNode, AutomationNodeMapping } from "types/automations";
|
||||
|
||||
export interface MultiNodeEditorProps {
|
||||
sequence: AutomationNode[];
|
||||
allowedTypes: Array<keyof AutomationNodeMapping>;
|
||||
onClose?: () => void;
|
||||
onSave?: (n: AutomationNode[]) => void;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { AutomationNode, AutomationNodeTypes } from 'types/automations';
|
||||
import { AutomationNodeSubtype } from 'types/automations';
|
||||
import { getOptionManager } from './getOptionManager';
|
||||
import { getNodeType, getSubTypeList } from 'utils/automations';
|
||||
import { getNodeSubType } from '../constants';
|
||||
|
||||
|
||||
export const useEditorNodeState = (node: AutomationNode) => {
|
||||
const [{ node: state, isModified }, setAllState] = useState({
|
||||
node,
|
||||
isModified: false,
|
||||
});
|
||||
useEffect(() => {
|
||||
setAllState({ node, isModified: false })
|
||||
}, [node])
|
||||
const setState = (node: AutomationNode) => setAllState(({ node, isModified: true }));
|
||||
const originalNodeType = getNodeType(node);
|
||||
const originalNodeSubType = getNodeSubType(node);
|
||||
const nodeType = getNodeType(state);
|
||||
const subType = getNodeSubType(state);
|
||||
const subTypes = getSubTypeList(nodeType)
|
||||
const optionManager = getOptionManager(nodeType, subType as any);
|
||||
return {
|
||||
nodeType,
|
||||
subType,
|
||||
subTypes,
|
||||
get isModified() {
|
||||
return isModified
|
||||
},
|
||||
get data() {
|
||||
return state
|
||||
},
|
||||
renderOptionList() {
|
||||
return optionManager.renderOptionList(state, setState);
|
||||
},
|
||||
isReady() {
|
||||
return optionManager.isReady(state);
|
||||
},
|
||||
setNodeType(newType: AutomationNodeTypes) {
|
||||
if (newType === originalNodeType) {
|
||||
setState(node)
|
||||
} else {
|
||||
setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState())
|
||||
}
|
||||
},
|
||||
setSubType(newSubType: AutomationNodeSubtype<typeof nodeType>) {
|
||||
if (newSubType === originalNodeSubType) {
|
||||
setState(node)
|
||||
} else {
|
||||
setState(getOptionManager(nodeType, newSubType as any).defaultState())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
||||
import { AutomationNode, AutomationNodeTypes } from 'types/automations';
|
||||
import { AutomationNodeSubtype } from 'types/automations';
|
||||
import { getOptionManager } from './getOptionManager';
|
||||
import { getNodeType, getSubTypeList } from 'utils/automations';
|
||||
import { getNodeSubType } from '../constants';
|
||||
import InputYaml from 'components/Inputs/InputYaml';
|
||||
|
||||
type UseState = <S>(s: S) => [S, Dispatch<SetStateAction<S>>]
|
||||
|
||||
const mockUseState: UseState = s => {
|
||||
return [s, () => { }]
|
||||
}
|
||||
|
||||
export const useEditorNodeState = (originalNode: AutomationNode, uState: UseState = useState) => {
|
||||
const [allState, setAllState] = uState({
|
||||
node: originalNode,
|
||||
yamlMode: false,
|
||||
isModified: false,
|
||||
invalidManualYaml: "",
|
||||
});
|
||||
const { node: currentNode, isModified, yamlMode, invalidManualYaml } = allState;
|
||||
useEffect(() => {
|
||||
setAllState({ ...allState, node: originalNode, isModified: false, })
|
||||
}, [originalNode])
|
||||
const setState = (node: AutomationNode) => setAllState(({ ...allState, node, isModified: true, }));
|
||||
const setYamlMode = (yamlMode: boolean) => setAllState({ ...allState, yamlMode, });
|
||||
const setStateForManualYaml = (yaml: any) => {
|
||||
try {
|
||||
createData(yaml, yaml)
|
||||
setAllState({ ...allState, node: yaml, invalidManualYaml: '' })
|
||||
} catch (err) {
|
||||
setAllState({ ...allState, invalidManualYaml: String(err) })
|
||||
}
|
||||
}
|
||||
const {
|
||||
originalNodeType,
|
||||
originalNodeSubType,
|
||||
nodeType,
|
||||
subType,
|
||||
subTypes,
|
||||
optionManager,
|
||||
} = createData(originalNode, currentNode);
|
||||
return {
|
||||
nodeType,
|
||||
subType,
|
||||
subTypes,
|
||||
yamlMode,
|
||||
setYamlMode,
|
||||
invalidManualYaml,
|
||||
isModified,
|
||||
get data() {
|
||||
return currentNode
|
||||
},
|
||||
renderOptionList() {
|
||||
if (yamlMode) {
|
||||
return <>
|
||||
<InputYaml
|
||||
label=''
|
||||
value={currentNode}
|
||||
onChange={setStateForManualYaml}
|
||||
resizable
|
||||
/>
|
||||
<span className="node-editor--error">{invalidManualYaml}</span>
|
||||
</>
|
||||
}
|
||||
return optionManager.renderOptionList(currentNode, setState);
|
||||
},
|
||||
isReady() {
|
||||
return optionManager.isReady(currentNode);
|
||||
},
|
||||
setNodeType(newType: AutomationNodeTypes) {
|
||||
if (newType === originalNodeType) {
|
||||
setState(originalNode)
|
||||
} else {
|
||||
setState(getOptionManager(newType, getSubTypeList(newType)[0]).defaultState())
|
||||
}
|
||||
},
|
||||
setSubType(newSubType: AutomationNodeSubtype<typeof nodeType>) {
|
||||
if (newSubType === originalNodeSubType) {
|
||||
setState(originalNode)
|
||||
} else {
|
||||
setState(getOptionManager(nodeType, newSubType as any).defaultState())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const createData = (originalNode: AutomationNode, currentNode: AutomationNode) => {
|
||||
const originalNodeType = getNodeType(originalNode);
|
||||
const originalNodeSubType = getNodeSubType(originalNode);
|
||||
const nodeType = getNodeType(currentNode);
|
||||
const subType = getNodeSubType(currentNode);
|
||||
const subTypes = getSubTypeList(nodeType)
|
||||
const optionManager = getOptionManager(nodeType, subType as any);
|
||||
|
||||
return {
|
||||
originalNodeType,
|
||||
originalNodeSubType,
|
||||
nodeType,
|
||||
subType,
|
||||
subTypes,
|
||||
optionManager,
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import "./index.css";
|
||||
|
||||
import { FC } from "react";
|
||||
import { FC } from 'react';
|
||||
import { AutomationNode, AutomationNodeMapping } from 'types/automations/index';
|
||||
import { useEditorNodeState } from "./OptionManager";
|
||||
import { InputList } from "components/Inputs/InputList";
|
||||
import { Button } from "components/Inputs/Button";
|
||||
import InputBoolean from "components/Inputs/InputBoolean";
|
||||
|
||||
export interface Props {
|
||||
export interface NodeEditorProps {
|
||||
node: AutomationNode
|
||||
allowedTypes?: Array<keyof AutomationNodeMapping>;
|
||||
onClose?: () => void;
|
||||
@@ -15,7 +16,7 @@ export interface Props {
|
||||
saveBtnCreateText?: boolean;
|
||||
}
|
||||
|
||||
export const NodeEditor: FC<Props> = ({
|
||||
export const NodeEditor: FC<NodeEditorProps> = ({
|
||||
node,
|
||||
allowedTypes = ["action", "condition", "trigger"],
|
||||
onClose = () => { },
|
||||
@@ -30,15 +31,14 @@ export const NodeEditor: FC<Props> = ({
|
||||
// alias
|
||||
const isModified = state.isModified;
|
||||
const isReady = state.isReady();
|
||||
const areYouSureNotReady = () => !isReady ?
|
||||
window.confirm("This node is missing some values, are you sure you want to save?") :
|
||||
const areYouSureNotReady = (what: string) => !isReady ?
|
||||
window.confirm(`This node is missing some values, are you sure you want to ${what}?`) :
|
||||
true;
|
||||
|
||||
// events
|
||||
onFlags(isReady, isModified);
|
||||
|
||||
// render
|
||||
return <div className={["node-editor--root", isModified ? "modded" : "", !isReady ? 'not-ready' : ''].join(" ")}>
|
||||
return <div className={["node-editor--root", isModified ? "modded" : "", (!isReady && isModified) ? 'not-ready' : ''].join(" ")}>
|
||||
<div className="node-editor--body">
|
||||
<div className="node-editor--body-title">
|
||||
{allowedTypes.length > 1 ? <InputList
|
||||
@@ -53,14 +53,21 @@ export const NodeEditor: FC<Props> = ({
|
||||
options={state.subTypes}
|
||||
onChange={state.setSubType}
|
||||
/> : <></>}
|
||||
<InputBoolean label="Yaml" onChange={state.setYamlMode} value={state.yamlMode} />
|
||||
</div>
|
||||
{state.renderOptionList()}
|
||||
</div>
|
||||
<div className="node-editor--footer">
|
||||
<Button className="node-editor--footer--close" onClick={onClose}>Close</Button>
|
||||
<Button className="node-editor--footer--save" onClick={() => {
|
||||
areYouSureNotReady() && onSave(state.data)
|
||||
}} title={!isReady ? "Some fields have not been properly filled up" : ""}>
|
||||
<Button className="node-editor--footer--close" onClick={() => areYouSureNotReady('close') && onClose()}>Close</Button>
|
||||
<Button
|
||||
className="node-editor--footer--save"
|
||||
onClick={() => {
|
||||
areYouSureNotReady('save') && onSave(state.data)
|
||||
}}
|
||||
title={
|
||||
!isReady ? "Some fields have not been properly filled up" : ""
|
||||
}
|
||||
>
|
||||
{saveBtnCreateText ? "Create" : "Save"}
|
||||
</Button>
|
||||
{children}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
--green-opaque: #1f15;
|
||||
--green-light: #6f5;
|
||||
--error: #c55;
|
||||
--error-light: #f77;
|
||||
--error-opaque: #c555;
|
||||
--error-accent: #9f3a3a;
|
||||
--change: #0f9;
|
||||
|
||||
@@ -30,6 +30,7 @@ export const {
|
||||
red: 'var(--error)',
|
||||
redOpaque: 'var(--error-opaque)',
|
||||
redAccent: 'var(--error-accent)',
|
||||
redLight: 'var(--error-light)',
|
||||
}));
|
||||
|
||||
export type GetThemeType<C extends Context<any>> = C extends Context<infer T> ? T : unknown;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { AutomationNode, AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
|
||||
import { AutomationNode, AutomationNodeMapping, AutomationNodeSubtype, AutomationNodeTypes } from "types/automations";
|
||||
import { AutomationTrigger } from 'types/automations/triggers';
|
||||
|
||||
|
||||
export const getNodeType = (node: AutomationNode): AutomationNodeTypes => {
|
||||
console.log({ node })
|
||||
if ('condition' in node) {
|
||||
return 'condition'
|
||||
} else if ('platform' in node) {
|
||||
@@ -51,4 +53,29 @@ export const getSubTypeList = <T extends AutomationNodeTypes>(nodeType: T): Auto
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const makeDefault = (nodeType: keyof AutomationNodeMapping): AutomationNode => {
|
||||
switch (nodeType) {
|
||||
case 'action':
|
||||
return {
|
||||
'data': {},
|
||||
'service': '',
|
||||
'target': {},
|
||||
}
|
||||
case 'condition':
|
||||
return {
|
||||
condition: 'and',
|
||||
conditions: []
|
||||
}
|
||||
default:
|
||||
return {
|
||||
platform: 'device',
|
||||
device_id: '',
|
||||
domain: '',
|
||||
type: '',
|
||||
subtype: '',
|
||||
} as AutomationTrigger
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useRef, useEffect } from 'react';
|
||||
|
||||
|
||||
export const useDelayEffect = (cb: () => void, deps: any[], timeout: number) => {
|
||||
const fcn = useDelayedFunction(cb, timeout);
|
||||
useEffect(() => {
|
||||
fcn()
|
||||
}, [deps])
|
||||
}
|
||||
|
||||
export const useDelayedFunction = <FcnParams extends any[]>(
|
||||
cb: (...p: FcnParams) => void, timeout: number
|
||||
) => {
|
||||
const timeid = useRef<number | null>(null);
|
||||
return (...args: FcnParams) => {
|
||||
if (timeid.current) {
|
||||
window.clearTimeout(timeid.current)
|
||||
}
|
||||
timeid.current = window.setTimeout(() => {
|
||||
cb(...args)
|
||||
}, timeout)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user