# all files / diagram-js/lib/layout/ ManhattanLayout.js

94.32% Statements 166/176
88.89% Branches 136/153
100% Functions 29/29
94.32% Lines 166/176

    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
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744

    1×
    1×

    1×

    1×
    1×

    40×

    156×

    156×

    156×

    156×
    156×

    156×
    156×
    156×

    156×

    156×
    116×

    116×

    40×

    40×

    40×

    40×
    13×

    13×

    27×

    27×

    156×

    78×

    78×

    78×

    78×
    78×

    78×
    2×

    78×
    2×

    78×

    78×

    78×

    156×

    525×
    525×

    525×
    37×

    488×
    57×

    431×
    283×

    148×
    148×

    603×

    603×

    603×
    78×
    78×
    78×

    78×

    525×

    369×

    369×
    369×

    369×

    369×

    369×

    369×

    369×

    369×

    369×
    369×

    369×

    369×
    369×

    369×

    618×

    618×
    618×

    618×
    618×

    618×

    618×
    73×

    545×

    545×
    54×

    491×

    491×
    44×

    447×
    78×

    369×

    78×

    78×

    78×

    101×

    101×

    101×
    23×

    78×
    74×

    78×
    4×

    78×

    12×

    12×

    12×

    66×
    5×

    61×

    61×

    206×

    183×

    183×

    183×

    409×
    268×

    141×

    141×
    476×

    476×

    118×

    118×

    59×

    55×

    4×

    118×

    168×

    20×

    98×

    409×
    291×

    118×
    118×

    118×
    118×

    118×

    118×
    20×

    98×

    369×
    68×

    301×

    10×

    25×

    197×

    69×

    603×

    972×

    369×

    738×
    524×

    738×
    118×

    738×
    101×

    637×
    270×

    367×
    91×

    276×
    276×

    987×

    3618×
    3618×

    3618×
    2840×

    3618×

     import {
      isArray,
      find,
      without,
      assign
    } from 'min-dash';

    import {
      getOrientation,
      getMid
    } from './LayoutUtil';

    import {
      pointInRect,
      pointDistance,
      pointsAligned,
      pointsOnLine
    } from '../util/Geometry';

    var MIN_SEGMENT_LENGTH = 20,
        POINT_ORIENTATION_PADDING = 5;

    var round = Math.round;

    var INTERSECTION_THRESHOLD = 20,
        ORIENTATION_THRESHOLD = {
          'h:h': 20,
          'v:v': 20,
          'h:v': -10,
          'v:h': -10
        };

    function needsTurn(orientation, startDirection) {
      return !{
        t: /top/,
        r: /right/,
        b: /bottom/,
        l: /left/,
        h: /./,
        v: /./
      }[startDirection].test(orientation);
    }

    function canLayoutStraight(direction, targetOrientation) {
      return {
        t: /top/,
        r: /right/,
        b: /bottom/,
        l: /left/,
        h: /left|right/,
        v: /top|bottom/
      }[direction].test(targetOrientation);
    }

    function getSegmentBendpoints(a, b, directions) {
      var orientation = getOrientation(b, a, POINT_ORIENTATION_PADDING);

      var startDirection = directions.split(':')[0];

      var xmid = round((b.x - a.x) / 2 + a.x),
          ymid = round((b.y - a.y) / 2 + a.y);

      var segmentEnd, segmentDirections;

      var layoutStraight = canLayoutStraight(startDirection, orientation),
          layoutHorizontal = /h|r|l/.test(startDirection),
          layoutTurn = false;

      var turnNextDirections = false;

      if (layoutStraight) {
        segmentEnd = layoutHorizontal ? { x: xmid, y: a.y } : { x: a.x, y: ymid };

        segmentDirections = layoutHorizontal ? 'h:h' : 'v:v';
      } else {
        layoutTurn = needsTurn(orientation, startDirection);

        segmentDirections = layoutHorizontal ? 'h:v' : 'v:h';

        Eif (layoutTurn) {

          if (layoutHorizontal) {
            turnNextDirections = ymid === a.y;

            segmentEnd = {
              x: a.x + MIN_SEGMENT_LENGTH * (/l/.test(startDirection) ? -1 : 1),
              y: turnNextDirections ? ymid + MIN_SEGMENT_LENGTH : ymid
            };
          } else {
            turnNextDirections = xmid === a.x;

            segmentEnd = {
              x: turnNextDirections ? xmid + MIN_SEGMENT_LENGTH : xmid,
              y: a.y + MIN_SEGMENT_LENGTH * (/t/.test(startDirection) ? -1 : 1)
            };
          }

        } else {
          segmentEnd = {
            x: xmid,
            y: ymid
          };
        }
      }

      return {
        waypoints: getBendpoints(a, segmentEnd, segmentDirections).concat(segmentEnd),
        directions:  segmentDirections,
        turnNextDirections: turnNextDirections
      };
    }

    function getStartSegment(a, b, directions) {
      return getSegmentBendpoints(a, b, directions);
    }

    function getEndSegment(a, b, directions) {
      var invertedSegment = getSegmentBendpoints(b, a, invertDirections(directions));

      return {
        waypoints: invertedSegment.waypoints.slice().reverse(),
        directions: invertDirections(invertedSegment.directions),
        turnNextDirections: invertedSegment.turnNextDirections
      };
    }

    function getMidSegment(startSegment, endSegment) {

      var startDirection = startSegment.directions.split(':')[1],
          endDirection = endSegment.directions.split(':')[0];

      if (startSegment.turnNextDirections) {
        startDirection = startDirection == 'h' ? 'v' : 'h';
      }

      if (endSegment.turnNextDirections) {
        endDirection = endDirection == 'h' ? 'v' : 'h';
      }

      var directions = startDirection + ':' + endDirection;

      var bendpoints = getBendpoints(
        startSegment.waypoints[startSegment.waypoints.length - 1],
        endSegment.waypoints[0],
        directions
      );

      return {
        waypoints: bendpoints,
        directions: directions
      };
    }

    function invertDirections(directions) {
      return directions.split(':').reverse().join(':');
    }

    /**
     * Handle simple layouts with maximum two bendpoints.
     */
    function getSimpleBendpoints(a, b, directions) {

      var xmid = round((b.x - a.x) / 2 + a.x),
          ymid = round((b.y - a.y) / 2 + a.y);

      // one point, right or left from a
      if (directions === 'h:v') {
        return [ { x: b.x, y: a.y } ];
      }

      // one point, above or below a
      if (directions === 'v:h') {
        return [ { x: a.x, y: b.y } ];
      }

      // vertical segment between a and b
      if (directions === 'h:h') {
        return [
          { x: xmid, y: a.y },
          { x: xmid, y: b.y }
        ];
      }

      // horizontal segment between a and b
      Eif (directions === 'v:v') {
        return [
          { x: a.x, y: ymid },
          { x: b.x, y: ymid }
        ];
      }

      throw new Error('invalid directions: can only handle varians of [hv]:[hv]');
    }

    /**
     * Returns the mid points for a manhattan connection between two points.
     *
     * @example h:h (horizontal:horizontal)
     *
     * [a]----[x]
     *         |
     *        [x]----[b]
     *
     * @example h:v (horizontal:vertical)
     *
     * [a]----[x]
     *         |
     *        [b]
     *
     * @example h:r (horizontal:right)
     *
     * [a]----[x]
     *         |
     *    [b]-[x]
     *
     * @param  {Point} a
     * @param  {Point} b
     * @param  {String} directions
     *
     * @return {Array<Point>}
     */
    function getBendpoints(a, b, directions) {
      directions = directions || 'h:h';

      Iif (!isValidDirections(directions)) {
        throw new Error(
          'unknown directions: <' + directions + '>: ' +
          'must be specified as <start>:<end> ' +
          'with start/end in { h,v,t,r,b,l }'
        );
      }

      // compute explicit directions, involving trbl dockings
      // using a three segmented layouting algorithm
      if (isExplicitDirections(directions)) {
        var startSegment = getStartSegment(a, b, directions),
            endSegment = getEndSegment(a, b, directions),
            midSegment = getMidSegment(startSegment, endSegment);

        return [].concat(
          startSegment.waypoints,
          midSegment.waypoints,
          endSegment.waypoints
        );
      }

      // handle simple [hv]:[hv] cases that can be easily computed
      return getSimpleBendpoints(a, b, directions);
    }

    /**
     * Create a connection between the two points according
     * to the manhattan layout (only horizontal and vertical) edges.
     *
     * @param {Point} a
     * @param {Point} b
     *
     * @param {String} [directions='h:h'] specifies manhattan directions for each point as {adirection}:{bdirection}.
                       A directionfor a point is either `h` (horizontal) or `v` (vertical)
     *
     * @return {Array<Point>}
     */
    export function connectPoints(a, b, directions) {

      var points = getBendpoints(a, b, directions);

      points.unshift(a);
      points.push(b);

      return withoutRedundantPoints(points);
    }

    /**
     * Connect two rectangles using a manhattan layouted connection.
     *
     * @param {Bounds} source source rectangle
     * @param {Bounds} target target rectangle
     * @param {Point} [start] source docking
     * @param {Point} [end] target docking
     *
     * @param {Object} [hints]
     * @param {String} [hints.preserveDocking=source] preserve docking on selected side
     * @param {Array<String>} [hints.preferredLayouts]
     * @param {Point|Boolean} [hints.connectionStart] whether the start changed
     * @param {Point|Boolean} [hints.connectionEnd] whether the end changed
     *
     * @return {Array<Point>} connection points
     */
    export function connectRectangles(source, target, start, end, hints) {

      var preferredLayouts = hints && hints.preferredLayouts || [];

      var preferredLayout = without(preferredLayouts, 'straight')[0] || 'h:h';

      var threshold = ORIENTATION_THRESHOLD[preferredLayout] || 0;

      var orientation = getOrientation(source, target, threshold);

      var directions = getDirections(orientation, preferredLayout);

      start = start || getMid(source);
      end = end || getMid(target);

      var directionSplit = directions.split(':');

      // compute actual docking points for start / end
      // this ensures we properly layout only parts of the
      // connection that lies in between the two rectangles
      var startDocking = getDockingPoint(start, source, directionSplit[0], invertOrientation(orientation)),
          endDocking = getDockingPoint(end, target, directionSplit[1], orientation);

      return connectPoints(startDocking, endDocking, directions);
    }

    /**
     * Repair the connection between two rectangles, of which one has been updated.
     *
     * @param {Bounds} source
     * @param {Bounds} target
     * @param {Point} [start]
     * @param {Point} [end]
     * @param {Array<Point>} [waypoints]
     * @param {Object} [hints]
     * @param {Array<String>} [hints.preferredLayouts] list of preferred layouts
     * @param {Boolean} [hints.connectionStart]
     * @param {Boolean} [hints.connectionEnd]
     *
     * @return {Array<Point>} repaired waypoints
     */
    export function repairConnection(source, target, start, end, waypoints, hints) {

      Iif (isArray(start)) {
        waypoints = start;
        hints = end;

        start = getMid(source);
        end = getMid(target);
      }

      hints = assign({ preferredLayouts: [] }, hints);
      waypoints = waypoints || [];

      var preferredLayouts = hints.preferredLayouts,
          preferStraight = preferredLayouts.indexOf('straight') !== -1,
          repairedWaypoints;

      // just layout non-existing or simple connections
      // attempt to render straight lines, if required

      // attempt to layout a straight line
      repairedWaypoints = preferStraight && tryLayoutStraight(source, target, start, end, hints);

      if (repairedWaypoints) {
        return repairedWaypoints;
      }

      // try to layout from end
      repairedWaypoints = hints.connectionEnd && tryRepairConnectionEnd(target, source, end, waypoints);

      if (repairedWaypoints) {
        return repairedWaypoints;
      }

      // try to layout from start
      repairedWaypoints = hints.connectionStart && tryRepairConnectionStart(source, target, start, waypoints);

      if (repairedWaypoints) {
        return repairedWaypoints;
      }

      // or whether nothing seems to have changed
      if (!hints.connectionStart && !hints.connectionEnd && waypoints && waypoints.length) {
        return waypoints;
      }

      // simply reconnect if nothing else worked
      return connectRectangles(source, target, start, end, hints);
    }

    function inRange(a, start, end) {
      return a >= start && a <= end;
    }

    function isInRange(axis, a, b) {
      var size = {
        x: 'width',
        y: 'height'
      };

      return inRange(a[axis], b[axis], b[axis] + b[size[axis]]);
    }

    /**
     * Layout a straight connection
     *
     * @param {Bounds} source
     * @param {Bounds} target
     * @param {Point} start
     * @param {Point} end
     * @param {Object} [hints]
     *
     * @return {Array<Point>|null} waypoints if straight layout worked
     */
    export function tryLayoutStraight(source, target, start, end, hints) {
      var axis = {},
          primaryAxis,
          orientation;

      orientation = getOrientation(source, target);

      // only layout a straight connection if shapes are
      // horizontally or vertically aligned
      if (!/^(top|bottom|left|right)$/.test(orientation)) {
        return null;
      }

      if (/top|bottom/.test(orientation)) {
        primaryAxis = 'x';
      }

      if (/left|right/.test(orientation)) {
        primaryAxis = 'y';
      }

      if (hints.preserveDocking === 'target') {

        Iif (!isInRange(primaryAxis, end, source)) {
          return null;
        }

        axis[primaryAxis] = end[primaryAxis];

        return [
          {
            x: axis.x !== undefined ? axis.x : start.x,
            y: axis.y !== undefined ? axis.y : start.y,
            original: {
              x: axis.x !== undefined ? axis.x : start.x,
              y: axis.y !== undefined ? axis.y : start.y
            }
          },
          {
            x: end.x,
            y: end.y
          }
        ];

      } else {

        if (!isInRange(primaryAxis, start, target)) {
          return null;
        }

        axis[primaryAxis] = start[primaryAxis];

        return [
          {
            x: start.x,
            y: start.y
          },
          {
            x: axis.x !== undefined ? axis.x : end.x,
            y: axis.y !== undefined ? axis.y : end.y,
            original: {
              x: axis.x !== undefined ? axis.x : end.x,
              y: axis.y !== undefined ? axis.y : end.y
            }
          }
        ];
      }

    }

    /**
     * Repair a connection from start.
     *
     * @param {Bounds} moved
     * @param {Bounds} other
     * @param {Point} newDocking
     * @param {Array<Point>} points originalPoints from moved to other
     *
     * @return {Array<Point>|null} the repaired points between the two rectangles
     */
    function tryRepairConnectionStart(moved, other, newDocking, points) {
      return _tryRepairConnectionSide(moved, other, newDocking, points);
    }

    /**
     * Repair a connection from end.
     *
     * @param {Bounds} moved
     * @param {Bounds} other
     * @param {Point} newDocking
     * @param {Array<Point>} points originalPoints from moved to other
     *
     * @return {Array<Point>|null} the repaired points between the two rectangles
     */
    function tryRepairConnectionEnd(moved, other, newDocking, points) {
      var waypoints = points.slice().reverse();

      waypoints = _tryRepairConnectionSide(moved, other, newDocking, waypoints);

      return waypoints ? waypoints.reverse() : null;
    }

    /**
     * Repair a connection from one side that moved.
     *
     * @param {Bounds} moved
     * @param {Bounds} other
     * @param {Point} newDocking
     * @param {Array<Point>} points originalPoints from moved to other
     *
     * @return {Array<Point>} the repaired points between the two rectangles
     */
    function _tryRepairConnectionSide(moved, other, newDocking, points) {

      function needsRelayout(moved, other, points) {

        if (points.length < 3) {
          return true;
        }

        Iif (points.length > 4) {
          return false;
        }

        // relayout if two points overlap
        // this is most likely due to
        return !!find(points, function(p, idx) {
          var q = points[idx - 1];

          return q && pointDistance(p, q) < 3;
        });
      }

      function repairBendpoint(candidate, oldPeer, newPeer) {

        var alignment = pointsAligned(oldPeer, candidate);

        switch (alignment) {
        case 'v':
          // repair horizontal alignment
          return { x: newPeer.x, y: candidate.y };
        case 'h':
          // repair vertical alignment
          return { x: candidate.x, y: newPeer.y };
        }

        return { x: candidate.x, y: candidate. y };
      }

      function removeOverlapping(points, a, b) {
        var i;

        for (i = points.length - 2; i !== 0; i--) {

          // intersects (?) break, remove all bendpoints up to this one and relayout
          if (pointInRect(points[i], a, INTERSECTION_THRESHOLD) ||
              pointInRect(points[i], b, INTERSECTION_THRESHOLD)) {

            // return sliced old connection
            return points.slice(i);
          }
        }

        return points;
      }

      // (0) only repair what has layoutable bendpoints

      // (1) if only one bendpoint and on shape moved onto other shapes axis
      //     (horizontally / vertically), relayout

      if (needsRelayout(moved, other, points)) {
        return null;
      }

      var oldDocking = points[0],
          newPoints = points.slice(),
          slicedPoints;

      // (2) repair only last line segment and only if it was layouted before

      newPoints[0] = newDocking;
      newPoints[1] = repairBendpoint(newPoints[1], oldDocking, newDocking);

      // (3) if shape intersects with any bendpoint after repair,
      //     remove all segments up to this bendpoint and repair from there

      slicedPoints = removeOverlapping(newPoints, moved, other);

      if (slicedPoints !== newPoints) {
        return _tryRepairConnectionSide(moved, other, newDocking, slicedPoints);
      }

      return newPoints;
    }

    /**
     * Returns the manhattan directions connecting two rectangles
     * with the given orientation.
     *
     * Will always return the default layout, if it is specific
     * regarding sides already (trbl).
     *
     * @example
     *
     * getDirections('top'); // -> 'v:v'
     * getDirections('intersect'); // -> 't:t'
     *
     * getDirections('top-right', 'v:h'); // -> 'v:h'
     * getDirections('top-right', 'h:h'); // -> 'h:h'
     *
     *
     * @param {String} orientation
     * @param {String} defaultLayout
     *
     * @return {String}
     */
    function getDirections(orientation, defaultLayout) {

      // don't override specific trbl directions
      if (isExplicitDirections(defaultLayout)) {
        return defaultLayout;
      }

      switch (orientation) {
      case 'intersect':
        return 't:t';

      case 'top':
      case 'bottom':
        return 'v:v';

      case 'left':
      case 'right':
        return 'h:h';

      // 'top-left'
      // 'top-right'
      // 'bottom-left'
      // 'bottom-right'
      default:
        return defaultLayout;
      }
    }

    function isValidDirections(directions) {
      return directions && /^h|v|t|r|b|l:h|v|t|r|b|l$/.test(directions);
    }

    function isExplicitDirections(directions) {
      return directions && /t|r|b|l/.test(directions);
    }

    function invertOrientation(orientation) {
      return {
        'top': 'bottom',
        'bottom': 'top',
        'left': 'right',
        'right': 'left',
        'top-left': 'bottom-right',
        'bottom-right': 'top-left',
        'top-right': 'bottom-left',
        'bottom-left': 'top-right',
      }[orientation];
    }

    function getDockingPoint(point, rectangle, dockingDirection, targetOrientation) {

      // ensure we end up with a specific docking direction
      // based on the targetOrientation, if <h|v> is being passed

      if (dockingDirection === 'h') {
        dockingDirection = /left/.test(targetOrientation) ? 'l' : 'r';
      }

      if (dockingDirection === 'v') {
        dockingDirection = /top/.test(targetOrientation) ? 't' : 'b';
      }

      if (dockingDirection === 't') {
        return { original: point, x: point.x, y: rectangle.y };
      }

      if (dockingDirection === 'r') {
        return { original: point, x: rectangle.x + rectangle.width, y: point.y };
      }

      if (dockingDirection === 'b') {
        return { original: point, x: point.x, y: rectangle.y + rectangle.height };
      }

      Eif (dockingDirection === 'l') {
        return { original: point, x: rectangle.x, y: point.y };
      }

      throw new Error('unexpected dockingDirection: <' + dockingDirection + '>');
    }

    /**
     * Return list of waypoints with redundant ones filtered out.
     *
     * @example
     *
     * Original points:
     *
     *   [x] ----- [x] ------ [x]
     *                         |
     *                        [x] ----- [x] - [x]
     *
     * Filtered:
     *
     *   [x] ---------------- [x]
     *                         |
     *                        [x] ----------- [x]
     *
     * @param  {Array<Point>} waypoints
     *
     * @return {Array<Point>}
     */
    export function withoutRedundantPoints(waypoints) {
      return waypoints.reduce(function(points, p, idx) {

        var previous = points[points.length - 1],
            next = waypoints[idx + 1];

        if (!pointsOnLine(previous, next, p, 0)) {
          points.push(p);
        }

        return points;
      }, []);
    }