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

89.47% Statements 17/19
66.67% Branches 4/6
100% Functions 3/3
89.47% Lines 17/19

    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

    1×

    2378×

    1×

    1×

    518×
    518×
    518×
    518×

    518×

    518×

    518×
    198×

    320×

    518×

    518×

    1×

    88×
     import { assign } from 'min-dash';

    var round = Math.round;

    /**
     * A handler that implements reversible addition of shapes.
     *
     * @param {canvas} Canvas
     */
    export default function CreateShapeHandler(canvas) {
      this._canvas = canvas;
    }

    CreateShapeHandler.$inject = [ 'canvas' ];

    // api //////////////////////

    /**
     * Appends a shape to a target shape
     *
     * @param {Object} context
     * @param {djs.model.Base} context.parent the parent object
     * @param {Point} context.position position of the new element
     */
    CreateShapeHandler.prototype.execute = function(context) {

      var shape = context.shape,
          positionOrBounds = context.position,
          parent = context.parent,
          parentIndex = context.parentIndex;

      Iif (!parent) {
        throw new Error('parent required');
      }

      Iif (!positionOrBounds) {
        throw new Error('position required');
      }

      // (1) add at event center position _or_ at given bounds
      if (positionOrBounds.width !== undefined) {
        assign(shape, positionOrBounds);
      } else {
        assign(shape, {
          x: positionOrBounds.x - round(shape.width / 2),
          y: positionOrBounds.y - round(shape.height / 2)
        });
      }

      // (2) add to canvas
      this._canvas.addShape(shape, parent, parentIndex);

      return shape;
    };

    /**
     * Undo append by removing the shape
     */
    CreateShapeHandler.prototype.revert = function(context) {

      // (3) remove form canvas
      this._canvas.removeShape(context.shape);
    };