partridgejiang / Kekule.js

A Javascript cheminformatics toolkit.
http://partridgejiang.github.io/Kekule.js
MIT License
247 stars 61 forks source link

Do Kekule js provide auto charge func in composer widget? #283

Closed keeper1030 closed 2 years ago

keeper1030 commented 2 years ago

I want to use auto charge func like below video. Do Kekule js provide that func or another method to use like that?

https://user-images.githubusercontent.com/100748485/177679273-7a7235a9-3248-48d2-9238-da0aee32e105.mov

partridgejiang commented 2 years ago

Hi @keeper1030, such a function can be applied with codes something like the following ones:

composer.getEditor().on('editObjsUpdated', function(e){  // detect changed and updated objects in editor
    for (var key in e.details)
    {
        var item = e.details[key];
        var obj = item.obj;
        if (obj && obj instanceof Kekule.StructureFragment)  // iterate all child atoms in changed molecules
        {
            obj.getNodes().forEach(function(node){
                if (node instanceof Kekule.Atom)
                {
                    var currValence = node.getExplicitValence() || 0;
                    var maxValence = Kekule.ValenceUtils.getMaxPossibleMdlValence(node.getAtomicNumber(), 0);
                    if (currValence && maxValence)
                    {   
                        if (currValence >= maxValence)
                        {
                            node.setCharge(currValence - maxValence);
                        }
                    }
                }
            });
        }
    }
});
keeper1030 commented 2 years ago

Thanks to you, I solved it well!!