@appbaseio/reactivesearch-vue
Version:
A Vue UI components library for building search experiences
1,151 lines (1,142 loc) • 71.2 kB
JavaScript
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var reactivecore = require('@appbaseio/reactivecore');
var constants = require('@appbaseio/reactivecore/lib/utils/constants');
var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-1a877b17.js');
var vue = require('vue');
var VueTypes = _interopDefault(require('vue-types'));
var helper = require('@appbaseio/reactivecore/lib/utils/helper');
var vueEmotion = require('@appbaseio/vue-emotion');
var Button = require('./Button-7aee17e3.js');
var vueTypes = require('./vueTypes-adf43075.js');
var ReactiveList = require('./ReactiveList.js');
var transform = require('@appbaseio/reactivecore/lib/utils/transform');
var index = require('./index-7ca9570e.js');
var ComponentWrapper = require('./ComponentWrapper-3bedbe57.js');
var PreferencesConsumer = require('./PreferencesConsumer-37cab7a0.js');
var Title = require('./Title-d513ac26.js');
var ListItem = require('./ListItem-f272f502.js');
var Flex = require('./Flex-f7af0673.js');
var analytics = require('@appbaseio/reactivecore/lib/actions/analytics');
var ReactiveBase = require('./ReactiveBase.js');
var remarkable = require('remarkable');
var SearchBox = require('./SearchBox-9278c775.js');
var CancelSvg = require('./CancelSvg-6094cd37.js');
var Input = require('./Input-55fbd8e1.js');
var Container = require('./Container-1c05785a.js');
var query = require('@appbaseio/reactivecore/lib/actions/query');
var suggestions = require('@appbaseio/reactivecore/lib/utils/suggestions');
var FormControlList = require('./FormControlList-2c10e01a.js');
var utils = require('./utils-a3db8765.js');
var SingleList = require('./SingleList.js');
var MultiList = require('./MultiList.js');
var types = _interopDefault(require('@appbaseio/reactivecore/lib/utils/types'));
var SingleDropdownList = require('./SingleDropdownList.js');
var MultiDropdownList = require('./MultiDropdownList.js');
var ToggleButton = require('./ToggleButton.js');
var ReactiveComponent = require('./ReactiveComponent.js');
var DynamicRangeSlider = require('./DynamicRangeSlider.js');
var SingleRange = require('./SingleRange.js');
var MultiRange = require('./MultiRange.js');
var RangeSlider = require('./RangeSlider.js');
var RangeInput = require('./RangeInput.js');
var SelectedFilters = require('./SelectedFilters.js');
var ResultCard = require('./ResultCard.js');
var ResultList = require('./ResultList.js');
var StateProvider = require('./StateProvider.js');
var _excluded = ["_source"];
function _isSlot(s) {
return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !vue.isVNode(s);
}
var md = new remarkable.Remarkable();
md.set({
html: true,
breaks: true,
xhtmlOut: true,
linkify: true,
linkTarget: '_blank'
});
var _inputWrapperRef = 'inputWrapperRef';
var _inputRef = 'inputRef';
var _errorContainerRef = 'errorContainerRef';
var AIAnswer = vue.defineComponent({
name: 'AIAnswer',
data: function data() {
var props = this.$props;
this.__state = {
messages: [],
inputMessage: '',
AISessionId: '',
error: null,
sourceDocIds: null,
initialHits: null,
isTriggered: false
};
this.internalComponent = props.componentId + "__internal";
return this.__state;
},
inject: {
theme: {
from: 'theme_reactivesearch'
}
},
created: function created() {
if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.ALWAYS) {
this.isTriggered = true;
} else if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.QUESTION && this.dependentComponentValue && this.dependentComponentValue.endsWith('?')) {
this.isTriggered = true;
if (this.AISessionId) {
this.handleSendMessage(null, false, '', true);
}
}
},
computed: {
hasCustomRenderer: function hasCustomRenderer() {
return index.hasCustomRenderer(this);
},
isLoadingState: function isLoadingState() {
return this.isAIResponseLoading || this.isLoading;
},
shouldShowComponent: function shouldShowComponent() {
return this.showComponent;
},
errorMessageForMissingSessionId: function errorMessageForMissingSessionId() {
return "AISessionId for " + this.$props.componentId + " is missing! AIAnswer component requires an AISessionId to function. Try reloading the App.";
},
hasTriggered: function hasTriggered() {
return this.isTriggered;
}
},
props: {
componentId: vueTypes.types.string.isRequired,
showVoiceInput: VueTypes.bool.def(false),
showFeedback: VueTypes.bool.def(true),
showIcon: VueTypes.bool.def(true),
onData: vueTypes.types.func,
innerRef: VueTypes.string.def('AISearchInputField'),
react: vueTypes.types.react,
enableAI: VueTypes.bool.def(true),
AIConfig: vueTypes.types.AIConfig,
iconPosition: vueTypes.types.iconPosition.def('left'),
icon: vueTypes.types.children,
iconURL: VueTypes.string.def(''),
renderMic: vueTypes.types.func,
getMicInstance: vueTypes.types.func,
innerClass: vueTypes.types.style,
placeholder: VueTypes.string.def('Ask a question'),
title: vueTypes.types.title,
enterButton: vueTypes.types.bool,
renderEnterButton: vueTypes.types.title,
showInput: VueTypes.bool.def(true),
clearSessionOnDestroy: VueTypes.bool.def(true),
render: vueTypes.types.func,
onError: vueTypes.types.func,
renderError: vueTypes.types.title,
style: vueTypes.types.style,
showSourceDocuments: VueTypes.bool.def(false),
renderSourceDocument: vueTypes.types.func,
onSourceClick: vueTypes.types.func,
triggerOn: VueTypes.string.def(constants.AI_TRIGGER_MODES.ALWAYS),
renderTriggerMessage: vueTypes.types.func
},
mounted: function mounted() {},
watch: {
AIResponse: function AIResponse(newVal) {
if (newVal) {
if (this.$props.showSourceDocuments && newVal.response && newVal.response.answer && Array.isArray(newVal.response.answer.documentIds)) {
this.sourceDocIds = newVal.response.answer.documentIds;
var localCache = helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) && helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY)[this.$props.componentId];
if (localCache && localCache.meta && localCache.meta.hits) {
this.initialHits = localCache.meta.hits;
}
}
this.AISessionId = ((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).sessionId || (((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).response || {}).sessionId;
var messagesHistory = newVal.messages,
response = newVal.response;
var finalMessages = [];
if (response && response.error) {
this.error = {
message: response.error
};
}
// pushing message history so far
if (messagesHistory && Array.isArray(messagesHistory)) {
finalMessages.push.apply(finalMessages, messagesHistory.filter(function (msg) {
return msg.role !== constants.AI_ROLES.SYSTEM;
}));
if (finalMessages[0].role === constants.AI_ROLES.USER) {
finalMessages.shift();
}
} else if (response && response.answer && response.answer.text) {
finalMessages.push({
role: constants.AI_ROLES.ASSISTANT,
content: response.answer.text
});
if (!this.AISessionId) this.error = {
message: this.errorMessageForMissingSessionId
};
}
this.messages = finalMessages;
} else if (!newVal && !this.error) {
this.messages = [];
}
},
rawData: function rawData(newVal) {
this.$emit('on-data', {
data: this.messages,
rawData: newVal,
loading: this.isAIResponseLoading || this.$props.isLoading,
error: this.$props.AIResponseError
});
if (newVal && newVal.hits && newVal.hits.hits) {
this.initialHits = newVal.hits.hits;
}
},
isAIResponseLoading: function isAIResponseLoading(newVal) {
this.$emit('on-data', {
data: this.messages,
rawData: this.$props.rawData,
loading: newVal || this.isLoading,
error: this.$props.AIResponseError
});
},
isLoading: function isLoading(newVal) {
this.$emit('on-data', {
data: this.messages,
rawData: this.$props.rawData,
loading: newVal || this.isAIResponseLoading,
error: this.$props.AIResponseError
});
},
sessionIdFromStore: function sessionIdFromStore(newVal) {
if (newVal) {
this.sessionId = newVal;
}
},
AIResponseError: function AIResponseError(newVal) {
this.error = newVal;
this.AISessionId = ((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).sessionId || (((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).response || {}).sessionId;
if (this.error && !this.AISessionId) {
var errorMessage = this.errorMessageForMissingSessionId;
this.error = {
message: errorMessage
};
console.error(errorMessage);
}
this.$emit('on-data', {
data: this.messages,
rawData: this.$props.rawData,
loading: this.isAIResponseLoading || this.isLoading,
error: newVal
});
},
messages: function messages() {
this.scrollToBottom();
},
componentError: function componentError(newVal) {
var _this = this;
if (newVal && newVal._bodyBlob) {
this.AISessionId = ((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).sessionId || (((helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {})[this.$props.componentId] || {}).response || {}).sessionId;
if (!this.AISessionId) {
this.generateNewSessionId();
}
newVal._bodyBlob.text().then(function (textData) {
try {
var parsedErrorRes = JSON.parse(textData);
if (parsedErrorRes.error) {
_this.error = parsedErrorRes.error;
_this.$emit('on-data', {
data: _this.messages,
rawData: _this.$props.rawData,
loading: _this.$props.isAIResponseLoading || _this.$props.isLoading,
error: parsedErrorRes.error
});
}
} catch (error) {
console.error('Error parsing component error JSON:', error);
}
})["catch"](function (error) {
console.error('Error reading component error text data:', error);
});
}
},
showComponent: function showComponent() {
if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.QUESTION && this.$props.dependentComponentValue.endsWith('?')) {
this.isTriggered = true;
}
},
dependentComponentValue: function dependentComponentValue(newVal) {
if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.QUESTION && newVal && newVal.endsWith('?')) {
this.isTriggered = true;
if (this.AISessionId) {
this.handleSendMessage(null, false, '', true);
}
} else if (this.hasTriggered && this.$props.triggerOn !== constants.AI_TRIGGER_MODES.ALWAYS) {
this.isTriggered = false;
}
},
AISessionId: function AISessionId(newVal) {
if (newVal) {
if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.QUESTION && this.dependentComponentValue && this.dependentComponentValue.endsWith('?') || this.$props.triggerOn === constants.AI_TRIGGER_MODES.ALWAYS) {
this.handleSendMessage(null, false, '', true);
}
}
},
triggerOn: function triggerOn(newVal) {
if (newVal === constants.AI_TRIGGER_MODES.ALWAYS) {
this.isTriggered = true;
}
}
},
methods: {
renderTriggerMessageFunc: function renderTriggerMessageFunc() {
var triggerOn = this.$props.triggerOn;
if (this.$props.renderTriggerMessage) {
return this.$props.renderTriggerMessage;
}
if (this.$slots.renderTriggerMessage) {
return this.$slots.renderTriggerMessage();
}
if (triggerOn === constants.AI_TRIGGER_MODES.QUESTION) {
if (!this.dependentComponentValue.endsWith('?')) {
return vue.createVNode("span", null, [vue.createVNode("span", {
"role": "img",
"aria-label": "bulb"
}, [vue.createTextVNode("\uD83D\uDCA1")]), vue.createTextVNode("End your question with a question mark (?)")]);
}
} else if (triggerOn === constants.AI_TRIGGER_MODES.MANUAL) {
return vue.createVNode("span", null, [vue.createTextVNode("Click here to ask AI"), ' ', vue.createVNode("span", {
"role": "img",
"aria-label": "bulb"
}, [vue.createTextVNode("\uD83E\uDD16")])]);
}
return null;
},
handleTriggerClick: function handleTriggerClick() {
if (this.$props.triggerOn === constants.AI_TRIGGER_MODES.MANUAL) {
this.handleSendMessage(null, false, '', true);
this.isTriggered = true;
}
},
getAISourceObjects: function getAISourceObjects() {
var _this2 = this;
var sourceObjects = [];
if (!this.AIResponse) return sourceObjects;
var docIds = this.sourceDocIds || [];
if (this.initialHits) {
docIds.forEach(function (id) {
var foundSourceObj = _this2.initialHits.find(function (hit) {
return hit._id === id;
}) || {};
if (foundSourceObj) {
var _foundSourceObj$_sour = foundSourceObj._source,
_source = _foundSourceObj$_sour === void 0 ? {} : _foundSourceObj$_sour,
rest = _rollupPluginBabelHelpers._objectWithoutPropertiesLoose(foundSourceObj, _excluded);
sourceObjects.push(_rollupPluginBabelHelpers._extends({}, rest, _source));
}
});
} else {
sourceObjects.push.apply(sourceObjects, docIds.map(function (id) {
return {
_id: id
};
}));
}
return sourceObjects;
},
renderAIScreenFooter: function renderAIScreenFooter() {
var _slot2;
var _this3 = this;
var _ref = this.$props || {},
_ref$showSourceDocume = _ref.showSourceDocuments,
showSourceDocuments = _ref$showSourceDocume === void 0 ? true : _ref$showSourceDocume,
_ref$onSourceClick = _ref.onSourceClick,
onSourceClick = _ref$onSourceClick === void 0 ? function () {} : _ref$onSourceClick,
renderSourceDocument = _ref.renderSourceDocument;
var customRenderSourceDoc = renderSourceDocument || this.$slots.renderSourceDocument;
if (this.isLoadingState || this.isAITyping) {
return null;
}
var renderSourceDocumentLabel = function renderSourceDocumentLabel(sourceObj) {
if (customRenderSourceDoc) {
return customRenderSourceDoc(sourceObj);
}
return sourceObj._id;
};
return showSourceDocuments && Array.isArray(this.sourceDocIds) && this.sourceDocIds.length ? vue.createVNode(SearchBox.Footer, {
"themePreset": this.$props.themePreset,
"style": {
marginTop: '1.5rem',
background: 'inherit'
}
}, {
"default": function _default() {
return [vue.createTextVNode("Summary generated using the following sources:"), ' ', vue.createVNode(SearchBox.SourceTags, null, _isSlot(_slot2 = _this3.getAISourceObjects().map(function (el) {
var _slot;
return vue.createVNode(Button.Button, {
"class": "--ai-source-tag " + (helper.getClassName(_this3.$props.innerClass, 'ai-source-tag') || ''),
"info": true,
"onClick": function onClick() {
return onSourceClick && onSourceClick(el);
},
"key": el._id
}, _isSlot(_slot = renderSourceDocumentLabel(el)) ? _slot : {
"default": function _default() {
return [_slot];
}
});
})) ? _slot2 : {
"default": function _default() {
return [_slot2];
}
})];
}
}) : null;
},
generateNewSessionId: function generateNewSessionId() {
var _this4 = this;
var newSessionPromise = this.createAISession();
newSessionPromise.then(function (res) {
_this4.AISessionId = res.AIsessionId;
})["catch"](function (e) {
console.error(e);
});
},
scrollToBottom: function scrollToBottom() {
var _this5 = this;
this.$nextTick(function () {
var _this5$$refs;
var messageContainer = (_this5$$refs = _this5.$refs) == null ? void 0 : _this5$$refs[_this5.$props.innerRef];
if (messageContainer && messageContainer.$el) {
messageContainer.$el.scrollTo({
top: messageContainer.$el.scrollHeight,
behavior: 'smooth'
});
}
});
},
handleMessageInputChange: function handleMessageInputChange(e) {
this.inputMessage = e.target.value;
this.handleTextAreaHeightChange();
},
handleSendMessage: function handleSendMessage(e, isRetry, text, fetchMeta) {
if (isRetry === void 0) {
isRetry = false;
}
if (text === void 0) {
text = this.inputMessage;
}
if (fetchMeta === void 0) {
fetchMeta = false;
}
if (typeof e === 'object' && e !== null) e.preventDefault();
if (text.trim() || !text && !e) {
if (this.isLoadingState) {
return;
}
if (this.AISessionId) {
if (!isRetry) {
var finalMessages = [].concat(this.messages);
if (text) {
finalMessages.push({
content: text,
role: constants.AI_ROLES.USER
});
}
this.messages = [].concat(finalMessages);
}
this.getAIResponse(this.AISessionId, this.componentId, text, fetchMeta);
} else {
console.error(this.errorMessageForMissingSessionId);
this.error = {
message: "AISessionId for " + this.$props.componentId + " is missing! AIAnswer component requires an AISessionId to function. Trying reloading the App."
};
}
this.inputMessage = '';
}
},
handleRetryRequest: function handleRetryRequest() {
if (this.messages && !this.isLoadingState) {
var _this$messages;
var lastUserRequestMessage = (_this$messages = this.messages[this.messages.length - 1]) == null ? void 0 : _this$messages.content;
if (this.AISessionId) {
this.getAIResponse(this.AISessionId, this.componentId, lastUserRequestMessage);
this.inputMessage = '';
} else {
console.error("AISessionId for " + this.componentId + " is missing! AIAnswer component requires an AISessionId to function. Try reloading the App.");
}
}
},
renderErrorComponent: function renderErrorComponent() {
var renderError = this.$slots.renderError || this.$props.renderError;
if (this.error && !this.isLoadingState) {
var _this$error, _this$error2;
if (renderError) {
return vue.createVNode("div", {
"ref": _errorContainerRef,
"class": "--ai-answer-error-container " + (helper.getClassName(this.$props.innerClass, 'ai-error') || '')
}, [index.isFunction(renderError) ? renderError(this.error, this.handleRetryRequest) : renderError]);
}
return vue.createVNode("div", {
"ref": _errorContainerRef,
"class": "--ai-answer-error-container " + (helper.getClassName(this.$props.innerClass, 'ai-error') || '')
}, [vue.createVNode("div", {
"class": "--default-error-element"
}, [vue.createVNode("span", null, [(_this$error = this.error) != null && _this$error.message ? this.error.message : 'There was an error in generating the response.', ' ', (_this$error2 = this.error) != null && _this$error2.code ? ", Code:\n\t\t\t\t\t\t\t" + this.error.code : '']), this.AISessionId && vue.createVNode(Button.Button, {
"primary": true,
"onClick": this.handleRetryRequest
}, {
"default": function _default() {
return [vue.createTextVNode("Try again")];
}
})])]);
}
return null;
},
handleKeyPress: function handleKeyPress(e) {
if (e.key === 'Enter') {
this.handleSendMessage(e);
this.inputMessage = '';
}
},
renderIcon: function renderIcon() {
if (this.$props.showIcon) {
if (this.$props.icon) {
return this.$props.icon;
}
if (this.$slots.icon) {
return this.$slots.icon();
}
if (this.$props.iconURL) {
return vue.createVNode("img", {
"style": {
maxHeight: '25px'
},
"src": this.$props.iconURL,
"alt": "search-icon"
}, null);
}
return vue.createVNode(SearchBox.SearchSvg, null, null);
}
return null;
},
shouldMicRender: function shouldMicRender(showVoiceSearch) {
// checks for SSR
if (typeof window === 'undefined') return false;
return showVoiceSearch && (window.webkitSpeechRecognition || window.SpeechRecognition);
},
handleVoiceResults: function handleVoiceResults(_ref2) {
var results = _ref2.results;
if (results && results[0] && results[0].isFinal && results[0][0] && results[0][0].transcript && results[0][0].transcript.trim()) {
this.handleSendMessage(null, false, results[0][0].transcript.trim());
}
},
renderIcons: function renderIcons() {
var _this6 = this;
var _slot3, _slot4;
var _this$$props = this.$props,
getMicInstance = _this$$props.getMicInstance,
showVoiceInput = _this$$props.showVoiceInput,
iconPosition = _this$$props.iconPosition,
innerClass = _this$$props.innerClass;
var renderMic = this.$slots.renderMic || this.$props.renderMic;
return vue.createVNode("div", null, [vue.createVNode(CancelSvg.IconGroup, {
"enableAI": true,
"groupPosition": "right",
"positionType": "absolute"
}, {
"default": function _default() {
return [!_this6.isLoadingState && _this6.AISessionId && _this6.shouldMicRender(showVoiceInput) && vue.createVNode(SearchBox.Mic, {
"getInstance": getMicInstance,
"render": renderMic,
"handleResult": _this6.handleVoiceResults,
"class": helper.getClassName(innerClass, 'ai-search-mic') || null
}, null), iconPosition === 'right' && vue.createVNode(CancelSvg.IconWrapper, null, _isSlot(_slot3 = _this6.renderIcon()) ? _slot3 : {
"default": function _default() {
return [_slot3];
}
})];
}
}), vue.createVNode(CancelSvg.IconGroup, {
"enableAI": true,
"groupPosition": "left",
"positionType": "absolute"
}, {
"default": function _default() {
return [iconPosition === 'left' && vue.createVNode(CancelSvg.IconWrapper, null, _isSlot(_slot4 = _this6.renderIcon()) ? _slot4 : {
"default": function _default() {
return [_slot4];
}
})];
}
})]);
},
enterButtonOnClick: function enterButtonOnClick(e) {
this.handleSendMessage(e);
},
renderEnterButtonElement: function renderEnterButtonElement() {
var _this7 = this;
var _this$$props2 = this.$props,
enterButton = _this$$props2.enterButton,
innerClass = _this$$props2.innerClass;
var renderEnterButton = this.$slots.renderEnterButton;
if (enterButton) {
var getEnterButtonMarkup = function getEnterButtonMarkup() {
if (renderEnterButton) {
return renderEnterButton(_this7.enterButtonOnClick);
}
return vue.createVNode(SearchBox.SendButton, {
"primary": true,
"type": "submit",
"tabIndex": 0,
"onClick": _this7.handleSendMessage,
"onKeyPress": _this7.handleKeyPress,
"class": "ask-btn " + helper.getClassName(innerClass, 'ai-enter-button'),
"disabled": _this7.isLoadingState || !_this7.AISessionId
}, {
"default": function _default() {
return [vue.createTextVNode("Send")];
}
});
};
return vue.createVNode("div", {
"class": "ai-enter-button-wrapper"
}, [getEnterButtonMarkup()]);
}
return null;
},
getComponent: function getComponent() {
var data = {
error: this.AIResponseError,
loading: this.isAIResponseLoading,
data: this.messages,
rawData: this.rawData
};
return index.getComponent(data, this);
},
handleTextAreaHeightChange: function handleTextAreaHeightChange() {
var _this$$refs, _this$$refs2, _this$$refs3;
var textArea = (_this$$refs = this.$refs) == null || (_this$$refs = _this$$refs[_inputRef]) == null ? void 0 : _this$$refs.$el;
var inputWrapper = (_this$$refs2 = this.$refs) == null || (_this$$refs2 = _this$$refs2[_inputWrapperRef]) == null ? void 0 : _this$$refs2.$el;
var errorContainer = (_this$$refs3 = this.$refs) == null ? void 0 : _this$$refs3[_errorContainerRef];
if (textArea) {
textArea.style.height = '42px';
var lineHeight = parseInt(getComputedStyle(textArea).lineHeight, 10);
var maxHeight = lineHeight * 11; // max height for 10 lines
var height = Math.min(textArea.scrollHeight, maxHeight);
textArea.style.height = height + "px";
textArea.style.overflowY = height === maxHeight ? 'auto' : 'hidden';
// wrapper around input/ textarea
inputWrapper.style.height = height + "px";
// adjust error-container
if (errorContainer) {
errorContainer.style.bottom = height + "px";
}
this.$forceUpdate();
}
},
getTitle: function getTitle() {
var _this8 = this;
var hasTitle = this.$props.title || this.$slots.title || null;
if (hasTitle) {
return vue.createVNode(Title.Title, {
"class": helper.getClassName(this.$props.innerClass, 'ai-title') || null
}, {
"default": function _default() {
return [_this8.$props.title || _this8.$slots.title()];
}
});
}
return null;
}
},
beforeUnmount: function beforeUnmount() {
if (this.$props.clearSessionOnDestroy) {
// cleanup logic
// final Object to store in local storage cache
var finalCacheObj = helper.getObjectFromLocalStorage(constants.AI_LOCAL_CACHE_KEY) || {};
// delete current component's cache
delete finalCacheObj[this.$props.componentId];
// update local cache
helper.setObjectInLocalStorage(constants.AI_LOCAL_CACHE_KEY, finalCacheObj);
}
},
render: function render() {
var _slot5;
var _this9 = this;
var props = this.$props;
if (!this.shouldShowComponent) {
return null;
}
if (!this.isTriggered) {
return vue.createVNode(SearchBox.Chatbox, {
"style": props.style || {}
}, {
"default": function _default() {
return [_this9.getTitle(), vue.createVNode("div", {
"class": "--trigger-message-wrapper",
"onClick": _this9.handleTriggerClick,
"aria-hidden": "true"
}, [_this9.renderTriggerMessageFunc()])];
}
});
}
return vue.createVNode(SearchBox.Chatbox, {
"style": props.style || {}
}, {
"default": function _default() {
return [_this9.getTitle(), vue.createVNode(SearchBox.ChatContainer, {
"class": "--ai-chat-container",
"theme": props.theme,
"showInput": props.showInput
}, {
"default": function _default() {
return [_this9.hasCustomRenderer && vue.createVNode(SearchBox.MessagesContainer, {
"themePreset": _this9.themePreset,
"theme": props.theme,
"ref": _this9.$props.innerRef,
"class": "--ai-message-container " + (helper.getClassName(props.innerClass, 'ai-message-container') || '')
}, _isSlot(_slot5 = _this9.getComponent()) ? _slot5 : {
"default": function _default() {
return [_slot5];
}
}), !_this9.hasCustomRenderer && vue.createVNode(SearchBox.MessagesContainer, {
"themePreset": _this9.themePreset,
"theme": props.theme,
"ref": _this9.$props.innerRef,
"class": "--ai-message-container " + (helper.getClassName(props.innerClass, 'ai-message-container') || '')
}, {
"default": function _default() {
return [_this9.messages.map(function (message, index) {
return vue.createVNode(SearchBox.Message, {
"key": index,
"isSender": message.role === constants.AI_ROLES.USER,
"innerHTML": md.render(message.content),
"themePreset": _this9.themePreset,
"theme": props.theme,
"class": "--ai-answer-message " + (helper.getClassName(props.innerClass, 'ai-message') || '')
}, null);
}), _this9.isLoadingState && vue.createVNode(SearchBox.Message, {
"themePreset": _this9.themePreset,
"theme": props.theme,
"isSender": false,
"class": "--ai-answer-message " + (helper.getClassName(props.innerClass, 'ai-message') || null)
}, {
"default": function _default() {
return [vue.createVNode(SearchBox.TypingIndicator, null, {
"default": function _default() {
return [vue.createVNode(SearchBox.TypingDot, {
"themePreset": _this9.themePreset
}, null), vue.createVNode(SearchBox.TypingDot, {
"themePreset": _this9.themePreset
}, null), vue.createVNode(SearchBox.TypingDot, {
"themePreset": _this9.themePreset
}, null)];
}
})];
}
})];
}
}), _this9.renderErrorComponent(), ' ', props.showFeedback && !_this9.isLoadingState && !_this9.isAITyping && vue.createVNode("div", {
"class": "--ai-answer-feedback-container " + (helper.getClassName(props.innerClass, 'ai-feedback') || '')
}, [vue.createVNode(SearchBox.AIFeedback, {
"hideUI": _this9.isLoadingState || !_this9.sessionId,
"key": _this9.sessionId,
"onFeedbackSubmit": function onFeedbackSubmit(useful, reason) {
_this9.trackUsefullness(_this9.sessionId, {
useful: useful,
reason: reason
});
}
}, null)]), ' ', _this9.renderAIScreenFooter(), props.showInput && !_this9.isLoadingState && !_this9.isAITyping && vue.createVNode(SearchBox.MessageInputContainer, {
"class": "--ai-input-container",
"onSubmit": _this9.handleSendMessage
}, {
"default": function _default() {
return [vue.createVNode(SearchBox.InputGroup, {
"enableAI": true,
"isOpen": false
}, {
"default": function _default() {
return [vue.createVNode(CancelSvg.InputWrapper, {
"ref": _inputWrapperRef
}, {
"default": function _default() {
return [vue.createVNode(SearchBox.MessageInput, {
"ref": _inputRef,
"placeholder": props.placeholder,
"enterButton": props.enterButton,
"value": _this9.inputMessage,
"onInput": _this9.handleMessageInputChange,
"id": props.componentId + "-ai-input",
"showIcon": props.showIcon,
"iconPosition": props.iconPosition,
"themePreset": _this9.themePreset,
"disabled": _this9.isLoadingState || !_this9.AISessionId,
"class": helper.getClassName(props.innerClass, 'ai-input') || null
}, null), ' ', _this9.renderIcons()];
}
})];
}
}), _this9.renderEnterButtonElement()];
}
}), ' '];
}
})];
}
});
}
});
AIAnswer.hasInternalComponent = function () {
return true;
};
var mapStateToProps = function mapStateToProps(state, props) {
var dependencyComponent = Object.values(props.react)[0];
if (Array.isArray(dependencyComponent)) {
// eslint-disable-next-line prefer-destructuring
dependencyComponent = dependencyComponent[0];
}
var showComponent = !!(state.selectedValues[dependencyComponent] && state.selectedValues[dependencyComponent].value);
var dependentComponentValue = state.selectedValues[dependencyComponent] && state.selectedValues[dependencyComponent].value || '';
return {
showComponent: showComponent,
dependentComponentValue: dependentComponentValue,
AIResponse: state.AIResponses[props.componentId] && state.AIResponses[props.componentId].response,
isAIResponseLoading: state.AIResponses[props.componentId] && state.AIResponses[props.componentId].isLoading,
AIResponseError: state.AIResponses[props.componentId] && state.AIResponses[props.componentId].error,
rawData: state.rawData[props.componentId],
themePreset: state.config.themePreset,
isLoading: state.isLoading[props.componentId] || false,
sessionIdFromStore: state.AIResponses[props.componentId] && state.AIResponses[props.componentId].response && state.AIResponses[props.componentId].response.sessionId || '',
componentError: state.error[props.componentId] || null,
isAITyping: state.AIResponses[props.componentId] && state.AIResponses[props.componentId].response && state.AIResponses[props.componentId].response.isTyping || false
};
};
var mapDispatchToProps = {
getAIResponse: function getAIResponse(sessionId, componentId, message, shouldFetchMeta) {
if (shouldFetchMeta === void 0) {
shouldFetchMeta = false;
}
return query.fetchAIResponse(sessionId, componentId, message, null, shouldFetchMeta);
},
trackUsefullness: analytics.recordAISessionUsefulness,
createAISession: query.createAISession
};
var AIConnected = PreferencesConsumer.PreferencesConsumer(ComponentWrapper.ComponentWrapper(index.connect(mapStateToProps, mapDispatchToProps)(AIAnswer), {
componentType: constants.componentTypes.AIAnswer,
internalComponent: true
}));
AIConnected.name = AIAnswer.name;
AIConnected.hasInternalComponent = AIAnswer.hasInternalComponent;
AIConnected.install = function (Vue) {
Vue.component(AIConnected.name, AIConnected);
};
// Add componentType for SSR
AIConnected.componentType = constants.componentTypes.AIAnswer;
var _templateObject, _templateObject2;
var HierarchicalMenuList = vueEmotion.styled('ul')(_templateObject || (_templateObject = _rollupPluginBabelHelpers._taggedTemplateLiteralLoose(["\n\tlist-style: none;\n\tpadding: 0;\n\tmargin: 0;\n\tmax-height: 0;\n\toverflow: hidden;\n\n\t&.--open {\n\t\tmax-height: 100%;\n\t}\n"])));
var HierarchicalMenuListItem = vueEmotion.styled('li')(_templateObject2 || (_templateObject2 = _rollupPluginBabelHelpers._taggedTemplateLiteralLoose(["\n\tfont-weight: 400;\n\tline-height: 1.5;\n\tbox-sizing: border-box;\n\n\ta {\n\t\tcolor: #424242;\n\t\ttext-decoration: none;\n\t\tgap: 5px;\n\t\t.--leaf-icon,\n\t\t.--folder-icon {\n\t\t\tline-height: 15px;\n\t\t\tsvg {\n\t\t\t\theight: 15px;\n\t\t\t}\n\t\t}\n\n\t\tinput {\n\t\t\tmargin: 0;\n\t\t\tcursor: pointer;\n\t\t}\n\t}\n\n\t.--switcher-icon {\n\t\ttransition: all 0.2s ease-in;\n\t\tmargin-right: 2px;\n\t}\n\t.--list-child {\n\t\tpadding-left: 1rem;\n\t\tposition: relative;\n\t\t&:before {\n\t\t\theight: 100%;\n\t\t\tcontent: '';\n\t\t\tposition: absolute;\n\t\t\tborder-left: 1px solid #787878;\n\t\t\twidth: 0;\n\t\t\tleft: 19px;\n\t\t\t", ";\n\t\t}\n\n\t\t&.--show-switcher-icon {\n\t\t\tpadding-left: 36px;\n\t\t}\n\t}\n\t.--list-item-label {\n\t\tline-height: 100%;\n\t}\n\t.--list-item-count {\n\t\tmargin-left: 10px;\n\t\tpadding: 0.1rem 0.4rem;\n\t\tfont-size: 0.8rem;\n\t\tcolor: #424242;\n\t\tbackground-color: #dee1e6;\n\t\tborder-radius: 8px;\n\t}\n\t&.-selected-item {\n\t\tfont-weight: 700 !important;\n\t}\n\t&.-expanded-item {\n\t\t& > a {\n\t\t\t& div > .--switcher-icon {\n\t\t\t\ttransform: rotate(90deg);\n\t\t\t}\n\t\t}\n\t}\n\t.--list-item-label-count-wrapper {\n\t\tdisplay: flex;\n\t\talign-items: center;\n\t\t&:hover {\n\t\t\t.--list-item-count,\n\t\t\t.--list-item-label {\n\t\t\t\tfont-weight: 700;\n\t\t\t}\n\t\t}\n\t}\n"])), function (props) {
return !props.showLine && "\n\t\t\t\t\tdisplay: none;\n\t\t\t\t";
});
var HierarchicalMenuListItemComponent = {
name: 'HierarchicalMenuListItemComponent',
data: function data() {
return {
isExpanded: false,
newParentPath: ''
};
},
created: function created() {
var listItemLabel = this.listItem.key;
var newParentPath = listItemLabel;
if (this.parentPath) {
newParentPath = "" + this.parentPath + constants.TREELIST_VALUES_PATH_SEPARATOR + listItemLabel;
}
this.newParentPath = newParentPath;
this.isExpanded = !!helper.recLookup(this.selectedValues, newParentPath, constants.TREELIST_VALUES_PATH_SEPARATOR);
},
watch: {
listItem: function listItem(newVal) {
if (newVal.initiallyExpanded) {
this.isExpanded = newVal.initiallyExpanded;
}
},
selectedValues: function selectedValues(newVal) {
this.isExpanded = !!helper.recLookup(newVal, this.newParentPath, constants.TREELIST_VALUES_PATH_SEPARATOR);
}
},
props: {
parentPath: types.string,
selectedValues: types.rawData,
mode: types.string,
searchTerm: types.string,
listItem: types.rawData,
showLine: types.bool,
renderItem: types.func,
handleListItemClick: types.func,
renderSwitcherIcon: types.func,
showCheckbox: VueTypes.bool,
innerClass: types.style,
showRadio: VueTypes.bool,
renderIcon: types.func,
showCount: VueTypes.bool,
showSwitcherIcon: types.bool,
switcherIcon: types.children
},
render: function render() {
var _this = this;
var _this$$props = this.$props,
selectedValues = _this$$props.selectedValues,
mode = _this$$props.mode,
searchTerm = _this$$props.searchTerm,
listItem = _this$$props.listItem,
parentPath = _this$$props.parentPath,
showLine = _this$$props.showLine,
renderItem = _this$$props.renderItem,
handleListItemClick = _this$$props.handleListItemClick,
showCheckbox = _this$$props.showCheckbox,
innerClass = _this$$props.innerClass,
showRadio = _this$$props.showRadio,
renderIcon = _this$$props.renderIcon,
showCount = _this$$props.showCount,
showSwitcherIcon = _this$$props.showSwitcherIcon;
if (!(listItem instanceof Object) || Object.keys(listItem).length === 0) {
return null;
}
var listItemLabel = listItem.key;
var listItemCount = listItem.count;
var isLeafNode = !(Array.isArray(listItem.list) && listItem.list.length > 0);
var renderSwitcherIcon = function renderSwitcherIcon(isExpandedProp) {
if (showSwitcherIcon === false) {
return null;
}
var switcherIcon = _this.$props.switcherIcon;
if (switcherIcon) return switcherIcon(isExpandedProp);
return (
/* eslint-disable jsx-a11y/click-events-have-key-events
, jsx-a11y/no-static-element-interactions,jsx-a11y/no-noninteractive-tabindex */
vue.createVNode("span", {
"tabIndex": "0",
"onClick": function onClick(e) {
e.stopPropagation();
_this.isExpanded = !_this.isExpanded;
},
"class": "--switcher-icon"
}, [vue.createTextVNode("\u27A4")])
);
};
var isSelected = false;
if (mode === 'single') {
if (helper.recLookup(selectedValues, this.newParentPath, constants.TREELIST_VALUES_PATH_SEPARATOR) === true) {
isSelected = true;
}
} else {
isSelected = !!helper.recLookup(selectedValues, this.newParentPath, constants.TREELIST_VALUES_PATH_SEPARATOR);
}
return vue.createVNode(HierarchicalMenuListItem, {
"class": (isSelected ? '-selected-item' : '') + " " + (this.isExpanded ? '-expanded-item' : ''),
"key": this.newParentPath,
"showLine": showLine
}, {
"default": function _default() {
return [vue.createVNode(ListItem.ListItem, {
"isTreeListItem": true,
"onClick": function onClick() {
handleListItemClick(listItemLabel, parentPath);
},
"style": {
textDecoration: 'none'
}
}, {
"default": function _default() {
return [renderItem ? renderItem(listItemLabel, listItemCount, isSelected) : vue.createVNode(Flex.Flex, {
"alignItems": "center",
"gap": "5px"
}, {
"default": function _default() {
return [!isLeafNode && renderSwitcherIcon(isSelected), mode === 'multiple' && showCheckbox && vue.createVNode(Flex.Flex, {
"alignItems": "center",
"gap": "5px"
}, {
"default": function _default() {
return [vue.createVNode(FormControlList.Checkbox, {
"type": "checkbox",
"class": helper.getClassName(innerClass, 'checkbox') || null,
"checked": isSelected,
"id": listItemLabel + "-checkbox-" + _this.newParentPath,
"name": listItemLabel + "-checkbox-" + _this.newParentPath,
"show": true,
"readOnly": true
}, null), vue.createVNode("label", {
"style": {
width: '26px',
marginTop: 0,
marginBottom: 0,
marginRight: '-9px',
left: '-3px'
},
"htmlFor": listItemLabel + "-checkbox-" + _this.newParentPath,
"onClick": function onClick(e) {
e.stopPropagation();
}
}, null)];
}
}), mode === 'single' && showRadio && vue.createVNode(Flex.Flex, {
"alignItems": "center",
"gap": "5px"
}, {
"default": function _default() {
return [vue.createVNode(FormControlList.Radio, {
"checked": isSelected,
"class": helper.getClassName(innerClass, 'radio') || null,
"id": listItemLabel + "-radio-" + _this.newParentPath,
"name": listItemLabel + "-radio-" + _this.newParentPath,
"show": true,
"readOnly": true,
"type": "radio"
}, null), vue.createVNode("label", {
"style": {
width: '26px',
marginTop: 0,
marginBottom: 0,
marginRight: '-9px',
left: '-3px'
},
"htmlFor": listItemLabel + "-radio-" + _this.newParentPath,
"onClick": function onClick(e) {
e.stopPropagation();
}
}, null)];
}
}), ' ', renderIcon(isLeafNode), vue.createVNode("div", {
"class": "--list-item-label-count-wrapper"
}, [vue.createVNode("span", {
"class": "--list-item-label " + (helper.getClassName(innerClass, 'label') || '')
}, [listItemLabel]), showCount && vue.createVNode("span", {
"class": "--list-item-count " + (helper.getClassName(innerClass, 'count') || '')
}, [listItemCount])])];
}
})];
}
}), isLeafNode === false && vue.createVNode("div", {
"class": "--list-child " + (showSwitcherIcon ? ' --show-switcher-icon' : '')
}, [vue.createVNode(HierarchicalMenuComponent, {
"key": _this.newParentPath + "-" + listItemLabel + "-" + listItemCount,
"listArray": listItem.list,
"parentPath": _this.newParentPath,
"isExpanded": _this.isExpanded,
"listItemProps": {
mode: mode,
selectedValues: selectedValues,
searchTerm: searchTerm,
showLine: showLine,
renderItem: renderItem,
handleListItemClick: handleListItemClick,
renderSwitcherIcon: renderSwitcherIcon,
showCheckbox: showCheckbox,
innerClass: innerClass,
showRadio: showRadio,
renderIcon: renderIcon,
showCount: showCount,
showSwitcherIcon: showSwitcherIcon,
switcherIcon: _this.$props.switcherIcon
}
}, null)])];
}
});
}
};
function _isSlot$1(s) {
return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !vue.isVNode(s);
}
var HierarchicalMenuComponent = {
name: 'HierarchicalMenuComponent',
props: {
listArray: VueTypes.arrayOf(VueTypes.object),
// array of objects
parentPath: VueTypes.string.def(''),
isExpanded: VueTypes.bool.def(false),
listItemProps: types.rawData
},
render: function render() {
var _slot;
var _this$$props = this.$props,
listArray = _this$$props.listArray,
isExpanded = _this$$props.isExpanded,
parentPath = _this$$props.parentPath,
listItemProps = _this$$props.listItemProps;
if (!Array.isArray(listArray) || listArray.length === 0) {
return null;
}
return vue.createVNode(HierarchicalMenuList, {
"class": "" + (isExpanded ? '--open' : ''),
"isSelected": isExpanded
}, _isSlot$1(_slot = listArray.map(function (listItem) {
return vue.createVNode(HierarchicalMenuListItemComponent, vue.mergeProps({
"key": parentPath + "__" + JSON.stringify(listItem),
"parentPath": parentPath,
"listItem": listItem
}, listItemProps), null);
})) ? _slot : {
"default": function _default() {
return [_slot];
}
});
}
};
function _isSlot$2(s) {
return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !vue.isVNode(s);
}
var updateQueryAction = reactivecore.Actions.updateQuery,
setQueryOptions = reactivecore.Actions.setQueryOptions;
var transformValueIntoLocalState = function transformValueIntoLocalState(valueArray) {
var valueToSet = {};
if (valueArray.length) {
var newSelectedValues = {};
valueArray.forEach(function (valueItem) {
helper.setDeep(newSelectedValues, valueItem.split(' > '), !helper.recLookup(newSelectedValues, valueItem.split(' > '), constants.TREELIST_VALUES_PATH_SEPARATOR), true);
});
valueToSet = newSelectedValues;
}
return valueToSet;
};
var TreeList = {
name: 'TreeList',
props: {
selectedValue: vueTypes.types.selectedValue,
error: vueTypes.types.title,
rawData: vueTypes.types.rawData,
aggregationData: vueTypes.types.rawData,
themePreset: vueTypes.types.themePreset,
updateQueryAction: vueTypes.types.funcRequired,
setQueryOptions: vueTypes.types.funcRequired,
// component props
componentId: vueTypes.types.string.isRequired,
className: vueTypes.types.string,
style: vueTypes.types.style,
showRadio: VueTypes.bool.def(false),
showCheckbox: vueTypes.types.bool.def(false),
mode: VueTypes.oneOf(['single', 'multiple']).def('multiple'),
showCount: VueTypes.bool.def(false),
showSearch: VueTypes.bool.def(false),
showIcon: VueTypes.bool.def(false),
icon: vueTypes.types.children,
showLeafIcon: VueTypes.bool.def(false),
leafIcon: vueTypes.types.children,
showLine: VueTypes.bool.def(false),
switcherIcon: vueTypes.types.func,
render: vueTypes.types.func,
renderItem: vueTypes.types.func,
innerClass: vueTypes.types.style,
placeholder: vueTypes.types.string,
title: vueTypes.types.title,
isLoading: vueTypes.types.bool,
dataField: vueTypes.types.stringArray.isRequired,
onQueryChange: vueTypes.types.func,
defaultValue: vueTypes.types.stringArray,
value: vueTypes.types.stringArray,
customQuery: vueTypes.types.func,
defaultQuery: vueTypes.types.func,
enableAppbase: vueTypes.types.bool,
index: vueTypes.types.string,
showFilter: vueTypes.types.bool,