FoldedResultList

Example Implementation

folded-result-list.fn.tsx

import {useEffect, useState, FunctionComponent} from 'react';
import {
  FoldedResult,
  FoldedResultList as HeadlessFoldedResultList,
} from '@coveo/headless';
import {ResultLink} from '../result-list/result-link';
 
interface FoldedResultListProps {
  controller: HeadlessFoldedResultList;
}
 
export const FoldedResultList: FunctionComponent<FoldedResultListProps> = (
  props
) => {
  const {controller} = props;
  const [state, setState] = useState(controller.state);
 
  useEffect(() => controller.subscribe(() => setState(controller.state)), []);
 
  function renderFoldedResults(results: FoldedResult[]) {
    return results.map(({result, children}) => (
      <li key={result.uniqueId}>
        <article>
          <h3>
            {/* Make sure to log analytics when the result link is clicked. */}
            <ResultLink result={result}>{result.title}</ResultLink>
          </h3>
          <p>{result.excerpt}</p>
          <ul>{renderFoldedResults(children)}</ul>
        </article>
      </li>
    ));
  }
 
  if (!state.results.length) {
    return <div>No results</div>;
  }
 
  return (
    <div>
      <ul style={{textAlign: 'left'}}>
        {state.results.map((collection) => (
          <li key={collection.result.uniqueId}>
            <article>
              <h3>
                {/* Make sure to log analytics when the result link is clicked. */}
                <ResultLink result={collection.result}>
                  {collection.result.title}
                </ResultLink>
              </h3>
              <p>{collection.result.excerpt}</p>
              <ul>{renderFoldedResults(collection.children)}</ul>
              {collection.moreResultsAvailable && (
                <button
                  disabled={collection.isLoadingMoreResults}
                  onClick={() => controller.loadCollection(collection)}
                >
                  Show more
                </button>
              )}
            </article>
          </li>
        ))}
      </ul>
    </div>
  );
};
 
// usage
 
/**
 * ```tsx
 * const controller = buildFoldedResultList(engine);
 *
 * <FoldedResultList controller={controller} />;
 * ```
 */

The FoldedResultList headless controller re-organizes results into hierarchical collections (a.k.a. threads).

Methods

fetchMoreResults

Using the same parameters as the last successful query, fetch another batch of results, if available. Particularly useful for infinite scrolling, for example.

This method is not compatible with the Pager controller.

findResultByCollection

Finds a folded result by its collection.

Parameters

  • collection: FoldedCollection

    The folded collection whose collection name will be used to find a collection in the results.

Returns FoldedResult | null: The FoldedResult associated with the collection’s name.

findResultById

Finds a folded result by its unique ID.

Parameters

  • collection: FoldedCollection

    The folded collection whose ID will be used to find a collection in the results.

Returns FoldedResult | null: The FoldedResult associated with the collection’s ID.

loadCollection

Loads all the folded results for a given collection.

Parameters

logShowLessFoldedResults

Logs a custom event when a user shows less folded results.

logShowMoreFoldedResults

Logs a click event when a user loads/shows more folded results.

Parameters

  • result: Result

    The result to send analytics for.

subscribe

Adds a callback that’s invoked on state change.

Parameters

  • listener: () => void

    A callback that’s invoked on state change.

Returns Unsubscribe: A function to remove the listener.

Attributes

state

The state of the FoldedResultList controller.

Properties

  • moreResultsAvailable: boolean

    Whether more results are available, using the same parameters as the last successful query.

    This property is not compatible with the Pager controller.

  • results: FoldedCollection[]

    The ordered list of collections.

  • searchResponseId: string

    The unique identifier of the response where the results were fetched, this value does not change when loading more results.

  • searchUid: string

    The unique identifier of the last executed search.

  • firstSearchExecuted: boolean

    Determines if a first search has been executed.

  • hasError: boolean

    true if there is an error for the last executed query and false otherwise.

  • hasResults: boolean

    Determines if there are results available for the last executed query.

  • isLoading: boolean

    Determines if a search is in progress.

Initialize

buildFoldedResultList

Creates a FoldedResultList controller instance.

Parameters

  • engine: SearchEngine

    The headless engine.

  • props: FoldedResultListProps

    The configurable FoldedResultList properties.

Returns FoldedResultList

FoldedResultListProps

