Skip to content
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

PART 2 - configurable query suggestions & recent queries #1267

Merged
merged 11 commits into from
Oct 6, 2021
2 changes: 1 addition & 1 deletion packages/atomic/src/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ export namespace Components {
"maxWithoutQuery"?: number;
}
interface AtomicSearchBoxRecentQueries {
"maxWithQuery"?: number;
"maxWithQuery": number;
"maxWithoutQuery"?: number;
}
interface AtomicSearchInterface {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ export class AtomicSearchBox {
this.pendingSuggestionEvents = [];
}

@Listen('atomic/searchBoxSuggestion')
public setFormat(event: CustomEvent<SearchBoxSuggestionsEvent>) {
@Listen('atomic/searchBoxSuggestion/register')
public registerSuggestions(event: CustomEvent<SearchBoxSuggestionsEvent>) {
event.preventDefault();
event.stopPropagation();
if (this.searchBox) {
Expand All @@ -111,6 +111,9 @@ export class AtomicSearchBox {
id: this.id,
searchBoxController: this.searchBox,
numberOfQueries: this.numberOfQueries,
inputRef: this.inputRef,
triggerSuggestions: () => this.triggerSuggestions(),
getSuggestions: () => this.suggestions,
};
}

Expand Down Expand Up @@ -179,7 +182,7 @@ export class AtomicSearchBox {
return;
}

const query = this.nextOrFirstValue.getAttribute('data-value');
const query = this.nextOrFirstValue.getAttribute('data-query');
!isNullOrUndefined(query) && this.updateQuery(query);
this.updateActiveDescendant(this.nextOrFirstValue.id);
this.scrollActiveDescendantIntoView();
Expand All @@ -190,7 +193,7 @@ export class AtomicSearchBox {
return;
}

const query = this.previousOrLastValue.getAttribute('data-value');
const query = this.previousOrLastValue.getAttribute('data-query');
!isNullOrUndefined(query) && this.updateQuery(query);
this.updateActiveDescendant(this.previousOrLastValue.id);
this.scrollActiveDescendantIntoView();
Expand All @@ -200,11 +203,15 @@ export class AtomicSearchBox {
await Promise.all(
this.suggestions.map((suggestion) => suggestion.onInput())
);
this.suggestionElements = this.suggestions
// TODO: sort by position
const suggestionElements = this.suggestions
.sort((a, b) => a.position - b.position)
.map((suggestion) => suggestion.renderItems())
.flat()
.slice(0, this.numberOfQueries);
.flat();

const max =
this.numberOfQueries +
suggestionElements.filter((sug) => sug.query === undefined).length;
this.suggestionElements = suggestionElements.slice(0, max);
}

private onInput(value: string) {
Expand All @@ -221,6 +228,7 @@ export class AtomicSearchBox {
private onBlur() {
this.isExpanded = false;
this.updateActiveDescendant();
this.clearSuggestionElements();
}

private onSubmit() {
Expand Down Expand Up @@ -298,6 +306,7 @@ export class AtomicSearchBox {
class="w-8 h-8 mr-1.5 text-neutral-dark"
onClick={() => {
this.searchBox.clear();
this.clearSuggestionElements();
this.inputRef.focus();
}}
ariaLabel={this.bindings.i18n.t('clear')}
Expand All @@ -323,6 +332,10 @@ export class AtomicSearchBox {
);
}

private clearSuggestionElements() {
this.suggestionElements = [];
}

private renderSuggestion(
suggestion: SearchBoxSuggestionElement,
index: number
Expand All @@ -334,14 +347,14 @@ export class AtomicSearchBox {
id={id}
role="option"
aria-selected={`${isSelected}`}
key={suggestion.value}
data-value={suggestion.value}
key={suggestion.key}
data-query={suggestion.query}
part={isSelected ? 'active-suggestion suggestion' : 'suggestion'}
class={`flex px-4 h-10 items-center text-neutral-dark hover:bg-neutral-light cursor-pointer first:rounded-t-md last:rounded-b-md ${
isSelected ? 'bg-neutral-light' : ''
}`}
onMouseDown={(e) => e.preventDefault()}
onClick={() => suggestion.onClick()}
onClick={() => suggestion.onSelect()}
>
{suggestion.content}
</li>
Expand Down Expand Up @@ -376,7 +389,10 @@ export class AtomicSearchBox {
class="w-12 h-auto rounded-r-md rounded-l-none -my-px"
part="submit-button"
ariaLabel={this.bindings.i18n.t('search')}
onClick={() => this.searchBox.submit()}
onClick={() => {
this.searchBox.submit();
this.clearSuggestionElements();
}}
>
<atomic-icon icon={SearchIcon} class="w-4 h-4"></atomic-icon>
</Button>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import {loadQuerySuggestActions, SearchEngine} from '@coveo/headless';
import SearchIcon from 'coveo-styleguide/resources/icons/svg/search.svg';
import {
loadQuerySuggestActions,
SearchEngine,
Suggestion,
} from '@coveo/headless';
import {QuerySuggestionSection} from '@coveo/headless/dist/definitions/state/state-sections';
import {Component, Element, Prop, State, h} from '@stencil/core';
import {dispatchSearchBoxSuggestionsEvent} from '../suggestions-common';
import {
dispatchSearchBoxSuggestionsEvent,
SearchBoxSuggestionElement,
SearchBoxSuggestionsBindings,
} from '../suggestions-common';

@Component({
tag: 'atomic-search-box-query-suggestions',
shadow: true,
})
export class AtomicSearchBoxQuerySuggestions {
private bindings!: SearchBoxSuggestionsBindings;
@Element() private host!: HTMLElement;

@State() public error!: Error;
Expand All @@ -17,42 +27,74 @@ export class AtomicSearchBoxQuerySuggestions {

componentWillLoad() {
try {
dispatchSearchBoxSuggestionsEvent(
({engine, id, searchBoxController, numberOfQueries}) => {
const {registerQuerySuggest, fetchQuerySuggestions} =
loadQuerySuggestActions(engine);

(engine as SearchEngine<QuerySuggestionSection>).dispatch(
registerQuerySuggest({
id,
count: numberOfQueries,
})
);

return {
onInput: () =>
(engine as SearchEngine<QuerySuggestionSection>).dispatch(
fetchQuerySuggestions({
id,
})
),
renderItems: () =>
// TODO: limit values according to maxWithQuery/maxWithoutQuery
searchBoxController.state.suggestions.map((suggestion) => ({
content: <span innerHTML={suggestion.highlightedValue}></span>,
value: suggestion.rawValue,
onClick: () =>
searchBoxController.selectSuggestion(suggestion.rawValue),
})),
};
},
this.host
);
dispatchSearchBoxSuggestionsEvent((bindings) => {
this.bindings = bindings;
return this.initialize();
}, this.host);
} catch (error) {
this.error = error as Error;
}
}

private initialize() {
const engine = this.bindings.engine as SearchEngine<QuerySuggestionSection>;
const {registerQuerySuggest, fetchQuerySuggestions} =
loadQuerySuggestActions(engine);

engine.dispatch(
registerQuerySuggest({
id: this.bindings.id,
count: this.bindings.numberOfQueries,
})
);

return {
position: Array.from(this.host.parentNode!.children).indexOf(this.host),
Copy link
Member

Choose a reason for hiding this comment

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

is that parentNode! actually safe ? In theory, it could be possible to have someone create a search box element in JS and not attach it to the DOM, no ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I would expect it to be, but I'll handle it just in case (ps: this is the child query suggestion configuration element)

onInput: () =>
engine.dispatch(
fetchQuerySuggestions({
id: this.bindings.id,
})
),
renderItems: () => this.renderItems(),
};
}

private renderItems(): SearchBoxSuggestionElement[] {
const hasQuery = this.bindings.searchBoxController.state.value !== '';
const max = hasQuery ? this.maxWithQuery : this.maxWithoutQuery;
return this.bindings.searchBoxController.state.suggestions
.slice(0, max)
.map((suggestion) => this.renderItem(suggestion));
}

private renderItem(suggestion: Suggestion) {
const hasQuery = this.bindings.searchBoxController.state.value !== '';
return {
content: (
<div class="flex items-center">
{this.bindings.getSuggestions().length > 1 && (
<atomic-icon
icon={SearchIcon}
class="w-4 h-4 text-neutral mr-2"
></atomic-icon>
)}
{hasQuery ? (
<span innerHTML={suggestion.highlightedValue}></span>
) : (
<span>{suggestion.rawValue}</span>
)}
</div>
),
key: `qs-${suggestion.rawValue}`,
query: suggestion.rawValue,
onSelect: () => {
this.bindings.searchBoxController.selectSuggestion(suggestion.rawValue);
this.bindings.inputRef.blur();
},
};
}

public render() {
if (this.error) {
return (
Expand Down
Loading