All files / core sigma.core.js

64.29% Statements 126/196
52.76% Branches 67/127
37.5% Functions 9/24
63.93% Lines 117/183

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 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    4x                                                                                                                                     11x       11x 11x                         11x 3x     8x 2x         11x 11x 5x         2x     11x             11x 45x 11x       11x     11x           11x       11x       11x       11x       11x       11x       11x         11x                                                   11x                   11x 11x     10x 10x           10x                 10x                       4x 14x   14x 10x 10x 10x     14x 1x   13x 13x     13x     13x 13x     13x       13x 13x                 4x 4x   4x           3x   3x   3x 3x 3x   3x   3x                                               4x     15x     15x 6x     9x 2x         15x         15x 10x 10x 10x   5x   15x 1x     14x 14x     14x 14x 5x 5x       9x   14x   14x 1x         13x 12x 12x         12x 4x                                                                               12x   12x                 4x 4x 4x 3x 3x 3x 3x 3x 3x                                             4x 14x   14x 14x       14x                   14x                                                                                                                 14x 14x 14x     4x 28x                                               4x 14x 14x                           4x                                                                                               4x                                                                   4x             4x      
import Dispatcher from "./domain/classes/Dispatcher";
 
const __instances = {};
 
/**
 * This is the sigma instances constructor. One instance of sigma represent
 * one graph. It is possible to represent this grapĥ with several renderers
 * at the same time. By default, the default renderer (WebGL + Canvas
 * polyfill) will be used as the only renderer, with the container specified
 * in the configuration.
 *
 * @param  {?*}    conf The configuration of the instance. There are a lot of
 *                      different recognized forms to instantiate sigma, check
 *                      example files, documentation in this file and unit
 *                      tests to know more.
 * @return {sigma}      The fresh new sigma instance.
 *
 * Instanciating sigma:
 * ********************
 * If no parameter is given to the constructor, the instance will be created
 * without any renderer or camera. It will just instantiate the graph, and
 * other modules will have to be instantiated through the public methods,
 * like "addRenderer" etc:
 *
 *  > s0 = new sigma();
 *  > s0.addRenderer({
 *  >   type: 'canvas',
 *  >   container: 'my-container-id'
 *  > });
 *
 * In most of the cases, sigma will simply be used with the default renderer.
 * Then, since the only required parameter is the DOM container, there are
 * some simpler way to call the constructor. The four following calls do the
 * exact same things:
 *
 *  > s1 = new sigma('my-container-id');
 *  > s2 = new sigma(document.getElementById('my-container-id'));
 *  > s3 = new sigma({
 *  >   container: document.getElementById('my-container-id')
 *  > });
 *  > s4 = new sigma({
 *  >   renderers: [{
 *  >     container: document.getElementById('my-container-id')
 *  >   }]
 *  > });
 *
 * Recognized parameters:
 * **********************
 * Here is the exhaustive list of every accepted parameters, when calling the
 * constructor with to top level configuration object (fourth case in the
 * previous examples):
 *
 *   {?string} id        The id of the instance. It will be generated
 *                       automatically if not specified.
 *   {?array}  renderers An array containing objects describing renderers.
 *   {?object} graph     An object containing an array of nodes and an array
 *                       of edges, to avoid having to add them by hand later.
 *   {?object} settings  An object containing instance specific settings that
 *                       will override the default ones defined in the object
 *                       sigma.settings.
 */
