smiles-drawer
Version:
A SMILES drawer and parser. Generate molecular structure depictions in pure JavaScript.
1,580 lines (1,346 loc) • 370 kB
JavaScript
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
//@ts-check
var Drawer = require('./src/Drawer');
var Parser = require('./src/Parser');
// Detect SSR (server side rendering)
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* The SmilesDrawer namespace.
* @typicalname SmilesDrawer
*/
var SmilesDrawer = {
Version: '1.0.0'
};
SmilesDrawer.Drawer = Drawer;
SmilesDrawer.Parser = Parser;
/**
* Cleans a SMILES string (removes non-valid characters)
*
* @static
* @param {String} smiles A SMILES string.
* @returns {String} The clean SMILES string.
*/
SmilesDrawer.clean = function (smiles) {
return smiles.replace(/[^A-Za-z0-9@\.\+\-\?!\(\)\[\]\{\}/\\=#\$:\*]/g, '');
};
/**
* Applies the smiles drawer draw function to each canvas element that has a smiles string in the data-smiles attribute.
*
* @static
* @param {Object} options SmilesDrawer options.
* @param {String} [selector='canvas[data-smiles]'] Selectors for the draw areas (canvas elements).
* @param {String} [themeName='light'] The theme to apply.
* @param {Function} [onError='null'] A callback function providing an error object.
*/
SmilesDrawer.apply = function (options) {
var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'canvas[data-smiles]';
var themeName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'light';
var onError = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var smilesDrawer = new Drawer(options);
var elements = document.querySelectorAll(selector);
var _loop = function _loop() {
var element = elements[i];
SmilesDrawer.parse(element.getAttribute('data-smiles'), function (tree) {
smilesDrawer.draw(tree, element, themeName, false);
}, function (err) {
if (onError) {
onError(err);
}
});
};
for (var i = 0; i < elements.length; i++) {
_loop();
}
};
/**
* Parses the entered smiles string.
*
* @static
* @param {String} smiles A SMILES string.
* @param {Function} successCallback A callback that is called on success with the parse tree.
* @param {Function} errorCallback A callback that is called with the error object on error.
*/
SmilesDrawer.parse = function (smiles, successCallback, errorCallback) {
try {
if (successCallback) {
successCallback(Parser.parse(smiles));
}
} catch (err) {
if (errorCallback) {
errorCallback(err);
}
}
};
if (canUseDOM) {
window.SmilesDrawer = SmilesDrawer;
}
// There be dragons (polyfills)
if (!Array.prototype.fill) {
Object.defineProperty(Array.prototype, 'fill', {
value: function value(_value) {
// Steps 1-2.
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ? len : end >> 0;
// Step 11.
var final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
// Step 12.
while (k < final) {
O[k] = _value;
k++;
}
// Step 13.
return O;
}
});
}
module.exports = SmilesDrawer;
},{"./src/Drawer":5,"./src/Parser":10}],2:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//@ts-check
/**
* A static class containing helper functions for array-related tasks.
*/
var ArrayHelper = function () {
function ArrayHelper() {
_classCallCheck(this, ArrayHelper);
}
_createClass(ArrayHelper, null, [{
key: 'clone',
/**
* Clone an array or an object. If an object is passed, a shallow clone will be created.
*
* @static
* @param {*} arr The array or object to be cloned.
* @returns {*} A clone of the array or object.
*/
value: function clone(arr) {
var out = Array.isArray(arr) ? Array() : {};
for (var key in arr) {
var value = arr[key];
if (typeof value.clone === 'function') {
out[key] = value.clone();
} else {
out[key] = (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' ? ArrayHelper.clone(value) : value;
}
}
return out;
}
/**
* Returns a boolean indicating whether or not the two arrays contain the same elements.
* Only supports 1d, non-nested arrays.
*
* @static
* @param {Array} arrA An array.
* @param {Array} arrB An array.
* @returns {Boolean} A boolean indicating whether or not the two arrays contain the same elements.
*/
}, {
key: 'equals',
value: function equals(arrA, arrB) {
if (arrA.length !== arrB.length) {
return false;
}
var tmpA = arrA.slice().sort();
var tmpB = arrB.slice().sort();
for (var i = 0; i < tmpA.length; i++) {
if (tmpA[i] !== tmpB[i]) {
return false;
}
}
return true;
}
/**
* Returns a string representation of an array. If the array contains objects with an id property, the id property is printed for each of the elements.
*
* @static
* @param {Object[]} arr An array.
* @param {*} arr[].id If the array contains an object with the property 'id', the properties value is printed. Else, the array elements value is printend.
* @returns {String} A string representation of the array.
*/
}, {
key: 'print',
value: function print(arr) {
if (arr.length == 0) {
return '';
}
var s = '(';
for (var i = 0; i < arr.length; i++) {
s += arr[i].id ? arr[i].id + ', ' : arr[i] + ', ';
}
s = s.substring(0, s.length - 2);
return s + ')';
}
/**
* Run a function for each element in the array. The element is supplied as an argument for the callback function
*
* @static
* @param {Array} arr An array.
* @param {Function} callback The callback function that is called for each element.
*/
}, {
key: 'each',
value: function each(arr, callback) {
for (var i = 0; i < arr.length; i++) {
callback(arr[i]);
}
}
/**
* Return the array element from an array containing objects, where a property of the object is set to a given value.
*
* @static
* @param {Array} arr An array.
* @param {(String|Number)} property A property contained within an object in the array.
* @param {(String|Number)} value The value of the property.
* @returns {*} The array element matching the value.
*/
}, {
key: 'get',
value: function get(arr, property, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i][property] == value) {
return arr[i];
}
}
}
/**
* Checks whether or not an array contains a given value. the options object passed as a second argument can contain three properties. value: The value to be searched for. property: The property that is to be searched for a given value. func: A function that is used as a callback to return either true or false in order to do a custom comparison.
*
* @static
* @param {Array} arr An array.
* @param {Object} options See method description.
* @param {*} options.value The value for which to check.
* @param {String} [options.property=undefined] The property on which to check.
* @param {Function} [options.func=undefined] A custom property function.
* @returns {Boolean} A boolean whether or not the array contains a value.
*/
}, {
key: 'contains',
value: function contains(arr, options) {
if (!options.property && !options.func) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == options.value) {
return true;
}
}
} else if (options.func) {
for (var _i = 0; _i < arr.length; _i++) {
if (options.func(arr[_i])) {
return true;
}
}
} else {
for (var _i2 = 0; _i2 < arr.length; _i2++) {
if (arr[_i2][options.property] == options.value) {
return true;
}
}
}
return false;
}
/**
* Returns an array containing the intersection between two arrays. That is, values that are common to both arrays.
*
* @static
* @param {Array} arrA An array.
* @param {Array} arrB An array.
* @returns {Array} The intersecting vlaues.
*/
}, {
key: 'intersection',
value: function intersection(arrA, arrB) {
var intersection = new Array();
for (var i = 0; i < arrA.length; i++) {
for (var j = 0; j < arrB.length; j++) {
if (arrA[i] === arrB[j]) {
intersection.push(arrA[i]);
}
}
}
return intersection;
}
/**
* Returns an array of unique elements contained in an array.
*
* @static
* @param {Array} arr An array.
* @returns {Array} An array of unique elements contained within the array supplied as an argument.
*/
}, {
key: 'unique',
value: function unique(arr) {
var contains = {};
return arr.filter(function (i) {
// using !== instead of hasOwnProperty (http://andrew.hedges.name/experiments/in/)
return contains[i] !== undefined ? false : contains[i] = true;
});
}
/**
* Count the number of occurences of a value in an array.
*
* @static
* @param {Array} arr An array.
* @param {*} value A value to be counted.
* @returns {Number} The number of occurences of a value in the array.
*/
}, {
key: 'count',
value: function count(arr, value) {
var count = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
count++;
}
}
return count;
}
/**
* Toggles the value of an array. If a value is not contained in an array, the array returned will contain all the values of the original array including the value. If a value is contained in an array, the array returned will contain all the values of the original array excluding the value.
*
* @static
* @param {Array} arr An array.
* @param {*} value A value to be toggled.
* @returns {Array} The toggled array.
*/
}, {
key: 'toggle',
value: function toggle(arr, value) {
var newArr = Array();
var removed = false;
for (var i = 0; i < arr.length; i++) {
// Do not copy value if it exists
if (arr[i] !== value) {
newArr.push(arr[i]);
} else {
// The element was not copied to the new array, which
// means it was removed
removed = true;
}
}
// If the element was not removed, then it was not in the array
// so add it
if (!removed) {
newArr.push(value);
}
return newArr;
}
/**
* Remove a value from an array.
*
* @static
* @param {Array} arr An array.
* @param {*} value A value to be removed.
* @returns {Array} A new array with the element with a given value removed.
*/
}, {
key: 'remove',
value: function remove(arr, value) {
var tmp = Array();
for (var i = 0; i < arr.length; i++) {
if (arr[i] !== value) {
tmp.push(arr[i]);
}
}
return tmp;
}
/**
* Remove a value from an array with unique values.
*
* @static
* @param {Array} arr An array.
* @param {*} value A value to be removed.
* @returns {Array} An array with the element with a given value removed.
*/
}, {
key: 'removeUnique',
value: function removeUnique(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
/**
* Remove all elements contained in one array from another array.
*
* @static
* @param {Array} arrA The array to be filtered.
* @param {Array} arrB The array containing elements that will be removed from the other array.
* @returns {Array} The filtered array.
*/
}, {
key: 'removeAll',
value: function removeAll(arrA, arrB) {
return arrA.filter(function (item) {
return arrB.indexOf(item) === -1;
});
}
/**
* Merges two arrays and returns the result. The first array will be appended to the second array.
*
* @static
* @param {Array} arrA An array.
* @param {Array} arrB An array.
* @returns {Array} The merged array.
*/
}, {
key: 'merge',
value: function merge(arrA, arrB) {
var arr = new Array(arrA.length + arrB.length);
for (var i = 0; i < arrA.length; i++) {
arr[i] = arrA[i];
}
for (var _i3 = 0; _i3 < arrB.length; _i3++) {
arr[arrA.length + _i3] = arrB[_i3];
}
return arr;
}
/**
* Checks whether or not an array contains all the elements of another array, without regard to the order.
*
* @static
* @param {Array} arrA An array.
* @param {Array} arrB An array.
* @returns {Boolean} A boolean indicating whether or not both array contain the same elements.
*/
}, {
key: 'containsAll',
value: function containsAll(arrA, arrB) {
var containing = 0;
for (var i = 0; i < arrA.length; i++) {
for (var j = 0; j < arrB.length; j++) {
if (arrA[i] === arrB[j]) {
containing++;
}
}
}
return containing === arrB.length;
}
/**
* Sort an array of atomic number information. Where the number is indicated as x, x.y, x.y.z, ...
*
* @param {Object[]} arr An array of vertex ids with their associated atomic numbers.
* @param {Number} arr[].vertexId A vertex id.
* @param {String} arr[].atomicNumber The atomic number associated with the vertex id.
* @returns {Object[]} The array sorted by atomic number. Example of an array entry: { atomicNumber: 2, vertexId: 5 }.
*/
}, {
key: 'sortByAtomicNumberDesc',
value: function sortByAtomicNumberDesc(arr) {
var map = arr.map(function (e, i) {
return { index: i, value: e.atomicNumber.split('.').map(Number) };
});
map.sort(function (a, b) {
var min = Math.min(b.value.length, a.value.length);
var i = 0;
while (i < min && b.value[i] === a.value[i]) {
i++;
}
return i === min ? b.value.length - a.value.length : b.value[i] - a.value[i];
});
return map.map(function (e) {
return arr[e.index];
});
}
/**
* Copies a an n-dimensional array.
*
* @param {Array} arr The array to be copied.
* @returns {Array} The copy.
*/
}, {
key: 'deepCopy',
value: function deepCopy(arr) {
var newArr = Array();
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (item instanceof Array) {
newArr[i] = ArrayHelper.deepCopy(item);
} else {
newArr[i] = item;
}
}
return newArr;
}
}]);
return ArrayHelper;
}();
module.exports = ArrayHelper;
},{}],3:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//@ts-check
var ArrayHelper = require('./ArrayHelper');
var Vertex = require('./Vertex');
var Ring = require('./Ring');
/**
* A class representing an atom.
*
* @property {String} element The element symbol of this atom. Single-letter symbols are always uppercase. Examples: H, C, F, Br, Si, ...
* @property {Boolean} drawExplicit A boolean indicating whether or not this atom is drawn explicitly (for example, a carbon atom). This overrides the default behaviour.
* @property {Object[]} ringbonds An array containing the ringbond ids and bond types as specified in the original SMILE.
* @property {String} branchBond The branch bond as defined in the SMILES.
* @property {Number} ringbonds[].id The ringbond id as defined in the SMILES.
* @property {String} ringbonds[].bondType The bond type of the ringbond as defined in the SMILES.
* @property {Number[]} rings The ids of rings which contain this atom.
* @property {String} bondType The bond type associated with this array. Examples: -, =, #, ...
* @property {Boolean} isBridge A boolean indicating whether or not this atom is part of a bridge in a bridged ring (contained by the largest ring).
* @property {Boolean} isBridgeNode A boolean indicating whether or not this atom is a bridge node (a member of the largest ring in a bridged ring which is connected to a bridge-atom).
* @property {Number[]} originalRings Used to back up rings when they are replaced by a bridged ring.
* @property {Number} bridgedRing The id of the bridged ring if the atom is part of a bridged ring.
* @property {Number[]} anchoredRings The ids of the rings that are anchored to this atom. The centers of anchored rings are translated when this atom is translated.
* @property {Object} bracket If this atom is defined as a bracket atom in the original SMILES, this object contains all the bracket information. Example: { hcount: {Number}, charge: ['--', '-', '+', '++'], isotope: {Number} }.
* @property {Number} plane Specifies on which "plane" the atoms is in stereochemical deptictions (-1 back, 0 middle, 1 front).
* @property {Object[]} attachedPseudoElements A map with containing information for pseudo elements or concatinated elements. The key is comprised of the element symbol and the hydrogen count.
* @property {String} attachedPseudoElement[].element The element symbol.
* @property {Number} attachedPseudoElement[].count The number of occurences that match the key.
* @property {Number} attachedPseudoElement[].hyrogenCount The number of hydrogens attached to each atom matching the key.
* @property {Boolean} hasAttachedPseudoElements A boolean indicating whether or not this attom will be drawn with an attached pseudo element or concatinated elements.
* @property {Boolean} isDrawn A boolean indicating whether or not this atom is drawn. In contrast to drawExplicit, the bond is drawn neither.
* @property {Boolean} isConnectedToRing A boolean indicating whether or not this atom is directly connected (but not a member of) a ring.
* @property {String[]} neighbouringElements An array containing the element symbols of neighbouring atoms.
* @property {Boolean} isPartOfAromaticRing A boolean indicating whether or not this atom is part of an explicitly defined aromatic ring. Example: c1ccccc1.
* @property {Number} bondCount The number of bonds in which this atom is participating.
* @property {String} chirality The chirality of this atom if it is a stereocenter (R or S).
* @property {Number} priority The priority of this atom acording to the CIP rules, where 0 is the highest priority.
* @property {Boolean} mainChain A boolean indicating whether or not this atom is part of the main chain (used for chirality).
* @property {String} hydrogenDirection The direction of the hydrogen, either up or down. Only for stereocenters with and explicit hydrogen.
* @property {Number} subtreeDepth The depth of the subtree coming from a stereocenter.
*/
var Atom = function () {
/**
* The constructor of the class Atom.
*
* @param {String} element The one-letter code of the element.
* @param {String} [bondType='-'] The type of the bond associated with this atom.
*/
function Atom(element) {
var bondType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';
_classCallCheck(this, Atom);
this.element = element.length === 1 ? element.toUpperCase() : element;
this.drawExplicit = false;
this.ringbonds = Array();
this.rings = Array();
this.bondType = bondType;
this.branchBond = null;
this.isBridge = false;
this.isBridgeNode = false;
this.originalRings = Array();
this.bridgedRing = null;
this.anchoredRings = Array();
this.bracket = null;
this.plane = 0;
this.attachedPseudoElements = {};
this.hasAttachedPseudoElements = false;
this.isDrawn = true;
this.isConnectedToRing = false;
this.neighbouringElements = Array();
this.isPartOfAromaticRing = element !== this.element;
this.bondCount = 0;
this.chirality = '';
this.isStereoCenter = false;
this.priority = 0;
this.mainChain = false;
this.hydrogenDirection = 'down';
this.subtreeDepth = 1;
this.hasHydrogen = false;
}
/**
* Adds a neighbouring element to this atom.
*
* @param {String} element A string representing an element.
*/
_createClass(Atom, [{
key: 'addNeighbouringElement',
value: function addNeighbouringElement(element) {
this.neighbouringElements.push(element);
}
/**
* Attaches a pseudo element (e.g. Ac) to the atom.
* @param {String} element The element identifier (e.g. Br, C, ...).
* @param {String} previousElement The element that is part of the main chain (not the terminals that are converted to the pseudo element or concatinated).
* @param {Number} [hydrogenCount=0] The number of hydrogens for the element.
* @param {Number} [charge=0] The charge for the element.
*/
}, {
key: 'attachPseudoElement',
value: function attachPseudoElement(element, previousElement) {
var hydrogenCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var charge = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
if (hydrogenCount === null) {
hydrogenCount = 0;
}
if (charge === null) {
charge = 0;
}
var key = hydrogenCount + element + charge;
if (this.attachedPseudoElements[key]) {
this.attachedPseudoElements[key].count += 1;
} else {
this.attachedPseudoElements[key] = {
element: element,
count: 1,
hydrogenCount: hydrogenCount,
previousElement: previousElement,
charge: charge
};
}
this.hasAttachedPseudoElements = true;
}
/**
* Returns the attached pseudo elements sorted by hydrogen count (ascending).
*
* @returns {Object} The sorted attached pseudo elements.
*/
}, {
key: 'getAttachedPseudoElements',
value: function getAttachedPseudoElements() {
var ordered = {};
var that = this;
Object.keys(this.attachedPseudoElements).sort().forEach(function (key) {
ordered[key] = that.attachedPseudoElements[key];
});
return ordered;
}
/**
* Returns the number of attached pseudo elements.
*
* @returns {Number} The number of attached pseudo elements.
*/
}, {
key: 'getAttachedPseudoElementsCount',
value: function getAttachedPseudoElementsCount() {
return Object.keys(this.attachedPseudoElements).length;
}
/**
* Returns whether this atom is a heteroatom (not C and not H).
*
* @returns {Boolean} A boolean indicating whether this atom is a heteroatom.
*/
}, {
key: 'isHeteroAtom',
value: function isHeteroAtom() {
return this.element !== 'C' && this.element !== 'H';
}
/**
* Defines this atom as the anchor for a ring. When doing repositionings of the vertices and the vertex associated with this atom is moved, the center of this ring is moved as well.
*
* @param {Number} ringId A ring id.
*/
}, {
key: 'addAnchoredRing',
value: function addAnchoredRing(ringId) {
if (!ArrayHelper.contains(this.anchoredRings, {
value: ringId
})) {
this.anchoredRings.push(ringId);
}
}
/**
* Returns the number of ringbonds (breaks in rings to generate the MST of the smiles) within this atom is connected to.
*
* @returns {Number} The number of ringbonds this atom is connected to.
*/
}, {
key: 'getRingbondCount',
value: function getRingbondCount() {
return this.ringbonds.length;
}
/**
* Backs up the current rings.
*/
}, {
key: 'backupRings',
value: function backupRings() {
this.originalRings = Array(this.rings.length);
for (var i = 0; i < this.rings.length; i++) {
this.originalRings[i] = this.rings[i];
}
}
/**
* Restores the most recent backed up rings.
*/
}, {
key: 'restoreRings',
value: function restoreRings() {
this.rings = Array(this.originalRings.length);
for (var i = 0; i < this.originalRings.length; i++) {
this.rings[i] = this.originalRings[i];
}
}
/**
* Checks whether or not two atoms share a common ringbond id. A ringbond is a break in a ring created when generating the spanning tree of a structure.
*
* @param {Atom} atomA An atom.
* @param {Atom} atomB An atom.
* @returns {Boolean} A boolean indicating whether or not two atoms share a common ringbond.
*/
}, {
key: 'haveCommonRingbond',
value: function haveCommonRingbond(atomA, atomB) {
for (var i = 0; i < atomA.ringbonds.length; i++) {
for (var j = 0; j < atomB.ringbonds.length; j++) {
if (atomA.ringbonds[i].id == atomB.ringbonds[j].id) {
return true;
}
}
}
return false;
}
/**
* Check whether or not the neighbouring elements of this atom equal the supplied array.
*
* @param {String[]} arr An array containing all the elements that are neighbouring this atom. E.g. ['C', 'O', 'O', 'N']
* @returns {Boolean} A boolean indicating whether or not the neighbours match the supplied array of elements.
*/
}, {
key: 'neighbouringElementsEqual',
value: function neighbouringElementsEqual(arr) {
if (arr.length !== this.neighbouringElements.length) {
return false;
}
arr.sort();
this.neighbouringElements.sort();
for (var i = 0; i < this.neighbouringElements.length; i++) {
if (arr[i] !== this.neighbouringElements[i]) {
return false;
}
}
return true;
}
/**
* Get the atomic number of this atom.
*
* @returns {Number} The atomic number of this atom.
*/
}, {
key: 'getAtomicNumber',
value: function getAtomicNumber() {
return Atom.atomicNumbers[this.element];
}
/**
* Get the maximum number of bonds for this atom.
*
* @returns {Number} The maximum number of bonds of this atom.
*/
}, {
key: 'getMaxBonds',
value: function getMaxBonds() {
return Atom.maxBonds[this.element];
}
/**
* A map mapping element symbols to their maximum bonds.
*/
}], [{
key: 'maxBonds',
get: function get() {
return {
'H': 1,
'C': 4,
'N': 3,
'O': 2,
'P': 3,
'S': 2,
'B': 3,
'F': 1,
'I': 1,
'Cl': 1,
'Br': 1
};
}
/**
* A map mapping element symbols to the atomic number.
*/
}, {
key: 'atomicNumbers',
get: function get() {
return {
'H': 1,
'He': 2,
'Li': 3,
'Be': 4,
'B': 5,
'b': 5,
'C': 6,
'c': 6,
'N': 7,
'n': 7,
'O': 8,
'o': 8,
'F': 9,
'Ne': 10,
'Na': 11,
'Mg': 12,
'Al': 13,
'Si': 14,
'P': 15,
'p': 15,
'S': 16,
's': 16,
'Cl': 17,
'Ar': 18,
'K': 19,
'Ca': 20,
'Sc': 21,
'Ti': 22,
'V': 23,
'Cr': 24,
'Mn': 25,
'Fe': 26,
'Co': 27,
'Ni': 28,
'Cu': 29,
'Zn': 30,
'Ga': 31,
'Ge': 32,
'As': 33,
'Se': 34,
'Br': 35,
'Kr': 36,
'Rb': 37,
'Sr': 38,
'Y': 39,
'Zr': 40,
'Nb': 41,
'Mo': 42,
'Tc': 43,
'Ru': 44,
'Rh': 45,
'Pd': 46,
'Ag': 47,
'Cd': 48,
'In': 49,
'Sn': 50,
'Sb': 51,
'Te': 52,
'I': 53,
'Xe': 54,
'Cs': 55,
'Ba': 56,
'La': 57,
'Ce': 58,
'Pr': 59,
'Nd': 60,
'Pm': 61,
'Sm': 62,
'Eu': 63,
'Gd': 64,
'Tb': 65,
'Dy': 66,
'Ho': 67,
'Er': 68,
'Tm': 69,
'Yb': 70,
'Lu': 71,
'Hf': 72,
'Ta': 73,
'W': 74,
'Re': 75,
'Os': 76,
'Ir': 77,
'Pt': 78,
'Au': 79,
'Hg': 80,
'Tl': 81,
'Pb': 82,
'Bi': 83,
'Po': 84,
'At': 85,
'Rn': 86,
'Fr': 87,
'Ra': 88,
'Ac': 89,
'Th': 90,
'Pa': 91,
'U': 92,
'Np': 93,
'Pu': 94,
'Am': 95,
'Cm': 96,
'Bk': 97,
'Cf': 98,
'Es': 99,
'Fm': 100,
'Md': 101,
'No': 102,
'Lr': 103,
'Rf': 104,
'Db': 105,
'Sg': 106,
'Bh': 107,
'Hs': 108,
'Mt': 109,
'Ds': 110,
'Rg': 111,
'Cn': 112,
'Uut': 113,
'Uuq': 114,
'Uup': 115,
'Uuh': 116,
'Uus': 117,
'Uuo': 118
};
}
/**
* A map mapping element symbols to the atomic mass.
*/
}, {
key: 'mass',
get: function get() {
return {
'H': 1,
'He': 2,
'Li': 3,
'Be': 4,
'B': 5,
'b': 5,
'C': 6,
'c': 6,
'N': 7,
'n': 7,
'O': 8,
'o': 8,
'F': 9,
'Ne': 10,
'Na': 11,
'Mg': 12,
'Al': 13,
'Si': 14,
'P': 15,
'p': 15,
'S': 16,
's': 16,
'Cl': 17,
'Ar': 18,
'K': 19,
'Ca': 20,
'Sc': 21,
'Ti': 22,
'V': 23,
'Cr': 24,
'Mn': 25,
'Fe': 26,
'Co': 27,
'Ni': 28,
'Cu': 29,
'Zn': 30,
'Ga': 31,
'Ge': 32,
'As': 33,
'Se': 34,
'Br': 35,
'Kr': 36,
'Rb': 37,
'Sr': 38,
'Y': 39,
'Zr': 40,
'Nb': 41,
'Mo': 42,
'Tc': 43,
'Ru': 44,
'Rh': 45,
'Pd': 46,
'Ag': 47,
'Cd': 48,
'In': 49,
'Sn': 50,
'Sb': 51,
'Te': 52,
'I': 53,
'Xe': 54,
'Cs': 55,
'Ba': 56,
'La': 57,
'Ce': 58,
'Pr': 59,
'Nd': 60,
'Pm': 61,
'Sm': 62,
'Eu': 63,
'Gd': 64,
'Tb': 65,
'Dy': 66,
'Ho': 67,
'Er': 68,
'Tm': 69,
'Yb': 70,
'Lu': 71,
'Hf': 72,
'Ta': 73,
'W': 74,
'Re': 75,
'Os': 76,
'Ir': 77,
'Pt': 78,
'Au': 79,
'Hg': 80,
'Tl': 81,
'Pb': 82,
'Bi': 83,
'Po': 84,
'At': 85,
'Rn': 86,
'Fr': 87,
'Ra': 88,
'Ac': 89,
'Th': 90,
'Pa': 91,
'U': 92,
'Np': 93,
'Pu': 94,
'Am': 95,
'Cm': 96,
'Bk': 97,
'Cf': 98,
'Es': 99,
'Fm': 100,
'Md': 101,
'No': 102,
'Lr': 103,
'Rf': 104,
'Db': 105,
'Sg': 106,
'Bh': 107,
'Hs': 108,
'Mt': 109,
'Ds': 110,
'Rg': 111,
'Cn': 112,
'Uut': 113,
'Uuq': 114,
'Uup': 115,
'Uuh': 116,
'Uus': 117,
'Uuo': 118
};
}
}]);
return Atom;
}();
module.exports = Atom;
},{"./ArrayHelper":2,"./Ring":11,"./Vertex":15}],4:[function(require,module,exports){
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//@ts-check
var MathHelper = require('./MathHelper');
var Vector2 = require('./Vector2');
var Line = require('./Line');
var Vertex = require('./Vertex');
var Ring = require('./Ring');
/**
* A class wrapping a canvas element.
*
* @property {HTMLElement} canvas The HTML element for the canvas associated with this CanvasWrapper instance.
* @property {CanvasRenderingContext2D} ctx The CanvasRenderingContext2D of the canvas associated with this CanvasWrapper instance.
* @property {Object} colors The colors object as defined in the SmilesDrawer options.
* @property {Object} opts The SmilesDrawer options.
* @property {Number} drawingWidth The width of the canvas.
* @property {Number} drawingHeight The height of the canvas.
* @property {Number} offsetX The horizontal offset required for centering the drawing.
* @property {Number} offsetY The vertical offset required for centering the drawing.
* @property {Number} fontLarge The large font size in pt.
* @property {Number} fontSmall The small font size in pt.
*/
var CanvasWrapper = function () {
/**
* The constructor for the class CanvasWrapper.
*
* @param {(String|HTMLElement)} target The canvas id or the canvas HTMLElement.
* @param {Object} theme A theme from the smiles drawer options.
* @param {Object} options The smiles drawer options object.
*/
function CanvasWrapper(target, theme, options) {
_classCallCheck(this, CanvasWrapper);
if (typeof target === 'string' || target instanceof String) {
this.canvas = document.getElementById(target);
} else {
this.canvas = target;
}
this.ctx = this.canvas.getContext('2d');
this.colors = theme;
this.opts = options;
this.drawingWidth = 0.0;
this.drawingHeight = 0.0;
this.offsetX = 0.0;
this.offsetY = 0.0;
this.fontLarge = this.opts.fontSizeLarge + 'pt Helvetica, Arial, sans-serif';
this.fontSmall = this.opts.fontSizeSmall + 'pt Helvetica, Arial, sans-serif';
this.updateSize(this.opts.width, this.opts.height);
this.ctx.font = this.fontLarge;
this.hydrogenWidth = this.ctx.measureText('H').width;
this.halfHydrogenWidth = this.hydrogenWidth / 2.0;
this.halfBondThickness = this.opts.bondThickness / 2.0;
// TODO: Find out why clear was here.
// this.clear();
}
/**
* Update the width and height of the canvas
*
* @param {Number} width
* @param {Number} height
*/
_createClass(CanvasWrapper, [{
key: 'updateSize',
value: function updateSize(width, height) {
this.devicePixelRatio = window.devicePixelRatio || 1;
this.backingStoreRatio = this.ctx.webkitBackingStorePixelRatio || this.ctx.mozBackingStorePixelRatio || this.ctx.msBackingStorePixelRatio || this.ctx.oBackingStorePixelRatio || this.ctx.backingStorePixelRatio || 1;
this.ratio = this.devicePixelRatio / this.backingStoreRatio;
if (this.ratio !== 1) {
this.canvas.width = width * this.ratio;
this.canvas.height = height * this.ratio;
this.canvas.style.width = width + 'px';
this.canvas.style.height = height + 'px';
this.ctx.setTransform(this.ratio, 0, 0, this.ratio, 0, 0);
} else {
this.canvas.width = width * this.ratio;
this.canvas.height = height * this.ratio;
}
}
/**
* Sets a provided theme.
*
* @param {Object} theme A theme from the smiles drawer options.
*/
}, {
key: 'setTheme',
value: function setTheme(theme) {
this.colors = theme;
}
/**
* Scale the canvas based on vertex positions.
*
* @param {Vertex[]} vertices An array of vertices containing the vertices associated with the current molecule.
*/
}, {
key: 'scale',
value: function scale(vertices) {
// Figure out the final size of the image
var maxX = -Number.MAX_VALUE;
var maxY = -Number.MAX_VALUE;
var minX = Number.MAX_VALUE;
var minY = Number.MAX_VALUE;
for (var i = 0; i < vertices.length; i++) {
if (!vertices[i].value.isDrawn) {
continue;
}
var p = vertices[i].position;
if (maxX < p.x) maxX = p.x;
if (maxY < p.y) maxY = p.y;
if (minX > p.x) minX = p.x;
if (minY > p.y) minY = p.y;
}
// Add padding
var padding = this.opts.padding;
maxX += padding;
maxY += padding;
minX -= padding;
minY -= padding;
this.drawingWidth = maxX - minX;
this.drawingHeight = maxY - minY;
var scaleX = this.canvas.offsetWidth / this.drawingWidth;
var scaleY = this.canvas.offsetHeight / this.drawingHeight;
var scale = scaleX < scaleY ? scaleX : scaleY;
this.ctx.scale(scale, scale);
this.offsetX = -minX;
this.offsetY = -minY;
// Center
if (scaleX < scaleY) {
this.offsetY += this.canvas.offsetHeight / (2.0 * scale) - this.drawingHeight / 2.0;
} else {
this.offsetX += this.canvas.offsetWidth / (2.0 * scale) - this.drawingWidth / 2.0;
}
}
/**
* Resets the transform of the canvas.
*/
}, {
key: 'reset',
value: function reset() {
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
}
/**
* Returns the hex code of a color associated with a key from the current theme.
*
* @param {String} key The color key in the theme (e.g. C, N, BACKGROUND, ...).
* @returns {String} A color hex value.
*/
}, {
key: 'getColor',
value: function getColor(key) {
key = key.toUpperCase();
if (key in this.colors) {
return this.colors[key];
}
return this.colors['C'];
}
/**
* Draws a circle to a canvas context.
* @param {Number} x The x coordinate of the circles center.
* @param {Number} y The y coordinate of the circles center.
* @param {Number} radius The radius of the circle
* @param {String} color A hex encoded color.
* @param {Boolean} [fill=true] Whether to fill or stroke the circle.
* @param {Boolean} [debug=false] Draw in debug mode.
* @param {String} [debugText=''] A debug message.
*/
}, {
key: 'drawCircle',
value: function drawCircle(x, y, radius, color) {
var fill = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
var debug = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
var debugText = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : '';
var ctx = this.ctx;
var offsetX = this.offsetX;
var offsetY = this.offsetY;
ctx.save();
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(x + offsetX, y + offsetY, radius, 0, MathHelper.twoPI, true);
ctx.closePath();
if (debug) {
if (fill) {
ctx.fillStyle = '#f00';
ctx.fill();
} else {
ctx.strokeStyle = '#f00';
ctx.stroke();
}
this.drawDebugText(x, y, debugText);
} else {
if (fill) {
ctx.fillStyle = color;
ctx.fill();
} else {
ctx.strokeStyle = color;
ctx.stroke();
}
}
ctx.restore();
}
/**
* Draw a line to a canvas.
*
* @param {Line} line A line.
* @param {Boolean} [dashed=false] Whether or not the line is dashed.
* @param {Number} [alpha=1.0] The alpha value of the color.
*/
}, {
key: 'drawLine',
value: function drawLine(line) {
var dashed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1.0;
var ctx = this.ctx;
var offsetX = this.offsetX;
var offsetY = this.offsetY;
// Add a shadow behind the line
var shortLine = line.clone().shorten(4.0);
var l = shortLine.getLeftVector().clone();
var r = shortLine.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
// Draw the "shadow"
if (!dashed) {
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.moveTo(l.x, l.y);
ctx.lineTo(r.x, r.y);
ctx.lineCap = 'round';
ctx.lineWidth = this.opts.bondThickness + 1.2;
ctx.strokeStyle = this.getColor('BACKGROUND');
ctx.stroke();
ctx.globalCompositeOperation = 'source-over';
ctx.restore();
}
l = line.getLeftVector().clone();
r = line.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
ctx.save();
ctx.beginPath();
ctx.moveTo(l.x, l.y);
ctx.lineTo(r.x, r.y);
ctx.lineCap = 'round';
ctx.lineWidth = this.opts.bondThickness;
var gradient = this.ctx.createLinearGradient(l.x, l.y, r.x, r.y);
gradient.addColorStop(0.4, this.getColor(line.getLeftElement()) || this.getColor('C'));
gradient.addColorStop(0.6, this.getColor(line.getRightElement()) || this.getColor('C'));
if (dashed) {
ctx.setLineDash([1, 1.5]);
ctx.lineWidth = this.opts.bondThickness / 1.5;
}
if (alpha < 1.0) {
ctx.globalAlpha = alpha;
}
ctx.strokeStyle = gradient;
ctx.stroke();
ctx.restore();
}
/**
* Draw a wedge on the canvas.
*
* @param {Line} line A line.
* @param {Number} width The wedge width.
*/
}, {
key: 'drawWedge',
value: function drawWedge(line) {
var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1.0;
if (isNaN(line.from.x) || isNaN(line.from.y) || isNaN(line.to.x) || isNaN(line.to.y)) {
return;
}
var ctx = this.ctx;
var offsetX = this.offsetX;
var offsetY = this.offsetY;
// Add a shadow behind the line
var shortLine = line.clone().shorten(5.0);
var l = shortLine.getLeftVector().clone();
var r = shortLine.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
l = line.getLeftVector().clone();
r = line.getRightVector().clone();
l.x += offsetX;
l.y += offsetY;
r.x += offsetX;
r.y += offsetY;
ctx.save();
var normals = Vector2.normals(l, r);
normals[0].normalize();
normals[1].normalize();
var isRightChiralCenter = line.getRightChiral();
var start = l;
var end = r;
if (isRightChiralCenter) {
start = r;
end = l;
}
var t = Vector2.add(start, Vector2.multiplyScalar(normals[0], this.halfBondThickness));
var u = Vector2.add(end, Vector2.multiplyScalar(normals[0], 1.5 + this.halfBondThickness));
var v = Vector2.add(end, Vector2.multiplyScalar(normals[1], 1.5 + this.halfBondThickness));
var w = Vector2.add(start, Vector2.multiplyScalar(normals[1], this.halfBondThickness));
ctx.beginPath();
ctx.m