Skip to content

Conversation

@tw2113
Copy link
Member

@tw2113 tw2113 commented Sep 20, 2023

I named the branch wrong, it should be "feature/232-autocomplete-upgrade", so this should be for #232

Upgrade our available options for Algolia Autocomplete

With this feature, we will not be forcing everyone to upgrade their Autocomplete version, but we will start the process of offering the ability to.

Due to the detail that Algolia Autocomplete version 1.x and higher changes from listening to all specified form inputs, to requesting a dedicated div to render in, we can't blanket update everyone. Every user wanting to upgrade will need to amend their theme and website to have something like <div id="autocomplete"></div> or similar selector. This is where Algolia will render the autocomplete search field. The ID does not matter so much, as much as a valid selector in general. I have added filterability for this detail, as you'll see in the code.

With this PR, to help with some separation, there is a new assets directory that stores the frontend assets for:

  1. AlgoliaSearch Javascript Client
  2. Autocomplete.js 1.x
  3. Autocomplete Theme classic 1.x
  4. instantsearch.js

Autocomplete.js 0.38.x will at present time be left in the original js location, as well as the other libraries. We can remove the duplicates from version control if really desired.

Choosing Autocomplete version

There is a new setting on the "Autocomplete" settings page that lets users choose between "Legacy" aka our current 0.38.x version, or "Modern", which is presently at version 1.11.x. This option defaults to "Legacy" and upon admin loading, should populate the option with that default value, preventing accidental breaking changes.

What assets and template file(s) gets loaded depends on the selected setting.

Template changes

The plugin has a new autocomplete-modern.php file, as well as a new algolia-autocomplete-modern.css stylesheet file. The template file has been updated to match the structure and style that Autocomplete 1.11.x expects, and I aimed to replicate the look and feel of the dropdown as much as possible from our legacy. The stylesheet file is largely retained but the selectors are updated to match what comes in.

Autocomplete config changes

I have gone ahead and added a new input_selector_modern property with its own WordPress filter for customization. It does default to '#autocomplete' where that gets passed into the configuration object for Autocomplete in the template file.

Let me know what your thoughts are, anything you would like changed, anything you think could be changed but needs further discussion, and whatnot.

Hopefully this pushes us over the proverbial edge to help our users start leveraging modern Autocomplete functionality, without having to leave them scratching their heads with a blank slate.

…sets. This will be used to load the js libraries instead of the current js folder.
@tw2113
Copy link
Member Author

tw2113 commented Jun 6, 2025

I'm eying getting this sync'd up with the main branch today as much as able, which could help you with any testing you can do.

@tw2113 tw2113 changed the base branch from main to release2110 June 6, 2025 20:12
@tw2113
Copy link
Member Author

tw2113 commented Jun 6, 2025

I believe the branch should be updated with version 2.9.0 now.

@tw2113 tw2113 modified the milestones: 3.0.0, 2.11.0 Jun 9, 2025
@8ctopus
Copy link

8ctopus commented Jun 10, 2025

Good morning, thank you for taking the time to solve the conflicts. I've just tested the branch this morning and it worked once I applied two fixes which I just opened a PR for.
Here's what I tested:

  • Use Algolia with the native WordPress search template
  • Use Algolia with Instantsearch.js
  • Enable Autocomplete in legacy and modern version

Autocomplete js code can be improved in the modern way to check that the div actually exists

