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

Add first-class link support to Related Resources #271

Merged
merged 16 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion web/app/components/document/sidebar.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@
@modalHeaderTitle="Add related resource"
@modalInputPlaceholder="Search docs or paste a URL..."
@scrollContainer={{this.body}}
@optionalSearchFilters={{array (concat "product:" @document.product)}}
@optionalSearchFilters={{concat "product:" @document.product}}
/>
</div>

Expand Down
4 changes: 3 additions & 1 deletion web/app/components/document/sidebar/related-resources.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@
@inputPlaceholder={{@modalInputPlaceholder}}
@onClose={{this.hideAddResourceModal}}
@addResource={{this.addResource}}
@shownDocuments={{this.algoliaResults}}
@algoliaResults={{this.algoliaResults}}
@objectID={{@objectID}}
@relatedDocuments={{this.relatedDocuments}}
@relatedLinks={{this.relatedLinks}}
@allowAddingExternalLinks={{@allowAddingExternalLinks}}
@search={{perform this.search}}
@getObject={{perform this.getObject}}
@resetAlgoliaResults={{this.resetAlgoliaResults}}
@searchErrorIsShown={{this.searchErrorIsShown}}
@searchIsRunning={{this.search.isRunning}}
/>
Expand Down
85 changes: 75 additions & 10 deletions web/app/components/document/sidebar/related-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import htmlElement from "hermes/utils/html-element";
import Ember from "ember";
import FlashMessageService from "ember-cli-flash/services/flash-messages";
import maybeScrollIntoView from "hermes/utils/maybe-scroll-into-view";
import { assert } from "@ember/debug";
import { XDropdownListAnchorAPI } from "hermes/components/x/dropdown-list";
import { SearchOptions } from "instantsearch.js";

export type RelatedResource = RelatedExternalLink | RelatedHermesDocument;

Expand Down Expand Up @@ -44,7 +44,7 @@ export interface DocumentSidebarRelatedResourcesComponentArgs {
headerTitle: string;
modalHeaderTitle: string;
searchFilters?: string;
optionalSearchFilters?: string[];
optionalSearchFilters?: string;
itemLimit?: number;
modalInputPlaceholder: string;
documentIsDraft?: boolean;
Expand Down Expand Up @@ -159,6 +159,7 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
}
return documents;
}

/**
* The text passed to the TooltipIcon beside the title.
*/
Expand All @@ -181,6 +182,41 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
});
}

/**
* Requests an Algolia document by ID.
* If found, sets the local Algolia results to an array
* with that document. If not, throws a 404 to the child component.
*/
protected getObject = restartableTask(
async (dd: XDropdownListAnchorAPI | null, objectID: string) => {
try {
let algoliaResponse = await this.algolia.getObject.perform(objectID);
if (algoliaResponse) {
this._algoliaResults = [
algoliaResponse,
] as unknown as HermesDocument[];
if (dd) {
dd.resetFocusedItemIndex();
}
if (dd) {
next(() => {
dd.scheduleAssignMenuItemIDs();
});
}
}
} catch (e: unknown) {
const typedError = e as { status?: number };
if (typedError.status === 404) {
// This means the document wasn't found.
// Let the child component handle the error.
throw e;
} else {
this.handleSearchError(e);
}
}
}
);

