Reputation: 28780
I have lots of code like this:
export const getNodeShapeSize = ({
scaleToFit,
compress,
expanded
}: {
scaleToFit: boolean;
compress: boolean;
expanded: boolean;
}): number => {
if (scaleToFit) {
return ShapeSizes.full;
}
if (compress && !expanded) {
return ShapeSizes.preview;
}
return ShapeSizes.expanded;
};
I was wondering if I could clean this up by using xstate? I could have 3 states
scaleToFit
compressed
expnded
So far I have this:
export const treeMachineConfig = Machine({
strict: true,
id: 'treefsm',
initial: TreeSFMActionTypes.Unkonwn,
states: {
unknown: {
on: {
scaleToFit: 'scaledToFit',
compress: 'compressed',
expand: 'expanded'
}
},
scaledToFit: {
on: {
compress: 'compressed',
expand: 'expanded'
}
},
compressed: {
on: {
scaleToFit: 'scaledToFit',
expand: 'expanded'
}
},
expanded: {
on: {
scaleToFit: 'scaledToFit',
compress: 'compressed'
}
}
}
});
But where would the values lie? Would I put them in the context?
Upvotes: 0
Views: 100
Reputation: 5203
Yes, you would put them in context
(docs 📖) and it would look like this:
import { Machine, assign } from 'xstate';
export const treeMachineConfig = Machine({
strict: true,
id: 'treefsm',
context: {
width: 0,
height: 0
},
initial: TreeSFMActionTypes.Unkonwn,
states: {
// ...
compressed: {
// Just an example: set to this size whenever 'compressed' state is entered
entry: assign({ x: 10, y: 10 }),
on: // ...
},
expanded: {
entry: assign({ /* ... */ }),
on: // ...
}
}
});
Upvotes: 1