# all files / Github/diagram-js/lib/features/popup-menu/ PopupMenu.js

88% Statements 154/175
72.09% Branches 62/86
91.67% Functions 22/24
88% Lines 154/175

    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

    1×

    163×

    163×

    163×
    163×
    163×
    163×

    1×

    1×
    163×

    1×
    31×

    31×

    31×

    31×
    31×

    31×
    31×

    31×

    1×

    109×

    109×

    109×

    109×

    109×

    109×

    109×

    109×
    109×

    109×

    109×

    109×
    109×

    109×
    42×

    109×
    106×

    109×
    109×

    109×

    1×

    60×

    60×

    60×
    60×
    60×

    1×
    169×

    1×

    23×

    23×
    23×

    23×

    23×
    23×

    1×

    27×

    27×

    27×

    27×

    1×
    169×

    1×
    109×
    109×
    109×

    109×

    109×

    109×

    1×
    109×

    109×

    109×

    109×

    109×
    3×

    109×

    1×
    109×

    109×

    109×

    109×

    109×

    109×
    109×

    109×

    109×

    109×

    1×
    3×
    3×

    3×
    3×
    3×
    3×
    3×

    3×

    3×
    1×

    3×
    2×

    3×
    1×
    1×
    2×

    2×
    1×
    1×
    1×

    3×

    1×

    148×
    148×

    148×

    148×
    742×
    742×

    148×

    1×

    742×

    742×
    742×

    742×

    742×
    742×
    742×

    742×

    742×
    607×
    607×
    607×

    742×

    742×
    31×

    742×

    742×
    135×

    742×

    1×

    109×
    109×

    60×

    109×
    109×
    109×

    1×

    60×
    60×

    60×
    60×
    60×

    109×

    109×
    327×

     import {
      forEach,
      assign,
      find,
      matchPattern,
      isDefined
    } from 'min-dash';

    import {
      delegate as domDelegate,
      domify as domify,
      classes as domClasses,
      attr as domAttr,
      remove as domRemove
    } from 'min-dom';

    var DATA_REF = 'data-id';

    /**
     * A popup menu that can be used to display a list of actions anywhere in the canvas.
     *
     * @param {Object} config
     * @param {Boolean|Object} [config.scale={ min: 1.0, max: 1.5 }]
     * @param {Number} [config.scale.min]
     * @param {Number} [config.scale.max]
     * @param {EventBus} eventBus
     * @param {Canvas} canvas
     *
     * @class
     * @constructor
     */
    export default function PopupMenu(config, eventBus, canvas) {

      var scale = isDefined(config && config.scale) ? config.scale : {
        min: 1,
        max: 1.5
      };

      this._config = {
        scale: scale
      };

      this._eventBus = eventBus;
      this._canvas = canvas;
      this._providers = {};
      this._current = {};
    }

    PopupMenu.$inject = [
      'config.popupMenu',
      'eventBus',
      'canvas'
    ];

    /**
     * Registers a popup menu provider
     *
     * @param  {String} id
     * @param  {Object} provider
     *
     * @example
     *
     * popupMenu.registerProvider('myMenuID', {
     *   getEntries: function(element) {
     *     return [
     *       {
     *         id: 'entry-1',
     *         label: 'My Entry',
     *         action: 'alert("I have been clicked!")'
     *       }
     *     ];
     *   }
     * });
     */
    PopupMenu.prototype.registerProvider = function(id, provider) {
      this._providers[id] = provider;
    };

    /**
     * Determine if the popup menu has entries.
     *
     * @return {Boolean} true if empty
     */
    PopupMenu.prototype.isEmpty = function(element, providerId) {
      Iif (!element) {
        throw new Error('element parameter is missing');
      }

      Iif (!providerId) {
        throw new Error('providerId parameter is missing');
      }

      var provider = this._providers[providerId];

      var entries = provider.getEntries(element),
          headerEntries = provider.getHeaderEntries && provider.getHeaderEntries(element);

      var hasEntries = entries.length > 0,
          hasHeaderEntries = headerEntries && headerEntries.length > 0;

      return !hasEntries && !hasHeaderEntries;
    };

    /**
     * Create entries and open popup menu at given position
     *
     * @param  {Object} element
     * @param  {String} id provider id
     * @param  {Object} position
     *
     * @return {Object} popup menu instance
     */
    PopupMenu.prototype.open = function(element, id, position) {

      var provider = this._providers[id];

      Iif (!element) {
        throw new Error('Element is missing');
      }

      Iif (!provider) {
        throw new Error('Provider is not registered: ' + id);
      }

      Iif (!position) {
        throw new Error('the position argument is missing');
      }

      Iif (this.isOpen()) {
        this.close();
      }

      this._emit('open');

      var current = this._current = {
        provider: provider,
        className: id,
        element: element,
        position: position
      };

      Eif (provider.getHeaderEntries) {
        current.headerEntries = provider.getHeaderEntries(element);
      }

      current.entries = provider.getEntries(element);

      current.container = this._createContainer();

      var headerEntries = current.headerEntries || [],
          entries = current.entries || [];

      if (headerEntries.length) {
        current.container.appendChild(
          this._createEntries(current.headerEntries, 'djs-popup-header')
        );
      }

      if (entries.length) {
        current.container.appendChild(
          this._createEntries(current.entries, 'djs-popup-body')
        );
      }

      var canvas = this._canvas,
          parent = canvas.getContainer();

      this._attachContainer(current.container, parent, position.cursor);
    };

    /**
     * Removes the popup menu and unbinds the event handlers.
     */
    PopupMenu.prototype.close = function() {

      Iif (!this.isOpen()) {
        return;
      }

      this._emit('close');

      this._unbindHandlers();
      domRemove(this._current.container);
      this._current.container = null;
    };

    /**
     * Determine if an open popup menu exist.
     *
     * @return {Boolean} true if open
     */
    PopupMenu.prototype.isOpen = function() {
      return !!this._current.container;
    };

    /**
     * Trigger an action associated with an entry.
     *
     * @param {Object} event
     *
     * @return the result of the action callback, if any
     */
    PopupMenu.prototype.trigger = function(event) {

      // silence other actions
      event.preventDefault();

      var element = event.delegateTarget || event.target,
          entryId = domAttr(element, DATA_REF);

      var entry = this._getEntry(entryId);

      Eif (entry.action) {
        return entry.action.call(null, event, entry);
      }
    };

    /**
     * Gets an entry instance (either entry or headerEntry) by id.
     *
     * @param  {String} entryId
     *
     * @return {Object} entry instance
     */
    PopupMenu.prototype._getEntry = function(entryId) {

      var search = matchPattern({ id: entryId });

      var entry = find(this._current.entries, search) || find(this._current.headerEntries, search);

      Iif (!entry) {
        throw new Error('entry not found');
      }

      return entry;
    };

    PopupMenu.prototype._emit = function(eventName) {
      this._eventBus.fire('popupMenu.' + eventName);
    };

    /**
     * Creates the popup menu container.
     *
     * @return {Object} a DOM container
     */
    PopupMenu.prototype._createContainer = function() {
      var container = domify('<div class="djs-popup">'),
          position = this._current.position,
          className = this._current.className;

      assign(container.style, {
        position: 'absolute',
        left: position.x + 'px',
        top: position.y + 'px',
        visibility: 'hidden'
      });

      domClasses(container).add(className);

      return container;
    };

    /**
     * Attaches the container to the DOM and binds the event handlers.
     *
     * @param {Object} container
     * @param {Object} parent
     */
    PopupMenu.prototype._attachContainer = function(container, parent, cursor) {
      var self = this;

      // Event handler
      domDelegate.bind(container, '.entry' ,'click', function(event) {
        self.trigger(event);
      });

      this._updateScale(container);

      // Attach to DOM
      parent.appendChild(container);

      if (cursor) {
        this._assureIsInbounds(container, cursor);
      }

      // Add Handler
      this._bindHandlers();
    };

    /**
     * Updates popup style.transform with respect to the config and zoom level.
     *
     * @method _updateScale
     *
     * @param {Object} container
     */
    PopupMenu.prototype._updateScale = function(container) {
      var zoom = this._canvas.zoom();

      var scaleConfig = this._config.scale,
          minScale,
          maxScale,
          scale = zoom;

      Eif (scaleConfig !== true) {

        Iif (scaleConfig === false) {
          minScale = 1;
          maxScale = 1;
        } else {
          minScale = scaleConfig.min;
          maxScale = scaleConfig.max;
        }

        Iif (isDefined(minScale) && zoom < minScale) {
          scale = minScale;
        }

        Iif (isDefined(maxScale) && zoom > maxScale) {
          scale = maxScale;
        }

      }

      setTransform(container, 'scale(' + scale + ')');
    };

    /**
     * Make sure that the menu is always fully shown
     *
     * @method function
     *
     * @param  {Object} container
     * @param  {Position} cursor {x, y}
     */
    PopupMenu.prototype._assureIsInbounds = function(container, cursor) {
      var canvas = this._canvas,
          clientRect = canvas._container.getBoundingClientRect();

      var containerX = container.offsetLeft,
          containerY = container.offsetTop,
          containerWidth = container.scrollWidth,
          containerHeight = container.scrollHeight,
          overAxis = {},
          left, top;

      var cursorPosition = {
        x: cursor.x - clientRect.left,
        y: cursor.y - clientRect.top
      };

      if (containerX + containerWidth > clientRect.width) {
        overAxis.x = true;
      }

      if (containerY + containerHeight > clientRect.height) {
        overAxis.y = true;
      }

      if (overAxis.x && overAxis.y) {
        left = cursorPosition.x - containerWidth + 'px';
        top = cursorPosition.y - containerHeight + 'px';
      } else Iif (overAxis.x) {
        left = cursorPosition.x - containerWidth + 'px';
        top = cursorPosition.y + 'px';
      } else if (overAxis.y && cursorPosition.y < containerHeight) {
        left = cursorPosition.x + 'px';
        top = 10 + 'px';
      } else Iif (overAxis.y) {
        left = cursorPosition.x + 'px';
        top = cursorPosition.y - containerHeight + 'px';
      }

      assign(container.style, { left: left, top: top }, { visibility: 'visible', 'z-index': 1000 });
    };

    /**
     * Creates a list of entries and returns them as a DOM container.
     *
     * @param {Array<Object>} entries an array of entry objects
     * @param {String} className the class name of the entry container
     *
     * @return {Object} a DOM container
     */
    PopupMenu.prototype._createEntries = function(entries, className) {

      var entriesContainer = domify('<div>'),
          self = this;

      domClasses(entriesContainer).add(className);

      forEach(entries, function(entry) {
        var entryContainer = self._createEntry(entry, entriesContainer);
        entriesContainer.appendChild(entryContainer);
      });

      return entriesContainer;
    };

    /**
     * Creates a single entry and returns it as a DOM container.
     *
     * @param  {Object} entry
     *
     * @return {Object} a DOM container
     */
    PopupMenu.prototype._createEntry = function(entry) {

      Iif (!entry.id) {
        throw new Error ('every entry must have the id property set');
      }

      var entryContainer = domify('<div>'),
          entryClasses = domClasses(entryContainer);

      entryClasses.add('entry');

      Eif (entry.className) {
        entry.className.split(' ').forEach(function(className) {
          entryClasses.add(className);
        });
      }

      domAttr(entryContainer, DATA_REF, entry.id);

      if (entry.label) {
        var label = domify('<span>');
        label.textContent = entry.label;
        entryContainer.appendChild(label);
      }

      Iif (entry.imageUrl) {
        entryContainer.appendChild(domify('<img src="' + entry.imageUrl + '" />'));
      }

      if (entry.active === true) {
        entryClasses.add('active');
      }

      Iif (entry.disabled === true) {
        entryClasses.add('disabled');
      }

      if (entry.title) {
        entryContainer.title = entry.title;
      }

      return entryContainer;
    };

    /**
     * Binds the `close` method to 'contextPad.close' & 'canvas.viewbox.changed'.
     */
    PopupMenu.prototype._bindHandlers = function() {

      var eventBus = this._eventBus,
          self = this;

      function close() {
        self.close();
      }

      eventBus.once('contextPad.close', close);
      eventBus.once('canvas.viewbox.changing', close);
      eventBus.once('commandStack.changed', close);
    };

    /**
     * Unbinds the `close` method to 'contextPad.close' & 'canvas.viewbox.changing'.
     */
    PopupMenu.prototype._unbindHandlers = function() {

      var eventBus = this._eventBus,
          self = this;

      function close() {
        self.close();
      }

      eventBus.off('contextPad.close', close);
      eventBus.off('canvas.viewbox.changed', close);
      eventBus.off('commandStack.changed', close);
    };

    // helpers /////////////////////////////

    function setTransform(element, transform) {
      element.style['transform-origin'] = 'top left';

      [ '', '-ms-', '-webkit-' ].forEach(function(prefix) {
        element.style[prefix + 'transform'] = transform;
      });
    }