The configurable FoldedResultList properties.

Properties

FoldedResultListOptions

The options for the FoldedResultList controller.

Properties

  • folding?: FoldingOptions

  • fieldsToInclude?: string[]

    A list of indexed fields to include in the objects returned by the result list. These results are included in addition to the default fields. If this is left empty only the default fields are included.

FoldedCollection

Properties

  • isLoadingMoreResults: boolean

    Whether there is an ongoing query to add more results to the collection.

  • moreResultsAvailable: boolean

    Whether more results might be available in the collection.

  • children: FoldedResult[]

    The children of this result sorted in the same order as the search results.

  • result: Result

    The result at this position in the collection.

FoldedResult

Properties

  • children: FoldedResult[]

    The children of this result sorted in the same order as the search results.

  • result: Result

    The result at this position in the collection.

FoldedResult | null

Properties

  • children: FoldedResult[]

    The children of this result sorted in the same order as the search results.

  • result: Result

    The result at this position in the collection.

FoldingOptions

Properties

  • childField?: string

    The name of the field that uniquely identifies a result within a collection.

    Default: foldingchild

  • collectionField?: string

    The name of the field on which to do the folding. The folded result list component will use the values of this field to resolve the collections of result items.

    Default: foldingcollection

  • numberOfFoldedResults?: number

    The number of child results to fold under the root collection element, before expansion.

    Default: 2

  • parentField?: string

    The name of the field that determines whether a certain result is a top result containing other child results within a collection.

    Default: foldingparent

HighlightKeyword

Properties

  • length: number

    The length of the offset.

  • offset: number

    The 0 based offset inside the string where the highlight should start.

Raw

Properties

  • [key: string]: unknown

    Custom keys that depend on the documents in the index.

Result

Properties

  • absentTerms: string[]

    The basic query expression terms which this query result item does not match. Note: This property is populated by terms from the query pipeline-processed q value (not from the original q value).

  • clickUri: string

    The hyperlinkable item URI. Notes: Use the clickUri value when you want to create hyperlinks to the item, rather than the uri or printableUri value.

  • excerpt: string

    The contextual excerpt generated for the item (see the excerptLength query parameter).

  • excerptHighlights: HighlightKeyword[]

    The length and offset of each word to highlight in the item excerpt string.

  • firstSentences: string

    The first sentences retrieved from the item (see the retrieveFirstSentences query parameter).

  • firstSentencesHighlights: HighlightKeyword[]

    The length and offset of each word to highlight in the item firstSentences string.

  • flags: string

    The flags that are set on the item by the index. Distinct values are separated by semicolons.

  • hasHtmlVersion: boolean

    Whether the index contains an HTML version of this item.

  • isRecommendation: boolean

    Whether the item score was boosted as a Coveo ML recommendation.

  • isTopResult: boolean

    Whether the item score was boosted by a featured result rule in the query pipeline.

  • percentScore: number

    The item ranking score expressed as a percentage (see the sortCriteria and rankingFunctions query parameters).

  • printableUri: string

    The human readable item URI. Note: Avoid using the printableUri value to create hyperlinks to the item. Use the clickUri value instead.

  • printableUriHighlights: HighlightKeyword[]

    The length and offset of each word to highlight in the item printableUri string.

  • rankingInfo: string | null

    The raw debug information generated by the index to detail how the item was ranked. This property is null unless the debug query parameter is set to true.

  • raw: Raw

    The values of the fields which were retrieved for this item (see the fieldsToInclude and fieldsToExclude query parameters).

  • score: number

    The total ranking score computed for the item (see the sortCriteria and rankingFunctions query parameters).

  • summary: null

    The item summary (see the summaryLength query parameter).

  • summaryHighlights: HighlightKeyword[]

    The length and offset of each word to highlight in the item summary string.

  • title: string

    Contains the title of the item.

  • titleHighlights: HighlightKeyword[]

    The length and offset of each word to highlight in the item title string.

  • uniqueId: string

    The unique item identifier. You should consider the uniqueId value as an opaque string.

  • uri: string

    The item URI. Notes: Avoid using the uri value to create hyperlinks to the item. Use the clickUri value instead.

  • rankingModifier?: string

    If applicable, represents the type of ranking modification that was applied to this result.

Unsubscribe

Call signatures

  • (): void

What's next for me?