@iktos-oss/molecule-representation
Version:
exports interactif molecule represnetations as react components
251 lines (247 loc) • 12.1 kB
JavaScript
/*
MIT License
Copyright (c) 2023 Iktos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { cloneElement } from 'react';
import convert from 'react-from-dom';
import { createHitboxFromAtomEllipse, createHitboxPathFromPath, getPathEdgePoints, getSvgDimensionsWithAppendedElements, } from './html';
import { getAtomHighliteEllipseIdentifier, getAtomIdsFromClassnames, getAtomSelectorIdentifier, getBondIdFromClassnames, getBondSelectorIdentifier, getClickableAtomIdFromAtomIdx, getClickableBondId, isHighlightingPath, RDKIT_ATOMS_CLASS_REGEX, RDKIT_HIGHLIGHTED_ELIPSES_IDENTIFIER, } from './identifiers';
export const createSvgElement = (svg, svgProps) => {
if (!svg)
throw new Error('Missing svg');
const element = convert(svg);
if (!element)
throw new Error('Could not convert to element');
return cloneElement(element, Object.assign({}, svgProps));
};
export const computeIconsCoords = ({ svg, attachedIcons, }) => {
var _a, _b, _c, _d;
if (!svg)
return [];
const coords = [];
const parentWrapper = document.createElement('div');
parentWrapper.innerHTML = svg;
const parentSvg = parentWrapper.getElementsByTagName('svg')[0];
if (!parentSvg)
return [];
for (const attachedIcon of attachedIcons) {
const attachedIconPlacements = [];
const svgDimenssions = getSvgDimensionsWithAppendedElements(attachedIcon.svg);
if (!svgDimenssions) {
continue;
}
const { width: svgWidth, height: svgHeight } = svgDimenssions;
const referenceAtoms = Array.from(parentSvg.querySelectorAll('ellipse.atom-0'));
const scale = referenceAtoms.length
? Math.min((parseFloat((_a = referenceAtoms[0].getAttribute('rx')) !== null && _a !== void 0 ? _a : '0.5') * 2) / svgWidth, (parseFloat((_b = referenceAtoms[0].getAttribute('ry')) !== null && _b !== void 0 ? _b : '0.5') * 2) / svgHeight)
: 1;
const processedBondIds = new Set();
for (const atomId of attachedIcon.atomIds) {
const matchedElems = Array.from(parentSvg.querySelectorAll(`ellipse.atom-${atomId}`));
for (const matchedElem of matchedElems) {
const { x, y } = matchedElem.getBoundingClientRect();
const cx = parseFloat((_c = matchedElem.getAttribute('cx')) !== null && _c !== void 0 ? _c : `${x}`);
const cy = parseFloat((_d = matchedElem.getAttribute('cy')) !== null && _d !== void 0 ? _d : `${y}`);
attachedIconPlacements.push({
xTranslate: cx,
yTranslate: cy,
});
}
}
for (const bondId of attachedIcon.bondIds) {
const matchedElems = Array.from(parentSvg.querySelectorAll(`.bond-${bondId}`));
for (const matchedElem of matchedElems) {
if (processedBondIds.has(bondId)) {
// ignore double bonds
continue;
}
if (matchedElem.id.includes('clickable') || isHighlightingPath(matchedElem)) {
// ignore clickable & highlighted (they are duplicates of the original bond)
continue;
}
const { start, end } = getPathEdgePoints(matchedElem);
attachedIconPlacements.push({
xTranslate: (start.x + end.x) / 2,
yTranslate: (start.y + end.y) / 2,
});
processedBondIds.add(bondId);
}
}
coords.push({
svg: attachedIcon.svg,
scale,
placements: attachedIconPlacements.map((placement) => (Object.assign(Object.assign({}, placement), { xTranslate: placement.xTranslate - (svgWidth * scale) / 2, yTranslate: placement.yTranslate - (svgHeight * scale) / 2 }))),
});
}
return coords;
};
export const buildBondsHitboxes = ({
// this doesn't look into dom, but uses the svg string instead
numAtoms, svg, isClickable, }) => {
const parentWrapper = document.createElement('div');
parentWrapper.innerHTML = svg;
const parentSvg = parentWrapper.getElementsByTagName('svg')[0];
if (!parentSvg)
return [];
const clickablePaths = [];
for (let atomIdx = 0; atomIdx < numAtoms; atomIdx++) {
const matchedElems = Array.from(parentSvg.querySelectorAll(getBondSelectorIdentifier(atomIdx)));
for (const elem of matchedElems) {
const atomIndicesInBond = getAtomIdsFromClassnames(elem.classList);
const bondIndicies = getBondIdFromClassnames(elem.classList);
if (bondIndicies.length !== 1 || atomIndicesInBond.length !== 2) {
console.error('[@iktos-oss/molecule-representation] invalid bond classname', bondIndicies, elem.classList);
continue;
}
if (isHighlightingPath(elem)) {
continue;
}
const hitboxPath = createHitboxPathFromPath({
path: elem,
id: getClickableBondId({
bondId: bondIndicies[0],
startAtomId: atomIndicesInBond[0],
endAtomId: atomIndicesInBond[1],
}),
isClickable,
});
clickablePaths.push(hitboxPath);
}
}
return clickablePaths;
};
export const buildAtomsHitboxes = ({
// this doesn't look into dom, but uses the svg string instead
numAtoms, svg, clickableAtoms, isClickable, }) => {
const parentWrapper = document.createElement('div');
parentWrapper.innerHTML = svg;
const parentSvg = parentWrapper.getElementsByTagName('svg')[0];
if (!parentSvg)
return [];
const clickablePaths = [];
for (let atomIdx = 0; atomIdx < numAtoms; atomIdx++) {
if (clickableAtoms && !clickableAtoms.has(atomIdx)) {
// ignore non clickableAtoms if clickableAtoms is specified
continue;
}
const matchedElems = Array.from(parentSvg.querySelectorAll(getAtomHighliteEllipseIdentifier(atomIdx)));
for (const elem of matchedElems) {
const atomIndicesInBond = getAtomIdsFromClassnames(elem.classList);
if (atomIndicesInBond.length !== 1) {
console.warn('Found an ellipse with more than one atomid');
continue;
}
const hitboxPath = createHitboxFromAtomEllipse({
ellipse: elem,
id: getClickableAtomIdFromAtomIdx(atomIdx),
isClickable,
});
clickablePaths.push(hitboxPath);
}
}
return clickablePaths;
};
export const applyUserStyles = ({ svg, numAtoms, atomsStyles, bondsStyles, }) => {
if (!atomsStyles && !bondsStyles)
return svg;
const parentWrapper = document.createElement('div');
parentWrapper.innerHTML = svg;
const parentSvg = parentWrapper.getElementsByTagName('svg')[0];
if (!parentSvg)
return svg;
const _a = atomsStyles || {}, { default: defaultAtomsStyles } = _a, specificAtomsStyles = __rest(_a, ["default"]);
const _b = bondsStyles || {}, { default: defaultBondsStyles } = _b, specificBondsStyles = __rest(_b, ["default"]);
for (let atomIdx = 0; atomIdx < numAtoms; atomIdx++) {
const matchedAtomsElems = Array.from(parentSvg.querySelectorAll(getAtomSelectorIdentifier(atomIdx)));
const matchedBondsElems = Array.from(parentSvg.querySelectorAll(getBondSelectorIdentifier(atomIdx)));
for (const matchedElem of matchedAtomsElems) {
const stylesToApply = specificAtomsStyles[atomIdx] || defaultAtomsStyles || {};
Object.assign(matchedElem.style, stylesToApply);
}
for (const matchedElem of matchedBondsElems) {
const [bondId] = getBondIdFromClassnames(matchedElem.classList);
const [startAtomId, endAtomId] = Array.from(matchedElem.classList)
.filter((c) => c.includes('atom'))
.map((c) => parseInt(c.replace('atom-', '')));
const stylesToApply = specificBondsStyles[bondId] ||
specificBondsStyles[`${startAtomId}-${endAtomId}`] ||
specificBondsStyles[`${startAtomId}-*`] ||
specificBondsStyles[`*-${endAtomId}`] ||
defaultBondsStyles ||
{};
Object.assign(matchedElem.style, stylesToApply);
}
}
return parentWrapper.innerHTML;
};
export const appendEllipsesToSvg = (mainSvg, ellipsesSourceSvg) => {
if (!ellipsesSourceSvg || !mainSvg) {
return mainSvg;
}
try {
const mainParser = document.createElement('div');
mainParser.innerHTML = mainSvg;
const existingAtomIndexes = new Set();
const mainEllipses = mainParser.querySelectorAll(RDKIT_HIGHLIGHTED_ELIPSES_IDENTIFIER);
// collect already present clickable atoms from main svg
mainEllipses.forEach((el) => {
const classString = el.className.baseVal;
const match = classString.match(RDKIT_ATOMS_CLASS_REGEX);
if (match && match[1]) {
existingAtomIndexes.add(match[1]);
}
});
// collect only the ellipses for atoms not already present from ellipses svg
const sourceParser = document.createElement('div');
sourceParser.innerHTML = ellipsesSourceSvg;
const sourceEllipses = sourceParser.querySelectorAll(RDKIT_HIGHLIGHTED_ELIPSES_IDENTIFIER);
const ellipsesToAdd = [];
sourceEllipses.forEach((el) => {
const classString = el.className.baseVal;
const match = classString.match(RDKIT_ATOMS_CLASS_REGEX);
if (match && match[1] && !existingAtomIndexes.has(match[1])) {
ellipsesToAdd.push(el.outerHTML);
}
});
// if there are new, unique ellipses to add, append them to the main svg
if (ellipsesToAdd.length > 0) {
const ellipsesString = ellipsesToAdd.join('');
const closingSvgTagIndex = mainSvg.lastIndexOf('</svg>');
if (closingSvgTagIndex !== -1) {
return mainSvg.substring(0, closingSvgTagIndex) + ellipsesString + mainSvg.substring(closingSvgTagIndex);
}
}
}
catch (error) {
console.error('Error processing and de-duplicating clickableSvg ellipses:', error);
return mainSvg;
}
return mainSvg; // return original if no new ellipses were found
};
//# sourceMappingURL=svg-computation.js.map