@metacell/geppetto-meta-ui
Version:
React components from geppetto-meta to create neuroscience applications and visualize data.
406 lines (395 loc) • 16.7 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
import React, { Component } from 'react';
import * as util from '../../utilities';
import Instance from '@metacell/geppetto-meta-core/model/Instance';
import IconText from './IconText';
import Typography from '@mui/material/Typography';
import ConnectivityTooltip from './ConnectivityTooltip';
var d3 = require('d3');
var classes = {
legends: "connectivity-plot-legends",
legendTitle: "connectivity-plot-legend-title"
};
var ConnectivityPlot = /*#__PURE__*/function (_Component) {
function ConnectivityPlot(props) {
var _this;
_classCallCheck(this, ConnectivityPlot);
_this = _callSuper(this, ConnectivityPlot, [props]);
_this.height = _this.props.size.height;
_this.width = _this.props.size.width;
_this.linkCache = {};
_this.defaultOptions = {
nodeType: function nodeType(node) {
if (node instanceof Instance) {
return node.getParent().getId();
} else {
return node.getPath().split('_')[0];
}
},
linkWeight: function linkWeight(conn) {
return 1;
},
linkType: function linkType(conn) {
return 1;
},
library: _this.props.modelFactory.geppettoModel.common
};
_this.setNodeColormap(_this.props.colorMap);
_this.subRef = /*#__PURE__*/React.createRef();
_this.tooltipRef = /*#__PURE__*/React.createRef();
return _this;
}
_inherits(ConnectivityPlot, _Component);
return _createClass(ConnectivityPlot, [{
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState, nextContext) {
return this.props.toolbarVisibility === nextProps.toolbarVisibility;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.setOptions();
this.setData(this.props.data);
this.setNodeColormap(this.props.colorMap);
this.draw();
this.forceUpdate();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.options !== this.props.options || prevProps.layout !== this.props.layout || this.options === null) {
this.setOptions();
}
this.setData(this.props.data);
this.setNodeColormap(this.props.colorMap);
this.draw();
}
/**
*
* Sets connectivity auxiliary functions
*
* @command setOptions()
*/
}, {
key: "setOptions",
value: function setOptions() {
this.options = this.defaultOptions;
if (this.props.linkType != null) {
this.options.linkType = this.props.linkType;
}
if (this.props.nodeType != null) {
this.options.nodeType = this.props.nodeType;
}
if (this.props.linkWeight != null) {
this.options.linkWeight = this.props.linkWeight;
}
if (this.props.library != null) {
this.options.library = this.props.library;
}
}
/**
*
* Creates dataset with provided data
*
* @command setData(data)
*
* @param data
*/
}, {
key: "setData",
value: function setData(data) {
this.dataset = {};
this.mapping = {};
this.mappingSize = 0;
this.dataset['root'] = data;
}
/**
*
* Sets nodeColormap
*
* @command setNodeColormap(nodeColormap)
*
* @param nodeColormap
*/
}, {
key: "setNodeColormap",
value: function setNodeColormap(nodeColormap) {
if (nodeColormap != null) {
this.nodeColormap = nodeColormap;
} else {
this.nodeColormap = this.defaultColorMapFunction();
}
}
/**
*
* Returns default colorScale
*
* @command defaultColorMapFunction()
*
*/
}, {
key: "defaultColorMapFunction",
value: function defaultColorMapFunction() {
var domain = this.props.names;
var range = this.props.colors;
return d3.scaleOrdinal(range).domain(domain);
}
/**
*
* Creates connections and draws layout
*
* @command draw()
*
*/
}, {
key: "draw",
value: function draw() {
if (this.createDataFromConnections()) {
this.drawLayout();
}
}
/**
*
* Creates data from connections
*
* @command createDataFromConnections()
*/
}, {
key: "createDataFromConnections",
value: function createDataFromConnections() {
var connectionVariables = this.props.modelFactory.getAllTypesOfType(this.options.library.connection)[0].getVariableReferences();
if (connectionVariables.length > 0) {
if (this.dataset['root'].getMetaType() === this.props.resources.INSTANCE_NODE) {
var subInstances = this.dataset['root'].getChildren();
this.dataset['nodes'] = [];
this.dataset['links'] = [];
for (var k = 0; k < subInstances.length; k++) {
var subInstance = subInstances[k];
if (subInstance.getMetaType() === this.props.resources.ARRAY_INSTANCE_NODE) {
var populationChildren = subInstance.getChildren();
for (var l = 0; l < populationChildren.length; l++) {
var populationChild = populationChildren[l];
this.createNode(populationChild.getId(), this.options.nodeType(populationChild));
}
}
}
for (var x = 0; x < connectionVariables.length; x++) {
var connectionVariable = connectionVariables[x];
var source = connectionVariable.getA();
var target = connectionVariable.getB();
var sourceId = source.getElements()[source.getElements().length - 1].getPath();
var targetId = target.getElements()[source.getElements().length - 1].getPath();
this.createLink(sourceId, targetId, this.options.linkType.bind(this)(connectionVariable, this.linkCache), this.options.linkWeight(connectionVariable));
}
}
this.dataset.nodeTypes = util.uniq(util.pluck(this.dataset.nodes, 'type')).sort();
this.dataset.linkTypes = util.uniq(util.pluck(this.dataset.links, 'type')).sort();
return true;
}
return false;
}
/**
*
* Prepocesses node degrees
*
* @command calculateNodeDegrees(normalize)
* @param normalize
*/
}, {
key: "calculateNodeDegrees",
value: function calculateNodeDegrees(normalize) {
var indegrees = util.countBy(this.dataset.links, function (link) {
return link.source;
});
var outdegrees = util.countBy(this.dataset.links, function (link) {
return link.target;
});
var maxDeg = 1;
this.dataset.nodes.forEach(function (node, idx) {
var idg = typeof indegrees[idx] === 'undefined' ? 0 : indegrees[idx];
var odg = typeof outdegrees[idx] === 'undefined' ? 0 : outdegrees[idx];
node.degree = idg + odg;
if (node.degree > maxDeg) {
maxDeg = node.degree;
}
});
if (normalize) {
this.dataset.nodes.forEach(function (node) {
node.degree /= maxDeg;
});
}
}
/**
*
* Creates node
*
* @command createNode(id, type)
*
* @param id
* @param type
*/
}, {
key: "createNode",
value: function createNode(id, type) {
if (!(id in this.mapping)) {
var nodeItem = {
id: id,
type: type
};
this.dataset['nodes'].push(nodeItem);
this.mapping[nodeItem['id']] = this.mappingSize;
this.mappingSize++;
}
}
/**
*
* Creates link
*
* @command createLink(sourceId, targetId, type, weight)
*
* @param sourceId
* @param targetId
* @param type
* @param weight
*/
}, {
key: "createLink",
value: function createLink(sourceId, targetId, type, weight) {
var linkItem = {
source: this.mapping[sourceId],
target: this.mapping[targetId],
type: type,
weight: weight
};
this.dataset['links'].push(linkItem);
}
/**
*
* Draws the layout
*
* @command drawLayout()
*
*/
}, {
key: "drawLayout",
value: function drawLayout() {
this.width = this.props.size.width;
this.height = this.props.size.height;
this.cleanCanvas();
this.svg = d3.select('#' + this.props.id).append('svg').attr('width', this.width).attr('height', this.height);
this.props.layout.draw(this);
}
/**
*
* Cleans the canvas
*
* @command cleanCanvas()
*
*/
}, {
key: "cleanCanvas",
value: function cleanCanvas() {
if (this.svg) {
this.svg.remove();
}
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
id = _this$props.id,
legendsVisibility = _this$props.legendsVisibility,
layout = _this$props.layout;
var legends = [];
if (layout && this.nodeColormap && this.dataset) {
var layoutLegends = layout.getLegends(this);
var _iterator = _createForOfIteratorHelper(layoutLegends),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var obj = _step.value;
if (obj.title) {
legends.push(/*#__PURE__*/React.createElement(Typography, {
key: obj.title,
className: classes.legendTitle,
variant: "h6",
gutterBottom: true
}, obj.title));
}
var domain = obj.colorScale.domain().slice().sort();
var _iterator2 = _createForOfIteratorHelper(domain.entries()),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
i = _step2$value[0],
v = _step2$value[1];
legends.push(/*#__PURE__*/React.createElement(IconText, {
key: v,
icon: "fa fa-square-full legend-item",
color: obj.colorScale(i),
subtitle: v,
width: '20px',
height: '20px'
}));
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
var plot = /*#__PURE__*/React.createElement("div", {
className: "connecticity-plot-plot"
}, /*#__PURE__*/React.createElement(ConnectivityTooltip, {
ref: this.tooltipRef,
layout: layout
}), /*#__PURE__*/React.createElement("div", {
id: id
}));
var show;
if (legends.length === 0 || !legendsVisibility) {
show = /*#__PURE__*/React.createElement("div", {
className: "plot-container"
}, plot);
} else {
show = /*#__PURE__*/React.createElement("div", {
className: "grid-container connectivity-plot-container"
}, /*#__PURE__*/React.createElement("div", {
className: "connectivity-plot-legends"
}, /*#__PURE__*/React.createElement("div", {
ref: this.subRef
}, legendsVisibility ? legends.map(function (entry) {
return entry;
}) : '')), plot);
}
return show;
}
}]);
}(Component);
export default ConnectivityPlot;