"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useChatConfig = void 0; var _react = require("react"); var _services = require("../../services"); var _get_chat_context = require("./get_chat_context"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ const MESSAGE_WIDGET_READY = 'driftWidgetReady'; const MESSAGE_IFRAME_READY = 'driftIframeReady'; const MESSAGE_RESIZE = 'driftIframeResize'; const MESSAGE_SET_CONTEXT = 'driftSetContext'; /** * Hook which handles positioning and communication with the chat widget. */ const useChatConfig = ({ onReady = () => {}, onResize = () => {} }) => { const ref = (0, _react.useRef)(null); const chat = (0, _services.useChat)(); const [style, setStyle] = (0, _react.useState)({ height: 0, width: 0 }); const [isReady, setIsReady] = (0, _react.useState)(false); const [isResized, setIsResized] = (0, _react.useState)(false); (0, _react.useEffect)(() => { const handleMessage = event => { const { current: chatIframe } = ref; if (!chat || !(chatIframe !== null && chatIframe !== void 0 && chatIframe.contentWindow) || event.source !== (chatIframe === null || chatIframe === void 0 ? void 0 : chatIframe.contentWindow)) { return; } const context = (0, _get_chat_context.getChatContext)(); const { data: message } = event; const { user: userConfig } = chat; const { id, email, jwt, trialEndDate, kbnVersion, kbnBuildNum } = userConfig; switch (message.type) { // The IFRAME is ready to receive messages. case MESSAGE_IFRAME_READY: { const user = { id, attributes: { email, trial_end_date: trialEndDate, kbn_version: kbnVersion, kbn_build_num: kbnBuildNum }, jwt }; chatIframe.contentWindow.postMessage({ type: MESSAGE_SET_CONTEXT, data: { context, user } }, '*'); break; } // Drift is attempting to resize the IFRAME based on interactions with // its interface. case MESSAGE_RESIZE: { const styles = message.data.styles || {}; setStyle({ ...style, ...styles }); if (!isResized) { setIsResized(true); } onResize(); break; } // The chat widget is ready. case MESSAGE_WIDGET_READY: setIsReady(true); onReady(); default: break; } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); }, [chat, style, onReady, onResize, isReady, isResized]); if (chat) { return { enabled: true, src: chat.chatURL, ref, style, isReady, isResized }; } return { enabled: false }; }; exports.useChatConfig = useChatConfig;