File size: 6,388 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
import { isIndexWidget } from 'instantsearch.js/es/lib/utils/index';
import React from 'react';
import {
InstantSearchServerContext,
InstantSearchSSRProvider,
} from 'react-instantsearch-hooks';
import type { InitialResults, InstantSearch, UiState } from 'instantsearch.js';
import type { IndexWidget } from 'instantsearch.js/es/widgets/index/index';
import type { ReactNode } from 'react';
import type {
InstantSearchServerContextApi,
InstantSearchServerState,
} from 'react-instantsearch-hooks';
type SearchRef = { current: InstantSearch | undefined };
export type RenderToString = (element: JSX.Element) => unknown;
export type GetServerStateOptions = {
renderToString?: RenderToString;
};
/**
* Returns the InstantSearch server state from a component.
*/
export function getServerState(
children: ReactNode,
options: GetServerStateOptions = {}
): Promise<InstantSearchServerState> {
const searchRef: SearchRef = {
current: undefined,
};
const notifyServer: InstantSearchServerContextApi<
UiState,
UiState
>['notifyServer'] = ({ search }) => {
searchRef.current = search;
};
return importRenderToString(options.renderToString)
.then((renderToString) => {
return execute({
children,
renderToString,
searchRef,
notifyServer,
}).then((serverState) => ({ serverState, renderToString }));
})
.then(({ renderToString, serverState }) => {
let shouldRefetch = false;
// <DynamicWidgets> requires another query to retrieve the dynamic widgets
// to render.
walkIndex(searchRef.current!.mainIndex, (index) => {
shouldRefetch =
shouldRefetch ||
index
.getWidgets()
.some((widget) => widget.$$type === 'ais.dynamicWidgets');
});
if (shouldRefetch) {
return execute({
children: (
<InstantSearchSSRProvider {...serverState}>
{children}
</InstantSearchSSRProvider>
),
renderToString,
searchRef,
notifyServer,
});
}
return serverState;
});
}
type ExecuteArgs = {
children: ReactNode;
renderToString: RenderToString;
notifyServer: InstantSearchServerContextApi<UiState, UiState>['notifyServer'];
searchRef: SearchRef;
};
function execute({
children,
renderToString,
notifyServer,
searchRef,
}: ExecuteArgs) {
renderToString(
<InstantSearchServerContext.Provider value={{ notifyServer }}>
{children}
</InstantSearchServerContext.Provider>
);
// We wait for the component to mount so that `notifyServer()` is called.
return new Promise((resolve) => setTimeout(resolve, 0))
.then(() => {
// If `notifyServer()` is not called by then, it means that <InstantSearch>
// wasn't within the `children`.
// We decide to go with a strict behavior in that case; throwing. If users have
// some routes that don't mount the <InstantSearch> component, they would need
// to try/catch the `getServerState()` call.
// If this behavior turns out to be too strict for many users, we can decide
// to warn instead of throwing.
if (!searchRef.current) {
throw new Error(
"Unable to retrieve InstantSearch's server state in `getServerState()`. Did you mount the <InstantSearch> component?"
);
}
return waitForResults(searchRef.current);
})
.then(() => {
const initialResults = getInitialResults(searchRef.current!.mainIndex);
return {
initialResults,
};
});
}
/**
* Waits for the results from the search instance to coordinate the next steps
* in `getServerState()`.
*/
function waitForResults(search: InstantSearch) {
const helper = search.mainHelper!;
helper.searchOnlyWithDerivedHelpers();
return new Promise<void>((resolve, reject) => {
// All derived helpers resolve in the same tick so we're safe only relying
// on the first one.
helper.derivedHelpers[0].on('result', () => {
resolve();
});
// However, we listen to errors that can happen on any derived helper because
// any error is critical.
helper.derivedHelpers.forEach((derivedHelper) =>
derivedHelper.on('error', (error) => {
reject(error);
})
);
});
}
/**
* Recurse over all child indices
*/
function walkIndex(
indexWidget: IndexWidget,
callback: (widget: IndexWidget) => void
) {
callback(indexWidget);
return indexWidget.getWidgets().forEach((widget) => {
if (!isIndexWidget(widget)) {
return;
}
callback(widget);
walkIndex(widget, callback);
});
}
/**
* Walks the InstantSearch root index to construct the initial results.
*/
function getInitialResults(rootIndex: IndexWidget): InitialResults {
const initialResults: InitialResults = {};
walkIndex(rootIndex, (widget) => {
const searchResults = widget.getResults()!;
initialResults[widget.getIndexId()] = {
// We convert the Helper state to a plain object to pass parsable data
// structures from server to client.
state: { ...searchResults._state },
results: searchResults._rawResults,
};
});
return initialResults;
}
function importRenderToString(
renderToString?: RenderToString
): Promise<RenderToString> {
if (renderToString) {
return Promise.resolve(renderToString);
}
// eslint-disable-next-line no-console
console.warn(
'[InstantSearch] `renderToString` should be passed to getServerState(<App/>, { renderToString })'
);
// React pre-18 doesn't use `exports` in package.json, requiring a fully resolved path
// Thus, only one of these imports is correct
const modules = ['react-dom/server.js', 'react-dom/server'];
// import is an expression to make sure https://github.com/webpack/webpack/issues/13865 does not kick in
return Promise.all(modules.map((mod) => import(mod).catch(() => {}))).then(
(imports: unknown[]) => {
const ReactDOMServer = imports.find(
(mod): mod is { renderToString: RenderToString } => mod !== undefined
);
if (!ReactDOMServer) {
throw new Error(
'Could not import ReactDOMServer. You can provide it as an argument: getServerState(<Search />, { renderToString }).'
);
}
return ReactDOMServer.renderToString;
}
);
}
|