Skip to main content

API

The FindkitUI constructor supports following options for customization

const ui = new FindkitUI({
publicToken: "<TOKEN>",
minTerms: 0,
// ...
});

Constructor Options

api docs

publicToken: string

The public token which identifies the Findkit Project. This can be seen from the Hub or with findkit status CLI command.

This is the only required option.

api docs

minTerms: number

Search terms threshold when to make the search request. Defaults to 3. Can be set to 0 as well when a search will be then made immediately when the UI is rendered.

api docs

css: string

Inject custom styles to the Shadow Root. See Styling.

api docs

backdrop: boolean

New in v0.18.0

Show backdrop shadow when opened as a modal.

Default false

api docs

closeOnOutsideClick: boolean

New in v0.18.0

Close the modal when a non-focus traped element is clicked.

Default false

api docs

lockScroll: boolean

Lock page scrolling. Only used with mode: "modal". Defaults to true. You may want set this to false when using the Offset Modal Pattern with page scrolling.

Use this CSS to enable page scrolling:

.findkit--modal-container {
inset: initial;
position: absolute;
width: 100%;
}
api docs

shadowDom: boolean

Enable or disable shadow dom. See Styling.

Defaults to true.

api docs

cssLayers: boolean

Enable or disable CSS Layers. See Styling.

Defaults to true.

api docs

slots: object

Inject custom components to into the UI. See Slot Overrides.

api docs

params: object

Customize search request params. See Search Params.

api docs

groups: object[]

Group search results. See Groups.

api docs

groupOrder: "relevancy" | "static" | (a: GroupResults,b: GroupResults)=>number

Group order logic. Defaults to "static" which preserves groups array order.

In "relevancy" mode groups are ordered based on the groups highest score. Relevancy mode can be affected by groups' option relevancyBoost, which is multiplied with the result relevancy

New in v0.20.0

Also supports custom sort function which receives GroupResults objects as the arguments.

api docs

infiniteScroll: boolean

Disable automatic result loading on scroll and require button click to load more results.

api docs

forceHistoryReplace: boolean

New in v0.12.0

Set to true to force history.replaceState usage instead of history.pushState with querystring and hash routers. Normally FindkitUI uses History push when opening the modal so it can be closed using the browser back button.

This is set to true when the container option is used.

When using frontend frameworks such as Next.js that control the routing too this can be used to fix navigation conflicts with the FindkitUI router with the caveat of disabling the back button modal close.

api docs

manageScroll: boolean

New in v0.12.0

Manage scroll position by restoring it when user navigates back to the FindkitUI view. Generally no need to disable this but if you have other conflicting libraries or frameworks it might be helpful to disable it.

Defaults to true

api docs

instanceId: string

When using multiple FindkitUI instances you must provide a custom instanceId to avoid conflicts in the query strings and idendifying class names. This is needed for example when you have global site search and a more specific search running on the same page.

Empty string in instanceId or instanceId consisting of only whitespace characters will cause an error. If you would like to remove instanceId from the query parameters see searchKey.

note

If you have only one search setup and you are getting an error about a conflicting instance id it means you are accidentally doing multiple new Findkit() calls without calling .dispose() on the previous instance.

Hot Module Reloading

If you are using hot module loading you might need to dispose the UI instance when the module is disposed:

// Vite
import.meta.hot?.dispose(() => {
ui.dispose();
});

// Webpack, Next.js etc.
module.hot?.dispose(() => {
ui.dispose();
});

React Component

If you are creating the FindkitUI instance inside a React component you must call the dispose method on a useEffect cleanup. See the React custom container example. :::

Defaults to "fdk".

api docs

load: Function

Custom async function for loading the implemention code. See Disable CDN.

api docs

searchEndpoint: string

Send search requests to this custom endpoint.

api docs

container: selectorOrElement

Render the modal to a custom container. If not defined Findkit UI will create one dynamically and appends it to <body>.

Can be defined as a CSS selector or as an Element object.

Automatically sets modal: false if not explicitly defined.

api docs

Open the search in a <dialog> overlaying the page. This is the default mode.

Set to false to disable the modal mode. This makes sense only when used with a custom container with the container option.

See the inert option for modal focus trapping behaviour customization.

api docs

