All files / xstate/src StateTree.ts

90.97% Statements 141/155
87.36% Branches 76/87
86.67% Functions 26/30
91.67% Lines 132/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336              1x 1x 1x           1x       1x           15938x 15938x 30014x   15938x                 4330x       15938x 15938x     2772x 2772x   1x   1746x 1746x       1025x       1x                       2759x   2759x 135x     2624x       2x     2622x   1768x       2622x 135x 137x     135x 1x   134x       2487x 2485x     2x     1x 1862x         1x 1066x     168x 168x 168x 168x   168x 212x 168x   44x 44x       168x     18x 18x   18x   13x   13x       18x     1x 207x     223x 223x       217x   55x 55x 1x   1x 1x   1x   54x   54x       46x 46x 46x       162x 162x   162x   162x 342x 331x   11x       160x 160x 160x             1x 7906x 23x     7883x 989x 1717x       6894x 6894x 8x   6886x 6886x 4969x     1917x 1917x           1x     4115x       4115x       4115x   2883x         2883x 2883x   2883x 1267x 1267x   1616x           2883x 156x 156x   2883x     228x 516x           228x         228x 516x 516x     228x 5x 5x     228x       1004x 299x         705x             1710x 1710x       1710x     443x           1694x 1694x       1694x   427x       1x  
import { StateNode } from './StateNode';
import {
  StateValue,
  EntryExitStateArrays,
  EventType,
  StateValueMap
} from './types';
import { mapValues, flatten, toStatePaths, keys } from './utils';
import { matchesState } from './utils';
import { done } from './actions';
 
export interface StateTreeOptions {
  resolved?: boolean;
}
 
const defaultStateTreeOptions = {
  resolved: false
};
 
export class StateTree {
  public parent?: StateTree | undefined;
  public nodes: Record<string, StateTree>;
  public isResolved: boolean;
 
  constructor(
    public stateNode: StateNode,
    public _stateValue: StateValue | undefined,
    options: StateTreeOptions = defaultStateTreeOptions
  ) {
    this.nodes = _stateValue
      ? typeof _stateValue === 'string'
        ? {
            [_stateValue]: new StateTree(
              stateNode.getStateNode(_stateValue),
              undefined
            )
          }
        : mapValues(_stateValue, (subValue, key) => {
            return new StateTree(stateNode.getStateNode(key), subValue);
          })
      : {};
 
    const resolvedOptions = { ...defaultStateTreeOptions, ...options };
    this.isResolved = resolvedOptions.resolved;
  }
 
  public get done(): boolean {
    switch (this.stateNode.type) {
      case 'final':
        return true;
      case 'compound':
        const childNode = this.nodes[keys(this.nodes)[0]];
        return childNode.stateNode.type === 'final';
      case 'parallel':
        return keys(this.nodes).some(key => this.nodes[key].done);
      default:
        return false;
    }
  }
 
  public get atomicNodes(): StateNode[] {
    if (this.stateNode.type === 'atomic' || this.stateNode.type === 'final') {
      return [this.stateNode];
    }
 
    return flatten(
      keys(this.value as StateValueMap).map(key => {
        return this.value[key].atomicNodes;
      })
    );
  }
 
  public getDoneEvents(entryStateNodes?: Set<StateNode>): EventType[] {
    // If no state nodes are being entered, no done events will be fired
    if (!entryStateNodes || !entryStateNodes.size) {
      return [];
    }
 
    if (
      entryStateNodes.has(this.stateNode) &&
      this.stateNode.type === 'final'
    ) {
      return [done(this.stateNode.id)];
    }
 
    const childDoneEvents = flatten(
      keys(this.nodes).map(key => {
        return this.nodes[key].getDoneEvents(entryStateNodes);
      })
    );
 
    if (this.stateNode.type === 'parallel') {
      const allChildrenDone = keys(this.nodes).every(
        key => this.nodes[key].done
      );
 
      if (childDoneEvents && allChildrenDone) {
        return [done(this.stateNode.id)].concat(childDoneEvents);
      } else {
        return childDoneEvents;
      }
    }
 
    if (!this.done || !childDoneEvents.length) {
      return childDoneEvents;
    }
 
    return [done(this.stateNode.id)].concat(childDoneEvents);
  }
 
  public get resolved(): StateTree {
    return new StateTree(this.stateNode, this.stateNode.resolve(this.value), {
      resolved: true
    });
  }
 
  public get paths(): string[][] {
    return toStatePaths(this.value);
  }
 
  public get absolute(): StateTree {
    const { _stateValue } = this;
    const absoluteStateValue = {};
    let marker: any = absoluteStateValue;
 
    this.stateNode.path.forEach((key, i) => {
      if (i === this.stateNode.path.length - 1) {
        marker[key] = _stateValue;
      } else {
        marker[key] = {};
        marker = marker[key];
      }
    });
 
    return new StateTree(this.stateNode.machine, absoluteStateValue);
  }
 
