Files
OpenNoodl/packages/noodl-runtime/src/variants.js
Michael Cartner b9c60b07dc Initial commit
Co-Authored-By: Eric Tuvesson <eric.tuvesson@gmail.com>
Co-Authored-By: mikaeltellhed <2311083+mikaeltellhed@users.noreply.github.com>
Co-Authored-By: kotte <14197736+mrtamagotchi@users.noreply.github.com>
Co-Authored-By: Anders Larsson <64838990+anders-topp@users.noreply.github.com>
Co-Authored-By: Johan  <4934465+joolsus@users.noreply.github.com>
Co-Authored-By: Tore Knudsen <18231882+torekndsn@users.noreply.github.com>
Co-Authored-By: victoratndl <99176179+victoratndl@users.noreply.github.com>
2024-01-26 11:52:55 +01:00

42 lines
1.3 KiB
JavaScript

class Variants {
constructor({graphModel, getNodeScope}) {
this.getNodeScope = getNodeScope;
if(graphModel) {
this.graphModel = graphModel;
graphModel.on('variantUpdated', variant => this.onVariantUpdated(variant));
}
}
getVariant(typename, name) {
if(!this.graphModel) return undefined;
return this.graphModel.getVariant(typename, name);
}
onVariantUpdated(variant) {
const nodeScope = this.getNodeScope();
if(!nodeScope) return;
//get all nodes with the type the variant applies to
const nodes = nodeScope.getNodesWithTypeRecursive(variant.typename);
//and filter for the ones using the updated variant
const nodesWithVariant = nodes.filter(node => {
//if a variant has been set during runtime, it'll override the value from the model
if(node.variant) return node.variant.name === variant.name;
//otherwise check the model (which always matches the editor)
return node.model && node.model.variant === variant.name;
});
//and re-apply the variant
for(const node of nodesWithVariant) {
node.setVariant(variant);
}
}
}
module.exports = Variants;