var visualizer=function(){var web=function(){function getParamsFromCurrentUrl(){const paramsStr=window.location.search,urlParams=new URLSearchParams(paramsStr),params={};return urlParams.forEach((value,key)=>{params[key]=value}),params}function urlIsValid(url){try{new URL(url)}catch(error){return!1}return!0}function initializeDefaultParameters(params){params=_standardizeParameters(params),Object.keys(params).forEach(key=>{const value=params[key];(""===value||null==value||"null"==value||Number.isNaN(value))&&(params[key]=void 0)});var{mode:mode="",json_url:json_url="",plot_type:plot_type="",iframe:iframe=!1,height:height=600,width:width=1200,font_family:font_family="sans-serif",font_size:font_size=14,hide_legend:hide_legend=!1,legends:legends=null,background_color:background_color="#F9F9F9",click_action:click_action="",colors:colors=[],color_scale:color_scale="linear",stroke_color:stroke_color="black",hide_numbers:hide_numbers=!0,relevancy_mode:relevancy_mode=!1,sdg_map:sdg_map=!1,fig_size:fig_size=null,filter_min_weight:filter_min_weight=[],filter_min_value:filter_min_value=null,token:token="",hide_nodes:hide_nodes=[],word_type:word_type=null,center_node:center_node=null,max_nodes:max_nodes=null,show_action_buttons:show_action_buttons=!0,number_of_results:number_of_results=20,initial_zoom:initial_zoom=null,center_camera_around:center_camera_around=null,only_nearest_neighbours:only_nearest_neighbours=!1,show_number:show_number=null}=params;null==fig_size&&(fig_size="square"==plot_type?100:70);const newParams={mode:mode,json_url:json_url,plot_type:plot_type,iframe:iframe,width:width,height:height,font_family:font_family,font_size:font_size,hide_legend:hide_legend,legends:legends,background_color:background_color,click_action:click_action,colors:colors,color_scale:color_scale,stroke_color:stroke_color,hide_numbers:hide_numbers,relevancy_mode:relevancy_mode,sdg_map:sdg_map,fig_size:fig_size,filter_min_weight:filter_min_weight,filter_min_value:filter_min_value,token:token,hide_nodes:hide_nodes,word_type:word_type,center_node:center_node,max_nodes:max_nodes,show_action_buttons:show_action_buttons,number_of_results:number_of_results,initial_zoom:initial_zoom,center_camera_around:center_camera_around,only_nearest_neighbours:only_nearest_neighbours,show_number:show_number};return newParams}function _standardizeParameters(params){params.hasOwnProperty("filter_min_weight")&&""==params.filter_min_weight&&(params.filter_min_weight=null);const numericalParams=["width","height","font_size","fig_size","filter_min_value","filter_min_weight","max_nodes","number_of_results","initial_zoom"];numericalParams.forEach(key=>{if(!params.hasOwnProperty(key))return;const value=params[key],newValue=_stringToNumber(value);"number"==typeof newValue&&newValue<0&&(newValue=null),params[key]=newValue});const booleanParams=["iframe","hide_legend","hide_numbers","relevancy_mode","sdg_map","show_action_buttons","only_nearest_neighbours"];booleanParams.forEach(key=>{if(!params.hasOwnProperty(key))return;const value=params[key],newValue=_stringToBoolean(value);params[key]=newValue});const listParams=["colors","legends","hide_nodes"];if(listParams.forEach(key=>{if(!params.hasOwnProperty(key))return;const value=params[key],newValue=_stringToList(value);params[key]=newValue}),params.hasOwnProperty("colors")&&Array.isArray(params.colors))for(var i=0;i{if(!params.hasOwnProperty(key))return;const value=params[key],newValue=value.toLowerCase();params[key]=newValue}),Object.keys(CORRECT_VALUES).forEach(key=>{if(!params.hasOwnProperty(key))return;const value=params[key],correctValues=CORRECT_VALUES[key];if(void 0===correctValues.find(d=>d==value)){const message=`Warning Standardizing Parameters: Skipping ${key} due to an invalid value -> '${value}'`;console.log(message)}});const colorParams=["background_color","stroke_color"];return colorParams.forEach(key=>{if(!params.hasOwnProperty(key))return;const value=params[key],newValue=_stringToColor(value);params[key]=newValue}),params}function _stringToColor(str){if("string"!=typeof str)return null;const hexaColorRegex=/^([a-fA-F0-9]{6})$/;return hexaColorRegex.test(str)?"#"+str:str}function _stringToBoolean(str){return"boolean"==typeof str?str:"string"!=typeof str?null:(str=str.toLowerCase(),"false"!=str&&("true"==str||null))}function _stringToNumber(str){return"number"==typeof str?str:"string"!=typeof str?null:0==str.trim().length?null:(number=Number(str),Number.isNaN(number)?null:number)}function _stringToList(str){if("string"!=typeof str)return null;if(0==str.length)return null;const LIST_SEPARATOR=",",elements=str.split(LIST_SEPARATOR);for(let i=0;i{const id=d.id;idsToPreserve.push(id)});const json=JSON.parse(_DATA_STR);return wordplot.json.reduceMap(json,idsToPreserve),json}function overlapParams(baseParams,extraParams){const params={};if("object"!=typeof baseParams||Array.isArray(baseParams))return params;if("object"!=typeof extraParams||Array.isArray(extraParams))return params;const listBaseParams=Object.keys(baseParams);listBaseParams.forEach(key=>{params[key]=baseParams[key]});const listExtraParams=Object.keys(extraParams);return listExtraParams.forEach(key=>{params[key]=extraParams[key]}),params}return{getDefaultPlotType:getDefaultPlotType,getCurrentJson:getCurrentJson,overlapParams:overlapParams}}(),gui=function(){function showMessage(id,message,props={}){cleanSVG(id);const plot=new wordplot.Visualization(id,props);plot.showMessage(message)}function showTemporalMessage(id,message,timeMilliSeconds,props={}){("number"!=typeof timeMilliSeconds||timeMilliSeconds<0)&&(console.log("Warning at showTemporalMessage() -> timeMilliSeconds must be a positive number"),console.log(typeof timeMilliSeconds),timeMilliSeconds=1e3),showMessage(id,message,props),sleep(timeMilliSeconds).then(()=>{cleanSVG(id)})}function _addModifiedDataUrl(originalUrl,modifiedDataUrl){_JSONS_STORE_MODIFIED_DATA[originalUrl]=modifiedDataUrl}function _storeModifiedData(){const{json_url:json_url,token:token}=form.getSelectedValues(),{width:width}=props,messageProps={width:width};var originalUrl=json_url;if(_JSONS_STORE_MODIFIED_DATA.hasOwnProperty(originalUrl))var url=_JSONS_STORE_MODIFIED_DATA[originalUrl],update=!0;else{url=originalUrl,update=!1;_addModifiedDataUrl(url,null)}if(_JSONS_STORE_MODIFIED_DATA[originalUrl]==originalUrl){const message="Store Modified Data: Prevent overriding original data";return console.log(message),void showTemporalMessage(MESSAGE_PLOT_ID,message,4e3,messageProps)}const requestParams={url:url,token:token,update:update},megatronUrl=wordplot.megatron.buildStoreModifiedDataUrl(requestParams),modifiedData=visualizer.json.getCurrentJson(),httpParams={method:"POST",body:JSON.stringify(modifiedData)};d3.json(megatronUrl,httpParams).then(response=>{if(console.log(response),response.hasOwnProperty("location")){const message="Cleaned Data has been stored. Click on 'Copy Data URL' to get the new URL.";_DATA_URL=response.location,_addModifiedDataUrl(url,response.location),showTemporalMessage(MESSAGE_PLOT_ID,message,4e3,messageProps)}else{const message="Error: Something unexpected happened storing the modified data. Please check that your Token is correct.";showTemporalMessage(MESSAGE_PLOT_ID,message,8e3,messageProps)}})}function getCurrentPlot(){return null==plot?null:null!=plot._subPlot?plot._subPlot:null!=plot._currentMap?plot._currentMap:plot}function _savePng(){_saveVisualization("png")}function _saveSvg(){_saveVisualization("svg")}function _saveVisualization(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=getCurrentPlot(),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)})}function _saveJson(){var json=visualizer.json.getCurrentJson();wordplot.web.downloadObjectAsJsonFile(json)}function cleanSVG(plotId){var svg=d3.select("#"+plotId);svg.selectAll("*").remove(),svg.attr("height","unset").attr("width","unset").style("height","unset").style("width","unset")}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms))}function _copyURL(){const jsonUrl=_DATA_URL;navigator.clipboard.writeText(jsonUrl);const id=MESSAGE_PLOT_ID,message="The URL of the JSON has been copied to your clipboard.",timeMilliSeconds=2e3,props={width:800,height:24};showTemporalMessage(id,message,timeMilliSeconds,props)}function showCleanButtons(divId){const div=d3.select(`div#${divId}`);div.selectAll("button.storeData").data([null]).enter().append("button").attr("class","storeData").on("click",_storeModifiedData).text("Upload Modified JSON"),div.selectAll("button.copyUrl").data([null]).enter().append("button").attr("class","copyUrl").on("click",_copyURL).text("Copy Data URL"),div.selectAll("button.saveJson").data([null]).enter().append("button").attr("class","saveJson").on("click",_saveJson).text("Download Modified JSON")}function showExportButtons(divId){const div=d3.select(`div#${divId}`);div.selectAll("button.savePng").data([null]).enter().append("button").attr("class","savePng").on("click",_savePng).text("Save PNG"),div.selectAll("button.saveSvg").data([null]).enter().append("button").attr("class","saveSvg").on("click",_saveSvg).text("Save SVG"),div.selectAll("button.saveJson").data([null]).enter().append("button").attr("class","saveJson").on("click",_saveJson).text("Save JSON")}function addCleanButtonToForm(formId){const div=d3.select(`div#${formId}`);div.selectAll("button.formClean").data([null]).enter().append("button").attr("class","formClean").on("click",plotFromFormParams).text("Generate Visualization")}function addCustomizeButtonToForm(formId){const div=d3.select(`div#${formId}`);div.selectAll("button.formCustomize").data([null]).enter().append("button").attr("class","formCustomize").on("click",plotFromFormParams).text("Generate Visualization")}return{showMessage:showMessage,showTemporalMessage:showTemporalMessage,showCleanButtons:showCleanButtons,showExportButtons:showExportButtons,addCleanButtonToForm:addCleanButtonToForm,addCustomizeButtonToForm:addCustomizeButtonToForm,cleanSVG:cleanSVG}}(),api={},forms=function(){function buildCustomizeForm(formId,params){const formData=_formCustomize,form=new wordplot.forms.Form(formId,formData);_setFormValues(form,params);const{div:div}=form.getComponents();div.style("min-width","250px");const selection=div.selectAll("br.buttonSeparator").data([null]).enter();return selection.append("br").attr("class","buttonSeparator"),selection.append("br").attr("class","buttonSeparator"),visualizer.gui.addCustomizeButtonToForm(formId),form}function buildCleanForm(formId,params){const formData=_formClean,form=new wordplot.forms.Form(formId,formData),{json_url:json_url,filter_min_weight:filter_min_weight,filter_min_value:filter_min_value,token:token}=params,filteredParams={json_url:json_url,filter_min_weight:filter_min_weight,filter_min_value:filter_min_value,token:token};_setFormValues(form,filteredParams);const{div:div}=form.getComponents();return div.style("min-width","250px"),div.append("br"),div.append("br"),visualizer.gui.addCleanButtonToForm(formId),form}function _setFormValues(form,formValues){const params=Object.keys(form.getSelectedValues());params.forEach(param=>{if(formValues.hasOwnProperty(param)){var value=formValues[param];if(value==form.getSelectedValue(param))return;Array.isArray(value)&&(value=String(value)),form.setValue(param,value)}})}var _formCustomize=[{title:"Json Url",tooltip:"Insert the URL that contains the MindMap you want to customize",type:"text",identifier:"json_url"},{title:"Chart Type",tooltip:"Choose the type of the visualization",type:"checkbox",identifier:"plot_type",options:[{value:"hexagon",label:"Hexagonal Map ⬢",show:["fig_size","stroke_color","hide_numbers","relevancy_mode","color_scale"]},{value:"square",label:"Squared Map ■",show:["fig_size","stroke_color","hide_numbers","relevancy_mode","color_scale"]},{value:"linechart",label:"LineChart",show:[]},{value:"top20",label:"Top 20 Chart",show:[]},{value:"horizontalbarchart",label:"Horizontal BarChart 📊",show:[]},{value:"verticalbarchart",label:"Vertical BarChart 📊",show:[]}]},{title:"Figure Size",type:"select",identifier:"fig_size",hidden:!0,options:[{value:"50",label:"50"},{value:"60",label:"60"},{value:"70",label:"70"},{value:"80",label:"80"},{value:"90",label:"90"},{value:"100",label:"100"}]},{title:"Color Scale",tooltip:"Each scale highlights the colors of the keywords in a different way",type:"checkbox",identifier:"color_scale",options:[{value:"sqrt",label:"Square Root Scale"},{value:"log",label:"Logarithmic Scale"},{value:"linear",label:"Linear Scale"},{value:"pow",label:"Power Scale"},{value:"flat",label:"Flat Scale"}]},{title:"Font Size",type:"select",identifier:"font_size",options:[{value:10,label:10},{value:11,label:11},{value:12,label:12},{value:13,label:13},{value:14,label:14}]},{title:"Font Family",type:"select",identifier:"font_family",options:[{value:"sans-serif",label:"Sans-Serif"},{value:"serif",label:"Serif"},{value:"cursive",label:"Cursive"},{value:"monospace",label:"Monospace"}]},{title:"Colors",tooltip:"List of hexadecimal colors separated by comma. Each color is associated to one group. Some maps contain 1 single group.",type:"text",identifier:"colors"},{title:"Background Color",type:"text",identifier:"background_color"},{title:"Stroke Color",tooltip:"Color of the strokes that separate non-related Concepts",type:"text",identifier:"stroke_color",hidden:!0},{title:"Numerical Values",tooltip:"Do you want to hide the value of each concept?",type:"checkbox",identifier:"hide_numbers",hidden:!0,options:[{value:!0,label:"Hide numbers"}]},{title:"Visualize Relevancy",tooltip:"Do you want to visualize the different levels of relevancy? You cannot modify the default colors of this mode.",type:"checkbox",identifier:"relevancy_mode",hidden:!0,options:[{value:!0,label:"Enable Relevancy Mode"}]}],_formClean=[{title:"Json Url",tooltip:"Insert the URL that contains the MindMap that you want to clean",type:"text",identifier:"json_url"},{title:"Filter by Value",tooltip:"Insert the minimun value that will serve as filter for the nodes",type:"text",identifier:"filter_min_value"},{title:"Filter by Weight",tooltip:"Insert the minimum value ",type:"select",identifier:"filter_min_weight",options:[{value:1,label:"No Filter"},{value:2,label:"Weights 2,3,4,5"},{value:3,label:"Weights 3,4,5"},{value:4,label:"Weights 4,5"},{value:5,label:"Weight 5"}]},{title:"Token",type:"password",identifier:"token"}];return{buildCustomizeForm:buildCustomizeForm,buildCleanForm:buildCleanForm}}(),sdg=function(){function _setTooltipStyle(span){span.style("visibility","hidden").style("position","absolute").style("width","130px").style("background-color","#555").style("color","#fff").style("text-align","center").style("padding","5px 0").style("font-size","12px").style("border-radius","6px").style("z-index","1").style("opacity","0").style("transition","opacity 0.6s")}function loadDataInPanel(panelId,json){try{const goal=json.info.sources.goal;_showSdgImage(panelId,goal);const scores=json.data.scores,indicators=json.data.indicators;_showScores(panelId,scores,indicators)}catch(error){var message="Error executing loadDataInPanel() -> Please verify that the format of your JSON is compatible with SDG Analytics.\n";console.log(message,error),visualizer.gui.showMessage(PLOT_ID,message,props)}}function _showSdgImage(panelId,goal){if(goal.toLowerCase().includes("sdg")&&goal.toLowerCase().includes("goal")){var try_goal_num=goal.match(/\d+/)[0];goal="un_sdg_goal"+try_goal_num+"_en"}const goalToUrl={un_sdg_goal1_en:"https://megatron.headai.com/E-WEB-Goal-01.png",un_sdg_goal2_en:"https://megatron.headai.com/E-WEB-Goal-02.png",un_sdg_goal3_en:"https://megatron.headai.com/E-WEB-Goal-03.png",un_sdg_goal4_en:"https://megatron.headai.com/E-WEB-Goal-04.png",un_sdg_goal5_en:"https://megatron.headai.com/E-WEB-Goal-05.png",un_sdg_goal6_en:"https://megatron.headai.com/E-WEB-Goal-06.png",un_sdg_goal7_en:"https://megatron.headai.com/E-WEB-Goal-07.png",un_sdg_goal8_en:"https://megatron.headai.com/E-WEB-Goal-08.png",un_sdg_goal9_en:"https://megatron.headai.com/E-WEB-Goal-09.png",un_sdg_goal10_en:"https://megatron.headai.com/E-WEB-Goal-10.png",un_sdg_goal11_en:"https://megatron.headai.com/E-WEB-Goal-11.png",un_sdg_goal12_en:"https://megatron.headai.com/E-WEB-Goal-12.png",un_sdg_goal13_en:"https://megatron.headai.com/E-WEB-Goal-13.png",un_sdg_goal14_en:"https://megatron.headai.com/E-WEB-Goal-14.png"};if(!goalToUrl.hasOwnProperty(goal))return;const sdgUrl=goalToUrl[goal],{sdgImage:sdgImage}=_getComponentsFromPanel(panelId);sdgImage.selectAll("img.sdgImage").data([null]).enter().append("img").attr("class","sdgImage").attr("src",sdgUrl).style("width","120px").style("height","120px")}function _showHeadaiImage(panelId){const headaiUrl="https://headai.com/wp-content/uploads/2020/11/headai-logo-with-name-black-transparent.png",{headaiImage:headaiImage}=_getComponentsFromPanel(panelId);headaiImage.selectAll("img.headaiLogo").data([null]).enter().append("img").attr("class","headaiLogo").attr("src",headaiUrl).style("width","120px").style("height","120px")}function _showScores(panelId,scores,indicators){if(null==scores||null==indicators)return;const fullScore=scores.full_score,fullScoreNormalized=scores.full_score_normalized,importantTopicsScore=scores.important_topics_score,importantTopicsScoreNormalized=scores.important_topics_score_normalized,dataSizeBalance=(indicators.meaningful_words_count,indicators.important_topics_count,indicators.data_size_balance),dataQualityFactor=indicators.data_quality_factor,{sdgMessage1:sdgMessage1,sdgMessage2:sdgMessage2}=_getComponentsFromPanel(panelId),messageBox=sdgMessage1,messageBox2=sdgMessage2;var tooltips=[scores.full_score_explanation,scores.full_score_normalized_explanation,indicators.data_size_balance_explanation],messages=["All Concepts: "+String(fullScore),"All Concepts Normalized: "+String(fullScoreNormalized.toFixed(2)),"Data Size Balance: "+String(dataSizeBalance.toFixed(2))];const messages1=[];for(var i=0;id.message);var questionMarks=tooltipBox.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")}),spanTooltip=questionMarks.append("span").attr("class","tooltip_title").text(d=>d.tooltip);_setTooltipStyle(spanTooltip),tooltipBox.append("br")}function isSDGMap(json){if(null==json)return!1;if(!json.hasOwnProperty("data"))return!1;const data=json.data;return!!data.hasOwnProperty("indicators")&&!!data.hasOwnProperty("scores")}function _setStyleToPanelComponents(panelId){const{div:div,headaiImage:headaiImage,sdgTitle:sdgTitle,sdgMessage1:sdgMessage1,sdgMessage2:sdgMessage2,sdgImage:sdgImage}=_getComponentsFromPanel(panelId);div.style("display","flex").style("flex-direction","row"),[headaiImage,sdgMessage1,sdgMessage2,sdgImage].forEach(column=>{column.style("float","left").style("height","100px").style("margin-top","20px").style("margin-right","10px").style("margin-left","10px").style("margin-bottom","10px")}),sdgImage.style("max-width","220px").style("margin-right","20px").style("margin-top","0px"),sdgTitle.style("max-width","250px"),[sdgMessage1,sdgMessage2].forEach(message=>{message.style("min-width","180px").style("max-width","400px").style("margin-top","30px")}),headaiImage.style("width","120px").style("margin-top","0px"),sdgTitle.style("font-family","Raleway").style("font-size","30px").style("margin-left","10px")}function initializePanel(panelId){const div=d3.select(`div#${panelId}`),sdgTitle=(div.selectAll("div.headaiImage").data([null]).enter().append("div").attr("class","headaiImage"),div.selectAll("div.sdgTitle").data([null]).enter().append("div").attr("class","sdgTitle")),panelTitle="Headai SDG MindSet";sdgTitle.append("p").attr("class","title").text(panelTitle),div.selectAll("div.sdgMessage1").data([null]).enter().append("div").attr("class","sdgMessage1"),div.selectAll("div.sdgMessage2").data([null]).enter().append("div").attr("class","sdgMessage2"),div.selectAll("div.sdgImage").data([null]).enter().append("div").attr("class","sdgImage"),_setStyleToPanelComponents(panelId),_showHeadaiImage(panelId)}function _getComponentsFromPanel(panelId){const div=d3.select(`div#${panelId}`),headaiImage=div.select("div.headaiImage"),sdgTitle=div.select("div.sdgTitle"),sdgMessage1=div.select("div.sdgMessage1"),sdgMessage2=div.select("div.sdgMessage2"),sdgImage=div.select("div.sdgImage");return{div:div,headaiImage:headaiImage,sdgTitle:sdgTitle,sdgMessage1:sdgMessage1,sdgMessage2:sdgMessage2,sdgImage:sdgImage}}return{initializePanel:initializePanel,loadDataInPanel:loadDataInPanel,isSDGMap:isSDGMap}}(),mindmap=function(){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}return{generateColorsForPlot:generateColorsForPlot,setColorsToMindMap:setColorsToMindMap}}(),version="2.3.3";return{api:api,forms:forms,gui:gui,json:json,mindmap:mindmap,sdg:sdg,version:version,web:web}}();