# all files / Github/diagram-js/lib/features/modeling/cmd/ UpdateAttachmentHandler.js

96.3% Statements 26/27
83.33% Branches 5/6
100% Functions 5/5
96.3% Lines 26/27

    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

    1128×

    1×

    1×
    145×
    145×
    145×

    145×
    145×

    145×

    145×

    145×

    1×
    20×
    20×
    20×
    20×

    20×

    20×

    20×

    20×

    165×

    165×
    42×

    123×

    123×

    123×

     import {
      add as collectionAdd,
      remove as collectionRemove
    } from '../../../util/Collections';

    /**
     * A handler that implements reversible attaching/detaching of shapes.
     */
    export default function UpdateAttachmentHandler(modeling) {
      this._modeling = modeling;
    }

    UpdateAttachmentHandler.$inject = [ 'modeling' ];

    UpdateAttachmentHandler.prototype.execute = function(context) {
      var shape = context.shape,
          newHost = context.newHost,
          oldHost = shape.host;

      // (0) detach from old host
      context.oldHost = oldHost;
      context.attacherIdx = removeAttacher(oldHost, shape);

      // (1) attach to new host
      addAttacher(newHost, shape);

      // (2) update host
      shape.host = newHost;

      return shape;
    };

    UpdateAttachmentHandler.prototype.revert = function(context) {
      var shape = context.shape,
          newHost = context.newHost,
          oldHost = context.oldHost,
          attacherIdx = context.attacherIdx;

      // (2) update host
      shape.host = oldHost;

      // (1) attach to new host
      removeAttacher(newHost, shape);

      // (0) detach from old host
      addAttacher(oldHost, shape, attacherIdx);

      return shape;
    };

    function removeAttacher(host, attacher) {
      // remove attacher from host
      return collectionRemove(host && host.attachers, attacher);
    }

    function addAttacher(host, attacher, idx) {

      if (!host) {
        return;
      }

      var attachers = host.attachers;

      Iif (!attachers) {
        host.attachers = attachers = [];
      }

      collectionAdd(attachers, attacher, idx);
    }