UNPKG

2.77 kBJavaScriptView Raw
1"use strict";
2/**
3 * Sigma.js Rendering Utils
4 * ===========================
5 *
6 * Helpers used by most renderers.
7 */
8var __read = (this && this.__read) || function (o, n) {
9 var m = typeof Symbol === "function" && o[Symbol.iterator];
10 if (!m) return o;
11 var i = m.call(o), r, ar = [], e;
12 try {
13 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
14 }
15 catch (error) { e = { error: error }; }
16 finally {
17 try {
18 if (r && !r.done && (m = i["return"])) m.call(i);
19 }
20 finally { if (e) throw e.error; }
21 }
22 return ar;
23};
24Object.defineProperty(exports, "__esModule", { value: true });
25exports.createNormalizationFunction = exports.getPixelRatio = exports.createElement = void 0;
26/**
27 * Function used to create DOM elements easily.
28 *
29 * @param {string} tag - Tag name of the element to create.
30 * @param {object} attributes - Attributes map.
31 * @return {HTMLElement}
32 */
33function createElement(tag, attributes) {
34 var element = document.createElement(tag);
35 if (!attributes)
36 return element;
37 for (var k in attributes) {
38 if (k === "style") {
39 for (var s in attributes[k])
40 element.style[s] = attributes[k][s];
41 }
42 else {
43 element.setAttribute(k, attributes[k]);
44 }
45 }
46 return element;
47}
48exports.createElement = createElement;
49/**
50 * Function returning the browser's pixel ratio.
51 *
52 * @return {number}
53 */
54function getPixelRatio() {
55 if (typeof window.devicePixelRatio !== "undefined")
56 return window.devicePixelRatio;
57 return 1;
58}
59exports.getPixelRatio = getPixelRatio;
60/**
61 * Factory returning a function normalizing the given node's position & size.
62 *
63 * @param {object} extent - Extent of the graph.
64 * @return {function}
65 */
66function createNormalizationFunction(extent) {
67 var _a = __read(extent.x, 2), minX = _a[0], maxX = _a[1], _b = __read(extent.y, 2), minY = _b[0], maxY = _b[1];
68 var ratio = Math.max(maxX - minX, maxY - minY);
69 if (ratio === 0)
70 ratio = 1;
71 var dX = (maxX + minX) / 2, dY = (maxY + minY) / 2;
72 var fn = function (data) {
73 return {
74 x: 0.5 + (data.x - dX) / ratio,
75 y: 0.5 + (data.y - dY) / ratio,
76 };
77 };
78 // TODO: possibility to apply this in batch over array of indices
79 fn.applyTo = function (data) {
80 data.x = 0.5 + (data.x - dX) / ratio;
81 data.y = 0.5 + (data.y - dY) / ratio;
82 };
83 fn.inverse = function (data) {
84 return {
85 x: dX + ratio * (data.x - 0.5),
86 y: dY + ratio * (data.y - 0.5),
87 };
88 };
89 fn.ratio = ratio;
90 return fn;
91}
92exports.createNormalizationFunction = createNormalizationFunction;