@appbaseio/reactivecore
Advanced tools
Comparing version 10.0.0-alpha.10 to 10.0.0-alpha.11
@@ -1,1 +0,1 @@ | ||
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.setSuggestionsSearchValue=setSuggestionsSearchValue;exports.clearSuggestionsSearchValue=clearSuggestionsSearchValue;exports.updateAnalyticsConfig=updateAnalyticsConfig;exports.getRecentSearches=getRecentSearches;exports.recordResultClick=recordResultClick;exports.recordSuggestionClick=recordSuggestionClick;exports.recordImpressions=recordImpressions;var _constants=require('../constants');function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function setSuggestionsSearchValue(value){return{type:_constants.SET_SUGGESTIONS_SEARCH_VALUE,value:value};}function clearSuggestionsSearchValue(){return{type:_constants.CLEAR_SUGGESTIONS_SEARCH_VALUE};}function updateAnalyticsConfig(analyticsConfig){return{type:_constants.UPDATE_ANALYTICS_CONFIG,analyticsConfig:analyticsConfig};}function getRecentSearches(){var queryOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{size:5,minChars:3};return function(dispatch,getState){var _getState=getState(),config=_getState.config,headers=_getState.headers,_getState$appbaseRef=_getState.appbaseRef,url=_getState$appbaseRef.url,protocol=_getState$appbaseRef.protocol,credentials=_getState$appbaseRef.credentials;var app=config.app,mongodb=config.mongodb;var esURL=protocol+'://'+url;var parsedURL=(esURL||'').replace(/\/+$/,'');var requestOptions={headers:_extends({},headers,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials)})};var queryString='';var addParam=function addParam(key,value){if(queryString){queryString+='&'+key+'='+value;}else{queryString+=key+'='+value;}};if(config.analyticsConfig&&config.analyticsConfig.userId){addParam('user_id',config.analyticsConfig.userId);}if(queryOptions){if(queryOptions.size){addParam('size',String(queryOptions.size));}if(queryOptions.from){addParam('from',queryOptions.from);}if(queryOptions.to){addParam('to',queryOptions.to);}if(queryOptions.minChars){addParam('min_chars',String(queryOptions.minChars));}if(queryOptions.customEvents){Object.keys(queryOptions.customEvents).forEach(function(key){addParam(key,queryOptions.customEvents[key]);});}}if(mongodb){return dispatch({type:_constants.RECENT_SEARCHES_SUCCESS,data:[]});}return fetch(parsedURL+'/_analytics/'+app+'/recent-searches?'+queryString,requestOptions).then(function(res){if(res.status>=500||res.status>=400){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:res});}return res.json().then(function(recentSearches){return dispatch({type:_constants.RECENT_SEARCHES_SUCCESS,data:recentSearches});}).catch(function(e){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:e});});}).catch(function(e){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:e});});};}function recordClick(_ref){var documentId=_ref.documentId,clickPosition=_ref.clickPosition,analyticsInstance=_ref.analyticsInstance,isSuggestionClick=_ref.isSuggestionClick;if(!documentId){console.warn('ReactiveSearch: document id is required to record the click analytics');}else{analyticsInstance.click({queryID:analyticsInstance.getQueryID(),objects:_defineProperty({},documentId,clickPosition+1),isSuggestionClick:isSuggestionClick});}}function recordResultClick(searchPosition,documentId){return function(dispatch,getState){var _getState2=getState(),config=_getState2.config,searchId=_getState2.analytics.searchId,headers=_getState2.headers,_getState2$appbaseRef=_getState2.appbaseRef,url=_getState2$appbaseRef.url,protocol=_getState2$appbaseRef.protocol,credentials=_getState2$appbaseRef.credentials,analyticsInstance=_getState2.analyticsRef;var app=config.app;var esURL=protocol+'://'+url;if(config.analytics&&searchId){var parsedHeaders=headers;delete parsedHeaders['X-Search-Query'];var parsedURL=(esURL||'').replace(/\/+$/,'');if(parsedURL.includes('scalr.api.appbase.io')){fetch(parsedURL+'/'+app+'/_analytics',{method:'POST',headers:_extends({},parsedHeaders,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials),'X-Search-Id':searchId,'X-Search-Click':true,'X-Search-ClickPosition':searchPosition+1})});}else{recordClick({documentId:documentId,clickPosition:searchPosition,analyticsInstance:analyticsInstance});}}};}function recordSuggestionClick(searchPosition,documentId){return function(dispatch,getState){var _getState3=getState(),config=_getState3.config,suggestionsSearchId=_getState3.analytics.suggestionsSearchId,headers=_getState3.headers,_getState3$appbaseRef=_getState3.appbaseRef,url=_getState3$appbaseRef.url,protocol=_getState3$appbaseRef.protocol,credentials=_getState3$appbaseRef.credentials,analyticsInstance=_getState3.analyticsRef;var app=config.app;var esURL=protocol+'://'+url;if(config.analytics&&(config.analyticsConfig===undefined||config.analyticsConfig.suggestionAnalytics===undefined||config.analyticsConfig.suggestionAnalytics)){var parsedHeaders=headers;delete parsedHeaders['X-Search-Query'];var parsedURL=(esURL||'').replace(/\/+$/,'');if(parsedURL.includes('scalr.api.appbase.io')&&searchPosition!==undefined&&suggestionsSearchId){fetch(parsedURL+'/'+app+'/_analytics',{method:'POST',headers:_extends({},parsedHeaders,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials),'X-Search-Id':suggestionsSearchId,'X-Search-Suggestions-Click':true,'X-Search-Suggestions-ClickPosition':searchPosition+1})});}else if(searchPosition!==undefined){recordClick({documentId:documentId,clickPosition:searchPosition,analyticsInstance:analyticsInstance,isSuggestionClick:true});}}};}function recordImpressions(queryId){var impressions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];return function(dispatch,getState){var _getState4=getState(),_getState4$appbaseRef=_getState4.appbaseRef,url=_getState4$appbaseRef.url,protocol=_getState4$appbaseRef.protocol,analyticsInstance=_getState4.analyticsRef,config=_getState4.config;var esURL=protocol+'://'+url;var parsedURL=esURL.replace(/\/+$/,'');if(config.analytics&&!parsedURL.includes('scalr.api.appbase.io')&&queryId&&impressions.length){analyticsInstance.search({queryID:analyticsInstance.getQueryID(),impressions:impressions});}};} | ||
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.setSuggestionsSearchValue=setSuggestionsSearchValue;exports.clearSuggestionsSearchValue=clearSuggestionsSearchValue;exports.updateAnalyticsConfig=updateAnalyticsConfig;exports.getRecentSearches=getRecentSearches;exports.recordResultClick=recordResultClick;exports.recordSuggestionClick=recordSuggestionClick;exports.recordImpressions=recordImpressions;exports.recordAISessionUsefulness=recordAISessionUsefulness;var _constants=require('../constants');function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function setSuggestionsSearchValue(value){return{type:_constants.SET_SUGGESTIONS_SEARCH_VALUE,value:value};}function clearSuggestionsSearchValue(){return{type:_constants.CLEAR_SUGGESTIONS_SEARCH_VALUE};}function updateAnalyticsConfig(analyticsConfig){return{type:_constants.UPDATE_ANALYTICS_CONFIG,analyticsConfig:analyticsConfig};}function getRecentSearches(){var queryOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{size:5,minChars:3};return function(dispatch,getState){var _getState=getState(),config=_getState.config,headers=_getState.headers,_getState$appbaseRef=_getState.appbaseRef,url=_getState$appbaseRef.url,protocol=_getState$appbaseRef.protocol,credentials=_getState$appbaseRef.credentials;var app=config.app,mongodb=config.mongodb;var esURL=protocol+'://'+url;var parsedURL=(esURL||'').replace(/\/+$/,'');var requestOptions={headers:_extends({},headers,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials)})};var queryString='';var addParam=function addParam(key,value){if(queryString){queryString+='&'+key+'='+value;}else{queryString+=key+'='+value;}};if(config.analyticsConfig&&config.analyticsConfig.userId){addParam('user_id',config.analyticsConfig.userId);}if(queryOptions){if(queryOptions.size){addParam('size',String(queryOptions.size));}if(queryOptions.from){addParam('from',queryOptions.from);}if(queryOptions.to){addParam('to',queryOptions.to);}if(queryOptions.minChars){addParam('min_chars',String(queryOptions.minChars));}if(queryOptions.customEvents){Object.keys(queryOptions.customEvents).forEach(function(key){addParam(key,queryOptions.customEvents[key]);});}}if(mongodb){return dispatch({type:_constants.RECENT_SEARCHES_SUCCESS,data:[]});}return fetch(parsedURL+'/_analytics/'+app+'/recent-searches?'+queryString,requestOptions).then(function(res){if(res.status>=500||res.status>=400){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:res});}return res.json().then(function(recentSearches){return dispatch({type:_constants.RECENT_SEARCHES_SUCCESS,data:recentSearches});}).catch(function(e){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:e});});}).catch(function(e){return dispatch({type:_constants.RECENT_SEARCHES_ERROR,error:e});});};}function recordClick(_ref){var documentId=_ref.documentId,clickPosition=_ref.clickPosition,analyticsInstance=_ref.analyticsInstance,isSuggestionClick=_ref.isSuggestionClick;if(!documentId){console.warn('ReactiveSearch: document id is required to record the click analytics');}else{analyticsInstance.click({queryID:analyticsInstance.getQueryID(),objects:_defineProperty({},documentId,clickPosition+1),isSuggestionClick:isSuggestionClick});}}function recordResultClick(searchPosition,documentId){return function(dispatch,getState){var _getState2=getState(),config=_getState2.config,searchId=_getState2.analytics.searchId,headers=_getState2.headers,_getState2$appbaseRef=_getState2.appbaseRef,url=_getState2$appbaseRef.url,protocol=_getState2$appbaseRef.protocol,credentials=_getState2$appbaseRef.credentials,analyticsInstance=_getState2.analyticsRef;var app=config.app;var esURL=protocol+'://'+url;if(config.analytics&&searchId){var parsedHeaders=headers;delete parsedHeaders['X-Search-Query'];var parsedURL=(esURL||'').replace(/\/+$/,'');if(parsedURL.includes('scalr.api.appbase.io')){fetch(parsedURL+'/'+app+'/_analytics',{method:'POST',headers:_extends({},parsedHeaders,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials),'X-Search-Id':searchId,'X-Search-Click':true,'X-Search-ClickPosition':searchPosition+1})});}else{recordClick({documentId:documentId,clickPosition:searchPosition,analyticsInstance:analyticsInstance});}}};}function recordSuggestionClick(searchPosition,documentId){return function(dispatch,getState){var _getState3=getState(),config=_getState3.config,suggestionsSearchId=_getState3.analytics.suggestionsSearchId,headers=_getState3.headers,_getState3$appbaseRef=_getState3.appbaseRef,url=_getState3$appbaseRef.url,protocol=_getState3$appbaseRef.protocol,credentials=_getState3$appbaseRef.credentials,analyticsInstance=_getState3.analyticsRef;var app=config.app;var esURL=protocol+'://'+url;if(config.analytics&&(config.analyticsConfig===undefined||config.analyticsConfig.suggestionAnalytics===undefined||config.analyticsConfig.suggestionAnalytics)){var parsedHeaders=headers;delete parsedHeaders['X-Search-Query'];var parsedURL=(esURL||'').replace(/\/+$/,'');if(parsedURL.includes('scalr.api.appbase.io')&&searchPosition!==undefined&&suggestionsSearchId){fetch(parsedURL+'/'+app+'/_analytics',{method:'POST',headers:_extends({},parsedHeaders,{'Content-Type':'application/json',Authorization:'Basic '+btoa(credentials),'X-Search-Id':suggestionsSearchId,'X-Search-Suggestions-Click':true,'X-Search-Suggestions-ClickPosition':searchPosition+1})});}else if(searchPosition!==undefined){recordClick({documentId:documentId,clickPosition:searchPosition,analyticsInstance:analyticsInstance,isSuggestionClick:true});}}};}function recordImpressions(queryId){var impressions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];return function(dispatch,getState){var _getState4=getState(),_getState4$appbaseRef=_getState4.appbaseRef,url=_getState4$appbaseRef.url,protocol=_getState4$appbaseRef.protocol,analyticsInstance=_getState4.analyticsRef,config=_getState4.config;var esURL=protocol+'://'+url;var parsedURL=esURL.replace(/\/+$/,'');if(config.analytics&&!parsedURL.includes('scalr.api.appbase.io')&&queryId&&impressions.length){analyticsInstance.search({queryID:analyticsInstance.getQueryID(),impressions:impressions});}};}function recordAISessionUsefulness(sessionId,otherInfo){return function(dispatch,getState){var _getState5=getState(),analyticsInstance=_getState5.analyticsRef,config=_getState5.config;var userID=config&&config.analyticsConfig&&config.analyticsConfig.userId;if(!sessionId){console.warn('ReactiveSearch: AI sessionID is required to record the usefulness of session.');}analyticsInstance.saveSessionUsefulness(sessionId,_extends({},otherInfo,{userID:userID}),function(err,res){console.log('res',res);});};} |
@@ -1,1 +0,1 @@ | ||
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.loadPopularSuggestions=loadPopularSuggestions;exports.executeQuery=executeQuery;exports.setQueryOptions=setQueryOptions;exports.updateQuery=updateQuery;exports.loadMore=loadMore;exports.loadDataToExport=loadDataToExport;exports.fetchAIResponse=fetchAIResponse;var _value2=require('./value');var _utils=require('./utils');var _misc=require('./misc');var _helper=require('../utils/helper');var _maps=require('./maps');var _constants=require('../utils/constants');var _transform=require('../utils/transform');var _transform2=require('../../lib/utils/transform');function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function loadPopularSuggestions(componentId){return function(dispatch,getState){var _getState=getState(),config=_getState.config,appbaseRef=_getState.appbaseRef,props=_getState.props,internalValues=_getState.internalValues;var componentProps=props[componentId]||{};var internalValue=internalValues[componentId];var value=internalValue&&internalValue.value||'';if(componentProps.enablePopularSuggestions){if(config.mongodb){dispatch((0,_misc.setDefaultPopularSuggestions)([],componentId.split('__internal')[0]));return;}var suggQuery=(0,_utils.getSuggestionQuery)(getState,componentId);appbaseRef.getQuerySuggestions(suggQuery).then(function(suggestions){var querySuggestion=suggestions[(0,_utils.getQuerySuggestionsId)(componentId)];if(value){dispatch((0,_misc.setPopularSuggestions)(querySuggestion&&querySuggestion.hits&&querySuggestion.hits.hits,componentId.split('__internal')[0]));}else{dispatch((0,_misc.setDefaultPopularSuggestions)(querySuggestion&&querySuggestion.hits&&querySuggestion.hits.hits,componentId.split('__internal')[0]));}}).catch(function(e){(0,_utils.handleError)({orderOfQueries:[componentId],error:e},getState,dispatch);});}};}function appbaseSearch(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},queryId=_ref.queryId,query=_ref.query,orderOfQueries=_ref.orderOfQueries,_ref$appendToHits=_ref.appendToHits,appendToHits=_ref$appendToHits===undefined?false:_ref$appendToHits,_ref$isSuggestionsQue=_ref.isSuggestionsQuery,isSuggestionsQuery=_ref$isSuggestionsQue===undefined?false:_ref$isSuggestionsQue,searchComponentID=_ref.searchComponentID,_ref$appendToAggs=_ref.appendToAggs,appendToAggs=_ref$appendToAggs===undefined?false:_ref$appendToAggs;return function(dispatch,getState){var _getState2=getState(),appbaseRef=_getState2.appbaseRef,config=_getState2.config,headers=_getState2.headers,props=_getState2.props;var isAnalyticsEnabled=false;if(config){if((0,_utils.isPropertyDefined)(config.analytics)){isAnalyticsEnabled=config.analytics;}else if(config.analyticsConfig){if((0,_utils.isPropertyDefined)(config.analyticsConfig.recordAnalytics)){isAnalyticsEnabled=config.analyticsConfig.recordAnalytics;}else if((0,_utils.isPropertyDefined)(config.analyticsConfig.analytics)){isAnalyticsEnabled=config.analyticsConfig.analytics;}}}var settings={recordAnalytics:isAnalyticsEnabled};if(config.analyticsConfig){settings.userId=(0,_utils.isPropertyDefined)(config.analyticsConfig.userId)?config.analyticsConfig.userId:undefined;settings.enableQueryRules=(0,_utils.isPropertyDefined)(config.analyticsConfig.enableQueryRules)?config.analyticsConfig.enableQueryRules:undefined;settings.customEvents=(0,_utils.isPropertyDefined)(config.analyticsConfig.customEvents)?config.analyticsConfig.customEvents:undefined;settings.emptyQuery=(0,_utils.isPropertyDefined)(config.analyticsConfig.emptyQuery)?config.analyticsConfig.emptyQuery:undefined;var searchRelevancy=config.analyticsConfig.enableSearchRelevancy;settings.enableSearchRelevancy=(0,_utils.isPropertyDefined)(searchRelevancy)?searchRelevancy:undefined;settings.suggestionAnalytics=(0,_utils.isPropertyDefined)(config.analyticsConfig.suggestionAnalytics)?config.analyticsConfig.suggestionAnalytics:undefined;settings.useCache=(0,_utils.isPropertyDefined)(config.analyticsConfig.useCache)?config.analyticsConfig.useCache:undefined;settings.queryParams=(0,_utils.isPropertyDefined)(config.analyticsConfig.queryParams)?config.analyticsConfig.queryParams:undefined;}orderOfQueries.forEach(function(component){dispatch((0,_misc.setLoading)(component,true));if(props[component]&&props[component].enableAI){dispatch((0,_misc.removeAIResponse)(component));}dispatch((0,_misc.setError)(component,null));});appbaseRef.setHeaders(_extends({},headers));if(isSuggestionsQuery&&searchComponentID){dispatch(loadPopularSuggestions(searchComponentID));}appbaseRef.reactiveSearch(query,settings,settings.queryParams).then(function(res){(0,_utils.handleResponse)({res:res,orderOfQueries:orderOfQueries,appendToHits:appendToHits,appendToAggs:appendToAggs,query:query,queryId:queryId},getState,dispatch);}).catch(function(err){(0,_utils.handleError)({orderOfQueries:orderOfQueries,error:err,queryId:queryId},getState,dispatch);});};}var requestStack=[];function executeQuery(componentId){var executeWatchList=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var mustExecuteMapQuery=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var componentType=arguments[3];var metaOptions=arguments[4];var requestId=arguments[5];return function(dispatch,getState){var _getState3=getState(),queryLog=_getState3.queryLog,config=_getState3.config,mapData=_getState3.mapData,watchMan=_getState3.watchMan,queryListener=_getState3.queryListener,props=_getState3.props,internalValues=_getState3.internalValues,lock=_getState3.lock,dependencyTree=_getState3.dependencyTree,queryList=_getState3.queryList,queryOptions=_getState3.queryOptions;var lockTime=config.initialQueriesSyncTime||100;var initialTimestamp=config.initialTimestamp;var queryId=requestId||new Date().getTime();if(config.queryLockConfig instanceof Object){lockTime=config.queryLockConfig.lockTime;initialTimestamp=config.queryLockConfig.initialTimestamp;}var componentList=[componentId];var finalQuery=[];var appbaseQuery={};var orderOfQueries=[];if(executeWatchList){var watchList=watchMan[componentId]||[];componentList=[].concat(_toConsumableArray(componentList),_toConsumableArray(watchList));}componentList.forEach(function(component){var _buildQuery=(0,_helper.buildQuery)(component,dependencyTree,queryList,queryOptions),queryObj=_buildQuery.queryObj,options=_buildQuery.options;if(!queryObj&&!options){return;}var value=void 0;var isInternalComponent=componentId.endsWith('__internal');var mainComponentProps=props[componentId];if(isInternalComponent&&mainComponentProps&&(0,_transform.isSearchComponent)(mainComponentProps.componentType)){value=internalValues[componentId]&&internalValues[componentId].value;}var query=(0,_transform.getRSQuery)(component,(0,_transform.extractPropsFromState)(getState(),component,_extends({},value?{value:value}:null,metaOptions?{from:metaOptions.from}:null)));if(query&&!!Object.keys(query).length){var currentQuery=query;var oldQuery=queryLog[component];var componentProps=props[component];var dependentQueries=(0,_transform.getDependentQueries)(getState(),component,orderOfQueries);var queryToLog=_extends(_defineProperty({},component,currentQuery),Object.keys(dependentQueries).reduce(function(acc,q){return _extends({},acc,_defineProperty({},q,_extends({},dependentQueries[q],{execute:false},dependentQueries[q].type===_constants.queryTypes.suggestion?{type:'search'}:{})));},{}));var queryType=_transform.componentToTypeMap[componentProps&&componentProps.componentType];if([_constants.queryTypes.range,_constants.queryTypes.term].includes(queryType)){var _value=currentQuery.value,rest=_objectWithoutProperties(currentQuery,['value']);queryToLog=_extends(_defineProperty({},component,rest),Object.keys(dependentQueries).reduce(function(acc,q){return _extends({},acc,_defineProperty({},q,_extends({},dependentQueries[q],{execute:false},dependentQueries[q].type===_constants.queryTypes.suggestion?{type:'search'}:{})));},{}));}if(mustExecuteMapQuery||!(0,_helper.compareQueries)(queryToLog,oldQuery,false)){orderOfQueries=[].concat(_toConsumableArray(orderOfQueries),[component]);var isMapComponent=Object.keys(mapData).includes(component);if(isMapComponent){dispatch((0,_misc.setLastUsedAppbaseQuery)(_defineProperty({},component,{queryId:queryId})));}dispatch((0,_misc.logQuery)(component,queryToLog));if(isMapComponent&&mapData[component].query){var existingQuery=currentQuery.query;currentQuery.query={bool:{must:[existingQuery,mapData[component].query]}};if(!mapData[component].persistMapQuery){dispatch((0,_maps.updateMapData)(componentId,null,false));}var _getState4=getState(),combinedLog=_getState4.combinedLog;if((0,_helper.compareQueries)(combinedLog[component],currentQuery))return;dispatch((0,_misc.logCombinedQuery)(component,currentQuery));}(0,_utils.executeQueryListener)(queryListener[component],oldQuery,currentQuery);if(query){appbaseQuery=_extends({},appbaseQuery,_defineProperty({},component,query),(0,_transform.getDependentQueries)(getState(),component,orderOfQueries));}if(isMapComponent){var internalComponent=(0,_transform2.getInternalComponentID)(component);var internalQuery=(0,_transform.getRSQuery)(internalComponent,(0,_transform.extractPropsFromState)(getState(),internalComponent,metaOptions?{from:metaOptions.from}:null));if(internalQuery){appbaseQuery[internalComponent]=_extends({},internalQuery,{execute:false});}}}}});finalQuery=Object.keys(appbaseQuery).map(function(component){return appbaseQuery[component];});if(finalQuery.length){var suggestionsComponents=[_constants.componentTypes.dataSearch,_constants.componentTypes.categorySearch];var isInternalComponent=componentId.endsWith('__internal');var isSuggestionsQuery=isInternalComponent&&suggestionsComponents.indexOf(componentType)!==-1;var currentTime=new Date().getTime();if(currentTime-initialTimestamp<lockTime){if(!lock||config.queryLockConfig){setTimeout(function(){var finalOrderOfQueries=[];var finalIsSuggestionsQuery=false;var finalSearchComponentID='';var orderOfQueriesMap={};var processedQueriesMap={};var queryExecutionMap={};requestStack.forEach(function(request){if(!finalIsSuggestionsQuery){finalIsSuggestionsQuery=request.isSuggestionsQuery;}if(!finalSearchComponentID){finalSearchComponentID=request.searchComponentID;}if(Array.isArray(request.query)){request.query.forEach(function(query){if(query.execute){queryExecutionMap[query.id]=query.execute;}var newQuery=query;if(queryExecutionMap[query.id]){newQuery.execute=true;}if(processedQueriesMap[query.id]&&processedQueriesMap[query.id].type===_constants.queryTypes.suggestion&&newQuery.type!==_constants.queryTypes.suggestion){processedQueriesMap[query.id+'__suggestion_type']=_extends({},processedQueriesMap[query.id]);processedQueriesMap[query.id]=_extends({},newQuery,{execute:false});return;}processedQueriesMap[query.id]=newQuery;});}if(Array.isArray(request.orderOfQueries)){request.orderOfQueries.forEach(function(query){if(!orderOfQueriesMap[query.id]){finalOrderOfQueries=[query].concat(_toConsumableArray(finalOrderOfQueries));}else{orderOfQueriesMap[query.id]=true;}});}});var finalCombinedQuery=Object.values(processedQueriesMap);if(finalCombinedQuery.length){dispatch(appbaseSearch({query:finalCombinedQuery,orderOfQueries:finalOrderOfQueries,isSuggestionsQuery:finalIsSuggestionsQuery,searchComponentID:finalSearchComponentID}));}requestStack=[];dispatch((0,_utils.updateStoreConfig)({queryLockConfig:undefined}));},lockTime);}dispatch((0,_utils.updateStoreConfig)({lock:true}));requestStack.push({query:finalQuery,orderOfQueries:orderOfQueries,isSuggestionsQuery:isSuggestionsQuery,searchComponentID:componentId});}else{dispatch(appbaseSearch({queryId:queryId,query:finalQuery,orderOfQueries:Array.from(new Set([].concat(_toConsumableArray(orderOfQueries),_toConsumableArray(componentList.filter(function(c){return props[c].enableAI;}))))),isSuggestionsQuery:isSuggestionsQuery,searchComponentID:componentId}));}}};}function setQueryOptions(component,queryOptions){var execute=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return function(dispatch){dispatch((0,_misc.updateQueryOptions)(component,queryOptions));if(execute){dispatch(executeQuery(component,true));}};}function updateQuery(_ref2){var componentId=_ref2.componentId,query=_ref2.query,value=_ref2.value,_ref2$label=_ref2.label,label=_ref2$label===undefined?null:_ref2$label,_ref2$showFilter=_ref2.showFilter,showFilter=_ref2$showFilter===undefined?true:_ref2$showFilter,_ref2$URLParams=_ref2.URLParams,URLParams=_ref2$URLParams===undefined?false:_ref2$URLParams,_ref2$componentType=_ref2.componentType,componentType=_ref2$componentType===undefined?null:_ref2$componentType,_ref2$category=_ref2.category,category=_ref2$category===undefined?null:_ref2$category,_ref2$meta=_ref2.meta,meta=_ref2$meta===undefined?{}:_ref2$meta;var execute=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var shouldSetInternalValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return function(dispatch){var queryToDispatch=query;if(query&&query.query){queryToDispatch=query.query;}if(!componentId.endsWith('__internal')){dispatch((0,_value2.setValue)(componentId,value,label,showFilter,URLParams,componentType,category,meta));if(shouldSetInternalValue){if(componentType===_constants.componentTypes.dynamicRangeSlider){dispatch((0,_value2.setInternalValue)((0,_transform.getHistogramComponentID)(componentId),value,componentType,category,meta));}else{dispatch((0,_value2.setInternalValue)(componentId+'__internal',value,componentType,category,meta));}}}else{dispatch((0,_value2.setInternalValue)(componentId,value,componentType,category,meta));}dispatch((0,_misc.setQuery)(componentId,queryToDispatch));if(execute)dispatch(executeQuery(componentId,true,false,componentType));};}function loadMore(component,newOptions){var appendToHits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var appendToAggs=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;return function(dispatch,getState){var store=getState();var _buildQuery2=(0,_helper.buildQuery)(component,store.dependencyTree,store.queryList,store.queryOptions),queryObj=_buildQuery2.queryObj,options=_buildQuery2.options;var queryLog=store.queryLog;if(!options)options={};options=_extends({},options,newOptions);if(!queryObj||queryObj&&!Object.keys(queryObj).length){queryObj={match_all:{}};}var appbaseQuery={};var componentProps=store.props[component]||{};var compositeAggregationField=componentProps.aggregationField;var queryType=_transform.componentToTypeMap[componentProps.componentType];if(queryType===_constants.queryTypes.term){compositeAggregationField=componentProps.dataField;}var query=(0,_transform.getRSQuery)(component,(0,_transform.extractPropsFromState)(store,component,{from:options.from,after:store.aggregations[component]&&store.aggregations[component][compositeAggregationField]&&store.aggregations[component][compositeAggregationField].after_key||undefined}));appbaseQuery=_extends(_defineProperty({},component,query),(0,_transform.getDependentQueries)(getState(),component,[]));if((0,_helper.compareQueries)(queryLog[component],appbaseQuery))return;dispatch((0,_misc.logQuery)(component,appbaseQuery));var finalQuery=Object.keys(appbaseQuery).map(function(c){return appbaseQuery[c];});dispatch(appbaseSearch({query:finalQuery,orderOfQueries:[component],appendToHits:appendToHits,appendToAggs:appendToAggs}));};}function loadDataToExport(componentId){var deepPaginationCursor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var totalResults=arguments[2];var data=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[];return function(dispatch,getState){var _getState5=getState(),appbaseRef=_getState5.appbaseRef,lastUsedAppbaseQuery=_getState5.lastUsedAppbaseQuery;var queryFromStore=lastUsedAppbaseQuery[componentId];if(queryFromStore){var query=queryFromStore.map(function(queryItem){if(queryItem.id===componentId){var finalQueryItem=_extends({},queryItem,{deepPaginationConfig:{cursor:deepPaginationCursor},deepPagination:true,size:totalResults<1000?totalResults:1000,sortField:'_id',sortBy:'asc'});delete finalQueryItem.from;return finalQueryItem;}return queryItem;});if(totalResults&&Array.isArray(data)&&totalResults<=data.length){return data;}return appbaseRef.reactiveSearchv3(query).then(function(res){var newDataChunk=res[componentId].hits.hits;if(!Array.isArray(newDataChunk)||newDataChunk.length===0){return data;}return dispatch(loadDataToExport(componentId,newDataChunk[newDataChunk.length-1]._id,res[componentId].hits.total.value,[].concat(_toConsumableArray(data),_toConsumableArray(newDataChunk))));}).catch(function(err){console.error('Error fetching data to export! ',err);});}return console.error('Error fetching data to export!');};}function fetchAIResponse(AIAnswerKey,componentId,question){var meta=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};return function(dispatch,getState){var isPostRequest=!!question;dispatch((0,_misc.setAIResponseLoading)(componentId,true));var _getState6=getState(),_getState6$config=_getState6.config,url=_getState6$config.url,configCredentials=_getState6$config.credentials;var urlObj=new URL(url);var credentials=configCredentials;if(urlObj.username&&urlObj.password){credentials=urlObj.username+':'+urlObj.password;urlObj.username='';urlObj.password='';}var fetchUrl=urlObj.toString()+'_ai/'+AIAnswerKey;var headers=new Headers();if(credentials){var encodedCredentials=btoa(credentials);headers.append('Authorization','Basic '+encodedCredentials);}var method=isPostRequest?'POST':'GET';var body=void 0;var localCache=((0,_helper.getObjectFromLocalStorage)(_constants.AI_LOCAL_CACHE_KEY)||{})[componentId];if(isPostRequest&&question){body=JSON.stringify({question:question});}fetch(fetchUrl,{headers:headers,method:method,body:body}).then(function(res){return res.json();}).then(function(parsedRes){if(parsedRes.response&&parsedRes.response.error){dispatch((0,_misc.setAIResponseError)(componentId,parsedRes.response.error,{sessionId:AIAnswerKey}));}else if(parsedRes.error){dispatch((0,_misc.setAIResponseError)(componentId,parsedRes.error,{sessionId:AIAnswerKey}));}else{var finalResponse=_extends({},parsedRes);if(finalResponse.answer){finalResponse.answer.role=_constants.AI_ROLES.ASSISTANT;}dispatch((0,_misc.setAIResponse)(componentId,{meta:meta,sessionId:AIAnswerKey,messages:[].concat(_toConsumableArray(isPostRequest?localCache.messages:[]),_toConsumableArray(finalResponse.question?[{content:finalResponse.question,role:_constants.AI_ROLES.USER}]:[]),_toConsumableArray(finalResponse.answer?[{content:finalResponse.answer.text,role:_constants.AI_ROLES.ASSISTANT}]:[])),response:_extends({},finalResponse)}));}}).catch(function(e){dispatch((0,_misc.setAIResponseError)(componentId,e,{sessionId:AIAnswerKey}));});};} | ||
Object.defineProperty(exports,"__esModule",{value:true});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.loadPopularSuggestions=loadPopularSuggestions;exports.executeQuery=executeQuery;exports.setQueryOptions=setQueryOptions;exports.updateQuery=updateQuery;exports.loadMore=loadMore;exports.loadDataToExport=loadDataToExport;exports.fetchAIResponse=fetchAIResponse;var _value2=require('./value');var _utils=require('./utils');var _misc=require('./misc');var _helper=require('../utils/helper');var _maps=require('./maps');var _constants=require('../utils/constants');var _transform=require('../utils/transform');var _transform2=require('../../lib/utils/transform');function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function loadPopularSuggestions(componentId){return function(dispatch,getState){var _getState=getState(),config=_getState.config,appbaseRef=_getState.appbaseRef,props=_getState.props,internalValues=_getState.internalValues;var componentProps=props[componentId]||{};var internalValue=internalValues[componentId];var value=internalValue&&internalValue.value||'';if(componentProps.enablePopularSuggestions){if(config.mongodb){dispatch((0,_misc.setDefaultPopularSuggestions)([],componentId.split('__internal')[0]));return;}var suggQuery=(0,_utils.getSuggestionQuery)(getState,componentId);appbaseRef.getQuerySuggestions(suggQuery).then(function(suggestions){var querySuggestion=suggestions[(0,_utils.getQuerySuggestionsId)(componentId)];if(value){dispatch((0,_misc.setPopularSuggestions)(querySuggestion&&querySuggestion.hits&&querySuggestion.hits.hits,componentId.split('__internal')[0]));}else{dispatch((0,_misc.setDefaultPopularSuggestions)(querySuggestion&&querySuggestion.hits&&querySuggestion.hits.hits,componentId.split('__internal')[0]));}}).catch(function(e){(0,_utils.handleError)({orderOfQueries:[componentId],error:e},getState,dispatch);});}};}function appbaseSearch(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},queryId=_ref.queryId,query=_ref.query,orderOfQueries=_ref.orderOfQueries,_ref$appendToHits=_ref.appendToHits,appendToHits=_ref$appendToHits===undefined?false:_ref$appendToHits,_ref$isSuggestionsQue=_ref.isSuggestionsQuery,isSuggestionsQuery=_ref$isSuggestionsQue===undefined?false:_ref$isSuggestionsQue,searchComponentID=_ref.searchComponentID,_ref$appendToAggs=_ref.appendToAggs,appendToAggs=_ref$appendToAggs===undefined?false:_ref$appendToAggs;return function(dispatch,getState){var _getState2=getState(),appbaseRef=_getState2.appbaseRef,config=_getState2.config,headers=_getState2.headers,props=_getState2.props;var isAnalyticsEnabled=false;if(config){if((0,_utils.isPropertyDefined)(config.analytics)){isAnalyticsEnabled=config.analytics;}else if(config.analyticsConfig){if((0,_utils.isPropertyDefined)(config.analyticsConfig.recordAnalytics)){isAnalyticsEnabled=config.analyticsConfig.recordAnalytics;}else if((0,_utils.isPropertyDefined)(config.analyticsConfig.analytics)){isAnalyticsEnabled=config.analyticsConfig.analytics;}}}var settings={recordAnalytics:isAnalyticsEnabled};if(config.analyticsConfig){settings.userId=(0,_utils.isPropertyDefined)(config.analyticsConfig.userId)?config.analyticsConfig.userId:undefined;settings.enableQueryRules=(0,_utils.isPropertyDefined)(config.analyticsConfig.enableQueryRules)?config.analyticsConfig.enableQueryRules:undefined;settings.customEvents=(0,_utils.isPropertyDefined)(config.analyticsConfig.customEvents)?config.analyticsConfig.customEvents:undefined;settings.emptyQuery=(0,_utils.isPropertyDefined)(config.analyticsConfig.emptyQuery)?config.analyticsConfig.emptyQuery:undefined;var searchRelevancy=config.analyticsConfig.enableSearchRelevancy;settings.enableSearchRelevancy=(0,_utils.isPropertyDefined)(searchRelevancy)?searchRelevancy:undefined;settings.suggestionAnalytics=(0,_utils.isPropertyDefined)(config.analyticsConfig.suggestionAnalytics)?config.analyticsConfig.suggestionAnalytics:undefined;settings.useCache=(0,_utils.isPropertyDefined)(config.analyticsConfig.useCache)?config.analyticsConfig.useCache:undefined;settings.queryParams=(0,_utils.isPropertyDefined)(config.analyticsConfig.queryParams)?config.analyticsConfig.queryParams:undefined;}orderOfQueries.forEach(function(component){dispatch((0,_misc.setLoading)(component,true));if(props[component]&&props[component].enableAI){dispatch((0,_misc.removeAIResponse)(component));}dispatch((0,_misc.setError)(component,null));});appbaseRef.setHeaders(_extends({},headers));if(isSuggestionsQuery&&searchComponentID){dispatch(loadPopularSuggestions(searchComponentID));}appbaseRef.reactiveSearch(query,settings,settings.queryParams).then(function(res){(0,_utils.handleResponse)({res:res,orderOfQueries:orderOfQueries,appendToHits:appendToHits,appendToAggs:appendToAggs,query:query,queryId:queryId},getState,dispatch);}).catch(function(err){(0,_utils.handleError)({orderOfQueries:orderOfQueries,error:err,queryId:queryId},getState,dispatch);});};}var requestStack=[];function executeQuery(componentId){var executeWatchList=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var mustExecuteMapQuery=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var componentType=arguments[3];var metaOptions=arguments[4];var requestId=arguments[5];return function(dispatch,getState){var _getState3=getState(),queryLog=_getState3.queryLog,config=_getState3.config,mapData=_getState3.mapData,watchMan=_getState3.watchMan,queryListener=_getState3.queryListener,props=_getState3.props,internalValues=_getState3.internalValues,lock=_getState3.lock,dependencyTree=_getState3.dependencyTree,queryList=_getState3.queryList,queryOptions=_getState3.queryOptions;var lockTime=config.initialQueriesSyncTime||100;var initialTimestamp=config.initialTimestamp;var queryId=requestId||new Date().getTime();if(config.queryLockConfig instanceof Object){lockTime=config.queryLockConfig.lockTime;initialTimestamp=config.queryLockConfig.initialTimestamp;}var componentList=[componentId];var finalQuery=[];var appbaseQuery={};var orderOfQueries=[];if(executeWatchList){var watchList=watchMan[componentId]||[];componentList=[].concat(_toConsumableArray(componentList),_toConsumableArray(watchList));}componentList.forEach(function(component){var _buildQuery=(0,_helper.buildQuery)(component,dependencyTree,queryList,queryOptions),queryObj=_buildQuery.queryObj,options=_buildQuery.options;if(!queryObj&&!options){return;}var value=void 0;var isInternalComponent=componentId.endsWith('__internal');var mainComponentProps=props[componentId];if(isInternalComponent&&mainComponentProps&&(0,_transform.isSearchComponent)(mainComponentProps.componentType)){value=internalValues[componentId]&&internalValues[componentId].value;}var query=(0,_transform.getRSQuery)(component,(0,_transform.extractPropsFromState)(getState(),component,_extends({},value?{value:value}:null,metaOptions?_extends({from:metaOptions.from},value&&metaOptions.enableAI===true?{enableAI:true,type:'search'}:{}):null)));if(query&&!!Object.keys(query).length){var currentQuery=query;var oldQuery=queryLog[component];var componentProps=props[component];var dependentQueries=(0,_transform.getDependentQueries)(getState(),component,orderOfQueries);var queryToLog=_extends(_defineProperty({},component,currentQuery),Object.keys(dependentQueries).reduce(function(acc,q){return _extends({},acc,_defineProperty({},q,_extends({},dependentQueries[q],{execute:false},dependentQueries[q].type===_constants.queryTypes.suggestion?{type:'search'}:{})));},{}));var queryType=_transform.componentToTypeMap[componentProps&&componentProps.componentType];if([_constants.queryTypes.range,_constants.queryTypes.term].includes(queryType)){var _value=currentQuery.value,rest=_objectWithoutProperties(currentQuery,['value']);queryToLog=_extends(_defineProperty({},component,rest),Object.keys(dependentQueries).reduce(function(acc,q){return _extends({},acc,_defineProperty({},q,_extends({},dependentQueries[q],{execute:false},dependentQueries[q].type===_constants.queryTypes.suggestion?{type:'search'}:{})));},{}));}if(mustExecuteMapQuery||!(0,_helper.compareQueries)(queryToLog,oldQuery,false)){orderOfQueries=[].concat(_toConsumableArray(orderOfQueries),[component]);var isMapComponent=Object.keys(mapData).includes(component);if(isMapComponent){dispatch((0,_misc.setLastUsedAppbaseQuery)(_defineProperty({},component,{queryId:queryId})));}dispatch((0,_misc.logQuery)(component,queryToLog));if(isMapComponent&&mapData[component].query){var existingQuery=currentQuery.query;currentQuery.query={bool:{must:[existingQuery,mapData[component].query]}};if(!mapData[component].persistMapQuery){dispatch((0,_maps.updateMapData)(componentId,null,false));}var _getState4=getState(),combinedLog=_getState4.combinedLog;if((0,_helper.compareQueries)(combinedLog[component],currentQuery))return;dispatch((0,_misc.logCombinedQuery)(component,currentQuery));}(0,_utils.executeQueryListener)(queryListener[component],oldQuery,currentQuery);if(query){appbaseQuery=_extends({},appbaseQuery,_defineProperty({},component,query),(0,_transform.getDependentQueries)(getState(),component,orderOfQueries));}if(isMapComponent){var internalComponent=(0,_transform2.getInternalComponentID)(component);var internalQuery=(0,_transform.getRSQuery)(internalComponent,(0,_transform.extractPropsFromState)(getState(),internalComponent,metaOptions?{from:metaOptions.from}:null));if(internalQuery){appbaseQuery[internalComponent]=_extends({},internalQuery,{execute:false});}}}}});finalQuery=Object.keys(appbaseQuery).map(function(component){return appbaseQuery[component];});if(finalQuery.length){var suggestionsComponents=[_constants.componentTypes.dataSearch,_constants.componentTypes.categorySearch];var isInternalComponent=componentId.endsWith('__internal');var isSuggestionsQuery=isInternalComponent&&suggestionsComponents.indexOf(componentType)!==-1;var currentTime=new Date().getTime();if(currentTime-initialTimestamp<lockTime){if(!lock||config.queryLockConfig){setTimeout(function(){var finalOrderOfQueries=[];var finalIsSuggestionsQuery=false;var finalSearchComponentID='';var orderOfQueriesMap={};var processedQueriesMap={};var queryExecutionMap={};requestStack.forEach(function(request){if(!finalIsSuggestionsQuery){finalIsSuggestionsQuery=request.isSuggestionsQuery;}if(!finalSearchComponentID){finalSearchComponentID=request.searchComponentID;}if(Array.isArray(request.query)){request.query.forEach(function(query){if(query.execute){queryExecutionMap[query.id]=query.execute;}var newQuery=query;if(queryExecutionMap[query.id]){newQuery.execute=true;}if(processedQueriesMap[query.id]&&processedQueriesMap[query.id].type===_constants.queryTypes.suggestion&&newQuery.type!==_constants.queryTypes.suggestion){processedQueriesMap[query.id+'__suggestion_type']=_extends({},processedQueriesMap[query.id]);processedQueriesMap[query.id]=_extends({},newQuery,{execute:false});return;}processedQueriesMap[query.id]=newQuery;});}if(Array.isArray(request.orderOfQueries)){request.orderOfQueries.forEach(function(query){if(!orderOfQueriesMap[query.id]){finalOrderOfQueries=[query].concat(_toConsumableArray(finalOrderOfQueries));}else{orderOfQueriesMap[query.id]=true;}});}});var finalCombinedQuery=Object.values(processedQueriesMap);if(finalCombinedQuery.length){dispatch(appbaseSearch({query:finalCombinedQuery,orderOfQueries:finalOrderOfQueries,isSuggestionsQuery:finalIsSuggestionsQuery,searchComponentID:finalSearchComponentID}));}requestStack=[];dispatch((0,_utils.updateStoreConfig)({queryLockConfig:undefined}));},lockTime);}dispatch((0,_utils.updateStoreConfig)({lock:true}));requestStack.push({query:finalQuery,orderOfQueries:orderOfQueries,isSuggestionsQuery:isSuggestionsQuery,searchComponentID:componentId});}else{dispatch(appbaseSearch({queryId:queryId,query:finalQuery,orderOfQueries:orderOfQueries,isSuggestionsQuery:isSuggestionsQuery,searchComponentID:componentId}));}}};}function setQueryOptions(component,queryOptions){var execute=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return function(dispatch){dispatch((0,_misc.updateQueryOptions)(component,queryOptions));if(execute){dispatch(executeQuery(component,true));}};}function updateQuery(_ref2){var componentId=_ref2.componentId,query=_ref2.query,value=_ref2.value,_ref2$label=_ref2.label,label=_ref2$label===undefined?null:_ref2$label,_ref2$showFilter=_ref2.showFilter,showFilter=_ref2$showFilter===undefined?true:_ref2$showFilter,_ref2$URLParams=_ref2.URLParams,URLParams=_ref2$URLParams===undefined?false:_ref2$URLParams,_ref2$componentType=_ref2.componentType,componentType=_ref2$componentType===undefined?null:_ref2$componentType,_ref2$category=_ref2.category,category=_ref2$category===undefined?null:_ref2$category,_ref2$meta=_ref2.meta,meta=_ref2$meta===undefined?{}:_ref2$meta;var execute=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var shouldSetInternalValue=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return function(dispatch){var queryToDispatch=query;if(query&&query.query){queryToDispatch=query.query;}if(!componentId.endsWith('__internal')){dispatch((0,_value2.setValue)(componentId,value,label,showFilter,URLParams,componentType,category,meta));if(shouldSetInternalValue){if(componentType===_constants.componentTypes.dynamicRangeSlider){dispatch((0,_value2.setInternalValue)((0,_transform.getHistogramComponentID)(componentId),value,componentType,category,meta));}else{dispatch((0,_value2.setInternalValue)(componentId+'__internal',value,componentType,category,meta));}}}else{dispatch((0,_value2.setInternalValue)(componentId,value,componentType,category,meta));}dispatch((0,_misc.setQuery)(componentId,queryToDispatch));if(execute){dispatch(executeQuery(componentId,true,false,componentType,componentType===_constants.componentTypes.searchBox&&meta&&typeof meta.enableAI==='boolean'?{enableAI:meta.enableAI}:undefined));}};}function loadMore(component,newOptions){var appendToHits=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var appendToAggs=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;return function(dispatch,getState){var store=getState();var _buildQuery2=(0,_helper.buildQuery)(component,store.dependencyTree,store.queryList,store.queryOptions),queryObj=_buildQuery2.queryObj,options=_buildQuery2.options;var queryLog=store.queryLog;if(!options)options={};options=_extends({},options,newOptions);if(!queryObj||queryObj&&!Object.keys(queryObj).length){queryObj={match_all:{}};}var appbaseQuery={};var componentProps=store.props[component]||{};var compositeAggregationField=componentProps.aggregationField;var queryType=_transform.componentToTypeMap[componentProps.componentType];if(queryType===_constants.queryTypes.term){compositeAggregationField=componentProps.dataField;}var query=(0,_transform.getRSQuery)(component,(0,_transform.extractPropsFromState)(store,component,{from:options.from,after:store.aggregations[component]&&store.aggregations[component][compositeAggregationField]&&store.aggregations[component][compositeAggregationField].after_key||undefined}));appbaseQuery=_extends(_defineProperty({},component,query),(0,_transform.getDependentQueries)(getState(),component,[]));if((0,_helper.compareQueries)(queryLog[component],appbaseQuery))return;dispatch((0,_misc.logQuery)(component,appbaseQuery));var finalQuery=Object.keys(appbaseQuery).map(function(c){return appbaseQuery[c];});dispatch(appbaseSearch({query:finalQuery,orderOfQueries:[component],appendToHits:appendToHits,appendToAggs:appendToAggs}));};}function loadDataToExport(componentId){var deepPaginationCursor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var totalResults=arguments[2];var data=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[];return function(dispatch,getState){var _getState5=getState(),appbaseRef=_getState5.appbaseRef,lastUsedAppbaseQuery=_getState5.lastUsedAppbaseQuery;var queryFromStore=lastUsedAppbaseQuery[componentId];if(queryFromStore){var query=queryFromStore.map(function(queryItem){if(queryItem.id===componentId){var finalQueryItem=_extends({},queryItem,{deepPaginationConfig:{cursor:deepPaginationCursor},deepPagination:true,size:totalResults<1000?totalResults:1000,sortField:'_id',sortBy:'asc'});delete finalQueryItem.from;return finalQueryItem;}return queryItem;});if(totalResults&&Array.isArray(data)&&totalResults<=data.length){return data;}return appbaseRef.reactiveSearchv3(query).then(function(res){var newDataChunk=res[componentId].hits.hits;if(!Array.isArray(newDataChunk)||newDataChunk.length===0){return data;}return dispatch(loadDataToExport(componentId,newDataChunk[newDataChunk.length-1]._id,res[componentId].hits.total.value,[].concat(_toConsumableArray(data),_toConsumableArray(newDataChunk))));}).catch(function(err){console.error('Error fetching data to export! ',err);});}return console.error('Error fetching data to export!');};}function fetchAIResponse(AIAnswerKey,componentId,question){var meta=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};return function(dispatch,getState){var isPostRequest=!!question;dispatch((0,_misc.setAIResponseLoading)(componentId,true));var _getState6=getState(),_getState6$config=_getState6.config,url=_getState6$config.url,configCredentials=_getState6$config.credentials;var urlObj=new URL(url);var credentials=configCredentials;if(urlObj.username&&urlObj.password){credentials=urlObj.username+':'+urlObj.password;urlObj.username='';urlObj.password='';}var fetchUrl=urlObj.toString()+'_ai/'+AIAnswerKey;var headers=new Headers();if(credentials){var encodedCredentials=btoa(credentials);headers.append('Authorization','Basic '+encodedCredentials);}var method=isPostRequest?'POST':'GET';var body=void 0;var localCache=((0,_helper.getObjectFromLocalStorage)(_constants.AI_LOCAL_CACHE_KEY)||{})[componentId];if(isPostRequest&&question){body=JSON.stringify({question:question});}fetch(fetchUrl,{headers:headers,method:method,body:body}).then(function(res){return res.json();}).then(function(parsedRes){if(parsedRes.response&&parsedRes.response.error){dispatch((0,_misc.setAIResponseError)(componentId,parsedRes.response.error,{sessionId:AIAnswerKey}));}else if(parsedRes.error){dispatch((0,_misc.setAIResponseError)(componentId,parsedRes.error,{sessionId:AIAnswerKey}));}else{var finalResponse=_extends({},parsedRes);if(finalResponse.answer){finalResponse.answer.role=_constants.AI_ROLES.ASSISTANT;}dispatch((0,_misc.setAIResponse)(componentId,{meta:meta,sessionId:AIAnswerKey,messages:[].concat(_toConsumableArray(isPostRequest?localCache.messages:[]),_toConsumableArray(finalResponse.question?[{content:finalResponse.question,role:_constants.AI_ROLES.USER}]:[]),_toConsumableArray(finalResponse.answer?[{content:finalResponse.answer.text,role:_constants.AI_ROLES.ASSISTANT}]:[])),response:_extends({},finalResponse)}));}}).catch(function(e){dispatch((0,_misc.setAIResponseError)(componentId,e,{sessionId:AIAnswerKey}));});};} |
@@ -1,1 +0,1 @@ | ||
Object.defineProperty(exports,"__esModule",{value:true});exports.hexToRGBA=exports.getObjectFromLocalStorage=exports.setObjectInLocalStorage=exports.transformRequestUsingEndpoint=exports.flatten=exports.saveDataAsFile=exports.transformTreeListLocalStateIntoQueryComptaibleFormat=exports.transformRawTreeListData=exports.recLookup=exports.hasCustomRenderer=exports.getComponent=exports.isFunction=exports.getCalendarIntervalErrorMessage=exports.queryFormatMillisecondsMap=exports.featuredSuggestionsActionTypes=exports.suggestionTypes=exports.getTopSuggestions=exports.withClickIds=exports.getCompositeAggsQuery=exports.getAggsQuery=exports.extractQueryFromDefaultQuery=exports.updateInternalQuery=exports.getSearchState=exports.componentTypeToDefaultValue=exports.extractQueryFromCustomQuery=exports.getOptionsForCustomQuery=exports.getOptionsFromQuery=exports.parseHits=exports.handleA11yAction=exports.getInnerKey=exports.getClassName=exports.checkSomePropChange=exports.checkPropChange=exports.updateDefaultQuery=exports.updateCustomQuery=undefined;var _componentTypeToDefau;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.isEqual=isEqual;exports.compareQueries=compareQueries;exports.debounce=debounce;exports.getQueryOptions=getQueryOptions;exports.buildQuery=buildQuery;exports.pushToAndClause=pushToAndClause;exports.checkValueChange=checkValueChange;exports.getAggsOrder=getAggsOrder;exports.formatDate=formatDate;exports.unwrapToNativeDate=unwrapToNativeDate;exports.getResultStats=getResultStats;exports.extractFieldsFromSource=extractFieldsFromSource;exports.normalizeDataField=normalizeDataField;exports.handleOnSuggestions=handleOnSuggestions;exports.isValidDateRangeQueryFormat=isValidDateRangeQueryFormat;exports.setDeep=setDeep;var _dateFormats=require('./dateFormats');var _dateFormats2=_interopRequireDefault(_dateFormats);var _suggestions=require('./suggestions');var _suggestions2=_interopRequireDefault(_suggestions);var _constants=require('./constants');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var updateCustomQuery=exports.updateCustomQuery=function updateCustomQuery(componentId,props,value){if(props.customQuery&&typeof props.customQuery==='function'){props.setCustomQuery(componentId,props.customQuery(value,props));}};var updateDefaultQuery=exports.updateDefaultQuery=function updateDefaultQuery(componentId,props,value){if(props.defaultQuery&&typeof props.defaultQuery==='function'){props.setDefaultQuery(componentId,props.defaultQuery(value,props));}};function isEqual(x,y){if(x===y)return true;if(!(x instanceof Object)||!(y instanceof Object))return false;if(x.constructor!==y.constructor)return false;for(var p in x){if(!x.hasOwnProperty(p))continue;if(!y.hasOwnProperty(p))return false;if(x[p]===y[p])continue;if(typeof x[p]!=='object')return false;if(!isEqual(x[p],y[p]))return false;}for(var _p in y){if(y.hasOwnProperty(_p)&&!x.hasOwnProperty(_p))return false;}return true;}function compareQueries(x,y){try{return isEqual(JSON.parse(JSON.stringify(x)),JSON.parse(JSON.stringify(y)));}catch(e){return false;}}function debounce(callback,wait){var context=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this;if(!wait){return callback;}var timeout=null;var callbackArgs=null;var later=function later(){return callback.apply(context,callbackArgs);};return function debouncedFunction(){callbackArgs=arguments;clearTimeout(timeout);timeout=setTimeout(later,wait);};}function getQueryOptions(props){var options={};if(props.size!==undefined){options.size=props.size;}if(props.includeFields||props.excludeFields){var source={};if(props.includeFields){source.includes=props.includeFields;}if(props.excludeFields){source.excludes=props.excludeFields;}options._source=source;}return options;}function getOperation(conjunction){if(conjunction==='and'){return'must';}if(conjunction==='or'){return'should';}return'must_not';}function createBoolQuery(operation,query){var resultQuery=null;if(Array.isArray(query)&&query.length||!Array.isArray(query)&&query){resultQuery={bool:_defineProperty({},operation,query)};}if(operation==='should'&&resultQuery){resultQuery={bool:_extends({},resultQuery.bool,{minimum_should_match:1})};}return resultQuery;}function getQuery(react,queryList){var query=[];Object.keys(react).forEach(function(conjunction){if(Array.isArray(react[conjunction])){var operation=getOperation(conjunction);var queryArr=react[conjunction].map(function(comp){if(typeof comp!=='string'){return getQuery(comp,queryList);}else if(comp in queryList){if(queryList[comp]&&Object.keys(queryList[comp]).length){return queryList[comp];}}return null;}).filter(function(item){return!!item;});var boolQuery=createBoolQuery(operation,queryArr);if(boolQuery&&Object.keys(boolQuery).length){query=[].concat(_toConsumableArray(query),[boolQuery]);}}else if(typeof react[conjunction]==='string'){var _operation=getOperation(conjunction);var _boolQuery=createBoolQuery(_operation,queryList[react[conjunction]]);if(_boolQuery&&Object.keys(_boolQuery).length){query=[].concat(_toConsumableArray(query),[_boolQuery]);}}else if(typeof react[conjunction]==='object'&&react[conjunction]!==null){var _boolQuery2=getQuery(react[conjunction],queryList);if(_boolQuery2&&Object.keys(_boolQuery2).length){query=[].concat(_toConsumableArray(query),[_boolQuery2]);}}});if(Array.isArray(query)&&query.length){return{bool:{must:query}};}if(query&&Object.keys(query).length){return query;}return null;}function getExternalQueryOptions(react,options,component){var queryOptions={};Object.keys(react).forEach(function(conjunction){if(Array.isArray(react[conjunction])){react[conjunction].forEach(function(comp){if(options[comp]){queryOptions=_extends({},queryOptions,options[comp]);}});}else if(typeof react[conjunction]==='string'){if(options[react[conjunction]]){queryOptions=_extends({},queryOptions,options[react[conjunction]]);}}else if(typeof react[conjunction]==='object'&&react[conjunction]!==null&&!Array.isArray(react[conjunction])){queryOptions=_extends({},queryOptions,getExternalQueryOptions(react[conjunction],options));}});if(options[component]){queryOptions=_extends({},queryOptions,options[component]);}return queryOptions;}function buildQuery(component,dependencyTree,queryList,queryOptions){var queryObj=null;var options=null;if(component in dependencyTree){queryObj=getQuery(dependencyTree[component],queryList);options=getExternalQueryOptions(dependencyTree[component],queryOptions,component);}return{queryObj:queryObj,options:options};}function pushToAndClause(reactProp,component){var react=_extends({},reactProp);if(react.and){if(Array.isArray(react.and)){react.and=[].concat(_toConsumableArray(react.and),[component]);return react;}else if(typeof react.and==='string'){react.and=[react.and,component];return react;}react.and=pushToAndClause(react.and,component);return react;}return _extends({},react,{and:component});}function checkValueChange(componentId,value,beforeValueChange,performUpdate){var selectedValue=value;if(Array.isArray(value)&&!value.length){selectedValue=null;}var handleError=function handleError(e){console.warn(componentId+' - beforeValueChange rejected the promise with ',e);};if(beforeValueChange){try{var promise=beforeValueChange(selectedValue);if(promise instanceof Promise){promise.then(performUpdate).catch(handleError);}else{performUpdate();}}catch(e){handleError(e);}}else{performUpdate();}}function getAggsOrder(sortBy){if(sortBy==='count'){return{_count:'desc'};}return{_key:sortBy};}var checkPropChange=exports.checkPropChange=function checkPropChange(prevProp,nextProp,callback){if(!isEqual(prevProp,nextProp)){callback();return true;}return false;};var checkSomePropChange=exports.checkSomePropChange=function checkSomePropChange(){var prevProps=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var nextProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var propsList=arguments[2];var callback=arguments[3];propsList.some(function(prop){return checkPropChange(prevProps[prop],nextProps[prop],callback);});};var getClassName=exports.getClassName=function getClassName(classMap,component){return classMap&&classMap[component]||'';};var getInnerKey=exports.getInnerKey=function getInnerKey(obj,key){return obj&&obj[key]||{};};var handleA11yAction=exports.handleA11yAction=function handleA11yAction(e,callback){if(e.key==='Enter'||e.key===' '){e.preventDefault();callback();}};var highlightResults=function highlightResults(result){var data=_extends({},result);if(data.highlight){Object.keys(data.highlight).forEach(function(highlightItem){var highlightValue=data.highlight[highlightItem][0];data._source=_extends({},data._source,_defineProperty({},highlightItem,highlightValue));});}return data;};var parseHits=exports.parseHits=function parseHits(hits){var showHighlighted=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var results=null;if(hits){results=[].concat(_toConsumableArray(hits)).map(function(item){var data=_extends({},item);if(showHighlighted)data=highlightResults(item);var result=Object.keys(data).filter(function(key){return key!=='_source';}).reduce(function(obj,key){obj[key]=data[key];return obj;},_extends({highlight:data.highlight||{}},data._source));return result;});}return results;};function formatDate(date,props){if(props.parseDate){return props.parseDate(date,props);}switch(props.queryFormat){case'epoch_millis':return date.valueOf();case'epoch_second':return Math.floor(date.valueOf()/1000);default:{if(_dateFormats2.default[props.queryFormat]){return date.format(_dateFormats2.default[props.queryFormat]);}return date.valueOf();}}}function unwrapToNativeDate(wrappedDateInstance){if(wrappedDateInstance){return new Date(wrappedDateInstance.valueOf());}return wrappedDateInstance;}var getOptionsFromQuery=function getOptionsFromQuery(){var customQuery=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(customQuery){var query=customQuery.query,rest=_objectWithoutProperties(customQuery,['query']);return Object.keys(rest).length?rest:null;}return null;};exports.getOptionsFromQuery=getOptionsFromQuery;var getOptionsForCustomQuery=function getOptionsForCustomQuery(){var customQuery=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(customQuery){var query=customQuery.query,id=customQuery.id,params=customQuery.params,rest=_objectWithoutProperties(customQuery,['query','id','params']);return Object.keys(rest).length?rest:null;}return null;};exports.getOptionsForCustomQuery=getOptionsForCustomQuery;var extractQueryFromCustomQuery=exports.extractQueryFromCustomQuery=function extractQueryFromCustomQuery(customQuery){if(customQuery){if(customQuery.id){return{id:customQuery.id,params:customQuery.params};}return customQuery.query;}return null;};function computeResultStats(){var hits=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var searchState=arguments[1];var promotedResults=arguments[2];Object.keys(hits).forEach(function(componentId){var _ref=hits[componentId]||{},hidden=_ref.hidden,total=_ref.total,time=_ref.time;searchState[componentId]=_extends({},searchState[componentId],{resultStats:_extends({},searchState[componentId].resultStats,{numberOfResults:total,time:time,promoted:promotedResults[componentId]&&promotedResults[componentId].length,hidden:hidden||0})});});}var componentTypeToDefaultValue=exports.componentTypeToDefaultValue=(_componentTypeToDefau={},_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDataList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDropdownList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDataList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDropdownList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.tagCloud,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.toggleButton,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDropdownRange,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDropdownRange,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleRange,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiRange,[]),_componentTypeToDefau);var getSearchState=exports.getSearchState=function getSearchState(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var forHeaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var selectedValues=state.selectedValues,queryLog=state.queryLog,dependencyTree=state.dependencyTree,props=state.props,hits=state.hits,aggregations=state.aggregations,isLoading=state.isLoading,error=state.error,promotedResults=state.promotedResults,settings=state.settings,customData=state.customData,rawData=state.rawData;var searchState={};var populateState=function populateState(){var obj=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var key=arguments[1];return Object.keys(obj).forEach(function(componentId){searchState[componentId]=_extends({},searchState[componentId],key?_defineProperty({},key,obj[componentId]):obj[componentId]);});};populateState(props);Object.keys(selectedValues||{}).forEach(function(componentId){var componentState=searchState[componentId];var selectedValue=selectedValues[componentId];var componentProps=props[componentId];var componentType=componentProps?componentProps.componentType:null;if(selectedValue){var s=_extends({},componentState,_extends({title:selectedValue.label,componentType:selectedValue.componentType,value:selectedValue.value||componentTypeToDefaultValue[componentType]},selectedValue.category&&{category:selectedValue.category},{URLParams:selectedValue.URLParams}));if(Object.keys(s).length){searchState[componentId]=s;}}});if(!forHeaders){populateState(queryLog);populateState(hits,'hits');populateState(aggregations,'aggregations');populateState(isLoading,'isLoading');populateState(error,'error');populateState(promotedResults,'promotedData');populateState(settings,'settings');populateState(customData,'customData');populateState(rawData,'rawData');computeResultStats(hits,searchState,promotedResults);}populateState(dependencyTree,'react');return searchState;};var updateInternalQuery=exports.updateInternalQuery=function updateInternalQuery(componentId,queryOptions,value,props,defaultQueryToExecute,queryParams){var defaultQuery=props.defaultQuery;var defaultQueryOptions=void 0;var query=defaultQueryToExecute;if(defaultQuery){var queryTobeSet=defaultQuery(value,props);var _ref3=queryTobeSet||{};query=_ref3.query;defaultQueryOptions=getOptionsFromQuery(queryTobeSet);updateDefaultQuery(componentId,props,value);}if(query){props.setQueryOptions(componentId,_extends({},defaultQueryOptions,queryOptions||defaultQueryToExecute));props.updateQuery(_extends({componentId:componentId,query:query,value:value},queryParams));}else{props.setQueryOptions(componentId,_extends({},defaultQueryOptions,queryOptions||defaultQueryToExecute));}};var extractQueryFromDefaultQuery=function extractQueryFromDefaultQuery(props,value){var queryToBeReturned={};var defaultQuery=props.defaultQuery;if(defaultQuery){var evaluateQuery=defaultQuery(value,props);if(evaluateQuery){var query=evaluateQuery.query,options=_objectWithoutProperties(evaluateQuery,['query']);if(options){queryToBeReturned=options;}}}return queryToBeReturned;};exports.extractQueryFromDefaultQuery=extractQueryFromDefaultQuery;var getAggsQuery=exports.getAggsQuery=function getAggsQuery(value,query,props){var clonedQuery=query;var dataField=props.dataField,size=props.size,sortBy=props.sortBy,showMissing=props.showMissing,missingLabel=props.missingLabel,aggregationSize=props.aggregationSize;clonedQuery.size=0;if(typeof dataField==='string'){clonedQuery.aggs=_defineProperty({},dataField,{terms:_extends({field:dataField,size:size,aggregationSize:aggregationSize,order:getAggsOrder(sortBy||'count')},showMissing?{missing:missingLabel}:{})});}else{var aggs=void 0;[].concat(_toConsumableArray(dataField)).reverse().forEach(function(dataFieldItem){aggs=_defineProperty({},dataFieldItem,{terms:_extends({field:dataFieldItem,size:size,aggregationSize:aggregationSize,order:getAggsOrder(sortBy||'count')},showMissing?{missing:missingLabel}:{}),aggs:aggs});});clonedQuery.aggs=aggs;}if(props.nestedField){clonedQuery.aggs={reactivesearch_nested:{nested:{path:props.nestedField},aggs:clonedQuery.aggs}};}return _extends({},clonedQuery,extractQueryFromDefaultQuery(props,value));};var getCompositeAggsQuery=exports.getCompositeAggsQuery=function getCompositeAggsQuery(){var _ref4=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref4$query=_ref4.query,query=_ref4$query===undefined?{}:_ref4$query,props=_ref4.props,_ref4$after=_ref4.after,after=_ref4$after===undefined?null:_ref4$after,_ref4$showTopHits=_ref4.showTopHits,showTopHits=_ref4$showTopHits===undefined?false:_ref4$showTopHits,value=_ref4.value;var clonedQuery=query;var dataField=props.dataField,size=props.size,sortBy=props.sortBy,showMissing=props.showMissing,aggregationField=props.aggregationField;var finalField=aggregationField||dataField;var order=sortBy==='count'?{}:{order:sortBy};clonedQuery.aggs=_defineProperty({},finalField,_extends({composite:_extends({sources:[_defineProperty({},finalField,{terms:_extends({field:finalField},order,showMissing?{missing_bucket:true}:{})})],size:size},after)},showTopHits?{aggs:_defineProperty({},finalField,{top_hits:{size:1}})}:{}));clonedQuery.size=0;if(props.nestedField){clonedQuery.aggs={reactivesearch_nested:{nested:{path:props.nestedField},aggs:clonedQuery.aggs}};}return _extends({},clonedQuery,extractQueryFromDefaultQuery(props,value));};var withClickIds=exports.withClickIds=function withClickIds(){var results=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];return results.map(function(result,index){return _extends({},result,{_click_id:index});});};function getResultStats(props){var total=props.total,size=props.size,time=props.time,hidden=props.hidden,promotedResults=props.promotedResults;return _extends({numberOfResults:total},size>0?{numberOfPages:Math.ceil(total/size)}:null,{time:time||0,hidden:hidden,promoted:promotedResults?promotedResults.length:0});}function extractFieldsFromSource(esSource){function getFields(){var source=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var prefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';return Object.keys(source).reduce(function(){var acc=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var k=arguments[1];var key=prefix?prefix+'.'+k:k;if(!Number.isNaN(parseInt(k,10))){key=prefix||k;}if(source[k]&&typeof source[k]==='object'){return _extends({},acc,getFields(source[k],key));}return _extends({},acc,_defineProperty({},key,true));},[]);}var fields=getFields(esSource);return Object.keys(fields);}function normalizeDataField(dataField){var fieldWeights=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];if(typeof dataField==='string'){return[{field:dataField,weight:fieldWeights.length?fieldWeights[0]:undefined}];}if(Array.isArray(dataField)){return dataField.map(function(field,index){var normalizedField={};if(typeof field==='string'){normalizedField.field=field;if(fieldWeights.length>index){normalizedField.weight=fieldWeights[index];}}else if(typeof field==='object'&&field&&field.field){normalizedField.field=field.field;normalizedField.weight=field.weight;}return normalizedField;});}if(typeof dataField==='object'&&dataField){return[{field:dataField.field,weight:dataField.weight}];}return[];}function handleOnSuggestions(results,currentValue,props){var parseSuggestion=props.parseSuggestion,promotedResults=props.promotedResults,enablePredictiveSuggestions=props.enablePredictiveSuggestions;var fields=[];if(props.dataField){fields=normalizeDataField(props.dataField).map(function(f){return f.field;});}else if(results&&Array.isArray(results)&&results.length>0&&results[0]&&results[0]._source){fields=extractFieldsFromSource(results[0]._source);}var newResults=parseHits(results,false);var parsedPromotedResults=parseHits(promotedResults,false);if(parsedPromotedResults&&parsedPromotedResults.length){var ids=parsedPromotedResults.map(function(item){return item._id;}).filter(Boolean);if(ids){newResults=newResults.filter(function(item){return!ids.includes(item._id);});}newResults=[].concat(_toConsumableArray(parsedPromotedResults),_toConsumableArray(newResults));}var parsedSuggestions=(0,_suggestions2.default)({fields:fields,suggestions:newResults,currentValue:currentValue.toLowerCase(),showDistinctSuggestions:props.showDistinctSuggestions,enablePredictiveSuggestions:enablePredictiveSuggestions,enableSynonyms:props.enableSynonyms});if(parseSuggestion){return parsedSuggestions.map(function(suggestion){return parseSuggestion(suggestion);});}return parsedSuggestions;}var getTopSuggestions=exports.getTopSuggestions=function getTopSuggestions(querySuggestions){var currentValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var showDistinctSuggestions=arguments[2];var parsedSuggestions=parseHits(querySuggestions,false);var finalSuggestions=(0,_suggestions2.default)({fields:['key','key.autosuggest','key.search'],suggestions:parsedSuggestions||[],currentValue:currentValue.toLowerCase(),showDistinctSuggestions:showDistinctSuggestions});return withClickIds(finalSuggestions);};function isValidDateRangeQueryFormat(queryFormat){return Object.keys(_dateFormats2.default).includes(queryFormat);}var suggestionTypes=exports.suggestionTypes={Popular:'popular',Index:'index',Recent:'recent',Promoted:'promoted',Featured:'featured'};var featuredSuggestionsActionTypes=exports.featuredSuggestionsActionTypes={NAVIGATE:'navigate',FUNCTION:'function',SELECT:'select'};var queryFormatMillisecondsMap=exports.queryFormatMillisecondsMap={minute:60000,hour:3600000,day:86400000,week:604800000,month:2629746000,quarter:7889238000,year:31556952000};var getCalendarIntervalErrorMessage=exports.getCalendarIntervalErrorMessage=function getCalendarIntervalErrorMessage(totalRange){var calendarInterval=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'minute';var queryFormatMillisecondsMapKeys=Object.keys(queryFormatMillisecondsMap);var indexOfCurrentCalendarInterval=queryFormatMillisecondsMapKeys.indexOf(calendarInterval);if(indexOfCurrentCalendarInterval===-1){console.error('Invalid calendarInterval Passed');}if(calendarInterval==='year'){return'Try using a shorter range of values.';}for(var index=indexOfCurrentCalendarInterval+1;index<queryFormatMillisecondsMapKeys.length;index+=1){if(totalRange/Object.values(queryFormatMillisecondsMap)[index]<=100){var calendarIntervalKey=queryFormatMillisecondsMapKeys[index];return{errorMessage:'Please pass calendarInterval prop with value greater than or equal to a `'+calendarIntervalKey+'` for a meaningful resolution of histogram.',calculatedCalendarInterval:calendarIntervalKey};}}return{errorMessage:'Try using a shorter range of values.',calculatedCalendarInterval:'year'};};var isFunction=exports.isFunction=function isFunction(element){return typeof element==='function';};var getComponent=exports.getComponent=function getComponent(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var children=props.children,render=props.render;if(isFunction(children)){return children(data);}if(isFunction(render)){return render(data);}return null;};var hasCustomRenderer=exports.hasCustomRenderer=function hasCustomRenderer(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var render=props.render,children=props.children;return isFunction(children)||isFunction(render);};var recLookup=exports.recLookup=function recLookup(obj,path){var separator=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'.';try{var parts=path.split(separator);if(parts.length===1){return obj[parts[0]];}return recLookup(obj[parts[0]],parts.slice(1).join(separator),separator);}catch(e){return false;}};function setDeep(obj,path,value){var setrecursively=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;path.reduce(function(acc,currentItem,level){if(setrecursively&&typeof acc[currentItem]!=='object'&&level!==path.length-1){acc[currentItem]={};return acc[currentItem];}if(level===path.length-1){acc[currentItem]=value;return value;}return typeof acc[currentItem]==='object'?acc[currentItem]:{};},obj);}var transformRawTreeListData=exports.transformRawTreeListData=function transformRawTreeListData(data,dataField){var level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var newState=[];if(data instanceof Object){var aggsKeys=Object.keys(data);aggsKeys.forEach(function(key){if(Array.isArray(data[key].buckets)){data[key].buckets.forEach(function(bucket){newState.push(_extends({key:bucket.key,count:bucket.doc_count,level:level},bucket[dataField[level+1]]instanceof Object?{list:transformRawTreeListData(_defineProperty({},dataField[level+1],bucket[dataField[level+1]]),dataField,level+1)}:{}));});}});}return newState;};var transformTreeListLocalStateIntoQueryComptaibleFormat=exports.transformTreeListLocalStateIntoQueryComptaibleFormat=function transformTreeListLocalStateIntoQueryComptaibleFormat(obj){var currentPath=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var result=[];if(obj instanceof Object){if(Object.keys(obj).length){Object.keys(obj).forEach(function(key){if(obj[key]instanceof Object){result.push.apply(result,_toConsumableArray(transformTreeListLocalStateIntoQueryComptaibleFormat(obj[key],currentPath?currentPath+' > '+key:key)));}if(obj[key]===true){result.push(currentPath?currentPath+' > '+key:key);}});}else if(currentPath){result.push(currentPath);}}return result;};var saveDataAsFile=exports.saveDataAsFile=function saveDataAsFile(){var filename=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'exportedData';var data=arguments[1];var format=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'csv';var dataToWrite=data;var dataType='text/'+format;if(format==='json'){dataToWrite=JSON.stringify(dataToWrite,0,4);}var blob=new Blob([dataToWrite],{type:dataType});var link=document.createElement('a');link.download=filename+'.'+format;link.href=window.URL.createObjectURL(blob);link.dataset.downloadurl=[dataType,link.download,link.href].join(':');var evt=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});link.dispatchEvent(evt);link.remove();};var flatten=exports.flatten=function flatten(data){var result={};function recurse(cur){var prop=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';if(Object(cur)!==cur){result[prop]=cur;}else if(Array.isArray(cur)){result[prop]=JSON.stringify(cur);}else{var isEmpty=true;Object.keys(cur).forEach(function(p){isEmpty=false;recurse(cur[p],prop?prop+'.'+p:p);});if(isEmpty&&prop){result[prop]={};}}}recurse(data);return result;};var transformRequestUsingEndpoint=function transformRequestUsingEndpoint(request,endpointParam){if(endpointParam instanceof Object){var _endpointParam$header=endpointParam.headers,headers=_endpointParam$header===undefined?{}:_endpointParam$header,body=endpointParam.body,rest=_objectWithoutProperties(endpointParam,['headers','body']);var endpointModifiedRequest=_extends({},request,rest,{headers:_extends({},request.headers,headers)},body instanceof Object?{body:JSON.stringify(body)}:{});return endpointModifiedRequest;}return request;};exports.transformRequestUsingEndpoint=transformRequestUsingEndpoint;var setObjectInLocalStorage=exports.setObjectInLocalStorage=function setObjectInLocalStorage(key,value){if(!key||!value){throw new Error('Key and value are required for setObject');}try{var serializedValue=JSON.stringify(value);localStorage.setItem(key,serializedValue);}catch(error){console.error('Error saving object to localStorage:',error);}};var getObjectFromLocalStorage=exports.getObjectFromLocalStorage=function getObjectFromLocalStorage(key){if(!key){throw new Error('Key is required for getObject');}try{var serializedValue=localStorage.getItem(key);if(serializedValue===null){return null;}return JSON.parse(serializedValue);}catch(error){console.error('Error retrieving object from localStorage:',error);return null;}};var isHex=function isHex(color){return /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(color);};var isRgb=function isRgb(color){return /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.test(color);};var isRgba=function isRgba(color){return /^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(0|1|0\.\d{1,2})\)$/.test(color);};var isHsl=function isHsl(color){return /^hsl\(\d{1,3},\s*[\d.]+%,\s*[\d.]+%\)$/.test(color);};var isHsla=function isHsla(color){return /^hsla\(\d{1,3},\s*[\d.]+%,\s*[\d.]+%,\s*(0|1|0\.\d{1,2})\)$/.test(color);};var hexToRGBA=exports.hexToRGBA=function hexToRGBA(colorParam){if(isRgb(colorParam)||isRgba(colorParam)||isHsl(colorParam)||isHsla(colorParam)){return colorParam;}if(!isHex(colorParam)){return null;}var shorthandRegex=/^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i;var color=colorParam.replace(shorthandRegex,function(m,r,g,b,a){return r+r+g+g+b+b+(a?a+a:'');});var result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(color);if(!result){return null;}var r=parseInt(result[1],16);var g=parseInt(result[2],16);var b=parseInt(result[3],16);var a=result[4]?parseInt(result[4],16)/255:1;return'rgba('+r+', '+g+', '+b+', '+a+')';}; | ||
Object.defineProperty(exports,"__esModule",{value:true});exports.hexToRGBA=exports.getObjectFromLocalStorage=exports.setObjectInLocalStorage=exports.transformRequestUsingEndpoint=exports.flatten=exports.saveDataAsFile=exports.transformTreeListLocalStateIntoQueryComptaibleFormat=exports.transformRawTreeListData=exports.recLookup=exports.hasCustomRenderer=exports.getComponent=exports.isFunction=exports.getCalendarIntervalErrorMessage=exports.queryFormatMillisecondsMap=exports.featuredSuggestionsActionTypes=exports.suggestionTypes=exports.getTopSuggestions=exports.withClickIds=exports.getCompositeAggsQuery=exports.getAggsQuery=exports.extractQueryFromDefaultQuery=exports.updateInternalQuery=exports.getSearchState=exports.componentTypeToDefaultValue=exports.extractQueryFromCustomQuery=exports.getOptionsForCustomQuery=exports.getOptionsFromQuery=exports.parseHits=exports.handleA11yAction=exports.getInnerKey=exports.getClassName=exports.checkSomePropChange=exports.checkPropChange=exports.updateDefaultQuery=exports.updateCustomQuery=undefined;var _componentTypeToDefau;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports.isEqual=isEqual;exports.compareQueries=compareQueries;exports.debounce=debounce;exports.getQueryOptions=getQueryOptions;exports.buildQuery=buildQuery;exports.pushToAndClause=pushToAndClause;exports.checkValueChange=checkValueChange;exports.getAggsOrder=getAggsOrder;exports.formatDate=formatDate;exports.unwrapToNativeDate=unwrapToNativeDate;exports.getResultStats=getResultStats;exports.extractFieldsFromSource=extractFieldsFromSource;exports.normalizeDataField=normalizeDataField;exports.handleOnSuggestions=handleOnSuggestions;exports.isValidDateRangeQueryFormat=isValidDateRangeQueryFormat;exports.setDeep=setDeep;exports.getStackTrace=getStackTrace;var _dateFormats=require('./dateFormats');var _dateFormats2=_interopRequireDefault(_dateFormats);var _suggestions=require('./suggestions');var _suggestions2=_interopRequireDefault(_suggestions);var _constants=require('./constants');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i];}return target;}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var updateCustomQuery=exports.updateCustomQuery=function updateCustomQuery(componentId,props,value){if(props.customQuery&&typeof props.customQuery==='function'){props.setCustomQuery(componentId,props.customQuery(value,props));}};var updateDefaultQuery=exports.updateDefaultQuery=function updateDefaultQuery(componentId,props,value){if(props.defaultQuery&&typeof props.defaultQuery==='function'){props.setDefaultQuery(componentId,props.defaultQuery(value,props));}};function isEqual(x,y){if(x===y)return true;if(!(x instanceof Object)||!(y instanceof Object))return false;if(x.constructor!==y.constructor)return false;for(var p in x){if(!x.hasOwnProperty(p))continue;if(!y.hasOwnProperty(p))return false;if(x[p]===y[p])continue;if(typeof x[p]!=='object')return false;if(!isEqual(x[p],y[p]))return false;}for(var _p in y){if(y.hasOwnProperty(_p)&&!x.hasOwnProperty(_p))return false;}return true;}function compareQueries(x,y){try{return isEqual(JSON.parse(JSON.stringify(x)),JSON.parse(JSON.stringify(y)));}catch(e){return false;}}function debounce(callback,wait){var context=arguments.length>2&&arguments[2]!==undefined?arguments[2]:this;if(!wait){return callback;}var timeout=null;var callbackArgs=null;var later=function later(){return callback.apply(context,callbackArgs);};return function debouncedFunction(){callbackArgs=arguments;clearTimeout(timeout);timeout=setTimeout(later,wait);};}function getQueryOptions(props){var options={};if(props.size!==undefined){options.size=props.size;}if(props.includeFields||props.excludeFields){var source={};if(props.includeFields){source.includes=props.includeFields;}if(props.excludeFields){source.excludes=props.excludeFields;}options._source=source;}return options;}function getOperation(conjunction){if(conjunction==='and'){return'must';}if(conjunction==='or'){return'should';}return'must_not';}function createBoolQuery(operation,query){var resultQuery=null;if(Array.isArray(query)&&query.length||!Array.isArray(query)&&query){resultQuery={bool:_defineProperty({},operation,query)};}if(operation==='should'&&resultQuery){resultQuery={bool:_extends({},resultQuery.bool,{minimum_should_match:1})};}return resultQuery;}function getQuery(react,queryList){var query=[];Object.keys(react).forEach(function(conjunction){if(Array.isArray(react[conjunction])){var operation=getOperation(conjunction);var queryArr=react[conjunction].map(function(comp){if(typeof comp!=='string'){return getQuery(comp,queryList);}else if(comp in queryList){if(queryList[comp]&&Object.keys(queryList[comp]).length){return queryList[comp];}}return null;}).filter(function(item){return!!item;});var boolQuery=createBoolQuery(operation,queryArr);if(boolQuery&&Object.keys(boolQuery).length){query=[].concat(_toConsumableArray(query),[boolQuery]);}}else if(typeof react[conjunction]==='string'){var _operation=getOperation(conjunction);var _boolQuery=createBoolQuery(_operation,queryList[react[conjunction]]);if(_boolQuery&&Object.keys(_boolQuery).length){query=[].concat(_toConsumableArray(query),[_boolQuery]);}}else if(typeof react[conjunction]==='object'&&react[conjunction]!==null){var _boolQuery2=getQuery(react[conjunction],queryList);if(_boolQuery2&&Object.keys(_boolQuery2).length){query=[].concat(_toConsumableArray(query),[_boolQuery2]);}}});if(Array.isArray(query)&&query.length){return{bool:{must:query}};}if(query&&Object.keys(query).length){return query;}return null;}function getExternalQueryOptions(react,options,component){var queryOptions={};Object.keys(react).forEach(function(conjunction){if(Array.isArray(react[conjunction])){react[conjunction].forEach(function(comp){if(options[comp]){queryOptions=_extends({},queryOptions,options[comp]);}});}else if(typeof react[conjunction]==='string'){if(options[react[conjunction]]){queryOptions=_extends({},queryOptions,options[react[conjunction]]);}}else if(typeof react[conjunction]==='object'&&react[conjunction]!==null&&!Array.isArray(react[conjunction])){queryOptions=_extends({},queryOptions,getExternalQueryOptions(react[conjunction],options));}});if(options[component]){queryOptions=_extends({},queryOptions,options[component]);}return queryOptions;}function buildQuery(component,dependencyTree,queryList,queryOptions){var queryObj=null;var options=null;if(component in dependencyTree){queryObj=getQuery(dependencyTree[component],queryList);options=getExternalQueryOptions(dependencyTree[component],queryOptions,component);}return{queryObj:queryObj,options:options};}function pushToAndClause(reactProp,component){var react=_extends({},reactProp);if(react.and){if(Array.isArray(react.and)){react.and=[].concat(_toConsumableArray(react.and),[component]);return react;}else if(typeof react.and==='string'){react.and=[react.and,component];return react;}react.and=pushToAndClause(react.and,component);return react;}return _extends({},react,{and:component});}function checkValueChange(componentId,value,beforeValueChange,performUpdate){var selectedValue=value;if(Array.isArray(value)&&!value.length){selectedValue=null;}var handleError=function handleError(e){console.warn(componentId+' - beforeValueChange rejected the promise with ',e);};if(beforeValueChange){try{var promise=beforeValueChange(selectedValue);if(promise instanceof Promise){promise.then(performUpdate).catch(handleError);}else{performUpdate();}}catch(e){handleError(e);}}else{performUpdate();}}function getAggsOrder(sortBy){if(sortBy==='count'){return{_count:'desc'};}return{_key:sortBy};}var checkPropChange=exports.checkPropChange=function checkPropChange(prevProp,nextProp,callback){if(!isEqual(prevProp,nextProp)){callback();return true;}return false;};var checkSomePropChange=exports.checkSomePropChange=function checkSomePropChange(){var prevProps=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var nextProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var propsList=arguments[2];var callback=arguments[3];propsList.some(function(prop){return checkPropChange(prevProps[prop],nextProps[prop],callback);});};var getClassName=exports.getClassName=function getClassName(classMap,component){return classMap&&classMap[component]||'';};var getInnerKey=exports.getInnerKey=function getInnerKey(obj,key){return obj&&obj[key]||{};};var handleA11yAction=exports.handleA11yAction=function handleA11yAction(e,callback){if(e.key==='Enter'||e.key===' '){e.preventDefault();callback();}};var highlightResults=function highlightResults(result){var data=_extends({},result);if(data.highlight){Object.keys(data.highlight).forEach(function(highlightItem){var highlightValue=data.highlight[highlightItem][0];data._source=_extends({},data._source,_defineProperty({},highlightItem,highlightValue));});}return data;};var parseHits=exports.parseHits=function parseHits(hits){var showHighlighted=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var results=null;if(hits){results=[].concat(_toConsumableArray(hits)).map(function(item){var data=_extends({},item);if(showHighlighted)data=highlightResults(item);var result=Object.keys(data).filter(function(key){return key!=='_source';}).reduce(function(obj,key){obj[key]=data[key];return obj;},_extends({highlight:data.highlight||{}},data._source));return result;});}return results;};function formatDate(date,props){if(props.parseDate){return props.parseDate(date,props);}switch(props.queryFormat){case'epoch_millis':return date.valueOf();case'epoch_second':return Math.floor(date.valueOf()/1000);default:{if(_dateFormats2.default[props.queryFormat]){return date.format(_dateFormats2.default[props.queryFormat]);}return date.valueOf();}}}function unwrapToNativeDate(wrappedDateInstance){if(wrappedDateInstance){return new Date(wrappedDateInstance.valueOf());}return wrappedDateInstance;}var getOptionsFromQuery=function getOptionsFromQuery(){var customQuery=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(customQuery){var query=customQuery.query,rest=_objectWithoutProperties(customQuery,['query']);return Object.keys(rest).length?rest:null;}return null;};exports.getOptionsFromQuery=getOptionsFromQuery;var getOptionsForCustomQuery=function getOptionsForCustomQuery(){var customQuery=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(customQuery){var query=customQuery.query,id=customQuery.id,params=customQuery.params,rest=_objectWithoutProperties(customQuery,['query','id','params']);return Object.keys(rest).length?rest:null;}return null;};exports.getOptionsForCustomQuery=getOptionsForCustomQuery;var extractQueryFromCustomQuery=exports.extractQueryFromCustomQuery=function extractQueryFromCustomQuery(customQuery){if(customQuery){if(customQuery.id){return{id:customQuery.id,params:customQuery.params};}return customQuery.query;}return null;};function computeResultStats(){var hits=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var searchState=arguments[1];var promotedResults=arguments[2];Object.keys(hits).forEach(function(componentId){var _ref=hits[componentId]||{},hidden=_ref.hidden,total=_ref.total,time=_ref.time;searchState[componentId]=_extends({},searchState[componentId],{resultStats:_extends({},searchState[componentId].resultStats,{numberOfResults:total,time:time,promoted:promotedResults[componentId]&&promotedResults[componentId].length,hidden:hidden||0})});});}var componentTypeToDefaultValue=exports.componentTypeToDefaultValue=(_componentTypeToDefau={},_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDataList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDropdownList,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDataList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDropdownList,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.tagCloud,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.toggleButton,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleDropdownRange,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiDropdownRange,[]),_defineProperty(_componentTypeToDefau,_constants.componentTypes.singleRange,''),_defineProperty(_componentTypeToDefau,_constants.componentTypes.multiRange,[]),_componentTypeToDefau);var getSearchState=exports.getSearchState=function getSearchState(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var forHeaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var selectedValues=state.selectedValues,queryLog=state.queryLog,dependencyTree=state.dependencyTree,props=state.props,hits=state.hits,aggregations=state.aggregations,isLoading=state.isLoading,error=state.error,promotedResults=state.promotedResults,settings=state.settings,customData=state.customData,rawData=state.rawData;var searchState={};var populateState=function populateState(){var obj=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var key=arguments[1];return Object.keys(obj).forEach(function(componentId){searchState[componentId]=_extends({},searchState[componentId],key?_defineProperty({},key,obj[componentId]):obj[componentId]);});};populateState(props);Object.keys(selectedValues||{}).forEach(function(componentId){var componentState=searchState[componentId];var selectedValue=selectedValues[componentId];var componentProps=props[componentId];var componentType=componentProps?componentProps.componentType:null;if(selectedValue){var s=_extends({},componentState,_extends({title:selectedValue.label,componentType:selectedValue.componentType,value:selectedValue.value||componentTypeToDefaultValue[componentType]},selectedValue.category&&{category:selectedValue.category},{URLParams:selectedValue.URLParams}));if(Object.keys(s).length){searchState[componentId]=s;}}});if(!forHeaders){populateState(queryLog);populateState(hits,'hits');populateState(aggregations,'aggregations');populateState(isLoading,'isLoading');populateState(error,'error');populateState(promotedResults,'promotedData');populateState(settings,'settings');populateState(customData,'customData');populateState(rawData,'rawData');computeResultStats(hits,searchState,promotedResults);}populateState(dependencyTree,'react');return searchState;};var updateInternalQuery=exports.updateInternalQuery=function updateInternalQuery(componentId,queryOptions,value,props,defaultQueryToExecute,queryParams){var defaultQuery=props.defaultQuery;var defaultQueryOptions=void 0;var query=defaultQueryToExecute;if(defaultQuery){var queryTobeSet=defaultQuery(value,props);var _ref3=queryTobeSet||{};query=_ref3.query;defaultQueryOptions=getOptionsFromQuery(queryTobeSet);updateDefaultQuery(componentId,props,value);}if(query){props.setQueryOptions(componentId,_extends({},defaultQueryOptions,queryOptions||defaultQueryToExecute));props.updateQuery(_extends({componentId:componentId,query:query,value:value},queryParams));}else{props.setQueryOptions(componentId,_extends({},defaultQueryOptions,queryOptions||defaultQueryToExecute));}};var extractQueryFromDefaultQuery=function extractQueryFromDefaultQuery(props,value){var queryToBeReturned={};var defaultQuery=props.defaultQuery;if(defaultQuery){var evaluateQuery=defaultQuery(value,props);if(evaluateQuery){var query=evaluateQuery.query,options=_objectWithoutProperties(evaluateQuery,['query']);if(options){queryToBeReturned=options;}}}return queryToBeReturned;};exports.extractQueryFromDefaultQuery=extractQueryFromDefaultQuery;var getAggsQuery=exports.getAggsQuery=function getAggsQuery(value,query,props){var clonedQuery=query;var dataField=props.dataField,size=props.size,sortBy=props.sortBy,showMissing=props.showMissing,missingLabel=props.missingLabel,aggregationSize=props.aggregationSize;clonedQuery.size=0;if(typeof dataField==='string'){clonedQuery.aggs=_defineProperty({},dataField,{terms:_extends({field:dataField,size:size,aggregationSize:aggregationSize,order:getAggsOrder(sortBy||'count')},showMissing?{missing:missingLabel}:{})});}else{var aggs=void 0;[].concat(_toConsumableArray(dataField)).reverse().forEach(function(dataFieldItem){aggs=_defineProperty({},dataFieldItem,{terms:_extends({field:dataFieldItem,size:size,aggregationSize:aggregationSize,order:getAggsOrder(sortBy||'count')},showMissing?{missing:missingLabel}:{}),aggs:aggs});});clonedQuery.aggs=aggs;}if(props.nestedField){clonedQuery.aggs={reactivesearch_nested:{nested:{path:props.nestedField},aggs:clonedQuery.aggs}};}return _extends({},clonedQuery,extractQueryFromDefaultQuery(props,value));};var getCompositeAggsQuery=exports.getCompositeAggsQuery=function getCompositeAggsQuery(){var _ref4=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref4$query=_ref4.query,query=_ref4$query===undefined?{}:_ref4$query,props=_ref4.props,_ref4$after=_ref4.after,after=_ref4$after===undefined?null:_ref4$after,_ref4$showTopHits=_ref4.showTopHits,showTopHits=_ref4$showTopHits===undefined?false:_ref4$showTopHits,value=_ref4.value;var clonedQuery=query;var dataField=props.dataField,size=props.size,sortBy=props.sortBy,showMissing=props.showMissing,aggregationField=props.aggregationField;var finalField=aggregationField||dataField;var order=sortBy==='count'?{}:{order:sortBy};clonedQuery.aggs=_defineProperty({},finalField,_extends({composite:_extends({sources:[_defineProperty({},finalField,{terms:_extends({field:finalField},order,showMissing?{missing_bucket:true}:{})})],size:size},after)},showTopHits?{aggs:_defineProperty({},finalField,{top_hits:{size:1}})}:{}));clonedQuery.size=0;if(props.nestedField){clonedQuery.aggs={reactivesearch_nested:{nested:{path:props.nestedField},aggs:clonedQuery.aggs}};}return _extends({},clonedQuery,extractQueryFromDefaultQuery(props,value));};var withClickIds=exports.withClickIds=function withClickIds(){var results=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];return results.map(function(result,index){return _extends({},result,{_click_id:index});});};function getResultStats(props){var total=props.total,size=props.size,time=props.time,hidden=props.hidden,promotedResults=props.promotedResults;return _extends({numberOfResults:total},size>0?{numberOfPages:Math.ceil(total/size)}:null,{time:time||0,hidden:hidden,promoted:promotedResults?promotedResults.length:0});}function extractFieldsFromSource(esSource){function getFields(){var source=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var prefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';return Object.keys(source).reduce(function(){var acc=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var k=arguments[1];var key=prefix?prefix+'.'+k:k;if(!Number.isNaN(parseInt(k,10))){key=prefix||k;}if(source[k]&&typeof source[k]==='object'){return _extends({},acc,getFields(source[k],key));}return _extends({},acc,_defineProperty({},key,true));},[]);}var fields=getFields(esSource);return Object.keys(fields);}function normalizeDataField(dataField){var fieldWeights=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];if(typeof dataField==='string'){return[{field:dataField,weight:fieldWeights.length?fieldWeights[0]:undefined}];}if(Array.isArray(dataField)){return dataField.map(function(field,index){var normalizedField={};if(typeof field==='string'){normalizedField.field=field;if(fieldWeights.length>index){normalizedField.weight=fieldWeights[index];}}else if(typeof field==='object'&&field&&field.field){normalizedField.field=field.field;normalizedField.weight=field.weight;}return normalizedField;});}if(typeof dataField==='object'&&dataField){return[{field:dataField.field,weight:dataField.weight}];}return[];}function handleOnSuggestions(results,currentValue,props){var parseSuggestion=props.parseSuggestion,promotedResults=props.promotedResults,enablePredictiveSuggestions=props.enablePredictiveSuggestions;var fields=[];if(props.dataField){fields=normalizeDataField(props.dataField).map(function(f){return f.field;});}else if(results&&Array.isArray(results)&&results.length>0&&results[0]&&results[0]._source){fields=extractFieldsFromSource(results[0]._source);}var newResults=parseHits(results,false);var parsedPromotedResults=parseHits(promotedResults,false);if(parsedPromotedResults&&parsedPromotedResults.length){var ids=parsedPromotedResults.map(function(item){return item._id;}).filter(Boolean);if(ids){newResults=newResults.filter(function(item){return!ids.includes(item._id);});}newResults=[].concat(_toConsumableArray(parsedPromotedResults),_toConsumableArray(newResults));}var parsedSuggestions=(0,_suggestions2.default)({fields:fields,suggestions:newResults,currentValue:currentValue.toLowerCase(),showDistinctSuggestions:props.showDistinctSuggestions,enablePredictiveSuggestions:enablePredictiveSuggestions,enableSynonyms:props.enableSynonyms});if(parseSuggestion){return parsedSuggestions.map(function(suggestion){return parseSuggestion(suggestion);});}return parsedSuggestions;}var getTopSuggestions=exports.getTopSuggestions=function getTopSuggestions(querySuggestions){var currentValue=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var showDistinctSuggestions=arguments[2];var parsedSuggestions=parseHits(querySuggestions,false);var finalSuggestions=(0,_suggestions2.default)({fields:['key','key.autosuggest','key.search'],suggestions:parsedSuggestions||[],currentValue:currentValue.toLowerCase(),showDistinctSuggestions:showDistinctSuggestions});return withClickIds(finalSuggestions);};function isValidDateRangeQueryFormat(queryFormat){return Object.keys(_dateFormats2.default).includes(queryFormat);}var suggestionTypes=exports.suggestionTypes={Popular:'popular',Index:'index',Recent:'recent',Promoted:'promoted',Featured:'featured'};var featuredSuggestionsActionTypes=exports.featuredSuggestionsActionTypes={NAVIGATE:'navigate',FUNCTION:'function',SELECT:'select'};var queryFormatMillisecondsMap=exports.queryFormatMillisecondsMap={minute:60000,hour:3600000,day:86400000,week:604800000,month:2629746000,quarter:7889238000,year:31556952000};var getCalendarIntervalErrorMessage=exports.getCalendarIntervalErrorMessage=function getCalendarIntervalErrorMessage(totalRange){var calendarInterval=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'minute';var queryFormatMillisecondsMapKeys=Object.keys(queryFormatMillisecondsMap);var indexOfCurrentCalendarInterval=queryFormatMillisecondsMapKeys.indexOf(calendarInterval);if(indexOfCurrentCalendarInterval===-1){console.error('Invalid calendarInterval Passed');}if(calendarInterval==='year'){return'Try using a shorter range of values.';}for(var index=indexOfCurrentCalendarInterval+1;index<queryFormatMillisecondsMapKeys.length;index+=1){if(totalRange/Object.values(queryFormatMillisecondsMap)[index]<=100){var calendarIntervalKey=queryFormatMillisecondsMapKeys[index];return{errorMessage:'Please pass calendarInterval prop with value greater than or equal to a `'+calendarIntervalKey+'` for a meaningful resolution of histogram.',calculatedCalendarInterval:calendarIntervalKey};}}return{errorMessage:'Try using a shorter range of values.',calculatedCalendarInterval:'year'};};var isFunction=exports.isFunction=function isFunction(element){return typeof element==='function';};var getComponent=exports.getComponent=function getComponent(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var children=props.children,render=props.render;if(isFunction(children)){return children(data);}if(isFunction(render)){return render(data);}return null;};var hasCustomRenderer=exports.hasCustomRenderer=function hasCustomRenderer(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var render=props.render,children=props.children;return isFunction(children)||isFunction(render);};var recLookup=exports.recLookup=function recLookup(obj,path){var separator=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'.';try{var parts=path.split(separator);if(parts.length===1){return obj[parts[0]];}return recLookup(obj[parts[0]],parts.slice(1).join(separator),separator);}catch(e){return false;}};function setDeep(obj,path,value){var setrecursively=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;path.reduce(function(acc,currentItem,level){if(setrecursively&&typeof acc[currentItem]!=='object'&&level!==path.length-1){acc[currentItem]={};return acc[currentItem];}if(level===path.length-1){acc[currentItem]=value;return value;}return typeof acc[currentItem]==='object'?acc[currentItem]:{};},obj);}var transformRawTreeListData=exports.transformRawTreeListData=function transformRawTreeListData(data,dataField){var level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var newState=[];if(data instanceof Object){var aggsKeys=Object.keys(data);aggsKeys.forEach(function(key){if(Array.isArray(data[key].buckets)){data[key].buckets.forEach(function(bucket){newState.push(_extends({key:bucket.key,count:bucket.doc_count,level:level},bucket[dataField[level+1]]instanceof Object?{list:transformRawTreeListData(_defineProperty({},dataField[level+1],bucket[dataField[level+1]]),dataField,level+1)}:{}));});}});}return newState;};var transformTreeListLocalStateIntoQueryComptaibleFormat=exports.transformTreeListLocalStateIntoQueryComptaibleFormat=function transformTreeListLocalStateIntoQueryComptaibleFormat(obj){var currentPath=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var result=[];if(obj instanceof Object){if(Object.keys(obj).length){Object.keys(obj).forEach(function(key){if(obj[key]instanceof Object){result.push.apply(result,_toConsumableArray(transformTreeListLocalStateIntoQueryComptaibleFormat(obj[key],currentPath?currentPath+' > '+key:key)));}if(obj[key]===true){result.push(currentPath?currentPath+' > '+key:key);}});}else if(currentPath){result.push(currentPath);}}return result;};var saveDataAsFile=exports.saveDataAsFile=function saveDataAsFile(){var filename=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'exportedData';var data=arguments[1];var format=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'csv';var dataToWrite=data;var dataType='text/'+format;if(format==='json'){dataToWrite=JSON.stringify(dataToWrite,0,4);}var blob=new Blob([dataToWrite],{type:dataType});var link=document.createElement('a');link.download=filename+'.'+format;link.href=window.URL.createObjectURL(blob);link.dataset.downloadurl=[dataType,link.download,link.href].join(':');var evt=new MouseEvent('click',{view:window,bubbles:true,cancelable:true});link.dispatchEvent(evt);link.remove();};var flatten=exports.flatten=function flatten(data){var result={};function recurse(cur){var prop=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';if(Object(cur)!==cur){result[prop]=cur;}else if(Array.isArray(cur)){result[prop]=JSON.stringify(cur);}else{var isEmpty=true;Object.keys(cur).forEach(function(p){isEmpty=false;recurse(cur[p],prop?prop+'.'+p:p);});if(isEmpty&&prop){result[prop]={};}}}recurse(data);return result;};var transformRequestUsingEndpoint=function transformRequestUsingEndpoint(request,endpointParam){if(endpointParam instanceof Object){var _endpointParam$header=endpointParam.headers,headers=_endpointParam$header===undefined?{}:_endpointParam$header,body=endpointParam.body,rest=_objectWithoutProperties(endpointParam,['headers','body']);var endpointModifiedRequest=_extends({},request,rest,{headers:_extends({},request.headers,headers)},body instanceof Object?{body:JSON.stringify(body)}:{});return endpointModifiedRequest;}return request;};exports.transformRequestUsingEndpoint=transformRequestUsingEndpoint;var setObjectInLocalStorage=exports.setObjectInLocalStorage=function setObjectInLocalStorage(key,value){if(!key||!value){throw new Error('Key and value are required for setObject');}try{var serializedValue=JSON.stringify(value);localStorage.setItem(key,serializedValue);}catch(error){console.error('Error saving object to localStorage:',error);}};var getObjectFromLocalStorage=exports.getObjectFromLocalStorage=function getObjectFromLocalStorage(key){if(!key){throw new Error('Key is required for getObject');}try{var serializedValue=localStorage.getItem(key);if(serializedValue===null){return null;}return JSON.parse(serializedValue);}catch(error){console.error('Error retrieving object from localStorage:',error);return null;}};var isHex=function isHex(color){return /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(color);};var isRgb=function isRgb(color){return /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.test(color);};var isRgba=function isRgba(color){return /^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(0|1|0\.\d{1,2})\)$/.test(color);};var isHsl=function isHsl(color){return /^hsl\(\d{1,3},\s*[\d.]+%,\s*[\d.]+%\)$/.test(color);};var isHsla=function isHsla(color){return /^hsla\(\d{1,3},\s*[\d.]+%,\s*[\d.]+%,\s*(0|1|0\.\d{1,2})\)$/.test(color);};var hexToRGBA=exports.hexToRGBA=function hexToRGBA(colorParam){if(isRgb(colorParam)||isRgba(colorParam)||isHsl(colorParam)||isHsla(colorParam)){return colorParam;}if(!isHex(colorParam)){return null;}var shorthandRegex=/^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i;var color=colorParam.replace(shorthandRegex,function(m,r,g,b,a){return r+r+g+g+b+b+(a?a+a:'');});var result=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(color);if(!result){return null;}var r=parseInt(result[1],16);var g=parseInt(result[2],16);var b=parseInt(result[3],16);var a=result[4]?parseInt(result[4],16)/255:1;return'rgba('+r+', '+g+', '+b+', '+a+')';};function getStackTrace(){var error=new Error();console.log(error.stack);} |
@@ -1,1 +0,1 @@ | ||
Object.defineProperty(exports,"__esModule",{value:true});exports.transformValueToComponentStateFormat=exports.getDependentQueries=exports.extractPropsFromState=exports.getValidInterval=exports.getRSQuery=exports.hasPaginationSupport=exports.isComponentUsesLabelAsValue=exports.isSearchComponent=exports.isDRSRangeComponent=exports.getHistogramComponentID=exports.getInternalComponentID=exports.isInternalComponent=exports.getNormalizedField=exports.componentToTypeMap=undefined;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _componentToTypeMap;exports.flatReactProp=flatReactProp;var _dayjs=require('dayjs');var _dayjs2=_interopRequireDefault(_dayjs);var _constants=require('./constants');var _dateFormats=require('./dateFormats');var _dateFormats2=_interopRequireDefault(_dateFormats);var _helper=require('./helper');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var componentToTypeMap=exports.componentToTypeMap=(_componentToTypeMap={},_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveList,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.dataSearch,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.categorySearch,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.searchBox,_constants.queryTypes.suggestion),_defineProperty(_componentToTypeMap,_constants.componentTypes.AIAnswer,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDataList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDropdownList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDataList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDropdownList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.tagCloud,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.toggleButton,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveChart,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.treeList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.numberBox,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.datePicker,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.dateRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.dynamicRangeSlider,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDropdownRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDropdownRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.rangeSlider,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.ratingsFilter,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.rangeInput,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.geoDistanceDropdown,_constants.queryTypes.geo),_defineProperty(_componentToTypeMap,_constants.componentTypes.geoDistanceSlider,_constants.queryTypes.geo),_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveMap,_constants.queryTypes.geo),_componentToTypeMap);var multiRangeComponents=[_constants.componentTypes.multiRange,_constants.componentTypes.multiDropdownRange];var dateRangeComponents=[_constants.componentTypes.dateRange,_constants.componentTypes.datePicker];var searchComponents=[_constants.componentTypes.categorySearch,_constants.componentTypes.dataSearch,_constants.componentTypes.searchBox];var listComponentsWithPagination=[_constants.componentTypes.singleList,_constants.componentTypes.multiList,_constants.componentTypes.singleDropdownList,_constants.componentTypes.multiDropdownList];var getNormalizedField=exports.getNormalizedField=function getNormalizedField(field){if(field&&!Array.isArray(field)){return[field];}return field;};var isInternalComponent=exports.isInternalComponent=function isInternalComponent(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID.endsWith('__internal');};var getInternalComponentID=exports.getInternalComponentID=function getInternalComponentID(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID+'__internal';};var getHistogramComponentID=exports.getHistogramComponentID=function getHistogramComponentID(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID+'__histogram__internal';};var isDRSRangeComponent=exports.isDRSRangeComponent=function isDRSRangeComponent(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID.endsWith('__range__internal');};var isSearchComponent=exports.isSearchComponent=function isSearchComponent(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return searchComponents.includes(componentType);};var isComponentUsesLabelAsValue=exports.isComponentUsesLabelAsValue=function isComponentUsesLabelAsValue(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentType===_constants.componentTypes.multiDataList||componentType===_constants.componentTypes.singleDataList||componentType===_constants.componentTypes.tabDataList;};var hasPaginationSupport=exports.hasPaginationSupport=function hasPaginationSupport(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return listComponentsWithPagination.includes(componentType);};var getRSQuery=exports.getRSQuery=function getRSQuery(componentId,props){var execute=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;if(props&&componentId){var queryType=props.type?props.type:componentToTypeMap[props.componentType];if(props.componentType!==_constants.componentTypes.AIAnswer&&!isSearchComponent(props.componentType)&&!props.dataField){return null;}var endpoint=void 0;if(props.endpoint instanceof Object){endpoint=props.endpoint;}return _extends({id:componentId,type:queryType||_constants.queryTypes.search,dataField:getNormalizedField(props.dataField),execute:execute,react:props.react,highlight:props.highlight,highlightField:getNormalizedField(props.highlightField),fuzziness:props.fuzziness,searchOperators:props.searchOperators,includeFields:props.includeFields,excludeFields:props.excludeFields,size:props.size,aggregationSize:props.aggregationSize,from:props.from||undefined,queryFormat:props.queryFormat,sortBy:props.sortBy,fieldWeights:getNormalizedField(props.fieldWeights),includeNullValues:props.includeNullValues,aggregationField:props.aggregationField||undefined,categoryField:props.categoryField||undefined,missingLabel:props.missingLabel||undefined,showMissing:props.showMissing,nestedField:props.nestedField||undefined,interval:props.interval,highlightConfig:props.customHighlight||props.highlightConfig,customQuery:props.customQuery,defaultQuery:props.defaultQuery,value:props.value,categoryValue:props.categoryValue||undefined,after:props.after||undefined,aggregations:props.aggregations||undefined,enableSynonyms:props.enableSynonyms,selectAllLabel:props.selectAllLabel,pagination:props.pagination,queryString:props.queryString,distinctField:props.distinctField,distinctFieldConfig:props.distinctFieldConfig,index:props.index},queryType===_constants.queryTypes.suggestion?_extends({enablePopularSuggestions:props.enablePopularSuggestions,enableEndpointSuggestions:props.enableEndpointSuggestions,enableRecentSuggestions:props.enableRecentSuggestions,popularSuggestionsConfig:props.popularSuggestionsConfig,recentSuggestionsConfig:props.recentSuggestionsConfig,applyStopwords:props.applyStopwords,customStopwords:props.customStopwords,enablePredictiveSuggestions:props.enablePredictiveSuggestions,featuredSuggestionsConfig:props.featuredSuggestionsConfig,indexSuggestionsConfig:props.indexSuggestionsConfig,enableFeaturedSuggestions:props.enableFeaturedSuggestions,enableIndexSuggestions:props.enableIndexSuggestions},props.searchboxId?{searchboxId:props.searchboxId}:{}):{},{calendarInterval:props.calendarInterval,endpoint:endpoint,range:props.range},queryType!==_constants.queryTypes.suggestion&&props.enableAI?_extends({enableAI:true},props.AIConfig?{AIConfig:props.AIConfig}:{},{execute:true}):{});}return null;};var getValidInterval=exports.getValidInterval=function getValidInterval(interval){var range=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var min=Math.ceil((range.end-range.start)/100)||1;if(!interval){return min;}else if(interval<min){return min;}return interval;};var extractPropsFromState=exports.extractPropsFromState=function extractPropsFromState(store,component,customOptions){var componentProps=store.props[component];if(!componentProps){return null;}var queryType=componentProps.type?componentProps.type:componentToTypeMap[componentProps.componentType];var calcValues=store.selectedValues[component];var value=calcValues!==undefined&&calcValues!==null?calcValues.value:undefined;var queryFormat=componentProps.queryFormat;var calendarInterval=void 0;var interval=componentProps.interval;var type=queryType;var dataField=componentProps.dataField;var aggregations=componentProps.aggregations;var pagination=void 0;var from=componentProps.from;var range=void 0;if(queryType===_constants.queryTypes.term){if(componentProps.showLoadMore&&hasPaginationSupport(componentProps.componentType)){pagination=true;}if(value!=null&&typeof value==='object'&&value.value){value=value.value;}else if(Array.isArray(value)){var parsedValue=[];value.forEach(function(val){if(val!=null&&typeof val==='object'&&val.value){parsedValue.push(val.value);}else{parsedValue.push(val);}});value=parsedValue;}}if(queryType===_constants.queryTypes.range){if(Array.isArray(value)){if(multiRangeComponents.includes(componentProps.componentType)){value=value.map(function(_ref){var start=_ref.start,end=_ref.end;return{start:start,end:end};});}else{value={start:value[0],end:value[1]};}}else if(componentProps.showHistogram){var internalComponentID=getInternalComponentID(component);var internalComponentValue=store.internalValues[internalComponentID];if(!internalComponentValue){var histogramComponentID=getHistogramComponentID(component);internalComponentValue=store.internalValues[histogramComponentID];}if(internalComponentValue&&Array.isArray(internalComponentValue.value)){value={start:internalComponentValue.value[0],end:internalComponentValue.value[1]};}}if(isDRSRangeComponent(component)){aggregations=['min','max'];}else if(componentProps.showHistogram){aggregations=['histogram'];}if(componentProps.componentType===_constants.componentTypes.dynamicRangeSlider||componentProps.componentType===_constants.componentTypes.rangeSlider){calendarInterval=Object.keys(_dateFormats2.default).includes(queryFormat)?componentProps.calendarInterval:undefined;if(value){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){value={start:(0,_helper.formatDate)((0,_dayjs2.default)(new Date(value.start)),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(new Date(value.end)),componentProps)};}else{value={start:parseFloat(value.start),end:parseFloat(value.end)};}}var rangeValue=void 0;if(componentProps.componentType===_constants.componentTypes.dynamicRangeSlider){rangeValue=store.aggregations[component+'__range__internal'];if(componentProps.nestedField){rangeValue=rangeValue&&store.aggregations[component+'__range__internal'][componentProps.nestedField].min?{start:store.aggregations[component+'__range__internal'][componentProps.nestedField].min.value,end:store.aggregations[component+'__range__internal'][componentProps.nestedField].max.value}:null;}else{rangeValue=rangeValue&&store.aggregations[component+'__range__internal'].min&&store.aggregations[component+'__range__internal'].min.value?{start:store.aggregations[component+'__range__internal'].min.value,end:store.aggregations[component+'__range__internal'].max.value}:null;}}else{rangeValue=componentProps.range;}if(rangeValue){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){range={start:(0,_helper.formatDate)((0,_dayjs2.default)(rangeValue.start),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(rangeValue.end),componentProps)};}else{range={start:parseFloat(rangeValue.start),end:parseFloat(rangeValue.end)};}}}if(dateRangeComponents.includes(componentProps.componentType)){if(value){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){if(typeof value==='string'){value={start:(0,_helper.formatDate)((0,_dayjs2.default)(value).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(value),componentProps)};}else if(Array.isArray(value)){value=value.map(function(val){return{start:(0,_helper.formatDate)((0,_dayjs2.default)(val).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(val),componentProps)};});}else{value={start:(0,_helper.formatDate)((0,_dayjs2.default)(value.start).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(value.end),componentProps)};}}}}}if(queryType===_constants.queryTypes.geo){value=undefined;var geoCalcValues=store.selectedValues[component]||store.internalValues[component]||store.internalValues[getInternalComponentID(component)];if(geoCalcValues&&geoCalcValues.meta){if(geoCalcValues.meta.distance&&geoCalcValues.meta.coordinates){value={distance:geoCalcValues.meta.distance,location:geoCalcValues.meta.coordinates};if(componentProps.unit){value.unit=componentProps.unit;}}if(geoCalcValues.meta.mapBoxBounds&&geoCalcValues.meta.mapBoxBounds.top_left&&geoCalcValues.meta.mapBoxBounds.bottom_right){value={geoBoundingBox:{topLeft:geoCalcValues.meta.mapBoxBounds.top_left[1]+', '+geoCalcValues.meta.mapBoxBounds.top_left[0],bottomRight:geoCalcValues.meta.mapBoxBounds.bottom_right[1]+', '+geoCalcValues.meta.mapBoxBounds.bottom_right[0]}};}}}if(componentProps.componentType===_constants.componentTypes.numberBox){if(queryFormat==='exact'){type='term';}else{type='range';if(queryFormat==='lte'){value={end:value,boost:2.0};}else{value={start:value,boost:2.0};}}queryFormat='or';}if(componentProps.componentType===_constants.componentTypes.reactiveComponent){type='term';dataField='reactive_component_field';value=undefined;}if(isSearchComponent(componentProps.componentType)&&!value){value='';}if(isComponentUsesLabelAsValue(componentProps.componentType)){var data=componentProps.data,selectAllLabel=componentProps.selectAllLabel;var absValue=[];if(value&&Array.isArray(value)){absValue=value;}else if(value&&typeof value==='string'){absValue=[value];}var normalizedValue=[];if(absValue.length){if(data&&Array.isArray(data)){absValue.forEach(function(val){var dataItem=data.find(function(o){return o.label===val;});if(dataItem&&dataItem.value){normalizedValue.push(dataItem.value);}});}}if(selectAllLabel&&absValue.length&&absValue.includes(selectAllLabel)){normalizedValue=absValue;}if(normalizedValue.length){value=normalizedValue;}else{value=undefined;}}if(componentProps.componentType===_constants.componentTypes.reactiveList){if(value>0){from=(value-1)*(componentProps.size||10);}value=undefined;}var queryValue=value||undefined;if(componentProps.componentType===_constants.componentTypes.searchBox){if(Array.isArray(queryValue)){queryValue=undefined;}}var endpoint=void 0;if(componentProps.endpoint instanceof Object){endpoint=_extends({},endpoint||{},componentProps.endpoint);}return _extends({},componentProps,{endpoint:endpoint,calendarInterval:calendarInterval,dataField:dataField,queryFormat:queryFormat,type:type,aggregations:aggregations,interval:interval,react:store.dependencyTree?store.dependencyTree[component]:undefined,customQuery:store.customQueries?store.customQueries[component]:undefined,defaultQuery:store.defaultQueries?store.defaultQueries[component]:undefined,customHighlight:store.customHighlightOptions?store.customHighlightOptions[component]:undefined,categoryValue:store.internalValues[component]?store.internalValues[component].category:undefined,value:queryValue,pagination:pagination,from:from,range:range},customOptions);};function flatReactProp(reactProp,componentID){var flattenReact=[];var flatReact=function flatReact(react){if(react&&Object.keys(react)){Object.keys(react).forEach(function(r){if(react[r]){if(typeof react[r]==='string'){flattenReact=[].concat(_toConsumableArray(flattenReact),[react[r]]);}else if(Array.isArray(react[r])){flattenReact=[].concat(_toConsumableArray(flattenReact),_toConsumableArray(react[r]));}else if(typeof react[r]==='object'){flatReact(react[r]);}}});}};flatReact(reactProp);flattenReact=flattenReact.filter(function(react){return react!==componentID;});return flattenReact;}var getDependentQueries=exports.getDependentQueries=function getDependentQueries(store,componentID){var orderOfQueries=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var finalQuery={};var react=flatReactProp(store.dependencyTree[componentID],componentID);react.forEach(function(componentObject){var component=componentObject;var customQuery=store.customQueries[component];if(!isInternalComponent(component)){var calcValues=store.selectedValues[component]||store.internalValues[component];if((calcValues&&calcValues.value||customQuery)&&!finalQuery[component]){var execute=false;if(Array.isArray(orderOfQueries)&&orderOfQueries.includes(component)){execute=true;}var componentProps=store.props[component];var dependentQuery=getRSQuery(component,extractPropsFromState(store,component,_extends({},componentProps&&_extends({},componentProps.componentType===_constants.componentTypes.searchBox?_extends({},execute===false?{type:_constants.queryTypes.search}:{},calcValues.category?{categoryValue:calcValues.category}:{categoryValue:undefined},calcValues.value?{value:calcValues.value}:{}):{},componentProps.componentType===_constants.componentTypes.categorySearch?_extends({},calcValues.category?{categoryValue:calcValues.category}:{categoryValue:undefined}):{}))),execute);if(dependentQuery){finalQuery[component]=dependentQuery;}}}});return finalQuery;};var transformValueToComponentStateFormat=exports.transformValueToComponentStateFormat=function transformValueToComponentStateFormat(value,componentProps){var componentType=componentProps.componentType,data=componentProps.data,queryFormat=componentProps.queryFormat;var transformedValue=value;var meta={};if(value){switch(componentType){case _constants.componentTypes.singleDataList:case _constants.componentTypes.tabDataList:transformedValue='';if(Array.isArray(value)&&typeof value[0]==='string'){transformedValue=value[0];}else if(typeof value==='object'&&value.label){transformedValue=value.label;}else{transformedValue=value;}break;case _constants.componentTypes.multiDataList:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&(valObj.label||valObj.value)){transformedValue.push(valObj.label||valObj.value);}else if(typeof valObj==='string'){transformedValue.push(valObj);}});}break;case _constants.componentTypes.toggleButton:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&valObj.label&&valObj.value){transformedValue.push(valObj);}else if(typeof valObj==='string'){var findDataObj=data.find(function(item){return item.label.trim()===valObj.trim()||item.value.trim()===valObj.trim();});transformedValue.push(findDataObj);}});}else if(typeof value==='object'&&value.label&&value.value){transformedValue=value.value;}else if(typeof value==='string'){var findDataObj=data.find(function(item){return item.label.trim()===value.trim()||item.value.trim()===value.trim();});transformedValue=findDataObj.value;}break;case _constants.componentTypes.singleRange:case _constants.componentTypes.singleDropdownRange:transformedValue={};if(!Array.isArray(value)&&typeof value==='object'){transformedValue=_extends({},value);}else if(typeof value==='string'){var _findDataObj=data.find(function(item){return item.label.trim()===value.trim();});transformedValue=_extends({},_findDataObj);}break;case _constants.componentTypes.multiDropdownRange:case _constants.componentTypes.multiRange:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&typeof valObj.start==='number'&&typeof valObj.end==='number'){var _findDataObj2=_extends({},valObj);if(!_findDataObj2.label){_findDataObj2=data.find(function(item){return item.start===valObj.start&&item.end===valObj.end;});}transformedValue.push(_findDataObj2);}else if(typeof valObj==='string'){var _findDataObj3=data.find(function(item){return item.label.trim()===valObj.trim();});transformedValue.push(_findDataObj3);}});}else if(typeof value==='string'){var _findDataObj4=data.find(function(item){return item.label.trim()===value.trim();});transformedValue.push(_findDataObj4);}break;case _constants.componentTypes.rangeSlider:case _constants.componentTypes.ratingsFilter:case _constants.componentTypes.dynamicRangeSlider:case _constants.componentTypes.reactiveChart:transformedValue=[];if(queryFormat){if(Array.isArray(value)){transformedValue=value.map(function(item){return(0,_helper.formatDate)((0,_dayjs2.default)(item),componentProps);});}else if(typeof value==='object'){transformedValue=[(0,_helper.formatDate)((0,_dayjs2.default)(value.start),componentProps),(0,_helper.formatDate)((0,_dayjs2.default)(value.end),componentProps)];}}else if(Array.isArray(value)){transformedValue=[].concat(_toConsumableArray(value));}else if(typeof value==='object'){transformedValue=[value.start,value.end];}else{transformedValue=value;}break;case _constants.componentTypes.numberBox:transformedValue=[];if(!Array.isArray(value)&&typeof value==='object'){transformedValue=value.start;}else if(typeof value==='number'){transformedValue=value;}break;case _constants.componentTypes.datePicker:transformedValue='';if(typeof value!=='object'){transformedValue=(0,_dayjs2.default)(value).format('YYYY-MM-DD');}else if(value.end){transformedValue=(0,_dayjs2.default)(value.end).format('YYYY-MM-DD');}else if(value.start){transformedValue=(0,_dayjs2.default)(value.start).add(24,'hour').format('YYYY-MM-DD');}break;case _constants.componentTypes.dateRange:transformedValue=[];if(Array.isArray(value)){transformedValue=value.map(function(t){return(0,_dayjs2.default)(t).format('YYYY-MM-DD');});}else if(typeof value==='object'){transformedValue=[(0,_dayjs2.default)(value.start).format('YYYY-MM-DD'),(0,_dayjs2.default)(value.end).format('YYYY-MM-DD')];}break;case _constants.componentTypes.categorySearch:transformedValue='';if(typeof value==='object'){transformedValue=value.value;if(value.category!==undefined){meta.category=value.category;}}else if(typeof value==='string'){transformedValue=value;}break;default:break;}}return{value:transformedValue,meta:meta};}; | ||
Object.defineProperty(exports,"__esModule",{value:true});exports.transformValueToComponentStateFormat=exports.getDependentQueries=exports.extractPropsFromState=exports.getValidInterval=exports.getRSQuery=exports.hasPaginationSupport=exports.isComponentUsesLabelAsValue=exports.isSearchComponent=exports.isDRSRangeComponent=exports.getHistogramComponentID=exports.getInternalComponentID=exports.isInternalComponent=exports.getNormalizedField=exports.componentToTypeMap=undefined;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};var _componentToTypeMap;exports.flatReactProp=flatReactProp;var _dayjs=require('dayjs');var _dayjs2=_interopRequireDefault(_dayjs);var _constants=require('./constants');var _dateFormats=require('./dateFormats');var _dateFormats2=_interopRequireDefault(_dateFormats);var _helper=require('./helper');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var componentToTypeMap=exports.componentToTypeMap=(_componentToTypeMap={},_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveList,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.dataSearch,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.categorySearch,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.searchBox,_constants.queryTypes.suggestion),_defineProperty(_componentToTypeMap,_constants.componentTypes.AIAnswer,_constants.queryTypes.search),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDataList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDropdownList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDataList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDropdownList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.tagCloud,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.toggleButton,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveChart,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.treeList,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.numberBox,_constants.queryTypes.term),_defineProperty(_componentToTypeMap,_constants.componentTypes.datePicker,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.dateRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.dynamicRangeSlider,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleDropdownRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiDropdownRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.singleRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.multiRange,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.rangeSlider,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.ratingsFilter,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.rangeInput,_constants.queryTypes.range),_defineProperty(_componentToTypeMap,_constants.componentTypes.geoDistanceDropdown,_constants.queryTypes.geo),_defineProperty(_componentToTypeMap,_constants.componentTypes.geoDistanceSlider,_constants.queryTypes.geo),_defineProperty(_componentToTypeMap,_constants.componentTypes.reactiveMap,_constants.queryTypes.geo),_componentToTypeMap);var multiRangeComponents=[_constants.componentTypes.multiRange,_constants.componentTypes.multiDropdownRange];var dateRangeComponents=[_constants.componentTypes.dateRange,_constants.componentTypes.datePicker];var searchComponents=[_constants.componentTypes.categorySearch,_constants.componentTypes.dataSearch,_constants.componentTypes.searchBox];var listComponentsWithPagination=[_constants.componentTypes.singleList,_constants.componentTypes.multiList,_constants.componentTypes.singleDropdownList,_constants.componentTypes.multiDropdownList];var getNormalizedField=exports.getNormalizedField=function getNormalizedField(field){if(field&&!Array.isArray(field)){return[field];}return field;};var isInternalComponent=exports.isInternalComponent=function isInternalComponent(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID.endsWith('__internal');};var getInternalComponentID=exports.getInternalComponentID=function getInternalComponentID(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID+'__internal';};var getHistogramComponentID=exports.getHistogramComponentID=function getHistogramComponentID(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID+'__histogram__internal';};var isDRSRangeComponent=exports.isDRSRangeComponent=function isDRSRangeComponent(){var componentID=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentID.endsWith('__range__internal');};var isSearchComponent=exports.isSearchComponent=function isSearchComponent(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return searchComponents.includes(componentType);};var isComponentUsesLabelAsValue=exports.isComponentUsesLabelAsValue=function isComponentUsesLabelAsValue(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return componentType===_constants.componentTypes.multiDataList||componentType===_constants.componentTypes.singleDataList||componentType===_constants.componentTypes.tabDataList;};var hasPaginationSupport=exports.hasPaginationSupport=function hasPaginationSupport(){var componentType=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return listComponentsWithPagination.includes(componentType);};var getRSQuery=exports.getRSQuery=function getRSQuery(componentId,props){var execute=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;if(props&&componentId){var queryType=props.type?props.type:componentToTypeMap[props.componentType];if(props.componentType!==_constants.componentTypes.AIAnswer&&!isSearchComponent(props.componentType)&&!props.dataField){return null;}var endpoint=void 0;if(props.endpoint instanceof Object){endpoint=props.endpoint;}return _extends({id:componentId,type:queryType||_constants.queryTypes.search,dataField:getNormalizedField(props.dataField),execute:execute,react:props.react,highlight:props.highlight,highlightField:getNormalizedField(props.highlightField),fuzziness:props.fuzziness,searchOperators:props.searchOperators,includeFields:props.includeFields,excludeFields:props.excludeFields,size:props.size,aggregationSize:props.aggregationSize,from:props.from||undefined,queryFormat:props.queryFormat,sortBy:props.sortBy,fieldWeights:getNormalizedField(props.fieldWeights),includeNullValues:props.includeNullValues,aggregationField:props.aggregationField||undefined,categoryField:props.categoryField||undefined,missingLabel:props.missingLabel||undefined,showMissing:props.showMissing,nestedField:props.nestedField||undefined,interval:props.interval,highlightConfig:props.customHighlight||props.highlightConfig,customQuery:props.customQuery,defaultQuery:props.defaultQuery,value:props.value,categoryValue:props.categoryValue||undefined,after:props.after||undefined,aggregations:props.aggregations||undefined,enableSynonyms:props.enableSynonyms,selectAllLabel:props.selectAllLabel,pagination:props.pagination,queryString:props.queryString,distinctField:props.distinctField,distinctFieldConfig:props.distinctFieldConfig,index:props.index},queryType===_constants.queryTypes.suggestion?_extends({enablePopularSuggestions:props.enablePopularSuggestions,enableEndpointSuggestions:props.enableEndpointSuggestions,enableRecentSuggestions:props.enableRecentSuggestions,popularSuggestionsConfig:props.popularSuggestionsConfig,recentSuggestionsConfig:props.recentSuggestionsConfig,applyStopwords:props.applyStopwords,customStopwords:props.customStopwords,enablePredictiveSuggestions:props.enablePredictiveSuggestions,featuredSuggestionsConfig:props.featuredSuggestionsConfig,indexSuggestionsConfig:props.indexSuggestionsConfig,enableFeaturedSuggestions:props.enableFeaturedSuggestions,enableIndexSuggestions:props.enableIndexSuggestions},props.searchboxId?{searchboxId:props.searchboxId}:{}):{},{calendarInterval:props.calendarInterval,endpoint:endpoint,range:props.range},queryType!==_constants.queryTypes.suggestion&&props.enableAI&&execute?_extends({enableAI:true},props.AIConfig?{AIConfig:props.AIConfig}:{},{execute:true}):{});}return null;};var getValidInterval=exports.getValidInterval=function getValidInterval(interval){var range=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var min=Math.ceil((range.end-range.start)/100)||1;if(!interval){return min;}else if(interval<min){return min;}return interval;};var extractPropsFromState=exports.extractPropsFromState=function extractPropsFromState(store,component,customOptions){var componentProps=store.props[component];if(!componentProps){return null;}var queryType=componentProps.type?componentProps.type:componentToTypeMap[componentProps.componentType];var calcValues=store.selectedValues[component];var value=calcValues!==undefined&&calcValues!==null?calcValues.value:undefined;var queryFormat=componentProps.queryFormat;var calendarInterval=void 0;var interval=componentProps.interval;var type=queryType;var dataField=componentProps.dataField;var aggregations=componentProps.aggregations;var pagination=void 0;var from=componentProps.from;var range=void 0;if(queryType===_constants.queryTypes.term){if(componentProps.showLoadMore&&hasPaginationSupport(componentProps.componentType)){pagination=true;}if(value!=null&&typeof value==='object'&&value.value){value=value.value;}else if(Array.isArray(value)){var parsedValue=[];value.forEach(function(val){if(val!=null&&typeof val==='object'&&val.value){parsedValue.push(val.value);}else{parsedValue.push(val);}});value=parsedValue;}}if(queryType===_constants.queryTypes.range){if(Array.isArray(value)){if(multiRangeComponents.includes(componentProps.componentType)){value=value.map(function(_ref){var start=_ref.start,end=_ref.end;return{start:start,end:end};});}else{value={start:value[0],end:value[1]};}}else if(componentProps.showHistogram){var internalComponentID=getInternalComponentID(component);var internalComponentValue=store.internalValues[internalComponentID];if(!internalComponentValue){var histogramComponentID=getHistogramComponentID(component);internalComponentValue=store.internalValues[histogramComponentID];}if(internalComponentValue&&Array.isArray(internalComponentValue.value)){value={start:internalComponentValue.value[0],end:internalComponentValue.value[1]};}}if(isDRSRangeComponent(component)){aggregations=['min','max'];}else if(componentProps.showHistogram){aggregations=['histogram'];}if(componentProps.componentType===_constants.componentTypes.dynamicRangeSlider||componentProps.componentType===_constants.componentTypes.rangeSlider){calendarInterval=Object.keys(_dateFormats2.default).includes(queryFormat)?componentProps.calendarInterval:undefined;if(value){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){value={start:(0,_helper.formatDate)((0,_dayjs2.default)(new Date(value.start)),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(new Date(value.end)),componentProps)};}else{value={start:parseFloat(value.start),end:parseFloat(value.end)};}}var rangeValue=void 0;if(componentProps.componentType===_constants.componentTypes.dynamicRangeSlider){rangeValue=store.aggregations[component+'__range__internal'];if(componentProps.nestedField){rangeValue=rangeValue&&store.aggregations[component+'__range__internal'][componentProps.nestedField].min?{start:store.aggregations[component+'__range__internal'][componentProps.nestedField].min.value,end:store.aggregations[component+'__range__internal'][componentProps.nestedField].max.value}:null;}else{rangeValue=rangeValue&&store.aggregations[component+'__range__internal'].min&&store.aggregations[component+'__range__internal'].min.value?{start:store.aggregations[component+'__range__internal'].min.value,end:store.aggregations[component+'__range__internal'].max.value}:null;}}else{rangeValue=componentProps.range;}if(rangeValue){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){range={start:(0,_helper.formatDate)((0,_dayjs2.default)(rangeValue.start),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(rangeValue.end),componentProps)};}else{range={start:parseFloat(rangeValue.start),end:parseFloat(rangeValue.end)};}}}if(dateRangeComponents.includes(componentProps.componentType)){if(value){if((0,_helper.isValidDateRangeQueryFormat)(componentProps.queryFormat)){if(typeof value==='string'){value={start:(0,_helper.formatDate)((0,_dayjs2.default)(value).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(value),componentProps)};}else if(Array.isArray(value)){value=value.map(function(val){return{start:(0,_helper.formatDate)((0,_dayjs2.default)(val).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(val),componentProps)};});}else{value={start:(0,_helper.formatDate)((0,_dayjs2.default)(value.start).subtract(24,'hour'),componentProps),end:(0,_helper.formatDate)((0,_dayjs2.default)(value.end),componentProps)};}}}}}if(queryType===_constants.queryTypes.geo){value=undefined;var geoCalcValues=store.selectedValues[component]||store.internalValues[component]||store.internalValues[getInternalComponentID(component)];if(geoCalcValues&&geoCalcValues.meta){if(geoCalcValues.meta.distance&&geoCalcValues.meta.coordinates){value={distance:geoCalcValues.meta.distance,location:geoCalcValues.meta.coordinates};if(componentProps.unit){value.unit=componentProps.unit;}}if(geoCalcValues.meta.mapBoxBounds&&geoCalcValues.meta.mapBoxBounds.top_left&&geoCalcValues.meta.mapBoxBounds.bottom_right){value={geoBoundingBox:{topLeft:geoCalcValues.meta.mapBoxBounds.top_left[1]+', '+geoCalcValues.meta.mapBoxBounds.top_left[0],bottomRight:geoCalcValues.meta.mapBoxBounds.bottom_right[1]+', '+geoCalcValues.meta.mapBoxBounds.bottom_right[0]}};}}}if(componentProps.componentType===_constants.componentTypes.numberBox){if(queryFormat==='exact'){type='term';}else{type='range';if(queryFormat==='lte'){value={end:value,boost:2.0};}else{value={start:value,boost:2.0};}}queryFormat='or';}if(componentProps.componentType===_constants.componentTypes.reactiveComponent){type='term';dataField='reactive_component_field';value=undefined;}if(isSearchComponent(componentProps.componentType)&&!value){value='';}if(isComponentUsesLabelAsValue(componentProps.componentType)){var data=componentProps.data,selectAllLabel=componentProps.selectAllLabel;var absValue=[];if(value&&Array.isArray(value)){absValue=value;}else if(value&&typeof value==='string'){absValue=[value];}var normalizedValue=[];if(absValue.length){if(data&&Array.isArray(data)){absValue.forEach(function(val){var dataItem=data.find(function(o){return o.label===val;});if(dataItem&&dataItem.value){normalizedValue.push(dataItem.value);}});}}if(selectAllLabel&&absValue.length&&absValue.includes(selectAllLabel)){normalizedValue=absValue;}if(normalizedValue.length){value=normalizedValue;}else{value=undefined;}}if(componentProps.componentType===_constants.componentTypes.reactiveList){if(value>0){from=(value-1)*(componentProps.size||10);}value=undefined;}var queryValue=value||undefined;if(componentProps.componentType===_constants.componentTypes.searchBox){if(Array.isArray(queryValue)){queryValue=undefined;}}var endpoint=void 0;if(componentProps.endpoint instanceof Object){endpoint=_extends({},endpoint||{},componentProps.endpoint);}return _extends({},componentProps,{endpoint:endpoint,calendarInterval:calendarInterval,dataField:dataField,queryFormat:queryFormat,type:type,aggregations:aggregations,interval:interval,react:store.dependencyTree?store.dependencyTree[component]:undefined,customQuery:store.customQueries?store.customQueries[component]:undefined,defaultQuery:store.defaultQueries?store.defaultQueries[component]:undefined,customHighlight:store.customHighlightOptions?store.customHighlightOptions[component]:undefined,categoryValue:store.internalValues[component]?store.internalValues[component].category:undefined,value:queryValue,pagination:pagination,from:from,range:range},customOptions);};function flatReactProp(reactProp,componentID){var flattenReact=[];var flatReact=function flatReact(react){if(react&&Object.keys(react)){Object.keys(react).forEach(function(r){if(react[r]){if(typeof react[r]==='string'){flattenReact=[].concat(_toConsumableArray(flattenReact),[react[r]]);}else if(Array.isArray(react[r])){flattenReact=[].concat(_toConsumableArray(flattenReact),_toConsumableArray(react[r]));}else if(typeof react[r]==='object'){flatReact(react[r]);}}});}};flatReact(reactProp);flattenReact=flattenReact.filter(function(react){return react!==componentID;});return flattenReact;}var getDependentQueries=exports.getDependentQueries=function getDependentQueries(store,componentID){var orderOfQueries=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var finalQuery={};var react=flatReactProp(store.dependencyTree[componentID],componentID);react.forEach(function(componentObject){var component=componentObject;var customQuery=store.customQueries[component];if(!isInternalComponent(component)){var calcValues=store.selectedValues[component]||store.internalValues[component];if((calcValues&&calcValues.value||customQuery)&&!finalQuery[component]){var execute=false;var componentProps=store.props[component];if(Array.isArray(orderOfQueries)&&orderOfQueries.includes(component)&&!(componentProps.componentType===_constants.componentTypes.searchBox&&componentProps.enableAI)){execute=true;}var dependentQuery=getRSQuery(component,extractPropsFromState(store,component,_extends({},componentProps&&_extends({},componentProps.componentType===_constants.componentTypes.searchBox?_extends({},execute===false?{type:_constants.queryTypes.search}:{},calcValues.category?{categoryValue:calcValues.category}:{categoryValue:undefined},calcValues.value?{value:calcValues.value}:{}):{},componentProps.componentType===_constants.componentTypes.categorySearch?_extends({},calcValues.category?{categoryValue:calcValues.category}:{categoryValue:undefined}):{}))),execute);if(dependentQuery){finalQuery[component]=dependentQuery;}}}});return finalQuery;};var transformValueToComponentStateFormat=exports.transformValueToComponentStateFormat=function transformValueToComponentStateFormat(value,componentProps){var componentType=componentProps.componentType,data=componentProps.data,queryFormat=componentProps.queryFormat;var transformedValue=value;var meta={};if(value){switch(componentType){case _constants.componentTypes.singleDataList:case _constants.componentTypes.tabDataList:transformedValue='';if(Array.isArray(value)&&typeof value[0]==='string'){transformedValue=value[0];}else if(typeof value==='object'&&value.label){transformedValue=value.label;}else{transformedValue=value;}break;case _constants.componentTypes.multiDataList:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&(valObj.label||valObj.value)){transformedValue.push(valObj.label||valObj.value);}else if(typeof valObj==='string'){transformedValue.push(valObj);}});}break;case _constants.componentTypes.toggleButton:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&valObj.label&&valObj.value){transformedValue.push(valObj);}else if(typeof valObj==='string'){var findDataObj=data.find(function(item){return item.label.trim()===valObj.trim()||item.value.trim()===valObj.trim();});transformedValue.push(findDataObj);}});}else if(typeof value==='object'&&value.label&&value.value){transformedValue=value.value;}else if(typeof value==='string'){var findDataObj=data.find(function(item){return item.label.trim()===value.trim()||item.value.trim()===value.trim();});transformedValue=findDataObj.value;}break;case _constants.componentTypes.singleRange:case _constants.componentTypes.singleDropdownRange:transformedValue={};if(!Array.isArray(value)&&typeof value==='object'){transformedValue=_extends({},value);}else if(typeof value==='string'){var _findDataObj=data.find(function(item){return item.label.trim()===value.trim();});transformedValue=_extends({},_findDataObj);}break;case _constants.componentTypes.multiDropdownRange:case _constants.componentTypes.multiRange:transformedValue=[];if(Array.isArray(value)){value.forEach(function(valObj){if(typeof valObj==='object'&&typeof valObj.start==='number'&&typeof valObj.end==='number'){var _findDataObj2=_extends({},valObj);if(!_findDataObj2.label){_findDataObj2=data.find(function(item){return item.start===valObj.start&&item.end===valObj.end;});}transformedValue.push(_findDataObj2);}else if(typeof valObj==='string'){var _findDataObj3=data.find(function(item){return item.label.trim()===valObj.trim();});transformedValue.push(_findDataObj3);}});}else if(typeof value==='string'){var _findDataObj4=data.find(function(item){return item.label.trim()===value.trim();});transformedValue.push(_findDataObj4);}break;case _constants.componentTypes.rangeSlider:case _constants.componentTypes.ratingsFilter:case _constants.componentTypes.dynamicRangeSlider:case _constants.componentTypes.reactiveChart:transformedValue=[];if(queryFormat){if(Array.isArray(value)){transformedValue=value.map(function(item){return(0,_helper.formatDate)((0,_dayjs2.default)(item),componentProps);});}else if(typeof value==='object'){transformedValue=[(0,_helper.formatDate)((0,_dayjs2.default)(value.start),componentProps),(0,_helper.formatDate)((0,_dayjs2.default)(value.end),componentProps)];}}else if(Array.isArray(value)){transformedValue=[].concat(_toConsumableArray(value));}else if(typeof value==='object'){transformedValue=[value.start,value.end];}else{transformedValue=value;}break;case _constants.componentTypes.numberBox:transformedValue=[];if(!Array.isArray(value)&&typeof value==='object'){transformedValue=value.start;}else if(typeof value==='number'){transformedValue=value;}break;case _constants.componentTypes.datePicker:transformedValue='';if(typeof value!=='object'){transformedValue=(0,_dayjs2.default)(value).format('YYYY-MM-DD');}else if(value.end){transformedValue=(0,_dayjs2.default)(value.end).format('YYYY-MM-DD');}else if(value.start){transformedValue=(0,_dayjs2.default)(value.start).add(24,'hour').format('YYYY-MM-DD');}break;case _constants.componentTypes.dateRange:transformedValue=[];if(Array.isArray(value)){transformedValue=value.map(function(t){return(0,_dayjs2.default)(t).format('YYYY-MM-DD');});}else if(typeof value==='object'){transformedValue=[(0,_dayjs2.default)(value.start).format('YYYY-MM-DD'),(0,_dayjs2.default)(value.end).format('YYYY-MM-DD')];}break;case _constants.componentTypes.categorySearch:transformedValue='';if(typeof value==='object'){transformedValue=value.value;if(value.category!==undefined){meta.category=value.category;}}else if(typeof value==='string'){transformedValue=value;}break;default:break;}}return{value:transformedValue,meta:meta};}; |
{ | ||
"name": "@appbaseio/reactivecore", | ||
"version": "10.0.0-alpha.10", | ||
"version": "10.0.0-alpha.11", | ||
"description": "Core architecture of reactive UI libraries", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
226206