Skip to content
This repository has been archived by the owner on Feb 2, 2023. It is now read-only.

feat(is-routing): support instantsearch routing #551

Merged
merged 5 commits into from
Aug 8, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
115 changes: 115 additions & 0 deletions src/instantsearch/__snapshots__/widget.test.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`instantsearch widget routing getWidgetSearchParameters should add the refinements according to the UI state provided 1`] = `
SearchParameters {
"advancedSyntax": undefined,
"allowTyposOnNumericTokens": undefined,
"analytics": undefined,
"analyticsTags": undefined,
"aroundLatLng": "123,123",
"aroundLatLngViaIP": undefined,
"aroundPrecision": undefined,
"aroundRadius": undefined,
"attributesToHighlight": undefined,
"attributesToRetrieve": undefined,
"attributesToSnippet": undefined,
"disableExactOnAttributes": undefined,
"disjunctiveFacets": Array [],
"disjunctiveFacetsRefinements": Object {},
"distinct": undefined,
"enableExactOnSingleWordQuery": undefined,
"facets": Array [],
"facetsExcludes": Object {},
"facetsRefinements": Object {},
"getRankingInfo": undefined,
"hierarchicalFacets": Array [],
"hierarchicalFacetsRefinements": Object {},
"highlightPostTag": undefined,
"highlightPreTag": undefined,
"hitsPerPage": undefined,
"ignorePlurals": undefined,
"index": "",
"insideBoundingBox": undefined,
"insidePolygon": undefined,
"length": undefined,
"maxValuesPerFacet": undefined,
"minProximity": undefined,
"minWordSizefor1Typo": undefined,
"minWordSizefor2Typos": undefined,
"minimumAroundRadius": undefined,
"numericFilters": undefined,
"numericRefinements": Object {},
"offset": undefined,
"optionalFacetFilters": undefined,
"optionalTagFilters": undefined,
"optionalWords": undefined,
"page": 0,
"query": "",
"queryType": undefined,
"removeWordsIfNoResults": undefined,
"replaceSynonymsInHighlight": undefined,
"restrictSearchableAttributes": undefined,
"snippetEllipsisText": undefined,
"synonyms": undefined,
"tagFilters": undefined,
"tagRefinements": Array [],
"typoTolerance": undefined,
}
`;

exports[`instantsearch widget routing getWidgetSearchParameters should enforce the default value if no value is in the UI State 1`] = `
SearchParameters {
"advancedSyntax": undefined,
"allowTyposOnNumericTokens": undefined,
"analytics": undefined,
"analyticsTags": undefined,
"aroundLatLng": "2,2",
"aroundLatLngViaIP": undefined,
"aroundPrecision": undefined,
"aroundRadius": undefined,
"attributesToHighlight": undefined,
"attributesToRetrieve": undefined,
"attributesToSnippet": undefined,
"disableExactOnAttributes": undefined,
"disjunctiveFacets": Array [],
"disjunctiveFacetsRefinements": Object {},
"distinct": undefined,
"enableExactOnSingleWordQuery": undefined,
"facets": Array [],
"facetsExcludes": Object {},
"facetsRefinements": Object {},
"getRankingInfo": undefined,
"hierarchicalFacets": Array [],
"hierarchicalFacetsRefinements": Object {},
"highlightPostTag": undefined,
"highlightPreTag": undefined,
"hitsPerPage": undefined,
"ignorePlurals": undefined,
"index": "",
"insideBoundingBox": undefined,
"insidePolygon": undefined,
"length": undefined,
"maxValuesPerFacet": undefined,
"minProximity": undefined,
"minWordSizefor1Typo": undefined,
"minWordSizefor2Typos": undefined,
"minimumAroundRadius": undefined,
"numericFilters": undefined,
"numericRefinements": Object {},
"offset": undefined,
"optionalFacetFilters": undefined,
"optionalTagFilters": undefined,
"optionalWords": undefined,
"page": 0,
"query": "",
"queryType": undefined,
"removeWordsIfNoResults": undefined,
"replaceSynonymsInHighlight": undefined,
"restrictSearchableAttributes": undefined,
"snippetEllipsisText": undefined,
"synonyms": undefined,
"tagFilters": undefined,
"tagRefinements": Array [],
"typoTolerance": undefined,
}
`;
44 changes: 39 additions & 5 deletions src/instantsearch/widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,68 @@ class AlgoliaPlacesWidget {
}

this.placesOptions = placesOptions;
this.placesAutocomplete = places(this.placesOptions);

