Skip to content

Commit

Permalink
feat(core): rename private and public methods and properties (#349)
Browse files Browse the repository at this point in the history
BREAKING CHANGE
  • Loading branch information
francoischalifour authored Oct 29, 2020
1 parent 753c8ca commit aeebe6d
Show file tree
Hide file tree
Showing 28 changed files with 356 additions and 362 deletions.
12 changes: 7 additions & 5 deletions examples/js/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
autocomplete,
AutocompleteSource,
getAlgoliaHits,
reverseHighlightItem,
reverseHighlightHit,
} from '@algolia/autocomplete-js';
import { createRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import '@algolia/autocomplete-plugin-recent-searches/style';
Expand Down Expand Up @@ -40,17 +40,19 @@ autocomplete<Hit<QuerySuggestionHit>>({
}).then(([hits]) => {
return [
{
getInputValue: ({ suggestion }) => suggestion.query,
getSuggestions() {
getItemInputValue({ item }) {
return item.query;
},
getItems() {
return hits;
},
templates: {
item({ item }) {
return `
<div class="item-icon">${searchIcon}</div>
<div>
${reverseHighlightItem({
item,
${reverseHighlightHit({
hit: item,
attribute: 'query',
})}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
import { createAutocomplete, AutocompleteSuggestion } from '..';
import { createAutocomplete, AutocompleteCollection } from '..';

function createSuggestion<TItem extends { label: string }>(
function createCollection<TItem extends { label: string }>(
items: TItem[] | TItem[][] = []
): AutocompleteSuggestion<TItem | TItem[]> | AutocompleteSuggestion<TItem[]> {
): AutocompleteCollection<TItem | TItem[]> | AutocompleteCollection<TItem[]> {
return {
source: {
getInputValue: ({ suggestion }) => suggestion.label,
getSuggestionUrl: () => undefined,
getItemInputValue: ({ item }) => item.label,
getItemUrl: () => undefined,
onHighlight: () => {},
onSelect: () => {},
getSuggestions: () => items,
getItems: () => items,
},
items,
};
}

describe('createAutocomplete', () => {
test('setHighlightedIndex', () => {
test('setSelectedItemId', () => {
const onStateChange = jest.fn();
const { setHighlightedIndex } = createAutocomplete({
const { setSelectedItemId } = createAutocomplete({
getSources: () => [],
onStateChange,
});

setHighlightedIndex(1);
setSelectedItemId(1);

expect(onStateChange).toHaveBeenCalledTimes(1);
expect(onStateChange).toHaveBeenCalledWith(
expect.objectContaining({
state: expect.objectContaining({ highlightedIndex: 1 }),
state: expect.objectContaining({ selectedItemId: 1 }),
})
);

setHighlightedIndex(null);
setSelectedItemId(null);

expect(onStateChange).toHaveBeenCalledTimes(2);
expect(onStateChange).toHaveBeenCalledWith(
expect.objectContaining({
state: expect.objectContaining({ highlightedIndex: null }),
state: expect.objectContaining({ selectedItemId: null }),
})
);
});
Expand All @@ -59,21 +59,21 @@ describe('createAutocomplete', () => {
);
});

describe('setSuggestions', () => {
describe('setCollections', () => {
test('default', () => {
const onStateChange = jest.fn();
const { setSuggestions } = createAutocomplete({
const { setCollections } = createAutocomplete({
getSources: () => [],
onStateChange,
});

setSuggestions([createSuggestion([{ label: 'hi' }])]);
setCollections([createCollection([{ label: 'hi' }])]);

expect(onStateChange).toHaveBeenCalledTimes(1);
expect(onStateChange).toHaveBeenCalledWith({
prevState: expect.any(Object),
state: expect.objectContaining({
suggestions: [
collections: [
{
items: [
{
Expand All @@ -90,18 +90,18 @@ describe('createAutocomplete', () => {

test('flattens suggestions', () => {
const onStateChange = jest.fn();
const { setSuggestions } = createAutocomplete({
const { setCollections } = createAutocomplete({
openOnFocus: true,
getSources: () => [],
onStateChange,
});

setSuggestions([createSuggestion([[{ label: 'hi' }]])]);
setCollections([createCollection([[{ label: 'hi' }]])]);

expect(onStateChange).toHaveBeenCalledWith({
prevState: expect.any(Object),
state: expect.objectContaining({
suggestions: [
collections: [
expect.objectContaining({
items: [{ label: 'hi', __autocomplete_id: 0 }],
}),
Expand Down
16 changes: 8 additions & 8 deletions packages/autocomplete-core/src/createAutocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export function createAutocomplete<
const store = createStore(stateReducer, props, [completionStateEnhancer]);

const {
setHighlightedIndex,
setSelectedItemId,
setQuery,
setSuggestions,
setCollections,
setIsOpen,
setStatus,
setContext,
Expand All @@ -38,9 +38,9 @@ export function createAutocomplete<
} = getPropGetters<TItem, TEvent, TMouseEvent, TKeyboardEvent>({
store,
props,
setHighlightedIndex,
setSelectedItemId,
setQuery,
setSuggestions,
setCollections,
setIsOpen,
setStatus,
setContext,
Expand All @@ -53,9 +53,9 @@ export function createAutocomplete<
event: new Event('input'),
store,
props,
setHighlightedIndex,
setSelectedItemId,
setQuery,
setSuggestions,
setCollections,
setIsOpen,
setStatus,
setContext,
Expand All @@ -67,9 +67,9 @@ export function createAutocomplete<
}

return {
setHighlightedIndex,
setSelectedItemId,
setQuery,
setSuggestions,
setCollections,
setIsOpen,
setStatus,
setContext,
Expand Down
18 changes: 9 additions & 9 deletions packages/autocomplete-core/src/getAutocompleteSetters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,31 @@ interface GetAutocompleteSettersOptions<TItem> {
export function getAutocompleteSetters<TItem>({
store,
}: GetAutocompleteSettersOptions<TItem>) {
const setHighlightedIndex: AutocompleteApi<TItem>['setHighlightedIndex'] = (
const setSelectedItemId: AutocompleteApi<TItem>['setSelectedItemId'] = (
value
) => {
store.send('setHighlightedIndex', value);
store.send('setSelectedItemId', value);
};

const setQuery: AutocompleteApi<TItem>['setQuery'] = (value) => {
store.send('setQuery', value);
};

const setSuggestions: AutocompleteApi<TItem>['setSuggestions'] = (
const setCollections: AutocompleteApi<TItem | TItem[]>['setCollections'] = (
rawValue
) => {
let baseItemId = 0;
const value = rawValue.map((suggestion) => ({
...suggestion,
const value = rawValue.map((collection) => ({
...collection,
// We flatten the stored items to support calling `getAlgoliaHits`
// from the source itself.
items: flatten(suggestion.items).map((item) => ({
items: flatten(collection.items).map((item) => ({
...item,
__autocomplete_id: baseItemId++,
})),
}));

store.send('setSuggestions', value);
store.send('setCollections', value);
};

const setIsOpen: AutocompleteApi<TItem>['setIsOpen'] = (value) => {
Expand All @@ -48,9 +48,9 @@ export function getAutocompleteSetters<TItem>({
};

return {
setHighlightedIndex,
setSelectedItemId,
setQuery,
setSuggestions,
setCollections,
setIsOpen,
setStatus,
setContext,
Expand Down
18 changes: 10 additions & 8 deletions packages/autocomplete-core/src/getCompletion.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { InternalAutocompleteOptions, AutocompleteState } from './types';
import { getHighlightedItem } from './utils';
import { getSelectedItem } from './utils';

interface GetCompletionProps<TItem> {
state: AutocompleteState<TItem>;
Expand All @@ -13,28 +13,30 @@ export function getCompletion<TItem>({
if (
props.enableCompletion === false ||
state.isOpen === false ||
state.highlightedIndex === null ||
state.selectedItemId === null ||
state.status === 'stalled'
) {
return null;
}

const { itemValue } = getHighlightedItem({ state })!;
const { itemInputValue } = getSelectedItem({ state })!;

// The completion should appear only if the _first_ characters of the query
// match with the suggestion.
// match with the item.
if (
state.query.length > 0 &&
itemValue.toLocaleLowerCase().indexOf(state.query.toLocaleLowerCase()) === 0
itemInputValue
.toLocaleLowerCase()
.indexOf(state.query.toLocaleLowerCase()) === 0
) {
// If the query typed has a different case than the suggestion, we want
// If the query typed has a different case than the item, we want
// to show the completion matching the case of the query. This makes both
// strings overlap correctly.
// Example:
// - query: 'Gui'
// - suggestion: 'guitar'
// - item: 'guitar'
// => completion: 'Guitar'
const completion = state.query + itemValue.slice(state.query.length);
const completion = state.query + itemInputValue.slice(state.query.length);

if (completion === state.query) {
return null;
Expand Down
26 changes: 10 additions & 16 deletions packages/autocomplete-core/src/getDefaultProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function getDefaultProps<TItem>(
openOnFocus: false,
placeholder: '',
autoFocus: false,
defaultHighlightedIndex: null,
defaultSelectedItemId: null,
enableCompletion: false,
stallThreshold: 300,
environment,
Expand All @@ -32,10 +32,10 @@ export function getDefaultProps<TItem>(
id: props.id ?? generateAutocompleteId(),
// The following props need to be deeply defaulted.
initialState: {
highlightedIndex: null,
selectedItemId: null,
query: '',
completion: null,
suggestions: [],
collections: [],
isOpen: false,
status: 'idle',
statusContext: {},
Expand All @@ -62,9 +62,7 @@ export function getDefaultProps<TItem>(
getNormalizedSources(getSources!, options)
)
)
.then((nested) =>
flatten(nested)
)
.then((nested) => flatten(nested))
.then((sources) =>
sources.map((source) => ({
...source,
Expand All @@ -80,22 +78,18 @@ export function getDefaultProps<TItem>(
);
},
navigator: {
navigate({ suggestionUrl }) {
environment.location.assign(suggestionUrl);
navigate({ itemUrl }) {
environment.location.assign(itemUrl);
},
navigateNewTab({ suggestionUrl }) {
const windowReference = environment.open(
suggestionUrl,
'_blank',
'noopener'
);
navigateNewTab({ itemUrl }) {
const windowReference = environment.open(itemUrl, '_blank', 'noopener');

if (windowReference) {
windowReference.focus();
}
},
navigateNewWindow({ suggestionUrl }) {
environment.open(suggestionUrl, '_blank', 'noopener');
navigateNewWindow({ itemUrl }) {
environment.open(itemUrl, '_blank', 'noopener');
},
...props.navigator,
},
Expand Down
Loading

0 comments on commit aeebe6d

Please sign in to comment.