Set to false to hide the default modal header with the search input and the close button. Useful with the non-fullscreen embedding patterns where the input is placed on the website outside the Findkit UI context. Ex. in the site header.

api docs

router: Router

Possible values:

  • "querystring" (default)
  • "hash"
  • "memory"

See Routing.

danger

If you use WordPress router: "hash" is recommended as query string routing collides with the Interactivity API routing. See the issue 60455 for details.

api docs

fetchCount: number

How many results to fetch in a single request.

api docs

lang: string

New in v0.5.0

Set the UI language. If not defined the language is read from the <html lang> attribute. See setLang. Not to be confused with the lang search param filter.

Replaces deprecated ui.lang in v0.5.0

api docs

translations: object

New in v0.5.0

Add the UI translations. See addTranslation.

See TranslationStrings for the available transtion strings.

Example

const ui = new FindkitUI({
publicToken: "<TOKEN>",
lang: "sv",
// Add translations
translations: {
sv: {
close: "Stänga",
// ... https://findk.it/strings
},
},
});

Replaces deprecated ui.overrides in v0.5.0

api docs

monitorDocumentLang: boolean

New in v0.5.0

Update the UI language by monitoring <html lang> changes. Useful on Single-Page Apps where the language can change without a page load.

Defaults to true

api docs

fetchThrottle: boolean

New in v0.9.0

Minimum time between search requests in milliseconds.

Defaults to 200

api docs

defaultCustomRouterData: object

New in v0.9.0

Default values to to emit from the custom-router-data event when setCustomRouterData has not been called.

api docs

builtinStyles: boolean

New in v0.21.0

Enable or disable loading of the built-in styles. Useful when you want total control over the UI styles or you want to load the styles with your own bundler.

Defaults to true

api docs

separator: string

New in v1.0.0

Set namespacing separator for the query string. Eg. the _ in ?fdk_q=. Defaults to "_". Used in the custom router keys as well.

searchKey: string

New in v1.5.0

Set namespacing search key for the query string. searchKey replaces the default instanceId + separator + q e.g. the fdk_q in ?fdk_q=test.

note

Findkit prefixes query parameters by default to prevent clashing with other systems. E.g. WordPress will capture ?s= query string if the default search is not disabled.

groupKey: string

New in v1.5.0

Set namespacing group key for the query string. groupKey replaces the deault instanceId + separator + id Eg. the fdk_id in ?fdk_q=test&fdk_id=group-1.

customRouterDataPrefix: string

New in v1.5.0

Set namespacing prefix for the custom router data keys in the query string.

The prefix is used detect which keys belong to the FindkitUI instance if there are multiple FindkitUI instances or other code using query string keys for other purposes.

Default instanceId + separator + c + separator

Example: By default, custom data keys follow the format fdk_c_mykey. If you set the prefix to ns-, the keys will be formatted as ns-mykey.

inert: string | boolean

New in v1.0.0

Control how the elements outside the modal are made inert when using modal: true. An inert element is an element which cannot be focused or accessed using a screen reader. This is used to trap the focus and screen readers inside the modal when it is open.

  • inert: true: Make all element outside the modal inert using the <dialog>.showModal() method.
  • inert: string: CSS selector to make the matching elements inert. The <dialog> is opened with the .open() method. Use when you want to put the search input outside the modal. See the Offset modal pattern.
  • inert: false: Do not make any elements inert.

Defaults to true

Example:

const ui = new FindkitUI({
publicToken: "<token>",
inert: "main, footer",
});

ui.bindInput("header input[type=search]");
api docs

Methods

Following methods are available on the FindkitUI instance.

api docs

.open(terms)

Open the search modal. If search terms are passed in the input will populated with it and a search request is made immediately.

.toggle()

New in v0.18.0

Toggle the modal open / closed state.

api docs

Make a search with the given search terms. Opens the modal if closed (and not using modal: false). Populates all bound inputs with the given search terms.

api docs

.openFrom(selectorOrElement)

Open the modal from the given element or elements. Select can be a Element object or a CSS selector string. A cleanup function is returned which will unbind all the event listeners when called.

If the given element contains data-clicked="true" the modal will be opened immediately. This is useful on slow network situations when the user manages to click the open button before the code loads. Use inline JavaScript to add the attribute to ensure it is always added when clicked.