function sigma(conf) {
  // Local variables:
  // ****************
  let i;
  let l;
  let a;
  let id;
 
  Dispatcher.extend(this);
 
  // Private attributes:
  // *******************
  const _self = this;
  let _conf = conf || {};
 
  // Little shortcut:
  // ****************
  // The configuration is supposed to have a list of the configuration
  // objects for each renderer.
  //  - If there are no configuration at all, then nothing is done.
  //  - If there are no renderer list, the given configuration object will be
  //    considered as describing the first and only renderer.
  //  - If there are no renderer list nor "container" object, it will be
  //    considered as the container itself (a DOM element).
  //  - If the argument passed to sigma() is a string, it will be considered
  //    as the ID of the DOM container.
  if (typeof _conf === "string" || _conf instanceof HTMLElement)
    _conf = {
      renderers: [_conf]
    };
  else if (Object.prototype.toString.call(_conf) === "[object Array]")
    _conf = {
      renderers: _conf
    };
 
  // Also check "renderer" and "container" keys:
  const o = _conf.renderers || _conf.renderer || _conf.container;
  if (!_conf.renderers || _conf.renderers.length === 0)
    if (
      typeof o === "string" ||
      o instanceof HTMLElement ||
      (typeof o === "object" && "container" in o)
    )
      _conf.renderers = [o];
 
  // Recense the instance:
  Iif (_conf.id) {
    if (__instances[_conf.id])
      throw new Error(`sigma: Instance "${_conf.id}" already exists.`);
    Object.defineProperty(this, "id", {
      value: _conf.id
    });
  } else {
    id = 0;
    while (__instances[id]) id++;
    Object.defineProperty(this, "id", {
      value: `${id}`
    });
  }
  __instances[this.id] = this;
 
  // Initialize settings function:
  this.settings = sigma.classes.configurable(
    sigma.settings,
    _conf.settings || {}
  );
 
  // Initialize locked attributes:
  Object.defineProperty(this, "graph", {
    value: new sigma.classes.graph(this.settings),
    configurable: true
  });
  Object.defineProperty(this, "middlewares", {
    value: [],
    configurable: true
  });
  Object.defineProperty(this, "cameras", {
    value: {},
    configurable: true
  });
  Object.defineProperty(this, "renderers", {
    value: {},
    configurable: true
  });
  Object.defineProperty(this, "renderersPerCamera", {
    value: {},
    configurable: true
  });
  Object.defineProperty(this, "cameraFrames", {
    value: {},
    configurable: true
  });
  Object.defineProperty(this, "camera", {
    get() {
      return this.cameras[0];
    }
  });
  Object.defineProperty(this, "events", {
    value: [
      "click",
      "rightClick",
      "clickStage",
      "doubleClickStage",
      "rightClickStage",
      "clickNode",
      "clickNodes",
      "doubleClickNode",
      "doubleClickNodes",
      "rightClickNode",
      "rightClickNodes",
      "overNode",
      "overNodes",
      "outNode",
      "outNodes",
      "downNode",
      "downNodes",
      "upNode",
      "upNodes"
    ],
    configurable: true
  });
 
  // Add a custom handler, to redispatch events from renderers:
  this._handler = e => {
    const data = {};
    Object.keys(e.data).forEach(key => {
      data[key] = e.data[key];
    });
    data.renderer = e.target;
    this.dispatchEvent(e.type, data);
  };
 
  // Initialize renderers:
  a = _conf.renderers || [];
  for (i = 0, l = a.length; i < l; i++) this.addRenderer(a[i]);
 
  // Initialize middlewares:
  a = _conf.middlewares || [];
  for (i = 0, l = a.length; i < l; i++)
    this.middlewares.push(
      typeof a[i] === "string" ? sigma.middlewares[a[i]] : a[i]
    );
 
  // Check if there is already a graph to fill in:
  Iif (typeof _conf.graph === "object" && _conf.graph) {
    this.graph.read(_conf.graph);
 
    // If a graph is given to the to the instance, the "refresh" method is
    // directly called:
    this.refresh();
  }
 
  // Deal with resize:
  window.addEventListener("resize", () => {
    if (_self.settings) _self.refresh();
  });
}
 
/**
 * This methods will instantiate and reference a new camera. If no id is
 * specified, then an automatic id will be generated.
 *
 * @param  {?string}              id Eventually the camera id.
 * @return {sigma.classes.camera}    The fresh new camera instance.
 */
