Skip to content

poc: interact with collections as a hierarchical attribute #6421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/js/getting-started/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ <h1 class="header-title">
</div>

<div class="search-panel__results">
<div id="breadcrumb" style="margin-bottom: 1rem"></div>
<div id="searchbox"></div>
<div id="hits"></div>
<div id="pagination"></div>
Expand Down
40 changes: 24 additions & 16 deletions examples/js/getting-started/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@ import { liteClient as algoliasearch } from 'algoliasearch/lite';
import instantsearch from 'instantsearch.js';
import { carousel } from 'instantsearch.js/es/templates';
import {
breadcrumb,
configure,
hierarchicalMenu,
hits,
pagination,
panel,
refinementList,
searchBox,
trendingItems,
} from 'instantsearch.js/es/widgets';

import 'instantsearch.css/themes/satellite.css';

const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
'LOEC74WPH7',
'3b38713a560044da51e7b1e56fac000f'
);

const search = instantsearch({
indexName: 'instant_search',
indexName: 'pokedex-fr',
searchClient,
insights: true,
collection: 'Gen 1 > Pokémon Souris',
});

search.addWidgets([
Expand All @@ -33,13 +35,18 @@ search.addWidgets([
templates: {
item: (hit, { html, components }) => html`
<article>
<h1>
<a href="/products.html?pid=${hit.objectID}"
>${components.Highlight({ hit, attribute: 'name' })}</a
>
</h1>
<p>${components.Highlight({ hit, attribute: 'description' })}</p>
<a href="/products.html?pid=${hit.objectID}">See product</a>
<div style="display: flex; align-items: center">
<img
src=${hit.sprites.regular}
alt=${hit.name.fr}
style="margin-right: 1rem"
width="64"
/>
<div>
<h2>${components.Highlight({ hit, attribute: 'name.fr' })}</h2>
<p>${components.Highlight({ hit, attribute: 'category' })}</p>
</div>
</div>
</article>
`,
},
Expand All @@ -49,9 +56,11 @@ search.addWidgets([
}),
panel({
templates: { header: 'brand' },
})(refinementList)({
})(hierarchicalMenu)({
container: '#brand-list',
attribute: 'brand',
}),
breadcrumb({
container: '#breadcrumb',
}),
pagination({
container: '#pagination',
Expand All @@ -64,10 +73,9 @@ search.addWidgets([
<div>
<article>
<div>
<img src="${item.image}" />
<h2>${item.name}</h2>
<img src="${item.sprites.regular}" />
<h2>${item.name.fr}</h2>
</div>
<a href="/products.html?pid=${item.objectID}">See product</a>
</article>
</div>
`,
Expand Down
57 changes: 36 additions & 21 deletions examples/react/getting-started/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import {
Hits,
InstantSearch,
Pagination,
RefinementList,
SearchBox,
TrendingItems,
Carousel,
Breadcrumb,
HierarchicalMenu,
} from 'react-instantsearch';

import { Panel } from './Panel';
Expand All @@ -20,8 +21,8 @@ import 'instantsearch.css/themes/satellite.css';
import './App.css';

const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
'LOEC74WPH7',
'3b38713a560044da51e7b1e56fac000f'
);

export function App() {
Expand All @@ -42,18 +43,20 @@ export function App() {
<div className="container">
<InstantSearch
searchClient={searchClient}
indexName="instant_search"
indexName="pokedex-fr"
insights={true}
collection="Gen 1 > Pokémon Souris"
>
<Configure hitsPerPage={8} />
<div className="search-panel">
<div className="search-panel__filters">
<Panel header="brand">
<RefinementList attribute="brand" />
<HierarchicalMenu />
</Panel>
</div>

<div className="search-panel__results">
<Breadcrumb style={{ marginBottom: '1rem' }} />
<SearchBox placeholder="" className="searchbox" />
<Hits hitComponent={HitComponent} />

Expand All @@ -76,36 +79,48 @@ export function App() {
}

type HitType = Hit<{
image: string;
name: string;
description: string;
category: string;
name: {
fr: string;
};
pokedex_id: number;
sprites: {
regular: string;
};
}>;

function HitComponent({ hit }: { hit: HitType }) {
return (
<article>
<h1>
<a href={`/products.html?pid=${hit.objectID}`}>
<Highlight attribute="name" hit={hit} />
</a>
</h1>
<p>
<Highlight attribute="description" hit={hit} />
</p>
<a href={`/products.html?pid=${hit.objectID}`}>See product</a>
<div style={{ display: 'flex', alignItems: 'center' }}>
<img
src={hit.sprites.regular}
alt={hit.name.fr}
style={{ marginRight: '1rem' }}
width="64"
/>
<div>
<h2>
{/* @ts-ignore */}
<Highlight attribute="name.fr" hit={hit} /> ({hit.pokedex_id})
</h2>
<p>
<Highlight attribute="category" hit={hit} />
</p>
</div>
</div>
</article>
);
}

function ItemComponent({ item }: { item: Hit }) {
function ItemComponent({ item }: { item: HitType }) {
return (
<div>
<article>
<div>
<img src={item.image} />
<h2>{item.name}</h2>
<img src={item.sprites.regular} />
<h2>{item.name.fr}</h2>
</div>
<a href={`/products.html?pid=${item.objectID}`}>See product</a>
</article>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export type BreadcrumbConnectorParams = {
/**
* Attributes to use to generate the hierarchy of the breadcrumb.
*/
attributes: string[];
attributes?: string[];

/**
* Prefix path to use if the first level is not the root level.
Expand Down Expand Up @@ -111,21 +111,16 @@ const connectBreadcrumb: BreadcrumbConnector = function connectBreadcrumb(

return (widgetParams) => {
const {
attributes,
attributes: providedAttributes,
separator = ' > ',
rootPath = null,
transformItems = ((items) => items) as NonNullable<
BreadcrumbConnectorParams['transformItems']
>,
} = widgetParams || {};

if (!attributes || !Array.isArray(attributes) || attributes.length === 0) {
throw new Error(
withUsage('The `attributes` option expects an array of strings.')
);
}

const [hierarchicalFacetName] = attributes;
let attributes = providedAttributes || [];
let [hierarchicalFacetName] = attributes || [];

function getRefinedState(
state: SearchParameters,
Expand Down Expand Up @@ -256,7 +251,24 @@ const connectBreadcrumb: BreadcrumbConnector = function connectBreadcrumb(
);
},

getWidgetSearchParameters(searchParameters, { uiState }) {
getWidgetSearchParameters(searchParameters, { collection, uiState }) {
if (
!hierarchicalFacetName &&
!collection &&
(!Array.isArray(attributes) || attributes.length === 0)
) {
throw new Error(
withUsage('The `attributes` option expects an array of strings.')
);
}

if (!hierarchicalFacetName && collection) {
attributes = Array(5)
.fill(undefined)
.map((_, i) => `_collections.lvl${i}`);
hierarchicalFacetName = attributes[0];
}

const values =
uiState.hierarchicalMenu &&
uiState.hierarchicalMenu[hierarchicalFacetName];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export type HierarchicalMenuConnectorParams = {
/**
* Attributes to use to generate the hierarchy of the menu.
*/
attributes: string[];
attributes?: string[];
/**
* Separator used in the attributes to separate level values.
*/
Expand Down Expand Up @@ -171,7 +171,7 @@ const connectHierarchicalMenu: HierarchicalMenuConnector =

return (widgetParams) => {
const {
attributes,
attributes: providedAttributes,
separator = ' > ',
rootPath = null,
showParentLevel = true,
Expand All @@ -184,16 +184,6 @@ const connectHierarchicalMenu: HierarchicalMenuConnector =
>,
} = widgetParams || {};

if (
!attributes ||
!Array.isArray(attributes) ||
attributes.length === 0
) {
throw new Error(
withUsage('The `attributes` option expects an array of strings.')
);
}

if (showMore === true && showMoreLimit <= limit) {
throw new Error(
withUsage('The `showMoreLimit` option must be greater than `limit`.')
Expand All @@ -209,7 +199,8 @@ const connectHierarchicalMenu: HierarchicalMenuConnector =
// we need to provide a hierarchicalFacet name for the search state
// so that we can always map $hierarchicalFacetName => real attributes
// we use the first attribute name
const [hierarchicalFacetName] = attributes;
let attributes = providedAttributes || [];
let [hierarchicalFacetName] = attributes || [];

let sendEvent: HierarchicalMenuRenderState['sendEvent'];

Expand Down Expand Up @@ -409,7 +400,25 @@ const connectHierarchicalMenu: HierarchicalMenuConnector =
);
},

getWidgetSearchParameters(searchParameters, { uiState }) {
getWidgetSearchParameters(searchParameters, { collection, uiState }) {
if (
!hierarchicalFacetName &&
!collection &&
(!Array.isArray(attributes) || attributes.length === 0)
) {
throw new Error(
withUsage('The `attributes` option expects an array of strings.')
);
} else {
}

if (!hierarchicalFacetName && collection) {
attributes = Array(5)
.fill(undefined)
.map((_, i) => `_collections.lvl${i}`);
hierarchicalFacetName = attributes[0];
}

const values =
uiState.hierarchicalMenu &&
uiState.hierarchicalMenu[hierarchicalFacetName];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,18 +193,29 @@ export default (function connectTrendingItems<
return recommendState.removeParams(this.$$id!);
},

getWidgetParameters(state) {
getWidgetParameters(state, { collection }) {
const collectionParameters = collection
? {
facetFilters: [
`_collections.lvl${
collection.split(' > ').length - 1
}:${collection}`,
],
}
: {};
return state.removeParams(this.$$id!).addTrendingItems({
facetName: facetName as string,
facetValue: facetValue as string,
maxRecommendations: limit,
threshold,
fallbackParameters: {
...fallbackParameters,
...collectionParameters,
...(escapeHTML ? TAG_PLACEHOLDER : {}),
},
queryParameters: {
...queryParameters,
...collectionParameters,
...(escapeHTML ? TAG_PLACEHOLDER : {}),
},
$$id: this.$$id!,
Expand Down
3 changes: 3 additions & 0 deletions packages/instantsearch.js/src/lib/InstantSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ export type InstantSearchOptions<
// @MAJOR: Remove legacy behaviour here and in algoliasearch-helper
persistHierarchicalRootCount?: boolean;
};

collection?: string;
};

export type InstantSearchStatus = 'idle' | 'loading' | 'stalled' | 'error';
Expand Down Expand Up @@ -345,6 +347,7 @@ See documentation: ${createDocumentationLink({
this.mainHelper = null;
this.mainIndex = index({
indexName,
collection: options.collection,
});
this.onStateChange = onStateChange;

Expand Down
Loading