2025-06-10_091314

  const containerElement = getHTMLElement(environment, container);

  invariant(
    containerElement.tagName !== 'INPUT',
    'The `container` option does not support `input` elements. You need to change the container to a `div`.'
  );```

If I tried the following:

wp_deregister_script('jquery');

then everything is broken.

* Allow composer installers 2.x

* Fix admin get autocomplete version
@tw2113
Copy link
Member Author

tw2113 commented Jun 10, 2025

Added a new issue for the div bits over at #484

@tw2113
Copy link
Member Author

tw2113 commented Jun 10, 2025

Note to me:

We have Autocomplete config overrides in Algolia Pro that we need to keep in mind for this.

Particularly this line: 'tmpl_suggestion' => 'autocomplete-post-suggestion'

@8ctopus
Copy link

8ctopus commented Jun 11, 2025

@tw2113 Anything else you want me to test?

@tw2113
Copy link
Member Author

tw2113 commented Jun 11, 2025

@8ctopus Nothing at the moment. I'm prepping for 2.10.0 release before I go more in depth with this Autocomplete stuff and a 2.11.0 release

@8ctopus
Copy link

8ctopus commented Jun 18, 2025

hello @tw2113

I have managed to use instantsearch v4 with the default wordpress input after a while of trial and error. I'm attaching the code snippet, I hope it saves you a bunch of time when you get to it.

const algolia = () => {
  const { algoliasearch, instantsearch } = window;

  const searchClient = algoliasearch(
    'APPLICATION_ID',
    'SEARCH_API_KEY'
  );

  // https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/js/
  const search = instantsearch({
    indexName: 'YOUR_INDEX',
    searchClient,
    future: {
      preserveSharedStateOnUnmount: true
    },
    searchFunction(helper) {
      if (helper.state.query === '') {
        // hide hits container when nothing is typed yet
        document.querySelector('#hits').style.display = 'none';
        return;
      }

      document.querySelector('#hits').style.display = '';
      helper.search();
    },
  });

  // create custom search widget
  const { connectSearchBox } = instantsearch.connectors;

  // create a render function
  const renderSearchBox = (renderOptions, isFirstRender) => {
    const { query, refine, clear, isSearchStalled, widgetParams } = renderOptions;

    const input = document.querySelector('input[type=search]');

    if (isFirstRender) {
      input.addEventListener('input', event => {
        refine(event.target.value);
      });
    }

    input.value = query;
  };

  const customSearchBox = connectSearchBox(renderSearchBox);

  search.addWidgets([
    customSearchBox({
      container: document.querySelector('#searchbox'),
    }),
    instantsearch.widgets.poweredBy({
      container: '#poweredBy',
    }),
    // https://www.algolia.com/doc/api-reference/widgets/hits/js/
    instantsearch.widgets.hits({
      container: '#hits',
      escapeHTML: true,
      templates: {
        item: (hit, { html, components }) => html`
          <article>
            <a href="?p=${hit.post_id}">${components.Highlight({ hit, attribute: 'post_title' })}</a>
          </article>
        `,
        empty: "We didn't find any results for the search <em>\"{{query}}\"</em>",
      },
      hitsPerPage: 8,
    }),
    instantsearch.widgets.configure({
      hitsPerPage: 8,
      distinct: true,
      clickAnalytics: true,
      enablePersonalization: true,
    }),
    instantsearch.widgets.pagination({
      container: '#pagination',
    }),
  ]);

  search.start();
};

export default algolia;

and the html code

<form role="search" method="get" action="<?= home_url('/'); ?>">
    <div class="d-flex">
        <div class="flex-grow-1 ps-2 ps-lg-0">
            <input type="search" class="form-control form-control-lg" name="s" placeholder="<?php _e('Search...', 'framework'); ?>" value="<?php the_search_query(); ?>">
        </div>
        <div class="px-2 pe-lg-0">
            <button type="submit" class="btn btn-primary btn-lg ctst-red-new-bg ctst-red-bg-hover">
                <i class='bx bx-search'>&nbsp;</i> <?php _e('Search', 'framework'); ?>
            </button>
        </div>
    </div>
</form>
<div id="poweredBy" class="pt-2"></div>
<div class="search-panel__results">
    <div id="hits"></div>
    <div id="pagination"></div>
</div>

@tw2113
Copy link
Member Author

tw2113 commented Jun 18, 2025

Not quite sure what issue you're solving here, as we're already shipping with InstantSearch 4.x. Are you referring to shipping something that isn't all tied in with an instantsearch.php template file, allowing for some separation?

The PR we're discussing this in is regarding Autocomplete as well.

@8ctopus
Copy link

8ctopus commented Jun 19, 2025

@tw2113 sorry I made a mistake. I assumed that:

| One of the biggest reasons that "modern autocomplete" has yet to be merged in is because of how Algolia changed instantiation processes. Before version 1.x, we are able to attach to any text input, which is extremely convenient with WordPress because typically theme search fields all make use of <input type="text" name="s" .../> and that name attribute is pretty global.

meant that you didn't yet figure out a way how to do it, hence why I posted the info in this thread.

I my case, I wanted to use a lighter implementation of the frontend that only covers my specific use case, hence I dequeued most of the frontend stuff and implemented the js myself.

@tw2113
Copy link
Member Author

tw2113 commented Jun 23, 2025

Noted on that part.

While I definitely want to get things merged in, usage of Autocomplete 1.x won't be default until Algolia stops supporting 0.38.x completely.

@tw2113
Copy link
Member Author

tw2113 commented Jun 25, 2025

@tw2113
Copy link
Member Author

tw2113 commented Aug 8, 2025

Potentially once again needs another new branch with re-applied changes.

@tw2113 tw2113 modified the milestones: 2.11.0, 3.0.0 Dec 9, 2025
Base automatically changed from release2110 to main December 9, 2025 19:12
@tw2113 tw2113 modified the milestones: 3.0.0, 2.12.0 Dec 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants