0

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?

dagda1
  • 26,856
  • 59
  • 237
  • 450
  • Would you mind clarifying what you mean by values ? Do you mean the "Node" of a tree that you've modelled, would have properties like width or height or a property like "node" where the value would be another node, forming a recursive structure. – TameBadger Jun 08 '19 at 14:18

1 Answers1

1

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: // ...
    }
  }
});
David Khourshid
  • 4,918
  • 1
  • 11
  • 10