this.state = {};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not completely sure, but this could be called this.uiState

}
init({ helper }) {
const placesAutocomplete = places(this.placesOptions);

init({ helper }) {
helper
.setQueryParameter('insideBoundingBox')
.setQueryParameter('aroundLatLng', this.defaultPosition);

placesAutocomplete.on('change', opts => {
this.placesAutocomplete.on('change', opts => {
const {
suggestion: {
latlng: { lat, lng },
value,
},
} = opts;

this.state.position = `${lat},${lng}`;
this.state.query = value;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than duplicate the source of truth for the values why doesn't read them directly from the helper & placesAutocomplete?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not the query you're looking for. It's actually the value for searching for values in places, which is nowhere in the main search state.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but since you have access to the Places instance you can have access to it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although you can simplify the internal state by removing the position information, you cannot make it completely disappear, as the getVal method from the placesAutocomplete instance will yield stale data.

the placesAutocomplete.on('change', () => {}) is triggered before the update of the value of the input, and so is getWidgetState. So placesAutocomplete.getVal will yield the previous input value, instead of the new one.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok thanks for the update!


helper
.setQueryParameter('insideBoundingBox')
.setQueryParameter('aroundLatLng', `${lat},${lng}`)
.setQueryParameter('aroundLatLng', this.state.position)
.search();
});

placesAutocomplete.on('clear', () => {
this.placesAutocomplete.on('clear', () => {
this.state.position = undefined;
this.state.query = undefined;

helper
.setQueryParameter('insideBoundingBox')
.setQueryParameter('aroundLatLng', this.defaultPosition)
.search();
});
}

getWidgetSearchParameters(searchParameters, { uiState }) {
if (uiState.places) {
const { query, position } = uiState.places;
if (position === undefined) {
return searchParameters;
}

this.placesAutocomplete.setVal(query || '');
return searchParameters
.setQueryParameter('insideBoundingBox')
.setQueryParameter('aroundLatLng', position);
}

return searchParameters;
}

getWidgetState(uiState) {
if (this.state.position === undefined && this.state.query === undefined) {
const newUiState = Object.assign({}, uiState);
delete newUiState.places;
return newUiState;
}
return Object.assign({}, uiState, { places: this.state });
}
}

/**
Expand Down
149 changes: 147 additions & 2 deletions src/instantsearch/widget.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import searchHelper from 'algoliasearch-helper';
import searchHelper, { SearchParameters } from 'algoliasearch-helper';
import algoliaPlacesWidget from './widget.js';
import places from '../places.js';

jest.mock('../places.js', () => {
const module = jest.fn(() => {
const instance = { on: jest.fn() };
const instance = { on: jest.fn(), setVal: jest.fn() };

module.__instance = instance;
return instance;
Expand Down Expand Up @@ -107,4 +107,149 @@ describe('instantsearch widget', () => {
aroundLatLng: '2,2',
});
});

describe('routing', () => {
const getInitializedWidget = () => {
const client = createFakeClient();
const helper = createFakekHelper(client);
const widget = algoliaPlacesWidget({ defaultPosition: [2, 2] });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there probably should be a test without defaultPosition too

widget.init({ helper, state: helper.state });

return [widget, helper];
};

describe('getWidgetState', () => {
test('should give back the object unmodified if the default value is selected', () => {
const [widget, helper] = getInitializedWidget();
const uiStateBefore = {};
const uiStateAfter = widget.getWidgetState(uiStateBefore, {
searchParameters: helper.state,
helper,
});

expect(uiStateAfter).toMatchObject(uiStateBefore);
});

test('should give update uiState with position', () => {
const [widget, helper] = getInitializedWidget();

const eventName = places.__instance.on.mock.calls[0][0];
const eventListener = places.__instance.on.mock.calls[0][1];

expect(eventName).toEqual('change');

eventListener({
suggestion: { latlng: { lat: '123', lng: '456' }, value: 'Paris' },
});
expect(helper.search).toBeCalled();
expect(helper.getState()).toMatchObject({
insideBoundingBox: undefined,
aroundLatLng: '123,456',
});

const uiStateBefore = {};

const uiStateAfter = widget.getWidgetState(uiStateBefore, {
searchParameters: helper.state,
helper,
});

const expectedUiState = {
places: {
position: '123,456',
query: 'Paris',
},
};

expect(uiStateAfter).toMatchObject(expectedUiState);
});

test('should give reset places uiState on clear', () => {
const [widget, helper] = getInitializedWidget();

const eventName = places.__instance.on.mock.calls[1][0];
const eventListener = places.__instance.on.mock.calls[1][1];

expect(eventName).toEqual('clear');

eventListener();

expect(helper.search).toBeCalled();
expect(helper.getState()).toMatchObject({
insideBoundingBox: undefined,
aroundLatLng: '2,2',
});

const uiStateBefore = {
places: {
position: '123,456',
query: 'Paris',
},
};

const uiStateAfter = widget.getWidgetState(uiStateBefore, {
searchParameters: helper.state,
helper,
});

const expectedUiState = {};

expect(uiStateAfter).toEqual(expectedUiState);
});
});

describe('getWidgetSearchParameters', () => {
test('should return the same SP if there are no refinements in the UI state', () => {
const [widget, helper] = getInitializedWidget();
// The user presses back (browser), and the URL contains no parameters
const uiState = {};
// The current state is empty (and page is set to 0 by default)
const searchParametersBefore = SearchParameters.make(helper.state);
const searchParametersAfter = widget.getWidgetSearchParameters(
searchParametersBefore,
{ uiState }
);
// Applying the same values should not return a new object
expect(searchParametersAfter).toBe(searchParametersBefore);
});

test('should enforce the default value if no value is in the UI State', () => {
const [widget, helper] = getInitializedWidget();
// The user presses back (browser), and the URL contains no parameters
const uiState = {};
// The current state is set to page 4

const searchParametersBefore = SearchParameters.make(helper.state);
const searchParametersAfter = widget.getWidgetSearchParameters(
searchParametersBefore,
{ uiState }
);
// Applying an empty state, should force back to page 0
expect(searchParametersAfter).toMatchSnapshot();
expect(searchParametersAfter.aroundLatLng).toBe('2,2');
expect(searchParametersAfter.insideBoundingBox).toBe(undefined);
});

test('should add the refinements according to the UI state provided', () => {
const [widget, helper] = getInitializedWidget();
// The user presses back (browser), and the URL contains some parameters
const uiState = {
places: {
position: '123,123',
query: 'Paris',
},
};

const searchParametersBefore = SearchParameters.make(helper.state);
const searchParametersAfter = widget.getWidgetSearchParameters(
searchParametersBefore,
{ uiState }
);
// Applying a state with new parameters should apply them on the search
expect(searchParametersAfter).toMatchSnapshot();
expect(searchParametersAfter.insideBoundingBox).toBe(undefined);
expect(searchParametersAfter.aroundLatLng).toBe('123,123');
});
});
});
});