This is the site for the beta version of Stork Search. Take me back to stable!

Javascript API Reference

Just getting started? Learn how to embed the search interface on your site.

The Stork Javascript library exposes a single global variable, stork, which exposes methods for working with Stork search indexes.

The method you'll most likely use is the register() method, which takes three parameters:

stork.register(name, url, options)

This method initializes Stork, downloads your search index, and harnesses the DOM to make the search elements interactive.

  • The name parameter is a string that defines which HTML elements Stork should attach to. This name should be the same as the name you put in the data-stork attributes in your input and output elements.
  • The url parameter is a string that contains the URL of your index file. The file at this URL should be a Stork index file generated by the stork build command.
  • The options parameter is an optional object. Any properties of the Registration Options object or the UI Options object may be accepted.
stork.register(
    "registration-name"
    "https://my-site.com/search-index.st",
    {
        forceRefreshIndex: false,
        strings: {
            attribution: "Powered by Stork",
            closeButtonSvg: `<svg>...</svg>`,
            queryTooShort: "Searching...",
        },
        generateMessage: (totalResultCount, duration) => {
            return `${totalResultCount} results in ${duration} milliseconds`
        },
        onQueryUpdate: (query) => {
            console.log(query)
        },
        onResultSelected: (query, result) => {
            return analytics.log(`User selected ${result.entry.url} searching for ${query}`);
        },
        transformResultUrl: (url) => url,
        excerptLength: 150,
        numberOfResults: 10,
        numberOfExcerpts: 5
    }
)

stork.register() is an "all-in-one" method that handles three different steps behind the scenes. To control each step individually, there are other methods on the stork global variable that let you initiate each step of the Stork UI framework lifecycle. For more information on how to use these methods, read the advanced JavaScript Usage documentation.

stork.initialize(wasm_url)

Loads and prepares the WASM library for use.

The optional wasm_url parameter lets you specify a URL from which the WASM binary should be downloaded. When omitted, Stork will load the appropriate WASM binary from the Stork CDN.

This function returns a promise resolves with an object which contains the version and source URL of the loaded WASM blob, for debugging purposes.

If the promise fails, the WASM blob was not loaded successfully and you are able to call stork.initialize() again.

If the promise succeeds, any subsequent calls to stork.initialize() will not have any effect. The returned promise will resolve immediately with the loaded WASM blob's debugging information.

If stork.initialize() is called before the previous invocation's promise completes, the function will return with the in-flight promise.

stork.downloadIndex(name, url, options)

Downloads a search index file from the given URL.

This function returns a promise which resolves with the search index's statistics, for debugging purposes. After the promise resolves, you will be able to run search queries with the given index identifier, either via the stork.search() function or via the attached <input> tag.

This promise may fail for one of several reasons:

  • This function was called before stork.initialize() was called
  • The index file could not be fetched at the given URL.
  • The index file was downloaded, but could not be parsed by the WASM binary
  • The WASM binary failed to load successfully, and the promise returned by stork.initialize() threw an error

If the promise fails, you can try calling stork.downloadIndex() again. If you call stork.downloadIndex() with the same index identifier and the index file has already been downloaded, Stork will use the same index binary unless {forceRefreshIndex: true} is included in the passed-in config.

After the promise succeeds, any subsequent calls to stork.downloadIndex() with the same index identifier will have no effect, unless {forceRefreshIndex: true} is passed into the config, even if the given URL is different. When forceRefreshIndex is true, the index will be re-downloaded and reloaded into the WASM.

If you call stork.downloadIndex() before a previous call with the same index identifier has finished (i.e. before the promise has resolved or thrown), the function will not perform any actions, and will return with the previous in-flight promise.

Registration Options

The following fields can be used to configure the Stork index downloading behavior, and should be passed into the stork.downloadIndex() method as the third parameter.

forceRefreshIndexboolean, Default: false

If true, you will be able to re-register indexes with the same name. If false, re-registering an index with the same name as an already-registered index will throw an error.

stork.attach(name, options)

