UNPKG

react-instantsearch-nextjs

Version:
77 lines (74 loc) 3.39 kB
import { _ as _$1 } from '@swc/helpers/esm/_object_spread.js'; import { _ } from '@swc/helpers/esm/_type_of.js'; import historyRouter from 'instantsearch.js/es/lib/routers/history.js'; import { usePathname, useSearchParams } from 'next/navigation.js'; import { useRef, useEffect } from 'react'; import { useNextHeaders } from './useNextHeaders.js'; function useInstantSearchRouting(passedRouting, isMounting) { var isServer = typeof window === 'undefined'; var pathname = usePathname(); var searchParams = useSearchParams(); var routingRef = useRef(null); var onUpdateRef = useRef(null); var isUnmounting = useRef(false); // Skip the on-mount fire of the effect below: `subscribe()` already merges // the URL into `_initialUiState`, and a redundant `setUiState` can wipe the // URL with a nested `<Index>` (see #6980). var previousRouteRef = useRef(null); useEffect(function() { var _ref; var currentRoute = "".concat(pathname !== null && pathname !== void 0 ? pathname : '', "?").concat((_ref = searchParams === null || searchParams === void 0 ? void 0 : searchParams.toString()) !== null && _ref !== void 0 ? _ref : ''); if (previousRouteRef.current === currentRoute) { return; } var isFirstRun = previousRouteRef.current === null; previousRouteRef.current = currentRoute; if (isFirstRun) { return; } if (onUpdateRef.current) { onUpdateRef.current(); } }, [ pathname, searchParams ]); useEffect(function() { isUnmounting.current = false; return function() { isUnmounting.current = true; }; }); var headers = useNextHeaders(); if (passedRouting && !routingRef.current) { var browserHistoryOptions = {}; browserHistoryOptions.getLocation = function() { if (isServer) { var url = "".concat((headers === null || headers === void 0 ? void 0 : headers.get('x-forwarded-proto')) || 'http', "://").concat(headers === null || headers === void 0 ? void 0 : headers.get('host')).concat(pathname, "?").concat(searchParams); return new URL(url); } if (isMounting.current) { return new URL("".concat(window.location.protocol, "//").concat(window.location.host).concat(pathname, "?").concat(searchParams)); } return window.location; }; browserHistoryOptions.push = function push(url) { // This is to skip the push with empty routeState on dispose as it would clear params set on a <Link> if (this.isDisposed && isUnmounting.current) { return; } history.pushState({}, '', url); }; browserHistoryOptions.start = function start(onUpdate) { onUpdateRef.current = onUpdate; }; routingRef.current = {}; if ((typeof passedRouting === "undefined" ? "undefined" : _(passedRouting)) === 'object') { browserHistoryOptions = _$1({}, browserHistoryOptions, passedRouting.router); routingRef.current.stateMapping = passedRouting.stateMapping; } routingRef.current.router = historyRouter(browserHistoryOptions); } return routingRef.current; } export { useInstantSearchRouting };