/**
* The search task passed to the "Add..." modal.
* Returns Algolia document matches for a query and updates
Expand All @@ -191,7 +227,8 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
async (
dd: XDropdownListAnchorAPI | null,
query: string,
shouldIgnoreDelay?: boolean
shouldIgnoreDelay?: boolean,
options?: SearchOptions
) => {
let index = this.configSvc.config.algolia_docs_index_name;

Expand All @@ -216,10 +253,20 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
filterString += ` AND (${this.args.searchFilters})`;
}

let maybeOptionalFilters = "";

if (this.args.optionalSearchFilters) {
maybeOptionalFilters = this.args.optionalSearchFilters;
}

if (options?.optionalFilters) {
maybeOptionalFilters += ` ${options.optionalFilters}`;
}

try {
let algoliaResponse = await this.algolia.searchIndex
.perform(index, query, {
hitsPerPage: 4,
hitsPerPage: options?.hitsPerPage || 4,
filters: filterString,
attributesToRetrieve: [
"title",
Expand All @@ -233,7 +280,7 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
// https://www.algolia.com/doc/guides/managing-results/rules/merchandising-and-promoting/in-depth/optional-filters/
// Include any optional search filters, e.g., "product:Terraform"
// to give a higher ranking to results that match the filter.
optionalFilters: this.args.optionalSearchFilters,
optionalFilters: maybeOptionalFilters,
})
.then((response) => response);
if (algoliaResponse) {
Expand All @@ -256,15 +303,23 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
await timeout(Ember.testing ? 0 : 200);
}
} catch (e: unknown) {
// This will trigger the "no matches" block,
// which is where we're displaying the error.
this._algoliaResults = null;
this.searchErrorIsShown = true;
console.error(e);
this.handleSearchError(e);
}
}
);

/**
* The action run when a search errors. Resets the Algolia results
* and causes a search error to appear.
*/
@action private handleSearchError(e: unknown) {
// This triggers the "no matches" block,
// which is where we're displaying the error.
this.resetAlgoliaResults();
this.searchErrorIsShown = true;
console.error("Algolia search failed", e);
}

/**
* The action run when the "add resource" plus button is clicked.
* Shows the modal.
Expand Down Expand Up @@ -299,6 +354,7 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
// The getter doesn't update when a new resource is added, so we manually save it.
// TODO: Improve this
this.relatedLinks = this.relatedLinks;

void this.saveRelatedResources.perform(
this.relatedDocuments,
cachedLinks,
Expand Down Expand Up @@ -334,6 +390,15 @@ export default class DocumentSidebarRelatedResourcesComponent extends Component<
this.hideAddResourceModal();
}

/**
* The action to set the locally tracked Algolia results to null.
* Used in template computations when a search fails, or when a link is
* recognized as an external resource by a child component.
*/
@action protected resetAlgoliaResults() {
this._algoliaResults = null;
}

/**
* The task called to remove a resource from a document.
* Triggered via the overflow menu or the "Edit resource" modal.
Expand Down
15 changes: 5 additions & 10 deletions web/app/components/document/sidebar/related-resources/add.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<M.Body>
<X::DropdownList
data-test-add-related-resources-list
@items={{@shownDocuments}}
@items={{this.algoliaResults}}
@onItemClick={{this.onItemClick}}
@offset={{hash mainAxis=1 crossAxis=0}}
@isLoading={{this.loadInitialData.isRunning}}
Expand All @@ -27,10 +27,9 @@

<Hds::Form::TextInput::Base
data-test-related-resources-search-input
{{did-insert dd.registerAnchor}}
{{did-insert (fn this.didInsertInput dd)}}
{{on "input" (fn this.onInput dd)}}
{{on "keydown" (fn this.onInputKeydown dd)}}
{{on "input" this.onInput}}
{{on "keydown" this.onInputKeydown}}
{{on "focusin" this.enableKeyboardNav}}
{{on "focusout" this.disableKeyboardNav}}
@type="search"
Expand Down Expand Up @@ -66,7 +65,7 @@
</div>
{{/if}}

{{#if (and @allowAddingExternalLinks this.queryIsURL)}}
{{#if (and @allowAddingExternalLinks this.queryIsExternalURL)}}
<Document::Sidebar::RelatedResources::Add::ExternalResource
@onInput={{this.onExternalLinkTitleInput}}
@onSubmit={{this.onExternalLinkSubmit}}
Expand All @@ -91,11 +90,7 @@
class="related-resources-modal-container mt-36"
>
<h3 class="related-resources-modal-body-header">
{{if
@searchErrorIsShown
"Search error. Type to retry."
"No results found"
}}
{{this.noMatchesMessage}}
</h3>
</div>
{{/unless}}
Expand Down
Loading