  public get nextEvents(): EventType[] {
    const ownEvents = this.stateNode.ownEvents;
 
    const childEvents = flatten(
      keys(this.nodes).map(key => {
        const subTree = this.nodes[key];
 
        return subTree.nextEvents;
      })
    );
 
    return [...new Set(childEvents.concat(ownEvents))];
  }
 
  public clone(): StateTree {
    return new StateTree(this.stateNode, this.value);
  }
 
  public combine(tree: StateTree): StateTree {
    Iif (tree.stateNode !== this.stateNode) {
      throw new Error('Cannot combine distinct trees');
    }
 
    if (this.stateNode.type === 'compound') {
      // Only combine if no child state is defined
      let newValue: Record<string, StateTree>;
      if (!keys(this.nodes).length || !keys(tree.nodes).length) {
        newValue = Object.assign({}, this.nodes, tree.nodes);
 
        const newTree = this.clone();
        newTree.nodes = newValue;
 
        return newTree;
      } else {
        const childKey = keys(this.nodes)[0];
 
        newValue = {
          [childKey]: this.nodes[childKey].combine(tree.nodes[childKey])
        };
 
        const newTree = this.clone();
        newTree.nodes = newValue;
        return newTree;
      }
    }
 
    Eif (this.stateNode.type === 'parallel') {
      const valueKeys = new Set([...keys(this.nodes), ...keys(tree.nodes)]);
 
      const newValue: Record<string, StateTree> = {};
 
      valueKeys.forEach(key => {
        if (!this.nodes[key] || !tree.nodes[key]) {
          newValue[key] = this.nodes[key] || tree.nodes[key];
        } else {
          newValue[key] = this.nodes[key]!.combine(tree.nodes[key]!);
        }
      });
 
      const newTree = this.clone();
      newTree.nodes = newValue;
      return newTree;
    }
 
    // nothing to do
    return this;
  }
 
  public get value(): StateValue {
    if (this.stateNode.type === 'atomic' || this.stateNode.type === 'final') {
      return {};
    }
 
    if (this.stateNode.type === 'parallel') {
      return mapValues(this.nodes, st => {
        return st.value;
      });
    }
 
    Eif (this.stateNode.type === 'compound') {
      if (keys(this.nodes).length === 0) {
        return {};
      }
      const childStateNode = this.nodes[keys(this.nodes)[0]].stateNode;
      if (childStateNode.type === 'atomic' || childStateNode.type === 'final') {
        return childStateNode.key;
      }
 
      return mapValues(this.nodes, st => {
        return st.value;
      });
    }
 
    return {};
  }
  public matches(parentValue: StateValue): boolean {
    return matchesState(parentValue, this.value);
  }
  public getEntryExitStates(
    prevTree: StateTree,
    externalNodes?: Set<StateNode<any>>
  ): EntryExitStateArrays<any> {
    Iif (prevTree.stateNode !== this.stateNode) {
      throw new Error('Cannot compare distinct trees');
    }
 
    switch (this.stateNode.type) {
      case 'compound':
        let r1: EntryExitStateArrays<any> = {
          exit: [],
          entry: []
        };
 
        const currentChildKey = keys(this.nodes)[0];
        const prevChildKey = keys(prevTree.nodes)[0];
 
        if (currentChildKey !== prevChildKey) {
          r1.exit = prevTree.nodes[prevChildKey!].getExitStates();
          r1.entry = this.nodes[currentChildKey!].getEntryStates();
        } else {
          r1 = this.nodes[currentChildKey!].getEntryExitStates(
            prevTree.nodes[prevChildKey!],
            externalNodes
          );
        }
 
        if (externalNodes && externalNodes.has(this.stateNode)) {
          r1.exit.push(this.stateNode);
          r1.entry.unshift(this.stateNode);
        }
        return r1;
 
      case 'parallel':
        const all = keys(this.nodes).map(key => {
          return this.nodes[key].getEntryExitStates(
            prevTree.nodes[key],
            externalNodes
          );
        });
 
        const result: EntryExitStateArrays<any> = {
          exit: [],
          entry: []
        };
 
        all.forEach(ees => {
          result.exit = [...result.exit, ...ees.exit];
          result.entry = [...result.entry, ...ees.entry];
        });
 
        if (externalNodes && externalNodes.has(this.stateNode)) {
          result.exit.push(this.stateNode);
          result.entry.unshift(this.stateNode);
        }
 
        return result;
 
      case 'atomic':
      default:
        if (externalNodes && externalNodes.has(this.stateNode)) {
          return {
            exit: [this.stateNode],
            entry: [this.stateNode]
          };
        }
        return {
          exit: [],
          entry: []
        };
    }
  }
 
  public getEntryStates(): StateNode[] {
    Iif (!this.nodes) {
      return [this.stateNode];
    }
 
    return [this.stateNode].concat(
      flatten(
        keys(this.nodes).map(key => {
          return this.nodes[key].getEntryStates();
        })
      )
    );
  }
 
  public getExitStates(): StateNode[] {
    Iif (!this.nodes) {
      return [this.stateNode];
    }
 
    return flatten(
      keys(this.nodes).map(key => {
        return this.nodes[key].getExitStates();
      })
    ).concat(this.stateNode);
  }
}