sigma.prototype.addCamera = function addCamera(id) {
  const self = this;
 
  if (!arguments.length) {
    id = 0;
    while (this.cameras[`${id}`]) id++;
    id = `${id}`;
  }
 
  if (this.cameras[id])
    throw new Error(`sigma.addCamera: The camera "${id}" already exists.`);
 
  const camera = new sigma.classes.camera(id, this.graph, this.settings);
  this.cameras[id] = camera;
 
  // Add a quadtree to the camera:
  camera.quadtree = new sigma.classes.quad();
 
  // Add an edgequadtree to the camera:
  Eif (sigma.classes.edgequad !== undefined) {
    camera.edgequadtree = new sigma.classes.edgequad();
  }
 
  camera.bind("coordinatesUpdated", () =>
    self.renderCamera(camera, camera.isAnimated)
  );
 
  this.renderersPerCamera[id] = [];
  return camera;
};
 
/**
 * This method kills a camera, and every renderer attached to it.
 *
 * @param  {string|camera} v The camera to kill or its ID.
 * @return {sigma}           Returns the instance.
 */
sigma.prototype.killCamera = function killCamera(v) {
  v = typeof v === "string" ? this.cameras[v] : v;
 
  if (!v) throw new Error("sigma.killCamera: The camera is undefined.");
 
  let i;
 
  let l;
 
  const a = this.renderersPerCamera[v.id];
 
  for (l = a.length, i = l - 1; i >= 0; i--) this.killRenderer(a[i]);
 
  delete this.renderersPerCamera[v.id];
  delete this.cameraFrames[v.id];
  delete this.cameras[v.id];
 
  Iif (v.kill) v.kill();
 
  return this;
};
 
/**
 * This methods will instantiate and reference a new renderer. The "type"
 * argument can be the constructor or its name in the "sigma.renderers"
 * package. If no type is specified, then "sigma.renderers.def" will be used.
 * If no id is specified, then an automatic id will be generated.
 *
 * @param  {?object}  options Eventually some options to give to the renderer
 *                            constructor.
 * @return {renderer}         The fresh new renderer instance.
 *
 * Recognized parameters:
 * **********************
 * Here is the exhaustive list of every accepted parameters in the "options"
 * object:
 *
 *   {?string}            id     Eventually the renderer id.
 *   {?(function|string)} type   Eventually the renderer constructor or its
 *                               name in the "sigma.renderers" package.
 *   {?(camera|string)}   camera Eventually the renderer camera or its
 *                               id.
 */
sigma.prototype.addRenderer = function addRenderer(options) {
  let id;
  let fn;
  let o = options || {};
 
  // Polymorphism:
  if (typeof o === "string")
    o = {
      container: document.getElementById(o)
    };
  else if (o instanceof HTMLElement)
    o = {
      container: o
    };
 
  // If the container still is a string, we get it by id
  Iif (typeof o.container === "string") {
    o.container = document.getElementById(o.container);
  }
 
  // Reference the new renderer:
  if (!("id" in o)) {
    id = 0;
    while (this.renderers[`${id}`]) id++;
    id = `${id}`;
    // eslint-disable-next-line prefer-destructuring
  } else id = o.id;
 
  if (this.renderers[id])
    throw new Error(`sigma.addRenderer: The renderer "${id}" already exists.`);
 
  // Find the good constructor:
  fn = typeof o.type === "function" ? o.type : sigma.renderers[o.type];
  fn = fn || sigma.renderers.def;
 
  // Find the good camera:
  const findGoodCamera = () => {
    if ("camera" in o) {
      Eif (o.camera instanceof sigma.classes.camera) {
        return o.camera;
      }
      return this.cameras[o.camera] || this.addCamera(o.camera);
    }
    return this.addCamera();
  };
  const camera = findGoodCamera();
 
  if (this.cameras[camera.id] !== camera)
    throw new Error(
      "sigma.addRenderer: The camera is not properly referenced."
    );
 
  // Instantiate:
  const renderer = new fn(this.graph, camera, this.settings, o);
  this.renderers[id] = renderer;
  Object.defineProperty(renderer, "id", {
    value: id
  });
 
  // Bind events:
  if (renderer.bind)
    renderer.bind(
      [
        "click",
        "rightClick",
        "clickStage",
        "doubleClickStage",
        "rightClickStage",
        "clickNode",
        "clickNodes",
        "clickEdge",
        "clickEdges",
        "doubleClickNode",
        "doubleClickNodes",
        "doubleClickEdge",
        "doubleClickEdges",
        "rightClickNode",
        "rightClickNodes",
        "rightClickEdge",
        "rightClickEdges",
        "overNode",
        "overNodes",
        "overEdge",
        "overEdges",
        "outNode",
        "outNodes",
        "outEdge",
        "outEdges",
        "downNode",
        "downNodes",
        "downEdge",
        "downEdges",
        "upNode",
        "upNodes",
        "upEdge",
        "upEdges"
      ],
      this._handler
    );
 
  // Reference the renderer by its camera:
  this.renderersPerCamera[camera.id].push(renderer);
 
  return renderer;
};
 