<button type="button" onclick="this.dataset.clicked=true">
Open Search Modal
</button>

The attribute handling was added in v0.17.0

api docs

.trapFocus(selectorOrElement)

🚨 Removed in v1.0.0!

Use the inert option instead.

Add additional elements to the focus trap. For example if you want to add close button outside of the modal use this to make it keyboard accessible.A function is returned which will remove the element from the focus trap when invoked.

.setCustomRouterData(data)

New in v0.9.0

Set custom data to the Findkit Router. The value is flushed to the url only when a search request is made. Eg. usually should be called right before updateParams or updateGroups or in the fetch event.

The object values can only be strings. In Typescript terms the data type is {[key: string]: string }.

api docs

.bindInput(selectorOrElement)

Bind any input to the Search UI. The selector can be CSS string or the raw HTMLInputElement. An unbind funtion is returned.

  • Input value is throttled to UI search terms
  • Focus is included in the focus trap
  • The lazy load will be triggered when the input is focused
api docs

.preload(): Promise

Preload the implementation code and css. This is automatically called on mouseover for elements passed to .openFrom() and on focus for inputs passed to .bindInput().

api docs

.close()

Close the search modal.

api docs

.activateGroup(idOrIndex)

New in v0.20.0

Activate a group by id or index. The ui will be navigated to the group. When in modal mode it does not open the modal. Call open manually to open it.

api docs

.clearGroup()

New in v0.20.0

Clear active group. The ui will be navigated to the multi-group view.

api docs

.dispose()

Close the search modal and discard the FindkitUI instance with its resources. The modal cannot be opened any more after it is disposed.

api docs

.updateParams(fnOrParams)

Update the search params. It calls the given function immediately giving the search params object as the first parameter. The object can mutated or a new one can be returned. A new search request is sent when the updated params differ from the previously used params.

Calls are throttled with leading invoke, meaning that the first call is made immediately and subsequent calls every 200ms or what is defined in fetchThrottle.

Example

ui.updateParams((params) => {
params.filter.category = "kitchen";
});

It is also possible to replace the params completely by giving the params object directly

ui.updateParams({ filter: { category: "kitchen" } });

There is also useParams() hook for slot overrides.

api docs

.updateGroups(fn)

Group version of updateParams which operates on groups instead of single Search Params object. The groups are spread to the function arguments.

Example

const ui = new FindkitUI({
publicToken: "<TOKEN>",
groups: [
{ params: { filter: { tags: "html" } } },
{ params: { filter: { tags: "pdf" } } },
],
});

ui.updateGroups((pages, pdf) => {
pages.previewSize = 5;
pdf.previewSize = 5;
});

There is also useGroups() hook for slot overrides.

api docs

.setLang(lang)

New in v0.5.0

Set the current UI language. See lang.

api docs

.addTranslation(lang, translation)

New in v0.5.0

Args

  • language: string
  • overrides: {[key: string]: string}: Override the build-in translations
  • custom: {[key: string]: string}: Add custom translation keys

Add a new UI translation. Can be used to override existing translation strings as well. See available translation strings here.

See translations.

api docs

.on()

Args

  • eventName: string
  • callback: (event) => void

Bind event handler to an event. Returns an unbind function. See Events.

api docs

.once()

Args

  • eventName: string
  • callback: (event) => void

Like .on() but unbound immediately after the first event. See Events.

api docs

Properties

.params

The current Search Params

api docs

.groups

The current Groups

api docs

.usedTerms

New in v1.3.0

The search terms used on the last completed search request. For next terms see .nextTerms.

.nextTerms

New in v1.3.0

The next terms the search will be performed with. Updated immediately on input changes and on .search() calls. Once the search completes and they are no longer pending search terms, and this will be the same as the .usedTerms prop.

The search terms in the URL are populated to this value on initialization. Readable after loaded or custom-router-data events.

.customRouterData

New in v1.2.0

The current custom router data. Read only, use setCustomRouterData to update it.

Readable only after the loaded event. Throws before that. Force the event by calling preload. You may check .loaded to see if it has been loaded already.

api docs

.loaded

New in v1.2.0

True when the implementation code and css are loaded. The loaded event is fired when this turn to true.

Force loading with the preload method.

api docs