regenerate: true


{% capture cache %}

{% comment %}

# -----------------------------------------------------------------------------
#  ~/assets/themes/j1/core/js/adapter/algolia.js
#  Liquid template to create the Template Adapter for Algolia
#
#  Product/Info:
#  https://jekyll.one

# community.algolia.com/instantsearch.js/v2/getting-started.html

#  Copyright (C) 2019 Juergen Adams
#
#  J1 Template is licensed under the MIT License.
#  For details, see https://jekyll.one
#
# -----------------------------------------------------------------------------
# Test data:
#  {{ liquid_var | debug }}
#
# -----------------------------------------------------------------------------

{% endcomment %}

/*

# -----------------------------------------------------------------------------
#  ~/assets/themes/j1/core/js/adapter/algolia.js
#  J1 Adapter for Algolia
#
#  Product/Info:
#  https://jekyll.one
#
#  Copyright (C) 2019 Juergen Adams
#
#  J1 Template is licensed under the MIT License.
#  For details, see https://jekyll.one
#
# -----------------------------------------------------------------------------
#  Adapter generated: {{site.time}}
# -----------------------------------------------------------------------------

*/ 'use strict';

{% comment %} Load YML config data ——————————————————————————– {% endcomment %} {% assign algolia_config = site.algolia %}

j1.Algolia = (function (j1, window) {

var environment = '{{environment}}'; // Set environment
var state       = 'not_started';
var logger;
var logText;

return {

  // -------------------------------------------------------------------------
  // Initialize InstantSearch
  // -------------------------------------------------------------------------
  init: function () {

    // Config settings object
    var algoliaConfig = {};

    {% comment %} Set global variables
    -------------------------------------------------------------------------- {% endcomment %}
    logger = log4javascript.getLogger("j1.Algolia.adapter"); // Setup logger

    // Set|Log status
    state = 'initialize';
    logger.info('state: ' + state);

    {% comment %} Load module config from yml data
    -------------------------------------------------------------------------- {% endcomment %}
    // Load  module DEFAULTS|CONFIG
    algoliaConfig = $.extend({}, {{algolia_config | replace: '=>', ':' }});

    var search = instantsearch({
      appId:      algoliaConfig.application_id,
      apiKey:     algoliaConfig.search_only_api_key,
      indexName:  algoliaConfig.index_name,
      routing:    true
    });

    var hitTemplate = function(hit) {
      // state = 'start search';
      // logger.info('state: ' + state);
      // var re = new RegExp("^\/posts");
      // var re = new RegExp("^\/pages");
      var re = new RegExp("^\/pages|^\/posts|^\/collections");
      if ( re.test(hit.url) ) {
        let date = '';
        if (hit.date) {
          date = moment.unix(hit.date).format('MMM D, YYYY');
        }
        // let url = `/jekyll-algolia-example${hit.url}#${hit.anchor}`;
        let url = `${hit.url}`;

        const title = hit._highlightResult.title.value;
        let breadcrumbs = '';

        if (hit._highlightResult.headings) {
          breadcrumbs = hit._highlightResult.headings.map(match => {
            return `<span class="post-breadcrumb">${match.value}</span>`
          }).join(' > ')
        }

        var content = hit._highlightResult.html.value;

        return `
          <li class="search-result-item">
            <div class="card card-flat">
              <div class="card-body">
                <span class="post-meta">${date}</span>
                <h2 class="card-title">${title}</h2>
                <h6 class="card-subtitle mb-2 text-muted">${hit.tagline}</h6>
                <div class="card-text">${content}</div>
                <div class="card-footer">
                  <a class="card-link" href="${url}" target="_blank">Read more ..</a>
                </div>
              </div>
            </div>
          </li>
        `;
      }
      // state = 'finished search';
      // logger.info('state: ' + state);
    }

    if ( algoliaConfig.enabled == true ) {
      // initialize currentRefinedValues
      search.addWidget(
        instantsearch.widgets.currentRefinedValues({
          container: '#current-refined-values',
          // This widget can also contain a clear all link to remove all filters,
          // we disable it in this example since we use `clearAll` widget on its own.
          clearAll: false
        })
      );

      // initialize clearAll
      search.addWidget(
        instantsearch.widgets.clearAll({
          container: '#clear-all',
          templates: {
            link: 'Reset TAGS'
          },
          clearsQuery: false,
          autoHideContainer: false
        })
      );

      // initialize pagination
      search.addWidget(
        instantsearch.widgets.pagination({
          container: '#pagination',
          maxPages: 20,
          // default is to scroll to 'body', here we disable this behavior
          scrollTo: false
        })
      );
      // initialize SearchBox
      search.addWidget(
        instantsearch.widgets.searchBox({
          container:            '#search-searchbar',
          placeholder:          'Search this site ..',
          autofocus:            true,
          reset:                true,
          loadingIndicator:     false,
          poweredBy:            true // This is required if you're on the free Community plan
        })
      );
      // initialize hits widget
      search.addWidget(
        instantsearch.widgets.hits({
          container:  '#search-hits',
          templates:  {
            empty:    'No results',
            item:     hitTemplate
          }
        })
      );
      // initialize RefinementList
      search.addWidget(
        instantsearch.widgets.refinementList({
          container:        '#refinement-list',
          attributeName:    'tags',
          collapsible:      true,
          operator:         "and",
          limit:            5,
          sortBy:           ["isRefined","count:desc","name:asc"],
          templates: {
            header:         'Tags'
          },
          showMore:         true
        })
      );
      /*
      search.addWidget(
        instantsearch.widgets.hitsPerPageSelector({
          container: '#hits-per-page-selector',
          items: [
            {value: 3, label: '3 per page', default: true},
            {value: 6, label: '6 per page'},
            {value: 12, label: '12 per page'},
          ]
        })
      );
      */
    }

    if ( algoliaConfig.enabled == true ) {
      search.start();
      $('#searcher').addClass('row');

      state = 'finished';
      logger.info('state: ' + state);
      logger.info("J1 Algolia successfully initialized");
    } else {
      $('#algolia-site-search').append( '<p class="ml-5 mt-5 mb-5 "> <strong>Algolia Search DISABLED</strong> </p>' );
      state = 'finished';
      logger.info('state: ' + state);
      logger.info("J1 Algolia Seach NOT enabled");
    }

    return true;
  }, // end init

  // -------------------------------------------------------------------------
  //  returns the current (processing) state of the module
  // -------------------------------------------------------------------------
  state: function () {
    return state;
  } // end state

}; // end return

})(j1, window);

{% endcapture %}

{{ cache | strip_empty_lines }} {% assign cache = nil %}