/**
 * This method kills a renderer.
 *
 * @param  {string|renderer} v The renderer to kill or its ID.
 * @return {sigma}             Returns the instance.
 */
sigma.prototype.killRenderer = function killRenderer(v) {
  v = typeof v === "string" ? this.renderers[v] : v;
  if (!v) throw new Error("sigma.killRenderer: The renderer is undefined.");
  const a = this.renderersPerCamera[v.camera.id];
  const i = a.indexOf(v);
  Eif (i >= 0) a.splice(i, 1);
  Eif (v.kill) v.kill();
  delete this.renderers[v.id];
  return this;
};
 
/**
 * This method calls the "render" method of each renderer, with the same
 * arguments than the "render" method, but will also check if the renderer
 * has a "process" method, and call it if it exists.
 *
 * It is useful for quadtrees or WebGL processing, for instance.
 *
 * @param  {?object}  options Eventually some options to give to the refresh
 *                            method.
 * @return {sigma}            Returns the instance itself.
 *
 * Recognized parameters:
 * **********************
 * Here is the exhaustive list of every accepted parameters in the "options"
 * object:
 *
 *   {?boolean} skipIndexation A flag specifying wether or not the refresh
 *                             function should reindex the graph in the
 *                             quadtrees or not (default: false).
 */
sigma.prototype.refresh = function refresh(options) {
  const middlewares = this.middlewares || [];
  let bounds;
  let prefix = 0;
  options = options || {};
 
  // Call each middleware:
 
  middlewares.forEach((mw, i) => {
    mw.call(
      this,
      i === 0 ? "" : `tmp${prefix}:`,
      i === middlewares.length - 1 ? "ready:" : `tmp${++prefix}:`
    );
  });
 
  // Then, for each camera, call the "rescale" middleware, unless the
  // settings specify not to:
  Object.keys(this.cameras).forEach(camId => {
    const cam = this.cameras[camId];
    if (
      cam.settings("autoRescale") &&
      this.renderersPerCamera[cam.id] &&
      this.renderersPerCamera[cam.id].length
    )
      sigma.middlewares.rescale.call(
        this,
        middlewares.length ? "ready:" : "",
        cam.readPrefix,
        {
          width: this.renderersPerCamera[cam.id][0].width,
          height: this.renderersPerCamera[cam.id][0].height
        }
      );
    else
      sigma.middlewares.copy.call(
        this,
        middlewares.length ? "ready:" : "",
        cam.readPrefix
      );
 
    if (!options.skipIndexation) {
      // Find graph boundaries:
      bounds = sigma.utils.geom.getBoundaries(this.graph, cam.readPrefix);
 
      // Refresh quadtree:
      cam.quadtree.index(this.graph.nodes(), {
        prefix: cam.readPrefix,
        bounds: {
          x: bounds.minX,
          y: bounds.minY,
          width: bounds.maxX - bounds.minX,
          height: bounds.maxY - bounds.minY
        }
      });
 
      // Refresh edgequadtree:
      if (
        cam.edgequadtree !== undefined &&
        cam.settings("drawEdges") &&
        cam.settings("enableEdgeHovering")
      ) {
        cam.edgequadtree.index(this.graph, {
          prefix: cam.readPrefix,
          bounds: {
            x: bounds.minX,
            y: bounds.minY,
            width: bounds.maxX - bounds.minX,
            height: bounds.maxY - bounds.minY
          }
        });
      }
    }
  });
 
  this._forEachRenderer("process");
  this.render();
  return this;
};
 
