Algolia Typeahead retrieve results

I am trying to create a discussion tool in my Rails app. I'd like to add users to a discussion like in Facebook messenger.

To do so, I implemented Algolia instant search sith Typeahead. It works fine to show th results but when I click on a result it does nothing at all. It looks like if the event I am using was not working.

I cannot use my keyboard to go up or down the results, it's very strange. Could you help me? I tried all the events on the Typeahead documentation but no one is working.

Thank you so much.

<div class="uk-grid message">
  <div class="uk-width-medium-2-6"></div>
  <div class="uk-width-medium-3-6 bubble">
    <%= form_tag create_discussion_path, method: :post, remote: true, class: 'uk-form', id: 'createDiscussionForm' do %>
        <div class="form-group">
          <div class="uk-grid">
            <div class="uk-width-1-6">
              <span><%= t('to') %></span>
            </div>
            <div class="uk-width-5-6">
              <%= text_field_tag 'recipients', '', class: 'recipients typeahead', id: 'typeahead-algolia-template', spellcheck: false %>
            </div>
          </div>
          <%= text_area_tag 'body', nil, cols: 3, class: 'form-control uk-width-1-1 body', placeholder: 'Ask something or just say hi!', required: true %>
        </div>
        <%= submit_tag t('dashboard.discussions.send_message'), class: 'uk-button uk-width-1-1' %>
    <% end %>
    <div class="arrow-right"></div>
  </div>
  <div class="uk-width-medium-1-6 text-center">
    <%= link_to user_path(current_user) do %>
        <%= image_tag(current_user.pictures.first.image(:square_thumb)) %>
    <% end %>
    <p><%= current_user.first_name %></p>
  </div>
</div>


<!-- Algolia search callback -->
<script type="text/javascript">
  function searchCallback(success, content) {
    if (content.query != $("#typeahead-algolia-template").val()) {
      // do not take out-dated answers into account
      return;
    }

    if (content.hits.length == 0) {
      // no results
      $('#hits').empty();
      return;
    }
  } // end search callback
</script>
<!-- end Algolia search callback -->

<!-- Algolia with typehead and hogan -->
<script type="text/javascript">
  $(document).ready(function() {

    // Algolia initialization
    var $inputfield = $("#typeahead-algolia-template");
    var algolia = algoliasearch('<%= ENV['ALGOLIA_ID'] %>', '<%= ENV['ALGOLIA_PUBLIC_KEY'] %>');
    var index = algolia.initIndex('<%= 'User_' + Rails.env  %>');
    var ttAdapterParams = {
      hitsPerPage: 5,
      facets: '*',
      tagFilters: ''
    };

    // Templating
    var templates = {
      algolia: {
        hit: Hogan.compile(
            '<div class="uk-grid">' +
            '<div class="uk-width-1-4">' +
            '<img src="{{{_highlightResult.picture.value}}}">' +
            '</div>' +
            '<div class="uk-width-3-4">' +
            '<span class="name">' +
            '{{{_highlightResult.first_name.value}}}, ' +
            '</span>' +
            '<span class="occupation">' +
            '{{{_highlightResult.occupation.value}}}' +
            '</span>' +
            '</div>' +
            '</div>'
        )
      }
    };


    // Search?
    $inputfield.typeahead({
          highlight: true,
          hint: true,
          minLength: 1
        },
        {
          source: index.ttAdapter(ttAdapterParams),
          displayKey: 'name',
          templates: {
            suggestion: function(hit) {
              var tpl = templates.algolia.hit.render(hit);
              //console.log(tpl, 'hit');
              return tpl;
            }
          }
        }).on('typeahead:open', function(event, data) {
//          var $form = $(this).closest('form');
//          $form.data('sendToServer', true);
//          $form.submit();
    });
    var val = $inputfield.typeahead('val');
    console.log(val);
    $("#typeahead-algolia-template").bind('typeahead:open', function(ev, suggestion) {
      console.log('Selection: ' + suggestion);
    });
  });
</script>

Upvotes: 3

Views: 302

Answers (1)

Thanks to the great Algolia support team I managed to make it work!

As suggested, I switched to https://github.com/algolia/autocomplete.js and it's just perfect. I changed a few things, basically replacing .typeahead by .autocomplete and the event listener name.

Here is the snippet:

$inputfield.autocomplete({
      highlight: true,
      autoselect: true,
      openOnFocus: true
    }, [
      {
        source: $.fn.autocomplete.sources.hits(index, ttAdapterParams),
        displayKey: 'first_name',
        templates: {
          suggestion: function(hit) {
            var tpl = templates.algolia.hit.render(hit);
            //console.log(tpl, 'hit');
            return tpl;
          }
        }
      }]).on('autocomplete:selected', function(event, suggestion, dataset) {
        console.log(suggestion);
});

Upvotes: 3

Related Questions