var wordplot=function(){function buildVisualization(plotId,json,plotType,props={}){switch(plotType=plotType.toLowerCase(),plotType){case"hexagon":case"square":const dataFormat=wordplot.json.detectDataType(json);return"mapseries"==dataFormat?wordplot.wordmap.buildMapSeries(plotId,json,plotType,props):wordplot.wordmap.buildWordMap(plotId,json,plotType,props);case"barchart":case"barchartgroup":case"basicbarchart":case"topbarchart":return wordplot.bars.buildBarChart(plotId,json,plotType,props);case"linechart":case"linechartgroup":return wordplot.line.buildLineChart(plotId,json,plotType,props);case"top20":return wordplot.top.buildTopChart(plotId,json,props);default:console.log("Error at BuildVisualization(): Invalid plotType",plotType)}}function initLogo(plot){var{outerSVG:outerSVG}=plot.getComponents();const{width:width,height:height}=plot.getProperties(),imageSrc="https://megatron.headai.com/lib/headai-logo-without-name-black-transparent.png",sizeImage=80,xImage=width-sizeImage,yImage=height-sizeImage,textHeight=20,textSize="13px",logoContainer=outerSVG.selectAll("svg.headaiLogo").data([null]).enter().append("svg").attr("class","headaiLogo").attr("width",sizeImage).attr("height",sizeImage).attr("x",xImage).attr("y",yImage);var foreignImage=logoContainer.append("foreignObject").attr("class","foreignImage").attr("x",0).attr("y",0).attr("width",sizeImage).attr("height",sizeImage).node(),imageLogo=document.createElement("img");imageLogo.setAttribute("width",sizeImage),imageLogo.setAttribute("height",sizeImage),imageLogo.setAttribute("src",imageSrc),foreignImage.appendChild(imageLogo);const copyrightText="© Headai";var foreignText=logoContainer.append("foreignObject").attr("class","foreignText").attr("x",0).attr("y",sizeImage-textHeight).attr("width",sizeImage).attr("height",textHeight).node(),textLogo=document.createElement("p");textLogo.setAttribute("width",sizeImage),textLogo.innerHTML=copyrightText,textLogo.style.textAlign="center",textLogo.style.margin=0,textLogo.style.fontFamily="sans-serif",textLogo.style.fontSize=textSize,textLogo.style.fontWeight="normal",textLogo.style.pointerEvents="none",foreignText.appendChild(textLogo)}function buildWordMap(plotId,json,plotType="hexagon",props={}){plotType=plotType.toLowerCase();if(null!=props&&"Object"==props.constructor.name||(props={}),!["hexagon","square"].includes(plotType))return console.log("Error at BuildWordMap() invalid plotType "+plotType),null;const isWideMap=props.hasOwnProperty("onlyNearestNeighbours")&&!0===props.onlyNearestNeighbours;json=wordplot.json.normalizeMindMapJson(json);const mindmap=new wordplot.wordmap.MindMap(json,props);var processor;processor=!0===isWideMap?new wordplot.graph.WideGraphToMap(mindmap,plotType,props):new wordplot.graph.GraphToMap(mindmap,plotType,props);const locatedNodes=processor.getLocatedNodes();var plot=null;const isSignalsMap=wordplot.json.isMapWithSignals(json);if(isSignalsMap&&(props.actionOnClick="showvalues",props.enableTooltipChart=!0),"hexagon"==plotType?plot=new wordplot.wordmap.HexagonMap(plotId,props):"square"==plotType?plot=new wordplot.wordmap.SquareMap(plotId,props):console.log("Error at BuildWordMap() Unexpected plot type:",plotType),plot.setGraphToMap(processor),plot.setPlotData(locatedNodes),plot.setLegend(json.legends),isSignalsMap)if(wordplot.wordmap.configureMapWithSignals(plot),json.hasOwnProperty("info")&&json.info.hasOwnProperty("timeLabels")){const tooltipProps={timeLabels:json.info.timeLabels};plot.enableTooltipChart("basiclinechart",tooltipProps)}else props.hasOwnProperty("tooltipChartProps")||console.log("Warning: The JSON contains information about signals but doesn't provide time labels. For this reason, the embedded linechart has been disabled");return plot}function configureMapWithSignals(plot){var colors=["#001773","#6987ff","#0090b8","#666666","#c4c4c4","#c79f00","#ed5300","#990000"];plot.setColors(colors);var groupToColorIndexAux={1:0,2:1,3:2,4:3,5:4,6:5,7:6,8:7};plot._groupToColorIndex=groupToColorIndexAux;const props={actionOnClick:"showvalues",enableTooltipChart:!0,scale:"flat"};plot.setProperties(props)}function setSDGColorsInMap(plot){var colors=["#E5243B","#DDA63A","#4C9F38","#C5192D","#FF3A21","#26BDE2","#FCC30B","#A21942","#FD6925","#DD1367","#FD9D24","#BF8B2E","#3F7E44","#0A97D9","#56C02B","#00689D","#19486A"];plot.setColors(colors);var groupToColorIndexAux={1:0,2:1,3:2,4:3,5:4,6:5,7:6,8:7,9:8,10:9,11:10,12:11,13:12,14:13,15:14,16:15,17:16},groupToColorIndex=plot._groupToColorIndex;Object.keys(groupToColorIndex).forEach(group=>{groupToColorIndexAux.hasOwnProperty(group)?groupToColorIndex[group]=groupToColorIndexAux[group]:console.log(`ERROR at setSDGColorsInMap() : Group ${group} is not part of SDG Data`)}),plot._groupToColorIndex=groupToColorIndex;var legend={1:"No Poverty",2:"Zero Hunger",3:"Good Health and Well-Being",4:"Quality Education",5:"Gender Equality",6:"Clean Water and Sanitation",7:"Affordable and Clean Energy",8:"Decent Work and Economic Growth",9:"Industry, Innovation and Infrastructure",10:"Reduced Inequalities",11:"Sustainable Cities and Communities",12:"Responsible consumption and Production",13:"Climate Action",14:"Life bellow water",15:"Life on land",16:"Peace, Justice and Strong Institutions",17:"Partnerships for the goals"};plot.setLegend(legend)}function centerMap(plot){const{div:div}=plot.getComponents(),concepts=div.selectAll("svg.concept").nodes();if(0==concepts.length)return;for(var xMin=concepts[0].getAttribute("x"),yMin=concepts[0].getAttribute("y"),xMax=xMin,yMax=yMin,i=0;ixMax&&(xMax=x),y>yMax&&(yMax=y)}const figureSize=concepts[0].hasAttribute("width")?Number.parseFloat(concepts[0].getAttribute("width")):0,radius=figureSize/2;xMin-=radius,xMax+=radius;const width=xMax-xMin,scale=plot._width/width;var initialX=(-xMin-radius)*scale,initialY=-yMin*scale;plot.setInitialPosition(initialX,initialY),plot.setInitialZoom(scale),plot.translateVisualization(initialX,initialY,scale)}function enableRelevancyMode(plot){const DEFAULT_RELEVANCY_COLORS=["#cc3232","#db7b2b","#e7b416","#99c140","#2dc937"],props={scale:"flat",categoryField:"weight",colors:DEFAULT_RELEVANCY_COLORS};plot.setProperties(props);var groupToColorIndex={1:0,2:1,3:2,4:3,5:4};plot._groupToColorIndex=groupToColorIndex;const legend={1:"Weight 1",2:"Weight 2",3:"Weight 3",4:"Weight 4",5:"Weight 5"};plot.setLegend(legend)}function setColorsToMindMap(plot){if(null==plot)return;const colors=generateColorsForPlot(plot);plot.setColors(colors)}function generateColorsForPlot(plot){if(null==plot)return[];plot._colors;const groupField=plot._categoryField,categoryCount={};var newColors=[];const categories=Object.keys(plot._groupToColorIndex);categories.forEach(group=>{categoryCount[group]=0}),plot._plotData.forEach(node=>{const group=node[groupField];categoryCount.hasOwnProperty(group)?categoryCount[group]+=1:console.log(`Warning at SetColors() : Group '${group}' was not correctly identified`)});const nCategories=categories.length;if(1==nCategories)return newColors=["#08233B"],newColors;if(2==nCategories){const nNodesCat1=categoryCount[categories[0]],nNodesCat2=categoryCount[categories[1]];if(1==nNodesCat1&&nNodesCat2>=1||nNodesCat1>=1&&1==nNodesCat2)return newColors=["#11A1F3","#ee5e0c"],newColors;if(0==nNodesCat1||0==nNodesCat2)return newColors=["#08233B","#08233B"],newColors;newColors=["#4DC3F9","#E59476"]}else if(3==nCategories)return newColors=["#58C69A","#E59476","#4DC3F9"],newColors;return newColors}function buildMapSeries(plotId,json,plotType,props){if(props.actionOnClick="showvalues",props.enableTooltipChart=!0,json.hasOwnProperty("info")&&json.info.hasOwnProperty("timeLabels")){const timeLabels=json.info.timeLabels;props.tooltipChartProps={timeLabels:timeLabels}}const plot=new wordplot.wordmap.MapSeries(plotId,json,plotType,props);return plot}function load(){var dependencies=[{isLoaded:!!window.d3&&!!d3.hexbin,url:"https://d3js.org/d3-hexbin.v0.2.min.js"},{isLoaded:!!window.d3&&!!d3.select,url:"https://d3js.org/d3.v6.min.js"}];return null==loadPromise&&(loadPromise=importer.urls(dependencies)),loadPromise}const properties=(()=>{function validateType(value,type){return"array"==type?Array.isArray(value):"number"==type?"number"==typeof value&&!isNaN(value):["boolean","string"].includes(type)?typeof value===type:(console.log(`Error at validateType(${value},${type}) - Unsuported type`),!1)}function validateChange(oldValue,newValue,type){if("array"==type){const changed=JSON.stringify(oldValue)!==JSON.stringify(newValue);return changed}return["number","boolean","string"].includes(type)?oldValue!==newValue:(console.log(`Error at validateChange(${oldValue},${newValue},${type}) - Unsuported type`),!1)}function preprocess(value,type,preprocessType){if("array"==type&&"comma-separated"==preprocessType&&validateType(value,"string")){value=value.split(",");const newValue=[];for(let i=0;i{const type=propsDetails[prop].type,preprocessType=propsDetails[prop].preprocess,oldValue=props[prop];var newValue=newProps[prop];if("string"==typeof preprocessType&&(newValue=preprocess(newValue,type,preprocessType)),null==newValue)return;const correctType=validateType(newValue,type),changed=validateChange(oldValue,newValue,type);correctType&&changed&&(props[prop]=newValue,changes[prop]=newValue)}),changes}return{setProperties:setProperties,preprocess:preprocess}})(),legends=(()=>{function getSelectedGroups(plot){const{legendContainer:legendContainer}=plot.getComponents(),legends=legendContainer.selectAll("g.legendSelectButton"),groups=[];return legends.each((data,index,rects)=>{const thisRect=d3.select(rects[index]).select("rect"),isActive="true"===thisRect.attr("active");var groupId=thisRect.attr("groupId");groupId=Number.parseInt(groupId),isActive&&!isNaN(groupId)&&groups.push(groupId)}),groups}function hideButtonsLegend(plot){const{legendContainer:legendContainer,innerSVG:innerSVG}=plot.getComponents();legendContainer.selectAll("g.legendSelectButton").style("display","none").style("opacity",0),innerSVG.select("rect.hideContent").style("display","none").style("opacity",0)}function showButtonsLegend(plot){const{legendContainer:legendContainer,innerSVG:innerSVG}=plot.getComponents();legendContainer.selectAll("g.legendSelectButton").style("display","unset").style("opacity",1),innerSVG.select("rect.hideContent").style("display","unset").style("opacity",1)}function initButtonsLegend(plot){const legends=plot._legends,width=plot._width;if(null==legends||Array.isArray(legends))return;const groups=Object.keys(plot._groupToColorIndex),{innerSVG:innerSVG,legendContainer:legendContainer}=plot.getComponents(),{fontSize:fontSize}=plot.getProperties();var legendFontSize=fontSize+2;const legendSquareSize=legendFontSize+5,spaceBetweenLegends=2;innerSVG.selectAll("rect.hideContent").data([null]).enter().append("rect").attr("class","hideContent").style("width","100%").style("height","100%").attr("fill","#A0A0A0AA");var legend=function(svg){const g=svg.attr("transform",`translate(${width},0)`).style("text-anchor","end").selectAll("g.legendSelectButton").data(groups).join("g").attr("class","legendSelectButton").attr("transform",(d,i)=>`translate(0,${i*(legendSquareSize+spaceBetweenLegends)})`);g.append("rect").attr("x",-legendSquareSize).attr("width",legendSquareSize).attr("height",legendSquareSize).attr("fill",function(d){return plot.getColor(d)}).attr("active",!0).attr("groupId",d=>d).style("stroke-width","1px").style("stroke","black").on("click",function(event,groupId){const thisRect=d3.select(this);var isActive="true"===thisRect.attr("active");isActive=!isActive,thisRect.attr("active",isActive),isActive?thisRect.attr("fill",d=>plot.getColor(d)).style("stroke-width","1px"):thisRect.attr("fill","#A0A0A0").style("stroke-width","0px")})};legendContainer.call(legend),hideButtonsLegend(plot)}function initLegend(plot){const legends=plot._legends,width=plot._width;if(null==legends||Array.isArray(legends))return;const groups=Object.keys(plot._groupToColorIndex),{outerSVG:outerSVG}=plot.getComponents(),{fontFamily:fontFamily,fontSize:fontSize}=plot.getProperties();var legendFontSize=fontSize+2;const legendSquareSize=legendFontSize+5,spaceBetweenLegends=2,legendContainer=outerSVG.selectAll("g.legend").data([null]).enter().append("g").attr("class","legend");!0===plot._hideLegend?legendContainer.style("display","none"):legendContainer.style("display","unset");const legendBackground=legendContainer.selectAll("g.legend-background").data([null]).enter().append("g").attr("class","legend-background");var legend=function(svg){const g=svg.attr("transform",`translate(${width},0)`).style("text-anchor","end").selectAll("g.legendTitle").data(groups).join("g").attr("class","legendTitle").attr("transform",(d,i)=>`translate(0,${i*(legendSquareSize+spaceBetweenLegends)})`);g.append("rect").attr("x",-legendSquareSize).attr("width",legendSquareSize).attr("height",legendSquareSize).attr("fill",function(d){return plot.getColor(d)}),g.append("text").attr("x",-(legendSquareSize+5)).style("font-size",legendFontSize+"px").style("font-family",fontFamily).attr("y",9.5).attr("dy","0.35em").text(function(l){return legends[l]}).attr("fill","black")};legendContainer.call(legend);const textNodes=legendContainer.selectAll("text").nodes();for(var longestWidth=0,i=0;ilongestWidth&&(longestWidth=nodeWidth)}const legendWidth=longestWidth+legendSquareSize+20,legendHeight=(legendSquareSize+spaceBetweenLegends)*groups.length;legendBackground.attr("transform",`translate(-${legendWidth},0)`).append("rect").attr("fill","#e0e0e0e0").attr("height",legendHeight).attr("width",legendWidth);const constructors=["HexagonMap","SquareMap"];constructors.includes(plot.constructor.name)&&initButtonsLegend(plot)}return{initLegend:initLegend,initButtonsLegend:initButtonsLegend,hideButtonsLegend:hideButtonsLegend,showButtonsLegend:showButtonsLegend,getSelectedGroups:getSelectedGroups}})();class GraphProcessor{constructor(mapType){if(this.constructor==GraphProcessor)throw new Error("GraphProcessor is an Abstract class, can't be instantiated.");this.mapType=mapType}getNeighborsCoordinates(center){throw new Error("Abstract Method getNeighborsCoordinates(center) has no implementation")}getSurroundingIds(center,matrix){throw new Error("Abstract Method getSurroundingIds(center,matrix) has no implementation")}getValidNeighborsCoordinates(center,matrix){for(var coords=this.getNeighborsCoordinates(center),possibleNeighbors=coords.length,validCoords=[],i=0;i=0&&y>=0&&ydelete node[attr])}}getLocatedNodes(){return this._locatedNodes}_processNodes(nodes){nodes.forEach(node=>{if(!node.hasOwnProperty("id"))throw new Error("Node doesn't have a well defined id");node.isPlaced=!1}),this._numberOfPendingNodes=nodes.length}setCenterLabel(label){"string"==typeof label&&(label=label.trim(),0!=label.length&&this.mindmap.hasLabel(label)&&this.setProperties({centerNode:label}))}locateNodes(){const{nameField:nameField}=this.getProperties();this.cleanProcessor(),this._singles=[];const{nodes:nodes}=this.mindmap.getData();if(0!=nodes.length){var{centerNode:centerNode}=this.getProperties();null!=centerNode&&this.mindmap.hasLabel(centerNode)||this.setCenterLabel(nodes[0][nameField]);var{centerNode:centerNode}=this.getProperties(),node=this.mindmap.getNodeInfoByLabel(centerNode),nodesBeingLocated=this.locateNode(node);this.placeNodes(nodesBeingLocated);for(var i=0;i!1===this.mindmap.getNodeInfoById(id).isPlaced).length;if(0===numberOfNeighbors)return this._singles.push(node),[];const c=Math.ceil(this._numberOfPendingNodes/2),cx=c,cy=c,{id:id}=node;node.x=cx,node.y=cy,node.isPlaced=!0,this._numberOfPendingNodes--;var nodesBeingLocated=[node],rows=2*cy+1,cols=2*cx+1,matrix=Array(rows).fill(null).map(()=>Array(cols).fill(-1));return matrix[cy][cx]=id,this.locateChildren([node],nodesBeingLocated,matrix),this.centerNodes(nodesBeingLocated),nodesBeingLocated}locateChildren(nodes,nodesBeingLocated,matrix){var nodesForNextIteration=[];nodes.forEach(node=>{const{id:id}=node,children=this.mindmap.getNeighborsById(id).filter(id=>!1===this.mindmap.getNodeInfoById(id).isPlaced),center=[node.x,node.y],validCoordinates=this.processor.getValidNeighborsCoordinates(center,matrix),nChildrensToPlace=Math.min(children.length,validCoordinates.length);for(var i=0;i0&&this.locateChildren(nodesForNextIteration,nodesBeingLocated,matrix)}matricesAreOverlapping(A,B,bx,by,emptyValue=-1){const A_rows=A.length;if(0==A_rows)return!1;if(by>=A_rows)return!1;const A_cols=A[0].length;if(0==A_cols)return!1;if(bx>=A_cols)return!1;const B_rows=B.length;if(0==B_rows)return!1;const B_cols=B[0].length;if(0==B_cols)return!1;const x0=bx,x1=Math.min(A_cols,bx+B_cols),y0=by,y1=Math.min(A_rows,by+B_rows);for(var B_x=0,A_x=x0;A_x=0&&!this.matricesAreOverlapping(A,B,x_i,y_i);y_i-=decrease)yPad=y_i;return{xPad:xPad,yPad:yPad}}getMaxVerticalOverlap(A,B){const A_rows=A.length;if(0==A_rows)throw new Error("A matrix is empty");const A_cols=A[0].length;for(var xPadMin=0,yPadMin=A_rows,x_i=0;x_iArray(cols).fill(-1)),i=0;imaxCols&&(y+=2,x=0)}return singles}locateSinglesHexagon(singles,maxCols){const nSingles=singles.length;for(var x=0,y=0,i=0;imaxCols&&(y++,x=y%2==0?0:1)}return singles}locateSingles(){const singles=this._singles,maxCols=Math.ceil(Math.sqrt(singles.length));return"hexagon"==this.mapType?this.locateSinglesHexagon(singles,maxCols):"square"==this.mapType?this.locateSinglesSquare(singles,maxCols):void 0}_padNodes(nodes,xPad,yPad){return nodes.forEach(function(node){node.x+=xPad,node.y+=yPad})}}class Visualization{constructor(plotId,props){this.removeUndefinedKeys(props),this.plotId=plotId,this.tooltip=null,this.tooltipChart=null,this.tooltipSubPlot=null,this.tooltipChartProps={},this.properties={disableSaveButtons:!1,margin:{top:0,right:0,left:0,bottom:0},fontSize:14,fontFamily:"sans-serif",enableAutoResize:!1,enableZoom:!1,nameField:"displayname",valueField:"value",initialZoom:1},this._buttons=[],this._removedElements=[],this._subPlotProperties={},this._initProperties(props),this.restartSVG()}_initProperties(props){const{width:width=100,height:height=100,backgroundColor:backgroundColor="#F9F9F9",colors:colors=[],enableTooltip:enableTooltip=!1,minWidth:minWidth=width,maxWidth:maxWidth=width,scale:scale="linear",parentHtmlTag:parentHtmlTag="div",subPlotField:subPlotField="subPlot",subPlotTypeField:subPlotTypeField="plotType",actionOnClick:actionOnClick="recenter",uniqueName:uniqueName=null,initialPosition:initialPosition=[0,0],hideLegend:hideLegend=!1,nameField:nameField,valueField:valueField,margin:margin,enableZoom:enableZoom,fontSize:fontSize,fontFamily:fontFamily,enableAutoResize:enableAutoResize,disableSaveButtons:disableSaveButtons,initialZoom:initialZoom}=props;this._parentHtmlTag=parentHtmlTag,this._initialPosition=initialPosition,this.setInitialZoom(initialZoom),this._currentPosition=initialPosition,this._currentZoom=this.properties.initialZoom,this._width=width,this._height=height,this.setColors(colors),this.setBackgroundColor(backgroundColor),this.enableZoom(enableZoom),this._minWidth=minWidth,this._maxWidth=maxWidth,this.setScale(scale),this.hideLegend(hideLegend),this._enableTooltip=enableTooltip,this._legends=null,this._subPlotField=subPlotField,this._subPlotTypeField=subPlotTypeField,this.setPlotData([]),this.setActionOnClick(actionOnClick),this._uniqueName=uniqueName;const propsVerifiedByType={nameField:nameField,valueField:valueField,margin:margin,enableZoom:enableZoom,fontSize:fontSize,fontFamily:fontFamily,enableAutoResize:enableAutoResize,disableSaveButtons:disableSaveButtons};this.setProperties(propsVerifiedByType)}setInitialZoom(zoom){"number"!=typeof zoom||isNaN(zoom)||zoom<=0||(this.properties.initialZoom=zoom)}removeUndefinedKeys(props){null!=props&&Object.keys(props).forEach(prop=>{null==props[prop]&&delete props[prop]})}setProperties(props){if(props.constructor===Object){this.removeUndefinedKeys(props);var{nameField:nameField,valueField:valueField,margin:margin,enableZoom:enableZoom,fontFamily:fontFamily,fontSize:fontSize,enableAutoResize:enableAutoResize,disableSaveButtons:disableSaveButtons,initialZoom:initialZoom}=props,width=this._width,height=this._height;props.hasOwnProperty("width")&&(width=props.width),props.hasOwnProperty("height")&&(height=props.height),this.setSize(width,height),props.hasOwnProperty("backgroundColor")&&this.setBackgroundColor(props.backgroundColor),props.hasOwnProperty("colors")&&this.setColors(props.colors),props.hasOwnProperty("minWidth")&&(this._minWidth=props.minWidth),props.hasOwnProperty("maxWidth")&&(this._maxWidth=props.maxWidth),props.hasOwnProperty("enableTooltip")&&this.enableTooltip(props.enableTooltip),props.hasOwnProperty("subPlotField")&&(this._subPlotField=props.subPlotField),props.hasOwnProperty("actionOnClick")&&this.setActionOnClick(props.actionOnClick),props.hasOwnProperty("uniqueName")&&(this._uniqueName=props.uniqueName),props.hasOwnProperty("scale")&&this.setScale(props.scale),props.hasOwnProperty("hideLegend")&&this.hideLegend(props.hideLegend),this.setMargin(margin),"string"==typeof fontFamily&&(this.properties.fontFamily=fontFamily),"number"==typeof fontSize&&(this.properties.fontSize=fontSize),"boolean"==typeof disableSaveButtons&&(this.properties.disableSaveButtons=disableSaveButtons),"boolean"==typeof enableAutoResize&&this.enableAutoResize(enableAutoResize),this.enableZoom(enableZoom),"string"==typeof nameField&&(this.properties.nameField=nameField),"string"==typeof valueField&&(this.properties.valueField=valueField),this.setInitialZoom(initialZoom),this._refreshComponents()}}getProperties(){var properties={innerWidth:this._innerWidth,innerHeight:this._innerHeight,width:this._width,height:this._height,backgroundColor:this._backgroundColor,colors:this._colors,enableZoom:this._enableZoom,enableTooltip:this._enableTooltip,minWidth:this._minWidth,maxWidth:this._maxWidth,subPlotField:this._subPlotField,actionOnClick:this._actionOnClick,uniqueName:this._uniqueName,initialPosition:this._initialPosition,currentZoom:this._currentZoom,currentPosition:this._currentPosition,autoResize:this.properties.enableAutoResize};properties=Object.assign({},this.properties,properties);return properties}setPlotData(plotData){null!=plotData&&(this._plotData=plotData)}setSubPlotProperties(props={}){this._subPlotProperties=props}getPlotData(){return this._plotData}refresh(){const data=this.getPlotData();if(this.plot(data),null!=this.tooltipChart&&null!=this.tooltipSubPlot){const tooltipProps=this.tooltipChartProps;this.enableTooltipChart("basiclinechart",tooltipProps)}}plot(data){console.log("Plot Method is undefined for ",this.constructor.name)}hideLegend(hide){"boolean"==typeof hide&&(this._hideLegend=hide)}setLegend(legends){this._legends=legends,wordplot.legends.initLegend(this)}enableTooltip(enable){const oldValue=this._enableTooltip;!0!==enable&&!1!==enable||(this._enableTooltip=enable,oldValue!=enable&&(enable?this._createTooltip():(this.tooltip.cleanSVG(),this.tooltip.getComponents().div.remove(),this.tooltip=null)))}enableZoom(enable){!0!==enable&&!1!==enable||(this._enableZoom=enable,this._refreshComponents())}enableAutoResize(enable){!0!==enable&&!1!==enable||(this.properties.enableAutoResize=enable),this._refreshComponents()}setActionOnClick(action){null!=action&&"string"==typeof action&&(action=action.toLowerCase(),this._actionOnClick=action)}enableTooltipChart(plotType,props={}){if(null==plotType)return;if("string"!=typeof plotType)return;var{outerSVG:outerSVG}=this.getComponents();const tooltipId=this.plotId+"_tooltip_chart";outerSVG.selectAll("svg#"+tooltipId).data([null]).enter().append("svg").attr("class","tooltipChart").attr("id",tooltipId);this.tooltipChartProps=props;const{padding:padding=20}=props,tooltip=new wordplot.Tooltip(tooltipId,props);this.tooltipChart=tooltip;const tooltipWidth=this._width-2*padding,tooltipHeight=this._height-2*padding;tooltip.setSize(tooltipWidth,tooltipHeight),tooltip.hide();const funcAfterHide=()=>{if(null==this.tooltipChart)return;const{innerSVG:innerSVG}=this.getComponents();innerSVG.style("opacity",1)},funcAfterShow=()=>{if(null==this.tooltipChart)return;const{innerSVG:innerSVG}=this.getComponents();innerSVG.style("opacity",.2)};switch(tooltip.executeFunctionAfterHide(funcAfterHide),tooltip.executeFunctionAfterShowing(funcAfterShow),props.parentHtmlTag="svg",plotType){case"basiclinechart":props.parentHtmlTag="svg";const tooltipId=this.plotId+"_tooltip_chart";this.tooltipSubPlot=new wordplot.line.BasicLineChart(tooltipId,props);break;default:console.log(`TooltipChart is not implemented for plotType = ${plotType}`)}}_showTooltipChart(){const tooltip=this.tooltipChart;if(null==this.tooltipChart)return;this.tooltipChart.show();const{innerSVG:innerSVG}=this.getComponents();innerSVG.style("opacity",.2);const tooltipSVG=tooltip.getComponents().outerSVG;tooltipSVG.style("opacity",1)}_hideTooltipChart(){if(null==this.tooltipChart)return;this.tooltipChart.hide();const{innerSVG:innerSVG}=this.getComponents();innerSVG.style("opacity",1)}getColor(group){if(group>=this._colors.length)for(;this._colors.length<=group;){var color=Math.floor(16777216*Math.random()).toString(16);color="#000000".slice(0,-color.length)+color,this._colors.push(color)}return this._colors[group]}setScale(scale){switch(scale){case"log":case"linear":case"sqrt":case"pow":case"flat":this._scale=scale;break;default:console.log("Error executing setColorScale: Valid Scales [ log, linear, sqrt, pow, flat ]")}}getScale(domain,range){switch(this._scale){case"log":var scale=d3.scaleSymlog();break;case"flat":case"linear":scale=d3.scaleLinear();break;case"sqrt":scale=d3.scaleSqrt();break;case"pow":scale=d3.scalePow()}return scale.domain(domain).nice().range(range),scale}_scaleValue(value){switch(this._scale){case"log":const defVal=1e-4;return value=Math.log(value),Math.max(value,defVal);case"linear":return value;case"sqrt":return Math.sqrt(value);case"pow":return Math.pow(value,2);case"flat":return 1;default:return console.log("Invalid Color scale -> ",this._scale),value}}setColors(colors){Array.isArray(colors)?this._colors=colors:console.log("Error executing setColors(colors), colors must be an Array of strings")}setSize(width,height){width>0&&(this._width=width),height>0&&(this._height=height),this._recalculateInnerSize()}cleanSVG(){const{outerSVG:outerSVG}=this.getComponents();outerSVG.remove()}restartSVG(){ this.cleanSVG(),this._initContainer()}setMargin(margin){if(null!=margin&&margin.constructor===Object){var m=this.properties.margin;margin.hasOwnProperty("top")&&(m.top=margin.top),margin.hasOwnProperty("bottom")&&(m.bottom=margin.bottom),margin.hasOwnProperty("left")&&(m.left=margin.left),margin.hasOwnProperty("right")&&(m.right=margin.right),this._recalculateInnerSize()}}_recalculateInnerSize(){var{margin:margin,width:width,height:height}=this.getProperties();this._innerWidth=width-margin.left-margin.right,this._innerHeight=height-margin.top-margin.bottom,this._refreshComponents()}_setTextProperties(text){var{fontSize:fontSize,fontFamily:fontFamily}=this.getProperties();text.style("font-size",fontSize+"px").style("font-family",fontFamily)}setBackgroundColor(color){this._backgroundColor=color;const{background:background}=this.getComponents();background.attr("fill",this._backgroundColor)}getComponents(){var div=d3.select(this._parentHtmlTag+"#"+this.plotId);const titleId=this.plotId+"_title";var titleSVG=div.select("svg#"+titleId),outerSVG=div.select("svg.outerSVG"),innerSVG=outerSVG.select("svg.innerSVG"),background=innerSVG.select("rect.background"),container=innerSVG.select("g.container"),legendContainer=outerSVG.selectAll("g.legend");return{div:div,outerSVG:outerSVG,innerSVG:innerSVG,container:container,background:background,titleSVG:titleSVG,legendContainer:legendContainer}}_initContainer(){var div=d3.select(this._parentHtmlTag+"#"+this.plotId);if(div.empty())return void console.log("Could not find a "+this._parentHtmlTag+" tag with id="+this.plotId);const{width:width,fontFamily:fontFamily,backgroundColor:backgroundColor}=this.getProperties(),TITLE_FONT_SIZE="24px",TITLE_HEIGHT="30px",titleId=this.plotId+"_title",titleSVG=div.selectAll("svg#"+titleId).data([null]).enter().append("svg").attr("id",titleId).style("width",width).style("height",TITLE_HEIGHT).style("display","none");titleSVG.selectAll("text").data([null]).enter().append("text").attr("y",TITLE_FONT_SIZE).attr("x","50%").style("font-family",fontFamily).style("font-size",TITLE_FONT_SIZE).style("text-anchor","middle").style("text-transform","capitalize");var expansorSVG=div.selectAll("svg.expansor").data([null]).enter().append("svg").attr("class","expansor");expansorSVG.style("width","100%").style("height","0px");var outerSVG=div.selectAll("svg.outerSVG").data([null]).enter().append("svg").attr("class","outerSVG"),innerSVG=outerSVG.selectAll("svg.innerSVG").data([null]).enter().append("svg").attr("class","innerSVG");innerSVG.selectAll("rect.background").data([null]).enter().append("rect").attr("class","background").attr("fill",backgroundColor).attr("width","100%").attr("height","100%"),innerSVG.selectAll("g.container").data([null]).enter().append("g").attr("class","container");this._refreshComponents(),!0===this._enableTooltip&&this._createTooltip(),this._drawButtons()}_createTooltip(){const{container:container}=this.getComponents(),tooltipId=this.plotId+"_tooltip";container.selectAll("svg#"+tooltipId).data([null]).enter().append("svg").attr("class","tooltip").attr("id",tooltipId);const{fontFamily:fontFamily,fontSize:fontSize}=this.getProperties(),tooltipProps={fontSize:fontSize,fontFamily:fontFamily};null===this.tooltip?this.tooltip=new wordplot.Tooltip(tooltipId,tooltipProps):this.tooltip.restartSVG(),this.tooltip.hide()}_refreshComponents(){const{div:div,outerSVG:outerSVG,innerSVG:innerSVG,container:container,background:background}=this.getComponents(),{width:width,height:height,innerWidth:innerWidth,innerHeight:innerHeight,margin:margin,backgroundColor:backgroundColor,initialPosition:initialPosition,initialZoom:initialZoom,maxWidth:maxWidth,minWidth:minWidth,autoResize:autoResize}=this.getProperties();outerSVG.attr("viewBox",`0 0 ${width} ${height}`),background.attr("fill",backgroundColor),innerSVG.attr("width",innerWidth).attr("height",innerHeight).attr("x",margin.left).attr("y",margin.top);const thisPlot=this,[initialX,initialY]=initialPosition,zoom=d3.zoom();this._enableZoom?innerSVG.call(zoom.on("zoom",function(event){container.attr("transform",event.transform);const x=event.transform.x,y=event.transform.y;thisPlot._currentZoom=event.transform.k,thisPlot._currentPosition=[x,y]})):innerSVG.call(zoom.on("zoom",null)),innerSVG.call(zoom.transform,d3.zoomIdentity.translate(initialX,initialY).scale(initialZoom)),div.style("height",height+"px").style("width",width+"px"),!0===autoResize&&div.style("max-width",maxWidth).style("min-width",minWidth).style("height","unset").style("width","100%"),wordplot.legends.initLegend(this)}addButton(buttonInfo={},onClick){if(null==buttonInfo)buttonInfo={};buttonInfo=Object.assign({x:0,y:0,width:100,height:30,label:"Button",backgroundColor:"gray"},buttonInfo);buttonInfo.onClick=onClick;const{outerSVG:outerSVG}=this.getComponents();this._buttons.push(buttonInfo),this._drawButtons()}_drawButtons(){const buttons=this._buttons,{outerSVG:outerSVG}=this.getComponents();var button=outerSVG.selectAll("rect.button").data(buttons).enter().append("svg").attr("class","button").attr("width",d=>d.width).attr("height",d=>d.height).attr("x",d=>d.x).attr("y",d=>d.y);button.append("rect").attr("class","buttonBackground").attr("fill",d=>d.backgroundColor).attr("width","100%").attr("height","100%").on("click",(event,data)=>{data.onClick()}),button.append("text").attr("class","buttonText").text(d=>d.label).attr("y","50%").attr("x","50%").style("text-anchor","middle").style("dominant-baseline","middle").on("click",(event,data)=>{data.onClick()}),button.style("cursor","pointer")}showEmbeddedVisualizationFromUrl(url,plotType,uniqueName=null){d3.json(url).then(json=>this.showEmbeddedVisualization(json,plotType,uniqueName))}showEmbeddedVisualization(json,plotType,uniqueName=null){const plotId=this.plotId;var subPlot=null,props=(plotType=plotType.toLowerCase(),this.getProperties());switch(props.uniqueName=uniqueName,delete props.nameField,delete props.valueField,delete props.margin,delete props.enableAutoResize,delete props.enableTooltip,delete props.enableZoom,delete props.hideNumber,props=wordplot.helpers.mergeDictionaries(props,this._subPlotProperties),plotType){case"hexagon":case"square":subPlot=wordplot.wordmap.buildWordMap(plotId,json,plotType,props);break;case"topbarchart":case"barchart":case"basicbarchart":case"barchartgroup":subPlot=wordplot.bars.buildBarChart(plotId,json,plotType,props);break;case"basiclinechart":subPlot=new wordplot.line.BasicLineChart(plotId,props);subPlot.plot(json);break;case"linechart":case"top20":case"barchart":default:return void console.log("ShowEmbeddedVisualization is not implemented for plotType = "+plotType)}if(null==subPlot)return;this._setSubPlot(subPlot),subPlot._setSuperPlot(this),subPlot.refresh();const backButtonProperties={label:"⏎ Back"};subPlot.addButton(backButtonProperties,()=>{this._setSubPlot(null),subPlot._backToSuperPlot()})}_backToSuperPlot(){if(this.hasOwnProperty("_superPlot")){var superPlotType=this._superPlot.constructor;switch(superPlotType){case wordplot.wordmap.HexagonMap:this._backToSuperPlotMap();break;default:console.log("BackToSuperPlot is not implemented for Plot Type "+superPlotType)}}}_backToSuperPlotMap(){if(!this.hasOwnProperty("_superPlot"))return;const superPlot=this._superPlot,data=superPlot.graphToMap.getLocatedNodes();superPlot.plot(data)}_setSubPlot(subPlot){this._subPlot=subPlot}_setSuperPlot(superPlot){this._superPlot=superPlot}setNameField(nameField){this.properties.nameField=nameField}setValueField(valueField){this.properties.valueField=valueField}getStorableComponent(){var{outerSVG:outerSVG}=this.getComponents();return outerSVG}showMessage(message){this.cleanSVG();const{div:div}=this.getComponents();div.append("text").text(message).attr("id","loadingText").attr("x",0).attr("y",30)}removeElementByName(elementName){const data=this.getPlotData(),{nameField:nameField}=this.getProperties(),index=data.findIndex(d=>d[nameField]==elementName);if(index<0)return void console.log("removeElementByName() : Element not found");const removedElement=data.splice(index,1)[0];this._removedElements.push(removedElement),this.refresh()}setTitle(title){null!=title&&"string"==typeof title&&(title=title.replace(/_/g," "),this._title=title,this._showTitle())}_showTitle(){const title=this._title,{titleSVG:titleSVG}=this.getComponents();titleSVG.style("display","unset"),titleSVG.select("text").text(title)}}class AxisVisualization extends Visualization{constructor(plotId,props={}){super(plotId,props)}addAxis(axis,position){const{margin:margin,innerHeight:innerHeight}=this.getProperties(),{outerSVG:outerSVG}=this.getComponents();switch(position){case"bottom":var gAxis=outerSVG.selectAll("g.axisBottom").data([null]).enter().append("g").attr("class","axisBottom").attr("transform",`translate(${margin.left},${innerHeight+margin.top})`).call(axis),axisText=gAxis.selectAll("text");this._setTextProperties(axisText);break;case"left":gAxis=outerSVG.selectAll("g.axisLeft").data([null]).enter().append("g").attr("class","axisLeft").attr("transform",`translate(${margin.left},${margin.top})`).call(axis),axisText=gAxis.selectAll("text");this._setTextProperties(axisText);break;case"right":case"top":return void console.log(`Error executing addAxis(axis,position) Position ${position} not implemented yet`);default:return void console.log("Error executing addAxis(axis,position) Supported Positions: [bottom, left]")}return gAxis}wrapAxis(position,length){const{outerSVG:outerSVG}=this.getComponents();var axisId="";switch(position){case"left":axisId="axisLeft";break;case"bottom":axisId="axisBottom";break;default:console.log("Error executing addAxis(axis,position) Supported Positions: [bottom, left]")}const gAxis=outerSVG.selectAll(`g.${axisId}`),axisText=gAxis.selectAll("text");axisText.call(wordplot.helpers.wrapLines,length)}}var helpers=function(){function getSplittedText(text,width,textObject){const splittedText=[];var originalWords=text.split(/\s+/).reverse(),words=[];originalWords.forEach(d=>words.push(d.charAt(0).toUpperCase()+d.slice(1)));for(var word=null,line=[],tspan=textObject.append("tspan").attr("dy","0em").attr("id","_TEMPORAL");word=words.pop();)if(line.push(word),tspan.text(line.join(" ")),tspan.node().getComputedTextLength()>width&&(line.length>1&&(line.pop(),splittedText.push(line.join(" ")),line=[word],tspan.text("")),tspan.node().getComputedTextLength()>width&&1===line.length)){var length=word.length,i=length-1;line.pop();do{var subWord=line.join(" ")+" "+word.substring(0,i)+"-",remain=word.substring(i,length);tspan.text(subWord),i--}while(tspan.node().getComputedTextLength()>width&&i>0);words.push(remain),splittedText.push(subWord),line=[],tspan.text("")}return line.length>0&&splittedText.push(line.join(" ")),textObject.select("tspan#_TEMPORAL").remove(),splittedText}function wrapLines(text,width){text.each(function(){var text=d3.select(this),originalWords=text.text().split(/\s+/).reverse(),words=[];originalWords.forEach(d=>words.push(d.charAt(0).toUpperCase()+d.slice(1)));var word=null,line=[],lineHeight=1.1,x=text.attr("x");null==x&&(x="0px");for(var tspan=text.text(null).append("tspan").attr("x",x).attr("dy","0em");word=words.pop();)if(line.push(word),tspan.text(line.join(" ")),tspan.node().getComputedTextLength()>width&&(line.length>1&&(line.pop(),tspan.text(line.join(" ")),line=[word],tspan=text.append("tspan").attr("x",x).attr("dy",lineHeight+"em").text(word)),tspan.node().getComputedTextLength()>width&&1===line.length)){var length=word.length,i=length-1;line.pop();do{var subWord=line.join(" ")+" "+word.substring(0,i)+"-",remain=word.substring(i,length);tspan.text(subWord),i--}while(tspan.node().getComputedTextLength()>width&&i>0);words.push(remain),line=[],tspan=text.append("tspan").attr("x",x).attr("dy",lineHeight+"em").text("")}})}function invertColor(hex){0===hex.indexOf("#")&&(hex=hex.slice(1)),6!=hex.length&&console.log("Invalid Hex Color:",hex);var r=parseInt(hex.slice(0,2),16),g=parseInt(hex.slice(2,4),16),b=parseInt(hex.slice(4,6),16);return.299*r+.587*g+.114*b>170?"#000000":"#FFFFFF"}function increaseBrightness(hex,percent){100===percent&&(percent=99),hex=hex.replace(/^\s*#|\s*$/g,"");var r=parseInt(hex.substr(0,2),16),g=parseInt(hex.substr(2,2),16),b=parseInt(hex.substr(4,2),16),nr=(0|256+r+(256-r)*percent/100).toString(16).substr(1),ng=(0|256+g+(256-g)*percent/100).toString(16).substr(1),nb=(0|256+b+(256-b)*percent/100).toString(16).substr(1),newHex="#"+nr+ng+nb;return newHex}function sortArrayOfObjects(array,fieldName){if(0===array.length)return array;var sorted=array.sort((a,b)=>b[fieldName]-a[fieldName]);return sorted}function readjustFontSize(textObject,textContent,fontSize,maxWidth){textObject.style("font-size",fontSize+"px").html(textContent),textObject.call(wordplot.helpers.wrapLines,maxWidth)}function mergeDictionaries(baseDict,newValues){var merge={};return Object.assign(merge,baseDict),Object.assign(merge,newValues),merge}return{increaseBrightness:increaseBrightness,invertColor:invertColor,wrapLines:wrapLines,sortArrayOfObjects:sortArrayOfObjects,getSplittedText:getSplittedText,readjustFontSize:readjustFontSize,mergeDictionaries:mergeDictionaries}}();class TopBarChartGroup{constructor(plotId,json,props={}){const{elemsPerGroup:elemsPerGroup=20}=props;this.elemsPerGroup=elemsPerGroup,this.barChart=new wordplot.bars.TopBarChart(plotId,elemsPerGroup,props),this.plotId=plotId,this.data=json.data,this.cleanSVG(),this.createDropDownMenu(this.data),this.refreshGraphic()}setColors(colors){this.barChart.setColors(colors)}getComponents(){return this.barChart.getComponents()}getStorableComponent(){return null==this.barChart?null:this.barChart.getStorableComponent()}setProperties(props){this.barChart.setProperties(props),this.refreshGraphic()}setMargin(margin){this.barChart.setMargin(margin)}updateGroups(){for(var nElements=this.data.length,nGroups=Math.ceil(nElements/this.elemsPerGroup),groupList=document.getElementById("groupList"),i=0;ib.value-a.value);const data=wordplot.json.nodesToStatistics(nodes);props.valueField="value";const plot=new wordplot.bars.TopBarChartGroup(plotId,data,props),color="#08233B",colors=[],minPercent=0,maxPercent=80;for(var i=0;i=0&&p<1&&(this._padding=p)}horizontalPlot(data){this.setPlotData(data),this.restartSVG();var thisPlot=this,{margin:margin,innerWidth:innerWidth,innerHeight:innerHeight,nameField:nameField,valueField:valueField}=this.getProperties();const{outerSVG:outerSVG,container:container}=this.getComponents();var svg=container,y=d3.scaleBand().domain(data.map(function(d){return d[nameField]})).range([0,innerHeight]).padding(thisPlot._padding),xDomain=[0,d3.max(data,d=>Math.max(d[valueField]))],xRange=[0,innerWidth-30],x=this.getScale(xDomain,xRange),onClickFunction=()=>{};switch(this._actionOnClick){case"remove":onClickFunction=((action,data)=>{this.removeElementByName(data[nameField])})}svg.selectAll("rect").data(data).enter().append("rect").attr("id","bar").attr("concept",function(d){return d[nameField]}).attr("x",function(){return 0}).attr("y",function(d,j){return y(d[nameField])}).attr("width",function(d){return x(d[valueField])}).attr("height",function(){return y.bandwidth()}).attr("fill",function(d,j){return thisPlot.getColor(j)}).on("click",onClickFunction).on("mouseover",function(e,d){var thisConcept=d[nameField];d3.selectAll("rect#bar").attr("opacity",function(f){return f[nameField]==thisConcept?1:.1}),d3.selectAll("text#barValue").attr("opacity",function(f){return f[nameField]==thisConcept?1:.1}).style("font-weight",function(f){return f[nameField]==thisConcept?"bold":"normal"}),d3.selectAll("text#barName").attr("opacity",function(f){return f==thisConcept?1:.1}).style("font-weight",function(f){return f==thisConcept?"bold":"normal"})}).on("mouseout",function(e,d){d3.selectAll("rect#bar").attr("opacity",1),d3.selectAll("text#barValue").attr("opacity",1).style("font-weight","normal"),d3.selectAll("text#barName").attr("opacity",1).style("font-weight","normal")});var barValues=outerSVG.selectAll("text.barValue").data(data).enter().append("text").attr("class","barValue").attr("concept",function(d){return d[nameField]}).attr("y",function(d,j){return y(d[nameField])+.6*y.bandwidth()+margin.top}).attr("x",function(d){return x(Math.max(d[valueField],0))+3+margin.left}).text(function(d){return d[valueField]}).style("fill",function(d,j){return"black"});this._setTextProperties(barValues);var yAxis=d3.axisLeft(y).tickSizeInner(10).tickSizeOuter(0);this.addAxis(yAxis,"left");this.wrapAxis("left",margin.left-13-3)}}class BarChart extends AxisVisualization{constructor(plotId,props={}){super(plotId,props);const{orientation:orientation="horizontal",padding:padding=.2,valuesField:valuesField="demand",width:width=600,height:height=600}=props;switch(this._orientation=orientation,this.setPadding(padding),this.setValuesField(valuesField),this.setSize(width,height),this.enableZoom(!1),orientation){case"vertical":this.setMargin({top:0,right:10,bottom:40,left:0}),this.plot=this.verticalPlot;break;case"horizontal":this.setMargin({top:0,right:50,bottom:10,left:100}),this.plot=this.horizontalPlot;break;default:this.plot=function(){console.log("Error executing BarChart.plot(): Valid Orientations [ vertical, horizontal ]")}}}setProperties(props){super.setProperties(props),props.hasOwnProperty("padding")&&this.setPadding(props.padding),props.hasOwnProperty("valuesField")&&this.setValuesField(props.valuesField)}setPadding(p){p>=0&&p<1&&(this._padding=p)}setValuesField(vf){this._valuesField=vf}verticalPlot(data,legends=[]){if(this.setPlotData(data),this.restartSVG(),0==data.length)return;const thisPlot=this,valuesField=this._valuesField;var{margin:margin,width:width,height:height,innerWidth:innerWidth,innerHeight:innerHeight,fontFamily:fontFamily,fontSize:fontSize,nameField:nameField}=this.getProperties();const{outerSVG:outerSVG,container:container}=this.getComponents(),svg=container;var x0=d3.scaleBand().rangeRound([0,innerWidth]).domain(data.map(function(d){return d[nameField]})).padding(thisPlot._padding),x1=d3.scaleBand().domain(d3.range(data[0][valuesField].length)).range([0,x0.bandwidth()]),yDomain=[0,d3.max(data,d=>Math.max(Math.max.apply(null,d[valuesField])))],yRange=[innerHeight,30],y=this.getScale(yDomain,yRange);svg.selectAll("g").data(data).enter().append("g").each(function(item){var g=d3.select(this);g.selectAll("rect").data(item[valuesField]).enter().append("rect").attr("x",function(value,j){return x0(item[nameField])+x1(j)}).attr("y",function(value){return y(value)}).attr("width",function(){return x1.bandwidth()}).attr("height",function(value){return Math.abs(y(0)-y(value))}).attr("fill",function(d,j){return thisPlot.getColor(j)});var barLabels=g.selectAll("text.label").data(item[valuesField]).enter().append("text").attr("class","label").attr("x",function(value,j){return x0(item[nameField])+x1(j)+x1.bandwidth()/2}).attr("y",function(value){return y(Math.max(value,0))-4}).text(function(value){return value}).style("fill","black").style("text-anchor","middle");thisPlot._setTextProperties(barLabels)});var xAxis=d3.axisBottom(x0).tickSizeInner(10).tickSizeOuter(0);this.addAxis(xAxis,"bottom"),null!=legends&&0!=legends.length||(legends=this._legends);var legend=function(svg){const g=svg.attr("transform",`translate(${width},0)`).style("text-anchor","end").style("font-family",fontFamily).style("font-size",fontSize).selectAll("g").data(legends).join("g").attr("transform",(d,i)=>`translate(0,${20*i})`);g.append("rect").attr("x",-19).attr("width",19).attr("height",19).attr("fill",function(d,i){return thisPlot.getColor(i)}),g.append("text").attr("x",-24).attr("y",9.5).attr("dy","0.35em").text(function(l){return l})};outerSVG.append("g").call(legend)}horizontalPlot(data,legends){if(this.setPlotData(data),this.restartSVG(),0==data.length)return;const thisPlot=this,valuesField=this._valuesField;var{margin:margin,width:width,height:height,innerWidth:innerWidth,innerHeight:innerHeight,fontFamily:fontFamily,fontSize:fontSize,nameField:nameField}=this.getProperties();const{outerSVG:outerSVG,container:container}=this.getComponents(),svg=container,y0=d3.scaleBand().rangeRound([0,innerHeight]).domain(data.map(function(d){return d[nameField]})).padding(thisPlot._padding),y1=d3.scaleBand().domain(d3.range(data[0][valuesField].length)).range([0,y0.bandwidth()]);var xDomain=[0,d3.max(data,d=>Math.max(Math.max.apply(null,d[valuesField])))],xRange=[0,innerWidth-40],x=this.getScale(xDomain,xRange);svg.selectAll("g").data(data).enter().append("g").each(function(item){var g=d3.select(this);g.selectAll("rect").data(item[valuesField]).enter().append("rect").attr("x",function(){return 0}).attr("y",function(value,j){return y0(item[nameField])+y1(j)}).attr("width",function(value){return Math.abs(x(value))}).attr("height",function(value,j){return y1.bandwidth()}).attr("fill",function(d,j){return thisPlot.getColor(j)});var barLabels=g.selectAll("text.label").data(item[valuesField]).enter().append("text").attr("class","label").attr("y",function(value,j){return y0(item[nameField])+y1(j)+.7*y1.bandwidth()}).attr("x",function(value){return x(Math.max(value,0))+3}).text(function(value){return value}).style("fill",function(d,j){return"black"});thisPlot._setTextProperties(barLabels)});var yAxis=d3.axisLeft(y0).tickSizeInner(10).tickSizeOuter(0);this.addAxis(yAxis,"left"),this.wrapAxis("left",margin.left-13-3),null!=legends&&0!=legends.length||(legends=this._legends);var legend=function(svg){const g=svg.attr("transform",`translate(${width},0)`).style("text-anchor","end").style("font-family",fontFamily).style("font-size",fontSize+"px").selectAll("g").data(legends).join("g").attr("transform",(d,i)=>`translate(0,${20*i})`);g.append("rect").attr("x",-19).attr("width",19).attr("height",19).attr("fill",function(d,i){return thisPlot.getColor(i)}),g.append("text").attr("x",-24).attr("y",9.5).attr("dy","0.35em").text(function(l){return l})};outerSVG.append("g").call(legend)}}class TopBarChart extends BasicBarChart{constructor(plotId,nTop=20,props={}){const DEFAULT_TOPBARCHART_PROPS={valueField:"relevancy"};props=wordplot.helpers.mergeDictionaries(DEFAULT_TOPBARCHART_PROPS,props),super(plotId,props),this.nTop=nTop,this._parentPlot=this.plot,this.plot=this.topChartPlot}topChartPlot(data){this.setPlotData(data);var topData=this.getTopResults(data);this._parentPlot(topData),this.setPlotData(data)}getTopResults(data){if(0==data.length)return data;var top=this.nTop,{valueField:valueField}=this.getProperties(),sorted=data.sort(function(a,b){return b[valueField]-a[valueField]});return sorted.slice(0,top)}setNumberTop(nTop){this.nTop=nTop,this.refresh()}refresh(){const data=this.getPlotData();this.plot(data)}}class BarChartGroup{constructor(plotId,data,legend,props={}){const{elemsPerGroup:elemsPerGroup=3}=props;this.elemsPerGroup=elemsPerGroup,this.barChart=new BarChart(plotId,props),this.plotId=plotId,this.data=data,this.legend=legend,this.cleanSVG(),this.createDropDownMenu(data),this.refreshGraphic()}getComponents(){return this.barChart.getComponents()}getStorableComponent(){return null==this.barChart?null:this.barChart.getStorableComponent()}setProperties(props){this.barChart.setProperties(props),this.refreshGraphic()}setMargin(margin){this.barChart.setMargin(margin)}updateGroups(){for(var nElements=this.data.length,nGroups=Math.ceil(nElements/this.elemsPerGroup),groupList=document.getElementById("groupList"),i=0;i=0;j--)values.push(d[valuesField][j].value);elem[valuesField]=values,processedData.push(elem)}),processedData}_processLegend(data){var legend=[];const valuesField=this.valuesField;if(data.length>0)for(var elem=data[0],j=elem[valuesField].length-1;j>=0;j--){var d=elem[valuesField][j],year=d.year,month=d.month,date=this._buildDateStr(year,month);legend.push(date)}return legend}_buildDateStr(year,month){var date=`${year}/${month}/01`;return date=new Date(date),date.toLocaleString("en",{month:"short",year:"numeric"})}_processColors(data,yearColors=null){var colors=[];const valuesField=this.valuesField;if(data.length>0){null==yearColors&&(yearColors={});for(var elem=data[0],j=elem[valuesField].length-1;j>=0;j--){var d=elem[valuesField][j],year=d.year;if(!yearColors.hasOwnProperty(year)){var yColor=Math.floor(16777216*Math.random()).toString(16);yColor="#000000".slice(0,-yColor.length)+yColor,yearColors[year]=yColor}var month=d.month,color=wordplot.helpers.increaseBrightness(yearColors[year],month/14*100);colors.push(color)}}return colors}}return{BarChart:BarChart,BarChartGroup:BarChartGroup,BasicBarChart:BasicBarChart,BarChartDataProcessor:BarChartDataProcessor,TopBarChart:TopBarChart,TopBarChartGroup:TopBarChartGroup,buildBarChart:buildBarChart}}();const save=(()=>{function exportPng(plot){_saveVisualization(plot,"png")}function exportSvg(plot){_saveVisualization(plot,"svg")}function _saveVisualization(plot,format){format=format.toLowerCase();var saveFunction=()=>{};if("png"==format)saveFunction=saveSvgAsPng;else{if("svg"!=format)return void console.log(`Error at saveVisualization() -> incorrect format ${format}`);saveFunction=saveSvg}const currentPlot=plot,components=currentPlot.getComponents();if(components.hasOwnProperty("outerSVG"))var internalButtons=components.outerSVG.selectAll("svg.button");else internalButtons=d3.select();internalButtons.style("display","none");var svgToPlot=currentPlot.getStorableComponent();const translateBackup=svgToPlot.attr("transform");if(svgToPlot.attr("transform","translate(0,0) scale(1)"),null!=currentPlot._uniqueName)var fileName=`${currentPlot._uniqueName}.${format}`;else fileName=`plot.${format}`;saveFunction(svgToPlot.node(),fileName).then(()=>internalButtons.style("display","unset")).then(()=>{svgToPlot.attr("transform",translateBackup)})}return{exportSvg:exportSvg,exportPng:exportPng}})();class WordMap extends Visualization{constructor(mapType,plotId,props={}){const DEFAULT_MAP_PROPS={enableZoom:!0,hideNumber:!0,valueFieldToShow:"value"};if(props=wordplot.helpers.mergeDictionaries(DEFAULT_MAP_PROPS,props),super(plotId,props),this.mapType=mapType,this.constructor==WordMap)throw new Error("WordMap is an Abstract class, can't be instantiated.");this.graphToMap=null,this._obtainTooltipData=null,this._groupToColorIndex={}, this.centerCameraAround=null,this._actionOnClickFunction=(()=>{})}_initProperties(props){super._initProperties(props),this.properties={...this.properties,defaultCamera:!0},this._showActionButtons=!0;var{sourceField:sourceField="sources",categoryField:categoryField="group",mouseOverDisabled:mouseOverDisabled=!1,showActionButtons:showActionButtons=!0,centerNode:centerNode=null,centerCameraAround:centerCameraAround=null,hideNumber:hideNumber,valueFieldToShow:valueFieldToShow,initialZoom:initialZoom}=props;this._categoryField=categoryField,this._sourceField=sourceField,this._mouseOverDisabled=!1,this.disableMouseOver(mouseOverDisabled),this.showActionButtons(showActionButtons),this.hideNumber(hideNumber);const propsVerifiedByType={initialZoom:initialZoom,valueFieldToShow:valueFieldToShow,centerCameraAround:centerCameraAround,centerNode:centerNode};this.setProperties(propsVerifiedByType)}setProperties(props){if(null==props)return;if("object"!=typeof props)return details;super.setProperties(props);var requiresDataRefresh=!1;const{initialZoom:initialZoom,centerCameraAround:centerCameraAround}=props;if("string"==typeof props.valueFieldToShow&&(this.valueFieldToShow=props.valueFieldToShow,props.hideNumber=!1),"string"==typeof props.categoryField&&(this._categoryField=props.categoryField,this._initColorIndices()),"number"==typeof initialZoom&&initialZoom>0&&(this.properties.defaultCamera=!1),props.hasOwnProperty("sourceField")&&(this._sourceField=props.sourceField),props.hasOwnProperty("colors")&&this._initColorIndices(),props.hasOwnProperty("showActionButtons")&&this.showActionButtons(props.showActionButtons),props.hasOwnProperty("mouseOverDisabled")&&this.disableMouseOver(props.mouseOverDisabled),props.hasOwnProperty("hideNumber")&&this.hideNumber(props.hideNumber),props.hasOwnProperty("centerNode")&&this.setCenterNode(props.centerNode),"string"==typeof centerCameraAround&&this.setCenterCameraAround(centerCameraAround),null!=this.mindmap){const{reprocess:reprocess,changes:changes}=this.mindmap.setProperties(props);!0===reprocess&&(requiresDataRefresh=!0)}if(null!=this.graphToMap){const graphChanges=this.graphToMap.setProperties(props).changes;null!=graphChanges.centerNode&&(requiresDataRefresh=!0)}return!0===requiresDataRefresh?(console.log("REFRESHING DATA"),void this.refreshData()):void 0}setCenterCameraAround(centerCameraAround){"string"==typeof centerCameraAround&&(null!=this.mindmap?this.mindmap.hasLabel(centerCameraAround)&&(this.centerCameraAround=centerCameraAround):this.centerCameraAround=centerCameraAround)}_initColorIndicesAux(groups){if(!Array.isArray(groups))return;const groupsInt=[];groups.forEach(d=>groupsInt.push(Number.parseInt(d)));const sortedGroups=groupsInt.sort(function(a,b){return a-b});for(var i=0;i=this._colors.length){var color=Math.floor(16777216*Math.random()).toString(16);color="#000000".slice(0,-color.length)+color;this._colors.push(color)}}}_initColorIndices(){if(null==this.graphToMap)return;this._groupToColorIndex={};const{categoryField:categoryField}=this.getProperties(),groups=[];this.graphToMap.getLocatedNodes().forEach(function(d){const group=d[categoryField];groups.includes(group)||groups.push(group)}),this._initColorIndicesAux(groups)}getColor(group){const groupAlreadyRegistered=this._groupToColorIndex.hasOwnProperty(group),index=Object.keys(this._groupToColorIndex).length,needsMoreColors=index>this._colors.length;if(needsMoreColors||!groupAlreadyRegistered){var color=Math.floor(16777216*Math.random()).toString(16);color="#000000".slice(0,-color.length)+color;this._colors.push(color)}groupAlreadyRegistered||(this._groupToColorIndex[group]=index);const colorIndex=this._groupToColorIndex[group];return this._colors[colorIndex]}showActionButtons(enable){"boolean"==typeof enable&&(this._showActionButtons=enable,wordplot.wordmap.interaction.initializeButtons(this))}setCenterNode(centerLabel){if("string"!=typeof centerLabel)return;if(this.properties.centerNodeLabel=centerLabel,null==this.mindmap)return;const centerInfo=this.mindmap.getNodeInfoByLabel(centerLabel),centerId=centerInfo.id;this.properties.centerNodeId=centerId}disableMouseOver(disable){"boolean"==typeof disable&&(this._mouseOverDisabled=disable)}refresh(){super.refresh()}validateParameters(){var{centerNodeId:centerNodeId,centerNodeLabel:centerNodeLabel}=this.getProperties();null==centerNodeId&&null!=centerNodeLabel&&this.setCenterNode(centerNodeLabel)}getProperties(){var properties={hideNumber:this._hideNumber,categoryField:this._categoryField,colors:this._colors,actionButtons:this._actionButtons,centerCameraAround:this.centerCameraAround,sourceField:this._sourceField};properties=Object.assign(super.getProperties(),properties);return properties}hideNumber(hide){!0!==hide&&!1!==hide||(this._hideNumber=hide)}setGraphToMap(graphToMap){null!=graphToMap&&(this.graphToMap=graphToMap,this.mindmap=graphToMap.mindmap,this._initColorIndices())}_refreshCenter(nodeId){if(null==this.graphToMap)return void console.log("WordMap doesn't have a well defined graphToMap processor");this.properties.centerNodeId=nodeId,this.graphToMap.locateNodesAround(nodeId);const newNodes=this.graphToMap.getLocatedNodes();this.plot(newNodes)}_showTooltipInfo(nodeId){if(!1===this._enableTooltip)return;var nodeInfo=this.mindmap.getNodeInfoById(nodeId),nodeSVG=this.getComponents().container.select(`svg.concept[nodeId="${nodeId}"]`);if(!nodeInfo.hasOwnProperty("tooltipInfo"))return;const tooltip=this.tooltip;var explains=nodeInfo.tooltipInfo;tooltip.restartSVG(),explains.forEach(e=>{tooltip.addLink(e.url,e.title),tooltip.addLine("\n")});const x=Number(nodeSVG.attr("x"))-(tooltip._width-Number(nodeSVG.attr("width")))/2,y=Number(nodeSVG.attr("y"))-tooltip._height+15;tooltip.move(x,y),this.tooltip.show()}setFunctionToObtainTooltipData(f){"function"==typeof f&&(this._obtainTooltipData=f)}getStorableComponent(){if(null!=this.graphToMap){var recenteredNodes=this.graphToMap.getLocatedNodes();this.plot(recenteredNodes)}else this.refresh();const{container:container}=this.getComponents(),svgToPlot=container;return svgToPlot}setInitialPosition(x,y){"number"==typeof x&&"number"==typeof y&&(isNaN(x)||isNaN(y)||(this._initialPosition=[x,y]))}_highlightAllNodes(){const{innerSVG:innerSVG}=this.getComponents(),allNodes=innerSVG.selectAll("svg.concept");allNodes.style("opacity","1").style("font-weight","normal"),allNodes.selectAll("line").style("opacity","1")}_unHighlightAllNodes(){const{innerSVG:innerSVG}=this.getComponents(),allNodes=innerSVG.selectAll("svg.concept");allNodes.style("opacity","0.3").style("font-weight","normal"),allNodes.selectAll("line").style("opacity","0.3")}_highlightListOfNodes(nodes){const{innerSVG:innerSVG}=this.getComponents(),{centerNodeId:centerNodeId}=this.getProperties(),This=this,categoryField=this._categoryField,allNodes=this.mindmap.getData().nodes;var maxValue=allNodes[0].value;maxValue=this._scaleValue(maxValue);Array.isArray(nodes)&&nodes.forEach(function(nId){const nodeInfo=This.graphToMap.mindmap.getNodeInfoById(nId),nodeSVG=innerSVG.select(`svg.concept[nodeId="${nId}"]`);if(nodeSVG.style("opacity","1"),nodeSVG.selectAll("line").style("opacity","1"),nId!=centerNodeId){var value=This._scaleValue(nodeInfo.value),percentBrightness=This.scaleBrightness(value,maxValue),color=(percentBrightness=Math.max(percentBrightness,0),This.getColor(nodeInfo[categoryField]));color=wordplot.helpers.increaseBrightness(color,percentBrightness);nodeSVG.select("path").attr("fill",color)}})}scaleBrightness(value,maxValue,minBright=0,maxBright=80){var brightness=1-value/maxValue,percentBrightness=brightness*(maxBright-minBright)+minBright;return percentBrightness}_highlightNode(nodeId){if(null==nodeId)return;if(null==this.graphToMap)return;const neighbors=this.mindmap.getNeighborsById(nodeId),{innerSVG:innerSVG}=this.getComponents(),allNodes=innerSVG.selectAll("svg.concept");allNodes.style("opacity","0.3").style("font-weight","normal"),allNodes.selectAll("line").style("opacity","0.3");const mainNode=innerSVG.select(`svg.concept[nodeId="${nodeId}"]`);mainNode.style("font-weight","bold"),this._highlightListOfNodes([nodeId].concat(neighbors))}refreshData(){this.graphToMap.locateNodes();const newPlotData=this.graphToMap.getLocatedNodes();this.setPlotData(newPlotData),this.refresh()}removeElementByName(elementName){this.mindmap.removeElementByLabel(elementName),this.refreshData()}removeListOfElementsByName(listOfElements){Array.isArray(listOfElements)&&0!=listOfElements.length&&(this.mindmap.removeListOfElementsByName(listOfElements),this.refreshData())}removeElementById(elementId){this.mindmap.removeElementById(elementId),this.graphToMap.locateNodes();const newPlotData=this.graphToMap.getLocatedNodes();this.setPlotData(newPlotData),this.refresh()}translateVisualization(x,y,scale){const zoom=d3.zoom(),transform=`translate(${x},${y}) scale(${scale})`;this.getComponents().container.attr("transform",transform),this.getComponents().innerSVG.call(zoom.transform,d3.zoomIdentity.translate(x,y).scale(scale))}addZoomButtons(){const zoomButtonSize=30,separation=5,zoomInButtonInfo={x:separation+1*zoomButtonSize,y:0,width:zoomButtonSize,height:zoomButtonSize,label:"➕",backgroundColor:"white"},zoomIn=()=>{const increaseFactor=.2,[x,y]=this._currentPosition,scale=this._currentZoom+increaseFactor;this.translateVisualization(x,y,scale),this._currentPosition=[x,y],this._currentZoom=scale};this.addButton(zoomInButtonInfo,zoomIn);const buttonInfo={x:0,y:0,width:zoomButtonSize,height:zoomButtonSize,label:"➖",backgroundColor:"white"},zoomOut=()=>{const increaseFactor=.2,[x,y]=this._currentPosition,scale=this._currentZoom-increaseFactor;this.translateVisualization(x,y,scale),this._currentPosition=[x,y],this._currentZoom=scale};this.addButton(buttonInfo,zoomOut)}setActionOnClick(action){if("string"!=typeof action)return;if(0==action.length)return;action=action.toLowerCase(),wordplot.wordmap.interaction.changeOnClickAction(this,action);const{container:container}=this.getComponents();var concepts=container.selectAll("svg.concept");concepts.on("click",this._actionOnClickFunction)}}class HexagonMap extends WordMap{constructor(plotId,props={}){const DEFAULT_HEXAGONMAP_PROPS={strokeWidth:3,strokeColor:"#000000",hexagonRadius:70,spaceBetweenHexagons:.5,width:800,height:600,enableZoom:!0,nameField:"label"};props=wordplot.helpers.mergeDictionaries(DEFAULT_HEXAGONMAP_PROPS,props),super("hexagon",plotId,props),this._initProperties(props)}_initProperties(props){super._initProperties(props);const{strokeWidth:strokeWidth,strokeColor:strokeColor,hexagonRadius:hexagonRadius,spaceBetweenHexagons:spaceBetweenHexagons,width:width,height:height}=props;this.setStrokeWidth(strokeWidth),this.setStrokeColor(strokeColor),this.setHexagonRadius(hexagonRadius),this.setSpaceBetween(spaceBetweenHexagons),this.setSize(width,height)}setProperties(props){super.setProperties(props),props.hasOwnProperty("strokeWidth")&&this.setStrokeWidth(props.strokeWidth),props.hasOwnProperty("strokeColor")&&this.setStrokeColor(props.strokeColor),props.hasOwnProperty("hexagonRadius")&&this.setHexagonRadius(props.hexagonRadius),props.hasOwnProperty("spaceBetweenHexagons")&&this.setSpaceBetween(props.spaceBetweenHexagons)}getProperties(){var properties={strokeWidth:this._strokeWidth,strokeColor:this._strokeColor,hexagonRadius:this._hexaRadius,spaceBetweenHexagons:this._spaceBetweenHexa};properties=Object.assign(super.getProperties(),properties);return properties}setStrokeWidth(sw){sw>0&&(this._strokeWidth=sw)}setSpaceBetween(space){space>0&&(this._spaceBetweenHexa=space)}setHexagonRadius(radius){radius>0&&(this._hexaRadius=radius)}setStrokeColor(color){this._strokeColor=color}centerCamera(label,zoom){if("number"!=typeof zoom)return;if(1==this.properties.defaultCamera)return;if("string"==typeof label&&0!=label.length||(label=this.graphToMap.getProperties().centerNode),!this.mindmap.hasLabel(label))return console.log(`Error at centerCamera() : Label "${label}" was not found`),this.properties.defaultCamera=!0,void(this.properties.centerCameraAround=null);var concept=this.mindmap.getNodeInfoByLabel(label);const radius=this._hexaRadius,hexaWidth=radius*Math.sqrt(3),hexaHeight=2*radius;var xIndex=concept.x,yIndex=concept.y,xConcept=this.getCenter(radius,yIndex,xIndex)[0];xConcept-=hexaWidth/2;var yConcept=this.getCenter(radius,yIndex,xIndex)[1];yConcept-=hexaHeight/2;var x=this._width/2/zoom-hexaWidth/2-xConcept;x*=zoom;var y=this._height/2/zoom-hexaHeight/2-yConcept;y*=zoom,this.setInitialZoom(zoom),this.setInitialPosition(x,y)}plot(data){this.validateParameters();var{centerCameraAround:centerCameraAround,initialZoom:initialZoom,categoryField:categoryField,nameField:nameField,centerNodeId:centerNodeId}=this.getProperties();!1===this.properties.defaultCamera&&this.centerCamera(centerCameraAround,initialZoom),this.restartSVG();var This=this;if(this.setPlotData(data),0==data.length)return;var hexaRadius=this._hexaRadius,hexaHeight=2*hexaRadius,hexaWidth=hexaRadius*Math.sqrt(3),rows=Math.max.apply(Math,data.map(function(o){return o.y}))+1,cols=Math.max.apply(Math,data.map(function(o){return o.x}))+1,height=3*(rows+1/3)/2*hexaRadius,width=(cols+.5)*Math.sqrt(3)*hexaRadius;const{container:container}=this.getComponents();var svg=container,hexbin=d3.hexbin().radius(hexaRadius).extent([[0,0],[width,height]]),concepts=svg.selectAll("svg.concept").data(data).enter().append("svg").attr("class","concept").attr("nodeId",d=>d.id).attr("height",hexaHeight).attr("width",hexaWidth).attr("x",function(d){var cx=This.getCenter(hexaRadius,d.y,d.x)[0];return cx-hexaWidth/2}).attr("y",function(d){var cy=This.getCenter(hexaRadius,d.y,d.x)[1];return cy-hexaHeight/2});concepts.on("mouseover",function(d){if(!0!==This._mouseOverDisabled&&!["highlight"].includes(This._actionOnClick)){var nodeId=this.getAttribute("nodeId");This._highlightNode(nodeId)}}),concepts.on("mouseout",function(d){if(!0!==This._mouseOverDisabled&&!["highlight"].includes(This._actionOnClick)){!0===This._enableTooltip&&This.tooltip.hide();var nodeId=this.getAttribute("nodeId");This._unHighlightNode(nodeId)}}),concepts.on("click",this._actionOnClickFunction),!0===this._showActionButtons&&wordplot.wordmap.interaction.initializeButtons(this),concepts.on("contextmenu",function(event){event.preventDefault();var nodeId=this.getAttribute("nodeId"),nodeInfo=This.graphToMap.mindmap.getNodeInfoById(nodeId);nodeInfo.hasOwnProperty("tooltipInfo")||null==This._obtainTooltipData||This._obtainTooltipData(event),This._showTooltipInfo(nodeId)});var maxValue=data.sort(function(a,b){return parseFloat(b.value)-parseFloat(a.value)})[0].value;maxValue=This._scaleValue(maxValue);var hexagons=concepts.append("path").attr("d",hexbin.hexagon(hexaRadius-This._spaceBetweenHexa)).attr("transform",function(d){return"translate("+hexaWidth/2+","+hexaHeight/2+")"});hexagons.attr("fill",function(d){var value=d.value;value=This._scaleValue(value);var percentBrightness=This.scaleBrightness(value,maxValue),color=This.getColor(d[categoryField]);color=wordplot.helpers.increaseBrightness(color,percentBrightness);return color});var text=concepts.append("text").attr("class","textInside").attr("x","50%").attr("y","40%").style("pointer-events","none").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("fill",function(d){var value=d.value;value=This._scaleValue(value);var percentBrightness=This.scaleBrightness(value,maxValue),color=This.getColor(d[categoryField]);color=wordplot.helpers.increaseBrightness(color,percentBrightness);return color=wordplot.helpers.invertColor(color),color}).text(function(d){var line=d[nameField];const conceptHasField=d.hasOwnProperty(This.valueFieldToShow),isNumerical=!isNaN(d[This.valueFieldToShow]);return!This._hideNumber&&conceptHasField&&isNumerical&&(line=line+"\t("+d[This.valueFieldToShow]+")"),line.replace(/_/g," ")});this._setTextProperties(text),text.call(wordplot.helpers.wrapLines,hexaWidth),text.each(function(d){var text=d3.select(this),nLines=text.selectAll("tspan").size();nLines>=5&&text.attr("y","25%"),4==nLines&&text.attr("y","35%"),1==nLines&&text.attr("y","45%")}),this.drawBorders(svg,hexaRadius),!0===this._enableTooltip&&this.tooltip.getComponents().div.raise(),this._boldNode(centerNodeId),wordplot.logo.initLogo(this),!0===this.properties.defaultCamera&&wordplot.wordmap.centerMap(this)}getCenter(hexaRadius,row,col){var x=hexaRadius*col*Math.sqrt(3);row%2==1&&(x+=hexaRadius*Math.sqrt(3)/2);var y=hexaRadius*row*1.5;return[x+hexaRadius,y+hexaRadius]}drawBorders(){const r=this._hexaRadius,{container:container}=this.getComponents(),svg=container;for(var w=Math.sqrt(3)*r,s=0,v={a:[0+s,r/2],b:[w/2,0],c:[w-s,r/2],d:[w-s,3*r/2],e:[w/2,2*r],f:[0+s,3*r/2]},hexagonEdges={s1:{from:v.a,to:v.b},s2:{from:v.b,to:v.c},s3:{from:v.c,to:v.d},s4:{from:v.d,to:v.e},s5:{from:v.e,to:v.f},s6:{from:v.f,to:v.a}},sides=["s1","s2","s3","s4","s5","s6"],i=0;i{const nodeInfo=This.mindmap.getNodeInfoById(nodeId),nodeSVG=innerSVG.select(`svg.concept[nodeId="${nodeId}"]`);var value=This._scaleValue(nodeInfo.value),percentBrightness=This.scaleBrightness(value,maxValue),color=This.getColor(nodeInfo[categoryField]);color=wordplot.helpers.increaseBrightness(color,percentBrightness),nodeSVG.select("path").attr("fill",color)}),this._boldNode(centerNodeId)}}class HexagonGraphProcessor extends GraphProcessor{constructor(){super("hexagon"),this.adjacentCoordinatesOrder=["s3","s6","s5","s4","s1","s2"]}getSurroundingIds(center,matrix){for(var ids={},coords=this.getNeighborsCoordinates(center),sidesOrder=this.adjacentCoordinatesOrder,i=0;i=0&&y>=0&&y=0&&(this._spaceBetweenSquares=space)}setSquareSize(size){size>0&&(this._squareSize=size)}centerCamera(label,zoom){if("number"==typeof zoom&&1!=this.properties.defaultCamera){if("string"==typeof label&&0!=label.length||(label=this.graphToMap.getProperties().centerNode),this.mindmap.hasLabel(concept))return console.log(`Error at centerCamera() : Label "${label}" was not found`),this.properties.defaultCamera=!0,void(this.properties.centerCameraAround=null);var concept=this.mindmap.getNodeInfoByLabel(label),figSize=this._squareSize,spaceBetween=this._spaceBetweenSquares,xIndex=concept.x,yIndex=concept.y,xConcept=xIndex*(figSize+spaceBetween),yConcept=yIndex*(figSize+spaceBetween),x=this._width/2/zoom-figSize/2-xConcept;x*=zoom;var y=this._height/2/zoom-figSize/2-yConcept;y*=zoom,this.setInitialZoom(zoom),this.setInitialPosition(x,y)}}plot(data){this.validateParameters();const{centerCameraAround:centerCameraAround,initialZoom:initialZoom,categoryField:categoryField,nameField:nameField,centerNodeId:centerNodeId}=this.getProperties();!1===this.properties.defaultCamera&&this.centerCamera(centerCameraAround,initialZoom);const squareCurvature=10;this.restartSVG();var This=this,spaceBetween=this._spaceBetweenSquares,squareSize=this._squareSize;const{container:container}=this.getComponents();var svg=container,concepts=svg.selectAll("svg.concept").data(data).enter().append("svg").attr("class","concept").attr("nodeId",d=>d.id).attr("height",squareSize).attr("width",squareSize).attr("x",function(d){return d.x*(squareSize+spaceBetween)}).attr("y",function(d){return d.y*(squareSize+spaceBetween)});concepts.on("mouseover",function(d){if(!["highlight"].includes(This._actionOnClick)){var nodeId=this.getAttribute("nodeId");This._highlightNode(nodeId)}}),concepts.on("mouseout",function(d){if(!["highlight"].includes(This._actionOnClick)){!0===This._enableTooltip&&This.tooltip.hide();var nodeId=this.getAttribute("nodeId");This._unHighlightNode(nodeId)}}),concepts.on("click",this._actionOnClickFunction),!0===this._showActionButtons&&wordplot.wordmap.interaction.initializeButtons(this),concepts.on("contextmenu",function(event){event.preventDefault();var nodeId=this.getAttribute("nodeId"),nodeInfo=This.graphToMap.mindmap.getNodeInfoById(nodeId);nodeInfo.hasOwnProperty("tooltipInfo")||null==This._obtainTooltipData||This._obtainTooltipData(event),This._showTooltipInfo(nodeId)}),this.drawBorders();var maxValue=data.sort(function(a,b){return parseFloat(b.value)-parseFloat(a.value)})[0].value;maxValue=this._scaleValue(maxValue),concepts.append("rect").attr("x","1%").attr("y","1%").attr("height","98%").attr("width","98%").attr("ry",squareCurvature).attr("rx",squareCurvature).attr("class","conceptSquare").attr("fill",function(d){var value=d.value;value=This._scaleValue(value);var percentBrightness=This.scaleBrightness(value,maxValue),color=This.getColor(d[categoryField]);color=wordplot.helpers.increaseBrightness(color,percentBrightness);return color});var text=concepts.append("text").attr("class","textInside").attr("x","50%").attr("y","50%").style("pointer-events","none").attr("text-anchor","middle").attr("dominant-baseline","middle").attr("fill",function(d){var value=d.value,percentBrightness=This.scaleBrightness(value,maxValue),color=This.getColor(d[categoryField]);color=wordplot.helpers.increaseBrightness(color,percentBrightness);return color=wordplot.helpers.invertColor(color),color}).text(function(d){var line=d[nameField];const conceptHasField=d.hasOwnProperty(This.valueFieldToShow),isNumerical=!isNaN(d[This.valueFieldToShow]);return!This._hideNumber&&conceptHasField&&isNumerical&&(line=line+"\t("+d[This.valueFieldToShow]+")"),line.replace(/_/g," ")});this._setTextProperties(text),text.call(wordplot.helpers.wrapLines,This._squareSize),text.each(function(d){var text=d3.select(this);This._adjustTextHeight(text)}),!0===this._enableTooltip&&this.tooltip.getComponents().div.raise(),this._boldNode(centerNodeId),wordplot.logo.initLogo(this),!0===this.properties.defaultCamera&&wordplot.wordmap.centerMap(this)}_adjustTextHeight(text){var nLines=text.selectAll("tspan").size();nLines>=6&&text.attr("y","1em"),5==nLines&&text.attr("y","15%"),4==nLines&&text.attr("y","30%"),3==nLines&&text.attr("y","35%"),2==nLines&&text.attr("y","45%"),1==nLines&&text.attr("y","50%")}drawBorders(){const{container:container}=this.getComponents();for(var concepts=container.selectAll("svg.concept"),sides=["s1","s2","s3","s4","s5","s6","s7","s8"],i=0;i=0&&y>=0&&y0&&(this._strokeWidth=width)}setErrorField(name){this._errorField=name}setValuesField(name){this._valuesField=name}setBoxSize(width,height){width>=0&&height>=0&&(this._boxSize=[width,height],this._detailBox.style("height",height).style("width",width))}_hideCircles(){const{container:container}=this.getComponents();var circles=container.selectAll("circle.tipcircle");circles.style("opacity",0)}_restoreSeries(){const{outerSVG:outerSVG,container:container}=this.getComponents();outerSVG.selectAll("g[id=legend]").style("opacity",1),container.selectAll("path[id=line]").style("stroke-width",this._strokeWidth+"px").style("opacity",this._lineOpacity),container.selectAll("path[id=confidence]").style("opacity",this._confidenceOpacity)}_highlightSeries(concept){var thisPlot=this;const{outerSVG:outerSVG,container:container}=this.getComponents();container.selectAll("path#line").style("stroke-width",function(){return this.getAttribute("concept")===concept?"6px":thisPlot._strokeWidth}).style("opacity",function(){return this.getAttribute("concept")===concept?1:.1}),container.selectAll("path[id=confidence]").style("opacity",function(a){return this.getAttribute("concept")===concept?.5:.05}),outerSVG.selectAll("g[id=legend]").style("opacity",function(a){return this.getAttribute("concept")===concept?1:.05})}_highlightCircles(concept){const{container:container}=this.getComponents();var circles=container.selectAll("circle.tipcircle");circles.filter(function(){return this.getAttribute("concept")==concept}).style("opacity",.6)}plot(data,labels=null,title=null){if(this.restartSVG(),null==data||!Array.isArray(data)||0==data.length)return void this.showMessage("Error at SimpleLineChart.plot() : input data is invalid");if(0==data.length)return void this.showMessage("Empty data");if(this.setTimeLabels(labels),labels=this.timeLabels,null==labels||!Array.isArray(labels)||labels.length invalid format`),labels=[];for(var i=0;i0&&(this._strokeWidth=width)}_createDetailBox(){const{fontFamily:fontFamily,fontSize:fontSize}=this.getProperties();var detailBox=d3.select(this._detailBoxParent).selectAll("#"+this._detailBoxId).data([null]).enter().append("div").attr("id",this._detailBoxId).attr("class","detailBox").style("opacity",0).style("font-size",fontSize+"px").style("font-family",fontFamily).style("font-weight","bold").style("width",this._boxSize[0]+"px").style("height",this._boxSize[1]+"px").style("text-align","center").style("position","absolute").style("border-radius","6px").style("border","0px").style("display","inline").style("pointer-events","none").style("line-height",1.3);this._detailBox=detailBox}_destoyDetailBox(){d3.selectAll("div#"+this._detailBoxId).remove()}setDetailBoxParent(p){this._detailBoxParent=p}setErrorField(name){this._errorField=name}setValuesField(name){this._valuesField=name}setBoxSize(width,height){width>=0&&height>=0&&(this._boxSize=[width,height],this._detailBox.style("height",height).style("width",width))}buildDate(year,month){var date=`${year}/${month}/01`;return date=new Date(date),date}_hideCircles(){const{container:container}=this.getComponents();var circles=container.selectAll("circle.tipcircle");circles.style("opacity",0)}_restoreSeries(){const{outerSVG:outerSVG,container:container}=this.getComponents();outerSVG.selectAll("g[id=legend]").style("opacity",1),container.selectAll("path[id=line]").style("stroke-width",this._strokeWidth+"px").style("opacity",this._lineOpacity),container.selectAll("path[id=confidence]").style("opacity",this._confidenceOpacity)}_highlightSeries(concept){var thisPlot=this;const{outerSVG:outerSVG,container:container}=this.getComponents();container.selectAll("path#line").style("stroke-width",function(){return this.getAttribute("concept")===concept?"6px":thisPlot._strokeWidth}).style("opacity",function(){return this.getAttribute("concept")===concept?1:.1}),container.selectAll("path[id=confidence]").style("opacity",function(a){return this.getAttribute("concept")===concept?.5:.05}),outerSVG.selectAll("g[id=legend]").style("opacity",function(a){return this.getAttribute("concept")===concept?1:.05})}_highlightCircles(concept){const{container:container}=this.getComponents();var circles=container.selectAll("circle.tipcircle");circles.filter(function(){return this.getAttribute("concept")==concept}).style("opacity",.6)}plot(data){this.restartSVG(),this._createDetailBox();var thisPlot=this,strokeWidth=this._strokeWidth,confidenceOpacity=this._confidenceOpacity;const{nameField:nameField}=this.getProperties();var valuesField=this._valuesField,errorField=this._errorField,{width:width,height:height,innerWidth:innerWidth,innerHeight:innerHeight,margin:margin}=this.getProperties(),detailBox=this._detailBox;const{outerSVG:outerSVG,container:container}=this.getComponents();var svg=container,mainSVG=outerSVG,x=d3.scaleTime().domain([d3.min(data,function(c){return d3.min(c[valuesField],function(v){return thisPlot.buildDate(v.year,v.month)})}),d3.max(data,function(c){return d3.max(c[valuesField],function(v){return thisPlot.buildDate(v.year,v.month)})})]).range([0,innerWidth]),y=d3.scaleLinear().domain([Math.min(0,d3.min(data,function(c){return d3.min(c[valuesField],function(v){return Number(v.value)})})),d3.max(data,function(c){return d3.max(c[valuesField],function(v){var value=Number(v.value);return v.hasOwnProperty(errorField)&&(value+=Number(v[errorField])),value})})]).range([innerHeight,0]);svg.selectAll("g").data(data).enter().append("g").each(function(item,index){d3.select(this).append("path").datum(item[valuesField]).attr("fill",thisPlot.getColor(index)).attr("stroke","none").style("opacity",confidenceOpacity).attr("id","confidence").attr("concept",item[nameField]).attr("d",d3.area().x(function(d){return x(thisPlot.buildDate(d.year,d.month))}).y0(function(d){var error=d.hasOwnProperty(errorField)?d[errorField]:0,n=y(Number(d.value)+Number(error));return n}).y1(function(d){var error=d.hasOwnProperty(errorField)?d[errorField]:0,n=y(Number(d.value)-Number(error));return n}))}).each(function(item,index){d3.select(this).append("path").datum(item[valuesField]).attr("fill","none").attr("id","line").attr("stroke",thisPlot.getColor(index)).attr("concept",item[nameField]).attr("d",d3.line().x(function(d){return x(thisPlot.buildDate(d.year,d.month))}).y(function(d){return y(d.value)})).attr("stroke-width",strokeWidth+"px").attr("opacity",thisPlot._lineOpacity).on("mouseover",function(b){var concept=this.getAttribute("concept");thisPlot._highlightSeries(concept)}).on("mouseout",function(d){thisPlot._restoreSeries()})}).each(function(item,index){d3.select(this).selectAll("circle").data(item[valuesField]).enter().append("circle").attr("value",function(d){return d.value}).attr("class","tipcircle").attr("concept",item[nameField]).attr("cx",function(d){return x(thisPlot.buildDate(d.year,d.month))}).attr("cy",function(d){return y(d.value)}).attr("r",8).style("opacity",0).style("fill",thisPlot.getColor(index)).attr("title",item[nameField]).on("mouseover",function(){var concept=this.getAttribute("concept");thisPlot._highlightCircles(concept),thisPlot._highlightSeries(concept),detailBox.style("opacity",thisPlot._boxOpacity)}).on("mousemove",function(d){var year=this.__data__.year,month=this.__data__.month,value=this.__data__.value,date=thisPlot.buildDate(year,month).toLocaleString("en",{month:"short",year:"numeric"});detailBox.html(function(){return`${date}
${value}`}).style("color",wordplot.helpers.invertColor(thisPlot.getColor(index))).style("left",window.event.pageX+"px").style("top",window.event.pageY-50+"px").style("background-color",thisPlot.getColor(index))}).on("mouseout",function(){detailBox.style("opacity",0),thisPlot._restoreSeries(),thisPlot._hideCircles()})});var xAxis=d3.axisBottom().scale(x).tickFormat(d3.timeFormat("%b %Y")).ticks(6),yAxis=d3.axisLeft(y).ticks(5);this.addAxis(xAxis,"bottom"),this.addAxis(yAxis,"left");var legend=function(svg){const g=svg.attr("transform",`translate(${width},0)`).attr("text-anchor","end").selectAll("g").data(data).join("g").attr("transform",(d,i)=>`translate(0,${20*i})`).attr("concept",function(d,i){return d[nameField]}).attr("id","legend");g.append("rect").attr("x",-19).attr("width",19).attr("height",19).attr("fill",function(d,i){return thisPlot.getColor(i)}).on("mouseover",function(e,d){var concept=d[nameField];thisPlot._highlightSeries(concept)}).on("mouseout",function(d){thisPlot._restoreSeries()});var legendText=g.append("text").attr("x",-24).attr("y",9.5).attr("dy","0.35em").text(function(l){return l[nameField]});thisPlot._setTextProperties(legendText)};mainSVG.append("g").call(legend)}}class LineChartGroup{constructor(plotId,data,props={}){const{elemsPerGroup:elemsPerGroup}=props;this.data=data,this.elemsPerGroup=elemsPerGroup,this.lineChart=new LineChart(plotId,props),this.plotId=plotId,this.cleanSVG(),this.createDropDownMenu(data),this.refreshGraphic()}setProperties(props){this.lineChart.setProperties(props),this.refreshGraphic()}setNameField(name){this.lineChart.properties.nameField=name,this.refreshGraphic()}setDetailBoxParent(p){this.lineChart.setDetailBoxParent(p)}getComponents(){return this.lineChart.getComponents()}updateGroups(){for(var nElements=this.data.length,nGroups=Math.ceil(nElements/this.elemsPerGroup),groupList=document.getElementById("groupList"),i=0;i"data"==i.origin).map(i=>i.value).reduce((prev,next)=>Number(prev)+Number(next)),item.values=d.demand,processedData.push(item)}),processedData=wordplot.helpers.sortArrayOfObjects(processedData,"value"),processedData}function buildTopChart(plotId,json,props){var processedData=processData(json);const plot=new wordplot.top.TopChart(plotId,processedData,props);return plot}class TopChart{constructor(plotId,data,props){this.plotId=plotId,this._topChartId="topChart",this._miniTopChartId="miniTopChart",this._detailChartId="detailChart",this._data=data,this._initContainers();var orientation="horizontal";this._topChart=new wordplot.bars.BasicBarChart(this._topChartId,{orientation:orientation}),this._miniTopChart=new wordplot.bars.BasicBarChart(this._miniTopChartId,{orientation:orientation}),this._detailChart=new wordplot.line.LineChart(this._detailChartId),this.setNameField("name"),this.setValuesField("values"),this.setProperties(props),this.refresh()}setProperties(props){if(null==props)return;if(props.constructur==Object)return;const{width:width,height:height,maxWidth:maxWidth,minWidth:minWidth}=props,commonProperties={width:width},responsiveMode=null!=maxWidth&&null!=minWidth;responsiveMode&&(commonProperties.maxWidth=null,commonProperties.minWidth=null),this._setCommonProperties(commonProperties),responsiveMode&&this.setSize(minWidth,maxWidth);const topChartProps={height:height},detailChartProps={height:height-height/this._data.length,margin:{left:60,top:0,right:0,bottom:40}};this.setTopChartProperties(topChartProps),this.setDetailChartProperties(detailChartProps)}refresh(){this.plotTopChart()}setTopChartProperties(props){this._topChart.setProperties(props),this.plotTopChart()}setSize(minWidth,maxWidth){const{container:container}=this.getComponents();container.style("min-width",minWidth).style("max-width",maxWidth).style("width","100%").style("height","unset"),this._topChart.enableAutoResize(!0),this._detailChart.enableAutoResize(!0),this._miniTopChart.enableAutoResize(!0),this.refresh()}setDetailChartProperties(props){this._detailChart.setProperties(props),this.refresh()}setMiniTopChartProperties(props){this._miniTopChart.setProperties(props),this.refresh()}_setCommonProperties(props){this._miniTopChart.setProperties(props),this._detailChart.setProperties(props),this._topChart.setProperties(props),this.refresh()}cleanSVG(){var svg=d3.select("div#"+this.plotId);svg.selectAll("*").remove()}setNameField(name){this._topChart.setNameField(name),this._detailChart.setNameField(name),this._miniTopChart.setNameField(name),this.refresh()}setValuesField(name){this._detailChart.setValuesField(name),this.refresh()}setValueField(name){this._topChart.setValueField(name),this._detailChart.setValueField(name),this._miniTopChart.setValueField(name),this.refresh()}getComponents(){var container=d3.select("div#"+this.plotId),divDetailChart=container.select("div#"+this._detailChartId),divMiniTopChart=container.select("div#"+this._miniTopChartId),divTopChart=container.select("div#"+this._topChartId);return{container:container,divDetailChart:divDetailChart,divTopChart:divTopChart,divMiniTopChart:divMiniTopChart}}_initContainers(){const container=d3.select("div#"+this.plotId);container.selectAll("div#"+this._topChartId).data([null]).enter().append("div").attr("id",this._topChartId),container.selectAll("div#"+this._miniTopChartId).data([null]).enter().append("div").attr("id",this._miniTopChartId),container.selectAll("br.spaceBetween").data([null]).enter().append("br").attr("class","spaceBetween"),container.selectAll("div#"+this._detailChartId).data([null]).enter().append("div").attr("id",this._detailChartId)}_resetTopChart(){const{divTopChart:divTopChart}=this.getComponents();divTopChart.style("width",0).style("height",0),this._topChart.cleanSVG()}_resetDetailChart(){const{divDetailChart:divDetailChart}=this.getComponents();divDetailChart.style("width",0).style("height",0),this._detailChart.cleanSVG()}_resetMiniTopChart(){const{divMiniTopChart:divMiniTopChart}=this.getComponents();divMiniTopChart.style("width",0).style("height",0),this._miniTopChart.cleanSVG()}_setClickActionRectangles(state="inactive"){var thisPlot=this;d3.selectAll("rect[id=bar]").attr("state",state).on("click",function(event,item){var thisRect=d3.select(this),color=thisRect.attr("fill");thisPlot._detailChart.setColors([color]),thisPlot._miniTopChart.setColors([color]),"active"==thisRect.attr("state")?thisPlot.plotTopChart():(thisRect.attr("active","inactive"),thisPlot.plotMiniTopChart(item),thisPlot.plotDetailChart([item]))})}plotDetailChart(data){this._detailChart.plot(data)}plotMiniTopChart(item){this._resetTopChart();var smallData=[item],width=this._topChart._width,height=this._topChart._height/this._data.length;this._miniTopChart.setSize(width,height),this._miniTopChart.plot(smallData),this._setClickActionRectangles("active")}plotTopChart(){this._resetDetailChart(),this._resetMiniTopChart(),this._topChart.plot(this._data),this._setClickActionRectangles()}getStorableComponent(){var{div:div,outerSVG:outerSVG}=this._topChart.getComponents();if("0px"==div.style("width"))var{outerSVG:outerSVG}=this._detailChart.getComponents(),svgToPlot=outerSVG;else svgToPlot=outerSVG;return svgToPlot}}return{TopChart:TopChart,processData:processData,buildTopChart:buildTopChart}}(),web=function(){function downloadObjectAsJsonFile(object,fileName="data.json"){var dataStr="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(object)),downloadAnchorNode=document.createElement("a");downloadAnchorNode.setAttribute("href",dataStr),downloadAnchorNode.setAttribute("download",fileName),downloadAnchorNode.click(),downloadAnchorNode.remove()}function getParamsFromCurrentUrl(){const urlParams=new URLSearchParams(window.location.search),params={};return urlParams.forEach((value,key)=>{params[key]=value}),params}return{downloadObjectAsJsonFile:downloadObjectAsJsonFile,getParamsFromCurrentUrl:getParamsFromCurrentUrl}}();class Form{constructor(plotId,formInfo){this.plotId=plotId,this._formInfo=formInfo,this._addCSS(),this._buildForm(),this._buildParamToType()}getComponents(){const div=d3.select("div#"+this.plotId);var components={div:div};return Object.keys(this.paramToType).forEach(param=>{const paramDiv=div.select("div#"+param);components[param]=paramDiv}),components}_buildParamToType(){var paramToType={};this._formInfo.forEach(d=>paramToType[d.identifier]=d.type),this.paramToType=paramToType}_addCSS(){0===d3.selectAll("style.form_css").size()&&(d3.select("body").append("style").attr("class","form_css").html('.sameLine::after{content:"\\a";white-space: pre !important }'),d3.select("body").append("style").attr("class","form_css").html(".tooltip_title{visibility: hidden;position: absolute;width: 130px;background-color: #555;color: #fff;text-align: center;padding: 5px 0;font-size: 12px;border-radius: 6px;z-index: 1;opacity: 0;transition: opacity 0.6s;}"))}_buildForm(){const formInfo=this._formInfo,container=d3.select("#"+this.plotId),div=container.selectAll("div").data(formInfo).enter().append("div").attr("id",param=>param.identifier).attr("type",param=>param.type).style("display",function(d){return d.hasOwnProperty("hidden")&&!0===d.hidden?"none":"unset"}),titles=div.append("h3").text(param=>param.title).style("margin-top","1em").style("margin-bottom","0.7em"),tooltipDiv=titles.filter(d=>d.hasOwnProperty("tooltip")).append("div").text("❔").style("position","relative").style("display","inline-block").style("border-bottom","1px dotted #ccc").style("color","#006080").on("mouseover",function(){d3.select(this).select("span").style("opacity",1).style("visibility","visible")}).on("mouseout",function(){d3.select(this).select("span").style("opacity",0).style("visibility","hidden")});tooltipDiv.append("span").attr("class","tooltip_title").text(d=>d.tooltip);const textParams=div.filter(d=>"text"==d.type);textParams.append("input").style("width","unset").attr("placeholder",data=>data.hasOwnProperty("placeholder")?data.placeholder:null);const passwordParams=div.filter(d=>"password"==d.type);passwordParams.append("input").attr("type","password").attr("autocomplete","off").style("width","unset");const checkBoxParams=div.filter(d=>"checkbox"==d.type);this._addOptionsToCheckbox(checkBoxParams);const selectParams=div.filter(d=>"select"==d.type);this._addOptionsToSelect(selectParams)}_addOptionsToCheckbox(div){const thisForm=this,paramDiv=div.selectAll("div.sameLine").data(d=>d.options).enter().append("div").attr("class","sameLine").style("display","inline"),checkBox=paramDiv.append("input").attr("type","checkbox").attr("value",d=>d.value).style("display","inline !important").style("margin-right","5px");checkBox.on("click",function(e,data){thisForm._boxClicked(this,data,thisForm)});const title=paramDiv.append("div").text(d=>d.label).style("display","inline");title.on("click",function(e,data){thisForm._titleClicked(this,data,thisForm)})}_addOptionsToSelect(div){const selectDiv=div.append("select").style("width","unset");selectDiv.selectAll("option").data(d=>d.options).enter().append("option").attr("value",d=>d.value).text(d=>d.label)}_titleClicked(element,data){const optionDiv=d3.select(element.parentNode),checkBox=optionDiv.select("input").node();checkBox.checked=!checkBox.checked;const paramDiv=d3.select(element.parentNode.parentNode);this._onlyOneCheckBox(checkBox,data,paramDiv)}_boxClicked(element,data){const paramDiv=d3.select(element.parentNode.parentNode);this._onlyOneCheckBox(element,data,paramDiv)}_onlyOneCheckBox(element,data,paramDiv){const thisForm=this,options=paramDiv.selectAll("input").filter(d=>d.value!=data.value);options.each(function(d){thisForm._hideParameters(d.hasOwnProperty("show")?d.show:[])}),options.nodes().forEach(option=>option.checked=!1);const paramsToShow=data.hasOwnProperty("show")?data.show:[];!0===element.checked?this._showParameters(paramsToShow):this._hideParameters(paramsToShow)}_showParameters(params){const thisForm=this;params.forEach(function(paramId){d3.select("div#"+paramId).style("display","unset");const selectedParamInfo=thisForm._getInfoSelectedValue(paramId);if(null!=selectedParamInfo){const paramsToShow=selectedParamInfo.hasOwnProperty("show")?selectedParamInfo.show:[];thisForm._showParameters(paramsToShow)}})}_hideParameters(params){const thisForm=this;params.forEach(function(paramId){const selectedParamInfo=thisForm._getInfoSelectedValue(paramId);if(null!=selectedParamInfo){const paramsToHide=selectedParamInfo.hasOwnProperty("show")?selectedParamInfo.show:[];thisForm._hideParameters(paramsToHide)}d3.select("div#"+paramId).style("display","none")})}getSelectedValue(parameter){if(!this.paramToType.hasOwnProperty(parameter))return console.log("Parameter "+parameter+" doesn't exist in the form"),"";if("none"==d3.select("div#"+parameter).style("display"))return"";const paramType=this.paramToType[parameter];switch(paramType){case"checkbox":return this._getValueCheckBox(parameter);case"text":case"password":return this._getValueText(parameter);case"select":return this._getValueSelect(parameter);default:return console.log(parameter),console.log("Parameter Type "+paramType+" is not valid for "+parameter),""}}_getInfoSelectedValue(parameter){const paramInfo=this._formInfo.find(d=>d.identifier==parameter);if(!this.paramToType.hasOwnProperty(parameter))return null;const selectedValue=this.getSelectedValue(parameter);if(""==selectedValue)return{};const paramType=this.paramToType[parameter];switch(paramType){case"checkbox":case"select":return paramInfo.options.find(d=>d.value==selectedValue);case"text":case"password":return paramInfo}}_getValueCheckBox(parameter){const paramDiv=d3.select("div#"+parameter),nodes=paramDiv.selectAll("input").nodes(),node=nodes.find(d=>!0===d.checked);return null==node?"":node.value}_getValueSelect(parameter){const select=d3.select("div#"+parameter).select("select").node(),value=select.value;return value}_getValueText(parameter){var textBox=d3.select("div#"+parameter).select("input").node(),value=textBox.value;return value}getSelectedValues(){const selectedValues={};return this._formInfo.forEach(param=>selectedValues[param.identifier]=this.getSelectedValue(param.identifier)),selectedValues}setValue(param,value){if(!this.paramToType.hasOwnProperty(param))return;const paramDiv=this.getComponents()[param],paramType=this.paramToType[param],paramInfo=this._formInfo.find(d=>d.identifier==param);switch(paramType){case"checkbox":const currentValue=this.getSelectedValue(param);if(!0===value&&"true"==currentValue)return;if(!1===value&&"true"==currentValue&&(value=!0),null==paramInfo.options.find(d=>d.value==value))return;var checkBox=paramDiv.select(`input[value=${value}]`).node(),info=paramInfo.options.find(d=>d.value==value);this._titleClicked(d3.select(checkBox.parentNode).select("div").node(),info);break;case"select":if(null==paramInfo.options.find(d=>d.value==value))return;paramDiv.select("select").node().value=value;break;case"text":paramDiv.select("input").node().value=value;break;case"password":paramDiv.select("input").node().value=value}}}var json=function(){function reduceMap(json,idsToPreserve){json=wordplot.json.normalizeMindMapJson(json);const nodes=json.nodes,edges=json.edges;for(var i=0,length=nodes.length;i0){const firstElement=json[0];if(firstElement.hasOwnProperty("demand"))return"statistics";if(firstElement.hasOwnProperty("buttonTitle"))return"mapseries"}return dataType}function getCenterNode(nodes){const centerField="search_center";var centerNode=null;if(!Array.isArray(nodes))return centerNode;for(var i=0;i{if(node.value=minWeight&&filteredNodes.push(node)}const nFilteredNodes=filteredNodes.length;if(nFilteredNodes<=desiredSize)return 0;const lastNode=filteredNodes[nFilteredNodes-desiredSize],minValue=lastNode.value;return minValue}function findOptimalFilter(nodes,desiredSize,minWeight){var minValue=findOptimalMinValue(nodes,desiredSize,minWeight);const totalOption1=filterAndCount(nodes,minValue,minWeight),totalOption2=filterAndCount(nodes,minValue+1,minWeight),dif1=Math.abs(totalOption1-desiredSize),dif2=Math.abs(totalOption2-desiredSize);if(dif2a[valueField]-b[valueField]);return sorted}function findOptimalFilters(nodes,desiredSize){if("number"!=typeof desiredSize)return{};if(!Array.isArray(nodes)||0==nodes.length)return{};if(desiredSize<=0)return{minWeight:null,minValue:null,count:null};if(desiredSize>=nodes.length)return{minWeight:null,minValue:null,count:null};const reorganizedNodes=sortNodes(nodes);if(null==nodes[0].weight)return console.log("Warning at findOptimalFilters() - Make sure that the given map contains weights, otherwise, automatic reduction won't work."),{};const minWeights=[1,2,3,4,5];for(var selectedMinValue=null,selectedMinWeight=null,selectedDifference=null,selectedCount=null,i=0;i{function _getButtonDetails(plot){var details={remove:{id:"removeButton",char:"🗑️",hover:"Remove clicked elements from the MindMap temporally",x:1,y:2,action:()=>{plot.setActionOnClick("remove"),_highlightActionButton(plot)}},recenter:{id:"recenterButton",char:"🎯",hover:"Recenter the concepts around the selected one",x:1,y:3,action:()=>{plot.setActionOnClick("recenter"),_highlightActionButton(plot)}},highlight:{id:"highlightButton",char:"💡",hover:"Highlights the concepts that are related to the selected concept",x:1,y:4,action:()=>{plot.setActionOnClick("highlight"),_highlightActionButton(plot)}},source:{id:"sourceButton",char:"🕵️",hover:"See the links to the sources of the selected concept",x:1,y:5,action:()=>{plot.setActionOnClick("source"),_highlightActionButton(plot)}},showdetails:{id:"showDetailsButton",char:"📝",hover:"Shows the attributes of the clicked concept",x:1,y:6,action:()=>{plot.setActionOnClick("showdetails"),_highlightActionButton(plot)}},selectgroups:{id:"selectGroupsButton",char:"🗂️",hover:"Choose which groups do you want to visualizer",x:1,y:7,action:()=>{0!=plot._legends.length&&(hideButtons(plot,MAIN_MENU_BUTTONS,0),showButtons(plot,["exitSelectGroupsButton"],500),wordplot.legends.showButtonsLegend(plot))}},downloadMenu:{id:"showDownloadMenuButton",char:"💾",hover:"Show Download Options",x:1,y:8,action:()=>{showDownloadMenu(plot)}},showrelations:{id:"showRelationsButton",char:"🔌",hover:"Shows the list of relations of the clicked concept",x:1,y:9,action:()=>{plot.setActionOnClick("showrelations"),_highlightActionButton(plot)}},exitselectgroups:{id:"exitSelectGroupsButton",char:"🔙",hover:"Back",background:"none",x:1,y:1,action:()=>{wordplot.legends.hideButtonsLegend(plot);const groups=wordplot.legends.getSelectedGroups(plot);plot.setProperties({filterGroups:groups}),exitLegendSelection(plot)}},search:{id:"searchButton",char:"🔍",hover:"Search a concept",x:1,y:1,action:()=>{showOrHideSearchBox(plot)}},hideDownloadMenu:{id:"hideDownloadMenuButton",char:"🔙",hover:"Back",background:"none",x:1,y:1,action:()=>{hideDownloadMenu(plot)}},downloadPng:{id:"downloadPngButton",char:"PNG",color:"white",width:80,hover:"Download MindMap as PNG",x:1,y:2,action:()=>{wordplot.save.exportPng(plot)}},downloadSvg:{id:"downloadSvgButton",char:"SVG",color:"white",width:80,hover:"Download MindMap as SVG",x:1,y:3,action:()=>{wordplot.save.exportSvg(plot)}}};const{disableSaveButtons:disableSaveButtons}=plot.getProperties();return!0===disableSaveButtons&&(details.downloadMenu=void 0),details}function changeOnClickAction(plot,action){function showValuesOnClick(event,data){if(null==thisPlot.graphToMap)return;if(null==thisPlot.tooltipSubPlot)return;var nodeId=this.getAttribute("nodeId"),nodeInfo=thisPlot.graphToMap.mindmap.getNodeInfoById(nodeId);const valuesField="values";if(nodeInfo.hasOwnProperty(valuesField)){const json=nodeInfo[valuesField],title=nodeInfo[nameField];thisPlot.tooltipSubPlot.plot(json),thisPlot.tooltipSubPlot.setTitle(title),thisPlot._showTooltipChart()}}function recenterOnClick(event){if(null!=thisPlot.graphToMap){var nodeId=this.getAttribute("nodeId"),nodeInfo=thisPlot.graphToMap.mindmap.getNodeInfoById(nodeId);if(nodeInfo.hasOwnProperty(thisPlot._subPlotField)){var subPlotUrl=nodeInfo[thisPlot._subPlotField],subPlotType=nodeInfo[thisPlot._subPlotTypeField];if(nodeInfo.hasOwnProperty("concept"))var uniqueName=nodeInfo.concept;else uniqueName=null;thisPlot.showEmbeddedVisualizationFromUrl(subPlotUrl,subPlotType,uniqueName)}else thisPlot._refreshCenter(nodeId)}}const thisPlot=plot,{nameField:nameField}=plot.getProperties(),onClick=recenterOnClick,removeOnClick=function(event){var nodeId=this.getAttribute("nodeId");nodeId=parseInt(nodeId);thisPlot.removeElementById(nodeId)},highlightOnClick=function(){var nodeId=this.getAttribute("nodeId");nodeId=parseInt(nodeId);thisPlot._highlightNode(nodeId)},sourceOnClick=function(){var nodeId=this.getAttribute("nodeId");nodeId=parseInt(nodeId);_showSourceData(thisPlot,nodeId)},showNodeDetails=function(){var nodeId=this.getAttribute("nodeId");nodeId=parseInt(nodeId);_showNodeDetails(thisPlot,nodeId)},showNodeRelations=function(){var nodeId=this.getAttribute("nodeId");nodeId=parseInt(nodeId);_showNodeRelations(thisPlot,nodeId)};switch(action){case"showdetails":var actionOnClick=showNodeDetails;plot.enableTooltip(!0),plot.tooltip.setMargin({top:10,bottom:10,left:10,right:10});break;case"remove":actionOnClick=removeOnClick;break;case"showvalues":actionOnClick=showValuesOnClick;break;case"recenter":actionOnClick=recenterOnClick;break;case"highlight":actionOnClick=highlightOnClick;break;case"source":actionOnClick=sourceOnClick;_initializeSourceTooltip(plot);break;case"showrelations":actionOnClick=showNodeRelations;plot.enableTooltip(!0),plot.tooltip.setMargin({top:10,bottom:10,left:10,right:10});break;default:actionOnClick=onClick}plot._actionOnClick=action,plot._actionOnClickFunction=actionOnClick}function _initializeButton(plot,buttonInfo){if(null==buttonInfo)return;const{id:id,x:x,y:y,char:char,hover:hover,action:action,color:color,width:width,background:background}=buttonInfo;if("string"!=typeof id||0==id.length)return;if("number"!=typeof x||x<=0)return;if("number"!=typeof y||y<=0)return;const svg=plot.getComponents().outerSVG;var buttonWidth=35,buttonHeight=35;const xPadding=10,yPadding=10,plotHeight=plot._height,FONT_SIZE_BUTTON="23px";if("string"==typeof background)var buttonColor=background;else buttonColor="#08233b";if("number"==typeof width)buttonWidth=width;const xButton=xPadding+(x-1)*(buttonWidth+xPadding),yButton=plotHeight-y*(buttonHeight+yPadding),button=svg.selectAll("svg#"+id).data([null]).enter().append("svg").attr("id",id).attr("x",xButton).attr("y",yButton).attr("height",buttonHeight).attr("width",buttonWidth).style("cursor","pointer");if(null==button.node())return button;button.append("rect").attr("height","100%").attr("width","100%").attr("rx","10").attr("ry","10").attr("fill",buttonColor);const foreign=button.append("foreignObject").attr("x",0).attr("y",3).attr("width","100%").attr("height","100%").node();var buttonText=document.createElement("text");return foreign.appendChild(buttonText),buttonText=d3.select(buttonText).style("text-align","center").style("display","block").style("font-size",FONT_SIZE_BUTTON).text(char),"string"==typeof hover&&buttonText.attr("title",hover),"string"==typeof color&&buttonText.style("color",color),button.on("click",action),button}function getButtonsSvg(plot){const svg=plot.getComponents().outerSVG,buttons={},svgIds=["removeButton","highlightButton","recenterButton","sourceButton","searchButton","showDetailsButton","showRelationsButton","showDownloadMenuButton","downloadPngButton","hideDownloadMenuButton","downloadSvgButton","downloadJsonButton","selectGroupsButton","exitSelectGroupsButton"];svgIds.forEach(id=>{const svgButton=svg.select(`svg#${id}`);buttons[id]=svgButton});const foreignIds=["searchBox"];return foreignIds.forEach(id=>{const svgButton=svg.select(`foreignObject#${id}`);buttons[id]=svgButton}),buttons}function initializeButtons(plot){const svg=plot.getComponents().outerSVG;if(null==svg.node())return;const buttonDetails=_getButtonDetails(plot),thisPlot=plot;Object.keys(buttonDetails).forEach(buttonName=>{_initializeButton(plot,buttonDetails[buttonName])}),_initSearchBox(thisPlot),_highlightActionButton(plot),hideButtons(plot,DOWNLOAD_MENU_BUTTONS,0)}function showDownloadMenu(plot){hideButtons(plot,MAIN_MENU_BUTTONS,0),hideSearchBox(plot),showButtons(plot,DOWNLOAD_MENU_BUTTONS,500)}function hideDownloadMenu(plot,duration){"number"!=typeof duration&&(duration=500),hideButtons(plot,DOWNLOAD_MENU_BUTTONS,duration),hideSearchBox(plot),showButtons(plot,MAIN_MENU_BUTTONS,duration)}function exitLegendSelection(plot,duration){"number"!=typeof duration&&(duration=500),hideButtons(plot,["exitSelectGroupsButton"],0),showButtons(plot,MAIN_MENU_BUTTONS,duration)}function showOrHideSearchBox(plot){const{searchBox:searchBox}=getButtonsSvg(plot);"unset"!=searchBox.style("display")?searchBox.transition().duration(500).style("display","unset"):hideSearchBox(plot)}function showButtons(plot,buttons,duration){if(!Array.isArray(buttons))return;const svgs=getButtonsSvg(plot);buttons.forEach(buttonName=>{const button=svgs[buttonName];button.select("rect"),button.transition().duration(duration).style("opacity",1).style("display","unset")})}function hideButtons(plot,buttons,duration){if(!Array.isArray(buttons))return;const svgs=getButtonsSvg(plot);buttons.forEach(buttonName=>{const button=svgs[buttonName];button.transition().duration(duration).style("opacity",0).transition().style("display","none")})}function hideSearchBox(plot){const{searchBox:searchBox}=getButtonsSvg(plot);searchBox.style("display","none"),plot._highlightAllNodes(),plot.disableMouseOver(!1)}function _initSearchBox(plot){const outerSVG=plot.getComponents().outerSVG,buttonSize=35,xPadding=10,yPadding=10,height=plot._height,yBox=height-buttonSize-yPadding,xBox=xPadding+1*(buttonSize+xPadding),foreignObject=outerSVG.selectAll("foreignObject#searchBox").data([null]).enter().append("foreignObject").attr("id","searchBox").attr("height",buttonSize).attr("width",100).attr("x",xBox).attr("y",yBox),input=foreignObject.append("xhtml:input").attr("type","text").style("width","100%").style("height","100%").style("font-size",16);input.on("keyup",function(event){"Escape"==event.key&&hideSearchBox(plot)}),input.on("keypress",function(event){if("Enter"!=event.key)return;const searchText=this.value;_highlightSearch(plot,searchText)}),foreignObject.style("display","none")}function _highlightSearch(plot,search){search=search.trim();if("string"!=typeof search||0==search.length)return plot._highlightAllNodes(),void plot.disableMouseOver(!1);search=search.replaceAll(" ","_"),search=search.toLowerCase();const nodes=plot._plotData,filteredNodes=[];if(nodes.forEach(d=>{const label=d.label,id=d.id;label.includes(search)&&filteredNodes.push(id)}),0==filteredNodes.length)return plot._highlightAllNodes(),void plot.disableMouseOver(!1);plot.disableMouseOver(!0),plot._unHighlightAllNodes(),plot._highlightListOfNodes(filteredNodes)}function _highlightActionButton(plot){var defaultButtonColor="#08233b";const buttons=getButtonsSvg(plot),buttonsDetails=_getButtonDetails(plot),action=plot._actionOnClick,actionToButton={remove:"removeButton",highlight:"highlightButton",recenter:"recenterButton",source:"sourceButton",showdetails:"showDetailsButton",showrelations:"showRelationsButton"},highlightColor="#ffffff";if(!actionToButton.hasOwnProperty(action))return;const buttonTag=actionToButton[action];Object.keys(actionToButton).forEach(d=>{const buttonId=actionToButton[d],buttonInfo=buttonsDetails[d];if(null==buttonInfo||null==buttonId)return;const button=buttons[buttonId];if("string"==typeof buttonInfo.background)var buttonColor=buttonInfo.background;else buttonColor=defaultButtonColor;button.select("rect").attr("fill",buttonColor)});const button=buttons[buttonTag];button.select("rect").style("stroke","black").style("stroke-width",2).attr("fill",highlightColor)}function _showSourceData(plot,nodeId){const page=1;_showSourceDataAux(plot,nodeId,page)}function _showSourceDataAux(plot,nodeId,page){const RESULTS_PER_PAGE=10;plot.tooltip.clean(),plot.tooltip.setSize(300,50);const sourceField=plot._sourceField,data=plot.mindmap.getNodeInfoById(nodeId);if(data.id!=nodeId)return void console.log("Warning at showSourceData() : Id is not consistant");if(!data.hasOwnProperty(sourceField))return;const sources=data[sourceField];if(!Array.isArray(sources))return;const startIndex=(page-1)*RESULTS_PER_PAGE,sourcesCurrentPage=sources.slice(startIndex,startIndex+RESULTS_PER_PAGE);for(let i=0;i1){const prevButtonText="⬅️",prevButton=buttonContainer.append("tspan").text(prevButtonText);prevButton.on("click",()=>{_showSourceDataAux(plot,nodeId,page-1)}),prevButton.style("cursor","pointer")}const nSources=sources.length;var nPages=Math.floor(nSources/RESULTS_PER_PAGE);nSources%RESULTS_PER_PAGE>0&&(nPages+=1);const pageIsLastPage=page==nPages;if(0==pageIsLastPage){const nextButtonText="➡️",nextButton=buttonContainer.append("tspan").text(nextButtonText);nextButton.on("click",()=>{_showSourceDataAux(plot,nodeId,page+1)}),nextButton.style("cursor","pointer")}const node=d3.selectAll("svg.concept").filter(function(){var id=d3.select(this).attr("nodeId");return id==String(nodeId)});if(0==node.size)return;const x=node.attr("x"),y=node.attr("y")-plot.tooltip._height+0;plot.tooltip.move(x,y),plot.tooltip.show()}function _showNodeDetails(plot,nodeId){plot.tooltip.clean(),plot.tooltip.setSize(300,50);const data=plot.mindmap.getNodeInfoById(nodeId);if(data.id!=nodeId)return void console.log("Warning at showSourceData() : Id is not consistant");const fields=["id","label","value","unique_value","weight","normalized_value","group","original_label"];fields.forEach(field=>{if(null==data[field])return;const value=data[field],formattedKey=formatField(field);plot.tooltip.addKeyValue(formattedKey,value)});const tooltipText=plot.tooltip.getComponents().text,buttonContainer=plot.tooltip._addOneLineInsideText(tooltipText,"");plot.tooltip._nLines=tooltipText.selectAll("tspan.tooltipLine").size(),plot.tooltip._checkResize(),buttonContainer.attr("x","100%"),buttonContainer.style("text-anchor","end");const node=d3.selectAll("svg.concept").filter(function(){var id=d3.select(this).attr("nodeId");return id==String(nodeId)});if(0==node.size)return;const x=node.attr("x"),y=node.attr("y")-plot.tooltip._height+0;plot.tooltip.move(x,y),plot.tooltip.show()}function _showNodeRelations(plot,nodeId){const page=1;_showNodeRelationsAux(plot,nodeId,page)}function _showNodeRelationsAux(plot,nodeId,page){const RESULTS_PER_PAGE=10;plot.tooltip.clean(),plot.tooltip.setSize(300,50);const relationsField="relations",data=plot.mindmap.getNodeInfoById(nodeId);if(data.id!=nodeId)return void console.log("Warning at showSourceData() : Id is not consistant");if(!data.hasOwnProperty(relationsField))return;const relations=data[relationsField];if(!Array.isArray(relations))return;if(0==relations.length)return;const startIndex=(page-1)*RESULTS_PER_PAGE,currentPage=relations.slice(startIndex,startIndex+RESULTS_PER_PAGE);for(let i=0;i1){const prevButtonText="⬅️",prevButton=buttonContainer.append("tspan").text(prevButtonText);prevButton.on("click",()=>{_showNodeRelationsAux(plot,nodeId,page-1)}),prevButton.style("cursor","pointer")}const nRelations=relations.length;var nPages=Math.floor(nRelations/RESULTS_PER_PAGE);nRelations%RESULTS_PER_PAGE>0&&(nPages+=1);const pageIsLastPage=page==nPages;if(0==pageIsLastPage){const nextButtonText="➡️",nextButton=buttonContainer.append("tspan").text(nextButtonText);nextButton.on("click",()=>{_showNodeRelationsAux(plot,nodeId,page+1)}),nextButton.style("cursor","pointer")}const node=d3.selectAll("svg.concept").filter(function(){var id=d3.select(this).attr("nodeId");return id==String(nodeId)});if(0==node.size)return;const x=node.attr("x"),y=node.attr("y")-plot.tooltip._height+0;plot.tooltip.move(x,y),plot.tooltip.show()}function formatField(label){return"string"!=typeof label?label:(label=label.replaceAll("_"," "),label=label.replace(/(^\w{1})|(\s+\w{1})/g,letter=>letter.toUpperCase()),label)}function _initializeSourceTooltip(plot){plot.enableTooltip(!0);const tooltip=plot.tooltip;tooltip.setSize(300,50),tooltip.setMargin({left:10,top:10,bottom:10,right:10}),tooltip.setBackgroundColor("#c0c0c0")}const MAIN_MENU_BUTTONS=["showDownloadMenuButton","searchButton","removeButton","highlightButton","recenterButton","sourceButton","showDetailsButton","selectGroupsButton","showRelationsButton"],DOWNLOAD_MENU_BUTTONS=["downloadPngButton","hideDownloadMenuButton","downloadSvgButton"];return{changeOnClickAction:changeOnClickAction,initializeButtons:initializeButtons,getButtonsSvg:getButtonsSvg}})();var megatron=function(){function buildTextToMindmapUrl(params){var output="json",predictionType="linear",noise="full",city="";const{_country:_country,_cluster:_cluster,_language:_language,_timeMonths:_timeMonths,_timeYears:_timeYears,_sizeMap:_sizeMap,_ontology:_ontology,_wordType:_wordType,_token:_token,_limit:_limit,_datasource:_datasource,_plotType:_plotType}=params;if(["open_access_journals","theseus_database"].includes(_datasource))var _time=_timeYears;else _time=_timeMonths;var url="https://megatron.headai.com/TextToMindMap?"+`token=${_token}&language=${_language}&ontology=${_ontology}&`+`search_text=${_limit}&word_type=${_wordType}&noise=${noise}&`+`prediction_type=${predictionType}&cluster_name=${_cluster}&`+`country=${_country}&months=${_time}&size=${_sizeMap}&`+`city=${city}&output=${output}&dataset=${_datasource}`;return url}function buildTextToStatisticsUrl(params){var output="json",predictionType="linear",noise="full";const{_country:_country,_cluster:_cluster,_language:_language,_timeMonths:_timeMonths,_timeYears:_timeYears,_sizeStats:_sizeStats,_ontology:_ontology,_wordType:_wordType,_token:_token,_limit:_limit,_datasource:_datasource,_plotType:_plotType}=params;if("top20"==_plotType)var _size=20;else _size=_sizeStats;if(["open_access_journals","theseus_database"].includes(_datasource))var _time=_timeYears;else _time=_timeMonths;var url="https://megatron.headai.com/TextToStatistics?"+`country=${_country}&cluster_name=${_cluster}&output=${output}&language=${_language}&months=${_time}`+`&size=${_size}&ontology=${_ontology}&noise=${noise}&prediction_type=${predictionType}`+`&word_type=${_wordType}&token=${_token}&search_text=${_limit}&dataset=${_datasource}`;return url}function buildExplainUrl(params){const{context:context,year:year,text:text}=params;var url=`https://megatron.headai.com/mc_api?action=explain_map&type=json&context=${context}&search_year=${year}&text=${text}`;return url}function buildStoreModifiedDataUrl(params){const{token:token="",url:url="",update:update=!1}=params;var megatronUrl=`https://megatron.headai.com/Utils?action=store_modified_data&url=${url}&update=${update}&token=${token}`;return megatronUrl}return{buildTextToMindmapUrl:buildTextToMindmapUrl,buildTextToStatisticsUrl:buildTextToStatisticsUrl,buildExplainUrl:buildExplainUrl,buildStoreModifiedDataUrl:buildStoreModifiedDataUrl}}();class MapSeries{constructor(plotId,data,plotType,props={}){this._buttonTitleField="buttonTitle",this._titleField="title",this._currentMap=null,this._currentPromise=new Promise(function(resolve,reject){resolve(!0)}),this._initProperties(),this.plotId=plotId,this._plotData=[],this._plots=[],this.setProperties(props),this._plotType=plotType,this.setPlotData(data),this.initializeDiv(),this.changeMap(0)}getCurrentPromise(){return this._currentPromise}getProperties(){return this.props}_initProperties(){const props={responsiveMode:!1,buttonsHeight:40,buttonsMargin:10,inactiveColor:"#08233B",activeColor:"#11A1F3",width:200,height:200,enableTooltipChart:!1,tooltipChartProps:{},colors:["#08233B","#08233B"],hideNodes:[]};this.props=props}_normalizeData(data){return data.hasOwnProperty("data")&&(data=data.data),data}setPlotData(data){if(data=this._normalizeData(data),Array.isArray(data)){this._plotData=data,this._plots=[];for(var i=0;i{skipProps.includes(propName)||(this.props[propName]=props[propName])}),null!=this._currentMap&&this.getCurrentMap().setProperties(props),(props.hasOwnProperty("width")||props.hasOwnProperty("height"))&&this.refreshComponents()}setMapUrls(mapUrls){Array.isArray(mapUrls)&&0!=mapUrls.length&&"string"==typeof mapUrls[0]||(mapUrls=[]),this._mapUrls=mapUrls}_changeTitle(mapIndex){const title=this._getTitle(mapIndex),{titleDIV:titleDIV}=this.getComponents();titleDIV.select("h2").text(title)}_getTitle(mapIndex){const titleField=this._titleField;var title="";if("number"!=typeof mapIndex)return title;if(mapIndex>=this._plotData.length||mapIndex<0)return title;const data=this._plotData[mapIndex];return data.hasOwnProperty(titleField)?(title=data[titleField],title):title}_getButtonTitle(mapIndex){const buttonTitleField=this._buttonTitleField;var title="";if("number"!=typeof mapIndex)return title;if(mapIndex>=this._plotData.length||mapIndex<0)return title;const data=this._plotData[mapIndex];return data.hasOwnProperty(buttonTitleField)?(title=data[buttonTitleField],title):title}changeMap(mapIndex){if(this.hasOwnProperty("_currentMap")&&null!=this._currentMap)var currentMap=this._currentMap;else{const id=this.plotId+"_map";currentMap=new wordplot.Visualization(id,this.props)}currentMap.restartSVG(),currentMap.showMessage("Loading...");const data=this._plotData,urlField="url";if(mapIndex>=data.length)return void(this._currentMap=null);this.highlightButton(mapIndex);var mapId=this.plotId+"_map";const thisPlot=this._plots[mapIndex];if(null!=thisPlot)return d3.select("div#"+mapId).selectAll("text#loadingText").remove(),thisPlot.refresh(),this._currentMap=thisPlot,!0===this.props.responsiveMode&&this._setResponsiveConfig(),void this._changeTitle(mapIndex);const url=data[mapIndex][urlField],promise=d3.json(url).then(json=>{const plot=wordplot.wordmap.buildWordMap(mapId,json,this._plotType,this.props);this._plots[mapIndex]=plot,d3.select("div#"+mapId).selectAll("text#loadingText").remove();const hideLegend=data[mapIndex].hideLegend;"true"!==hideLegend&&!0!==hideLegend||plot.hideLegend(!0);const groups=Object.keys(plot._groupToColorIndex),nGroups=groups.length;if(nGroups<=2&&wordplot.wordmap.setColorsToMindMap(plot),plot.refresh(),wordplot.wordmap.centerMap(plot),this._currentMap=plot,!0===this.props.enableTooltipChart){const tooltipProps=this.props.tooltipChartProps;plot.enableTooltipChart("basiclinechart",tooltipProps)}}).then(()=>{!0===this.props.responsiveMode&&this._setResponsiveConfig()});return this._changeTitle(mapIndex),this._currentPromise=promise,promise}initializeDiv(){const titleId=this.plotId+"_title",mapId=this.plotId+"_map",buttonsId=this.plotId+"_buttons",div=d3.select("div#"+this.plotId),title=div.append("div").attr("id",titleId);title.selectAll("h2").data([null]).enter().append("center").append("h2");div.append("div").attr("id",mapId);const buttonsDiv=div.append("div").attr("id",buttonsId);buttonsDiv.selectAll("svg.expansor").data([null]).enter().append("svg").attr("class","expansor").style("width","100%").style("height","0px");const buttons=buttonsDiv.append("svg").attr("class","buttons"),width=this.props.width,height=this.getButtonsHeight();buttons.attr("viewBox",`0 0 ${width} ${height}`),buttons.attr("width",width),this.addButtons()}refreshComponents(){if(!0===this.responsiveMode)return void this._setResponsiveConfig();const{div:div,titleDIV:titleDIV,mapDIV:mapDIV,buttonsSVG:buttonsSVG,buttonsDIV:buttonsDIV}=this.getComponents();titleDIV.style("width",this.props.width);const width=this.props.width;buttonsSVG.attr("width",width)}getButtonsHeight(){const BUTTON_TITLE_HEIGHT=30,height=this.props.buttonsHeight+2*this.props.buttonsMargin+BUTTON_TITLE_HEIGHT;return height}getComponents(){var div=d3.select("div#"+this.plotId);const titleId=this.plotId+"_title";var titleDIV=div.select("div#"+titleId);const mapId=this.plotId+"_map";var mapDIV=div.select("div#"+mapId);const buttonsId=this.plotId+"_buttons";var buttonsDIV=div.select("div#"+buttonsId),buttonsSVG=div.select("svg.buttons");return{div:div,titleDIV:titleDIV,mapDIV:mapDIV,buttonsSVG:buttonsSVG,buttonsDIV:buttonsDIV}}_normalizePixels(pixels){return"number"==typeof pixels?pixels:"string"==typeof pixels?parseFloat(pixels):null}enableResponsiveMode(minWidthPixels,maxWidthPixels){minWidthPixels=this._normalizePixels(minWidthPixels),maxWidthPixels=this._normalizePixels(maxWidthPixels),"number"==typeof minWidthPixels&&"number"==typeof maxWidthPixels&&(minWidthPixels<=0||maxWidthPixels<=0||(this.props.minWidthPixels=minWidthPixels,this.props.maxWidthPixels=maxWidthPixels,this.props.responsiveMode=!0,this._setResponsiveConfig()))}_setResponsiveConfig(){if(!0!==this.props.responsiveMode)return;const minWidthPixels=this.props.minWidthPixels,maxWidthPixels=this.props.maxWidthPixels,{div:div,titleDIV:titleDIV,mapDIV:mapDIV,buttonsSVG:buttonsSVG,buttonsDIV:buttonsDIV}=this.getComponents();titleDIV.style("min-width",minWidthPixels+"px").style("max-width",maxWidthPixels+"px").style("width",null),mapDIV.style("min-width",minWidthPixels+"px").style("max-width",maxWidthPixels+"px").style("width",void 0).style("height",void 0),buttonsDIV.style("min-width",minWidthPixels+"px").style("max-width",maxWidthPixels+"px").style("width",null),buttonsSVG.style("width","100%")}getCurrentMap(){return this._currentMap}highlightButton(index){const{buttonsSVG:buttonsSVG}=this.getComponents(),buttons=buttonsSVG.selectAll("circle");buttons.attr("fill",this.props.inactiveColor).attr("stroke-width",3).attr("stroke",null);const button=buttonsSVG.selectAll(`circle[index='${index}']`);button.attr("fill",this.props.activeColor).attr("stroke",this.props.inactiveColor)}refresh(){null!=this._currentMap&&(this.refreshComponents(),this._currentMap.refresh())}addButtons(){const data=this._plotData,width=this.props.width,{buttonsSVG:buttonsSVG}=this.getComponents(),r=this.props.buttonsHeight/2,nMaps=data.length,buttonsData=[];for(var i=0;id.x1).attr("x2",d=>d.x2).attr("y1",yPos).attr("y2",yPos).attr("stroke","gray").attr("stroke-dasharray",7),buttonsSVG.selectAll("circle").data(buttonsData).enter().append("circle").attr("r",r).attr("cy",yPos).attr("cx",d=>d.x).attr("index",d=>d.index).style("cursor","pointer").on("click",(action,data)=>{const index=data.index;thisPlot.changeMap(index)});const BUTTON_TITLE_WIDTH=150,BUTTON_TITLE_HEIGHT=30,buttonTitles=buttonsSVG.selectAll("svg.buttonTitle").data(buttonsData).enter().append("svg").attr("class","buttonTitle").attr("width",BUTTON_TITLE_WIDTH).attr("height",BUTTON_TITLE_HEIGHT).attr("x",d=>d.x-BUTTON_TITLE_WIDTH/2).attr("y",d=>yPos+r);buttonTitles.append("text").attr("y","50%").attr("x","50%").attr("dominant-baseline","middle").attr("text-anchor","middle").text(d=>d.title),buttonsSVG.selectAll("svg.text").data(buttonsData)}}class WideGraphToMap extends GraphToMap{constructor(mindmap,mapType,props={}){super(mindmap,mapType,props)}canPlaceNode(node,x,y,matrix){const nodeId=node.id,neighbors=this.mindmap.getNeighborsById(nodeId),location=[x,y],validCoordinates=this.processor.getNeighborsCoordinates(location,matrix);for(var i=0;i=matrix.length)continue;if(matrix.length>0&&cx>=matrix[0].length)continue;const id=matrix[cy][cx];if(-1!=id&&!neighbors.includes(id))return!1}return!0}locateChildren(nodes,nodesBeingLocated,matrix){var nodesForNextIteration=[];nodes.forEach(node=>{const nodeId=node.id;var children=this.mindmap.getNeighborsById(nodeId).filter(id=>!1===this.mindmap.getNodeInfoById(id).isPlaced);const center=[node.x,node.y],validCoordinates=this.processor.getValidNeighborsCoordinates(center,matrix),nChildrensToPlace=Math.min(children.length,validCoordinates.length);for(var i=0;i!1===this.mindmap.getNodeInfoById(id).isPlaced),matrix[y][x]=childId,nodesForNextIteration.push(child)}}),nodesForNextIteration.length>0&&this.locateChildren(nodesForNextIteration,nodesBeingLocated,matrix)}matricesAreOverlapping(A,B,bx,by,emptyValue=-1){const{nodes:nodes}=this.mindmap.getData(),A_rows=A.length;if(0==A_rows)return!1;if(by>=A_rows)return!1;const A_cols=A[0].length;if(0==A_cols)return!1;if(bx>=A_cols)return!1;const B_rows=B.length;if(0==B_rows)return!1;const B_cols=B[0].length;if(0==B_cols)return!1;const x0=bx,x1=Math.min(A_cols,bx+B_cols),y0=by,y1=Math.min(A_rows,by+B_rows);for(var B_x=0,A_x=x0;A_x=A_rows)return null;const A_cols=A[0].length;if(0==A_cols)return null;if(bx>=A_cols)return null;const B_rows=B.length;if(0==B_rows)return null;const B_cols=B[0].length;if(0==B_cols)return null;const x0=Math.max(bx-padding,0),x1=Math.min(A_cols,bx+B_cols+padding),y0=Math.max(by-padding,0),y1=Math.min(A_rows,by+B_rows+padding),cols=x1-x0,rows=y1-y0,newMatrix=Array(rows).fill(null).map(()=>Array(cols).fill(-1));for(var y=0;y=rows||Ax>=cols||(newMatrix[Ay][Ax]=value))}return newMatrix}matrixHasDivisions(matrix){if(null==matrix)return!1;for(var y=0;y0&&(this._width=width),height>0&&(this._height=height),this._recalculateInnerSize(),!1===isDinamicIncrease&&(this._initialHeight=this._height,this._initialWidth=this._width)}_checkResize(){const{fontSize:fontSize}=this.getProperties(),height=this._innerHeight,textHeight=this._nLines*fontSize*1.1;if(textHeight>height){const diff=textHeight-height;var isDinamicIncrease=!0;this.setSize(this._width,this._height+diff,isDinamicIncrease)}}_createTooltipBackground(){const{outerSVG:outerSVG}=this.getComponents();outerSVG.style("opacity",1).style("font-weight","normal").style("text-align","center").style("border-radius","6px").style("border","0px").style("display","inline");outerSVG.selectAll("rect.background").data([null]).enter().append("rect").attr("class","background").attr("width","100%").attr("height","100%").attr("fill",this._backgroundColor).lower()}_initContainer(){this.setSize(this._initialWidth,this._initialHeight),super._initContainer();const{innerSVG:innerSVG,container:container,div:div}=this.getComponents(),{fontFamily:fontFamily,fontSize:fontSize}=this.getProperties();div.style("transition","visibility 0.5s").on("mouseover",d=>this.show()).on("mouseout",d=>this.hide()),innerSVG.select("rect.background").remove(),this._createTooltipBackground(),container.selectAll("text.text").data([null]).enter().append("text").attr("class","text").style("width",this._innerWidth).style("display","block").style("font-size",fontSize+"px").style("font-family",fontFamily).attr("y","1em").attr("x","0%")}_refreshComponents(){super._refreshComponents();const{div:div,outerSVG:outerSVG,innerSVG:innerSVG,container:container,background:background}=this.getComponents(),{width:width,height:height}=this.getProperties();div.attr("height",height+"px").attr("width",width+"px")}getComponents(){const components=super.getComponents();return components.text=components.container.select("text.text"),components.background=components.outerSVG.select("rect.background"),components}_addOneLineInsideText(text,line){const x=text.attr("x");var lineHeight=1.1;0==text.selectAll("tspan.tooltipLine").size()&&(lineHeight=0);var tspan=text.append("tspan").attr("class","tooltipLine");return tspan.text(line).attr("x",x).attr("dy",lineHeight+"em"),tspan}_addLinesInsideText(text,lines){lines.forEach(line=>this._addOneLineInsideText(text,line))}_addOneLinkInsideText(text,url,label){const x=text.attr("x");var lineHeight=1.1;0==text.selectAll("tspan.tooltipLine").size()&&(lineHeight=0);const link=text.append("a").append("tspan").attr("class","tooltipLine").text(label).attr("x",x).attr("dy",lineHeight+"em");return link.on("click",()=>{window.open(url,"_blank")}),link.style("cursor","pointer"),link}_addLinksInsideText(text,urls,labels){var thisPlot=this;urls.forEach(function(url,i){thisPlot._addOneLinkInsideText(text,url,labels[i])})}move(x=null,y=null){const{div:div}=this.getComponents();null!==x&&div.attr("x",x),null!==y&&div.attr("y",y)}hide(){const{div:div}=this.getComponents();div.style("visibility","hidden"),this._hideAux()}_hideAux(){}executeFunctionAfterHide(func){"function"==typeof func&&(this._hideAux=func)}show(){const{div:div}=this.getComponents();div.style("visibility","unset"),div.style("opacity","1.0"),this._showAux()}_showAux(){}executeFunctionAfterShowing(func){"function"==typeof func&&(this._showAux=func)}addLine(line){const{text:text}=this.getComponents(),width=this._innerWidth;var lines=wordplot.helpers.getSplittedText(line,width,text);if("\n"===line)lines=[" "];this._addLinesInsideText(text,lines),this._nLines=text.selectAll("tspan.tooltipLine").size(),this._checkResize()}addKeyValue(key,value){const{text:text}=this.getComponents(),x=(this._innerWidth,text.attr("x"));var lineHeight=1.1;0==text.selectAll("tspan.tooltipLine").size()&&(lineHeight=0);var tspan=text.append("tspan").attr("class","tooltipLine").attr("x",x).attr("dy",lineHeight+"em").style("margin","20px");tspan.append("tspan").text(`${key}: `).style("font-weight","bold"),tspan.append("tspan").text(`${value}`),this._nLines=text.selectAll("tspan.tooltipLine").size(),this._checkResize()}addLink(url,label){const{text:text}=this.getComponents(),width=this._innerWidth,labels=wordplot.helpers.getSplittedText(label,width,text),urls=[];labels.forEach(d=>urls.push(url)),this._addLinksInsideText(text,urls,labels),this._nLines=text.selectAll("tspan.tooltipLine").size(),this._checkResize()}clean(){const{text:text}=this.getComponents();text.selectAll("tspan").remove(),text.selectAll("a").remove(),this._nLines=0}}class MindMap{constructor(json,props){this.originalData=JSON.parse(JSON.stringify(json)),this.properties={onlyCompounds:!1,filterMinWeight:0,filterMinValue:0,filterGroups:[],maxNodes:null,valueField:"value",hideNodes:[]},this._nodes=[],this._edges=[],this._neighbors={},this._idToIndex={},this._labelToIndex={},this.setProperties(props);const{valueField:valueField}=this.getProperties(),{nodes:nodes,edges:edges}=this.getOriginalData(),sortedNodes=this._sortArrayOfObjects(nodes,valueField),sortedEdges=this._sortArrayOfObjects(edges,valueField);this.modifyOriginalData({nodes:sortedNodes,edges:sortedEdges}),this._processData()}setProperties(props){const details={reprocess:!1,changes:null};if("object"!=typeof props)return details;const propsDetails={filterMinWeight:{type:"number"},filterMinValue:{type:"number"},filterGroups:{type:"array"},onlyCompounds:{type:"boolean"},maxNodes:{type:"number"},valueField:{type:"string"},hideNodes:{type:"array",preprocess:"comma-separated"}},oldProps=this.getProperties(),newProps=props,changes=wordplot.properties.setProperties(propsDetails,oldProps,newProps);details.changes=changes;const refreshFields=["filterMinWeight","filterMinValue","filterGroups","onlyCompounds","hideNodes","maxNodes"];for(let i=0;i{const{hideNodes:hideNodes}=this.getProperties();hideNodes.includes(label)||this.hasLabel(label)&&hideNodes.push(label)}),this._processData())}_processData(){this._neighbors={},this._idToIndex={},this._labelToIndex={};var{nodes:nodes}=this.getOriginalData();const{maxNodes:maxNodes}=this.getProperties();if("number"==typeof maxNodes&&Array.isArray(nodes)&&nodes.length>0){const{minWeight:minWeight,minValue:minValue,count:count}=wordplot.graph.shrink.findOptimalFilters(nodes,maxNodes);null!=count&&console.log(`Map Shrink: Nodes:'${count}', MinWeight:'${minWeight}', MinValue:'${minValue}'`),this.properties.filterMinWeight=minWeight,this.properties.filterMinValue=minValue}var{nodes:nodes,edges:edges}=this._filterData();this._nodes=nodes,this._edges=edges,this._processNeighbors();for(let i=0;i{const{from:from,to:to}=edge;null==neighbors[from]&&(neighbors[from]=new Set),null==neighbors[to]&&(neighbors[to]=new Set),neighbors[from].add(to),neighbors[to].add(from)}),Object.keys(neighbors).forEach(id=>{neighbors[id]=Array.from(neighbors[id])})}_filterData(){const{filterMinValue:filterMinValue,filterMinWeight:filterMinWeight,filterGroups:filterGroups,onlyCompounds:onlyCompounds,hideNodes:hideNodes}=this.getProperties();var{nodes:nodes,edges:edges}=this.getOriginalData();const valueFilterIsActive=filterMinValue>0,weightFilterIsActive=filterMinWeight>0,groupFilterIsActive=filterGroups.length>0,hideNodesIsActive=hideNodes.length>0,filteredNodes=[],filteredEdges=[],filteredIds=new Set,filteredData={nodes:filteredNodes,edges:filteredEdges,ids:filteredIds},groups=new Set(filterGroups);for(let i=0;i1}_sortArrayOfObjects(array,field){if(0===array.length)return array;var sorted=array.sort((a,b)=>b[field]-a[field]);return sorted}_normalizeNodeInfo(node){node.group=Number.parseInt(node.group)}}var version="0.2.2";const importer={url:dependency=>dependency.isLoaded?Promise.resolve():new Promise((resolve,reject)=>{let script=document.createElement("script");script.type="text/javascript",script.src=dependency.url,script.addEventListener("load",()=>resolve(script),!1),script.addEventListener("error",()=>reject(script),!1),document.body.appendChild(script)}),urls:dependencies=>Promise.all(dependencies.map(importer.url))};let loadPromise=null;return{Visualization:Visualization,AxisVisualization:AxisVisualization,Tooltip:Tooltip,buildVisualization:buildVisualization,line:line,legends:legends,logo:{initLogo:initLogo},helpers:helpers,properties:properties,wordmap:{MindMap:MindMap,WordMap:WordMap,HexagonMap:HexagonMap,SquareMap:SquareMap,buildWordMap:buildWordMap,buildMapSeries:buildMapSeries,setSDGColorsInMap:setSDGColorsInMap,configureMapWithSignals:configureMapWithSignals,centerMap:centerMap,MapSeries:MapSeries,enableRelevancyMode:enableRelevancyMode,setColorsToMindMap:setColorsToMindMap,interaction:interaction},top:top,graph:{GraphToMap:GraphToMap,WideGraphToMap:WideGraphToMap,GraphProcessor:GraphProcessor,HexagonGraphProcessor:HexagonGraphProcessor,SquareGraphProcessor:SquareGraphProcessor,shrink:shrink},forms:{Form:Form},json:json,bars:bars,web:web,version:version,save:save,megatron:megatron,load:load}}();