sigma.prototype._forEachRenderer = function _forEachRenderer(name) {
  Object.keys(this.renderers).forEach(key => {
    const renderer = this.renderers[key];
    if (renderer[name]) {
      if (this.settings("skipErrors")) {
        try {
          renderer[name]();
        } catch (e) {
          console.log(
            `Warning: The renderer "${key}" crashed on ".${name}()"`,
            e
          );
        }
      } else {
        renderer[name]();
      }
    }
  });
};
 
/**
 * This method calls the "render" method of each renderer.
 *
 * @return {sigma} Returns the instance itself.
 */
sigma.prototype.render = function render() {
  this._forEachRenderer("render");
  return this;
};
 
/**
 * This method calls the "render" method of each renderer that is bound to
 * the specified camera. To improve the performances, if this method is
 * called too often, the number of effective renderings is limitated to one
 * per frame, unless you are using the "force" flag.
 *
 * @param  {sigma.classes.camera} camera The camera to render.
 * @param  {?boolean}             force  If true, will render the camera
 *                                       directly.
 * @return {sigma}                       Returns the instance itself.
 */
sigma.prototype.renderCamera = function renderCamera(camera, force) {
  let i;
 
  let l;
 
  let a;
 
  const self = this;
 
  if (force) {
    a = this.renderersPerCamera[camera.id];
    for (i = 0, l = a.length; i < l; i++)
      if (this.settings("skipErrors"))
        try {
          a[i].render();
        } catch (e) {
          if (this.settings("verbose"))
            console.log(
              `Warning: The renderer "${a[i].id}" crashed on ".render()"`
            );
        }
      else a[i].render();
  } else if (!this.cameraFrames[camera.id]) {
    a = this.renderersPerCamera[camera.id];
    for (i = 0, l = a.length; i < l; i++)
      if (this.settings("skipErrors"))
        try {
          a[i].render();
        } catch (e) {
          if (this.settings("verbose"))
            console.log(
              `Warning: The renderer "${a[i].id}" crashed on ".render()"`
            );
        }
      else a[i].render();
 
    this.cameraFrames[camera.id] = requestAnimationFrame(() => {
      delete self.cameraFrames[camera.id];
    });
  }
 
  return this;
};
 
/**
 * This method calls the "kill" method of each module and destroys any
 * reference from the instance.
 */
sigma.prototype.kill = function kill() {
  // Dispatching event
  this.dispatchEvent("kill");
 
  // Kill graph:
  this.graph.kill();
 
  // Kill middlewares:
  delete this.middlewares;
 
  // Kill each renderer:
  Object.keys(this.renderers).forEach(key =>
    this.killRenderer(this.renderers[key])
  );
 
  // Kill each camera:
  Object.keys(this.cameras).forEach(key => this.killCamera(this.cameras[key]));
 
  delete this.renderers;
  delete this.cameras;
 
  // Kill everything else:
  Object.keys(this).forEach(key => delete this[key]);
 
  delete __instances[this.id];
};
 
/**
 * Returns a clone of the instances object or a specific running instance.
 *
 * @param  {?string} id Eventually an instance ID.
 * @return {object}     The related instance or a clone of the instances
 *                      object.
 */
sigma.instances = function instances(id) {
  return arguments.length ? __instances[id] : { ...__instances };
};
 
/**
 * The current version of sigma:
 */
sigma.version = "1.2.1";
 
export default sigma;