Skip to content

Algolia Instantsearch Update #1443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 95 additions & 98 deletions js/search.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,25 @@
import algoliasearch from 'algoliasearch';
import instantsearch from 'instantsearch.js';
import {searchBox, hits, pagination, currentRefinedValues, menu, refinementList} from "instantsearch.js/es/widgets";

document.getElementById('search_query_query').addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
e.preventDefault();
}
});

// Add accessibility functionality:
// "Press '/' to focus the searchbar".
document.addEventListener('keydown', function (e) {
if (e.key !== '/') {
return;
}
var searchInput = document.getElementById('search_query_query');
// Just ignore if we can't find the search input for some reason maybe we are on a page without it.
if (!searchInput) {
return;
}
// If we already have input focus ignore.
if (document.activeElement.tagName === 'INPUT') {
return;
}
searchInput.focus();
// Prevent '/' being inserted on focus.
e.preventDefault();
});

var searchParameters = {};
import { connectSearchBox } from 'instantsearch.js/es/connectors';
import { hits, pagination, currentRefinements, menu, refinementList} from "instantsearch.js/es/widgets";

if (decodeURI(location.search).match(/[<>]/)) {
location.replace(location.pathname);
}

var searchThrottle = null;
var search = instantsearch({
appId: algoliaConfig.app_id,
apiKey: algoliaConfig.search_key,
let searchThrottle = null;
const search = instantsearch({
indexName: algoliaConfig.index_name,
searchClient: algoliasearch(algoliaConfig.app_id, algoliaConfig.search_key),
routing: {
stateMapping: {
stateToRoute: function (uiState) {
const state = uiState[algoliaConfig.index_name];
return {
query: uiState.query && uiState.query.replace(new RegExp('([^\\s])--', 'g'), '$1-'),
type: uiState.menu && uiState.menu.type,
tags: uiState.refinementList && uiState.refinementList.tags && uiState.refinementList.tags.join('~'),
page: uiState.page,
query: state.query && state.query.replace(new RegExp('([^\\s])--', 'g'), '$1-'),
type: state.menu && state.menu.type,
tags: state.refinementList && state.refinementList.tags && state.refinementList.tags.join('~'),
page: state.page,
};
},
routeToState: function (routeState) {
@@ -62,24 +36,27 @@ var search = instantsearch({
}

return {
query: routeState.query || '',
menu: {
type: routeState.type
},
refinementList: {
tags: routeState.tags && routeState.tags.replace(/[\s-]+/g, ' ').split('~'),
},
page: routeState.page
};
[algoliaConfig.index_name]: {
query: routeState.query || '',
menu: {
type: routeState.type
},
refinementList: {
tags: routeState.tags && routeState.tags.replace(/[\s-]+/g, ' ').split('~'),
},
page: routeState.page
}
}
},
},
},
searchFunction: function(helper) {
var searchResults = document.querySelector('#search-container');
onStateChange: function({uiState, setUiState}) {
const searchResults = document.querySelector('#search-container');
const state = uiState[algoliaConfig.index_name];

if (helper.state.query === ''
&& helper.state.hierarchicalFacetsRefinements.type === undefined
&& (helper.state.disjunctiveFacetsRefinements.tags === undefined || helper.state.disjunctiveFacetsRefinements.tags.length === 0)
if (state.query === ''
&& state.hierarchicalFacetsRefinements.type === undefined
&& (state.disjunctiveFacetsRefinements.tags === undefined || state.disjunctiveFacetsRefinements.tags.length === 0)
) {
searchResults.classList.add('hidden');
return;
@@ -92,41 +69,73 @@ var search = instantsearch({
}

// force focus to prevent algolia from updating the search field input with the modified value
if (helper.state.query.match(/-/)) {
if (state.query.match(/-/)) {
document.getElementById('search_query_query').focus();
}

if (helper.state.query.match(/^PKSA-.{14}$/) || helper.state.query.match(/^GHSA-.{14}$/) || helper.state.query.match(/^CVE-\d{4}-\d+$/)) {
document.location.href = "/security-advisories/" + helper.state.query;
if (state.query.match(/^PKSA-.{14}$/) || state.query.match(/^GHSA-.{14}$/) || state.query.match(/^CVE-\d{4}-\d+$/)) {
document.location.href = "/security-advisories/" + state.query;
}

helper.state.query = helper.state.query.replace(new RegExp('([^\\s])-', 'g'), '$1--');
state.query = state.query.replace(new RegExp('([^\\s])-', 'g'), '$1--');

searchThrottle = setTimeout(function () {
helper.search();
searchThrottle = setTimeout(() => {
setUiState({[algoliaConfig.index_name]: state});
}, 300);
},
searchParameters: searchParameters
});

var autofocus = false;
if (location.pathname == "/" || location.pathname == "/explore/") {
autofocus = true;
}
search.addWidget(
searchBox({
container: '#search_query_query',
magnifier: false,
reset: false,
wrapInput: false,
autofocus: autofocus
})
);

search.addWidget(
const renderSearchBox = (renderOptions, isFirstRender) => {
const { query, refine, clear, isSearchStalled, widgetParams } = renderOptions;
const input = document.querySelector('#search_query_query');

// register events on the first render
if (isFirstRender) {
// focus the search on the homepage and explore
if(location.pathname === "/" || location.pathname === "/explore/") {
input.focus();
}

// trigger search on input change
input.addEventListener('input', event => {
refine(event.target.value);
});

// prevent form submission
input.addEventListener('keydown', event => {
if (event.key === 'Enter') {
event.preventDefault();
}
});

// clear search on escape
input.addEventListener('keydown', event => {
if (event.key === 'Escape') {
clear();
}
});

// focus search on / but not when typing in the input
document.addEventListener('keydown', event => {
if (event.key !== '/' || document.activeElement === input) {
return;
}

input.focus();
event.preventDefault();
});
}

input.value = query;
};

const customSearchBox = connectSearchBox(renderSearchBox);

search.addWidgets([
customSearchBox({}),
hits({
container: '.search-list',
transformData: function (hit) {
transformItems: hits => hits.map(hit => {
hit.url = '/packages/' + hit.name;
if (hit.type === 'virtual-package') {
hit.virtual = true;
@@ -144,7 +153,7 @@ search.addWidget(
}

return hit;
},
}),
templates: {
empty: 'No packages found.',
item: `
@@ -153,7 +162,7 @@ search.addWidget(
<div class="col-sm-9 col-lg-10">
<p class="pull-right language">{{ language }}</p>
<h4 class="font-bold">
<a href="{{ url }}" tabindex="2">{{{ _highlightResult.name.value }}}</a>
<a href="{{ url }}" tabindex="2">{{#helpers.highlight}}{ "attribute": "name" }{{/helpers.highlight}}</a>
{{#virtual}}
<small>(Virtual Package)</small>
{{/virtual}}
@@ -187,20 +196,14 @@ search.addWidget(
root: 'packages',
item: 'row'
}
})
);

search.addWidget(
}),
pagination({
container: '.pagination',
maxPages: 200,
scrollTo: document.getElementById('search_query_query'),
showFirstLast: false,
})
);

search.addWidget(
currentRefinedValues({
}),
currentRefinements({
container: '.search-facets-active-filters',
clearAll: 'before',
clearsQuery: false,
@@ -210,40 +213,34 @@ search.addWidget(
templates: {
header: 'Active filters',
item: function (filter) {
if ('tags' == filter.attributeName) {
if ('tags' === filter.attributeName) {
return 'tag: ' + filter.name
} else {
return filter.attributeName + ': ' + filter.name
}
}
},
onlyListedAttributes: true,
})
);

search.addWidget(
}),
menu({
container: '.search-facets-type',
attributeName: 'type',
attribute: 'type',
limit: 15,
showMore: true,
templates: {
header: 'Package type'
}
})
);

search.addWidget(
}),
refinementList({
container: '.search-facets-tags',
attributeName: 'tags',
attribute: 'tags',
limit: 15,
showMore: true,
templates: {
header: 'Tags'
},
searchForFacetValues:true
})
);
}),
]);

search.start();
1,323 changes: 434 additions & 889 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"name": "packagist.org",
"dependencies": {
"algoliasearch": "^4.22.1",
"bootstrap": "3.3.5",
"d3": "^3.5.17",
"instantsearch.js": "^2.7.4",
"instantsearch.js": "^4.66.0",
"jquery": "^3.6.0",
"nvd3": "^1.8.6",
"plausible-tracker": "^0.3",
6 changes: 1 addition & 5 deletions templates/layout.html.twig
Original file line number Diff line number Diff line change
@@ -223,11 +223,7 @@
</footer>

<script nonce="{{ csp_nonce('script') }}">
var algoliaConfig = {{ algolia|json_encode|raw }};
{# For Aloglia instantsearch 2.x, can be dropped once we upgrade to 4.x #}
window.process = {
env: { DEBUG: undefined },
};
const algoliaConfig = {{ algolia|json_encode|raw }};
</script>
{% block script_init %}{% endblock %}