UNPKG

cozy-search

Version:

UI components about search bar and IA assistant

59 lines (47 loc) 2.25 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = require("react"); var _reactRouterDom = require("react-router-dom"); var _AssistantProvider = require("../components/AssistantProvider"); var _helpers = require("../components/helpers"); var useConversation = function useConversation() { var navigate = (0, _reactRouterDom.useNavigate)(); var location = (0, _reactRouterDom.useLocation)(); var _useAssistant = (0, _AssistantProvider.useAssistant)(), setIsOpenSearchConversation = _useAssistant.setIsOpenSearchConversation; // `useNavigate()` returns a new function whenever the location changes, and // `location` itself changes on every navigation. Keep both in refs so // `goToConversation` can stay referentially stable across renders. A stable // callback is required for `React.memo` on the conversation list items to // actually skip re-renders on every conversation switch. var navigateRef = (0, _react.useRef)(navigate); var locationRef = (0, _react.useRef)(location); (0, _react.useEffect)(function () { navigateRef.current = navigate; locationRef.current = location; }, [navigate, location]); var goToConversation = (0, _react.useCallback)(function (conversationId) { var _match$; var loc = locationRef.current; // Extract base path safely by identifying the start of '/assistant' if it exists. var match = loc.pathname.match(/^(.*?)(\/assistant(\/|$).*|$)/); var basePath = ((_match$ = match === null || match === void 0 ? void 0 : match[1]) !== null && _match$ !== void 0 ? _match$ : loc.pathname).replace(/\/$/, ''); var newPathname = "".concat(basePath, "/assistant/").concat(conversationId); setIsOpenSearchConversation(false); navigateRef.current({ pathname: newPathname, search: loc.search, hash: loc.hash }); }, [setIsOpenSearchConversation]); var createNewConversation = (0, _react.useCallback)(function () { goToConversation((0, _helpers.makeConversationId)()); }, [goToConversation]); return { goToConversation: goToConversation, createNewConversation: createNewConversation }; }; var _default = useConversation; exports.default = _default;