Harnesses existing DOM elements on the page to display live search results based on the query typed into an <input> tag.

This function will look for two elements in the current DOM. Given the index identifier myIndex, this function will expect:

  • An <input> tag with the attribute data-stork="myIndex"
  • A <div> tag with the attribute data-stork="myIndex-output"

These elements can be anywhere in the current DOM tree; they don't need to be near each other.

This function doesn't return a value, but will throw if there is a problem. This function will throw if:

  • It is called before stork.downloadIndex() is called
  • The required elements cannot be found

Calling this function will have no effect if a previous call to stork.attach() with the same index identifier was successful and the given elements have already been harnessed. To refresh the Stork-managed DOM, either refresh the page, or:

  1. Remove all the elements with the data-stork attribute, and their children
  2. Add back your <input> and <div> elements
  3. Call stork.attach() again

UI Options

The following fields can be used to configure the Stork UI, and should be passed into the stork.attach() method as the second parameter.

strings.attributionstring, Default: "Powered by Stork"

The text displayed under the search results.

strings.closeButtonSvgstring

An SVG used as a button. When clicked, the search results are hidden.

strings.queryTooShortstring, Default: Searching...

The message shown to users when the query is too short for search results to be properly displayed.

generateMessageFunction: (number, number) => string

The message shown to users when search results are being displayed. The first argument is the total number of documents that were found matching the search results. The second argument is the duration, in milliseconds, that the most recent search operation took.

onQueryUpdateFunction: (string) => void

A callback function that is called every time the search query updates and new results are displayed. The argument is the query that the user typed into the search field.

onResultSelectedFunction: (string, result) => void | promise

A callback function that is called when the user selects a search result with the intent to navigate to that URL. The first argument is the query the user typed into the search field. The second is a Result object representing the document the user selected.

If you return a Promise from this function, Stork will await that promise before changing the window location.

transformResultURLFunction: (string) => string

A function that will transform search result URLs before they get output to the DOM as clickable links in the dropdown menu.

excerptLengthnumber, Default: 150

The length, in characters, of an excerpt of text displayed in a search result.

numberOfResultsnumber, Default: 10

The maximum number of documents displayed in the list of search results.

numberOfExcerptsnumber, Default: 5

The maximum number of excerpts displayed for a single document in the list of search results.

stork.search(name, query)

Runs a search and returns an array of Result objects. If you want to manage your own UI, you can use this method instead of stork.attach() to run a search entirely within JavaScript.

The Result Object

{
    entry: {
        url: "https://example.com/my-document",
        title: "My Document",
    },
    excerpts: [
        {
            text: "This is an excerpt from the document that matches a search result.",
            highlight_ranges: [
                {
                    beginning: 25,
                    end: 29
                }
            ],
            score: 255,
            url_suffix: "#my-hash" // or null
        }
    ],
    title_highlight_ranges: [
        {
            beginning: 8,
            end: 12
        }
    ],
    score: 100,
}

entryDocument object

Holds information about the document whose contents matched the search query. Contains two fields: the title of the document and the url that should be navigated to when that URL is selected.

excerptsArray of Excerpt objects

An excerpt is a selection of text that matched the search query. An excerpt holds one or more textual matches, and those matches can be highlighted in your UI by using the highlight_ranges information.

An excerpt can have a URL suffix. If so, when the user navigates to the containing document, append the URL suffix to the entry's URL.

title_highlight_rangesArray of Highlight Range objects

If text within the document's title match the search query, this array will contain character indexes that should be highlighted to indicate a match to the user.

scoreNumber

The relevance score that Stork computed for the document.

Was this page helpful?

Documentation Preferences

These options let you customize the documentation based on how you want to use Stork.

Installation Method

Configuration File Format

Document Source

© 2019–2023.

Stork is maintained by James Little, who's really excited that you're checking it out.

This site is open source. Please file a bug if you see something confusing or incorrect.

Logo art by Bruno Monts, with special thanks to the fission.codes team.
Please contact James Little before using the logo for anything.